diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 75d24cdef74..b75a7896eec 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -2,6 +2,6 @@ /web/ui/module @juliusv @nexucis /storage/remote @csmarchbanks @cstyan @bwplotka @tomwilkie /discovery/kubernetes @brancz -/tsdb @codesome +/tsdb @jesusvazquez /promql @roidelapluie /cmd/promtool @dgl diff --git a/.github/workflows/buf-lint.yml b/.github/workflows/buf-lint.yml index 3275d08fc32..79430ee56ad 100644 --- a/.github/workflows/buf-lint.yml +++ b/.github/workflows/buf-lint.yml @@ -10,7 +10,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - - uses: bufbuild/buf-setup-action@v1.16.0 + - uses: bufbuild/buf-setup-action@v1.17.0 with: github_token: ${{ secrets.GITHUB_TOKEN }} - uses: bufbuild/buf-lint-action@v1 diff --git a/.github/workflows/buf.yml b/.github/workflows/buf.yml index c80183b18a6..06e53172e8d 100644 --- a/.github/workflows/buf.yml +++ b/.github/workflows/buf.yml @@ -9,7 +9,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - - uses: bufbuild/buf-setup-action@v1.16.0 + - uses: bufbuild/buf-setup-action@v1.17.0 with: github_token: ${{ secrets.GITHUB_TOKEN }} - uses: bufbuild/buf-lint-action@v1 diff --git a/.golangci.yml b/.golangci.yml index d1cd86ed597..fc2721455cd 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -13,8 +13,9 @@ linters: - gocritic - gofumpt - goimports - - revive - misspell + - predeclared + - revive - unconvert - unused diff --git a/.yamllint b/.yamllint.yml similarity index 90% rename from .yamllint rename to .yamllint.yml index 19552574b20..955a5a6270d 100644 --- a/.yamllint +++ b/.yamllint.yml @@ -20,5 +20,4 @@ rules: config/testdata/section_key_dup.bad.yml line-length: disable truthy: - ignore: | - .github/workflows/*.yml + check-keys: false diff --git a/CHANGELOG.md b/CHANGELOG.md index f7dc32273e2..76b6e51b5fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,29 @@ # Changelog + +## 2.45.0 / 2023-06-23 + +This release is a LTS (Long-Term Support) release of Prometheus and will +receive security, documentation and bugfix patches for at least 12 months. +Please read more about our LTS release cycle at +. + +* [FEATURE] API: New limit parameter to limit the number of items returned by `/api/v1/status/tsdb` endpoint. #12336 +* [FEATURE] Config: Add limits to global config. #12126 +* [FEATURE] Consul SD: Added support for `path_prefix`. #12372 +* [FEATURE] Native histograms: Add option to scrape both classic and native histograms. #12350 +* [FEATURE] Native histograms: Added support for two more arithmetic operators `avg_over_time` and `sum_over_time`. #12262 +* [FEATURE] Promtool: When providing the block id, only one block will be loaded and analyzed. #12031 +* [FEATURE] Remote-write: New Azure ad configuration to support remote writing directly to Azure Monitor workspace. #11944 +* [FEATURE] TSDB: Samples per chunk are now configurable with flag `storage.tsdb.samples-per-chunk`. By default set to its former value 120. #12055 +* [ENHANCEMENT] Native histograms: bucket size can now be limited to avoid scrape fails. #12254 +* [ENHANCEMENT] TSDB: Dropped series are now deleted from the WAL sooner. #12297 +* [BUGFIX] Native histograms: ChunkSeries iterator now checks if a new sample can be appended to the open chunk. #12185 +* [BUGFIX] Native histograms: Fix Histogram Appender `Appendable()` segfault. #12357 +* [BUGFIX] Native histograms: Fix setting reset header to gauge histograms in seriesToChunkEncoder. #12329 +* [BUGFIX] TSDB: Tombstone intervals are not modified after Get() call. #12245 +* [BUGFIX] TSDB: Use path/filepath to set the WAL directory. #12349 + ## 2.44.0 / 2023-05-13 This version is built with Go tag `stringlabels`, to use the smaller data @@ -20,6 +44,10 @@ details about this code change see #10991. * [BUGFIX] TSDB: Block compaction failed when shutting down. #12179 * [BUGFIX] TSDB: Out-of-order chunks could be ignored if the write-behind log was deleted. #12127 +## 2.43.1 / 2023-05-03 + +* [BUGFIX] Labels: `Set()` after `Del()` would be ignored, which broke some relabeling rules. #12322 + ## 2.43.0 / 2023-03-21 We are working on some performance improvements in Prometheus, which are only @@ -33,7 +61,7 @@ the gains on their production architecture. We are providing release artefacts improvements for testing. #10991 * [FEATURE] Promtool: Add HTTP client configuration to query commands. #11487 -* [FEATURE] Scrape: Add `include_scrape_configs` to include scrape configs from different files. #12019 +* [FEATURE] Scrape: Add `scrape_config_files` to include scrape configs from different files. #12019 * [FEATURE] HTTP client: Add `no_proxy` to exclude URLs from proxied requests. #12098 * [FEATURE] HTTP client: Add `proxy_from_enviroment` to read proxies from env variables. #12098 * [ENHANCEMENT] API: Add support for setting lookback delta per query via the API. #12088 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2fbed38809b..57055ef38c2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -85,7 +85,7 @@ The PromQL parser grammar is located in `promql/parser/generated_parser.y` and i The parser is built using [goyacc](https://pkg.go.dev/golang.org/x/tools/cmd/goyacc) If doing some sort of debugging, then it is possible to add some verbose output. After generating the parser, then you -can modify the the `./promql/parser/generated_parser.y.go` manually. +can modify the `./promql/parser/generated_parser.y.go` manually. ```golang // As of writing this was somewhere around line 600. diff --git a/README.md b/README.md index 9becf71aa1b..8b89bb01e5e 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ The features that distinguish Prometheus from other metrics and monitoring syste ## Architecture overview -![Architecture overview](https://cdn.jsdelivr.net/gh/prometheus/prometheus@c34257d069c630685da35bcef084632ffd5d6209/documentation/images/architecture.svg) +![Architecture overview](documentation/images/architecture.svg) ## Install diff --git a/RELEASE.md b/RELEASE.md index 26f72ba628c..f5c907fe996 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -49,7 +49,8 @@ Release cadence of first pre-releases being cut is 6 weeks. | v2.42 | 2023-01-25 | Kemal Akkoyun (GitHub: @kakkoyun) | | v2.43 | 2023-03-08 | Julien Pivotto (GitHub: @roidelapluie) | | v2.44 | 2023-04-19 | Bryan Boreham (GitHub: @bboreham) | -| v2.45 | 2023-05-31 | **searching for volunteer** | +| v2.45 LTS | 2023-05-31 | Jesus Vazquez (Github: @jesusvazquez) | +| v2.46 | 2023-07-12 | **searching for volunteer** | If you are interested in volunteering please create a pull request against the [prometheus/prometheus](https://github.com/prometheus/prometheus) repository and propose yourself for the release series of your choice. diff --git a/VERSION b/VERSION index 3e197472e26..e599014eab6 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -2.44.0 +2.45.0 diff --git a/cmd/prometheus/main.go b/cmd/prometheus/main.go index 57c21c6d8d9..e05ac79570b 100644 --- a/cmd/prometheus/main.go +++ b/cmd/prometheus/main.go @@ -337,6 +337,9 @@ func main() { serverOnlyFlag(a, "storage.tsdb.head-chunks-write-queue-size", "Size of the queue through which head chunks are written to the disk to be m-mapped, 0 disables the queue completely. Experimental."). Default("0").IntVar(&cfg.tsdb.HeadChunksWriteQueueSize) + serverOnlyFlag(a, "storage.tsdb.samples-per-chunk", "Target number of samples per chunk."). + Default("120").Hidden().IntVar(&cfg.tsdb.SamplesPerChunk) + agentOnlyFlag(a, "storage.agent.path", "Base path for metrics storage."). Default("data-agent/").StringVar(&cfg.agentStoragePath) @@ -1050,6 +1053,7 @@ func main() { startTimeMargin := int64(2 * time.Duration(cfg.tsdb.MinBlockDuration).Seconds() * 1000) localStorage.Set(db, startTimeMargin) + db.SetWriteNotified(remoteStorage) close(dbOpen) <-cancel return nil @@ -1482,11 +1486,11 @@ func (s *readyStorage) Snapshot(dir string, withHead bool) error { } // Stats implements the api_v1.TSDBAdminStats interface. -func (s *readyStorage) Stats(statsByLabelName string) (*tsdb.Stats, error) { +func (s *readyStorage) Stats(statsByLabelName string, limit int) (*tsdb.Stats, error) { if x := s.get(); x != nil { switch db := x.(type) { case *tsdb.DB: - return db.Head().Stats(statsByLabelName), nil + return db.Head().Stats(statsByLabelName, limit), nil case *agent.DB: return nil, agent.ErrUnsupported default: @@ -1543,6 +1547,7 @@ type tsdbOptions struct { NoLockfile bool WALCompression bool HeadChunksWriteQueueSize int + SamplesPerChunk int StripeSize int MinBlockDuration model.Duration MaxBlockDuration model.Duration @@ -1563,6 +1568,7 @@ func (opts tsdbOptions) ToTSDBOptions() tsdb.Options { AllowOverlappingCompaction: true, WALCompression: opts.WALCompression, HeadChunksWriteQueueSize: opts.HeadChunksWriteQueueSize, + SamplesPerChunk: opts.SamplesPerChunk, StripeSize: opts.StripeSize, MinBlockDuration: int64(time.Duration(opts.MinBlockDuration) / time.Millisecond), MaxBlockDuration: int64(time.Duration(opts.MaxBlockDuration) / time.Millisecond), diff --git a/cmd/promtool/tsdb.go b/cmd/promtool/tsdb.go index 84aa43a9c40..b7fad5fe095 100644 --- a/cmd/promtool/tsdb.go +++ b/cmd/promtool/tsdb.go @@ -398,26 +398,20 @@ func openBlock(path, blockID string) (*tsdb.DBReadOnly, tsdb.BlockReader, error) if err != nil { return nil, nil, err } - blocks, err := db.Blocks() - if err != nil { - return nil, nil, err - } - var block tsdb.BlockReader - switch { - case blockID != "": - for _, b := range blocks { - if b.Meta().ULID.String() == blockID { - block = b - break - } + + if blockID == "" { + blockID, err = db.LastBlockID() + if err != nil { + return nil, nil, err } - case len(blocks) > 0: - block = blocks[len(blocks)-1] } - if block == nil { - return nil, nil, fmt.Errorf("block %s not found", blockID) + + b, err := db.Block(blockID) + if err != nil { + return nil, nil, err } - return db, block, nil + + return db, b, nil } func analyzeBlock(path, blockID string, limit int, runExtended bool) error { diff --git a/config/config.go b/config/config.go index 5c51d5a0d85..d32fcc33c98 100644 --- a/config/config.go +++ b/config/config.go @@ -34,6 +34,7 @@ import ( "github.com/prometheus/prometheus/discovery" "github.com/prometheus/prometheus/model/labels" "github.com/prometheus/prometheus/model/relabel" + "github.com/prometheus/prometheus/storage/remote/azuread" ) var ( @@ -146,13 +147,14 @@ var ( // DefaultScrapeConfig is the default scrape configuration. DefaultScrapeConfig = ScrapeConfig{ - // ScrapeTimeout and ScrapeInterval default to the - // configured globals. - MetricsPath: "/metrics", - Scheme: "http", - HonorLabels: false, - HonorTimestamps: true, - HTTPClientConfig: config.DefaultHTTPClientConfig, + // ScrapeTimeout and ScrapeInterval default to the configured + // globals. + ScrapeClassicHistograms: false, + MetricsPath: "/metrics", + Scheme: "http", + HonorLabels: false, + HonorTimestamps: true, + HTTPClientConfig: config.DefaultHTTPClientConfig, } // DefaultAlertmanagerConfig is the default alertmanager configuration. @@ -266,7 +268,7 @@ func (c *Config) GetScrapeConfigs() ([]*ScrapeConfig, error) { for i, scfg := range c.ScrapeConfigs { // We do these checks for library users that would not call Validate in // Unmarshal. - if err := scfg.Validate(c.GlobalConfig.ScrapeInterval, c.GlobalConfig.ScrapeTimeout); err != nil { + if err := scfg.Validate(c.GlobalConfig); err != nil { return nil, err } @@ -293,7 +295,7 @@ func (c *Config) GetScrapeConfigs() ([]*ScrapeConfig, error) { return nil, fileErr(filename, err) } for _, scfg := range cfg.ScrapeConfigs { - if err := scfg.Validate(c.GlobalConfig.ScrapeInterval, c.GlobalConfig.ScrapeTimeout); err != nil { + if err := scfg.Validate(c.GlobalConfig); err != nil { return nil, fileErr(filename, err) } @@ -342,7 +344,7 @@ func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error { // Do global overrides and validate unique names. jobNames := map[string]struct{}{} for _, scfg := range c.ScrapeConfigs { - if err := scfg.Validate(c.GlobalConfig.ScrapeInterval, c.GlobalConfig.ScrapeTimeout); err != nil { + if err := scfg.Validate(c.GlobalConfig); err != nil { return err } @@ -389,6 +391,24 @@ type GlobalConfig struct { QueryLogFile string `yaml:"query_log_file,omitempty"` // The labels to add to any timeseries that this Prometheus instance scrapes. ExternalLabels labels.Labels `yaml:"external_labels,omitempty"` + // An uncompressed response body larger than this many bytes will cause the + // scrape to fail. 0 means no limit. + BodySizeLimit units.Base2Bytes `yaml:"body_size_limit,omitempty"` + // More than this many samples post metric-relabeling will cause the scrape to + // fail. 0 means no limit. + SampleLimit uint `yaml:"sample_limit,omitempty"` + // More than this many targets after the target relabeling will cause the + // scrapes to fail. 0 means no limit. + TargetLimit uint `yaml:"target_limit,omitempty"` + // More than this many labels post metric-relabeling will cause the scrape to + // fail. 0 means no limit. + LabelLimit uint `yaml:"label_limit,omitempty"` + // More than this label name length post metric-relabeling will cause the + // scrape to fail. 0 means no limit. + LabelNameLengthLimit uint `yaml:"label_name_length_limit,omitempty"` + // More than this label value length post metric-relabeling will cause the + // scrape to fail. 0 means no limit. + LabelValueLengthLimit uint `yaml:"label_value_length_limit,omitempty"` } // SetDirectory joins any relative file paths with dir. @@ -467,6 +487,8 @@ type ScrapeConfig struct { ScrapeInterval model.Duration `yaml:"scrape_interval,omitempty"` // The timeout for scraping targets of this config. ScrapeTimeout model.Duration `yaml:"scrape_timeout,omitempty"` + // Whether to scrape a classic histogram that is also exposed as a native histogram. + ScrapeClassicHistograms bool `yaml:"scrape_classic_histograms,omitempty"` // The HTTP resource path on which to fetch metrics from targets. MetricsPath string `yaml:"metrics_path,omitempty"` // The URL scheme with which to fetch metrics from targets. @@ -475,20 +497,23 @@ type ScrapeConfig struct { // scrape to fail. 0 means no limit. BodySizeLimit units.Base2Bytes `yaml:"body_size_limit,omitempty"` // More than this many samples post metric-relabeling will cause the scrape to - // fail. + // fail. 0 means no limit. SampleLimit uint `yaml:"sample_limit,omitempty"` // More than this many targets after the target relabeling will cause the - // scrapes to fail. + // scrapes to fail. 0 means no limit. TargetLimit uint `yaml:"target_limit,omitempty"` // More than this many labels post metric-relabeling will cause the scrape to - // fail. + // fail. 0 means no limit. LabelLimit uint `yaml:"label_limit,omitempty"` // More than this label name length post metric-relabeling will cause the - // scrape to fail. + // scrape to fail. 0 means no limit. LabelNameLengthLimit uint `yaml:"label_name_length_limit,omitempty"` // More than this label value length post metric-relabeling will cause the - // scrape to fail. + // scrape to fail. 0 means no limit. LabelValueLengthLimit uint `yaml:"label_value_length_limit,omitempty"` + // More than this many buckets in a native histogram will cause the scrape to + // fail. + NativeHistogramBucketLimit uint `yaml:"native_histogram_bucket_limit,omitempty"` // We cannot do proper Go type embedding below as the parser will then parse // values arbitrarily into the overflow maps of further-down types. @@ -546,25 +571,44 @@ func (c *ScrapeConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { return nil } -func (c *ScrapeConfig) Validate(defaultInterval, defaultTimeout model.Duration) error { +func (c *ScrapeConfig) Validate(globalConfig GlobalConfig) error { if c == nil { return errors.New("empty or null scrape config section") } // First set the correct scrape interval, then check that the timeout // (inferred or explicit) is not greater than that. if c.ScrapeInterval == 0 { - c.ScrapeInterval = defaultInterval + c.ScrapeInterval = globalConfig.ScrapeInterval } if c.ScrapeTimeout > c.ScrapeInterval { return fmt.Errorf("scrape timeout greater than scrape interval for scrape config with job name %q", c.JobName) } if c.ScrapeTimeout == 0 { - if defaultTimeout > c.ScrapeInterval { + if globalConfig.ScrapeTimeout > c.ScrapeInterval { c.ScrapeTimeout = c.ScrapeInterval } else { - c.ScrapeTimeout = defaultTimeout + c.ScrapeTimeout = globalConfig.ScrapeTimeout } } + if c.BodySizeLimit == 0 { + c.BodySizeLimit = globalConfig.BodySizeLimit + } + if c.SampleLimit == 0 { + c.SampleLimit = globalConfig.SampleLimit + } + if c.TargetLimit == 0 { + c.TargetLimit = globalConfig.TargetLimit + } + if c.LabelLimit == 0 { + c.LabelLimit = globalConfig.LabelLimit + } + if c.LabelNameLengthLimit == 0 { + c.LabelNameLengthLimit = globalConfig.LabelNameLengthLimit + } + if c.LabelValueLengthLimit == 0 { + c.LabelValueLengthLimit = globalConfig.LabelValueLengthLimit + } + return nil } @@ -864,6 +908,7 @@ type RemoteWriteConfig struct { QueueConfig QueueConfig `yaml:"queue_config,omitempty"` MetadataConfig MetadataConfig `yaml:"metadata_config,omitempty"` SigV4Config *sigv4.SigV4Config `yaml:"sigv4,omitempty"` + AzureADConfig *azuread.AzureADConfig `yaml:"azuread,omitempty"` } // SetDirectory joins any relative file paths with dir. @@ -900,8 +945,12 @@ func (c *RemoteWriteConfig) UnmarshalYAML(unmarshal func(interface{}) error) err httpClientConfigAuthEnabled := c.HTTPClientConfig.BasicAuth != nil || c.HTTPClientConfig.Authorization != nil || c.HTTPClientConfig.OAuth2 != nil - if httpClientConfigAuthEnabled && c.SigV4Config != nil { - return fmt.Errorf("at most one of basic_auth, authorization, oauth2, & sigv4 must be configured") + if httpClientConfigAuthEnabled && (c.SigV4Config != nil || c.AzureADConfig != nil) { + return fmt.Errorf("at most one of basic_auth, authorization, oauth2, sigv4, & azuread must be configured") + } + + if c.SigV4Config != nil && c.AzureADConfig != nil { + return fmt.Errorf("at most one of basic_auth, authorization, oauth2, sigv4, & azuread must be configured") } return nil @@ -922,7 +971,7 @@ func validateHeadersForTracing(headers map[string]string) error { func validateHeaders(headers map[string]string) error { for header := range headers { if strings.ToLower(header) == "authorization" { - return errors.New("authorization header must be changed via the basic_auth, authorization, oauth2, or sigv4 parameter") + return errors.New("authorization header must be changed via the basic_auth, authorization, oauth2, sigv4, or azuread parameter") } if _, ok := reservedHeaders[strings.ToLower(header)]; ok { return fmt.Errorf("%s is a reserved header. It must not be changed", header) diff --git a/config/config_test.go b/config/config_test.go index 3ee327c5fac..d3288cc90d3 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -68,6 +68,15 @@ func mustParseURL(u string) *config.URL { return &config.URL{URL: parsed} } +const ( + globBodySizeLimit = 15 * units.MiB + globSampleLimit = 1500 + globTargetLimit = 30 + globLabelLimit = 30 + globLabelNameLengthLimit = 200 + globLabelValueLengthLimit = 200 +) + var expectedConf = &Config{ GlobalConfig: GlobalConfig{ ScrapeInterval: model.Duration(15 * time.Second), @@ -76,6 +85,13 @@ var expectedConf = &Config{ QueryLogFile: "", ExternalLabels: labels.FromStrings("foo", "bar", "monitor", "codelab"), + + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, }, RuleFiles: []string{ @@ -165,10 +181,16 @@ var expectedConf = &Config{ { JobName: "prometheus", - HonorLabels: true, - HonorTimestamps: true, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + HonorLabels: true, + HonorTimestamps: true, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, MetricsPath: DefaultScrapeConfig.MetricsPath, Scheme: DefaultScrapeConfig.Scheme, @@ -261,11 +283,15 @@ var expectedConf = &Config{ { JobName: "service-x", - HonorTimestamps: true, - ScrapeInterval: model.Duration(50 * time.Second), - ScrapeTimeout: model.Duration(5 * time.Second), - BodySizeLimit: 10 * units.MiB, - SampleLimit: 1000, + HonorTimestamps: true, + ScrapeInterval: model.Duration(50 * time.Second), + ScrapeTimeout: model.Duration(5 * time.Second), + BodySizeLimit: 10 * units.MiB, + SampleLimit: 1000, + TargetLimit: 35, + LabelLimit: 35, + LabelNameLengthLimit: 210, + LabelValueLengthLimit: 210, HTTPClientConfig: config.HTTPClientConfig{ BasicAuth: &config.BasicAuth{ @@ -352,9 +378,15 @@ var expectedConf = &Config{ { JobName: "service-y", - HonorTimestamps: true, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + HonorTimestamps: true, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, MetricsPath: DefaultScrapeConfig.MetricsPath, Scheme: DefaultScrapeConfig.Scheme, @@ -363,6 +395,7 @@ var expectedConf = &Config{ ServiceDiscoveryConfigs: discovery.Configs{ &consul.SDConfig{ Server: "localhost:1234", + PathPrefix: "/consul", Token: "mysecret", Services: []string{"nginx", "cache", "mysql"}, ServiceTags: []string{"canary", "v1"}, @@ -398,9 +431,15 @@ var expectedConf = &Config{ { JobName: "service-z", - HonorTimestamps: true, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: model.Duration(10 * time.Second), + HonorTimestamps: true, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: model.Duration(10 * time.Second), + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, MetricsPath: "/metrics", Scheme: "http", @@ -423,9 +462,15 @@ var expectedConf = &Config{ { JobName: "service-kubernetes", - HonorTimestamps: true, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + HonorTimestamps: true, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, MetricsPath: DefaultScrapeConfig.MetricsPath, Scheme: DefaultScrapeConfig.Scheme, @@ -454,9 +499,15 @@ var expectedConf = &Config{ { JobName: "service-kubernetes-namespaces", - HonorTimestamps: true, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + HonorTimestamps: true, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, MetricsPath: DefaultScrapeConfig.MetricsPath, Scheme: DefaultScrapeConfig.Scheme, @@ -485,9 +536,15 @@ var expectedConf = &Config{ { JobName: "service-kuma", - HonorTimestamps: true, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + HonorTimestamps: true, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, MetricsPath: DefaultScrapeConfig.MetricsPath, Scheme: DefaultScrapeConfig.Scheme, @@ -505,9 +562,15 @@ var expectedConf = &Config{ { JobName: "service-marathon", - HonorTimestamps: true, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + HonorTimestamps: true, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, MetricsPath: DefaultScrapeConfig.MetricsPath, Scheme: DefaultScrapeConfig.Scheme, @@ -534,9 +597,15 @@ var expectedConf = &Config{ { JobName: "service-nomad", - HonorTimestamps: true, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + HonorTimestamps: true, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, MetricsPath: DefaultScrapeConfig.MetricsPath, Scheme: DefaultScrapeConfig.Scheme, @@ -560,9 +629,15 @@ var expectedConf = &Config{ { JobName: "service-ec2", - HonorTimestamps: true, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + HonorTimestamps: true, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, MetricsPath: DefaultScrapeConfig.MetricsPath, Scheme: DefaultScrapeConfig.Scheme, @@ -593,9 +668,15 @@ var expectedConf = &Config{ { JobName: "service-lightsail", - HonorTimestamps: true, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + HonorTimestamps: true, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, MetricsPath: DefaultScrapeConfig.MetricsPath, Scheme: DefaultScrapeConfig.Scheme, @@ -616,9 +697,15 @@ var expectedConf = &Config{ { JobName: "service-azure", - HonorTimestamps: true, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + HonorTimestamps: true, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, MetricsPath: DefaultScrapeConfig.MetricsPath, Scheme: DefaultScrapeConfig.Scheme, @@ -642,9 +729,15 @@ var expectedConf = &Config{ { JobName: "service-nerve", - HonorTimestamps: true, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + HonorTimestamps: true, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, MetricsPath: DefaultScrapeConfig.MetricsPath, Scheme: DefaultScrapeConfig.Scheme, @@ -661,9 +754,15 @@ var expectedConf = &Config{ { JobName: "0123service-xxx", - HonorTimestamps: true, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + HonorTimestamps: true, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, MetricsPath: DefaultScrapeConfig.MetricsPath, Scheme: DefaultScrapeConfig.Scheme, @@ -683,9 +782,15 @@ var expectedConf = &Config{ { JobName: "badfederation", - HonorTimestamps: false, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + HonorTimestamps: false, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, MetricsPath: "/federate", Scheme: DefaultScrapeConfig.Scheme, @@ -705,9 +810,15 @@ var expectedConf = &Config{ { JobName: "測試", - HonorTimestamps: true, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + HonorTimestamps: true, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, MetricsPath: DefaultScrapeConfig.MetricsPath, Scheme: DefaultScrapeConfig.Scheme, @@ -727,9 +838,15 @@ var expectedConf = &Config{ { JobName: "httpsd", - HonorTimestamps: true, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + HonorTimestamps: true, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, MetricsPath: DefaultScrapeConfig.MetricsPath, Scheme: DefaultScrapeConfig.Scheme, @@ -746,9 +863,15 @@ var expectedConf = &Config{ { JobName: "service-triton", - HonorTimestamps: true, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + HonorTimestamps: true, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, MetricsPath: DefaultScrapeConfig.MetricsPath, Scheme: DefaultScrapeConfig.Scheme, @@ -773,9 +896,15 @@ var expectedConf = &Config{ { JobName: "digitalocean-droplets", - HonorTimestamps: true, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + HonorTimestamps: true, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, MetricsPath: DefaultScrapeConfig.MetricsPath, Scheme: DefaultScrapeConfig.Scheme, @@ -799,9 +928,15 @@ var expectedConf = &Config{ { JobName: "docker", - HonorTimestamps: true, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + HonorTimestamps: true, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, MetricsPath: DefaultScrapeConfig.MetricsPath, Scheme: DefaultScrapeConfig.Scheme, @@ -821,9 +956,15 @@ var expectedConf = &Config{ { JobName: "dockerswarm", - HonorTimestamps: true, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + HonorTimestamps: true, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, MetricsPath: DefaultScrapeConfig.MetricsPath, Scheme: DefaultScrapeConfig.Scheme, @@ -843,9 +984,15 @@ var expectedConf = &Config{ { JobName: "service-openstack", - HonorTimestamps: true, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + HonorTimestamps: true, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, MetricsPath: DefaultScrapeConfig.MetricsPath, Scheme: DefaultScrapeConfig.Scheme, @@ -869,9 +1016,15 @@ var expectedConf = &Config{ { JobName: "service-puppetdb", - HonorTimestamps: true, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + HonorTimestamps: true, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, MetricsPath: DefaultScrapeConfig.MetricsPath, Scheme: DefaultScrapeConfig.Scheme, @@ -897,10 +1050,16 @@ var expectedConf = &Config{ }, }, { - JobName: "hetzner", - HonorTimestamps: true, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + JobName: "hetzner", + HonorTimestamps: true, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, MetricsPath: DefaultScrapeConfig.MetricsPath, Scheme: DefaultScrapeConfig.Scheme, @@ -946,9 +1105,15 @@ var expectedConf = &Config{ { JobName: "service-eureka", - HonorTimestamps: true, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + HonorTimestamps: true, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, MetricsPath: DefaultScrapeConfig.MetricsPath, Scheme: DefaultScrapeConfig.Scheme, @@ -965,9 +1130,16 @@ var expectedConf = &Config{ { JobName: "ovhcloud", - HonorTimestamps: true, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + HonorTimestamps: true, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, + HTTPClientConfig: config.DefaultHTTPClientConfig, MetricsPath: DefaultScrapeConfig.MetricsPath, Scheme: DefaultScrapeConfig.Scheme, @@ -994,9 +1166,16 @@ var expectedConf = &Config{ { JobName: "scaleway", - HonorTimestamps: true, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + HonorTimestamps: true, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, + HTTPClientConfig: config.DefaultHTTPClientConfig, MetricsPath: DefaultScrapeConfig.MetricsPath, Scheme: DefaultScrapeConfig.Scheme, @@ -1029,9 +1208,15 @@ var expectedConf = &Config{ { JobName: "linode-instances", - HonorTimestamps: true, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + HonorTimestamps: true, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, MetricsPath: DefaultScrapeConfig.MetricsPath, Scheme: DefaultScrapeConfig.Scheme, @@ -1056,9 +1241,16 @@ var expectedConf = &Config{ { JobName: "uyuni", - HonorTimestamps: true, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + HonorTimestamps: true, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, + HTTPClientConfig: config.DefaultHTTPClientConfig, MetricsPath: DefaultScrapeConfig.MetricsPath, Scheme: DefaultScrapeConfig.Scheme, @@ -1075,10 +1267,16 @@ var expectedConf = &Config{ }, }, { - JobName: "ionos", - HonorTimestamps: true, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + JobName: "ionos", + HonorTimestamps: true, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, MetricsPath: DefaultScrapeConfig.MetricsPath, Scheme: DefaultScrapeConfig.Scheme, @@ -1100,9 +1298,15 @@ var expectedConf = &Config{ { JobName: "vultr", - HonorTimestamps: true, - ScrapeInterval: model.Duration(15 * time.Second), - ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + HonorTimestamps: true, + ScrapeInterval: model.Duration(15 * time.Second), + ScrapeTimeout: DefaultGlobalConfig.ScrapeTimeout, + BodySizeLimit: globBodySizeLimit, + SampleLimit: globSampleLimit, + TargetLimit: globTargetLimit, + LabelLimit: globLabelLimit, + LabelNameLengthLimit: globLabelNameLengthLimit, + LabelValueLengthLimit: globLabelValueLengthLimit, MetricsPath: DefaultScrapeConfig.MetricsPath, Scheme: DefaultScrapeConfig.Scheme, @@ -1523,7 +1727,7 @@ var expectedErrors = []struct { }, { filename: "remote_write_authorization_header.bad.yml", - errMsg: `authorization header must be changed via the basic_auth, authorization, oauth2, or sigv4 parameter`, + errMsg: `authorization header must be changed via the basic_auth, authorization, oauth2, sigv4, or azuread parameter`, }, { filename: "remote_write_url_missing.bad.yml", diff --git a/config/testdata/conf.good.yml b/config/testdata/conf.good.yml index 764f1a342b0..19cfe1eb5d4 100644 --- a/config/testdata/conf.good.yml +++ b/config/testdata/conf.good.yml @@ -2,6 +2,12 @@ global: scrape_interval: 15s evaluation_interval: 30s + body_size_limit: 15MB + sample_limit: 1500 + target_limit: 30 + label_limit: 30 + label_name_length_limit: 200 + label_value_length_limit: 200 # scrape_timeout is set to the global default (10s). external_labels: @@ -111,6 +117,11 @@ scrape_configs: body_size_limit: 10MB sample_limit: 1000 + target_limit: 35 + label_limit: 35 + label_name_length_limit: 210 + label_value_length_limit: 210 + metrics_path: /my_path scheme: https @@ -151,6 +162,7 @@ scrape_configs: consul_sd_configs: - server: "localhost:1234" token: mysecret + path_prefix: /consul services: ["nginx", "cache", "mysql"] tags: ["canary", "v1"] node_meta: diff --git a/discovery/consul/consul.go b/discovery/consul/consul.go index c59bd1f5d8d..99ea396b99a 100644 --- a/discovery/consul/consul.go +++ b/discovery/consul/consul.go @@ -111,6 +111,7 @@ func init() { // SDConfig is the configuration for Consul service discovery. type SDConfig struct { Server string `yaml:"server,omitempty"` + PathPrefix string `yaml:"path_prefix,omitempty"` Token config.Secret `yaml:"token,omitempty"` Datacenter string `yaml:"datacenter,omitempty"` Namespace string `yaml:"namespace,omitempty"` @@ -211,6 +212,7 @@ func NewDiscovery(conf *SDConfig, logger log.Logger) (*Discovery, error) { clientConf := &consul.Config{ Address: conf.Server, + PathPrefix: conf.PathPrefix, Scheme: conf.Scheme, Datacenter: conf.Datacenter, Namespace: conf.Namespace, diff --git a/discovery/kubernetes/endpoints.go b/discovery/kubernetes/endpoints.go index 27742ab4642..2413dab455b 100644 --- a/discovery/kubernetes/endpoints.go +++ b/discovery/kubernetes/endpoints.go @@ -305,7 +305,11 @@ func (e *Endpoints) buildEndpoints(eps *apiv1.Endpoints) *targetgroup.Group { } if e.withNodeMetadata { - target = addNodeLabels(target, e.nodeInf, e.logger, addr.NodeName) + if addr.NodeName != nil { + target = addNodeLabels(target, e.nodeInf, e.logger, addr.NodeName) + } else if addr.TargetRef != nil && addr.TargetRef.Kind == "Node" { + target = addNodeLabels(target, e.nodeInf, e.logger, &addr.TargetRef.Name) + } } pod := e.resolvePodRef(addr.TargetRef) @@ -466,5 +470,6 @@ func addNodeLabels(tg model.LabelSet, nodeInf cache.SharedInformer, logger log.L nodeLabelset[model.LabelName(nodeLabelPrefix+ln)] = lv(v) nodeLabelset[model.LabelName(nodeLabelPresentPrefix+ln)] = presentValue } + return tg.Merge(nodeLabelset) } diff --git a/discovery/kubernetes/endpoints_test.go b/discovery/kubernetes/endpoints_test.go index 91b1b0c6760..5aa58bdc49c 100644 --- a/discovery/kubernetes/endpoints_test.go +++ b/discovery/kubernetes/endpoints_test.go @@ -69,6 +69,24 @@ func makeEndpoints() *v1.Endpoints { }, }, }, + { + Addresses: []v1.EndpointAddress{ + { + IP: "6.7.8.9", + TargetRef: &v1.ObjectReference{ + Kind: "Node", + Name: "barbaz", + }, + }, + }, + Ports: []v1.EndpointPort{ + { + Name: "testport", + Port: 9002, + Protocol: v1.ProtocolTCP, + }, + }, + }, }, } } @@ -106,6 +124,14 @@ func TestEndpointsDiscoveryBeforeRun(t *testing.T) { "__meta_kubernetes_endpoint_port_protocol": "TCP", "__meta_kubernetes_endpoint_ready": "false", }, + { + "__address__": "6.7.8.9:9002", + "__meta_kubernetes_endpoint_address_target_kind": "Node", + "__meta_kubernetes_endpoint_address_target_name": "barbaz", + "__meta_kubernetes_endpoint_port_name": "testport", + "__meta_kubernetes_endpoint_port_protocol": "TCP", + "__meta_kubernetes_endpoint_ready": "true", + }, }, Labels: model.LabelSet{ "__meta_kubernetes_namespace": "default", @@ -398,6 +424,14 @@ func TestEndpointsDiscoveryWithService(t *testing.T) { "__meta_kubernetes_endpoint_port_protocol": "TCP", "__meta_kubernetes_endpoint_ready": "false", }, + { + "__address__": "6.7.8.9:9002", + "__meta_kubernetes_endpoint_address_target_kind": "Node", + "__meta_kubernetes_endpoint_address_target_name": "barbaz", + "__meta_kubernetes_endpoint_port_name": "testport", + "__meta_kubernetes_endpoint_port_protocol": "TCP", + "__meta_kubernetes_endpoint_ready": "true", + }, }, Labels: model.LabelSet{ "__meta_kubernetes_namespace": "default", @@ -466,6 +500,14 @@ func TestEndpointsDiscoveryWithServiceUpdate(t *testing.T) { "__meta_kubernetes_endpoint_port_protocol": "TCP", "__meta_kubernetes_endpoint_ready": "false", }, + { + "__address__": "6.7.8.9:9002", + "__meta_kubernetes_endpoint_address_target_kind": "Node", + "__meta_kubernetes_endpoint_address_target_name": "barbaz", + "__meta_kubernetes_endpoint_port_name": "testport", + "__meta_kubernetes_endpoint_port_protocol": "TCP", + "__meta_kubernetes_endpoint_ready": "true", + }, }, Labels: model.LabelSet{ "__meta_kubernetes_namespace": "default", @@ -484,8 +526,10 @@ func TestEndpointsDiscoveryWithServiceUpdate(t *testing.T) { func TestEndpointsDiscoveryWithNodeMetadata(t *testing.T) { metadataConfig := AttachMetadataConfig{Node: true} - nodeLabels := map[string]string{"az": "us-east1"} - node := makeNode("foobar", "", "", nodeLabels, nil) + nodeLabels1 := map[string]string{"az": "us-east1"} + nodeLabels2 := map[string]string{"az": "us-west2"} + node1 := makeNode("foobar", "", "", nodeLabels1, nil) + node2 := makeNode("barbaz", "", "", nodeLabels2, nil) svc := &v1.Service{ ObjectMeta: metav1.ObjectMeta{ Name: "testendpoints", @@ -495,7 +539,7 @@ func TestEndpointsDiscoveryWithNodeMetadata(t *testing.T) { }, }, } - n, _ := makeDiscoveryWithMetadata(RoleEndpoint, NamespaceDiscovery{}, metadataConfig, makeEndpoints(), svc, node) + n, _ := makeDiscoveryWithMetadata(RoleEndpoint, NamespaceDiscovery{}, metadataConfig, makeEndpoints(), svc, node1, node2) k8sDiscoveryTest{ discovery: n, @@ -526,6 +570,17 @@ func TestEndpointsDiscoveryWithNodeMetadata(t *testing.T) { "__meta_kubernetes_endpoint_port_protocol": "TCP", "__meta_kubernetes_endpoint_ready": "false", }, + { + "__address__": "6.7.8.9:9002", + "__meta_kubernetes_endpoint_address_target_kind": "Node", + "__meta_kubernetes_endpoint_address_target_name": "barbaz", + "__meta_kubernetes_endpoint_port_name": "testport", + "__meta_kubernetes_endpoint_port_protocol": "TCP", + "__meta_kubernetes_endpoint_ready": "true", + "__meta_kubernetes_node_label_az": "us-west2", + "__meta_kubernetes_node_labelpresent_az": "true", + "__meta_kubernetes_node_name": "barbaz", + }, }, Labels: model.LabelSet{ "__meta_kubernetes_namespace": "default", @@ -541,8 +596,10 @@ func TestEndpointsDiscoveryWithNodeMetadata(t *testing.T) { } func TestEndpointsDiscoveryWithUpdatedNodeMetadata(t *testing.T) { - nodeLabels := map[string]string{"az": "us-east1"} - nodes := makeNode("foobar", "", "", nodeLabels, nil) + nodeLabels1 := map[string]string{"az": "us-east1"} + nodeLabels2 := map[string]string{"az": "us-west2"} + node1 := makeNode("foobar", "", "", nodeLabels1, nil) + node2 := makeNode("barbaz", "", "", nodeLabels2, nil) metadataConfig := AttachMetadataConfig{Node: true} svc := &v1.Service{ ObjectMeta: metav1.ObjectMeta{ @@ -553,13 +610,13 @@ func TestEndpointsDiscoveryWithUpdatedNodeMetadata(t *testing.T) { }, }, } - n, c := makeDiscoveryWithMetadata(RoleEndpoint, NamespaceDiscovery{}, metadataConfig, makeEndpoints(), nodes, svc) + n, c := makeDiscoveryWithMetadata(RoleEndpoint, NamespaceDiscovery{}, metadataConfig, makeEndpoints(), node1, node2, svc) k8sDiscoveryTest{ discovery: n, afterStart: func() { - nodes.Labels["az"] = "eu-central1" - c.CoreV1().Nodes().Update(context.Background(), nodes, metav1.UpdateOptions{}) + node1.Labels["az"] = "eu-central1" + c.CoreV1().Nodes().Update(context.Background(), node1, metav1.UpdateOptions{}) }, expectedMaxItems: 2, expectedRes: map[string]*targetgroup.Group{ @@ -572,7 +629,7 @@ func TestEndpointsDiscoveryWithUpdatedNodeMetadata(t *testing.T) { "__meta_kubernetes_endpoint_port_name": "testport", "__meta_kubernetes_endpoint_port_protocol": "TCP", "__meta_kubernetes_endpoint_ready": "true", - "__meta_kubernetes_node_label_az": "eu-central1", + "__meta_kubernetes_node_label_az": "us-east1", "__meta_kubernetes_node_labelpresent_az": "true", "__meta_kubernetes_node_name": "foobar", }, @@ -588,6 +645,17 @@ func TestEndpointsDiscoveryWithUpdatedNodeMetadata(t *testing.T) { "__meta_kubernetes_endpoint_port_protocol": "TCP", "__meta_kubernetes_endpoint_ready": "false", }, + { + "__address__": "6.7.8.9:9002", + "__meta_kubernetes_endpoint_address_target_kind": "Node", + "__meta_kubernetes_endpoint_address_target_name": "barbaz", + "__meta_kubernetes_endpoint_port_name": "testport", + "__meta_kubernetes_endpoint_port_protocol": "TCP", + "__meta_kubernetes_endpoint_ready": "true", + "__meta_kubernetes_node_label_az": "us-west2", + "__meta_kubernetes_node_labelpresent_az": "true", + "__meta_kubernetes_node_name": "barbaz", + }, }, Labels: model.LabelSet{ "__meta_kubernetes_namespace": "default", @@ -699,6 +767,14 @@ func TestEndpointsDiscoveryNamespaces(t *testing.T) { "__meta_kubernetes_endpoint_port_protocol": "TCP", "__meta_kubernetes_endpoint_ready": "false", }, + { + "__address__": "6.7.8.9:9002", + "__meta_kubernetes_endpoint_address_target_kind": "Node", + "__meta_kubernetes_endpoint_address_target_name": "barbaz", + "__meta_kubernetes_endpoint_port_name": "testport", + "__meta_kubernetes_endpoint_port_protocol": "TCP", + "__meta_kubernetes_endpoint_ready": "true", + }, }, Labels: model.LabelSet{ "__meta_kubernetes_namespace": "ns1", @@ -815,6 +891,14 @@ func TestEndpointsDiscoveryOwnNamespace(t *testing.T) { "__meta_kubernetes_endpoint_port_protocol": "TCP", "__meta_kubernetes_endpoint_ready": "false", }, + { + "__address__": "6.7.8.9:9002", + "__meta_kubernetes_endpoint_address_target_kind": "Node", + "__meta_kubernetes_endpoint_address_target_name": "barbaz", + "__meta_kubernetes_endpoint_port_name": "testport", + "__meta_kubernetes_endpoint_port_protocol": "TCP", + "__meta_kubernetes_endpoint_ready": "true", + }, }, Labels: model.LabelSet{ "__meta_kubernetes_namespace": "own-ns", diff --git a/discovery/kubernetes/endpointslice.go b/discovery/kubernetes/endpointslice.go index 841b7d4f619..c7df6425256 100644 --- a/discovery/kubernetes/endpointslice.go +++ b/discovery/kubernetes/endpointslice.go @@ -339,7 +339,11 @@ func (e *EndpointSlice) buildEndpointSlice(eps endpointSliceAdaptor) *targetgrou } if e.withNodeMetadata { - target = addNodeLabels(target, e.nodeInf, e.logger, ep.nodename()) + if ep.targetRef() != nil && ep.targetRef().Kind == "Node" { + target = addNodeLabels(target, e.nodeInf, e.logger, &ep.targetRef().Name) + } else { + target = addNodeLabels(target, e.nodeInf, e.logger, ep.nodename()) + } } pod := e.resolvePodRef(ep.targetRef()) diff --git a/discovery/kubernetes/endpointslice_test.go b/discovery/kubernetes/endpointslice_test.go index f4076b943d5..8104e3db3b6 100644 --- a/discovery/kubernetes/endpointslice_test.go +++ b/discovery/kubernetes/endpointslice_test.go @@ -90,6 +90,17 @@ func makeEndpointSliceV1() *v1.EndpointSlice { Serving: boolptr(true), Terminating: boolptr(true), }, + }, { + Addresses: []string{"4.5.6.7"}, + Conditions: v1.EndpointConditions{ + Ready: boolptr(true), + Serving: boolptr(true), + Terminating: boolptr(false), + }, + TargetRef: &corev1.ObjectReference{ + Kind: "Node", + Name: "barbaz", + }, }, }, } @@ -130,6 +141,17 @@ func makeEndpointSliceV1beta1() *v1beta1.EndpointSlice { Serving: boolptr(true), Terminating: boolptr(true), }, + }, { + Addresses: []string{"4.5.6.7"}, + Conditions: v1beta1.EndpointConditions{ + Ready: boolptr(true), + Serving: boolptr(true), + Terminating: boolptr(false), + }, + TargetRef: &corev1.ObjectReference{ + Kind: "Node", + Name: "barbaz", + }, }, }, } @@ -183,6 +205,18 @@ func TestEndpointSliceDiscoveryBeforeRun(t *testing.T) { "__meta_kubernetes_endpointslice_port_name": "testport", "__meta_kubernetes_endpointslice_port_protocol": "TCP", }, + { + "__address__": "4.5.6.7:9000", + "__meta_kubernetes_endpointslice_address_target_kind": "Node", + "__meta_kubernetes_endpointslice_address_target_name": "barbaz", + "__meta_kubernetes_endpointslice_endpoint_conditions_ready": "true", + "__meta_kubernetes_endpointslice_endpoint_conditions_serving": "true", + "__meta_kubernetes_endpointslice_endpoint_conditions_terminating": "false", + "__meta_kubernetes_endpointslice_port": "9000", + "__meta_kubernetes_endpointslice_port_app_protocol": "http", + "__meta_kubernetes_endpointslice_port_name": "testport", + "__meta_kubernetes_endpointslice_port_protocol": "TCP", + }, }, Labels: model.LabelSet{ "__meta_kubernetes_endpointslice_address_type": "IPv4", @@ -233,6 +267,17 @@ func TestEndpointSliceDiscoveryBeforeRunV1beta1(t *testing.T) { "__meta_kubernetes_endpointslice_port_name": "testport", "__meta_kubernetes_endpointslice_port_protocol": "TCP", }, + { + "__address__": "4.5.6.7:9000", + "__meta_kubernetes_endpointslice_address_target_kind": "Node", + "__meta_kubernetes_endpointslice_address_target_name": "barbaz", + "__meta_kubernetes_endpointslice_endpoint_conditions_ready": "true", + "__meta_kubernetes_endpointslice_endpoint_conditions_serving": "true", + "__meta_kubernetes_endpointslice_endpoint_conditions_terminating": "false", + "__meta_kubernetes_endpointslice_port": "9000", + "__meta_kubernetes_endpointslice_port_name": "testport", + "__meta_kubernetes_endpointslice_port_protocol": "TCP", + }, }, Labels: model.LabelSet{ "__meta_kubernetes_endpointslice_address_type": "IPv4", @@ -419,6 +464,18 @@ func TestEndpointSliceDiscoveryDelete(t *testing.T) { "__meta_kubernetes_endpointslice_port_name": "testport", "__meta_kubernetes_endpointslice_port_protocol": "TCP", }, + { + "__address__": "4.5.6.7:9000", + "__meta_kubernetes_endpointslice_address_target_kind": "Node", + "__meta_kubernetes_endpointslice_address_target_name": "barbaz", + "__meta_kubernetes_endpointslice_endpoint_conditions_ready": "true", + "__meta_kubernetes_endpointslice_endpoint_conditions_serving": "true", + "__meta_kubernetes_endpointslice_endpoint_conditions_terminating": "false", + "__meta_kubernetes_endpointslice_port": "9000", + "__meta_kubernetes_endpointslice_port_app_protocol": "http", + "__meta_kubernetes_endpointslice_port_name": "testport", + "__meta_kubernetes_endpointslice_port_protocol": "TCP", + }, }, Labels: map[model.LabelName]model.LabelValue{ "__meta_kubernetes_endpointslice_address_type": "IPv4", @@ -503,6 +560,18 @@ func TestEndpointSliceDiscoveryUpdate(t *testing.T) { "__meta_kubernetes_endpointslice_port_name": "testport", "__meta_kubernetes_endpointslice_port_protocol": "TCP", }, + { + "__address__": "4.5.6.7:9000", + "__meta_kubernetes_endpointslice_address_target_kind": "Node", + "__meta_kubernetes_endpointslice_address_target_name": "barbaz", + "__meta_kubernetes_endpointslice_endpoint_conditions_ready": "true", + "__meta_kubernetes_endpointslice_endpoint_conditions_serving": "true", + "__meta_kubernetes_endpointslice_endpoint_conditions_terminating": "false", + "__meta_kubernetes_endpointslice_port": "9000", + "__meta_kubernetes_endpointslice_port_app_protocol": "http", + "__meta_kubernetes_endpointslice_port_name": "testport", + "__meta_kubernetes_endpointslice_port_protocol": "TCP", + }, }, Labels: model.LabelSet{ "__meta_kubernetes_endpointslice_address_type": "IPv4", @@ -576,6 +645,18 @@ func TestEndpointSliceDiscoveryEmptyEndpoints(t *testing.T) { "__meta_kubernetes_endpointslice_port_name": "testport", "__meta_kubernetes_endpointslice_port_protocol": "TCP", }, + { + "__address__": "4.5.6.7:9000", + "__meta_kubernetes_endpointslice_address_target_kind": "Node", + "__meta_kubernetes_endpointslice_address_target_name": "barbaz", + "__meta_kubernetes_endpointslice_endpoint_conditions_ready": "true", + "__meta_kubernetes_endpointslice_endpoint_conditions_serving": "true", + "__meta_kubernetes_endpointslice_endpoint_conditions_terminating": "false", + "__meta_kubernetes_endpointslice_port": "9000", + "__meta_kubernetes_endpointslice_port_app_protocol": "http", + "__meta_kubernetes_endpointslice_port_name": "testport", + "__meta_kubernetes_endpointslice_port_protocol": "TCP", + }, }, Labels: model.LabelSet{ "__meta_kubernetes_endpointslice_address_type": "IPv4", @@ -644,6 +725,18 @@ func TestEndpointSliceDiscoveryWithService(t *testing.T) { "__meta_kubernetes_endpointslice_port_name": "testport", "__meta_kubernetes_endpointslice_port_protocol": "TCP", }, + { + "__address__": "4.5.6.7:9000", + "__meta_kubernetes_endpointslice_address_target_kind": "Node", + "__meta_kubernetes_endpointslice_address_target_name": "barbaz", + "__meta_kubernetes_endpointslice_endpoint_conditions_ready": "true", + "__meta_kubernetes_endpointslice_endpoint_conditions_serving": "true", + "__meta_kubernetes_endpointslice_endpoint_conditions_terminating": "false", + "__meta_kubernetes_endpointslice_port": "9000", + "__meta_kubernetes_endpointslice_port_app_protocol": "http", + "__meta_kubernetes_endpointslice_port_name": "testport", + "__meta_kubernetes_endpointslice_port_protocol": "TCP", + }, }, Labels: model.LabelSet{ "__meta_kubernetes_endpointslice_address_type": "IPv4", @@ -728,6 +821,18 @@ func TestEndpointSliceDiscoveryWithServiceUpdate(t *testing.T) { "__meta_kubernetes_endpointslice_port_protocol": "TCP", "__meta_kubernetes_endpointslice_port_app_protocol": "http", }, + { + "__address__": "4.5.6.7:9000", + "__meta_kubernetes_endpointslice_address_target_kind": "Node", + "__meta_kubernetes_endpointslice_address_target_name": "barbaz", + "__meta_kubernetes_endpointslice_endpoint_conditions_ready": "true", + "__meta_kubernetes_endpointslice_endpoint_conditions_serving": "true", + "__meta_kubernetes_endpointslice_endpoint_conditions_terminating": "false", + "__meta_kubernetes_endpointslice_port": "9000", + "__meta_kubernetes_endpointslice_port_app_protocol": "http", + "__meta_kubernetes_endpointslice_port_name": "testport", + "__meta_kubernetes_endpointslice_port_protocol": "TCP", + }, }, Labels: model.LabelSet{ "__meta_kubernetes_endpointslice_address_type": "IPv4", @@ -747,7 +852,8 @@ func TestEndpointSliceDiscoveryWithServiceUpdate(t *testing.T) { func TestEndpointsSlicesDiscoveryWithNodeMetadata(t *testing.T) { metadataConfig := AttachMetadataConfig{Node: true} - nodeLabels := map[string]string{"az": "us-east1"} + nodeLabels1 := map[string]string{"az": "us-east1"} + nodeLabels2 := map[string]string{"az": "us-west2"} svc := &corev1.Service{ ObjectMeta: metav1.ObjectMeta{ Name: "testendpoints", @@ -757,7 +863,7 @@ func TestEndpointsSlicesDiscoveryWithNodeMetadata(t *testing.T) { }, }, } - objs := []runtime.Object{makeEndpointSliceV1(), makeNode("foobar", "", "", nodeLabels, nil), svc} + objs := []runtime.Object{makeEndpointSliceV1(), makeNode("foobar", "", "", nodeLabels1, nil), makeNode("barbaz", "", "", nodeLabels2, nil), svc} n, _ := makeDiscoveryWithMetadata(RoleEndpointSlice, NamespaceDiscovery{}, metadataConfig, objs...) k8sDiscoveryTest{ @@ -804,6 +910,21 @@ func TestEndpointsSlicesDiscoveryWithNodeMetadata(t *testing.T) { "__meta_kubernetes_endpointslice_port_name": "testport", "__meta_kubernetes_endpointslice_port_protocol": "TCP", }, + { + "__address__": "4.5.6.7:9000", + "__meta_kubernetes_endpointslice_address_target_kind": "Node", + "__meta_kubernetes_endpointslice_address_target_name": "barbaz", + "__meta_kubernetes_endpointslice_endpoint_conditions_ready": "true", + "__meta_kubernetes_endpointslice_endpoint_conditions_serving": "true", + "__meta_kubernetes_endpointslice_endpoint_conditions_terminating": "false", + "__meta_kubernetes_endpointslice_port": "9000", + "__meta_kubernetes_endpointslice_port_app_protocol": "http", + "__meta_kubernetes_endpointslice_port_name": "testport", + "__meta_kubernetes_endpointslice_port_protocol": "TCP", + "__meta_kubernetes_node_label_az": "us-west2", + "__meta_kubernetes_node_labelpresent_az": "true", + "__meta_kubernetes_node_name": "barbaz", + }, }, Labels: model.LabelSet{ "__meta_kubernetes_endpointslice_address_type": "IPv4", @@ -821,7 +942,8 @@ func TestEndpointsSlicesDiscoveryWithNodeMetadata(t *testing.T) { func TestEndpointsSlicesDiscoveryWithUpdatedNodeMetadata(t *testing.T) { metadataConfig := AttachMetadataConfig{Node: true} - nodeLabels := map[string]string{"az": "us-east1"} + nodeLabels1 := map[string]string{"az": "us-east1"} + nodeLabels2 := map[string]string{"az": "us-west2"} svc := &corev1.Service{ ObjectMeta: metav1.ObjectMeta{ Name: "testendpoints", @@ -831,16 +953,17 @@ func TestEndpointsSlicesDiscoveryWithUpdatedNodeMetadata(t *testing.T) { }, }, } - node := makeNode("foobar", "", "", nodeLabels, nil) - objs := []runtime.Object{makeEndpointSliceV1(), node, svc} + node1 := makeNode("foobar", "", "", nodeLabels1, nil) + node2 := makeNode("barbaz", "", "", nodeLabels2, nil) + objs := []runtime.Object{makeEndpointSliceV1(), node1, node2, svc} n, c := makeDiscoveryWithMetadata(RoleEndpointSlice, NamespaceDiscovery{}, metadataConfig, objs...) k8sDiscoveryTest{ discovery: n, expectedMaxItems: 2, afterStart: func() { - node.Labels["az"] = "us-central1" - c.CoreV1().Nodes().Update(context.Background(), node, metav1.UpdateOptions{}) + node1.Labels["az"] = "us-central1" + c.CoreV1().Nodes().Update(context.Background(), node1, metav1.UpdateOptions{}) }, expectedRes: map[string]*targetgroup.Group{ "endpointslice/default/testendpoints": { @@ -859,7 +982,7 @@ func TestEndpointsSlicesDiscoveryWithUpdatedNodeMetadata(t *testing.T) { "__meta_kubernetes_endpointslice_port_app_protocol": "http", "__meta_kubernetes_endpointslice_port_name": "testport", "__meta_kubernetes_endpointslice_port_protocol": "TCP", - "__meta_kubernetes_node_label_az": "us-central1", + "__meta_kubernetes_node_label_az": "us-east1", "__meta_kubernetes_node_labelpresent_az": "true", "__meta_kubernetes_node_name": "foobar", }, @@ -883,6 +1006,21 @@ func TestEndpointsSlicesDiscoveryWithUpdatedNodeMetadata(t *testing.T) { "__meta_kubernetes_endpointslice_port_name": "testport", "__meta_kubernetes_endpointslice_port_protocol": "TCP", }, + { + "__address__": "4.5.6.7:9000", + "__meta_kubernetes_endpointslice_address_target_kind": "Node", + "__meta_kubernetes_endpointslice_address_target_name": "barbaz", + "__meta_kubernetes_endpointslice_endpoint_conditions_ready": "true", + "__meta_kubernetes_endpointslice_endpoint_conditions_serving": "true", + "__meta_kubernetes_endpointslice_endpoint_conditions_terminating": "false", + "__meta_kubernetes_endpointslice_port": "9000", + "__meta_kubernetes_endpointslice_port_app_protocol": "http", + "__meta_kubernetes_endpointslice_port_name": "testport", + "__meta_kubernetes_endpointslice_port_protocol": "TCP", + "__meta_kubernetes_node_label_az": "us-west2", + "__meta_kubernetes_node_labelpresent_az": "true", + "__meta_kubernetes_node_name": "barbaz", + }, }, Labels: model.LabelSet{ "__meta_kubernetes_endpointslice_address_type": "IPv4", @@ -1007,6 +1145,18 @@ func TestEndpointSliceDiscoveryNamespaces(t *testing.T) { "__meta_kubernetes_endpointslice_port_protocol": "TCP", "__meta_kubernetes_endpointslice_port_app_protocol": "http", }, + { + "__address__": "4.5.6.7:9000", + "__meta_kubernetes_endpointslice_address_target_kind": "Node", + "__meta_kubernetes_endpointslice_address_target_name": "barbaz", + "__meta_kubernetes_endpointslice_endpoint_conditions_ready": "true", + "__meta_kubernetes_endpointslice_endpoint_conditions_serving": "true", + "__meta_kubernetes_endpointslice_endpoint_conditions_terminating": "false", + "__meta_kubernetes_endpointslice_port": "9000", + "__meta_kubernetes_endpointslice_port_app_protocol": "http", + "__meta_kubernetes_endpointslice_port_name": "testport", + "__meta_kubernetes_endpointslice_port_protocol": "TCP", + }, }, Labels: model.LabelSet{ "__meta_kubernetes_endpointslice_address_type": "IPv4", @@ -1139,6 +1289,18 @@ func TestEndpointSliceDiscoveryOwnNamespace(t *testing.T) { "__meta_kubernetes_endpointslice_port_protocol": "TCP", "__meta_kubernetes_endpointslice_port_app_protocol": "http", }, + { + "__address__": "4.5.6.7:9000", + "__meta_kubernetes_endpointslice_address_target_kind": "Node", + "__meta_kubernetes_endpointslice_address_target_name": "barbaz", + "__meta_kubernetes_endpointslice_endpoint_conditions_ready": "true", + "__meta_kubernetes_endpointslice_endpoint_conditions_serving": "true", + "__meta_kubernetes_endpointslice_endpoint_conditions_terminating": "false", + "__meta_kubernetes_endpointslice_port": "9000", + "__meta_kubernetes_endpointslice_port_app_protocol": "http", + "__meta_kubernetes_endpointslice_port_name": "testport", + "__meta_kubernetes_endpointslice_port_protocol": "TCP", + }, }, Labels: model.LabelSet{ "__meta_kubernetes_endpointslice_address_type": "IPv4", diff --git a/discovery/kubernetes/kubernetes.go b/discovery/kubernetes/kubernetes.go index a44bd513cea..e87a1c9b24e 100644 --- a/discovery/kubernetes/kubernetes.go +++ b/discovery/kubernetes/kubernetes.go @@ -761,15 +761,21 @@ func (d *Discovery) newEndpointsByNodeInformer(plw *cache.ListWatch) cache.Share indexers[nodeIndex] = func(obj interface{}) ([]string, error) { e, ok := obj.(*apiv1.Endpoints) if !ok { - return nil, fmt.Errorf("object is not a pod") + return nil, fmt.Errorf("object is not endpoints") } var nodes []string for _, target := range e.Subsets { for _, addr := range target.Addresses { - if addr.NodeName == nil { - continue + if addr.TargetRef != nil { + switch addr.TargetRef.Kind { + case "Pod": + if addr.NodeName != nil { + nodes = append(nodes, *addr.NodeName) + } + case "Node": + nodes = append(nodes, addr.TargetRef.Name) + } } - nodes = append(nodes, *addr.NodeName) } } return nodes, nil @@ -789,17 +795,29 @@ func (d *Discovery) newEndpointSlicesByNodeInformer(plw *cache.ListWatch, object switch e := obj.(type) { case *disv1.EndpointSlice: for _, target := range e.Endpoints { - if target.NodeName == nil { - continue + if target.TargetRef != nil { + switch target.TargetRef.Kind { + case "Pod": + if target.NodeName != nil { + nodes = append(nodes, *target.NodeName) + } + case "Node": + nodes = append(nodes, target.TargetRef.Name) + } } - nodes = append(nodes, *target.NodeName) } case *disv1beta1.EndpointSlice: for _, target := range e.Endpoints { - if target.NodeName == nil { - continue + if target.TargetRef != nil { + switch target.TargetRef.Kind { + case "Pod": + if target.NodeName != nil { + nodes = append(nodes, *target.NodeName) + } + case "Node": + nodes = append(nodes, target.TargetRef.Name) + } } - nodes = append(nodes, *target.NodeName) } default: return nil, fmt.Errorf("object is not an endpointslice") diff --git a/discovery/kubernetes/node.go b/discovery/kubernetes/node.go index 16a06e7a0c2..d0a6d2780da 100644 --- a/discovery/kubernetes/node.go +++ b/discovery/kubernetes/node.go @@ -209,7 +209,7 @@ func (n *Node) buildNode(node *apiv1.Node) *targetgroup.Group { return tg } -// nodeAddresses returns the provided node's address, based on the priority: +// nodeAddress returns the provided node's address, based on the priority: // 1. NodeInternalIP // 2. NodeInternalDNS // 3. NodeExternalIP diff --git a/docs/configuration/configuration.md b/docs/configuration/configuration.md index f27f8256a54..db41c3247d0 100644 --- a/docs/configuration/configuration.md +++ b/docs/configuration/configuration.md @@ -73,6 +73,39 @@ global: # Reloading the configuration will reopen the file. [ query_log_file: ] + # An uncompressed response body larger than this many bytes will cause the + # scrape to fail. 0 means no limit. Example: 100MB. + # This is an experimental feature, this behaviour could + # change or be removed in the future. + [ body_size_limit: | default = 0 ] + + # Per-scrape limit on number of scraped samples that will be accepted. + # If more than this number of samples are present after metric relabeling + # the entire scrape will be treated as failed. 0 means no limit. + [ sample_limit: | default = 0 ] + + # Per-scrape limit on number of labels that will be accepted for a sample. If + # more than this number of labels are present post metric-relabeling, the + # entire scrape will be treated as failed. 0 means no limit. + [ label_limit: | default = 0 ] + + # Per-scrape limit on length of labels name that will be accepted for a sample. + # If a label name is longer than this number post metric-relabeling, the entire + # scrape will be treated as failed. 0 means no limit. + [ label_name_length_limit: | default = 0 ] + + # Per-scrape limit on length of labels value that will be accepted for a sample. + # If a label value is longer than this number post metric-relabeling, the + # entire scrape will be treated as failed. 0 means no limit. + [ label_value_length_limit: | default = 0 ] + + # Per-scrape config limit on number of unique targets that will be + # accepted. If more than this number of targets are present after target + # relabeling, Prometheus will mark the targets as failed without scraping them. + # 0 means no limit. This is an experimental feature, this behaviour could + # change in the future. + [ target_limit: | default = 0 ] + # Rule files specifies a list of globs. Rules and alerts are read from # all matching files. rule_files: @@ -134,6 +167,10 @@ job_name: # Per-scrape timeout when scraping this job. [ scrape_timeout: | default = ] +# Whether to scrape a classic histogram that is also exposed as a native +# histogram (has no effect without --enable-feature=native-histograms). +[ scrape_classic_histograms: | default = false ] + # The HTTP resource path on which to fetch metrics from targets. [ metrics_path: | default = /metrics ] @@ -376,6 +413,11 @@ metric_relabel_configs: # 0 means no limit. This is an experimental feature, this behaviour could # change in the future. [ target_limit: | default = 0 ] + +# Limit on total number of positive and negative buckets allowed in a single +# native histogram. If this is exceeded, the entire scrape will be treated as +# failed. 0 means no limit. +[ native_histogram_bucket_limit: | default = 0 ] ``` Where `` must be unique across all scrape configurations. @@ -385,11 +427,16 @@ Where `` must be unique across all scrape configurations. A `tls_config` allows configuring TLS connections. ```yaml -# CA certificate to validate API server certificate with. +# CA certificate to validate API server certificate with. At most one of ca and ca_file is allowed. +[ ca: ] [ ca_file: ] -# Certificate and key files for client cert authentication to the server. +# Certificate and key for client cert authentication to the server. +# At most one of cert and cert_file is allowed. +# At most one of key and key_file is allowed. +[ cert: ] [ cert_file: ] +[ key: ] [ key_file: ] # ServerName extension to indicate the name of the server. @@ -576,6 +623,8 @@ The following meta labels are available on targets during [relabeling](#relabel_ # The information to access the Consul API. It is to be defined # as the Consul documentation requires. [ server: | default = "localhost:8500" ] +# Prefix for URIs for when consul is behind an API gateway (reverse proxy). +[ path_prefix: ] [ token: ] [ datacenter: ] # Namespaces are only supported in Consul Enterprise. @@ -3422,7 +3471,7 @@ authorization: [ credentials_file: ] # Optionally configures AWS's Signature Verification 4 signing process to -# sign requests. Cannot be set at the same time as basic_auth, authorization, or oauth2. +# sign requests. Cannot be set at the same time as basic_auth, authorization, oauth2, or azuread. # To use the default credentials from the AWS SDK, use `sigv4: {}`. sigv4: # The AWS region. If blank, the region from the default credentials chain @@ -3441,10 +3490,20 @@ sigv4: [ role_arn: ] # Optional OAuth 2.0 configuration. -# Cannot be used at the same time as basic_auth, authorization, or sigv4. +# Cannot be used at the same time as basic_auth, authorization, sigv4, or azuread. oauth2: [ ] +# Optional AzureAD configuration. +# Cannot be used at the same time as basic_auth, authorization, oauth2, or sigv4. +azuread: + # The Azure Cloud. Options are 'AzurePublic', 'AzureChina', or 'AzureGovernment'. + [ cloud: | default = AzurePublic ] + + # Azure User-assigned Managed identity. + [ managed_identity: + [ client_id: ] + # Configures the remote write request's TLS settings. tls_config: [ ] diff --git a/docs/configuration/https.md b/docs/configuration/https.md index d31aca7b4b6..bc83e07a380 100644 --- a/docs/configuration/https.md +++ b/docs/configuration/https.md @@ -44,6 +44,13 @@ tls_server_config: # CA certificate for client certificate authentication to the server. [ client_ca_file: ] + # Verify that the client certificate has a Subject Alternate Name (SAN) + # which is an exact match to an entry in this list, else terminate the + # connection. SAN match can be one or multiple of the following: DNS, + # IP, e-mail, or URI address from https://pkg.go.dev/crypto/x509#Certificate. + [ client_allowed_sans: + [ - ] ] + # Minimum TLS version that is acceptable. [ min_version: | default = "TLS12" ] diff --git a/docs/getting_started.md b/docs/getting_started.md index 11d8d0fb82b..e89ac705eeb 100644 --- a/docs/getting_started.md +++ b/docs/getting_started.md @@ -264,4 +264,4 @@ process ID. While Prometheus does have recovery mechanisms in the case that there is an abrupt process failure it is recommend to use the `SIGTERM` signal to cleanly shutdown a Prometheus instance. If you're running on Linux this can be performed -by using `kill -s SIGHUP `, replacing `` with your Prometheus process ID. +by using `kill -s SIGTERM `, replacing `` with your Prometheus process ID. diff --git a/docs/querying/api.md b/docs/querying/api.md index ef7fa54c67e..edce366ee6d 100644 --- a/docs/querying/api.md +++ b/docs/querying/api.md @@ -1074,6 +1074,10 @@ The following endpoint returns various cardinality statistics about the Promethe ``` GET /api/v1/status/tsdb ``` +URL query parameters: +- `limit=`: Limit the number of returned items to a given number for each set of statistics. By default, 10 items are returned. + +The `data` section of the query result consists of - **headStats**: This provides the following data about the head block of the TSDB: - **numSeries**: The number of series. - **chunkCount**: The number of chunks. diff --git a/docs/querying/functions.md b/docs/querying/functions.md index e92a58937d0..e1a0b4a769c 100644 --- a/docs/querying/functions.md +++ b/docs/querying/functions.md @@ -359,7 +359,7 @@ increase(http_requests_total{job="api-server"}[5m]) ``` `increase` acts on native histograms by calculating a new histogram where each -compononent (sum and count of observations, buckets) is the increase between +component (sum and count of observations, buckets) is the increase between the respective component in the first and last native histogram in `v`. However, each element in `v` that contains a mix of float and native histogram samples within the range, will be missing from the result vector. @@ -589,8 +589,9 @@ over time and return an instant vector with per-series aggregation results: Note that all values in the specified interval have the same weight in the aggregation even if the values are not equally spaced throughout the interval. -`count_over_time`, `last_over_time`, and `present_over_time` handle native -histograms as expected. All other functions ignore histogram samples. +`avg_over_time`, `sum_over_time`, `count_over_time`, `last_over_time`, and +`present_over_time` handle native histograms as expected. All other functions +ignore histogram samples. ## Trigonometric Functions diff --git a/docs/querying/operators.md b/docs/querying/operators.md index 0cd53689412..c691a0f1a8a 100644 --- a/docs/querying/operators.md +++ b/docs/querying/operators.md @@ -318,19 +318,23 @@ histograms is still very limited. Logical/set binary operators work as expected even if histogram samples are involved. They only check for the existence of a vector element and don't change their behavior depending on the sample type of an element (float or -histogram). +histogram). The `count` aggregation operator works similarly. -The binary `+` operator between two native histograms and the `sum` aggregation -operator to aggregate native histograms are fully supported. Even if the -histograms involved have different bucket layouts, the buckets are -automatically converted appropriately so that the operation can be +The binary `+` and `-` operators between two native histograms and the `sum` +and `avg` aggregation operators to aggregate native histograms are fully +supported. Even if the histograms involved have different bucket layouts, the +buckets are automatically converted appropriately so that the operation can be performed. (With the currently supported bucket schemas, that's always -possible.) If either operator has to sum up a mix of histogram samples and +possible.) If either operator has to aggregate a mix of histogram samples and float samples, the corresponding vector element is removed from the output vector entirely. -All other operators do not behave in a meaningful way. They either treat the -histogram sample as if it were a float sample of value 0, or (in case of -arithmetic operations between a scalar and a vector) they leave the histogram -sample unchanged. This behavior will change to a meaningful one before native -histograms are a stable feature. +The binary `*` operator works between a native histogram and a float in any +order, while the binary `/` operator can be used between a native histogram +and a float in that exact order. + +All other operators (and unmentioned cases for the above operators) do not +behave in a meaningful way. They either treat the histogram sample as if it +were a float sample of value 0, or (in case of arithmetic operations between a +scalar and a vector) they leave the histogram sample unchanged. This behavior +will change to a meaningful one before native histograms are a stable feature. diff --git a/docs/stability.md b/docs/stability.md index e4cc3203b21..1fd2e51e0c6 100644 --- a/docs/stability.md +++ b/docs/stability.md @@ -18,12 +18,13 @@ Things considered stable for 2.x: * Configuration file format (minus the service discovery remote read/write, see below) * Rule/alert file format * Console template syntax and semantics +* Remote write sending, per the [1.0 specification](https://prometheus.io/docs/concepts/remote_write_spec/). Things considered unstable for 2.x: * Any feature listed as experimental or subject to change, including: * The [`holt_winters` PromQL function](https://github.com/prometheus/prometheus/issues/2458) - * Remote read, remote write and the remote read endpoint + * Remote write receiving, remote read and the remote read endpoint * Server-side HTTPS and basic authentication * Service discovery integrations, with the exception of `static_configs` and `file_sd_configs` * Go APIs of packages that are part of the server diff --git a/documentation/examples/remote_storage/go.mod b/documentation/examples/remote_storage/go.mod index 5e0e6ddb134..1db3e9a9e4a 100644 --- a/documentation/examples/remote_storage/go.mod +++ b/documentation/examples/remote_storage/go.mod @@ -8,7 +8,7 @@ require ( github.com/gogo/protobuf v1.3.2 github.com/golang/snappy v0.0.4 github.com/influxdata/influxdb v1.11.0 - github.com/prometheus/client_golang v1.14.0 + github.com/prometheus/client_golang v1.15.0 github.com/prometheus/common v0.42.0 github.com/prometheus/prometheus v0.43.0 github.com/stretchr/testify v1.8.2 @@ -29,7 +29,7 @@ require ( github.com/grafana/regexp v0.0.0-20221122212121-6b5c0a4cb7fd // indirect github.com/jmespath/go-jmespath v0.4.0 // indirect github.com/jpillora/backoff v1.0.0 // indirect - github.com/kr/pretty v0.3.0 // indirect + github.com/kr/text v0.2.0 // indirect github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f // indirect github.com/pkg/errors v0.9.1 // indirect @@ -51,7 +51,7 @@ require ( golang.org/x/text v0.8.0 // indirect golang.org/x/time v0.3.0 // indirect google.golang.org/appengine v1.6.7 // indirect - google.golang.org/protobuf v1.29.0 // indirect + google.golang.org/protobuf v1.30.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/documentation/examples/remote_storage/go.sum b/documentation/examples/remote_storage/go.sum index 11c29451518..c4350e78b09 100644 --- a/documentation/examples/remote_storage/go.sum +++ b/documentation/examples/remote_storage/go.sum @@ -141,8 +141,7 @@ github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxv github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= -github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -181,8 +180,8 @@ github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXP github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= github.com/prometheus/client_golang v1.11.0/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0= -github.com/prometheus/client_golang v1.14.0 h1:nJdhIvne2eSX/XRAFV9PcvFFRbrjbcTUj0VP62TMhnw= -github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y= +github.com/prometheus/client_golang v1.15.0 h1:5fCgGYogn0hFdhyhLbw7hEsWxufKtY9klyvdNfFlFhM= +github.com/prometheus/client_golang v1.15.0/go.mod h1:e9yaBhRPU2pPNsZwE+JdQl0KEt1N9XgF6zxWmaC0xOk= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= @@ -204,7 +203,6 @@ github.com/prometheus/procfs v0.9.0 h1:wzCHvIvM5SxWqYvwgVL7yJY8Lz3PKn49KQtpgMYJf github.com/prometheus/procfs v0.9.0/go.mod h1:+pB4zwohETzFnmlpe6yd2lSc+0/46IYZRB/chUwxUZY= github.com/prometheus/prometheus v0.43.0 h1:18iCSfrbAHbXvYFvR38U1Pt4uZmU9SmDcCpCrBKUiGg= github.com/prometheus/prometheus v0.43.0/go.mod h1:2BA14LgBeqlPuzObSEbh+Y+JwLH2GcqDlJKbF2sA6FM= -github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= github.com/scaleway/scaleway-sdk-go v1.0.0-beta.14 h1:yFl3jyaSVLNYXlnNYM5z2pagEk1dYQhfr1p20T1NyKY= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= @@ -341,14 +339,12 @@ google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzi google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.29.0 h1:44S3JjaKmLEE4YIkjzexaP+NzZsudE3Zin5Njn/pYX0= -google.golang.org/protobuf v1.29.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng= +google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= -gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/documentation/images/architecture.svg b/documentation/images/architecture.svg index df93e13cb20..4e1e85995d6 100644 --- a/documentation/images/architecture.svg +++ b/documentation/images/architecture.svg @@ -1,2 +1,4 @@ + + -
pull metrics


[Not supported by viewer]
HDD / SSD
[Not supported by viewer]
Pushgateway
Pushgateway
Short-lived jobs
Short-lived jobs
Jobs / Exporters
Jobs / Exporters
Storage
Storage
Retrieval
Retrieval
PromQL
PromQL
Prometheus Server
[Not supported by viewer]
Node
<b>Node</b>
Service Discovery

Service Discovery<div><br></div>
             find 
                 targets
[Not supported by viewer]
Prometheus Server
Prometheus Server
Alertmanager
Alertmanager
push alerts         


[Not supported by viewer]
Web UI
Web UI
Grafana
Grafana
API clients
API clients
PagerDuty
PagerDuty
Email
Email
  • DNS
  • Kubernetes
  • Consul
  • ...
  • Custom integration
[Not supported by viewer]
              notify
[Not supported by viewer]
...
...
\ No newline at end of file +
pull metrics


pull metrics...
HDD / SSD
HDD / SSD
Pushgateway
Pushgateway
Short-lived jobs
Short-lived jobs
Jobs / Exporters
Jobs / Exporters
Storage
Storage
Retrieval
Retrieval
PromQL
PromQL
Prometheus Server
Prometheus Server
Node
Node
Service Discovery

Service Discovery
             find 
                 targets
find...
Prometheus Server
Prometheus Server
Alertmanager
Alertmanager
push alerts         


push alerts...
Web UI
Web UI
Grafana
Grafana
API clients
API clients
PagerDuty
PagerDuty
Email
Email
  • DNS
  • Kubernetes
  • Consul
  • ...
  • Custom integration
DNSKubernetesConsul...Custom in...
              notify
              notify
...
...
Text is not SVG - cannot display
\ No newline at end of file diff --git a/documentation/images/internal_architecture.svg b/documentation/images/internal_architecture.svg index 5948186a7da..1242548ddb9 100644 --- a/documentation/images/internal_architecture.svg +++ b/documentation/images/internal_architecture.svg @@ -1,2 +1,4 @@ + + -
Fanout Storage
Fanout Storage
read/write
series data 
[Not supported by viewer]
Local
Storage
Local<br>Storage
disk
disk
write series data
write series data
Remote Storage
Remote Storage
send
alerts
[Not supported by viewer]
append rule results
append rule results
Rule Manager
Rule Manager
Notifier
Notifier
discover Alertmanager targets
discover Alertmanager targets
Notifier Discovery
Notifier Discovery
update
Alertmanager
targets
[Not supported by viewer]
Alertmanagers
Alertmanagers
send
alerts
[Not supported by viewer]
read/write
series data
[Not supported by viewer]
scrape
metrics
[Not supported by viewer]
Scrape Manager
Scrape Manager
append 
samples 
[Not supported by viewer]
update scrape targets
[Not supported by viewer]
discover scrape targets
discover scrape targets
Scrape Discovery
Scrape Discovery
query
query
PromQL
[Not supported by viewer]
read series data
read series data
Remote Read Endpoints
Remote Read Endpoints<br>
Remote Write Endpoints
Remote Write Endpoints
Targets
Targets
Service Discovery
Service Discovery
Web API/UI
Web API/UI
query
query
PromQL
[Not supported by viewer]
Reload Handler
Reload Handler
Termination
Handler
Termination<br>Handler<br>
(most other
components)
[Not supported by viewer]
reload
reload
terminate
terminate<br>
view/control
view/control
view/control
view/control
Web Clients
Web Clients
Prometheus Server
<b>Prometheus Server</b>
\ No newline at end of file +
Fanout Storage
Fanout Storage
read/write
series data 
read/write...
Local
Storage
Local...
disk
disk
write series data
write series data
Remote Storage
Remote Storage
send
alerts
send...
append rule results
append rule results
Rule Manager
Rule Manager
Notifier
Notifier
discover Alertmanager targets
discover Alertmanager targets
Notifier Discovery
Notifier Disco...
update
Alertmanager
targets
update...
Alertmanagers
Alertmanagers
send
alerts
send...
read/write
series data
read/write...
scrape
metrics
scrape...
Scrape Manager
Scrape Manager
append 
samples 
append...
update scrape targets
update scrape targets
discover scrape targets
discover scrape targets
Scrape Discovery
Scrape Discove...
query
query
PromQL
PromQL
read series data
read series data
Remote Read Endpoints
Remote Read En...
Remote Write Endpoints
Remote Write E...
Targets
Targets
Service Discovery
Service Discov...
Web API/UI
Web API/UI
query
query
PromQL
PromQL
Reload Handler
Reload Handler
Termination
Handler
Termination...
(most other
components)
(most other...
reload
reload
terminate
termin...
view/control
view/c...
view/control
view/control
Web Clients
Web Clients
Prometheus Server
Prometheus Server
Text is not SVG - cannot display
\ No newline at end of file diff --git a/go.mod b/go.mod index 7b309b03f5e..9e4ab7ce95d 100644 --- a/go.mod +++ b/go.mod @@ -4,18 +4,20 @@ go 1.19 require ( github.com/Azure/azure-sdk-for-go v65.0.0+incompatible - github.com/Azure/go-autorest/autorest v0.11.28 + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.3.1 + github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.2.1 + github.com/Azure/go-autorest/autorest v0.11.29 github.com/Azure/go-autorest/autorest/adal v0.9.23 github.com/alecthomas/kingpin/v2 v2.3.2 github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137 - github.com/aws/aws-sdk-go v1.44.245 + github.com/aws/aws-sdk-go v1.44.276 github.com/cespare/xxhash/v2 v2.2.0 github.com/dennwc/varint v1.0.0 - github.com/digitalocean/godo v1.98.0 - github.com/docker/docker v23.0.4+incompatible + github.com/digitalocean/godo v1.99.0 + github.com/docker/docker v24.0.2+incompatible github.com/edsrzf/mmap-go v1.1.0 github.com/envoyproxy/go-control-plane v0.11.0 - github.com/envoyproxy/protoc-gen-validate v0.10.1 + github.com/envoyproxy/protoc-gen-validate v1.0.1 github.com/fsnotify/fsnotify v1.6.0 github.com/go-kit/log v0.2.1 github.com/go-logfmt/logfmt v0.6.0 @@ -23,53 +25,53 @@ require ( github.com/go-zookeeper/zk v1.0.3 github.com/gogo/protobuf v1.3.2 github.com/golang/snappy v0.0.4 - github.com/google/pprof v0.0.0-20230406165453-00490a63f317 - github.com/gophercloud/gophercloud v1.3.0 + github.com/google/pprof v0.0.0-20230602150820-91b7bce49751 + github.com/gophercloud/gophercloud v1.4.0 github.com/grafana/regexp v0.0.0-20221122212121-6b5c0a4cb7fd github.com/grpc-ecosystem/grpc-gateway v1.16.0 - github.com/hashicorp/consul/api v1.20.0 - github.com/hashicorp/nomad/api v0.0.0-20230418003350-3067191c5197 - github.com/hetznercloud/hcloud-go v1.42.0 - github.com/ionos-cloud/sdk-go/v6 v6.1.6 + github.com/hashicorp/consul/api v1.21.0 + github.com/hashicorp/nomad/api v0.0.0-20230605233119-67e39d5d248f + github.com/hetznercloud/hcloud-go v1.45.1 + github.com/ionos-cloud/sdk-go/v6 v6.1.7 github.com/json-iterator/go v1.1.12 github.com/kolo/xmlrpc v0.0.0-20220921171641-a4b6fa1dd06b - github.com/linode/linodego v1.16.1 - github.com/miekg/dns v1.1.53 + github.com/linode/linodego v1.17.0 + github.com/miekg/dns v1.1.54 github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f github.com/oklog/run v1.1.0 github.com/oklog/ulid v1.3.1 github.com/ovh/go-ovh v1.4.1 github.com/pkg/errors v0.9.1 github.com/prometheus/alertmanager v0.25.0 - github.com/prometheus/client_golang v1.15.0 - github.com/prometheus/client_model v0.3.0 - github.com/prometheus/common v0.42.0 + github.com/prometheus/client_golang v1.15.1 + github.com/prometheus/client_model v0.4.0 + github.com/prometheus/common v0.44.0 github.com/prometheus/common/assets v0.2.0 github.com/prometheus/common/sigv4 v0.1.0 - github.com/prometheus/exporter-toolkit v0.9.1 - github.com/scaleway/scaleway-sdk-go v1.0.0-beta.15 + github.com/prometheus/exporter-toolkit v0.10.0 + github.com/scaleway/scaleway-sdk-go v1.0.0-beta.17 github.com/shurcooL/httpfs v0.0.0-20190707220628-8d4bc4ba7749 - github.com/stretchr/testify v1.8.2 + github.com/stretchr/testify v1.8.4 github.com/vultr/govultr/v2 v2.17.2 - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.40.0 - go.opentelemetry.io/otel v1.14.0 - go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.14.0 - go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.14.0 - go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.14.0 - go.opentelemetry.io/otel/sdk v1.14.0 - go.opentelemetry.io/otel/trace v1.14.0 - go.uber.org/atomic v1.10.0 + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.42.0 + go.opentelemetry.io/otel v1.16.0 + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.16.0 + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.16.0 + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.16.0 + go.opentelemetry.io/otel/sdk v1.16.0 + go.opentelemetry.io/otel/trace v1.16.0 + go.uber.org/atomic v1.11.0 go.uber.org/automaxprocs v1.5.2 go.uber.org/goleak v1.2.1 - golang.org/x/net v0.9.0 - golang.org/x/oauth2 v0.7.0 - golang.org/x/sync v0.1.0 - golang.org/x/sys v0.7.0 + golang.org/x/net v0.10.0 + golang.org/x/oauth2 v0.8.0 + golang.org/x/sync v0.2.0 + golang.org/x/sys v0.8.0 golang.org/x/time v0.3.0 - golang.org/x/tools v0.8.0 + golang.org/x/tools v0.9.3 google.golang.org/api v0.114.0 - google.golang.org/genproto v0.0.0-20230306155012-7f2fa6fef1f4 - google.golang.org/grpc v1.53.0 + google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 + google.golang.org/grpc v1.55.0 google.golang.org/protobuf v1.30.0 gopkg.in/yaml.v2 v2.4.0 gopkg.in/yaml.v3 v3.0.1 @@ -77,20 +79,24 @@ require ( k8s.io/apimachinery v0.26.2 k8s.io/client-go v0.26.2 k8s.io/klog v1.0.0 - k8s.io/klog/v2 v2.90.1 + k8s.io/klog/v2 v2.100.1 ) require ( cloud.google.com/go/compute/metadata v0.2.3 // indirect + github.com/Azure/azure-sdk-for-go/sdk/internal v1.3.0 // indirect + github.com/AzureAD/microsoft-authentication-library-for-go v0.8.1 // indirect github.com/coreos/go-systemd/v22 v22.5.0 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect - github.com/rogpeppe/go-internal v1.10.0 // indirect + github.com/kylelemons/godebug v1.1.0 // indirect + github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 // indirect + github.com/stretchr/objx v0.5.0 // indirect github.com/xhit/go-str2duration/v2 v2.1.0 // indirect ) require ( - cloud.google.com/go/compute v1.18.0 // indirect + cloud.google.com/go/compute v1.19.0 // indirect github.com/Azure/go-autorest v14.2.0+incompatible // indirect github.com/Azure/go-autorest/autorest/date v0.3.0 // indirect github.com/Azure/go-autorest/autorest/to v0.4.0 // indirect @@ -101,8 +107,8 @@ require ( github.com/armon/go-metrics v0.4.1 // indirect github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect github.com/beorn7/perks v1.0.1 // indirect - github.com/cenkalti/backoff/v4 v4.2.0 // indirect - github.com/cncf/xds/go v0.0.0-20230112175826-46e39c7b9b43 // indirect + github.com/cenkalti/backoff/v4 v4.2.1 // indirect + github.com/cncf/xds/go v0.0.0-20230428030218-4003588d1b74 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/docker/distribution v2.8.1+incompatible // indirect github.com/docker/go-connections v0.4.0 // indirect @@ -113,7 +119,7 @@ require ( github.com/felixge/httpsnoop v1.0.3 // indirect github.com/ghodss/yaml v1.0.0 // indirect github.com/go-kit/kit v0.12.0 // indirect - github.com/go-logr/logr v1.2.3 // indirect + github.com/go-logr/logr v1.2.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-openapi/analysis v0.21.4 // indirect github.com/go-openapi/errors v0.20.3 // indirect @@ -125,18 +131,18 @@ require ( github.com/go-openapi/validate v0.22.1 // indirect github.com/go-resty/resty/v2 v2.7.0 // indirect github.com/golang-jwt/jwt/v4 v4.5.0 // indirect - github.com/golang/glog v1.0.0 // indirect + github.com/golang/glog v1.1.0 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/golang/protobuf v1.5.3 // indirect github.com/google/gnostic v0.6.9 // indirect github.com/google/go-cmp v0.5.9 // indirect github.com/google/go-querystring v1.1.0 // indirect github.com/google/gofuzz v1.2.0 // indirect - github.com/google/uuid v1.3.0 // indirect + github.com/google/uuid v1.3.0 github.com/googleapis/enterprise-certificate-proxy v0.2.3 // indirect github.com/googleapis/gax-go/v2 v2.7.1 // indirect github.com/gorilla/websocket v1.5.0 // indirect - github.com/grpc-ecosystem/grpc-gateway/v2 v2.15.2 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.15.0 // indirect github.com/hashicorp/cronexpr v1.1.1 // indirect github.com/hashicorp/go-cleanhttp v0.5.2 // indirect github.com/hashicorp/go-hclog v1.4.0 // indirect @@ -168,19 +174,19 @@ require ( github.com/spf13/pflag v1.0.5 // indirect go.mongodb.org/mongo-driver v1.11.3 // indirect go.opencensus.io v0.24.0 // indirect - go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.14.0 // indirect - go.opentelemetry.io/otel/metric v0.37.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.16.0 // indirect + go.opentelemetry.io/otel/metric v1.16.0 // indirect go.opentelemetry.io/proto/otlp v0.19.0 // indirect - golang.org/x/crypto v0.7.0 // indirect - golang.org/x/exp v0.0.0-20230321023759-10a507213a29 + golang.org/x/crypto v0.8.0 // indirect + golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1 golang.org/x/mod v0.10.0 // indirect - golang.org/x/term v0.7.0 // indirect + golang.org/x/term v0.8.0 // indirect golang.org/x/text v0.9.0 // indirect google.golang.org/appengine v1.6.7 // indirect gopkg.in/inf.v0 v0.9.1 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gotest.tools/v3 v3.0.3 // indirect - k8s.io/kube-openapi v0.0.0-20230303024457-afdc3dddf62d // indirect + k8s.io/kube-openapi v0.0.0-20230501164219-8b0f38b5fd1f // indirect k8s.io/utils v0.0.0-20230308161112-d77c459e9343 // indirect sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect sigs.k8s.io/structured-merge-diff/v4 v4.2.3 // indirect diff --git a/go.sum b/go.sum index c699aa9dff8..897e6acff60 100644 --- a/go.sum +++ b/go.sum @@ -19,8 +19,8 @@ cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvf cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg= cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc= cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ= -cloud.google.com/go/compute v1.18.0 h1:FEigFqoDbys2cvFkZ9Fjq4gnHBP55anJ0yQyau2f9oY= -cloud.google.com/go/compute v1.18.0/go.mod h1:1X7yHxec2Ga+Ss6jPyjxRxpu2uu7PLgsOVXvgU0yacs= +cloud.google.com/go/compute v1.19.0 h1:+9zda3WGgW1ZSTlVppLCYFIr48Pa35q1uG2N1itbCEQ= +cloud.google.com/go/compute v1.19.0/go.mod h1:rikpw2y+UMidAe9tISo04EHNOIf42RLYF/q8Bs93scU= cloud.google.com/go/compute/metadata v0.2.3 h1:mg4jlk7mCAj6xXp9UJ4fjI9VUI5rubuGBW5aJ7UnBMY= cloud.google.com/go/compute/metadata v0.2.3/go.mod h1:VAV5nSsACxMJvgaAuX6Pk2AawlZn8kiOGuCv6gTkwuA= cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= @@ -38,13 +38,19 @@ cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9 dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= github.com/Azure/azure-sdk-for-go v65.0.0+incompatible h1:HzKLt3kIwMm4KeJYTdx9EbjRYTySD/t8i1Ee/W5EGXw= github.com/Azure/azure-sdk-for-go v65.0.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.3.1 h1:gVXuXcWd1i4C2Ruxe321aU+IKGaStvGB/S90PUPB/W8= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.3.1/go.mod h1:DffdKW9RFqa5VgmsjUOsS7UE7eiA5iAvYUs63bhKQ0M= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.2.1 h1:T8quHYlUGyb/oqtSTwqlCr1ilJHrDv+ZtpSfo+hm1BU= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.2.1/go.mod h1:gLa1CL2RNE4s7M3yopJ/p0iq5DdY6Yv5ZUt9MTRZOQM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.3.0 h1:sXr+ck84g/ZlZUOZiNELInmMgOsuGwdjjVkEIde0OtY= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.3.0/go.mod h1:okt5dMMTOFjX/aovMlrjvvXoPMBVSPzk9185BT0+eZM= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= github.com/Azure/go-autorest v14.2.0+incompatible h1:V5VMDjClD3GiElqLWO7mz2MxNAK/vTfRHdAubSIPRgs= github.com/Azure/go-autorest v14.2.0+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24= -github.com/Azure/go-autorest/autorest v0.11.28 h1:ndAExarwr5Y+GaHE6VCaY1kyS/HwwGGyuimVhWsHOEM= -github.com/Azure/go-autorest/autorest v0.11.28/go.mod h1:MrkzG3Y3AH668QyF9KRk5neJnGgmhQ6krbhR8Q5eMvA= -github.com/Azure/go-autorest/autorest/adal v0.9.18/go.mod h1:XVVeme+LZwABT8K5Lc3hA4nAe8LDBVle26gTrguhhPQ= +github.com/Azure/go-autorest/autorest v0.11.29 h1:I4+HL/JDvErx2LjyzaVxllw2lRDB5/BT2Bm4g20iqYw= +github.com/Azure/go-autorest/autorest v0.11.29/go.mod h1:ZtEzC4Jy2JDrZLxvWs8LrBWEBycl1hbT1eknI8MtfAs= +github.com/Azure/go-autorest/autorest/adal v0.9.22/go.mod h1:XuAbAEUv2Tta//+voMI038TrJBqjKam0me7qR+L8Cmk= github.com/Azure/go-autorest/autorest/adal v0.9.23 h1:Yepx8CvFxwNKpH6ja7RZ+sKX+DWYNldbLiALMC3BTz8= github.com/Azure/go-autorest/autorest/adal v0.9.23/go.mod h1:5pcMqFkdPhviJdlEy3kC/v1ZLnQl0MH6XA5YCcMhy4c= github.com/Azure/go-autorest/autorest/date v0.3.0 h1:7gUk1U5M/CQbp9WoqinNzJar+8KY+LPI6wiWrP/myHw= @@ -60,6 +66,8 @@ github.com/Azure/go-autorest/logger v0.2.1 h1:IG7i4p/mDa2Ce4TRyAO8IHnVhAVF3RFU+Z github.com/Azure/go-autorest/logger v0.2.1/go.mod h1:T9E3cAhj2VqvPOtCYAvby9aBXkZmbF5NWuPV8+WeEW8= github.com/Azure/go-autorest/tracing v0.6.0 h1:TYi4+3m5t6K48TGI9AUdb+IzbnSxvnvUMfuitfgcfuo= github.com/Azure/go-autorest/tracing v0.6.0/go.mod h1:+vhtPC754Xsa23ID7GlGsrdKBpUA79WCAKPPZVC2DeU= +github.com/AzureAD/microsoft-authentication-library-for-go v0.8.1 h1:oPdPEZFSbl7oSPEAIPMPBMUmiL+mqgzBJwM/9qYcwNg= +github.com/AzureAD/microsoft-authentication-library-for-go v0.8.1/go.mod h1:4qFor3D/HDsvBME35Xy9rwW9DecL+M2sNw1ybjPtwA0= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= @@ -98,8 +106,8 @@ github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:W github.com/aws/aws-lambda-go v1.13.3/go.mod h1:4UKl9IzQMoD+QF79YdCuzCwp8VbmG4VAQwij/eHl5CU= github.com/aws/aws-sdk-go v1.27.0/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= github.com/aws/aws-sdk-go v1.38.35/go.mod h1:hcU610XS61/+aQV88ixoOzUoG7v3b31pl2zKMmprdro= -github.com/aws/aws-sdk-go v1.44.245 h1:KtY2s4q31/kn33AdV63R5t77mdxsI7rq3YT7Mgo805M= -github.com/aws/aws-sdk-go v1.44.245/go.mod h1:aVsgQcEevwlmQ7qHE9I3h+dtQgpqhFB+i8Phjh7fkwI= +github.com/aws/aws-sdk-go v1.44.276 h1:ywPlx9C5Yc482dUgAZ9bHpQ6onVvJvYE9FJWsNDCEy0= +github.com/aws/aws-sdk-go v1.44.276/go.mod h1:aVsgQcEevwlmQ7qHE9I3h+dtQgpqhFB+i8Phjh7fkwI= github.com/aws/aws-sdk-go-v2 v0.18.0/go.mod h1:JWVYvqSMppoMJC0x5wdwiImzgXTI9FuZwxzkQq9wy+g= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= @@ -109,8 +117,8 @@ github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kB github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0= github.com/casbin/casbin/v2 v2.1.2/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ= github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM= -github.com/cenkalti/backoff/v4 v4.2.0 h1:HN5dHm3WBOgndBH6E8V0q2jIYIR3s9yglV8k/+MN3u4= -github.com/cenkalti/backoff/v4 v4.2.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= +github.com/cenkalti/backoff/v4 v4.2.1 h1:y4OZtCnogmCPw98Zjyt5a6+QwPLGkiQsYW5oUqylYbM= +github.com/cenkalti/backoff/v4 v4.2.1/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= @@ -130,8 +138,8 @@ github.com/cncf/xds/go v0.0.0-20210312221358-fbca930ec8ed/go.mod h1:eXthEFrGJvWH github.com/cncf/xds/go v0.0.0-20210805033703-aa0b78936158/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= -github.com/cncf/xds/go v0.0.0-20230112175826-46e39c7b9b43 h1:XP+uhjN0yBCN/tPkr8Z0BNDc5rZam9RG6UWyf2FrSQ0= -github.com/cncf/xds/go v0.0.0-20230112175826-46e39c7b9b43/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20230428030218-4003588d1b74 h1:zlUubfBUxApscKFsF4VSvvfhsBNTBu0eF/ddvpo96yk= +github.com/cncf/xds/go v0.0.0-20230428030218-4003588d1b74/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= @@ -149,13 +157,13 @@ github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs github.com/dennwc/varint v1.0.0 h1:kGNFFSSw8ToIy3obO/kKr8U9GZYUAxQEVuix4zfDWzE= github.com/dennwc/varint v1.0.0/go.mod h1:hnItb35rvZvJrbTALZtY/iQfDs48JKRG1RPpgziApxA= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= -github.com/digitalocean/godo v1.98.0 h1:potyC1eD0N9n5/P4/WmJuKgg+OGYZOBWEW+/aKTX6QQ= -github.com/digitalocean/godo v1.98.0/go.mod h1:NRpFznZFvhHjBoqZAaOD3khVzsJ3EibzKqFL4R60dmA= +github.com/digitalocean/godo v1.99.0 h1:gUHO7n9bDaZFWvbzOum4bXE0/09ZuYA9yA8idQHX57E= +github.com/digitalocean/godo v1.99.0/go.mod h1:SsS2oXo2rznfM/nORlZ/6JaUJZFhmKTib1YhopUc8NA= github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI= github.com/docker/distribution v2.8.1+incompatible h1:Q50tZOPR6T/hjNsyc9g8/syEs6bk8XXApsHjKukMl68= github.com/docker/distribution v2.8.1+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= -github.com/docker/docker v23.0.4+incompatible h1:Kd3Bh9V/rO+XpTP/BLqM+gx8z7+Yb0AA2Ibj+nNo4ek= -github.com/docker/docker v23.0.4+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/docker v24.0.2+incompatible h1:eATx+oLz9WdNVkQrr0qjQ8HvRJ4bOOxfzEo8R+dA3cg= +github.com/docker/docker v24.0.2+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec= github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= @@ -180,8 +188,8 @@ github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go. github.com/envoyproxy/go-control-plane v0.11.0 h1:jtLewhRR2vMRNnq2ZZUoCjUlgut+Y0+sDDWPOfwOi1o= github.com/envoyproxy/go-control-plane v0.11.0/go.mod h1:VnHyVMpzcLvCFt9yUz1UnCwHLhwx1WguiVDV7pTG/tI= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/envoyproxy/protoc-gen-validate v0.10.1 h1:c0g45+xCJhdgFGw7a5QAfdS4byAbud7miNWJ1WwEVf8= -github.com/envoyproxy/protoc-gen-validate v0.10.1/go.mod h1:DRjgyB0I43LtJapqN6NiRwroiAU2PaFuvk/vjgh61ss= +github.com/envoyproxy/protoc-gen-validate v1.0.1 h1:kt9FtLiooDc0vbwTLhdg3dyNX1K9Qwa1EK9LcD4jVUQ= +github.com/envoyproxy/protoc-gen-validate v1.0.1/go.mod h1:0vj8bNkYbSTNS2PIyH87KZaeN4x9zpL9Qt8fQC7d+vs= github.com/evanphx/json-patch v4.12.0+incompatible h1:4onqiflcdA9EOZ4RxV643DvftH5pOlLGNtQ5lPWQu84= github.com/evanphx/json-patch v4.12.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= @@ -216,8 +224,8 @@ github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG github.com/go-logfmt/logfmt v0.6.0 h1:wGYYu3uicYdqXVgoYbvnkrPVXkuLM1p1ifugDMEdRi4= github.com/go-logfmt/logfmt v0.6.0/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.2.3 h1:2DntVwHkVopvECVRSlL5PSo9eG+cAkDCuckLubN+rq0= -github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ= +github.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-openapi/analysis v0.21.2/go.mod h1:HZwRk4RRisyG8vx2Oe6aqeSQcoxRp47Xkp3+K6q+LdY= @@ -293,12 +301,12 @@ github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zV github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang-jwt/jwt/v4 v4.0.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg= -github.com/golang-jwt/jwt/v4 v4.2.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg= github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg= github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/glog v1.0.0 h1:nfP3RFugxnNRyKgeWd4oI1nYvXpxrx8ck8ZrcizshdQ= github.com/golang/glog v1.0.0/go.mod h1:EWib/APOK0SL3dFbYqvxE3UYd8E6s1ouQ7iEp/0LWV4= +github.com/golang/glog v1.1.0 h1:/d3pCKDPWNnvIWe0vVUpNP32qc8U3PDVxySP/y360qE= +github.com/golang/glog v1.1.0/go.mod h1:pfYeQZ3JWZoXTV5sFc986z3HTpwQs9At6P4ImfuP3NQ= github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= @@ -367,8 +375,8 @@ github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hf github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20230406165453-00490a63f317 h1:hFhpt7CTmR3DX+b4R19ydQFtofxT0Sv3QsKNMVQYTMQ= -github.com/google/pprof v0.0.0-20230406165453-00490a63f317/go.mod h1:79YE0hCXdHag9sBkw2o+N/YnZtTkXi0UT9Nnixa5eYk= +github.com/google/pprof v0.0.0-20230602150820-91b7bce49751 h1:hR7/MlvK23p6+lIw9SN1TigNLn9ZnF3W4SYRKq2gAHs= +github.com/google/pprof v0.0.0-20230602150820-91b7bce49751/go.mod h1:Jh3hGz2jkYak8qXPD19ryItVnUgpgeqzdkY/D0EaeuA= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -381,8 +389,8 @@ github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+ github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/googleapis/gax-go/v2 v2.7.1 h1:gF4c0zjUP2H/s/hEGyLA3I0fA2ZWjzYiONAD6cvPr8A= github.com/googleapis/gax-go/v2 v2.7.1/go.mod h1:4orTrqY6hXxxaUL4LHIPl6lGo8vAE38/qKbhSAKP6QI= -github.com/gophercloud/gophercloud v1.3.0 h1:RUKyCMiZoQR3VlVR5E3K7PK1AC3/qppsWYo6dtBiqs8= -github.com/gophercloud/gophercloud v1.3.0/go.mod h1:aAVqcocTSXh2vYFZ1JTvx4EQmfgzxRcNupUfxZbBNDM= +github.com/gophercloud/gophercloud v1.4.0 h1:RqEu43vaX0lb0LanZr5BylK5ICVxjpFFoc0sxivyuHU= +github.com/gophercloud/gophercloud v1.4.0/go.mod h1:aAVqcocTSXh2vYFZ1JTvx4EQmfgzxRcNupUfxZbBNDM= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= @@ -398,11 +406,11 @@ github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t github.com/grpc-ecosystem/grpc-gateway v1.16.0 h1:gmcG1KaJ57LophUzW0Hy8NmPhnMZb4M0+kPpLofRdBo= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/grpc-ecosystem/grpc-gateway/v2 v2.7.0/go.mod h1:hgWBS7lorOAVIJEQMi4ZsPv9hVvWI6+ch50m39Pf2Ks= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.15.2 h1:gDLXvp5S9izjldquuoAhDzccbskOL6tDC5jMSyx3zxE= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.15.2/go.mod h1:7pdNwVWBBHGiCxa9lAszqCJMbfTISJ7oMftp8+UGV08= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.15.0 h1:1JYBfzqrWPcCclBwxFCPAou9n+q86mfnu7NAeHfte7A= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.15.0/go.mod h1:YDZoGHuwE+ov0c8smSH49WLF3F2LaWnYYuDVd+EWrc0= github.com/hashicorp/consul/api v1.3.0/go.mod h1:MmDNSzIMUjNpY/mQ398R4bk2FnqQLoPndWW5VkKPlCE= -github.com/hashicorp/consul/api v1.20.0 h1:9IHTjNVSZ7MIwjlW3N3a7iGiykCMDpxZu8jsxFJh0yc= -github.com/hashicorp/consul/api v1.20.0/go.mod h1:nR64eD44KQ59Of/ECwt2vUmIK2DKsDzAwTmwmLl8Wpo= +github.com/hashicorp/consul/api v1.21.0 h1:WMR2JiyuaQWRAMFaOGiYfY4Q4HRpyYRe/oYQofjyduM= +github.com/hashicorp/consul/api v1.21.0/go.mod h1:f8zVJwBcLdr1IQnfdfszjUM0xzp31Zl3bpws3pL9uFM= github.com/hashicorp/consul/sdk v0.3.0/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= github.com/hashicorp/consul/sdk v0.13.1 h1:EygWVWWMczTzXGpO93awkHFzfUka6hLYJ0qhETd+6lY= github.com/hashicorp/cronexpr v1.1.1 h1:NJZDd87hGXjoZBdvyCF9mX4DCq5Wy7+A/w+A7q0wn6c= @@ -451,13 +459,13 @@ github.com/hashicorp/mdns v1.0.4/go.mod h1:mtBihi+LeNXGtG8L9dX59gAEa12BDtBQSp4v/ github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= github.com/hashicorp/memberlist v0.5.0 h1:EtYPN8DpAURiapus508I4n9CzHs2W+8NZGbmmR/prTM= github.com/hashicorp/memberlist v0.5.0/go.mod h1:yvyXLpo0QaGE59Y7hDTsTzDD25JYBZ4mHgHUZ8lrOI0= -github.com/hashicorp/nomad/api v0.0.0-20230418003350-3067191c5197 h1:I5xhKLePXpXgM6pZ4xZNTiurLLS3sGuZrZFFzAbM67A= -github.com/hashicorp/nomad/api v0.0.0-20230418003350-3067191c5197/go.mod h1:2TCrNvonL09r7EiQ6M2rNt+Cmjbn1QbzchFoTWJFpj4= +github.com/hashicorp/nomad/api v0.0.0-20230605233119-67e39d5d248f h1:yxjcAZRuYymIDC0W4IQHgTe9EQdu2BsjPlVmKwyVZT4= +github.com/hashicorp/nomad/api v0.0.0-20230605233119-67e39d5d248f/go.mod h1:Xjd3OXUTfsWbCCBsQd3EdfPTz5evDi+fxqdvpN+WqQg= github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= github.com/hashicorp/serf v0.10.1 h1:Z1H2J60yRKvfDYAOZLd2MU0ND4AH/WDz7xYHDWQsIPY= github.com/hashicorp/serf v0.10.1/go.mod h1:yL2t6BqATOLGc5HF7qbFkTfXoPIY0WZdWHfEvMqbG+4= -github.com/hetznercloud/hcloud-go v1.42.0 h1:Es/CDOForQN3nOOP5Vxh1N/YHjpCg386iYEX5zCgi+A= -github.com/hetznercloud/hcloud-go v1.42.0/go.mod h1:YADL8AbmQYH0Eo+1lkuyoc8LutT0UeMvaKP47nNUb+Y= +github.com/hetznercloud/hcloud-go v1.45.1 h1:nl0OOklFfQT5J6AaNIOhl5Ruh3fhmGmhvZEqHbibVuk= +github.com/hetznercloud/hcloud-go v1.45.1/go.mod h1:aAUGxSfSnB8/lVXHNEDxtCT1jykaul8kqjD7f5KQXF8= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/hudl/fargo v1.3.0/go.mod h1:y3CKSmjA+wD2gak7sUSXTAoopbhU08POFhmITJgmKTg= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= @@ -465,8 +473,8 @@ github.com/imdario/mergo v0.3.13 h1:lFzP57bqS/wsqKssCGmtLAb8A0wKjLGrve2q3PPVcBk= github.com/imdario/mergo v0.3.13/go.mod h1:4lJ1jqUDcsbIECGy0RUJAXNIhg+6ocWgb1ALK2O4oXg= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo= -github.com/ionos-cloud/sdk-go/v6 v6.1.6 h1:0n4irdqNska+1s3YMCRhrAqKbibEgQ7SwwhAlHzYT5A= -github.com/ionos-cloud/sdk-go/v6 v6.1.6/go.mod h1:EzEgRIDxBELvfoa/uBN0kOQaqovLjUWEB7iW4/Q+t4k= +github.com/ionos-cloud/sdk-go/v6 v6.1.7 h1:uVG1Q/ZDJ7YmCI9Oevpue9xJEH5UrUMyXv8gm7NTxIw= +github.com/ionos-cloud/sdk-go/v6 v6.1.7/go.mod h1:EzEgRIDxBELvfoa/uBN0kOQaqovLjUWEB7iW4/Q+t4k= github.com/jarcoal/httpmock v1.3.0 h1:2RJ8GP0IIaWwcC9Fp2BmVi8Kog3v2Hn7VXM3fTd+nuc= github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= @@ -513,10 +521,12 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM= github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4= -github.com/linode/linodego v1.16.1 h1:5otq57M4PdHycPERRfSFZ0s1yz1ETVWGjCp3hh7+F9w= -github.com/linode/linodego v1.16.1/go.mod h1:aESRAbpLY9R6IA1WGAWHikRI9DU9Lhesapv1MhKmPHM= +github.com/linode/linodego v1.17.0 h1:aWS98f0jUoY2lhsEuBxRdVkqyGM0nazPd68AEDF0EvU= +github.com/linode/linodego v1.17.0/go.mod h1:/omzPxie0/YI6S0sTw1q47qDt5IYSlbO/infRR4UG+A= github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= @@ -549,8 +559,8 @@ github.com/maxatome/go-testdeep v1.12.0 h1:Ql7Go8Tg0C1D/uMMX59LAoYK7LffeJQ6X2T04 github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= github.com/miekg/dns v1.1.26/go.mod h1:bPDLeHnStXmXAq1m/Ch/hvfNHr14JKNPMBo3VZKjuso= github.com/miekg/dns v1.1.41/go.mod h1:p6aan82bvRIyn+zDIv9xYNUpwa73JcSh9BKwknJysuI= -github.com/miekg/dns v1.1.53 h1:ZBkuHr5dxHtB1caEOlZTLPo7D3L3TWckgUUs/RHfDxw= -github.com/miekg/dns v1.1.53/go.mod h1:uInx36IzPl7FYnDcMeVWxj9byh7DutNykX4G9Sj60FY= +github.com/miekg/dns v1.1.54 h1:5jon9mWcb0sFJGpnI99tOMhCPyJ+RPVz5b63MQG0VWI= +github.com/miekg/dns v1.1.54/go.mod h1:uInx36IzPl7FYnDcMeVWxj9byh7DutNykX4G9Sj60FY= github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= github.com/mitchellh/cli v1.1.0/go.mod h1:xcISNoH86gajksDmfB23e/pu+B+GeFRMYmoHXxx3xhI= github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= @@ -628,6 +638,8 @@ github.com/pelletier/go-toml v1.7.0/go.mod h1:vwGMzjaWMwyfHwgIBhI2YUM4fB6nL6lVAv github.com/performancecopilot/speed v3.0.0+incompatible/go.mod h1:/CLtqpZ5gBg1M9iaPbIdPPGyKcA8hKdoy6hAWba7Yac= github.com/pierrec/lz4 v1.0.2-0.20190131084431-473cd7ce01a1/go.mod h1:3/3N9NVKO0jef7pBehbT1qWhCMrIgbYNnFAZCqQ5LRc= github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= +github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 h1:KoWmjvw+nsYOo29YJK9vDA65RGE3NrOnUtO7a+RF9HU= +github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8/go.mod h1:HKlIX3XHQyzLZPlr7++PzdhaXEj94dEiJgZDTsxEqUI= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= @@ -647,16 +659,16 @@ github.com/prometheus/client_golang v1.3.0/go.mod h1:hJaj2vgQTGQmVCsAACORcieXFeD github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= github.com/prometheus/client_golang v1.11.0/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0= -github.com/prometheus/client_golang v1.15.0 h1:5fCgGYogn0hFdhyhLbw7hEsWxufKtY9klyvdNfFlFhM= -github.com/prometheus/client_golang v1.15.0/go.mod h1:e9yaBhRPU2pPNsZwE+JdQl0KEt1N9XgF6zxWmaC0xOk= +github.com/prometheus/client_golang v1.15.1 h1:8tXpTmJbyH5lydzFPoxSIJ0J46jdh3tylbvM1xCv0LI= +github.com/prometheus/client_golang v1.15.1/go.mod h1:e9yaBhRPU2pPNsZwE+JdQl0KEt1N9XgF6zxWmaC0xOk= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.1.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/client_model v0.3.0 h1:UBgGFHqYdG/TPFD1B1ogZywDqEkwp3fBMvqdiQ7Xew4= -github.com/prometheus/client_model v0.3.0/go.mod h1:LDGWKZIo7rky3hgvBe+caln+Dr3dPggB5dvjtD7w9+w= +github.com/prometheus/client_model v0.4.0 h1:5lQXD3cAg1OXBf4Wq03gTrXHeaV0TQvGfUooCfx1yqY= +github.com/prometheus/client_model v0.4.0/go.mod h1:oMQmHW1/JoDwqLtg57MGgP/Fb1CJEYF2imWWhWtMkYU= github.com/prometheus/common v0.2.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.7.0/go.mod h1:DjGbpBbp5NYNiECxcL/VnbXCCaQpKd3tt26CguLLsqA= @@ -664,14 +676,14 @@ github.com/prometheus/common v0.9.1/go.mod h1:yhUN8i9wzaXS3w1O07YhxHEBxD+W35wd8b github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9VFqTh1DIvc= github.com/prometheus/common v0.29.0/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls= -github.com/prometheus/common v0.42.0 h1:EKsfXEYo4JpWMHH5cg+KOUWeuJSov1Id8zGR8eeI1YM= -github.com/prometheus/common v0.42.0/go.mod h1:xBwqVerjNdUDjgODMpudtOMwlOwf2SaTr1yjz4b7Zbc= +github.com/prometheus/common v0.44.0 h1:+5BrQJwiBB9xsMygAB3TNvpQKOwlkc25LbISbrdOOfY= +github.com/prometheus/common v0.44.0/go.mod h1:ofAIvZbQ1e/nugmZGz4/qCb9Ap1VoSTIO7x0VV9VvuY= github.com/prometheus/common/assets v0.2.0 h1:0P5OrzoHrYBOSM1OigWL3mY8ZvV2N4zIE/5AahrSrfM= github.com/prometheus/common/assets v0.2.0/go.mod h1:D17UVUE12bHbim7HzwUvtqm6gwBEaDQ0F+hIGbFbccI= github.com/prometheus/common/sigv4 v0.1.0 h1:qoVebwtwwEhS85Czm2dSROY5fTo2PAPEVdDeppTwGX4= github.com/prometheus/common/sigv4 v0.1.0/go.mod h1:2Jkxxk9yYvCkE5G1sQT7GuEXm57JrvHu9k5YwTjsNtI= -github.com/prometheus/exporter-toolkit v0.9.1 h1:cNkC01riqiOS+kh3zdnNwRsbe/Blh0WwK3ij5rPJ9Sw= -github.com/prometheus/exporter-toolkit v0.9.1/go.mod h1:iFlTmFISCix0vyuyBmm0UqOUCTao9+RsAsKJP3YM9ec= +github.com/prometheus/exporter-toolkit v0.10.0 h1:yOAzZTi4M22ZzVxD+fhy1URTuNRj/36uQJJ5S8IPza8= +github.com/prometheus/exporter-toolkit v0.10.0/go.mod h1:+sVFzuvV5JDyw+Ih6p3zFxZNVnKQa3x5qPmDSiPu4ZY= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= @@ -687,15 +699,14 @@ github.com/rogpeppe/go-internal v1.1.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR github.com/rogpeppe/go-internal v1.2.2/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= -github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E= -github.com/scaleway/scaleway-sdk-go v1.0.0-beta.15 h1:Y7xOFbD+3jaPw+VN7lkakNJ/pa+ZSQVFp1ONtJaBxns= -github.com/scaleway/scaleway-sdk-go v1.0.0-beta.15/go.mod h1:fCa7OJZ/9DRTnOKmxvT6pn+LPWUptQAmHF/SBJUGEcg= +github.com/scaleway/scaleway-sdk-go v1.0.0-beta.17 h1:1WuWJu7/e8SqK+uQl7lfk/N/oMZTL2NE/TJsNKRNMc4= +github.com/scaleway/scaleway-sdk-go v1.0.0-beta.17/go.mod h1:fCa7OJZ/9DRTnOKmxvT6pn+LPWUptQAmHF/SBJUGEcg= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529 h1:nn5Wsu0esKSJiIVhscUtVbo7ada43DJhG55ua/hjS5I= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= -github.com/shoenig/test v0.6.3 h1:GVXWJFk9PiOjN0KoJ7VrJGH6uLPnqxR7/fe3HUPfE0c= +github.com/shoenig/test v0.6.6 h1:Oe8TPH9wAbv++YPNDKJWUnI8Q4PPWCx3UbOfH+FxiMU= github.com/shurcooL/httpfs v0.0.0-20190707220628-8d4bc4ba7749 h1:bUGsEnyNbVPw06Bs80sCeARAlK8lhwqGyi6UT8ymuGk= github.com/shurcooL/httpfs v0.0.0-20190707220628-8d4bc4ba7749/go.mod h1:ZY1cvUeJuFPAdZ/B6v7RHavJWZn2YPVFQ1OSXhCGOkg= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= @@ -737,8 +748,9 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +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/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4= github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= @@ -780,31 +792,31 @@ go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.40.0 h1:lE9EJyw3/JhrjWH/hEy9FptnalDQgj7vpbgC2KCCCxE= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.40.0/go.mod h1:pcQ3MM3SWvrA71U4GDqv9UFDJ3HQsW7y5ZO3tDTlUdI= -go.opentelemetry.io/otel v1.14.0 h1:/79Huy8wbf5DnIPhemGB+zEPVwnN6fuQybr/SRXa6hM= -go.opentelemetry.io/otel v1.14.0/go.mod h1:o4buv+dJzx8rohcUeRmWUZhqupFvzWis188WlggnNeU= -go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.14.0 h1:/fXHZHGvro6MVqV34fJzDhi7sHGpX3Ej/Qjmfn003ho= -go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.14.0/go.mod h1:UFG7EBMRdXyFstOwH028U0sVf+AvukSGhF0g8+dmNG8= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.14.0 h1:TKf2uAs2ueguzLaxOCBXNpHxfO/aC7PAdDsSH0IbeRQ= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.14.0/go.mod h1:HrbCVv40OOLTABmOn1ZWty6CHXkU8DK/Urc43tHug70= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.14.0 h1:ap+y8RXX3Mu9apKVtOkM6WSFESLM8K3wNQyOU8sWHcc= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.14.0/go.mod h1:5w41DY6S9gZrbjuq6Y+753e96WfPha5IcsOSZTtullM= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.14.0 h1:3jAYbRHQAqzLjd9I4tzxwJ8Pk/N6AqBcF6m1ZHrxG94= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.14.0/go.mod h1:+N7zNjIJv4K+DeX67XXET0P+eIciESgaFDBqh+ZJFS4= -go.opentelemetry.io/otel/metric v0.37.0 h1:pHDQuLQOZwYD+Km0eb657A25NaRzy0a+eLyKfDXedEs= -go.opentelemetry.io/otel/metric v0.37.0/go.mod h1:DmdaHfGt54iV6UKxsV9slj2bBRJcKC1B1uvDLIioc1s= -go.opentelemetry.io/otel/sdk v1.14.0 h1:PDCppFRDq8A1jL9v6KMI6dYesaq+DFcDZvjsoGvxGzY= -go.opentelemetry.io/otel/sdk v1.14.0/go.mod h1:bwIC5TjrNG6QDCHNWvW4HLHtUQ4I+VQDsnjhvyZCALM= -go.opentelemetry.io/otel/trace v1.14.0 h1:wp2Mmvj41tDsyAJXiWDWpfNsOiIyd38fy85pyKcFq/M= -go.opentelemetry.io/otel/trace v1.14.0/go.mod h1:8avnQLK+CG77yNLUae4ea2JDQ6iT+gozhnZjy/rw9G8= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.42.0 h1:pginetY7+onl4qN1vl0xW/V/v6OBZ0vVdH+esuJgvmM= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.42.0/go.mod h1:XiYsayHc36K3EByOO6nbAXnAWbrUxdjUROCEeeROOH8= +go.opentelemetry.io/otel v1.16.0 h1:Z7GVAX/UkAXPKsy94IU+i6thsQS4nb7LviLpnaNeW8s= +go.opentelemetry.io/otel v1.16.0/go.mod h1:vl0h9NUa1D5s1nv3A5vZOYWn8av4K8Ml6JDeHrT/bx4= +go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.16.0 h1:t4ZwRPU+emrcvM2e9DHd0Fsf0JTPVcbfa/BhTDF03d0= +go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.16.0/go.mod h1:vLarbg68dH2Wa77g71zmKQqlQ8+8Rq3GRG31uc0WcWI= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.16.0 h1:cbsD4cUcviQGXdw8+bo5x2wazq10SKz8hEbtCRPcU78= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.16.0/go.mod h1:JgXSGah17croqhJfhByOLVY719k1emAXC8MVhCIJlRs= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.16.0 h1:TVQp/bboR4mhZSav+MdgXB8FaRho1RC8UwVn3T0vjVc= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.16.0/go.mod h1:I33vtIe0sR96wfrUcilIzLoA3mLHhRmz9S9Te0S3gDo= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.16.0 h1:iqjq9LAB8aK++sKVcELezzn655JnBNdsDhghU4G/So8= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.16.0/go.mod h1:hGXzO5bhhSHZnKvrDaXB82Y9DRFour0Nz/KrBh7reWw= +go.opentelemetry.io/otel/metric v1.16.0 h1:RbrpwVG1Hfv85LgnZ7+txXioPDoh6EdbZHo26Q3hqOo= +go.opentelemetry.io/otel/metric v1.16.0/go.mod h1:QE47cpOmkwipPiefDwo2wDzwJrlfxxNYodqc4xnGCo4= +go.opentelemetry.io/otel/sdk v1.16.0 h1:Z1Ok1YsijYL0CSJpHt4cS3wDDh7p572grzNrBMiMWgE= +go.opentelemetry.io/otel/sdk v1.16.0/go.mod h1:tMsIuKXuuIWPBAOrH+eHtvhTL+SntFtXF9QD68aP6p4= +go.opentelemetry.io/otel/trace v1.16.0 h1:8JRpaObFoW0pxuVPapkgH8UhHQj+bJW8jJsCZEu5MQs= +go.opentelemetry.io/otel/trace v1.16.0/go.mod h1:Yt9vYq1SdNz3xdjZZK7wcXv1qv2pwLkqr2QVwea0ef0= go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= go.opentelemetry.io/proto/otlp v0.19.0 h1:IVN6GR+mhC4s5yfcTbmzHYODqvWAp3ZedA2SJPI1Nnw= go.opentelemetry.io/proto/otlp v0.19.0/go.mod h1:H7XAot3MsfNsj7EXtrA2q5xSNQ10UqI405h3+duxN4U= go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= -go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ= -go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= +go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= +go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/automaxprocs v1.5.2 h1:2LxUOGiR3O6tw8ui5sZa2LAaHnsviZdVOUZw4fvbnME= go.uber.org/automaxprocs v1.5.2/go.mod h1:eRbA25aqJrxAbsLO0xy5jVwPt7FQnRgjW+efnwa1WM0= go.uber.org/goleak v1.2.1 h1:NBol2c7O1ZokfZ0LEU9K6Whx/KnwvepVetCUhtKja4A= @@ -830,8 +842,8 @@ golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0 golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.0.0-20220829220503-c86fa9a7ed90/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58= -golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A= -golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= +golang.org/x/crypto v0.8.0 h1:pd9TJtTueMTVQXzk8E2XESSMQDj/U7OUu0PqJqPXQjQ= +golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -842,8 +854,8 @@ golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u0 golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= -golang.org/x/exp v0.0.0-20230321023759-10a507213a29 h1:ooxPy7fPvB4kwsA2h+iBNHkAbp/4JxTSwCmvdjEYmug= -golang.org/x/exp v0.0.0-20230321023759-10a507213a29/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc= +golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1 h1:k/i9J1pBpvlfR+9QsetwPyERsqu1GIbi967PQMq3Ivc= +golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1/go.mod h1:V1LtkGg67GoY2N1AnLN78QLrzxkLyJw7RJb1gzOOz9w= golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= @@ -914,8 +926,8 @@ golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qx 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.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM= -golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= +golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -923,8 +935,8 @@ golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4Iltr golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.7.0 h1:qe6s0zUXlPX80/dITx3440hWZ7GwMwgDDyrSGTPJG/g= -golang.org/x/oauth2 v0.7.0/go.mod h1:hPLQkd9LyjfXTiRohC/41GhcFqxisoUQ99sCUOHO9x4= +golang.org/x/oauth2 v0.8.0 h1:6dkIjl3j3LtZ/O3sTgZTMsLKSftL/B8Zgq4huOIIUu8= +golang.org/x/oauth2 v0.8.0/go.mod h1:yr7u4HXZRm1R1kBWqr/xKNqewf0plRYoB7sla+BCIXE= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -938,8 +950,8 @@ golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/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 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o= -golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.2.0 h1:PUR+T4wwASmuSTYdKjYHI5TD22Wy5ogLU5qZCOLxBrI= +golang.org/x/sync v0.2.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -995,6 +1007,7 @@ golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210616045830-e2b7044e8c71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -1006,14 +1019,14 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU= -golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU= +golang.org/x/sys v0.8.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/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= -golang.org/x/term v0.7.0 h1:BEvjmm5fURWqcfbSKTdpkDXYBrUS1c0m8agp14W48vQ= -golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= +golang.org/x/term v0.8.0 h1:n5xxQn2i3PC0yLAbjTpNT85q/Kgzcr2gIoX9OrJUols= +golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -1085,8 +1098,8 @@ golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roY golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.8.0 h1:vSDcovVPld282ceKgDimkRSC8kpaH1dgyc9UMzlt84Y= -golang.org/x/tools v0.8.0/go.mod h1:JxBZ99ISMI5ViVkT1tr6tdNmXeTrcpVSD3vZ1RsRdN4= +golang.org/x/tools v0.9.3 h1:Gn1I8+64MsuTb/HpH+LmQtNas23LhUVr3rYZ0eKuaMM= +golang.org/x/tools v0.9.3/go.mod h1:owI94Op576fPu3cIGQeHs3joujW/2Oc6MtlxbF5dfNc= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -1148,8 +1161,8 @@ google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7Fc google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20211118181313-81c1377c94b1/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= google.golang.org/genproto v0.0.0-20220107163113-42d7afdf6368/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= -google.golang.org/genproto v0.0.0-20230306155012-7f2fa6fef1f4 h1:DdoeryqhaXp1LtT/emMP1BRJPHHKFi5akj/nbx/zNTA= -google.golang.org/genproto v0.0.0-20230306155012-7f2fa6fef1f4/go.mod h1:NWraEVixdDnqcqQ30jipen1STv2r/n24Wb7twVTGR4s= +google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 h1:khxVcsk/FhnzxMKOyD+TDGwjbEOpcPuIpmafPGFmhMA= +google.golang.org/genproto v0.0.0-20230320184635-7606e756e683/go.mod h1:NWraEVixdDnqcqQ30jipen1STv2r/n24Wb7twVTGR4s= google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.0/go.mod h1:chYK+tFQF0nDUGJgXMSgLCQk3phJEuONr2DCgLDdAQM= @@ -1171,8 +1184,8 @@ google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.40.0/go.mod h1:ogyxbiOoUXAkP+4+xa6PZSE9DZgIHtSpzjDTB9KAK34= google.golang.org/grpc v1.42.0/go.mod h1:k+4IHHFw41K8+bbowsex27ge2rCb65oeWqe4jJ590SU= -google.golang.org/grpc v1.53.0 h1:LAv2ds7cmFV/XTS3XG1NneeENYrXGmorPxsBbptIjNc= -google.golang.org/grpc v1.53.0/go.mod h1:OnIrk0ipVdj4N5d9IUoFUx72/VlD7+jUsHwZgwSMQpw= +google.golang.org/grpc v1.55.0 h1:3Oj82/tFSCeUrRTg/5E/7d/W5A1tj6Ky1ABAuZuv5ag= +google.golang.org/grpc v1.55.0/go.mod h1:iYEXKGkEBhg1PjZQvoYEVPTDkHo1/bjTnfwTeGONTY8= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= @@ -1240,8 +1253,8 @@ k8s.io/apimachinery v0.26.2 h1:da1u3D5wfR5u2RpLhE/ZtZS2P7QvDgLZTi9wrNZl/tQ= k8s.io/apimachinery v0.26.2/go.mod h1:ats7nN1LExKHvJ9TmwootT00Yz05MuYqPXEXaVeOy5I= k8s.io/client-go v0.26.2 h1:s1WkVujHX3kTp4Zn4yGNFK+dlDXy1bAAkIl+cFAiuYI= k8s.io/client-go v0.26.2/go.mod h1:u5EjOuSyBa09yqqyY7m3abZeovO/7D/WehVVlZ2qcqU= -k8s.io/kube-openapi v0.0.0-20230303024457-afdc3dddf62d h1:VcFq5n7wCJB2FQMCIHfC+f+jNcGgNMar1uKd6rVlifU= -k8s.io/kube-openapi v0.0.0-20230303024457-afdc3dddf62d/go.mod h1:y5VtZWM9sHHc2ZodIH/6SHzXj+TPU5USoA8lcIeKEKY= +k8s.io/kube-openapi v0.0.0-20230501164219-8b0f38b5fd1f h1:2kWPakN3i/k81b0gvD5C5FJ2kxm1WrQFanWchyKuqGg= +k8s.io/kube-openapi v0.0.0-20230501164219-8b0f38b5fd1f/go.mod h1:byini6yhqGC14c3ebc/QwanvYwhuMWF6yz2F8uwW8eg= k8s.io/utils v0.0.0-20230308161112-d77c459e9343 h1:m7tbIjXGcGIAtpmQr7/NAi7RsWoW3E7Zcm4jI1HicTc= k8s.io/utils v0.0.0-20230308161112-d77c459e9343/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= diff --git a/model/histogram/float_histogram.go b/model/histogram/float_histogram.go index f95f0051c92..f4ee13facc1 100644 --- a/model/histogram/float_histogram.go +++ b/model/histogram/float_histogram.go @@ -159,12 +159,12 @@ func (h *FloatHistogram) ZeroBucket() Bucket[float64] { } } -// Scale scales the FloatHistogram by the provided factor, i.e. it scales all +// Mul multiplies the FloatHistogram by the provided factor, i.e. it scales all // bucket counts including the zero bucket and the count and the sum of // observations. The bucket layout stays the same. This method changes the // receiving histogram directly (rather than acting on a copy). It returns a // pointer to the receiving histogram for convenience. -func (h *FloatHistogram) Scale(factor float64) *FloatHistogram { +func (h *FloatHistogram) Mul(factor float64) *FloatHistogram { h.ZeroCount *= factor h.Count *= factor h.Sum *= factor @@ -177,6 +177,21 @@ func (h *FloatHistogram) Scale(factor float64) *FloatHistogram { return h } +// Div works like Scale but divides instead of multiplies. +// When dividing by 0, everything will be set to Inf. +func (h *FloatHistogram) Div(scalar float64) *FloatHistogram { + h.ZeroCount /= scalar + h.Count /= scalar + h.Sum /= scalar + for i := range h.PositiveBuckets { + h.PositiveBuckets[i] /= scalar + } + for i := range h.NegativeBuckets { + h.NegativeBuckets[i] /= scalar + } + return h +} + // Add adds the provided other histogram to the receiving histogram. Count, Sum, // and buckets from the other histogram are added to the corresponding // components of the receiving histogram. Buckets in the other histogram that do diff --git a/model/histogram/float_histogram_test.go b/model/histogram/float_histogram_test.go index 58aad9645ec..242ef4c92c7 100644 --- a/model/histogram/float_histogram_test.go +++ b/model/histogram/float_histogram_test.go @@ -15,12 +15,13 @@ package histogram import ( "fmt" + "math" "testing" "github.com/stretchr/testify/require" ) -func TestFloatHistogramScale(t *testing.T) { +func TestFloatHistogramMul(t *testing.T) { cases := []struct { name string in *FloatHistogram @@ -33,6 +34,30 @@ func TestFloatHistogramScale(t *testing.T) { 3.1415, &FloatHistogram{}, }, + { + "zero multiplier", + &FloatHistogram{ + ZeroThreshold: 0.01, + ZeroCount: 5.5, + Count: 3493.3, + Sum: 2349209.324, + PositiveSpans: []Span{{-2, 1}, {2, 3}}, + PositiveBuckets: []float64{1, 3.3, 4.2, 0.1}, + NegativeSpans: []Span{{3, 2}, {3, 2}}, + NegativeBuckets: []float64{3.1, 3, 1.234e5, 1000}, + }, + 0, + &FloatHistogram{ + ZeroThreshold: 0.01, + ZeroCount: 0, + Count: 0, + Sum: 0, + PositiveSpans: []Span{{-2, 1}, {2, 3}}, + PositiveBuckets: []float64{0, 0, 0, 0}, + NegativeSpans: []Span{{3, 2}, {3, 2}}, + NegativeBuckets: []float64{0, 0, 0, 0}, + }, + }, { "no-op", &FloatHistogram{ @@ -81,17 +106,137 @@ func TestFloatHistogramScale(t *testing.T) { NegativeBuckets: []float64{6.2, 6, 1.234e5 * 2, 2000}, }, }, + { + "triple", + &FloatHistogram{ + ZeroThreshold: 0.01, + ZeroCount: 11, + Count: 30, + Sum: 23, + PositiveSpans: []Span{{-2, 2}, {1, 3}}, + PositiveBuckets: []float64{1, 0, 3, 4, 7}, + NegativeSpans: []Span{{3, 2}, {3, 2}}, + NegativeBuckets: []float64{3, 1, 5, 6}, + }, + 3, + &FloatHistogram{ + ZeroThreshold: 0.01, + ZeroCount: 33, + Count: 90, + Sum: 69, + PositiveSpans: []Span{{-2, 2}, {1, 3}}, + PositiveBuckets: []float64{3, 0, 9, 12, 21}, + NegativeSpans: []Span{{3, 2}, {3, 2}}, + NegativeBuckets: []float64{9, 3, 15, 18}, + }, + }, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { - require.Equal(t, c.expected, c.in.Scale(c.scale)) + require.Equal(t, c.expected, c.in.Mul(c.scale)) // Has it also happened in-place? require.Equal(t, c.expected, c.in) }) } } +func TestFloatHistogramDiv(t *testing.T) { + cases := []struct { + name string + fh *FloatHistogram + s float64 + expected *FloatHistogram + }{ + { + "zero value", + &FloatHistogram{}, + 3.1415, + &FloatHistogram{}, + }, + { + "zero divisor", + &FloatHistogram{ + ZeroThreshold: 0.01, + ZeroCount: 5.5, + Count: 3493.3, + Sum: 2349209.324, + PositiveSpans: []Span{{-2, 1}, {2, 3}}, + PositiveBuckets: []float64{1, 3.3, 4.2, 0.1}, + NegativeSpans: []Span{{3, 2}, {3, 2}}, + NegativeBuckets: []float64{3.1, 3, 1.234e5, 1000}, + }, + 0, + &FloatHistogram{ + ZeroThreshold: 0.01, + ZeroCount: math.Inf(1), + Count: math.Inf(1), + Sum: math.Inf(1), + PositiveSpans: []Span{{-2, 1}, {2, 3}}, + PositiveBuckets: []float64{math.Inf(1), math.Inf(1), math.Inf(1), math.Inf(1)}, + NegativeSpans: []Span{{3, 2}, {3, 2}}, + NegativeBuckets: []float64{math.Inf(1), math.Inf(1), math.Inf(1), math.Inf(1)}, + }, + }, + { + "no-op", + &FloatHistogram{ + ZeroThreshold: 0.01, + ZeroCount: 5.5, + Count: 3493.3, + Sum: 2349209.324, + PositiveSpans: []Span{{-2, 1}, {2, 3}}, + PositiveBuckets: []float64{1, 3.3, 4.2, 0.1}, + NegativeSpans: []Span{{3, 2}, {3, 2}}, + NegativeBuckets: []float64{3.1, 3, 1.234e5, 1000}, + }, + 1, + &FloatHistogram{ + ZeroThreshold: 0.01, + ZeroCount: 5.5, + Count: 3493.3, + Sum: 2349209.324, + PositiveSpans: []Span{{-2, 1}, {2, 3}}, + PositiveBuckets: []float64{1, 3.3, 4.2, 0.1}, + NegativeSpans: []Span{{3, 2}, {3, 2}}, + NegativeBuckets: []float64{3.1, 3, 1.234e5, 1000}, + }, + }, + { + "half", + &FloatHistogram{ + ZeroThreshold: 0.01, + ZeroCount: 11, + Count: 30, + Sum: 23, + PositiveSpans: []Span{{-2, 2}, {1, 3}}, + PositiveBuckets: []float64{1, 0, 3, 4, 7}, + NegativeSpans: []Span{{3, 2}, {3, 2}}, + NegativeBuckets: []float64{3, 1, 5, 6}, + }, + 2, + &FloatHistogram{ + ZeroThreshold: 0.01, + ZeroCount: 5.5, + Count: 15, + Sum: 11.5, + PositiveSpans: []Span{{-2, 2}, {1, 3}}, + PositiveBuckets: []float64{0.5, 0, 1.5, 2, 3.5}, + NegativeSpans: []Span{{3, 2}, {3, 2}}, + NegativeBuckets: []float64{1.5, 0.5, 2.5, 3}, + }, + }, + } + + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + require.Equal(t, c.expected, c.fh.Div(c.s)) + // Has it also happened in-place? + require.Equal(t, c.expected, c.fh) + }) + } +} + func TestFloatHistogramDetectReset(t *testing.T) { cases := []struct { name string diff --git a/model/labels/labels.go b/model/labels/labels.go index 9ac0e5b53fc..0c27e15c724 100644 --- a/model/labels/labels.go +++ b/model/labels/labels.go @@ -621,7 +621,7 @@ func (b *ScratchBuilder) Sort() { slices.SortFunc(b.add, func(a, b Label) bool { return a.Name < b.Name }) } -// Asssign is for when you already have a Labels which you want this ScratchBuilder to return. +// Assign is for when you already have a Labels which you want this ScratchBuilder to return. func (b *ScratchBuilder) Assign(ls Labels) { b.add = append(b.add[:0], ls...) // Copy on top of our slice, so we don't retain the input slice. } diff --git a/model/labels/labels_string.go b/model/labels/labels_string.go index 6d54e98ab94..e232ca7a4d2 100644 --- a/model/labels/labels_string.go +++ b/model/labels/labels_string.go @@ -800,7 +800,7 @@ func (b *ScratchBuilder) Sort() { slices.SortFunc(b.add, func(a, b Label) bool { return a.Name < b.Name }) } -// Asssign is for when you already have a Labels which you want this ScratchBuilder to return. +// Assign is for when you already have a Labels which you want this ScratchBuilder to return. func (b *ScratchBuilder) Assign(l Labels) { b.output = l } diff --git a/model/textparse/interface.go b/model/textparse/interface.go index 9efd942e832..efa581410fa 100644 --- a/model/textparse/interface.go +++ b/model/textparse/interface.go @@ -71,7 +71,7 @@ type Parser interface { // // This function always returns a valid parser, but might additionally // return an error if the content type cannot be parsed. -func New(b []byte, contentType string) (Parser, error) { +func New(b []byte, contentType string, parseClassicHistograms bool) (Parser, error) { if contentType == "" { return NewPromParser(b), nil } @@ -84,7 +84,7 @@ func New(b []byte, contentType string) (Parser, error) { case "application/openmetrics-text": return NewOpenMetricsParser(b), nil case "application/vnd.google.protobuf": - return NewProtobufParser(b), nil + return NewProtobufParser(b, parseClassicHistograms), nil default: return NewPromParser(b), nil } @@ -100,7 +100,7 @@ const ( EntrySeries Entry = 2 // A series with a simple float64 as value. EntryComment Entry = 3 EntryUnit Entry = 4 - EntryHistogram Entry = 5 // A series with a sparse histogram as a value. + EntryHistogram Entry = 5 // A series with a native histogram as a value. ) // MetricType represents metric type values. diff --git a/model/textparse/interface_test.go b/model/textparse/interface_test.go index d94467d4dbc..de140d6819d 100644 --- a/model/textparse/interface_test.go +++ b/model/textparse/interface_test.go @@ -91,7 +91,7 @@ func TestNewParser(t *testing.T) { tt := tt // Copy to local variable before going parallel. t.Parallel() - p, err := New([]byte{}, tt.contentType) + p, err := New([]byte{}, tt.contentType, false) tt.validateParser(t, p) if tt.err == "" { require.NoError(t, err) diff --git a/model/textparse/protobufparse.go b/model/textparse/protobufparse.go index eca145955e8..b831251ad05 100644 --- a/model/textparse/protobufparse.go +++ b/model/textparse/protobufparse.go @@ -52,8 +52,10 @@ type ProtobufParser struct { // fieldPos is the position within a Summary or (legacy) Histogram. -2 // is the count. -1 is the sum. Otherwise it is the index within // quantiles/buckets. - fieldPos int - fieldsDone bool // true if no more fields of a Summary or (legacy) Histogram to be processed. + fieldPos int + fieldsDone bool // true if no more fields of a Summary or (legacy) Histogram to be processed. + redoClassic bool // true after parsing a native histogram if we need to parse it again as a classit histogram. + // state is marked by the entry we are processing. EntryInvalid implies // that we have to decode the next MetricFamily. state Entry @@ -62,17 +64,22 @@ type ProtobufParser struct { mf *dto.MetricFamily + // Wether to also parse a classic histogram that is also present as a + // native histogram. + parseClassicHistograms bool + // The following are just shenanigans to satisfy the Parser interface. metricBytes *bytes.Buffer // A somewhat fluid representation of the current metric. } // NewProtobufParser returns a parser for the payload in the byte slice. -func NewProtobufParser(b []byte) Parser { +func NewProtobufParser(b []byte, parseClassicHistograms bool) Parser { return &ProtobufParser{ - in: b, - state: EntryInvalid, - mf: &dto.MetricFamily{}, - metricBytes: &bytes.Buffer{}, + in: b, + state: EntryInvalid, + mf: &dto.MetricFamily{}, + metricBytes: &bytes.Buffer{}, + parseClassicHistograms: parseClassicHistograms, } } @@ -106,19 +113,28 @@ func (p *ProtobufParser) Series() ([]byte, *int64, float64) { v = s.GetQuantile()[p.fieldPos].GetValue() } case dto.MetricType_HISTOGRAM, dto.MetricType_GAUGE_HISTOGRAM: - // This should only happen for a legacy histogram. + // This should only happen for a classic histogram. h := m.GetHistogram() switch p.fieldPos { case -2: - v = float64(h.GetSampleCount()) + v = h.GetSampleCountFloat() + if v == 0 { + v = float64(h.GetSampleCount()) + } case -1: v = h.GetSampleSum() default: bb := h.GetBucket() if p.fieldPos >= len(bb) { - v = float64(h.GetSampleCount()) + v = h.GetSampleCountFloat() + if v == 0 { + v = float64(h.GetSampleCount()) + } } else { - v = float64(bb[p.fieldPos].GetCumulativeCount()) + v = bb[p.fieldPos].GetCumulativeCountFloat() + if v == 0 { + v = float64(bb[p.fieldPos].GetCumulativeCount()) + } } } default: @@ -149,6 +165,9 @@ func (p *ProtobufParser) Histogram() ([]byte, *int64, *histogram.Histogram, *his ts = m.GetTimestampMs() h = m.GetHistogram() ) + if p.parseClassicHistograms && len(h.GetBucket()) > 0 { + p.redoClassic = true + } if h.GetSampleCountFloat() > 0 || h.GetZeroCountFloat() > 0 { // It is a float histogram. fh := histogram.FloatHistogram{ @@ -376,6 +395,12 @@ func (p *ProtobufParser) Next() (Entry, error) { return EntryInvalid, err } case EntryHistogram, EntrySeries: + if p.redoClassic { + p.redoClassic = false + p.state = EntrySeries + p.fieldPos = -3 + p.fieldsDone = false + } t := p.mf.GetType() if p.state == EntrySeries && !p.fieldsDone && (t == dto.MetricType_SUMMARY || @@ -432,7 +457,7 @@ func (p *ProtobufParser) updateMetricBytes() error { // state. func (p *ProtobufParser) getMagicName() string { t := p.mf.GetType() - if p.state == EntryHistogram || (t != dto.MetricType_HISTOGRAM && t != dto.MetricType_SUMMARY) { + if p.state == EntryHistogram || (t != dto.MetricType_HISTOGRAM && t != dto.MetricType_GAUGE_HISTOGRAM && t != dto.MetricType_SUMMARY) { return p.mf.GetName() } if p.fieldPos == -2 { diff --git a/model/textparse/protobufparse_test.go b/model/textparse/protobufparse_test.go index 90c6a90f326..882cce59d39 100644 --- a/model/textparse/protobufparse_test.go +++ b/model/textparse/protobufparse_test.go @@ -30,8 +30,8 @@ import ( dto "github.com/prometheus/prometheus/prompb/io/prometheus/client" ) -func TestProtobufParse(t *testing.T) { - textMetricFamilies := []string{ +func createTestProtoBuf(t *testing.T) *bytes.Buffer { + testMetricFamilies := []string{ `name: "go_build_info" help: "Build information about the main Go module." type: GAUGE @@ -231,8 +231,7 @@ help: "Test float histogram with many buckets removed to keep it manageable in s type: HISTOGRAM metric: < histogram: < - sample_count: 175 - sample_count_float: 175.0 + sample_count_float: 175.0 sample_sum: 0.0008280461746287094 bucket: < cumulative_count_float: 2.0 @@ -302,8 +301,7 @@ help: "Like test_float_histogram but as gauge histogram." type: GAUGE_HISTOGRAM metric: < histogram: < - sample_count: 175 - sample_count_float: 175.0 + sample_count_float: 175.0 sample_sum: 0.0008280461746287094 bucket: < cumulative_count_float: 2.0 @@ -450,9 +448,9 @@ metric: < } varintBuf := make([]byte, binary.MaxVarintLen32) - inputBuf := &bytes.Buffer{} + buf := &bytes.Buffer{} - for _, tmf := range textMetricFamilies { + for _, tmf := range testMetricFamilies { pb := &dto.MetricFamily{} // From text to proto message. require.NoError(t, proto.UnmarshalText(tmf, pb)) @@ -462,11 +460,15 @@ metric: < // Write first length, then binary protobuf. varintLength := binary.PutUvarint(varintBuf, uint64(len(protoBuf))) - inputBuf.Write(varintBuf[:varintLength]) - inputBuf.Write(protoBuf) + buf.Write(varintBuf[:varintLength]) + buf.Write(protoBuf) } - exp := []struct { + return buf +} + +func TestProtobufParse(t *testing.T) { + type parseResult struct { lset labels.Labels m string t int64 @@ -478,417 +480,1006 @@ metric: < shs *histogram.Histogram fhs *histogram.FloatHistogram e []exemplar.Exemplar + } + + inputBuf := createTestProtoBuf(t) + + scenarios := []struct { + name string + parser Parser + expected []parseResult }{ { - m: "go_build_info", - help: "Build information about the main Go module.", - }, - { - m: "go_build_info", - typ: MetricTypeGauge, - }, - { - m: "go_build_info\xFFchecksum\xFF\xFFpath\xFFgithub.com/prometheus/client_golang\xFFversion\xFF(devel)", - v: 1, - lset: labels.FromStrings( - "__name__", "go_build_info", - "checksum", "", - "path", "github.com/prometheus/client_golang", - "version", "(devel)", - ), - }, - { - m: "go_memstats_alloc_bytes_total", - help: "Total number of bytes allocated, even if freed.", - }, - { - m: "go_memstats_alloc_bytes_total", - typ: MetricTypeCounter, - }, - { - m: "go_memstats_alloc_bytes_total", - v: 1.546544e+06, - lset: labels.FromStrings( - "__name__", "go_memstats_alloc_bytes_total", - ), - e: []exemplar.Exemplar{ - {Labels: labels.FromStrings("dummyID", "42"), Value: 12, HasTs: true, Ts: 1625851151233}, - }, - }, - { - m: "something_untyped", - help: "Just to test the untyped type.", - }, - { - m: "something_untyped", - typ: MetricTypeUnknown, - }, - { - m: "something_untyped", - t: 1234567, - v: 42, - lset: labels.FromStrings( - "__name__", "something_untyped", - ), - }, - { - m: "test_histogram", - help: "Test histogram with many buckets removed to keep it manageable in size.", - }, - { - m: "test_histogram", - typ: MetricTypeHistogram, - }, - { - m: "test_histogram", - t: 1234568, - shs: &histogram.Histogram{ - Count: 175, - ZeroCount: 2, - Sum: 0.0008280461746287094, - ZeroThreshold: 2.938735877055719e-39, - Schema: 3, - PositiveSpans: []histogram.Span{ - {Offset: -161, Length: 1}, - {Offset: 8, Length: 3}, - }, - NegativeSpans: []histogram.Span{ - {Offset: -162, Length: 1}, - {Offset: 23, Length: 4}, - }, - PositiveBuckets: []int64{1, 2, -1, -1}, - NegativeBuckets: []int64{1, 3, -2, -1, 1}, - }, - lset: labels.FromStrings( - "__name__", "test_histogram", - ), - e: []exemplar.Exemplar{ - {Labels: labels.FromStrings("dummyID", "59727"), Value: -0.00039, HasTs: true, Ts: 1625851155146}, - {Labels: labels.FromStrings("dummyID", "5617"), Value: -0.00029, HasTs: false}, - }, - }, - { - m: "test_gauge_histogram", - help: "Like test_histogram but as gauge histogram.", - }, - { - m: "test_gauge_histogram", - typ: MetricTypeGaugeHistogram, - }, - { - m: "test_gauge_histogram", - t: 1234568, - shs: &histogram.Histogram{ - CounterResetHint: histogram.GaugeType, - Count: 175, - ZeroCount: 2, - Sum: 0.0008280461746287094, - ZeroThreshold: 2.938735877055719e-39, - Schema: 3, - PositiveSpans: []histogram.Span{ - {Offset: -161, Length: 1}, - {Offset: 8, Length: 3}, - }, - NegativeSpans: []histogram.Span{ - {Offset: -162, Length: 1}, - {Offset: 23, Length: 4}, - }, - PositiveBuckets: []int64{1, 2, -1, -1}, - NegativeBuckets: []int64{1, 3, -2, -1, 1}, - }, - lset: labels.FromStrings( - "__name__", "test_gauge_histogram", - ), - e: []exemplar.Exemplar{ - {Labels: labels.FromStrings("dummyID", "59727"), Value: -0.00039, HasTs: true, Ts: 1625851155146}, - {Labels: labels.FromStrings("dummyID", "5617"), Value: -0.00029, HasTs: false}, - }, - }, - { - m: "test_float_histogram", - help: "Test float histogram with many buckets removed to keep it manageable in size.", - }, - { - m: "test_float_histogram", - typ: MetricTypeHistogram, - }, - { - m: "test_float_histogram", - t: 1234568, - fhs: &histogram.FloatHistogram{ - Count: 175.0, - ZeroCount: 2.0, - Sum: 0.0008280461746287094, - ZeroThreshold: 2.938735877055719e-39, - Schema: 3, - PositiveSpans: []histogram.Span{ - {Offset: -161, Length: 1}, - {Offset: 8, Length: 3}, - }, - NegativeSpans: []histogram.Span{ - {Offset: -162, Length: 1}, - {Offset: 23, Length: 4}, - }, - PositiveBuckets: []float64{1.0, 2.0, -1.0, -1.0}, - NegativeBuckets: []float64{1.0, 3.0, -2.0, -1.0, 1.0}, - }, - lset: labels.FromStrings( - "__name__", "test_float_histogram", - ), - e: []exemplar.Exemplar{ - {Labels: labels.FromStrings("dummyID", "59727"), Value: -0.00039, HasTs: true, Ts: 1625851155146}, - {Labels: labels.FromStrings("dummyID", "5617"), Value: -0.00029, HasTs: false}, - }, - }, - { - m: "test_gauge_float_histogram", - help: "Like test_float_histogram but as gauge histogram.", - }, - { - m: "test_gauge_float_histogram", - typ: MetricTypeGaugeHistogram, - }, - { - m: "test_gauge_float_histogram", - t: 1234568, - fhs: &histogram.FloatHistogram{ - CounterResetHint: histogram.GaugeType, - Count: 175.0, - ZeroCount: 2.0, - Sum: 0.0008280461746287094, - ZeroThreshold: 2.938735877055719e-39, - Schema: 3, - PositiveSpans: []histogram.Span{ - {Offset: -161, Length: 1}, - {Offset: 8, Length: 3}, - }, - NegativeSpans: []histogram.Span{ - {Offset: -162, Length: 1}, - {Offset: 23, Length: 4}, - }, - PositiveBuckets: []float64{1.0, 2.0, -1.0, -1.0}, - NegativeBuckets: []float64{1.0, 3.0, -2.0, -1.0, 1.0}, - }, - lset: labels.FromStrings( - "__name__", "test_gauge_float_histogram", - ), - e: []exemplar.Exemplar{ - {Labels: labels.FromStrings("dummyID", "59727"), Value: -0.00039, HasTs: true, Ts: 1625851155146}, - {Labels: labels.FromStrings("dummyID", "5617"), Value: -0.00029, HasTs: false}, - }, - }, - { - m: "test_histogram2", - help: "Similar histogram as before but now without sparse buckets.", - }, - { - m: "test_histogram2", - typ: MetricTypeHistogram, - }, - { - m: "test_histogram2_count", - v: 175, - lset: labels.FromStrings( - "__name__", "test_histogram2_count", - ), - }, - { - m: "test_histogram2_sum", - v: 0.000828, - lset: labels.FromStrings( - "__name__", "test_histogram2_sum", - ), - }, - { - m: "test_histogram2_bucket\xffle\xff-0.00048", - v: 2, - lset: labels.FromStrings( - "__name__", "test_histogram2_bucket", - "le", "-0.00048", - ), - }, - { - m: "test_histogram2_bucket\xffle\xff-0.00038", - v: 4, - lset: labels.FromStrings( - "__name__", "test_histogram2_bucket", - "le", "-0.00038", - ), - e: []exemplar.Exemplar{ - {Labels: labels.FromStrings("dummyID", "59727"), Value: -0.00038, HasTs: true, Ts: 1625851153146}, + name: "ignore classic buckets of native histograms", + parser: NewProtobufParser(inputBuf.Bytes(), false), + expected: []parseResult{ + { + m: "go_build_info", + help: "Build information about the main Go module.", + }, + { + m: "go_build_info", + typ: MetricTypeGauge, + }, + { + m: "go_build_info\xFFchecksum\xFF\xFFpath\xFFgithub.com/prometheus/client_golang\xFFversion\xFF(devel)", + v: 1, + lset: labels.FromStrings( + "__name__", "go_build_info", + "checksum", "", + "path", "github.com/prometheus/client_golang", + "version", "(devel)", + ), + }, + { + m: "go_memstats_alloc_bytes_total", + help: "Total number of bytes allocated, even if freed.", + }, + { + m: "go_memstats_alloc_bytes_total", + typ: MetricTypeCounter, + }, + { + m: "go_memstats_alloc_bytes_total", + v: 1.546544e+06, + lset: labels.FromStrings( + "__name__", "go_memstats_alloc_bytes_total", + ), + e: []exemplar.Exemplar{ + {Labels: labels.FromStrings("dummyID", "42"), Value: 12, HasTs: true, Ts: 1625851151233}, + }, + }, + { + m: "something_untyped", + help: "Just to test the untyped type.", + }, + { + m: "something_untyped", + typ: MetricTypeUnknown, + }, + { + m: "something_untyped", + t: 1234567, + v: 42, + lset: labels.FromStrings( + "__name__", "something_untyped", + ), + }, + { + m: "test_histogram", + help: "Test histogram with many buckets removed to keep it manageable in size.", + }, + { + m: "test_histogram", + typ: MetricTypeHistogram, + }, + { + m: "test_histogram", + t: 1234568, + shs: &histogram.Histogram{ + Count: 175, + ZeroCount: 2, + Sum: 0.0008280461746287094, + ZeroThreshold: 2.938735877055719e-39, + Schema: 3, + PositiveSpans: []histogram.Span{ + {Offset: -161, Length: 1}, + {Offset: 8, Length: 3}, + }, + NegativeSpans: []histogram.Span{ + {Offset: -162, Length: 1}, + {Offset: 23, Length: 4}, + }, + PositiveBuckets: []int64{1, 2, -1, -1}, + NegativeBuckets: []int64{1, 3, -2, -1, 1}, + }, + lset: labels.FromStrings( + "__name__", "test_histogram", + ), + e: []exemplar.Exemplar{ + {Labels: labels.FromStrings("dummyID", "59727"), Value: -0.00039, HasTs: true, Ts: 1625851155146}, + {Labels: labels.FromStrings("dummyID", "5617"), Value: -0.00029, HasTs: false}, + }, + }, + { + m: "test_gauge_histogram", + help: "Like test_histogram but as gauge histogram.", + }, + { + m: "test_gauge_histogram", + typ: MetricTypeGaugeHistogram, + }, + { + m: "test_gauge_histogram", + t: 1234568, + shs: &histogram.Histogram{ + CounterResetHint: histogram.GaugeType, + Count: 175, + ZeroCount: 2, + Sum: 0.0008280461746287094, + ZeroThreshold: 2.938735877055719e-39, + Schema: 3, + PositiveSpans: []histogram.Span{ + {Offset: -161, Length: 1}, + {Offset: 8, Length: 3}, + }, + NegativeSpans: []histogram.Span{ + {Offset: -162, Length: 1}, + {Offset: 23, Length: 4}, + }, + PositiveBuckets: []int64{1, 2, -1, -1}, + NegativeBuckets: []int64{1, 3, -2, -1, 1}, + }, + lset: labels.FromStrings( + "__name__", "test_gauge_histogram", + ), + e: []exemplar.Exemplar{ + {Labels: labels.FromStrings("dummyID", "59727"), Value: -0.00039, HasTs: true, Ts: 1625851155146}, + {Labels: labels.FromStrings("dummyID", "5617"), Value: -0.00029, HasTs: false}, + }, + }, + { + m: "test_float_histogram", + help: "Test float histogram with many buckets removed to keep it manageable in size.", + }, + { + m: "test_float_histogram", + typ: MetricTypeHistogram, + }, + { + m: "test_float_histogram", + t: 1234568, + fhs: &histogram.FloatHistogram{ + Count: 175.0, + ZeroCount: 2.0, + Sum: 0.0008280461746287094, + ZeroThreshold: 2.938735877055719e-39, + Schema: 3, + PositiveSpans: []histogram.Span{ + {Offset: -161, Length: 1}, + {Offset: 8, Length: 3}, + }, + NegativeSpans: []histogram.Span{ + {Offset: -162, Length: 1}, + {Offset: 23, Length: 4}, + }, + PositiveBuckets: []float64{1.0, 2.0, -1.0, -1.0}, + NegativeBuckets: []float64{1.0, 3.0, -2.0, -1.0, 1.0}, + }, + lset: labels.FromStrings( + "__name__", "test_float_histogram", + ), + e: []exemplar.Exemplar{ + {Labels: labels.FromStrings("dummyID", "59727"), Value: -0.00039, HasTs: true, Ts: 1625851155146}, + {Labels: labels.FromStrings("dummyID", "5617"), Value: -0.00029, HasTs: false}, + }, + }, + { + m: "test_gauge_float_histogram", + help: "Like test_float_histogram but as gauge histogram.", + }, + { + m: "test_gauge_float_histogram", + typ: MetricTypeGaugeHistogram, + }, + { + m: "test_gauge_float_histogram", + t: 1234568, + fhs: &histogram.FloatHistogram{ + CounterResetHint: histogram.GaugeType, + Count: 175.0, + ZeroCount: 2.0, + Sum: 0.0008280461746287094, + ZeroThreshold: 2.938735877055719e-39, + Schema: 3, + PositiveSpans: []histogram.Span{ + {Offset: -161, Length: 1}, + {Offset: 8, Length: 3}, + }, + NegativeSpans: []histogram.Span{ + {Offset: -162, Length: 1}, + {Offset: 23, Length: 4}, + }, + PositiveBuckets: []float64{1.0, 2.0, -1.0, -1.0}, + NegativeBuckets: []float64{1.0, 3.0, -2.0, -1.0, 1.0}, + }, + lset: labels.FromStrings( + "__name__", "test_gauge_float_histogram", + ), + e: []exemplar.Exemplar{ + {Labels: labels.FromStrings("dummyID", "59727"), Value: -0.00039, HasTs: true, Ts: 1625851155146}, + {Labels: labels.FromStrings("dummyID", "5617"), Value: -0.00029, HasTs: false}, + }, + }, + { + m: "test_histogram2", + help: "Similar histogram as before but now without sparse buckets.", + }, + { + m: "test_histogram2", + typ: MetricTypeHistogram, + }, + { + m: "test_histogram2_count", + v: 175, + lset: labels.FromStrings( + "__name__", "test_histogram2_count", + ), + }, + { + m: "test_histogram2_sum", + v: 0.000828, + lset: labels.FromStrings( + "__name__", "test_histogram2_sum", + ), + }, + { + m: "test_histogram2_bucket\xffle\xff-0.00048", + v: 2, + lset: labels.FromStrings( + "__name__", "test_histogram2_bucket", + "le", "-0.00048", + ), + }, + { + m: "test_histogram2_bucket\xffle\xff-0.00038", + v: 4, + lset: labels.FromStrings( + "__name__", "test_histogram2_bucket", + "le", "-0.00038", + ), + e: []exemplar.Exemplar{ + {Labels: labels.FromStrings("dummyID", "59727"), Value: -0.00038, HasTs: true, Ts: 1625851153146}, + }, + }, + { + m: "test_histogram2_bucket\xffle\xff1.0", + v: 16, + lset: labels.FromStrings( + "__name__", "test_histogram2_bucket", + "le", "1.0", + ), + e: []exemplar.Exemplar{ + {Labels: labels.FromStrings("dummyID", "5617"), Value: -0.000295, HasTs: false}, + }, + }, + { + m: "test_histogram2_bucket\xffle\xff+Inf", + v: 175, + lset: labels.FromStrings( + "__name__", "test_histogram2_bucket", + "le", "+Inf", + ), + }, + { + m: "rpc_durations_seconds", + help: "RPC latency distributions.", + }, + { + m: "rpc_durations_seconds", + typ: MetricTypeSummary, + }, + { + m: "rpc_durations_seconds_count\xffservice\xffexponential", + v: 262, + lset: labels.FromStrings( + "__name__", "rpc_durations_seconds_count", + "service", "exponential", + ), + }, + { + m: "rpc_durations_seconds_sum\xffservice\xffexponential", + v: 0.00025551262820703587, + lset: labels.FromStrings( + "__name__", "rpc_durations_seconds_sum", + "service", "exponential", + ), + }, + { + m: "rpc_durations_seconds\xffservice\xffexponential\xffquantile\xff0.5", + v: 6.442786329648548e-07, + lset: labels.FromStrings( + "__name__", "rpc_durations_seconds", + "quantile", "0.5", + "service", "exponential", + ), + }, + { + m: "rpc_durations_seconds\xffservice\xffexponential\xffquantile\xff0.9", + v: 1.9435742936658396e-06, + lset: labels.FromStrings( + "__name__", "rpc_durations_seconds", + "quantile", "0.9", + "service", "exponential", + ), + }, + { + m: "rpc_durations_seconds\xffservice\xffexponential\xffquantile\xff0.99", + v: 4.0471608667037015e-06, + lset: labels.FromStrings( + "__name__", "rpc_durations_seconds", + "quantile", "0.99", + "service", "exponential", + ), + }, + { + m: "without_quantiles", + help: "A summary without quantiles.", + }, + { + m: "without_quantiles", + typ: MetricTypeSummary, + }, + { + m: "without_quantiles_count", + v: 42, + lset: labels.FromStrings( + "__name__", "without_quantiles_count", + ), + }, + { + m: "without_quantiles_sum", + v: 1.234, + lset: labels.FromStrings( + "__name__", "without_quantiles_sum", + ), + }, }, }, { - m: "test_histogram2_bucket\xffle\xff1.0", - v: 16, - lset: labels.FromStrings( - "__name__", "test_histogram2_bucket", - "le", "1.0", - ), - e: []exemplar.Exemplar{ - {Labels: labels.FromStrings("dummyID", "5617"), Value: -0.000295, HasTs: false}, + name: "parse classic and native buckets", + parser: NewProtobufParser(inputBuf.Bytes(), true), + expected: []parseResult{ + { // 0 + m: "go_build_info", + help: "Build information about the main Go module.", + }, + { // 1 + m: "go_build_info", + typ: MetricTypeGauge, + }, + { // 2 + m: "go_build_info\xFFchecksum\xFF\xFFpath\xFFgithub.com/prometheus/client_golang\xFFversion\xFF(devel)", + v: 1, + lset: labels.FromStrings( + "__name__", "go_build_info", + "checksum", "", + "path", "github.com/prometheus/client_golang", + "version", "(devel)", + ), + }, + { // 3 + m: "go_memstats_alloc_bytes_total", + help: "Total number of bytes allocated, even if freed.", + }, + { // 4 + m: "go_memstats_alloc_bytes_total", + typ: MetricTypeCounter, + }, + { // 5 + m: "go_memstats_alloc_bytes_total", + v: 1.546544e+06, + lset: labels.FromStrings( + "__name__", "go_memstats_alloc_bytes_total", + ), + e: []exemplar.Exemplar{ + {Labels: labels.FromStrings("dummyID", "42"), Value: 12, HasTs: true, Ts: 1625851151233}, + }, + }, + { // 6 + m: "something_untyped", + help: "Just to test the untyped type.", + }, + { // 7 + m: "something_untyped", + typ: MetricTypeUnknown, + }, + { // 8 + m: "something_untyped", + t: 1234567, + v: 42, + lset: labels.FromStrings( + "__name__", "something_untyped", + ), + }, + { // 9 + m: "test_histogram", + help: "Test histogram with many buckets removed to keep it manageable in size.", + }, + { // 10 + m: "test_histogram", + typ: MetricTypeHistogram, + }, + { // 11 + m: "test_histogram", + t: 1234568, + shs: &histogram.Histogram{ + Count: 175, + ZeroCount: 2, + Sum: 0.0008280461746287094, + ZeroThreshold: 2.938735877055719e-39, + Schema: 3, + PositiveSpans: []histogram.Span{ + {Offset: -161, Length: 1}, + {Offset: 8, Length: 3}, + }, + NegativeSpans: []histogram.Span{ + {Offset: -162, Length: 1}, + {Offset: 23, Length: 4}, + }, + PositiveBuckets: []int64{1, 2, -1, -1}, + NegativeBuckets: []int64{1, 3, -2, -1, 1}, + }, + lset: labels.FromStrings( + "__name__", "test_histogram", + ), + e: []exemplar.Exemplar{ + {Labels: labels.FromStrings("dummyID", "59727"), Value: -0.00039, HasTs: true, Ts: 1625851155146}, + {Labels: labels.FromStrings("dummyID", "5617"), Value: -0.00029, HasTs: false}, + }, + }, + { // 12 + m: "test_histogram_count", + t: 1234568, + v: 175, + lset: labels.FromStrings( + "__name__", "test_histogram_count", + ), + }, + { // 13 + m: "test_histogram_sum", + t: 1234568, + v: 0.0008280461746287094, + lset: labels.FromStrings( + "__name__", "test_histogram_sum", + ), + }, + { // 14 + m: "test_histogram_bucket\xffle\xff-0.0004899999999999998", + t: 1234568, + v: 2, + lset: labels.FromStrings( + "__name__", "test_histogram_bucket", + "le", "-0.0004899999999999998", + ), + }, + { // 15 + m: "test_histogram_bucket\xffle\xff-0.0003899999999999998", + t: 1234568, + v: 4, + lset: labels.FromStrings( + "__name__", "test_histogram_bucket", + "le", "-0.0003899999999999998", + ), + e: []exemplar.Exemplar{ + {Labels: labels.FromStrings("dummyID", "59727"), Value: -0.00039, HasTs: true, Ts: 1625851155146}, + }, + }, + { // 16 + m: "test_histogram_bucket\xffle\xff-0.0002899999999999998", + t: 1234568, + v: 16, + lset: labels.FromStrings( + "__name__", "test_histogram_bucket", + "le", "-0.0002899999999999998", + ), + e: []exemplar.Exemplar{ + {Labels: labels.FromStrings("dummyID", "5617"), Value: -0.00029, HasTs: false}, + }, + }, + { // 17 + m: "test_histogram_bucket\xffle\xff+Inf", + t: 1234568, + v: 175, + lset: labels.FromStrings( + "__name__", "test_histogram_bucket", + "le", "+Inf", + ), + }, + { // 18 + m: "test_gauge_histogram", + help: "Like test_histogram but as gauge histogram.", + }, + { // 19 + m: "test_gauge_histogram", + typ: MetricTypeGaugeHistogram, + }, + { // 20 + m: "test_gauge_histogram", + t: 1234568, + shs: &histogram.Histogram{ + CounterResetHint: histogram.GaugeType, + Count: 175, + ZeroCount: 2, + Sum: 0.0008280461746287094, + ZeroThreshold: 2.938735877055719e-39, + Schema: 3, + PositiveSpans: []histogram.Span{ + {Offset: -161, Length: 1}, + {Offset: 8, Length: 3}, + }, + NegativeSpans: []histogram.Span{ + {Offset: -162, Length: 1}, + {Offset: 23, Length: 4}, + }, + PositiveBuckets: []int64{1, 2, -1, -1}, + NegativeBuckets: []int64{1, 3, -2, -1, 1}, + }, + lset: labels.FromStrings( + "__name__", "test_gauge_histogram", + ), + e: []exemplar.Exemplar{ + {Labels: labels.FromStrings("dummyID", "59727"), Value: -0.00039, HasTs: true, Ts: 1625851155146}, + {Labels: labels.FromStrings("dummyID", "5617"), Value: -0.00029, HasTs: false}, + }, + }, + { // 21 + m: "test_gauge_histogram_count", + t: 1234568, + v: 175, + lset: labels.FromStrings( + "__name__", "test_gauge_histogram_count", + ), + }, + { // 22 + m: "test_gauge_histogram_sum", + t: 1234568, + v: 0.0008280461746287094, + lset: labels.FromStrings( + "__name__", "test_gauge_histogram_sum", + ), + }, + { // 23 + m: "test_gauge_histogram_bucket\xffle\xff-0.0004899999999999998", + t: 1234568, + v: 2, + lset: labels.FromStrings( + "__name__", "test_gauge_histogram_bucket", + "le", "-0.0004899999999999998", + ), + }, + { // 24 + m: "test_gauge_histogram_bucket\xffle\xff-0.0003899999999999998", + t: 1234568, + v: 4, + lset: labels.FromStrings( + "__name__", "test_gauge_histogram_bucket", + "le", "-0.0003899999999999998", + ), + e: []exemplar.Exemplar{ + {Labels: labels.FromStrings("dummyID", "59727"), Value: -0.00039, HasTs: true, Ts: 1625851155146}, + }, + }, + { // 25 + m: "test_gauge_histogram_bucket\xffle\xff-0.0002899999999999998", + t: 1234568, + v: 16, + lset: labels.FromStrings( + "__name__", "test_gauge_histogram_bucket", + "le", "-0.0002899999999999998", + ), + e: []exemplar.Exemplar{ + {Labels: labels.FromStrings("dummyID", "5617"), Value: -0.00029, HasTs: false}, + }, + }, + { // 26 + m: "test_gauge_histogram_bucket\xffle\xff+Inf", + t: 1234568, + v: 175, + lset: labels.FromStrings( + "__name__", "test_gauge_histogram_bucket", + "le", "+Inf", + ), + }, + { // 27 + m: "test_float_histogram", + help: "Test float histogram with many buckets removed to keep it manageable in size.", + }, + { // 28 + m: "test_float_histogram", + typ: MetricTypeHistogram, + }, + { // 29 + m: "test_float_histogram", + t: 1234568, + fhs: &histogram.FloatHistogram{ + Count: 175.0, + ZeroCount: 2.0, + Sum: 0.0008280461746287094, + ZeroThreshold: 2.938735877055719e-39, + Schema: 3, + PositiveSpans: []histogram.Span{ + {Offset: -161, Length: 1}, + {Offset: 8, Length: 3}, + }, + NegativeSpans: []histogram.Span{ + {Offset: -162, Length: 1}, + {Offset: 23, Length: 4}, + }, + PositiveBuckets: []float64{1.0, 2.0, -1.0, -1.0}, + NegativeBuckets: []float64{1.0, 3.0, -2.0, -1.0, 1.0}, + }, + lset: labels.FromStrings( + "__name__", "test_float_histogram", + ), + e: []exemplar.Exemplar{ + {Labels: labels.FromStrings("dummyID", "59727"), Value: -0.00039, HasTs: true, Ts: 1625851155146}, + {Labels: labels.FromStrings("dummyID", "5617"), Value: -0.00029, HasTs: false}, + }, + }, + { // 30 + m: "test_float_histogram_count", + t: 1234568, + v: 175, + lset: labels.FromStrings( + "__name__", "test_float_histogram_count", + ), + }, + { // 31 + m: "test_float_histogram_sum", + t: 1234568, + v: 0.0008280461746287094, + lset: labels.FromStrings( + "__name__", "test_float_histogram_sum", + ), + }, + { // 32 + m: "test_float_histogram_bucket\xffle\xff-0.0004899999999999998", + t: 1234568, + v: 2, + lset: labels.FromStrings( + "__name__", "test_float_histogram_bucket", + "le", "-0.0004899999999999998", + ), + }, + { // 33 + m: "test_float_histogram_bucket\xffle\xff-0.0003899999999999998", + t: 1234568, + v: 4, + lset: labels.FromStrings( + "__name__", "test_float_histogram_bucket", + "le", "-0.0003899999999999998", + ), + e: []exemplar.Exemplar{ + {Labels: labels.FromStrings("dummyID", "59727"), Value: -0.00039, HasTs: true, Ts: 1625851155146}, + }, + }, + { // 34 + m: "test_float_histogram_bucket\xffle\xff-0.0002899999999999998", + t: 1234568, + v: 16, + lset: labels.FromStrings( + "__name__", "test_float_histogram_bucket", + "le", "-0.0002899999999999998", + ), + e: []exemplar.Exemplar{ + {Labels: labels.FromStrings("dummyID", "5617"), Value: -0.00029, HasTs: false}, + }, + }, + { // 35 + m: "test_float_histogram_bucket\xffle\xff+Inf", + t: 1234568, + v: 175, + lset: labels.FromStrings( + "__name__", "test_float_histogram_bucket", + "le", "+Inf", + ), + }, + { // 36 + m: "test_gauge_float_histogram", + help: "Like test_float_histogram but as gauge histogram.", + }, + { // 37 + m: "test_gauge_float_histogram", + typ: MetricTypeGaugeHistogram, + }, + { // 38 + m: "test_gauge_float_histogram", + t: 1234568, + fhs: &histogram.FloatHistogram{ + CounterResetHint: histogram.GaugeType, + Count: 175.0, + ZeroCount: 2.0, + Sum: 0.0008280461746287094, + ZeroThreshold: 2.938735877055719e-39, + Schema: 3, + PositiveSpans: []histogram.Span{ + {Offset: -161, Length: 1}, + {Offset: 8, Length: 3}, + }, + NegativeSpans: []histogram.Span{ + {Offset: -162, Length: 1}, + {Offset: 23, Length: 4}, + }, + PositiveBuckets: []float64{1.0, 2.0, -1.0, -1.0}, + NegativeBuckets: []float64{1.0, 3.0, -2.0, -1.0, 1.0}, + }, + lset: labels.FromStrings( + "__name__", "test_gauge_float_histogram", + ), + e: []exemplar.Exemplar{ + {Labels: labels.FromStrings("dummyID", "59727"), Value: -0.00039, HasTs: true, Ts: 1625851155146}, + {Labels: labels.FromStrings("dummyID", "5617"), Value: -0.00029, HasTs: false}, + }, + }, + { // 39 + m: "test_gauge_float_histogram_count", + t: 1234568, + v: 175, + lset: labels.FromStrings( + "__name__", "test_gauge_float_histogram_count", + ), + }, + { // 40 + m: "test_gauge_float_histogram_sum", + t: 1234568, + v: 0.0008280461746287094, + lset: labels.FromStrings( + "__name__", "test_gauge_float_histogram_sum", + ), + }, + { // 41 + m: "test_gauge_float_histogram_bucket\xffle\xff-0.0004899999999999998", + t: 1234568, + v: 2, + lset: labels.FromStrings( + "__name__", "test_gauge_float_histogram_bucket", + "le", "-0.0004899999999999998", + ), + }, + { // 42 + m: "test_gauge_float_histogram_bucket\xffle\xff-0.0003899999999999998", + t: 1234568, + v: 4, + lset: labels.FromStrings( + "__name__", "test_gauge_float_histogram_bucket", + "le", "-0.0003899999999999998", + ), + e: []exemplar.Exemplar{ + {Labels: labels.FromStrings("dummyID", "59727"), Value: -0.00039, HasTs: true, Ts: 1625851155146}, + }, + }, + { // 43 + m: "test_gauge_float_histogram_bucket\xffle\xff-0.0002899999999999998", + t: 1234568, + v: 16, + lset: labels.FromStrings( + "__name__", "test_gauge_float_histogram_bucket", + "le", "-0.0002899999999999998", + ), + e: []exemplar.Exemplar{ + {Labels: labels.FromStrings("dummyID", "5617"), Value: -0.00029, HasTs: false}, + }, + }, + { // 44 + m: "test_gauge_float_histogram_bucket\xffle\xff+Inf", + t: 1234568, + v: 175, + lset: labels.FromStrings( + "__name__", "test_gauge_float_histogram_bucket", + "le", "+Inf", + ), + }, + { // 45 + m: "test_histogram2", + help: "Similar histogram as before but now without sparse buckets.", + }, + { // 46 + m: "test_histogram2", + typ: MetricTypeHistogram, + }, + { // 47 + m: "test_histogram2_count", + v: 175, + lset: labels.FromStrings( + "__name__", "test_histogram2_count", + ), + }, + { // 48 + m: "test_histogram2_sum", + v: 0.000828, + lset: labels.FromStrings( + "__name__", "test_histogram2_sum", + ), + }, + { // 49 + m: "test_histogram2_bucket\xffle\xff-0.00048", + v: 2, + lset: labels.FromStrings( + "__name__", "test_histogram2_bucket", + "le", "-0.00048", + ), + }, + { // 50 + m: "test_histogram2_bucket\xffle\xff-0.00038", + v: 4, + lset: labels.FromStrings( + "__name__", "test_histogram2_bucket", + "le", "-0.00038", + ), + e: []exemplar.Exemplar{ + {Labels: labels.FromStrings("dummyID", "59727"), Value: -0.00038, HasTs: true, Ts: 1625851153146}, + }, + }, + { // 51 + m: "test_histogram2_bucket\xffle\xff1.0", + v: 16, + lset: labels.FromStrings( + "__name__", "test_histogram2_bucket", + "le", "1.0", + ), + e: []exemplar.Exemplar{ + {Labels: labels.FromStrings("dummyID", "5617"), Value: -0.000295, HasTs: false}, + }, + }, + { // 52 + m: "test_histogram2_bucket\xffle\xff+Inf", + v: 175, + lset: labels.FromStrings( + "__name__", "test_histogram2_bucket", + "le", "+Inf", + ), + }, + { // 53 + m: "rpc_durations_seconds", + help: "RPC latency distributions.", + }, + { // 54 + m: "rpc_durations_seconds", + typ: MetricTypeSummary, + }, + { // 55 + m: "rpc_durations_seconds_count\xffservice\xffexponential", + v: 262, + lset: labels.FromStrings( + "__name__", "rpc_durations_seconds_count", + "service", "exponential", + ), + }, + { // 56 + m: "rpc_durations_seconds_sum\xffservice\xffexponential", + v: 0.00025551262820703587, + lset: labels.FromStrings( + "__name__", "rpc_durations_seconds_sum", + "service", "exponential", + ), + }, + { // 57 + m: "rpc_durations_seconds\xffservice\xffexponential\xffquantile\xff0.5", + v: 6.442786329648548e-07, + lset: labels.FromStrings( + "__name__", "rpc_durations_seconds", + "quantile", "0.5", + "service", "exponential", + ), + }, + { // 58 + m: "rpc_durations_seconds\xffservice\xffexponential\xffquantile\xff0.9", + v: 1.9435742936658396e-06, + lset: labels.FromStrings( + "__name__", "rpc_durations_seconds", + "quantile", "0.9", + "service", "exponential", + ), + }, + { // 59 + m: "rpc_durations_seconds\xffservice\xffexponential\xffquantile\xff0.99", + v: 4.0471608667037015e-06, + lset: labels.FromStrings( + "__name__", "rpc_durations_seconds", + "quantile", "0.99", + "service", "exponential", + ), + }, + { // 60 + m: "without_quantiles", + help: "A summary without quantiles.", + }, + { // 61 + m: "without_quantiles", + typ: MetricTypeSummary, + }, + { // 62 + m: "without_quantiles_count", + v: 42, + lset: labels.FromStrings( + "__name__", "without_quantiles_count", + ), + }, + { // 63 + m: "without_quantiles_sum", + v: 1.234, + lset: labels.FromStrings( + "__name__", "without_quantiles_sum", + ), + }, }, }, - { - m: "test_histogram2_bucket\xffle\xff+Inf", - v: 175, - lset: labels.FromStrings( - "__name__", "test_histogram2_bucket", - "le", "+Inf", - ), - }, - { - m: "rpc_durations_seconds", - help: "RPC latency distributions.", - }, - { - m: "rpc_durations_seconds", - typ: MetricTypeSummary, - }, - { - m: "rpc_durations_seconds_count\xffservice\xffexponential", - v: 262, - lset: labels.FromStrings( - "__name__", "rpc_durations_seconds_count", - "service", "exponential", - ), - }, - { - m: "rpc_durations_seconds_sum\xffservice\xffexponential", - v: 0.00025551262820703587, - lset: labels.FromStrings( - "__name__", "rpc_durations_seconds_sum", - "service", "exponential", - ), - }, - { - m: "rpc_durations_seconds\xffservice\xffexponential\xffquantile\xff0.5", - v: 6.442786329648548e-07, - lset: labels.FromStrings( - "__name__", "rpc_durations_seconds", - "quantile", "0.5", - "service", "exponential", - ), - }, - { - m: "rpc_durations_seconds\xffservice\xffexponential\xffquantile\xff0.9", - v: 1.9435742936658396e-06, - lset: labels.FromStrings( - "__name__", "rpc_durations_seconds", - "quantile", "0.9", - "service", "exponential", - ), - }, - { - m: "rpc_durations_seconds\xffservice\xffexponential\xffquantile\xff0.99", - v: 4.0471608667037015e-06, - lset: labels.FromStrings( - "__name__", "rpc_durations_seconds", - "quantile", "0.99", - "service", "exponential", - ), - }, - { - m: "without_quantiles", - help: "A summary without quantiles.", - }, - { - m: "without_quantiles", - typ: MetricTypeSummary, - }, - { - m: "without_quantiles_count", - v: 42, - lset: labels.FromStrings( - "__name__", "without_quantiles_count", - ), - }, - { - m: "without_quantiles_sum", - v: 1.234, - lset: labels.FromStrings( - "__name__", "without_quantiles_sum", - ), - }, } - p := NewProtobufParser(inputBuf.Bytes()) - i := 0 - - var res labels.Labels + for _, scenario := range scenarios { + t.Run(scenario.name, func(t *testing.T) { + var ( + i int + res labels.Labels + p = scenario.parser + exp = scenario.expected + ) - for { - et, err := p.Next() - if errors.Is(err, io.EOF) { - break - } - require.NoError(t, err) + for { + et, err := p.Next() + if errors.Is(err, io.EOF) { + break + } + require.NoError(t, err) - switch et { - case EntrySeries: - m, ts, v := p.Series() + switch et { + case EntrySeries: + m, ts, v := p.Series() - var e exemplar.Exemplar - p.Metric(&res) - found := p.Exemplar(&e) - require.Equal(t, exp[i].m, string(m)) - if ts != nil { - require.Equal(t, exp[i].t, *ts) - } else { - require.Equal(t, exp[i].t, int64(0)) - } - require.Equal(t, exp[i].v, v) - require.Equal(t, exp[i].lset, res) - if len(exp[i].e) == 0 { - require.Equal(t, false, found) - } else { - require.Equal(t, true, found) - require.Equal(t, exp[i].e[0], e) - } + var e exemplar.Exemplar + p.Metric(&res) + found := p.Exemplar(&e) + require.Equal(t, exp[i].m, string(m)) + if ts != nil { + require.Equal(t, exp[i].t, *ts) + } else { + require.Equal(t, exp[i].t, int64(0)) + } + require.Equal(t, exp[i].v, v) + require.Equal(t, exp[i].lset, res) + if len(exp[i].e) == 0 { + require.Equal(t, false, found) + } else { + require.Equal(t, true, found) + require.Equal(t, exp[i].e[0], e) + } - case EntryHistogram: - m, ts, shs, fhs := p.Histogram() - p.Metric(&res) - require.Equal(t, exp[i].m, string(m)) - if ts != nil { - require.Equal(t, exp[i].t, *ts) - } else { - require.Equal(t, exp[i].t, int64(0)) - } - require.Equal(t, exp[i].lset, res) - require.Equal(t, exp[i].m, string(m)) - if shs != nil { - require.Equal(t, exp[i].shs, shs) - } else { - require.Equal(t, exp[i].fhs, fhs) - } - j := 0 - for e := (exemplar.Exemplar{}); p.Exemplar(&e); j++ { - require.Equal(t, exp[i].e[j], e) - e = exemplar.Exemplar{} - } - require.Equal(t, len(exp[i].e), j, "not enough exemplars found") + case EntryHistogram: + m, ts, shs, fhs := p.Histogram() + p.Metric(&res) + require.Equal(t, exp[i].m, string(m)) + if ts != nil { + require.Equal(t, exp[i].t, *ts) + } else { + require.Equal(t, exp[i].t, int64(0)) + } + require.Equal(t, exp[i].lset, res) + require.Equal(t, exp[i].m, string(m)) + if shs != nil { + require.Equal(t, exp[i].shs, shs) + } else { + require.Equal(t, exp[i].fhs, fhs) + } + j := 0 + for e := (exemplar.Exemplar{}); p.Exemplar(&e); j++ { + require.Equal(t, exp[i].e[j], e) + e = exemplar.Exemplar{} + } + require.Equal(t, len(exp[i].e), j, "not enough exemplars found") - case EntryType: - m, typ := p.Type() - require.Equal(t, exp[i].m, string(m)) - require.Equal(t, exp[i].typ, typ) + case EntryType: + m, typ := p.Type() + require.Equal(t, exp[i].m, string(m)) + require.Equal(t, exp[i].typ, typ) - case EntryHelp: - m, h := p.Help() - require.Equal(t, exp[i].m, string(m)) - require.Equal(t, exp[i].help, string(h)) + case EntryHelp: + m, h := p.Help() + require.Equal(t, exp[i].m, string(m)) + require.Equal(t, exp[i].help, string(h)) - case EntryUnit: - m, u := p.Unit() - require.Equal(t, exp[i].m, string(m)) - require.Equal(t, exp[i].unit, string(u)) + case EntryUnit: + m, u := p.Unit() + require.Equal(t, exp[i].m, string(m)) + require.Equal(t, exp[i].unit, string(u)) - case EntryComment: - require.Equal(t, exp[i].comment, string(p.Comment())) - } + case EntryComment: + require.Equal(t, exp[i].comment, string(p.Comment())) + } - i++ + i++ + } + require.Equal(t, len(exp), i) + }) } - require.Equal(t, len(exp), i) } diff --git a/notifier/notifier.go b/notifier/notifier.go index c3b2e5c7e0f..891372c43e2 100644 --- a/notifier/notifier.go +++ b/notifier/notifier.go @@ -349,19 +349,6 @@ func (n *Manager) Send(alerts ...*Alert) { n.mtx.Lock() defer n.mtx.Unlock() - // Attach external labels before relabelling and sending. - for _, a := range alerts { - lb := labels.NewBuilder(a.Labels) - - n.opts.ExternalLabels.Range(func(l labels.Label) { - if a.Labels.Get(l.Name) == "" { - lb.Set(l.Name, l.Value) - } - }) - - a.Labels = lb.Labels() - } - alerts = n.relabelAlerts(alerts) if len(alerts) == 0 { return @@ -390,15 +377,25 @@ func (n *Manager) Send(alerts ...*Alert) { n.setMore() } +// Attach external labels and process relabelling rules. func (n *Manager) relabelAlerts(alerts []*Alert) []*Alert { + lb := labels.NewBuilder(labels.EmptyLabels()) var relabeledAlerts []*Alert - for _, alert := range alerts { - labels, keep := relabel.Process(alert.Labels, n.opts.RelabelConfigs...) - if keep { - alert.Labels = labels - relabeledAlerts = append(relabeledAlerts, alert) + for _, a := range alerts { + lb.Reset(a.Labels) + n.opts.ExternalLabels.Range(func(l labels.Label) { + if a.Labels.Get(l.Name) == "" { + lb.Set(l.Name, l.Value) + } + }) + + keep := relabel.ProcessBuilder(lb, n.opts.RelabelConfigs...) + if !keep { + continue } + a.Labels = lb.Labels() + relabeledAlerts = append(relabeledAlerts, a) } return relabeledAlerts } @@ -701,36 +698,38 @@ func postPath(pre string, v config.AlertmanagerAPIVersion) string { func AlertmanagerFromGroup(tg *targetgroup.Group, cfg *config.AlertmanagerConfig) ([]alertmanager, []alertmanager, error) { var res []alertmanager var droppedAlertManagers []alertmanager + lb := labels.NewBuilder(labels.EmptyLabels()) for _, tlset := range tg.Targets { - lbls := make([]labels.Label, 0, len(tlset)+2+len(tg.Labels)) + lb.Reset(labels.EmptyLabels()) for ln, lv := range tlset { - lbls = append(lbls, labels.Label{Name: string(ln), Value: string(lv)}) + lb.Set(string(ln), string(lv)) } // Set configured scheme as the initial scheme label for overwrite. - lbls = append(lbls, labels.Label{Name: model.SchemeLabel, Value: cfg.Scheme}) - lbls = append(lbls, labels.Label{Name: pathLabel, Value: postPath(cfg.PathPrefix, cfg.APIVersion)}) + lb.Set(model.SchemeLabel, cfg.Scheme) + lb.Set(pathLabel, postPath(cfg.PathPrefix, cfg.APIVersion)) // Combine target labels with target group labels. for ln, lv := range tg.Labels { if _, ok := tlset[ln]; !ok { - lbls = append(lbls, labels.Label{Name: string(ln), Value: string(lv)}) + lb.Set(string(ln), string(lv)) } } - lset, keep := relabel.Process(labels.New(lbls...), cfg.RelabelConfigs...) + preRelabel := lb.Labels() + keep := relabel.ProcessBuilder(lb, cfg.RelabelConfigs...) if !keep { - droppedAlertManagers = append(droppedAlertManagers, alertmanagerLabels{labels.New(lbls...)}) + droppedAlertManagers = append(droppedAlertManagers, alertmanagerLabels{preRelabel}) continue } - addr := lset.Get(model.AddressLabel) + addr := lb.Get(model.AddressLabel) if err := config.CheckTargetAddress(model.LabelValue(addr)); err != nil { return nil, nil, err } - res = append(res, alertmanagerLabels{lset}) + res = append(res, alertmanagerLabels{lb.Labels()}) } return res, droppedAlertManagers, nil } diff --git a/prompb/README.md b/prompb/README.md index 8c19b17e9df..a33d7bfb881 100644 --- a/prompb/README.md +++ b/prompb/README.md @@ -4,6 +4,6 @@ re-compile them when building Prometheus. If however you have modified the defs and do need to re-compile, run `make proto` from the parent dir. -In order for the script to run, you'll need `protoc` (version 3.12.3) in your -PATH. +In order for the [script](../scripts/genproto.sh) to run, you'll need `protoc` (version 3.15.8) in +your PATH. diff --git a/promql/engine.go b/promql/engine.go index cbeeb82a1ab..8a64fdf3941 100644 --- a/promql/engine.go +++ b/promql/engine.go @@ -1850,14 +1850,14 @@ func (ev *evaluator) vectorSelectorSingle(it *storage.MemoizedSeriesIterator, no } case chunkenc.ValFloat: t, v = it.At() - case chunkenc.ValHistogram, chunkenc.ValFloatHistogram: + case chunkenc.ValFloatHistogram: t, h = it.AtFloatHistogram() default: panic(fmt.Errorf("unknown value type %v", valueType)) } if valueType == chunkenc.ValNone || t > refTime { var ok bool - t, v, _, h, ok = it.PeekPrev() + t, v, h, ok = it.PeekPrev() if !ok || t < refTime-durationMilliseconds(ev.lookbackDelta) { return 0, 0, nil, false } @@ -2263,14 +2263,11 @@ func (ev *evaluator) VectorBinop(op parser.ItemType, lhs, rhs Vector, matching * insertedSigs[insertSig] = struct{}{} } - if (hl != nil && hr != nil) || (hl == nil && hr == nil) { - // Both lhs and rhs are of same type. - enh.Out = append(enh.Out, Sample{ - Metric: metric, - F: floatValue, - H: histogramValue, - }) - } + enh.Out = append(enh.Out, Sample{ + Metric: metric, + F: floatValue, + H: histogramValue, + }) } return enh.Out } @@ -2337,28 +2334,33 @@ func resultMetric(lhs, rhs labels.Labels, op parser.ItemType, matching *parser.V // VectorscalarBinop evaluates a binary operation between a Vector and a Scalar. func (ev *evaluator) VectorscalarBinop(op parser.ItemType, lhs Vector, rhs Scalar, swap, returnBool bool, enh *EvalNodeHelper) Vector { for _, lhsSample := range lhs { - lv, rv := lhsSample.F, rhs.V + lf, rf := lhsSample.F, rhs.V + var rh *histogram.FloatHistogram + lh := lhsSample.H // lhs always contains the Vector. If the original position was different // swap for calculating the value. if swap { - lv, rv = rv, lv + lf, rf = rf, lf + lh, rh = rh, lh } - value, _, keep := vectorElemBinop(op, lv, rv, nil, nil) + float, histogram, keep := vectorElemBinop(op, lf, rf, lh, rh) // Catch cases where the scalar is the LHS in a scalar-vector comparison operation. // We want to always keep the vector element value as the output value, even if it's on the RHS. if op.IsComparisonOperator() && swap { - value = rv + float = rf + histogram = rh } if returnBool { if keep { - value = 1.0 + float = 1.0 } else { - value = 0.0 + float = 0.0 } keep = true } if keep { - lhsSample.F = value + lhsSample.F = float + lhsSample.H = histogram if shouldDropMetricName(op) || returnBool { lhsSample.Metric = enh.DropMetricName(lhsSample.Metric) } @@ -2413,16 +2415,33 @@ func vectorElemBinop(op parser.ItemType, lhs, rhs float64, hlhs, hrhs *histogram // The histogram being added must have the larger schema // code (i.e. the higher resolution). if hrhs.Schema >= hlhs.Schema { - return 0, hlhs.Copy().Add(hrhs), true + return 0, hlhs.Copy().Add(hrhs).Compact(0), true } - return 0, hrhs.Copy().Add(hlhs), true + return 0, hrhs.Copy().Add(hlhs).Compact(0), true } return lhs + rhs, nil, true case parser.SUB: + if hlhs != nil && hrhs != nil { + // The histogram being subtracted must have the larger schema + // code (i.e. the higher resolution). + if hrhs.Schema >= hlhs.Schema { + return 0, hlhs.Copy().Sub(hrhs).Compact(0), true + } + return 0, hrhs.Copy().Mul(-1).Add(hlhs).Compact(0), true + } return lhs - rhs, nil, true case parser.MUL: + if hlhs != nil && hrhs == nil { + return 0, hlhs.Copy().Mul(rhs), true + } + if hlhs == nil && hrhs != nil { + return 0, hrhs.Copy().Mul(lhs), true + } return lhs * rhs, nil, true case parser.DIV: + if hlhs != nil && hrhs == nil { + return 0, hlhs.Copy().Div(rhs), true + } return lhs / rhs, nil, true case parser.POW: return math.Pow(lhs, rhs), nil, true @@ -2452,7 +2471,8 @@ type groupedAggregation struct { labels labels.Labels floatValue float64 histogramValue *histogram.FloatHistogram - mean float64 + floatMean float64 + histogramMean *histogram.FloatHistogram groupCount int heap vectorByValueHeap reverseHeap vectorByReverseValueHeap @@ -2536,7 +2556,7 @@ func (ev *evaluator) aggregation(op parser.ItemType, grouping []string, without newAgg := &groupedAggregation{ labels: m, floatValue: s.F, - mean: s.F, + floatMean: s.F, groupCount: 1, } switch { @@ -2545,6 +2565,11 @@ func (ev *evaluator) aggregation(op parser.ItemType, grouping []string, without case op == parser.SUM: newAgg.histogramValue = s.H.Copy() newAgg.hasHistogram = true + case op == parser.AVG: + newAgg.histogramMean = s.H.Copy() + newAgg.hasHistogram = true + case op == parser.STDVAR || op == parser.STDDEV: + newAgg.groupCount = 0 } result[groupingKey] = newAgg @@ -2589,9 +2614,7 @@ func (ev *evaluator) aggregation(op parser.ItemType, grouping []string, without if s.H.Schema >= group.histogramValue.Schema { group.histogramValue.Add(s.H) } else { - h := s.H.Copy() - h.Add(group.histogramValue) - group.histogramValue = h + group.histogramValue = s.H.Copy().Add(group.histogramValue) } } // Otherwise the aggregation contained floats @@ -2604,25 +2627,46 @@ func (ev *evaluator) aggregation(op parser.ItemType, grouping []string, without case parser.AVG: group.groupCount++ - if math.IsInf(group.mean, 0) { - if math.IsInf(s.F, 0) && (group.mean > 0) == (s.F > 0) { - // The `mean` and `s.V` values are `Inf` of the same sign. They - // can't be subtracted, but the value of `mean` is correct - // already. - break + if s.H != nil { + group.hasHistogram = true + if group.histogramMean != nil { + left := s.H.Copy().Div(float64(group.groupCount)) + right := group.histogramMean.Copy().Div(float64(group.groupCount)) + // The histogram being added/subtracted must have + // an equal or larger schema. + if s.H.Schema >= group.histogramMean.Schema { + toAdd := right.Mul(-1).Add(left) + group.histogramMean.Add(toAdd) + } else { + toAdd := left.Sub(right) + group.histogramMean = toAdd.Add(group.histogramMean) + } } - if !math.IsInf(s.F, 0) && !math.IsNaN(s.F) { - // At this stage, the mean is an infinite. If the added - // value is neither an Inf or a Nan, we can keep that mean - // value. - // This is required because our calculation below removes - // the mean value, which would look like Inf += x - Inf and - // end up as a NaN. - break + // Otherwise the aggregation contained floats + // previously and will be invalid anyway. No + // point in copying the histogram in that case. + } else { + group.hasFloat = true + if math.IsInf(group.floatMean, 0) { + if math.IsInf(s.F, 0) && (group.floatMean > 0) == (s.F > 0) { + // The `floatMean` and `s.F` values are `Inf` of the same sign. They + // can't be subtracted, but the value of `floatMean` is correct + // already. + break + } + if !math.IsInf(s.F, 0) && !math.IsNaN(s.F) { + // At this stage, the mean is an infinite. If the added + // value is neither an Inf or a Nan, we can keep that mean + // value. + // This is required because our calculation below removes + // the mean value, which would look like Inf += x - Inf and + // end up as a NaN. + break + } } + // Divide each side of the `-` by `group.groupCount` to avoid float64 overflows. + group.floatMean += s.F/float64(group.groupCount) - group.floatMean/float64(group.groupCount) } - // Divide each side of the `-` by `group.groupCount` to avoid float64 overflows. - group.mean += s.F/float64(group.groupCount) - group.mean/float64(group.groupCount) case parser.GROUP: // Do nothing. Required to avoid the panic in `default:` below. @@ -2641,10 +2685,12 @@ func (ev *evaluator) aggregation(op parser.ItemType, grouping []string, without group.groupCount++ case parser.STDVAR, parser.STDDEV: - group.groupCount++ - delta := s.F - group.mean - group.mean += delta / float64(group.groupCount) - group.floatValue += delta * (s.F - group.mean) + if s.H == nil { // Ignore native histograms. + group.groupCount++ + delta := s.F - group.floatMean + group.floatMean += delta / float64(group.groupCount) + group.floatValue += delta * (s.F - group.floatMean) + } case parser.TOPK: // We build a heap of up to k elements, with the smallest element at heap[0]. @@ -2696,7 +2742,16 @@ func (ev *evaluator) aggregation(op parser.ItemType, grouping []string, without for _, aggr := range orderedResult { switch op { case parser.AVG: - aggr.floatValue = aggr.mean + if aggr.hasFloat && aggr.hasHistogram { + // We cannot aggregate histogram sample with a float64 sample. + // TODO(zenador): Issue warning when plumbing is in place. + continue + } + if aggr.hasHistogram { + aggr.histogramValue = aggr.histogramMean.Compact(0) + } else { + aggr.floatValue = aggr.floatMean + } case parser.COUNT, parser.COUNT_VALUES: aggr.floatValue = float64(aggr.groupCount) @@ -2739,8 +2794,12 @@ func (ev *evaluator) aggregation(op parser.ItemType, grouping []string, without case parser.SUM: if aggr.hasFloat && aggr.hasHistogram { // We cannot aggregate histogram sample with a float64 sample. + // TODO(zenador): Issue warning when plumbing is in place. continue } + if aggr.hasHistogram { + aggr.histogramValue.Compact(0) + } default: // For other aggregations, we already have the right value. } diff --git a/promql/engine_test.go b/promql/engine_test.go index cfe3694dd94..72cbf91533e 100644 --- a/promql/engine_test.go +++ b/promql/engine_test.go @@ -3966,7 +3966,202 @@ func TestNativeHistogram_HistogramFraction(t *testing.T) { } } -func TestNativeHistogram_Sum_Count_AddOperator(t *testing.T) { +func TestNativeHistogram_Sum_Count_Add_AvgOperator(t *testing.T) { + // TODO(codesome): Integrate histograms into the PromQL testing framework + // and write more tests there. + cases := []struct { + histograms []histogram.Histogram + expected histogram.FloatHistogram + expectedAvg histogram.FloatHistogram + }{ + { + histograms: []histogram.Histogram{ + { + CounterResetHint: histogram.GaugeType, + Schema: 0, + Count: 21, + Sum: 1234.5, + ZeroThreshold: 0.001, + ZeroCount: 4, + PositiveSpans: []histogram.Span{ + {Offset: 0, Length: 2}, + {Offset: 1, Length: 2}, + }, + PositiveBuckets: []int64{1, 1, -1, 0}, + NegativeSpans: []histogram.Span{ + {Offset: 0, Length: 2}, + {Offset: 2, Length: 2}, + }, + NegativeBuckets: []int64{2, 2, -3, 8}, + }, + { + CounterResetHint: histogram.GaugeType, + Schema: 0, + Count: 36, + Sum: 2345.6, + ZeroThreshold: 0.001, + ZeroCount: 5, + PositiveSpans: []histogram.Span{ + {Offset: 0, Length: 4}, + {Offset: 0, Length: 0}, + {Offset: 0, Length: 3}, + }, + PositiveBuckets: []int64{1, 2, -2, 1, -1, 0, 0}, + NegativeSpans: []histogram.Span{ + {Offset: 1, Length: 4}, + {Offset: 2, Length: 0}, + {Offset: 2, Length: 3}, + }, + NegativeBuckets: []int64{1, 3, -2, 5, -2, 0, -3}, + }, + { + CounterResetHint: histogram.GaugeType, + Schema: 0, + Count: 36, + Sum: 1111.1, + ZeroThreshold: 0.001, + ZeroCount: 5, + PositiveSpans: []histogram.Span{ + {Offset: 0, Length: 4}, + {Offset: 0, Length: 0}, + {Offset: 0, Length: 3}, + }, + PositiveBuckets: []int64{1, 2, -2, 1, -1, 0, 0}, + NegativeSpans: []histogram.Span{ + {Offset: 1, Length: 4}, + {Offset: 2, Length: 0}, + {Offset: 2, Length: 3}, + }, + NegativeBuckets: []int64{1, 3, -2, 5, -2, 0, -3}, + }, + { + CounterResetHint: histogram.GaugeType, + Schema: 1, // Everything is 0 just to make the count 4 so avg has nicer numbers. + }, + }, + expected: histogram.FloatHistogram{ + CounterResetHint: histogram.GaugeType, + Schema: 0, + ZeroThreshold: 0.001, + ZeroCount: 14, + Count: 93, + Sum: 4691.2, + PositiveSpans: []histogram.Span{ + {Offset: 0, Length: 7}, + }, + PositiveBuckets: []float64{3, 8, 2, 5, 3, 2, 2}, + NegativeSpans: []histogram.Span{ + {Offset: 0, Length: 6}, + {Offset: 3, Length: 3}, + }, + NegativeBuckets: []float64{2, 6, 8, 4, 15, 9, 10, 10, 4}, + }, + expectedAvg: histogram.FloatHistogram{ + CounterResetHint: histogram.GaugeType, + Schema: 0, + ZeroThreshold: 0.001, + ZeroCount: 3.5, + Count: 23.25, + Sum: 1172.8, + PositiveSpans: []histogram.Span{ + {Offset: 0, Length: 7}, + }, + PositiveBuckets: []float64{0.75, 2, 0.5, 1.25, 0.75, 0.5, 0.5}, + NegativeSpans: []histogram.Span{ + {Offset: 0, Length: 6}, + {Offset: 3, Length: 3}, + }, + NegativeBuckets: []float64{0.5, 1.5, 2, 1, 3.75, 2.25, 2.5, 2.5, 1}, + }, + }, + } + + idx0 := int64(0) + for _, c := range cases { + for _, floatHisto := range []bool{true, false} { + t.Run(fmt.Sprintf("floatHistogram=%t %d", floatHisto, idx0), func(t *testing.T) { + test, err := NewTest(t, "") + require.NoError(t, err) + t.Cleanup(test.Close) + + seriesName := "sparse_histogram_series" + seriesNameOverTime := "sparse_histogram_series_over_time" + + engine := test.QueryEngine() + + ts := idx0 * int64(10*time.Minute/time.Millisecond) + app := test.Storage().Appender(context.TODO()) + for idx1, h := range c.histograms { + lbls := labels.FromStrings("__name__", seriesName, "idx", fmt.Sprintf("%d", idx1)) + // Since we mutate h later, we need to create a copy here. + if floatHisto { + _, err = app.AppendHistogram(0, lbls, ts, nil, h.Copy().ToFloat()) + } else { + _, err = app.AppendHistogram(0, lbls, ts, h.Copy(), nil) + } + require.NoError(t, err) + + lbls = labels.FromStrings("__name__", seriesNameOverTime) + newTs := ts + int64(idx1)*int64(time.Minute/time.Millisecond) + // Since we mutate h later, we need to create a copy here. + if floatHisto { + _, err = app.AppendHistogram(0, lbls, newTs, nil, h.Copy().ToFloat()) + } else { + _, err = app.AppendHistogram(0, lbls, newTs, h.Copy(), nil) + } + require.NoError(t, err) + } + require.NoError(t, app.Commit()) + + queryAndCheck := func(queryString string, ts int64, exp Vector) { + qry, err := engine.NewInstantQuery(test.context, test.Queryable(), nil, queryString, timestamp.Time(ts)) + require.NoError(t, err) + + res := qry.Exec(test.Context()) + require.NoError(t, res.Err) + + vector, err := res.Vector() + require.NoError(t, err) + + require.Equal(t, exp, vector) + } + + // sum(). + queryString := fmt.Sprintf("sum(%s)", seriesName) + queryAndCheck(queryString, ts, []Sample{{T: ts, H: &c.expected, Metric: labels.EmptyLabels()}}) + + // + operator. + queryString = fmt.Sprintf(`%s{idx="0"}`, seriesName) + for idx := 1; idx < len(c.histograms); idx++ { + queryString += fmt.Sprintf(` + ignoring(idx) %s{idx="%d"}`, seriesName, idx) + } + queryAndCheck(queryString, ts, []Sample{{T: ts, H: &c.expected, Metric: labels.EmptyLabels()}}) + + // count(). + queryString = fmt.Sprintf("count(%s)", seriesName) + queryAndCheck(queryString, ts, []Sample{{T: ts, F: 4, Metric: labels.EmptyLabels()}}) + + // avg(). + queryString = fmt.Sprintf("avg(%s)", seriesName) + queryAndCheck(queryString, ts, []Sample{{T: ts, H: &c.expectedAvg, Metric: labels.EmptyLabels()}}) + + offset := int64(len(c.histograms) - 1) + newTs := ts + offset*int64(time.Minute/time.Millisecond) + + // sum_over_time(). + queryString = fmt.Sprintf("sum_over_time(%s[%dm:1m])", seriesNameOverTime, offset) + queryAndCheck(queryString, newTs, []Sample{{T: newTs, H: &c.expected, Metric: labels.EmptyLabels()}}) + + // avg_over_time(). + queryString = fmt.Sprintf("avg_over_time(%s[%dm:1m])", seriesNameOverTime, offset) + queryAndCheck(queryString, newTs, []Sample{{T: newTs, H: &c.expectedAvg, Metric: labels.EmptyLabels()}}) + }) + idx0++ + } + } +} + +func TestNativeHistogram_SubOperator(t *testing.T) { // TODO(codesome): Integrate histograms into the PromQL testing framework // and write more tests there. cases := []struct { @@ -3977,21 +4172,60 @@ func TestNativeHistogram_Sum_Count_AddOperator(t *testing.T) { histograms: []histogram.Histogram{ { Schema: 0, - Count: 21, + Count: 36, + Sum: 2345.6, + ZeroThreshold: 0.001, + ZeroCount: 5, + PositiveSpans: []histogram.Span{ + {Offset: 0, Length: 4}, + {Offset: 0, Length: 0}, + {Offset: 0, Length: 3}, + }, + PositiveBuckets: []int64{1, 2, -2, 1, -1, 0, 0}, + NegativeSpans: []histogram.Span{ + {Offset: 1, Length: 4}, + {Offset: 2, Length: 0}, + {Offset: 2, Length: 3}, + }, + NegativeBuckets: []int64{1, 3, -2, 5, -2, 0, -3}, + }, + { + Schema: 0, + Count: 11, Sum: 1234.5, ZeroThreshold: 0.001, - ZeroCount: 4, + ZeroCount: 3, PositiveSpans: []histogram.Span{ - {Offset: 0, Length: 2}, {Offset: 1, Length: 2}, }, - PositiveBuckets: []int64{1, 1, -1, 0}, + PositiveBuckets: []int64{2, -1}, NegativeSpans: []histogram.Span{ - {Offset: 0, Length: 2}, {Offset: 2, Length: 2}, }, - NegativeBuckets: []int64{2, 2, -3, 8}, + NegativeBuckets: []int64{3, -1}, }, + }, + expected: histogram.FloatHistogram{ + Schema: 0, + Count: 25, + Sum: 1111.1, + ZeroThreshold: 0.001, + ZeroCount: 2, + PositiveSpans: []histogram.Span{ + {Offset: 0, Length: 2}, + {Offset: 1, Length: 4}, + }, + PositiveBuckets: []float64{1, 1, 2, 1, 1, 1}, + NegativeSpans: []histogram.Span{ + {Offset: 1, Length: 2}, + {Offset: 1, Length: 1}, + {Offset: 4, Length: 3}, + }, + NegativeBuckets: []float64{1, 1, 7, 5, 5, 2}, + }, + }, + { + histograms: []histogram.Histogram{ { Schema: 0, Count: 36, @@ -4011,10 +4245,61 @@ func TestNativeHistogram_Sum_Count_AddOperator(t *testing.T) { }, NegativeBuckets: []int64{1, 3, -2, 5, -2, 0, -3}, }, + { + Schema: 1, + Count: 11, + Sum: 1234.5, + ZeroThreshold: 0.001, + ZeroCount: 3, + PositiveSpans: []histogram.Span{ + {Offset: 1, Length: 2}, + }, + PositiveBuckets: []int64{2, -1}, + NegativeSpans: []histogram.Span{ + {Offset: 2, Length: 2}, + }, + NegativeBuckets: []int64{3, -1}, + }, + }, + expected: histogram.FloatHistogram{ + Schema: 0, + Count: 25, + Sum: 1111.1, + ZeroThreshold: 0.001, + ZeroCount: 2, + PositiveSpans: []histogram.Span{ + {Offset: 0, Length: 1}, + {Offset: 1, Length: 5}, + }, + PositiveBuckets: []float64{1, 1, 2, 1, 1, 1}, + NegativeSpans: []histogram.Span{ + {Offset: 1, Length: 4}, + {Offset: 4, Length: 3}, + }, + NegativeBuckets: []float64{-2, 2, 2, 7, 5, 5, 2}, + }, + }, + { + histograms: []histogram.Histogram{ + { + Schema: 1, + Count: 11, + Sum: 1234.5, + ZeroThreshold: 0.001, + ZeroCount: 3, + PositiveSpans: []histogram.Span{ + {Offset: 1, Length: 2}, + }, + PositiveBuckets: []int64{2, -1}, + NegativeSpans: []histogram.Span{ + {Offset: 2, Length: 2}, + }, + NegativeBuckets: []int64{3, -1}, + }, { Schema: 0, Count: 36, - Sum: 1111.1, + Sum: 2345.6, ZeroThreshold: 0.001, ZeroCount: 5, PositiveSpans: []histogram.Span{ @@ -4033,21 +4318,20 @@ func TestNativeHistogram_Sum_Count_AddOperator(t *testing.T) { }, expected: histogram.FloatHistogram{ Schema: 0, + Count: -25, + Sum: -1111.1, ZeroThreshold: 0.001, - ZeroCount: 14, - Count: 93, - Sum: 4691.2, + ZeroCount: -2, PositiveSpans: []histogram.Span{ - {Offset: 0, Length: 3}, - {Offset: 0, Length: 4}, + {Offset: 0, Length: 1}, + {Offset: 1, Length: 5}, }, - PositiveBuckets: []float64{3, 8, 2, 5, 3, 2, 2}, + PositiveBuckets: []float64{-1, -1, -2, -1, -1, -1}, NegativeSpans: []histogram.Span{ - {Offset: 0, Length: 4}, - {Offset: 0, Length: 2}, - {Offset: 3, Length: 3}, + {Offset: 1, Length: 4}, + {Offset: 4, Length: 3}, }, - NegativeBuckets: []float64{2, 6, 8, 4, 15, 9, 10, 10, 4}, + NegativeBuckets: []float64{2, -2, -2, -7, -5, -5, -2}, }, }, } @@ -4091,20 +4375,177 @@ func TestNativeHistogram_Sum_Count_AddOperator(t *testing.T) { require.Equal(t, exp, vector) } - // sum(). - queryString := fmt.Sprintf("sum(%s)", seriesName) - queryAndCheck(queryString, []Sample{{T: ts, H: &c.expected, Metric: labels.EmptyLabels()}}) - - // + operator. - queryString = fmt.Sprintf(`%s{idx="0"}`, seriesName) + // - operator. + queryString := fmt.Sprintf(`%s{idx="0"}`, seriesName) for idx := 1; idx < len(c.histograms); idx++ { - queryString += fmt.Sprintf(` + ignoring(idx) %s{idx="%d"}`, seriesName, idx) + queryString += fmt.Sprintf(` - ignoring(idx) %s{idx="%d"}`, seriesName, idx) } queryAndCheck(queryString, []Sample{{T: ts, H: &c.expected, Metric: labels.EmptyLabels()}}) + }) + idx0++ + } + } +} - // count(). - queryString = fmt.Sprintf("count(%s)", seriesName) - queryAndCheck(queryString, []Sample{{T: ts, F: 3, Metric: labels.EmptyLabels()}}) +func TestNativeHistogram_MulDivOperator(t *testing.T) { + // TODO(codesome): Integrate histograms into the PromQL testing framework + // and write more tests there. + originalHistogram := histogram.Histogram{ + Schema: 0, + Count: 21, + Sum: 33, + ZeroThreshold: 0.001, + ZeroCount: 3, + PositiveSpans: []histogram.Span{ + {Offset: 0, Length: 3}, + }, + PositiveBuckets: []int64{3, 0, 0}, + NegativeSpans: []histogram.Span{ + {Offset: 0, Length: 3}, + }, + NegativeBuckets: []int64{3, 0, 0}, + } + + cases := []struct { + scalar float64 + histogram histogram.Histogram + expectedMul histogram.FloatHistogram + expectedDiv histogram.FloatHistogram + }{ + { + scalar: 3, + histogram: originalHistogram, + expectedMul: histogram.FloatHistogram{ + Schema: 0, + Count: 63, + Sum: 99, + ZeroThreshold: 0.001, + ZeroCount: 9, + PositiveSpans: []histogram.Span{ + {Offset: 0, Length: 3}, + }, + PositiveBuckets: []float64{9, 9, 9}, + NegativeSpans: []histogram.Span{ + {Offset: 0, Length: 3}, + }, + NegativeBuckets: []float64{9, 9, 9}, + }, + expectedDiv: histogram.FloatHistogram{ + Schema: 0, + Count: 7, + Sum: 11, + ZeroThreshold: 0.001, + ZeroCount: 1, + PositiveSpans: []histogram.Span{ + {Offset: 0, Length: 3}, + }, + PositiveBuckets: []float64{1, 1, 1}, + NegativeSpans: []histogram.Span{ + {Offset: 0, Length: 3}, + }, + NegativeBuckets: []float64{1, 1, 1}, + }, + }, + { + scalar: 0, + histogram: originalHistogram, + expectedMul: histogram.FloatHistogram{ + Schema: 0, + Count: 0, + Sum: 0, + ZeroThreshold: 0.001, + ZeroCount: 0, + PositiveSpans: []histogram.Span{ + {Offset: 0, Length: 3}, + }, + PositiveBuckets: []float64{0, 0, 0}, + NegativeSpans: []histogram.Span{ + {Offset: 0, Length: 3}, + }, + NegativeBuckets: []float64{0, 0, 0}, + }, + expectedDiv: histogram.FloatHistogram{ + Schema: 0, + Count: math.Inf(1), + Sum: math.Inf(1), + ZeroThreshold: 0.001, + ZeroCount: math.Inf(1), + PositiveSpans: []histogram.Span{ + {Offset: 0, Length: 3}, + }, + PositiveBuckets: []float64{math.Inf(1), math.Inf(1), math.Inf(1)}, + NegativeSpans: []histogram.Span{ + {Offset: 0, Length: 3}, + }, + NegativeBuckets: []float64{math.Inf(1), math.Inf(1), math.Inf(1)}, + }, + }, + } + + idx0 := int64(0) + for _, c := range cases { + for _, floatHisto := range []bool{true, false} { + t.Run(fmt.Sprintf("floatHistogram=%t %d", floatHisto, idx0), func(t *testing.T) { + test, err := NewTest(t, "") + require.NoError(t, err) + t.Cleanup(test.Close) + + seriesName := "sparse_histogram_series" + floatSeriesName := "float_series" + + engine := test.QueryEngine() + + ts := idx0 * int64(10*time.Minute/time.Millisecond) + app := test.Storage().Appender(context.TODO()) + h := c.histogram + lbls := labels.FromStrings("__name__", seriesName) + // Since we mutate h later, we need to create a copy here. + if floatHisto { + _, err = app.AppendHistogram(0, lbls, ts, nil, h.Copy().ToFloat()) + } else { + _, err = app.AppendHistogram(0, lbls, ts, h.Copy(), nil) + } + require.NoError(t, err) + _, err = app.Append(0, labels.FromStrings("__name__", floatSeriesName), ts, c.scalar) + require.NoError(t, err) + require.NoError(t, app.Commit()) + + queryAndCheck := func(queryString string, exp Vector) { + qry, err := engine.NewInstantQuery(test.context, test.Queryable(), nil, queryString, timestamp.Time(ts)) + require.NoError(t, err) + + res := qry.Exec(test.Context()) + require.NoError(t, res.Err) + + vector, err := res.Vector() + require.NoError(t, err) + + require.Equal(t, exp, vector) + } + + // histogram * scalar. + queryString := fmt.Sprintf(`%s * %f`, seriesName, c.scalar) + queryAndCheck(queryString, []Sample{{T: ts, H: &c.expectedMul, Metric: labels.EmptyLabels()}}) + + // scalar * histogram. + queryString = fmt.Sprintf(`%f * %s`, c.scalar, seriesName) + queryAndCheck(queryString, []Sample{{T: ts, H: &c.expectedMul, Metric: labels.EmptyLabels()}}) + + // histogram * float. + queryString = fmt.Sprintf(`%s * %s`, seriesName, floatSeriesName) + queryAndCheck(queryString, []Sample{{T: ts, H: &c.expectedMul, Metric: labels.EmptyLabels()}}) + + // float * histogram. + queryString = fmt.Sprintf(`%s * %s`, floatSeriesName, seriesName) + queryAndCheck(queryString, []Sample{{T: ts, H: &c.expectedMul, Metric: labels.EmptyLabels()}}) + + // histogram / scalar. + queryString = fmt.Sprintf(`%s / %f`, seriesName, c.scalar) + queryAndCheck(queryString, []Sample{{T: ts, H: &c.expectedDiv, Metric: labels.EmptyLabels()}}) + + // histogram / float. + queryString = fmt.Sprintf(`%s / %s`, seriesName, floatSeriesName) + queryAndCheck(queryString, []Sample{{T: ts, H: &c.expectedDiv, Metric: labels.EmptyLabels()}}) }) idx0++ } diff --git a/promql/functions.go b/promql/functions.go index df29d6c5dc0..96bffab96d3 100644 --- a/promql/functions.go +++ b/promql/functions.go @@ -162,7 +162,7 @@ func extrapolatedRate(vals []parser.Value, args parser.Expressions, enh *EvalNod if resultHistogram == nil { resultFloat *= factor } else { - resultHistogram.Scale(factor) + resultHistogram.Mul(factor) } return append(enh.Out, Sample{F: resultFloat, H: resultHistogram}) @@ -443,15 +443,40 @@ func aggrOverTime(vals []parser.Value, enh *EvalNodeHelper, aggrFn func(Series) return append(enh.Out, Sample{F: aggrFn(el)}) } +func aggrHistOverTime(vals []parser.Value, enh *EvalNodeHelper, aggrFn func(Series) *histogram.FloatHistogram) Vector { + el := vals[0].(Matrix)[0] + + return append(enh.Out, Sample{H: aggrFn(el)}) +} + // === avg_over_time(Matrix parser.ValueTypeMatrix) Vector === func funcAvgOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { - if len(vals[0].(Matrix)[0].Floats) == 0 { - // TODO(beorn7): The passed values only contain - // histograms. avg_over_time ignores histograms for now. If - // there are only histograms, we have to return without adding - // anything to enh.Out. + if len(vals[0].(Matrix)[0].Floats) > 0 && len(vals[0].(Matrix)[0].Histograms) > 0 { + // TODO(zenador): Add warning for mixed floats and histograms. return enh.Out } + if len(vals[0].(Matrix)[0].Floats) == 0 { + // The passed values only contain histograms. + return aggrHistOverTime(vals, enh, func(s Series) *histogram.FloatHistogram { + count := 1 + mean := s.Histograms[0].H.Copy() + for _, h := range s.Histograms[1:] { + count++ + left := h.H.Copy().Div(float64(count)) + right := mean.Copy().Div(float64(count)) + // The histogram being added/subtracted must have + // an equal or larger schema. + if h.H.Schema >= mean.Schema { + toAdd := right.Mul(-1).Add(left) + mean.Add(toAdd) + } else { + toAdd := left.Sub(right) + mean = toAdd.Add(mean) + } + } + return mean + }) + } return aggrOverTime(vals, enh, func(s Series) float64 { var mean, count, c float64 for _, f := range s.Floats { @@ -558,13 +583,26 @@ func funcMinOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNode // === sum_over_time(Matrix parser.ValueTypeMatrix) Vector === func funcSumOverTime(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector { - if len(vals[0].(Matrix)[0].Floats) == 0 { - // TODO(beorn7): The passed values only contain - // histograms. sum_over_time ignores histograms for now. If - // there are only histograms, we have to return without adding - // anything to enh.Out. + if len(vals[0].(Matrix)[0].Floats) > 0 && len(vals[0].(Matrix)[0].Histograms) > 0 { + // TODO(zenador): Add warning for mixed floats and histograms. return enh.Out } + if len(vals[0].(Matrix)[0].Floats) == 0 { + // The passed values only contain histograms. + return aggrHistOverTime(vals, enh, func(s Series) *histogram.FloatHistogram { + sum := s.Histograms[0].H.Copy() + for _, h := range s.Histograms[1:] { + // The histogram being added must have + // an equal or larger schema. + if h.H.Schema >= sum.Schema { + sum.Add(h.H) + } else { + sum = h.H.Copy().Add(sum) + } + } + return sum + }) + } return aggrOverTime(vals, enh, func(s Series) float64 { var sum, c float64 for _, f := range s.Floats { diff --git a/promql/fuzz.go b/promql/fuzz.go index 39933378e69..aff6eb15b20 100644 --- a/promql/fuzz.go +++ b/promql/fuzz.go @@ -58,7 +58,7 @@ const ( ) func fuzzParseMetricWithContentType(in []byte, contentType string) int { - p, warning := textparse.New(in, contentType) + p, warning := textparse.New(in, contentType, false) if warning != nil { // An invalid content type is being passed, which should not happen // in this context. diff --git a/rh-manifest.txt b/rh-manifest.txt index 3ac295f942c..5156b2a9ccf 100644 --- a/rh-manifest.txt +++ b/rh-manifest.txt @@ -1,25 +1,25 @@ @babel/runtime@7.19.0 -@codemirror/autocomplete@6.4.0 -@codemirror/commands@6.2.0 -@codemirror/language@6.4.0 -@codemirror/lint@6.1.0 -@codemirror/search@6.2.3 -@codemirror/state@6.2.0 -@codemirror/view@6.7.3 +@codemirror/autocomplete@6.7.1 +@codemirror/commands@6.2.4 +@codemirror/language@6.7.0 +@codemirror/lint@6.2.2 +@codemirror/search@6.5.0 +@codemirror/state@6.2.1 +@codemirror/view@6.13.0 @forevolve/bootstrap-dark@2.1.1 -@fortawesome/fontawesome-common-types@6.2.1 -@fortawesome/fontawesome-svg-core@6.2.1 -@fortawesome/free-solid-svg-icons@6.2.1 +@fortawesome/fontawesome-common-types@6.4.0 +@fortawesome/fontawesome-svg-core@6.4.0 +@fortawesome/free-solid-svg-icons@6.4.0 @fortawesome/react-fontawesome@0.2.0 @hypnosphi/create-react-context@0.3.1 -@lezer/common@1.0.2 -@lezer/highlight@1.1.3 -@lezer/lr@1.3.1 +@lezer/common@1.0.3 +@lezer/highlight@1.1.6 +@lezer/lr@1.3.6 @nexucis/fuzzy@0.4.1 @nexucis/kvsearch@0.8.1 -@prometheus-io/app@0.44.0 -@prometheus-io/codemirror-promql@0.44.0 -@prometheus-io/lezer-promql@0.44.0 +@prometheus-io/app@0.45.0 +@prometheus-io/codemirror-promql@0.45.0 +@prometheus-io/lezer-promql@0.45.0 @types/body-parser@1.19.2 @types/connect@3.4.35 @types/express-serve-static-core@4.17.31 @@ -51,7 +51,7 @@ dom-serializer@2.0.0 domelementtype@2.3.0 domhandler@5.0.3 domutils@3.0.1 -downshift@7.2.0 +downshift@7.6.0 entities@4.4.0 escape-string-regexp@4.0.0 eventemitter3@4.0.7 @@ -84,14 +84,14 @@ is-plain-object@5.0.0 is-regex@1.1.4 isarray@0.0.1 jquery.flot.tooltip@0.9.0 -jquery@3.6.3 +jquery@3.7.0 js-tokens@4.0.0 lodash.flattendeep@4.4.0 lodash@4.17.21 loose-envify@1.4.0 lru-cache@6.0.0 micromatch@4.0.5 -moment-timezone@0.5.40 +moment-timezone@0.5.43 moment@2.29.4 nanoid@3.3.4 nearley@2.7.10 @@ -130,8 +130,8 @@ regexp.prototype.flags@1.4.3 requires-port@1.0.0 resolve-pathname@3.0.0 ret@0.1.15 -sanitize-html@2.8.1 -sass@1.57.1 +sanitize-html@2.10.0 +sass@1.62.1 scheduler@0.20.2 source-map-js@1.0.2 style-mod@4.0.0 diff --git a/scrape/clientprotobuf.go b/scrape/clientprotobuf.go new file mode 100644 index 00000000000..2213268d59c --- /dev/null +++ b/scrape/clientprotobuf.go @@ -0,0 +1,54 @@ +// Copyright 2023 The Prometheus Authors +// 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 scrape + +import ( + "bytes" + "encoding/binary" + + "github.com/gogo/protobuf/proto" + + // Intentionally using client model to simulate client in tests. + dto "github.com/prometheus/client_model/go" +) + +// Write a MetricFamily into a protobuf. +// This function is intended for testing scraping by providing protobuf serialized input. +func MetricFamilyToProtobuf(metricFamily *dto.MetricFamily) ([]byte, error) { + buffer := &bytes.Buffer{} + err := AddMetricFamilyToProtobuf(buffer, metricFamily) + if err != nil { + return nil, err + } + return buffer.Bytes(), nil +} + +// Append a MetricFamily protobuf representation to a buffer. +// This function is intended for testing scraping by providing protobuf serialized input. +func AddMetricFamilyToProtobuf(buffer *bytes.Buffer, metricFamily *dto.MetricFamily) error { + protoBuf, err := proto.Marshal(metricFamily) + if err != nil { + return err + } + + varintBuf := make([]byte, binary.MaxVarintLen32) + varintLength := binary.PutUvarint(varintBuf, uint64(len(protoBuf))) + + _, err = buffer.Write(varintBuf[:varintLength]) + if err != nil { + return err + } + _, err = buffer.Write(protoBuf) + return err +} diff --git a/scrape/manager.go b/scrape/manager.go index d75fe30cf5e..d7cf6792c26 100644 --- a/scrape/manager.go +++ b/scrape/manager.go @@ -150,7 +150,7 @@ type Manager struct { append storage.Appendable graceShut chan struct{} - jitterSeed uint64 // Global jitterSeed seed is used to spread scrape workload across HA setup. + offsetSeed uint64 // Global offsetSeed seed is used to spread scrape workload across HA setup. mtxScrape sync.Mutex // Guards the fields below. scrapeConfigs map[string]*config.ScrapeConfig scrapePools map[string]*scrapePool @@ -214,7 +214,7 @@ func (m *Manager) reload() { level.Error(m.logger).Log("msg", "error reloading target set", "err", "invalid config id:"+setName) continue } - sp, err := newScrapePool(scrapeConfig, m.append, m.jitterSeed, log.With(m.logger, "scrape_pool", setName), m.opts) + sp, err := newScrapePool(scrapeConfig, m.append, m.offsetSeed, log.With(m.logger, "scrape_pool", setName), m.opts) if err != nil { level.Error(m.logger).Log("msg", "error creating new scrape pool", "err", err, "scrape_pool", setName) continue @@ -234,8 +234,8 @@ func (m *Manager) reload() { wg.Wait() } -// setJitterSeed calculates a global jitterSeed per server relying on extra label set. -func (m *Manager) setJitterSeed(labels labels.Labels) error { +// setOffsetSeed calculates a global offsetSeed per server relying on extra label set. +func (m *Manager) setOffsetSeed(labels labels.Labels) error { h := fnv.New64a() hostname, err := osutil.GetFQDN() if err != nil { @@ -244,7 +244,7 @@ func (m *Manager) setJitterSeed(labels labels.Labels) error { if _, err := fmt.Fprintf(h, "%s%s", hostname, labels.String()); err != nil { return err } - m.jitterSeed = h.Sum64() + m.offsetSeed = h.Sum64() return nil } @@ -281,7 +281,7 @@ func (m *Manager) ApplyConfig(cfg *config.Config) error { } m.scrapeConfigs = c - if err := m.setJitterSeed(cfg.GlobalConfig.ExternalLabels); err != nil { + if err := m.setOffsetSeed(cfg.GlobalConfig.ExternalLabels); err != nil { return err } diff --git a/scrape/manager_test.go b/scrape/manager_test.go index d05d25fa2c8..50f63201376 100644 --- a/scrape/manager_test.go +++ b/scrape/manager_test.go @@ -596,7 +596,7 @@ func TestManagerTargetsUpdates(t *testing.T) { } } -func TestSetJitter(t *testing.T) { +func TestSetOffsetSeed(t *testing.T) { getConfig := func(prometheus string) *config.Config { cfgText := ` global: @@ -617,24 +617,24 @@ global: // Load the first config. cfg1 := getConfig("ha1") - if err := scrapeManager.setJitterSeed(cfg1.GlobalConfig.ExternalLabels); err != nil { + if err := scrapeManager.setOffsetSeed(cfg1.GlobalConfig.ExternalLabels); err != nil { t.Error(err) } - jitter1 := scrapeManager.jitterSeed + offsetSeed1 := scrapeManager.offsetSeed - if jitter1 == 0 { - t.Error("Jitter has to be a hash of uint64") + if offsetSeed1 == 0 { + t.Error("Offset seed has to be a hash of uint64") } // Load the first config. cfg2 := getConfig("ha2") - if err := scrapeManager.setJitterSeed(cfg2.GlobalConfig.ExternalLabels); err != nil { + if err := scrapeManager.setOffsetSeed(cfg2.GlobalConfig.ExternalLabels); err != nil { t.Error(err) } - jitter2 := scrapeManager.jitterSeed + offsetSeed2 := scrapeManager.offsetSeed - if jitter1 == jitter2 { - t.Error("Jitter should not be the same on different set of external labels") + if offsetSeed1 == offsetSeed2 { + t.Error("Offset seed should not be the same on different set of external labels") } } diff --git a/scrape/scrape.go b/scrape/scrape.go index 5c649e729ab..8c4cc51e740 100644 --- a/scrape/scrape.go +++ b/scrape/scrape.go @@ -191,6 +191,12 @@ var ( }, []string{"scrape_job"}, ) + targetScrapeNativeHistogramBucketLimit = prometheus.NewCounter( + prometheus.CounterOpts{ + Name: "prometheus_target_scrapes_exceeded_native_histogram_bucket_limit_total", + Help: "Total number of scrapes that hit the native histogram bucket limit and were rejected.", + }, + ) ) func init() { @@ -216,6 +222,7 @@ func init() { targetScrapeExemplarOutOfOrder, targetScrapePoolExceededLabelLimits, targetSyncFailed, + targetScrapeNativeHistogramBucketLimit, ) } @@ -253,16 +260,18 @@ type labelLimits struct { } type scrapeLoopOptions struct { - target *Target - scraper scraper - sampleLimit int - labelLimits *labelLimits - honorLabels bool - honorTimestamps bool - interval time.Duration - timeout time.Duration - mrc []*relabel.Config - cache *scrapeCache + target *Target + scraper scraper + sampleLimit int + bucketLimit int + labelLimits *labelLimits + honorLabels bool + honorTimestamps bool + interval time.Duration + timeout time.Duration + scrapeClassicHistograms bool + mrc []*relabel.Config + cache *scrapeCache } const maxAheadTime = 10 * time.Minute @@ -270,7 +279,7 @@ const maxAheadTime = 10 * time.Minute // returning an empty label set is interpreted as "drop" type labelsMutator func(labels.Labels) labels.Labels -func newScrapePool(cfg *config.ScrapeConfig, app storage.Appendable, jitterSeed uint64, logger log.Logger, options *Options) (*scrapePool, error) { +func newScrapePool(cfg *config.ScrapeConfig, app storage.Appendable, offsetSeed uint64, logger log.Logger, options *Options) (*scrapePool, error) { targetScrapePools.Inc() if logger == nil { logger = log.NewNopLogger() @@ -316,12 +325,14 @@ func newScrapePool(cfg *config.ScrapeConfig, app storage.Appendable, jitterSeed func(l labels.Labels) labels.Labels { return mutateReportSampleLabels(l, opts.target) }, func(ctx context.Context) storage.Appender { return app.Appender(ctx) }, cache, - jitterSeed, + offsetSeed, opts.honorTimestamps, opts.sampleLimit, + opts.bucketLimit, opts.labelLimits, opts.interval, opts.timeout, + opts.scrapeClassicHistograms, options.ExtraMetrics, options.EnableMetadataStorage, opts.target, @@ -412,6 +423,7 @@ func (sp *scrapePool) reload(cfg *config.ScrapeConfig) error { timeout = time.Duration(sp.config.ScrapeTimeout) bodySizeLimit = int64(sp.config.BodySizeLimit) sampleLimit = int(sp.config.SampleLimit) + bucketLimit = int(sp.config.NativeHistogramBucketLimit) labelLimits = &labelLimits{ labelLimit: int(sp.config.LabelLimit), labelNameLengthLimit: int(sp.config.LabelNameLengthLimit), @@ -446,6 +458,7 @@ func (sp *scrapePool) reload(cfg *config.ScrapeConfig) error { target: t, scraper: s, sampleLimit: sampleLimit, + bucketLimit: bucketLimit, labelLimits: labelLimits, honorLabels: honorLabels, honorTimestamps: honorTimestamps, @@ -530,14 +543,16 @@ func (sp *scrapePool) sync(targets []*Target) { timeout = time.Duration(sp.config.ScrapeTimeout) bodySizeLimit = int64(sp.config.BodySizeLimit) sampleLimit = int(sp.config.SampleLimit) + bucketLimit = int(sp.config.NativeHistogramBucketLimit) labelLimits = &labelLimits{ labelLimit: int(sp.config.LabelLimit), labelNameLengthLimit: int(sp.config.LabelNameLengthLimit), labelValueLengthLimit: int(sp.config.LabelValueLengthLimit), } - honorLabels = sp.config.HonorLabels - honorTimestamps = sp.config.HonorTimestamps - mrc = sp.config.MetricRelabelConfigs + honorLabels = sp.config.HonorLabels + honorTimestamps = sp.config.HonorTimestamps + mrc = sp.config.MetricRelabelConfigs + scrapeClassicHistograms = sp.config.ScrapeClassicHistograms ) sp.targetMtx.Lock() @@ -556,15 +571,17 @@ func (sp *scrapePool) sync(targets []*Target) { } s := &targetScraper{Target: t, client: sp.client, timeout: timeout, bodySizeLimit: bodySizeLimit, acceptHeader: acceptHeader} l := sp.newLoop(scrapeLoopOptions{ - target: t, - scraper: s, - sampleLimit: sampleLimit, - labelLimits: labelLimits, - honorLabels: honorLabels, - honorTimestamps: honorTimestamps, - mrc: mrc, - interval: interval, - timeout: timeout, + target: t, + scraper: s, + sampleLimit: sampleLimit, + bucketLimit: bucketLimit, + labelLimits: labelLimits, + honorLabels: honorLabels, + honorTimestamps: honorTimestamps, + mrc: mrc, + interval: interval, + timeout: timeout, + scrapeClassicHistograms: scrapeClassicHistograms, }) if err != nil { l.setForcedError(err) @@ -731,17 +748,24 @@ func mutateReportSampleLabels(lset labels.Labels, target *Target) labels.Labels } // appender returns an appender for ingested samples from the target. -func appender(app storage.Appender, limit int) storage.Appender { +func appender(app storage.Appender, sampleLimit, bucketLimit int) storage.Appender { app = &timeLimitAppender{ Appender: app, maxTime: timestamp.FromTime(time.Now().Add(maxAheadTime)), } - // The limit is applied after metrics are potentially dropped via relabeling. - if limit > 0 { + // The sampleLimit is applied after metrics are potentially dropped via relabeling. + if sampleLimit > 0 { app = &limitAppender{ Appender: app, - limit: limit, + limit: sampleLimit, + } + } + + if bucketLimit > 0 { + app = &bucketLimitAppender{ + Appender: app, + limit: bucketLimit, } } return app @@ -751,7 +775,7 @@ func appender(app storage.Appender, limit int) storage.Appender { type scraper interface { scrape(ctx context.Context, w io.Writer) (string, error) Report(start time.Time, dur time.Duration, err error) - offset(interval time.Duration, jitterSeed uint64) time.Duration + offset(interval time.Duration, offsetSeed uint64) time.Duration } // targetScraper implements the scraper interface for a target. @@ -862,19 +886,21 @@ type cacheEntry struct { } type scrapeLoop struct { - scraper scraper - l log.Logger - cache *scrapeCache - lastScrapeSize int - buffers *pool.Pool - jitterSeed uint64 - honorTimestamps bool - forcedErr error - forcedErrMtx sync.Mutex - sampleLimit int - labelLimits *labelLimits - interval time.Duration - timeout time.Duration + scraper scraper + l log.Logger + cache *scrapeCache + lastScrapeSize int + buffers *pool.Pool + offsetSeed uint64 + honorTimestamps bool + forcedErr error + forcedErrMtx sync.Mutex + sampleLimit int + bucketLimit int + labelLimits *labelLimits + interval time.Duration + timeout time.Duration + scrapeClassicHistograms bool appender func(ctx context.Context) storage.Appender sampleMutator labelsMutator @@ -1149,12 +1175,14 @@ func newScrapeLoop(ctx context.Context, reportSampleMutator labelsMutator, appender func(ctx context.Context) storage.Appender, cache *scrapeCache, - jitterSeed uint64, + offsetSeed uint64, honorTimestamps bool, sampleLimit int, + bucketLimit int, labelLimits *labelLimits, interval time.Duration, timeout time.Duration, + scrapeClassicHistograms bool, reportExtraMetrics bool, appendMetadataToWAL bool, target *Target, @@ -1182,24 +1210,26 @@ func newScrapeLoop(ctx context.Context, } sl := &scrapeLoop{ - scraper: sc, - buffers: buffers, - cache: cache, - appender: appender, - sampleMutator: sampleMutator, - reportSampleMutator: reportSampleMutator, - stopped: make(chan struct{}), - jitterSeed: jitterSeed, - l: l, - parentCtx: ctx, - appenderCtx: appenderCtx, - honorTimestamps: honorTimestamps, - sampleLimit: sampleLimit, - labelLimits: labelLimits, - interval: interval, - timeout: timeout, - reportExtraMetrics: reportExtraMetrics, - appendMetadataToWAL: appendMetadataToWAL, + scraper: sc, + buffers: buffers, + cache: cache, + appender: appender, + sampleMutator: sampleMutator, + reportSampleMutator: reportSampleMutator, + stopped: make(chan struct{}), + offsetSeed: offsetSeed, + l: l, + parentCtx: ctx, + appenderCtx: appenderCtx, + honorTimestamps: honorTimestamps, + sampleLimit: sampleLimit, + bucketLimit: bucketLimit, + labelLimits: labelLimits, + interval: interval, + timeout: timeout, + scrapeClassicHistograms: scrapeClassicHistograms, + reportExtraMetrics: reportExtraMetrics, + appendMetadataToWAL: appendMetadataToWAL, } sl.ctx, sl.cancel = context.WithCancel(ctx) @@ -1208,7 +1238,7 @@ func newScrapeLoop(ctx context.Context, func (sl *scrapeLoop) run(errc chan<- error) { select { - case <-time.After(sl.scraper.offset(sl.interval, sl.jitterSeed)): + case <-time.After(sl.scraper.offset(sl.interval, sl.offsetSeed)): // Continue after a scraping offset. case <-sl.ctx.Done(): close(sl.stopped) @@ -1469,7 +1499,7 @@ type appendErrors struct { } func (sl *scrapeLoop) append(app storage.Appender, b []byte, contentType string, ts time.Time) (total, added, seriesAdded int, err error) { - p, err := textparse.New(b, contentType) + p, err := textparse.New(b, contentType, sl.scrapeClassicHistograms) if err != nil { level.Debug(sl.l).Log( "msg", "Invalid content type on scrape, using prometheus parser as fallback.", @@ -1482,6 +1512,7 @@ func (sl *scrapeLoop) append(app storage.Appender, b []byte, contentType string, defTime = timestamp.FromTime(ts) appErrs = appendErrors{} sampleLimitErr error + bucketLimitErr error e exemplar.Exemplar // escapes to heap so hoisted out of loop meta metadata.Metadata metadataChanged bool @@ -1510,7 +1541,7 @@ func (sl *scrapeLoop) append(app storage.Appender, b []byte, contentType string, } // Take an appender with limits. - app = appender(app, sl.sampleLimit) + app = appender(app, sl.sampleLimit, sl.bucketLimit) defer func() { if err != nil { @@ -1631,7 +1662,7 @@ loop: } else { ref, err = app.Append(ref, lset, t, val) } - sampleAdded, err = sl.checkAddError(ce, met, parsedTimestamp, err, &sampleLimitErr, &appErrs) + sampleAdded, err = sl.checkAddError(ce, met, parsedTimestamp, err, &sampleLimitErr, &bucketLimitErr, &appErrs) if err != nil { if err != storage.ErrNotFound { level.Debug(sl.l).Log("msg", "Unexpected error", "series", string(met), "err", err) @@ -1645,7 +1676,7 @@ loop: sl.cache.trackStaleness(hash, lset) } sl.cache.addRef(met, ref, lset, hash) - if sampleAdded && sampleLimitErr == nil { + if sampleAdded && sampleLimitErr == nil && bucketLimitErr == nil { seriesAdded++ } } @@ -1681,6 +1712,13 @@ loop: // We only want to increment this once per scrape, so this is Inc'd outside the loop. targetScrapeSampleLimit.Inc() } + if bucketLimitErr != nil { + if err == nil { + err = bucketLimitErr // If sample limit is hit, that error takes precedence. + } + // We only want to increment this once per scrape, so this is Inc'd outside the loop. + targetScrapeNativeHistogramBucketLimit.Inc() + } if appErrs.numOutOfOrder > 0 { level.Warn(sl.l).Log("msg", "Error on ingesting out-of-order samples", "num_dropped", appErrs.numOutOfOrder) } @@ -1710,8 +1748,8 @@ loop: } // Adds samples to the appender, checking the error, and then returns the # of samples added, -// whether the caller should continue to process more samples, and any sample limit errors. -func (sl *scrapeLoop) checkAddError(ce *cacheEntry, met []byte, tp *int64, err error, sampleLimitErr *error, appErrs *appendErrors) (bool, error) { +// whether the caller should continue to process more samples, and any sample or bucket limit errors. +func (sl *scrapeLoop) checkAddError(ce *cacheEntry, met []byte, tp *int64, err error, sampleLimitErr, bucketLimitErr *error, appErrs *appendErrors) (bool, error) { switch errors.Cause(err) { case nil: if tp == nil && ce != nil { @@ -1740,6 +1778,11 @@ func (sl *scrapeLoop) checkAddError(ce *cacheEntry, met []byte, tp *int64, err e // total number of samples scraped. *sampleLimitErr = err return false, nil + case errBucketLimit: + // Keep on parsing output if we hit the limit, so we report the correct + // total number of samples scraped. + *bucketLimitErr = err + return false, nil default: return false, err } diff --git a/scrape/scrape_test.go b/scrape/scrape_test.go index 2a2ca094850..6c45c26b429 100644 --- a/scrape/scrape_test.go +++ b/scrape/scrape_test.go @@ -30,6 +30,7 @@ import ( "github.com/go-kit/log" "github.com/pkg/errors" + "github.com/prometheus/client_golang/prometheus" dto "github.com/prometheus/client_model/go" config_util "github.com/prometheus/common/config" "github.com/prometheus/common/model" @@ -190,8 +191,9 @@ func TestScrapePoolStop(t *testing.T) { labels: labels.FromStrings(model.AddressLabel, fmt.Sprintf("example.com:%d", i)), } l := &testLoop{} + d := time.Duration((i+1)*20) * time.Millisecond l.stopFunc = func() { - time.Sleep(time.Duration(i*20) * time.Millisecond) + time.Sleep(d) mtx.Lock() stopped[t.hash()] = true @@ -273,8 +275,9 @@ func TestScrapePoolReload(t *testing.T) { discoveredLabels: labels, } l := &testLoop{} + d := time.Duration((i+1)*20) * time.Millisecond l.stopFunc = func() { - time.Sleep(time.Duration(i*20) * time.Millisecond) + time.Sleep(d) mtx.Lock() stopped[t.hash()] = true @@ -487,7 +490,7 @@ func TestScrapePoolAppender(t *testing.T) { appl, ok := loop.(*scrapeLoop) require.True(t, ok, "Expected scrapeLoop but got %T", loop) - wrapped := appender(appl.appender(context.Background()), 0) + wrapped := appender(appl.appender(context.Background()), 0, 0) tl, ok := wrapped.(*timeLimitAppender) require.True(t, ok, "Expected timeLimitAppender but got %T", wrapped) @@ -503,7 +506,7 @@ func TestScrapePoolAppender(t *testing.T) { appl, ok = loop.(*scrapeLoop) require.True(t, ok, "Expected scrapeLoop but got %T", loop) - wrapped = appender(appl.appender(context.Background()), sampleLimit) + wrapped = appender(appl.appender(context.Background()), sampleLimit, 0) sl, ok := wrapped.(*limitAppender) require.True(t, ok, "Expected limitAppender but got %T", wrapped) @@ -513,6 +516,20 @@ func TestScrapePoolAppender(t *testing.T) { _, ok = tl.Appender.(nopAppender) require.True(t, ok, "Expected base appender but got %T", tl.Appender) + + wrapped = appender(appl.appender(context.Background()), sampleLimit, 100) + + bl, ok := wrapped.(*bucketLimitAppender) + require.True(t, ok, "Expected bucketLimitAppender but got %T", wrapped) + + sl, ok = bl.Appender.(*limitAppender) + require.True(t, ok, "Expected limitAppender but got %T", bl) + + tl, ok = sl.Appender.(*timeLimitAppender) + require.True(t, ok, "Expected timeLimitAppender but got %T", sl.Appender) + + _, ok = tl.Appender.(nopAppender) + require.True(t, ok, "Expected base appender but got %T", tl.Appender) } func TestScrapePoolRaces(t *testing.T) { @@ -610,12 +627,13 @@ func TestScrapeLoopStopBeforeRun(t *testing.T) { nopMutator, nil, nil, 0, true, - 0, + 0, 0, nil, 1, 0, false, false, + false, nil, false, ) @@ -682,12 +700,13 @@ func TestScrapeLoopStop(t *testing.T) { nil, 0, true, - 0, + 0, 0, nil, 10*time.Millisecond, time.Hour, false, false, + false, nil, false, ) @@ -758,12 +777,13 @@ func TestScrapeLoopRun(t *testing.T) { nil, 0, true, - 0, + 0, 0, nil, time.Second, time.Hour, false, false, + false, nil, false, ) @@ -813,12 +833,13 @@ func TestScrapeLoopRun(t *testing.T) { nil, 0, true, - 0, + 0, 0, nil, time.Second, 100*time.Millisecond, false, false, + false, nil, false, ) @@ -872,12 +893,13 @@ func TestScrapeLoopForcedErr(t *testing.T) { nil, 0, true, - 0, + 0, 0, nil, time.Second, time.Hour, false, false, + false, nil, false, ) @@ -930,12 +952,13 @@ func TestScrapeLoopMetadata(t *testing.T) { cache, 0, true, - 0, + 0, 0, nil, 0, 0, false, false, + false, nil, false, ) @@ -987,12 +1010,13 @@ func simpleTestScrapeLoop(t testing.TB) (context.Context, *scrapeLoop) { nil, 0, true, - 0, + 0, 0, nil, 0, 0, false, false, + false, nil, false, ) @@ -1047,12 +1071,13 @@ func TestScrapeLoopFailWithInvalidLabelsAfterRelabel(t *testing.T) { nil, 0, true, - 0, + 0, 0, nil, 0, 0, false, false, + false, nil, false, ) @@ -1125,12 +1150,13 @@ func TestScrapeLoopRunCreatesStaleMarkersOnFailedScrape(t *testing.T) { nil, 0, true, - 0, + 0, 0, nil, 10*time.Millisecond, time.Hour, false, false, + false, nil, false, ) @@ -1188,12 +1214,13 @@ func TestScrapeLoopRunCreatesStaleMarkersOnParseFailure(t *testing.T) { nil, 0, true, - 0, + 0, 0, nil, 10*time.Millisecond, time.Hour, false, false, + false, nil, false, ) @@ -1254,12 +1281,13 @@ func TestScrapeLoopCache(t *testing.T) { nil, 0, true, - 0, + 0, 0, nil, 10*time.Millisecond, time.Hour, false, false, + false, nil, false, ) @@ -1337,12 +1365,13 @@ func TestScrapeLoopCacheMemoryExhaustionProtection(t *testing.T) { nil, 0, true, - 0, + 0, 0, nil, 10*time.Millisecond, time.Hour, false, false, + false, nil, false, ) @@ -1451,12 +1480,13 @@ func TestScrapeLoopAppend(t *testing.T) { nil, 0, true, - 0, + 0, 0, nil, 0, 0, false, false, + false, nil, false, ) @@ -1546,7 +1576,7 @@ func TestScrapeLoopAppendForConflictingPrefixedLabels(t *testing.T) { return mutateSampleLabels(l, &Target{labels: labels.FromStrings(tc.targetLabels...)}, false, nil) }, nil, - func(ctx context.Context) storage.Appender { return app }, nil, 0, true, 0, nil, 0, 0, false, false, nil, false, + func(ctx context.Context) storage.Appender { return app }, nil, 0, true, 0, 0, nil, 0, 0, false, false, false, nil, false, ) slApp := sl.appender(context.Background()) _, _, _, err := sl.append(slApp, []byte(tc.exposedLabels), "", time.Date(2000, 1, 1, 1, 0, 0, 0, time.UTC)) @@ -1577,12 +1607,13 @@ func TestScrapeLoopAppendCacheEntryButErrNotFound(t *testing.T) { nil, 0, true, - 0, + 0, 0, nil, 0, 0, false, false, + false, nil, false, ) @@ -1590,7 +1621,7 @@ func TestScrapeLoopAppendCacheEntryButErrNotFound(t *testing.T) { fakeRef := storage.SeriesRef(1) expValue := float64(1) metric := []byte(`metric{n="1"} 1`) - p, warning := textparse.New(metric, "") + p, warning := textparse.New(metric, "", false) require.NoError(t, warning) var lset labels.Labels @@ -1635,12 +1666,13 @@ func TestScrapeLoopAppendSampleLimit(t *testing.T) { nil, 0, true, - app.limit, + app.limit, 0, nil, 0, 0, false, false, + false, nil, false, ) @@ -1695,6 +1727,105 @@ func TestScrapeLoopAppendSampleLimit(t *testing.T) { require.Equal(t, 0, seriesAdded) } +func TestScrapeLoop_HistogramBucketLimit(t *testing.T) { + resApp := &collectResultAppender{} + app := &bucketLimitAppender{Appender: resApp, limit: 2} + + sl := newScrapeLoop(context.Background(), + nil, nil, nil, + func(l labels.Labels) labels.Labels { + if l.Has("deleteme") { + return labels.EmptyLabels() + } + return l + }, + nopMutator, + func(ctx context.Context) storage.Appender { return app }, + nil, + 0, + true, + app.limit, 0, + nil, + 0, + 0, + false, + false, + false, + nil, + false, + ) + + metric := dto.Metric{} + err := targetScrapeNativeHistogramBucketLimit.Write(&metric) + require.NoError(t, err) + beforeMetricValue := metric.GetCounter().GetValue() + + nativeHistogram := prometheus.NewHistogramVec( + prometheus.HistogramOpts{ + Namespace: "testing", + Name: "example_native_histogram", + Help: "This is used for testing", + ConstLabels: map[string]string{"some": "value"}, + NativeHistogramBucketFactor: 1.1, // 10% increase from bucket to bucket + NativeHistogramMaxBucketNumber: 100, // intentionally higher than the limit we'll use in the scraper + }, + []string{"size"}, + ) + registry := prometheus.NewRegistry() + registry.Register(nativeHistogram) + nativeHistogram.WithLabelValues("S").Observe(1.0) + nativeHistogram.WithLabelValues("M").Observe(1.0) + nativeHistogram.WithLabelValues("L").Observe(1.0) + nativeHistogram.WithLabelValues("M").Observe(10.0) + nativeHistogram.WithLabelValues("L").Observe(10.0) // in different bucket since > 1*1.1 + + gathered, err := registry.Gather() + require.NoError(t, err) + require.NotEmpty(t, gathered) + + histogramMetricFamily := gathered[0] + msg, err := MetricFamilyToProtobuf(histogramMetricFamily) + require.NoError(t, err) + + now := time.Now() + total, added, seriesAdded, err := sl.append(app, msg, "application/vnd.google.protobuf", now) + require.NoError(t, err) + require.Equal(t, 3, total) + require.Equal(t, 3, added) + require.Equal(t, 3, seriesAdded) + + err = targetScrapeNativeHistogramBucketLimit.Write(&metric) + require.NoError(t, err) + metricValue := metric.GetCounter().GetValue() + require.Equal(t, beforeMetricValue, metricValue) + beforeMetricValue = metricValue + + nativeHistogram.WithLabelValues("L").Observe(100.0) // in different bucket since > 10*1.1 + + gathered, err = registry.Gather() + require.NoError(t, err) + require.NotEmpty(t, gathered) + + histogramMetricFamily = gathered[0] + msg, err = MetricFamilyToProtobuf(histogramMetricFamily) + require.NoError(t, err) + + now = time.Now() + total, added, seriesAdded, err = sl.append(app, msg, "application/vnd.google.protobuf", now) + if err != errBucketLimit { + t.Fatalf("Did not see expected histogram bucket limit error: %s", err) + } + require.NoError(t, app.Rollback()) + require.Equal(t, 3, total) + require.Equal(t, 3, added) + require.Equal(t, 0, seriesAdded) + + err = targetScrapeNativeHistogramBucketLimit.Write(&metric) + require.NoError(t, err) + metricValue = metric.GetCounter().GetValue() + require.Equal(t, beforeMetricValue+1, metricValue) +} + func TestScrapeLoop_ChangingMetricString(t *testing.T) { // This is a regression test for the scrape loop cache not properly maintaining // IDs when the string representation of a metric changes across a scrape. Thus @@ -1712,12 +1843,13 @@ func TestScrapeLoop_ChangingMetricString(t *testing.T) { nil, 0, true, - 0, + 0, 0, nil, 0, 0, false, false, + false, nil, false, ) @@ -1760,12 +1892,13 @@ func TestScrapeLoopAppendStaleness(t *testing.T) { nil, 0, true, - 0, + 0, 0, nil, 0, 0, false, false, + false, nil, false, ) @@ -1811,12 +1944,13 @@ func TestScrapeLoopAppendNoStalenessIfTimestamp(t *testing.T) { nil, 0, true, - 0, + 0, 0, nil, 0, 0, false, false, + false, nil, false, ) @@ -1922,12 +2056,13 @@ metric_total{n="2"} 2 # {t="2"} 2.0 20000 nil, 0, true, - 0, + 0, 0, nil, 0, 0, false, false, + false, nil, false, ) @@ -1987,12 +2122,13 @@ func TestScrapeLoopAppendExemplarSeries(t *testing.T) { nil, 0, true, - 0, + 0, 0, nil, 0, 0, false, false, + false, nil, false, ) @@ -2039,12 +2175,13 @@ func TestScrapeLoopRunReportsTargetDownOnScrapeError(t *testing.T) { nil, 0, true, - 0, + 0, 0, nil, 10*time.Millisecond, time.Hour, false, false, + false, nil, false, ) @@ -2075,12 +2212,13 @@ func TestScrapeLoopRunReportsTargetDownOnInvalidUTF8(t *testing.T) { nil, 0, true, - 0, + 0, 0, nil, 10*time.Millisecond, time.Hour, false, false, + false, nil, false, ) @@ -2124,12 +2262,13 @@ func TestScrapeLoopAppendGracefullyIfAmendOrOutOfOrderOrOutOfBounds(t *testing.T nil, 0, true, - 0, + 0, 0, nil, 0, 0, false, false, + false, nil, false, ) @@ -2169,12 +2308,13 @@ func TestScrapeLoopOutOfBoundsTimeError(t *testing.T) { nil, 0, true, - 0, + 0, 0, nil, 0, 0, false, false, + false, nil, false, ) @@ -2441,12 +2581,13 @@ func TestScrapeLoop_RespectTimestamps(t *testing.T) { func(ctx context.Context) storage.Appender { return capp }, nil, 0, true, - 0, + 0, 0, nil, 0, 0, false, false, + false, nil, false, ) @@ -2482,12 +2623,13 @@ func TestScrapeLoop_DiscardTimestamps(t *testing.T) { func(ctx context.Context) storage.Appender { return capp }, nil, 0, false, - 0, + 0, 0, nil, 0, 0, false, false, + false, nil, false, ) @@ -2522,12 +2664,13 @@ func TestScrapeLoopDiscardDuplicateLabels(t *testing.T) { nil, 0, true, - 0, + 0, 0, nil, 0, 0, false, false, + false, nil, false, ) @@ -2580,12 +2723,13 @@ func TestScrapeLoopDiscardUnnamedMetrics(t *testing.T) { nil, 0, true, - 0, + 0, 0, nil, 0, 0, false, false, + false, nil, false, ) @@ -2843,12 +2987,13 @@ func TestScrapeAddFast(t *testing.T) { nil, 0, true, - 0, + 0, 0, nil, 0, 0, false, false, + false, nil, false, ) @@ -2906,7 +3051,7 @@ func TestReuseCacheRace(*testing.T) { func TestCheckAddError(t *testing.T) { var appErrs appendErrors sl := scrapeLoop{l: log.NewNopLogger()} - sl.checkAddError(nil, nil, nil, storage.ErrOutOfOrderSample, nil, &appErrs) + sl.checkAddError(nil, nil, nil, storage.ErrOutOfOrderSample, nil, nil, &appErrs) require.Equal(t, 1, appErrs.numOutOfOrder) } @@ -2929,12 +3074,13 @@ func TestScrapeReportSingleAppender(t *testing.T) { nil, 0, true, - 0, + 0, 0, nil, 10*time.Millisecond, time.Hour, false, false, + false, nil, false, ) @@ -3131,12 +3277,13 @@ func TestScrapeLoopLabelLimit(t *testing.T) { nil, 0, true, - 0, + 0, 0, &test.labelLimits, 0, 0, false, false, + false, nil, false, ) diff --git a/scrape/target.go b/scrape/target.go index 6c470311865..a655e85413c 100644 --- a/scrape/target.go +++ b/scrape/target.go @@ -27,6 +27,7 @@ import ( "github.com/prometheus/prometheus/config" "github.com/prometheus/prometheus/discovery/targetgroup" + "github.com/prometheus/prometheus/model/histogram" "github.com/prometheus/prometheus/model/labels" "github.com/prometheus/prometheus/model/relabel" "github.com/prometheus/prometheus/model/textparse" @@ -313,7 +314,10 @@ func (ts Targets) Len() int { return len(ts) } func (ts Targets) Less(i, j int) bool { return ts[i].URL().String() < ts[j].URL().String() } func (ts Targets) Swap(i, j int) { ts[i], ts[j] = ts[j], ts[i] } -var errSampleLimit = errors.New("sample limit exceeded") +var ( + errSampleLimit = errors.New("sample limit exceeded") + errBucketLimit = errors.New("histogram bucket limit exceeded") +) // limitAppender limits the number of total appended samples in a batch. type limitAppender struct { @@ -355,6 +359,31 @@ func (app *timeLimitAppender) Append(ref storage.SeriesRef, lset labels.Labels, return ref, nil } +// bucketLimitAppender limits the number of total appended samples in a batch. +type bucketLimitAppender struct { + storage.Appender + + limit int +} + +func (app *bucketLimitAppender) AppendHistogram(ref storage.SeriesRef, lset labels.Labels, t int64, h *histogram.Histogram, fh *histogram.FloatHistogram) (storage.SeriesRef, error) { + if h != nil { + if len(h.PositiveBuckets)+len(h.NegativeBuckets) > app.limit { + return 0, errBucketLimit + } + } + if fh != nil { + if len(fh.PositiveBuckets)+len(fh.NegativeBuckets) > app.limit { + return 0, errBucketLimit + } + } + ref, err := app.Appender.AppendHistogram(ref, lset, t, h, fh) + if err != nil { + return 0, err + } + return ref, nil +} + // PopulateLabels builds a label set from the given label set and scrape configuration. // It returns a label set before relabeling was applied as the second return value. // Returns the original discovered label set found before relabelling was applied if the target is dropped during relabeling. diff --git a/scrape/target_test.go b/scrape/target_test.go index 9d25df41490..4f0c840cd05 100644 --- a/scrape/target_test.go +++ b/scrape/target_test.go @@ -31,6 +31,7 @@ import ( "github.com/prometheus/prometheus/config" "github.com/prometheus/prometheus/discovery/targetgroup" + "github.com/prometheus/prometheus/model/histogram" "github.com/prometheus/prometheus/model/labels" ) @@ -58,7 +59,7 @@ func TestTargetLabels(t *testing.T) { func TestTargetOffset(t *testing.T) { interval := 10 * time.Second - jitter := uint64(0) + offsetSeed := uint64(0) offsets := make([]time.Duration, 10000) @@ -67,7 +68,7 @@ func TestTargetOffset(t *testing.T) { target := newTestTarget("example.com:80", 0, labels.FromStrings( "label", fmt.Sprintf("%d", i), )) - offsets[i] = target.offset(interval, jitter) + offsets[i] = target.offset(interval, offsetSeed) } // Put the offsets into buckets and validate that they are all @@ -488,3 +489,63 @@ scrape_configs: }) } } + +func TestBucketLimitAppender(t *testing.T) { + example := histogram.Histogram{ + Schema: 0, + Count: 21, + Sum: 33, + ZeroThreshold: 0.001, + ZeroCount: 3, + PositiveSpans: []histogram.Span{ + {Offset: 0, Length: 3}, + }, + PositiveBuckets: []int64{3, 0, 0}, + NegativeSpans: []histogram.Span{ + {Offset: 0, Length: 3}, + }, + NegativeBuckets: []int64{3, 0, 0}, + } + + cases := []struct { + h histogram.Histogram + limit int + expectError bool + }{ + { + h: example, + limit: 3, + expectError: true, + }, + { + h: example, + limit: 10, + expectError: false, + }, + } + + resApp := &collectResultAppender{} + + for _, c := range cases { + for _, floatHisto := range []bool{true, false} { + t.Run(fmt.Sprintf("floatHistogram=%t", floatHisto), func(t *testing.T) { + app := &bucketLimitAppender{Appender: resApp, limit: c.limit} + ts := int64(10 * time.Minute / time.Millisecond) + h := c.h + lbls := labels.FromStrings("__name__", "sparse_histogram_series") + var err error + if floatHisto { + _, err = app.AppendHistogram(0, lbls, ts, nil, h.Copy().ToFloat()) + } else { + _, err = app.AppendHistogram(0, lbls, ts, h.Copy(), nil) + } + if c.expectError { + require.Error(t, err) + } else { + require.NoError(t, err) + } + require.NoError(t, app.Commit()) + }) + } + } +} diff --git a/storage/memoized_iterator.go b/storage/memoized_iterator.go index 88eee0756b8..cb9fdeef46a 100644 --- a/storage/memoized_iterator.go +++ b/storage/memoized_iterator.go @@ -21,6 +21,9 @@ import ( ) // MemoizedSeriesIterator wraps an iterator with a buffer to look back the previous element. +// +// This iterator regards integer histograms as float histograms; calls to Seek() will never return chunkenc.Histogram. +// This iterator deliberately does not implement chunkenc.Iterator. type MemoizedSeriesIterator struct { it chunkenc.Iterator delta int64 @@ -31,12 +34,7 @@ type MemoizedSeriesIterator struct { // Keep track of the previously returned value. prevTime int64 prevValue float64 - prevHistogram *histogram.Histogram prevFloatHistogram *histogram.FloatHistogram - // TODO(beorn7): MemoizedSeriesIterator is currently only used by the - // PromQL engine, which only works with FloatHistograms. For better - // performance, we could change MemoizedSeriesIterator to also only - // handle FloatHistograms. } // NewMemoizedEmptyIterator is like NewMemoizedIterator but it's initialised with an empty iterator. @@ -66,11 +64,11 @@ func (b *MemoizedSeriesIterator) Reset(it chunkenc.Iterator) { // PeekPrev returns the previous element of the iterator. If there is none buffered, // ok is false. -func (b *MemoizedSeriesIterator) PeekPrev() (t int64, v float64, h *histogram.Histogram, fh *histogram.FloatHistogram, ok bool) { +func (b *MemoizedSeriesIterator) PeekPrev() (t int64, v float64, fh *histogram.FloatHistogram, ok bool) { if b.prevTime == math.MinInt64 { - return 0, 0, nil, nil, false + return 0, 0, nil, false } - return b.prevTime, b.prevValue, b.prevHistogram, b.prevFloatHistogram, true + return b.prevTime, b.prevValue, b.prevFloatHistogram, true } // Seek advances the iterator to the element at time t or greater. @@ -83,8 +81,11 @@ func (b *MemoizedSeriesIterator) Seek(t int64) chunkenc.ValueType { b.prevTime = math.MinInt64 b.valueType = b.it.Seek(t0) - if b.valueType == chunkenc.ValNone { + switch b.valueType { + case chunkenc.ValNone: return chunkenc.ValNone + case chunkenc.ValHistogram: + b.valueType = chunkenc.ValFloatHistogram } b.lastTime = b.it.AtT() } @@ -100,7 +101,8 @@ func (b *MemoizedSeriesIterator) Seek(t int64) chunkenc.ValueType { return chunkenc.ValNone } -// Next advances the iterator to the next element. +// Next advances the iterator to the next element. Note that this does not check whether the element being buffered is +// within the time range of the current element and the duration of delta before. func (b *MemoizedSeriesIterator) Next() chunkenc.ValueType { // Keep track of the previous element. switch b.valueType { @@ -108,15 +110,9 @@ func (b *MemoizedSeriesIterator) Next() chunkenc.ValueType { return chunkenc.ValNone case chunkenc.ValFloat: b.prevTime, b.prevValue = b.it.At() - b.prevHistogram = nil b.prevFloatHistogram = nil - case chunkenc.ValHistogram: - b.prevValue = 0 - b.prevTime, b.prevHistogram = b.it.AtHistogram() - _, b.prevFloatHistogram = b.it.AtFloatHistogram() - case chunkenc.ValFloatHistogram: + case chunkenc.ValHistogram, chunkenc.ValFloatHistogram: b.prevValue = 0 - b.prevHistogram = nil b.prevTime, b.prevFloatHistogram = b.it.AtFloatHistogram() } @@ -124,6 +120,9 @@ func (b *MemoizedSeriesIterator) Next() chunkenc.ValueType { if b.valueType != chunkenc.ValNone { b.lastTime = b.it.AtT() } + if b.valueType == chunkenc.ValHistogram { + b.valueType = chunkenc.ValFloatHistogram + } return b.valueType } @@ -132,21 +131,11 @@ func (b *MemoizedSeriesIterator) At() (int64, float64) { return b.it.At() } -// AtHistogram returns the current histogram element of the iterator. -func (b *MemoizedSeriesIterator) AtHistogram() (int64, *histogram.Histogram) { - return b.it.AtHistogram() -} - // AtFloatHistogram returns the current float-histogram element of the iterator. func (b *MemoizedSeriesIterator) AtFloatHistogram() (int64, *histogram.FloatHistogram) { return b.it.AtFloatHistogram() } -// AtT returns the current timestamp of the iterator. -func (b *MemoizedSeriesIterator) AtT() int64 { - return b.it.AtT() -} - // Err returns the last encountered error. func (b *MemoizedSeriesIterator) Err() error { return b.it.Err() diff --git a/storage/memoized_iterator_test.go b/storage/memoized_iterator_test.go index d996436e009..1c87119283b 100644 --- a/storage/memoized_iterator_test.go +++ b/storage/memoized_iterator_test.go @@ -18,23 +18,34 @@ import ( "github.com/stretchr/testify/require" + "github.com/prometheus/prometheus/model/histogram" "github.com/prometheus/prometheus/tsdb/chunkenc" + "github.com/prometheus/prometheus/tsdb/tsdbutil" ) func TestMemoizedSeriesIterator(t *testing.T) { - // TODO(beorn7): Include histograms in testing. var it *MemoizedSeriesIterator - sampleEq := func(ets int64, ev float64) { - ts, v := it.At() - require.Equal(t, ets, ts, "timestamp mismatch") - require.Equal(t, ev, v, "value mismatch") + sampleEq := func(ets int64, ev float64, efh *histogram.FloatHistogram) { + if efh == nil { + ts, v := it.At() + require.Equal(t, ets, ts, "timestamp mismatch") + require.Equal(t, ev, v, "value mismatch") + } else { + ts, fh := it.AtFloatHistogram() + require.Equal(t, ets, ts, "timestamp mismatch") + require.Equal(t, efh, fh, "histogram mismatch") + } } - prevSampleEq := func(ets int64, ev float64, eok bool) { - ts, v, _, _, ok := it.PeekPrev() + prevSampleEq := func(ets int64, ev float64, efh *histogram.FloatHistogram, eok bool) { + ts, v, fh, ok := it.PeekPrev() require.Equal(t, eok, ok, "exist mismatch") require.Equal(t, ets, ts, "timestamp mismatch") - require.Equal(t, ev, v, "value mismatch") + if efh == nil { + require.Equal(t, ev, v, "value mismatch") + } else { + require.Equal(t, efh, fh, "histogram mismatch") + } } it = NewMemoizedIterator(NewListSeriesIterator(samples{ @@ -46,31 +57,50 @@ func TestMemoizedSeriesIterator(t *testing.T) { fSample{t: 99, f: 8}, fSample{t: 100, f: 9}, fSample{t: 101, f: 10}, + hSample{t: 102, h: tsdbutil.GenerateTestHistogram(0)}, + hSample{t: 103, h: tsdbutil.GenerateTestHistogram(1)}, + fhSample{t: 104, fh: tsdbutil.GenerateTestFloatHistogram(2)}, + fhSample{t: 199, fh: tsdbutil.GenerateTestFloatHistogram(3)}, + hSample{t: 200, h: tsdbutil.GenerateTestHistogram(4)}, + fhSample{t: 299, fh: tsdbutil.GenerateTestFloatHistogram(5)}, + fSample{t: 300, f: 11}, + hSample{t: 399, h: tsdbutil.GenerateTestHistogram(6)}, + fSample{t: 400, f: 12}, }), 2) require.Equal(t, it.Seek(-123), chunkenc.ValFloat, "seek failed") - sampleEq(1, 2) - prevSampleEq(0, 0, false) - - require.Equal(t, it.Next(), chunkenc.ValFloat, "next failed") - sampleEq(2, 3) - prevSampleEq(1, 2, true) - - require.Equal(t, it.Next(), chunkenc.ValFloat, "next failed") - require.Equal(t, it.Next(), chunkenc.ValFloat, "next failed") - require.Equal(t, it.Next(), chunkenc.ValFloat, "next failed") - sampleEq(5, 6) - prevSampleEq(4, 5, true) + sampleEq(1, 2, nil) + prevSampleEq(0, 0, nil, false) require.Equal(t, it.Seek(5), chunkenc.ValFloat, "seek failed") - sampleEq(5, 6) - prevSampleEq(4, 5, true) - - require.Equal(t, it.Seek(101), chunkenc.ValFloat, "seek failed") - sampleEq(101, 10) - prevSampleEq(100, 9, true) + sampleEq(5, 6, nil) + prevSampleEq(4, 5, nil, true) + + // Seek to a histogram sample with a previous float sample. + require.Equal(t, it.Seek(102), chunkenc.ValFloatHistogram, "seek failed") + sampleEq(102, 10, tsdbutil.GenerateTestFloatHistogram(0)) + prevSampleEq(101, 10, nil, true) + + // Attempt to seek backwards (no-op). + require.Equal(t, it.Seek(50), chunkenc.ValFloatHistogram, "seek failed") + sampleEq(102, 10, tsdbutil.GenerateTestFloatHistogram(0)) + prevSampleEq(101, 10, nil, true) + + // Seek to a float histogram sample with a previous histogram sample. + require.Equal(t, it.Seek(104), chunkenc.ValFloatHistogram, "seek failed") + sampleEq(104, 0, tsdbutil.GenerateTestFloatHistogram(2)) + prevSampleEq(103, 0, tsdbutil.GenerateTestFloatHistogram(1), true) + + // Seek to a float sample with a previous float histogram sample. + require.Equal(t, chunkenc.ValFloat, it.Seek(300), "seek failed") + sampleEq(300, 11, nil) + prevSampleEq(299, 0, tsdbutil.GenerateTestFloatHistogram(5), true) + + // Seek to a float sample with a previous histogram sample. + require.Equal(t, chunkenc.ValFloat, it.Seek(400), "seek failed") + sampleEq(400, 12, nil) + prevSampleEq(399, 0, tsdbutil.GenerateTestFloatHistogram(6), true) - require.Equal(t, it.Next(), chunkenc.ValNone, "next succeeded unexpectedly") require.Equal(t, it.Seek(1024), chunkenc.ValNone, "seek succeeded unexpectedly") } diff --git a/storage/remote/azuread/README.md b/storage/remote/azuread/README.md new file mode 100644 index 00000000000..b3b4457a6ef --- /dev/null +++ b/storage/remote/azuread/README.md @@ -0,0 +1,8 @@ +azuread package +========================================= + +azuread provides an http.RoundTripper that attaches an Azure AD accessToken +to remote write requests. + +This module is considered internal to Prometheus, without any stability +guarantees for external usage. diff --git a/storage/remote/azuread/azuread.go b/storage/remote/azuread/azuread.go new file mode 100644 index 00000000000..94b6144da1e --- /dev/null +++ b/storage/remote/azuread/azuread.go @@ -0,0 +1,247 @@ +// Copyright 2023 The Prometheus Authors +// 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 azuread + +import ( + "context" + "errors" + "fmt" + "net/http" + "strings" + "sync" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/google/uuid" +) + +const ( + // Clouds. + AzureChina = "AzureChina" + AzureGovernment = "AzureGovernment" + AzurePublic = "AzurePublic" + + // Audiences. + IngestionChinaAudience = "https://monitor.azure.cn//.default" + IngestionGovernmentAudience = "https://monitor.azure.us//.default" + IngestionPublicAudience = "https://monitor.azure.com//.default" +) + +// ManagedIdentityConfig is used to store managed identity config values +type ManagedIdentityConfig struct { + // ClientID is the clientId of the managed identity that is being used to authenticate. + ClientID string `yaml:"client_id,omitempty"` +} + +// AzureADConfig is used to store the config values. +type AzureADConfig struct { // nolint:revive + // ManagedIdentity is the managed identity that is being used to authenticate. + ManagedIdentity *ManagedIdentityConfig `yaml:"managed_identity,omitempty"` + + // Cloud is the Azure cloud in which the service is running. Example: AzurePublic/AzureGovernment/AzureChina. + Cloud string `yaml:"cloud,omitempty"` +} + +// azureADRoundTripper is used to store the roundtripper and the tokenprovider. +type azureADRoundTripper struct { + next http.RoundTripper + tokenProvider *tokenProvider +} + +// tokenProvider is used to store and retrieve Azure AD accessToken. +type tokenProvider struct { + // token is member used to store the current valid accessToken. + token string + // mu guards access to token. + mu sync.Mutex + // refreshTime is used to store the refresh time of the current valid accessToken. + refreshTime time.Time + // credentialClient is the Azure AD credential client that is being used to retrieve accessToken. + credentialClient azcore.TokenCredential + options *policy.TokenRequestOptions +} + +// Validate validates config values provided. +func (c *AzureADConfig) Validate() error { + if c.Cloud == "" { + c.Cloud = AzurePublic + } + + if c.Cloud != AzureChina && c.Cloud != AzureGovernment && c.Cloud != AzurePublic { + return fmt.Errorf("must provide a cloud in the Azure AD config") + } + + if c.ManagedIdentity == nil { + return fmt.Errorf("must provide an Azure Managed Identity in the Azure AD config") + } + + if c.ManagedIdentity.ClientID == "" { + return fmt.Errorf("must provide an Azure Managed Identity client_id in the Azure AD config") + } + + _, err := uuid.Parse(c.ManagedIdentity.ClientID) + if err != nil { + return fmt.Errorf("the provided Azure Managed Identity client_id provided is invalid") + } + return nil +} + +// UnmarshalYAML unmarshal the Azure AD config yaml. +func (c *AzureADConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { + type plain AzureADConfig + *c = AzureADConfig{} + if err := unmarshal((*plain)(c)); err != nil { + return err + } + return c.Validate() +} + +// NewAzureADRoundTripper creates round tripper adding Azure AD authorization to calls. +func NewAzureADRoundTripper(cfg *AzureADConfig, next http.RoundTripper) (http.RoundTripper, error) { + if next == nil { + next = http.DefaultTransport + } + + cred, err := newTokenCredential(cfg) + if err != nil { + return nil, err + } + + tokenProvider, err := newTokenProvider(cfg, cred) + if err != nil { + return nil, err + } + + rt := &azureADRoundTripper{ + next: next, + tokenProvider: tokenProvider, + } + return rt, nil +} + +// RoundTrip sets Authorization header for requests. +func (rt *azureADRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { + accessToken, err := rt.tokenProvider.getAccessToken(req.Context()) + if err != nil { + return nil, err + } + bearerAccessToken := "Bearer " + accessToken + req.Header.Set("Authorization", bearerAccessToken) + + return rt.next.RoundTrip(req) +} + +// newTokenCredential returns a TokenCredential of different kinds like Azure Managed Identity and Azure AD application. +func newTokenCredential(cfg *AzureADConfig) (azcore.TokenCredential, error) { + cred, err := newManagedIdentityTokenCredential(cfg.ManagedIdentity.ClientID) + if err != nil { + return nil, err + } + + return cred, nil +} + +// newManagedIdentityTokenCredential returns new Managed Identity token credential. +func newManagedIdentityTokenCredential(managedIdentityClientID string) (azcore.TokenCredential, error) { + clientID := azidentity.ClientID(managedIdentityClientID) + opts := &azidentity.ManagedIdentityCredentialOptions{ID: clientID} + return azidentity.NewManagedIdentityCredential(opts) +} + +// newTokenProvider helps to fetch accessToken for different types of credential. This also takes care of +// refreshing the accessToken before expiry. This accessToken is attached to the Authorization header while making requests. +func newTokenProvider(cfg *AzureADConfig, cred azcore.TokenCredential) (*tokenProvider, error) { + audience, err := getAudience(cfg.Cloud) + if err != nil { + return nil, err + } + + tokenProvider := &tokenProvider{ + credentialClient: cred, + options: &policy.TokenRequestOptions{Scopes: []string{audience}}, + } + + return tokenProvider, nil +} + +// getAccessToken returns the current valid accessToken. +func (tokenProvider *tokenProvider) getAccessToken(ctx context.Context) (string, error) { + tokenProvider.mu.Lock() + defer tokenProvider.mu.Unlock() + if tokenProvider.valid() { + return tokenProvider.token, nil + } + err := tokenProvider.getToken(ctx) + if err != nil { + return "", errors.New("Failed to get access token: " + err.Error()) + } + return tokenProvider.token, nil +} + +// valid checks if the token in the token provider is valid and not expired. +func (tokenProvider *tokenProvider) valid() bool { + if len(tokenProvider.token) == 0 { + return false + } + if tokenProvider.refreshTime.After(time.Now().UTC()) { + return true + } + return false +} + +// getToken retrieves a new accessToken and stores the newly retrieved token in the tokenProvider. +func (tokenProvider *tokenProvider) getToken(ctx context.Context) error { + accessToken, err := tokenProvider.credentialClient.GetToken(ctx, *tokenProvider.options) + if err != nil { + return err + } + if len(accessToken.Token) == 0 { + return errors.New("access token is empty") + } + + tokenProvider.token = accessToken.Token + err = tokenProvider.updateRefreshTime(accessToken) + if err != nil { + return err + } + return nil +} + +// updateRefreshTime handles logic to set refreshTime. The refreshTime is set at half the duration of the actual token expiry. +func (tokenProvider *tokenProvider) updateRefreshTime(accessToken azcore.AccessToken) error { + tokenExpiryTimestamp := accessToken.ExpiresOn.UTC() + deltaExpirytime := time.Now().Add(time.Until(tokenExpiryTimestamp) / 2) + if deltaExpirytime.After(time.Now().UTC()) { + tokenProvider.refreshTime = deltaExpirytime + } else { + return errors.New("access token expiry is less than the current time") + } + return nil +} + +// getAudience returns audiences for different clouds. +func getAudience(cloud string) (string, error) { + switch strings.ToLower(cloud) { + case strings.ToLower(AzureChina): + return IngestionChinaAudience, nil + case strings.ToLower(AzureGovernment): + return IngestionGovernmentAudience, nil + case strings.ToLower(AzurePublic): + return IngestionPublicAudience, nil + default: + return "", errors.New("Cloud is not specified or is incorrect: " + cloud) + } +} diff --git a/storage/remote/azuread/azuread_test.go b/storage/remote/azuread/azuread_test.go new file mode 100644 index 00000000000..ebbd98958cb --- /dev/null +++ b/storage/remote/azuread/azuread_test.go @@ -0,0 +1,252 @@ +// Copyright 2023 The Prometheus Authors +// 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 azuread + +import ( + "context" + "net/http" + "os" + "strings" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/google/uuid" + "github.com/prometheus/client_golang/prometheus/promhttp" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/suite" + "gopkg.in/yaml.v2" +) + +const ( + dummyAudience = "dummyAudience" + dummyClientID = "00000000-0000-0000-0000-000000000000" + testTokenString = "testTokenString" +) + +var testTokenExpiry = time.Now().Add(10 * time.Second) + +type AzureAdTestSuite struct { + suite.Suite + mockCredential *mockCredential +} + +type TokenProviderTestSuite struct { + suite.Suite + mockCredential *mockCredential +} + +// mockCredential mocks azidentity TokenCredential interface. +type mockCredential struct { + mock.Mock +} + +func (ad *AzureAdTestSuite) BeforeTest(_, _ string) { + ad.mockCredential = new(mockCredential) +} + +func TestAzureAd(t *testing.T) { + suite.Run(t, new(AzureAdTestSuite)) +} + +func (ad *AzureAdTestSuite) TestAzureAdRoundTripper() { + var gotReq *http.Request + + testToken := &azcore.AccessToken{ + Token: testTokenString, + ExpiresOn: testTokenExpiry, + } + + managedIdentityConfig := &ManagedIdentityConfig{ + ClientID: dummyClientID, + } + + azureAdConfig := &AzureADConfig{ + Cloud: "AzurePublic", + ManagedIdentity: managedIdentityConfig, + } + + ad.mockCredential.On("GetToken", mock.Anything, mock.Anything).Return(*testToken, nil) + + tokenProvider, err := newTokenProvider(azureAdConfig, ad.mockCredential) + ad.Assert().NoError(err) + + rt := &azureADRoundTripper{ + next: promhttp.RoundTripperFunc(func(req *http.Request) (*http.Response, error) { + gotReq = req + return &http.Response{StatusCode: http.StatusOK}, nil + }), + tokenProvider: tokenProvider, + } + + cli := &http.Client{Transport: rt} + + req, err := http.NewRequest(http.MethodPost, "https://example.com", strings.NewReader("Hello, world!")) + ad.Assert().NoError(err) + + _, err = cli.Do(req) + ad.Assert().NoError(err) + ad.Assert().NotNil(gotReq) + + origReq := gotReq + ad.Assert().NotEmpty(origReq.Header.Get("Authorization")) + ad.Assert().Equal("Bearer "+testTokenString, origReq.Header.Get("Authorization")) +} + +func loadAzureAdConfig(filename string) (*AzureADConfig, error) { + content, err := os.ReadFile(filename) + if err != nil { + return nil, err + } + cfg := AzureADConfig{} + if err = yaml.UnmarshalStrict(content, &cfg); err != nil { + return nil, err + } + return &cfg, nil +} + +func testGoodConfig(t *testing.T, filename string) { + _, err := loadAzureAdConfig(filename) + if err != nil { + t.Fatalf("Unexpected error parsing %s: %s", filename, err) + } +} + +func TestGoodAzureAdConfig(t *testing.T) { + filename := "testdata/azuread_good.yaml" + testGoodConfig(t, filename) +} + +func TestGoodCloudMissingAzureAdConfig(t *testing.T) { + filename := "testdata/azuread_good_cloudmissing.yaml" + testGoodConfig(t, filename) +} + +func TestBadClientIdMissingAzureAdConfig(t *testing.T) { + filename := "testdata/azuread_bad_clientidmissing.yaml" + _, err := loadAzureAdConfig(filename) + if err == nil { + t.Fatalf("Did not receive expected error unmarshaling bad azuread config") + } + if !strings.Contains(err.Error(), "must provide an Azure Managed Identity in the Azure AD config") { + t.Errorf("Received unexpected error from unmarshal of %s: %s", filename, err.Error()) + } +} + +func TestBadInvalidClientIdAzureAdConfig(t *testing.T) { + filename := "testdata/azuread_bad_invalidclientid.yaml" + _, err := loadAzureAdConfig(filename) + if err == nil { + t.Fatalf("Did not receive expected error unmarshaling bad azuread config") + } + if !strings.Contains(err.Error(), "the provided Azure Managed Identity client_id provided is invalid") { + t.Errorf("Received unexpected error from unmarshal of %s: %s", filename, err.Error()) + } +} + +func (m *mockCredential) GetToken(ctx context.Context, options policy.TokenRequestOptions) (azcore.AccessToken, error) { + args := m.MethodCalled("GetToken", ctx, options) + if args.Get(0) == nil { + return azcore.AccessToken{}, args.Error(1) + } + + return args.Get(0).(azcore.AccessToken), nil +} + +func (s *TokenProviderTestSuite) BeforeTest(_, _ string) { + s.mockCredential = new(mockCredential) +} + +func TestTokenProvider(t *testing.T) { + suite.Run(t, new(TokenProviderTestSuite)) +} + +func (s *TokenProviderTestSuite) TestNewTokenProvider_NilAudience_Fail() { + managedIdentityConfig := &ManagedIdentityConfig{ + ClientID: dummyClientID, + } + + azureAdConfig := &AzureADConfig{ + Cloud: "PublicAzure", + ManagedIdentity: managedIdentityConfig, + } + + actualTokenProvider, actualErr := newTokenProvider(azureAdConfig, s.mockCredential) + + s.Assert().Nil(actualTokenProvider) + s.Assert().NotNil(actualErr) + s.Assert().Equal("Cloud is not specified or is incorrect: "+azureAdConfig.Cloud, actualErr.Error()) +} + +func (s *TokenProviderTestSuite) TestNewTokenProvider_Success() { + managedIdentityConfig := &ManagedIdentityConfig{ + ClientID: dummyClientID, + } + + azureAdConfig := &AzureADConfig{ + Cloud: "AzurePublic", + ManagedIdentity: managedIdentityConfig, + } + s.mockCredential.On("GetToken", mock.Anything, mock.Anything).Return(getToken(), nil) + + actualTokenProvider, actualErr := newTokenProvider(azureAdConfig, s.mockCredential) + + s.Assert().NotNil(actualTokenProvider) + s.Assert().Nil(actualErr) + s.Assert().NotNil(actualTokenProvider.getAccessToken(context.Background())) +} + +func (s *TokenProviderTestSuite) TestPeriodicTokenRefresh_Success() { + // setup + managedIdentityConfig := &ManagedIdentityConfig{ + ClientID: dummyClientID, + } + + azureAdConfig := &AzureADConfig{ + Cloud: "AzurePublic", + ManagedIdentity: managedIdentityConfig, + } + testToken := &azcore.AccessToken{ + Token: testTokenString, + ExpiresOn: testTokenExpiry, + } + + s.mockCredential.On("GetToken", mock.Anything, mock.Anything).Return(*testToken, nil).Once(). + On("GetToken", mock.Anything, mock.Anything).Return(getToken(), nil) + + actualTokenProvider, actualErr := newTokenProvider(azureAdConfig, s.mockCredential) + + s.Assert().NotNil(actualTokenProvider) + s.Assert().Nil(actualErr) + s.Assert().NotNil(actualTokenProvider.getAccessToken(context.Background())) + + // Token set to refresh at half of the expiry time. The test tokens are set to expiry in 10s. + // Hence, the 6 seconds wait to check if the token is refreshed. + time.Sleep(6 * time.Second) + + s.Assert().NotNil(actualTokenProvider.getAccessToken(context.Background())) + + s.mockCredential.AssertNumberOfCalls(s.T(), "GetToken", 2) + accessToken, err := actualTokenProvider.getAccessToken(context.Background()) + s.Assert().Nil(err) + s.Assert().NotEqual(accessToken, testTokenString) +} + +func getToken() azcore.AccessToken { + return azcore.AccessToken{ + Token: uuid.New().String(), + ExpiresOn: time.Now().Add(10 * time.Second), + } +} diff --git a/storage/remote/azuread/testdata/azuread_bad_clientidmissing.yaml b/storage/remote/azuread/testdata/azuread_bad_clientidmissing.yaml new file mode 100644 index 00000000000..68b119cd42e --- /dev/null +++ b/storage/remote/azuread/testdata/azuread_bad_clientidmissing.yaml @@ -0,0 +1 @@ +cloud: AzurePublic diff --git a/storage/remote/azuread/testdata/azuread_bad_invalidclientid.yaml b/storage/remote/azuread/testdata/azuread_bad_invalidclientid.yaml new file mode 100644 index 00000000000..1f72fbb71ff --- /dev/null +++ b/storage/remote/azuread/testdata/azuread_bad_invalidclientid.yaml @@ -0,0 +1,3 @@ +cloud: AzurePublic +managed_identity: + client_id: foo-foobar-bar-foo-00000000 diff --git a/storage/remote/azuread/testdata/azuread_good.yaml b/storage/remote/azuread/testdata/azuread_good.yaml new file mode 100644 index 00000000000..de39f0a060b --- /dev/null +++ b/storage/remote/azuread/testdata/azuread_good.yaml @@ -0,0 +1,3 @@ +cloud: AzurePublic +managed_identity: + client_id: 00000000-0000-0000-0000-000000000000 diff --git a/storage/remote/azuread/testdata/azuread_good_cloudmissing.yaml b/storage/remote/azuread/testdata/azuread_good_cloudmissing.yaml new file mode 100644 index 00000000000..bef63187434 --- /dev/null +++ b/storage/remote/azuread/testdata/azuread_good_cloudmissing.yaml @@ -0,0 +1,2 @@ +managed_identity: + client_id: 00000000-0000-0000-0000-000000000000 diff --git a/storage/remote/client.go b/storage/remote/client.go index 1625c9918de..33774203c5e 100644 --- a/storage/remote/client.go +++ b/storage/remote/client.go @@ -36,6 +36,7 @@ import ( "go.opentelemetry.io/otel/trace" "github.com/prometheus/prometheus/prompb" + "github.com/prometheus/prometheus/storage/remote/azuread" ) const maxErrMsgLen = 1024 @@ -97,6 +98,7 @@ type ClientConfig struct { Timeout model.Duration HTTPClientConfig config_util.HTTPClientConfig SigV4Config *sigv4.SigV4Config + AzureADConfig *azuread.AzureADConfig Headers map[string]string RetryOnRateLimit bool } @@ -146,6 +148,13 @@ func NewWriteClient(name string, conf *ClientConfig) (WriteClient, error) { } } + if conf.AzureADConfig != nil { + t, err = azuread.NewAzureADRoundTripper(conf.AzureADConfig, httpClient.Transport) + if err != nil { + return nil, err + } + } + if len(conf.Headers) > 0 { t = newInjectHeadersRoundTripper(conf.Headers, t) } diff --git a/storage/remote/storage.go b/storage/remote/storage.go index 88892e62e3c..d01f96b3bae 100644 --- a/storage/remote/storage.go +++ b/storage/remote/storage.go @@ -76,6 +76,13 @@ func NewStorage(l log.Logger, reg prometheus.Registerer, stCallback startTimeCal return s } +func (s *Storage) Notify() { + for _, q := range s.rws.queues { + // These should all be non blocking + q.watcher.Notify() + } +} + // ApplyConfig updates the state as the new config requires. func (s *Storage) ApplyConfig(conf *config.Config) error { s.mtx.Lock() diff --git a/storage/remote/write.go b/storage/remote/write.go index 6a33c0adf91..4b0a2490148 100644 --- a/storage/remote/write.go +++ b/storage/remote/write.go @@ -158,6 +158,7 @@ func (rws *WriteStorage) ApplyConfig(conf *config.Config) error { Timeout: rwConf.RemoteTimeout, HTTPClientConfig: rwConf.HTTPClientConfig, SigV4Config: rwConf.SigV4Config, + AzureADConfig: rwConf.AzureADConfig, Headers: rwConf.Headers, RetryOnRateLimit: rwConf.QueueConfig.RetryOnRateLimit, }) diff --git a/storage/series.go b/storage/series.go index f609df3f021..b73f1e35ce9 100644 --- a/storage/series.go +++ b/storage/series.go @@ -281,7 +281,7 @@ func NewSeriesToChunkEncoder(series Series) ChunkSeries { func (s *seriesToChunkEncoder) Iterator(it chunks.Iterator) chunks.Iterator { var ( chk chunkenc.Chunk - app chunkenc.Appender + app *RecodingAppender err error ) mint := int64(math.MaxInt64) @@ -297,23 +297,20 @@ func (s *seriesToChunkEncoder) Iterator(it chunks.Iterator) chunks.Iterator { seriesIter := s.Series.Iterator(nil) lastType := chunkenc.ValNone for typ := seriesIter.Next(); typ != chunkenc.ValNone; typ = seriesIter.Next() { + chunkCreated := false if typ != lastType || i >= seriesToChunkEncoderSplit { // Create a new chunk if the sample type changed or too many samples in the current one. - if chk != nil { - chks = append(chks, chunks.Meta{ - MinTime: mint, - MaxTime: maxt, - Chunk: chk, - }) - } + chks = appendChunk(chks, mint, maxt, chk) + chunkCreated = true chk, err = chunkenc.NewEmptyChunk(typ.ChunkEncoding()) if err != nil { return errChunksIterator{err: err} } - app, err = chk.Appender() + chkAppender, err := chk.Appender() if err != nil { return errChunksIterator{err: err} } + app = NewRecodingAppender(&chk, chkAppender) mint = int64(math.MaxInt64) // maxt is immediately overwritten below which is why setting it here won't make a difference. i = 0 @@ -332,10 +329,53 @@ func (s *seriesToChunkEncoder) Iterator(it chunks.Iterator) chunks.Iterator { app.Append(t, v) case chunkenc.ValHistogram: t, h = seriesIter.AtHistogram() - app.AppendHistogram(t, h) + if ok, counterReset := app.AppendHistogram(t, h); !ok { + chks = appendChunk(chks, mint, maxt, chk) + histChunk := chunkenc.NewHistogramChunk() + chunkCreated = true + if counterReset { + histChunk.SetCounterResetHeader(chunkenc.CounterReset) + } + chk = histChunk + + chkAppender, err := chk.Appender() + if err != nil { + return errChunksIterator{err: err} + } + mint = int64(math.MaxInt64) + i = 0 + app = NewRecodingAppender(&chk, chkAppender) + if ok, _ := app.AppendHistogram(t, h); !ok { + panic("unexpected error while appending histogram") + } + } + if chunkCreated && h.CounterResetHint == histogram.GaugeType { + chk.(*chunkenc.HistogramChunk).SetCounterResetHeader(chunkenc.GaugeType) + } case chunkenc.ValFloatHistogram: t, fh = seriesIter.AtFloatHistogram() - app.AppendFloatHistogram(t, fh) + if ok, counterReset := app.AppendFloatHistogram(t, fh); !ok { + chks = appendChunk(chks, mint, maxt, chk) + floatHistChunk := chunkenc.NewFloatHistogramChunk() + chunkCreated = true + if counterReset { + floatHistChunk.SetCounterResetHeader(chunkenc.CounterReset) + } + chk = floatHistChunk + chkAppender, err := chk.Appender() + if err != nil { + return errChunksIterator{err: err} + } + mint = int64(math.MaxInt64) + i = 0 + app = NewRecodingAppender(&chk, chkAppender) + if ok, _ := app.AppendFloatHistogram(t, fh); !ok { + panic("unexpected error while float appending histogram") + } + } + if chunkCreated && fh.CounterResetHint == histogram.GaugeType { + chk.(*chunkenc.FloatHistogramChunk).SetCounterResetHeader(chunkenc.GaugeType) + } default: return errChunksIterator{err: fmt.Errorf("unknown sample type %s", typ.String())} } @@ -350,6 +390,16 @@ func (s *seriesToChunkEncoder) Iterator(it chunks.Iterator) chunks.Iterator { return errChunksIterator{err: err} } + chks = appendChunk(chks, mint, maxt, chk) + + if existing { + lcsi.Reset(chks...) + return lcsi + } + return NewListChunkSeriesIterator(chks...) +} + +func appendChunk(chks []chunks.Meta, mint, maxt int64, chk chunkenc.Chunk) []chunks.Meta { if chk != nil { chks = append(chks, chunks.Meta{ MinTime: mint, @@ -357,12 +407,7 @@ func (s *seriesToChunkEncoder) Iterator(it chunks.Iterator) chunks.Iterator { Chunk: chk, }) } - - if existing { - lcsi.Reset(chks...) - return lcsi - } - return NewListChunkSeriesIterator(chks...) + return chks } type errChunksIterator struct { @@ -420,3 +465,126 @@ func ExpandChunks(iter chunks.Iterator) ([]chunks.Meta, error) { } return result, iter.Err() } + +// RecodingAppender is a tsdb.Appender that recodes histogram samples if needed during appends. +// It takes an existing appender and a chunk to which samples are appended. +type RecodingAppender struct { + chk *chunkenc.Chunk + app chunkenc.Appender +} + +func NewRecodingAppender(chk *chunkenc.Chunk, app chunkenc.Appender) *RecodingAppender { + return &RecodingAppender{ + chk: chk, + app: app, + } +} + +// Append appends a float sample to the appender. +func (a *RecodingAppender) Append(t int64, v float64) { + a.app.Append(t, v) +} + +// AppendHistogram appends a histogram sample to the underlying chunk. +// The method returns false if the sample cannot be appended and a boolean value set to true +// when it is not appendable because of a counter reset. +// If counterReset is true, okToAppend is always false. +func (a *RecodingAppender) AppendHistogram(t int64, h *histogram.Histogram) (okToAppend, counterReset bool) { + app, ok := a.app.(*chunkenc.HistogramAppender) + if !ok { + return false, false + } + + if app.NumSamples() == 0 { + a.app.AppendHistogram(t, h) + return true, false + } + + var ( + pForwardInserts, nForwardInserts []chunkenc.Insert + pBackwardInserts, nBackwardInserts []chunkenc.Insert + pMergedSpans, nMergedSpans []histogram.Span + ) + switch h.CounterResetHint { + case histogram.GaugeType: + pForwardInserts, nForwardInserts, + pBackwardInserts, nBackwardInserts, + pMergedSpans, nMergedSpans, + okToAppend = app.AppendableGauge(h) + default: + pForwardInserts, nForwardInserts, okToAppend, counterReset = app.Appendable(h) + } + if !okToAppend || counterReset { + return false, counterReset + } + + if len(pBackwardInserts)+len(nBackwardInserts) > 0 { + h.PositiveSpans = pMergedSpans + h.NegativeSpans = nMergedSpans + app.RecodeHistogram(h, pBackwardInserts, nBackwardInserts) + } + if len(pForwardInserts) > 0 || len(nForwardInserts) > 0 { + chk, app := app.Recode( + pForwardInserts, nForwardInserts, + h.PositiveSpans, h.NegativeSpans, + ) + *a.chk = chk + a.app = app + } + + a.app.AppendHistogram(t, h) + return true, counterReset +} + +// AppendFloatHistogram appends a float histogram sample to the underlying chunk. +// The method returns false if the sample cannot be appended and a boolean value set to true +// when it is not appendable because of a counter reset. +// If counterReset is true, okToAppend is always false. +func (a *RecodingAppender) AppendFloatHistogram(t int64, fh *histogram.FloatHistogram) (okToAppend, counterReset bool) { + app, ok := a.app.(*chunkenc.FloatHistogramAppender) + if !ok { + return false, false + } + + if app.NumSamples() == 0 { + a.app.AppendFloatHistogram(t, fh) + return true, false + } + + var ( + pForwardInserts, nForwardInserts []chunkenc.Insert + pBackwardInserts, nBackwardInserts []chunkenc.Insert + pMergedSpans, nMergedSpans []histogram.Span + ) + switch fh.CounterResetHint { + case histogram.GaugeType: + pForwardInserts, nForwardInserts, + pBackwardInserts, nBackwardInserts, + pMergedSpans, nMergedSpans, + okToAppend = app.AppendableGauge(fh) + default: + pForwardInserts, nForwardInserts, okToAppend, counterReset = app.Appendable(fh) + } + + if !okToAppend || counterReset { + return false, counterReset + } + + if len(pBackwardInserts)+len(nBackwardInserts) > 0 { + fh.PositiveSpans = pMergedSpans + fh.NegativeSpans = nMergedSpans + app.RecodeHistogramm(fh, pBackwardInserts, nBackwardInserts) + } + + if len(pForwardInserts) > 0 || len(nForwardInserts) > 0 { + chunk, app := app.Recode( + pForwardInserts, nForwardInserts, + fh.PositiveSpans, fh.NegativeSpans, + ) + *a.chk = chunk + a.app = app + } + + a.app.AppendFloatHistogram(t, fh) + return true, counterReset +} diff --git a/storage/series_test.go b/storage/series_test.go index 210a68e2837..5c74fae096c 100644 --- a/storage/series_test.go +++ b/storage/series_test.go @@ -14,12 +14,17 @@ package storage import ( + "fmt" + "math" "testing" "github.com/stretchr/testify/require" + "github.com/prometheus/prometheus/model/histogram" "github.com/prometheus/prometheus/model/labels" + "github.com/prometheus/prometheus/model/value" "github.com/prometheus/prometheus/tsdb/chunkenc" + "github.com/prometheus/prometheus/tsdb/chunks" "github.com/prometheus/prometheus/tsdb/tsdbutil" ) @@ -119,3 +124,381 @@ func TestChunkSeriesSetToSeriesSet(t *testing.T) { } } } + +type histogramTest struct { + samples []tsdbutil.Sample + expectedCounterResetHeaders []chunkenc.CounterResetHeader +} + +func TestHistogramSeriesToChunks(t *testing.T) { + h1 := &histogram.Histogram{ + Count: 7, + ZeroCount: 2, + ZeroThreshold: 0.001, + Sum: 100, + Schema: 0, + PositiveSpans: []histogram.Span{ + {Offset: 0, Length: 2}, + }, + PositiveBuckets: []int64{2, 1}, // Abs: 2, 3 + } + // Appendable to h1. + h2 := &histogram.Histogram{ + Count: 12, + ZeroCount: 2, + ZeroThreshold: 0.001, + Sum: 100, + Schema: 0, + PositiveSpans: []histogram.Span{ + {Offset: 0, Length: 2}, + {Offset: 1, Length: 2}, + }, + PositiveBuckets: []int64{2, 1, -2, 3}, // Abs: 2, 3, 1, 4 + } + // Implicit counter reset by reduction in buckets, not appendable. + h2down := &histogram.Histogram{ + Count: 10, + ZeroCount: 2, + ZeroThreshold: 0.001, + Sum: 100, + Schema: 0, + PositiveSpans: []histogram.Span{ + {Offset: 0, Length: 2}, + {Offset: 1, Length: 2}, + }, + PositiveBuckets: []int64{1, 1, -1, 3}, // Abs: 1, 2, 1, 4 + } + + fh1 := &histogram.FloatHistogram{ + Count: 6, + ZeroCount: 2, + ZeroThreshold: 0.001, + Sum: 100, + Schema: 0, + PositiveSpans: []histogram.Span{ + {Offset: 0, Length: 2}, + }, + PositiveBuckets: []float64{3, 1}, + } + // Appendable to fh1. + fh2 := &histogram.FloatHistogram{ + Count: 17, + ZeroCount: 2, + ZeroThreshold: 0.001, + Sum: 100, + Schema: 0, + PositiveSpans: []histogram.Span{ + {Offset: 0, Length: 2}, + {Offset: 1, Length: 2}, + }, + PositiveBuckets: []float64{4, 2, 7, 2}, + } + // Implicit counter reset by reduction in buckets, not appendable. + fh2down := &histogram.FloatHistogram{ + Count: 15, + ZeroCount: 2, + ZeroThreshold: 0.001, + Sum: 100, + Schema: 0, + PositiveSpans: []histogram.Span{ + {Offset: 0, Length: 2}, + {Offset: 1, Length: 2}, + }, + PositiveBuckets: []float64{2, 2, 7, 2}, + } + + // Gauge histogram. + gh1 := &histogram.Histogram{ + CounterResetHint: histogram.GaugeType, + Count: 7, + ZeroCount: 2, + ZeroThreshold: 0.001, + Sum: 100, + Schema: 0, + PositiveSpans: []histogram.Span{ + {Offset: 0, Length: 2}, + }, + PositiveBuckets: []int64{2, 1}, // Abs: 2, 3 + } + gh2 := &histogram.Histogram{ + CounterResetHint: histogram.GaugeType, + Count: 12, + ZeroCount: 2, + ZeroThreshold: 0.001, + Sum: 100, + Schema: 0, + PositiveSpans: []histogram.Span{ + {Offset: 0, Length: 2}, + {Offset: 1, Length: 2}, + }, + PositiveBuckets: []int64{2, 1, -2, 3}, // Abs: 2, 3, 1, 4 + } + + // Float gauge histogram. + gfh1 := &histogram.FloatHistogram{ + CounterResetHint: histogram.GaugeType, + Count: 6, + ZeroCount: 2, + ZeroThreshold: 0.001, + Sum: 100, + Schema: 0, + PositiveSpans: []histogram.Span{ + {Offset: 0, Length: 2}, + }, + PositiveBuckets: []float64{3, 1}, + } + gfh2 := &histogram.FloatHistogram{ + CounterResetHint: histogram.GaugeType, + Count: 17, + ZeroCount: 2, + ZeroThreshold: 0.001, + Sum: 100, + Schema: 0, + PositiveSpans: []histogram.Span{ + {Offset: 0, Length: 2}, + {Offset: 1, Length: 2}, + }, + PositiveBuckets: []float64{4, 2, 7, 2}, + } + + staleHistogram := &histogram.Histogram{ + Sum: math.Float64frombits(value.StaleNaN), + } + staleFloatHistogram := &histogram.FloatHistogram{ + Sum: math.Float64frombits(value.StaleNaN), + } + + tests := map[string]histogramTest{ + "single histogram to single chunk": { + samples: []tsdbutil.Sample{ + hSample{t: 1, h: h1}, + }, + expectedCounterResetHeaders: []chunkenc.CounterResetHeader{chunkenc.UnknownCounterReset}, + }, + "two histograms encoded to a single chunk": { + samples: []tsdbutil.Sample{ + hSample{t: 1, h: h1}, + hSample{t: 2, h: h2}, + }, + expectedCounterResetHeaders: []chunkenc.CounterResetHeader{chunkenc.UnknownCounterReset}, + }, + "two histograms encoded to two chunks": { + samples: []tsdbutil.Sample{ + hSample{t: 1, h: h2}, + hSample{t: 2, h: h1}, + }, + expectedCounterResetHeaders: []chunkenc.CounterResetHeader{chunkenc.UnknownCounterReset, chunkenc.CounterReset}, + }, + "histogram and stale sample encoded to two chunks": { + samples: []tsdbutil.Sample{ + hSample{t: 1, h: staleHistogram}, + hSample{t: 2, h: h1}, + }, + expectedCounterResetHeaders: []chunkenc.CounterResetHeader{chunkenc.UnknownCounterReset, chunkenc.UnknownCounterReset}, + }, + "histogram and reduction in bucket encoded to two chunks": { + samples: []tsdbutil.Sample{ + hSample{t: 1, h: h1}, + hSample{t: 2, h: h2down}, + }, + expectedCounterResetHeaders: []chunkenc.CounterResetHeader{chunkenc.UnknownCounterReset, chunkenc.CounterReset}, + }, + // Float histograms. + "single float histogram to single chunk": { + samples: []tsdbutil.Sample{ + fhSample{t: 1, fh: fh1}, + }, + expectedCounterResetHeaders: []chunkenc.CounterResetHeader{chunkenc.UnknownCounterReset}, + }, + "two float histograms encoded to a single chunk": { + samples: []tsdbutil.Sample{ + fhSample{t: 1, fh: fh1}, + fhSample{t: 2, fh: fh2}, + }, + expectedCounterResetHeaders: []chunkenc.CounterResetHeader{chunkenc.UnknownCounterReset}, + }, + "two float histograms encoded to two chunks": { + samples: []tsdbutil.Sample{ + fhSample{t: 1, fh: fh2}, + fhSample{t: 2, fh: fh1}, + }, + expectedCounterResetHeaders: []chunkenc.CounterResetHeader{chunkenc.UnknownCounterReset, chunkenc.CounterReset}, + }, + "float histogram and stale sample encoded to two chunks": { + samples: []tsdbutil.Sample{ + fhSample{t: 1, fh: staleFloatHistogram}, + fhSample{t: 2, fh: fh1}, + }, + expectedCounterResetHeaders: []chunkenc.CounterResetHeader{chunkenc.UnknownCounterReset, chunkenc.UnknownCounterReset}, + }, + "float histogram and reduction in bucket encoded to two chunks": { + samples: []tsdbutil.Sample{ + fhSample{t: 1, fh: fh1}, + fhSample{t: 2, fh: fh2down}, + }, + expectedCounterResetHeaders: []chunkenc.CounterResetHeader{chunkenc.UnknownCounterReset, chunkenc.CounterReset}, + }, + // Mixed. + "histogram and float histogram encoded to two chunks": { + samples: []tsdbutil.Sample{ + hSample{t: 1, h: h1}, + fhSample{t: 2, fh: fh2}, + }, + expectedCounterResetHeaders: []chunkenc.CounterResetHeader{chunkenc.UnknownCounterReset, chunkenc.UnknownCounterReset}, + }, + "float histogram and histogram encoded to two chunks": { + samples: []tsdbutil.Sample{ + fhSample{t: 1, fh: fh1}, + hSample{t: 2, h: h2}, + }, + expectedCounterResetHeaders: []chunkenc.CounterResetHeader{chunkenc.UnknownCounterReset, chunkenc.UnknownCounterReset}, + }, + "histogram and stale float histogram encoded to two chunks": { + samples: []tsdbutil.Sample{ + hSample{t: 1, h: h1}, + fhSample{t: 2, fh: staleFloatHistogram}, + }, + expectedCounterResetHeaders: []chunkenc.CounterResetHeader{chunkenc.UnknownCounterReset, chunkenc.UnknownCounterReset}, + }, + "single gauge histogram encoded to one chunk": { + samples: []tsdbutil.Sample{ + hSample{t: 1, h: gh1}, + }, + expectedCounterResetHeaders: []chunkenc.CounterResetHeader{chunkenc.GaugeType}, + }, + "two gauge histograms encoded to one chunk when counter increases": { + samples: []tsdbutil.Sample{ + hSample{t: 1, h: gh1}, + hSample{t: 2, h: gh2}, + }, + expectedCounterResetHeaders: []chunkenc.CounterResetHeader{chunkenc.GaugeType}, + }, + "two gauge histograms encoded to one chunk when counter decreases": { + samples: []tsdbutil.Sample{ + hSample{t: 1, h: gh2}, + hSample{t: 2, h: gh1}, + }, + expectedCounterResetHeaders: []chunkenc.CounterResetHeader{chunkenc.GaugeType}, + }, + "single gauge float histogram encoded to one chunk": { + samples: []tsdbutil.Sample{ + fhSample{t: 1, fh: gfh1}, + }, + expectedCounterResetHeaders: []chunkenc.CounterResetHeader{chunkenc.GaugeType}, + }, + "two float gauge histograms encoded to one chunk when counter increases": { + samples: []tsdbutil.Sample{ + fhSample{t: 1, fh: gfh1}, + fhSample{t: 2, fh: gfh2}, + }, + expectedCounterResetHeaders: []chunkenc.CounterResetHeader{chunkenc.GaugeType}, + }, + "two float gauge histograms encoded to one chunk when counter decreases": { + samples: []tsdbutil.Sample{ + fhSample{t: 1, fh: gfh2}, + fhSample{t: 2, fh: gfh1}, + }, + expectedCounterResetHeaders: []chunkenc.CounterResetHeader{chunkenc.GaugeType}, + }, + } + + for testName, test := range tests { + t.Run(testName, func(t *testing.T) { + testHistogramsSeriesToChunks(t, test) + }) + } +} + +func testHistogramsSeriesToChunks(t *testing.T, test histogramTest) { + lbs := labels.FromStrings("__name__", "up", "instance", "localhost:8080") + copiedSamples := []tsdbutil.Sample{} + for _, s := range test.samples { + switch cs := s.(type) { + case hSample: + copiedSamples = append(copiedSamples, hSample{t: cs.t, h: cs.h.Copy()}) + case fhSample: + copiedSamples = append(copiedSamples, fhSample{t: cs.t, fh: cs.fh.Copy()}) + default: + t.Error("internal error, unexpected type") + } + } + series := NewListSeries(lbs, copiedSamples) + encoder := NewSeriesToChunkEncoder(series) + require.EqualValues(t, lbs, encoder.Labels()) + + chks, err := ExpandChunks(encoder.Iterator(nil)) + require.NoError(t, err) + require.Equal(t, len(test.expectedCounterResetHeaders), len(chks)) + + // Decode all encoded samples and assert they are equal to the original ones. + encodedSamples := expandHistogramSamples(chks) + require.Equal(t, len(test.samples), len(encodedSamples)) + + for i, s := range test.samples { + switch expectedSample := s.(type) { + case hSample: + encodedSample, ok := encodedSamples[i].(hSample) + require.True(t, ok, "expect histogram", fmt.Sprintf("at idx %d", i)) + // Ignore counter reset if not gauge here, will check on chunk level. + if expectedSample.h.CounterResetHint != histogram.GaugeType { + encodedSample.h.CounterResetHint = histogram.UnknownCounterReset + } + if value.IsStaleNaN(expectedSample.h.Sum) { + require.True(t, value.IsStaleNaN(encodedSample.h.Sum), fmt.Sprintf("at idx %d", i)) + continue + } + require.Equal(t, *expectedSample.h, *encodedSample.h.Compact(0), fmt.Sprintf("at idx %d", i)) + case fhSample: + encodedSample, ok := encodedSamples[i].(fhSample) + require.True(t, ok, "expect float histogram", fmt.Sprintf("at idx %d", i)) + // Ignore counter reset if not gauge here, will check on chunk level. + if expectedSample.fh.CounterResetHint != histogram.GaugeType { + encodedSample.fh.CounterResetHint = histogram.UnknownCounterReset + } + if value.IsStaleNaN(expectedSample.fh.Sum) { + require.True(t, value.IsStaleNaN(encodedSample.fh.Sum), fmt.Sprintf("at idx %d", i)) + continue + } + require.Equal(t, *expectedSample.fh, *encodedSample.fh.Compact(0), fmt.Sprintf("at idx %d", i)) + default: + t.Error("internal error, unexpected type") + } + } + + for i, expectedCounterResetHint := range test.expectedCounterResetHeaders { + require.Equal(t, expectedCounterResetHint, getCounterResetHint(chks[i]), fmt.Sprintf("chunk at index %d", i)) + } +} + +func expandHistogramSamples(chunks []chunks.Meta) (result []tsdbutil.Sample) { + if len(chunks) == 0 { + return + } + + for _, chunk := range chunks { + it := chunk.Chunk.Iterator(nil) + for vt := it.Next(); vt != chunkenc.ValNone; vt = it.Next() { + switch vt { + case chunkenc.ValHistogram: + t, h := it.AtHistogram() + result = append(result, hSample{t: t, h: h}) + case chunkenc.ValFloatHistogram: + t, fh := it.AtFloatHistogram() + result = append(result, fhSample{t: t, fh: fh}) + default: + panic("unexpected value type") + } + } + } + return +} + +func getCounterResetHint(chunk chunks.Meta) chunkenc.CounterResetHeader { + switch chk := chunk.Chunk.(type) { + case *chunkenc.HistogramChunk: + return chk.GetCounterResetHeader() + case *chunkenc.FloatHistogramChunk: + return chk.GetCounterResetHeader() + } + return chunkenc.UnknownCounterReset +} diff --git a/tsdb/agent/db.go b/tsdb/agent/db.go index 3343ee18ef7..13cad6bfca7 100644 --- a/tsdb/agent/db.go +++ b/tsdb/agent/db.go @@ -665,7 +665,7 @@ func (db *DB) truncate(mint int64) error { } seg, ok := db.deleted[id] - return ok && seg >= first + return ok && seg > last } db.metrics.checkpointCreationTotal.Inc() @@ -687,7 +687,7 @@ func (db *DB) truncate(mint int64) error { // The checkpoint is written and segments before it are truncated, so we // no longer need to track deleted series that were being kept around. for ref, segment := range db.deleted { - if segment < first { + if segment <= last { delete(db.deleted, ref) } } diff --git a/tsdb/chunkenc/float_histogram.go b/tsdb/chunkenc/float_histogram.go index 0349de9abe5..d49885a1c5b 100644 --- a/tsdb/chunkenc/float_histogram.go +++ b/tsdb/chunkenc/float_histogram.go @@ -358,9 +358,9 @@ func counterResetInAnyFloatBucket(oldBuckets []xorValue, newBuckets []float64, o if oldIdx <= newIdx { // Moving ahead old bucket and span by 1 index. - if oldInsideSpanIdx == oldSpans[oldSpanSliceIdx].Length-1 { + if oldInsideSpanIdx+1 >= oldSpans[oldSpanSliceIdx].Length { // Current span is over. - oldSpanSliceIdx++ + oldSpanSliceIdx = nextNonEmptySpanSliceIdx(oldSpanSliceIdx, oldSpans) oldInsideSpanIdx = 0 if oldSpanSliceIdx >= len(oldSpans) { // All old spans are over. @@ -377,9 +377,9 @@ func counterResetInAnyFloatBucket(oldBuckets []xorValue, newBuckets []float64, o if oldIdx > newIdx { // Moving ahead new bucket and span by 1 index. - if newInsideSpanIdx == newSpans[newSpanSliceIdx].Length-1 { + if newInsideSpanIdx+1 >= newSpans[newSpanSliceIdx].Length { // Current span is over. - newSpanSliceIdx++ + newSpanSliceIdx = nextNonEmptySpanSliceIdx(newSpanSliceIdx, newSpans) newInsideSpanIdx = 0 if newSpanSliceIdx >= len(newSpans) { // All new spans are over. diff --git a/tsdb/chunkenc/float_histogram_test.go b/tsdb/chunkenc/float_histogram_test.go index 90c16d1ea94..c662e5ffa18 100644 --- a/tsdb/chunkenc/float_histogram_test.go +++ b/tsdb/chunkenc/float_histogram_test.go @@ -365,6 +365,64 @@ func TestFloatHistogramChunkAppendable(t *testing.T) { } } +func TestFloatHistogramChunkAppendableWithEmptySpan(t *testing.T) { + h1 := &histogram.FloatHistogram{ + Schema: 0, + Count: 21, + Sum: 1234.5, + ZeroThreshold: 0.001, + ZeroCount: 4, + PositiveSpans: []histogram.Span{ + {Offset: 0, Length: 4}, + {Offset: 0, Length: 0}, + {Offset: 0, Length: 3}, + }, + PositiveBuckets: []float64{1, 2, 1, 1, 1, 1, 1}, + NegativeSpans: []histogram.Span{ + {Offset: 1, Length: 4}, + {Offset: 2, Length: 0}, + {Offset: 2, Length: 3}, + }, + NegativeBuckets: []float64{1, 2, 1, 2, 2, 2, 2}, + } + h2 := &histogram.FloatHistogram{ + Schema: 0, + Count: 37, + Sum: 2345.6, + ZeroThreshold: 0.001, + ZeroCount: 5, + PositiveSpans: []histogram.Span{ + {Offset: 0, Length: 4}, + {Offset: 0, Length: 0}, + {Offset: 0, Length: 3}, + }, + PositiveBuckets: []float64{1, 3, 1, 2, 1, 1, 1}, + NegativeSpans: []histogram.Span{ + {Offset: 1, Length: 4}, + {Offset: 2, Length: 0}, + {Offset: 2, Length: 3}, + }, + NegativeBuckets: []float64{1, 4, 2, 7, 5, 5, 2}, + } + + c := Chunk(NewFloatHistogramChunk()) + + // Create fresh appender and add the first histogram. + app, err := c.Appender() + require.NoError(t, err) + require.Equal(t, 0, c.NumSamples()) + + app.AppendFloatHistogram(1, h1) + require.Equal(t, 1, c.NumSamples()) + hApp, _ := app.(*FloatHistogramAppender) + + pI, nI, okToAppend, counterReset := hApp.Appendable(h2) + require.Empty(t, pI) + require.Empty(t, nI) + require.True(t, okToAppend) + require.False(t, counterReset) +} + func TestFloatHistogramChunkAppendableGauge(t *testing.T) { c := Chunk(NewFloatHistogramChunk()) diff --git a/tsdb/chunkenc/histogram.go b/tsdb/chunkenc/histogram.go index f9a63d18f7c..2350b2af276 100644 --- a/tsdb/chunkenc/histogram.go +++ b/tsdb/chunkenc/histogram.go @@ -386,9 +386,9 @@ func counterResetInAnyBucket(oldBuckets, newBuckets []int64, oldSpans, newSpans if oldIdx <= newIdx { // Moving ahead old bucket and span by 1 index. - if oldInsideSpanIdx == oldSpans[oldSpanSliceIdx].Length-1 { + if oldInsideSpanIdx+1 >= oldSpans[oldSpanSliceIdx].Length { // Current span is over. - oldSpanSliceIdx++ + oldSpanSliceIdx = nextNonEmptySpanSliceIdx(oldSpanSliceIdx, oldSpans) oldInsideSpanIdx = 0 if oldSpanSliceIdx >= len(oldSpans) { // All old spans are over. @@ -405,9 +405,9 @@ func counterResetInAnyBucket(oldBuckets, newBuckets []int64, oldSpans, newSpans if oldIdx > newIdx { // Moving ahead new bucket and span by 1 index. - if newInsideSpanIdx == newSpans[newSpanSliceIdx].Length-1 { + if newInsideSpanIdx+1 >= newSpans[newSpanSliceIdx].Length { // Current span is over. - newSpanSliceIdx++ + newSpanSliceIdx = nextNonEmptySpanSliceIdx(newSpanSliceIdx, newSpans) newInsideSpanIdx = 0 if newSpanSliceIdx >= len(newSpans) { // All new spans are over. diff --git a/tsdb/chunkenc/histogram_meta.go b/tsdb/chunkenc/histogram_meta.go index 027eee11297..7a21bc20bdc 100644 --- a/tsdb/chunkenc/histogram_meta.go +++ b/tsdb/chunkenc/histogram_meta.go @@ -487,3 +487,10 @@ func counterResetHint(crh CounterResetHeader, numRead uint16) histogram.CounterR return histogram.UnknownCounterReset } } + +// Handle pathological case of empty span when advancing span idx. +func nextNonEmptySpanSliceIdx(idx int, spans []histogram.Span) (newIdx int) { + for idx++; idx < len(spans) && spans[idx].Length == 0; idx++ { + } + return idx +} diff --git a/tsdb/chunkenc/histogram_test.go b/tsdb/chunkenc/histogram_test.go index 45f31a3b4d5..9ef7e24a4c7 100644 --- a/tsdb/chunkenc/histogram_test.go +++ b/tsdb/chunkenc/histogram_test.go @@ -14,6 +14,7 @@ package chunkenc import ( + "fmt" "testing" "github.com/stretchr/testify/require" @@ -387,6 +388,64 @@ func TestHistogramChunkAppendable(t *testing.T) { } } +func TestHistogramChunkAppendableWithEmptySpan(t *testing.T) { + h1 := &histogram.Histogram{ + Schema: 0, + Count: 21, + Sum: 1234.5, + ZeroThreshold: 0.001, + ZeroCount: 4, + PositiveSpans: []histogram.Span{ + {Offset: 0, Length: 4}, + {Offset: 0, Length: 0}, + {Offset: 0, Length: 3}, + }, + PositiveBuckets: []int64{1, 1, -1, 0, 0, 0, 0}, + NegativeSpans: []histogram.Span{ + {Offset: 1, Length: 4}, + {Offset: 2, Length: 0}, + {Offset: 2, Length: 3}, + }, + NegativeBuckets: []int64{1, 1, -1, 1, 0, 0, 0}, + } + h2 := &histogram.Histogram{ + Schema: 0, + Count: 37, + Sum: 2345.6, + ZeroThreshold: 0.001, + ZeroCount: 5, + PositiveSpans: []histogram.Span{ + {Offset: 0, Length: 4}, + {Offset: 0, Length: 0}, + {Offset: 0, Length: 3}, + }, + PositiveBuckets: []int64{1, 2, -2, 1, -1, 0, 0}, + NegativeSpans: []histogram.Span{ + {Offset: 1, Length: 4}, + {Offset: 2, Length: 0}, + {Offset: 2, Length: 3}, + }, + NegativeBuckets: []int64{1, 3, -2, 5, -2, 0, -3}, + } + + c := Chunk(NewHistogramChunk()) + + // Create fresh appender and add the first histogram. + app, err := c.Appender() + require.NoError(t, err) + require.Equal(t, 0, c.NumSamples()) + + app.AppendHistogram(1, h1) + require.Equal(t, 1, c.NumSamples()) + hApp, _ := app.(*HistogramAppender) + + pI, nI, okToAppend, counterReset := hApp.Appendable(h2) + require.Empty(t, pI) + require.Empty(t, nI) + require.True(t, okToAppend) + require.False(t, counterReset) +} + func TestAtFloatHistogram(t *testing.T) { input := []histogram.Histogram{ { @@ -514,6 +573,10 @@ func TestAtFloatHistogram(t *testing.T) { app, err := chk.Appender() require.NoError(t, err) for i := range input { + if i > 0 { + _, _, okToAppend, _ := app.(*HistogramAppender).Appendable(&input[i]) + require.True(t, okToAppend, fmt.Sprintf("idx: %d", i)) + } app.AppendHistogram(int64(i), &input[i]) } it := chk.Iterator(nil) diff --git a/tsdb/db.go b/tsdb/db.go index de37bdb4f91..32dae57a529 100644 --- a/tsdb/db.go +++ b/tsdb/db.go @@ -78,6 +78,7 @@ func DefaultOptions() *Options { NoLockfile: false, AllowOverlappingCompaction: true, WALCompression: false, + SamplesPerChunk: DefaultSamplesPerChunk, StripeSize: DefaultStripeSize, HeadChunksWriteBufferSize: chunks.DefaultWriteBufferSize, IsolationDisabled: defaultIsolationDisabled, @@ -149,6 +150,9 @@ type Options struct { // HeadChunksWriteQueueSize configures the size of the chunk write queue used in the head chunks mapper. HeadChunksWriteQueueSize int + // SamplesPerChunk configures the target number of samples per chunk. + SamplesPerChunk int + // SeriesLifecycleCallback specifies a list of callbacks that will be called during a lifecycle of a series. // It is always a no-op in Prometheus and mainly meant for external users who import TSDB. SeriesLifecycleCallback SeriesLifecycleCallback @@ -225,6 +229,8 @@ type DB struct { // out-of-order compaction and vertical queries. oooWasEnabled atomic.Bool + writeNotified wlog.WriteNotified + registerer prometheus.Registerer } @@ -601,6 +607,60 @@ func (db *DBReadOnly) Blocks() ([]BlockReader, error) { return blockReaders, nil } +// LastBlockID returns the BlockID of latest block. +func (db *DBReadOnly) LastBlockID() (string, error) { + entries, err := os.ReadDir(db.dir) + if err != nil { + return "", err + } + + max := uint64(0) + + lastBlockID := "" + + for _, e := range entries { + // Check if dir is a block dir or not. + dirName := e.Name() + ulidObj, err := ulid.ParseStrict(dirName) + if err != nil { + continue // Not a block dir. + } + timestamp := ulidObj.Time() + if timestamp > max { + max = timestamp + lastBlockID = dirName + } + } + + if lastBlockID == "" { + return "", errors.New("no blocks found") + } + + return lastBlockID, nil +} + +// Block returns a block reader by given block id. +func (db *DBReadOnly) Block(blockID string) (BlockReader, error) { + select { + case <-db.closed: + return nil, ErrClosed + default: + } + + _, err := os.Stat(filepath.Join(db.dir, blockID)) + if os.IsNotExist(err) { + return nil, errors.Errorf("invalid block ID %s", blockID) + } + + block, err := OpenBlock(db.logger, filepath.Join(db.dir, blockID), nil) + if err != nil { + return nil, err + } + db.closers = append(db.closers, block) + + return block, nil +} + // Close all block readers. func (db *DBReadOnly) Close() error { select { @@ -634,6 +694,9 @@ func validateOpts(opts *Options, rngs []int64) (*Options, []int64) { if opts.HeadChunksWriteQueueSize < 0 { opts.HeadChunksWriteQueueSize = chunks.DefaultWriteQueueSize } + if opts.SamplesPerChunk <= 0 { + opts.SamplesPerChunk = DefaultSamplesPerChunk + } if opts.MaxBlockChunkSegmentSize <= 0 { opts.MaxBlockChunkSegmentSize = chunks.DefaultChunkSegmentSize } @@ -778,6 +841,7 @@ func open(dir string, l log.Logger, r prometheus.Registerer, opts *Options, rngs headOpts.ChunkPool = db.chunkPool headOpts.ChunkWriteBufferSize = opts.HeadChunksWriteBufferSize headOpts.ChunkWriteQueueSize = opts.HeadChunksWriteQueueSize + headOpts.SamplesPerChunk = opts.SamplesPerChunk headOpts.StripeSize = opts.StripeSize headOpts.SeriesCallback = opts.SeriesLifecycleCallback headOpts.EnableExemplarStorage = opts.EnableExemplarStorage @@ -797,6 +861,7 @@ func open(dir string, l log.Logger, r prometheus.Registerer, opts *Options, rngs if err != nil { return nil, err } + db.head.writeNotified = db.writeNotified // Register metrics after assigning the head block. db.metrics = newDBMetrics(db, r) @@ -1841,7 +1906,7 @@ func (db *DB) Querier(_ context.Context, mint, maxt int64) (storage.Querier, err return storage.NewMergeQuerier(blockQueriers, nil, storage.ChainedSeriesMerge), nil } -// blockQueriersForRange returns individual block chunk queriers from the persistent blocks, in-order head block, and the +// blockChunkQuerierForRange returns individual block chunk queriers from the persistent blocks, in-order head block, and the // out-of-order head block, overlapping with the given time range. func (db *DB) blockChunkQuerierForRange(mint, maxt int64) ([]storage.ChunkQuerier, error) { var blocks []BlockReader @@ -2011,6 +2076,12 @@ func (db *DB) CleanTombstones() (err error) { return nil } +func (db *DB) SetWriteNotified(wn wlog.WriteNotified) { + db.writeNotified = wn + // It's possible we already created the head struct, so we should also set the WN for that. + db.head.writeNotified = wn +} + func isBlockDir(fi fs.DirEntry) bool { if !fi.IsDir() { return false diff --git a/tsdb/db_test.go b/tsdb/db_test.go index 0b980f6ec64..427a3b7afab 100644 --- a/tsdb/db_test.go +++ b/tsdb/db_test.go @@ -2384,6 +2384,7 @@ func TestDBReadOnly(t *testing.T) { dbDir string logger = log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr)) expBlocks []*Block + expBlock *Block expSeries map[string][]tsdbutil.Sample expChunks map[string][][]tsdbutil.Sample expDBHash []byte @@ -2427,6 +2428,7 @@ func TestDBReadOnly(t *testing.T) { require.NoError(t, app.Commit()) expBlocks = dbWritable.Blocks() + expBlock = expBlocks[0] expDbSize, err := fileutil.DirSize(dbWritable.Dir()) require.NoError(t, err) require.Greater(t, expDbSize, dbSizeBeforeAppend, "db size didn't increase after an append") @@ -2455,7 +2457,22 @@ func TestDBReadOnly(t *testing.T) { require.Equal(t, expBlock.Meta(), blocks[i].Meta(), "block meta mismatch") } }) - + t.Run("block", func(t *testing.T) { + blockID := expBlock.meta.ULID.String() + block, err := dbReadOnly.Block(blockID) + require.NoError(t, err) + require.Equal(t, expBlock.Meta(), block.Meta(), "block meta mismatch") + }) + t.Run("invalid block ID", func(t *testing.T) { + blockID := "01GTDVZZF52NSWB5SXQF0P2PGF" + _, err := dbReadOnly.Block(blockID) + require.Error(t, err) + }) + t.Run("last block ID", func(t *testing.T) { + blockID, err := dbReadOnly.LastBlockID() + require.NoError(t, err) + require.Equal(t, expBlocks[2].Meta().ULID.String(), blockID) + }) t.Run("querier", func(t *testing.T) { // Open a read only db and ensure that the API returns the same result as the normal DB. q, err := dbReadOnly.Querier(context.TODO(), math.MinInt64, math.MaxInt64) diff --git a/tsdb/exemplar.go b/tsdb/exemplar.go index ad3b2ef39b1..01718bb57d3 100644 --- a/tsdb/exemplar.go +++ b/tsdb/exemplar.go @@ -216,9 +216,9 @@ func (ce *CircularExemplarStorage) ValidateExemplar(l labels.Labels, e exemplar. return ce.validateExemplar(seriesLabels, e, false) } -// Not thread safe. The append parameters tells us whether this is an external validation, or internal +// Not thread safe. The appended parameters tells us whether this is an external validation, or internal // as a result of an AddExemplar call, in which case we should update any relevant metrics. -func (ce *CircularExemplarStorage) validateExemplar(key []byte, e exemplar.Exemplar, append bool) error { +func (ce *CircularExemplarStorage) validateExemplar(key []byte, e exemplar.Exemplar, appended bool) error { if len(ce.exemplars) == 0 { return storage.ErrExemplarsDisabled } @@ -250,7 +250,7 @@ func (ce *CircularExemplarStorage) validateExemplar(key []byte, e exemplar.Exemp } if e.Ts <= ce.exemplars[idx.newest].exemplar.Ts { - if append { + if appended { ce.metrics.outOfOrderExemplars.Inc() } return storage.ErrOutOfOrderExemplar diff --git a/tsdb/head.go b/tsdb/head.go index 5bd5bbccc96..a1d61fd6ab9 100644 --- a/tsdb/head.go +++ b/tsdb/head.go @@ -121,6 +121,8 @@ type Head struct { stats *HeadStats reg prometheus.Registerer + writeNotified wlog.WriteNotified + memTruncationInProcess atomic.Bool } @@ -150,6 +152,8 @@ type HeadOptions struct { ChunkWriteBufferSize int ChunkWriteQueueSize int + SamplesPerChunk int + // StripeSize sets the number of entries in the hash map, it must be a power of 2. // A larger StripeSize will allocate more memory up-front, but will increase performance when handling a large number of series. // A smaller StripeSize reduces the memory allocated, but can decrease performance with large number of series. @@ -169,6 +173,8 @@ type HeadOptions struct { const ( // DefaultOutOfOrderCapMax is the default maximum size of an in-memory out-of-order chunk. DefaultOutOfOrderCapMax int64 = 32 + // DefaultSamplesPerChunk provides a default target number of samples per chunk. + DefaultSamplesPerChunk = 120 ) func DefaultHeadOptions() *HeadOptions { @@ -178,6 +184,7 @@ func DefaultHeadOptions() *HeadOptions { ChunkPool: chunkenc.NewPool(), ChunkWriteBufferSize: chunks.DefaultWriteBufferSize, ChunkWriteQueueSize: chunks.DefaultWriteQueueSize, + SamplesPerChunk: DefaultSamplesPerChunk, StripeSize: DefaultStripeSize, SeriesCallback: &noopSeriesLifecycleCallback{}, IsolationDisabled: defaultIsolationDisabled, @@ -971,7 +978,7 @@ func (h *Head) DisableNativeHistograms() { } // PostingsCardinalityStats returns top 10 highest cardinality stats By label and value names. -func (h *Head) PostingsCardinalityStats(statsByLabelName string) *index.PostingsStats { +func (h *Head) PostingsCardinalityStats(statsByLabelName string, limit int) *index.PostingsStats { h.cardinalityMutex.Lock() defer h.cardinalityMutex.Unlock() currentTime := time.Duration(time.Now().Unix()) * time.Second @@ -982,7 +989,7 @@ func (h *Head) PostingsCardinalityStats(statsByLabelName string) *index.Postings if h.cardinalityCache != nil { return h.cardinalityCache } - h.cardinalityCache = h.postings.Stats(statsByLabelName) + h.cardinalityCache = h.postings.Stats(statsByLabelName, limit) h.lastPostingsStatsCall = time.Duration(time.Now().Unix()) * time.Second return h.cardinalityCache @@ -1212,9 +1219,9 @@ func (h *Head) truncateWAL(mint int64) error { return true } h.deletedMtx.Lock() - _, ok := h.deleted[id] + keepUntil, ok := h.deleted[id] h.deletedMtx.Unlock() - return ok + return ok && keepUntil > last } h.metrics.checkpointCreationTotal.Inc() if _, err = wlog.Checkpoint(h.logger, h.wal, first, last, keep, mint); err != nil { @@ -1235,7 +1242,7 @@ func (h *Head) truncateWAL(mint int64) error { // longer need to track deleted series that are before it. h.deletedMtx.Lock() for ref, segment := range h.deleted { - if segment < first { + if segment <= last { delete(h.deleted, ref) } } @@ -1322,12 +1329,12 @@ type Stats struct { // Stats returns important current HEAD statistics. Note that it is expensive to // calculate these. -func (h *Head) Stats(statsByLabelName string) *Stats { +func (h *Head) Stats(statsByLabelName string, limit int) *Stats { return &Stats{ NumSeries: h.NumSeries(), MaxTime: h.MaxTime(), MinTime: h.MinTime(), - IndexPostingStats: h.PostingsCardinalityStats(statsByLabelName), + IndexPostingStats: h.PostingsCardinalityStats(statsByLabelName, limit), } } diff --git a/tsdb/head_append.go b/tsdb/head_append.go index 86cb097513f..44847dceb20 100644 --- a/tsdb/head_append.go +++ b/tsdb/head_append.go @@ -842,6 +842,10 @@ func (a *headAppender) Commit() (err error) { return errors.Wrap(err, "write to WAL") } + if a.head.writeNotified != nil { + a.head.writeNotified.Notify() + } + // No errors logging to WAL, so pass the exemplars along to the in memory storage. for _, e := range a.exemplars { s := a.head.series.getByID(chunks.HeadSeriesRef(e.ref)) @@ -983,7 +987,7 @@ func (a *headAppender) Commit() (err error) { samplesAppended-- } default: - ok, chunkCreated = series.append(s.T, s.V, a.appendID, a.head.chunkDiskMapper, chunkRange) + ok, chunkCreated = series.append(s.T, s.V, a.appendID, a.head.chunkDiskMapper, chunkRange, a.head.opts.SamplesPerChunk) if ok { if s.T < inOrderMint { inOrderMint = s.T @@ -1012,7 +1016,7 @@ func (a *headAppender) Commit() (err error) { for i, s := range a.histograms { series = a.histogramSeries[i] series.Lock() - ok, chunkCreated := series.appendHistogram(s.T, s.H, a.appendID, a.head.chunkDiskMapper, chunkRange) + ok, chunkCreated := series.appendHistogram(s.T, s.H, a.appendID, a.head.chunkDiskMapper, chunkRange, a.head.opts.SamplesPerChunk) series.cleanupAppendIDsBelow(a.cleanupAppendIDsBelow) series.pendingCommit = false series.Unlock() @@ -1038,7 +1042,7 @@ func (a *headAppender) Commit() (err error) { for i, s := range a.floatHistograms { series = a.floatHistogramSeries[i] series.Lock() - ok, chunkCreated := series.appendFloatHistogram(s.T, s.FH, a.appendID, a.head.chunkDiskMapper, chunkRange) + ok, chunkCreated := series.appendFloatHistogram(s.T, s.FH, a.appendID, a.head.chunkDiskMapper, chunkRange, a.head.opts.SamplesPerChunk) series.cleanupAppendIDsBelow(a.cleanupAppendIDsBelow) series.pendingCommit = false series.Unlock() @@ -1118,8 +1122,8 @@ func (s *memSeries) insert(t int64, v float64, chunkDiskMapper *chunks.ChunkDisk // the appendID for isolation. (The appendID can be zero, which results in no // isolation for this append.) // It is unsafe to call this concurrently with s.iterator(...) without holding the series lock. -func (s *memSeries) append(t int64, v float64, appendID uint64, chunkDiskMapper *chunks.ChunkDiskMapper, chunkRange int64) (sampleInOrder, chunkCreated bool) { - c, sampleInOrder, chunkCreated := s.appendPreprocessor(t, chunkenc.EncXOR, chunkDiskMapper, chunkRange) +func (s *memSeries) append(t int64, v float64, appendID uint64, chunkDiskMapper *chunks.ChunkDiskMapper, chunkRange int64, samplesPerChunk int) (sampleInOrder, chunkCreated bool) { + c, sampleInOrder, chunkCreated := s.appendPreprocessor(t, chunkenc.EncXOR, chunkDiskMapper, chunkRange, samplesPerChunk) if !sampleInOrder { return sampleInOrder, chunkCreated } @@ -1140,7 +1144,7 @@ func (s *memSeries) append(t int64, v float64, appendID uint64, chunkDiskMapper // appendHistogram adds the histogram. // It is unsafe to call this concurrently with s.iterator(...) without holding the series lock. -func (s *memSeries) appendHistogram(t int64, h *histogram.Histogram, appendID uint64, chunkDiskMapper *chunks.ChunkDiskMapper, chunkRange int64) (sampleInOrder, chunkCreated bool) { +func (s *memSeries) appendHistogram(t int64, h *histogram.Histogram, appendID uint64, chunkDiskMapper *chunks.ChunkDiskMapper, chunkRange int64, samplesPerChunk int) (sampleInOrder, chunkCreated bool) { // Head controls the execution of recoding, so that we own the proper // chunk reference afterwards. We check for Appendable from appender before // appendPreprocessor because in case it ends up creating a new chunk, @@ -1153,7 +1157,7 @@ func (s *memSeries) appendHistogram(t int64, h *histogram.Histogram, appendID ui pMergedSpans, nMergedSpans []histogram.Span okToAppend, counterReset, gauge bool ) - c, sampleInOrder, chunkCreated := s.appendPreprocessor(t, chunkenc.EncHistogram, chunkDiskMapper, chunkRange) + c, sampleInOrder, chunkCreated := s.appendPreprocessor(t, chunkenc.EncHistogram, chunkDiskMapper, chunkRange, samplesPerChunk) if !sampleInOrder { return sampleInOrder, chunkCreated } @@ -1234,7 +1238,7 @@ func (s *memSeries) appendHistogram(t int64, h *histogram.Histogram, appendID ui // appendFloatHistogram adds the float histogram. // It is unsafe to call this concurrently with s.iterator(...) without holding the series lock. -func (s *memSeries) appendFloatHistogram(t int64, fh *histogram.FloatHistogram, appendID uint64, chunkDiskMapper *chunks.ChunkDiskMapper, chunkRange int64) (sampleInOrder, chunkCreated bool) { +func (s *memSeries) appendFloatHistogram(t int64, fh *histogram.FloatHistogram, appendID uint64, chunkDiskMapper *chunks.ChunkDiskMapper, chunkRange int64, samplesPerChunk int) (sampleInOrder, chunkCreated bool) { // Head controls the execution of recoding, so that we own the proper // chunk reference afterwards. We check for Appendable from appender before // appendPreprocessor because in case it ends up creating a new chunk, @@ -1247,7 +1251,7 @@ func (s *memSeries) appendFloatHistogram(t int64, fh *histogram.FloatHistogram, pMergedSpans, nMergedSpans []histogram.Span okToAppend, counterReset, gauge bool ) - c, sampleInOrder, chunkCreated := s.appendPreprocessor(t, chunkenc.EncFloatHistogram, chunkDiskMapper, chunkRange) + c, sampleInOrder, chunkCreated := s.appendPreprocessor(t, chunkenc.EncFloatHistogram, chunkDiskMapper, chunkRange, samplesPerChunk) if !sampleInOrder { return sampleInOrder, chunkCreated } @@ -1330,13 +1334,8 @@ func (s *memSeries) appendFloatHistogram(t int64, fh *histogram.FloatHistogram, // It is unsafe to call this concurrently with s.iterator(...) without holding the series lock. // This should be called only when appending data. func (s *memSeries) appendPreprocessor( - t int64, e chunkenc.Encoding, chunkDiskMapper *chunks.ChunkDiskMapper, chunkRange int64, + t int64, e chunkenc.Encoding, chunkDiskMapper *chunks.ChunkDiskMapper, chunkRange int64, samplesPerChunk int, ) (c *memChunk, sampleInOrder, chunkCreated bool) { - // Based on Gorilla white papers this offers near-optimal compression ratio - // so anything bigger that this has diminishing returns and increases - // the time range within which we have to decompress all samples. - const samplesPerChunk = 120 - c = s.head() if c == nil { diff --git a/tsdb/head_read.go b/tsdb/head_read.go index 9c546ab164a..0e6e005ea2b 100644 --- a/tsdb/head_read.go +++ b/tsdb/head_read.go @@ -331,7 +331,7 @@ func (h *headChunkReader) chunk(meta chunks.Meta, copyLastChunk bool) (chunkenc. } s.Unlock() - return &safeChunk{ + return &safeHeadChunk{ Chunk: chk, s: s, cid: cid, @@ -627,15 +627,15 @@ func (b boundedIterator) Seek(t int64) chunkenc.ValueType { return b.Iterator.Seek(t) } -// safeChunk makes sure that the chunk can be accessed without a race condition -type safeChunk struct { +// safeHeadChunk makes sure that the chunk can be accessed without a race condition +type safeHeadChunk struct { chunkenc.Chunk s *memSeries cid chunks.HeadChunkID isoState *isolationState } -func (c *safeChunk) Iterator(reuseIter chunkenc.Iterator) chunkenc.Iterator { +func (c *safeHeadChunk) Iterator(reuseIter chunkenc.Iterator) chunkenc.Iterator { c.s.Lock() it := c.s.iterator(c.cid, c.Chunk, c.isoState, reuseIter) c.s.Unlock() diff --git a/tsdb/head_test.go b/tsdb/head_test.go index 45b58740565..14468e0716d 100644 --- a/tsdb/head_test.go +++ b/tsdb/head_test.go @@ -286,7 +286,7 @@ func BenchmarkLoadWAL(b *testing.B) { for k := 0; k < c.batches*c.seriesPerBatch; k++ { // Create one mmapped chunk per series, with one sample at the given time. s := newMemSeries(labels.Labels{}, chunks.HeadSeriesRef(k)*101, defaultIsolationDisabled) - s.append(c.mmappedChunkT, 42, 0, chunkDiskMapper, c.mmappedChunkT) + s.append(c.mmappedChunkT, 42, 0, chunkDiskMapper, c.mmappedChunkT, DefaultSamplesPerChunk) s.mmapCurrentHeadChunk(chunkDiskMapper) } require.NoError(b, chunkDiskMapper.Close()) @@ -810,7 +810,7 @@ func TestMemSeries_truncateChunks(t *testing.T) { s := newMemSeries(labels.FromStrings("a", "b"), 1, defaultIsolationDisabled) for i := 0; i < 4000; i += 5 { - ok, _ := s.append(int64(i), float64(i), 0, chunkDiskMapper, chunkRange) + ok, _ := s.append(int64(i), float64(i), 0, chunkDiskMapper, chunkRange, DefaultSamplesPerChunk) require.True(t, ok, "sample append failed") } @@ -1343,19 +1343,19 @@ func TestMemSeries_append(t *testing.T) { // Add first two samples at the very end of a chunk range and the next two // on and after it. // New chunk must correctly be cut at 1000. - ok, chunkCreated := s.append(998, 1, 0, chunkDiskMapper, chunkRange) + ok, chunkCreated := s.append(998, 1, 0, chunkDiskMapper, chunkRange, DefaultSamplesPerChunk) require.True(t, ok, "append failed") require.True(t, chunkCreated, "first sample created chunk") - ok, chunkCreated = s.append(999, 2, 0, chunkDiskMapper, chunkRange) + ok, chunkCreated = s.append(999, 2, 0, chunkDiskMapper, chunkRange, DefaultSamplesPerChunk) require.True(t, ok, "append failed") require.False(t, chunkCreated, "second sample should use same chunk") - ok, chunkCreated = s.append(1000, 3, 0, chunkDiskMapper, chunkRange) + ok, chunkCreated = s.append(1000, 3, 0, chunkDiskMapper, chunkRange, DefaultSamplesPerChunk) require.True(t, ok, "append failed") require.True(t, chunkCreated, "expected new chunk on boundary") - ok, chunkCreated = s.append(1001, 4, 0, chunkDiskMapper, chunkRange) + ok, chunkCreated = s.append(1001, 4, 0, chunkDiskMapper, chunkRange, DefaultSamplesPerChunk) require.True(t, ok, "append failed") require.False(t, chunkCreated, "second sample should use same chunk") @@ -1368,7 +1368,7 @@ func TestMemSeries_append(t *testing.T) { // Fill the range [1000,2000) with many samples. Intermediate chunks should be cut // at approximately 120 samples per chunk. for i := 1; i < 1000; i++ { - ok, _ := s.append(1001+int64(i), float64(i), 0, chunkDiskMapper, chunkRange) + ok, _ := s.append(1001+int64(i), float64(i), 0, chunkDiskMapper, chunkRange, DefaultSamplesPerChunk) require.True(t, ok, "append failed") } @@ -1404,19 +1404,19 @@ func TestMemSeries_appendHistogram(t *testing.T) { // Add first two samples at the very end of a chunk range and the next two // on and after it. // New chunk must correctly be cut at 1000. - ok, chunkCreated := s.appendHistogram(998, histograms[0], 0, chunkDiskMapper, chunkRange) + ok, chunkCreated := s.appendHistogram(998, histograms[0], 0, chunkDiskMapper, chunkRange, DefaultSamplesPerChunk) require.True(t, ok, "append failed") require.True(t, chunkCreated, "first sample created chunk") - ok, chunkCreated = s.appendHistogram(999, histograms[1], 0, chunkDiskMapper, chunkRange) + ok, chunkCreated = s.appendHistogram(999, histograms[1], 0, chunkDiskMapper, chunkRange, DefaultSamplesPerChunk) require.True(t, ok, "append failed") require.False(t, chunkCreated, "second sample should use same chunk") - ok, chunkCreated = s.appendHistogram(1000, histograms[2], 0, chunkDiskMapper, chunkRange) + ok, chunkCreated = s.appendHistogram(1000, histograms[2], 0, chunkDiskMapper, chunkRange, DefaultSamplesPerChunk) require.True(t, ok, "append failed") require.True(t, chunkCreated, "expected new chunk on boundary") - ok, chunkCreated = s.appendHistogram(1001, histograms[3], 0, chunkDiskMapper, chunkRange) + ok, chunkCreated = s.appendHistogram(1001, histograms[3], 0, chunkDiskMapper, chunkRange, DefaultSamplesPerChunk) require.True(t, ok, "append failed") require.False(t, chunkCreated, "second sample should use same chunk") @@ -1426,7 +1426,7 @@ func TestMemSeries_appendHistogram(t *testing.T) { require.Equal(t, int64(1000), s.headChunk.minTime, "wrong chunk range") require.Equal(t, int64(1001), s.headChunk.maxTime, "wrong chunk range") - ok, chunkCreated = s.appendHistogram(1002, histogramWithOneMoreBucket, 0, chunkDiskMapper, chunkRange) + ok, chunkCreated = s.appendHistogram(1002, histogramWithOneMoreBucket, 0, chunkDiskMapper, chunkRange, DefaultSamplesPerChunk) require.True(t, ok, "append failed") require.False(t, chunkCreated, "third sample should trigger a re-encoded chunk") @@ -1456,7 +1456,7 @@ func TestMemSeries_append_atVariableRate(t *testing.T) { var nextTs int64 var totalAppendedSamples int for i := 0; i < samplesPerChunk/4; i++ { - ok, _ := s.append(nextTs, float64(i), 0, chunkDiskMapper, chunkRange) + ok, _ := s.append(nextTs, float64(i), 0, chunkDiskMapper, chunkRange, DefaultSamplesPerChunk) require.Truef(t, ok, "slow sample %d was not appended", i) nextTs += slowRate totalAppendedSamples++ @@ -1465,12 +1465,12 @@ func TestMemSeries_append_atVariableRate(t *testing.T) { // Suddenly, the rate increases and we receive a sample every millisecond. for i := 0; i < math.MaxUint16; i++ { - ok, _ := s.append(nextTs, float64(i), 0, chunkDiskMapper, chunkRange) + ok, _ := s.append(nextTs, float64(i), 0, chunkDiskMapper, chunkRange, DefaultSamplesPerChunk) require.Truef(t, ok, "quick sample %d was not appended", i) nextTs++ totalAppendedSamples++ } - ok, chunkCreated := s.append(DefaultBlockDuration, float64(0), 0, chunkDiskMapper, chunkRange) + ok, chunkCreated := s.append(DefaultBlockDuration, float64(0), 0, chunkDiskMapper, chunkRange, DefaultSamplesPerChunk) require.True(t, ok, "new chunk sample was not appended") require.True(t, chunkCreated, "sample at block duration timestamp should create a new chunk") @@ -1495,18 +1495,18 @@ func TestGCChunkAccess(t *testing.T) { s, _, _ := h.getOrCreate(1, labels.FromStrings("a", "1")) // Appending 2 samples for the first chunk. - ok, chunkCreated := s.append(0, 0, 0, h.chunkDiskMapper, chunkRange) + ok, chunkCreated := s.append(0, 0, 0, h.chunkDiskMapper, chunkRange, DefaultSamplesPerChunk) require.True(t, ok, "series append failed") require.True(t, chunkCreated, "chunks was not created") - ok, chunkCreated = s.append(999, 999, 0, h.chunkDiskMapper, chunkRange) + ok, chunkCreated = s.append(999, 999, 0, h.chunkDiskMapper, chunkRange, DefaultSamplesPerChunk) require.True(t, ok, "series append failed") require.False(t, chunkCreated, "chunks was created") // A new chunks should be created here as it's beyond the chunk range. - ok, chunkCreated = s.append(1000, 1000, 0, h.chunkDiskMapper, chunkRange) + ok, chunkCreated = s.append(1000, 1000, 0, h.chunkDiskMapper, chunkRange, DefaultSamplesPerChunk) require.True(t, ok, "series append failed") require.True(t, chunkCreated, "chunks was not created") - ok, chunkCreated = s.append(1999, 1999, 0, h.chunkDiskMapper, chunkRange) + ok, chunkCreated = s.append(1999, 1999, 0, h.chunkDiskMapper, chunkRange, DefaultSamplesPerChunk) require.True(t, ok, "series append failed") require.False(t, chunkCreated, "chunks was created") @@ -1548,18 +1548,18 @@ func TestGCSeriesAccess(t *testing.T) { s, _, _ := h.getOrCreate(1, labels.FromStrings("a", "1")) // Appending 2 samples for the first chunk. - ok, chunkCreated := s.append(0, 0, 0, h.chunkDiskMapper, chunkRange) + ok, chunkCreated := s.append(0, 0, 0, h.chunkDiskMapper, chunkRange, DefaultSamplesPerChunk) require.True(t, ok, "series append failed") require.True(t, chunkCreated, "chunks was not created") - ok, chunkCreated = s.append(999, 999, 0, h.chunkDiskMapper, chunkRange) + ok, chunkCreated = s.append(999, 999, 0, h.chunkDiskMapper, chunkRange, DefaultSamplesPerChunk) require.True(t, ok, "series append failed") require.False(t, chunkCreated, "chunks was created") // A new chunks should be created here as it's beyond the chunk range. - ok, chunkCreated = s.append(1000, 1000, 0, h.chunkDiskMapper, chunkRange) + ok, chunkCreated = s.append(1000, 1000, 0, h.chunkDiskMapper, chunkRange, DefaultSamplesPerChunk) require.True(t, ok, "series append failed") require.True(t, chunkCreated, "chunks was not created") - ok, chunkCreated = s.append(1999, 1999, 0, h.chunkDiskMapper, chunkRange) + ok, chunkCreated = s.append(1999, 1999, 0, h.chunkDiskMapper, chunkRange, DefaultSamplesPerChunk) require.True(t, ok, "series append failed") require.False(t, chunkCreated, "chunks was created") @@ -1795,10 +1795,10 @@ func TestHeadReadWriterRepair(t *testing.T) { require.True(t, created, "series was not created") for i := 0; i < 7; i++ { - ok, chunkCreated := s.append(int64(i*chunkRange), float64(i*chunkRange), 0, h.chunkDiskMapper, chunkRange) + ok, chunkCreated := s.append(int64(i*chunkRange), float64(i*chunkRange), 0, h.chunkDiskMapper, chunkRange, DefaultSamplesPerChunk) require.True(t, ok, "series append failed") require.True(t, chunkCreated, "chunk was not created") - ok, chunkCreated = s.append(int64(i*chunkRange)+chunkRange-1, float64(i*chunkRange), 0, h.chunkDiskMapper, chunkRange) + ok, chunkCreated = s.append(int64(i*chunkRange)+chunkRange-1, float64(i*chunkRange), 0, h.chunkDiskMapper, chunkRange, DefaultSamplesPerChunk) require.True(t, ok, "series append failed") require.False(t, chunkCreated, "chunk was created") h.chunkDiskMapper.CutNewFile() @@ -2146,7 +2146,7 @@ func TestIsolationAppendIDZeroIsNoop(t *testing.T) { s, _, _ := h.getOrCreate(1, labels.FromStrings("a", "1")) - ok, _ := s.append(0, 0, 0, h.chunkDiskMapper, h.chunkRange.Load()) + ok, _ := s.append(0, 0, 0, h.chunkDiskMapper, h.chunkRange.Load(), DefaultSamplesPerChunk) require.True(t, ok, "Series append failed.") require.Equal(t, 0, s.txs.txIDCount, "Series should not have an appendID after append with appendID=0.") } @@ -2613,7 +2613,7 @@ func TestIteratorSeekIntoBuffer(t *testing.T) { s := newMemSeries(labels.Labels{}, 1, defaultIsolationDisabled) for i := 0; i < 7; i++ { - ok, _ := s.append(int64(i), float64(i), 0, chunkDiskMapper, chunkRange) + ok, _ := s.append(int64(i), float64(i), 0, chunkDiskMapper, chunkRange, DefaultSamplesPerChunk) require.True(t, ok, "sample append failed") } diff --git a/tsdb/head_wal.go b/tsdb/head_wal.go index 6e81f179328..9741d1da04a 100644 --- a/tsdb/head_wal.go +++ b/tsdb/head_wal.go @@ -588,7 +588,7 @@ func (wp *walSubsetProcessor) processWALSamples(h *Head, mmappedChunks, oooMmapp if s.T <= ms.mmMaxTime { continue } - if _, chunkCreated := ms.append(s.T, s.V, 0, h.chunkDiskMapper, chunkRange); chunkCreated { + if _, chunkCreated := ms.append(s.T, s.V, 0, h.chunkDiskMapper, chunkRange, h.opts.SamplesPerChunk); chunkCreated { h.metrics.chunksCreated.Inc() h.metrics.chunks.Inc() } @@ -618,9 +618,9 @@ func (wp *walSubsetProcessor) processWALSamples(h *Head, mmappedChunks, oooMmapp } var chunkCreated bool if s.h != nil { - _, chunkCreated = ms.appendHistogram(s.t, s.h, 0, h.chunkDiskMapper, chunkRange) + _, chunkCreated = ms.appendHistogram(s.t, s.h, 0, h.chunkDiskMapper, chunkRange, h.opts.SamplesPerChunk) } else { - _, chunkCreated = ms.appendFloatHistogram(s.t, s.fh, 0, h.chunkDiskMapper, chunkRange) + _, chunkCreated = ms.appendFloatHistogram(s.t, s.fh, 0, h.chunkDiskMapper, chunkRange, h.opts.SamplesPerChunk) } if chunkCreated { h.metrics.chunksCreated.Inc() diff --git a/tsdb/index/postings.go b/tsdb/index/postings.go index b93d3a20214..2ac6edbdca2 100644 --- a/tsdb/index/postings.go +++ b/tsdb/index/postings.go @@ -156,10 +156,8 @@ type PostingsStats struct { } // Stats calculates the cardinality statistics from postings. -func (p *MemPostings) Stats(label string) *PostingsStats { - const maxNumOfRecords = 10 +func (p *MemPostings) Stats(label string, limit int) *PostingsStats { var size uint64 - p.mtx.RLock() metrics := &maxHeap{} @@ -168,10 +166,10 @@ func (p *MemPostings) Stats(label string) *PostingsStats { labelValuePairs := &maxHeap{} numLabelPairs := 0 - metrics.init(maxNumOfRecords) - labels.init(maxNumOfRecords) - labelValueLength.init(maxNumOfRecords) - labelValuePairs.init(maxNumOfRecords) + metrics.init(limit) + labels.init(limit) + labelValueLength.init(limit) + labelValuePairs.init(limit) for n, e := range p.m { if n == "" { @@ -184,8 +182,9 @@ func (p *MemPostings) Stats(label string) *PostingsStats { if n == label { metrics.push(Stat{Name: name, Count: uint64(len(values))}) } - labelValuePairs.push(Stat{Name: n + "=" + name, Count: uint64(len(values))}) - size += uint64(len(name)) + seriesCnt := uint64(len(values)) + labelValuePairs.push(Stat{Name: n + "=" + name, Count: seriesCnt}) + size += uint64(len(name)) * seriesCnt } labelValueLength.push(Stat{Name: n, Count: size}) } diff --git a/tsdb/index/postings_test.go b/tsdb/index/postings_test.go index a34f3c12df7..9454def467a 100644 --- a/tsdb/index/postings_test.go +++ b/tsdb/index/postings_test.go @@ -912,10 +912,39 @@ func BenchmarkPostings_Stats(b *testing.B) { } b.ResetTimer() for n := 0; n < b.N; n++ { - p.Stats("__name__") + p.Stats("__name__", 10) } } +func TestMemPostingsStats(t *testing.T) { + // create a new MemPostings + p := NewMemPostings() + + // add some postings to the MemPostings + p.Add(1, labels.FromStrings("label", "value1")) + p.Add(1, labels.FromStrings("label", "value2")) + p.Add(1, labels.FromStrings("label", "value3")) + p.Add(2, labels.FromStrings("label", "value1")) + + // call the Stats method to calculate the cardinality statistics + stats := p.Stats("label", 10) + + // assert that the expected statistics were calculated + require.Equal(t, uint64(2), stats.CardinalityMetricsStats[0].Count) + require.Equal(t, "value1", stats.CardinalityMetricsStats[0].Name) + + require.Equal(t, uint64(3), stats.CardinalityLabelStats[0].Count) + require.Equal(t, "label", stats.CardinalityLabelStats[0].Name) + + require.Equal(t, uint64(24), stats.LabelValueStats[0].Count) + require.Equal(t, "label", stats.LabelValueStats[0].Name) + + require.Equal(t, uint64(2), stats.LabelValuePairsStats[0].Count) + require.Equal(t, "label=value1", stats.LabelValuePairsStats[0].Name) + + require.Equal(t, 3, stats.NumLabelPairs) +} + func TestMemPostings_Delete(t *testing.T) { p := NewMemPostings() p.Add(1, labels.FromStrings("lbl1", "a")) diff --git a/tsdb/isolation.go b/tsdb/isolation.go index 401e5885a02..e436884a8db 100644 --- a/tsdb/isolation.go +++ b/tsdb/isolation.go @@ -244,9 +244,9 @@ type txRing struct { txIDCount int // How many ids in the ring. } -func newTxRing(cap int) *txRing { +func newTxRing(capacity int) *txRing { return &txRing{ - txIDs: make([]uint64, cap), + txIDs: make([]uint64, capacity), } } diff --git a/tsdb/querier.go b/tsdb/querier.go index 70f8f6de8dd..72b6b514144 100644 --- a/tsdb/querier.go +++ b/tsdb/querier.go @@ -190,7 +190,14 @@ func findSetMatches(pattern string) []string { } escaped := false sets := []*strings.Builder{{}} - for i := 4; i < len(pattern)-2; i++ { + init := 4 + end := len(pattern) - 2 + // If the regex is wrapped in a group we can remove the first and last parentheses + if pattern[init] == '(' && pattern[end-1] == ')' { + init++ + end-- + } + for i := init; i < end; i++ { if escaped { switch { case isRegexMetaCharacter(pattern[i]): @@ -361,6 +368,22 @@ func postingsForMatcher(ix IndexReader, m *labels.Matcher) (index.Postings, erro // inversePostingsForMatcher returns the postings for the series with the label name set but not matching the matcher. func inversePostingsForMatcher(ix IndexReader, m *labels.Matcher) (index.Postings, error) { + // Fast-path for MatchNotRegexp matching. + // Inverse of a MatchNotRegexp is MatchRegexp (double negation). + // Fast-path for set matching. + if m.Type == labels.MatchNotRegexp { + setMatches := findSetMatches(m.GetRegexString()) + if len(setMatches) > 0 { + return ix.Postings(m.Name, setMatches...) + } + } + + // Fast-path for MatchNotEqual matching. + // Inverse of a MatchNotEqual is MatchEqual (double negation). + if m.Type == labels.MatchNotEqual { + return ix.Postings(m.Name, m.Value) + } + vals, err := ix.LabelValues(m.Name) if err != nil { return nil, err @@ -777,14 +800,35 @@ func (p *populateWithDelChunkSeriesIterator) Next() bool { if app, err = newChunk.Appender(); err != nil { break } - if hc, ok := p.currChkMeta.Chunk.(*chunkenc.HistogramChunk); ok { + + switch hc := p.currChkMeta.Chunk.(type) { + case *chunkenc.HistogramChunk: newChunk.(*chunkenc.HistogramChunk).SetCounterResetHeader(hc.GetCounterResetHeader()) + case *safeHeadChunk: + if unwrapped, ok := hc.Chunk.(*chunkenc.HistogramChunk); ok { + newChunk.(*chunkenc.HistogramChunk).SetCounterResetHeader(unwrapped.GetCounterResetHeader()) + } else { + err = fmt.Errorf("internal error, could not unwrap safeHeadChunk to histogram chunk: %T", hc.Chunk) + } + default: + err = fmt.Errorf("internal error, unknown chunk type %T when expecting histogram", p.currChkMeta.Chunk) + } + if err != nil { + break } + var h *histogram.Histogram t, h = p.currDelIter.AtHistogram() p.curr.MinTime = t + // Detect missing gauge reset hint. + if h.CounterResetHint == histogram.GaugeType && newChunk.(*chunkenc.HistogramChunk).GetCounterResetHeader() != chunkenc.GaugeType { + err = fmt.Errorf("found gauge histogram in non gauge chunk") + break + } + app.AppendHistogram(t, h) + for vt := p.currDelIter.Next(); vt != chunkenc.ValNone; vt = p.currDelIter.Next() { if vt != chunkenc.ValHistogram { err = fmt.Errorf("found value type %v in histogram chunk", vt) @@ -793,23 +837,37 @@ func (p *populateWithDelChunkSeriesIterator) Next() bool { t, h = p.currDelIter.AtHistogram() // Defend against corrupted chunks. - pI, nI, okToAppend, counterReset := app.(*chunkenc.HistogramAppender).Appendable(h) - if len(pI)+len(nI) > 0 { - err = fmt.Errorf( - "bucket layout has changed unexpectedly: %d positive and %d negative bucket interjections required", - len(pI), len(nI), - ) - break - } - if counterReset { - err = errors.New("detected unexpected counter reset in histogram") - break - } - if !okToAppend { - err = errors.New("unable to append histogram due to unexpected schema change") - break + if h.CounterResetHint == histogram.GaugeType { + pI, nI, bpI, bnI, _, _, okToAppend := app.(*chunkenc.HistogramAppender).AppendableGauge(h) + if !okToAppend { + err = errors.New("unable to append histogram due to unexpected schema change") + break + } + if len(pI)+len(nI)+len(bpI)+len(bnI) > 0 { + err = fmt.Errorf( + "bucket layout has changed unexpectedly: forward %d positive, %d negative, backward %d positive %d negative bucket interjections required", + len(pI), len(nI), len(bpI), len(bnI), + ) + break + } + } else { + pI, nI, okToAppend, counterReset := app.(*chunkenc.HistogramAppender).Appendable(h) + if len(pI)+len(nI) > 0 { + err = fmt.Errorf( + "bucket layout has changed unexpectedly: %d positive and %d negative bucket interjections required", + len(pI), len(nI), + ) + break + } + if counterReset { + err = errors.New("detected unexpected counter reset in histogram") + break + } + if !okToAppend { + err = errors.New("unable to append histogram due to unexpected schema change") + break + } } - app.AppendHistogram(t, h) } case chunkenc.ValFloat: @@ -834,14 +892,35 @@ func (p *populateWithDelChunkSeriesIterator) Next() bool { if app, err = newChunk.Appender(); err != nil { break } - if hc, ok := p.currChkMeta.Chunk.(*chunkenc.FloatHistogramChunk); ok { + + switch hc := p.currChkMeta.Chunk.(type) { + case *chunkenc.FloatHistogramChunk: newChunk.(*chunkenc.FloatHistogramChunk).SetCounterResetHeader(hc.GetCounterResetHeader()) + case *safeHeadChunk: + if unwrapped, ok := hc.Chunk.(*chunkenc.FloatHistogramChunk); ok { + newChunk.(*chunkenc.FloatHistogramChunk).SetCounterResetHeader(unwrapped.GetCounterResetHeader()) + } else { + err = fmt.Errorf("internal error, could not unwrap safeHeadChunk to float histogram chunk: %T", hc.Chunk) + } + default: + err = fmt.Errorf("internal error, unknown chunk type %T when expecting float histogram", p.currChkMeta.Chunk) } + if err != nil { + break + } + var h *histogram.FloatHistogram t, h = p.currDelIter.AtFloatHistogram() p.curr.MinTime = t + // Detect missing gauge reset hint. + if h.CounterResetHint == histogram.GaugeType && newChunk.(*chunkenc.FloatHistogramChunk).GetCounterResetHeader() != chunkenc.GaugeType { + err = fmt.Errorf("found float gauge histogram in non gauge chunk") + break + } + app.AppendFloatHistogram(t, h) + for vt := p.currDelIter.Next(); vt != chunkenc.ValNone; vt = p.currDelIter.Next() { if vt != chunkenc.ValFloatHistogram { err = fmt.Errorf("found value type %v in histogram chunk", vt) @@ -850,21 +929,36 @@ func (p *populateWithDelChunkSeriesIterator) Next() bool { t, h = p.currDelIter.AtFloatHistogram() // Defend against corrupted chunks. - pI, nI, okToAppend, counterReset := app.(*chunkenc.FloatHistogramAppender).Appendable(h) - if len(pI)+len(nI) > 0 { - err = fmt.Errorf( - "bucket layout has changed unexpectedly: %d positive and %d negative bucket interjections required", - len(pI), len(nI), - ) - break - } - if counterReset { - err = errors.New("detected unexpected counter reset in histogram") - break - } - if !okToAppend { - err = errors.New("unable to append histogram due to unexpected schema change") - break + if h.CounterResetHint == histogram.GaugeType { + pI, nI, bpI, bnI, _, _, okToAppend := app.(*chunkenc.FloatHistogramAppender).AppendableGauge(h) + if !okToAppend { + err = errors.New("unable to append histogram due to unexpected schema change") + break + } + if len(pI)+len(nI)+len(bpI)+len(bnI) > 0 { + err = fmt.Errorf( + "bucket layout has changed unexpectedly: forward %d positive, %d negative, backward %d positive %d negative bucket interjections required", + len(pI), len(nI), len(bpI), len(bnI), + ) + break + } + } else { + pI, nI, okToAppend, counterReset := app.(*chunkenc.FloatHistogramAppender).Appendable(h) + if len(pI)+len(nI) > 0 { + err = fmt.Errorf( + "bucket layout has changed unexpectedly: %d positive and %d negative bucket interjections required", + len(pI), len(nI), + ) + break + } + if counterReset { + err = errors.New("detected unexpected counter reset in histogram") + break + } + if !okToAppend { + err = errors.New("unable to append histogram due to unexpected schema change") + break + } } app.AppendFloatHistogram(t, h) diff --git a/tsdb/querier_bench_test.go b/tsdb/querier_bench_test.go index 89758a1d316..c6deaeb44ca 100644 --- a/tsdb/querier_bench_test.go +++ b/tsdb/querier_bench_test.go @@ -113,7 +113,9 @@ func benchmarkPostingsForMatchers(b *testing.B, ir IndexReader) { jXplus := labels.MustNewMatcher(labels.MatchRegexp, "j", "X.+") iCharSet := labels.MustNewMatcher(labels.MatchRegexp, "i", "1[0-9]") iAlternate := labels.MustNewMatcher(labels.MatchRegexp, "i", "(1|2|3|4|5|6|20|55)") + iNotAlternate := labels.MustNewMatcher(labels.MatchNotRegexp, "i", "(1|2|3|4|5|6|20|55)") iXYZ := labels.MustNewMatcher(labels.MatchRegexp, "i", "X|Y|Z") + iNotXYZ := labels.MustNewMatcher(labels.MatchNotRegexp, "i", "X|Y|Z") cases := []struct { name string matchers []*labels.Matcher @@ -124,13 +126,16 @@ func benchmarkPostingsForMatchers(b *testing.B, ir IndexReader) { {`n="X",j="foo"`, []*labels.Matcher{nX, jFoo}}, {`j="foo",n="1"`, []*labels.Matcher{jFoo, n1}}, {`n="1",j!="foo"`, []*labels.Matcher{n1, jNotFoo}}, + {`n="1",i!="2"`, []*labels.Matcher{n1, iNot2}}, {`n="X",j!="foo"`, []*labels.Matcher{nX, jNotFoo}}, {`i=~"1[0-9]",j=~"foo|bar"`, []*labels.Matcher{iCharSet, jFooBar}}, {`j=~"foo|bar"`, []*labels.Matcher{jFooBar}}, {`j=~"XXX|YYY"`, []*labels.Matcher{jXXXYYY}}, {`j=~"X.+"`, []*labels.Matcher{jXplus}}, {`i=~"(1|2|3|4|5|6|20|55)"`, []*labels.Matcher{iAlternate}}, + {`i!~"(1|2|3|4|5|6|20|55)"`, []*labels.Matcher{iNotAlternate}}, {`i=~"X|Y|Z"`, []*labels.Matcher{iXYZ}}, + {`i!~"X|Y|Z"`, []*labels.Matcher{iNotXYZ}}, {`i=~".*"`, []*labels.Matcher{iStar}}, {`i=~"1.*"`, []*labels.Matcher{i1Star}}, {`i=~".*1"`, []*labels.Matcher{iStar1}}, @@ -146,6 +151,7 @@ func benchmarkPostingsForMatchers(b *testing.B, ir IndexReader) { {`n="1",i!="",j=~"X.+"`, []*labels.Matcher{n1, iNotEmpty, jXplus}}, {`n="1",i!="",j=~"XXX|YYY"`, []*labels.Matcher{n1, iNotEmpty, jXXXYYY}}, {`n="1",i=~"X|Y|Z",j="foo"`, []*labels.Matcher{n1, iXYZ, jFoo}}, + {`n="1",i!~"X|Y|Z",j="foo"`, []*labels.Matcher{n1, iNotXYZ, jFoo}}, {`n="1",i=~".+",j="foo"`, []*labels.Matcher{n1, iPlus, jFoo}}, {`n="1",i=~"1.+",j="foo"`, []*labels.Matcher{n1, i1Plus, jFoo}}, {`n="1",i=~".*1.*",j="foo"`, []*labels.Matcher{n1, iStar1Star, jFoo}}, @@ -157,6 +163,8 @@ func benchmarkPostingsForMatchers(b *testing.B, ir IndexReader) { for _, c := range cases { b.Run(c.name, func(b *testing.B) { + b.ReportAllocs() + b.ResetTimer() for i := 0; i < b.N; i++ { _, err := PostingsForMatchers(ir, c.matchers...) require.NoError(b, err) diff --git a/tsdb/querier_test.go b/tsdb/querier_test.go index 5bb99a4539c..e9dd3b75f40 100644 --- a/tsdb/querier_test.go +++ b/tsdb/querier_test.go @@ -29,6 +29,7 @@ import ( "github.com/pkg/errors" "github.com/stretchr/testify/require" + "github.com/prometheus/prometheus/model/histogram" "github.com/prometheus/prometheus/model/labels" "github.com/prometheus/prometheus/storage" "github.com/prometheus/prometheus/tsdb/chunkenc" @@ -501,6 +502,46 @@ func TestBlockQuerier_AgainstHeadWithOpenChunks(t *testing.T) { } } +func TestBlockQuerier_TrimmingDoesNotModifyOriginalTombstoneIntervals(t *testing.T) { + c := blockQuerierTestCase{ + mint: 2, + maxt: 6, + ms: []*labels.Matcher{labels.MustNewMatcher(labels.MatchRegexp, "a", "a")}, + exp: newMockSeriesSet([]storage.Series{ + storage.NewListSeries(labels.FromStrings("a", "a"), + []tsdbutil.Sample{sample{3, 4, nil, nil}, sample{5, 2, nil, nil}, sample{6, 3, nil, nil}}, + ), + storage.NewListSeries(labels.FromStrings("a", "a", "b", "b"), + []tsdbutil.Sample{sample{3, 3, nil, nil}, sample{5, 3, nil, nil}, sample{6, 6, nil, nil}}, + ), + }), + expChks: newMockChunkSeriesSet([]storage.ChunkSeries{ + storage.NewListChunkSeriesFromSamples(labels.FromStrings("a", "a"), + []tsdbutil.Sample{sample{3, 4, nil, nil}}, []tsdbutil.Sample{sample{5, 2, nil, nil}, sample{6, 3, nil, nil}}, + ), + storage.NewListChunkSeriesFromSamples(labels.FromStrings("a", "a", "b", "b"), + []tsdbutil.Sample{sample{3, 3, nil, nil}}, []tsdbutil.Sample{sample{5, 3, nil, nil}, sample{6, 6, nil, nil}}, + ), + }), + } + ir, cr, _, _ := createIdxChkReaders(t, testData) + stones := tombstones.NewMemTombstones() + p, err := ir.Postings("a", "a") + require.NoError(t, err) + refs, err := index.ExpandPostings(p) + require.NoError(t, err) + for _, ref := range refs { + stones.AddInterval(ref, tombstones.Interval{Mint: 1, Maxt: 2}) + } + testBlockQuerier(t, c, ir, cr, stones) + for _, ref := range refs { + intervals, err := stones.Get(ref) + require.NoError(t, err) + // Without copy, the intervals could be [math.MinInt64, 2]. + require.Equal(t, tombstones.Intervals{{Mint: 1, Maxt: 2}}, intervals) + } +} + var testData = []seriesSamples{ { lset: map[string]string{"a": "a"}, @@ -867,6 +908,202 @@ func TestPopulateWithTombSeriesIterators(t *testing.T) { sample{3, 5, nil, nil}, sample{6, 1, nil, nil}, sample{7, 89, nil, nil}, }, }, + { + name: "one histogram chunk", + chks: [][]tsdbutil.Sample{ + { + sample{1, 0, tsdbutil.GenerateTestHistogram(1), nil}, + sample{2, 0, tsdbutil.GenerateTestHistogram(2), nil}, + sample{3, 0, tsdbutil.GenerateTestHistogram(3), nil}, + sample{6, 0, tsdbutil.GenerateTestHistogram(6), nil}, + }, + }, + expected: []tsdbutil.Sample{ + sample{1, 0, tsdbutil.GenerateTestHistogram(1), nil}, + sample{2, 0, tsdbutil.SetHistogramNotCounterReset(tsdbutil.GenerateTestHistogram(2)), nil}, + sample{3, 0, tsdbutil.SetHistogramNotCounterReset(tsdbutil.GenerateTestHistogram(3)), nil}, + sample{6, 0, tsdbutil.SetHistogramNotCounterReset(tsdbutil.GenerateTestHistogram(6)), nil}, + }, + expectedChks: []chunks.Meta{ + tsdbutil.ChunkFromSamples([]tsdbutil.Sample{ + sample{1, 0, tsdbutil.GenerateTestHistogram(1), nil}, + sample{2, 0, tsdbutil.SetHistogramNotCounterReset(tsdbutil.GenerateTestHistogram(2)), nil}, + sample{3, 0, tsdbutil.SetHistogramNotCounterReset(tsdbutil.GenerateTestHistogram(3)), nil}, + sample{6, 0, tsdbutil.SetHistogramNotCounterReset(tsdbutil.GenerateTestHistogram(6)), nil}, + }), + }, + }, + { + name: "one histogram chunk intersect with deletion interval", + chks: [][]tsdbutil.Sample{ + { + sample{1, 0, tsdbutil.GenerateTestHistogram(1), nil}, + sample{2, 0, tsdbutil.GenerateTestHistogram(2), nil}, + sample{3, 0, tsdbutil.GenerateTestHistogram(3), nil}, + sample{6, 0, tsdbutil.GenerateTestHistogram(6), nil}, + }, + }, + intervals: tombstones.Intervals{{Mint: 5, Maxt: 20}}, + expected: []tsdbutil.Sample{ + sample{1, 0, tsdbutil.GenerateTestHistogram(1), nil}, + sample{2, 0, tsdbutil.SetHistogramNotCounterReset(tsdbutil.GenerateTestHistogram(2)), nil}, + sample{3, 0, tsdbutil.SetHistogramNotCounterReset(tsdbutil.GenerateTestHistogram(3)), nil}, + }, + expectedChks: []chunks.Meta{ + tsdbutil.ChunkFromSamples([]tsdbutil.Sample{ + sample{1, 0, tsdbutil.GenerateTestHistogram(1), nil}, + sample{2, 0, tsdbutil.SetHistogramNotCounterReset(tsdbutil.GenerateTestHistogram(2)), nil}, + sample{3, 0, tsdbutil.SetHistogramNotCounterReset(tsdbutil.GenerateTestHistogram(3)), nil}, + }), + }, + }, + { + name: "one float histogram chunk", + chks: [][]tsdbutil.Sample{ + { + sample{1, 0, nil, tsdbutil.GenerateTestFloatHistogram(1)}, + sample{2, 0, nil, tsdbutil.GenerateTestFloatHistogram(2)}, + sample{3, 0, nil, tsdbutil.GenerateTestFloatHistogram(3)}, + sample{6, 0, nil, tsdbutil.GenerateTestFloatHistogram(6)}, + }, + }, + expected: []tsdbutil.Sample{ + sample{1, 0, nil, tsdbutil.GenerateTestFloatHistogram(1)}, + sample{2, 0, nil, tsdbutil.SetFloatHistogramNotCounterReset(tsdbutil.GenerateTestFloatHistogram(2))}, + sample{3, 0, nil, tsdbutil.SetFloatHistogramNotCounterReset(tsdbutil.GenerateTestFloatHistogram(3))}, + sample{6, 0, nil, tsdbutil.SetFloatHistogramNotCounterReset(tsdbutil.GenerateTestFloatHistogram(6))}, + }, + expectedChks: []chunks.Meta{ + tsdbutil.ChunkFromSamples([]tsdbutil.Sample{ + sample{1, 0, nil, tsdbutil.GenerateTestFloatHistogram(1)}, + sample{2, 0, nil, tsdbutil.SetFloatHistogramNotCounterReset(tsdbutil.GenerateTestFloatHistogram(2))}, + sample{3, 0, nil, tsdbutil.SetFloatHistogramNotCounterReset(tsdbutil.GenerateTestFloatHistogram(3))}, + sample{6, 0, nil, tsdbutil.SetFloatHistogramNotCounterReset(tsdbutil.GenerateTestFloatHistogram(6))}, + }), + }, + }, + { + name: "one float histogram chunk intersect with deletion interval", + chks: [][]tsdbutil.Sample{ + { + sample{1, 0, nil, tsdbutil.GenerateTestFloatHistogram(1)}, + sample{2, 0, nil, tsdbutil.GenerateTestFloatHistogram(2)}, + sample{3, 0, nil, tsdbutil.GenerateTestFloatHistogram(3)}, + sample{6, 0, nil, tsdbutil.GenerateTestFloatHistogram(6)}, + }, + }, + intervals: tombstones.Intervals{{Mint: 5, Maxt: 20}}, + expected: []tsdbutil.Sample{ + sample{1, 0, nil, tsdbutil.GenerateTestFloatHistogram(1)}, + sample{2, 0, nil, tsdbutil.SetFloatHistogramNotCounterReset(tsdbutil.GenerateTestFloatHistogram(2))}, + sample{3, 0, nil, tsdbutil.SetFloatHistogramNotCounterReset(tsdbutil.GenerateTestFloatHistogram(3))}, + }, + expectedChks: []chunks.Meta{ + tsdbutil.ChunkFromSamples([]tsdbutil.Sample{ + sample{1, 0, nil, tsdbutil.GenerateTestFloatHistogram(1)}, + sample{2, 0, nil, tsdbutil.SetFloatHistogramNotCounterReset(tsdbutil.GenerateTestFloatHistogram(2))}, + sample{3, 0, nil, tsdbutil.SetFloatHistogramNotCounterReset(tsdbutil.GenerateTestFloatHistogram(3))}, + }), + }, + }, + { + name: "one gauge histogram chunk", + chks: [][]tsdbutil.Sample{ + { + sample{1, 0, tsdbutil.GenerateTestGaugeHistogram(1), nil}, + sample{2, 0, tsdbutil.GenerateTestGaugeHistogram(2), nil}, + sample{3, 0, tsdbutil.GenerateTestGaugeHistogram(3), nil}, + sample{6, 0, tsdbutil.GenerateTestGaugeHistogram(6), nil}, + }, + }, + expected: []tsdbutil.Sample{ + sample{1, 0, tsdbutil.GenerateTestGaugeHistogram(1), nil}, + sample{2, 0, tsdbutil.GenerateTestGaugeHistogram(2), nil}, + sample{3, 0, tsdbutil.GenerateTestGaugeHistogram(3), nil}, + sample{6, 0, tsdbutil.GenerateTestGaugeHistogram(6), nil}, + }, + expectedChks: []chunks.Meta{ + tsdbutil.ChunkFromSamples([]tsdbutil.Sample{ + sample{1, 0, tsdbutil.GenerateTestGaugeHistogram(1), nil}, + sample{2, 0, tsdbutil.GenerateTestGaugeHistogram(2), nil}, + sample{3, 0, tsdbutil.GenerateTestGaugeHistogram(3), nil}, + sample{6, 0, tsdbutil.GenerateTestGaugeHistogram(6), nil}, + }), + }, + }, + { + name: "one gauge histogram chunk intersect with deletion interval", + chks: [][]tsdbutil.Sample{ + { + sample{1, 0, tsdbutil.GenerateTestGaugeHistogram(1), nil}, + sample{2, 0, tsdbutil.GenerateTestGaugeHistogram(2), nil}, + sample{3, 0, tsdbutil.GenerateTestGaugeHistogram(3), nil}, + sample{6, 0, tsdbutil.GenerateTestGaugeHistogram(6), nil}, + }, + }, + intervals: tombstones.Intervals{{Mint: 5, Maxt: 20}}, + expected: []tsdbutil.Sample{ + sample{1, 0, tsdbutil.GenerateTestGaugeHistogram(1), nil}, + sample{2, 0, tsdbutil.GenerateTestGaugeHistogram(2), nil}, + sample{3, 0, tsdbutil.GenerateTestGaugeHistogram(3), nil}, + }, + expectedChks: []chunks.Meta{ + tsdbutil.ChunkFromSamples([]tsdbutil.Sample{ + sample{1, 0, tsdbutil.GenerateTestGaugeHistogram(1), nil}, + sample{2, 0, tsdbutil.GenerateTestGaugeHistogram(2), nil}, + sample{3, 0, tsdbutil.GenerateTestGaugeHistogram(3), nil}, + }), + }, + }, + { + name: "one gauge float histogram", + chks: [][]tsdbutil.Sample{ + { + sample{1, 0, nil, tsdbutil.GenerateTestGaugeFloatHistogram(1)}, + sample{2, 0, nil, tsdbutil.GenerateTestGaugeFloatHistogram(2)}, + sample{3, 0, nil, tsdbutil.GenerateTestGaugeFloatHistogram(3)}, + sample{6, 0, nil, tsdbutil.GenerateTestGaugeFloatHistogram(6)}, + }, + }, + expected: []tsdbutil.Sample{ + sample{1, 0, nil, tsdbutil.GenerateTestGaugeFloatHistogram(1)}, + sample{2, 0, nil, tsdbutil.GenerateTestGaugeFloatHistogram(2)}, + sample{3, 0, nil, tsdbutil.GenerateTestGaugeFloatHistogram(3)}, + sample{6, 0, nil, tsdbutil.GenerateTestGaugeFloatHistogram(6)}, + }, + expectedChks: []chunks.Meta{ + tsdbutil.ChunkFromSamples([]tsdbutil.Sample{ + sample{1, 0, nil, tsdbutil.GenerateTestGaugeFloatHistogram(1)}, + sample{2, 0, nil, tsdbutil.GenerateTestGaugeFloatHistogram(2)}, + sample{3, 0, nil, tsdbutil.GenerateTestGaugeFloatHistogram(3)}, + sample{6, 0, nil, tsdbutil.GenerateTestGaugeFloatHistogram(6)}, + }), + }, + }, + { + name: "one gauge float histogram chunk intersect with deletion interval", + chks: [][]tsdbutil.Sample{ + { + sample{1, 0, nil, tsdbutil.GenerateTestGaugeFloatHistogram(1)}, + sample{2, 0, nil, tsdbutil.GenerateTestGaugeFloatHistogram(2)}, + sample{3, 0, nil, tsdbutil.GenerateTestGaugeFloatHistogram(3)}, + sample{6, 0, nil, tsdbutil.GenerateTestGaugeFloatHistogram(6)}, + }, + }, + intervals: tombstones.Intervals{{Mint: 5, Maxt: 20}}, + expected: []tsdbutil.Sample{ + sample{1, 0, nil, tsdbutil.GenerateTestGaugeFloatHistogram(1)}, + sample{2, 0, nil, tsdbutil.GenerateTestGaugeFloatHistogram(2)}, + sample{3, 0, nil, tsdbutil.GenerateTestGaugeFloatHistogram(3)}, + }, + expectedChks: []chunks.Meta{ + tsdbutil.ChunkFromSamples([]tsdbutil.Sample{ + sample{1, 0, nil, tsdbutil.GenerateTestGaugeFloatHistogram(1)}, + sample{2, 0, nil, tsdbutil.GenerateTestGaugeFloatHistogram(2)}, + sample{3, 0, nil, tsdbutil.GenerateTestGaugeFloatHistogram(3)}, + }), + }, + }, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -1801,6 +2038,25 @@ func TestPostingsForMatchers(t *testing.T) { labels.FromStrings("n", "2.5"), }, }, + { + matchers: []*labels.Matcher{labels.MustNewMatcher(labels.MatchNotRegexp, "n", "1")}, + exp: []labels.Labels{ + labels.FromStrings("n", "2"), + labels.FromStrings("n", "2.5"), + }, + }, + { + matchers: []*labels.Matcher{labels.MustNewMatcher(labels.MatchNotRegexp, "n", "1|2.5")}, + exp: []labels.Labels{ + labels.FromStrings("n", "2"), + }, + }, + { + matchers: []*labels.Matcher{labels.MustNewMatcher(labels.MatchNotRegexp, "n", "(1|2.5)")}, + exp: []labels.Labels{ + labels.FromStrings("n", "2"), + }, + }, { matchers: []*labels.Matcher{labels.MustNewMatcher(labels.MatchEqual, "n", "1"), labels.MustNewMatcher(labels.MatchNotRegexp, "i", "^a$")}, exp: []labels.Labels{ @@ -1862,6 +2118,13 @@ func TestPostingsForMatchers(t *testing.T) { labels.FromStrings("n", "1", "i", "b"), }, }, + { + matchers: []*labels.Matcher{labels.MustNewMatcher(labels.MatchRegexp, "i", "(a|b)")}, + exp: []labels.Labels{ + labels.FromStrings("n", "1", "i", "a"), + labels.FromStrings("n", "1", "i", "b"), + }, + }, { matchers: []*labels.Matcher{labels.MustNewMatcher(labels.MatchRegexp, "n", "x1|2")}, exp: []labels.Labels{ @@ -1884,33 +2147,50 @@ func TestPostingsForMatchers(t *testing.T) { labels.FromStrings("n", "2.5"), }, }, + { + matchers: []*labels.Matcher{labels.MustNewMatcher(labels.MatchRegexp, "i", "(c||d)")}, + exp: []labels.Labels{ + labels.FromStrings("n", "1"), + labels.FromStrings("n", "2"), + labels.FromStrings("n", "2.5"), + }, + }, } ir, err := h.Index() require.NoError(t, err) for _, c := range cases { - exp := map[string]struct{}{} - for _, l := range c.exp { - exp[l.String()] = struct{}{} + name := "" + for i, matcher := range c.matchers { + if i > 0 { + name += "," + } + name += matcher.String() } - p, err := PostingsForMatchers(ir, c.matchers...) - require.NoError(t, err) + t.Run(name, func(t *testing.T) { + exp := map[string]struct{}{} + for _, l := range c.exp { + exp[l.String()] = struct{}{} + } + p, err := PostingsForMatchers(ir, c.matchers...) + require.NoError(t, err) - var builder labels.ScratchBuilder - for p.Next() { - require.NoError(t, ir.Series(p.At(), &builder, &[]chunks.Meta{})) - lbls := builder.Labels() - if _, ok := exp[lbls.String()]; !ok { - t.Errorf("Evaluating %v, unexpected result %s", c.matchers, lbls.String()) - } else { - delete(exp, lbls.String()) + var builder labels.ScratchBuilder + for p.Next() { + require.NoError(t, ir.Series(p.At(), &builder, &[]chunks.Meta{})) + lbls := builder.Labels() + if _, ok := exp[lbls.String()]; !ok { + t.Errorf("Evaluating %v, unexpected result %s", c.matchers, lbls.String()) + } else { + delete(exp, lbls.String()) + } } - } - require.NoError(t, p.Err()) - if len(exp) != 0 { - t.Errorf("Evaluating %v, missing results %+v", c.matchers, exp) - } + require.NoError(t, p.Err()) + if len(exp) != 0 { + t.Errorf("Evaluating %v, missing results %+v", c.matchers, exp) + } + }) } } @@ -2349,3 +2629,80 @@ func BenchmarkHeadQuerier(b *testing.B) { require.NoError(b, ss.Err()) } } + +// This is a regression test for the case where gauge histograms were not handled by +// populateWithDelChunkSeriesIterator correctly. +func TestQueryWithDeletedHistograms(t *testing.T) { + testcases := map[string]func(int) (*histogram.Histogram, *histogram.FloatHistogram){ + "intCounter": func(i int) (*histogram.Histogram, *histogram.FloatHistogram) { + return tsdbutil.GenerateTestHistogram(i), nil + }, + "intgauge": func(i int) (*histogram.Histogram, *histogram.FloatHistogram) { + return tsdbutil.GenerateTestGaugeHistogram(rand.Int() % 1000), nil + }, + "floatCounter": func(i int) (*histogram.Histogram, *histogram.FloatHistogram) { + return nil, tsdbutil.GenerateTestFloatHistogram(i) + }, + "floatGauge": func(i int) (*histogram.Histogram, *histogram.FloatHistogram) { + return nil, tsdbutil.GenerateTestGaugeFloatHistogram(rand.Int() % 1000) + }, + } + + for name, tc := range testcases { + t.Run(name, func(t *testing.T) { + db := openTestDB(t, nil, nil) + defer func() { + require.NoError(t, db.Close()) + }() + + db.EnableNativeHistograms() + appender := db.Appender(context.Background()) + + var ( + err error + seriesRef storage.SeriesRef + ) + lbs := labels.FromStrings("__name__", "test", "type", name) + + for i := 0; i < 100; i++ { + h, fh := tc(i) + seriesRef, err = appender.AppendHistogram(seriesRef, lbs, int64(i), h, fh) + require.NoError(t, err) + } + + err = appender.Commit() + require.NoError(t, err) + + matcher, err := labels.NewMatcher(labels.MatchEqual, "__name__", "test") + require.NoError(t, err) + + // Delete the last 20. + err = db.Delete(80, 100, matcher) + require.NoError(t, err) + + chunkQuerier, err := db.ChunkQuerier(context.Background(), 0, 100) + require.NoError(t, err) + + css := chunkQuerier.Select(false, nil, matcher) + + seriesCount := 0 + for css.Next() { + seriesCount++ + series := css.At() + + sampleCount := 0 + it := series.Iterator(nil) + for it.Next() { + chk := it.At() + for cit := chk.Chunk.Iterator(nil); cit.Next() != chunkenc.ValNone; { + sampleCount++ + } + } + require.NoError(t, it.Err()) + require.Equal(t, 80, sampleCount) + } + require.NoError(t, css.Err()) + require.Equal(t, 1, seriesCount) + }) + } +} diff --git a/tsdb/tombstones/tombstones.go b/tsdb/tombstones/tombstones.go index a52e1caa973..94daf519533 100644 --- a/tsdb/tombstones/tombstones.go +++ b/tsdb/tombstones/tombstones.go @@ -18,6 +18,7 @@ import ( "fmt" "hash" "hash/crc32" + "math" "os" "path/filepath" "sort" @@ -252,7 +253,14 @@ func NewTestMemTombstones(intervals []Intervals) *MemTombstones { func (t *MemTombstones) Get(ref storage.SeriesRef) (Intervals, error) { t.mtx.RLock() defer t.mtx.RUnlock() - return t.intvlGroups[ref], nil + intervals, ok := t.intvlGroups[ref] + if !ok { + return nil, nil + } + // Make a copy to avoid race. + res := make(Intervals, len(intervals)) + copy(res, intervals) + return res, nil } func (t *MemTombstones) DeleteTombstones(refs map[storage.SeriesRef]struct{}) { @@ -349,17 +357,23 @@ func (in Intervals) Add(n Interval) Intervals { // Find min and max indexes of intervals that overlap with the new interval. // Intervals are closed [t1, t2] and t is discreet, so if neighbour intervals are 1 step difference // to the new one, we can merge those together. - mini := sort.Search(len(in), func(i int) bool { return in[i].Maxt >= n.Mint-1 }) - if mini == len(in) { - return append(in, n) + mini := 0 + if n.Mint != math.MinInt64 { // Avoid overflow. + mini = sort.Search(len(in), func(i int) bool { return in[i].Maxt >= n.Mint-1 }) + if mini == len(in) { + return append(in, n) + } } - maxi := sort.Search(len(in)-mini, func(i int) bool { return in[mini+i].Mint > n.Maxt+1 }) - if maxi == 0 { - if mini == 0 { - return append(Intervals{n}, in...) + maxi := len(in) + if n.Maxt != math.MaxInt64 { // Avoid overflow. + maxi = sort.Search(len(in)-mini, func(i int) bool { return in[mini+i].Mint > n.Maxt+1 }) + if maxi == 0 { + if mini == 0 { + return append(Intervals{n}, in...) + } + return append(in[:mini], append(Intervals{n}, in[mini:]...)...) } - return append(in[:mini], append(Intervals{n}, in[mini:]...)...) } if n.Mint < in[mini].Mint { diff --git a/tsdb/tombstones/tombstones_test.go b/tsdb/tombstones/tombstones_test.go index ffe25b0be1f..36c9f1c1e3f 100644 --- a/tsdb/tombstones/tombstones_test.go +++ b/tsdb/tombstones/tombstones_test.go @@ -81,6 +81,22 @@ func TestDeletingTombstones(t *testing.T) { require.Empty(t, intervals) } +func TestTombstonesGetWithCopy(t *testing.T) { + stones := NewMemTombstones() + stones.AddInterval(1, Intervals{{Mint: 1, Maxt: 2}, {Mint: 7, Maxt: 8}, {Mint: 11, Maxt: 12}}...) + + intervals0, err := stones.Get(1) + require.NoError(t, err) + require.Equal(t, Intervals{{Mint: 1, Maxt: 2}, {Mint: 7, Maxt: 8}, {Mint: 11, Maxt: 12}}, intervals0) + intervals1 := intervals0.Add(Interval{Mint: 4, Maxt: 6}) + require.Equal(t, Intervals{{Mint: 1, Maxt: 2}, {Mint: 4, Maxt: 8}, {Mint: 11, Maxt: 12}}, intervals0) // Original slice changed. + require.Equal(t, Intervals{{Mint: 1, Maxt: 2}, {Mint: 4, Maxt: 8}, {Mint: 11, Maxt: 12}}, intervals1) + + intervals2, err := stones.Get(1) + require.NoError(t, err) + require.Equal(t, Intervals{{Mint: 1, Maxt: 2}, {Mint: 7, Maxt: 8}, {Mint: 11, Maxt: 12}}, intervals2) +} + func TestTruncateBefore(t *testing.T) { cases := []struct { before Intervals @@ -210,6 +226,26 @@ func TestAddingNewIntervals(t *testing.T) { new: Interval{math.MinInt64, 10}, exp: Intervals{{math.MinInt64, math.MaxInt64}}, }, + { + exist: Intervals{{9, 10}}, + new: Interval{math.MinInt64, 7}, + exp: Intervals{{math.MinInt64, 7}, {9, 10}}, + }, + { + exist: Intervals{{9, 10}}, + new: Interval{12, math.MaxInt64}, + exp: Intervals{{9, 10}, {12, math.MaxInt64}}, + }, + { + exist: Intervals{{9, 10}}, + new: Interval{math.MinInt64, 8}, + exp: Intervals{{math.MinInt64, 10}}, + }, + { + exist: Intervals{{9, 10}}, + new: Interval{11, math.MaxInt64}, + exp: Intervals{{9, math.MaxInt64}}, + }, } for _, c := range cases { diff --git a/tsdb/tsdbutil/chunks.go b/tsdb/tsdbutil/chunks.go index 02a7dd61982..6e57016fec3 100644 --- a/tsdb/tsdbutil/chunks.go +++ b/tsdb/tsdbutil/chunks.go @@ -71,9 +71,19 @@ func ChunkFromSamplesGeneric(s Samples) chunks.Meta { case chunkenc.ValFloat: ca.Append(s.Get(i).T(), s.Get(i).F()) case chunkenc.ValHistogram: - ca.AppendHistogram(s.Get(i).T(), s.Get(i).H()) + h := s.Get(i).H() + ca.AppendHistogram(s.Get(i).T(), h) + if i == 0 && h.CounterResetHint == histogram.GaugeType { + hc := c.(*chunkenc.HistogramChunk) + hc.SetCounterResetHeader(chunkenc.GaugeType) + } case chunkenc.ValFloatHistogram: - ca.AppendFloatHistogram(s.Get(i).T(), s.Get(i).FH()) + fh := s.Get(i).FH() + ca.AppendFloatHistogram(s.Get(i).T(), fh) + if i == 0 && fh.CounterResetHint == histogram.GaugeType { + hc := c.(*chunkenc.FloatHistogramChunk) + hc.SetCounterResetHeader(chunkenc.GaugeType) + } default: panic(fmt.Sprintf("unknown sample type %s", sampleType.String())) } diff --git a/tsdb/tsdbutil/histogram.go b/tsdb/tsdbutil/histogram.go index 3c276c84119..2145034e197 100644 --- a/tsdb/tsdbutil/histogram.go +++ b/tsdb/tsdbutil/histogram.go @@ -108,3 +108,13 @@ func GenerateTestGaugeFloatHistogram(i int) *histogram.FloatHistogram { h.CounterResetHint = histogram.GaugeType return h } + +func SetHistogramNotCounterReset(h *histogram.Histogram) *histogram.Histogram { + h.CounterResetHint = histogram.NotCounterReset + return h +} + +func SetFloatHistogramNotCounterReset(h *histogram.FloatHistogram) *histogram.FloatHistogram { + h.CounterResetHint = histogram.NotCounterReset + return h +} diff --git a/tsdb/wlog/watcher.go b/tsdb/wlog/watcher.go index b0c17dcbac4..221e9607ca1 100644 --- a/tsdb/wlog/watcher.go +++ b/tsdb/wlog/watcher.go @@ -18,7 +18,7 @@ import ( "io" "math" "os" - "path" + "path/filepath" "strconv" "strings" "time" @@ -34,12 +34,16 @@ import ( ) const ( - readPeriod = 10 * time.Millisecond checkpointPeriod = 5 * time.Second segmentCheckPeriod = 100 * time.Millisecond consumer = "consumer" ) +var ( + ErrIgnorable = errors.New("ignore me") + readTimeout = 15 * time.Second +) + // WriteTo is an interface used by the Watcher to send the samples it's read // from the WAL on to somewhere else. Functions will be called concurrently // and it is left to the implementer to make sure they are safe. @@ -61,11 +65,17 @@ type WriteTo interface { SeriesReset(int) } +// Used to notifier the watcher that data has been written so that it can read. +type WriteNotified interface { + Notify() +} + type WatcherMetrics struct { recordsRead *prometheus.CounterVec recordDecodeFails *prometheus.CounterVec samplesSentPreTailing *prometheus.CounterVec currentSegment *prometheus.GaugeVec + notificationsSkipped *prometheus.CounterVec } // Watcher watches the TSDB WAL for a given WriteTo. @@ -88,9 +98,11 @@ type Watcher struct { recordDecodeFailsMetric prometheus.Counter samplesSentPreTailing prometheus.Counter currentSegmentMetric prometheus.Gauge + notificationsSkipped prometheus.Counter - quit chan struct{} - done chan struct{} + readNotify chan struct{} + quit chan struct{} + done chan struct{} // For testing, stop when we hit this segment. MaxSegment int @@ -134,6 +146,15 @@ func NewWatcherMetrics(reg prometheus.Registerer) *WatcherMetrics { }, []string{consumer}, ), + notificationsSkipped: prometheus.NewCounterVec( + prometheus.CounterOpts{ + Namespace: "prometheus", + Subsystem: "wal_watcher", + Name: "notifications_skipped_total", + Help: "The number of WAL write notifications that the Watcher has skipped due to already being in a WAL read routine.", + }, + []string{consumer}, + ), } if reg != nil { @@ -141,6 +162,7 @@ func NewWatcherMetrics(reg prometheus.Registerer) *WatcherMetrics { reg.MustRegister(m.recordDecodeFails) reg.MustRegister(m.samplesSentPreTailing) reg.MustRegister(m.currentSegment) + reg.MustRegister(m.notificationsSkipped) } return m @@ -156,18 +178,30 @@ func NewWatcher(metrics *WatcherMetrics, readerMetrics *LiveReaderMetrics, logge writer: writer, metrics: metrics, readerMetrics: readerMetrics, - walDir: path.Join(dir, "wal"), + walDir: filepath.Join(dir, "wal"), name: name, sendExemplars: sendExemplars, sendHistograms: sendHistograms, - quit: make(chan struct{}), - done: make(chan struct{}), + readNotify: make(chan struct{}), + quit: make(chan struct{}), + done: make(chan struct{}), MaxSegment: -1, } } +func (w *Watcher) Notify() { + select { + case w.readNotify <- struct{}{}: + return + default: // default so we can exit + // we don't need a buffered channel or any buffering since + // for each notification it recv's the watcher will read until EOF + w.notificationsSkipped.Inc() + } +} + func (w *Watcher) setMetrics() { // Setup the WAL Watchers metrics. We do this here rather than in the // constructor because of the ordering of creating Queue Managers's, @@ -177,6 +211,8 @@ func (w *Watcher) setMetrics() { w.recordDecodeFailsMetric = w.metrics.recordDecodeFails.WithLabelValues(w.name) w.samplesSentPreTailing = w.metrics.samplesSentPreTailing.WithLabelValues(w.name) w.currentSegmentMetric = w.metrics.currentSegment.WithLabelValues(w.name) + w.notificationsSkipped = w.metrics.notificationsSkipped.WithLabelValues(w.name) + } } @@ -262,7 +298,7 @@ func (w *Watcher) Run() error { // On start, after reading the existing WAL for series records, we have a pointer to what is the latest segment. // On subsequent calls to this function, currentSegment will have been incremented and we should open that segment. - if err := w.watch(currentSegment, currentSegment >= lastSegment); err != nil { + if err := w.watch(currentSegment, currentSegment >= lastSegment); err != nil && !errors.Is(err, ErrIgnorable) { return err } @@ -330,6 +366,26 @@ func (w *Watcher) segments(dir string) ([]int, error) { return refs, nil } +func (w *Watcher) readAndHandleError(r *LiveReader, segmentNum int, tail bool, size int64) error { + err := w.readSegment(r, segmentNum, tail) + + // Ignore all errors reading to end of segment whilst replaying the WAL. + if !tail { + if err != nil && errors.Cause(err) != io.EOF { + level.Warn(w.logger).Log("msg", "Ignoring error reading to end of segment, may have dropped data", "segment", segmentNum, "err", err) + } else if r.Offset() != size { + level.Warn(w.logger).Log("msg", "Expected to have read whole segment, may have dropped data", "segment", segmentNum, "read", r.Offset(), "size", size) + } + return ErrIgnorable + } + + // Otherwise, when we are tailing, non-EOFs are fatal. + if errors.Cause(err) != io.EOF { + return err + } + return nil +} + // Use tail true to indicate that the reader is currently on a segment that is // actively being written to. If false, assume it's a full segment and we're // replaying it on start to cache the series records. @@ -342,7 +398,7 @@ func (w *Watcher) watch(segmentNum int, tail bool) error { reader := NewLiveReader(w.logger, w.readerMetrics, segment) - readTicker := time.NewTicker(readPeriod) + readTicker := time.NewTicker(readTimeout) defer readTicker.Stop() checkpointTicker := time.NewTicker(checkpointPeriod) @@ -400,7 +456,6 @@ func (w *Watcher) watch(segmentNum int, tail bool) error { if last <= segmentNum { continue } - err = w.readSegment(reader, segmentNum, tail) // Ignore errors reading to end of segment whilst replaying the WAL. @@ -421,24 +476,23 @@ func (w *Watcher) watch(segmentNum int, tail bool) error { return nil + // we haven't read due to a notification in quite some time, try reading anyways case <-readTicker.C: - err = w.readSegment(reader, segmentNum, tail) - - // Ignore all errors reading to end of segment whilst replaying the WAL. - if !tail { - switch { - case err != nil && errors.Cause(err) != io.EOF: - level.Warn(w.logger).Log("msg", "Ignoring error reading to end of segment, may have dropped data", "segment", segmentNum, "err", err) - case reader.Offset() != size: - level.Warn(w.logger).Log("msg", "Expected to have read whole segment, may have dropped data", "segment", segmentNum, "read", reader.Offset(), "size", size) - } - return nil + level.Debug(w.logger).Log("msg", "Watcher is reading the WAL due to timeout, haven't received any write notifications recently", "timeout", readTimeout) + err := w.readAndHandleError(reader, segmentNum, tail, size) + if err != nil { + return err } + // still want to reset the ticker so we don't read too often + readTicker.Reset(readTimeout) - // Otherwise, when we are tailing, non-EOFs are fatal. - if errors.Cause(err) != io.EOF { + case <-w.readNotify: + err := w.readAndHandleError(reader, segmentNum, tail, size) + if err != nil { return err } + // still want to reset the ticker so we don't read too often + readTicker.Reset(readTimeout) } } } @@ -691,7 +745,7 @@ func (w *Watcher) readCheckpoint(checkpointDir string, readFn segmentReadFn) err func checkpointNum(dir string) (int, error) { // Checkpoint dir names are in the format checkpoint.000001 // dir may contain a hidden directory, so only check the base directory - chunks := strings.Split(path.Base(dir), ".") + chunks := strings.Split(filepath.Base(dir), ".") if len(chunks) != 2 { return 0, errors.Errorf("invalid checkpoint dir string: %s", dir) } diff --git a/tsdb/wlog/watcher_test.go b/tsdb/wlog/watcher_test.go index 530d0ffb4a4..94b6a92d12f 100644 --- a/tsdb/wlog/watcher_test.go +++ b/tsdb/wlog/watcher_test.go @@ -104,7 +104,7 @@ func (wtm *writeToMock) SeriesReset(index int) { } } -func (wtm *writeToMock) checkNumLabels() int { +func (wtm *writeToMock) checkNumSeries() int { wtm.seriesLock.Lock() defer wtm.seriesLock.Unlock() return len(wtm.seriesSegmentIndexes) @@ -230,9 +230,9 @@ func TestTailSamples(t *testing.T) { expectedExemplars := seriesCount * exemplarsCount expectedHistograms := seriesCount * histogramsCount retry(t, defaultRetryInterval, defaultRetries, func() bool { - return wt.checkNumLabels() >= expectedSeries + return wt.checkNumSeries() >= expectedSeries }) - require.Equal(t, expectedSeries, wt.checkNumLabels(), "did not receive the expected number of series") + require.Equal(t, expectedSeries, wt.checkNumSeries(), "did not receive the expected number of series") require.Equal(t, expectedSamples, wt.samplesAppended, "did not receive the expected number of samples") require.Equal(t, expectedExemplars, wt.exemplarsAppended, "did not receive the expected number of exemplars") require.Equal(t, expectedHistograms, wt.histogramsAppended, "did not receive the expected number of histograms") @@ -290,7 +290,7 @@ func TestReadToEndNoCheckpoint(t *testing.T) { } } require.NoError(t, w.Log(recs...)) - + readTimeout = time.Second _, _, err = Segments(w.Dir()) require.NoError(t, err) @@ -299,11 +299,10 @@ func TestReadToEndNoCheckpoint(t *testing.T) { go watcher.Start() expected := seriesCount - retry(t, defaultRetryInterval, defaultRetries, func() bool { - return wt.checkNumLabels() >= expected - }) + require.Eventually(t, func() bool { + return wt.checkNumSeries() == expected + }, 20*time.Second, 1*time.Second) watcher.Stop() - require.Equal(t, expected, wt.checkNumLabels()) }) } } @@ -383,16 +382,17 @@ func TestReadToEndWithCheckpoint(t *testing.T) { _, _, err = Segments(w.Dir()) require.NoError(t, err) + readTimeout = time.Second wt := newWriteToMock() watcher := NewWatcher(wMetrics, nil, nil, "", wt, dir, false, false) go watcher.Start() expected := seriesCount * 2 - retry(t, defaultRetryInterval, defaultRetries, func() bool { - return wt.checkNumLabels() >= expected - }) + + require.Eventually(t, func() bool { + return wt.checkNumSeries() == expected + }, 10*time.Second, 1*time.Second) watcher.Stop() - require.Equal(t, expected, wt.checkNumLabels()) }) } } @@ -460,10 +460,10 @@ func TestReadCheckpoint(t *testing.T) { expectedSeries := seriesCount retry(t, defaultRetryInterval, defaultRetries, func() bool { - return wt.checkNumLabels() >= expectedSeries + return wt.checkNumSeries() >= expectedSeries }) watcher.Stop() - require.Equal(t, expectedSeries, wt.checkNumLabels()) + require.Equal(t, expectedSeries, wt.checkNumSeries()) }) } } @@ -595,6 +595,7 @@ func TestCheckpointSeriesReset(t *testing.T) { _, _, err = Segments(w.Dir()) require.NoError(t, err) + readTimeout = time.Second wt := newWriteToMock() watcher := NewWatcher(wMetrics, nil, nil, "", wt, dir, false, false) watcher.MaxSegment = -1 @@ -602,9 +603,11 @@ func TestCheckpointSeriesReset(t *testing.T) { expected := seriesCount retry(t, defaultRetryInterval, defaultRetries, func() bool { - return wt.checkNumLabels() >= expected + return wt.checkNumSeries() >= expected }) - require.Equal(t, seriesCount, wt.checkNumLabels()) + require.Eventually(t, func() bool { + return wt.checkNumSeries() == seriesCount + }, 10*time.Second, 1*time.Second) _, err = Checkpoint(log.NewNopLogger(), w, 2, 4, func(x chunks.HeadSeriesRef) bool { return true }, 0) require.NoError(t, err) @@ -621,7 +624,9 @@ func TestCheckpointSeriesReset(t *testing.T) { // If you modify the checkpoint and truncate segment #'s run the test to see how // many series records you end up with and change the last Equals check accordingly // or modify the Equals to Assert(len(wt.seriesLabels) < seriesCount*10) - require.Equal(t, tc.segments, wt.checkNumLabels()) + require.Eventually(t, func() bool { + return wt.checkNumSeries() == tc.segments + }, 20*time.Second, 1*time.Second) }) } } diff --git a/tsdb/wlog/wlog.go b/tsdb/wlog/wlog.go index df8bab53ffe..e38cb94cbdd 100644 --- a/tsdb/wlog/wlog.go +++ b/tsdb/wlog/wlog.go @@ -188,6 +188,8 @@ type WL struct { compress bool snappyBuf []byte + WriteNotified WriteNotified + metrics *wlMetrics } @@ -343,6 +345,10 @@ func (w *WL) Dir() string { return w.dir } +func (w *WL) SetWriteNotified(wn WriteNotified) { + w.WriteNotified = wn +} + func (w *WL) run() { Loop: for { diff --git a/util/runtime/limits_default.go b/util/runtime/limits_default.go index cd0ce732f93..40af5f14da5 100644 --- a/util/runtime/limits_default.go +++ b/util/runtime/limits_default.go @@ -18,16 +18,18 @@ package runtime import ( "fmt" + "math" "syscall" ) -// syscall.RLIM_INFINITY is a constant and its default type is int. -// It needs to be converted to an int64 variable to be compared with uint64 values. -// See https://golang.org/ref/spec#Conversions -var unlimited int64 = syscall.RLIM_INFINITY +// syscall.RLIM_INFINITY is a constant. +// Its type is int on most architectures but there are exceptions such as loong64. +// Uniform it to uint accorind to the standard. +// https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_resource.h.html +var unlimited uint64 = syscall.RLIM_INFINITY & math.MaxUint64 func limitToString(v uint64, unit string) string { - if v == uint64(unlimited) { + if v == unlimited { return "unlimited" } return fmt.Sprintf("%d%s", v, unit) diff --git a/vendor/cloud.google.com/go/compute/internal/version.go b/vendor/cloud.google.com/go/compute/internal/version.go index ddddbd21f21..ac02a3ce126 100644 --- a/vendor/cloud.google.com/go/compute/internal/version.go +++ b/vendor/cloud.google.com/go/compute/internal/version.go @@ -15,4 +15,4 @@ package internal // Version is the current tagged release of the library. -const Version = "1.18.0" +const Version = "1.19.0" diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/CHANGELOG.md new file mode 100644 index 00000000000..c2176107e04 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/CHANGELOG.md @@ -0,0 +1,519 @@ +# Release History + +## 1.3.1 (2023-02-02) + +### Other Changes +* Update dependencies to latest versions. + +## 1.3.0 (2023-01-06) + +### Features Added +* Added `BearerTokenOptions.AuthorizationHandler` to enable extending `runtime.BearerTokenPolicy` + with custom authorization logic +* Added `Client` types and matching constructors to the `azcore` and `arm` packages. These represent a basic client for HTTP and ARM respectively. + +### Other Changes +* Updated `internal` module to latest version. +* `policy/Request.SetBody()` allows replacing a request's body with an empty one + +## 1.2.0 (2022-11-04) + +### Features Added +* Added `ClientOptions.APIVersion` field, which overrides the default version a client + requests of the service, if the client supports this (all ARM clients do). +* Added package `tracing` that contains the building blocks for distributed tracing. +* Added field `TracingProvider` to type `policy.ClientOptions` that will be used to set the per-client tracing implementation. + +### Bugs Fixed +* Fixed an issue in `runtime.SetMultipartFormData` to properly handle slices of `io.ReadSeekCloser`. +* Fixed the MaxRetryDelay default to be 60s. +* Failure to poll the state of an LRO will now return an `*azcore.ResponseError` for poller types that require this behavior. +* Fixed a bug in `runtime.NewPipeline` that would cause pipeline-specified allowed headers and query parameters to be lost. + +### Other Changes +* Retain contents of read-only fields when sending requests. + +## 1.1.4 (2022-10-06) + +### Bugs Fixed +* Don't retry a request if the `Retry-After` delay is greater than the configured `RetryOptions.MaxRetryDelay`. +* `runtime.JoinPaths`: do not unconditionally add a forward slash before the query string + +### Other Changes +* Removed logging URL from retry policy as it's redundant. +* Retry policy logs when it exits due to a non-retriable status code. + +## 1.1.3 (2022-09-01) + +### Bugs Fixed +* Adjusted the initial retry delay to 800ms per the Azure SDK guidelines. + +## 1.1.2 (2022-08-09) + +### Other Changes +* Fixed various doc bugs. + +## 1.1.1 (2022-06-30) + +### Bugs Fixed +* Avoid polling when a RELO LRO synchronously terminates. + +## 1.1.0 (2022-06-03) + +### Other Changes +* The one-second floor for `Frequency` when calling `PollUntilDone()` has been removed when running tests. + +## 1.0.0 (2022-05-12) + +### Features Added +* Added interface `runtime.PollingHandler` to support custom poller implementations. + * Added field `PollingHandler` of this type to `runtime.NewPollerOptions[T]` and `runtime.NewPollerFromResumeTokenOptions[T]`. + +### Breaking Changes +* Renamed `cloud.Configuration.LoginEndpoint` to `.ActiveDirectoryAuthorityHost` +* Renamed `cloud.AzurePublicCloud` to `cloud.AzurePublic` +* Removed `AuxiliaryTenants` field from `arm/ClientOptions` and `arm/policy/BearerTokenOptions` +* Removed `TokenRequestOptions.TenantID` +* `Poller[T].PollUntilDone()` now takes an `options *PollUntilDoneOptions` param instead of `freq time.Duration` +* Removed `arm/runtime.Poller[T]`, `arm/runtime.NewPoller[T]()` and `arm/runtime.NewPollerFromResumeToken[T]()` +* Removed `arm/runtime.FinalStateVia` and related `const` values +* Renamed `runtime.PageProcessor` to `runtime.PagingHandler` +* The `arm/runtime.ProviderRepsonse` and `arm/runtime.Provider` types are no longer exported. +* Renamed `NewRequestIdPolicy()` to `NewRequestIDPolicy()` +* `TokenCredential.GetToken` now returns `AccessToken` by value. + +### Bugs Fixed +* When per-try timeouts are enabled, only cancel the context after the body has been read and closed. +* The `Operation-Location` poller now properly handles `final-state-via` values. +* Improvements in `runtime.Poller[T]` + * `Poll()` shouldn't cache errors, allowing for additional retries when in a non-terminal state. + * `Result()` will cache the terminal result or error but not transient errors, allowing for additional retries. + +### Other Changes +* Updated to latest `internal` module and absorbed breaking changes. + * Use `temporal.Resource` and deleted copy. +* The internal poller implementation has been refactored. + * The implementation in `internal/pollers/poller.go` has been merged into `runtime/poller.go` with some slight modification. + * The internal poller types had their methods updated to conform to the `runtime.PollingHandler` interface. + * The creation of resume tokens has been refactored so that implementers of `runtime.PollingHandler` don't need to know about it. +* `NewPipeline()` places policies from `ClientOptions` after policies from `PipelineOptions` +* Default User-Agent headers no longer include `azcore` version information + +## 0.23.1 (2022-04-14) + +### Bugs Fixed +* Include XML header when marshalling XML content. +* Handle XML namespaces when searching for error code. +* Handle `odata.error` when searching for error code. + +## 0.23.0 (2022-04-04) + +### Features Added +* Added `runtime.Pager[T any]` and `runtime.Poller[T any]` supporting types for central, generic, implementations. +* Added `cloud` package with a new API for cloud configuration +* Added `FinalStateVia` field to `runtime.NewPollerOptions[T any]` type. + +### Breaking Changes +* Removed the `Poller` type-alias to the internal poller implementation. +* Added `Ptr[T any]` and `SliceOfPtrs[T any]` in the `to` package and removed all non-generic implementations. +* `NullValue` and `IsNullValue` now take a generic type parameter instead of an interface func parameter. +* Replaced `arm.Endpoint` with `cloud` API + * Removed the `endpoint` parameter from `NewRPRegistrationPolicy()` + * `arm/runtime.NewPipeline()` and `.NewRPRegistrationPolicy()` now return an `error` +* Refactored `NewPoller` and `NewPollerFromResumeToken` funcs in `arm/runtime` and `runtime` packages. + * Removed the `pollerID` parameter as it's no longer required. + * Created optional parameter structs and moved optional parameters into them. +* Changed `FinalStateVia` field to a `const` type. + +### Other Changes +* Converted expiring resource and dependent types to use generics. + +## 0.22.0 (2022-03-03) + +### Features Added +* Added header `WWW-Authenticate` to the default allow-list of headers for logging. +* Added a pipeline policy that enables the retrieval of HTTP responses from API calls. + * Added `runtime.WithCaptureResponse` to enable the policy at the API level (off by default). + +### Breaking Changes +* Moved `WithHTTPHeader` and `WithRetryOptions` from the `policy` package to the `runtime` package. + +## 0.21.1 (2022-02-04) + +### Bugs Fixed +* Restore response body after reading in `Poller.FinalResponse()`. (#16911) +* Fixed bug in `NullValue` that could lead to incorrect comparisons for empty maps/slices (#16969) + +### Other Changes +* `BearerTokenPolicy` is more resilient to transient authentication failures. (#16789) + +## 0.21.0 (2022-01-11) + +### Features Added +* Added `AllowedHeaders` and `AllowedQueryParams` to `policy.LogOptions` to control which headers and query parameters are written to the logger. +* Added `azcore.ResponseError` type which is returned from APIs when a non-success HTTP status code is received. + +### Breaking Changes +* Moved `[]policy.Policy` parameters of `arm/runtime.NewPipeline` and `runtime.NewPipeline` into a new struct, `runtime.PipelineOptions` +* Renamed `arm/ClientOptions.Host` to `.Endpoint` +* Moved `Request.SkipBodyDownload` method to function `runtime.SkipBodyDownload` +* Removed `azcore.HTTPResponse` interface type +* `arm.NewPoller()` and `runtime.NewPoller()` no longer require an `eu` parameter +* `runtime.NewResponseError()` no longer requires an `error` parameter + +## 0.20.0 (2021-10-22) + +### Breaking Changes +* Removed `arm.Connection` +* Removed `azcore.Credential` and `.NewAnonymousCredential()` + * `NewRPRegistrationPolicy` now requires an `azcore.TokenCredential` +* `runtime.NewPipeline` has a new signature that simplifies implementing custom authentication +* `arm/runtime.RegistrationOptions` embeds `policy.ClientOptions` +* Contents in the `log` package have been slightly renamed. +* Removed `AuthenticationOptions` in favor of `policy.BearerTokenOptions` +* Changed parameters for `NewBearerTokenPolicy()` +* Moved policy config options out of `arm/runtime` and into `arm/policy` + +### Features Added +* Updating Documentation +* Added string typdef `arm.Endpoint` to provide a hint toward expected ARM client endpoints +* `azcore.ClientOptions` contains common pipeline configuration settings +* Added support for multi-tenant authorization in `arm/runtime` +* Require one second minimum when calling `PollUntilDone()` + +### Bug Fixes +* Fixed a potential panic when creating the default Transporter. +* Close LRO initial response body when creating a poller. +* Fixed a panic when recursively cloning structs that contain time.Time. + +## 0.19.0 (2021-08-25) + +### Breaking Changes +* Split content out of `azcore` into various packages. The intent is to separate content based on its usage (common, uncommon, SDK authors). + * `azcore` has all core functionality. + * `log` contains facilities for configuring in-box logging. + * `policy` is used for configuring pipeline options and creating custom pipeline policies. + * `runtime` contains various helpers used by SDK authors and generated content. + * `streaming` has helpers for streaming IO operations. +* `NewTelemetryPolicy()` now requires module and version parameters and the `Value` option has been removed. + * As a result, the `Request.Telemetry()` method has been removed. +* The telemetry policy now includes the SDK prefix `azsdk-go-` so callers no longer need to provide it. +* The `*http.Request` in `runtime.Request` is no longer anonymously embedded. Use the `Raw()` method to access it. +* The `UserAgent` and `Version` constants have been made internal, `Module` and `Version` respectively. + +### Bug Fixes +* Fixed an issue in the retry policy where the request body could be overwritten after a rewind. + +### Other Changes +* Moved modules `armcore` and `to` content into `arm` and `to` packages respectively. + * The `Pipeline()` method on `armcore.Connection` has been replaced by `NewPipeline()` in `arm.Connection`. It takes module and version parameters used by the telemetry policy. +* Poller logic has been consolidated across ARM and core implementations. + * This required some changes to the internal interfaces for core pollers. +* The core poller types have been improved, including more logging and test coverage. + +## 0.18.1 (2021-08-20) + +### Features Added +* Adds an `ETag` type for comparing etags and handling etags on requests +* Simplifies the `requestBodyProgess` and `responseBodyProgress` into a single `progress` object + +### Bugs Fixed +* `JoinPaths` will preserve query parameters encoded in the `root` url. + +### Other Changes +* Bumps dependency on `internal` module to the latest version (v0.7.0) + +## 0.18.0 (2021-07-29) +### Features Added +* Replaces methods from Logger type with two package methods for interacting with the logging functionality. +* `azcore.SetClassifications` replaces `azcore.Logger().SetClassifications` +* `azcore.SetListener` replaces `azcore.Logger().SetListener` + +### Breaking Changes +* Removes `Logger` type from `azcore` + + +## 0.17.0 (2021-07-27) +### Features Added +* Adding TenantID to TokenRequestOptions (https://github.com/Azure/azure-sdk-for-go/pull/14879) +* Adding AuxiliaryTenants to AuthenticationOptions (https://github.com/Azure/azure-sdk-for-go/pull/15123) + +### Breaking Changes +* Rename `AnonymousCredential` to `NewAnonymousCredential` (https://github.com/Azure/azure-sdk-for-go/pull/15104) +* rename `AuthenticationPolicyOptions` to `AuthenticationOptions` (https://github.com/Azure/azure-sdk-for-go/pull/15103) +* Make Header constants private (https://github.com/Azure/azure-sdk-for-go/pull/15038) + + +## 0.16.2 (2021-05-26) +### Features Added +* Improved support for byte arrays [#14715](https://github.com/Azure/azure-sdk-for-go/pull/14715) + + +## 0.16.1 (2021-05-19) +### Features Added +* Add license.txt to azcore module [#14682](https://github.com/Azure/azure-sdk-for-go/pull/14682) + + +## 0.16.0 (2021-05-07) +### Features Added +* Remove extra `*` in UnmarshalAsByteArray() [#14642](https://github.com/Azure/azure-sdk-for-go/pull/14642) + + +## 0.15.1 (2021-05-06) +### Features Added +* Cache the original request body on Request [#14634](https://github.com/Azure/azure-sdk-for-go/pull/14634) + + +## 0.15.0 (2021-05-05) +### Features Added +* Add support for null map and slice +* Export `Response.Payload` method + +### Breaking Changes +* remove `Response.UnmarshalError` as it's no longer required + + +## 0.14.5 (2021-04-23) +### Features Added +* Add `UnmarshalError()` on `azcore.Response` + + +## 0.14.4 (2021-04-22) +### Features Added +* Support for basic LRO polling +* Added type `LROPoller` and supporting types for basic polling on long running operations. +* rename poller param and added doc comment + +### Bugs Fixed +* Fixed content type detection bug in logging. + + +## 0.14.3 (2021-03-29) +### Features Added +* Add support for multi-part form data +* Added method `WriteMultipartFormData()` to Request. + + +## 0.14.2 (2021-03-17) +### Features Added +* Add support for encoding JSON null values +* Adds `NullValue()` and `IsNullValue()` functions for setting and detecting sentinel values used for encoding a JSON null. +* Documentation fixes + +### Bugs Fixed +* Fixed improper error wrapping + + +## 0.14.1 (2021-02-08) +### Features Added +* Add `Pager` and `Poller` interfaces to azcore + + +## 0.14.0 (2021-01-12) +### Features Added +* Accept zero-value options for default values +* Specify zero-value options structs to accept default values. +* Remove `DefaultXxxOptions()` methods. +* Do not silently change TryTimeout on negative values +* make per-try timeout opt-in + + +## 0.13.4 (2020-11-20) +### Features Added +* Include telemetry string in User Agent + + +## 0.13.3 (2020-11-20) +### Features Added +* Updating response body handling on `azcore.Response` + + +## 0.13.2 (2020-11-13) +### Features Added +* Remove implementation of stateless policies as first-class functions. + + +## 0.13.1 (2020-11-05) +### Features Added +* Add `Telemetry()` method to `azcore.Request()` + + +## 0.13.0 (2020-10-14) +### Features Added +* Rename `log` to `logger` to avoid name collision with the log package. +* Documentation improvements +* Simplified `DefaultHTTPClientTransport()` implementation + + +## 0.12.1 (2020-10-13) +### Features Added +* Update `internal` module dependence to `v0.5.0` + + +## 0.12.0 (2020-10-08) +### Features Added +* Removed storage specific content +* Removed internal content to prevent API clutter +* Refactored various policy options to conform with our options pattern + + +## 0.11.0 (2020-09-22) +### Features Added + +* Removed `LogError` and `LogSlowResponse`. +* Renamed `options` in `RequestLogOptions`. +* Updated `NewRequestLogPolicy()` to follow standard pattern for options. +* Refactored `requestLogPolicy.Do()` per above changes. +* Cleaned up/added logging in retry policy. +* Export `NewResponseError()` +* Fix `RequestLogOptions` comment + + +## 0.10.1 (2020-09-17) +### Features Added +* Add default console logger +* Default console logger writes to stderr. To enable it, set env var `AZURE_SDK_GO_LOGGING` to the value 'all'. +* Added `Logger.Writef()` to reduce the need for `ShouldLog()` checks. +* Add `LogLongRunningOperation` + + +## 0.10.0 (2020-09-10) +### Features Added +* The `request` and `transport` interfaces have been refactored to align with the patterns in the standard library. +* `NewRequest()` now uses `http.NewRequestWithContext()` and performs additional validation, it also requires a context parameter. +* The `Policy` and `Transport` interfaces have had their context parameter removed as the context is associated with the underlying `http.Request`. +* `Pipeline.Do()` will validate the HTTP request before sending it through the pipeline, avoiding retries on a malformed request. +* The `Retrier` interface has been replaced with the `NonRetriableError` interface, and the retry policy updated to test for this. +* `Request.SetBody()` now requires a content type parameter for setting the request's MIME type. +* moved path concatenation into `JoinPaths()` func + + +## 0.9.6 (2020-08-18) +### Features Added +* Improvements to body download policy +* Always download the response body for error responses, i.e. HTTP status codes >= 400. +* Simplify variable declarations + + +## 0.9.5 (2020-08-11) +### Features Added +* Set the Content-Length header in `Request.SetBody` + + +## 0.9.4 (2020-08-03) +### Features Added +* Fix cancellation of per try timeout +* Per try timeout is used to ensure that an HTTP operation doesn't take too long, e.g. that a GET on some URL doesn't take an inordinant amount of time. +* Once the HTTP request returns, the per try timeout should be cancelled, not when the response has been read to completion. +* Do not drain response body if there are no more retries +* Do not retry non-idempotent operations when body download fails + + +## 0.9.3 (2020-07-28) +### Features Added +* Add support for custom HTTP request headers +* Inserts an internal policy into the pipeline that can extract HTTP header values from the caller's context, adding them to the request. +* Use `azcore.WithHTTPHeader` to add HTTP headers to a context. +* Remove method specific to Go 1.14 + + +## 0.9.2 (2020-07-28) +### Features Added +* Omit read-only content from request payloads +* If any field in a payload's object graph contains `azure:"ro"`, make a clone of the object graph, omitting all fields with this annotation. +* Verify no fields were dropped +* Handle embedded struct types +* Added test for cloning by value +* Add messages to failures + + +## 0.9.1 (2020-07-22) +### Features Added +* Updated dependency on internal module to fix race condition. + + +## 0.9.0 (2020-07-09) +### Features Added +* Add `HTTPResponse` interface to be used by callers to access the raw HTTP response from an error in the event of an API call failure. +* Updated `sdk/internal` dependency to latest version. +* Rename package alias + + +## 0.8.2 (2020-06-29) +### Features Added +* Added missing documentation comments + +### Bugs Fixed +* Fixed a bug in body download policy. + + +## 0.8.1 (2020-06-26) +### Features Added +* Miscellaneous clean-up reported by linters + + +## 0.8.0 (2020-06-01) +### Features Added +* Differentiate between standard and URL encoding. + + +## 0.7.1 (2020-05-27) +### Features Added +* Add support for for base64 encoding and decoding of payloads. + + +## 0.7.0 (2020-05-12) +### Features Added +* Change `RetryAfter()` to a function. + + +## 0.6.0 (2020-04-29) +### Features Added +* Updating `RetryAfter` to only return the detaion in the RetryAfter header + + +## 0.5.0 (2020-03-23) +### Features Added +* Export `TransportFunc` + +### Breaking Changes +* Removed `IterationDone` + + +## 0.4.1 (2020-02-25) +### Features Added +* Ensure per-try timeout is properly cancelled +* Explicitly call cancel the per-try timeout when the response body has been read/closed by the body download policy. +* When the response body is returned to the caller for reading/closing, wrap it in a `responseBodyReader` that will cancel the timeout when the body is closed. +* `Logger.Should()` will return false if no listener is set. + + +## 0.4.0 (2020-02-18) +### Features Added +* Enable custom `RetryOptions` to be specified per API call +* Added `WithRetryOptions()` that adds a custom `RetryOptions` to the provided context, allowing custom settings per API call. +* Remove 429 from the list of default HTTP status codes for retry. +* Change StatusCodesForRetry to a slice so consumers can append to it. +* Added support for retry-after in HTTP-date format. +* Cleaned up some comments specific to storage. +* Remove `Request.SetQueryParam()` +* Renamed `MaxTries` to `MaxRetries` + +## 0.3.0 (2020-01-16) +### Features Added +* Added `DefaultRetryOptions` to create initialized default options. + +### Breaking Changes +* Removed `Response.CheckStatusCode()` + + +## 0.2.0 (2020-01-15) +### Features Added +* Add support for marshalling and unmarshalling JSON +* Removed `Response.Payload` field +* Exit early when unmarsahlling if there is no payload + + +## 0.1.0 (2020-01-10) +### Features Added +* Initial release diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/LICENSE.txt b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/LICENSE.txt new file mode 100644 index 00000000000..48ea6616b5b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/README.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/README.md new file mode 100644 index 00000000000..35a74e18d09 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/README.md @@ -0,0 +1,39 @@ +# Azure Core Client Module for Go + +[![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/azcore)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore) +[![Build Status](https://dev.azure.com/azure-sdk/public/_apis/build/status/go/go%20-%20azcore%20-%20ci?branchName=main)](https://dev.azure.com/azure-sdk/public/_build/latest?definitionId=1843&branchName=main) +[![Code Coverage](https://img.shields.io/azure-devops/coverage/azure-sdk/public/1843/main)](https://img.shields.io/azure-devops/coverage/azure-sdk/public/1843/main) + +The `azcore` module provides a set of common interfaces and types for Go SDK client modules. +These modules follow the [Azure SDK Design Guidelines for Go](https://azure.github.io/azure-sdk/golang_introduction.html). + +## Getting started + +This project uses [Go modules](https://github.com/golang/go/wiki/Modules) for versioning and dependency management. + +Typically, you will not need to explicitly install `azcore` as it will be installed as a client module dependency. +To add the latest version to your `go.mod` file, execute the following command. + +```bash +go get github.com/Azure/azure-sdk-for-go/sdk/azcore +``` + +General documentation and examples can be found on [pkg.go.dev](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore). + +## Contributing +This project welcomes contributions and suggestions. Most contributions require +you to agree to a Contributor License Agreement (CLA) declaring that you have +the right to, and actually do, grant us the rights to use your contribution. +For details, visit [https://cla.microsoft.com](https://cla.microsoft.com). + +When you submit a pull request, a CLA-bot will automatically determine whether +you need to provide a CLA and decorate the PR appropriately (e.g., label, +comment). Simply follow the instructions provided by the bot. You will only +need to do this once across all repos using our CLA. + +This project has adopted the +[Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information, see the +[Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) +or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any +additional questions or comments. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/ci.yml b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/ci.yml new file mode 100644 index 00000000000..aab9218538d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/ci.yml @@ -0,0 +1,29 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. +trigger: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/azcore/ + - eng/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/azcore/ + - eng/ + +stages: +- template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: azcore diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud/cloud.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud/cloud.go new file mode 100644 index 00000000000..9d077a3e126 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud/cloud.go @@ -0,0 +1,44 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package cloud + +var ( + // AzureChina contains configuration for Azure China. + AzureChina = Configuration{ + ActiveDirectoryAuthorityHost: "https://login.chinacloudapi.cn/", Services: map[ServiceName]ServiceConfiguration{}, + } + // AzureGovernment contains configuration for Azure Government. + AzureGovernment = Configuration{ + ActiveDirectoryAuthorityHost: "https://login.microsoftonline.us/", Services: map[ServiceName]ServiceConfiguration{}, + } + // AzurePublic contains configuration for Azure Public Cloud. + AzurePublic = Configuration{ + ActiveDirectoryAuthorityHost: "https://login.microsoftonline.com/", Services: map[ServiceName]ServiceConfiguration{}, + } +) + +// ServiceName identifies a cloud service. +type ServiceName string + +// ResourceManager is a global constant identifying Azure Resource Manager. +const ResourceManager ServiceName = "resourceManager" + +// ServiceConfiguration configures a specific cloud service such as Azure Resource Manager. +type ServiceConfiguration struct { + // Audience is the audience the client will request for its access tokens. + Audience string + // Endpoint is the service's base URL. + Endpoint string +} + +// Configuration configures a cloud. +type Configuration struct { + // ActiveDirectoryAuthorityHost is the base URL of the cloud's Azure Active Directory. + ActiveDirectoryAuthorityHost string + // Services contains configuration for the cloud's services. + Services map[ServiceName]ServiceConfiguration +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud/doc.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud/doc.go new file mode 100644 index 00000000000..985b1bde2f2 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud/doc.go @@ -0,0 +1,53 @@ +//go:build go1.16 +// +build go1.16 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/* +Package cloud implements a configuration API for applications deployed to sovereign or private Azure clouds. + +Azure SDK client configuration defaults are appropriate for Azure Public Cloud (sometimes referred to as +"Azure Commercial" or simply "Microsoft Azure"). This package enables applications deployed to other +Azure Clouds to configure clients appropriately. + +This package contains predefined configuration for well-known sovereign clouds such as Azure Government and +Azure China. Azure SDK clients accept this configuration via the Cloud field of azcore.ClientOptions. For +example, configuring a credential and ARM client for Azure Government: + + opts := azcore.ClientOptions{Cloud: cloud.AzureGovernment} + cred, err := azidentity.NewDefaultAzureCredential( + &azidentity.DefaultAzureCredentialOptions{ClientOptions: opts}, + ) + handle(err) + + client, err := armsubscription.NewClient( + cred, &arm.ClientOptions{ClientOptions: opts}, + ) + handle(err) + +Applications deployed to a private cloud such as Azure Stack create a Configuration object with +appropriate values: + + c := cloud.Configuration{ + ActiveDirectoryAuthorityHost: "https://...", + Services: map[cloud.ServiceName]cloud.ServiceConfiguration{ + cloud.ResourceManager: { + Audience: "...", + Endpoint: "https://...", + }, + }, + } + opts := azcore.ClientOptions{Cloud: c} + + cred, err := azidentity.NewDefaultAzureCredential( + &azidentity.DefaultAzureCredentialOptions{ClientOptions: opts}, + ) + handle(err) + + client, err := armsubscription.NewClient( + cred, &arm.ClientOptions{ClientOptions: opts}, + ) + handle(err) +*/ +package cloud diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/core.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/core.go new file mode 100644 index 00000000000..72c2cf21eef --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/core.go @@ -0,0 +1,113 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azcore + +import ( + "reflect" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/tracing" +) + +// AccessToken represents an Azure service bearer access token with expiry information. +type AccessToken = exported.AccessToken + +// TokenCredential represents a credential capable of providing an OAuth token. +type TokenCredential = exported.TokenCredential + +// holds sentinel values used to send nulls +var nullables map[reflect.Type]interface{} = map[reflect.Type]interface{}{} + +// NullValue is used to send an explicit 'null' within a request. +// This is typically used in JSON-MERGE-PATCH operations to delete a value. +func NullValue[T any]() T { + t := shared.TypeOfT[T]() + v, found := nullables[t] + if !found { + var o reflect.Value + if k := t.Kind(); k == reflect.Map { + o = reflect.MakeMap(t) + } else if k == reflect.Slice { + // empty slices appear to all point to the same data block + // which causes comparisons to become ambiguous. so we create + // a slice with len/cap of one which ensures a unique address. + o = reflect.MakeSlice(t, 1, 1) + } else { + o = reflect.New(t.Elem()) + } + v = o.Interface() + nullables[t] = v + } + // return the sentinel object + return v.(T) +} + +// IsNullValue returns true if the field contains a null sentinel value. +// This is used by custom marshallers to properly encode a null value. +func IsNullValue[T any](v T) bool { + // see if our map has a sentinel object for this *T + t := reflect.TypeOf(v) + if o, found := nullables[t]; found { + o1 := reflect.ValueOf(o) + v1 := reflect.ValueOf(v) + // we found it; return true if v points to the sentinel object. + // NOTE: maps and slices can only be compared to nil, else you get + // a runtime panic. so we compare addresses instead. + return o1.Pointer() == v1.Pointer() + } + // no sentinel object for this *t + return false +} + +// ClientOptions contains configuration settings for a client's pipeline. +type ClientOptions = policy.ClientOptions + +// Client is a basic HTTP client. It consists of a pipeline and tracing provider. +type Client struct { + pl runtime.Pipeline + tr tracing.Tracer +} + +// NewClient creates a new Client instance with the provided values. +// - clientName - the fully qualified name of the client ("package.Client"); this is used by the tracing provider when creating spans +// - moduleVersion - the semantic version of the containing module; used by the telemetry policy +// - plOpts - pipeline configuration options; can be the zero-value +// - options - optional client configurations; pass nil to accept the default values +func NewClient(clientName, moduleVersion string, plOpts runtime.PipelineOptions, options *ClientOptions) (*Client, error) { + pkg, err := shared.ExtractPackageName(clientName) + if err != nil { + return nil, err + } + + if options == nil { + options = &ClientOptions{} + } + + if !options.Telemetry.Disabled { + if err := shared.ValidateModVer(moduleVersion); err != nil { + return nil, err + } + } + + pl := runtime.NewPipeline(pkg, moduleVersion, plOpts, options) + + tr := options.TracingProvider.NewTracer(clientName, moduleVersion) + return &Client{pl: pl, tr: tr}, nil +} + +// Pipeline returns the pipeline for this client. +func (c *Client) Pipeline() runtime.Pipeline { + return c.pl +} + +// Tracer returns the tracer for this client. +func (c *Client) Tracer() tracing.Tracer { + return c.tr +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/doc.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/doc.go new file mode 100644 index 00000000000..28c64678c76 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/doc.go @@ -0,0 +1,257 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright 2017 Microsoft Corporation. All rights reserved. +// Use of this source code is governed by an MIT +// license that can be found in the LICENSE file. + +/* +Package azcore implements an HTTP request/response middleware pipeline used by Azure SDK clients. + +The middleware consists of three components. + + - One or more Policy instances. + - A Transporter instance. + - A Pipeline instance that combines the Policy and Transporter instances. + +# Implementing the Policy Interface + +A Policy can be implemented in two ways; as a first-class function for a stateless Policy, or as +a method on a type for a stateful Policy. Note that HTTP requests made via the same pipeline share +the same Policy instances, so if a Policy mutates its state it MUST be properly synchronized to +avoid race conditions. + +A Policy's Do method is called when an HTTP request wants to be sent over the network. The Do method can +perform any operation(s) it desires. For example, it can log the outgoing request, mutate the URL, headers, +and/or query parameters, inject a failure, etc. Once the Policy has successfully completed its request +work, it must call the Next() method on the *policy.Request instance in order to pass the request to the +next Policy in the chain. + +When an HTTP response comes back, the Policy then gets a chance to process the response/error. The Policy instance +can log the response, retry the operation if it failed due to a transient error or timeout, unmarshal the response +body, etc. Once the Policy has successfully completed its response work, it must return the *http.Response +and error instances to its caller. + +Template for implementing a stateless Policy: + + type policyFunc func(*policy.Request) (*http.Response, error) + + // Do implements the Policy interface on policyFunc. + func (pf policyFunc) Do(req *policy.Request) (*http.Response, error) { + return pf(req) + } + + func NewMyStatelessPolicy() policy.Policy { + return policyFunc(func(req *policy.Request) (*http.Response, error) { + // TODO: mutate/process Request here + + // forward Request to next Policy & get Response/error + resp, err := req.Next() + + // TODO: mutate/process Response/error here + + // return Response/error to previous Policy + return resp, err + }) + } + +Template for implementing a stateful Policy: + + type MyStatefulPolicy struct { + // TODO: add configuration/setting fields here + } + + // TODO: add initialization args to NewMyStatefulPolicy() + func NewMyStatefulPolicy() policy.Policy { + return &MyStatefulPolicy{ + // TODO: initialize configuration/setting fields here + } + } + + func (p *MyStatefulPolicy) Do(req *policy.Request) (resp *http.Response, err error) { + // TODO: mutate/process Request here + + // forward Request to next Policy & get Response/error + resp, err := req.Next() + + // TODO: mutate/process Response/error here + + // return Response/error to previous Policy + return resp, err + } + +# Implementing the Transporter Interface + +The Transporter interface is responsible for sending the HTTP request and returning the corresponding +HTTP response or error. The Transporter is invoked by the last Policy in the chain. The default Transporter +implementation uses a shared http.Client from the standard library. + +The same stateful/stateless rules for Policy implementations apply to Transporter implementations. + +# Using Policy and Transporter Instances Via a Pipeline + +To use the Policy and Transporter instances, an application passes them to the runtime.NewPipeline function. + + func NewPipeline(transport Transporter, policies ...Policy) Pipeline + +The specified Policy instances form a chain and are invoked in the order provided to NewPipeline +followed by the Transporter. + +Once the Pipeline has been created, create a runtime.Request instance and pass it to Pipeline's Do method. + + func NewRequest(ctx context.Context, httpMethod string, endpoint string) (*Request, error) + + func (p Pipeline) Do(req *Request) (*http.Request, error) + +The Pipeline.Do method sends the specified Request through the chain of Policy and Transporter +instances. The response/error is then sent through the same chain of Policy instances in reverse +order. For example, assuming there are Policy types PolicyA, PolicyB, and PolicyC along with +TransportA. + + pipeline := NewPipeline(TransportA, PolicyA, PolicyB, PolicyC) + +The flow of Request and Response looks like the following: + + policy.Request -> PolicyA -> PolicyB -> PolicyC -> TransportA -----+ + | + HTTP(S) endpoint + | + caller <--------- PolicyA <- PolicyB <- PolicyC <- http.Response-+ + +# Creating a Request Instance + +The Request instance passed to Pipeline's Do method is a wrapper around an *http.Request. It also +contains some internal state and provides various convenience methods. You create a Request instance +by calling the runtime.NewRequest function: + + func NewRequest(ctx context.Context, httpMethod string, endpoint string) (*Request, error) + +If the Request should contain a body, call the SetBody method. + + func (req *Request) SetBody(body ReadSeekCloser, contentType string) error + +A seekable stream is required so that upon retry, the retry Policy instance can seek the stream +back to the beginning before retrying the network request and re-uploading the body. + +# Sending an Explicit Null + +Operations like JSON-MERGE-PATCH send a JSON null to indicate a value should be deleted. + + { + "delete-me": null + } + +This requirement conflicts with the SDK's default marshalling that specifies "omitempty" as +a means to resolve the ambiguity between a field to be excluded and its zero-value. + + type Widget struct { + Name *string `json:",omitempty"` + Count *int `json:",omitempty"` + } + +In the above example, Name and Count are defined as pointer-to-type to disambiguate between +a missing value (nil) and a zero-value (0) which might have semantic differences. + +In a PATCH operation, any fields left as nil are to have their values preserved. When updating +a Widget's count, one simply specifies the new value for Count, leaving Name nil. + +To fulfill the requirement for sending a JSON null, the NullValue() function can be used. + + w := Widget{ + Count: azcore.NullValue[*int](), + } + +This sends an explict "null" for Count, indicating that any current value for Count should be deleted. + +# Processing the Response + +When the HTTP response is received, the *http.Response is returned directly. Each Policy instance +can inspect/mutate the *http.Response. + +# Built-in Logging + +To enable logging, set environment variable AZURE_SDK_GO_LOGGING to "all" before executing your program. + +By default the logger writes to stderr. This can be customized by calling log.SetListener, providing +a callback that writes to the desired location. Any custom logging implementation MUST provide its +own synchronization to handle concurrent invocations. + +See the docs for the log package for further details. + +# Pageable Operations + +Pageable operations return potentially large data sets spread over multiple GET requests. The result of +each GET is a "page" of data consisting of a slice of items. + +Pageable operations can be identified by their New*Pager naming convention and return type of *runtime.Pager[T]. + + func (c *WidgetClient) NewListWidgetsPager(o *Options) *runtime.Pager[PageResponse] + +The call to WidgetClient.NewListWidgetsPager() returns an instance of *runtime.Pager[T] for fetching pages +and determining if there are more pages to fetch. No IO calls are made until the NextPage() method is invoked. + + pager := widgetClient.NewListWidgetsPager(nil) + for pager.More() { + page, err := pager.NextPage(context.TODO()) + // handle err + for _, widget := range page.Values { + // process widget + } + } + +# Long-Running Operations + +Long-running operations (LROs) are operations consisting of an initial request to start the operation followed +by polling to determine when the operation has reached a terminal state. An LRO's terminal state is one +of the following values. + + - Succeeded - the LRO completed successfully + - Failed - the LRO failed to complete + - Canceled - the LRO was canceled + +LROs can be identified by their Begin* prefix and their return type of *runtime.Poller[T]. + + func (c *WidgetClient) BeginCreateOrUpdate(ctx context.Context, w Widget, o *Options) (*runtime.Poller[Response], error) + +When a call to WidgetClient.BeginCreateOrUpdate() returns a nil error, it means that the LRO has started. +It does _not_ mean that the widget has been created or updated (or failed to be created/updated). + +The *runtime.Poller[T] provides APIs for determining the state of the LRO. To wait for the LRO to complete, +call the PollUntilDone() method. + + poller, err := widgetClient.BeginCreateOrUpdate(context.TODO(), Widget{}, nil) + // handle err + result, err := poller.PollUntilDone(context.TODO(), nil) + // handle err + // use result + +The call to PollUntilDone() will block the current goroutine until the LRO has reached a terminal state or the +context is canceled/timed out. + +Note that LROs can take anywhere from several seconds to several minutes. The duration is operation-dependent. Due to +this variant behavior, pollers do _not_ have a preconfigured time-out. Use a context with the appropriate cancellation +mechanism as required. + +# Resume Tokens + +Pollers provide the ability to serialize their state into a "resume token" which can be used by another process to +recreate the poller. This is achieved via the runtime.Poller[T].ResumeToken() method. + + token, err := poller.ResumeToken() + // handle error + +Note that a token can only be obtained for a poller that's in a non-terminal state. Also note that any subsequent calls +to poller.Poll() might change the poller's state. In this case, a new token should be created. + +After the token has been obtained, it can be used to recreate an instance of the originating poller. + + poller, err := widgetClient.BeginCreateOrUpdate(nil, Widget{}, &Options{ + ResumeToken: token, + }) + +When resuming a poller, no IO is performed, and zero-value arguments can be used for everything but the Options.ResumeToken. + +Resume tokens are unique per service client and operation. Attempting to resume a poller for LRO BeginB() with a token from LRO +BeginA() will result in an error. +*/ +package azcore diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/errors.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/errors.go new file mode 100644 index 00000000000..17bd50c6732 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/errors.go @@ -0,0 +1,14 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azcore + +import "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + +// ResponseError is returned when a request is made to a service and +// the service returns a non-success HTTP status code. +// Use errors.As() to access this type in the error chain. +type ResponseError = exported.ResponseError diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/etag.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/etag.go new file mode 100644 index 00000000000..23ea7e7c8ea --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/etag.go @@ -0,0 +1,48 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azcore + +import ( + "strings" +) + +// ETag is a property used for optimistic concurrency during updates +// ETag is a validator based on https://tools.ietf.org/html/rfc7232#section-2.3.2 +// An ETag can be empty (""). +type ETag string + +// ETagAny is an ETag that represents everything, the value is "*" +const ETagAny ETag = "*" + +// Equals does a strong comparison of two ETags. Equals returns true when both +// ETags are not weak and the values of the underlying strings are equal. +func (e ETag) Equals(other ETag) bool { + return !e.IsWeak() && !other.IsWeak() && e == other +} + +// WeakEquals does a weak comparison of two ETags. Two ETags are equivalent if their opaque-tags match +// character-by-character, regardless of either or both being tagged as "weak". +func (e ETag) WeakEquals(other ETag) bool { + getStart := func(e1 ETag) int { + if e1.IsWeak() { + return 2 + } + return 0 + } + aStart := getStart(e) + bStart := getStart(other) + + aVal := e[aStart:] + bVal := other[bStart:] + + return aVal == bVal +} + +// IsWeak specifies whether the ETag is strong or weak. +func (e ETag) IsWeak() bool { + return len(e) >= 4 && strings.HasPrefix(string(e), "W/\"") && strings.HasSuffix(string(e), "\"") +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/exported.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/exported.go new file mode 100644 index 00000000000..2ffbc0e4741 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/exported.go @@ -0,0 +1,83 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package exported + +import ( + "context" + "io" + "net/http" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" +) + +type nopCloser struct { + io.ReadSeeker +} + +func (n nopCloser) Close() error { + return nil +} + +// NopCloser returns a ReadSeekCloser with a no-op close method wrapping the provided io.ReadSeeker. +// Exported as streaming.NopCloser(). +func NopCloser(rs io.ReadSeeker) io.ReadSeekCloser { + return nopCloser{rs} +} + +// HasStatusCode returns true if the Response's status code is one of the specified values. +// Exported as runtime.HasStatusCode(). +func HasStatusCode(resp *http.Response, statusCodes ...int) bool { + if resp == nil { + return false + } + for _, sc := range statusCodes { + if resp.StatusCode == sc { + return true + } + } + return false +} + +// Payload reads and returns the response body or an error. +// On a successful read, the response body is cached. +// Subsequent reads will access the cached value. +// Exported as runtime.Payload(). +func Payload(resp *http.Response) ([]byte, error) { + // r.Body won't be a nopClosingBytesReader if downloading was skipped + if buf, ok := resp.Body.(*shared.NopClosingBytesReader); ok { + return buf.Bytes(), nil + } + bytesBody, err := io.ReadAll(resp.Body) + resp.Body.Close() + if err != nil { + return nil, err + } + resp.Body = shared.NewNopClosingBytesReader(bytesBody) + return bytesBody, nil +} + +// AccessToken represents an Azure service bearer access token with expiry information. +// Exported as azcore.AccessToken. +type AccessToken struct { + Token string + ExpiresOn time.Time +} + +// TokenRequestOptions contain specific parameter that may be used by credentials types when attempting to get a token. +// Exported as policy.TokenRequestOptions. +type TokenRequestOptions struct { + // Scopes contains the list of permission scopes required for the token. + Scopes []string +} + +// TokenCredential represents a credential capable of providing an OAuth token. +// Exported as azcore.TokenCredential. +type TokenCredential interface { + // GetToken requests an access token for the specified set of scopes. + GetToken(ctx context.Context, options TokenRequestOptions) (AccessToken, error) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/pipeline.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/pipeline.go new file mode 100644 index 00000000000..c44efd6eff5 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/pipeline.go @@ -0,0 +1,97 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package exported + +import ( + "errors" + "fmt" + "net/http" + + "golang.org/x/net/http/httpguts" +) + +// Policy represents an extensibility point for the Pipeline that can mutate the specified +// Request and react to the received Response. +// Exported as policy.Policy. +type Policy interface { + // Do applies the policy to the specified Request. When implementing a Policy, mutate the + // request before calling req.Next() to move on to the next policy, and respond to the result + // before returning to the caller. + Do(req *Request) (*http.Response, error) +} + +// Pipeline represents a primitive for sending HTTP requests and receiving responses. +// Its behavior can be extended by specifying policies during construction. +// Exported as runtime.Pipeline. +type Pipeline struct { + policies []Policy +} + +// Transporter represents an HTTP pipeline transport used to send HTTP requests and receive responses. +// Exported as policy.Transporter. +type Transporter interface { + // Do sends the HTTP request and returns the HTTP response or error. + Do(req *http.Request) (*http.Response, error) +} + +// used to adapt a TransportPolicy to a Policy +type transportPolicy struct { + trans Transporter +} + +func (tp transportPolicy) Do(req *Request) (*http.Response, error) { + if tp.trans == nil { + return nil, errors.New("missing transporter") + } + resp, err := tp.trans.Do(req.Raw()) + if err != nil { + return nil, err + } else if resp == nil { + // there was no response and no error (rare but can happen) + // this ensures the retry policy will retry the request + return nil, errors.New("received nil response") + } + return resp, nil +} + +// NewPipeline creates a new Pipeline object from the specified Policies. +// Not directly exported, but used as part of runtime.NewPipeline(). +func NewPipeline(transport Transporter, policies ...Policy) Pipeline { + // transport policy must always be the last in the slice + policies = append(policies, transportPolicy{trans: transport}) + return Pipeline{ + policies: policies, + } +} + +// Do is called for each and every HTTP request. It passes the request through all +// the Policy objects (which can transform the Request's URL/query parameters/headers) +// and ultimately sends the transformed HTTP request over the network. +func (p Pipeline) Do(req *Request) (*http.Response, error) { + if req == nil { + return nil, errors.New("request cannot be nil") + } + // check copied from Transport.roundTrip() + for k, vv := range req.Raw().Header { + if !httpguts.ValidHeaderFieldName(k) { + if req.Raw().Body != nil { + req.Raw().Body.Close() + } + return nil, fmt.Errorf("invalid header field name %q", k) + } + for _, v := range vv { + if !httpguts.ValidHeaderFieldValue(v) { + if req.Raw().Body != nil { + req.Raw().Body.Close() + } + return nil, fmt.Errorf("invalid header field value %q for key %v", v, k) + } + } + } + req.policies = p.policies + return req.Next() +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/request.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/request.go new file mode 100644 index 00000000000..38867574178 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/request.go @@ -0,0 +1,171 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package exported + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "reflect" + "strconv" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" +) + +// Request is an abstraction over the creation of an HTTP request as it passes through the pipeline. +// Don't use this type directly, use NewRequest() instead. +// Exported as policy.Request. +type Request struct { + req *http.Request + body io.ReadSeekCloser + policies []Policy + values opValues +} + +type opValues map[reflect.Type]interface{} + +// Set adds/changes a value +func (ov opValues) set(value interface{}) { + ov[reflect.TypeOf(value)] = value +} + +// Get looks for a value set by SetValue first +func (ov opValues) get(value interface{}) bool { + v, ok := ov[reflect.ValueOf(value).Elem().Type()] + if ok { + reflect.ValueOf(value).Elem().Set(reflect.ValueOf(v)) + } + return ok +} + +// NewRequest creates a new Request with the specified input. +// Exported as runtime.NewRequest(). +func NewRequest(ctx context.Context, httpMethod string, endpoint string) (*Request, error) { + req, err := http.NewRequestWithContext(ctx, httpMethod, endpoint, nil) + if err != nil { + return nil, err + } + if req.URL.Host == "" { + return nil, errors.New("no Host in request URL") + } + if !(req.URL.Scheme == "http" || req.URL.Scheme == "https") { + return nil, fmt.Errorf("unsupported protocol scheme %s", req.URL.Scheme) + } + return &Request{req: req}, nil +} + +// Body returns the original body specified when the Request was created. +func (req *Request) Body() io.ReadSeekCloser { + return req.body +} + +// Raw returns the underlying HTTP request. +func (req *Request) Raw() *http.Request { + return req.req +} + +// Next calls the next policy in the pipeline. +// If there are no more policies, nil and an error are returned. +// This method is intended to be called from pipeline policies. +// To send a request through a pipeline call Pipeline.Do(). +func (req *Request) Next() (*http.Response, error) { + if len(req.policies) == 0 { + return nil, errors.New("no more policies") + } + nextPolicy := req.policies[0] + nextReq := *req + nextReq.policies = nextReq.policies[1:] + return nextPolicy.Do(&nextReq) +} + +// SetOperationValue adds/changes a mutable key/value associated with a single operation. +func (req *Request) SetOperationValue(value interface{}) { + if req.values == nil { + req.values = opValues{} + } + req.values.set(value) +} + +// OperationValue looks for a value set by SetOperationValue(). +func (req *Request) OperationValue(value interface{}) bool { + if req.values == nil { + return false + } + return req.values.get(value) +} + +// SetBody sets the specified ReadSeekCloser as the HTTP request body, and sets Content-Type and Content-Length +// accordingly. If the ReadSeekCloser is nil or empty, Content-Length won't be set. If contentType is "", +// Content-Type won't be set. +// Use streaming.NopCloser to turn an io.ReadSeeker into an io.ReadSeekCloser. +func (req *Request) SetBody(body io.ReadSeekCloser, contentType string) error { + var err error + var size int64 + if body != nil { + size, err = body.Seek(0, io.SeekEnd) // Seek to the end to get the stream's size + if err != nil { + return err + } + } + if size == 0 { + // treat an empty stream the same as a nil one: assign req a nil body + body = nil + // RFC 9110 specifies a client shouldn't set Content-Length on a request containing no content + // (Del is a no-op when the header has no value) + req.req.Header.Del(shared.HeaderContentLength) + } else { + _, err = body.Seek(0, io.SeekStart) + if err != nil { + return err + } + req.req.Header.Set(shared.HeaderContentLength, strconv.FormatInt(size, 10)) + req.Raw().GetBody = func() (io.ReadCloser, error) { + _, err := body.Seek(0, io.SeekStart) // Seek back to the beginning of the stream + return body, err + } + } + // keep a copy of the body argument. this is to handle cases + // where req.Body is replaced, e.g. httputil.DumpRequest and friends. + req.body = body + req.req.Body = body + req.req.ContentLength = size + if contentType == "" { + // Del is a no-op when the header has no value + req.req.Header.Del(shared.HeaderContentType) + } else { + req.req.Header.Set(shared.HeaderContentType, contentType) + } + return nil +} + +// RewindBody seeks the request's Body stream back to the beginning so it can be resent when retrying an operation. +func (req *Request) RewindBody() error { + if req.body != nil { + // Reset the stream back to the beginning and restore the body + _, err := req.body.Seek(0, io.SeekStart) + req.req.Body = req.body + return err + } + return nil +} + +// Close closes the request body. +func (req *Request) Close() error { + if req.body == nil { + return nil + } + return req.body.Close() +} + +// Clone returns a deep copy of the request with its context changed to ctx. +func (req *Request) Clone(ctx context.Context) *Request { + r2 := *req + r2.req = req.req.Clone(ctx) + return &r2 +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/response_error.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/response_error.go new file mode 100644 index 00000000000..3db6acc8325 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported/response_error.go @@ -0,0 +1,142 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package exported + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "regexp" +) + +// NewResponseError creates a new *ResponseError from the provided HTTP response. +// Exported as runtime.NewResponseError(). +func NewResponseError(resp *http.Response) error { + respErr := &ResponseError{ + StatusCode: resp.StatusCode, + RawResponse: resp, + } + + // prefer the error code in the response header + if ec := resp.Header.Get("x-ms-error-code"); ec != "" { + respErr.ErrorCode = ec + return respErr + } + + // if we didn't get x-ms-error-code, check in the response body + body, err := Payload(resp) + if err != nil { + return err + } + + if len(body) > 0 { + if code := extractErrorCodeJSON(body); code != "" { + respErr.ErrorCode = code + } else if code := extractErrorCodeXML(body); code != "" { + respErr.ErrorCode = code + } + } + + return respErr +} + +func extractErrorCodeJSON(body []byte) string { + var rawObj map[string]interface{} + if err := json.Unmarshal(body, &rawObj); err != nil { + // not a JSON object + return "" + } + + // check if this is a wrapped error, i.e. { "error": { ... } } + // if so then unwrap it + if wrapped, ok := rawObj["error"]; ok { + unwrapped, ok := wrapped.(map[string]interface{}) + if !ok { + return "" + } + rawObj = unwrapped + } else if wrapped, ok := rawObj["odata.error"]; ok { + // check if this a wrapped odata error, i.e. { "odata.error": { ... } } + unwrapped, ok := wrapped.(map[string]any) + if !ok { + return "" + } + rawObj = unwrapped + } + + // now check for the error code + code, ok := rawObj["code"] + if !ok { + return "" + } + codeStr, ok := code.(string) + if !ok { + return "" + } + return codeStr +} + +func extractErrorCodeXML(body []byte) string { + // regular expression is much easier than dealing with the XML parser + rx := regexp.MustCompile(`<(?:\w+:)?[c|C]ode>\s*(\w+)\s*<\/(?:\w+:)?[c|C]ode>`) + res := rx.FindStringSubmatch(string(body)) + if len(res) != 2 { + return "" + } + // first submatch is the entire thing, second one is the captured error code + return res[1] +} + +// ResponseError is returned when a request is made to a service and +// the service returns a non-success HTTP status code. +// Use errors.As() to access this type in the error chain. +// Exported as azcore.ResponseError. +type ResponseError struct { + // ErrorCode is the error code returned by the resource provider if available. + ErrorCode string + + // StatusCode is the HTTP status code as defined in https://pkg.go.dev/net/http#pkg-constants. + StatusCode int + + // RawResponse is the underlying HTTP response. + RawResponse *http.Response +} + +// Error implements the error interface for type ResponseError. +// Note that the message contents are not contractual and can change over time. +func (e *ResponseError) Error() string { + // write the request method and URL with response status code + msg := &bytes.Buffer{} + fmt.Fprintf(msg, "%s %s://%s%s\n", e.RawResponse.Request.Method, e.RawResponse.Request.URL.Scheme, e.RawResponse.Request.URL.Host, e.RawResponse.Request.URL.Path) + fmt.Fprintln(msg, "--------------------------------------------------------------------------------") + fmt.Fprintf(msg, "RESPONSE %d: %s\n", e.RawResponse.StatusCode, e.RawResponse.Status) + if e.ErrorCode != "" { + fmt.Fprintf(msg, "ERROR CODE: %s\n", e.ErrorCode) + } else { + fmt.Fprintln(msg, "ERROR CODE UNAVAILABLE") + } + fmt.Fprintln(msg, "--------------------------------------------------------------------------------") + body, err := Payload(e.RawResponse) + if err != nil { + // this really shouldn't fail at this point as the response + // body is already cached (it was read in NewResponseError) + fmt.Fprintf(msg, "Error reading response body: %v", err) + } else if len(body) > 0 { + if err := json.Indent(msg, body, "", " "); err != nil { + // failed to pretty-print so just dump it verbatim + fmt.Fprint(msg, string(body)) + } + // the standard library doesn't have a pretty-printer for XML + fmt.Fprintln(msg) + } else { + fmt.Fprintln(msg, "Response contained no body") + } + fmt.Fprintln(msg, "--------------------------------------------------------------------------------") + + return msg.String() +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/log/log.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/log/log.go new file mode 100644 index 00000000000..0684cb31739 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/log/log.go @@ -0,0 +1,38 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// This is an internal helper package to combine the complete logging APIs. +package log + +import ( + azlog "github.com/Azure/azure-sdk-for-go/sdk/azcore/log" + "github.com/Azure/azure-sdk-for-go/sdk/internal/log" +) + +type Event = log.Event + +const ( + EventRequest = azlog.EventRequest + EventResponse = azlog.EventResponse + EventRetryPolicy = azlog.EventRetryPolicy + EventLRO = azlog.EventLRO +) + +func Write(cls log.Event, msg string) { + log.Write(cls, msg) +} + +func Writef(cls log.Event, format string, a ...interface{}) { + log.Writef(cls, format, a...) +} + +func SetListener(lst func(Event, string)) { + log.SetListener(lst) +} + +func Should(cls log.Event) bool { + return log.Should(cls) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/async/async.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/async/async.go new file mode 100644 index 00000000000..d34f161c7b0 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/async/async.go @@ -0,0 +1,158 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package async + +import ( + "context" + "errors" + "fmt" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/log" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" +) + +// see https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/async-api-reference.md + +// Applicable returns true if the LRO is using Azure-AsyncOperation. +func Applicable(resp *http.Response) bool { + return resp.Header.Get(shared.HeaderAzureAsync) != "" +} + +// CanResume returns true if the token can rehydrate this poller type. +func CanResume(token map[string]interface{}) bool { + _, ok := token["asyncURL"] + return ok +} + +// Poller is an LRO poller that uses the Azure-AsyncOperation pattern. +type Poller[T any] struct { + pl exported.Pipeline + + resp *http.Response + + // The URL from Azure-AsyncOperation header. + AsyncURL string `json:"asyncURL"` + + // The URL from Location header. + LocURL string `json:"locURL"` + + // The URL from the initial LRO request. + OrigURL string `json:"origURL"` + + // The HTTP method from the initial LRO request. + Method string `json:"method"` + + // The value of final-state-via from swagger, can be the empty string. + FinalState pollers.FinalStateVia `json:"finalState"` + + // The LRO's current state. + CurState string `json:"state"` +} + +// New creates a new Poller from the provided initial response and final-state type. +// Pass nil for response to create an empty Poller for rehydration. +func New[T any](pl exported.Pipeline, resp *http.Response, finalState pollers.FinalStateVia) (*Poller[T], error) { + if resp == nil { + log.Write(log.EventLRO, "Resuming Azure-AsyncOperation poller.") + return &Poller[T]{pl: pl}, nil + } + log.Write(log.EventLRO, "Using Azure-AsyncOperation poller.") + asyncURL := resp.Header.Get(shared.HeaderAzureAsync) + if asyncURL == "" { + return nil, errors.New("response is missing Azure-AsyncOperation header") + } + if !pollers.IsValidURL(asyncURL) { + return nil, fmt.Errorf("invalid polling URL %s", asyncURL) + } + // check for provisioning state. if the operation is a RELO + // and terminates synchronously this will prevent extra polling. + // it's ok if there's no provisioning state. + state, _ := pollers.GetProvisioningState(resp) + if state == "" { + state = pollers.StatusInProgress + } + p := &Poller[T]{ + pl: pl, + resp: resp, + AsyncURL: asyncURL, + LocURL: resp.Header.Get(shared.HeaderLocation), + OrigURL: resp.Request.URL.String(), + Method: resp.Request.Method, + FinalState: finalState, + CurState: state, + } + return p, nil +} + +// Done returns true if the LRO is in a terminal state. +func (p *Poller[T]) Done() bool { + return pollers.IsTerminalState(p.CurState) +} + +// Poll retrieves the current state of the LRO. +func (p *Poller[T]) Poll(ctx context.Context) (*http.Response, error) { + err := pollers.PollHelper(ctx, p.AsyncURL, p.pl, func(resp *http.Response) (string, error) { + if !pollers.StatusCodeValid(resp) { + p.resp = resp + return "", exported.NewResponseError(resp) + } + state, err := pollers.GetStatus(resp) + if err != nil { + return "", err + } else if state == "" { + return "", errors.New("the response did not contain a status") + } + p.resp = resp + p.CurState = state + return p.CurState, nil + }) + if err != nil { + return nil, err + } + return p.resp, nil +} + +func (p *Poller[T]) Result(ctx context.Context, out *T) error { + if p.resp.StatusCode == http.StatusNoContent { + return nil + } else if pollers.Failed(p.CurState) { + return exported.NewResponseError(p.resp) + } + var req *exported.Request + var err error + if p.Method == http.MethodPatch || p.Method == http.MethodPut { + // for PATCH and PUT, the final GET is on the original resource URL + req, err = exported.NewRequest(ctx, http.MethodGet, p.OrigURL) + } else if p.Method == http.MethodPost { + if p.FinalState == pollers.FinalStateViaAzureAsyncOp { + // no final GET required + } else if p.FinalState == pollers.FinalStateViaOriginalURI { + req, err = exported.NewRequest(ctx, http.MethodGet, p.OrigURL) + } else if p.LocURL != "" { + // ideally FinalState would be set to "location" but it isn't always. + // must check last due to more permissive condition. + req, err = exported.NewRequest(ctx, http.MethodGet, p.LocURL) + } + } + if err != nil { + return err + } + + // if a final GET request has been created, execute it + if req != nil { + resp, err := p.pl.Do(req) + if err != nil { + return err + } + p.resp = resp + } + + return pollers.ResultHelper(p.resp, pollers.Failed(p.CurState), out) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/body/body.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/body/body.go new file mode 100644 index 00000000000..7efdd8a0df1 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/body/body.go @@ -0,0 +1,134 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package body + +import ( + "context" + "errors" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/log" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers" +) + +// Kind is the identifier of this type in a resume token. +const kind = "body" + +// Applicable returns true if the LRO is using no headers, just provisioning state. +// This is only applicable to PATCH and PUT methods and assumes no polling headers. +func Applicable(resp *http.Response) bool { + // we can't check for absense of headers due to some misbehaving services + // like redis that return a Location header but don't actually use that protocol + return resp.Request.Method == http.MethodPatch || resp.Request.Method == http.MethodPut +} + +// CanResume returns true if the token can rehydrate this poller type. +func CanResume(token map[string]interface{}) bool { + t, ok := token["type"] + if !ok { + return false + } + tt, ok := t.(string) + if !ok { + return false + } + return tt == kind +} + +// Poller is an LRO poller that uses the Body pattern. +type Poller[T any] struct { + pl exported.Pipeline + + resp *http.Response + + // The poller's type, used for resume token processing. + Type string `json:"type"` + + // The URL for polling. + PollURL string `json:"pollURL"` + + // The LRO's current state. + CurState string `json:"state"` +} + +// New creates a new Poller from the provided initial response. +// Pass nil for response to create an empty Poller for rehydration. +func New[T any](pl exported.Pipeline, resp *http.Response) (*Poller[T], error) { + if resp == nil { + log.Write(log.EventLRO, "Resuming Body poller.") + return &Poller[T]{pl: pl}, nil + } + log.Write(log.EventLRO, "Using Body poller.") + p := &Poller[T]{ + pl: pl, + resp: resp, + Type: kind, + PollURL: resp.Request.URL.String(), + } + // default initial state to InProgress. depending on the HTTP + // status code and provisioning state, we might change the value. + curState := pollers.StatusInProgress + provState, err := pollers.GetProvisioningState(resp) + if err != nil && !errors.Is(err, pollers.ErrNoBody) { + return nil, err + } + if resp.StatusCode == http.StatusCreated && provState != "" { + // absense of provisioning state is ok for a 201, means the operation is in progress + curState = provState + } else if resp.StatusCode == http.StatusOK { + if provState != "" { + curState = provState + } else if provState == "" { + // for a 200, absense of provisioning state indicates success + curState = pollers.StatusSucceeded + } + } else if resp.StatusCode == http.StatusNoContent { + curState = pollers.StatusSucceeded + } + p.CurState = curState + return p, nil +} + +func (p *Poller[T]) Done() bool { + return pollers.IsTerminalState(p.CurState) +} + +func (p *Poller[T]) Poll(ctx context.Context) (*http.Response, error) { + err := pollers.PollHelper(ctx, p.PollURL, p.pl, func(resp *http.Response) (string, error) { + if !pollers.StatusCodeValid(resp) { + p.resp = resp + return "", exported.NewResponseError(resp) + } + if resp.StatusCode == http.StatusNoContent { + p.resp = resp + p.CurState = pollers.StatusSucceeded + return p.CurState, nil + } + state, err := pollers.GetProvisioningState(resp) + if errors.Is(err, pollers.ErrNoBody) { + // a missing response body in non-204 case is an error + return "", err + } else if state == "" { + // a response body without provisioning state is considered terminal success + state = pollers.StatusSucceeded + } else if err != nil { + return "", err + } + p.resp = resp + p.CurState = state + return p.CurState, nil + }) + if err != nil { + return nil, err + } + return p.resp, nil +} + +func (p *Poller[T]) Result(ctx context.Context, out *T) error { + return pollers.ResultHelper(p.resp, pollers.Failed(p.CurState), out) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/loc/loc.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/loc/loc.go new file mode 100644 index 00000000000..276685da443 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/loc/loc.go @@ -0,0 +1,118 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package loc + +import ( + "context" + "errors" + "fmt" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/log" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" +) + +// Kind is the identifier of this type in a resume token. +const kind = "loc" + +// Applicable returns true if the LRO is using Location. +func Applicable(resp *http.Response) bool { + return resp.Header.Get(shared.HeaderLocation) != "" +} + +// CanResume returns true if the token can rehydrate this poller type. +func CanResume(token map[string]interface{}) bool { + t, ok := token["type"] + if !ok { + return false + } + tt, ok := t.(string) + if !ok { + return false + } + return tt == kind +} + +// Poller is an LRO poller that uses the Location pattern. +type Poller[T any] struct { + pl exported.Pipeline + resp *http.Response + + Type string `json:"type"` + PollURL string `json:"pollURL"` + CurState string `json:"state"` +} + +// New creates a new Poller from the provided initial response. +// Pass nil for response to create an empty Poller for rehydration. +func New[T any](pl exported.Pipeline, resp *http.Response) (*Poller[T], error) { + if resp == nil { + log.Write(log.EventLRO, "Resuming Location poller.") + return &Poller[T]{pl: pl}, nil + } + log.Write(log.EventLRO, "Using Location poller.") + locURL := resp.Header.Get(shared.HeaderLocation) + if locURL == "" { + return nil, errors.New("response is missing Location header") + } + if !pollers.IsValidURL(locURL) { + return nil, fmt.Errorf("invalid polling URL %s", locURL) + } + // check for provisioning state. if the operation is a RELO + // and terminates synchronously this will prevent extra polling. + // it's ok if there's no provisioning state. + state, _ := pollers.GetProvisioningState(resp) + if state == "" { + state = pollers.StatusInProgress + } + return &Poller[T]{ + pl: pl, + resp: resp, + Type: kind, + PollURL: locURL, + CurState: state, + }, nil +} + +func (p *Poller[T]) Done() bool { + return pollers.IsTerminalState(p.CurState) +} + +func (p *Poller[T]) Poll(ctx context.Context) (*http.Response, error) { + err := pollers.PollHelper(ctx, p.PollURL, p.pl, func(resp *http.Response) (string, error) { + // location polling can return an updated polling URL + if h := resp.Header.Get(shared.HeaderLocation); h != "" { + p.PollURL = h + } + // if provisioning state is available, use that. this is only + // for some ARM LRO scenarios (e.g. DELETE with a Location header) + // so if it's missing then use HTTP status code. + provState, _ := pollers.GetProvisioningState(resp) + p.resp = resp + if provState != "" { + p.CurState = provState + } else if resp.StatusCode == http.StatusAccepted { + p.CurState = pollers.StatusInProgress + } else if resp.StatusCode > 199 && resp.StatusCode < 300 { + // any 2xx other than a 202 indicates success + p.CurState = pollers.StatusSucceeded + } else { + p.CurState = pollers.StatusFailed + } + return p.CurState, nil + }) + if err != nil { + return nil, err + } + return p.resp, nil +} + +func (p *Poller[T]) Result(ctx context.Context, out *T) error { + return pollers.ResultHelper(p.resp, pollers.Failed(p.CurState), out) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/op/op.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/op/op.go new file mode 100644 index 00000000000..c3c648266a2 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/op/op.go @@ -0,0 +1,144 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package op + +import ( + "context" + "errors" + "fmt" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/log" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" +) + +// Applicable returns true if the LRO is using Operation-Location. +func Applicable(resp *http.Response) bool { + return resp.Header.Get(shared.HeaderOperationLocation) != "" +} + +// CanResume returns true if the token can rehydrate this poller type. +func CanResume(token map[string]interface{}) bool { + _, ok := token["oplocURL"] + return ok +} + +// Poller is an LRO poller that uses the Operation-Location pattern. +type Poller[T any] struct { + pl exported.Pipeline + resp *http.Response + + OpLocURL string `json:"oplocURL"` + LocURL string `json:"locURL"` + OrigURL string `json:"origURL"` + Method string `json:"method"` + FinalState pollers.FinalStateVia `json:"finalState"` + CurState string `json:"state"` +} + +// New creates a new Poller from the provided initial response. +// Pass nil for response to create an empty Poller for rehydration. +func New[T any](pl exported.Pipeline, resp *http.Response, finalState pollers.FinalStateVia) (*Poller[T], error) { + if resp == nil { + log.Write(log.EventLRO, "Resuming Operation-Location poller.") + return &Poller[T]{pl: pl}, nil + } + log.Write(log.EventLRO, "Using Operation-Location poller.") + opURL := resp.Header.Get(shared.HeaderOperationLocation) + if opURL == "" { + return nil, errors.New("response is missing Operation-Location header") + } + if !pollers.IsValidURL(opURL) { + return nil, fmt.Errorf("invalid Operation-Location URL %s", opURL) + } + locURL := resp.Header.Get(shared.HeaderLocation) + // Location header is optional + if locURL != "" && !pollers.IsValidURL(locURL) { + return nil, fmt.Errorf("invalid Location URL %s", locURL) + } + // default initial state to InProgress. if the + // service sent us a status then use that instead. + curState := pollers.StatusInProgress + status, err := pollers.GetStatus(resp) + if err != nil && !errors.Is(err, pollers.ErrNoBody) { + return nil, err + } + if status != "" { + curState = status + } + + return &Poller[T]{ + pl: pl, + resp: resp, + OpLocURL: opURL, + LocURL: locURL, + OrigURL: resp.Request.URL.String(), + Method: resp.Request.Method, + FinalState: finalState, + CurState: curState, + }, nil +} + +func (p *Poller[T]) Done() bool { + return pollers.IsTerminalState(p.CurState) +} + +func (p *Poller[T]) Poll(ctx context.Context) (*http.Response, error) { + err := pollers.PollHelper(ctx, p.OpLocURL, p.pl, func(resp *http.Response) (string, error) { + if !pollers.StatusCodeValid(resp) { + p.resp = resp + return "", exported.NewResponseError(resp) + } + state, err := pollers.GetStatus(resp) + if err != nil { + return "", err + } else if state == "" { + return "", errors.New("the response did not contain a status") + } + p.resp = resp + p.CurState = state + return p.CurState, nil + }) + if err != nil { + return nil, err + } + return p.resp, nil +} + +func (p *Poller[T]) Result(ctx context.Context, out *T) error { + var req *exported.Request + var err error + if p.FinalState == pollers.FinalStateViaLocation && p.LocURL != "" { + req, err = exported.NewRequest(ctx, http.MethodGet, p.LocURL) + } else if p.FinalState == pollers.FinalStateViaOpLocation && p.Method == http.MethodPost { + // no final GET required, terminal response should have it + } else if rl, rlErr := pollers.GetResourceLocation(p.resp); rlErr != nil && !errors.Is(rlErr, pollers.ErrNoBody) { + return rlErr + } else if rl != "" { + req, err = exported.NewRequest(ctx, http.MethodGet, rl) + } else if p.Method == http.MethodPatch || p.Method == http.MethodPut { + req, err = exported.NewRequest(ctx, http.MethodGet, p.OrigURL) + } else if p.Method == http.MethodPost && p.LocURL != "" { + req, err = exported.NewRequest(ctx, http.MethodGet, p.LocURL) + } + if err != nil { + return err + } + + // if a final GET request has been created, execute it + if req != nil { + resp, err := p.pl.Do(req) + if err != nil { + return err + } + p.resp = resp + } + + return pollers.ResultHelper(p.resp, pollers.Failed(p.CurState), out) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/poller.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/poller.go new file mode 100644 index 00000000000..37ed647f4e0 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/poller.go @@ -0,0 +1,24 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package pollers + +// FinalStateVia is the enumerated type for the possible final-state-via values. +type FinalStateVia string + +const ( + // FinalStateViaAzureAsyncOp indicates the final payload comes from the Azure-AsyncOperation URL. + FinalStateViaAzureAsyncOp FinalStateVia = "azure-async-operation" + + // FinalStateViaLocation indicates the final payload comes from the Location URL. + FinalStateViaLocation FinalStateVia = "location" + + // FinalStateViaOriginalURI indicates the final payload comes from the original URL. + FinalStateViaOriginalURI FinalStateVia = "original-uri" + + // FinalStateViaOpLocation indicates the final payload comes from the Operation-Location URL. + FinalStateViaOpLocation FinalStateVia = "operation-location" +) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/util.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/util.go new file mode 100644 index 00000000000..17ab7dadc3f --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/util.go @@ -0,0 +1,317 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package pollers + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "reflect" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/log" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" +) + +// the well-known set of LRO status/provisioning state values. +const ( + StatusSucceeded = "Succeeded" + StatusCanceled = "Canceled" + StatusFailed = "Failed" + StatusInProgress = "InProgress" +) + +// IsTerminalState returns true if the LRO's state is terminal. +func IsTerminalState(s string) bool { + return strings.EqualFold(s, StatusSucceeded) || strings.EqualFold(s, StatusFailed) || strings.EqualFold(s, StatusCanceled) +} + +// Failed returns true if the LRO's state is terminal failure. +func Failed(s string) bool { + return strings.EqualFold(s, StatusFailed) || strings.EqualFold(s, StatusCanceled) +} + +// Succeeded returns true if the LRO's state is terminal success. +func Succeeded(s string) bool { + return strings.EqualFold(s, StatusSucceeded) +} + +// returns true if the LRO response contains a valid HTTP status code +func StatusCodeValid(resp *http.Response) bool { + return exported.HasStatusCode(resp, http.StatusOK, http.StatusAccepted, http.StatusCreated, http.StatusNoContent) +} + +// IsValidURL verifies that the URL is valid and absolute. +func IsValidURL(s string) bool { + u, err := url.Parse(s) + return err == nil && u.IsAbs() +} + +// getTokenTypeName creates a type name from the type parameter T. +func getTokenTypeName[T any]() (string, error) { + tt := shared.TypeOfT[T]() + var n string + if tt.Kind() == reflect.Pointer { + n = "*" + tt = tt.Elem() + } + n += tt.Name() + if n == "" { + return "", errors.New("nameless types are not allowed") + } + return n, nil +} + +type resumeTokenWrapper[T any] struct { + Type string `json:"type"` + Token T `json:"token"` +} + +// NewResumeToken creates a resume token from the specified type. +// An error is returned if the generic type has no name (e.g. struct{}). +func NewResumeToken[TResult, TSource any](from TSource) (string, error) { + n, err := getTokenTypeName[TResult]() + if err != nil { + return "", err + } + b, err := json.Marshal(resumeTokenWrapper[TSource]{ + Type: n, + Token: from, + }) + if err != nil { + return "", err + } + return string(b), nil +} + +// ExtractToken returns the poller-specific token information from the provided token value. +func ExtractToken(token string) ([]byte, error) { + raw := map[string]json.RawMessage{} + if err := json.Unmarshal([]byte(token), &raw); err != nil { + return nil, err + } + // this is dependent on the type resumeTokenWrapper[T] + tk, ok := raw["token"] + if !ok { + return nil, errors.New("missing token value") + } + return tk, nil +} + +// IsTokenValid returns an error if the specified token isn't applicable for generic type T. +func IsTokenValid[T any](token string) error { + raw := map[string]interface{}{} + if err := json.Unmarshal([]byte(token), &raw); err != nil { + return err + } + t, ok := raw["type"] + if !ok { + return errors.New("missing type value") + } + tt, ok := t.(string) + if !ok { + return fmt.Errorf("invalid type format %T", t) + } + n, err := getTokenTypeName[T]() + if err != nil { + return err + } + if tt != n { + return fmt.Errorf("cannot resume from this poller token. token is for type %s, not %s", tt, n) + } + return nil +} + +// ErrNoBody is returned if the response didn't contain a body. +var ErrNoBody = errors.New("the response did not contain a body") + +// GetJSON reads the response body into a raw JSON object. +// It returns ErrNoBody if there was no content. +func GetJSON(resp *http.Response) (map[string]interface{}, error) { + body, err := exported.Payload(resp) + if err != nil { + return nil, err + } + if len(body) == 0 { + return nil, ErrNoBody + } + // unmarshall the body to get the value + var jsonBody map[string]interface{} + if err = json.Unmarshal(body, &jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// provisioningState returns the provisioning state from the response or the empty string. +func provisioningState(jsonBody map[string]interface{}) string { + jsonProps, ok := jsonBody["properties"] + if !ok { + return "" + } + props, ok := jsonProps.(map[string]interface{}) + if !ok { + return "" + } + rawPs, ok := props["provisioningState"] + if !ok { + return "" + } + ps, ok := rawPs.(string) + if !ok { + return "" + } + return ps +} + +// status returns the status from the response or the empty string. +func status(jsonBody map[string]interface{}) string { + rawStatus, ok := jsonBody["status"] + if !ok { + return "" + } + status, ok := rawStatus.(string) + if !ok { + return "" + } + return status +} + +// GetStatus returns the LRO's status from the response body. +// Typically used for Azure-AsyncOperation flows. +// If there is no status in the response body the empty string is returned. +func GetStatus(resp *http.Response) (string, error) { + jsonBody, err := GetJSON(resp) + if err != nil { + return "", err + } + return status(jsonBody), nil +} + +// GetProvisioningState returns the LRO's state from the response body. +// If there is no state in the response body the empty string is returned. +func GetProvisioningState(resp *http.Response) (string, error) { + jsonBody, err := GetJSON(resp) + if err != nil { + return "", err + } + return provisioningState(jsonBody), nil +} + +// GetResourceLocation returns the LRO's resourceLocation value from the response body. +// Typically used for Operation-Location flows. +// If there is no resourceLocation in the response body the empty string is returned. +func GetResourceLocation(resp *http.Response) (string, error) { + jsonBody, err := GetJSON(resp) + if err != nil { + return "", err + } + v, ok := jsonBody["resourceLocation"] + if !ok { + // it might be ok if the field doesn't exist, the caller must make that determination + return "", nil + } + vv, ok := v.(string) + if !ok { + return "", fmt.Errorf("the resourceLocation value %v was not in string format", v) + } + return vv, nil +} + +// used if the operation synchronously completed +type NopPoller[T any] struct { + resp *http.Response + result T +} + +// NewNopPoller creates a NopPoller from the provided response. +// It unmarshals the response body into an instance of T. +func NewNopPoller[T any](resp *http.Response) (*NopPoller[T], error) { + np := &NopPoller[T]{resp: resp} + if resp.StatusCode == http.StatusNoContent { + return np, nil + } + payload, err := exported.Payload(resp) + if err != nil { + return nil, err + } + if len(payload) == 0 { + return np, nil + } + if err = json.Unmarshal(payload, &np.result); err != nil { + return nil, err + } + return np, nil +} + +func (*NopPoller[T]) Done() bool { + return true +} + +func (p *NopPoller[T]) Poll(context.Context) (*http.Response, error) { + return p.resp, nil +} + +func (p *NopPoller[T]) Result(ctx context.Context, out *T) error { + *out = p.result + return nil +} + +// PollHelper creates and executes the request, calling update() with the response. +// If the request fails, the update func is not called. +// The update func returns the state of the operation for logging purposes or an error +// if it fails to extract the required state from the response. +func PollHelper(ctx context.Context, endpoint string, pl exported.Pipeline, update func(resp *http.Response) (string, error)) error { + req, err := exported.NewRequest(ctx, http.MethodGet, endpoint) + if err != nil { + return err + } + resp, err := pl.Do(req) + if err != nil { + return err + } + state, err := update(resp) + if err != nil { + return err + } + log.Writef(log.EventLRO, "State %s", state) + return nil +} + +// ResultHelper processes the response as success or failure. +// In the success case, it unmarshals the payload into either a new instance of T or out. +// In the failure case, it creates an *azcore.Response error from the response. +func ResultHelper[T any](resp *http.Response, failed bool, out *T) error { + // short-circuit the simple success case with no response body to unmarshal + if resp.StatusCode == http.StatusNoContent { + return nil + } + + defer resp.Body.Close() + if !StatusCodeValid(resp) || failed { + // the LRO failed. unmarshall the error and update state + return exported.NewResponseError(resp) + } + + // success case + payload, err := exported.Payload(resp) + if err != nil { + return err + } + if len(payload) == 0 { + return nil + } + + if err = json.Unmarshal(payload, out); err != nil { + return err + } + return nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared/constants.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared/constants.go new file mode 100644 index 00000000000..0fe2e2cb7fd --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared/constants.go @@ -0,0 +1,34 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package shared + +const ( + ContentTypeAppJSON = "application/json" + ContentTypeAppXML = "application/xml" +) + +const ( + HeaderAuthorization = "Authorization" + HeaderAuxiliaryAuthorization = "x-ms-authorization-auxiliary" + HeaderAzureAsync = "Azure-AsyncOperation" + HeaderContentLength = "Content-Length" + HeaderContentType = "Content-Type" + HeaderLocation = "Location" + HeaderOperationLocation = "Operation-Location" + HeaderRetryAfter = "Retry-After" + HeaderUserAgent = "User-Agent" +) + +const BearerTokenPrefix = "Bearer " + +const ( + // Module is the name of the calling module used in telemetry data. + Module = "azcore" + + // Version is the semantic version (see http://semver.org) of this module. + Version = "v1.3.1" +) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared/shared.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared/shared.go new file mode 100644 index 00000000000..7c71df30700 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared/shared.go @@ -0,0 +1,159 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package shared + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "reflect" + "regexp" + "strconv" + "strings" + "time" +) + +// CtxWithHTTPHeaderKey is used as a context key for adding/retrieving http.Header. +type CtxWithHTTPHeaderKey struct{} + +// CtxWithRetryOptionsKey is used as a context key for adding/retrieving RetryOptions. +type CtxWithRetryOptionsKey struct{} + +// CtxIncludeResponseKey is used as a context key for retrieving the raw response. +type CtxIncludeResponseKey struct{} + +// Delay waits for the duration to elapse or the context to be cancelled. +func Delay(ctx context.Context, delay time.Duration) error { + select { + case <-time.After(delay): + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +// RetryAfter returns non-zero if the response contains a Retry-After header value. +func RetryAfter(resp *http.Response) time.Duration { + if resp == nil { + return 0 + } + ra := resp.Header.Get(HeaderRetryAfter) + if ra == "" { + return 0 + } + // retry-after values are expressed in either number of + // seconds or an HTTP-date indicating when to try again + if retryAfter, _ := strconv.Atoi(ra); retryAfter > 0 { + return time.Duration(retryAfter) * time.Second + } else if t, err := time.Parse(time.RFC1123, ra); err == nil { + return time.Until(t) + } + return 0 +} + +// TypeOfT returns the type of the generic type param. +func TypeOfT[T any]() reflect.Type { + // you can't, at present, obtain the type of + // a type parameter, so this is the trick + return reflect.TypeOf((*T)(nil)).Elem() +} + +// BytesSetter abstracts replacing a byte slice on some type. +type BytesSetter interface { + Set(b []byte) +} + +// NewNopClosingBytesReader creates a new *NopClosingBytesReader for the specified slice. +func NewNopClosingBytesReader(data []byte) *NopClosingBytesReader { + return &NopClosingBytesReader{s: data} +} + +// NopClosingBytesReader is an io.ReadSeekCloser around a byte slice. +// It also provides direct access to the byte slice to avoid rereading. +type NopClosingBytesReader struct { + s []byte + i int64 +} + +// Bytes returns the underlying byte slice. +func (r *NopClosingBytesReader) Bytes() []byte { + return r.s +} + +// Close implements the io.Closer interface. +func (*NopClosingBytesReader) Close() error { + return nil +} + +// Read implements the io.Reader interface. +func (r *NopClosingBytesReader) Read(b []byte) (n int, err error) { + if r.i >= int64(len(r.s)) { + return 0, io.EOF + } + n = copy(b, r.s[r.i:]) + r.i += int64(n) + return +} + +// Set replaces the existing byte slice with the specified byte slice and resets the reader. +func (r *NopClosingBytesReader) Set(b []byte) { + r.s = b + r.i = 0 +} + +// Seek implements the io.Seeker interface. +func (r *NopClosingBytesReader) Seek(offset int64, whence int) (int64, error) { + var i int64 + switch whence { + case io.SeekStart: + i = offset + case io.SeekCurrent: + i = r.i + offset + case io.SeekEnd: + i = int64(len(r.s)) + offset + default: + return 0, errors.New("nopClosingBytesReader: invalid whence") + } + if i < 0 { + return 0, errors.New("nopClosingBytesReader: negative position") + } + r.i = i + return i, nil +} + +var _ BytesSetter = (*NopClosingBytesReader)(nil) + +// TransportFunc is a helper to use a first-class func to satisfy the Transporter interface. +type TransportFunc func(*http.Request) (*http.Response, error) + +// Do implements the Transporter interface for the TransportFunc type. +func (pf TransportFunc) Do(req *http.Request) (*http.Response, error) { + return pf(req) +} + +// ValidateModVer verifies that moduleVersion is a valid semver 2.0 string. +func ValidateModVer(moduleVersion string) error { + modVerRegx := regexp.MustCompile(`^v\d+\.\d+\.\d+(?:-[a-zA-Z0-9_.-]+)?$`) + if !modVerRegx.MatchString(moduleVersion) { + return fmt.Errorf("malformed moduleVersion param value %s", moduleVersion) + } + return nil +} + +// ExtractPackageName returns "package" from "package.Client". +// If clientName is malformed, an error is returned. +func ExtractPackageName(clientName string) (string, error) { + pkg, client, ok := strings.Cut(clientName, ".") + if !ok { + return "", fmt.Errorf("missing . in clientName %s", clientName) + } else if pkg == "" || client == "" { + return "", fmt.Errorf("malformed clientName %s", clientName) + } + return pkg, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/log/doc.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/log/doc.go new file mode 100644 index 00000000000..2f3901bff3c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/log/doc.go @@ -0,0 +1,10 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright 2017 Microsoft Corporation. All rights reserved. +// Use of this source code is governed by an MIT +// license that can be found in the LICENSE file. + +// Package log contains functionality for configuring logging behavior. +// Default logging to stderr can be enabled by setting environment variable AZURE_SDK_GO_LOGGING to "all". +package log diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/log/log.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/log/log.go new file mode 100644 index 00000000000..7bde29d0a46 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/log/log.go @@ -0,0 +1,50 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// Package log provides functionality for configuring logging facilities. +package log + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/internal/log" +) + +// Event is used to group entries. Each group can be toggled on or off. +type Event = log.Event + +const ( + // EventRequest entries contain information about HTTP requests. + // This includes information like the URL, query parameters, and headers. + EventRequest Event = "Request" + + // EventResponse entries contain information about HTTP responses. + // This includes information like the HTTP status code, headers, and request URL. + EventResponse Event = "Response" + + // EventRetryPolicy entries contain information specific to the retry policy in use. + EventRetryPolicy Event = "Retry" + + // EventLRO entries contain information specific to long-running operations. + // This includes information like polling location, operation state, and sleep intervals. + EventLRO Event = "LongRunningOperation" +) + +// SetEvents is used to control which events are written to +// the log. By default all log events are writen. +// NOTE: this is not goroutine safe and should be called before using SDK clients. +func SetEvents(cls ...Event) { + log.SetEvents(cls...) +} + +// SetListener will set the Logger to write to the specified Listener. +// NOTE: this is not goroutine safe and should be called before using SDK clients. +func SetListener(lst func(Event, string)) { + log.SetListener(lst) +} + +// for testing purposes +func resetEvents() { + log.TestResetEvents() +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/policy/doc.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/policy/doc.go new file mode 100644 index 00000000000..fad2579ed6c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/policy/doc.go @@ -0,0 +1,10 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright 2017 Microsoft Corporation. All rights reserved. +// Use of this source code is governed by an MIT +// license that can be found in the LICENSE file. + +// Package policy contains the definitions needed for configuring in-box pipeline policies +// and creating custom policies. +package policy diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/policy/policy.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/policy/policy.go new file mode 100644 index 00000000000..c427e14d88c --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/policy/policy.go @@ -0,0 +1,155 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package policy + +import ( + "net/http" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/tracing" +) + +// Policy represents an extensibility point for the Pipeline that can mutate the specified +// Request and react to the received Response. +type Policy = exported.Policy + +// Transporter represents an HTTP pipeline transport used to send HTTP requests and receive responses. +type Transporter = exported.Transporter + +// Request is an abstraction over the creation of an HTTP request as it passes through the pipeline. +// Don't use this type directly, use runtime.NewRequest() instead. +type Request = exported.Request + +// ClientOptions contains optional settings for a client's pipeline. +// All zero-value fields will be initialized with default values. +type ClientOptions struct { + // APIVersion overrides the default version requested of the service. Set with caution as this package version has not been tested with arbitrary service versions. + APIVersion string + + // Cloud specifies a cloud for the client. The default is Azure Public Cloud. + Cloud cloud.Configuration + + // Logging configures the built-in logging policy. + Logging LogOptions + + // Retry configures the built-in retry policy. + Retry RetryOptions + + // Telemetry configures the built-in telemetry policy. + Telemetry TelemetryOptions + + // TracingProvider configures the tracing provider. + // It defaults to a no-op tracer. + TracingProvider tracing.Provider + + // Transport sets the transport for HTTP requests. + Transport Transporter + + // PerCallPolicies contains custom policies to inject into the pipeline. + // Each policy is executed once per request. + PerCallPolicies []Policy + + // PerRetryPolicies contains custom policies to inject into the pipeline. + // Each policy is executed once per request, and for each retry of that request. + PerRetryPolicies []Policy +} + +// LogOptions configures the logging policy's behavior. +type LogOptions struct { + // IncludeBody indicates if request and response bodies should be included in logging. + // The default value is false. + // NOTE: enabling this can lead to disclosure of sensitive information, use with care. + IncludeBody bool + + // AllowedHeaders is the slice of headers to log with their values intact. + // All headers not in the slice will have their values REDACTED. + // Applies to request and response headers. + AllowedHeaders []string + + // AllowedQueryParams is the slice of query parameters to log with their values intact. + // All query parameters not in the slice will have their values REDACTED. + AllowedQueryParams []string +} + +// RetryOptions configures the retry policy's behavior. +// Zero-value fields will have their specified default values applied during use. +// This allows for modification of a subset of fields. +type RetryOptions struct { + // MaxRetries specifies the maximum number of attempts a failed operation will be retried + // before producing an error. + // The default value is three. A value less than zero means one try and no retries. + MaxRetries int32 + + // TryTimeout indicates the maximum time allowed for any single try of an HTTP request. + // This is disabled by default. Specify a value greater than zero to enable. + // NOTE: Setting this to a small value might cause premature HTTP request time-outs. + TryTimeout time.Duration + + // RetryDelay specifies the initial amount of delay to use before retrying an operation. + // The value is used only if the HTTP response does not contain a Retry-After header. + // The delay increases exponentially with each retry up to the maximum specified by MaxRetryDelay. + // The default value is four seconds. A value less than zero means no delay between retries. + RetryDelay time.Duration + + // MaxRetryDelay specifies the maximum delay allowed before retrying an operation. + // Typically the value is greater than or equal to the value specified in RetryDelay. + // The default Value is 120 seconds. A value less than zero means there is no cap. + MaxRetryDelay time.Duration + + // StatusCodes specifies the HTTP status codes that indicate the operation should be retried. + // A nil slice will use the following values. + // http.StatusRequestTimeout 408 + // http.StatusTooManyRequests 429 + // http.StatusInternalServerError 500 + // http.StatusBadGateway 502 + // http.StatusServiceUnavailable 503 + // http.StatusGatewayTimeout 504 + // Specifying values will replace the default values. + // Specifying an empty slice will disable retries for HTTP status codes. + StatusCodes []int +} + +// TelemetryOptions configures the telemetry policy's behavior. +type TelemetryOptions struct { + // ApplicationID is an application-specific identification string to add to the User-Agent. + // It has a maximum length of 24 characters and must not contain any spaces. + ApplicationID string + + // Disabled will prevent the addition of any telemetry data to the User-Agent. + Disabled bool +} + +// TokenRequestOptions contain specific parameter that may be used by credentials types when attempting to get a token. +type TokenRequestOptions = exported.TokenRequestOptions + +// BearerTokenOptions configures the bearer token policy's behavior. +type BearerTokenOptions struct { + // AuthorizationHandler allows SDK developers to run client-specific logic when BearerTokenPolicy must authorize a request. + // When this field isn't set, the policy follows its default behavior of authorizing every request with a bearer token from + // its given credential. + AuthorizationHandler AuthorizationHandler +} + +// AuthorizationHandler allows SDK developers to insert custom logic that runs when BearerTokenPolicy must authorize a request. +type AuthorizationHandler struct { + // OnRequest is called each time the policy receives a request. Its func parameter authorizes the request with a token + // from the policy's given credential. Implementations that need to perform I/O should use the Request's context, + // available from Request.Raw().Context(). When OnRequest returns an error, the policy propagates that error and doesn't + // send the request. When OnRequest is nil, the policy follows its default behavior, authorizing the request with a + // token from its credential according to its configuration. + OnRequest func(*Request, func(TokenRequestOptions) error) error + + // OnChallenge is called when the policy receives a 401 response, allowing the AuthorizationHandler to re-authorize the + // request according to an authentication challenge (the Response's WWW-Authenticate header). OnChallenge is responsible + // for parsing parameters from the challenge. Its func parameter will authorize the request with a token from the policy's + // given credential. Implementations that need to perform I/O should use the Request's context, available from + // Request.Raw().Context(). When OnChallenge returns nil, the policy will send the request again. When OnChallenge is nil, + // the policy will return any 401 response to the client. + OnChallenge func(*Request, *http.Response, func(TokenRequestOptions) error) error +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/doc.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/doc.go new file mode 100644 index 00000000000..c9cfa438cb3 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/doc.go @@ -0,0 +1,10 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright 2017 Microsoft Corporation. All rights reserved. +// Use of this source code is governed by an MIT +// license that can be found in the LICENSE file. + +// Package runtime contains various facilities for creating requests and handling responses. +// The content is intended for SDK authors. +package runtime diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/errors.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/errors.go new file mode 100644 index 00000000000..6d03b291ebf --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/errors.go @@ -0,0 +1,19 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" +) + +// NewResponseError creates an *azcore.ResponseError from the provided HTTP response. +// Call this when a service request returns a non-successful status code. +func NewResponseError(resp *http.Response) error { + return exported.NewResponseError(resp) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/pager.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/pager.go new file mode 100644 index 00000000000..5507665d651 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/pager.go @@ -0,0 +1,77 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "context" + "encoding/json" + "errors" +) + +// PagingHandler contains the required data for constructing a Pager. +type PagingHandler[T any] struct { + // More returns a boolean indicating if there are more pages to fetch. + // It uses the provided page to make the determination. + More func(T) bool + + // Fetcher fetches the first and subsequent pages. + Fetcher func(context.Context, *T) (T, error) +} + +// Pager provides operations for iterating over paged responses. +type Pager[T any] struct { + current *T + handler PagingHandler[T] + firstPage bool +} + +// NewPager creates an instance of Pager using the specified PagingHandler. +// Pass a non-nil T for firstPage if the first page has already been retrieved. +func NewPager[T any](handler PagingHandler[T]) *Pager[T] { + return &Pager[T]{ + handler: handler, + firstPage: true, + } +} + +// More returns true if there are more pages to retrieve. +func (p *Pager[T]) More() bool { + if p.current != nil { + return p.handler.More(*p.current) + } + return true +} + +// NextPage advances the pager to the next page. +func (p *Pager[T]) NextPage(ctx context.Context) (T, error) { + var resp T + var err error + if p.current != nil { + if p.firstPage { + // we get here if it's an LRO-pager, we already have the first page + p.firstPage = false + return *p.current, nil + } else if !p.handler.More(*p.current) { + return *new(T), errors.New("no more pages") + } + resp, err = p.handler.Fetcher(ctx, p.current) + } else { + // non-LRO case, first page + p.firstPage = false + resp, err = p.handler.Fetcher(ctx, nil) + } + if err != nil { + return *new(T), err + } + p.current = &resp + return *p.current, nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for Pager[T]. +func (p *Pager[T]) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, &p.current) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/pipeline.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/pipeline.go new file mode 100644 index 00000000000..a2906f51bca --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/pipeline.go @@ -0,0 +1,77 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" +) + +// PipelineOptions contains Pipeline options for SDK developers +type PipelineOptions struct { + AllowedHeaders, AllowedQueryParameters []string + APIVersion APIVersionOptions + PerCall, PerRetry []policy.Policy +} + +// Pipeline represents a primitive for sending HTTP requests and receiving responses. +// Its behavior can be extended by specifying policies during construction. +type Pipeline = exported.Pipeline + +// NewPipeline creates a pipeline from connection options, with any additional policies as specified. +// Policies from ClientOptions are placed after policies from PipelineOptions. +// The module and version parameters are used by the telemetry policy, when enabled. +func NewPipeline(module, version string, plOpts PipelineOptions, options *policy.ClientOptions) Pipeline { + cp := policy.ClientOptions{} + if options != nil { + cp = *options + } + if len(plOpts.AllowedHeaders) > 0 { + headers := make([]string, len(plOpts.AllowedHeaders)+len(cp.Logging.AllowedHeaders)) + copy(headers, plOpts.AllowedHeaders) + headers = append(headers, cp.Logging.AllowedHeaders...) + cp.Logging.AllowedHeaders = headers + } + if len(plOpts.AllowedQueryParameters) > 0 { + qp := make([]string, len(plOpts.AllowedQueryParameters)+len(cp.Logging.AllowedQueryParams)) + copy(qp, plOpts.AllowedQueryParameters) + qp = append(qp, cp.Logging.AllowedQueryParams...) + cp.Logging.AllowedQueryParams = qp + } + // we put the includeResponsePolicy at the very beginning so that the raw response + // is populated with the final response (some policies might mutate the response) + policies := []policy.Policy{policyFunc(includeResponsePolicy)} + if cp.APIVersion != "" { + policies = append(policies, newAPIVersionPolicy(cp.APIVersion, &plOpts.APIVersion)) + } + if !cp.Telemetry.Disabled { + policies = append(policies, NewTelemetryPolicy(module, version, &cp.Telemetry)) + } + policies = append(policies, plOpts.PerCall...) + policies = append(policies, cp.PerCallPolicies...) + policies = append(policies, NewRetryPolicy(&cp.Retry)) + policies = append(policies, plOpts.PerRetry...) + policies = append(policies, cp.PerRetryPolicies...) + policies = append(policies, NewLogPolicy(&cp.Logging)) + policies = append(policies, policyFunc(httpHeaderPolicy), policyFunc(bodyDownloadPolicy)) + transport := cp.Transport + if transport == nil { + transport = defaultHTTPClient + } + return exported.NewPipeline(transport, policies...) +} + +// policyFunc is a type that implements the Policy interface. +// Use this type when implementing a stateless policy as a first-class function. +type policyFunc func(*policy.Request) (*http.Response, error) + +// Do implements the Policy interface on policyFunc. +func (pf policyFunc) Do(req *policy.Request) (*http.Response, error) { + return pf(req) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_api_version.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_api_version.go new file mode 100644 index 00000000000..e5309aa6c15 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_api_version.go @@ -0,0 +1,75 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "errors" + "fmt" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" +) + +// APIVersionOptions contains options for API versions +type APIVersionOptions struct { + // Location indicates where to set the version on a request, for example in a header or query param + Location APIVersionLocation + // Name is the name of the header or query parameter, for example "api-version" + Name string +} + +// APIVersionLocation indicates which part of a request identifies the service version +type APIVersionLocation int + +const ( + // APIVersionLocationQueryParam indicates a query parameter + APIVersionLocationQueryParam = 0 + // APIVersionLocationHeader indicates a header + APIVersionLocationHeader = 1 +) + +// newAPIVersionPolicy constructs an APIVersionPolicy. If version is "", Do will be a no-op. If version +// isn't empty and opts.Name is empty, Do will return an error. +func newAPIVersionPolicy(version string, opts *APIVersionOptions) *apiVersionPolicy { + if opts == nil { + opts = &APIVersionOptions{} + } + return &apiVersionPolicy{location: opts.Location, name: opts.Name, version: version} +} + +// apiVersionPolicy enables users to set the API version of every request a client sends. +type apiVersionPolicy struct { + // location indicates whether "name" refers to a query parameter or header. + location APIVersionLocation + + // name of the query param or header whose value should be overridden; provided by the client. + name string + + // version is the value (provided by the user) that replaces the default version value. + version string +} + +// Do sets the request's API version, if the policy is configured to do so, replacing any prior value. +func (a *apiVersionPolicy) Do(req *policy.Request) (*http.Response, error) { + if a.version != "" { + if a.name == "" { + // user set ClientOptions.APIVersion but the client ctor didn't set PipelineOptions.APIVersionOptions + return nil, errors.New("this client doesn't support overriding its API version") + } + switch a.location { + case APIVersionLocationHeader: + req.Raw().Header.Set(a.name, a.version) + case APIVersionLocationQueryParam: + q := req.Raw().URL.Query() + q.Set(a.name, a.version) + req.Raw().URL.RawQuery = q.Encode() + default: + return nil, fmt.Errorf("unknown APIVersionLocation %d", a.location) + } + } + return req.Next() +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_bearer_token.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_bearer_token.go new file mode 100644 index 00000000000..b61e4c121f6 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_bearer_token.go @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "errors" + "net/http" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo" + "github.com/Azure/azure-sdk-for-go/sdk/internal/temporal" +) + +// BearerTokenPolicy authorizes requests with bearer tokens acquired from a TokenCredential. +type BearerTokenPolicy struct { + // mainResource is the resource to be retreived using the tenant specified in the credential + mainResource *temporal.Resource[exported.AccessToken, acquiringResourceState] + // the following fields are read-only + authzHandler policy.AuthorizationHandler + cred exported.TokenCredential + scopes []string +} + +type acquiringResourceState struct { + req *policy.Request + p *BearerTokenPolicy + tro policy.TokenRequestOptions +} + +// acquire acquires or updates the resource; only one +// thread/goroutine at a time ever calls this function +func acquire(state acquiringResourceState) (newResource exported.AccessToken, newExpiration time.Time, err error) { + tk, err := state.p.cred.GetToken(state.req.Raw().Context(), state.tro) + if err != nil { + return exported.AccessToken{}, time.Time{}, err + } + return tk, tk.ExpiresOn, nil +} + +// NewBearerTokenPolicy creates a policy object that authorizes requests with bearer tokens. +// cred: an azcore.TokenCredential implementation such as a credential object from azidentity +// scopes: the list of permission scopes required for the token. +// opts: optional settings. Pass nil to accept default values; this is the same as passing a zero-value options. +func NewBearerTokenPolicy(cred exported.TokenCredential, scopes []string, opts *policy.BearerTokenOptions) *BearerTokenPolicy { + if opts == nil { + opts = &policy.BearerTokenOptions{} + } + return &BearerTokenPolicy{ + authzHandler: opts.AuthorizationHandler, + cred: cred, + scopes: scopes, + mainResource: temporal.NewResource(acquire), + } +} + +// authenticateAndAuthorize returns a function which authorizes req with a token from the policy's credential +func (b *BearerTokenPolicy) authenticateAndAuthorize(req *policy.Request) func(policy.TokenRequestOptions) error { + return func(tro policy.TokenRequestOptions) error { + as := acquiringResourceState{p: b, req: req, tro: tro} + tk, err := b.mainResource.Get(as) + if err != nil { + return err + } + req.Raw().Header.Set(shared.HeaderAuthorization, shared.BearerTokenPrefix+tk.Token) + return nil + } +} + +// Do authorizes a request with a bearer token +func (b *BearerTokenPolicy) Do(req *policy.Request) (*http.Response, error) { + var err error + if b.authzHandler.OnRequest != nil { + err = b.authzHandler.OnRequest(req, b.authenticateAndAuthorize(req)) + } else { + err = b.authenticateAndAuthorize(req)(policy.TokenRequestOptions{Scopes: b.scopes}) + } + if err != nil { + return nil, ensureNonRetriable(err) + } + + res, err := req.Next() + if err != nil { + return nil, err + } + + if res.StatusCode == http.StatusUnauthorized { + b.mainResource.Expire() + if res.Header.Get("WWW-Authenticate") != "" && b.authzHandler.OnChallenge != nil { + if err = b.authzHandler.OnChallenge(req, res, b.authenticateAndAuthorize(req)); err == nil { + res, err = req.Next() + } + } + } + return res, ensureNonRetriable(err) +} + +func ensureNonRetriable(err error) error { + var nre errorinfo.NonRetriable + if err != nil && !errors.As(err, &nre) { + err = btpError{err} + } + return err +} + +// btpError is a wrapper that ensures RetryPolicy doesn't retry requests BearerTokenPolicy couldn't authorize +type btpError struct { + error +} + +func (btpError) NonRetriable() {} + +var _ errorinfo.NonRetriable = (*btpError)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_body_download.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_body_download.go new file mode 100644 index 00000000000..02d621ee89e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_body_download.go @@ -0,0 +1,73 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "fmt" + "net/http" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo" +) + +// bodyDownloadPolicy creates a policy object that downloads the response's body to a []byte. +func bodyDownloadPolicy(req *policy.Request) (*http.Response, error) { + resp, err := req.Next() + if err != nil { + return resp, err + } + var opValues bodyDownloadPolicyOpValues + // don't skip downloading error response bodies + if req.OperationValue(&opValues); opValues.Skip && resp.StatusCode < 400 { + return resp, err + } + // Either bodyDownloadPolicyOpValues was not specified (so skip is false) + // or it was specified and skip is false: don't skip downloading the body + _, err = exported.Payload(resp) + if err != nil { + return resp, newBodyDownloadError(err, req) + } + return resp, err +} + +// bodyDownloadPolicyOpValues is the struct containing the per-operation values +type bodyDownloadPolicyOpValues struct { + Skip bool +} + +type bodyDownloadError struct { + err error +} + +func newBodyDownloadError(err error, req *policy.Request) error { + // on failure, only retry the request for idempotent operations. + // we currently identify them as DELETE, GET, and PUT requests. + if m := strings.ToUpper(req.Raw().Method); m == http.MethodDelete || m == http.MethodGet || m == http.MethodPut { + // error is safe for retry + return err + } + // wrap error to avoid retries + return &bodyDownloadError{ + err: err, + } +} + +func (b *bodyDownloadError) Error() string { + return fmt.Sprintf("body download policy: %s", b.err.Error()) +} + +func (b *bodyDownloadError) NonRetriable() { + // marker method +} + +func (b *bodyDownloadError) Unwrap() error { + return b.err +} + +var _ errorinfo.NonRetriable = (*bodyDownloadError)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_http_header.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_http_header.go new file mode 100644 index 00000000000..770e0a2b6a6 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_http_header.go @@ -0,0 +1,39 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "context" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" +) + +// newHTTPHeaderPolicy creates a policy object that adds custom HTTP headers to a request +func httpHeaderPolicy(req *policy.Request) (*http.Response, error) { + // check if any custom HTTP headers have been specified + if header := req.Raw().Context().Value(shared.CtxWithHTTPHeaderKey{}); header != nil { + for k, v := range header.(http.Header) { + // use Set to replace any existing value + // it also canonicalizes the header key + req.Raw().Header.Set(k, v[0]) + // add any remaining values + for i := 1; i < len(v); i++ { + req.Raw().Header.Add(k, v[i]) + } + } + } + return req.Next() +} + +// WithHTTPHeader adds the specified http.Header to the parent context. +// Use this to specify custom HTTP headers at the API-call level. +// Any overlapping headers will have their values replaced with the values specified here. +func WithHTTPHeader(parent context.Context, header http.Header) context.Context { + return context.WithValue(parent, shared.CtxWithHTTPHeaderKey{}, header) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_include_response.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_include_response.go new file mode 100644 index 00000000000..4714baa30cd --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_include_response.go @@ -0,0 +1,34 @@ +//go:build go1.16 +// +build go1.16 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "context" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" +) + +// includeResponsePolicy creates a policy that retrieves the raw HTTP response upon request +func includeResponsePolicy(req *policy.Request) (*http.Response, error) { + resp, err := req.Next() + if resp == nil { + return resp, err + } + if httpOutRaw := req.Raw().Context().Value(shared.CtxIncludeResponseKey{}); httpOutRaw != nil { + httpOut := httpOutRaw.(**http.Response) + *httpOut = resp + } + return resp, err +} + +// WithCaptureResponse applies the HTTP response retrieval annotation to the parent context. +// The resp parameter will contain the HTTP response after the request has completed. +func WithCaptureResponse(parent context.Context, resp **http.Response) context.Context { + return context.WithValue(parent, shared.CtxIncludeResponseKey{}, resp) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_logging.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_logging.go new file mode 100644 index 00000000000..30a02a7a41b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_logging.go @@ -0,0 +1,251 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "bytes" + "fmt" + "io" + "net/http" + "sort" + "strings" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/log" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/internal/diag" +) + +type logPolicy struct { + includeBody bool + allowedHeaders map[string]struct{} + allowedQP map[string]struct{} +} + +// NewLogPolicy creates a request/response logging policy object configured using the specified options. +// Pass nil to accept the default values; this is the same as passing a zero-value options. +func NewLogPolicy(o *policy.LogOptions) policy.Policy { + if o == nil { + o = &policy.LogOptions{} + } + // construct default hash set of allowed headers + allowedHeaders := map[string]struct{}{ + "accept": {}, + "cache-control": {}, + "connection": {}, + "content-length": {}, + "content-type": {}, + "date": {}, + "etag": {}, + "expires": {}, + "if-match": {}, + "if-modified-since": {}, + "if-none-match": {}, + "if-unmodified-since": {}, + "last-modified": {}, + "ms-cv": {}, + "pragma": {}, + "request-id": {}, + "retry-after": {}, + "server": {}, + "traceparent": {}, + "transfer-encoding": {}, + "user-agent": {}, + "www-authenticate": {}, + "x-ms-request-id": {}, + "x-ms-client-request-id": {}, + "x-ms-return-client-request-id": {}, + } + // add any caller-specified allowed headers to the set + for _, ah := range o.AllowedHeaders { + allowedHeaders[strings.ToLower(ah)] = struct{}{} + } + // now do the same thing for query params + allowedQP := map[string]struct{}{ + "api-version": {}, + } + for _, qp := range o.AllowedQueryParams { + allowedQP[strings.ToLower(qp)] = struct{}{} + } + return &logPolicy{ + includeBody: o.IncludeBody, + allowedHeaders: allowedHeaders, + allowedQP: allowedQP, + } +} + +// logPolicyOpValues is the struct containing the per-operation values +type logPolicyOpValues struct { + try int32 + start time.Time +} + +func (p *logPolicy) Do(req *policy.Request) (*http.Response, error) { + // Get the per-operation values. These are saved in the Message's map so that they persist across each retry calling into this policy object. + var opValues logPolicyOpValues + if req.OperationValue(&opValues); opValues.start.IsZero() { + opValues.start = time.Now() // If this is the 1st try, record this operation's start time + } + opValues.try++ // The first try is #1 (not #0) + req.SetOperationValue(opValues) + + // Log the outgoing request as informational + if log.Should(log.EventRequest) { + b := &bytes.Buffer{} + fmt.Fprintf(b, "==> OUTGOING REQUEST (Try=%d)\n", opValues.try) + p.writeRequestWithResponse(b, req, nil, nil) + var err error + if p.includeBody { + err = writeReqBody(req, b) + } + log.Write(log.EventRequest, b.String()) + if err != nil { + return nil, err + } + } + + // Set the time for this particular retry operation and then Do the operation. + tryStart := time.Now() + response, err := req.Next() // Make the request + tryEnd := time.Now() + tryDuration := tryEnd.Sub(tryStart) + opDuration := tryEnd.Sub(opValues.start) + + if log.Should(log.EventResponse) { + // We're going to log this; build the string to log + b := &bytes.Buffer{} + fmt.Fprintf(b, "==> REQUEST/RESPONSE (Try=%d/%v, OpTime=%v) -- ", opValues.try, tryDuration, opDuration) + if err != nil { // This HTTP request did not get a response from the service + fmt.Fprint(b, "REQUEST ERROR\n") + } else { + fmt.Fprint(b, "RESPONSE RECEIVED\n") + } + + p.writeRequestWithResponse(b, req, response, err) + if err != nil { + // skip frames runtime.Callers() and runtime.StackTrace() + b.WriteString(diag.StackTrace(2, 32)) + } else if p.includeBody { + err = writeRespBody(response, b) + } + log.Write(log.EventResponse, b.String()) + } + return response, err +} + +const redactedValue = "REDACTED" + +// writeRequestWithResponse appends a formatted HTTP request into a Buffer. If request and/or err are +// not nil, then these are also written into the Buffer. +func (p *logPolicy) writeRequestWithResponse(b *bytes.Buffer, req *policy.Request, resp *http.Response, err error) { + // redact applicable query params + cpURL := *req.Raw().URL + qp := cpURL.Query() + for k := range qp { + if _, ok := p.allowedQP[strings.ToLower(k)]; !ok { + qp.Set(k, redactedValue) + } + } + cpURL.RawQuery = qp.Encode() + // Write the request into the buffer. + fmt.Fprint(b, " "+req.Raw().Method+" "+cpURL.String()+"\n") + p.writeHeader(b, req.Raw().Header) + if resp != nil { + fmt.Fprintln(b, " --------------------------------------------------------------------------------") + fmt.Fprint(b, " RESPONSE Status: "+resp.Status+"\n") + p.writeHeader(b, resp.Header) + } + if err != nil { + fmt.Fprintln(b, " --------------------------------------------------------------------------------") + fmt.Fprint(b, " ERROR:\n"+err.Error()+"\n") + } +} + +// formatHeaders appends an HTTP request's or response's header into a Buffer. +func (p *logPolicy) writeHeader(b *bytes.Buffer, header http.Header) { + if len(header) == 0 { + b.WriteString(" (no headers)\n") + return + } + keys := make([]string, 0, len(header)) + // Alphabetize the headers + for k := range header { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + value := header.Get(k) + // redact all header values not in the allow-list + if _, ok := p.allowedHeaders[strings.ToLower(k)]; !ok { + value = redactedValue + } + fmt.Fprintf(b, " %s: %+v\n", k, value) + } +} + +// returns true if the request/response body should be logged. +// this is determined by looking at the content-type header value. +func shouldLogBody(b *bytes.Buffer, contentType string) bool { + contentType = strings.ToLower(contentType) + if strings.HasPrefix(contentType, "text") || + strings.Contains(contentType, "json") || + strings.Contains(contentType, "xml") { + return true + } + fmt.Fprintf(b, " Skip logging body for %s\n", contentType) + return false +} + +// writes to a buffer, used for logging purposes +func writeReqBody(req *policy.Request, b *bytes.Buffer) error { + if req.Raw().Body == nil { + fmt.Fprint(b, " Request contained no body\n") + return nil + } + if ct := req.Raw().Header.Get(shared.HeaderContentType); !shouldLogBody(b, ct) { + return nil + } + body, err := io.ReadAll(req.Raw().Body) + if err != nil { + fmt.Fprintf(b, " Failed to read request body: %s\n", err.Error()) + return err + } + if err := req.RewindBody(); err != nil { + return err + } + logBody(b, body) + return nil +} + +// writes to a buffer, used for logging purposes +func writeRespBody(resp *http.Response, b *bytes.Buffer) error { + ct := resp.Header.Get(shared.HeaderContentType) + if ct == "" { + fmt.Fprint(b, " Response contained no body\n") + return nil + } else if !shouldLogBody(b, ct) { + return nil + } + body, err := Payload(resp) + if err != nil { + fmt.Fprintf(b, " Failed to read response body: %s\n", err.Error()) + return err + } + if len(body) > 0 { + logBody(b, body) + } else { + fmt.Fprint(b, " Response contained no body\n") + } + return nil +} + +func logBody(b *bytes.Buffer, body []byte) { + fmt.Fprintln(b, " --------------------------------------------------------------------------------") + fmt.Fprintln(b, string(body)) + fmt.Fprintln(b, " --------------------------------------------------------------------------------") +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_request_id.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_request_id.go new file mode 100644 index 00000000000..db70955b28b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_request_id.go @@ -0,0 +1,34 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/internal/uuid" +) + +type requestIDPolicy struct{} + +// NewRequestIDPolicy returns a policy that add the x-ms-client-request-id header +func NewRequestIDPolicy() policy.Policy { + return &requestIDPolicy{} +} + +func (r *requestIDPolicy) Do(req *policy.Request) (*http.Response, error) { + const requestIdHeader = "x-ms-client-request-id" + if req.Raw().Header.Get(requestIdHeader) == "" { + id, err := uuid.New() + if err != nil { + return nil, err + } + req.Raw().Header.Set(requestIdHeader, id.String()) + } + + return req.Next() +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_retry.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_retry.go new file mode 100644 index 00000000000..b3300201872 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_retry.go @@ -0,0 +1,251 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "context" + "errors" + "io" + "math" + "math/rand" + "net/http" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/log" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo" +) + +const ( + defaultMaxRetries = 3 +) + +func setDefaults(o *policy.RetryOptions) { + if o.MaxRetries == 0 { + o.MaxRetries = defaultMaxRetries + } else if o.MaxRetries < 0 { + o.MaxRetries = 0 + } + + // SDK guidelines specify the default MaxRetryDelay is 60 seconds + if o.MaxRetryDelay == 0 { + o.MaxRetryDelay = 60 * time.Second + } else if o.MaxRetryDelay < 0 { + // not really an unlimited cap, but sufficiently large enough to be considered as such + o.MaxRetryDelay = math.MaxInt64 + } + if o.RetryDelay == 0 { + o.RetryDelay = 800 * time.Millisecond + } else if o.RetryDelay < 0 { + o.RetryDelay = 0 + } + if o.StatusCodes == nil { + // NOTE: if you change this list, you MUST update the docs in policy/policy.go + o.StatusCodes = []int{ + http.StatusRequestTimeout, // 408 + http.StatusTooManyRequests, // 429 + http.StatusInternalServerError, // 500 + http.StatusBadGateway, // 502 + http.StatusServiceUnavailable, // 503 + http.StatusGatewayTimeout, // 504 + } + } +} + +func calcDelay(o policy.RetryOptions, try int32) time.Duration { // try is >=1; never 0 + pow := func(number int64, exponent int32) int64 { // pow is nested helper function + var result int64 = 1 + for n := int32(0); n < exponent; n++ { + result *= number + } + return result + } + + delay := time.Duration(pow(2, try)-1) * o.RetryDelay + + // Introduce some jitter: [0.0, 1.0) / 2 = [0.0, 0.5) + 0.8 = [0.8, 1.3) + delay = time.Duration(delay.Seconds() * (rand.Float64()/2 + 0.8) * float64(time.Second)) // NOTE: We want math/rand; not crypto/rand + if delay > o.MaxRetryDelay { + delay = o.MaxRetryDelay + } + return delay +} + +// NewRetryPolicy creates a policy object configured using the specified options. +// Pass nil to accept the default values; this is the same as passing a zero-value options. +func NewRetryPolicy(o *policy.RetryOptions) policy.Policy { + if o == nil { + o = &policy.RetryOptions{} + } + p := &retryPolicy{options: *o} + return p +} + +type retryPolicy struct { + options policy.RetryOptions +} + +func (p *retryPolicy) Do(req *policy.Request) (resp *http.Response, err error) { + options := p.options + // check if the retry options have been overridden for this call + if override := req.Raw().Context().Value(shared.CtxWithRetryOptionsKey{}); override != nil { + options = override.(policy.RetryOptions) + } + setDefaults(&options) + // Exponential retry algorithm: ((2 ^ attempt) - 1) * delay * random(0.8, 1.2) + // When to retry: connection failure or temporary/timeout. + var rwbody *retryableRequestBody + if req.Body() != nil { + // wrap the body so we control when it's actually closed. + // do this outside the for loop so defers don't accumulate. + rwbody = &retryableRequestBody{body: req.Body()} + defer rwbody.realClose() + } + try := int32(1) + for { + resp = nil // reset + log.Writef(log.EventRetryPolicy, "=====> Try=%d", try) + + // For each try, seek to the beginning of the Body stream. We do this even for the 1st try because + // the stream may not be at offset 0 when we first get it and we want the same behavior for the + // 1st try as for additional tries. + err = req.RewindBody() + if err != nil { + return + } + // RewindBody() restores Raw().Body to its original state, so set our rewindable after + if rwbody != nil { + req.Raw().Body = rwbody + } + + if options.TryTimeout == 0 { + resp, err = req.Next() + } else { + // Set the per-try time for this particular retry operation and then Do the operation. + tryCtx, tryCancel := context.WithTimeout(req.Raw().Context(), options.TryTimeout) + clone := req.Clone(tryCtx) + resp, err = clone.Next() // Make the request + // if the body was already downloaded or there was an error it's safe to cancel the context now + if err != nil { + tryCancel() + } else if _, ok := resp.Body.(*shared.NopClosingBytesReader); ok { + tryCancel() + } else { + // must cancel the context after the body has been read and closed + resp.Body = &contextCancelReadCloser{cf: tryCancel, body: resp.Body} + } + } + if err == nil { + log.Writef(log.EventRetryPolicy, "response %d", resp.StatusCode) + } else { + log.Writef(log.EventRetryPolicy, "error %v", err) + } + + if err == nil && !HasStatusCode(resp, options.StatusCodes...) { + // if there is no error and the response code isn't in the list of retry codes then we're done. + log.Write(log.EventRetryPolicy, "exit due to non-retriable status code") + return + } else if ctxErr := req.Raw().Context().Err(); ctxErr != nil { + // don't retry if the parent context has been cancelled or its deadline exceeded + err = ctxErr + log.Writef(log.EventRetryPolicy, "abort due to %v", err) + return + } + + // check if the error is not retriable + var nre errorinfo.NonRetriable + if errors.As(err, &nre) { + // the error says it's not retriable so don't retry + log.Writef(log.EventRetryPolicy, "non-retriable error %T", nre) + return + } + + if try == options.MaxRetries+1 { + // max number of tries has been reached, don't sleep again + log.Writef(log.EventRetryPolicy, "MaxRetries %d exceeded", options.MaxRetries) + return + } + + // use the delay from retry-after if available + delay := shared.RetryAfter(resp) + if delay <= 0 { + delay = calcDelay(options, try) + } else if delay > options.MaxRetryDelay { + // the retry-after delay exceeds the the cap so don't retry + log.Writef(log.EventRetryPolicy, "Retry-After delay %s exceeds MaxRetryDelay of %s", delay, options.MaxRetryDelay) + return + } + + // drain before retrying so nothing is leaked + Drain(resp) + + log.Writef(log.EventRetryPolicy, "End Try #%d, Delay=%v", try, delay) + select { + case <-time.After(delay): + try++ + case <-req.Raw().Context().Done(): + err = req.Raw().Context().Err() + log.Writef(log.EventRetryPolicy, "abort due to %v", err) + return + } + } +} + +// WithRetryOptions adds the specified RetryOptions to the parent context. +// Use this to specify custom RetryOptions at the API-call level. +func WithRetryOptions(parent context.Context, options policy.RetryOptions) context.Context { + return context.WithValue(parent, shared.CtxWithRetryOptionsKey{}, options) +} + +// ********** The following type/methods implement the retryableRequestBody (a ReadSeekCloser) + +// This struct is used when sending a body to the network +type retryableRequestBody struct { + body io.ReadSeeker // Seeking is required to support retries +} + +// Read reads a block of data from an inner stream and reports progress +func (b *retryableRequestBody) Read(p []byte) (n int, err error) { + return b.body.Read(p) +} + +func (b *retryableRequestBody) Seek(offset int64, whence int) (offsetFromStart int64, err error) { + return b.body.Seek(offset, whence) +} + +func (b *retryableRequestBody) Close() error { + // We don't want the underlying transport to close the request body on transient failures so this is a nop. + // The retry policy closes the request body upon success. + return nil +} + +func (b *retryableRequestBody) realClose() error { + if c, ok := b.body.(io.Closer); ok { + return c.Close() + } + return nil +} + +// ********** The following type/methods implement the contextCancelReadCloser + +// contextCancelReadCloser combines an io.ReadCloser with a cancel func. +// it ensures the cancel func is invoked once the body has been read and closed. +type contextCancelReadCloser struct { + cf context.CancelFunc + body io.ReadCloser +} + +func (rc *contextCancelReadCloser) Read(p []byte) (n int, err error) { + return rc.body.Read(p) +} + +func (rc *contextCancelReadCloser) Close() error { + err := rc.body.Close() + rc.cf() + return err +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_telemetry.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_telemetry.go new file mode 100644 index 00000000000..2abcdc576b6 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/policy_telemetry.go @@ -0,0 +1,79 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "bytes" + "fmt" + "net/http" + "os" + "runtime" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" +) + +type telemetryPolicy struct { + telemetryValue string +} + +// NewTelemetryPolicy creates a telemetry policy object that adds telemetry information to outgoing HTTP requests. +// The format is [ ]azsdk-go-/ . +// Pass nil to accept the default values; this is the same as passing a zero-value options. +func NewTelemetryPolicy(mod, ver string, o *policy.TelemetryOptions) policy.Policy { + if o == nil { + o = &policy.TelemetryOptions{} + } + tp := telemetryPolicy{} + if o.Disabled { + return &tp + } + b := &bytes.Buffer{} + // normalize ApplicationID + if o.ApplicationID != "" { + o.ApplicationID = strings.ReplaceAll(o.ApplicationID, " ", "/") + if len(o.ApplicationID) > 24 { + o.ApplicationID = o.ApplicationID[:24] + } + b.WriteString(o.ApplicationID) + b.WriteRune(' ') + } + b.WriteString(formatTelemetry(mod, ver)) + b.WriteRune(' ') + b.WriteString(platformInfo) + tp.telemetryValue = b.String() + return &tp +} + +func formatTelemetry(comp, ver string) string { + return fmt.Sprintf("azsdk-go-%s/%s", comp, ver) +} + +func (p telemetryPolicy) Do(req *policy.Request) (*http.Response, error) { + if p.telemetryValue == "" { + return req.Next() + } + // preserve the existing User-Agent string + if ua := req.Raw().Header.Get(shared.HeaderUserAgent); ua != "" { + p.telemetryValue = fmt.Sprintf("%s %s", p.telemetryValue, ua) + } + req.Raw().Header.Set(shared.HeaderUserAgent, p.telemetryValue) + return req.Next() +} + +// NOTE: the ONLY function that should write to this variable is this func +var platformInfo = func() string { + operatingSystem := runtime.GOOS // Default OS string + switch operatingSystem { + case "windows": + operatingSystem = os.Getenv("OS") // Get more specific OS information + case "linux": // accept default OS info + case "freebsd": // accept default OS info + } + return fmt.Sprintf("(%s; %s)", runtime.Version(), operatingSystem) +}() diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/poller.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/poller.go new file mode 100644 index 00000000000..14c90fecfe5 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/poller.go @@ -0,0 +1,326 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "net/http" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/log" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/async" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/body" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/loc" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/op" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" +) + +// FinalStateVia is the enumerated type for the possible final-state-via values. +type FinalStateVia = pollers.FinalStateVia + +const ( + // FinalStateViaAzureAsyncOp indicates the final payload comes from the Azure-AsyncOperation URL. + FinalStateViaAzureAsyncOp = pollers.FinalStateViaAzureAsyncOp + + // FinalStateViaLocation indicates the final payload comes from the Location URL. + FinalStateViaLocation = pollers.FinalStateViaLocation + + // FinalStateViaOriginalURI indicates the final payload comes from the original URL. + FinalStateViaOriginalURI = pollers.FinalStateViaOriginalURI + + // FinalStateViaOpLocation indicates the final payload comes from the Operation-Location URL. + FinalStateViaOpLocation = pollers.FinalStateViaOpLocation +) + +// NewPollerOptions contains the optional parameters for NewPoller. +type NewPollerOptions[T any] struct { + // FinalStateVia contains the final-state-via value for the LRO. + FinalStateVia FinalStateVia + + // Response contains a preconstructed response type. + // The final payload will be unmarshaled into it and returned. + Response *T + + // Handler[T] contains a custom polling implementation. + Handler PollingHandler[T] +} + +// NewPoller creates a Poller based on the provided initial response. +func NewPoller[T any](resp *http.Response, pl exported.Pipeline, options *NewPollerOptions[T]) (*Poller[T], error) { + if options == nil { + options = &NewPollerOptions[T]{} + } + result := options.Response + if result == nil { + result = new(T) + } + if options.Handler != nil { + return &Poller[T]{ + op: options.Handler, + resp: resp, + result: result, + }, nil + } + + defer resp.Body.Close() + // this is a back-stop in case the swagger is incorrect (i.e. missing one or more status codes for success). + // ideally the codegen should return an error if the initial response failed and not even create a poller. + if !pollers.StatusCodeValid(resp) { + return nil, errors.New("the operation failed or was cancelled") + } + + // determine the polling method + var opr PollingHandler[T] + var err error + if async.Applicable(resp) { + // async poller must be checked first as it can also have a location header + opr, err = async.New[T](pl, resp, options.FinalStateVia) + } else if op.Applicable(resp) { + // op poller must be checked before loc as it can also have a location header + opr, err = op.New[T](pl, resp, options.FinalStateVia) + } else if loc.Applicable(resp) { + opr, err = loc.New[T](pl, resp) + } else if body.Applicable(resp) { + // must test body poller last as it's a subset of the other pollers. + // TODO: this is ambiguous for PATCH/PUT if it returns a 200 with no polling headers (sync completion) + opr, err = body.New[T](pl, resp) + } else if m := resp.Request.Method; resp.StatusCode == http.StatusAccepted && (m == http.MethodDelete || m == http.MethodPost) { + // if we get here it means we have a 202 with no polling headers. + // for DELETE and POST this is a hard error per ARM RPC spec. + return nil, errors.New("response is missing polling URL") + } else { + opr, err = pollers.NewNopPoller[T](resp) + } + + if err != nil { + return nil, err + } + return &Poller[T]{ + op: opr, + resp: resp, + result: result, + }, nil +} + +// NewPollerFromResumeTokenOptions contains the optional parameters for NewPollerFromResumeToken. +type NewPollerFromResumeTokenOptions[T any] struct { + // Response contains a preconstructed response type. + // The final payload will be unmarshaled into it and returned. + Response *T + + // Handler[T] contains a custom polling implementation. + Handler PollingHandler[T] +} + +// NewPollerFromResumeToken creates a Poller from a resume token string. +func NewPollerFromResumeToken[T any](token string, pl exported.Pipeline, options *NewPollerFromResumeTokenOptions[T]) (*Poller[T], error) { + if options == nil { + options = &NewPollerFromResumeTokenOptions[T]{} + } + result := options.Response + if result == nil { + result = new(T) + } + + if err := pollers.IsTokenValid[T](token); err != nil { + return nil, err + } + raw, err := pollers.ExtractToken(token) + if err != nil { + return nil, err + } + var asJSON map[string]interface{} + if err := json.Unmarshal(raw, &asJSON); err != nil { + return nil, err + } + + opr := options.Handler + // now rehydrate the poller based on the encoded poller type + if async.CanResume(asJSON) { + opr, _ = async.New[T](pl, nil, "") + } else if body.CanResume(asJSON) { + opr, _ = body.New[T](pl, nil) + } else if loc.CanResume(asJSON) { + opr, _ = loc.New[T](pl, nil) + } else if op.CanResume(asJSON) { + opr, _ = op.New[T](pl, nil, "") + } else if opr != nil { + log.Writef(log.EventLRO, "Resuming custom poller %T.", opr) + } else { + return nil, fmt.Errorf("unhandled poller token %s", string(raw)) + } + if err := json.Unmarshal(raw, &opr); err != nil { + return nil, err + } + return &Poller[T]{ + op: opr, + result: result, + }, nil +} + +// PollingHandler[T] abstracts the differences among poller implementations. +type PollingHandler[T any] interface { + // Done returns true if the LRO has reached a terminal state. + Done() bool + + // Poll fetches the latest state of the LRO. + Poll(context.Context) (*http.Response, error) + + // Result is called once the LRO has reached a terminal state. It populates the out parameter + // with the result of the operation. + Result(ctx context.Context, out *T) error +} + +// Poller encapsulates a long-running operation, providing polling facilities until the operation reaches a terminal state. +type Poller[T any] struct { + op PollingHandler[T] + resp *http.Response + err error + result *T + done bool +} + +// PollUntilDoneOptions contains the optional values for the Poller[T].PollUntilDone() method. +type PollUntilDoneOptions struct { + // Frequency is the time to wait between polling intervals in absence of a Retry-After header. Allowed minimum is one second. + // Pass zero to accept the default value (30s). + Frequency time.Duration +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached, an error is received, or the context expires. +// It internally uses Poll(), Done(), and Result() in its polling loop, sleeping for the specified duration between intervals. +// options: pass nil to accept the default values. +// NOTE: the default polling frequency is 30 seconds which works well for most operations. However, some operations might +// benefit from a shorter or longer duration. +func (p *Poller[T]) PollUntilDone(ctx context.Context, options *PollUntilDoneOptions) (T, error) { + if options == nil { + options = &PollUntilDoneOptions{} + } + cp := *options + if cp.Frequency == 0 { + cp.Frequency = 30 * time.Second + } + + // skip the floor check when executing tests so they don't take so long + if isTest := flag.Lookup("test.v"); isTest == nil && cp.Frequency < time.Second { + return *new(T), errors.New("polling frequency minimum is one second") + } + + start := time.Now() + logPollUntilDoneExit := func(v interface{}) { + log.Writef(log.EventLRO, "END PollUntilDone() for %T: %v, total time: %s", p.op, v, time.Since(start)) + } + log.Writef(log.EventLRO, "BEGIN PollUntilDone() for %T", p.op) + if p.resp != nil { + // initial check for a retry-after header existing on the initial response + if retryAfter := shared.RetryAfter(p.resp); retryAfter > 0 { + log.Writef(log.EventLRO, "initial Retry-After delay for %s", retryAfter.String()) + if err := shared.Delay(ctx, retryAfter); err != nil { + logPollUntilDoneExit(err) + return *new(T), err + } + } + } + // begin polling the endpoint until a terminal state is reached + for { + resp, err := p.Poll(ctx) + if err != nil { + logPollUntilDoneExit(err) + return *new(T), err + } + if p.Done() { + logPollUntilDoneExit("succeeded") + return p.Result(ctx) + } + d := cp.Frequency + if retryAfter := shared.RetryAfter(resp); retryAfter > 0 { + log.Writef(log.EventLRO, "Retry-After delay for %s", retryAfter.String()) + d = retryAfter + } else { + log.Writef(log.EventLRO, "delay for %s", d.String()) + } + if err = shared.Delay(ctx, d); err != nil { + logPollUntilDoneExit(err) + return *new(T), err + } + } +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If Poll succeeds, the poller's state is updated and the HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the last HTTP response. +func (p *Poller[T]) Poll(ctx context.Context) (*http.Response, error) { + if p.Done() { + // the LRO has reached a terminal state, don't poll again + return p.resp, nil + } + resp, err := p.op.Poll(ctx) + if err != nil { + return nil, err + } + p.resp = resp + return p.resp, nil +} + +// Done returns true if the LRO has reached a terminal state. +// Once a terminal state is reached, call Result(). +func (p *Poller[T]) Done() bool { + return p.op.Done() +} + +// Result returns the result of the LRO and is meant to be used in conjunction with Poll and Done. +// If the LRO completed successfully, a populated instance of T is returned. +// If the LRO failed or was canceled, an *azcore.ResponseError error is returned. +// Calling this on an LRO in a non-terminal state will return an error. +func (p *Poller[T]) Result(ctx context.Context) (T, error) { + if !p.Done() { + return *new(T), errors.New("poller is in a non-terminal state") + } + if p.done { + // the result has already been retrieved, return the cached value + if p.err != nil { + return *new(T), p.err + } + return *p.result, nil + } + err := p.op.Result(ctx, p.result) + var respErr *exported.ResponseError + if errors.As(err, &respErr) { + // the LRO failed. record the error + p.err = err + } else if err != nil { + // the call to Result failed, don't cache anything in this case + return *new(T), err + } + p.done = true + if p.err != nil { + return *new(T), p.err + } + return *p.result, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +// The token's format should be considered opaque and is subject to change. +// Calling this on an LRO in a terminal state will return an error. +func (p *Poller[T]) ResumeToken() (string, error) { + if p.Done() { + return "", errors.New("poller is in a terminal state") + } + tk, err := pollers.NewResumeToken[T](p.op) + if err != nil { + return "", err + } + return tk, err +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/request.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/request.go new file mode 100644 index 00000000000..98e00718488 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/request.go @@ -0,0 +1,248 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "encoding/xml" + "fmt" + "io" + "mime/multipart" + "os" + "path" + "reflect" + "strings" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" +) + +// Base64Encoding is usesd to specify which base-64 encoder/decoder to use when +// encoding/decoding a slice of bytes to/from a string. +type Base64Encoding int + +const ( + // Base64StdFormat uses base64.StdEncoding for encoding and decoding payloads. + Base64StdFormat Base64Encoding = 0 + + // Base64URLFormat uses base64.RawURLEncoding for encoding and decoding payloads. + Base64URLFormat Base64Encoding = 1 +) + +// NewRequest creates a new policy.Request with the specified input. +// The endpoint MUST be properly encoded before calling this function. +func NewRequest(ctx context.Context, httpMethod string, endpoint string) (*policy.Request, error) { + return exported.NewRequest(ctx, httpMethod, endpoint) +} + +// JoinPaths concatenates multiple URL path segments into one path, +// inserting path separation characters as required. JoinPaths will preserve +// query parameters in the root path +func JoinPaths(root string, paths ...string) string { + if len(paths) == 0 { + return root + } + + qps := "" + if strings.Contains(root, "?") { + splitPath := strings.Split(root, "?") + root, qps = splitPath[0], splitPath[1] + } + + p := path.Join(paths...) + // path.Join will remove any trailing slashes. + // if one was provided, preserve it. + if strings.HasSuffix(paths[len(paths)-1], "/") && !strings.HasSuffix(p, "/") { + p += "/" + } + + if qps != "" { + p = p + "?" + qps + } + + if strings.HasSuffix(root, "/") && strings.HasPrefix(p, "/") { + root = root[:len(root)-1] + } else if !strings.HasSuffix(root, "/") && !strings.HasPrefix(p, "/") { + p = "/" + p + } + return root + p +} + +// EncodeByteArray will base-64 encode the byte slice v. +func EncodeByteArray(v []byte, format Base64Encoding) string { + if format == Base64URLFormat { + return base64.RawURLEncoding.EncodeToString(v) + } + return base64.StdEncoding.EncodeToString(v) +} + +// MarshalAsByteArray will base-64 encode the byte slice v, then calls SetBody. +// The encoded value is treated as a JSON string. +func MarshalAsByteArray(req *policy.Request, v []byte, format Base64Encoding) error { + // send as a JSON string + encode := fmt.Sprintf("\"%s\"", EncodeByteArray(v, format)) + return req.SetBody(exported.NopCloser(strings.NewReader(encode)), shared.ContentTypeAppJSON) +} + +// MarshalAsJSON calls json.Marshal() to get the JSON encoding of v then calls SetBody. +func MarshalAsJSON(req *policy.Request, v interface{}) error { + if omit := os.Getenv("AZURE_SDK_GO_OMIT_READONLY"); omit == "true" { + v = cloneWithoutReadOnlyFields(v) + } + b, err := json.Marshal(v) + if err != nil { + return fmt.Errorf("error marshalling type %T: %s", v, err) + } + return req.SetBody(exported.NopCloser(bytes.NewReader(b)), shared.ContentTypeAppJSON) +} + +// MarshalAsXML calls xml.Marshal() to get the XML encoding of v then calls SetBody. +func MarshalAsXML(req *policy.Request, v interface{}) error { + b, err := xml.Marshal(v) + if err != nil { + return fmt.Errorf("error marshalling type %T: %s", v, err) + } + // inclue the XML header as some services require it + b = []byte(xml.Header + string(b)) + return req.SetBody(exported.NopCloser(bytes.NewReader(b)), shared.ContentTypeAppXML) +} + +// SetMultipartFormData writes the specified keys/values as multi-part form +// fields with the specified value. File content must be specified as a ReadSeekCloser. +// All other values are treated as string values. +func SetMultipartFormData(req *policy.Request, formData map[string]interface{}) error { + body := bytes.Buffer{} + writer := multipart.NewWriter(&body) + + writeContent := func(fieldname, filename string, src io.Reader) error { + fd, err := writer.CreateFormFile(fieldname, filename) + if err != nil { + return err + } + // copy the data to the form file + if _, err = io.Copy(fd, src); err != nil { + return err + } + return nil + } + + for k, v := range formData { + if rsc, ok := v.(io.ReadSeekCloser); ok { + if err := writeContent(k, k, rsc); err != nil { + return err + } + continue + } else if rscs, ok := v.([]io.ReadSeekCloser); ok { + for _, rsc := range rscs { + if err := writeContent(k, k, rsc); err != nil { + return err + } + } + continue + } + // ensure the value is in string format + s, ok := v.(string) + if !ok { + s = fmt.Sprintf("%v", v) + } + if err := writer.WriteField(k, s); err != nil { + return err + } + } + if err := writer.Close(); err != nil { + return err + } + return req.SetBody(exported.NopCloser(bytes.NewReader(body.Bytes())), writer.FormDataContentType()) +} + +// SkipBodyDownload will disable automatic downloading of the response body. +func SkipBodyDownload(req *policy.Request) { + req.SetOperationValue(bodyDownloadPolicyOpValues{Skip: true}) +} + +// returns a clone of the object graph pointed to by v, omitting values of all read-only +// fields. if there are no read-only fields in the object graph, no clone is created. +func cloneWithoutReadOnlyFields(v interface{}) interface{} { + val := reflect.Indirect(reflect.ValueOf(v)) + if val.Kind() != reflect.Struct { + // not a struct, skip + return v + } + // first walk the graph to find any R/O fields. + // if there aren't any, skip cloning the graph. + if !recursiveFindReadOnlyField(val) { + return v + } + return recursiveCloneWithoutReadOnlyFields(val) +} + +// returns true if any field in the object graph of val contains the `azure:"ro"` tag value +func recursiveFindReadOnlyField(val reflect.Value) bool { + t := val.Type() + // iterate over the fields, looking for the "azure" tag. + for i := 0; i < t.NumField(); i++ { + field := t.Field(i) + aztag := field.Tag.Get("azure") + if azureTagIsReadOnly(aztag) { + return true + } else if reflect.Indirect(val.Field(i)).Kind() == reflect.Struct && recursiveFindReadOnlyField(reflect.Indirect(val.Field(i))) { + return true + } + } + return false +} + +// clones the object graph of val. all non-R/O properties are copied to the clone +func recursiveCloneWithoutReadOnlyFields(val reflect.Value) interface{} { + t := val.Type() + clone := reflect.New(t) + // iterate over the fields, looking for the "azure" tag. + for i := 0; i < t.NumField(); i++ { + field := t.Field(i) + aztag := field.Tag.Get("azure") + if azureTagIsReadOnly(aztag) { + // omit from payload + continue + } + // clone field will receive the same value as the source field... + value := val.Field(i) + v := reflect.Indirect(value) + if v.IsValid() && v.Type() != reflect.TypeOf(time.Time{}) && v.Kind() == reflect.Struct { + // ...unless the source value is a struct, in which case we recurse to clone that struct. + // (We can't recursively clone time.Time because it contains unexported fields.) + c := recursiveCloneWithoutReadOnlyFields(v) + if field.Anonymous { + // NOTE: this does not handle the case of embedded fields of unexported struct types. + // this should be ok as we don't generate any code like this at present + value = reflect.Indirect(reflect.ValueOf(c)) + } else { + value = reflect.ValueOf(c) + } + } + reflect.Indirect(clone).Field(i).Set(value) + } + return clone.Interface() +} + +// returns true if the "azure" tag contains the option "ro" +func azureTagIsReadOnly(tag string) bool { + if tag == "" { + return false + } + parts := strings.Split(tag, ",") + for _, part := range parts { + if part == "ro" { + return true + } + } + return false +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/response.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/response.go new file mode 100644 index 00000000000..f86ec0b95ea --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/response.go @@ -0,0 +1,136 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "encoding/xml" + "fmt" + "io" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared" +) + +// Payload reads and returns the response body or an error. +// On a successful read, the response body is cached. +// Subsequent reads will access the cached value. +func Payload(resp *http.Response) ([]byte, error) { + return exported.Payload(resp) +} + +// HasStatusCode returns true if the Response's status code is one of the specified values. +func HasStatusCode(resp *http.Response, statusCodes ...int) bool { + return exported.HasStatusCode(resp, statusCodes...) +} + +// UnmarshalAsByteArray will base-64 decode the received payload and place the result into the value pointed to by v. +func UnmarshalAsByteArray(resp *http.Response, v *[]byte, format Base64Encoding) error { + p, err := Payload(resp) + if err != nil { + return err + } + return DecodeByteArray(string(p), v, format) +} + +// UnmarshalAsJSON calls json.Unmarshal() to unmarshal the received payload into the value pointed to by v. +func UnmarshalAsJSON(resp *http.Response, v interface{}) error { + payload, err := Payload(resp) + if err != nil { + return err + } + // TODO: verify early exit is correct + if len(payload) == 0 { + return nil + } + err = removeBOM(resp) + if err != nil { + return err + } + err = json.Unmarshal(payload, v) + if err != nil { + err = fmt.Errorf("unmarshalling type %T: %s", v, err) + } + return err +} + +// UnmarshalAsXML calls xml.Unmarshal() to unmarshal the received payload into the value pointed to by v. +func UnmarshalAsXML(resp *http.Response, v interface{}) error { + payload, err := Payload(resp) + if err != nil { + return err + } + // TODO: verify early exit is correct + if len(payload) == 0 { + return nil + } + err = removeBOM(resp) + if err != nil { + return err + } + err = xml.Unmarshal(payload, v) + if err != nil { + err = fmt.Errorf("unmarshalling type %T: %s", v, err) + } + return err +} + +// Drain reads the response body to completion then closes it. The bytes read are discarded. +func Drain(resp *http.Response) { + if resp != nil && resp.Body != nil { + _, _ = io.Copy(io.Discard, resp.Body) + resp.Body.Close() + } +} + +// removeBOM removes any byte-order mark prefix from the payload if present. +func removeBOM(resp *http.Response) error { + payload, err := Payload(resp) + if err != nil { + return err + } + // UTF8 + trimmed := bytes.TrimPrefix(payload, []byte("\xef\xbb\xbf")) + if len(trimmed) < len(payload) { + resp.Body.(shared.BytesSetter).Set(trimmed) + } + return nil +} + +// DecodeByteArray will base-64 decode the provided string into v. +func DecodeByteArray(s string, v *[]byte, format Base64Encoding) error { + if len(s) == 0 { + return nil + } + payload := string(s) + if payload[0] == '"' { + // remove surrounding quotes + payload = payload[1 : len(payload)-1] + } + switch format { + case Base64StdFormat: + decoded, err := base64.StdEncoding.DecodeString(payload) + if err == nil { + *v = decoded + return nil + } + return err + case Base64URLFormat: + // use raw encoding as URL format should not contain any '=' characters + decoded, err := base64.RawURLEncoding.DecodeString(payload) + if err == nil { + *v = decoded + return nil + } + return err + default: + return fmt.Errorf("unrecognized byte array format: %d", format) + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/transport_default_http_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/transport_default_http_client.go new file mode 100644 index 00000000000..869bed51184 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/transport_default_http_client.go @@ -0,0 +1,37 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package runtime + +import ( + "crypto/tls" + "net" + "net/http" + "time" +) + +var defaultHTTPClient *http.Client + +func init() { + defaultTransport := &http.Transport{ + Proxy: http.ProxyFromEnvironment, + DialContext: (&net.Dialer{ + Timeout: 30 * time.Second, + KeepAlive: 30 * time.Second, + }).DialContext, + ForceAttemptHTTP2: true, + MaxIdleConns: 100, + IdleConnTimeout: 90 * time.Second, + TLSHandshakeTimeout: 10 * time.Second, + ExpectContinueTimeout: 1 * time.Second, + TLSClientConfig: &tls.Config{ + MinVersion: tls.VersionTLS12, + }, + } + defaultHTTPClient = &http.Client{ + Transport: defaultTransport, + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming/doc.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming/doc.go new file mode 100644 index 00000000000..cadaef3d584 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming/doc.go @@ -0,0 +1,9 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright 2017 Microsoft Corporation. All rights reserved. +// Use of this source code is governed by an MIT +// license that can be found in the LICENSE file. + +// Package streaming contains helpers for streaming IO operations and progress reporting. +package streaming diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming/progress.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming/progress.go new file mode 100644 index 00000000000..fbcd48311b8 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming/progress.go @@ -0,0 +1,75 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package streaming + +import ( + "io" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported" +) + +type progress struct { + rc io.ReadCloser + rsc io.ReadSeekCloser + pr func(bytesTransferred int64) + offset int64 +} + +// NopCloser returns a ReadSeekCloser with a no-op close method wrapping the provided io.ReadSeeker. +// In addition to adding a Close method to an io.ReadSeeker, this can also be used to wrap an +// io.ReadSeekCloser with a no-op Close method to allow explicit control of when the io.ReedSeekCloser +// has its underlying stream closed. +func NopCloser(rs io.ReadSeeker) io.ReadSeekCloser { + return exported.NopCloser(rs) +} + +// NewRequestProgress adds progress reporting to an HTTP request's body stream. +func NewRequestProgress(body io.ReadSeekCloser, pr func(bytesTransferred int64)) io.ReadSeekCloser { + return &progress{ + rc: body, + rsc: body, + pr: pr, + offset: 0, + } +} + +// NewResponseProgress adds progress reporting to an HTTP response's body stream. +func NewResponseProgress(body io.ReadCloser, pr func(bytesTransferred int64)) io.ReadCloser { + return &progress{ + rc: body, + rsc: nil, + pr: pr, + offset: 0, + } +} + +// Read reads a block of data from an inner stream and reports progress +func (p *progress) Read(b []byte) (n int, err error) { + n, err = p.rc.Read(b) + if err != nil && err != io.EOF { + return + } + p.offset += int64(n) + // Invokes the user's callback method to report progress + p.pr(p.offset) + return +} + +// Seek only expects a zero or from beginning. +func (p *progress) Seek(offset int64, whence int) (int64, error) { + // This should only ever be called with offset = 0 and whence = io.SeekStart + n, err := p.rsc.Seek(offset, whence) + if err == nil { + p.offset = int64(n) + } + return n, err +} + +// requestBodyProgress supports Close but the underlying stream may not; if it does, Close will close it. +func (p *progress) Close() error { + return p.rc.Close() +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/tracing/constants.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/tracing/constants.go new file mode 100644 index 00000000000..80282d4ab0a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/tracing/constants.go @@ -0,0 +1,41 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package tracing + +// SpanKind represents the role of a Span inside a Trace. Often, this defines how a Span will be processed and visualized by various backends. +type SpanKind int + +const ( + // SpanKindInternal indicates the span represents an internal operation within an application. + SpanKindInternal SpanKind = 1 + + // SpanKindServer indicates the span covers server-side handling of a request. + SpanKindServer SpanKind = 2 + + // SpanKindClient indicates the span describes a request to a remote service. + SpanKindClient SpanKind = 3 + + // SpanKindProducer indicates the span was created by a messaging producer. + SpanKindProducer SpanKind = 4 + + // SpanKindConsumer indicates the span was created by a messaging consumer. + SpanKindConsumer SpanKind = 5 +) + +// SpanStatus represents the status of a span. +type SpanStatus int + +const ( + // SpanStatusUnset is the default status code. + SpanStatusUnset SpanStatus = 0 + + // SpanStatusError indicates the operation contains an error. + SpanStatusError SpanStatus = 1 + + // SpanStatusOK indicates the operation completed successfully. + SpanStatusOK SpanStatus = 2 +) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/tracing/tracing.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/tracing/tracing.go new file mode 100644 index 00000000000..75f757cedd3 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azcore/tracing/tracing.go @@ -0,0 +1,168 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// Package tracing contains the definitions needed to support distributed tracing. +package tracing + +import ( + "context" +) + +// ProviderOptions contains the optional values when creating a Provider. +type ProviderOptions struct { + // for future expansion +} + +// NewProvider creates a new Provider with the specified values. +// - newTracerFn is the underlying implementation for creating Tracer instances +// - options contains optional values; pass nil to accept the default value +func NewProvider(newTracerFn func(name, version string) Tracer, options *ProviderOptions) Provider { + return Provider{ + newTracerFn: newTracerFn, + } +} + +// Provider is the factory that creates Tracer instances. +// It defaults to a no-op provider. +type Provider struct { + newTracerFn func(name, version string) Tracer +} + +// NewTracer creates a new Tracer for the specified name and version. +// - name - the name of the tracer object, typically the fully qualified name of the service client +// - version - the version of the module in which the service client resides +func (p Provider) NewTracer(name, version string) (tracer Tracer) { + if p.newTracerFn != nil { + tracer = p.newTracerFn(name, version) + } + return +} + +///////////////////////////////////////////////////////////////////////////////////////////////////////////// + +// TracerOptions contains the optional values when creating a Tracer. +type TracerOptions struct { + // for future expansion +} + +// NewTracer creates a Tracer with the specified values. +// - newSpanFn is the underlying implementation for creating Span instances +// - options contains optional values; pass nil to accept the default value +func NewTracer(newSpanFn func(ctx context.Context, spanName string, options *SpanOptions) (context.Context, Span), options *TracerOptions) Tracer { + return Tracer{ + newSpanFn: newSpanFn, + } +} + +// Tracer is the factory that creates Span instances. +type Tracer struct { + newSpanFn func(ctx context.Context, spanName string, options *SpanOptions) (context.Context, Span) +} + +// Start creates a new span and a context.Context that contains it. +// - ctx is the parent context for this span. If it contains a Span, the newly created span will be a child of that span, else it will be a root span +// - spanName identifies the span within a trace, it's typically the fully qualified API name +// - options contains optional values for the span, pass nil to accept any defaults +func (t Tracer) Start(ctx context.Context, spanName string, options *SpanOptions) (context.Context, Span) { + if t.newSpanFn != nil { + return t.newSpanFn(ctx, spanName, options) + } + return ctx, Span{} +} + +// SpanOptions contains optional settings for creating a span. +type SpanOptions struct { + // Kind indicates the kind of Span. + Kind SpanKind + + // Attributes contains key-value pairs of attributes for the span. + Attributes []Attribute +} + +///////////////////////////////////////////////////////////////////////////////////////////////////////////// + +// SpanImpl abstracts the underlying implementation for Span, +// allowing it to work with various tracing implementations. +// Any zero-values will have their default, no-op behavior. +type SpanImpl struct { + // End contains the implementation for the Span.End method. + End func() + + // SetAttributes contains the implementation for the Span.SetAttributes method. + SetAttributes func(...Attribute) + + // AddEvent contains the implementation for the Span.AddEvent method. + AddEvent func(string, ...Attribute) + + // AddError contains the implementation for the Span.AddError method. + AddError func(err error) + + // SetStatus contains the implementation for the Span.SetStatus method. + SetStatus func(SpanStatus, string) +} + +// NewSpan creates a Span with the specified implementation. +func NewSpan(impl SpanImpl) Span { + return Span{ + impl: impl, + } +} + +// Span is a single unit of a trace. A trace can contain multiple spans. +// A zero-value Span provides a no-op implementation. +type Span struct { + impl SpanImpl +} + +// End terminates the span and MUST be called before the span leaves scope. +// Any further updates to the span will be ignored after End is called. +func (s Span) End() { + if s.impl.End != nil { + s.impl.End() + } +} + +// SetAttributes sets the specified attributes on the Span. +// Any existing attributes with the same keys will have their values overwritten. +func (s Span) SetAttributes(attrs ...Attribute) { + if s.impl.SetAttributes != nil { + s.impl.SetAttributes(attrs...) + } +} + +// AddEvent adds a named event with an optional set of attributes to the span. +func (s Span) AddEvent(name string, attrs ...Attribute) { + if s.impl.AddEvent != nil { + s.impl.AddEvent(name, attrs...) + } +} + +// AddError adds the specified error event to the span. +func (s Span) AddError(err error) { + if s.impl.AddError != nil { + s.impl.AddError(err) + } +} + +// SetStatus sets the status on the span along with a description. +func (s Span) SetStatus(code SpanStatus, desc string) { + if s.impl.SetStatus != nil { + s.impl.SetStatus(code, desc) + } +} + +///////////////////////////////////////////////////////////////////////////////////////////////////////////// + +// Attribute is a key-value pair. +type Attribute struct { + // Key is the name of the attribute. + Key string + + // Value is the attribute's value. + // Types that are natively supported include int64, float64, int, bool, string. + // Any other type will be formatted per rules of fmt.Sprintf("%v"). + Value any +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/CHANGELOG.md new file mode 100644 index 00000000000..6ac3a8e391e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/CHANGELOG.md @@ -0,0 +1,355 @@ +# Release History + +## 1.2.1 (2023-01-26) + +### Other Changes +* Upgrade MSAL to v0.8.1 + +## 1.3.0-beta.2 (2023-01-10) + +### Features Added +* Added `OnBehalfOfCredential` to support the on-behalf-of flow + ([#16642](https://github.com/Azure/azure-sdk-for-go/issues/16642)) + +### Bugs Fixed +* `AzureCLICredential` reports token expiration in local time (should be UTC) + +### Other Changes +* `AzureCLICredential` imposes its default timeout only when the `Context` + passed to `GetToken()` has no deadline +* Added `NewCredentialUnavailableError()`. This function constructs an error indicating + a credential can't authenticate and an encompassing `ChainedTokenCredential` should + try its next credential, if any. + +## 1.3.0-beta.1 (2022-12-13) + +### Features Added +* `WorkloadIdentityCredential` and `DefaultAzureCredential` support + Workload Identity Federation on Kubernetes. `DefaultAzureCredential` + support requires environment variable configuration as set by the + Workload Identity webhook. + ([#15615](https://github.com/Azure/azure-sdk-for-go/issues/15615)) + +## 1.2.0 (2022-11-08) + +### Other Changes +* This version includes all fixes and features from 1.2.0-beta.* + +## 1.2.0-beta.3 (2022-10-11) + +### Features Added +* `ManagedIdentityCredential` caches tokens in memory + +### Bugs Fixed +* `ClientCertificateCredential` sends only the leaf cert for SNI authentication + +## 1.2.0-beta.2 (2022-08-10) + +### Features Added +* Added `ClientAssertionCredential` to enable applications to authenticate + with custom client assertions + +### Other Changes +* Updated AuthenticationFailedError with links to TROUBLESHOOTING.md for relevant errors +* Upgraded `microsoft-authentication-library-for-go` requirement to v0.6.0 + +## 1.2.0-beta.1 (2022-06-07) + +### Features Added +* `EnvironmentCredential` reads certificate passwords from `AZURE_CLIENT_CERTIFICATE_PASSWORD` + ([#17099](https://github.com/Azure/azure-sdk-for-go/pull/17099)) + +## 1.1.0 (2022-06-07) + +### Features Added +* `ClientCertificateCredential` and `ClientSecretCredential` support ESTS-R. First-party + applications can set environment variable `AZURE_REGIONAL_AUTHORITY_NAME` with a + region name. + ([#15605](https://github.com/Azure/azure-sdk-for-go/issues/15605)) + +## 1.0.1 (2022-06-07) + +### Other Changes +* Upgrade `microsoft-authentication-library-for-go` requirement to v0.5.1 + ([#18176](https://github.com/Azure/azure-sdk-for-go/issues/18176)) + +## 1.0.0 (2022-05-12) + +### Features Added +* `DefaultAzureCredential` reads environment variable `AZURE_CLIENT_ID` for the + client ID of a user-assigned managed identity + ([#17293](https://github.com/Azure/azure-sdk-for-go/pull/17293)) + +### Breaking Changes +* Removed `AuthorizationCodeCredential`. Use `InteractiveBrowserCredential` instead + to authenticate a user with the authorization code flow. +* Instances of `AuthenticationFailedError` are now returned by pointer. +* `GetToken()` returns `azcore.AccessToken` by value + +### Bugs Fixed +* `AzureCLICredential` panics after receiving an unexpected error type + ([#17490](https://github.com/Azure/azure-sdk-for-go/issues/17490)) + +### Other Changes +* `GetToken()` returns an error when the caller specifies no scope +* Updated to the latest versions of `golang.org/x/crypto`, `azcore` and `internal` + +## 0.14.0 (2022-04-05) + +### Breaking Changes +* This module now requires Go 1.18 +* Removed `AuthorityHost`. Credentials are now configured for sovereign or private + clouds with the API in `azcore/cloud`, for example: + ```go + // before + opts := azidentity.ClientSecretCredentialOptions{AuthorityHost: azidentity.AzureGovernment} + cred, err := azidentity.NewClientSecretCredential(tenantID, clientID, secret, &opts) + + // after + import "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" + + opts := azidentity.ClientSecretCredentialOptions{} + opts.Cloud = cloud.AzureGovernment + cred, err := azidentity.NewClientSecretCredential(tenantID, clientID, secret, &opts) + ``` + +## 0.13.2 (2022-03-08) + +### Bugs Fixed +* Prevented a data race in `DefaultAzureCredential` and `ChainedTokenCredential` + ([#17144](https://github.com/Azure/azure-sdk-for-go/issues/17144)) + +### Other Changes +* Upgraded App Service managed identity version from 2017-09-01 to 2019-08-01 + ([#17086](https://github.com/Azure/azure-sdk-for-go/pull/17086)) + +## 0.13.1 (2022-02-08) + +### Features Added +* `EnvironmentCredential` supports certificate SNI authentication when + `AZURE_CLIENT_SEND_CERTIFICATE_CHAIN` is "true". + ([#16851](https://github.com/Azure/azure-sdk-for-go/pull/16851)) + +### Bugs Fixed +* `ManagedIdentityCredential.GetToken()` now returns an error when configured for + a user assigned identity in Azure Cloud Shell (which doesn't support such identities) + ([#16946](https://github.com/Azure/azure-sdk-for-go/pull/16946)) + +### Other Changes +* `NewDefaultAzureCredential()` logs non-fatal errors. These errors are also included in the + error returned by `DefaultAzureCredential.GetToken()` when it's unable to acquire a token + from any source. ([#15923](https://github.com/Azure/azure-sdk-for-go/issues/15923)) + +## 0.13.0 (2022-01-11) + +### Breaking Changes +* Replaced `AuthenticationFailedError.RawResponse()` with a field having the same name +* Unexported `CredentialUnavailableError` +* Instances of `ChainedTokenCredential` will now skip looping through the list of source credentials and re-use the first successful credential on subsequent calls to `GetToken`. + * If `ChainedTokenCredentialOptions.RetrySources` is true, `ChainedTokenCredential` will continue to try all of the originally provided credentials each time the `GetToken` method is called. + * `ChainedTokenCredential.successfulCredential` will contain a reference to the last successful credential. + * `DefaultAzureCredenial` will also re-use the first successful credential on subsequent calls to `GetToken`. + * `DefaultAzureCredential.chain.successfulCredential` will also contain a reference to the last successful credential. + +### Other Changes +* `ManagedIdentityCredential` no longer probes IMDS before requesting a token + from it. Also, an error response from IMDS no longer disables a credential + instance. Following an error, a credential instance will continue to send + requests to IMDS as necessary. +* Adopted MSAL for user and service principal authentication +* Updated `azcore` requirement to 0.21.0 + +## 0.12.0 (2021-11-02) +### Breaking Changes +* Raised minimum go version to 1.16 +* Removed `NewAuthenticationPolicy()` from credentials. Clients should instead use azcore's + `runtime.NewBearerTokenPolicy()` to construct a bearer token authorization policy. +* The `AuthorityHost` field in credential options structs is now a custom type, + `AuthorityHost`, with underlying type `string` +* `NewChainedTokenCredential` has a new signature to accommodate a placeholder + options struct: + ```go + // before + cred, err := NewChainedTokenCredential(credA, credB) + + // after + cred, err := NewChainedTokenCredential([]azcore.TokenCredential{credA, credB}, nil) + ``` +* Removed `ExcludeAzureCLICredential`, `ExcludeEnvironmentCredential`, and `ExcludeMSICredential` + from `DefaultAzureCredentialOptions` +* `NewClientCertificateCredential` requires a `[]*x509.Certificate` and `crypto.PrivateKey` instead of + a path to a certificate file. Added `ParseCertificates` to simplify getting these in common cases: + ```go + // before + cred, err := NewClientCertificateCredential("tenant", "client-id", "/cert.pem", nil) + + // after + certData, err := os.ReadFile("/cert.pem") + certs, key, err := ParseCertificates(certData, password) + cred, err := NewClientCertificateCredential(tenantID, clientID, certs, key, nil) + ``` +* Removed `InteractiveBrowserCredentialOptions.ClientSecret` and `.Port` +* Removed `AADAuthenticationFailedError` +* Removed `id` parameter of `NewManagedIdentityCredential()`. User assigned identities are now + specified by `ManagedIdentityCredentialOptions.ID`: + ```go + // before + cred, err := NewManagedIdentityCredential("client-id", nil) + // or, for a resource ID + opts := &ManagedIdentityCredentialOptions{ID: ResourceID} + cred, err := NewManagedIdentityCredential("/subscriptions/...", opts) + + // after + clientID := ClientID("7cf7db0d-...") + opts := &ManagedIdentityCredentialOptions{ID: clientID} + // or, for a resource ID + resID: ResourceID("/subscriptions/...") + opts := &ManagedIdentityCredentialOptions{ID: resID} + cred, err := NewManagedIdentityCredential(opts) + ``` +* `DeviceCodeCredentialOptions.UserPrompt` has a new type: `func(context.Context, DeviceCodeMessage) error` +* Credential options structs now embed `azcore.ClientOptions`. In addition to changing literal initialization + syntax, this change renames `HTTPClient` fields to `Transport`. +* Renamed `LogCredential` to `EventCredential` +* `AzureCLICredential` no longer reads the environment variable `AZURE_CLI_PATH` +* `NewManagedIdentityCredential` no longer reads environment variables `AZURE_CLIENT_ID` and + `AZURE_RESOURCE_ID`. Use `ManagedIdentityCredentialOptions.ID` instead. +* Unexported `AuthenticationFailedError` and `CredentialUnavailableError` structs. In their place are two + interfaces having the same names. + +### Bugs Fixed +* `AzureCLICredential.GetToken` no longer mutates its `opts.Scopes` + +### Features Added +* Added connection configuration options to `DefaultAzureCredentialOptions` +* `AuthenticationFailedError.RawResponse()` returns the HTTP response motivating the error, + if available + +### Other Changes +* `NewDefaultAzureCredential()` returns `*DefaultAzureCredential` instead of `*ChainedTokenCredential` +* Added `TenantID` field to `DefaultAzureCredentialOptions` and `AzureCLICredentialOptions` + +## 0.11.0 (2021-09-08) +### Breaking Changes +* Unexported `AzureCLICredentialOptions.TokenProvider` and its type, + `AzureCLITokenProvider` + +### Bug Fixes +* `ManagedIdentityCredential.GetToken` returns `CredentialUnavailableError` + when IMDS has no assigned identity, signaling `DefaultAzureCredential` to + try other credentials + + +## 0.10.0 (2021-08-30) +### Breaking Changes +* Update based on `azcore` refactor [#15383](https://github.com/Azure/azure-sdk-for-go/pull/15383) + +## 0.9.3 (2021-08-20) + +### Bugs Fixed +* `ManagedIdentityCredential.GetToken` no longer mutates its `opts.Scopes` + +### Other Changes +* Bumps version of `azcore` to `v0.18.1` + + +## 0.9.2 (2021-07-23) +### Features Added +* Adding support for Service Fabric environment in `ManagedIdentityCredential` +* Adding an option for using a resource ID instead of client ID in `ManagedIdentityCredential` + + +## 0.9.1 (2021-05-24) +### Features Added +* Add LICENSE.txt and bump version information + + +## 0.9.0 (2021-05-21) +### Features Added +* Add support for authenticating in Azure Stack environments +* Enable user assigned identities for the IMDS scenario in `ManagedIdentityCredential` +* Add scope to resource conversion in `GetToken()` on `ManagedIdentityCredential` + + +## 0.8.0 (2021-01-20) +### Features Added +* Updating documentation + + +## 0.7.1 (2021-01-04) +### Features Added +* Adding port option to `InteractiveBrowserCredential` + + +## 0.7.0 (2020-12-11) +### Features Added +* Add `redirectURI` parameter back to authentication code flow + + +## 0.6.1 (2020-12-09) +### Features Added +* Updating query parameter in `ManagedIdentityCredential` and updating datetime string for parsing managed identity access tokens. + + +## 0.6.0 (2020-11-16) +### Features Added +* Remove `RedirectURL` parameter from auth code flow to align with the MSAL implementation which relies on the native client redirect URL. + + +## 0.5.0 (2020-10-30) +### Features Added +* Flattening credential options + + +## 0.4.3 (2020-10-21) +### Features Added +* Adding Azure Arc support in `ManagedIdentityCredential` + + +## 0.4.2 (2020-10-16) +### Features Added +* Typo fixes + + +## 0.4.1 (2020-10-16) +### Features Added +* Ensure authority hosts are only HTTPs + + +## 0.4.0 (2020-10-16) +### Features Added +* Adding options structs for credentials + + +## 0.3.0 (2020-10-09) +### Features Added +* Update `DeviceCodeCredential` callback + + +## 0.2.2 (2020-10-09) +### Features Added +* Add `AuthorizationCodeCredential` + + +## 0.2.1 (2020-10-06) +### Features Added +* Add `InteractiveBrowserCredential` + + +## 0.2.0 (2020-09-11) +### Features Added +* Refactor `azidentity` on top of `azcore` refactor +* Updated policies to conform to `policy.Policy` interface changes. +* Updated non-retriable errors to conform to `azcore.NonRetriableError`. +* Fixed calls to `Request.SetBody()` to include content type. +* Switched endpoints to string types and removed extra parsing code. + + +## 0.1.1 (2020-09-02) +### Features Added +* Add `AzureCLICredential` to `DefaultAzureCredential` chain + + +## 0.1.0 (2020-07-23) +### Features Added +* Initial Release. Azure Identity library that provides Azure Active Directory token authentication support for the SDK. diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/LICENSE.txt b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/LICENSE.txt new file mode 100644 index 00000000000..48ea6616b5b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/MIGRATION.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/MIGRATION.md new file mode 100644 index 00000000000..4ac53eb7b27 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/MIGRATION.md @@ -0,0 +1,307 @@ +# Migrating from autorest/adal to azidentity + +`azidentity` provides Azure Active Directory (Azure AD) authentication for the newest Azure SDK modules (`github.com/azure-sdk-for-go/sdk/...`). Older Azure SDK packages (`github.com/azure-sdk-for-go/services/...`) use types from `github.com/go-autorest/autorest/adal` instead. + +This guide shows common authentication code using `autorest/adal` and its equivalent using `azidentity`. + +## Table of contents + +- [Acquire a token](#acquire-a-token) +- [Client certificate authentication](#client-certificate-authentication) +- [Client secret authentication](#client-secret-authentication) +- [Configuration](#configuration) +- [Device code authentication](#device-code-authentication) +- [Managed identity](#managed-identity) +- [Use azidentity credentials with older packages](#use-azidentity-credentials-with-older-packages) + +## Configuration + +### `autorest/adal` + +Token providers require a token audience (resource identifier) and an instance of `adal.OAuthConfig`, which requires an Azure AD endpoint and tenant: + +```go +import "github.com/Azure/go-autorest/autorest/adal" + +oauthCfg, err := adal.NewOAuthConfig("https://login.chinacloudapi.cn", tenantID) +handle(err) + +spt, err := adal.NewServicePrincipalTokenWithSecret( + *oauthCfg, clientID, "https://management.chinacloudapi.cn/", &adal.ServicePrincipalTokenSecret{ClientSecret: secret}, +) +``` + +### `azidentity` + +A credential instance can acquire tokens for any audience. The audience for each token is determined by the client requesting it. Credentials require endpoint configuration only for sovereign or private clouds. The `azcore/cloud` package has predefined configuration for sovereign clouds such as Azure China: + +```go +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" +) + +clientOpts := azcore.ClientOptions{Cloud: cloud.AzureChina} + +cred, err := azidentity.NewClientSecretCredential( + tenantID, clientID, secret, &azidentity.ClientSecretCredentialOptions{ClientOptions: clientOpts}, +) +handle(err) +``` + +## Client secret authentication + +### `autorest/adal` + +```go +import ( + "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-06-01/subscriptions" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/adal" +) + +oauthCfg, err := adal.NewOAuthConfig("https://login.microsoftonline.com", tenantID) +handle(err) +spt, err := adal.NewServicePrincipalTokenWithSecret( + *oauthCfg, clientID, "https://management.azure.com/", &adal.ServicePrincipalTokenSecret{ClientSecret: secret}, +) +handle(err) + +client := subscriptions.NewClient() +client.Authorizer = autorest.NewBearerAuthorizer(spt) +``` + +### `azidentity` + +```go +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armsubscriptions" +) + +cred, err := azidentity.NewClientSecretCredential(tenantID, clientID, secret, nil) +handle(err) + +client, err := armsubscriptions.NewClient(cred, nil) +handle(err) +``` + +## Client certificate authentication + +### `autorest/adal` + +```go +import ( + "os" + + "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-06-01/subscriptions" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/adal" +) +certData, err := os.ReadFile("./example.pfx") +handle(err) + +certificate, rsaPrivateKey, err := decodePkcs12(certData, "") +handle(err) + +oauthCfg, err := adal.NewOAuthConfig("https://login.microsoftonline.com", tenantID) +handle(err) + +spt, err := adal.NewServicePrincipalTokenFromCertificate( + *oauthConfig, clientID, certificate, rsaPrivateKey, "https://management.azure.com/", +) + +client := subscriptions.NewClient() +client.Authorizer = autorest.NewBearerAuthorizer(spt) +``` + +### `azidentity` + +```go +import ( + "os" + + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armsubscriptions" +) + +certData, err := os.ReadFile("./example.pfx") +handle(err) + +certs, key, err := azidentity.ParseCertificates(certData, nil) +handle(err) + +cred, err = azidentity.NewClientCertificateCredential(tenantID, clientID, certs, key, nil) +handle(err) + +client, err := armsubscriptions.NewClient(cred, nil) +handle(err) +``` + +## Managed identity + +### `autorest/adal` + +```go +import ( + "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-06-01/subscriptions" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/adal" +) + +spt, err := adal.NewServicePrincipalTokenFromManagedIdentity("https://management.azure.com/", nil) +handle(err) + +client := subscriptions.NewClient() +client.Authorizer = autorest.NewBearerAuthorizer(spt) +``` + +### `azidentity` + +```go +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armsubscriptions" +) + +cred, err := azidentity.NewManagedIdentityCredential(nil) +handle(err) + +client, err := armsubscriptions.NewClient(cred, nil) +handle(err) +``` + +### User-assigned identities + +`autorest/adal`: + +```go +import "github.com/Azure/go-autorest/autorest/adal" + +opts := &adal.ManagedIdentityOptions{ClientID: "..."} +spt, err := adal.NewServicePrincipalTokenFromManagedIdentity("https://management.azure.com/") +handle(err) +``` + +`azidentity`: + +```go +import "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + +opts := azidentity.ManagedIdentityCredentialOptions{ID: azidentity.ClientID("...")} +cred, err := azidentity.NewManagedIdentityCredential(&opts) +handle(err) +``` + +## Device code authentication + +### `autorest/adal` + +```go +import ( + "fmt" + "net/http" + + "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-06-01/subscriptions" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/adal" +) + +oauthClient := &http.Client{} +oauthCfg, err := adal.NewOAuthConfig("https://login.microsoftonline.com", tenantID) +handle(err) +resource := "https://management.azure.com/" +deviceCode, err := adal.InitiateDeviceAuth(oauthClient, *oauthCfg, clientID, resource) +handle(err) + +// display instructions, wait for the user to authenticate +fmt.Println(*deviceCode.Message) +token, err := adal.WaitForUserCompletion(oauthClient, deviceCode) +handle(err) + +spt, err := adal.NewServicePrincipalTokenFromManualToken(*oauthCfg, clientID, resource, *token) +handle(err) + +client := subscriptions.NewClient() +client.Authorizer = autorest.NewBearerAuthorizer(spt) +``` + +### `azidentity` + +```go +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armsubscriptions" +) + +cred, err := azidentity.NewDeviceCodeCredential(nil) +handle(err) + +client, err := armsubscriptions.NewSubscriptionsClient(cred, nil) +handle(err) +``` + +`azidentity.DeviceCodeCredential` will guide a user through authentication, printing instructions to the console by default. The user prompt is customizable. For more information, see the [package documentation](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#DeviceCodeCredential). + +## Acquire a token + +### `autorest/adal` + +```go +import "github.com/Azure/go-autorest/autorest/adal" + +oauthCfg, err := adal.NewOAuthConfig("https://login.microsoftonline.com", tenantID) +handle(err) + +spt, err := adal.NewServicePrincipalTokenWithSecret( + *oauthCfg, clientID, "https://vault.azure.net", &adal.ServicePrincipalTokenSecret{ClientSecret: secret}, +) + +err = spt.Refresh() +if err == nil { + token := spt.Token +} +``` + +### `azidentity` + +In ordinary usage, application code doesn't need to request tokens from credentials directly. Azure SDK clients handle token acquisition and refreshing internally. However, applications may call `GetToken()` to do so. All credential types have this method. + +```go +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" +) + +cred, err := azidentity.NewClientSecretCredential(tenantID, clientID, secret, nil) +handle(err) + +tk, err := cred.GetToken( + context.TODO(), policy.TokenRequestOptions{Scopes: []string{"https://vault.azure.net/.default"}}, +) +if err == nil { + token := tk.Token +} +``` + +Note that `azidentity` credentials use the Azure AD v2.0 endpoint, which requires OAuth 2 scopes instead of the resource identifiers `autorest/adal` expects. For more information, see [Azure AD documentation](https://docs.microsoft.com/azure/active-directory/develop/v2-permissions-and-consent). + +## Use azidentity credentials with older packages + +The [azidext module](https://pkg.go.dev/github.com/jongio/azidext/go/azidext) provides an adapter for `azidentity` credential types. The adapter enables using the credential types with older Azure SDK clients. For example: + +```go +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-06-01/subscriptions" + "github.com/jongio/azidext/go/azidext" +) + +cred, err := azidentity.NewClientSecretCredential(tenantID, clientID, secret, nil) +handle(err) + +client := subscriptions.NewClient() +client.Authorizer = azidext.NewTokenCredentialAdapter(cred, []string{"https://management.azure.com//.default"}) +``` + +![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-go%2Fsdk%2Fazidentity%2FMIGRATION.png) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/README.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/README.md new file mode 100644 index 00000000000..2df42c813a5 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/README.md @@ -0,0 +1,241 @@ +# Azure Identity Client Module for Go + +The Azure Identity module provides Azure Active Directory (Azure AD) token authentication support across the Azure SDK. It includes a set of `TokenCredential` implementations, which can be used with Azure SDK clients supporting token authentication. + +[![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/azidentity)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity) +| [Azure Active Directory documentation](https://docs.microsoft.com/azure/active-directory/) +| [Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/azidentity) + +# Getting started + +## Install the module + +This project uses [Go modules](https://github.com/golang/go/wiki/Modules) for versioning and dependency management. + +Install the Azure Identity module: + +```sh +go get -u github.com/Azure/azure-sdk-for-go/sdk/azidentity +``` + +## Prerequisites + +- an [Azure subscription](https://azure.microsoft.com/free/) +- Go 1.18 + +### Authenticating during local development + +When debugging and executing code locally, developers typically use their own accounts to authenticate calls to Azure services. The `azidentity` module supports authenticating through developer tools to simplify local development. + +#### Authenticating via the Azure CLI + +`DefaultAzureCredential` and `AzureCLICredential` can authenticate as the user +signed in to the [Azure CLI](https://docs.microsoft.com/cli/azure). To sign in to the Azure CLI, run `az login`. On a system with a default web browser, the Azure CLI will launch the browser to authenticate a user. + +When no default browser is available, `az login` will use the device code +authentication flow. This can also be selected manually by running `az login --use-device-code`. + +## Key concepts + +### Credentials + +A credential is a type which contains or can obtain the data needed for a +service client to authenticate requests. Service clients across the Azure SDK +accept a credential instance when they are constructed, and use that credential +to authenticate requests. + +The `azidentity` module focuses on OAuth authentication with Azure Active +Directory (AAD). It offers a variety of credential types capable of acquiring +an Azure AD access token. See [Credential Types](#credential-types "Credential Types") for a list of this module's credential types. + +### DefaultAzureCredential + +`DefaultAzureCredential` is appropriate for most apps that will be deployed to Azure. It combines common production credentials with development credentials. It attempts to authenticate via the following mechanisms in this order, stopping when one succeeds: + +![DefaultAzureCredential authentication flow](img/mermaidjs/DefaultAzureCredentialAuthFlow.svg) + +1. **Environment** - `DefaultAzureCredential` will read account information specified via [environment variables](#environment-variables) and use it to authenticate. +2. **Managed Identity** - If the app is deployed to an Azure host with managed identity enabled, `DefaultAzureCredential` will authenticate with it. +3. **Azure CLI** - If a user or service principal has authenticated via the Azure CLI `az login` command, `DefaultAzureCredential` will authenticate that identity. + +> Note: `DefaultAzureCredential` is intended to simplify getting started with the SDK by handling common scenarios with reasonable default behaviors. Developers who want more control or whose scenario isn't served by the default settings should use other credential types. + +## Managed Identity + +`DefaultAzureCredential` and `ManagedIdentityCredential` support +[managed identity authentication](https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/overview) +in any hosting environment which supports managed identities, such as (this list is not exhaustive): +* [Azure App Service](https://docs.microsoft.com/azure/app-service/overview-managed-identity) +* [Azure Arc](https://docs.microsoft.com/azure/azure-arc/servers/managed-identity-authentication) +* [Azure Cloud Shell](https://docs.microsoft.com/azure/cloud-shell/msi-authorization) +* [Azure Kubernetes Service](https://docs.microsoft.com/azure/aks/use-managed-identity) +* [Azure Service Fabric](https://docs.microsoft.com/azure/service-fabric/concepts-managed-identity) +* [Azure Virtual Machines](https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/how-to-use-vm-token) + +## Examples + +- [Authenticate with DefaultAzureCredential](#authenticate-with-defaultazurecredential "Authenticate with DefaultAzureCredential") +- [Define a custom authentication flow with ChainedTokenCredential](#define-a-custom-authentication-flow-with-chainedtokencredential "Define a custom authentication flow with ChainedTokenCredential") +- [Specify a user-assigned managed identity for DefaultAzureCredential](#specify-a-user-assigned-managed-identity-for-defaultazurecredential) + +### Authenticate with DefaultAzureCredential + +This example demonstrates authenticating a client from the `armresources` module with `DefaultAzureCredential`. + +```go +cred, err := azidentity.NewDefaultAzureCredential(nil) +if err != nil { + // handle error +} + +client := armresources.NewResourceGroupsClient("subscription ID", cred, nil) +``` + +### Specify a user-assigned managed identity for DefaultAzureCredential + +To configure `DefaultAzureCredential` to authenticate a user-assigned managed identity, set the environment variable `AZURE_CLIENT_ID` to the identity's client ID. + +### Define a custom authentication flow with `ChainedTokenCredential` + +`DefaultAzureCredential` is generally the quickest way to get started developing apps for Azure. For more advanced scenarios, `ChainedTokenCredential` links multiple credential instances to be tried sequentially when authenticating. It will try each chained credential in turn until one provides a token or fails to authenticate due to an error. + +The following example demonstrates creating a credential, which will attempt to authenticate using managed identity. It will fall back to authenticating via the Azure CLI when a managed identity is unavailable. + +```go +managed, err := azidentity.NewManagedIdentityCredential(nil) +if err != nil { + // handle error +} +azCLI, err := azidentity.NewAzureCLICredential(nil) +if err != nil { + // handle error +} +chain, err := azidentity.NewChainedTokenCredential([]azcore.TokenCredential{managed, azCLI}, nil) +if err != nil { + // handle error +} + +client := armresources.NewResourceGroupsClient("subscription ID", chain, nil) +``` + +## Credential Types + +### Authenticating Azure Hosted Applications + +|Credential|Usage +|-|- +|[DefaultAzureCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#DefaultAzureCredential)|Simplified authentication experience for getting started developing Azure apps +|[ChainedTokenCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#ChainedTokenCredential)|Define custom authentication flows, composing multiple credentials +|[EnvironmentCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#EnvironmentCredential)|Authenticate a service principal or user configured by environment variables +|[ManagedIdentityCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#ManagedIdentityCredential)|Authenticate the managed identity of an Azure resource + +### Authenticating Service Principals + +|Credential|Usage +|-|- +|[ClientAssertionCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity@v1.2.0-beta.2#ClientAssertionCredential)|Authenticate a service principal with a signed client assertion +|[ClientCertificateCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#ClientCertificateCredential)|Authenticate a service principal with a certificate +|[ClientSecretCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#ClientSecretCredential)|Authenticate a service principal with a secret + +### Authenticating Users + +|Credential|Usage +|-|- +|[InteractiveBrowserCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#InteractiveBrowserCredential)|Interactively authenticate a user with the default web browser +|[DeviceCodeCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#DeviceCodeCredential)|Interactively authenticate a user on a device with limited UI +|[UsernamePasswordCredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#UsernamePasswordCredential)|Authenticate a user with a username and password + +### Authenticating via Development Tools + +|Credential|Usage +|-|- +|[AzureCLICredential](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#AzureCLICredential)|Authenticate as the user signed in to the Azure CLI + +## Environment Variables + +`DefaultAzureCredential` and `EnvironmentCredential` can be configured with environment variables. Each type of authentication requires values for specific variables: + +#### Service principal with secret + +|variable name|value +|-|- +|`AZURE_CLIENT_ID`|ID of an Azure Active Directory application +|`AZURE_TENANT_ID`|ID of the application's Azure Active Directory tenant +|`AZURE_CLIENT_SECRET`|one of the application's client secrets + +#### Service principal with certificate + +|variable name|value +|-|- +|`AZURE_CLIENT_ID`|ID of an Azure Active Directory application +|`AZURE_TENANT_ID`|ID of the application's Azure Active Directory tenant +|`AZURE_CLIENT_CERTIFICATE_PATH`|path to a certificate file including private key +|`AZURE_CLIENT_CERTIFICATE_PASSWORD`|password of the certificate file, if any + +#### Username and password + +|variable name|value +|-|- +|`AZURE_CLIENT_ID`|ID of an Azure Active Directory application +|`AZURE_USERNAME`|a username (usually an email address) +|`AZURE_PASSWORD`|that user's password + +Configuration is attempted in the above order. For example, if values for a +client secret and certificate are both present, the client secret will be used. + +## Troubleshooting + +### Error Handling + +Credentials return an `error` when they fail to authenticate or lack data they require to authenticate. For guidance on resolving errors from specific credential types, see the [troubleshooting guide](https://aka.ms/azsdk/go/identity/troubleshoot). + +For more details on handling specific Azure Active Directory errors please refer to the +Azure Active Directory +[error code documentation](https://docs.microsoft.com/azure/active-directory/develop/reference-aadsts-error-codes). + +### Logging + +This module uses the classification-based logging implementation in `azcore`. To enable console logging for all SDK modules, set `AZURE_SDK_GO_LOGGING` to `all`. Use the `azcore/log` package to control log event output or to enable logs for `azidentity` only. For example: +```go +import azlog "github.com/Azure/azure-sdk-for-go/sdk/azcore/log" + +// print log output to stdout +azlog.SetListener(func(event azlog.Event, s string) { + fmt.Println(s) +}) + +// include only azidentity credential logs +azlog.SetEvents(azidentity.EventAuthentication) +``` + +Credentials log basic information only, such as `GetToken` success or failure and errors. These log entries don't contain authentication secrets but may contain sensitive information. + +## Next steps + +Client and management modules listed on the [Azure SDK releases page](https://azure.github.io/azure-sdk/releases/latest/go.html) support authenticating with `azidentity` credential types. You can learn more about using these libraries in their documentation, which is linked from the release page. + +## Provide Feedback + +If you encounter bugs or have suggestions, please +[open an issue](https://github.com/Azure/azure-sdk-for-go/issues). + +## Contributing + +This project welcomes contributions and suggestions. Most contributions require +you to agree to a Contributor License Agreement (CLA) declaring that you have +the right to, and actually do, grant us the rights to use your contribution. +For details, visit [https://cla.microsoft.com](https://cla.microsoft.com). + +When you submit a pull request, a CLA-bot will automatically determine whether +you need to provide a CLA and decorate the PR appropriately (e.g., label, +comment). Simply follow the instructions provided by the bot. You will only +need to do this once across all repos using our CLA. + +This project has adopted the +[Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information, see the +[Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) +or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any +additional questions or comments. + +![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-go%2Fsdk%2Fazidentity%2FREADME.png) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/TROUBLESHOOTING.md b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/TROUBLESHOOTING.md new file mode 100644 index 00000000000..affa91d0874 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/TROUBLESHOOTING.md @@ -0,0 +1,197 @@ +# Troubleshoot Azure Identity authentication issues + +This troubleshooting guide covers failure investigation techniques, common errors for the credential types in the `azidentity` module, and mitigation steps to resolve these errors. + +## Table of contents + +- [Handle azidentity errors](#handle-azidentity-errors) + - [Permission issues](#permission-issues) +- [Find relevant information in errors](#find-relevant-information-in-errors) +- [Enable and configure logging](#enable-and-configure-logging) +- [Troubleshoot DefaultAzureCredential authentication issues](#troubleshoot-defaultazurecredential-authentication-issues) +- [Troubleshoot EnvironmentCredential authentication issues](#troubleshoot-environmentcredential-authentication-issues) +- [Troubleshoot ClientSecretCredential authentication issues](#troubleshoot-clientsecretcredential-authentication-issues) +- [Troubleshoot ClientCertificateCredential authentication issues](#troubleshoot-clientcertificatecredential-authentication-issues) +- [Troubleshoot UsernamePasswordCredential authentication issues](#troubleshoot-usernamepasswordcredential-authentication-issues) +- [Troubleshoot ManagedIdentityCredential authentication issues](#troubleshoot-managedidentitycredential-authentication-issues) + - [Azure Virtual Machine managed identity](#azure-virtual-machine-managed-identity) + - [Azure App Service and Azure Functions managed identity](#azure-app-service-and-azure-functions-managed-identity) + - [Azure Kubernetes Service managed identity](#azure-kubernetes-service-managed-identity) +- [Troubleshoot AzureCliCredential authentication issues](#troubleshoot-azureclicredential-authentication-issues) +- [Get additional help](#get-additional-help) + +## Handle azidentity errors + +Any service client method that makes a request to the service may return an error due to authentication failure. This is because the credential authenticates on the first call to the service and on any subsequent call that needs to refresh an access token. Authentication errors include a description of the failure and possibly an error message from Azure Active Directory (Azure AD). Depending on the application, these errors may or may not be recoverable. + +### Permission issues + +Service client errors with a status code of 401 or 403 often indicate that authentication succeeded but the caller doesn't have permission to access the specified API. Check the service documentation to determine which RBAC roles are needed for the request, and ensure the authenticated user or service principal has the appropriate role assignments. + +## Find relevant information in errors + +Authentication errors can include responses from Azure AD and often contain information helpful in diagnosis. Consider the following error message: + +``` +ClientSecretCredential authentication failed +POST https://login.microsoftonline.com/3c631bb7-a9f7-4343-a5ba-a615913/oauth2/v2.0/token +-------------------------------------------------------------------------------- +RESPONSE 401 Unauthorized +-------------------------------------------------------------------------------- +{ + "error": "invalid_client", + "error_description": "AADSTS7000215: Invalid client secret provided. Ensure the secret being sent in the request is the client secret value, not the client secret ID, for a secret added to app '86be4c01-505b-45e9-bfc0-9b825fd84'.\r\nTrace ID: 03da4b8e-5ffe-48ca-9754-aff4276f0100\r\nCorrelation ID: 7b12f9bb-2eef-42e3-ad75-eee69ec9088d\r\nTimestamp: 2022-03-02 18:25:26Z", + "error_codes": [ + 7000215 + ], + "timestamp": "2022-03-02 18:25:26Z", + "trace_id": "03da4b8e-5ffe-48ca-9754-aff4276f0100", + "correlation_id": "7b12f9bb-2eef-42e3-ad75-eee69ec9088d", + "error_uri": "https://login.microsoftonline.com/error?code=7000215" +} +-------------------------------------------------------------------------------- +``` + +This error contains several pieces of information: + +- __Failing Credential Type__: The type of credential that failed to authenticate. This can be helpful when diagnosing issues with chained credential types such as `DefaultAzureCredential` or `ChainedTokenCredential`. + +- __Azure AD Error Code and Message__: The error code and message returned by Azure AD. This can give insight into the specific reason the request failed. For instance, in this case authentication failed because the provided client secret is incorrect. [Azure AD documentation](https://docs.microsoft.com/azure/active-directory/develop/reference-aadsts-error-codes#aadsts-error-codes) has more information on AADSTS error codes. + +- __Correlation ID and Timestamp__: The correlation ID and timestamp identify the request in server-side logs. This information can be useful to support engineers diagnosing unexpected Azure AD failures. + +### Enable and configure logging + +`azidentity` provides the same logging capabilities as the rest of the Azure SDK. The simplest way to see the logs to help debug authentication issues is to print credential logs to the console. +```go +import azlog "github.com/Azure/azure-sdk-for-go/sdk/azcore/log" + +// print log output to stdout +azlog.SetListener(func(event azlog.Event, s string) { + fmt.Println(s) +}) + +// include only azidentity credential logs +azlog.SetEvents(azidentity.EventAuthentication) +``` + +## Troubleshoot DefaultAzureCredential authentication issues + +| Error |Description| Mitigation | +|---|---|---| +|"DefaultAzureCredential failed to acquire a token"|No credential in the `DefaultAzureCredential` chain provided a token|
  • [Enable logging](#enable-and-configure-logging) to get further diagnostic information.
  • Consult the troubleshooting guide for underlying credential types for more information.
    • [EnvironmentCredential](#troubleshoot-environmentcredential-authentication-issues)
    • [ManagedIdentityCredential](#troubleshoot-visualstudiocredential-authentication-issues)
    • [AzureCLICredential](#troubleshoot-azureclicredential-authentication-issues)
    | +|Error from the client with a status code of 401 or 403|Authentication succeeded but the authorizing Azure service responded with a 401 (Unauthorized), or 403 (Forbidden) status code|
    • [Enable logging](#enable-and-configure-logging) to determine which credential in the chain returned the authenticating token.
    • If an unexpected credential is returning a token, check application configuration such as environment variables.
    • Ensure the correct role is assigned to the authenticated identity. For example, a service specific role rather than the subscription Owner role.
    | + +## Troubleshoot EnvironmentCredential authentication issues + +| Error Message |Description| Mitigation | +|---|---|---| +|Missing or incomplete environment variable configuration|A valid combination of environment variables wasn't set|Ensure the appropriate environment variables are set for the intended authentication method as described in the [module documentation](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#EnvironmentCredential)| + + +## Troubleshoot ClientSecretCredential authentication issues + +| Error Code | Issue | Mitigation | +|---|---|---| +|AADSTS7000215|An invalid client secret was provided.|Ensure the secret provided to the credential constructor is valid. If unsure, create a new client secret using the Azure portal. Details on creating a new client secret are in [Azure AD documentation](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal#option-2-create-a-new-application-secret).| +|AADSTS7000222|An expired client secret was provided.|Create a new client secret using the Azure portal. Details on creating a new client secret are in [Azure AD documentation](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal#option-2-create-a-new-application-secret).| +|AADSTS700016|The specified application wasn't found in the specified tenant.|Ensure the client and tenant IDs provided to the credential constructor are correct for your application registration. For multi-tenant apps, ensure the application has been added to the desired tenant by a tenant admin. To add a new application in the desired tenant, follow the [Azure AD instructions](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal).| + + +## Troubleshoot ClientCertificateCredential authentication issues + +| Error Code | Description | Mitigation | +|---|---|---| +|AADSTS700027|Client assertion contains an invalid signature.|Ensure the specified certificate has been uploaded to the application registration as described in [Azure AD documentation](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal#option-1-upload-a-certificate).| +|AADSTS700016|The specified application wasn't found in the specified tenant.|Ensure the client and tenant IDs provided to the credential constructor are correct for your application registration. For multi-tenant apps, ensure the application has been added to the desired tenant by a tenant admin. To add a new application in the desired tenant, follow the [Azure AD instructions](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal).| + + +## Troubleshoot UsernamePasswordCredential authentication issues + +| Error Code | Issue | Mitigation | +|---|---|---| +|AADSTS50126|The provided username or password is invalid.|Ensure the username and password provided to the credential constructor are valid.| + + +## Troubleshoot ManagedIdentityCredential authentication issues + +`ManagedIdentityCredential` is designed to work on a variety of Azure hosts support managed identity. Configuration and troubleshooting vary from host to host. The below table lists the Azure hosts that can be assigned a managed identity and are supported by `ManagedIdentityCredential`. + +|Host Environment| | | +|---|---|---| +|Azure Virtual Machines and Scale Sets|[Configuration](https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/qs-configure-portal-windows-vm)|[Troubleshooting](#azure-virtual-machine-managed-identity)| +|Azure App Service and Azure Functions|[Configuration](https://docs.microsoft.com/azure/app-service/overview-managed-identity)|[Troubleshooting](#azure-app-service-and-azure-functions-managed-identity)| +|Azure Kubernetes Service|[Configuration](https://azure.github.io/aad-pod-identity/docs/)|[Troubleshooting](#azure-kubernetes-service-managed-identity)| +|Azure Arc|[Configuration](https://docs.microsoft.com/azure/azure-arc/servers/managed-identity-authentication)|| +|Azure Service Fabric|[Configuration](https://docs.microsoft.com/azure/service-fabric/concepts-managed-identity)|| + +### Azure Virtual Machine managed identity + +| Error Message |Description| Mitigation | +|---|---|---| +|The requested identity hasn’t been assigned to this resource.|The IMDS endpoint responded with a status code of 400, indicating the requested identity isn’t assigned to the VM.|If using a user assigned identity, ensure the specified ID is correct.

    If using a system assigned identity, make sure it has been enabled as described in [managed identity documentation](https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/qs-configure-portal-windows-vm#enable-system-assigned-managed-identity-on-an-existing-vm).| +|The request failed due to a gateway error.|The request to the IMDS endpoint failed due to a gateway error, 502 or 504 status code.|IMDS doesn't support requests via proxy or gateway. Disable proxies or gateways running on the VM for requests to the IMDS endpoint `http://169.254.169.254`| +|No response received from the managed identity endpoint.|No response was received for the request to IMDS or the request timed out.|

    • Ensure the VM is configured for managed identity as described in [managed identity documentation](https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/qs-configure-portal-windows-vm).
    • Verify the IMDS endpoint is reachable on the VM. See [below](#verify-imds-is-available-on-the-vm) for instructions.
    | +|Multiple attempts failed to obtain a token from the managed identity endpoint.|The credential has exhausted its retries for a token request.|
    • Refer to the error message for more details on specific failures.
    • Ensure the VM is configured for managed identity as described in [managed identity documentation](https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/qs-configure-portal-windows-vm).
    • Verify the IMDS endpoint is reachable on the VM. See [below](#verify-imds-is-available-on-the-vm) for instructions.
    | + +#### Verify IMDS is available on the VM + +If you have access to the VM, you can use `curl` to verify the managed identity endpoint is available. + +```sh +curl 'http://169.254.169.254/metadata/identity/oauth2/token?resource=https://management.core.windows.net&api-version=2018-02-01' -H "Metadata: true" +``` + +> This command's output will contain an access token and SHOULD NOT BE SHARED, to avoid compromising account security. + +### Azure App Service and Azure Functions managed identity + +| Error Message |Description| Mitigation | +|---|---|---| +|Get "`http://169.254.169.254/...`" i/o timeout|The App Service host hasn't set environment variables for managed identity configuration.|
    • Ensure the App Service is configured for managed identity as described in [App Service documentation](https://docs.microsoft.com/azure/app-service/overview-managed-identity).
    • Verify the App Service environment is properly configured and the managed identity endpoint is available. See [below](#verify-the-app-service-managed-identity-endpoint-is-available) for instructions.
    | + +#### Verify the App Service managed identity endpoint is available + +If you can SSH into the App Service, you can verify managed identity is available in the environment. First ensure the environment variables `IDENTITY_ENDPOINT` and `IDENTITY_SECRET` are set. Then you can verify the managed identity endpoint is available using `curl`. + +```sh +curl "$IDENTITY_ENDPOINT?resource=https://management.core.windows.net&api-version=2019-08-01" -H "X-IDENTITY-HEADER: $IDENTITY_HEADER" +``` + +> This command's output will contain an access token and SHOULD NOT BE SHARED, to avoid compromising account security. + +### Azure Kubernetes Service managed identity + +#### Pod Identity + +| Error Message |Description| Mitigation | +|---|---|---| +|"no azure identity found for request clientID"|The application attempted to authenticate before an identity was assigned to its pod|Verify the pod is labeled correctly. This also occurs when a correctly labeled pod authenticates before the identity is ready. To prevent initialization races, configure NMI to set the Retry-After header in its responses as described in [Pod Identity documentation](https://azure.github.io/aad-pod-identity/docs/configure/feature_flags/#set-retry-after-header-in-nmi-response). + + +## Troubleshoot AzureCliCredential authentication issues + +| Error Message |Description| Mitigation | +|---|---|---| +|Azure CLI not found on path|The Azure CLI isn’t installed or isn't on the application's path.|
    • Ensure the Azure CLI is installed as described in [Azure CLI documentation](https://docs.microsoft.com/cli/azure/install-azure-cli).
    • Validate the installation location is in the application's `PATH` environment variable.
    | +|Please run 'az login' to set up account|No account is currently logged into the Azure CLI, or the login has expired.|
    • Run `az login` to log into the Azure CLI. More information about Azure CLI authentication is available in the [Azure CLI documentation](https://docs.microsoft.com/cli/azure/authenticate-azure-cli).
    • Verify that the Azure CLI can obtain tokens. See [below](#verify-the-azure-cli-can-obtain-tokens) for instructions.
    | + +#### Verify the Azure CLI can obtain tokens + +You can manually verify that the Azure CLI can authenticate and obtain tokens. First, use the `account` command to verify the logged in account. + +```azurecli +az account show +``` + +Once you've verified the Azure CLI is using the correct account, you can validate that it's able to obtain tokens for that account. + +```azurecli +az account get-access-token --output json --resource https://management.core.windows.net +``` + +> This command's output will contain an access token and SHOULD NOT BE SHARED, to avoid compromising account security. + +## Get additional help + +Additional information on ways to reach out for support can be found in [SUPPORT.md](https://github.com/Azure/azure-sdk-for-go/blob/main/SUPPORT.md). diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azidentity.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azidentity.go new file mode 100644 index 00000000000..98d6219ee7e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azidentity.go @@ -0,0 +1,165 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "bytes" + "context" + "errors" + "io" + "net/http" + "net/url" + "os" + "regexp" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/public" +) + +const ( + azureAuthorityHost = "AZURE_AUTHORITY_HOST" + azureClientCertificatePassword = "AZURE_CLIENT_CERTIFICATE_PASSWORD" + azureClientCertificatePath = "AZURE_CLIENT_CERTIFICATE_PATH" + azureClientID = "AZURE_CLIENT_ID" + azureClientSecret = "AZURE_CLIENT_SECRET" + azurePassword = "AZURE_PASSWORD" + azureRegionalAuthorityName = "AZURE_REGIONAL_AUTHORITY_NAME" + azureTenantID = "AZURE_TENANT_ID" + azureUsername = "AZURE_USERNAME" + + organizationsTenantID = "organizations" + developerSignOnClientID = "04b07795-8ddb-461a-bbee-02f9e1bf7b46" + defaultSuffix = "/.default" + tenantIDValidationErr = "invalid tenantID. You can locate your tenantID by following the instructions listed here: https://docs.microsoft.com/partner-center/find-ids-and-domain-names" +) + +func getConfidentialClient(clientID, tenantID string, cred confidential.Credential, co *azcore.ClientOptions, additionalOpts ...confidential.Option) (confidential.Client, error) { + if !validTenantID(tenantID) { + return confidential.Client{}, errors.New(tenantIDValidationErr) + } + authorityHost, err := setAuthorityHost(co.Cloud) + if err != nil { + return confidential.Client{}, err + } + o := []confidential.Option{ + confidential.WithAuthority(runtime.JoinPaths(authorityHost, tenantID)), + confidential.WithAzureRegion(os.Getenv(azureRegionalAuthorityName)), + confidential.WithHTTPClient(newPipelineAdapter(co)), + } + o = append(o, additionalOpts...) + return confidential.New(clientID, cred, o...) +} + +func getPublicClient(clientID, tenantID string, co *azcore.ClientOptions) (public.Client, error) { + if !validTenantID(tenantID) { + return public.Client{}, errors.New(tenantIDValidationErr) + } + authorityHost, err := setAuthorityHost(co.Cloud) + if err != nil { + return public.Client{}, err + } + return public.New(clientID, + public.WithAuthority(runtime.JoinPaths(authorityHost, tenantID)), + public.WithHTTPClient(newPipelineAdapter(co)), + ) +} + +// setAuthorityHost initializes the authority host for credentials. Precedence is: +// 1. cloud.Configuration.ActiveDirectoryAuthorityHost value set by user +// 2. value of AZURE_AUTHORITY_HOST +// 3. default: Azure Public Cloud +func setAuthorityHost(cc cloud.Configuration) (string, error) { + host := cc.ActiveDirectoryAuthorityHost + if host == "" { + if len(cc.Services) > 0 { + return "", errors.New("missing ActiveDirectoryAuthorityHost for specified cloud") + } + host = cloud.AzurePublic.ActiveDirectoryAuthorityHost + if envAuthorityHost := os.Getenv(azureAuthorityHost); envAuthorityHost != "" { + host = envAuthorityHost + } + } + u, err := url.Parse(host) + if err != nil { + return "", err + } + if u.Scheme != "https" { + return "", errors.New("cannot use an authority host without https") + } + return host, nil +} + +// validTenantID return true is it receives a valid tenantID, returns false otherwise +func validTenantID(tenantID string) bool { + match, err := regexp.MatchString("^[0-9a-zA-Z-.]+$", tenantID) + if err != nil { + return false + } + return match +} + +func newPipelineAdapter(opts *azcore.ClientOptions) pipelineAdapter { + pl := runtime.NewPipeline(component, version, runtime.PipelineOptions{}, opts) + return pipelineAdapter{pl: pl} +} + +type pipelineAdapter struct { + pl runtime.Pipeline +} + +func (p pipelineAdapter) CloseIdleConnections() { + // do nothing +} + +func (p pipelineAdapter) Do(r *http.Request) (*http.Response, error) { + req, err := runtime.NewRequest(r.Context(), r.Method, r.URL.String()) + if err != nil { + return nil, err + } + if r.Body != nil && r.Body != http.NoBody { + // create a rewindable body from the existing body as required + var body io.ReadSeekCloser + if rsc, ok := r.Body.(io.ReadSeekCloser); ok { + body = rsc + } else { + b, err := io.ReadAll(r.Body) + if err != nil { + return nil, err + } + body = streaming.NopCloser(bytes.NewReader(b)) + } + err = req.SetBody(body, r.Header.Get("Content-Type")) + if err != nil { + return nil, err + } + } + resp, err := p.pl.Do(req) + if err != nil { + return nil, err + } + return resp, err +} + +// enables fakes for test scenarios +type confidentialClient interface { + AcquireTokenSilent(ctx context.Context, scopes []string, options ...confidential.AcquireSilentOption) (confidential.AuthResult, error) + AcquireTokenByAuthCode(ctx context.Context, code string, redirectURI string, scopes []string, options ...confidential.AcquireByAuthCodeOption) (confidential.AuthResult, error) + AcquireTokenByCredential(ctx context.Context, scopes []string, options ...confidential.AcquireByCredentialOption) (confidential.AuthResult, error) +} + +// enables fakes for test scenarios +type publicClient interface { + AcquireTokenSilent(ctx context.Context, scopes []string, options ...public.AcquireSilentOption) (public.AuthResult, error) + AcquireTokenByUsernamePassword(ctx context.Context, scopes []string, username string, password string, options ...public.AcquireByUsernamePasswordOption) (public.AuthResult, error) + AcquireTokenByDeviceCode(ctx context.Context, scopes []string, options ...public.AcquireByDeviceCodeOption) (public.DeviceCode, error) + AcquireTokenByAuthCode(ctx context.Context, code string, redirectURI string, scopes []string, options ...public.AcquireByAuthCodeOption) (public.AuthResult, error) + AcquireTokenInteractive(ctx context.Context, scopes []string, options ...public.AcquireInteractiveOption) (public.AuthResult, error) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azure_cli_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azure_cli_credential.go new file mode 100644 index 00000000000..68f46d51a1e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/azure_cli_credential.go @@ -0,0 +1,189 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "os" + "os/exec" + "regexp" + "runtime" + "strings" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" +) + +const credNameAzureCLI = "AzureCLICredential" + +// used by tests to fake invoking the CLI +type azureCLITokenProvider func(ctx context.Context, resource string, tenantID string) ([]byte, error) + +// AzureCLICredentialOptions contains optional parameters for AzureCLICredential. +type AzureCLICredentialOptions struct { + // TenantID identifies the tenant the credential should authenticate in. + // Defaults to the CLI's default tenant, which is typically the home tenant of the logged in user. + TenantID string + + tokenProvider azureCLITokenProvider +} + +// init returns an instance of AzureCLICredentialOptions initialized with default values. +func (o *AzureCLICredentialOptions) init() { + if o.tokenProvider == nil { + o.tokenProvider = defaultTokenProvider() + } +} + +// AzureCLICredential authenticates as the identity logged in to the Azure CLI. +type AzureCLICredential struct { + tokenProvider azureCLITokenProvider + tenantID string +} + +// NewAzureCLICredential constructs an AzureCLICredential. Pass nil to accept default options. +func NewAzureCLICredential(options *AzureCLICredentialOptions) (*AzureCLICredential, error) { + cp := AzureCLICredentialOptions{} + if options != nil { + cp = *options + } + cp.init() + return &AzureCLICredential{ + tokenProvider: cp.tokenProvider, + tenantID: cp.TenantID, + }, nil +} + +// GetToken requests a token from the Azure CLI. This credential doesn't cache tokens, so every call invokes the CLI. +// This method is called automatically by Azure SDK clients. +func (c *AzureCLICredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + if len(opts.Scopes) != 1 { + return azcore.AccessToken{}, errors.New(credNameAzureCLI + ": GetToken() requires exactly one scope") + } + // CLI expects an AAD v1 resource, not a v2 scope + scope := strings.TrimSuffix(opts.Scopes[0], defaultSuffix) + at, err := c.authenticate(ctx, scope) + if err != nil { + return azcore.AccessToken{}, err + } + logGetTokenSuccess(c, opts) + return at, nil +} + +const timeoutCLIRequest = 10 * time.Second + +func (c *AzureCLICredential) authenticate(ctx context.Context, resource string) (azcore.AccessToken, error) { + output, err := c.tokenProvider(ctx, resource, c.tenantID) + if err != nil { + return azcore.AccessToken{}, err + } + + return c.createAccessToken(output) +} + +func defaultTokenProvider() func(ctx context.Context, resource string, tenantID string) ([]byte, error) { + return func(ctx context.Context, resource string, tenantID string) ([]byte, error) { + match, err := regexp.MatchString("^[0-9a-zA-Z-.:/]+$", resource) + if err != nil { + return nil, err + } + if !match { + return nil, fmt.Errorf(`%s: unexpected scope "%s". Only alphanumeric characters and ".", ";", "-", and "/" are allowed`, credNameAzureCLI, resource) + } + + ctx, cancel := context.WithTimeout(ctx, timeoutCLIRequest) + defer cancel() + + commandLine := "az account get-access-token -o json --resource " + resource + if tenantID != "" { + commandLine += " --tenant " + tenantID + } + var cliCmd *exec.Cmd + if runtime.GOOS == "windows" { + dir := os.Getenv("SYSTEMROOT") + if dir == "" { + return nil, newCredentialUnavailableError(credNameAzureCLI, "environment variable 'SYSTEMROOT' has no value") + } + cliCmd = exec.CommandContext(ctx, "cmd.exe", "/c", commandLine) + cliCmd.Dir = dir + } else { + cliCmd = exec.CommandContext(ctx, "/bin/sh", "-c", commandLine) + cliCmd.Dir = "/bin" + } + cliCmd.Env = os.Environ() + var stderr bytes.Buffer + cliCmd.Stderr = &stderr + + output, err := cliCmd.Output() + if err != nil { + msg := stderr.String() + var exErr *exec.ExitError + if errors.As(err, &exErr) && exErr.ExitCode() == 127 || strings.HasPrefix(msg, "'az' is not recognized") { + msg = "Azure CLI not found on path" + } + if msg == "" { + msg = err.Error() + } + return nil, newCredentialUnavailableError(credNameAzureCLI, msg) + } + + return output, nil + } +} + +func (c *AzureCLICredential) createAccessToken(tk []byte) (azcore.AccessToken, error) { + t := struct { + AccessToken string `json:"accessToken"` + Authority string `json:"_authority"` + ClientID string `json:"_clientId"` + ExpiresOn string `json:"expiresOn"` + IdentityProvider string `json:"identityProvider"` + IsMRRT bool `json:"isMRRT"` + RefreshToken string `json:"refreshToken"` + Resource string `json:"resource"` + TokenType string `json:"tokenType"` + UserID string `json:"userId"` + }{} + err := json.Unmarshal(tk, &t) + if err != nil { + return azcore.AccessToken{}, err + } + + tokenExpirationDate, err := parseExpirationDate(t.ExpiresOn) + if err != nil { + return azcore.AccessToken{}, fmt.Errorf("Error parsing Token Expiration Date %q: %+v", t.ExpiresOn, err) + } + + converted := azcore.AccessToken{ + Token: t.AccessToken, + ExpiresOn: *tokenExpirationDate, + } + return converted, nil +} + +// parseExpirationDate parses either a Azure CLI or CloudShell date into a time object +func parseExpirationDate(input string) (*time.Time, error) { + // CloudShell (and potentially the Azure CLI in future) + expirationDate, cloudShellErr := time.Parse(time.RFC3339, input) + if cloudShellErr != nil { + // Azure CLI (Python) e.g. 2017-08-31 19:48:57.998857 (plus the local timezone) + const cliFormat = "2006-01-02 15:04:05.999999" + expirationDate, cliErr := time.ParseInLocation(cliFormat, input, time.Local) + if cliErr != nil { + return nil, fmt.Errorf("Error parsing expiration date %q.\n\nCloudShell Error: \n%+v\n\nCLI Error:\n%+v", input, cloudShellErr, cliErr) + } + return &expirationDate, nil + } + return &expirationDate, nil +} + +var _ azcore.TokenCredential = (*AzureCLICredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/chained_token_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/chained_token_credential.go new file mode 100644 index 00000000000..86a89064569 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/chained_token_credential.go @@ -0,0 +1,133 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "context" + "errors" + "fmt" + "strings" + "sync" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/internal/log" +) + +// ChainedTokenCredentialOptions contains optional parameters for ChainedTokenCredential. +type ChainedTokenCredentialOptions struct { + // RetrySources configures how the credential uses its sources. When true, the credential always attempts to + // authenticate through each source in turn, stopping when one succeeds. When false, the credential authenticates + // only through this first successful source--it never again tries the sources which failed. + RetrySources bool +} + +// ChainedTokenCredential links together multiple credentials and tries them sequentially when authenticating. By default, +// it tries all the credentials until one authenticates, after which it always uses that credential. +type ChainedTokenCredential struct { + cond *sync.Cond + iterating bool + name string + retrySources bool + sources []azcore.TokenCredential + successfulCredential azcore.TokenCredential +} + +// NewChainedTokenCredential creates a ChainedTokenCredential. Pass nil for options to accept defaults. +func NewChainedTokenCredential(sources []azcore.TokenCredential, options *ChainedTokenCredentialOptions) (*ChainedTokenCredential, error) { + if len(sources) == 0 { + return nil, errors.New("sources must contain at least one TokenCredential") + } + for _, source := range sources { + if source == nil { // cannot have a nil credential in the chain or else the application will panic when GetToken() is called on nil + return nil, errors.New("sources cannot contain nil") + } + } + cp := make([]azcore.TokenCredential, len(sources)) + copy(cp, sources) + if options == nil { + options = &ChainedTokenCredentialOptions{} + } + return &ChainedTokenCredential{ + cond: sync.NewCond(&sync.Mutex{}), + name: "ChainedTokenCredential", + retrySources: options.RetrySources, + sources: cp, + }, nil +} + +// GetToken calls GetToken on the chained credentials in turn, stopping when one returns a token. +// This method is called automatically by Azure SDK clients. +func (c *ChainedTokenCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + if !c.retrySources { + // ensure only one goroutine at a time iterates the sources and perhaps sets c.successfulCredential + c.cond.L.Lock() + for { + if c.successfulCredential != nil { + c.cond.L.Unlock() + return c.successfulCredential.GetToken(ctx, opts) + } + if !c.iterating { + c.iterating = true + // allow other goroutines to wait while this one iterates + c.cond.L.Unlock() + break + } + c.cond.Wait() + } + } + + var err error + var errs []error + var token azcore.AccessToken + var successfulCredential azcore.TokenCredential + for _, cred := range c.sources { + token, err = cred.GetToken(ctx, opts) + if err == nil { + log.Writef(EventAuthentication, "%s authenticated with %s", c.name, extractCredentialName(cred)) + successfulCredential = cred + break + } + errs = append(errs, err) + if _, ok := err.(*credentialUnavailableError); !ok { + break + } + } + if c.iterating { + c.cond.L.Lock() + c.successfulCredential = successfulCredential + c.iterating = false + c.cond.L.Unlock() + c.cond.Broadcast() + } + // err is the error returned by the last GetToken call. It will be nil when that call succeeds + if err != nil { + // return credentialUnavailableError iff all sources did so; return AuthenticationFailedError otherwise + msg := createChainedErrorMessage(errs) + if _, ok := err.(*credentialUnavailableError); ok { + err = newCredentialUnavailableError(c.name, msg) + } else { + res := getResponseFromError(err) + err = newAuthenticationFailedError(c.name, msg, res) + } + } + return token, err +} + +func createChainedErrorMessage(errs []error) string { + msg := "failed to acquire a token.\nAttempted credentials:" + for _, err := range errs { + msg += fmt.Sprintf("\n\t%s", err.Error()) + } + return msg +} + +func extractCredentialName(credential azcore.TokenCredential) string { + return strings.TrimPrefix(fmt.Sprintf("%T", credential), "*azidentity.") +} + +var _ azcore.TokenCredential = (*ChainedTokenCredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/ci.yml b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/ci.yml new file mode 100644 index 00000000000..3b443e8eedb --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/ci.yml @@ -0,0 +1,47 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. +trigger: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/azidentity/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/azidentity/ + +stages: +- template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + RunLiveTests: true + ServiceDirectory: 'azidentity' + PreSteps: + - pwsh: | + [System.Convert]::FromBase64String($env:PFX_CONTENTS) | Set-Content -Path $(Agent.TempDirectory)/test.pfx -AsByteStream + Set-Content -Path $(Agent.TempDirectory)/test.pem -Value $env:PEM_CONTENTS + [System.Convert]::FromBase64String($env:SNI_CONTENTS) | Set-Content -Path $(Agent.TempDirectory)/testsni.pfx -AsByteStream + env: + PFX_CONTENTS: $(net-identity-spcert-pfx) + PEM_CONTENTS: $(net-identity-spcert-pem) + SNI_CONTENTS: $(net-identity-spcert-sni) + EnvVars: + AZURE_IDENTITY_TEST_TENANTID: $(net-identity-tenantid) + AZURE_IDENTITY_TEST_USERNAME: $(net-identity-username) + AZURE_IDENTITY_TEST_PASSWORD: $(net-identity-password) + IDENTITY_SP_TENANT_ID: $(net-identity-sp-tenantid) + IDENTITY_SP_CLIENT_ID: $(net-identity-sp-clientid) + IDENTITY_SP_CLIENT_SECRET: $(net-identity-sp-clientsecret) + IDENTITY_SP_CERT_PEM: $(Agent.TempDirectory)/test.pem + IDENTITY_SP_CERT_PFX: $(Agent.TempDirectory)/test.pfx + IDENTITY_SP_CERT_SNI: $(Agent.TempDirectory)/testsni.pfx diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_assertion_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_assertion_credential.go new file mode 100644 index 00000000000..ffcf2094be2 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_assertion_credential.go @@ -0,0 +1,74 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "context" + "errors" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential" +) + +const credNameAssertion = "ClientAssertionCredential" + +// ClientAssertionCredential authenticates an application with assertions provided by a callback function. +// This credential is for advanced scenarios. ClientCertificateCredential has a more convenient API for +// the most common assertion scenario, authenticating a service principal with a certificate. See +// [Azure AD documentation] for details of the assertion format. +// +// [Azure AD documentation]: https://docs.microsoft.com/azure/active-directory/develop/active-directory-certificate-credentials#assertion-format +type ClientAssertionCredential struct { + client confidentialClient +} + +// ClientAssertionCredentialOptions contains optional parameters for ClientAssertionCredential. +type ClientAssertionCredentialOptions struct { + azcore.ClientOptions +} + +// NewClientAssertionCredential constructs a ClientAssertionCredential. The getAssertion function must be thread safe. Pass nil for options to accept defaults. +func NewClientAssertionCredential(tenantID, clientID string, getAssertion func(context.Context) (string, error), options *ClientAssertionCredentialOptions) (*ClientAssertionCredential, error) { + if getAssertion == nil { + return nil, errors.New("getAssertion must be a function that returns assertions") + } + if options == nil { + options = &ClientAssertionCredentialOptions{} + } + cred := confidential.NewCredFromAssertionCallback( + func(ctx context.Context, _ confidential.AssertionRequestOptions) (string, error) { + return getAssertion(ctx) + }, + ) + c, err := getConfidentialClient(clientID, tenantID, cred, &options.ClientOptions) + if err != nil { + return nil, err + } + return &ClientAssertionCredential{client: c}, nil +} + +// GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients. +func (c *ClientAssertionCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + if len(opts.Scopes) == 0 { + return azcore.AccessToken{}, errors.New(credNameAssertion + ": GetToken() requires at least one scope") + } + ar, err := c.client.AcquireTokenSilent(ctx, opts.Scopes) + if err == nil { + logGetTokenSuccess(c, opts) + return azcore.AccessToken{Token: ar.AccessToken, ExpiresOn: ar.ExpiresOn.UTC()}, err + } + + ar, err = c.client.AcquireTokenByCredential(ctx, opts.Scopes) + if err != nil { + return azcore.AccessToken{}, newAuthenticationFailedErrorFromMSALError(credNameAssertion, err) + } + logGetTokenSuccess(c, opts) + return azcore.AccessToken{Token: ar.AccessToken, ExpiresOn: ar.ExpiresOn.UTC()}, err +} + +var _ azcore.TokenCredential = (*ClientAssertionCredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_certificate_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_certificate_credential.go new file mode 100644 index 00000000000..a61d824ef59 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_certificate_credential.go @@ -0,0 +1,163 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "context" + "crypto" + "crypto/x509" + "encoding/pem" + "errors" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential" + "golang.org/x/crypto/pkcs12" +) + +const credNameCert = "ClientCertificateCredential" + +// ClientCertificateCredentialOptions contains optional parameters for ClientCertificateCredential. +type ClientCertificateCredentialOptions struct { + azcore.ClientOptions + + // SendCertificateChain controls whether the credential sends the public certificate chain in the x5c + // header of each token request's JWT. This is required for Subject Name/Issuer (SNI) authentication. + // Defaults to False. + SendCertificateChain bool +} + +// ClientCertificateCredential authenticates a service principal with a certificate. +type ClientCertificateCredential struct { + client confidentialClient +} + +// NewClientCertificateCredential constructs a ClientCertificateCredential. Pass nil for options to accept defaults. +func NewClientCertificateCredential(tenantID string, clientID string, certs []*x509.Certificate, key crypto.PrivateKey, options *ClientCertificateCredentialOptions) (*ClientCertificateCredential, error) { + if len(certs) == 0 { + return nil, errors.New("at least one certificate is required") + } + if options == nil { + options = &ClientCertificateCredentialOptions{} + } + cred, err := confidential.NewCredFromCertChain(certs, key) + if err != nil { + return nil, err + } + var o []confidential.Option + if options.SendCertificateChain { + o = append(o, confidential.WithX5C()) + } + c, err := getConfidentialClient(clientID, tenantID, cred, &options.ClientOptions, o...) + if err != nil { + return nil, err + } + return &ClientCertificateCredential{client: c}, nil +} + +// GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients. +func (c *ClientCertificateCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + if len(opts.Scopes) == 0 { + return azcore.AccessToken{}, errors.New(credNameCert + ": GetToken() requires at least one scope") + } + ar, err := c.client.AcquireTokenSilent(ctx, opts.Scopes) + if err == nil { + logGetTokenSuccess(c, opts) + return azcore.AccessToken{Token: ar.AccessToken, ExpiresOn: ar.ExpiresOn.UTC()}, err + } + + ar, err = c.client.AcquireTokenByCredential(ctx, opts.Scopes) + if err != nil { + return azcore.AccessToken{}, newAuthenticationFailedErrorFromMSALError(credNameCert, err) + } + logGetTokenSuccess(c, opts) + return azcore.AccessToken{Token: ar.AccessToken, ExpiresOn: ar.ExpiresOn.UTC()}, err +} + +// ParseCertificates loads certificates and a private key, in PEM or PKCS12 format, for use with NewClientCertificateCredential. +// Pass nil for password if the private key isn't encrypted. This function can't decrypt keys in PEM format. +func ParseCertificates(certData []byte, password []byte) ([]*x509.Certificate, crypto.PrivateKey, error) { + var blocks []*pem.Block + var err error + if len(password) == 0 { + blocks, err = loadPEMCert(certData) + } + if len(blocks) == 0 || err != nil { + blocks, err = loadPKCS12Cert(certData, string(password)) + } + if err != nil { + return nil, nil, err + } + var certs []*x509.Certificate + var pk crypto.PrivateKey + for _, block := range blocks { + switch block.Type { + case "CERTIFICATE": + c, err := x509.ParseCertificate(block.Bytes) + if err != nil { + return nil, nil, err + } + certs = append(certs, c) + case "PRIVATE KEY": + if pk != nil { + return nil, nil, errors.New("certData contains multiple private keys") + } + pk, err = x509.ParsePKCS8PrivateKey(block.Bytes) + if err != nil { + pk, err = x509.ParsePKCS1PrivateKey(block.Bytes) + } + if err != nil { + return nil, nil, err + } + case "RSA PRIVATE KEY": + if pk != nil { + return nil, nil, errors.New("certData contains multiple private keys") + } + pk, err = x509.ParsePKCS1PrivateKey(block.Bytes) + if err != nil { + return nil, nil, err + } + } + } + if len(certs) == 0 { + return nil, nil, errors.New("found no certificate") + } + if pk == nil { + return nil, nil, errors.New("found no private key") + } + return certs, pk, nil +} + +func loadPEMCert(certData []byte) ([]*pem.Block, error) { + blocks := []*pem.Block{} + for { + var block *pem.Block + block, certData = pem.Decode(certData) + if block == nil { + break + } + blocks = append(blocks, block) + } + if len(blocks) == 0 { + return nil, errors.New("didn't find any PEM blocks") + } + return blocks, nil +} + +func loadPKCS12Cert(certData []byte, password string) ([]*pem.Block, error) { + blocks, err := pkcs12.ToPEM(certData, password) + if err != nil { + return nil, err + } + if len(blocks) == 0 { + // not mentioning PKCS12 in this message because we end up here when certData is garbage + return nil, errors.New("didn't find any certificate content") + } + return blocks, err +} + +var _ azcore.TokenCredential = (*ClientCertificateCredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_secret_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_secret_credential.go new file mode 100644 index 00000000000..1c3a516601b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/client_secret_credential.go @@ -0,0 +1,65 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "context" + "errors" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential" +) + +const credNameSecret = "ClientSecretCredential" + +// ClientSecretCredentialOptions contains optional parameters for ClientSecretCredential. +type ClientSecretCredentialOptions struct { + azcore.ClientOptions +} + +// ClientSecretCredential authenticates an application with a client secret. +type ClientSecretCredential struct { + client confidentialClient +} + +// NewClientSecretCredential constructs a ClientSecretCredential. Pass nil for options to accept defaults. +func NewClientSecretCredential(tenantID string, clientID string, clientSecret string, options *ClientSecretCredentialOptions) (*ClientSecretCredential, error) { + if options == nil { + options = &ClientSecretCredentialOptions{} + } + cred, err := confidential.NewCredFromSecret(clientSecret) + if err != nil { + return nil, err + } + c, err := getConfidentialClient(clientID, tenantID, cred, &options.ClientOptions) + if err != nil { + return nil, err + } + return &ClientSecretCredential{client: c}, nil +} + +// GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients. +func (c *ClientSecretCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + if len(opts.Scopes) == 0 { + return azcore.AccessToken{}, errors.New(credNameSecret + ": GetToken() requires at least one scope") + } + ar, err := c.client.AcquireTokenSilent(ctx, opts.Scopes) + if err == nil { + logGetTokenSuccess(c, opts) + return azcore.AccessToken{Token: ar.AccessToken, ExpiresOn: ar.ExpiresOn.UTC()}, err + } + + ar, err = c.client.AcquireTokenByCredential(ctx, opts.Scopes) + if err != nil { + return azcore.AccessToken{}, newAuthenticationFailedErrorFromMSALError(credNameSecret, err) + } + logGetTokenSuccess(c, opts) + return azcore.AccessToken{Token: ar.AccessToken, ExpiresOn: ar.ExpiresOn.UTC()}, err +} + +var _ azcore.TokenCredential = (*ClientSecretCredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/default_azure_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/default_azure_credential.go new file mode 100644 index 00000000000..c2b801c4a6d --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/default_azure_credential.go @@ -0,0 +1,134 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "context" + "errors" + "os" + "strings" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/internal/log" +) + +// DefaultAzureCredentialOptions contains optional parameters for DefaultAzureCredential. +// These options may not apply to all credentials in the chain. +type DefaultAzureCredentialOptions struct { + azcore.ClientOptions + + // TenantID identifies the tenant the Azure CLI should authenticate in. + // Defaults to the CLI's default tenant, which is typically the home tenant of the user logged in to the CLI. + TenantID string +} + +// DefaultAzureCredential is a default credential chain for applications that will deploy to Azure. +// It combines credentials suitable for deployment with credentials suitable for local development. +// It attempts to authenticate with each of these credential types, in the following order, stopping when one provides a token: +// +// EnvironmentCredential +// ManagedIdentityCredential +// AzureCLICredential +// +// Consult the documentation for these credential types for more information on how they authenticate. +// Once a credential has successfully authenticated, DefaultAzureCredential will use that credential for +// every subsequent authentication. +type DefaultAzureCredential struct { + chain *ChainedTokenCredential +} + +// NewDefaultAzureCredential creates a DefaultAzureCredential. Pass nil for options to accept defaults. +func NewDefaultAzureCredential(options *DefaultAzureCredentialOptions) (*DefaultAzureCredential, error) { + var creds []azcore.TokenCredential + var errorMessages []string + + if options == nil { + options = &DefaultAzureCredentialOptions{} + } + + envCred, err := NewEnvironmentCredential(&EnvironmentCredentialOptions{ClientOptions: options.ClientOptions}) + if err == nil { + creds = append(creds, envCred) + } else { + errorMessages = append(errorMessages, "EnvironmentCredential: "+err.Error()) + creds = append(creds, &defaultCredentialErrorReporter{credType: "EnvironmentCredential", err: err}) + } + + o := &ManagedIdentityCredentialOptions{ClientOptions: options.ClientOptions} + if ID, ok := os.LookupEnv(azureClientID); ok { + o.ID = ClientID(ID) + } + msiCred, err := NewManagedIdentityCredential(o) + if err == nil { + creds = append(creds, msiCred) + msiCred.mic.imdsTimeout = time.Second + } else { + errorMessages = append(errorMessages, credNameManagedIdentity+": "+err.Error()) + creds = append(creds, &defaultCredentialErrorReporter{credType: credNameManagedIdentity, err: err}) + } + + cliCred, err := NewAzureCLICredential(&AzureCLICredentialOptions{TenantID: options.TenantID}) + if err == nil { + creds = append(creds, cliCred) + } else { + errorMessages = append(errorMessages, credNameAzureCLI+": "+err.Error()) + creds = append(creds, &defaultCredentialErrorReporter{credType: credNameAzureCLI, err: err}) + } + + err = defaultAzureCredentialConstructorErrorHandler(len(creds), errorMessages) + if err != nil { + return nil, err + } + + chain, err := NewChainedTokenCredential(creds, nil) + if err != nil { + return nil, err + } + chain.name = "DefaultAzureCredential" + return &DefaultAzureCredential{chain: chain}, nil +} + +// GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients. +func (c *DefaultAzureCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + return c.chain.GetToken(ctx, opts) +} + +var _ azcore.TokenCredential = (*DefaultAzureCredential)(nil) + +func defaultAzureCredentialConstructorErrorHandler(numberOfSuccessfulCredentials int, errorMessages []string) (err error) { + errorMessage := strings.Join(errorMessages, "\n\t") + + if numberOfSuccessfulCredentials == 0 { + return errors.New(errorMessage) + } + + if len(errorMessages) != 0 { + log.Writef(EventAuthentication, "NewDefaultAzureCredential failed to initialize some credentials:\n\t%s", errorMessage) + } + + return nil +} + +// defaultCredentialErrorReporter is a substitute for credentials that couldn't be constructed. +// Its GetToken method always returns a credentialUnavailableError having the same message as +// the error that prevented constructing the credential. This ensures the message is present +// in the error returned by ChainedTokenCredential.GetToken() +type defaultCredentialErrorReporter struct { + credType string + err error +} + +func (d *defaultCredentialErrorReporter) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + if _, ok := d.err.(*credentialUnavailableError); ok { + return azcore.AccessToken{}, d.err + } + return azcore.AccessToken{}, newCredentialUnavailableError(d.credType, d.err.Error()) +} + +var _ azcore.TokenCredential = (*defaultCredentialErrorReporter)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/device_code_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/device_code_credential.go new file mode 100644 index 00000000000..2e9b5438dbd --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/device_code_credential.go @@ -0,0 +1,119 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "context" + "errors" + "fmt" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/public" +) + +const credNameDeviceCode = "DeviceCodeCredential" + +// DeviceCodeCredentialOptions contains optional parameters for DeviceCodeCredential. +type DeviceCodeCredentialOptions struct { + azcore.ClientOptions + + // TenantID is the Azure Active Directory tenant the credential authenticates in. Defaults to the + // "organizations" tenant, which can authenticate work and school accounts. Required for single-tenant + // applications. + TenantID string + // ClientID is the ID of the application users will authenticate to. + // Defaults to the ID of an Azure development application. + ClientID string + // UserPrompt controls how the credential presents authentication instructions. The credential calls + // this function with authentication details when it receives a device code. By default, the credential + // prints these details to stdout. + UserPrompt func(context.Context, DeviceCodeMessage) error +} + +func (o *DeviceCodeCredentialOptions) init() { + if o.TenantID == "" { + o.TenantID = organizationsTenantID + } + if o.ClientID == "" { + o.ClientID = developerSignOnClientID + } + if o.UserPrompt == nil { + o.UserPrompt = func(ctx context.Context, dc DeviceCodeMessage) error { + fmt.Println(dc.Message) + return nil + } + } +} + +// DeviceCodeMessage contains the information a user needs to complete authentication. +type DeviceCodeMessage struct { + // UserCode is the user code returned by the service. + UserCode string `json:"user_code"` + // VerificationURL is the URL at which the user must authenticate. + VerificationURL string `json:"verification_uri"` + // Message is user instruction from Azure Active Directory. + Message string `json:"message"` +} + +// DeviceCodeCredential acquires tokens for a user via the device code flow, which has the +// user browse to an Azure Active Directory URL, enter a code, and authenticate. It's useful +// for authenticating a user in an environment without a web browser, such as an SSH session. +// If a web browser is available, InteractiveBrowserCredential is more convenient because it +// automatically opens a browser to the login page. +type DeviceCodeCredential struct { + client publicClient + userPrompt func(context.Context, DeviceCodeMessage) error + account public.Account +} + +// NewDeviceCodeCredential creates a DeviceCodeCredential. Pass nil to accept default options. +func NewDeviceCodeCredential(options *DeviceCodeCredentialOptions) (*DeviceCodeCredential, error) { + cp := DeviceCodeCredentialOptions{} + if options != nil { + cp = *options + } + cp.init() + c, err := getPublicClient(cp.ClientID, cp.TenantID, &cp.ClientOptions) + if err != nil { + return nil, err + } + return &DeviceCodeCredential{userPrompt: cp.UserPrompt, client: c}, nil +} + +// GetToken requests an access token from Azure Active Directory. It will begin the device code flow and poll until the user completes authentication. +// This method is called automatically by Azure SDK clients. +func (c *DeviceCodeCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + if len(opts.Scopes) == 0 { + return azcore.AccessToken{}, errors.New(credNameDeviceCode + ": GetToken() requires at least one scope") + } + ar, err := c.client.AcquireTokenSilent(ctx, opts.Scopes, public.WithSilentAccount(c.account)) + if err == nil { + return azcore.AccessToken{Token: ar.AccessToken, ExpiresOn: ar.ExpiresOn.UTC()}, err + } + dc, err := c.client.AcquireTokenByDeviceCode(ctx, opts.Scopes) + if err != nil { + return azcore.AccessToken{}, newAuthenticationFailedErrorFromMSALError(credNameDeviceCode, err) + } + err = c.userPrompt(ctx, DeviceCodeMessage{ + UserCode: dc.Result.UserCode, + VerificationURL: dc.Result.VerificationURL, + Message: dc.Result.Message, + }) + if err != nil { + return azcore.AccessToken{}, err + } + ar, err = dc.AuthenticationResult(ctx) + if err != nil { + return azcore.AccessToken{}, newAuthenticationFailedErrorFromMSALError(credNameDeviceCode, err) + } + c.account = ar.Account + logGetTokenSuccess(c, opts) + return azcore.AccessToken{Token: ar.AccessToken, ExpiresOn: ar.ExpiresOn.UTC()}, err +} + +var _ azcore.TokenCredential = (*DeviceCodeCredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/environment_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/environment_credential.go new file mode 100644 index 00000000000..b1871b4d4d7 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/environment_credential.go @@ -0,0 +1,128 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "context" + "errors" + "fmt" + "os" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/internal/log" +) + +const envVarSendCertChain = "AZURE_CLIENT_SEND_CERTIFICATE_CHAIN" + +// EnvironmentCredentialOptions contains optional parameters for EnvironmentCredential +type EnvironmentCredentialOptions struct { + azcore.ClientOptions +} + +// EnvironmentCredential authenticates a service principal with a secret or certificate, or a user with a password, depending +// on environment variable configuration. It reads configuration from these variables, in the following order: +// +// # Service principal with client secret +// +// AZURE_TENANT_ID: ID of the service principal's tenant. Also called its "directory" ID. +// +// AZURE_CLIENT_ID: the service principal's client ID +// +// AZURE_CLIENT_SECRET: one of the service principal's client secrets +// +// # Service principal with certificate +// +// AZURE_TENANT_ID: ID of the service principal's tenant. Also called its "directory" ID. +// +// AZURE_CLIENT_ID: the service principal's client ID +// +// AZURE_CLIENT_CERTIFICATE_PATH: path to a PEM or PKCS12 certificate file including the private key. +// +// AZURE_CLIENT_CERTIFICATE_PASSWORD: (optional) password for the certificate file. +// +// # User with username and password +// +// AZURE_TENANT_ID: (optional) tenant to authenticate in. Defaults to "organizations". +// +// AZURE_CLIENT_ID: client ID of the application the user will authenticate to +// +// AZURE_USERNAME: a username (usually an email address) +// +// AZURE_PASSWORD: the user's password +type EnvironmentCredential struct { + cred azcore.TokenCredential +} + +// NewEnvironmentCredential creates an EnvironmentCredential. Pass nil to accept default options. +func NewEnvironmentCredential(options *EnvironmentCredentialOptions) (*EnvironmentCredential, error) { + if options == nil { + options = &EnvironmentCredentialOptions{} + } + tenantID := os.Getenv(azureTenantID) + if tenantID == "" { + return nil, errors.New("missing environment variable AZURE_TENANT_ID") + } + clientID := os.Getenv(azureClientID) + if clientID == "" { + return nil, errors.New("missing environment variable " + azureClientID) + } + if clientSecret := os.Getenv(azureClientSecret); clientSecret != "" { + log.Write(EventAuthentication, "EnvironmentCredential will authenticate with ClientSecretCredential") + o := &ClientSecretCredentialOptions{ClientOptions: options.ClientOptions} + cred, err := NewClientSecretCredential(tenantID, clientID, clientSecret, o) + if err != nil { + return nil, err + } + return &EnvironmentCredential{cred: cred}, nil + } + if certPath := os.Getenv(azureClientCertificatePath); certPath != "" { + log.Write(EventAuthentication, "EnvironmentCredential will authenticate with ClientCertificateCredential") + certData, err := os.ReadFile(certPath) + if err != nil { + return nil, fmt.Errorf(`failed to read certificate file "%s": %v`, certPath, err) + } + var password []byte + if v := os.Getenv(azureClientCertificatePassword); v != "" { + password = []byte(v) + } + certs, key, err := ParseCertificates(certData, password) + if err != nil { + return nil, fmt.Errorf(`failed to load certificate from "%s": %v`, certPath, err) + } + o := &ClientCertificateCredentialOptions{ClientOptions: options.ClientOptions} + if v, ok := os.LookupEnv(envVarSendCertChain); ok { + o.SendCertificateChain = v == "1" || strings.ToLower(v) == "true" + } + cred, err := NewClientCertificateCredential(tenantID, clientID, certs, key, o) + if err != nil { + return nil, err + } + return &EnvironmentCredential{cred: cred}, nil + } + if username := os.Getenv(azureUsername); username != "" { + if password := os.Getenv(azurePassword); password != "" { + log.Write(EventAuthentication, "EnvironmentCredential will authenticate with UsernamePasswordCredential") + o := &UsernamePasswordCredentialOptions{ClientOptions: options.ClientOptions} + cred, err := NewUsernamePasswordCredential(tenantID, clientID, username, password, o) + if err != nil { + return nil, err + } + return &EnvironmentCredential{cred: cred}, nil + } + return nil, errors.New("no value for AZURE_PASSWORD") + } + return nil, errors.New("incomplete environment variable configuration. Only AZURE_TENANT_ID and AZURE_CLIENT_ID are set") +} + +// GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients. +func (c *EnvironmentCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + return c.cred.GetToken(ctx, opts) +} + +var _ azcore.TokenCredential = (*EnvironmentCredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/errors.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/errors.go new file mode 100644 index 00000000000..6695f1b70e4 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/errors.go @@ -0,0 +1,124 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo" + msal "github.com/AzureAD/microsoft-authentication-library-for-go/apps/errors" +) + +// getResponseFromError retrieves the response carried by +// an AuthenticationFailedError or MSAL CallErr, if any +func getResponseFromError(err error) *http.Response { + var a *AuthenticationFailedError + var c msal.CallErr + var res *http.Response + if errors.As(err, &c) { + res = c.Resp + } else if errors.As(err, &a) { + res = a.RawResponse + } + return res +} + +// AuthenticationFailedError indicates an authentication request has failed. +type AuthenticationFailedError struct { + // RawResponse is the HTTP response motivating the error, if available. + RawResponse *http.Response + + credType string + message string +} + +func newAuthenticationFailedError(credType string, message string, resp *http.Response) error { + return &AuthenticationFailedError{credType: credType, message: message, RawResponse: resp} +} + +func newAuthenticationFailedErrorFromMSALError(credType string, err error) error { + res := getResponseFromError(err) + return newAuthenticationFailedError(credType, err.Error(), res) +} + +// Error implements the error interface. Note that the message contents are not contractual and can change over time. +func (e *AuthenticationFailedError) Error() string { + if e.RawResponse == nil { + return e.credType + ": " + e.message + } + msg := &bytes.Buffer{} + fmt.Fprintf(msg, e.credType+" authentication failed\n") + fmt.Fprintf(msg, "%s %s://%s%s\n", e.RawResponse.Request.Method, e.RawResponse.Request.URL.Scheme, e.RawResponse.Request.URL.Host, e.RawResponse.Request.URL.Path) + fmt.Fprintln(msg, "--------------------------------------------------------------------------------") + fmt.Fprintf(msg, "RESPONSE %s\n", e.RawResponse.Status) + fmt.Fprintln(msg, "--------------------------------------------------------------------------------") + body, err := io.ReadAll(e.RawResponse.Body) + e.RawResponse.Body.Close() + if err != nil { + fmt.Fprintf(msg, "Error reading response body: %v", err) + } else if len(body) > 0 { + e.RawResponse.Body = io.NopCloser(bytes.NewReader(body)) + if err := json.Indent(msg, body, "", " "); err != nil { + // failed to pretty-print so just dump it verbatim + fmt.Fprint(msg, string(body)) + } + } else { + fmt.Fprint(msg, "Response contained no body") + } + fmt.Fprintln(msg, "\n--------------------------------------------------------------------------------") + var anchor string + switch e.credType { + case credNameAzureCLI: + anchor = "azure-cli" + case credNameCert: + anchor = "client-cert" + case credNameSecret: + anchor = "client-secret" + case credNameManagedIdentity: + anchor = "managed-id" + case credNameUserPassword: + anchor = "username-password" + } + if anchor != "" { + fmt.Fprintf(msg, "To troubleshoot, visit https://aka.ms/azsdk/go/identity/troubleshoot#%s", anchor) + } + return msg.String() +} + +// NonRetriable indicates the request which provoked this error shouldn't be retried. +func (*AuthenticationFailedError) NonRetriable() { + // marker method +} + +var _ errorinfo.NonRetriable = (*AuthenticationFailedError)(nil) + +// credentialUnavailableError indicates a credential can't attempt +// authentication because it lacks required data or state. +type credentialUnavailableError struct { + credType string + message string +} + +func newCredentialUnavailableError(credType, message string) error { + return &credentialUnavailableError{credType: credType, message: message} +} + +func (e *credentialUnavailableError) Error() string { + return e.credType + ": " + e.message +} + +// NonRetriable indicates that this error should not be retried. +func (e *credentialUnavailableError) NonRetriable() { + // marker method +} + +var _ errorinfo.NonRetriable = (*credentialUnavailableError)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/interactive_browser_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/interactive_browser_credential.go new file mode 100644 index 00000000000..4d2afe4f5c5 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/interactive_browser_credential.go @@ -0,0 +1,85 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "context" + "errors" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/public" +) + +const credNameBrowser = "InteractiveBrowserCredentiall" + +// InteractiveBrowserCredentialOptions contains optional parameters for InteractiveBrowserCredential. +type InteractiveBrowserCredentialOptions struct { + azcore.ClientOptions + + // TenantID is the Azure Active Directory tenant the credential authenticates in. Defaults to the + // "organizations" tenant, which can authenticate work and school accounts. + TenantID string + // ClientID is the ID of the application users will authenticate to. + // Defaults to the ID of an Azure development application. + ClientID string + // RedirectURL will be supported in a future version but presently doesn't work: https://github.com/Azure/azure-sdk-for-go/issues/15632. + // Applications which have "http://localhost" registered as a redirect URL need not set this option. + RedirectURL string +} + +func (o *InteractiveBrowserCredentialOptions) init() { + if o.TenantID == "" { + o.TenantID = organizationsTenantID + } + if o.ClientID == "" { + o.ClientID = developerSignOnClientID + } +} + +// InteractiveBrowserCredential opens a browser to interactively authenticate a user. +type InteractiveBrowserCredential struct { + client publicClient + options InteractiveBrowserCredentialOptions + account public.Account +} + +// NewInteractiveBrowserCredential constructs a new InteractiveBrowserCredential. Pass nil to accept default options. +func NewInteractiveBrowserCredential(options *InteractiveBrowserCredentialOptions) (*InteractiveBrowserCredential, error) { + cp := InteractiveBrowserCredentialOptions{} + if options != nil { + cp = *options + } + cp.init() + c, err := getPublicClient(cp.ClientID, cp.TenantID, &cp.ClientOptions) + if err != nil { + return nil, err + } + return &InteractiveBrowserCredential{options: cp, client: c}, nil +} + +// GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients. +func (c *InteractiveBrowserCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + if len(opts.Scopes) == 0 { + return azcore.AccessToken{}, errors.New(credNameBrowser + ": GetToken() requires at least one scope") + } + ar, err := c.client.AcquireTokenSilent(ctx, opts.Scopes, public.WithSilentAccount(c.account)) + if err == nil { + logGetTokenSuccess(c, opts) + return azcore.AccessToken{Token: ar.AccessToken, ExpiresOn: ar.ExpiresOn.UTC()}, err + } + + ar, err = c.client.AcquireTokenInteractive(ctx, opts.Scopes, public.WithRedirectURI(c.options.RedirectURL)) + if err != nil { + return azcore.AccessToken{}, newAuthenticationFailedErrorFromMSALError(credNameBrowser, err) + } + c.account = ar.Account + logGetTokenSuccess(c, opts) + return azcore.AccessToken{Token: ar.AccessToken, ExpiresOn: ar.ExpiresOn.UTC()}, err +} + +var _ azcore.TokenCredential = (*InteractiveBrowserCredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/logging.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/logging.go new file mode 100644 index 00000000000..569453e4622 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/logging.go @@ -0,0 +1,30 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "fmt" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/internal/log" +) + +// EventAuthentication entries contain information about authentication. +// This includes information like the names of environment variables +// used when obtaining credentials and the type of credential used. +const EventAuthentication log.Event = "Authentication" + +func logGetTokenSuccess(cred azcore.TokenCredential, opts policy.TokenRequestOptions) { + if !log.Should(EventAuthentication) { + return + } + scope := strings.Join(opts.Scopes, ", ") + msg := fmt.Sprintf("%T.GetToken() acquired a token for scope %s\n", cred, scope) + log.Write(EventAuthentication, msg) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed_identity_client.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed_identity_client.go new file mode 100644 index 00000000000..c9b72663c27 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed_identity_client.go @@ -0,0 +1,401 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "os" + "strconv" + "strings" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming" + "github.com/Azure/azure-sdk-for-go/sdk/internal/log" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential" +) + +const ( + arcIMDSEndpoint = "IMDS_ENDPOINT" + identityEndpoint = "IDENTITY_ENDPOINT" + identityHeader = "IDENTITY_HEADER" + identityServerThumbprint = "IDENTITY_SERVER_THUMBPRINT" + headerMetadata = "Metadata" + imdsEndpoint = "http://169.254.169.254/metadata/identity/oauth2/token" + msiEndpoint = "MSI_ENDPOINT" + imdsAPIVersion = "2018-02-01" + azureArcAPIVersion = "2019-08-15" + serviceFabricAPIVersion = "2019-07-01-preview" + + qpClientID = "client_id" + qpResID = "mi_res_id" +) + +type msiType int + +const ( + msiTypeAppService msiType = iota + msiTypeAzureArc + msiTypeCloudShell + msiTypeIMDS + msiTypeServiceFabric +) + +// managedIdentityClient provides the base for authenticating in managed identity environments +// This type includes an runtime.Pipeline and TokenCredentialOptions. +type managedIdentityClient struct { + pipeline runtime.Pipeline + msiType msiType + endpoint string + id ManagedIDKind + imdsTimeout time.Duration +} + +type wrappedNumber json.Number + +func (n *wrappedNumber) UnmarshalJSON(b []byte) error { + c := string(b) + if c == "\"\"" { + return nil + } + return json.Unmarshal(b, (*json.Number)(n)) +} + +// setIMDSRetryOptionDefaults sets zero-valued fields to default values appropriate for IMDS +func setIMDSRetryOptionDefaults(o *policy.RetryOptions) { + if o.MaxRetries == 0 { + o.MaxRetries = 5 + } + if o.MaxRetryDelay == 0 { + o.MaxRetryDelay = 1 * time.Minute + } + if o.RetryDelay == 0 { + o.RetryDelay = 2 * time.Second + } + if o.StatusCodes == nil { + o.StatusCodes = []int{ + // IMDS docs recommend retrying 404, 429 and all 5xx + // https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/how-to-use-vm-token#error-handling + http.StatusNotFound, // 404 + http.StatusTooManyRequests, // 429 + http.StatusInternalServerError, // 500 + http.StatusNotImplemented, // 501 + http.StatusBadGateway, // 502 + http.StatusGatewayTimeout, // 504 + http.StatusHTTPVersionNotSupported, // 505 + http.StatusVariantAlsoNegotiates, // 506 + http.StatusInsufficientStorage, // 507 + http.StatusLoopDetected, // 508 + http.StatusNotExtended, // 510 + http.StatusNetworkAuthenticationRequired, // 511 + } + } + if o.TryTimeout == 0 { + o.TryTimeout = 1 * time.Minute + } +} + +// newManagedIdentityClient creates a new instance of the ManagedIdentityClient with the ManagedIdentityCredentialOptions +// that are passed into it along with a default pipeline. +// options: ManagedIdentityCredentialOptions configure policies for the pipeline and the authority host that +// will be used to retrieve tokens and authenticate +func newManagedIdentityClient(options *ManagedIdentityCredentialOptions) (*managedIdentityClient, error) { + if options == nil { + options = &ManagedIdentityCredentialOptions{} + } + cp := options.ClientOptions + c := managedIdentityClient{id: options.ID, endpoint: imdsEndpoint, msiType: msiTypeIMDS} + env := "IMDS" + if endpoint, ok := os.LookupEnv(identityEndpoint); ok { + if _, ok := os.LookupEnv(identityHeader); ok { + if _, ok := os.LookupEnv(identityServerThumbprint); ok { + env = "Service Fabric" + c.endpoint = endpoint + c.msiType = msiTypeServiceFabric + } else { + env = "App Service" + c.endpoint = endpoint + c.msiType = msiTypeAppService + } + } else if _, ok := os.LookupEnv(arcIMDSEndpoint); ok { + env = "Azure Arc" + c.endpoint = endpoint + c.msiType = msiTypeAzureArc + } + } else if endpoint, ok := os.LookupEnv(msiEndpoint); ok { + env = "Cloud Shell" + c.endpoint = endpoint + c.msiType = msiTypeCloudShell + } else { + setIMDSRetryOptionDefaults(&cp.Retry) + } + c.pipeline = runtime.NewPipeline(component, version, runtime.PipelineOptions{}, &cp) + + if log.Should(EventAuthentication) { + log.Writef(EventAuthentication, "Managed Identity Credential will use %s managed identity", env) + } + + return &c, nil +} + +// provideToken acquires a token for MSAL's confidential.Client, which caches the token +func (c *managedIdentityClient) provideToken(ctx context.Context, params confidential.TokenProviderParameters) (confidential.TokenProviderResult, error) { + result := confidential.TokenProviderResult{} + tk, err := c.authenticate(ctx, c.id, params.Scopes) + if err == nil { + result.AccessToken = tk.Token + result.ExpiresInSeconds = int(time.Until(tk.ExpiresOn).Seconds()) + } + return result, err +} + +// authenticate acquires an access token +func (c *managedIdentityClient) authenticate(ctx context.Context, id ManagedIDKind, scopes []string) (azcore.AccessToken, error) { + var cancel context.CancelFunc + if c.imdsTimeout > 0 && c.msiType == msiTypeIMDS { + ctx, cancel = context.WithTimeout(ctx, c.imdsTimeout) + defer cancel() + } + + msg, err := c.createAuthRequest(ctx, id, scopes) + if err != nil { + return azcore.AccessToken{}, err + } + + resp, err := c.pipeline.Do(msg) + if err != nil { + if cancel != nil && errors.Is(err, context.DeadlineExceeded) { + return azcore.AccessToken{}, newCredentialUnavailableError(credNameManagedIdentity, "IMDS token request timed out") + } + return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, err.Error(), nil) + } + + // got a response, remove the IMDS timeout so future requests use the transport's configuration + c.imdsTimeout = 0 + + if runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { + return c.createAccessToken(resp) + } + + if c.msiType == msiTypeIMDS && resp.StatusCode == 400 { + if id != nil { + return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, "the requested identity isn't assigned to this resource", resp) + } + return azcore.AccessToken{}, newCredentialUnavailableError(credNameManagedIdentity, "no default identity is assigned to this resource") + } + + return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, "authentication failed", resp) +} + +func (c *managedIdentityClient) createAccessToken(res *http.Response) (azcore.AccessToken, error) { + value := struct { + // these are the only fields that we use + Token string `json:"access_token,omitempty"` + RefreshToken string `json:"refresh_token,omitempty"` + ExpiresIn wrappedNumber `json:"expires_in,omitempty"` // this field should always return the number of seconds for which a token is valid + ExpiresOn interface{} `json:"expires_on,omitempty"` // the value returned in this field varies between a number and a date string + }{} + if err := runtime.UnmarshalAsJSON(res, &value); err != nil { + return azcore.AccessToken{}, fmt.Errorf("internal AccessToken: %v", err) + } + if value.ExpiresIn != "" { + expiresIn, err := json.Number(value.ExpiresIn).Int64() + if err != nil { + return azcore.AccessToken{}, err + } + return azcore.AccessToken{Token: value.Token, ExpiresOn: time.Now().Add(time.Second * time.Duration(expiresIn)).UTC()}, nil + } + switch v := value.ExpiresOn.(type) { + case float64: + return azcore.AccessToken{Token: value.Token, ExpiresOn: time.Unix(int64(v), 0).UTC()}, nil + case string: + if expiresOn, err := strconv.Atoi(v); err == nil { + return azcore.AccessToken{Token: value.Token, ExpiresOn: time.Unix(int64(expiresOn), 0).UTC()}, nil + } + return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, "unexpected expires_on value: "+v, res) + default: + msg := fmt.Sprintf("unsupported type received in expires_on: %T, %v", v, v) + return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, msg, res) + } +} + +func (c *managedIdentityClient) createAuthRequest(ctx context.Context, id ManagedIDKind, scopes []string) (*policy.Request, error) { + switch c.msiType { + case msiTypeIMDS: + return c.createIMDSAuthRequest(ctx, id, scopes) + case msiTypeAppService: + return c.createAppServiceAuthRequest(ctx, id, scopes) + case msiTypeAzureArc: + // need to perform preliminary request to retreive the secret key challenge provided by the HIMDS service + key, err := c.getAzureArcSecretKey(ctx, scopes) + if err != nil { + msg := fmt.Sprintf("failed to retreive secret key from the identity endpoint: %v", err) + return nil, newAuthenticationFailedError(credNameManagedIdentity, msg, nil) + } + return c.createAzureArcAuthRequest(ctx, id, scopes, key) + case msiTypeServiceFabric: + return c.createServiceFabricAuthRequest(ctx, id, scopes) + case msiTypeCloudShell: + return c.createCloudShellAuthRequest(ctx, id, scopes) + default: + return nil, newCredentialUnavailableError(credNameManagedIdentity, "managed identity isn't supported in this environment") + } +} + +func (c *managedIdentityClient) createIMDSAuthRequest(ctx context.Context, id ManagedIDKind, scopes []string) (*policy.Request, error) { + request, err := runtime.NewRequest(ctx, http.MethodGet, c.endpoint) + if err != nil { + return nil, err + } + request.Raw().Header.Set(headerMetadata, "true") + q := request.Raw().URL.Query() + q.Add("api-version", imdsAPIVersion) + q.Add("resource", strings.Join(scopes, " ")) + if id != nil { + if id.idKind() == miResourceID { + q.Add(qpResID, id.String()) + } else { + q.Add(qpClientID, id.String()) + } + } + request.Raw().URL.RawQuery = q.Encode() + return request, nil +} + +func (c *managedIdentityClient) createAppServiceAuthRequest(ctx context.Context, id ManagedIDKind, scopes []string) (*policy.Request, error) { + request, err := runtime.NewRequest(ctx, http.MethodGet, c.endpoint) + if err != nil { + return nil, err + } + request.Raw().Header.Set("X-IDENTITY-HEADER", os.Getenv(identityHeader)) + q := request.Raw().URL.Query() + q.Add("api-version", "2019-08-01") + q.Add("resource", scopes[0]) + if id != nil { + if id.idKind() == miResourceID { + q.Add(qpResID, id.String()) + } else { + q.Add(qpClientID, id.String()) + } + } + request.Raw().URL.RawQuery = q.Encode() + return request, nil +} + +func (c *managedIdentityClient) createServiceFabricAuthRequest(ctx context.Context, id ManagedIDKind, scopes []string) (*policy.Request, error) { + request, err := runtime.NewRequest(ctx, http.MethodGet, c.endpoint) + if err != nil { + return nil, err + } + q := request.Raw().URL.Query() + request.Raw().Header.Set("Accept", "application/json") + request.Raw().Header.Set("Secret", os.Getenv(identityHeader)) + q.Add("api-version", serviceFabricAPIVersion) + q.Add("resource", strings.Join(scopes, " ")) + if id != nil { + log.Write(EventAuthentication, "WARNING: Service Fabric doesn't support selecting a user-assigned identity at runtime") + if id.idKind() == miResourceID { + q.Add(qpResID, id.String()) + } else { + q.Add(qpClientID, id.String()) + } + } + request.Raw().URL.RawQuery = q.Encode() + return request, nil +} + +func (c *managedIdentityClient) getAzureArcSecretKey(ctx context.Context, resources []string) (string, error) { + // create the request to retreive the secret key challenge provided by the HIMDS service + request, err := runtime.NewRequest(ctx, http.MethodGet, c.endpoint) + if err != nil { + return "", err + } + request.Raw().Header.Set(headerMetadata, "true") + q := request.Raw().URL.Query() + q.Add("api-version", azureArcAPIVersion) + q.Add("resource", strings.Join(resources, " ")) + request.Raw().URL.RawQuery = q.Encode() + // send the initial request to get the short-lived secret key + response, err := c.pipeline.Do(request) + if err != nil { + return "", err + } + // the endpoint is expected to return a 401 with the WWW-Authenticate header set to the location + // of the secret key file. Any other status code indicates an error in the request. + if response.StatusCode != 401 { + msg := fmt.Sprintf("expected a 401 response, received %d", response.StatusCode) + return "", newAuthenticationFailedError(credNameManagedIdentity, msg, response) + } + header := response.Header.Get("WWW-Authenticate") + if len(header) == 0 { + return "", errors.New("did not receive a value from WWW-Authenticate header") + } + // the WWW-Authenticate header is expected in the following format: Basic realm=/some/file/path.key + pos := strings.LastIndex(header, "=") + if pos == -1 { + return "", fmt.Errorf("did not receive a correct value from WWW-Authenticate header: %s", header) + } + key, err := os.ReadFile(header[pos+1:]) + if err != nil { + return "", fmt.Errorf("could not read file (%s) contents: %v", header[pos+1:], err) + } + return string(key), nil +} + +func (c *managedIdentityClient) createAzureArcAuthRequest(ctx context.Context, id ManagedIDKind, resources []string, key string) (*policy.Request, error) { + request, err := runtime.NewRequest(ctx, http.MethodGet, c.endpoint) + if err != nil { + return nil, err + } + request.Raw().Header.Set(headerMetadata, "true") + request.Raw().Header.Set("Authorization", fmt.Sprintf("Basic %s", key)) + q := request.Raw().URL.Query() + q.Add("api-version", azureArcAPIVersion) + q.Add("resource", strings.Join(resources, " ")) + if id != nil { + log.Write(EventAuthentication, "WARNING: Azure Arc doesn't support user-assigned managed identities") + if id.idKind() == miResourceID { + q.Add(qpResID, id.String()) + } else { + q.Add(qpClientID, id.String()) + } + } + request.Raw().URL.RawQuery = q.Encode() + return request, nil +} + +func (c *managedIdentityClient) createCloudShellAuthRequest(ctx context.Context, id ManagedIDKind, scopes []string) (*policy.Request, error) { + request, err := runtime.NewRequest(ctx, http.MethodPost, c.endpoint) + if err != nil { + return nil, err + } + request.Raw().Header.Set(headerMetadata, "true") + data := url.Values{} + data.Set("resource", strings.Join(scopes, " ")) + dataEncoded := data.Encode() + body := streaming.NopCloser(strings.NewReader(dataEncoded)) + if err := request.SetBody(body, "application/x-www-form-urlencoded"); err != nil { + return nil, err + } + if id != nil { + log.Write(EventAuthentication, "WARNING: Cloud Shell doesn't support user-assigned managed identities") + q := request.Raw().URL.Query() + if id.idKind() == miResourceID { + q.Add(qpResID, id.String()) + } else { + q.Add(qpClientID, id.String()) + } + } + return request, nil +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed_identity_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed_identity_credential.go new file mode 100644 index 00000000000..18078171ee8 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/managed_identity_credential.go @@ -0,0 +1,125 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "context" + "errors" + "fmt" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential" +) + +const credNameManagedIdentity = "ManagedIdentityCredential" + +type managedIdentityIDKind int + +const ( + miClientID managedIdentityIDKind = 0 + miResourceID managedIdentityIDKind = 1 +) + +// ManagedIDKind identifies the ID of a managed identity as either a client or resource ID +type ManagedIDKind interface { + fmt.Stringer + idKind() managedIdentityIDKind +} + +// ClientID is the client ID of a user-assigned managed identity. +type ClientID string + +func (ClientID) idKind() managedIdentityIDKind { + return miClientID +} + +// String returns the string value of the ID. +func (c ClientID) String() string { + return string(c) +} + +// ResourceID is the resource ID of a user-assigned managed identity. +type ResourceID string + +func (ResourceID) idKind() managedIdentityIDKind { + return miResourceID +} + +// String returns the string value of the ID. +func (r ResourceID) String() string { + return string(r) +} + +// ManagedIdentityCredentialOptions contains optional parameters for ManagedIdentityCredential. +type ManagedIdentityCredentialOptions struct { + azcore.ClientOptions + + // ID is the ID of a managed identity the credential should authenticate. Set this field to use a specific identity + // instead of the hosting environment's default. The value may be the identity's client ID or resource ID, but note that + // some platforms don't accept resource IDs. + ID ManagedIDKind +} + +// ManagedIdentityCredential authenticates an Azure managed identity in any hosting environment supporting managed identities. +// This credential authenticates a system-assigned identity by default. Use ManagedIdentityCredentialOptions.ID to specify a +// user-assigned identity. See Azure Active Directory documentation for more information about managed identities: +// https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/overview +type ManagedIdentityCredential struct { + client confidentialClient + mic *managedIdentityClient +} + +// NewManagedIdentityCredential creates a ManagedIdentityCredential. Pass nil to accept default options. +func NewManagedIdentityCredential(options *ManagedIdentityCredentialOptions) (*ManagedIdentityCredential, error) { + if options == nil { + options = &ManagedIdentityCredentialOptions{} + } + mic, err := newManagedIdentityClient(options) + if err != nil { + return nil, err + } + cred := confidential.NewCredFromTokenProvider(mic.provideToken) + if err != nil { + return nil, err + } + // It's okay to give MSAL an invalid client ID because MSAL will use it only as part of a cache key. + // ManagedIdentityClient handles all the details of authentication and won't receive this value from MSAL. + clientID := "SYSTEM-ASSIGNED-MANAGED-IDENTITY" + if options.ID != nil { + clientID = options.ID.String() + } + c, err := confidential.New(clientID, cred) + if err != nil { + return nil, err + } + return &ManagedIdentityCredential{client: c, mic: mic}, nil +} + +// GetToken requests an access token from the hosting environment. This method is called automatically by Azure SDK clients. +func (c *ManagedIdentityCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + if len(opts.Scopes) != 1 { + err := errors.New(credNameManagedIdentity + ": GetToken() requires exactly one scope") + return azcore.AccessToken{}, err + } + // managed identity endpoints require an AADv1 resource (i.e. token audience), not a v2 scope, so we remove "/.default" here + scopes := []string{strings.TrimSuffix(opts.Scopes[0], defaultSuffix)} + ar, err := c.client.AcquireTokenSilent(ctx, scopes) + if err == nil { + logGetTokenSuccess(c, opts) + return azcore.AccessToken{Token: ar.AccessToken, ExpiresOn: ar.ExpiresOn.UTC()}, nil + } + ar, err = c.client.AcquireTokenByCredential(ctx, scopes) + if err != nil { + return azcore.AccessToken{}, err + } + logGetTokenSuccess(c, opts) + return azcore.AccessToken{Token: ar.AccessToken, ExpiresOn: ar.ExpiresOn.UTC()}, err +} + +var _ azcore.TokenCredential = (*ManagedIdentityCredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/username_password_credential.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/username_password_credential.go new file mode 100644 index 00000000000..2ab248c3c61 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/username_password_credential.go @@ -0,0 +1,68 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "context" + "errors" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/public" +) + +const credNameUserPassword = "UsernamePasswordCredential" + +// UsernamePasswordCredentialOptions contains optional parameters for UsernamePasswordCredential. +type UsernamePasswordCredentialOptions struct { + azcore.ClientOptions +} + +// UsernamePasswordCredential authenticates a user with a password. Microsoft doesn't recommend this kind of authentication, +// because it's less secure than other authentication flows. This credential is not interactive, so it isn't compatible +// with any form of multi-factor authentication, and the application must already have user or admin consent. +// This credential can only authenticate work and school accounts; it can't authenticate Microsoft accounts. +type UsernamePasswordCredential struct { + client publicClient + username string + password string + account public.Account +} + +// NewUsernamePasswordCredential creates a UsernamePasswordCredential. clientID is the ID of the application the user +// will authenticate to. Pass nil for options to accept defaults. +func NewUsernamePasswordCredential(tenantID string, clientID string, username string, password string, options *UsernamePasswordCredentialOptions) (*UsernamePasswordCredential, error) { + if options == nil { + options = &UsernamePasswordCredentialOptions{} + } + c, err := getPublicClient(clientID, tenantID, &options.ClientOptions) + if err != nil { + return nil, err + } + return &UsernamePasswordCredential{username: username, password: password, client: c}, nil +} + +// GetToken requests an access token from Azure Active Directory. This method is called automatically by Azure SDK clients. +func (c *UsernamePasswordCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) { + if len(opts.Scopes) == 0 { + return azcore.AccessToken{}, errors.New(credNameUserPassword + ": GetToken() requires at least one scope") + } + ar, err := c.client.AcquireTokenSilent(ctx, opts.Scopes, public.WithSilentAccount(c.account)) + if err == nil { + logGetTokenSuccess(c, opts) + return azcore.AccessToken{Token: ar.AccessToken, ExpiresOn: ar.ExpiresOn.UTC()}, err + } + ar, err = c.client.AcquireTokenByUsernamePassword(ctx, opts.Scopes, c.username, c.password) + if err != nil { + return azcore.AccessToken{}, newAuthenticationFailedErrorFromMSALError(credNameUserPassword, err) + } + c.account = ar.Account + logGetTokenSuccess(c, opts) + return azcore.AccessToken{Token: ar.AccessToken, ExpiresOn: ar.ExpiresOn.UTC()}, err +} + +var _ azcore.TokenCredential = (*UsernamePasswordCredential)(nil) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/version.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/version.go new file mode 100644 index 00000000000..85226d55ae1 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/azidentity/version.go @@ -0,0 +1,15 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +const ( + // UserAgent is the string to be used in the user agent string when making requests. + component = "azidentity" + + // Version is the semantic version (see http://semver.org) of this module. + version = "v1.2.1" +) diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/LICENSE.txt b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/LICENSE.txt new file mode 100644 index 00000000000..48ea6616b5b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/diag/diag.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/diag/diag.go new file mode 100644 index 00000000000..245af7d2bec --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/diag/diag.go @@ -0,0 +1,51 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package diag + +import ( + "fmt" + "runtime" + "strings" +) + +// Caller returns the file and line number of a frame on the caller's stack. +// If the funtion fails an empty string is returned. +// skipFrames - the number of frames to skip when determining the caller. +// Passing a value of 0 will return the immediate caller of this function. +func Caller(skipFrames int) string { + if pc, file, line, ok := runtime.Caller(skipFrames + 1); ok { + // the skipFrames + 1 is to skip ourselves + frame := runtime.FuncForPC(pc) + return fmt.Sprintf("%s()\n\t%s:%d", frame.Name(), file, line) + } + return "" +} + +// StackTrace returns a formatted stack trace string. +// If the funtion fails an empty string is returned. +// skipFrames - the number of stack frames to skip before composing the trace string. +// totalFrames - the maximum number of stack frames to include in the trace string. +func StackTrace(skipFrames, totalFrames int) string { + pcCallers := make([]uintptr, totalFrames) + if frames := runtime.Callers(skipFrames, pcCallers); frames == 0 { + return "" + } + frames := runtime.CallersFrames(pcCallers) + sb := strings.Builder{} + for { + frame, more := frames.Next() + sb.WriteString(frame.Function) + sb.WriteString("()\n\t") + sb.WriteString(frame.File) + sb.WriteRune(':') + sb.WriteString(fmt.Sprintf("%d\n", frame.Line)) + if !more { + break + } + } + return sb.String() +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/diag/doc.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/diag/doc.go new file mode 100644 index 00000000000..66bf13e5f04 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/diag/doc.go @@ -0,0 +1,7 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package diag diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo/doc.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo/doc.go new file mode 100644 index 00000000000..8c6eacb618a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo/doc.go @@ -0,0 +1,7 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package errorinfo diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo/errorinfo.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo/errorinfo.go new file mode 100644 index 00000000000..ade7b348e30 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo/errorinfo.go @@ -0,0 +1,16 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package errorinfo + +// NonRetriable represents a non-transient error. This works in +// conjunction with the retry policy, indicating that the error condition +// is idempotent, so no retries will be attempted. +// Use errors.As() to access this interface in the error chain. +type NonRetriable interface { + error + NonRetriable() +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/log/doc.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/log/doc.go new file mode 100644 index 00000000000..d7876d297ae --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/log/doc.go @@ -0,0 +1,7 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package log diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/log/log.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/log/log.go new file mode 100644 index 00000000000..4f1dcf1b78a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/log/log.go @@ -0,0 +1,104 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package log + +import ( + "fmt" + "os" + "time" +) + +/////////////////////////////////////////////////////////////////////////////////////////////////// +// NOTE: The following are exported as public surface area from azcore. DO NOT MODIFY +/////////////////////////////////////////////////////////////////////////////////////////////////// + +// Event is used to group entries. Each group can be toggled on or off. +type Event string + +// SetEvents is used to control which events are written to +// the log. By default all log events are writen. +func SetEvents(cls ...Event) { + log.cls = cls +} + +// SetListener will set the Logger to write to the specified listener. +func SetListener(lst func(Event, string)) { + log.lst = lst +} + +/////////////////////////////////////////////////////////////////////////////////////////////////// +// END PUBLIC SURFACE AREA +/////////////////////////////////////////////////////////////////////////////////////////////////// + +// Should returns true if the specified log event should be written to the log. +// By default all log events will be logged. Call SetEvents() to limit +// the log events for logging. +// If no listener has been set this will return false. +// Calling this method is useful when the message to log is computationally expensive +// and you want to avoid the overhead if its log event is not enabled. +func Should(cls Event) bool { + if log.lst == nil { + return false + } + if log.cls == nil || len(log.cls) == 0 { + return true + } + for _, c := range log.cls { + if c == cls { + return true + } + } + return false +} + +// Write invokes the underlying listener with the specified event and message. +// If the event shouldn't be logged or there is no listener then Write does nothing. +func Write(cls Event, message string) { + if !Should(cls) { + return + } + log.lst(cls, message) +} + +// Writef invokes the underlying listener with the specified event and formatted message. +// If the event shouldn't be logged or there is no listener then Writef does nothing. +func Writef(cls Event, format string, a ...interface{}) { + if !Should(cls) { + return + } + log.lst(cls, fmt.Sprintf(format, a...)) +} + +// TestResetEvents is used for TESTING PURPOSES ONLY. +func TestResetEvents() { + log.cls = nil +} + +// logger controls which events to log and writing to the underlying log. +type logger struct { + cls []Event + lst func(Event, string) +} + +// the process-wide logger +var log logger + +func init() { + initLogging() +} + +// split out for testing purposes +func initLogging() { + if cls := os.Getenv("AZURE_SDK_GO_LOGGING"); cls == "all" { + // cls could be enhanced to support a comma-delimited list of log events + log.lst = func(cls Event, msg string) { + // simple console logger, it writes to stderr in the following format: + // [time-stamp] Event: message + fmt.Fprintf(os.Stderr, "[%s] %s: %s\n", time.Now().Format(time.StampMicro), cls, msg) + } + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/temporal/resource.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/temporal/resource.go new file mode 100644 index 00000000000..238ef42ed03 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/temporal/resource.go @@ -0,0 +1,123 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package temporal + +import ( + "sync" + "time" +) + +// AcquireResource abstracts a method for refreshing a temporal resource. +type AcquireResource[TResource, TState any] func(state TState) (newResource TResource, newExpiration time.Time, err error) + +// Resource is a temporal resource (usually a credential) that requires periodic refreshing. +type Resource[TResource, TState any] struct { + // cond is used to synchronize access to the shared resource embodied by the remaining fields + cond *sync.Cond + + // acquiring indicates that some thread/goroutine is in the process of acquiring/updating the resource + acquiring bool + + // resource contains the value of the shared resource + resource TResource + + // expiration indicates when the shared resource expires; it is 0 if the resource was never acquired + expiration time.Time + + // lastAttempt indicates when a thread/goroutine last attempted to acquire/update the resource + lastAttempt time.Time + + // acquireResource is the callback function that actually acquires the resource + acquireResource AcquireResource[TResource, TState] +} + +// NewResource creates a new Resource that uses the specified AcquireResource for refreshing. +func NewResource[TResource, TState any](ar AcquireResource[TResource, TState]) *Resource[TResource, TState] { + return &Resource[TResource, TState]{cond: sync.NewCond(&sync.Mutex{}), acquireResource: ar} +} + +// Get returns the underlying resource. +// If the resource is fresh, no refresh is performed. +func (er *Resource[TResource, TState]) Get(state TState) (TResource, error) { + // If the resource is expiring within this time window, update it eagerly. + // This allows other threads/goroutines to keep running by using the not-yet-expired + // resource value while one thread/goroutine updates the resource. + const window = 5 * time.Minute // This example updates the resource 5 minutes prior to expiration + const backoff = 30 * time.Second // Minimum wait time between eager update attempts + + now, acquire, expired := time.Now(), false, false + + // acquire exclusive lock + er.cond.L.Lock() + resource := er.resource + + for { + expired = er.expiration.IsZero() || er.expiration.Before(now) + if expired { + // The resource was never acquired or has expired + if !er.acquiring { + // If another thread/goroutine is not acquiring/updating the resource, this thread/goroutine will do it + er.acquiring, acquire = true, true + break + } + // Getting here means that this thread/goroutine will wait for the updated resource + } else if er.expiration.Add(-window).Before(now) { + // The resource is valid but is expiring within the time window + if !er.acquiring && er.lastAttempt.Add(backoff).Before(now) { + // If another thread/goroutine is not acquiring/renewing the resource, and none has attempted + // to do so within the last 30 seconds, this thread/goroutine will do it + er.acquiring, acquire = true, true + break + } + // This thread/goroutine will use the existing resource value while another updates it + resource = er.resource + break + } else { + // The resource is not close to expiring, this thread/goroutine should use its current value + resource = er.resource + break + } + // If we get here, wait for the new resource value to be acquired/updated + er.cond.Wait() + } + er.cond.L.Unlock() // Release the lock so no threads/goroutines are blocked + + var err error + if acquire { + // This thread/goroutine has been selected to acquire/update the resource + var expiration time.Time + var newValue TResource + er.lastAttempt = now + newValue, expiration, err = er.acquireResource(state) + + // Atomically, update the shared resource's new value & expiration. + er.cond.L.Lock() + if err == nil { + // Update resource & expiration, return the new value + resource = newValue + er.resource, er.expiration = resource, expiration + } else if !expired { + // An eager update failed. Discard the error and return the current--still valid--resource value + err = nil + } + er.acquiring = false // Indicate that no thread/goroutine is currently acquiring the resource + + // Wake up any waiting threads/goroutines since there is a resource they can ALL use + er.cond.L.Unlock() + er.cond.Broadcast() + } + return resource, err // Return the resource this thread/goroutine can use +} + +// Expire marks the resource as expired, ensuring it's refreshed on the next call to Get(). +func (er *Resource[TResource, TState]) Expire() { + er.cond.L.Lock() + defer er.cond.L.Unlock() + + // Reset the expiration as if we never got this resource to begin with + er.expiration = time.Time{} +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/uuid/doc.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/uuid/doc.go new file mode 100644 index 00000000000..a3824bee8b5 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/uuid/doc.go @@ -0,0 +1,7 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package uuid diff --git a/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/uuid/uuid.go b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/uuid/uuid.go new file mode 100644 index 00000000000..278ac9cd1c2 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/sdk/internal/uuid/uuid.go @@ -0,0 +1,76 @@ +//go:build go1.18 +// +build go1.18 + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package uuid + +import ( + "crypto/rand" + "errors" + "fmt" + "strconv" +) + +// The UUID reserved variants. +const ( + reservedRFC4122 byte = 0x40 +) + +// A UUID representation compliant with specification in RFC4122 document. +type UUID [16]byte + +// New returns a new UUID using the RFC4122 algorithm. +func New() (UUID, error) { + u := UUID{} + // Set all bits to pseudo-random values. + // NOTE: this takes a process-wide lock + _, err := rand.Read(u[:]) + if err != nil { + return u, err + } + u[8] = (u[8] | reservedRFC4122) & 0x7F // u.setVariant(ReservedRFC4122) + + var version byte = 4 + u[6] = (u[6] & 0xF) | (version << 4) // u.setVersion(4) + return u, nil +} + +// String returns the UUID in "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" format. +func (u UUID) String() string { + return fmt.Sprintf("%x-%x-%x-%x-%x", u[0:4], u[4:6], u[6:8], u[8:10], u[10:]) +} + +// Parse parses a string formatted as "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" +// or "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}" into a UUID. +func Parse(s string) (UUID, error) { + var uuid UUID + // ensure format + switch len(s) { + case 36: + // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + case 38: + // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + s = s[1:37] + default: + return uuid, errors.New("invalid UUID format") + } + if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' { + return uuid, errors.New("invalid UUID format") + } + // parse chunks + for i, x := range [16]int{ + 0, 2, 4, 6, + 9, 11, + 14, 16, + 19, 21, + 24, 26, 28, 30, 32, 34} { + b, err := strconv.ParseUint(s[x:x+2], 16, 8) + if err != nil { + return uuid, fmt.Errorf("invalid UUID format: %s", err) + } + uuid[i] = byte(b) + } + return uuid, nil +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/autorest.go b/vendor/github.com/Azure/go-autorest/autorest/autorest.go index aafdf021fd6..211c98d1ed0 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/autorest.go +++ b/vendor/github.com/Azure/go-autorest/autorest/autorest.go @@ -6,33 +6,33 @@ generated Go code. The package breaks sending and responding to HTTP requests into three phases: Preparing, Sending, and Responding. A typical pattern is: - req, err := Prepare(&http.Request{}, - token.WithAuthorization()) + req, err := Prepare(&http.Request{}, + token.WithAuthorization()) - resp, err := Send(req, - WithLogging(logger), - DoErrorIfStatusCode(http.StatusInternalServerError), - DoCloseIfError(), - DoRetryForAttempts(5, time.Second)) + resp, err := Send(req, + WithLogging(logger), + DoErrorIfStatusCode(http.StatusInternalServerError), + DoCloseIfError(), + DoRetryForAttempts(5, time.Second)) - err = Respond(resp, - ByDiscardingBody(), - ByClosing()) + err = Respond(resp, + ByDiscardingBody(), + ByClosing()) Each phase relies on decorators to modify and / or manage processing. Decorators may first modify and then pass the data along, pass the data first and then modify the result, or wrap themselves around passing the data (such as a logger might do). Decorators run in the order provided. For example, the following: - req, err := Prepare(&http.Request{}, - WithBaseURL("https://microsoft.com/"), - WithPath("a"), - WithPath("b"), - WithPath("c")) + req, err := Prepare(&http.Request{}, + WithBaseURL("https://microsoft.com/"), + WithPath("a"), + WithPath("b"), + WithPath("c")) will set the URL to: - https://microsoft.com/a/b/c + https://microsoft.com/a/b/c Preparers and Responders may be shared and re-used (assuming the underlying decorators support sharing and re-use). Performant use is obtained by creating one or more Preparers and Responders diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/azure.go b/vendor/github.com/Azure/go-autorest/autorest/azure/azure.go index 1328f1764c2..868345db686 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/azure.go +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/azure.go @@ -214,7 +214,7 @@ func (r Resource) String() string { // See https://docs.microsoft.com/en-us/azure/azure-resource-manager/templates/template-functions-resource?tabs=json#resourceid. func ParseResourceID(resourceID string) (Resource, error) { - const resourceIDPatternText = `(?i)subscriptions/(.+)/resourceGroups/(.+)/providers/(.+?)/(.+?)/(.+)` + const resourceIDPatternText = `(?i)^/subscriptions/(.+)/resourceGroups/(.+)/providers/(.+?)/(.+?)/(.+)$` resourceIDPattern := regexp.MustCompile(resourceIDPatternText) match := resourceIDPattern.FindStringSubmatch(resourceID) diff --git a/vendor/github.com/Azure/go-autorest/autorest/utility.go b/vendor/github.com/Azure/go-autorest/autorest/utility.go index 3467b8fa604..d35b3850ab3 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/utility.go +++ b/vendor/github.com/Azure/go-autorest/autorest/utility.go @@ -60,9 +60,9 @@ func NewDecoder(encodedAs EncodedAs, r io.Reader) Decoder { // is especially useful if there is a chance the data will fail to decode. // encodedAs specifies the expected encoding, r provides the io.Reader to the data, and v // is the decoding destination. -func CopyAndDecode(encodedAs EncodedAs, r io.Reader, v interface{}) (bytes.Buffer, error) { - b := bytes.Buffer{} - return b, NewDecoder(encodedAs, io.TeeReader(r, &b)).Decode(v) +func CopyAndDecode(encodedAs EncodedAs, r io.Reader, v interface{}) (b bytes.Buffer, err error) { + err = NewDecoder(encodedAs, io.TeeReader(r, &b)).Decode(v) + return } // TeeReadCloser returns a ReadCloser that writes to w what it reads from rc. diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/LICENSE b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/LICENSE new file mode 100644 index 00000000000..3d8b93bc798 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/cache/cache.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/cache/cache.go new file mode 100644 index 00000000000..259ca6d56f4 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/cache/cache.go @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +/* +Package cache allows third parties to implement external storage for caching token data +for distributed systems or multiple local applications access. + +The data stored and extracted will represent the entire cache. Therefore it is recommended +one msal instance per user. This data is considered opaque and there are no guarantees to +implementers on the format being passed. +*/ +package cache + +// Marshaler marshals data from an internal cache to bytes that can be stored. +type Marshaler interface { + Marshal() ([]byte, error) +} + +// Unmarshaler unmarshals data from a storage medium into the internal cache, overwriting it. +type Unmarshaler interface { + Unmarshal([]byte) error +} + +// Serializer can serialize the cache to binary or from binary into the cache. +type Serializer interface { + Marshaler + Unmarshaler +} + +// ExportReplace is used export or replace what is in the cache. +type ExportReplace interface { + // Replace replaces the cache with what is in external storage. + // key is the suggested key which can be used for partioning the cache + Replace(cache Unmarshaler, key string) + // Export writes the binary representation of the cache (cache.Marshal()) to + // external storage. This is considered opaque. + // key is the suggested key which can be used for partioning the cache + Export(cache Marshaler, key string) +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential/confidential.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential/confidential.go new file mode 100644 index 00000000000..85a1ba6deae --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential/confidential.go @@ -0,0 +1,773 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +/* +Package confidential provides a client for authentication of "confidential" applications. +A "confidential" application is defined as an app that run on servers. They are considered +difficult to access and for that reason capable of keeping an application secret. +Confidential clients can hold configuration-time secrets. +*/ +package confidential + +import ( + "context" + "crypto" + "crypto/rsa" + "crypto/x509" + "encoding/base64" + "encoding/pem" + "errors" + "fmt" + "net/url" + + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/cache" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/exported" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/options" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/shared" +) + +/* +Design note: + +confidential.Client uses base.Client as an embedded type. base.Client statically assigns its attributes +during creation. As it doesn't have any pointers in it, anything borrowed from it, such as +Base.AuthParams is a copy that is free to be manipulated here. + +Duplicate Calls shared between public.Client and this package: +There is some duplicate call options provided here that are the same as in public.Client . This +is a design choices. Go proverb(https://www.youtube.com/watch?v=PAAkCSZUG1c&t=9m28s): +"a little copying is better than a little dependency". Yes, we could have another package with +shared options (fail). That divides like 2 options from all others which makes the user look +through more docs. We can have all clients in one package, but I think separate packages +here makes for better naming (public.Client vs client.PublicClient). So I chose a little +duplication. + +.Net People, Take note on X509: +This uses x509.Certificates and private keys. x509 does not store private keys. .Net +has some x509.Certificate2 thing that has private keys, but that is just some bullcrap that .Net +added, it doesn't exist in real life. Seriously, "x509.Certificate2", bahahahaha. As such I've +put a PEM decoder into here. +*/ + +// TODO(msal): This should have example code for each method on client using Go's example doc framework. +// base usage details should be include in the package documentation. + +// AuthResult contains the results of one token acquisition operation. +// For details see https://aka.ms/msal-net-authenticationresult +type AuthResult = base.AuthResult + +type Account = shared.Account + +// CertFromPEM converts a PEM file (.pem or .key) for use with NewCredFromCert(). The file +// must contain the public certificate and the private key. If a PEM block is encrypted and +// password is not an empty string, it attempts to decrypt the PEM blocks using the password. +// Multiple certs are due to certificate chaining for use cases like TLS that sign from root to leaf. +func CertFromPEM(pemData []byte, password string) ([]*x509.Certificate, crypto.PrivateKey, error) { + var certs []*x509.Certificate + var priv crypto.PrivateKey + for { + block, rest := pem.Decode(pemData) + if block == nil { + break + } + + //nolint:staticcheck // x509.IsEncryptedPEMBlock and x509.DecryptPEMBlock are deprecated. They are used here only to support a usecase. + if x509.IsEncryptedPEMBlock(block) { + b, err := x509.DecryptPEMBlock(block, []byte(password)) + if err != nil { + return nil, nil, fmt.Errorf("could not decrypt encrypted PEM block: %v", err) + } + block, _ = pem.Decode(b) + if block == nil { + return nil, nil, fmt.Errorf("encounter encrypted PEM block that did not decode") + } + } + + switch block.Type { + case "CERTIFICATE": + cert, err := x509.ParseCertificate(block.Bytes) + if err != nil { + return nil, nil, fmt.Errorf("block labelled 'CERTIFICATE' could not be parsed by x509: %v", err) + } + certs = append(certs, cert) + case "PRIVATE KEY": + if priv != nil { + return nil, nil, errors.New("found multiple private key blocks") + } + + var err error + priv, err = x509.ParsePKCS8PrivateKey(block.Bytes) + if err != nil { + return nil, nil, fmt.Errorf("could not decode private key: %v", err) + } + case "RSA PRIVATE KEY": + if priv != nil { + return nil, nil, errors.New("found multiple private key blocks") + } + var err error + priv, err = x509.ParsePKCS1PrivateKey(block.Bytes) + if err != nil { + return nil, nil, fmt.Errorf("could not decode private key: %v", err) + } + } + pemData = rest + } + + if len(certs) == 0 { + return nil, nil, fmt.Errorf("no certificates found") + } + + if priv == nil { + return nil, nil, fmt.Errorf("no private key found") + } + + return certs, priv, nil +} + +// AssertionRequestOptions has required information for client assertion claims +type AssertionRequestOptions = exported.AssertionRequestOptions + +// Credential represents the credential used in confidential client flows. +type Credential struct { + secret string + + cert *x509.Certificate + key crypto.PrivateKey + x5c []string + + assertionCallback func(context.Context, AssertionRequestOptions) (string, error) + + tokenProvider func(context.Context, TokenProviderParameters) (TokenProviderResult, error) +} + +// toInternal returns the accesstokens.Credential that is used internally. The current structure of the +// code requires that client.go, requests.go and confidential.go share a credential type without +// having import recursion. That requires the type used between is in a shared package. Therefore +// we have this. +func (c Credential) toInternal() (*accesstokens.Credential, error) { + if c.secret != "" { + return &accesstokens.Credential{Secret: c.secret}, nil + } + if c.cert != nil { + if c.key == nil { + return nil, errors.New("missing private key for certificate") + } + return &accesstokens.Credential{Cert: c.cert, Key: c.key, X5c: c.x5c}, nil + } + if c.key != nil { + return nil, errors.New("missing certificate for private key") + } + if c.assertionCallback != nil { + return &accesstokens.Credential{AssertionCallback: c.assertionCallback}, nil + } + if c.tokenProvider != nil { + return &accesstokens.Credential{TokenProvider: c.tokenProvider}, nil + } + return nil, errors.New("invalid credential") +} + +// NewCredFromSecret creates a Credential from a secret. +func NewCredFromSecret(secret string) (Credential, error) { + if secret == "" { + return Credential{}, errors.New("secret can't be empty string") + } + return Credential{secret: secret}, nil +} + +// NewCredFromAssertion creates a Credential from a signed assertion. +// +// Deprecated: a Credential created by this function can't refresh the +// assertion when it expires. Use NewCredFromAssertionCallback instead. +func NewCredFromAssertion(assertion string) (Credential, error) { + if assertion == "" { + return Credential{}, errors.New("assertion can't be empty string") + } + return NewCredFromAssertionCallback(func(context.Context, AssertionRequestOptions) (string, error) { return assertion, nil }), nil +} + +// NewCredFromAssertionCallback creates a Credential that invokes a callback to get assertions +// authenticating the application. The callback must be thread safe. +func NewCredFromAssertionCallback(callback func(context.Context, AssertionRequestOptions) (string, error)) Credential { + return Credential{assertionCallback: callback} +} + +// NewCredFromCert creates a Credential from an x509.Certificate and an RSA private key. +// CertFromPEM() can be used to get these values from a PEM file. +func NewCredFromCert(cert *x509.Certificate, key crypto.PrivateKey) Credential { + cred, _ := NewCredFromCertChain([]*x509.Certificate{cert}, key) + return cred +} + +// NewCredFromCertChain creates a Credential from a chain of x509.Certificates and an RSA private key +// as returned by CertFromPEM(). +func NewCredFromCertChain(certs []*x509.Certificate, key crypto.PrivateKey) (Credential, error) { + cred := Credential{key: key} + k, ok := key.(*rsa.PrivateKey) + if !ok { + return cred, errors.New("key must be an RSA key") + } + for _, cert := range certs { + if cert == nil { + // not returning an error here because certs may still contain a sufficient cert/key pair + continue + } + certKey, ok := cert.PublicKey.(*rsa.PublicKey) + if ok && k.E == certKey.E && k.N.Cmp(certKey.N) == 0 { + // We know this is the signing cert because its public key matches the given private key. + // This cert must be first in x5c. + cred.cert = cert + cred.x5c = append([]string{base64.StdEncoding.EncodeToString(cert.Raw)}, cred.x5c...) + } else { + cred.x5c = append(cred.x5c, base64.StdEncoding.EncodeToString(cert.Raw)) + } + } + if cred.cert == nil { + return cred, errors.New("key doesn't match any certificate") + } + return cred, nil +} + +// TokenProviderParameters is the authentication parameters passed to token providers +type TokenProviderParameters = exported.TokenProviderParameters + +// TokenProviderResult is the authentication result returned by custom token providers +type TokenProviderResult = exported.TokenProviderResult + +// NewCredFromTokenProvider creates a Credential from a function that provides access tokens. The function +// must be concurrency safe. This is intended only to allow the Azure SDK to cache MSI tokens. It isn't +// useful to applications in general because the token provider must implement all authentication logic. +func NewCredFromTokenProvider(provider func(context.Context, TokenProviderParameters) (TokenProviderResult, error)) Credential { + return Credential{tokenProvider: provider} +} + +// AutoDetectRegion instructs MSAL Go to auto detect region for Azure regional token service. +func AutoDetectRegion() string { + return "TryAutoDetect" +} + +// Client is a representation of authentication client for confidential applications as defined in the +// package doc. A new Client should be created PER SERVICE USER. +// For more information, visit https://docs.microsoft.com/azure/active-directory/develop/msal-client-applications +type Client struct { + base base.Client + + cred *accesstokens.Credential + + // userID is some unique identifier for a user. It actually isn't used by us at all, it + // simply acts as another hint that a confidential.Client is for a single user. + userID string +} + +// Options are optional settings for New(). These options are set using various functions +// returning Option calls. +type Options struct { + // Accessor controls cache persistence. + // By default there is no cache persistence. This can be set using the WithAccessor() option. + Accessor cache.ExportReplace + + // The host of the Azure Active Directory authority. + // The default is https://login.microsoftonline.com/common. This can be changed using the + // WithAuthority() option. + Authority string + + // The HTTP client used for making requests. + // It defaults to a shared http.Client. + HTTPClient ops.HTTPClient + + // SendX5C specifies if x5c claim(public key of the certificate) should be sent to STS. + SendX5C bool + + // Instructs MSAL Go to use an Azure regional token service with sepcified AzureRegion. + AzureRegion string + + capabilities []string + + disableInstanceDiscovery bool +} + +func (o Options) validate() error { + u, err := url.Parse(o.Authority) + if err != nil { + return fmt.Errorf("the Authority(%s) does not parse as a valid URL", o.Authority) + } + if u.Scheme != "https" { + return fmt.Errorf("the Authority(%s) does not appear to use https", o.Authority) + } + return nil +} + +// Option is an optional argument to New(). +type Option func(o *Options) + +// WithAuthority allows you to provide a custom authority for use in the client. +func WithAuthority(authority string) Option { + return func(o *Options) { + o.Authority = authority + } +} + +// WithAccessor provides a cache accessor that will read and write to some externally managed cache +// that may or may not be shared with other applications. +func WithAccessor(accessor cache.ExportReplace) Option { + return func(o *Options) { + o.Accessor = accessor + } +} + +// WithClientCapabilities allows configuring one or more client capabilities such as "CP1" +func WithClientCapabilities(capabilities []string) Option { + return func(o *Options) { + // there's no danger of sharing the slice's underlying memory with the application because + // this slice is simply passed to base.WithClientCapabilities, which copies its data + o.capabilities = capabilities + } +} + +// WithHTTPClient allows for a custom HTTP client to be set. +func WithHTTPClient(httpClient ops.HTTPClient) Option { + return func(o *Options) { + o.HTTPClient = httpClient + } +} + +// WithX5C specifies if x5c claim(public key of the certificate) should be sent to STS to enable Subject Name Issuer Authentication. +func WithX5C() Option { + return func(o *Options) { + o.SendX5C = true + } +} + +// WithInstanceDiscovery set to false to disable authority validation (to support private cloud scenarios) +func WithInstanceDiscovery(enabled bool) Option { + return func(o *Options) { + o.disableInstanceDiscovery = !enabled + } +} + +// WithAzureRegion sets the region(preferred) or Confidential.AutoDetectRegion() for auto detecting region. +// Region names as per https://azure.microsoft.com/en-ca/global-infrastructure/geographies/. +// See https://aka.ms/region-map for more details on region names. +// The region value should be short region name for the region where the service is deployed. +// For example "centralus" is short name for region Central US. +// Not all auth flows can use the regional token service. +// Service To Service (client credential flow) tokens can be obtained from the regional service. +// Requires configuration at the tenant level. +// Auto-detection works on a limited number of Azure artifacts (VMs, Azure functions). +// If auto-detection fails, the non-regional endpoint will be used. +// If an invalid region name is provided, the non-regional endpoint MIGHT be used or the token request MIGHT fail. +func WithAzureRegion(val string) Option { + return func(o *Options) { + o.AzureRegion = val + } +} + +// New is the constructor for Client. userID is the unique identifier of the user this client +// will store credentials for (a Client is per user). clientID is the Azure clientID and cred is +// the type of credential to use. +func New(clientID string, cred Credential, options ...Option) (Client, error) { + internalCred, err := cred.toInternal() + if err != nil { + return Client{}, err + } + + opts := Options{ + Authority: base.AuthorityPublicCloud, + HTTPClient: shared.DefaultClient, + } + + for _, o := range options { + o(&opts) + } + if err := opts.validate(); err != nil { + return Client{}, err + } + + baseOpts := []base.Option{ + base.WithCacheAccessor(opts.Accessor), + base.WithClientCapabilities(opts.capabilities), + base.WithRegionDetection(opts.AzureRegion), + base.WithX5C(opts.SendX5C), + base.WithInstanceDiscovery(!opts.disableInstanceDiscovery), + } + if cred.tokenProvider != nil { + // The caller will handle all details of authentication, using Client only as a token cache. + baseOpts = append(baseOpts, base.WithInstanceDiscovery(false)) + } + base, err := base.New(clientID, opts.Authority, oauth.New(opts.HTTPClient), baseOpts...) + if err != nil { + return Client{}, err + } + base.AuthParams.IsConfidentialClient = true + + return Client{base: base, cred: internalCred}, nil +} + +// UserID is the unique user identifier this client if for. +func (cca Client) UserID() string { + return cca.userID +} + +// authCodeURLOptions contains options for AuthCodeURL +type authCodeURLOptions struct { + claims, loginHint, tenantID, domainHint string +} + +// AuthCodeURLOption is implemented by options for AuthCodeURL +type AuthCodeURLOption interface { + authCodeURLOption() +} + +// AuthCodeURL creates a URL used to acquire an authorization code. Users need to call CreateAuthorizationCodeURLParameters and pass it in. +// +// Options: [WithClaims], [WithDomainHint], [WithLoginHint], [WithTenantID] +func (cca Client) AuthCodeURL(ctx context.Context, clientID, redirectURI string, scopes []string, opts ...AuthCodeURLOption) (string, error) { + o := authCodeURLOptions{} + if err := options.ApplyOptions(&o, opts); err != nil { + return "", err + } + ap, err := cca.base.AuthParams.WithTenant(o.tenantID) + if err != nil { + return "", err + } + ap.Claims = o.claims + ap.LoginHint = o.loginHint + ap.DomainHint = o.domainHint + return cca.base.AuthCodeURL(ctx, clientID, redirectURI, scopes, ap) +} + +// WithLoginHint pre-populates the login prompt with a username. +func WithLoginHint(username string) interface { + AuthCodeURLOption + options.CallOption +} { + return struct { + AuthCodeURLOption + options.CallOption + }{ + CallOption: options.NewCallOption( + func(a any) error { + switch t := a.(type) { + case *authCodeURLOptions: + t.loginHint = username + default: + return fmt.Errorf("unexpected options type %T", a) + } + return nil + }, + ), + } +} + +// WithDomainHint adds the IdP domain as domain_hint query parameter in the auth url. +func WithDomainHint(domain string) interface { + AuthCodeURLOption + options.CallOption +} { + return struct { + AuthCodeURLOption + options.CallOption + }{ + CallOption: options.NewCallOption( + func(a any) error { + switch t := a.(type) { + case *authCodeURLOptions: + t.domainHint = domain + default: + return fmt.Errorf("unexpected options type %T", a) + } + return nil + }, + ), + } +} + +// WithClaims sets additional claims to request for the token, such as those required by conditional access policies. +// Use this option when Azure AD returned a claims challenge for a prior request. The argument must be decoded. +// This option is valid for any token acquisition method. +func WithClaims(claims string) interface { + AcquireByAuthCodeOption + AcquireByCredentialOption + AcquireOnBehalfOfOption + AcquireSilentOption + AuthCodeURLOption + options.CallOption +} { + return struct { + AcquireByAuthCodeOption + AcquireByCredentialOption + AcquireOnBehalfOfOption + AcquireSilentOption + AuthCodeURLOption + options.CallOption + }{ + CallOption: options.NewCallOption( + func(a any) error { + switch t := a.(type) { + case *AcquireTokenByAuthCodeOptions: + t.claims = claims + case *acquireTokenByCredentialOptions: + t.claims = claims + case *acquireTokenOnBehalfOfOptions: + t.claims = claims + case *AcquireTokenSilentOptions: + t.claims = claims + case *authCodeURLOptions: + t.claims = claims + default: + return fmt.Errorf("unexpected options type %T", a) + } + return nil + }, + ), + } +} + +// WithTenantID specifies a tenant for a single authentication. It may be different than the tenant set in [New] by [WithAuthority]. +// This option is valid for any token acquisition method. +func WithTenantID(tenantID string) interface { + AcquireByAuthCodeOption + AcquireByCredentialOption + AcquireOnBehalfOfOption + AcquireSilentOption + AuthCodeURLOption + options.CallOption +} { + return struct { + AcquireByAuthCodeOption + AcquireByCredentialOption + AcquireOnBehalfOfOption + AcquireSilentOption + AuthCodeURLOption + options.CallOption + }{ + CallOption: options.NewCallOption( + func(a any) error { + switch t := a.(type) { + case *AcquireTokenByAuthCodeOptions: + t.tenantID = tenantID + case *acquireTokenByCredentialOptions: + t.tenantID = tenantID + case *acquireTokenOnBehalfOfOptions: + t.tenantID = tenantID + case *AcquireTokenSilentOptions: + t.tenantID = tenantID + case *authCodeURLOptions: + t.tenantID = tenantID + default: + return fmt.Errorf("unexpected options type %T", a) + } + return nil + }, + ), + } +} + +// AcquireTokenSilentOptions are all the optional settings to an AcquireTokenSilent() call. +// These are set by using various AcquireTokenSilentOption functions. +type AcquireTokenSilentOptions struct { + // Account represents the account to use. To set, use the WithSilentAccount() option. + Account Account + + claims, tenantID string +} + +// AcquireSilentOption is implemented by options for AcquireTokenSilent +type AcquireSilentOption interface { + acquireSilentOption() +} + +// AcquireTokenSilentOption changes options inside AcquireTokenSilentOptions used in .AcquireTokenSilent(). +type AcquireTokenSilentOption func(a *AcquireTokenSilentOptions) + +func (AcquireTokenSilentOption) acquireSilentOption() {} + +// WithSilentAccount uses the passed account during an AcquireTokenSilent() call. +func WithSilentAccount(account Account) interface { + AcquireSilentOption + options.CallOption +} { + return struct { + AcquireSilentOption + options.CallOption + }{ + CallOption: options.NewCallOption( + func(a any) error { + switch t := a.(type) { + case *AcquireTokenSilentOptions: + t.Account = account + default: + return fmt.Errorf("unexpected options type %T", a) + } + return nil + }, + ), + } +} + +// AcquireTokenSilent acquires a token from either the cache or using a refresh token. +// +// Options: [WithClaims], [WithSilentAccount], [WithTenantID] +func (cca Client) AcquireTokenSilent(ctx context.Context, scopes []string, opts ...AcquireSilentOption) (AuthResult, error) { + o := AcquireTokenSilentOptions{} + if err := options.ApplyOptions(&o, opts); err != nil { + return AuthResult{}, err + } + + if o.claims != "" { + return AuthResult{}, errors.New("call another AcquireToken method to request a new token having these claims") + } + + silentParameters := base.AcquireTokenSilentParameters{ + Scopes: scopes, + Account: o.Account, + RequestType: accesstokens.ATConfidential, + Credential: cca.cred, + IsAppCache: o.Account.IsZero(), + TenantID: o.tenantID, + } + + return cca.base.AcquireTokenSilent(ctx, silentParameters) +} + +// AcquireTokenByAuthCodeOptions contains the optional parameters used to acquire an access token using the authorization code flow. +type AcquireTokenByAuthCodeOptions struct { + Challenge string + + claims, tenantID string +} + +// AcquireByAuthCodeOption is implemented by options for AcquireTokenByAuthCode +type AcquireByAuthCodeOption interface { + acquireByAuthCodeOption() +} + +// AcquireTokenByAuthCodeOption changes options inside AcquireTokenByAuthCodeOptions used in .AcquireTokenByAuthCode(). +type AcquireTokenByAuthCodeOption func(a *AcquireTokenByAuthCodeOptions) + +func (AcquireTokenByAuthCodeOption) acquireByAuthCodeOption() {} + +// WithChallenge allows you to provide a challenge for the .AcquireTokenByAuthCode() call. +func WithChallenge(challenge string) interface { + AcquireByAuthCodeOption + options.CallOption +} { + return struct { + AcquireByAuthCodeOption + options.CallOption + }{ + CallOption: options.NewCallOption( + func(a any) error { + switch t := a.(type) { + case *AcquireTokenByAuthCodeOptions: + t.Challenge = challenge + default: + return fmt.Errorf("unexpected options type %T", a) + } + return nil + }, + ), + } +} + +// AcquireTokenByAuthCode is a request to acquire a security token from the authority, using an authorization code. +// The specified redirect URI must be the same URI that was used when the authorization code was requested. +// +// Options: [WithChallenge], [WithClaims], [WithTenantID] +func (cca Client) AcquireTokenByAuthCode(ctx context.Context, code string, redirectURI string, scopes []string, opts ...AcquireByAuthCodeOption) (AuthResult, error) { + o := AcquireTokenByAuthCodeOptions{} + if err := options.ApplyOptions(&o, opts); err != nil { + return AuthResult{}, err + } + + params := base.AcquireTokenAuthCodeParameters{ + Scopes: scopes, + Code: code, + Challenge: o.Challenge, + Claims: o.claims, + AppType: accesstokens.ATConfidential, + Credential: cca.cred, // This setting differs from public.Client.AcquireTokenByAuthCode + RedirectURI: redirectURI, + TenantID: o.tenantID, + } + + return cca.base.AcquireTokenByAuthCode(ctx, params) +} + +// acquireTokenByCredentialOptions contains optional configuration for AcquireTokenByCredential +type acquireTokenByCredentialOptions struct { + claims, tenantID string +} + +// AcquireByCredentialOption is implemented by options for AcquireTokenByCredential +type AcquireByCredentialOption interface { + acquireByCredOption() +} + +// AcquireTokenByCredential acquires a security token from the authority, using the client credentials grant. +// +// Options: [WithClaims], [WithTenantID] +func (cca Client) AcquireTokenByCredential(ctx context.Context, scopes []string, opts ...AcquireByCredentialOption) (AuthResult, error) { + o := acquireTokenByCredentialOptions{} + err := options.ApplyOptions(&o, opts) + if err != nil { + return AuthResult{}, err + } + authParams, err := cca.base.AuthParams.WithTenant(o.tenantID) + if err != nil { + return AuthResult{}, err + } + authParams.Scopes = scopes + authParams.AuthorizationType = authority.ATClientCredentials + authParams.Claims = o.claims + + token, err := cca.base.Token.Credential(ctx, authParams, cca.cred) + if err != nil { + return AuthResult{}, err + } + return cca.base.AuthResultFromToken(ctx, authParams, token, true) +} + +// acquireTokenOnBehalfOfOptions contains optional configuration for AcquireTokenOnBehalfOf +type acquireTokenOnBehalfOfOptions struct { + claims, tenantID string +} + +// AcquireOnBehalfOfOption is implemented by options for AcquireTokenOnBehalfOf +type AcquireOnBehalfOfOption interface { + acquireOBOOption() +} + +// AcquireTokenOnBehalfOf acquires a security token for an app using middle tier apps access token. +// Refer https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow. +// +// Options: [WithClaims], [WithTenantID] +func (cca Client) AcquireTokenOnBehalfOf(ctx context.Context, userAssertion string, scopes []string, opts ...AcquireOnBehalfOfOption) (AuthResult, error) { + o := acquireTokenOnBehalfOfOptions{} + if err := options.ApplyOptions(&o, opts); err != nil { + return AuthResult{}, err + } + params := base.AcquireTokenOnBehalfOfParameters{ + Scopes: scopes, + UserAssertion: userAssertion, + Claims: o.claims, + Credential: cca.cred, + TenantID: o.tenantID, + } + return cca.base.AcquireTokenOnBehalfOf(ctx, params) +} + +// Account gets the account in the token cache with the specified homeAccountID. +func (cca Client) Account(homeAccountID string) Account { + return cca.base.Account(homeAccountID) +} + +// RemoveAccount signs the account out and forgets account from token cache. +func (cca Client) RemoveAccount(account Account) error { + cca.base.RemoveAccount(account) + return nil +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/errors/error_design.md b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/errors/error_design.md new file mode 100644 index 00000000000..34a699f4801 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/errors/error_design.md @@ -0,0 +1,111 @@ +# MSAL Error Design + +Author: Abhidnya Patil(abhidnya.patil@microsoft.com) + +Contributors: + +- John Doak(jdoak@microsoft.com) +- Keegan Caruso(Keegan.Caruso@microsoft.com) +- Joel Hendrix(jhendrix@microsoft.com) + +## Background + +Errors in MSAL are intended for app developers to troubleshoot and not for displaying to end-users. + +### Go error handling vs other MSAL languages + +Most modern languages use exception based errors. Simply put, you "throw" an exception and it must be caught at some routine in the upper stack or it will eventually crash the program. + +Go doesn't use exceptions, instead it relies on multiple return values, one of which can be the builtin error interface type. It is up to the user to decide what to do. + +### Go custom error types + +Errors can be created in Go by simply using errors.New() or fmt.Errorf() to create an "error". + +Custom errors can be created in multiple ways. One of the more robust ways is simply to satisfy the error interface: + +```go +type MyCustomErr struct { + Msg string +} +func (m MyCustomErr) Error() string { // This implements "error" + return m.Msg +} +``` + +### MSAL Error Goals + +- Provide diagnostics to the user and for tickets that can be used to track down bugs or client misconfigurations +- Detect errors that are transitory and can be retried +- Allow the user to identify certain errors that the program can respond to, such a informing the user for the need to do an enrollment + +## Implementing Client Side Errors + +Client side errors indicate a misconfiguration or passing of bad arguments that is non-recoverable. Retrying isn't possible. + +These errors can simply be standard Go errors created by errors.New() or fmt.Errorf(). If down the line we need a custom error, we can introduce it, but for now the error messages just need to be clear on what the issue was. + +## Implementing Service Side Errors + +Service side errors occur when an external RPC responds either with an HTTP error code or returns a message that includes an error. + +These errors can be transitory (please slow down) or permanent (HTTP 404). To provide our diagnostic goals, we require the ability to differentiate these errors from other errors. + +The current implementation includes a specialized type that captures any error from the server: + +```go +// CallErr represents an HTTP call error. Has a Verbose() method that allows getting the +// http.Request and Response objects. Implements error. +type CallErr struct { + Req *http.Request + Resp *http.Response + Err error +} + +// Errors implements error.Error(). +func (e CallErr) Error() string { + return e.Err.Error() +} + +// Verbose prints a versbose error message with the request or response. +func (e CallErr) Verbose() string { + e.Resp.Request = nil // This brings in a bunch of TLS crap we don't need + e.Resp.TLS = nil // Same + return fmt.Sprintf("%s:\nRequest:\n%s\nResponse:\n%s", e.Err, prettyConf.Sprint(e.Req), prettyConf.Sprint(e.Resp)) +} +``` + +A user will always receive the most concise error we provide. They can tell if it is a server side error using Go error package: + +```go +var callErr CallErr +if errors.As(err, &callErr) { + ... +} +``` + +We provide a Verbose() function that can retrieve the most verbose message from any error we provide: + +```go +fmt.Println(errors.Verbose(err)) +``` + +If further differentiation is required, we can add custom errors that use Go error wrapping on top of CallErr to achieve our diagnostic goals (such as detecting when to retry a call due to transient errors). + +CallErr is always thrown from the comm package (which handles all http requests) and looks similar to: + +```go +return nil, errors.CallErr{ + Req: req, + Resp: reply, + Err: fmt.Errorf("http call(%s)(%s) error: reply status code was %d:\n%s", req.URL.String(), req.Method, reply.StatusCode, ErrorResponse), //ErrorResponse is the json body extracted from the http response + } +``` + +## Future Decisions + +The ability to retry calls needs to have centralized responsibility. Either the user is doing it or the client is doing it. + +If the user should be responsible, our errors package will include a CanRetry() function that will inform the user if the error provided to them is retryable. This is based on the http error code and possibly the type of error that was returned. It would also include a sleep time if the server returned an amount of time to wait. + +Otherwise we will do this internally and retries will be left to us. diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/errors/errors.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/errors/errors.go new file mode 100644 index 00000000000..c9b8dbed088 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/errors/errors.go @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package errors + +import ( + "errors" + "fmt" + "io" + "net/http" + "reflect" + "strings" + + "github.com/kylelemons/godebug/pretty" +) + +var prettyConf = &pretty.Config{ + IncludeUnexported: false, + SkipZeroFields: true, + TrackCycles: true, + Formatter: map[reflect.Type]interface{}{ + reflect.TypeOf((*io.Reader)(nil)).Elem(): func(r io.Reader) string { + b, err := io.ReadAll(r) + if err != nil { + return "could not read io.Reader content" + } + return string(b) + }, + }, +} + +type verboser interface { + Verbose() string +} + +// Verbose prints the most verbose error that the error message has. +func Verbose(err error) string { + build := strings.Builder{} + for { + if err == nil { + break + } + if v, ok := err.(verboser); ok { + build.WriteString(v.Verbose()) + } else { + build.WriteString(err.Error()) + } + err = errors.Unwrap(err) + } + return build.String() +} + +// New is equivalent to errors.New(). +func New(text string) error { + return errors.New(text) +} + +// CallErr represents an HTTP call error. Has a Verbose() method that allows getting the +// http.Request and Response objects. Implements error. +type CallErr struct { + Req *http.Request + // Resp contains response body + Resp *http.Response + Err error +} + +// Errors implements error.Error(). +func (e CallErr) Error() string { + return e.Err.Error() +} + +// Verbose prints a versbose error message with the request or response. +func (e CallErr) Verbose() string { + e.Resp.Request = nil // This brings in a bunch of TLS crap we don't need + e.Resp.TLS = nil // Same + return fmt.Sprintf("%s:\nRequest:\n%s\nResponse:\n%s", e.Err, prettyConf.Sprint(e.Req), prettyConf.Sprint(e.Resp)) +} + +// Is reports whether any error in errors chain matches target. +func Is(err, target error) bool { + return errors.Is(err, target) +} + +// As finds the first error in errors chain that matches target, +// and if so, sets target to that error value and returns true. +// Otherwise, it returns false. +func As(err error, target interface{}) bool { + return errors.As(err, target) +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/base.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/base.go new file mode 100644 index 00000000000..ed8715ced44 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/base.go @@ -0,0 +1,467 @@ +// Package base contains a "Base" client that is used by the external public.Client and confidential.Client. +// Base holds shared attributes that must be available to both clients and methods that act as +// shared calls. +package base + +import ( + "context" + "errors" + "fmt" + "net/url" + "reflect" + "strings" + "time" + + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/cache" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/shared" +) + +const ( + // AuthorityPublicCloud is the default AAD authority host + AuthorityPublicCloud = "https://login.microsoftonline.com/common" + scopeSeparator = " " +) + +// manager provides an internal cache. It is defined to allow faking the cache in tests. +// In all production use it is a *storage.Manager. +type manager interface { + Read(ctx context.Context, authParameters authority.AuthParams, account shared.Account) (storage.TokenResponse, error) + Write(authParameters authority.AuthParams, tokenResponse accesstokens.TokenResponse) (shared.Account, error) + AllAccounts() []shared.Account + Account(homeAccountID string) shared.Account + RemoveAccount(account shared.Account, clientID string) +} + +// partitionedManager provides an internal cache. It is defined to allow faking the cache in tests. +// In all production use it is a *storage.PartitionedManager. +type partitionedManager interface { + Read(ctx context.Context, authParameters authority.AuthParams) (storage.TokenResponse, error) + Write(authParameters authority.AuthParams, tokenResponse accesstokens.TokenResponse) (shared.Account, error) +} + +type noopCacheAccessor struct{} + +func (n noopCacheAccessor) Replace(cache cache.Unmarshaler, key string) {} +func (n noopCacheAccessor) Export(cache cache.Marshaler, key string) {} + +// AcquireTokenSilentParameters contains the parameters to acquire a token silently (from cache). +type AcquireTokenSilentParameters struct { + Scopes []string + Account shared.Account + RequestType accesstokens.AppType + Credential *accesstokens.Credential + IsAppCache bool + TenantID string + UserAssertion string + AuthorizationType authority.AuthorizeType + Claims string +} + +// AcquireTokenAuthCodeParameters contains the parameters required to acquire an access token using the auth code flow. +// To use PKCE, set the CodeChallengeParameter. +// Code challenges are used to secure authorization code grants; for more information, visit +// https://tools.ietf.org/html/rfc7636. +type AcquireTokenAuthCodeParameters struct { + Scopes []string + Code string + Challenge string + Claims string + RedirectURI string + AppType accesstokens.AppType + Credential *accesstokens.Credential + TenantID string +} + +type AcquireTokenOnBehalfOfParameters struct { + Scopes []string + Claims string + Credential *accesstokens.Credential + TenantID string + UserAssertion string +} + +// AuthResult contains the results of one token acquisition operation in PublicClientApplication +// or ConfidentialClientApplication. For details see https://aka.ms/msal-net-authenticationresult +type AuthResult struct { + Account shared.Account + IDToken accesstokens.IDToken + AccessToken string + ExpiresOn time.Time + GrantedScopes []string + DeclinedScopes []string +} + +// AuthResultFromStorage creates an AuthResult from a storage token response (which is generated from the cache). +func AuthResultFromStorage(storageTokenResponse storage.TokenResponse) (AuthResult, error) { + if err := storageTokenResponse.AccessToken.Validate(); err != nil { + return AuthResult{}, fmt.Errorf("problem with access token in StorageTokenResponse: %w", err) + } + + account := storageTokenResponse.Account + accessToken := storageTokenResponse.AccessToken.Secret + grantedScopes := strings.Split(storageTokenResponse.AccessToken.Scopes, scopeSeparator) + + // Checking if there was an ID token in the cache; this will throw an error in the case of confidential client applications. + var idToken accesstokens.IDToken + if !storageTokenResponse.IDToken.IsZero() { + err := idToken.UnmarshalJSON([]byte(storageTokenResponse.IDToken.Secret)) + if err != nil { + return AuthResult{}, fmt.Errorf("problem decoding JWT token: %w", err) + } + } + return AuthResult{account, idToken, accessToken, storageTokenResponse.AccessToken.ExpiresOn.T, grantedScopes, nil}, nil +} + +// NewAuthResult creates an AuthResult. +func NewAuthResult(tokenResponse accesstokens.TokenResponse, account shared.Account) (AuthResult, error) { + if len(tokenResponse.DeclinedScopes) > 0 { + return AuthResult{}, fmt.Errorf("token response failed because declined scopes are present: %s", strings.Join(tokenResponse.DeclinedScopes, ",")) + } + return AuthResult{ + Account: account, + IDToken: tokenResponse.IDToken, + AccessToken: tokenResponse.AccessToken, + ExpiresOn: tokenResponse.ExpiresOn.T, + GrantedScopes: tokenResponse.GrantedScopes.Slice, + }, nil +} + +// Client is a base client that provides access to common methods and primatives that +// can be used by multiple clients. +type Client struct { + Token *oauth.Client + manager manager // *storage.Manager or fakeManager in tests + pmanager partitionedManager // *storage.PartitionedManager or fakeManager in tests + + AuthParams authority.AuthParams // DO NOT EVER MAKE THIS A POINTER! See "Note" in New(). + cacheAccessor cache.ExportReplace +} + +// Option is an optional argument to the New constructor. +type Option func(c *Client) error + +// WithCacheAccessor allows you to set some type of cache for storing authentication tokens. +func WithCacheAccessor(ca cache.ExportReplace) Option { + return func(c *Client) error { + if ca != nil { + c.cacheAccessor = ca + } + return nil + } +} + +// WithClientCapabilities allows configuring one or more client capabilities such as "CP1" +func WithClientCapabilities(capabilities []string) Option { + return func(c *Client) error { + var err error + if len(capabilities) > 0 { + cc, err := authority.NewClientCapabilities(capabilities) + if err == nil { + c.AuthParams.Capabilities = cc + } + } + return err + } +} + +// WithKnownAuthorityHosts specifies hosts Client shouldn't validate or request metadata for because they're known to the user +func WithKnownAuthorityHosts(hosts []string) Option { + return func(c *Client) error { + cp := make([]string, len(hosts)) + copy(cp, hosts) + c.AuthParams.KnownAuthorityHosts = cp + return nil + } +} + +// WithX5C specifies if x5c claim(public key of the certificate) should be sent to STS to enable Subject Name Issuer Authentication. +func WithX5C(sendX5C bool) Option { + return func(c *Client) error { + c.AuthParams.SendX5C = sendX5C + return nil + } +} + +func WithRegionDetection(region string) Option { + return func(c *Client) error { + c.AuthParams.AuthorityInfo.Region = region + return nil + } +} + +func WithInstanceDiscovery(instanceDiscoveryEnabled bool) Option { + return func(c *Client) error { + c.AuthParams.AuthorityInfo.ValidateAuthority = instanceDiscoveryEnabled + c.AuthParams.AuthorityInfo.InstanceDiscoveryDisabled = !instanceDiscoveryEnabled + return nil + } +} + +// New is the constructor for Base. +func New(clientID string, authorityURI string, token *oauth.Client, options ...Option) (Client, error) { + //By default, validateAuthority is set to true and instanceDiscoveryDisabled is set to false + authInfo, err := authority.NewInfoFromAuthorityURI(authorityURI, true, false) + if err != nil { + return Client{}, err + } + authParams := authority.NewAuthParams(clientID, authInfo) + client := Client{ // Note: Hey, don't even THINK about making Base into *Base. See "design notes" in public.go and confidential.go + Token: token, + AuthParams: authParams, + cacheAccessor: noopCacheAccessor{}, + manager: storage.New(token), + pmanager: storage.NewPartitionedManager(token), + } + for _, o := range options { + if err = o(&client); err != nil { + break + } + } + return client, err + +} + +// AuthCodeURL creates a URL used to acquire an authorization code. +func (b Client) AuthCodeURL(ctx context.Context, clientID, redirectURI string, scopes []string, authParams authority.AuthParams) (string, error) { + endpoints, err := b.Token.ResolveEndpoints(ctx, authParams.AuthorityInfo, "") + if err != nil { + return "", err + } + + baseURL, err := url.Parse(endpoints.AuthorizationEndpoint) + if err != nil { + return "", err + } + + claims, err := authParams.MergeCapabilitiesAndClaims() + if err != nil { + return "", err + } + + v := url.Values{} + v.Add("client_id", clientID) + v.Add("response_type", "code") + v.Add("redirect_uri", redirectURI) + v.Add("scope", strings.Join(scopes, scopeSeparator)) + if authParams.State != "" { + v.Add("state", authParams.State) + } + if claims != "" { + v.Add("claims", claims) + } + if authParams.CodeChallenge != "" { + v.Add("code_challenge", authParams.CodeChallenge) + } + if authParams.CodeChallengeMethod != "" { + v.Add("code_challenge_method", authParams.CodeChallengeMethod) + } + if authParams.LoginHint != "" { + v.Add("login_hint", authParams.LoginHint) + } + if authParams.Prompt != "" { + v.Add("prompt", authParams.Prompt) + } + if authParams.DomainHint != "" { + v.Add("domain_hint", authParams.DomainHint) + } + // There were left over from an implementation that didn't use any of these. We may + // need to add them later, but as of now aren't needed. + /* + if p.ResponseMode != "" { + urlParams.Add("response_mode", p.ResponseMode) + } + */ + baseURL.RawQuery = v.Encode() + return baseURL.String(), nil +} + +func (b Client) AcquireTokenSilent(ctx context.Context, silent AcquireTokenSilentParameters) (AuthResult, error) { + // when tenant == "", the caller didn't specify a tenant and WithTenant will use the client's configured tenant + tenant := silent.TenantID + authParams, err := b.AuthParams.WithTenant(tenant) + if err != nil { + return AuthResult{}, err + } + authParams.Scopes = silent.Scopes + authParams.HomeAccountID = silent.Account.HomeAccountID + authParams.AuthorizationType = silent.AuthorizationType + authParams.Claims = silent.Claims + authParams.UserAssertion = silent.UserAssertion + + var storageTokenResponse storage.TokenResponse + if authParams.AuthorizationType == authority.ATOnBehalfOf { + if s, ok := b.pmanager.(cache.Serializer); ok { + suggestedCacheKey := authParams.CacheKey(silent.IsAppCache) + b.cacheAccessor.Replace(s, suggestedCacheKey) + defer b.cacheAccessor.Export(s, suggestedCacheKey) + } + storageTokenResponse, err = b.pmanager.Read(ctx, authParams) + if err != nil { + return AuthResult{}, err + } + } else { + if s, ok := b.manager.(cache.Serializer); ok { + suggestedCacheKey := authParams.CacheKey(silent.IsAppCache) + b.cacheAccessor.Replace(s, suggestedCacheKey) + defer b.cacheAccessor.Export(s, suggestedCacheKey) + } + authParams.AuthorizationType = authority.ATRefreshToken + storageTokenResponse, err = b.manager.Read(ctx, authParams, silent.Account) + if err != nil { + return AuthResult{}, err + } + } + + // ignore cached access tokens when given claims + if silent.Claims == "" { + result, err := AuthResultFromStorage(storageTokenResponse) + if err == nil { + return result, nil + } + } + + // redeem a cached refresh token, if available + if reflect.ValueOf(storageTokenResponse.RefreshToken).IsZero() { + return AuthResult{}, errors.New("no token found") + } + var cc *accesstokens.Credential + if silent.RequestType == accesstokens.ATConfidential { + cc = silent.Credential + } + + token, err := b.Token.Refresh(ctx, silent.RequestType, authParams, cc, storageTokenResponse.RefreshToken) + if err != nil { + return AuthResult{}, err + } + + return b.AuthResultFromToken(ctx, authParams, token, true) +} + +func (b Client) AcquireTokenByAuthCode(ctx context.Context, authCodeParams AcquireTokenAuthCodeParameters) (AuthResult, error) { + authParams, err := b.AuthParams.WithTenant(authCodeParams.TenantID) + if err != nil { + return AuthResult{}, err + } + authParams.Claims = authCodeParams.Claims + authParams.Scopes = authCodeParams.Scopes + authParams.Redirecturi = authCodeParams.RedirectURI + authParams.AuthorizationType = authority.ATAuthCode + + var cc *accesstokens.Credential + if authCodeParams.AppType == accesstokens.ATConfidential { + cc = authCodeParams.Credential + authParams.IsConfidentialClient = true + } + + req, err := accesstokens.NewCodeChallengeRequest(authParams, authCodeParams.AppType, cc, authCodeParams.Code, authCodeParams.Challenge) + if err != nil { + return AuthResult{}, err + } + + token, err := b.Token.AuthCode(ctx, req) + if err != nil { + return AuthResult{}, err + } + + return b.AuthResultFromToken(ctx, authParams, token, true) +} + +// AcquireTokenOnBehalfOf acquires a security token for an app using middle tier apps access token. +func (b Client) AcquireTokenOnBehalfOf(ctx context.Context, onBehalfOfParams AcquireTokenOnBehalfOfParameters) (AuthResult, error) { + var ar AuthResult + silentParameters := AcquireTokenSilentParameters{ + Scopes: onBehalfOfParams.Scopes, + RequestType: accesstokens.ATConfidential, + Credential: onBehalfOfParams.Credential, + UserAssertion: onBehalfOfParams.UserAssertion, + AuthorizationType: authority.ATOnBehalfOf, + TenantID: onBehalfOfParams.TenantID, + Claims: onBehalfOfParams.Claims, + } + ar, err := b.AcquireTokenSilent(ctx, silentParameters) + if err == nil { + return ar, err + } + authParams, err := b.AuthParams.WithTenant(onBehalfOfParams.TenantID) + if err != nil { + return AuthResult{}, err + } + authParams.AuthorizationType = authority.ATOnBehalfOf + authParams.Claims = onBehalfOfParams.Claims + authParams.Scopes = onBehalfOfParams.Scopes + authParams.UserAssertion = onBehalfOfParams.UserAssertion + token, err := b.Token.OnBehalfOf(ctx, authParams, onBehalfOfParams.Credential) + if err == nil { + ar, err = b.AuthResultFromToken(ctx, authParams, token, true) + } + return ar, err +} + +func (b Client) AuthResultFromToken(ctx context.Context, authParams authority.AuthParams, token accesstokens.TokenResponse, cacheWrite bool) (AuthResult, error) { + if !cacheWrite { + return NewAuthResult(token, shared.Account{}) + } + + var account shared.Account + var err error + if authParams.AuthorizationType == authority.ATOnBehalfOf { + if s, ok := b.pmanager.(cache.Serializer); ok { + suggestedCacheKey := token.CacheKey(authParams) + b.cacheAccessor.Replace(s, suggestedCacheKey) + defer b.cacheAccessor.Export(s, suggestedCacheKey) + } + account, err = b.pmanager.Write(authParams, token) + if err != nil { + return AuthResult{}, err + } + } else { + if s, ok := b.manager.(cache.Serializer); ok { + suggestedCacheKey := token.CacheKey(authParams) + b.cacheAccessor.Replace(s, suggestedCacheKey) + defer b.cacheAccessor.Export(s, suggestedCacheKey) + } + account, err = b.manager.Write(authParams, token) + if err != nil { + return AuthResult{}, err + } + } + return NewAuthResult(token, account) +} + +func (b Client) AllAccounts() []shared.Account { + if s, ok := b.manager.(cache.Serializer); ok { + suggestedCacheKey := b.AuthParams.CacheKey(false) + b.cacheAccessor.Replace(s, suggestedCacheKey) + defer b.cacheAccessor.Export(s, suggestedCacheKey) + } + + accounts := b.manager.AllAccounts() + return accounts +} + +func (b Client) Account(homeAccountID string) shared.Account { + authParams := b.AuthParams // This is a copy, as we dont' have a pointer receiver and .AuthParams is not a pointer. + authParams.AuthorizationType = authority.AccountByID + authParams.HomeAccountID = homeAccountID + if s, ok := b.manager.(cache.Serializer); ok { + suggestedCacheKey := b.AuthParams.CacheKey(false) + b.cacheAccessor.Replace(s, suggestedCacheKey) + defer b.cacheAccessor.Export(s, suggestedCacheKey) + } + account := b.manager.Account(homeAccountID) + return account +} + +// RemoveAccount removes all the ATs, RTs and IDTs from the cache associated with this account. +func (b Client) RemoveAccount(account shared.Account) { + if s, ok := b.manager.(cache.Serializer); ok { + suggestedCacheKey := b.AuthParams.CacheKey(false) + b.cacheAccessor.Replace(s, suggestedCacheKey) + defer b.cacheAccessor.Export(s, suggestedCacheKey) + } + b.manager.RemoveAccount(account, b.AuthParams.ClientID) +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/items.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/items.go new file mode 100644 index 00000000000..548c2faebf9 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/items.go @@ -0,0 +1,200 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package storage + +import ( + "errors" + "fmt" + "reflect" + "strings" + "time" + + internalTime "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/types/time" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/shared" +) + +// Contract is the JSON structure that is written to any storage medium when serializing +// the internal cache. This design is shared between MSAL versions in many languages. +// This cannot be changed without design that includes other SDKs. +type Contract struct { + AccessTokens map[string]AccessToken `json:"AccessToken,omitempty"` + RefreshTokens map[string]accesstokens.RefreshToken `json:"RefreshToken,omitempty"` + IDTokens map[string]IDToken `json:"IdToken,omitempty"` + Accounts map[string]shared.Account `json:"Account,omitempty"` + AppMetaData map[string]AppMetaData `json:"AppMetadata,omitempty"` + + AdditionalFields map[string]interface{} +} + +// Contract is the JSON structure that is written to any storage medium when serializing +// the internal cache. This design is shared between MSAL versions in many languages. +// This cannot be changed without design that includes other SDKs. +type InMemoryContract struct { + AccessTokensPartition map[string]map[string]AccessToken + RefreshTokensPartition map[string]map[string]accesstokens.RefreshToken + IDTokensPartition map[string]map[string]IDToken + AccountsPartition map[string]map[string]shared.Account + AppMetaData map[string]AppMetaData +} + +// NewContract is the constructor for Contract. +func NewInMemoryContract() *InMemoryContract { + return &InMemoryContract{ + AccessTokensPartition: map[string]map[string]AccessToken{}, + RefreshTokensPartition: map[string]map[string]accesstokens.RefreshToken{}, + IDTokensPartition: map[string]map[string]IDToken{}, + AccountsPartition: map[string]map[string]shared.Account{}, + AppMetaData: map[string]AppMetaData{}, + } +} + +// NewContract is the constructor for Contract. +func NewContract() *Contract { + return &Contract{ + AccessTokens: map[string]AccessToken{}, + RefreshTokens: map[string]accesstokens.RefreshToken{}, + IDTokens: map[string]IDToken{}, + Accounts: map[string]shared.Account{}, + AppMetaData: map[string]AppMetaData{}, + AdditionalFields: map[string]interface{}{}, + } +} + +// AccessToken is the JSON representation of a MSAL access token for encoding to storage. +type AccessToken struct { + HomeAccountID string `json:"home_account_id,omitempty"` + Environment string `json:"environment,omitempty"` + Realm string `json:"realm,omitempty"` + CredentialType string `json:"credential_type,omitempty"` + ClientID string `json:"client_id,omitempty"` + Secret string `json:"secret,omitempty"` + Scopes string `json:"target,omitempty"` + ExpiresOn internalTime.Unix `json:"expires_on,omitempty"` + ExtendedExpiresOn internalTime.Unix `json:"extended_expires_on,omitempty"` + CachedAt internalTime.Unix `json:"cached_at,omitempty"` + UserAssertionHash string `json:"user_assertion_hash,omitempty"` + + AdditionalFields map[string]interface{} +} + +// NewAccessToken is the constructor for AccessToken. +func NewAccessToken(homeID, env, realm, clientID string, cachedAt, expiresOn, extendedExpiresOn time.Time, scopes, token string) AccessToken { + return AccessToken{ + HomeAccountID: homeID, + Environment: env, + Realm: realm, + CredentialType: "AccessToken", + ClientID: clientID, + Secret: token, + Scopes: scopes, + CachedAt: internalTime.Unix{T: cachedAt.UTC()}, + ExpiresOn: internalTime.Unix{T: expiresOn.UTC()}, + ExtendedExpiresOn: internalTime.Unix{T: extendedExpiresOn.UTC()}, + } +} + +// Key outputs the key that can be used to uniquely look up this entry in a map. +func (a AccessToken) Key() string { + return strings.Join( + []string{a.HomeAccountID, a.Environment, a.CredentialType, a.ClientID, a.Realm, a.Scopes}, + shared.CacheKeySeparator, + ) +} + +// FakeValidate enables tests to fake access token validation +var FakeValidate func(AccessToken) error + +// Validate validates that this AccessToken can be used. +func (a AccessToken) Validate() error { + if FakeValidate != nil { + return FakeValidate(a) + } + if a.CachedAt.T.After(time.Now()) { + return errors.New("access token isn't valid, it was cached at a future time") + } + if a.ExpiresOn.T.Before(time.Now().Add(5 * time.Minute)) { + return fmt.Errorf("access token is expired") + } + if a.CachedAt.T.IsZero() { + return fmt.Errorf("access token does not have CachedAt set") + } + return nil +} + +// IDToken is the JSON representation of an MSAL id token for encoding to storage. +type IDToken struct { + HomeAccountID string `json:"home_account_id,omitempty"` + Environment string `json:"environment,omitempty"` + Realm string `json:"realm,omitempty"` + CredentialType string `json:"credential_type,omitempty"` + ClientID string `json:"client_id,omitempty"` + Secret string `json:"secret,omitempty"` + UserAssertionHash string `json:"user_assertion_hash,omitempty"` + AdditionalFields map[string]interface{} +} + +// IsZero determines if IDToken is the zero value. +func (i IDToken) IsZero() bool { + v := reflect.ValueOf(i) + for i := 0; i < v.NumField(); i++ { + field := v.Field(i) + if !field.IsZero() { + switch field.Kind() { + case reflect.Map, reflect.Slice: + if field.Len() == 0 { + continue + } + } + return false + } + } + return true +} + +// NewIDToken is the constructor for IDToken. +func NewIDToken(homeID, env, realm, clientID, idToken string) IDToken { + return IDToken{ + HomeAccountID: homeID, + Environment: env, + Realm: realm, + CredentialType: "IDToken", + ClientID: clientID, + Secret: idToken, + } +} + +// Key outputs the key that can be used to uniquely look up this entry in a map. +func (id IDToken) Key() string { + return strings.Join( + []string{id.HomeAccountID, id.Environment, id.CredentialType, id.ClientID, id.Realm}, + shared.CacheKeySeparator, + ) +} + +// AppMetaData is the JSON representation of application metadata for encoding to storage. +type AppMetaData struct { + FamilyID string `json:"family_id,omitempty"` + ClientID string `json:"client_id,omitempty"` + Environment string `json:"environment,omitempty"` + + AdditionalFields map[string]interface{} +} + +// NewAppMetaData is the constructor for AppMetaData. +func NewAppMetaData(familyID, clientID, environment string) AppMetaData { + return AppMetaData{ + FamilyID: familyID, + ClientID: clientID, + Environment: environment, + } +} + +// Key outputs the key that can be used to uniquely look up this entry in a map. +func (a AppMetaData) Key() string { + return strings.Join( + []string{"AppMetaData", a.Environment, a.ClientID}, + shared.CacheKeySeparator, + ) +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/partitioned_storage.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/partitioned_storage.go new file mode 100644 index 00000000000..87d7d797b3e --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/partitioned_storage.go @@ -0,0 +1,436 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package storage + +import ( + "context" + "errors" + "fmt" + "strings" + "sync" + "time" + + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/shared" +) + +// PartitionedManager is a partitioned in-memory cache of access tokens, accounts and meta data. +type PartitionedManager struct { + contract *InMemoryContract + contractMu sync.RWMutex + requests aadInstanceDiscoveryer // *oauth.Token + + aadCacheMu sync.RWMutex + aadCache map[string]authority.InstanceDiscoveryMetadata +} + +// NewPartitionedManager is the constructor for PartitionedManager. +func NewPartitionedManager(requests *oauth.Client) *PartitionedManager { + m := &PartitionedManager{requests: requests, aadCache: make(map[string]authority.InstanceDiscoveryMetadata)} + m.contract = NewInMemoryContract() + return m +} + +// Read reads a storage token from the cache if it exists. +func (m *PartitionedManager) Read(ctx context.Context, authParameters authority.AuthParams) (TokenResponse, error) { + tr := TokenResponse{} + realm := authParameters.AuthorityInfo.Tenant + clientID := authParameters.ClientID + scopes := authParameters.Scopes + + // fetch metadata if instanceDiscovery is enabled + aliases := []string{authParameters.AuthorityInfo.Host} + if !authParameters.AuthorityInfo.InstanceDiscoveryDisabled { + metadata, err := m.getMetadataEntry(ctx, authParameters.AuthorityInfo) + if err != nil { + return TokenResponse{}, err + } + aliases = metadata.Aliases + } + + userAssertionHash := authParameters.AssertionHash() + partitionKeyFromRequest := userAssertionHash + + // errors returned by read* methods indicate a cache miss and are therefore non-fatal. We continue populating + // TokenResponse fields so that e.g. lack of an ID token doesn't prevent the caller from receiving a refresh token. + accessToken, err := m.readAccessToken(aliases, realm, clientID, userAssertionHash, scopes, partitionKeyFromRequest) + if err == nil { + tr.AccessToken = accessToken + } + idToken, err := m.readIDToken(aliases, realm, clientID, userAssertionHash, getPartitionKeyIDTokenRead(accessToken)) + if err == nil { + tr.IDToken = idToken + } + + if appMetadata, err := m.readAppMetaData(aliases, clientID); err == nil { + // we need the family ID to identify the correct refresh token, if any + familyID := appMetadata.FamilyID + refreshToken, err := m.readRefreshToken(aliases, familyID, clientID, userAssertionHash, partitionKeyFromRequest) + if err == nil { + tr.RefreshToken = refreshToken + } + } + + account, err := m.readAccount(aliases, realm, userAssertionHash, idToken.HomeAccountID) + if err == nil { + tr.Account = account + } + return tr, nil +} + +// Write writes a token response to the cache and returns the account information the token is stored with. +func (m *PartitionedManager) Write(authParameters authority.AuthParams, tokenResponse accesstokens.TokenResponse) (shared.Account, error) { + authParameters.HomeAccountID = tokenResponse.ClientInfo.HomeAccountID() + homeAccountID := authParameters.HomeAccountID + environment := authParameters.AuthorityInfo.Host + realm := authParameters.AuthorityInfo.Tenant + clientID := authParameters.ClientID + target := strings.Join(tokenResponse.GrantedScopes.Slice, scopeSeparator) + userAssertionHash := authParameters.AssertionHash() + cachedAt := time.Now() + + var account shared.Account + + if len(tokenResponse.RefreshToken) > 0 { + refreshToken := accesstokens.NewRefreshToken(homeAccountID, environment, clientID, tokenResponse.RefreshToken, tokenResponse.FamilyID) + if authParameters.AuthorizationType == authority.ATOnBehalfOf { + refreshToken.UserAssertionHash = userAssertionHash + } + if err := m.writeRefreshToken(refreshToken, getPartitionKeyRefreshToken(refreshToken)); err != nil { + return account, err + } + } + + if len(tokenResponse.AccessToken) > 0 { + accessToken := NewAccessToken( + homeAccountID, + environment, + realm, + clientID, + cachedAt, + tokenResponse.ExpiresOn.T, + tokenResponse.ExtExpiresOn.T, + target, + tokenResponse.AccessToken, + ) + if authParameters.AuthorizationType == authority.ATOnBehalfOf { + accessToken.UserAssertionHash = userAssertionHash // get Hash method on this + } + + // Since we have a valid access token, cache it before moving on. + if err := accessToken.Validate(); err == nil { + if err := m.writeAccessToken(accessToken, getPartitionKeyAccessToken(accessToken)); err != nil { + return account, err + } + } else { + return shared.Account{}, err + } + } + + idTokenJwt := tokenResponse.IDToken + if !idTokenJwt.IsZero() { + idToken := NewIDToken(homeAccountID, environment, realm, clientID, idTokenJwt.RawToken) + if authParameters.AuthorizationType == authority.ATOnBehalfOf { + idToken.UserAssertionHash = userAssertionHash + } + if err := m.writeIDToken(idToken, getPartitionKeyIDToken(idToken)); err != nil { + return shared.Account{}, err + } + + localAccountID := idTokenJwt.LocalAccountID() + authorityType := authParameters.AuthorityInfo.AuthorityType + + preferredUsername := idTokenJwt.UPN + if idTokenJwt.PreferredUsername != "" { + preferredUsername = idTokenJwt.PreferredUsername + } + + account = shared.NewAccount( + homeAccountID, + environment, + realm, + localAccountID, + authorityType, + preferredUsername, + ) + if authParameters.AuthorizationType == authority.ATOnBehalfOf { + account.UserAssertionHash = userAssertionHash + } + if err := m.writeAccount(account, getPartitionKeyAccount(account)); err != nil { + return shared.Account{}, err + } + } + + AppMetaData := NewAppMetaData(tokenResponse.FamilyID, clientID, environment) + + if err := m.writeAppMetaData(AppMetaData); err != nil { + return shared.Account{}, err + } + return account, nil +} + +func (m *PartitionedManager) getMetadataEntry(ctx context.Context, authorityInfo authority.Info) (authority.InstanceDiscoveryMetadata, error) { + md, err := m.aadMetadataFromCache(ctx, authorityInfo) + if err != nil { + // not in the cache, retrieve it + md, err = m.aadMetadata(ctx, authorityInfo) + } + return md, err +} + +func (m *PartitionedManager) aadMetadataFromCache(ctx context.Context, authorityInfo authority.Info) (authority.InstanceDiscoveryMetadata, error) { + m.aadCacheMu.RLock() + defer m.aadCacheMu.RUnlock() + metadata, ok := m.aadCache[authorityInfo.Host] + if ok { + return metadata, nil + } + return metadata, errors.New("not found") +} + +func (m *PartitionedManager) aadMetadata(ctx context.Context, authorityInfo authority.Info) (authority.InstanceDiscoveryMetadata, error) { + discoveryResponse, err := m.requests.AADInstanceDiscovery(ctx, authorityInfo) + if err != nil { + return authority.InstanceDiscoveryMetadata{}, err + } + + m.aadCacheMu.Lock() + defer m.aadCacheMu.Unlock() + + for _, metadataEntry := range discoveryResponse.Metadata { + for _, aliasedAuthority := range metadataEntry.Aliases { + m.aadCache[aliasedAuthority] = metadataEntry + } + } + if _, ok := m.aadCache[authorityInfo.Host]; !ok { + m.aadCache[authorityInfo.Host] = authority.InstanceDiscoveryMetadata{ + PreferredNetwork: authorityInfo.Host, + PreferredCache: authorityInfo.Host, + } + } + return m.aadCache[authorityInfo.Host], nil +} + +func (m *PartitionedManager) readAccessToken(envAliases []string, realm, clientID, userAssertionHash string, scopes []string, partitionKey string) (AccessToken, error) { + m.contractMu.RLock() + defer m.contractMu.RUnlock() + if accessTokens, ok := m.contract.AccessTokensPartition[partitionKey]; ok { + // TODO: linear search (over a map no less) is slow for a large number (thousands) of tokens. + // this shows up as the dominating node in a profile. for real-world scenarios this likely isn't + // an issue, however if it does become a problem then we know where to look. + for _, at := range accessTokens { + if at.Realm == realm && at.ClientID == clientID && at.UserAssertionHash == userAssertionHash { + if checkAlias(at.Environment, envAliases) { + if isMatchingScopes(scopes, at.Scopes) { + return at, nil + } + } + } + } + } + return AccessToken{}, fmt.Errorf("access token not found") +} + +func (m *PartitionedManager) writeAccessToken(accessToken AccessToken, partitionKey string) error { + m.contractMu.Lock() + defer m.contractMu.Unlock() + key := accessToken.Key() + if m.contract.AccessTokensPartition[partitionKey] == nil { + m.contract.AccessTokensPartition[partitionKey] = make(map[string]AccessToken) + } + m.contract.AccessTokensPartition[partitionKey][key] = accessToken + return nil +} + +func matchFamilyRefreshTokenObo(rt accesstokens.RefreshToken, userAssertionHash string, envAliases []string) bool { + return rt.UserAssertionHash == userAssertionHash && checkAlias(rt.Environment, envAliases) && rt.FamilyID != "" +} + +func matchClientIDRefreshTokenObo(rt accesstokens.RefreshToken, userAssertionHash string, envAliases []string, clientID string) bool { + return rt.UserAssertionHash == userAssertionHash && checkAlias(rt.Environment, envAliases) && rt.ClientID == clientID +} + +func (m *PartitionedManager) readRefreshToken(envAliases []string, familyID, clientID, userAssertionHash, partitionKey string) (accesstokens.RefreshToken, error) { + byFamily := func(rt accesstokens.RefreshToken) bool { + return matchFamilyRefreshTokenObo(rt, userAssertionHash, envAliases) + } + byClient := func(rt accesstokens.RefreshToken) bool { + return matchClientIDRefreshTokenObo(rt, userAssertionHash, envAliases, clientID) + } + + var matchers []func(rt accesstokens.RefreshToken) bool + if familyID == "" { + matchers = []func(rt accesstokens.RefreshToken) bool{ + byClient, byFamily, + } + } else { + matchers = []func(rt accesstokens.RefreshToken) bool{ + byFamily, byClient, + } + } + + // TODO(keegan): All the tests here pass, but Bogdan says this is + // more complicated. I'm opening an issue for this to have him + // review the tests and suggest tests that would break this so + // we can re-write against good tests. His comments as follow: + // The algorithm is a bit more complex than this, I assume there are some tests covering everything. I would keep the order as is. + // The algorithm is: + // If application is NOT part of the family, search by client_ID + // If app is part of the family or if we DO NOT KNOW if it's part of the family, search by family ID, then by client_id (we will know if an app is part of the family after the first token response). + // https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/blob/311fe8b16e7c293462806f397e189a6aa1159769/src/client/Microsoft.Identity.Client/Internal/Requests/Silent/CacheSilentStrategy.cs#L95 + m.contractMu.RLock() + defer m.contractMu.RUnlock() + for _, matcher := range matchers { + for _, rt := range m.contract.RefreshTokensPartition[partitionKey] { + if matcher(rt) { + return rt, nil + } + } + } + + return accesstokens.RefreshToken{}, fmt.Errorf("refresh token not found") +} + +func (m *PartitionedManager) writeRefreshToken(refreshToken accesstokens.RefreshToken, partitionKey string) error { + m.contractMu.Lock() + defer m.contractMu.Unlock() + key := refreshToken.Key() + if m.contract.AccessTokensPartition[partitionKey] == nil { + m.contract.RefreshTokensPartition[partitionKey] = make(map[string]accesstokens.RefreshToken) + } + m.contract.RefreshTokensPartition[partitionKey][key] = refreshToken + return nil +} + +func (m *PartitionedManager) readIDToken(envAliases []string, realm, clientID, userAssertionHash, partitionKey string) (IDToken, error) { + m.contractMu.RLock() + defer m.contractMu.RUnlock() + for _, idt := range m.contract.IDTokensPartition[partitionKey] { + if idt.Realm == realm && idt.ClientID == clientID && idt.UserAssertionHash == userAssertionHash { + if checkAlias(idt.Environment, envAliases) { + return idt, nil + } + } + } + return IDToken{}, fmt.Errorf("token not found") +} + +func (m *PartitionedManager) writeIDToken(idToken IDToken, partitionKey string) error { + key := idToken.Key() + m.contractMu.Lock() + defer m.contractMu.Unlock() + if m.contract.IDTokensPartition[partitionKey] == nil { + m.contract.IDTokensPartition[partitionKey] = make(map[string]IDToken) + } + m.contract.IDTokensPartition[partitionKey][key] = idToken + return nil +} + +func (m *PartitionedManager) readAccount(envAliases []string, realm, UserAssertionHash, partitionKey string) (shared.Account, error) { + m.contractMu.RLock() + defer m.contractMu.RUnlock() + + // You might ask why, if cache.Accounts is a map, we would loop through all of these instead of using a key. + // We only use a map because the storage contract shared between all language implementations says use a map. + // We can't change that. The other is because the keys are made using a specific "env", but here we are allowing + // a match in multiple envs (envAlias). That means we either need to hash each possible keyand do the lookup + // or just statically check. Since the design is to have a storage.Manager per user, the amount of keys stored + // is really low (say 2). Each hash is more expensive than the entire iteration. + for _, acc := range m.contract.AccountsPartition[partitionKey] { + if checkAlias(acc.Environment, envAliases) && acc.UserAssertionHash == UserAssertionHash && acc.Realm == realm { + return acc, nil + } + } + return shared.Account{}, fmt.Errorf("account not found") +} + +func (m *PartitionedManager) writeAccount(account shared.Account, partitionKey string) error { + key := account.Key() + m.contractMu.Lock() + defer m.contractMu.Unlock() + if m.contract.AccountsPartition[partitionKey] == nil { + m.contract.AccountsPartition[partitionKey] = make(map[string]shared.Account) + } + m.contract.AccountsPartition[partitionKey][key] = account + return nil +} + +func (m *PartitionedManager) readAppMetaData(envAliases []string, clientID string) (AppMetaData, error) { + m.contractMu.RLock() + defer m.contractMu.RUnlock() + + for _, app := range m.contract.AppMetaData { + if checkAlias(app.Environment, envAliases) && app.ClientID == clientID { + return app, nil + } + } + return AppMetaData{}, fmt.Errorf("not found") +} + +func (m *PartitionedManager) writeAppMetaData(AppMetaData AppMetaData) error { + key := AppMetaData.Key() + m.contractMu.Lock() + defer m.contractMu.Unlock() + m.contract.AppMetaData[key] = AppMetaData + return nil +} + +// update updates the internal cache object. This is for use in tests, other uses are not +// supported. +func (m *PartitionedManager) update(cache *InMemoryContract) { + m.contractMu.Lock() + defer m.contractMu.Unlock() + m.contract = cache +} + +// Marshal implements cache.Marshaler. +func (m *PartitionedManager) Marshal() ([]byte, error) { + return json.Marshal(m.contract) +} + +// Unmarshal implements cache.Unmarshaler. +func (m *PartitionedManager) Unmarshal(b []byte) error { + m.contractMu.Lock() + defer m.contractMu.Unlock() + + contract := NewInMemoryContract() + + err := json.Unmarshal(b, contract) + if err != nil { + return err + } + + m.contract = contract + + return nil +} + +func getPartitionKeyAccessToken(item AccessToken) string { + if item.UserAssertionHash != "" { + return item.UserAssertionHash + } + return item.HomeAccountID +} + +func getPartitionKeyRefreshToken(item accesstokens.RefreshToken) string { + if item.UserAssertionHash != "" { + return item.UserAssertionHash + } + return item.HomeAccountID +} + +func getPartitionKeyIDToken(item IDToken) string { + return item.HomeAccountID +} + +func getPartitionKeyAccount(item shared.Account) string { + return item.HomeAccountID +} + +func getPartitionKeyIDTokenRead(item AccessToken) string { + return item.HomeAccountID +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/storage.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/storage.go new file mode 100644 index 00000000000..1c0471bb980 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/storage.go @@ -0,0 +1,514 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +// Package storage holds all cached token information for MSAL. This storage can be +// augmented with third-party extensions to provide persistent storage. In that case, +// reads and writes in upper packages will call Marshal() to take the entire in-memory +// representation and write it to storage and Unmarshal() to update the entire in-memory +// storage with what was in the persistent storage. The persistent storage can only be +// accessed in this way because multiple MSAL clients written in multiple languages can +// access the same storage and must adhere to the same method that was defined +// previously. +package storage + +import ( + "context" + "errors" + "fmt" + "strings" + "sync" + "time" + + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/shared" +) + +// aadInstanceDiscoveryer allows faking in tests. +// It is implemented in production by ops/authority.Client +type aadInstanceDiscoveryer interface { + AADInstanceDiscovery(ctx context.Context, authorityInfo authority.Info) (authority.InstanceDiscoveryResponse, error) +} + +// TokenResponse mimics a token response that was pulled from the cache. +type TokenResponse struct { + RefreshToken accesstokens.RefreshToken + IDToken IDToken // *Credential + AccessToken AccessToken + Account shared.Account +} + +// Manager is an in-memory cache of access tokens, accounts and meta data. This data is +// updated on read/write calls. Unmarshal() replaces all data stored here with whatever +// was given to it on each call. +type Manager struct { + contract *Contract + contractMu sync.RWMutex + requests aadInstanceDiscoveryer // *oauth.Token + + aadCacheMu sync.RWMutex + aadCache map[string]authority.InstanceDiscoveryMetadata +} + +// New is the constructor for Manager. +func New(requests *oauth.Client) *Manager { + m := &Manager{requests: requests, aadCache: make(map[string]authority.InstanceDiscoveryMetadata)} + m.contract = NewContract() + return m +} + +func checkAlias(alias string, aliases []string) bool { + for _, v := range aliases { + if alias == v { + return true + } + } + return false +} + +func isMatchingScopes(scopesOne []string, scopesTwo string) bool { + newScopesTwo := strings.Split(scopesTwo, scopeSeparator) + scopeCounter := 0 + for _, scope := range scopesOne { + for _, otherScope := range newScopesTwo { + if strings.EqualFold(scope, otherScope) { + scopeCounter++ + continue + } + } + } + return scopeCounter == len(scopesOne) +} + +// Read reads a storage token from the cache if it exists. +func (m *Manager) Read(ctx context.Context, authParameters authority.AuthParams, account shared.Account) (TokenResponse, error) { + tr := TokenResponse{} + homeAccountID := authParameters.HomeAccountID + realm := authParameters.AuthorityInfo.Tenant + clientID := authParameters.ClientID + scopes := authParameters.Scopes + + // fetch metadata if instanceDiscovery is enabled + aliases := []string{authParameters.AuthorityInfo.Host} + if !authParameters.AuthorityInfo.InstanceDiscoveryDisabled { + metadata, err := m.getMetadataEntry(ctx, authParameters.AuthorityInfo) + if err != nil { + return TokenResponse{}, err + } + aliases = metadata.Aliases + } + + accessToken := m.readAccessToken(homeAccountID, aliases, realm, clientID, scopes) + tr.AccessToken = accessToken + + if account.IsZero() { + return tr, nil + } + // errors returned by read* methods indicate a cache miss and are therefore non-fatal. We continue populating + // TokenResponse fields so that e.g. lack of an ID token doesn't prevent the caller from receiving a refresh token. + idToken, err := m.readIDToken(homeAccountID, aliases, realm, clientID) + if err == nil { + tr.IDToken = idToken + } + + if appMetadata, err := m.readAppMetaData(aliases, clientID); err == nil { + // we need the family ID to identify the correct refresh token, if any + familyID := appMetadata.FamilyID + refreshToken, err := m.readRefreshToken(homeAccountID, aliases, familyID, clientID) + if err == nil { + tr.RefreshToken = refreshToken + } + } + + account, err = m.readAccount(homeAccountID, aliases, realm) + if err == nil { + tr.Account = account + } + return tr, nil +} + +const scopeSeparator = " " + +// Write writes a token response to the cache and returns the account information the token is stored with. +func (m *Manager) Write(authParameters authority.AuthParams, tokenResponse accesstokens.TokenResponse) (shared.Account, error) { + authParameters.HomeAccountID = tokenResponse.ClientInfo.HomeAccountID() + homeAccountID := authParameters.HomeAccountID + environment := authParameters.AuthorityInfo.Host + realm := authParameters.AuthorityInfo.Tenant + clientID := authParameters.ClientID + target := strings.Join(tokenResponse.GrantedScopes.Slice, scopeSeparator) + cachedAt := time.Now() + + var account shared.Account + + if len(tokenResponse.RefreshToken) > 0 { + refreshToken := accesstokens.NewRefreshToken(homeAccountID, environment, clientID, tokenResponse.RefreshToken, tokenResponse.FamilyID) + if err := m.writeRefreshToken(refreshToken); err != nil { + return account, err + } + } + + if len(tokenResponse.AccessToken) > 0 { + accessToken := NewAccessToken( + homeAccountID, + environment, + realm, + clientID, + cachedAt, + tokenResponse.ExpiresOn.T, + tokenResponse.ExtExpiresOn.T, + target, + tokenResponse.AccessToken, + ) + + // Since we have a valid access token, cache it before moving on. + if err := accessToken.Validate(); err == nil { + if err := m.writeAccessToken(accessToken); err != nil { + return account, err + } + } + } + + idTokenJwt := tokenResponse.IDToken + if !idTokenJwt.IsZero() { + idToken := NewIDToken(homeAccountID, environment, realm, clientID, idTokenJwt.RawToken) + if err := m.writeIDToken(idToken); err != nil { + return shared.Account{}, err + } + + localAccountID := idTokenJwt.LocalAccountID() + authorityType := authParameters.AuthorityInfo.AuthorityType + + preferredUsername := idTokenJwt.UPN + if idTokenJwt.PreferredUsername != "" { + preferredUsername = idTokenJwt.PreferredUsername + } + + account = shared.NewAccount( + homeAccountID, + environment, + realm, + localAccountID, + authorityType, + preferredUsername, + ) + if err := m.writeAccount(account); err != nil { + return shared.Account{}, err + } + } + + AppMetaData := NewAppMetaData(tokenResponse.FamilyID, clientID, environment) + + if err := m.writeAppMetaData(AppMetaData); err != nil { + return shared.Account{}, err + } + return account, nil +} + +func (m *Manager) getMetadataEntry(ctx context.Context, authorityInfo authority.Info) (authority.InstanceDiscoveryMetadata, error) { + md, err := m.aadMetadataFromCache(ctx, authorityInfo) + if err != nil { + // not in the cache, retrieve it + md, err = m.aadMetadata(ctx, authorityInfo) + } + return md, err +} + +func (m *Manager) aadMetadataFromCache(ctx context.Context, authorityInfo authority.Info) (authority.InstanceDiscoveryMetadata, error) { + m.aadCacheMu.RLock() + defer m.aadCacheMu.RUnlock() + metadata, ok := m.aadCache[authorityInfo.Host] + if ok { + return metadata, nil + } + return metadata, errors.New("not found") +} + +func (m *Manager) aadMetadata(ctx context.Context, authorityInfo authority.Info) (authority.InstanceDiscoveryMetadata, error) { + m.aadCacheMu.Lock() + defer m.aadCacheMu.Unlock() + discoveryResponse, err := m.requests.AADInstanceDiscovery(ctx, authorityInfo) + if err != nil { + return authority.InstanceDiscoveryMetadata{}, err + } + + for _, metadataEntry := range discoveryResponse.Metadata { + for _, aliasedAuthority := range metadataEntry.Aliases { + m.aadCache[aliasedAuthority] = metadataEntry + } + } + if _, ok := m.aadCache[authorityInfo.Host]; !ok { + m.aadCache[authorityInfo.Host] = authority.InstanceDiscoveryMetadata{ + PreferredNetwork: authorityInfo.Host, + PreferredCache: authorityInfo.Host, + } + } + return m.aadCache[authorityInfo.Host], nil +} + +func (m *Manager) readAccessToken(homeID string, envAliases []string, realm, clientID string, scopes []string) AccessToken { + m.contractMu.RLock() + defer m.contractMu.RUnlock() + // TODO: linear search (over a map no less) is slow for a large number (thousands) of tokens. + // this shows up as the dominating node in a profile. for real-world scenarios this likely isn't + // an issue, however if it does become a problem then we know where to look. + for _, at := range m.contract.AccessTokens { + if at.HomeAccountID == homeID && at.Realm == realm && at.ClientID == clientID { + if checkAlias(at.Environment, envAliases) { + if isMatchingScopes(scopes, at.Scopes) { + return at + } + } + } + } + return AccessToken{} +} + +func (m *Manager) writeAccessToken(accessToken AccessToken) error { + m.contractMu.Lock() + defer m.contractMu.Unlock() + key := accessToken.Key() + m.contract.AccessTokens[key] = accessToken + return nil +} + +func (m *Manager) readRefreshToken(homeID string, envAliases []string, familyID, clientID string) (accesstokens.RefreshToken, error) { + byFamily := func(rt accesstokens.RefreshToken) bool { + return matchFamilyRefreshToken(rt, homeID, envAliases) + } + byClient := func(rt accesstokens.RefreshToken) bool { + return matchClientIDRefreshToken(rt, homeID, envAliases, clientID) + } + + var matchers []func(rt accesstokens.RefreshToken) bool + if familyID == "" { + matchers = []func(rt accesstokens.RefreshToken) bool{ + byClient, byFamily, + } + } else { + matchers = []func(rt accesstokens.RefreshToken) bool{ + byFamily, byClient, + } + } + + // TODO(keegan): All the tests here pass, but Bogdan says this is + // more complicated. I'm opening an issue for this to have him + // review the tests and suggest tests that would break this so + // we can re-write against good tests. His comments as follow: + // The algorithm is a bit more complex than this, I assume there are some tests covering everything. I would keep the order as is. + // The algorithm is: + // If application is NOT part of the family, search by client_ID + // If app is part of the family or if we DO NOT KNOW if it's part of the family, search by family ID, then by client_id (we will know if an app is part of the family after the first token response). + // https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/blob/311fe8b16e7c293462806f397e189a6aa1159769/src/client/Microsoft.Identity.Client/Internal/Requests/Silent/CacheSilentStrategy.cs#L95 + m.contractMu.RLock() + defer m.contractMu.RUnlock() + for _, matcher := range matchers { + for _, rt := range m.contract.RefreshTokens { + if matcher(rt) { + return rt, nil + } + } + } + + return accesstokens.RefreshToken{}, fmt.Errorf("refresh token not found") +} + +func matchFamilyRefreshToken(rt accesstokens.RefreshToken, homeID string, envAliases []string) bool { + return rt.HomeAccountID == homeID && checkAlias(rt.Environment, envAliases) && rt.FamilyID != "" +} + +func matchClientIDRefreshToken(rt accesstokens.RefreshToken, homeID string, envAliases []string, clientID string) bool { + return rt.HomeAccountID == homeID && checkAlias(rt.Environment, envAliases) && rt.ClientID == clientID +} + +func (m *Manager) writeRefreshToken(refreshToken accesstokens.RefreshToken) error { + key := refreshToken.Key() + m.contractMu.Lock() + defer m.contractMu.Unlock() + m.contract.RefreshTokens[key] = refreshToken + return nil +} + +func (m *Manager) readIDToken(homeID string, envAliases []string, realm, clientID string) (IDToken, error) { + m.contractMu.RLock() + defer m.contractMu.RUnlock() + for _, idt := range m.contract.IDTokens { + if idt.HomeAccountID == homeID && idt.Realm == realm && idt.ClientID == clientID { + if checkAlias(idt.Environment, envAliases) { + return idt, nil + } + } + } + return IDToken{}, fmt.Errorf("token not found") +} + +func (m *Manager) writeIDToken(idToken IDToken) error { + key := idToken.Key() + m.contractMu.Lock() + defer m.contractMu.Unlock() + m.contract.IDTokens[key] = idToken + return nil +} + +func (m *Manager) AllAccounts() []shared.Account { + m.contractMu.RLock() + defer m.contractMu.RUnlock() + + var accounts []shared.Account + for _, v := range m.contract.Accounts { + accounts = append(accounts, v) + } + + return accounts +} + +func (m *Manager) Account(homeAccountID string) shared.Account { + m.contractMu.RLock() + defer m.contractMu.RUnlock() + + for _, v := range m.contract.Accounts { + if v.HomeAccountID == homeAccountID { + return v + } + } + + return shared.Account{} +} + +func (m *Manager) readAccount(homeAccountID string, envAliases []string, realm string) (shared.Account, error) { + m.contractMu.RLock() + defer m.contractMu.RUnlock() + + // You might ask why, if cache.Accounts is a map, we would loop through all of these instead of using a key. + // We only use a map because the storage contract shared between all language implementations says use a map. + // We can't change that. The other is because the keys are made using a specific "env", but here we are allowing + // a match in multiple envs (envAlias). That means we either need to hash each possible keyand do the lookup + // or just statically check. Since the design is to have a storage.Manager per user, the amount of keys stored + // is really low (say 2). Each hash is more expensive than the entire iteration. + for _, acc := range m.contract.Accounts { + if acc.HomeAccountID == homeAccountID && checkAlias(acc.Environment, envAliases) && acc.Realm == realm { + return acc, nil + } + } + return shared.Account{}, fmt.Errorf("account not found") +} + +func (m *Manager) writeAccount(account shared.Account) error { + key := account.Key() + m.contractMu.Lock() + defer m.contractMu.Unlock() + m.contract.Accounts[key] = account + return nil +} + +func (m *Manager) readAppMetaData(envAliases []string, clientID string) (AppMetaData, error) { + m.contractMu.RLock() + defer m.contractMu.RUnlock() + + for _, app := range m.contract.AppMetaData { + if checkAlias(app.Environment, envAliases) && app.ClientID == clientID { + return app, nil + } + } + return AppMetaData{}, fmt.Errorf("not found") +} + +func (m *Manager) writeAppMetaData(AppMetaData AppMetaData) error { + key := AppMetaData.Key() + m.contractMu.Lock() + defer m.contractMu.Unlock() + m.contract.AppMetaData[key] = AppMetaData + return nil +} + +// RemoveAccount removes all the associated ATs, RTs and IDTs from the cache associated with this account. +func (m *Manager) RemoveAccount(account shared.Account, clientID string) { + m.removeRefreshTokens(account.HomeAccountID, account.Environment, clientID) + m.removeAccessTokens(account.HomeAccountID, account.Environment) + m.removeIDTokens(account.HomeAccountID, account.Environment) + m.removeAccounts(account.HomeAccountID, account.Environment) +} + +func (m *Manager) removeRefreshTokens(homeID string, env string, clientID string) { + m.contractMu.Lock() + defer m.contractMu.Unlock() + for key, rt := range m.contract.RefreshTokens { + // Check for RTs associated with the account. + if rt.HomeAccountID == homeID && rt.Environment == env { + // Do RT's app ownership check as a precaution, in case family apps + // and 3rd-party apps share same token cache, although they should not. + if rt.ClientID == clientID || rt.FamilyID != "" { + delete(m.contract.RefreshTokens, key) + } + } + } +} + +func (m *Manager) removeAccessTokens(homeID string, env string) { + m.contractMu.Lock() + defer m.contractMu.Unlock() + for key, at := range m.contract.AccessTokens { + // Remove AT's associated with the account + if at.HomeAccountID == homeID && at.Environment == env { + // # To avoid the complexity of locating sibling family app's AT, we skip AT's app ownership check. + // It means ATs for other apps will also be removed, it is OK because: + // non-family apps are not supposed to share token cache to begin with; + // Even if it happens, we keep other app's RT already, so SSO still works. + delete(m.contract.AccessTokens, key) + } + } +} + +func (m *Manager) removeIDTokens(homeID string, env string) { + m.contractMu.Lock() + defer m.contractMu.Unlock() + for key, idt := range m.contract.IDTokens { + // Remove ID tokens associated with the account. + if idt.HomeAccountID == homeID && idt.Environment == env { + delete(m.contract.IDTokens, key) + } + } +} + +func (m *Manager) removeAccounts(homeID string, env string) { + m.contractMu.Lock() + defer m.contractMu.Unlock() + for key, acc := range m.contract.Accounts { + // Remove the specified account. + if acc.HomeAccountID == homeID && acc.Environment == env { + delete(m.contract.Accounts, key) + } + } +} + +// update updates the internal cache object. This is for use in tests, other uses are not +// supported. +func (m *Manager) update(cache *Contract) { + m.contractMu.Lock() + defer m.contractMu.Unlock() + m.contract = cache +} + +// Marshal implements cache.Marshaler. +func (m *Manager) Marshal() ([]byte, error) { + return json.Marshal(m.contract) +} + +// Unmarshal implements cache.Unmarshaler. +func (m *Manager) Unmarshal(b []byte) error { + m.contractMu.Lock() + defer m.contractMu.Unlock() + + contract := NewContract() + + err := json.Unmarshal(b, contract) + if err != nil { + return err + } + + m.contract = contract + + return nil +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/test_serialized_cache.json b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/test_serialized_cache.json new file mode 100644 index 00000000000..1d8181924d1 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage/test_serialized_cache.json @@ -0,0 +1,56 @@ +{ + "Account": { + "uid.utid-login.windows.net-contoso": { + "username": "John Doe", + "local_account_id": "object1234", + "realm": "contoso", + "environment": "login.windows.net", + "home_account_id": "uid.utid", + "authority_type": "MSSTS" + } + }, + "RefreshToken": { + "uid.utid-login.windows.net-refreshtoken-my_client_id--s2 s1 s3": { + "target": "s2 s1 s3", + "environment": "login.windows.net", + "credential_type": "RefreshToken", + "secret": "a refresh token", + "client_id": "my_client_id", + "home_account_id": "uid.utid" + } + }, + "AccessToken": { + "an-entry": { + "foo": "bar" + }, + "uid.utid-login.windows.net-accesstoken-my_client_id-contoso-s2 s1 s3": { + "environment": "login.windows.net", + "credential_type": "AccessToken", + "secret": "an access token", + "realm": "contoso", + "target": "s2 s1 s3", + "client_id": "my_client_id", + "cached_at": "1000", + "home_account_id": "uid.utid", + "extended_expires_on": "4600", + "expires_on": "4600" + } + }, + "IdToken": { + "uid.utid-login.windows.net-idtoken-my_client_id-contoso-": { + "realm": "contoso", + "environment": "login.windows.net", + "credential_type": "IdToken", + "secret": "header.eyJvaWQiOiAib2JqZWN0MTIzNCIsICJwcmVmZXJyZWRfdXNlcm5hbWUiOiAiSm9obiBEb2UiLCAic3ViIjogInN1YiJ9.signature", + "client_id": "my_client_id", + "home_account_id": "uid.utid" + } + }, + "unknownEntity": {"field1":"1","field2":"whats"}, + "AppMetadata": { + "AppMetadata-login.windows.net-my_client_id": { + "environment": "login.windows.net", + "client_id": "my_client_id" + } + } + } \ No newline at end of file diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/exported/exported.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/exported/exported.go new file mode 100644 index 00000000000..7b673e3fe12 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/exported/exported.go @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +// package exported contains internal types that are re-exported from a public package +package exported + +// AssertionRequestOptions has information required to generate a client assertion +type AssertionRequestOptions struct { + // ClientID identifies the application for which an assertion is requested. Used as the assertion's "iss" and "sub" claims. + ClientID string + + // TokenEndpoint is the intended token endpoint. Used as the assertion's "aud" claim. + TokenEndpoint string +} + +// TokenProviderParameters is the authentication parameters passed to token providers +type TokenProviderParameters struct { + // Claims contains any additional claims requested for the token + Claims string + // CorrelationID of the authentication request + CorrelationID string + // Scopes requested for the token + Scopes []string + // TenantID identifies the tenant in which to authenticate + TenantID string +} + +// TokenProviderResult is the authentication result returned by custom token providers +type TokenProviderResult struct { + // AccessToken is the requested token + AccessToken string + // ExpiresInSeconds is the lifetime of the token in seconds + ExpiresInSeconds int +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/design.md b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/design.md new file mode 100644 index 00000000000..09edb01b7e4 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/design.md @@ -0,0 +1,140 @@ +# JSON Package Design +Author: John Doak(jdoak@microsoft.com) + +## Why? + +This project needs a special type of marshal/unmarshal not directly supported +by the encoding/json package. + +The need revolves around a few key wants/needs: +- unmarshal and marshal structs representing JSON messages +- fields in the messgage not in the struct must be maintained when unmarshalled +- those same fields must be marshalled back when encoded again + +The initial version used map[string]interface{} to put in the keys that +were known and then any other keys were put into a field called AdditionalFields. + +This has a few negatives: +- Dual marshaling/unmarshalling is required +- Adding a struct field requires manually adding a key by name to be encoded/decoded from the map (which is a loosely coupled construct), which can lead to bugs that aren't detected or have bad side effects +- Tests can become quickly disconnected if those keys aren't put +in tests as well. So you think you have support working, but you +don't. Existing tests were found that didn't test the marshalling output. +- There is no enforcement that if AdditionalFields is required on one struct, it should be on all containers +that don't have custom marshal/unmarshal. + +This package aims to support our needs by providing custom Marshal()/Unmarshal() functions. + +This prevents all the negatives in the initial solution listed above. However, it does add its own negative: +- Custom encoding/decoding via reflection is messy (as can be seen in encoding/json itself) + +Go proverb: Reflection is never clear +Suggested reading: https://blog.golang.org/laws-of-reflection + +## Important design decisions + +- We don't want to understand all JSON decoding rules +- We don't want to deal with all the quoting, commas, etc on decode +- Need support for json.Marshaler/Unmarshaler, so we can support types like time.Time +- If struct does not implement json.Unmarshaler, it must have AdditionalFields defined +- We only support root level objects that are \*struct or struct + +To faciliate these goals, we will utilize the json.Encoder and json.Decoder. +They provide streaming processing (efficient) and return errors on bad JSON. + +Support for json.Marshaler/Unmarshaler allows for us to use non-basic types +that must be specially encoded/decoded (like time.Time objects). + +We don't support types that can't customer unmarshal or have AdditionalFields +in order to prevent future devs from forgetting that important field and +generating bad return values. + +Support for root level objects of \*struct or struct simply acknowledges the +fact that this is designed only for the purposes listed in the Introduction. +Outside that (like encoding a lone number) should be done with the +regular json package (as it will not have additional fields). + +We don't support a few things on json supported reference types and structs: +- \*map: no need for pointers to maps +- \*slice: no need for pointers to slices +- any further pointers on struct after \*struct + +There should never be a need for this in Go. + +## Design + +## State Machines + +This uses state machine designs that based upon the Rob Pike talk on +lexers and parsers: https://www.youtube.com/watch?v=HxaD_trXwRE + +This is the most common pattern for state machines in Go and +the model to follow closesly when dealing with streaming +processing of textual data. + +Our state machines are based on the type: +```go +type stateFn func() (stateFn, error) +``` + +The state machine itself is simply a struct that has methods that +satisfy stateFn. + +Our state machines have a few standard calls +- run(): runs the state machine +- start(): always the first stateFn to be called + +All state machines have the following logic: +* run() is called +* start() is called and returns the next stateFn or error +* stateFn is called + - If returned stateFn(next state) is non-nil, call it + - If error is non-nil, run() returns the error + - If stateFn == nil and err == nil, run() return err == nil + +## Supporting types + +Marshalling/Unmarshalling must support(within top level struct): +- struct +- \*struct +- []struct +- []\*struct +- []map[string]structContainer +- [][]structContainer + +**Term note:** structContainer == type that has a struct or \*struct inside it + +We specifically do not support []interface or map[string]interface +where the interface value would hold some value with a struct in it. + +Those will still marshal/unmarshal, but without support for +AdditionalFields. + +## Marshalling + +The marshalling design will be based around a statemachine design. + +The basic logic is as follows: + +* If struct has custom marshaller, call it and return +* If struct has field "AdditionalFields", it must be a map[string]interface{} +* If struct does not have "AdditionalFields", give an error +* Get struct tag detailing json names to go names, create mapping +* For each public field name + - Write field name out + - If field value is a struct, recursively call our state machine + - Otherwise, use the json.Encoder to write out the value + +## Unmarshalling + +The unmarshalling desin is also based around a statemachine design. The +basic logic is as follows: + +* If struct has custom marhaller, call it +* If struct has field "AdditionalFields", it must be a map[string]interface{} +* Get struct tag detailing json names to go names, create mapping +* For each key found + - If key exists, + - If value is basic type, extract value into struct field using Decoder + - If value is struct type, recursively call statemachine + - If key doesn't exist, add it to AdditionalFields if it exists using Decoder diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/json.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/json.go new file mode 100644 index 00000000000..2238521f5f9 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/json.go @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +// Package json provide functions for marshalling an unmarshalling types to JSON. These functions are meant to +// be utilized inside of structs that implement json.Unmarshaler and json.Marshaler interfaces. +// This package provides the additional functionality of writing fields that are not in the struct when marshalling +// to a field called AdditionalFields if that field exists and is a map[string]interface{}. +// When marshalling, if the struct has all the same prerequisites, it will uses the keys in AdditionalFields as +// extra fields. This package uses encoding/json underneath. +package json + +import ( + "bytes" + "encoding/json" + "fmt" + "reflect" + "strings" +) + +const addField = "AdditionalFields" +const ( + marshalJSON = "MarshalJSON" + unmarshalJSON = "UnmarshalJSON" +) + +var ( + leftBrace = []byte("{")[0] + rightBrace = []byte("}")[0] + comma = []byte(",")[0] + leftParen = []byte("[")[0] + rightParen = []byte("]")[0] +) + +var mapStrInterType = reflect.TypeOf(map[string]interface{}{}) + +// stateFn defines a state machine function. This will be used in all state +// machines in this package. +type stateFn func() (stateFn, error) + +// Marshal is used to marshal a type into its JSON representation. It +// wraps the stdlib calls in order to marshal a struct or *struct so +// that a field called "AdditionalFields" of type map[string]interface{} +// with "-" used inside struct tag `json:"-"` can be marshalled as if +// they were fields within the struct. +func Marshal(i interface{}) ([]byte, error) { + buff := bytes.Buffer{} + enc := json.NewEncoder(&buff) + enc.SetEscapeHTML(false) + enc.SetIndent("", "") + + v := reflect.ValueOf(i) + if v.Kind() != reflect.Ptr && v.CanAddr() { + v = v.Addr() + } + err := marshalStruct(v, &buff, enc) + if err != nil { + return nil, err + } + return buff.Bytes(), nil +} + +// Unmarshal unmarshals a []byte representing JSON into i, which must be a *struct. In addition, if the struct has +// a field called AdditionalFields of type map[string]interface{}, JSON data representing fields not in the struct +// will be written as key/value pairs to AdditionalFields. +func Unmarshal(b []byte, i interface{}) error { + if len(b) == 0 { + return nil + } + + jdec := json.NewDecoder(bytes.NewBuffer(b)) + jdec.UseNumber() + return unmarshalStruct(jdec, i) +} + +// MarshalRaw marshals i into a json.RawMessage. If I cannot be marshalled, +// this will panic. This is exposed to help test AdditionalField values +// which are stored as json.RawMessage. +func MarshalRaw(i interface{}) json.RawMessage { + b, err := json.Marshal(i) + if err != nil { + panic(err) + } + return json.RawMessage(b) +} + +// isDelim simply tests to see if a json.Token is a delimeter. +func isDelim(got json.Token) bool { + switch got.(type) { + case json.Delim: + return true + } + return false +} + +// delimIs tests got to see if it is want. +func delimIs(got json.Token, want rune) bool { + switch v := got.(type) { + case json.Delim: + if v == json.Delim(want) { + return true + } + } + return false +} + +// hasMarshalJSON will determine if the value or a pointer to this value has +// the MarshalJSON method. +func hasMarshalJSON(v reflect.Value) bool { + if method := v.MethodByName(marshalJSON); method.Kind() != reflect.Invalid { + _, ok := v.Interface().(json.Marshaler) + return ok + } + + if v.Kind() == reflect.Ptr { + v = v.Elem() + } else { + if !v.CanAddr() { + return false + } + v = v.Addr() + } + + if method := v.MethodByName(marshalJSON); method.Kind() != reflect.Invalid { + _, ok := v.Interface().(json.Marshaler) + return ok + } + return false +} + +// callMarshalJSON will call MarshalJSON() method on the value or a pointer to this value. +// This will panic if the method is not defined. +func callMarshalJSON(v reflect.Value) ([]byte, error) { + if method := v.MethodByName(marshalJSON); method.Kind() != reflect.Invalid { + marsh := v.Interface().(json.Marshaler) + return marsh.MarshalJSON() + } + + if v.Kind() == reflect.Ptr { + v = v.Elem() + } else { + if v.CanAddr() { + v = v.Addr() + } + } + + if method := v.MethodByName(unmarshalJSON); method.Kind() != reflect.Invalid { + marsh := v.Interface().(json.Marshaler) + return marsh.MarshalJSON() + } + + panic(fmt.Sprintf("callMarshalJSON called on type %T that does not have MarshalJSON defined", v.Interface())) +} + +// hasUnmarshalJSON will determine if the value or a pointer to this value has +// the UnmarshalJSON method. +func hasUnmarshalJSON(v reflect.Value) bool { + // You can't unmarshal on a non-pointer type. + if v.Kind() != reflect.Ptr { + if !v.CanAddr() { + return false + } + v = v.Addr() + } + + if method := v.MethodByName(unmarshalJSON); method.Kind() != reflect.Invalid { + _, ok := v.Interface().(json.Unmarshaler) + return ok + } + + return false +} + +// hasOmitEmpty indicates if the field has instructed us to not output +// the field if omitempty is set on the tag. tag is the string +// returned by reflect.StructField.Tag().Get(). +func hasOmitEmpty(tag string) bool { + sl := strings.Split(tag, ",") + for _, str := range sl { + if str == "omitempty" { + return true + } + } + return false +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/mapslice.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/mapslice.go new file mode 100644 index 00000000000..cef442f25c8 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/mapslice.go @@ -0,0 +1,333 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package json + +import ( + "encoding/json" + "fmt" + "reflect" +) + +// unmarshalMap unmarshal's a map. +func unmarshalMap(dec *json.Decoder, m reflect.Value) error { + if m.Kind() != reflect.Ptr || m.Elem().Kind() != reflect.Map { + panic("unmarshalMap called on non-*map value") + } + mapValueType := m.Elem().Type().Elem() + walk := mapWalk{dec: dec, m: m, valueType: mapValueType} + if err := walk.run(); err != nil { + return err + } + return nil +} + +type mapWalk struct { + dec *json.Decoder + key string + m reflect.Value + valueType reflect.Type +} + +// run runs our decoder state machine. +func (m *mapWalk) run() error { + var state = m.start + var err error + for { + state, err = state() + if err != nil { + return err + } + if state == nil { + return nil + } + } +} + +func (m *mapWalk) start() (stateFn, error) { + // maps can have custom unmarshaler's. + if hasUnmarshalJSON(m.m) { + err := m.dec.Decode(m.m.Interface()) + if err != nil { + return nil, err + } + return nil, nil + } + + // We only want to use this if the map value is: + // *struct/struct/map/slice + // otherwise use standard decode + t, _ := m.valueBaseType() + switch t.Kind() { + case reflect.Struct, reflect.Map, reflect.Slice: + delim, err := m.dec.Token() + if err != nil { + return nil, err + } + // This indicates the value was set to JSON null. + if delim == nil { + return nil, nil + } + if !delimIs(delim, '{') { + return nil, fmt.Errorf("Unmarshal expected opening {, received %v", delim) + } + return m.next, nil + case reflect.Ptr: + return nil, fmt.Errorf("do not support maps with values of '**type' or '*reference") + } + + // This is a basic map type, so just use Decode(). + if err := m.dec.Decode(m.m.Interface()); err != nil { + return nil, err + } + + return nil, nil +} + +func (m *mapWalk) next() (stateFn, error) { + if m.dec.More() { + key, err := m.dec.Token() + if err != nil { + return nil, err + } + m.key = key.(string) + return m.storeValue, nil + } + // No more entries, so remove final }. + _, err := m.dec.Token() + if err != nil { + return nil, err + } + return nil, nil +} + +func (m *mapWalk) storeValue() (stateFn, error) { + v := m.valueType + for { + switch v.Kind() { + case reflect.Ptr: + v = v.Elem() + continue + case reflect.Struct: + return m.storeStruct, nil + case reflect.Map: + return m.storeMap, nil + case reflect.Slice: + return m.storeSlice, nil + } + return nil, fmt.Errorf("bug: mapWalk.storeValue() called on unsupported type: %v", v.Kind()) + } +} + +func (m *mapWalk) storeStruct() (stateFn, error) { + v := newValue(m.valueType) + if err := unmarshalStruct(m.dec, v.Interface()); err != nil { + return nil, err + } + + if m.valueType.Kind() == reflect.Ptr { + m.m.Elem().SetMapIndex(reflect.ValueOf(m.key), v) + return m.next, nil + } + m.m.Elem().SetMapIndex(reflect.ValueOf(m.key), v.Elem()) + + return m.next, nil +} + +func (m *mapWalk) storeMap() (stateFn, error) { + v := reflect.MakeMap(m.valueType) + ptr := newValue(v.Type()) + ptr.Elem().Set(v) + if err := unmarshalMap(m.dec, ptr); err != nil { + return nil, err + } + + m.m.Elem().SetMapIndex(reflect.ValueOf(m.key), v) + + return m.next, nil +} + +func (m *mapWalk) storeSlice() (stateFn, error) { + v := newValue(m.valueType) + if err := unmarshalSlice(m.dec, v); err != nil { + return nil, err + } + + m.m.Elem().SetMapIndex(reflect.ValueOf(m.key), v.Elem()) + + return m.next, nil +} + +// valueType returns the underlying Type. So a *struct would yield +// struct, etc... +func (m *mapWalk) valueBaseType() (reflect.Type, bool) { + ptr := false + v := m.valueType + if v.Kind() == reflect.Ptr { + ptr = true + v = v.Elem() + } + return v, ptr +} + +// unmarshalSlice unmarshal's the next value, which must be a slice, into +// ptrSlice, which must be a pointer to a slice. newValue() can be use to +// create the slice. +func unmarshalSlice(dec *json.Decoder, ptrSlice reflect.Value) error { + if ptrSlice.Kind() != reflect.Ptr || ptrSlice.Elem().Kind() != reflect.Slice { + panic("unmarshalSlice called on non-*[]slice value") + } + sliceValueType := ptrSlice.Elem().Type().Elem() + walk := sliceWalk{ + dec: dec, + s: ptrSlice, + valueType: sliceValueType, + } + if err := walk.run(); err != nil { + return err + } + + return nil +} + +type sliceWalk struct { + dec *json.Decoder + s reflect.Value // *[]slice + valueType reflect.Type +} + +// run runs our decoder state machine. +func (s *sliceWalk) run() error { + var state = s.start + var err error + for { + state, err = state() + if err != nil { + return err + } + if state == nil { + return nil + } + } +} + +func (s *sliceWalk) start() (stateFn, error) { + // slices can have custom unmarshaler's. + if hasUnmarshalJSON(s.s) { + err := s.dec.Decode(s.s.Interface()) + if err != nil { + return nil, err + } + return nil, nil + } + + // We only want to use this if the slice value is: + // []*struct/[]struct/[]map/[]slice + // otherwise use standard decode + t := s.valueBaseType() + + switch t.Kind() { + case reflect.Ptr: + return nil, fmt.Errorf("cannot unmarshal into a ** or *") + case reflect.Struct, reflect.Map, reflect.Slice: + delim, err := s.dec.Token() + if err != nil { + return nil, err + } + // This indicates the value was set to nil. + if delim == nil { + return nil, nil + } + if !delimIs(delim, '[') { + return nil, fmt.Errorf("Unmarshal expected opening [, received %v", delim) + } + return s.next, nil + } + + if err := s.dec.Decode(s.s.Interface()); err != nil { + return nil, err + } + return nil, nil +} + +func (s *sliceWalk) next() (stateFn, error) { + if s.dec.More() { + return s.storeValue, nil + } + // Nothing left in the slice, remove closing ] + _, err := s.dec.Token() + return nil, err +} + +func (s *sliceWalk) storeValue() (stateFn, error) { + t := s.valueBaseType() + switch t.Kind() { + case reflect.Ptr: + return nil, fmt.Errorf("do not support 'pointer to pointer' or 'pointer to reference' types") + case reflect.Struct: + return s.storeStruct, nil + case reflect.Map: + return s.storeMap, nil + case reflect.Slice: + return s.storeSlice, nil + } + return nil, fmt.Errorf("bug: sliceWalk.storeValue() called on unsupported type: %v", t.Kind()) +} + +func (s *sliceWalk) storeStruct() (stateFn, error) { + v := newValue(s.valueType) + if err := unmarshalStruct(s.dec, v.Interface()); err != nil { + return nil, err + } + + if s.valueType.Kind() == reflect.Ptr { + s.s.Elem().Set(reflect.Append(s.s.Elem(), v)) + return s.next, nil + } + + s.s.Elem().Set(reflect.Append(s.s.Elem(), v.Elem())) + return s.next, nil +} + +func (s *sliceWalk) storeMap() (stateFn, error) { + v := reflect.MakeMap(s.valueType) + ptr := newValue(v.Type()) + ptr.Elem().Set(v) + + if err := unmarshalMap(s.dec, ptr); err != nil { + return nil, err + } + + s.s.Elem().Set(reflect.Append(s.s.Elem(), v)) + + return s.next, nil +} + +func (s *sliceWalk) storeSlice() (stateFn, error) { + v := newValue(s.valueType) + if err := unmarshalSlice(s.dec, v); err != nil { + return nil, err + } + + s.s.Elem().Set(reflect.Append(s.s.Elem(), v.Elem())) + + return s.next, nil +} + +// valueType returns the underlying Type. So a *struct would yield +// struct, etc... +func (s *sliceWalk) valueBaseType() reflect.Type { + v := s.valueType + if v.Kind() == reflect.Ptr { + v = v.Elem() + } + return v +} + +// newValue() returns a new *type that represents type passed. +func newValue(valueType reflect.Type) reflect.Value { + if valueType.Kind() == reflect.Ptr { + return reflect.New(valueType.Elem()) + } + return reflect.New(valueType) +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/marshal.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/marshal.go new file mode 100644 index 00000000000..df5dc6e11b5 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/marshal.go @@ -0,0 +1,346 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package json + +import ( + "bytes" + "encoding/json" + "fmt" + "reflect" + "unicode" +) + +// marshalStruct takes in i, which must be a *struct or struct and marshals its content +// as JSON into buff (sometimes with writes to buff directly, sometimes via enc). +// This call is recursive for all fields of *struct or struct type. +func marshalStruct(v reflect.Value, buff *bytes.Buffer, enc *json.Encoder) error { + if v.Kind() == reflect.Ptr { + v = v.Elem() + } + // We only care about custom Marshalling a struct. + if v.Kind() != reflect.Struct { + return fmt.Errorf("bug: marshal() received a non *struct or struct, received type %T", v.Interface()) + } + + if hasMarshalJSON(v) { + b, err := callMarshalJSON(v) + if err != nil { + return err + } + buff.Write(b) + return nil + } + + t := v.Type() + + // If it has an AdditionalFields field make sure its the right type. + f := v.FieldByName(addField) + if f.Kind() != reflect.Invalid { + if f.Kind() != reflect.Map { + return fmt.Errorf("type %T has field 'AdditionalFields' that is not a map[string]interface{}", v.Interface()) + } + if !f.Type().AssignableTo(mapStrInterType) { + return fmt.Errorf("type %T has field 'AdditionalFields' that is not a map[string]interface{}", v.Interface()) + } + } + + translator, err := findFields(v) + if err != nil { + return err + } + + buff.WriteByte(leftBrace) + for x := 0; x < v.NumField(); x++ { + field := v.Field(x) + + // We don't access private fields. + if unicode.IsLower(rune(t.Field(x).Name[0])) { + continue + } + + if t.Field(x).Name == addField { + if v.Field(x).Len() > 0 { + if err := writeAddFields(field.Interface(), buff, enc); err != nil { + return err + } + buff.WriteByte(comma) + } + continue + } + + // If they have omitempty set, we don't write out the field if + // it is the zero value. + if hasOmitEmpty(t.Field(x).Tag.Get("json")) { + if v.Field(x).IsZero() { + continue + } + } + + // Write out the field name part. + jsonName := translator.jsonName(t.Field(x).Name) + buff.WriteString(fmt.Sprintf("%q:", jsonName)) + + if field.Kind() == reflect.Ptr { + field = field.Elem() + } + + if err := marshalStructField(field, buff, enc); err != nil { + return err + } + } + + buff.Truncate(buff.Len() - 1) // Remove final comma + buff.WriteByte(rightBrace) + + return nil +} + +func marshalStructField(field reflect.Value, buff *bytes.Buffer, enc *json.Encoder) error { + // Determine if we need a trailing comma. + defer buff.WriteByte(comma) + + switch field.Kind() { + // If it was a *struct or struct, we need to recursively all marshal(). + case reflect.Struct: + if field.CanAddr() { + field = field.Addr() + } + return marshalStruct(field, buff, enc) + case reflect.Map: + return marshalMap(field, buff, enc) + case reflect.Slice: + return marshalSlice(field, buff, enc) + } + + // It is just a basic type, so encode it. + if err := enc.Encode(field.Interface()); err != nil { + return err + } + buff.Truncate(buff.Len() - 1) // Remove Encode() added \n + + return nil +} + +func marshalMap(v reflect.Value, buff *bytes.Buffer, enc *json.Encoder) error { + if v.Kind() != reflect.Map { + return fmt.Errorf("bug: marshalMap() called on %T", v.Interface()) + } + if v.Len() == 0 { + buff.WriteByte(leftBrace) + buff.WriteByte(rightBrace) + return nil + } + encoder := mapEncode{m: v, buff: buff, enc: enc} + return encoder.run() +} + +type mapEncode struct { + m reflect.Value + buff *bytes.Buffer + enc *json.Encoder + + valueBaseType reflect.Type +} + +// run runs our encoder state machine. +func (m *mapEncode) run() error { + var state = m.start + var err error + for { + state, err = state() + if err != nil { + return err + } + if state == nil { + return nil + } + } +} + +func (m *mapEncode) start() (stateFn, error) { + if hasMarshalJSON(m.m) { + b, err := callMarshalJSON(m.m) + if err != nil { + return nil, err + } + m.buff.Write(b) + return nil, nil + } + + valueBaseType := m.m.Type().Elem() + if valueBaseType.Kind() == reflect.Ptr { + valueBaseType = valueBaseType.Elem() + } + m.valueBaseType = valueBaseType + + switch valueBaseType.Kind() { + case reflect.Ptr: + return nil, fmt.Errorf("Marshal does not support ** or *") + case reflect.Struct, reflect.Map, reflect.Slice: + return m.encode, nil + } + + // If the map value doesn't have a struct/map/slice, just Encode() it. + if err := m.enc.Encode(m.m.Interface()); err != nil { + return nil, err + } + m.buff.Truncate(m.buff.Len() - 1) // Remove Encode() added \n + return nil, nil +} + +func (m *mapEncode) encode() (stateFn, error) { + m.buff.WriteByte(leftBrace) + + iter := m.m.MapRange() + for iter.Next() { + // Write the key. + k := iter.Key() + m.buff.WriteString(fmt.Sprintf("%q:", k.String())) + + v := iter.Value() + switch m.valueBaseType.Kind() { + case reflect.Struct: + if v.CanAddr() { + v = v.Addr() + } + if err := marshalStruct(v, m.buff, m.enc); err != nil { + return nil, err + } + case reflect.Map: + if err := marshalMap(v, m.buff, m.enc); err != nil { + return nil, err + } + case reflect.Slice: + if err := marshalSlice(v, m.buff, m.enc); err != nil { + return nil, err + } + default: + panic(fmt.Sprintf("critical bug: mapEncode.encode() called with value base type: %v", m.valueBaseType.Kind())) + } + m.buff.WriteByte(comma) + } + m.buff.Truncate(m.buff.Len() - 1) // Remove final comma + m.buff.WriteByte(rightBrace) + + return nil, nil +} + +func marshalSlice(v reflect.Value, buff *bytes.Buffer, enc *json.Encoder) error { + if v.Kind() != reflect.Slice { + return fmt.Errorf("bug: marshalSlice() called on %T", v.Interface()) + } + if v.Len() == 0 { + buff.WriteByte(leftParen) + buff.WriteByte(rightParen) + return nil + } + encoder := sliceEncode{s: v, buff: buff, enc: enc} + return encoder.run() +} + +type sliceEncode struct { + s reflect.Value + buff *bytes.Buffer + enc *json.Encoder + + valueBaseType reflect.Type +} + +// run runs our encoder state machine. +func (s *sliceEncode) run() error { + var state = s.start + var err error + for { + state, err = state() + if err != nil { + return err + } + if state == nil { + return nil + } + } +} + +func (s *sliceEncode) start() (stateFn, error) { + if hasMarshalJSON(s.s) { + b, err := callMarshalJSON(s.s) + if err != nil { + return nil, err + } + s.buff.Write(b) + return nil, nil + } + + valueBaseType := s.s.Type().Elem() + if valueBaseType.Kind() == reflect.Ptr { + valueBaseType = valueBaseType.Elem() + } + s.valueBaseType = valueBaseType + + switch valueBaseType.Kind() { + case reflect.Ptr: + return nil, fmt.Errorf("Marshal does not support ** or *") + case reflect.Struct, reflect.Map, reflect.Slice: + return s.encode, nil + } + + // If the map value doesn't have a struct/map/slice, just Encode() it. + if err := s.enc.Encode(s.s.Interface()); err != nil { + return nil, err + } + s.buff.Truncate(s.buff.Len() - 1) // Remove Encode added \n + + return nil, nil +} + +func (s *sliceEncode) encode() (stateFn, error) { + s.buff.WriteByte(leftParen) + for i := 0; i < s.s.Len(); i++ { + v := s.s.Index(i) + switch s.valueBaseType.Kind() { + case reflect.Struct: + if v.CanAddr() { + v = v.Addr() + } + if err := marshalStruct(v, s.buff, s.enc); err != nil { + return nil, err + } + case reflect.Map: + if err := marshalMap(v, s.buff, s.enc); err != nil { + return nil, err + } + case reflect.Slice: + if err := marshalSlice(v, s.buff, s.enc); err != nil { + return nil, err + } + default: + panic(fmt.Sprintf("critical bug: mapEncode.encode() called with value base type: %v", s.valueBaseType.Kind())) + } + s.buff.WriteByte(comma) + } + s.buff.Truncate(s.buff.Len() - 1) // Remove final comma + s.buff.WriteByte(rightParen) + return nil, nil +} + +// writeAddFields writes the AdditionalFields struct field out to JSON as field +// values. i must be a map[string]interface{} or this will panic. +func writeAddFields(i interface{}, buff *bytes.Buffer, enc *json.Encoder) error { + m := i.(map[string]interface{}) + + x := 0 + for k, v := range m { + buff.WriteString(fmt.Sprintf("%q:", k)) + if err := enc.Encode(v); err != nil { + return err + } + buff.Truncate(buff.Len() - 1) // Remove Encode() added \n + + if x+1 != len(m) { + buff.WriteByte(comma) + } + x++ + } + return nil +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/struct.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/struct.go new file mode 100644 index 00000000000..07751544a28 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/struct.go @@ -0,0 +1,290 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package json + +import ( + "encoding/json" + "fmt" + "reflect" + "strings" +) + +func unmarshalStruct(jdec *json.Decoder, i interface{}) error { + v := reflect.ValueOf(i) + if v.Kind() != reflect.Ptr { + return fmt.Errorf("Unmarshal() received type %T, which is not a *struct", i) + } + v = v.Elem() + if v.Kind() != reflect.Struct { + return fmt.Errorf("Unmarshal() received type %T, which is not a *struct", i) + } + + if hasUnmarshalJSON(v) { + // Indicates that this type has a custom Unmarshaler. + return jdec.Decode(v.Addr().Interface()) + } + + f := v.FieldByName(addField) + if f.Kind() == reflect.Invalid { + return fmt.Errorf("Unmarshal(%T) only supports structs that have the field AdditionalFields or implements json.Unmarshaler", i) + } + + if f.Kind() != reflect.Map || !f.Type().AssignableTo(mapStrInterType) { + return fmt.Errorf("type %T has field 'AdditionalFields' that is not a map[string]interface{}", i) + } + + dec := newDecoder(jdec, v) + return dec.run() +} + +type decoder struct { + dec *json.Decoder + value reflect.Value // This will be a reflect.Struct + translator translateFields + key string +} + +func newDecoder(dec *json.Decoder, value reflect.Value) *decoder { + return &decoder{value: value, dec: dec} +} + +// run runs our decoder state machine. +func (d *decoder) run() error { + var state = d.start + var err error + for { + state, err = state() + if err != nil { + return err + } + if state == nil { + return nil + } + } +} + +// start looks for our opening delimeter '{' and then transitions to looping through our fields. +func (d *decoder) start() (stateFn, error) { + var err error + d.translator, err = findFields(d.value) + if err != nil { + return nil, err + } + + delim, err := d.dec.Token() + if err != nil { + return nil, err + } + if !delimIs(delim, '{') { + return nil, fmt.Errorf("Unmarshal expected opening {, received %v", delim) + } + + return d.next, nil +} + +// next gets the next struct field name from the raw json or stops the machine if we get our closing }. +func (d *decoder) next() (stateFn, error) { + if !d.dec.More() { + // Remove the closing }. + if _, err := d.dec.Token(); err != nil { + return nil, err + } + return nil, nil + } + + key, err := d.dec.Token() + if err != nil { + return nil, err + } + + d.key = key.(string) + return d.storeValue, nil +} + +// storeValue takes the next value and stores it our struct. If the field can't be found +// in the struct, it pushes the operation to storeAdditional(). +func (d *decoder) storeValue() (stateFn, error) { + goName := d.translator.goName(d.key) + if goName == "" { + goName = d.key + } + + // We don't have the field in the struct, so it goes in AdditionalFields. + f := d.value.FieldByName(goName) + if f.Kind() == reflect.Invalid { + return d.storeAdditional, nil + } + + // Indicates that this type has a custom Unmarshaler. + if hasUnmarshalJSON(f) { + err := d.dec.Decode(f.Addr().Interface()) + if err != nil { + return nil, err + } + return d.next, nil + } + + t, isPtr, err := fieldBaseType(d.value, goName) + if err != nil { + return nil, fmt.Errorf("type(%s) had field(%s) %w", d.value.Type().Name(), goName, err) + } + + switch t.Kind() { + // We need to recursively call ourselves on any *struct or struct. + case reflect.Struct: + if isPtr { + if f.IsNil() { + f.Set(reflect.New(t)) + } + } else { + f = f.Addr() + } + if err := unmarshalStruct(d.dec, f.Interface()); err != nil { + return nil, err + } + return d.next, nil + case reflect.Map: + v := reflect.MakeMap(f.Type()) + ptr := newValue(f.Type()) + ptr.Elem().Set(v) + if err := unmarshalMap(d.dec, ptr); err != nil { + return nil, err + } + f.Set(ptr.Elem()) + return d.next, nil + case reflect.Slice: + v := reflect.MakeSlice(f.Type(), 0, 0) + ptr := newValue(f.Type()) + ptr.Elem().Set(v) + if err := unmarshalSlice(d.dec, ptr); err != nil { + return nil, err + } + f.Set(ptr.Elem()) + return d.next, nil + } + + if !isPtr { + f = f.Addr() + } + + // For values that are pointers, we need them to be non-nil in order + // to decode into them. + if f.IsNil() { + f.Set(reflect.New(t)) + } + + if err := d.dec.Decode(f.Interface()); err != nil { + return nil, err + } + + return d.next, nil +} + +// storeAdditional pushes the key/value into our .AdditionalFields map. +func (d *decoder) storeAdditional() (stateFn, error) { + rw := json.RawMessage{} + if err := d.dec.Decode(&rw); err != nil { + return nil, err + } + field := d.value.FieldByName(addField) + if field.IsNil() { + field.Set(reflect.MakeMap(field.Type())) + } + field.SetMapIndex(reflect.ValueOf(d.key), reflect.ValueOf(rw)) + return d.next, nil +} + +func fieldBaseType(v reflect.Value, fieldName string) (t reflect.Type, isPtr bool, err error) { + sf, ok := v.Type().FieldByName(fieldName) + if !ok { + return nil, false, fmt.Errorf("bug: fieldBaseType() lookup of field(%s) on type(%s): do not have field", fieldName, v.Type().Name()) + } + t = sf.Type + if t.Kind() == reflect.Ptr { + t = t.Elem() + isPtr = true + } + if t.Kind() == reflect.Ptr { + return nil, isPtr, fmt.Errorf("received pointer to pointer type, not supported") + } + return t, isPtr, nil +} + +type translateField struct { + jsonName string + goName string +} + +// translateFields is a list of translateFields with a handy lookup method. +type translateFields []translateField + +// goName loops through a list of fields looking for one contaning the jsonName and +// returning the goName. If not found, returns the empty string. +// Note: not a map because at this size slices are faster even in tight loops. +func (t translateFields) goName(jsonName string) string { + for _, entry := range t { + if entry.jsonName == jsonName { + return entry.goName + } + } + return "" +} + +// jsonName loops through a list of fields looking for one contaning the goName and +// returning the jsonName. If not found, returns the empty string. +// Note: not a map because at this size slices are faster even in tight loops. +func (t translateFields) jsonName(goName string) string { + for _, entry := range t { + if entry.goName == goName { + return entry.jsonName + } + } + return "" +} + +var umarshalerType = reflect.TypeOf((*json.Unmarshaler)(nil)).Elem() + +// findFields parses a struct and writes the field tags for lookup. It will return an error +// if any field has a type of *struct or struct that does not implement json.Marshaler. +func findFields(v reflect.Value) (translateFields, error) { + if v.Kind() == reflect.Ptr { + v = v.Elem() + } + if v.Kind() != reflect.Struct { + return nil, fmt.Errorf("findFields received a %s type, expected *struct or struct", v.Type().Name()) + } + tfs := make([]translateField, 0, v.NumField()) + for i := 0; i < v.NumField(); i++ { + tf := translateField{ + goName: v.Type().Field(i).Name, + jsonName: parseTag(v.Type().Field(i).Tag.Get("json")), + } + switch tf.jsonName { + case "", "-": + tf.jsonName = tf.goName + } + tfs = append(tfs, tf) + + f := v.Field(i) + if f.Kind() == reflect.Ptr { + f = f.Elem() + } + if f.Kind() == reflect.Struct { + if f.Type().Implements(umarshalerType) { + return nil, fmt.Errorf("struct type %q which has field %q which "+ + "doesn't implement json.Unmarshaler", v.Type().Name(), v.Type().Field(i).Name) + } + } + } + return tfs, nil +} + +// parseTag just returns the first entry in the tag. tag is the string +// returned by reflect.StructField.Tag().Get(). +func parseTag(tag string) string { + if idx := strings.Index(tag, ","); idx != -1 { + return tag[:idx] + } + return tag +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/types/time/time.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/types/time/time.go new file mode 100644 index 00000000000..a1c99621e9f --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/types/time/time.go @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +// Package time provides for custom types to translate time from JSON and other formats +// into time.Time objects. +package time + +import ( + "fmt" + "strconv" + "strings" + "time" +) + +// Unix provides a type that can marshal and unmarshal a string representation +// of the unix epoch into a time.Time object. +type Unix struct { + T time.Time +} + +// MarshalJSON implements encoding/json.MarshalJSON(). +func (u Unix) MarshalJSON() ([]byte, error) { + if u.T.IsZero() { + return []byte(""), nil + } + return []byte(fmt.Sprintf("%q", strconv.FormatInt(u.T.Unix(), 10))), nil +} + +// UnmarshalJSON implements encoding/json.UnmarshalJSON(). +func (u *Unix) UnmarshalJSON(b []byte) error { + i, err := strconv.Atoi(strings.Trim(string(b), `"`)) + if err != nil { + return fmt.Errorf("unix time(%s) could not be converted from string to int: %w", string(b), err) + } + u.T = time.Unix(int64(i), 0) + return nil +} + +// DurationTime provides a type that can marshal and unmarshal a string representation +// of a duration from now into a time.Time object. +// Note: I'm not sure this is the best way to do this. What happens is we get a field +// called "expires_in" that represents the seconds from now that this expires. We +// turn that into a time we call .ExpiresOn. But maybe we should be recording +// when the token was received at .TokenRecieved and .ExpiresIn should remain as a duration. +// Then we could have a method called ExpiresOn(). Honestly, the whole thing is +// bad because the server doesn't return a concrete time. I think this is +// cleaner, but its not great either. +type DurationTime struct { + T time.Time +} + +// MarshalJSON implements encoding/json.MarshalJSON(). +func (d DurationTime) MarshalJSON() ([]byte, error) { + if d.T.IsZero() { + return []byte(""), nil + } + + dt := time.Until(d.T) + return []byte(fmt.Sprintf("%d", int64(dt*time.Second))), nil +} + +// UnmarshalJSON implements encoding/json.UnmarshalJSON(). +func (d *DurationTime) UnmarshalJSON(b []byte) error { + i, err := strconv.Atoi(strings.Trim(string(b), `"`)) + if err != nil { + return fmt.Errorf("unix time(%s) could not be converted from string to int: %w", string(b), err) + } + d.T = time.Now().Add(time.Duration(i) * time.Second) + return nil +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/local/server.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/local/server.go new file mode 100644 index 00000000000..04236ff3127 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/local/server.go @@ -0,0 +1,177 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +// Package local contains a local HTTP server used with interactive authentication. +package local + +import ( + "context" + "fmt" + "net" + "net/http" + "strconv" + "strings" + "time" +) + +var okPage = []byte(` + + + + + Authentication Complete + + +

    Authentication complete. You can return to the application. Feel free to close this browser tab.

    + + +`) + +const failPage = ` + + + + + Authentication Failed + + +

    Authentication failed. You can return to the application. Feel free to close this browser tab.

    +

    Error details: error %s error_description: %s

    + + +` + +// Result is the result from the redirect. +type Result struct { + // Code is the code sent by the authority server. + Code string + // Err is set if there was an error. + Err error +} + +// Server is an HTTP server. +type Server struct { + // Addr is the address the server is listening on. + Addr string + resultCh chan Result + s *http.Server + reqState string +} + +// New creates a local HTTP server and starts it. +func New(reqState string, port int) (*Server, error) { + var l net.Listener + var err error + var portStr string + if port > 0 { + // use port provided by caller + l, err = net.Listen("tcp", fmt.Sprintf("localhost:%d", port)) + portStr = strconv.FormatInt(int64(port), 10) + } else { + // find a free port + for i := 0; i < 10; i++ { + l, err = net.Listen("tcp", "localhost:0") + if err != nil { + continue + } + addr := l.Addr().String() + portStr = addr[strings.LastIndex(addr, ":")+1:] + break + } + } + if err != nil { + return nil, err + } + + serv := &Server{ + Addr: fmt.Sprintf("http://localhost:%s", portStr), + s: &http.Server{Addr: "localhost:0", ReadHeaderTimeout: time.Second}, + reqState: reqState, + resultCh: make(chan Result, 1), + } + serv.s.Handler = http.HandlerFunc(serv.handler) + + if err := serv.start(l); err != nil { + return nil, err + } + + return serv, nil +} + +func (s *Server) start(l net.Listener) error { + go func() { + err := s.s.Serve(l) + if err != nil { + select { + case s.resultCh <- Result{Err: err}: + default: + } + } + }() + + return nil +} + +// Result gets the result of the redirect operation. Once a single result is returned, the server +// is shutdown. ctx deadline will be honored. +func (s *Server) Result(ctx context.Context) Result { + select { + case <-ctx.Done(): + return Result{Err: ctx.Err()} + case r := <-s.resultCh: + return r + } +} + +// Shutdown shuts down the server. +func (s *Server) Shutdown() { + // Note: You might get clever and think you can do this in handler() as a defer, you can't. + _ = s.s.Shutdown(context.Background()) +} + +func (s *Server) putResult(r Result) { + select { + case s.resultCh <- r: + default: + } +} + +func (s *Server) handler(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + + headerErr := q.Get("error") + if headerErr != "" { + desc := q.Get("error_description") + // Note: It is a little weird we handle some errors by not going to the failPage. If they all should, + // change this to s.error() and make s.error() write the failPage instead of an error code. + _, _ = w.Write([]byte(fmt.Sprintf(failPage, headerErr, desc))) + s.putResult(Result{Err: fmt.Errorf(desc)}) + return + } + + respState := q.Get("state") + switch respState { + case s.reqState: + case "": + s.error(w, http.StatusInternalServerError, "server didn't send OAuth state") + return + default: + s.error(w, http.StatusInternalServerError, "mismatched OAuth state, req(%s), resp(%s)", s.reqState, respState) + return + } + + code := q.Get("code") + if code == "" { + s.error(w, http.StatusInternalServerError, "authorization code missing in query string") + return + } + + _, _ = w.Write(okPage) + s.putResult(Result{Code: code}) +} + +func (s *Server) error(w http.ResponseWriter, code int, str string, i ...interface{}) { + err := fmt.Errorf(str, i...) + http.Error(w, err.Error(), code) + s.putResult(Result{Err: err}) +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/oauth.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/oauth.go new file mode 100644 index 00000000000..f910823544b --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/oauth.go @@ -0,0 +1,297 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package oauth + +import ( + "context" + "encoding/json" + "fmt" + "io" + "time" + + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/errors" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/exported" + internalTime "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/types/time" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs" + "github.com/google/uuid" +) + +// ResolveEndpointer contains the methods for resolving authority endpoints. +type ResolveEndpointer interface { + ResolveEndpoints(ctx context.Context, authorityInfo authority.Info, userPrincipalName string) (authority.Endpoints, error) +} + +// AccessTokens contains the methods for fetching tokens from different sources. +type AccessTokens interface { + DeviceCodeResult(ctx context.Context, authParameters authority.AuthParams) (accesstokens.DeviceCodeResult, error) + FromUsernamePassword(ctx context.Context, authParameters authority.AuthParams) (accesstokens.TokenResponse, error) + FromAuthCode(ctx context.Context, req accesstokens.AuthCodeRequest) (accesstokens.TokenResponse, error) + FromRefreshToken(ctx context.Context, appType accesstokens.AppType, authParams authority.AuthParams, cc *accesstokens.Credential, refreshToken string) (accesstokens.TokenResponse, error) + FromClientSecret(ctx context.Context, authParameters authority.AuthParams, clientSecret string) (accesstokens.TokenResponse, error) + FromAssertion(ctx context.Context, authParameters authority.AuthParams, assertion string) (accesstokens.TokenResponse, error) + FromUserAssertionClientSecret(ctx context.Context, authParameters authority.AuthParams, userAssertion string, clientSecret string) (accesstokens.TokenResponse, error) + FromUserAssertionClientCertificate(ctx context.Context, authParameters authority.AuthParams, userAssertion string, assertion string) (accesstokens.TokenResponse, error) + FromDeviceCodeResult(ctx context.Context, authParameters authority.AuthParams, deviceCodeResult accesstokens.DeviceCodeResult) (accesstokens.TokenResponse, error) + FromSamlGrant(ctx context.Context, authParameters authority.AuthParams, samlGrant wstrust.SamlTokenInfo) (accesstokens.TokenResponse, error) +} + +// FetchAuthority will be implemented by authority.Authority. +type FetchAuthority interface { + UserRealm(context.Context, authority.AuthParams) (authority.UserRealm, error) + AADInstanceDiscovery(context.Context, authority.Info) (authority.InstanceDiscoveryResponse, error) +} + +// FetchWSTrust contains the methods for interacting with WSTrust endpoints. +type FetchWSTrust interface { + Mex(ctx context.Context, federationMetadataURL string) (defs.MexDocument, error) + SAMLTokenInfo(ctx context.Context, authParameters authority.AuthParams, cloudAudienceURN string, endpoint defs.Endpoint) (wstrust.SamlTokenInfo, error) +} + +// Client provides tokens for various types of token requests. +type Client struct { + Resolver ResolveEndpointer + AccessTokens AccessTokens + Authority FetchAuthority + WSTrust FetchWSTrust +} + +// New is the constructor for Token. +func New(httpClient ops.HTTPClient) *Client { + r := ops.New(httpClient) + return &Client{ + Resolver: newAuthorityEndpoint(r), + AccessTokens: r.AccessTokens(), + Authority: r.Authority(), + WSTrust: r.WSTrust(), + } +} + +// ResolveEndpoints gets the authorization and token endpoints and creates an AuthorityEndpoints instance. +func (t *Client) ResolveEndpoints(ctx context.Context, authorityInfo authority.Info, userPrincipalName string) (authority.Endpoints, error) { + return t.Resolver.ResolveEndpoints(ctx, authorityInfo, userPrincipalName) +} + +func (t *Client) AADInstanceDiscovery(ctx context.Context, authorityInfo authority.Info) (authority.InstanceDiscoveryResponse, error) { + return t.Authority.AADInstanceDiscovery(ctx, authorityInfo) +} + +// AuthCode returns a token based on an authorization code. +func (t *Client) AuthCode(ctx context.Context, req accesstokens.AuthCodeRequest) (accesstokens.TokenResponse, error) { + if err := t.resolveEndpoint(ctx, &req.AuthParams, ""); err != nil { + return accesstokens.TokenResponse{}, err + } + + tResp, err := t.AccessTokens.FromAuthCode(ctx, req) + if err != nil { + return accesstokens.TokenResponse{}, fmt.Errorf("could not retrieve token from auth code: %w", err) + } + return tResp, nil +} + +// Credential acquires a token from the authority using a client credentials grant. +func (t *Client) Credential(ctx context.Context, authParams authority.AuthParams, cred *accesstokens.Credential) (accesstokens.TokenResponse, error) { + if cred.TokenProvider != nil { + now := time.Now() + scopes := make([]string, len(authParams.Scopes)) + copy(scopes, authParams.Scopes) + params := exported.TokenProviderParameters{ + Claims: authParams.Claims, + CorrelationID: uuid.New().String(), + Scopes: scopes, + TenantID: authParams.AuthorityInfo.Tenant, + } + tr, err := cred.TokenProvider(ctx, params) + if err != nil { + return accesstokens.TokenResponse{}, err + } + return accesstokens.TokenResponse{ + AccessToken: tr.AccessToken, + ExpiresOn: internalTime.DurationTime{ + T: now.Add(time.Duration(tr.ExpiresInSeconds) * time.Second), + }, + GrantedScopes: accesstokens.Scopes{Slice: authParams.Scopes}, + }, nil + } + + if err := t.resolveEndpoint(ctx, &authParams, ""); err != nil { + return accesstokens.TokenResponse{}, err + } + + if cred.Secret != "" { + return t.AccessTokens.FromClientSecret(ctx, authParams, cred.Secret) + } + jwt, err := cred.JWT(ctx, authParams) + if err != nil { + return accesstokens.TokenResponse{}, err + } + return t.AccessTokens.FromAssertion(ctx, authParams, jwt) +} + +// Credential acquires a token from the authority using a client credentials grant. +func (t *Client) OnBehalfOf(ctx context.Context, authParams authority.AuthParams, cred *accesstokens.Credential) (accesstokens.TokenResponse, error) { + if err := t.resolveEndpoint(ctx, &authParams, ""); err != nil { + return accesstokens.TokenResponse{}, err + } + + if cred.Secret != "" { + return t.AccessTokens.FromUserAssertionClientSecret(ctx, authParams, authParams.UserAssertion, cred.Secret) + } + jwt, err := cred.JWT(ctx, authParams) + if err != nil { + return accesstokens.TokenResponse{}, err + } + return t.AccessTokens.FromUserAssertionClientCertificate(ctx, authParams, authParams.UserAssertion, jwt) +} + +func (t *Client) Refresh(ctx context.Context, reqType accesstokens.AppType, authParams authority.AuthParams, cc *accesstokens.Credential, refreshToken accesstokens.RefreshToken) (accesstokens.TokenResponse, error) { + if err := t.resolveEndpoint(ctx, &authParams, ""); err != nil { + return accesstokens.TokenResponse{}, err + } + + return t.AccessTokens.FromRefreshToken(ctx, reqType, authParams, cc, refreshToken.Secret) +} + +// UsernamePassword retrieves a token where a username and password is used. However, if this is +// a user realm of "Federated", this uses SAML tokens. If "Managed", uses normal username/password. +func (t *Client) UsernamePassword(ctx context.Context, authParams authority.AuthParams) (accesstokens.TokenResponse, error) { + if authParams.AuthorityInfo.AuthorityType == authority.ADFS { + if err := t.resolveEndpoint(ctx, &authParams, authParams.Username); err != nil { + return accesstokens.TokenResponse{}, err + } + return t.AccessTokens.FromUsernamePassword(ctx, authParams) + } + if err := t.resolveEndpoint(ctx, &authParams, ""); err != nil { + return accesstokens.TokenResponse{}, err + } + + userRealm, err := t.Authority.UserRealm(ctx, authParams) + if err != nil { + return accesstokens.TokenResponse{}, fmt.Errorf("problem getting user realm(user: %s) from authority: %w", authParams.Username, err) + } + + switch userRealm.AccountType { + case authority.Federated: + mexDoc, err := t.WSTrust.Mex(ctx, userRealm.FederationMetadataURL) + if err != nil { + return accesstokens.TokenResponse{}, fmt.Errorf("problem getting mex doc from federated url(%s): %w", userRealm.FederationMetadataURL, err) + } + + saml, err := t.WSTrust.SAMLTokenInfo(ctx, authParams, userRealm.CloudAudienceURN, mexDoc.UsernamePasswordEndpoint) + if err != nil { + return accesstokens.TokenResponse{}, fmt.Errorf("problem getting SAML token info: %w", err) + } + return t.AccessTokens.FromSamlGrant(ctx, authParams, saml) + case authority.Managed: + return t.AccessTokens.FromUsernamePassword(ctx, authParams) + } + return accesstokens.TokenResponse{}, errors.New("unknown account type") +} + +// DeviceCode is the result of a call to Token.DeviceCode(). +type DeviceCode struct { + // Result is the device code result from the first call in the device code flow. This allows + // the caller to retrieve the displayed code that is used to authorize on the second device. + Result accesstokens.DeviceCodeResult + authParams authority.AuthParams + + accessTokens AccessTokens +} + +// Token returns a token AFTER the user uses the user code on the second device. This will block +// until either: (1) the code is input by the user and the service releases a token, (2) the token +// expires, (3) the Context passed to .DeviceCode() is cancelled or expires, (4) some other service +// error occurs. +func (d DeviceCode) Token(ctx context.Context) (accesstokens.TokenResponse, error) { + if d.accessTokens == nil { + return accesstokens.TokenResponse{}, fmt.Errorf("DeviceCode was either created outside its package or the creating method had an error. DeviceCode is not valid") + } + + var cancel context.CancelFunc + d.Result.ExpiresOn.Sub(time.Now().UTC()) + if deadline, ok := ctx.Deadline(); !ok || d.Result.ExpiresOn.Before(deadline) { + ctx, cancel = context.WithDeadline(ctx, d.Result.ExpiresOn) + } else { + ctx, cancel = context.WithCancel(ctx) + } + defer cancel() + + var interval = 50 * time.Millisecond + timer := time.NewTimer(interval) + defer timer.Stop() + + for { + timer.Reset(interval) + select { + case <-ctx.Done(): + return accesstokens.TokenResponse{}, ctx.Err() + case <-timer.C: + interval += interval * 2 + if interval > 5*time.Second { + interval = 5 * time.Second + } + } + + token, err := d.accessTokens.FromDeviceCodeResult(ctx, d.authParams, d.Result) + if err != nil && isWaitDeviceCodeErr(err) { + continue + } + return token, err // This handles if it was a non-wait error or success + } +} + +type deviceCodeError struct { + Error string `json:"error"` +} + +func isWaitDeviceCodeErr(err error) bool { + var c errors.CallErr + if !errors.As(err, &c) { + return false + } + if c.Resp.StatusCode != 400 { + return false + } + var dCErr deviceCodeError + defer c.Resp.Body.Close() + body, err := io.ReadAll(c.Resp.Body) + if err != nil { + return false + } + err = json.Unmarshal(body, &dCErr) + if err != nil { + return false + } + if dCErr.Error == "authorization_pending" || dCErr.Error == "slow_down" { + return true + } + return false +} + +// DeviceCode returns a DeviceCode object that can be used to get the code that must be entered on the second +// device and optionally the token once the code has been entered on the second device. +func (t *Client) DeviceCode(ctx context.Context, authParams authority.AuthParams) (DeviceCode, error) { + if err := t.resolveEndpoint(ctx, &authParams, ""); err != nil { + return DeviceCode{}, err + } + + dcr, err := t.AccessTokens.DeviceCodeResult(ctx, authParams) + if err != nil { + return DeviceCode{}, err + } + + return DeviceCode{Result: dcr, authParams: authParams, accessTokens: t.AccessTokens}, nil +} + +func (t *Client) resolveEndpoint(ctx context.Context, authParams *authority.AuthParams, userPrincipalName string) error { + endpoints, err := t.Resolver.ResolveEndpoints(ctx, authParams.AuthorityInfo, userPrincipalName) + if err != nil { + return fmt.Errorf("unable to resolve an endpoint: %s", err) + } + authParams.Endpoints = endpoints + return nil +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens/accesstokens.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens/accesstokens.go new file mode 100644 index 00000000000..fa6bb61c8ef --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens/accesstokens.go @@ -0,0 +1,451 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +/* +Package accesstokens exposes a REST client for querying backend systems to get various types of +access tokens (oauth) for use in authentication. + +These calls are of type "application/x-www-form-urlencoded". This means we use url.Values to +represent arguments and then encode them into the POST body message. We receive JSON in +return for the requests. The request definition is defined in https://tools.ietf.org/html/rfc7521#section-4.2 . +*/ +package accesstokens + +import ( + "context" + "crypto" + + /* #nosec */ + "crypto/sha1" + "crypto/x509" + "encoding/base64" + "encoding/json" + "fmt" + "net/url" + "strconv" + "strings" + "time" + + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/exported" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/grant" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust" + "github.com/golang-jwt/jwt/v4" + "github.com/google/uuid" +) + +const ( + grantType = "grant_type" + deviceCode = "device_code" + clientID = "client_id" + clientInfo = "client_info" + clientInfoVal = "1" + username = "username" + password = "password" +) + +//go:generate stringer -type=AppType + +// AppType is whether the authorization code flow is for a public or confidential client. +type AppType int8 + +const ( + // ATUnknown is the zero value when the type hasn't been set. + ATUnknown AppType = iota + // ATPublic indicates this if for the Public.Client. + ATPublic + // ATConfidential indicates this if for the Confidential.Client. + ATConfidential +) + +type urlFormCaller interface { + URLFormCall(ctx context.Context, endpoint string, qv url.Values, resp interface{}) error +} + +// DeviceCodeResponse represents the HTTP response received from the device code endpoint +type DeviceCodeResponse struct { + authority.OAuthResponseBase + + UserCode string `json:"user_code"` + DeviceCode string `json:"device_code"` + VerificationURL string `json:"verification_url"` + ExpiresIn int `json:"expires_in"` + Interval int `json:"interval"` + Message string `json:"message"` + + AdditionalFields map[string]interface{} +} + +// Convert converts the DeviceCodeResponse to a DeviceCodeResult +func (dcr DeviceCodeResponse) Convert(clientID string, scopes []string) DeviceCodeResult { + expiresOn := time.Now().UTC().Add(time.Duration(dcr.ExpiresIn) * time.Second) + return NewDeviceCodeResult(dcr.UserCode, dcr.DeviceCode, dcr.VerificationURL, expiresOn, dcr.Interval, dcr.Message, clientID, scopes) +} + +// Credential represents the credential used in confidential client flows. This can be either +// a Secret or Cert/Key. +type Credential struct { + // Secret contains the credential secret if we are doing auth by secret. + Secret string + + // Cert is the public certificate, if we're authenticating by certificate. + Cert *x509.Certificate + // Key is the private key for signing, if we're authenticating by certificate. + Key crypto.PrivateKey + // X5c is the JWT assertion's x5c header value, required for SN/I authentication. + X5c []string + + // AssertionCallback is a function provided by the application, if we're authenticating by assertion. + AssertionCallback func(context.Context, exported.AssertionRequestOptions) (string, error) + + // TokenProvider is a function provided by the application that implements custom authentication + // logic for a confidential client + TokenProvider func(context.Context, exported.TokenProviderParameters) (exported.TokenProviderResult, error) +} + +// JWT gets the jwt assertion when the credential is not using a secret. +func (c *Credential) JWT(ctx context.Context, authParams authority.AuthParams) (string, error) { + if c.AssertionCallback != nil { + options := exported.AssertionRequestOptions{ + ClientID: authParams.ClientID, + TokenEndpoint: authParams.Endpoints.TokenEndpoint, + } + return c.AssertionCallback(ctx, options) + } + + token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{ + "aud": authParams.Endpoints.TokenEndpoint, + "exp": json.Number(strconv.FormatInt(time.Now().Add(10*time.Minute).Unix(), 10)), + "iss": authParams.ClientID, + "jti": uuid.New().String(), + "nbf": json.Number(strconv.FormatInt(time.Now().Unix(), 10)), + "sub": authParams.ClientID, + }) + token.Header = map[string]interface{}{ + "alg": "RS256", + "typ": "JWT", + "x5t": base64.StdEncoding.EncodeToString(thumbprint(c.Cert)), + } + + if authParams.SendX5C { + token.Header["x5c"] = c.X5c + } + + assertion, err := token.SignedString(c.Key) + if err != nil { + return "", fmt.Errorf("unable to sign a JWT token using private key: %w", err) + } + return assertion, nil +} + +// thumbprint runs the asn1.Der bytes through sha1 for use in the x5t parameter of JWT. +// https://tools.ietf.org/html/rfc7517#section-4.8 +func thumbprint(cert *x509.Certificate) []byte { + /* #nosec */ + a := sha1.Sum(cert.Raw) + return a[:] +} + +// Client represents the REST calls to get tokens from token generator backends. +type Client struct { + // Comm provides the HTTP transport client. + Comm urlFormCaller + + testing bool +} + +// FromUsernamePassword uses a username and password to get an access token. +func (c Client) FromUsernamePassword(ctx context.Context, authParameters authority.AuthParams) (TokenResponse, error) { + qv := url.Values{} + if err := addClaims(qv, authParameters); err != nil { + return TokenResponse{}, err + } + qv.Set(grantType, grant.Password) + qv.Set(username, authParameters.Username) + qv.Set(password, authParameters.Password) + qv.Set(clientID, authParameters.ClientID) + qv.Set(clientInfo, clientInfoVal) + addScopeQueryParam(qv, authParameters) + + return c.doTokenResp(ctx, authParameters, qv) +} + +// AuthCodeRequest stores the values required to request a token from the authority using an authorization code +type AuthCodeRequest struct { + AuthParams authority.AuthParams + Code string + CodeChallenge string + Credential *Credential + AppType AppType +} + +// NewCodeChallengeRequest returns an AuthCodeRequest that uses a code challenge.. +func NewCodeChallengeRequest(params authority.AuthParams, appType AppType, cc *Credential, code, challenge string) (AuthCodeRequest, error) { + if appType == ATUnknown { + return AuthCodeRequest{}, fmt.Errorf("bug: NewCodeChallengeRequest() called with AppType == ATUnknown") + } + return AuthCodeRequest{ + AuthParams: params, + AppType: appType, + Code: code, + CodeChallenge: challenge, + Credential: cc, + }, nil +} + +// FromAuthCode uses an authorization code to retrieve an access token. +func (c Client) FromAuthCode(ctx context.Context, req AuthCodeRequest) (TokenResponse, error) { + var qv url.Values + + switch req.AppType { + case ATUnknown: + return TokenResponse{}, fmt.Errorf("bug: Token.AuthCode() received request with AppType == ATUnknown") + case ATConfidential: + var err error + if req.Credential == nil { + return TokenResponse{}, fmt.Errorf("AuthCodeRequest had nil Credential for Confidential app") + } + qv, err = prepURLVals(ctx, req.Credential, req.AuthParams) + if err != nil { + return TokenResponse{}, err + } + case ATPublic: + qv = url.Values{} + default: + return TokenResponse{}, fmt.Errorf("bug: Token.AuthCode() received request with AppType == %v, which we do not recongnize", req.AppType) + } + + qv.Set(grantType, grant.AuthCode) + qv.Set("code", req.Code) + qv.Set("code_verifier", req.CodeChallenge) + qv.Set("redirect_uri", req.AuthParams.Redirecturi) + qv.Set(clientID, req.AuthParams.ClientID) + qv.Set(clientInfo, clientInfoVal) + addScopeQueryParam(qv, req.AuthParams) + if err := addClaims(qv, req.AuthParams); err != nil { + return TokenResponse{}, err + } + + return c.doTokenResp(ctx, req.AuthParams, qv) +} + +// FromRefreshToken uses a refresh token (for refreshing credentials) to get a new access token. +func (c Client) FromRefreshToken(ctx context.Context, appType AppType, authParams authority.AuthParams, cc *Credential, refreshToken string) (TokenResponse, error) { + qv := url.Values{} + if appType == ATConfidential { + var err error + qv, err = prepURLVals(ctx, cc, authParams) + if err != nil { + return TokenResponse{}, err + } + } + if err := addClaims(qv, authParams); err != nil { + return TokenResponse{}, err + } + qv.Set(grantType, grant.RefreshToken) + qv.Set(clientID, authParams.ClientID) + qv.Set(clientInfo, clientInfoVal) + qv.Set("refresh_token", refreshToken) + addScopeQueryParam(qv, authParams) + + return c.doTokenResp(ctx, authParams, qv) +} + +// FromClientSecret uses a client's secret (aka password) to get a new token. +func (c Client) FromClientSecret(ctx context.Context, authParameters authority.AuthParams, clientSecret string) (TokenResponse, error) { + qv := url.Values{} + if err := addClaims(qv, authParameters); err != nil { + return TokenResponse{}, err + } + qv.Set(grantType, grant.ClientCredential) + qv.Set("client_secret", clientSecret) + qv.Set(clientID, authParameters.ClientID) + addScopeQueryParam(qv, authParameters) + + token, err := c.doTokenResp(ctx, authParameters, qv) + if err != nil { + return token, fmt.Errorf("FromClientSecret(): %w", err) + } + return token, nil +} + +func (c Client) FromAssertion(ctx context.Context, authParameters authority.AuthParams, assertion string) (TokenResponse, error) { + qv := url.Values{} + if err := addClaims(qv, authParameters); err != nil { + return TokenResponse{}, err + } + qv.Set(grantType, grant.ClientCredential) + qv.Set("client_assertion_type", grant.ClientAssertion) + qv.Set("client_assertion", assertion) + qv.Set(clientID, authParameters.ClientID) + qv.Set(clientInfo, clientInfoVal) + addScopeQueryParam(qv, authParameters) + + token, err := c.doTokenResp(ctx, authParameters, qv) + if err != nil { + return token, fmt.Errorf("FromAssertion(): %w", err) + } + return token, nil +} + +func (c Client) FromUserAssertionClientSecret(ctx context.Context, authParameters authority.AuthParams, userAssertion string, clientSecret string) (TokenResponse, error) { + qv := url.Values{} + if err := addClaims(qv, authParameters); err != nil { + return TokenResponse{}, err + } + qv.Set(grantType, grant.JWT) + qv.Set(clientID, authParameters.ClientID) + qv.Set("client_secret", clientSecret) + qv.Set("assertion", userAssertion) + qv.Set(clientInfo, clientInfoVal) + qv.Set("requested_token_use", "on_behalf_of") + addScopeQueryParam(qv, authParameters) + + return c.doTokenResp(ctx, authParameters, qv) +} + +func (c Client) FromUserAssertionClientCertificate(ctx context.Context, authParameters authority.AuthParams, userAssertion string, assertion string) (TokenResponse, error) { + qv := url.Values{} + if err := addClaims(qv, authParameters); err != nil { + return TokenResponse{}, err + } + qv.Set(grantType, grant.JWT) + qv.Set("client_assertion_type", grant.ClientAssertion) + qv.Set("client_assertion", assertion) + qv.Set(clientID, authParameters.ClientID) + qv.Set("assertion", userAssertion) + qv.Set(clientInfo, clientInfoVal) + qv.Set("requested_token_use", "on_behalf_of") + addScopeQueryParam(qv, authParameters) + + return c.doTokenResp(ctx, authParameters, qv) +} + +func (c Client) DeviceCodeResult(ctx context.Context, authParameters authority.AuthParams) (DeviceCodeResult, error) { + qv := url.Values{} + if err := addClaims(qv, authParameters); err != nil { + return DeviceCodeResult{}, err + } + qv.Set(clientID, authParameters.ClientID) + addScopeQueryParam(qv, authParameters) + + endpoint := strings.Replace(authParameters.Endpoints.TokenEndpoint, "token", "devicecode", -1) + + resp := DeviceCodeResponse{} + err := c.Comm.URLFormCall(ctx, endpoint, qv, &resp) + if err != nil { + return DeviceCodeResult{}, err + } + + return resp.Convert(authParameters.ClientID, authParameters.Scopes), nil +} + +func (c Client) FromDeviceCodeResult(ctx context.Context, authParameters authority.AuthParams, deviceCodeResult DeviceCodeResult) (TokenResponse, error) { + qv := url.Values{} + if err := addClaims(qv, authParameters); err != nil { + return TokenResponse{}, err + } + qv.Set(grantType, grant.DeviceCode) + qv.Set(deviceCode, deviceCodeResult.DeviceCode) + qv.Set(clientID, authParameters.ClientID) + qv.Set(clientInfo, clientInfoVal) + addScopeQueryParam(qv, authParameters) + + return c.doTokenResp(ctx, authParameters, qv) +} + +func (c Client) FromSamlGrant(ctx context.Context, authParameters authority.AuthParams, samlGrant wstrust.SamlTokenInfo) (TokenResponse, error) { + qv := url.Values{} + if err := addClaims(qv, authParameters); err != nil { + return TokenResponse{}, err + } + qv.Set(username, authParameters.Username) + qv.Set(password, authParameters.Password) + qv.Set(clientID, authParameters.ClientID) + qv.Set(clientInfo, clientInfoVal) + qv.Set("assertion", base64.StdEncoding.WithPadding(base64.StdPadding).EncodeToString([]byte(samlGrant.Assertion))) + addScopeQueryParam(qv, authParameters) + + switch samlGrant.AssertionType { + case grant.SAMLV1: + qv.Set(grantType, grant.SAMLV1) + case grant.SAMLV2: + qv.Set(grantType, grant.SAMLV2) + default: + return TokenResponse{}, fmt.Errorf("GetAccessTokenFromSamlGrant returned unknown SAML assertion type: %q", samlGrant.AssertionType) + } + + return c.doTokenResp(ctx, authParameters, qv) +} + +func (c Client) doTokenResp(ctx context.Context, authParams authority.AuthParams, qv url.Values) (TokenResponse, error) { + resp := TokenResponse{} + err := c.Comm.URLFormCall(ctx, authParams.Endpoints.TokenEndpoint, qv, &resp) + if err != nil { + return resp, err + } + resp.ComputeScope(authParams) + if c.testing { + return resp, nil + } + return resp, resp.Validate() +} + +// prepURLVals returns an url.Values that sets various key/values if we are doing secrets +// or JWT assertions. +func prepURLVals(ctx context.Context, cc *Credential, authParams authority.AuthParams) (url.Values, error) { + params := url.Values{} + if cc.Secret != "" { + params.Set("client_secret", cc.Secret) + return params, nil + } + + jwt, err := cc.JWT(ctx, authParams) + if err != nil { + return nil, err + } + params.Set("client_assertion", jwt) + params.Set("client_assertion_type", grant.ClientAssertion) + return params, nil +} + +// openid required to get an id token +// offline_access required to get a refresh token +// profile required to get the client_info field back +var detectDefaultScopes = map[string]bool{ + "openid": true, + "offline_access": true, + "profile": true, +} + +var defaultScopes = []string{"openid", "offline_access", "profile"} + +func AppendDefaultScopes(authParameters authority.AuthParams) []string { + scopes := make([]string, 0, len(authParameters.Scopes)+len(defaultScopes)) + for _, scope := range authParameters.Scopes { + s := strings.TrimSpace(scope) + if s == "" { + continue + } + if detectDefaultScopes[scope] { + continue + } + scopes = append(scopes, scope) + } + scopes = append(scopes, defaultScopes...) + return scopes +} + +// addClaims adds client capabilities and claims from AuthParams to the given url.Values +func addClaims(v url.Values, ap authority.AuthParams) error { + claims, err := ap.MergeCapabilitiesAndClaims() + if err == nil && claims != "" { + v.Set("claims", claims) + } + return err +} + +func addScopeQueryParam(queryParams url.Values, authParameters authority.AuthParams) { + scopes := AppendDefaultScopes(authParameters) + queryParams.Set("scope", strings.Join(scopes, " ")) +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens/apptype_string.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens/apptype_string.go new file mode 100644 index 00000000000..3bec4a67cf1 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens/apptype_string.go @@ -0,0 +1,25 @@ +// Code generated by "stringer -type=AppType"; DO NOT EDIT. + +package accesstokens + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[ATUnknown-0] + _ = x[ATPublic-1] + _ = x[ATConfidential-2] +} + +const _AppType_name = "ATUnknownATPublicATConfidential" + +var _AppType_index = [...]uint8{0, 9, 17, 31} + +func (i AppType) String() string { + if i < 0 || i >= AppType(len(_AppType_index)-1) { + return "AppType(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _AppType_name[_AppType_index[i]:_AppType_index[i+1]] +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens/tokens.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens/tokens.go new file mode 100644 index 00000000000..b3892bf3f32 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens/tokens.go @@ -0,0 +1,335 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package accesstokens + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "reflect" + "strings" + "time" + + internalTime "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/types/time" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/shared" +) + +// IDToken consists of all the information used to validate a user. +// https://docs.microsoft.com/azure/active-directory/develop/id-tokens . +type IDToken struct { + PreferredUsername string `json:"preferred_username,omitempty"` + GivenName string `json:"given_name,omitempty"` + FamilyName string `json:"family_name,omitempty"` + MiddleName string `json:"middle_name,omitempty"` + Name string `json:"name,omitempty"` + Oid string `json:"oid,omitempty"` + TenantID string `json:"tid,omitempty"` + Subject string `json:"sub,omitempty"` + UPN string `json:"upn,omitempty"` + Email string `json:"email,omitempty"` + AlternativeID string `json:"alternative_id,omitempty"` + Issuer string `json:"iss,omitempty"` + Audience string `json:"aud,omitempty"` + ExpirationTime int64 `json:"exp,omitempty"` + IssuedAt int64 `json:"iat,omitempty"` + NotBefore int64 `json:"nbf,omitempty"` + RawToken string + + AdditionalFields map[string]interface{} +} + +var null = []byte("null") + +// UnmarshalJSON implements json.Unmarshaler. +func (i *IDToken) UnmarshalJSON(b []byte) error { + if bytes.Equal(null, b) { + return nil + } + + // Because we have a custom unmarshaler, you + // cannot directly call json.Unmarshal here. If you do, it will call this function + // recursively until reach our recursion limit. We have to create a new type + // that doesn't have this method in order to use json.Unmarshal. + type idToken2 IDToken + + jwt := strings.Trim(string(b), `"`) + jwtArr := strings.Split(jwt, ".") + if len(jwtArr) < 2 { + return errors.New("IDToken returned from server is invalid") + } + + jwtPart := jwtArr[1] + jwtDecoded, err := decodeJWT(jwtPart) + if err != nil { + return fmt.Errorf("unable to unmarshal IDToken, problem decoding JWT: %w", err) + } + + token := idToken2{} + err = json.Unmarshal(jwtDecoded, &token) + if err != nil { + return fmt.Errorf("unable to unmarshal IDToken: %w", err) + } + token.RawToken = jwt + + *i = IDToken(token) + return nil +} + +// IsZero indicates if the IDToken is the zero value. +func (i IDToken) IsZero() bool { + v := reflect.ValueOf(i) + for i := 0; i < v.NumField(); i++ { + field := v.Field(i) + if !field.IsZero() { + switch field.Kind() { + case reflect.Map, reflect.Slice: + if field.Len() == 0 { + continue + } + } + return false + } + } + return true +} + +// LocalAccountID extracts an account's local account ID from an ID token. +func (i IDToken) LocalAccountID() string { + if i.Oid != "" { + return i.Oid + } + return i.Subject +} + +// jwtDecoder is provided to allow tests to provide their own. +var jwtDecoder = decodeJWT + +// ClientInfo is used to create a Home Account ID for an account. +type ClientInfo struct { + UID string `json:"uid"` + UTID string `json:"utid"` + + AdditionalFields map[string]interface{} +} + +// UnmarshalJSON implements json.Unmarshaler.s +func (c *ClientInfo) UnmarshalJSON(b []byte) error { + s := strings.Trim(string(b), `"`) + // Client info may be empty in some flows, e.g. certificate exchange. + if len(s) == 0 { + return nil + } + + // Because we have a custom unmarshaler, you + // cannot directly call json.Unmarshal here. If you do, it will call this function + // recursively until reach our recursion limit. We have to create a new type + // that doesn't have this method in order to use json.Unmarshal. + type clientInfo2 ClientInfo + + raw, err := jwtDecoder(s) + if err != nil { + return fmt.Errorf("TokenResponse client_info field had JWT decode error: %w", err) + } + + var c2 clientInfo2 + + err = json.Unmarshal(raw, &c2) + if err != nil { + return fmt.Errorf("was unable to unmarshal decoded JWT in TokenRespone to ClientInfo: %w", err) + } + + *c = ClientInfo(c2) + return nil +} + +// HomeAccountID creates the home account ID. +func (c ClientInfo) HomeAccountID() string { + if c.UID == "" { + return "" + } else if c.UTID == "" { + return fmt.Sprintf("%s.%s", c.UID, c.UID) + } else { + return fmt.Sprintf("%s.%s", c.UID, c.UTID) + } +} + +// Scopes represents scopes in a TokenResponse. +type Scopes struct { + Slice []string +} + +// UnmarshalJSON implements json.Unmarshal. +func (s *Scopes) UnmarshalJSON(b []byte) error { + str := strings.Trim(string(b), `"`) + if len(str) == 0 { + return nil + } + sl := strings.Split(str, " ") + s.Slice = sl + return nil +} + +// TokenResponse is the information that is returned from a token endpoint during a token acquisition flow. +type TokenResponse struct { + authority.OAuthResponseBase + + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token"` + + FamilyID string `json:"foci"` + IDToken IDToken `json:"id_token"` + ClientInfo ClientInfo `json:"client_info"` + ExpiresOn internalTime.DurationTime `json:"expires_in"` + ExtExpiresOn internalTime.DurationTime `json:"ext_expires_in"` + GrantedScopes Scopes `json:"scope"` + DeclinedScopes []string // This is derived + + AdditionalFields map[string]interface{} + + scopesComputed bool +} + +// ComputeScope computes the final scopes based on what was granted by the server and +// what our AuthParams were from the authority server. Per OAuth spec, if no scopes are returned, the response should be treated as if all scopes were granted +// This behavior can be observed in client assertion flows, but can happen at any time, this check ensures we treat +// those special responses properly Link to spec: https://tools.ietf.org/html/rfc6749#section-3.3 +func (tr *TokenResponse) ComputeScope(authParams authority.AuthParams) { + if len(tr.GrantedScopes.Slice) == 0 { + tr.GrantedScopes = Scopes{Slice: authParams.Scopes} + } else { + tr.DeclinedScopes = findDeclinedScopes(authParams.Scopes, tr.GrantedScopes.Slice) + } + tr.scopesComputed = true +} + +// Validate validates the TokenResponse has basic valid values. It must be called +// after ComputeScopes() is called. +func (tr *TokenResponse) Validate() error { + if tr.Error != "" { + return fmt.Errorf("%s: %s", tr.Error, tr.ErrorDescription) + } + + if tr.AccessToken == "" { + return errors.New("response is missing access_token") + } + + if !tr.scopesComputed { + return fmt.Errorf("TokenResponse hasn't had ScopesComputed() called") + } + return nil +} + +func (tr *TokenResponse) CacheKey(authParams authority.AuthParams) string { + if authParams.AuthorizationType == authority.ATOnBehalfOf { + return authParams.AssertionHash() + } + if authParams.AuthorizationType == authority.ATClientCredentials { + return authParams.AppKey() + } + if authParams.IsConfidentialClient || authParams.AuthorizationType == authority.ATRefreshToken { + return tr.ClientInfo.HomeAccountID() + } + return "" +} + +func findDeclinedScopes(requestedScopes []string, grantedScopes []string) []string { + declined := []string{} + grantedMap := map[string]bool{} + for _, s := range grantedScopes { + grantedMap[strings.ToLower(s)] = true + } + // Comparing the requested scopes with the granted scopes to see if there are any scopes that have been declined. + for _, r := range requestedScopes { + if !grantedMap[strings.ToLower(r)] { + declined = append(declined, r) + } + } + return declined +} + +// decodeJWT decodes a JWT and converts it to a byte array representing a JSON object +// JWT has headers and payload base64url encoded without padding +// https://tools.ietf.org/html/rfc7519#section-3 and +// https://tools.ietf.org/html/rfc7515#section-2 +func decodeJWT(data string) ([]byte, error) { + // https://tools.ietf.org/html/rfc7515#appendix-C + return base64.RawURLEncoding.DecodeString(data) +} + +// RefreshToken is the JSON representation of a MSAL refresh token for encoding to storage. +type RefreshToken struct { + HomeAccountID string `json:"home_account_id,omitempty"` + Environment string `json:"environment,omitempty"` + CredentialType string `json:"credential_type,omitempty"` + ClientID string `json:"client_id,omitempty"` + FamilyID string `json:"family_id,omitempty"` + Secret string `json:"secret,omitempty"` + Realm string `json:"realm,omitempty"` + Target string `json:"target,omitempty"` + UserAssertionHash string `json:"user_assertion_hash,omitempty"` + + AdditionalFields map[string]interface{} +} + +// NewRefreshToken is the constructor for RefreshToken. +func NewRefreshToken(homeID, env, clientID, refreshToken, familyID string) RefreshToken { + return RefreshToken{ + HomeAccountID: homeID, + Environment: env, + CredentialType: "RefreshToken", + ClientID: clientID, + FamilyID: familyID, + Secret: refreshToken, + } +} + +// Key outputs the key that can be used to uniquely look up this entry in a map. +func (rt RefreshToken) Key() string { + var fourth = rt.FamilyID + if fourth == "" { + fourth = rt.ClientID + } + + return strings.Join( + []string{rt.HomeAccountID, rt.Environment, rt.CredentialType, fourth}, + shared.CacheKeySeparator, + ) +} + +func (rt RefreshToken) GetSecret() string { + return rt.Secret +} + +// DeviceCodeResult stores the response from the STS device code endpoint. +type DeviceCodeResult struct { + // UserCode is the code the user needs to provide when authentication at the verification URI. + UserCode string + // DeviceCode is the code used in the access token request. + DeviceCode string + // VerificationURL is the the URL where user can authenticate. + VerificationURL string + // ExpiresOn is the expiration time of device code in seconds. + ExpiresOn time.Time + // Interval is the interval at which the STS should be polled at. + Interval int + // Message is the message which should be displayed to the user. + Message string + // ClientID is the UUID issued by the authorization server for your application. + ClientID string + // Scopes is the OpenID scopes used to request access a protected API. + Scopes []string +} + +// NewDeviceCodeResult creates a DeviceCodeResult instance. +func NewDeviceCodeResult(userCode, deviceCode, verificationURL string, expiresOn time.Time, interval int, message, clientID string, scopes []string) DeviceCodeResult { + return DeviceCodeResult{userCode, deviceCode, verificationURL, expiresOn, interval, message, clientID, scopes} +} + +func (dcr DeviceCodeResult) String() string { + return fmt.Sprintf("UserCode: (%v)\nDeviceCode: (%v)\nURL: (%v)\nMessage: (%v)\n", dcr.UserCode, dcr.DeviceCode, dcr.VerificationURL, dcr.Message) + +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority/authority.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority/authority.go new file mode 100644 index 00000000000..de5f053f7d1 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority/authority.go @@ -0,0 +1,545 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package authority + +import ( + "context" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "path" + "strings" + "time" + + "github.com/google/uuid" +) + +const ( + authorizationEndpoint = "https://%v/%v/oauth2/v2.0/authorize" + instanceDiscoveryEndpoint = "https://%v/common/discovery/instance" + tenantDiscoveryEndpointWithRegion = "https://%s.%s/%s/v2.0/.well-known/openid-configuration" + regionName = "REGION_NAME" + defaultAPIVersion = "2021-10-01" + imdsEndpoint = "http://169.254.169.254/metadata/instance/compute/location?format=text&api-version=" + defaultAPIVersion + defaultHost = "login.microsoftonline.com" + autoDetectRegion = "TryAutoDetect" +) + +type jsonCaller interface { + JSONCall(ctx context.Context, endpoint string, headers http.Header, qv url.Values, body, resp interface{}) error +} + +var aadTrustedHostList = map[string]bool{ + "login.windows.net": true, // Microsoft Azure Worldwide - Used in validation scenarios where host is not this list + "login.chinacloudapi.cn": true, // Microsoft Azure China + "login.microsoftonline.de": true, // Microsoft Azure Blackforest + "login-us.microsoftonline.com": true, // Microsoft Azure US Government - Legacy + "login.microsoftonline.us": true, // Microsoft Azure US Government + "login.microsoftonline.com": true, // Microsoft Azure Worldwide + "login.cloudgovapi.us": true, // Microsoft Azure US Government +} + +// TrustedHost checks if an AAD host is trusted/valid. +func TrustedHost(host string) bool { + if _, ok := aadTrustedHostList[host]; ok { + return true + } + return false +} + +type OAuthResponseBase struct { + Error string `json:"error"` + SubError string `json:"suberror"` + ErrorDescription string `json:"error_description"` + ErrorCodes []int `json:"error_codes"` + CorrelationID string `json:"correlation_id"` + Claims string `json:"claims"` +} + +// TenantDiscoveryResponse is the tenant endpoints from the OpenID configuration endpoint. +type TenantDiscoveryResponse struct { + OAuthResponseBase + + AuthorizationEndpoint string `json:"authorization_endpoint"` + TokenEndpoint string `json:"token_endpoint"` + Issuer string `json:"issuer"` + + AdditionalFields map[string]interface{} +} + +// Validate validates that the response had the correct values required. +func (r *TenantDiscoveryResponse) Validate() error { + switch "" { + case r.AuthorizationEndpoint: + return errors.New("TenantDiscoveryResponse: authorize endpoint was not found in the openid configuration") + case r.TokenEndpoint: + return errors.New("TenantDiscoveryResponse: token endpoint was not found in the openid configuration") + case r.Issuer: + return errors.New("TenantDiscoveryResponse: issuer was not found in the openid configuration") + } + return nil +} + +type InstanceDiscoveryMetadata struct { + PreferredNetwork string `json:"preferred_network"` + PreferredCache string `json:"preferred_cache"` + Aliases []string `json:"aliases"` + + AdditionalFields map[string]interface{} +} + +type InstanceDiscoveryResponse struct { + TenantDiscoveryEndpoint string `json:"tenant_discovery_endpoint"` + Metadata []InstanceDiscoveryMetadata `json:"metadata"` + + AdditionalFields map[string]interface{} +} + +//go:generate stringer -type=AuthorizeType + +// AuthorizeType represents the type of token flow. +type AuthorizeType int + +// These are all the types of token flows. +const ( + ATUnknown AuthorizeType = iota + ATUsernamePassword + ATWindowsIntegrated + ATAuthCode + ATInteractive + ATClientCredentials + ATDeviceCode + ATRefreshToken + AccountByID + ATOnBehalfOf +) + +// These are all authority types +const ( + AAD = "MSSTS" + ADFS = "ADFS" +) + +// AuthParams represents the parameters used for authorization for token acquisition. +type AuthParams struct { + AuthorityInfo Info + CorrelationID string + Endpoints Endpoints + ClientID string + // Redirecturi is used for auth flows that specify a redirect URI (e.g. local server for interactive auth flow). + Redirecturi string + HomeAccountID string + // Username is the user-name portion for username/password auth flow. + Username string + // Password is the password portion for username/password auth flow. + Password string + // Scopes is the list of scopes the user consents to. + Scopes []string + // AuthorizationType specifies the auth flow being used. + AuthorizationType AuthorizeType + // State is a random value used to prevent cross-site request forgery attacks. + State string + // CodeChallenge is derived from a code verifier and is sent in the auth request. + CodeChallenge string + // CodeChallengeMethod describes the method used to create the CodeChallenge. + CodeChallengeMethod string + // Prompt specifies the user prompt type during interactive auth. + Prompt string + // IsConfidentialClient specifies if it is a confidential client. + IsConfidentialClient bool + // SendX5C specifies if x5c claim(public key of the certificate) should be sent to STS. + SendX5C bool + // UserAssertion is the access token used to acquire token on behalf of user + UserAssertion string + // Capabilities the client will include with each token request, for example "CP1". + // Call [NewClientCapabilities] to construct a value for this field. + Capabilities ClientCapabilities + // Claims required for an access token to satisfy a conditional access policy + Claims string + // KnownAuthorityHosts don't require metadata discovery because they're known to the user + KnownAuthorityHosts []string + // LoginHint is a username with which to pre-populate account selection during interactive auth + LoginHint string + // DomainHint is a directive that can be used to accelerate the user to their federated IdP sign-in page + DomainHint string +} + +// NewAuthParams creates an authorization parameters object. +func NewAuthParams(clientID string, authorityInfo Info) AuthParams { + return AuthParams{ + ClientID: clientID, + AuthorityInfo: authorityInfo, + CorrelationID: uuid.New().String(), + } +} + +// WithTenant returns a copy of the AuthParams having the specified tenant ID. If the given +// ID is empty, the copy is identical to the original. This function returns an error in +// several cases: +// - ID isn't specific (for example, it's "common") +// - ID is non-empty and the authority doesn't support tenants (for example, it's an ADFS authority) +// - the client is configured to authenticate only Microsoft accounts via the "consumers" endpoint +// - the resulting authority URL is invalid +func (p AuthParams) WithTenant(ID string) (AuthParams, error) { + switch ID { + case "", p.AuthorityInfo.Tenant: + // keep the default tenant because the caller didn't override it + return p, nil + case "common", "consumers", "organizations": + if p.AuthorityInfo.AuthorityType == AAD { + return p, fmt.Errorf(`tenant ID must be a specific tenant, not "%s"`, ID) + } + // else we'll return a better error below + } + if p.AuthorityInfo.AuthorityType != AAD { + return p, errors.New("the authority doesn't support tenants") + } + if p.AuthorityInfo.Tenant == "consumers" { + return p, errors.New(`client is configured to authenticate only personal Microsoft accounts, via the "consumers" endpoint`) + } + authority := "https://" + path.Join(p.AuthorityInfo.Host, ID) + info, err := NewInfoFromAuthorityURI(authority, p.AuthorityInfo.ValidateAuthority, p.AuthorityInfo.InstanceDiscoveryDisabled) + if err == nil { + info.Region = p.AuthorityInfo.Region + p.AuthorityInfo = info + } + return p, err +} + +// MergeCapabilitiesAndClaims combines client capabilities and challenge claims into a value suitable for an authentication request's "claims" parameter. +func (p AuthParams) MergeCapabilitiesAndClaims() (string, error) { + claims := p.Claims + if len(p.Capabilities.asMap) > 0 { + if claims == "" { + // without claims the result is simply the capabilities + return p.Capabilities.asJSON, nil + } + // Otherwise, merge claims and capabilties into a single JSON object. + // We handle the claims challenge as a map because we don't know its structure. + var challenge map[string]any + if err := json.Unmarshal([]byte(claims), &challenge); err != nil { + return "", fmt.Errorf(`claims must be JSON. Are they base64 encoded? json.Unmarshal returned "%v"`, err) + } + if err := merge(p.Capabilities.asMap, challenge); err != nil { + return "", err + } + b, err := json.Marshal(challenge) + if err != nil { + return "", err + } + claims = string(b) + } + return claims, nil +} + +// merges a into b without overwriting b's values. Returns an error when a and b share a key for which either has a non-object value. +func merge(a, b map[string]any) error { + for k, av := range a { + if bv, ok := b[k]; !ok { + // b doesn't contain this key => simply set it to a's value + b[k] = av + } else { + // b does contain this key => recursively merge a[k] into b[k], provided both are maps. If a[k] or b[k] isn't + // a map, return an error because merging would overwrite some value in b. Errors shouldn't occur in practice + // because the challenge will be from AAD, which knows the capabilities format. + if A, ok := av.(map[string]any); ok { + if B, ok := bv.(map[string]any); ok { + return merge(A, B) + } else { + // b[k] isn't a map + return errors.New("challenge claims conflict with client capabilities") + } + } else { + // a[k] isn't a map + return errors.New("challenge claims conflict with client capabilities") + } + } + } + return nil +} + +// ClientCapabilities stores capabilities in the formats used by AuthParams.MergeCapabilitiesAndClaims. +// [NewClientCapabilities] precomputes these representations because capabilities are static for the +// lifetime of a client and are included with every authentication request i.e., these computations +// always have the same result and would otherwise have to be repeated for every request. +type ClientCapabilities struct { + // asJSON is for the common case: adding the capabilities to an auth request with no challenge claims + asJSON string + // asMap is for merging the capabilities with challenge claims + asMap map[string]any +} + +func NewClientCapabilities(capabilities []string) (ClientCapabilities, error) { + c := ClientCapabilities{} + var err error + if len(capabilities) > 0 { + cpbs := make([]string, len(capabilities)) + for i := 0; i < len(cpbs); i++ { + cpbs[i] = fmt.Sprintf(`"%s"`, capabilities[i]) + } + c.asJSON = fmt.Sprintf(`{"access_token":{"xms_cc":{"values":[%s]}}}`, strings.Join(cpbs, ",")) + // note our JSON is valid but we can't stop users breaking it with garbage like "}" + err = json.Unmarshal([]byte(c.asJSON), &c.asMap) + } + return c, err +} + +// Info consists of information about the authority. +type Info struct { + Host string + CanonicalAuthorityURI string + AuthorityType string + UserRealmURIPrefix string + ValidateAuthority bool + Tenant string + Region string + InstanceDiscoveryDisabled bool +} + +func firstPathSegment(u *url.URL) (string, error) { + pathParts := strings.Split(u.EscapedPath(), "/") + if len(pathParts) >= 2 { + return pathParts[1], nil + } + + return "", errors.New("authority does not have two segments") +} + +// NewInfoFromAuthorityURI creates an AuthorityInfo instance from the authority URL provided. +func NewInfoFromAuthorityURI(authorityURI string, validateAuthority bool, instanceDiscoveryDisabled bool) (Info, error) { + authorityURI = strings.ToLower(authorityURI) + var authorityType string + u, err := url.Parse(authorityURI) + if err != nil { + return Info{}, fmt.Errorf("authorityURI passed could not be parsed: %w", err) + } + if u.Scheme != "https" { + return Info{}, fmt.Errorf("authorityURI(%s) must have scheme https", authorityURI) + } + + tenant, err := firstPathSegment(u) + if tenant == "adfs" { + authorityType = ADFS + } else { + authorityType = AAD + } + + if err != nil { + return Info{}, err + } + + // u.Host includes the port, if any, which is required for private cloud deployments + return Info{ + Host: u.Host, + CanonicalAuthorityURI: fmt.Sprintf("https://%v/%v/", u.Host, tenant), + AuthorityType: authorityType, + UserRealmURIPrefix: fmt.Sprintf("https://%v/common/userrealm/", u.Hostname()), + ValidateAuthority: validateAuthority, + Tenant: tenant, + InstanceDiscoveryDisabled: instanceDiscoveryDisabled, + }, nil +} + +// Endpoints consists of the endpoints from the tenant discovery response. +type Endpoints struct { + AuthorizationEndpoint string + TokenEndpoint string + selfSignedJwtAudience string + authorityHost string +} + +// NewEndpoints creates an Endpoints object. +func NewEndpoints(authorizationEndpoint string, tokenEndpoint string, selfSignedJwtAudience string, authorityHost string) Endpoints { + return Endpoints{authorizationEndpoint, tokenEndpoint, selfSignedJwtAudience, authorityHost} +} + +// UserRealmAccountType refers to the type of user realm. +type UserRealmAccountType string + +// These are the different types of user realms. +const ( + Unknown UserRealmAccountType = "" + Federated UserRealmAccountType = "Federated" + Managed UserRealmAccountType = "Managed" +) + +// UserRealm is used for the username password request to determine user type +type UserRealm struct { + AccountType UserRealmAccountType `json:"account_type"` + DomainName string `json:"domain_name"` + CloudInstanceName string `json:"cloud_instance_name"` + CloudAudienceURN string `json:"cloud_audience_urn"` + + // required if accountType is Federated + FederationProtocol string `json:"federation_protocol"` + FederationMetadataURL string `json:"federation_metadata_url"` + + AdditionalFields map[string]interface{} +} + +func (u UserRealm) validate() error { + switch "" { + case string(u.AccountType): + return errors.New("the account type (Federated or Managed) is missing") + case u.DomainName: + return errors.New("domain name of user realm is missing") + case u.CloudInstanceName: + return errors.New("cloud instance name of user realm is missing") + case u.CloudAudienceURN: + return errors.New("cloud Instance URN is missing") + } + + if u.AccountType == Federated { + switch "" { + case u.FederationProtocol: + return errors.New("federation protocol of user realm is missing") + case u.FederationMetadataURL: + return errors.New("federation metadata URL of user realm is missing") + } + } + return nil +} + +// Client represents the REST calls to authority backends. +type Client struct { + // Comm provides the HTTP transport client. + Comm jsonCaller // *comm.Client +} + +func (c Client) UserRealm(ctx context.Context, authParams AuthParams) (UserRealm, error) { + endpoint := fmt.Sprintf("https://%s/common/UserRealm/%s", authParams.Endpoints.authorityHost, url.PathEscape(authParams.Username)) + qv := url.Values{ + "api-version": []string{"1.0"}, + } + + resp := UserRealm{} + err := c.Comm.JSONCall( + ctx, + endpoint, + http.Header{"client-request-id": []string{authParams.CorrelationID}}, + qv, + nil, + &resp, + ) + if err != nil { + return resp, err + } + + return resp, resp.validate() +} + +func (c Client) GetTenantDiscoveryResponse(ctx context.Context, openIDConfigurationEndpoint string) (TenantDiscoveryResponse, error) { + resp := TenantDiscoveryResponse{} + err := c.Comm.JSONCall( + ctx, + openIDConfigurationEndpoint, + http.Header{}, + nil, + nil, + &resp, + ) + + return resp, err +} + +func (c Client) AADInstanceDiscovery(ctx context.Context, authorityInfo Info) (InstanceDiscoveryResponse, error) { + region := "" + var err error + resp := InstanceDiscoveryResponse{} + if authorityInfo.Region != "" && authorityInfo.Region != autoDetectRegion { + region = authorityInfo.Region + } else if authorityInfo.Region == autoDetectRegion { + region = detectRegion(ctx) + } + if region != "" { + environment := authorityInfo.Host + switch environment { + case "login.microsoft.com", "login.windows.net", "sts.windows.net", defaultHost: + environment = "r." + defaultHost + } + resp.TenantDiscoveryEndpoint = fmt.Sprintf(tenantDiscoveryEndpointWithRegion, region, environment, authorityInfo.Tenant) + metadata := InstanceDiscoveryMetadata{ + PreferredNetwork: fmt.Sprintf("%v.%v", region, authorityInfo.Host), + PreferredCache: authorityInfo.Host, + Aliases: []string{fmt.Sprintf("%v.%v", region, authorityInfo.Host), authorityInfo.Host}, + } + resp.Metadata = []InstanceDiscoveryMetadata{metadata} + } else { + qv := url.Values{} + qv.Set("api-version", "1.1") + qv.Set("authorization_endpoint", fmt.Sprintf(authorizationEndpoint, authorityInfo.Host, authorityInfo.Tenant)) + + discoveryHost := defaultHost + if TrustedHost(authorityInfo.Host) { + discoveryHost = authorityInfo.Host + } + + endpoint := fmt.Sprintf(instanceDiscoveryEndpoint, discoveryHost) + err = c.Comm.JSONCall(ctx, endpoint, http.Header{}, qv, nil, &resp) + } + return resp, err +} + +func detectRegion(ctx context.Context) string { + region := os.Getenv(regionName) + if region != "" { + region = strings.ReplaceAll(region, " ", "") + return strings.ToLower(region) + } + // HTTP call to IMDS endpoint to get region + // Refer : https://identitydivision.visualstudio.com/DevEx/_git/AuthLibrariesApiReview?path=%2FPinAuthToRegion%2FAAD%20SDK%20Proposal%20to%20Pin%20Auth%20to%20region.md&_a=preview&version=GBdev + // Set a 2 second timeout for this http client which only does calls to IMDS endpoint + client := http.Client{ + Timeout: time.Duration(2 * time.Second), + } + req, _ := http.NewRequest("GET", imdsEndpoint, nil) + req.Header.Set("Metadata", "true") + resp, err := client.Do(req) + // If the request times out or there is an error, it is retried once + if err != nil || resp.StatusCode != 200 { + resp, err = client.Do(req) + if err != nil || resp.StatusCode != 200 { + return "" + } + } + defer resp.Body.Close() + response, err := io.ReadAll(resp.Body) + if err != nil { + return "" + } + return string(response) +} + +func (a *AuthParams) CacheKey(isAppCache bool) string { + if a.AuthorizationType == ATOnBehalfOf { + return a.AssertionHash() + } + if a.AuthorizationType == ATClientCredentials || isAppCache { + return a.AppKey() + } + if a.AuthorizationType == ATRefreshToken || a.AuthorizationType == AccountByID { + return a.HomeAccountID + } + return "" +} +func (a *AuthParams) AssertionHash() string { + hasher := sha256.New() + // Per documentation this never returns an error : https://pkg.go.dev/hash#pkg-types + _, _ = hasher.Write([]byte(a.UserAssertion)) + sha := base64.URLEncoding.EncodeToString(hasher.Sum(nil)) + return sha +} + +func (a *AuthParams) AppKey() string { + if a.AuthorityInfo.Tenant != "" { + return fmt.Sprintf("%s_%s_AppTokenCache", a.ClientID, a.AuthorityInfo.Tenant) + } + return fmt.Sprintf("%s__AppTokenCache", a.ClientID) +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority/authorizetype_string.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority/authorizetype_string.go new file mode 100644 index 00000000000..10039773b06 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority/authorizetype_string.go @@ -0,0 +1,30 @@ +// Code generated by "stringer -type=AuthorizeType"; DO NOT EDIT. + +package authority + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[ATUnknown-0] + _ = x[ATUsernamePassword-1] + _ = x[ATWindowsIntegrated-2] + _ = x[ATAuthCode-3] + _ = x[ATInteractive-4] + _ = x[ATClientCredentials-5] + _ = x[ATDeviceCode-6] + _ = x[ATRefreshToken-7] +} + +const _AuthorizeType_name = "ATUnknownATUsernamePasswordATWindowsIntegratedATAuthCodeATInteractiveATClientCredentialsATDeviceCodeATRefreshToken" + +var _AuthorizeType_index = [...]uint8{0, 9, 27, 46, 56, 69, 88, 100, 114} + +func (i AuthorizeType) String() string { + if i < 0 || i >= AuthorizeType(len(_AuthorizeType_index)-1) { + return "AuthorizeType(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _AuthorizeType_name[_AuthorizeType_index[i]:_AuthorizeType_index[i+1]] +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/comm/comm.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/comm/comm.go new file mode 100644 index 00000000000..7d9ec7cd374 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/comm/comm.go @@ -0,0 +1,320 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +// Package comm provides helpers for communicating with HTTP backends. +package comm + +import ( + "bytes" + "context" + "encoding/json" + "encoding/xml" + "fmt" + "io" + "net/http" + "net/url" + "reflect" + "runtime" + "strings" + "time" + + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/errors" + customJSON "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/version" + "github.com/google/uuid" +) + +// HTTPClient represents an HTTP client. +// It's usually an *http.Client from the standard library. +type HTTPClient interface { + // Do sends an HTTP request and returns an HTTP response. + Do(req *http.Request) (*http.Response, error) + + // CloseIdleConnections closes any idle connections in a "keep-alive" state. + CloseIdleConnections() +} + +// Client provides a wrapper to our *http.Client that handles compression and serialization needs. +type Client struct { + client HTTPClient +} + +// New returns a new Client object. +func New(httpClient HTTPClient) *Client { + if httpClient == nil { + panic("http.Client cannot == nil") + } + + return &Client{client: httpClient} +} + +// JSONCall connects to the REST endpoint passing the HTTP query values, headers and JSON conversion +// of body in the HTTP body. It automatically handles compression and decompression with gzip. The response is JSON +// unmarshalled into resp. resp must be a pointer to a struct. If the body struct contains a field called +// "AdditionalFields" we use a custom marshal/unmarshal engine. +func (c *Client) JSONCall(ctx context.Context, endpoint string, headers http.Header, qv url.Values, body, resp interface{}) error { + if qv == nil { + qv = url.Values{} + } + + v := reflect.ValueOf(resp) + if err := c.checkResp(v); err != nil { + return err + } + + // Choose a JSON marshal/unmarshal depending on if we have AdditionalFields attribute. + var marshal = json.Marshal + var unmarshal = json.Unmarshal + if _, ok := v.Elem().Type().FieldByName("AdditionalFields"); ok { + marshal = customJSON.Marshal + unmarshal = customJSON.Unmarshal + } + + u, err := url.Parse(endpoint) + if err != nil { + return fmt.Errorf("could not parse path URL(%s): %w", endpoint, err) + } + u.RawQuery = qv.Encode() + + addStdHeaders(headers) + + req := &http.Request{Method: http.MethodGet, URL: u, Header: headers} + + if body != nil { + // Note: In case your wondering why we are not gzip encoding.... + // I'm not sure if these various services support gzip on send. + headers.Add("Content-Type", "application/json; charset=utf-8") + data, err := marshal(body) + if err != nil { + return fmt.Errorf("bug: conn.Call(): could not marshal the body object: %w", err) + } + req.Body = io.NopCloser(bytes.NewBuffer(data)) + req.Method = http.MethodPost + } + + data, err := c.do(ctx, req) + if err != nil { + return err + } + + if resp != nil { + if err := unmarshal(data, resp); err != nil { + return fmt.Errorf("json decode error: %w\njson message bytes were: %s", err, string(data)) + } + } + return nil +} + +// XMLCall connects to an endpoint and decodes the XML response into resp. This is used when +// sending application/xml . If sending XML via SOAP, use SOAPCall(). +func (c *Client) XMLCall(ctx context.Context, endpoint string, headers http.Header, qv url.Values, resp interface{}) error { + if err := c.checkResp(reflect.ValueOf(resp)); err != nil { + return err + } + + if qv == nil { + qv = url.Values{} + } + + u, err := url.Parse(endpoint) + if err != nil { + return fmt.Errorf("could not parse path URL(%s): %w", endpoint, err) + } + u.RawQuery = qv.Encode() + + headers.Set("Content-Type", "application/xml; charset=utf-8") // This was not set in he original Mex(), but... + addStdHeaders(headers) + + return c.xmlCall(ctx, u, headers, "", resp) +} + +// SOAPCall returns the SOAP message given an endpoint, action, body of the request and the response object to marshal into. +func (c *Client) SOAPCall(ctx context.Context, endpoint, action string, headers http.Header, qv url.Values, body string, resp interface{}) error { + if body == "" { + return fmt.Errorf("cannot make a SOAP call with body set to empty string") + } + + if err := c.checkResp(reflect.ValueOf(resp)); err != nil { + return err + } + + if qv == nil { + qv = url.Values{} + } + + u, err := url.Parse(endpoint) + if err != nil { + return fmt.Errorf("could not parse path URL(%s): %w", endpoint, err) + } + u.RawQuery = qv.Encode() + + headers.Set("Content-Type", "application/soap+xml; charset=utf-8") + headers.Set("SOAPAction", action) + addStdHeaders(headers) + + return c.xmlCall(ctx, u, headers, body, resp) +} + +// xmlCall sends an XML in body and decodes into resp. This simply does the transport and relies on +// an upper level call to set things such as SOAP parameters and Content-Type, if required. +func (c *Client) xmlCall(ctx context.Context, u *url.URL, headers http.Header, body string, resp interface{}) error { + req := &http.Request{Method: http.MethodGet, URL: u, Header: headers} + + if len(body) > 0 { + req.Method = http.MethodPost + req.Body = io.NopCloser(strings.NewReader(body)) + } + + data, err := c.do(ctx, req) + if err != nil { + return err + } + + return xml.Unmarshal(data, resp) +} + +// URLFormCall is used to make a call where we need to send application/x-www-form-urlencoded data +// to the backend and receive JSON back. qv will be encoded into the request body. +func (c *Client) URLFormCall(ctx context.Context, endpoint string, qv url.Values, resp interface{}) error { + if len(qv) == 0 { + return fmt.Errorf("URLFormCall() requires qv to have non-zero length") + } + + if err := c.checkResp(reflect.ValueOf(resp)); err != nil { + return err + } + + u, err := url.Parse(endpoint) + if err != nil { + return fmt.Errorf("could not parse path URL(%s): %w", endpoint, err) + } + + headers := http.Header{} + headers.Set("Content-Type", "application/x-www-form-urlencoded; charset=utf-8") + addStdHeaders(headers) + + enc := qv.Encode() + + req := &http.Request{ + Method: http.MethodPost, + URL: u, + Header: headers, + ContentLength: int64(len(enc)), + Body: io.NopCloser(strings.NewReader(enc)), + GetBody: func() (io.ReadCloser, error) { + return io.NopCloser(strings.NewReader(enc)), nil + }, + } + + data, err := c.do(ctx, req) + if err != nil { + return err + } + + v := reflect.ValueOf(resp) + if err := c.checkResp(v); err != nil { + return err + } + + var unmarshal = json.Unmarshal + if _, ok := v.Elem().Type().FieldByName("AdditionalFields"); ok { + unmarshal = customJSON.Unmarshal + } + if resp != nil { + if err := unmarshal(data, resp); err != nil { + return fmt.Errorf("json decode error: %w\nraw message was: %s", err, string(data)) + } + } + return nil +} + +// do makes the HTTP call to the server and returns the contents of the body. +func (c *Client) do(ctx context.Context, req *http.Request) ([]byte, error) { + if _, ok := ctx.Deadline(); !ok { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, 30*time.Second) + defer cancel() + } + req = req.WithContext(ctx) + + reply, err := c.client.Do(req) + if err != nil { + return nil, fmt.Errorf("server response error:\n %w", err) + } + defer reply.Body.Close() + + data, err := c.readBody(reply) + if err != nil { + return nil, fmt.Errorf("could not read the body of an HTTP Response: %w", err) + } + reply.Body = io.NopCloser(bytes.NewBuffer(data)) + + // NOTE: This doesn't happen immediately after the call so that we can get an error message + // from the server and include it in our error. + switch reply.StatusCode { + case 200, 201: + default: + sd := strings.TrimSpace(string(data)) + if sd != "" { + // We probably have the error in the body. + return nil, errors.CallErr{ + Req: req, + Resp: reply, + Err: fmt.Errorf("http call(%s)(%s) error: reply status code was %d:\n%s", req.URL.String(), req.Method, reply.StatusCode, sd), + } + } + return nil, errors.CallErr{ + Req: req, + Resp: reply, + Err: fmt.Errorf("http call(%s)(%s) error: reply status code was %d", req.URL.String(), req.Method, reply.StatusCode), + } + } + + return data, nil +} + +// checkResp checks a response object o make sure it is a pointer to a struct. +func (c *Client) checkResp(v reflect.Value) error { + if v.Kind() != reflect.Ptr { + return fmt.Errorf("bug: resp argument must a *struct, was %T", v.Interface()) + } + v = v.Elem() + if v.Kind() != reflect.Struct { + return fmt.Errorf("bug: resp argument must be a *struct, was %T", v.Interface()) + } + return nil +} + +// readBody reads the body out of an *http.Response. It supports gzip encoded responses. +func (c *Client) readBody(resp *http.Response) ([]byte, error) { + var reader io.Reader = resp.Body + switch resp.Header.Get("Content-Encoding") { + case "": + // Do nothing + case "gzip": + reader = gzipDecompress(resp.Body) + default: + return nil, fmt.Errorf("bug: comm.Client.JSONCall(): content was send with unsupported content-encoding %s", resp.Header.Get("Content-Encoding")) + } + return io.ReadAll(reader) +} + +var testID string + +// addStdHeaders adds the standard headers we use on all calls. +func addStdHeaders(headers http.Header) http.Header { + headers.Set("Accept-Encoding", "gzip") + // So that I can have a static id for tests. + if testID != "" { + headers.Set("client-request-id", testID) + headers.Set("Return-Client-Request-Id", "false") + } else { + headers.Set("client-request-id", uuid.New().String()) + headers.Set("Return-Client-Request-Id", "false") + } + headers.Set("x-client-sku", "MSAL.Go") + headers.Set("x-client-os", runtime.GOOS) + headers.Set("x-client-cpu", runtime.GOARCH) + headers.Set("x-client-ver", version.Version) + return headers +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/comm/compress.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/comm/compress.go new file mode 100644 index 00000000000..4d3dbfcf0a6 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/comm/compress.go @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package comm + +import ( + "compress/gzip" + "io" +) + +func gzipDecompress(r io.Reader) io.Reader { + gzipReader, _ := gzip.NewReader(r) + + pipeOut, pipeIn := io.Pipe() + go func() { + // decompression bomb would have to come from Azure services. + // If we want to limit, we should do that in comm.do(). + _, err := io.Copy(pipeIn, gzipReader) //nolint + if err != nil { + // don't need the error. + pipeIn.CloseWithError(err) //nolint + gzipReader.Close() + return + } + if err := gzipReader.Close(); err != nil { + // don't need the error. + pipeIn.CloseWithError(err) //nolint + return + } + pipeIn.Close() + }() + return pipeOut +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/grant/grant.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/grant/grant.go new file mode 100644 index 00000000000..b628f61ac08 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/grant/grant.go @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +// Package grant holds types of grants issued by authorization services. +package grant + +const ( + Password = "password" + JWT = "urn:ietf:params:oauth:grant-type:jwt-bearer" + SAMLV1 = "urn:ietf:params:oauth:grant-type:saml1_1-bearer" + SAMLV2 = "urn:ietf:params:oauth:grant-type:saml2-bearer" + DeviceCode = "device_code" + AuthCode = "authorization_code" + RefreshToken = "refresh_token" + ClientCredential = "client_credentials" + ClientAssertion = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" +) diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/ops.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/ops.go new file mode 100644 index 00000000000..1f9c543fa3b --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/ops.go @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +/* +Package ops provides operations to various backend services using REST clients. + +The REST type provides several clients that can be used to communicate to backends. +Usage is simple: + + rest := ops.New() + + // Creates an authority client and calls the UserRealm() method. + userRealm, err := rest.Authority().UserRealm(ctx, authParameters) + if err != nil { + // Do something + } +*/ +package ops + +import ( + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/comm" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust" +) + +// HTTPClient represents an HTTP client. +// It's usually an *http.Client from the standard library. +type HTTPClient = comm.HTTPClient + +// REST provides REST clients for communicating with various backends used by MSAL. +type REST struct { + client *comm.Client +} + +// New is the constructor for REST. +func New(httpClient HTTPClient) *REST { + return &REST{client: comm.New(httpClient)} +} + +// Authority returns a client for querying information about various authorities. +func (r *REST) Authority() authority.Client { + return authority.Client{Comm: r.client} +} + +// AccessTokens returns a client that can be used to get various access tokens for +// authorization purposes. +func (r *REST) AccessTokens() accesstokens.Client { + return accesstokens.Client{Comm: r.client} +} + +// WSTrust provides access to various metadata in a WSTrust service. This data can +// be used to gain tokens based on SAML data using the client provided by AccessTokens(). +func (r *REST) WSTrust() wstrust.Client { + return wstrust.Client{Comm: r.client} +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/endpointtype_string.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/endpointtype_string.go new file mode 100644 index 00000000000..a2bb6278ae5 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/endpointtype_string.go @@ -0,0 +1,25 @@ +// Code generated by "stringer -type=endpointType"; DO NOT EDIT. + +package defs + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[etUnknown-0] + _ = x[etUsernamePassword-1] + _ = x[etWindowsTransport-2] +} + +const _endpointType_name = "etUnknownetUsernamePasswordetWindowsTransport" + +var _endpointType_index = [...]uint8{0, 9, 27, 45} + +func (i endpointType) String() string { + if i < 0 || i >= endpointType(len(_endpointType_index)-1) { + return "endpointType(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _endpointType_name[_endpointType_index[i]:_endpointType_index[i+1]] +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/mex_document_definitions.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/mex_document_definitions.go new file mode 100644 index 00000000000..6497270028d --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/mex_document_definitions.go @@ -0,0 +1,394 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package defs + +import "encoding/xml" + +type Definitions struct { + XMLName xml.Name `xml:"definitions"` + Text string `xml:",chardata"` + Name string `xml:"name,attr"` + TargetNamespace string `xml:"targetNamespace,attr"` + WSDL string `xml:"wsdl,attr"` + XSD string `xml:"xsd,attr"` + T string `xml:"t,attr"` + SOAPENC string `xml:"soapenc,attr"` + SOAP string `xml:"soap,attr"` + TNS string `xml:"tns,attr"` + MSC string `xml:"msc,attr"` + WSAM string `xml:"wsam,attr"` + SOAP12 string `xml:"soap12,attr"` + WSA10 string `xml:"wsa10,attr"` + WSA string `xml:"wsa,attr"` + WSAW string `xml:"wsaw,attr"` + WSX string `xml:"wsx,attr"` + WSAP string `xml:"wsap,attr"` + WSU string `xml:"wsu,attr"` + Trust string `xml:"trust,attr"` + WSP string `xml:"wsp,attr"` + Policy []Policy `xml:"Policy"` + Types Types `xml:"types"` + Message []Message `xml:"message"` + PortType []PortType `xml:"portType"` + Binding []Binding `xml:"binding"` + Service Service `xml:"service"` +} + +type Policy struct { + Text string `xml:",chardata"` + ID string `xml:"Id,attr"` + ExactlyOne ExactlyOne `xml:"ExactlyOne"` +} + +type ExactlyOne struct { + Text string `xml:",chardata"` + All All `xml:"All"` +} + +type All struct { + Text string `xml:",chardata"` + NegotiateAuthentication NegotiateAuthentication `xml:"NegotiateAuthentication"` + TransportBinding TransportBinding `xml:"TransportBinding"` + UsingAddressing Text `xml:"UsingAddressing"` + EndorsingSupportingTokens EndorsingSupportingTokens `xml:"EndorsingSupportingTokens"` + WSS11 WSS11 `xml:"Wss11"` + Trust10 Trust10 `xml:"Trust10"` + SignedSupportingTokens SignedSupportingTokens `xml:"SignedSupportingTokens"` + Trust13 WSTrust13 `xml:"Trust13"` + SignedEncryptedSupportingTokens SignedEncryptedSupportingTokens `xml:"SignedEncryptedSupportingTokens"` +} + +type NegotiateAuthentication struct { + Text string `xml:",chardata"` + HTTP string `xml:"http,attr"` + XMLName xml.Name +} + +type TransportBinding struct { + Text string `xml:",chardata"` + SP string `xml:"sp,attr"` + Policy TransportBindingPolicy `xml:"Policy"` +} + +type TransportBindingPolicy struct { + Text string `xml:",chardata"` + TransportToken TransportToken `xml:"TransportToken"` + AlgorithmSuite AlgorithmSuite `xml:"AlgorithmSuite"` + Layout Layout `xml:"Layout"` + IncludeTimestamp Text `xml:"IncludeTimestamp"` +} + +type TransportToken struct { + Text string `xml:",chardata"` + Policy TransportTokenPolicy `xml:"Policy"` +} + +type TransportTokenPolicy struct { + Text string `xml:",chardata"` + HTTPSToken HTTPSToken `xml:"HttpsToken"` +} + +type HTTPSToken struct { + Text string `xml:",chardata"` + RequireClientCertificate string `xml:"RequireClientCertificate,attr"` +} + +type AlgorithmSuite struct { + Text string `xml:",chardata"` + Policy AlgorithmSuitePolicy `xml:"Policy"` +} + +type AlgorithmSuitePolicy struct { + Text string `xml:",chardata"` + Basic256 Text `xml:"Basic256"` + Basic128 Text `xml:"Basic128"` +} + +type Layout struct { + Text string `xml:",chardata"` + Policy LayoutPolicy `xml:"Policy"` +} + +type LayoutPolicy struct { + Text string `xml:",chardata"` + Strict Text `xml:"Strict"` +} + +type EndorsingSupportingTokens struct { + Text string `xml:",chardata"` + SP string `xml:"sp,attr"` + Policy EndorsingSupportingTokensPolicy `xml:"Policy"` +} + +type EndorsingSupportingTokensPolicy struct { + Text string `xml:",chardata"` + X509Token X509Token `xml:"X509Token"` + RSAToken RSAToken `xml:"RsaToken"` + SignedParts SignedParts `xml:"SignedParts"` + KerberosToken KerberosToken `xml:"KerberosToken"` + IssuedToken IssuedToken `xml:"IssuedToken"` + KeyValueToken KeyValueToken `xml:"KeyValueToken"` +} + +type X509Token struct { + Text string `xml:",chardata"` + IncludeToken string `xml:"IncludeToken,attr"` + Policy X509TokenPolicy `xml:"Policy"` +} + +type X509TokenPolicy struct { + Text string `xml:",chardata"` + RequireThumbprintReference Text `xml:"RequireThumbprintReference"` + WSSX509V3Token10 Text `xml:"WssX509V3Token10"` +} + +type RSAToken struct { + Text string `xml:",chardata"` + IncludeToken string `xml:"IncludeToken,attr"` + Optional string `xml:"Optional,attr"` + MSSP string `xml:"mssp,attr"` +} + +type SignedParts struct { + Text string `xml:",chardata"` + Header SignedPartsHeader `xml:"Header"` +} + +type SignedPartsHeader struct { + Text string `xml:",chardata"` + Name string `xml:"Name,attr"` + Namespace string `xml:"Namespace,attr"` +} + +type KerberosToken struct { + Text string `xml:",chardata"` + IncludeToken string `xml:"IncludeToken,attr"` + Policy KerberosTokenPolicy `xml:"Policy"` +} + +type KerberosTokenPolicy struct { + Text string `xml:",chardata"` + WSSGSSKerberosV5ApReqToken11 Text `xml:"WssGssKerberosV5ApReqToken11"` +} + +type IssuedToken struct { + Text string `xml:",chardata"` + IncludeToken string `xml:"IncludeToken,attr"` + RequestSecurityTokenTemplate RequestSecurityTokenTemplate `xml:"RequestSecurityTokenTemplate"` + Policy IssuedTokenPolicy `xml:"Policy"` +} + +type RequestSecurityTokenTemplate struct { + Text string `xml:",chardata"` + KeyType Text `xml:"KeyType"` + EncryptWith Text `xml:"EncryptWith"` + SignatureAlgorithm Text `xml:"SignatureAlgorithm"` + CanonicalizationAlgorithm Text `xml:"CanonicalizationAlgorithm"` + EncryptionAlgorithm Text `xml:"EncryptionAlgorithm"` + KeySize Text `xml:"KeySize"` + KeyWrapAlgorithm Text `xml:"KeyWrapAlgorithm"` +} + +type IssuedTokenPolicy struct { + Text string `xml:",chardata"` + RequireInternalReference Text `xml:"RequireInternalReference"` +} + +type KeyValueToken struct { + Text string `xml:",chardata"` + IncludeToken string `xml:"IncludeToken,attr"` + Optional string `xml:"Optional,attr"` +} + +type WSS11 struct { + Text string `xml:",chardata"` + SP string `xml:"sp,attr"` + Policy Wss11Policy `xml:"Policy"` +} + +type Wss11Policy struct { + Text string `xml:",chardata"` + MustSupportRefThumbprint Text `xml:"MustSupportRefThumbprint"` +} + +type Trust10 struct { + Text string `xml:",chardata"` + SP string `xml:"sp,attr"` + Policy Trust10Policy `xml:"Policy"` +} + +type Trust10Policy struct { + Text string `xml:",chardata"` + MustSupportIssuedTokens Text `xml:"MustSupportIssuedTokens"` + RequireClientEntropy Text `xml:"RequireClientEntropy"` + RequireServerEntropy Text `xml:"RequireServerEntropy"` +} + +type SignedSupportingTokens struct { + Text string `xml:",chardata"` + SP string `xml:"sp,attr"` + Policy SupportingTokensPolicy `xml:"Policy"` +} + +type SupportingTokensPolicy struct { + Text string `xml:",chardata"` + UsernameToken UsernameToken `xml:"UsernameToken"` +} +type UsernameToken struct { + Text string `xml:",chardata"` + IncludeToken string `xml:"IncludeToken,attr"` + Policy UsernameTokenPolicy `xml:"Policy"` +} + +type UsernameTokenPolicy struct { + Text string `xml:",chardata"` + WSSUsernameToken10 WSSUsernameToken10 `xml:"WssUsernameToken10"` +} + +type WSSUsernameToken10 struct { + Text string `xml:",chardata"` + XMLName xml.Name +} + +type WSTrust13 struct { + Text string `xml:",chardata"` + SP string `xml:"sp,attr"` + Policy WSTrust13Policy `xml:"Policy"` +} + +type WSTrust13Policy struct { + Text string `xml:",chardata"` + MustSupportIssuedTokens Text `xml:"MustSupportIssuedTokens"` + RequireClientEntropy Text `xml:"RequireClientEntropy"` + RequireServerEntropy Text `xml:"RequireServerEntropy"` +} + +type SignedEncryptedSupportingTokens struct { + Text string `xml:",chardata"` + SP string `xml:"sp,attr"` + Policy SupportingTokensPolicy `xml:"Policy"` +} + +type Types struct { + Text string `xml:",chardata"` + Schema Schema `xml:"schema"` +} + +type Schema struct { + Text string `xml:",chardata"` + TargetNamespace string `xml:"targetNamespace,attr"` + Import []Import `xml:"import"` +} + +type Import struct { + Text string `xml:",chardata"` + SchemaLocation string `xml:"schemaLocation,attr"` + Namespace string `xml:"namespace,attr"` +} + +type Message struct { + Text string `xml:",chardata"` + Name string `xml:"name,attr"` + Part Part `xml:"part"` +} + +type Part struct { + Text string `xml:",chardata"` + Name string `xml:"name,attr"` + Element string `xml:"element,attr"` +} + +type PortType struct { + Text string `xml:",chardata"` + Name string `xml:"name,attr"` + Operation Operation `xml:"operation"` +} + +type Operation struct { + Text string `xml:",chardata"` + Name string `xml:"name,attr"` + Input OperationIO `xml:"input"` + Output OperationIO `xml:"output"` +} + +type OperationIO struct { + Text string `xml:",chardata"` + Action string `xml:"Action,attr"` + Message string `xml:"message,attr"` + Body OperationIOBody `xml:"body"` +} + +type OperationIOBody struct { + Text string `xml:",chardata"` + Use string `xml:"use,attr"` +} + +type Binding struct { + Text string `xml:",chardata"` + Name string `xml:"name,attr"` + Type string `xml:"type,attr"` + PolicyReference PolicyReference `xml:"PolicyReference"` + Binding DefinitionsBinding `xml:"binding"` + Operation BindingOperation `xml:"operation"` +} + +type PolicyReference struct { + Text string `xml:",chardata"` + URI string `xml:"URI,attr"` +} + +type DefinitionsBinding struct { + Text string `xml:",chardata"` + Transport string `xml:"transport,attr"` +} + +type BindingOperation struct { + Text string `xml:",chardata"` + Name string `xml:"name,attr"` + Operation BindingOperationOperation `xml:"operation"` + Input BindingOperationIO `xml:"input"` + Output BindingOperationIO `xml:"output"` +} + +type BindingOperationOperation struct { + Text string `xml:",chardata"` + SoapAction string `xml:"soapAction,attr"` + Style string `xml:"style,attr"` +} + +type BindingOperationIO struct { + Text string `xml:",chardata"` + Body OperationIOBody `xml:"body"` +} + +type Service struct { + Text string `xml:",chardata"` + Name string `xml:"name,attr"` + Port []Port `xml:"port"` +} + +type Port struct { + Text string `xml:",chardata"` + Name string `xml:"name,attr"` + Binding string `xml:"binding,attr"` + Address Address `xml:"address"` + EndpointReference PortEndpointReference `xml:"EndpointReference"` +} + +type Address struct { + Text string `xml:",chardata"` + Location string `xml:"location,attr"` +} + +type PortEndpointReference struct { + Text string `xml:",chardata"` + Address Text `xml:"Address"` + Identity Identity `xml:"Identity"` +} + +type Identity struct { + Text string `xml:",chardata"` + XMLNS string `xml:"xmlns,attr"` + SPN Text `xml:"Spn"` +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/saml_assertion_definitions.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/saml_assertion_definitions.go new file mode 100644 index 00000000000..7d072556577 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/saml_assertion_definitions.go @@ -0,0 +1,230 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package defs + +import "encoding/xml" + +// TODO(msal): Someone (and it ain't gonna be me) needs to document these attributes or +// at the least put a link to RFC. + +type SAMLDefinitions struct { + XMLName xml.Name `xml:"Envelope"` + Text string `xml:",chardata"` + S string `xml:"s,attr"` + A string `xml:"a,attr"` + U string `xml:"u,attr"` + Header Header `xml:"Header"` + Body Body `xml:"Body"` +} + +type Header struct { + Text string `xml:",chardata"` + Action Action `xml:"Action"` + Security Security `xml:"Security"` +} + +type Action struct { + Text string `xml:",chardata"` + MustUnderstand string `xml:"mustUnderstand,attr"` +} + +type Security struct { + Text string `xml:",chardata"` + MustUnderstand string `xml:"mustUnderstand,attr"` + O string `xml:"o,attr"` + Timestamp Timestamp `xml:"Timestamp"` +} + +type Timestamp struct { + Text string `xml:",chardata"` + ID string `xml:"Id,attr"` + Created Text `xml:"Created"` + Expires Text `xml:"Expires"` +} + +type Text struct { + Text string `xml:",chardata"` +} + +type Body struct { + Text string `xml:",chardata"` + RequestSecurityTokenResponseCollection RequestSecurityTokenResponseCollection `xml:"RequestSecurityTokenResponseCollection"` +} + +type RequestSecurityTokenResponseCollection struct { + Text string `xml:",chardata"` + Trust string `xml:"trust,attr"` + RequestSecurityTokenResponse []RequestSecurityTokenResponse `xml:"RequestSecurityTokenResponse"` +} + +type RequestSecurityTokenResponse struct { + Text string `xml:",chardata"` + Lifetime Lifetime `xml:"Lifetime"` + AppliesTo AppliesTo `xml:"AppliesTo"` + RequestedSecurityToken RequestedSecurityToken `xml:"RequestedSecurityToken"` + RequestedAttachedReference RequestedAttachedReference `xml:"RequestedAttachedReference"` + RequestedUnattachedReference RequestedUnattachedReference `xml:"RequestedUnattachedReference"` + TokenType Text `xml:"TokenType"` + RequestType Text `xml:"RequestType"` + KeyType Text `xml:"KeyType"` +} + +type Lifetime struct { + Text string `xml:",chardata"` + Created WSUTimestamp `xml:"Created"` + Expires WSUTimestamp `xml:"Expires"` +} + +type WSUTimestamp struct { + Text string `xml:",chardata"` + Wsu string `xml:"wsu,attr"` +} + +type AppliesTo struct { + Text string `xml:",chardata"` + Wsp string `xml:"wsp,attr"` + EndpointReference EndpointReference `xml:"EndpointReference"` +} + +type EndpointReference struct { + Text string `xml:",chardata"` + Wsa string `xml:"wsa,attr"` + Address Text `xml:"Address"` +} + +type RequestedSecurityToken struct { + Text string `xml:",chardata"` + AssertionRawXML string `xml:",innerxml"` + Assertion Assertion `xml:"Assertion"` +} + +type Assertion struct { + XMLName xml.Name // Normally its `xml:"Assertion"`, but I think they want to capture the xmlns + Text string `xml:",chardata"` + MajorVersion string `xml:"MajorVersion,attr"` + MinorVersion string `xml:"MinorVersion,attr"` + AssertionID string `xml:"AssertionID,attr"` + Issuer string `xml:"Issuer,attr"` + IssueInstant string `xml:"IssueInstant,attr"` + Saml string `xml:"saml,attr"` + Conditions Conditions `xml:"Conditions"` + AttributeStatement AttributeStatement `xml:"AttributeStatement"` + AuthenticationStatement AuthenticationStatement `xml:"AuthenticationStatement"` + Signature Signature `xml:"Signature"` +} + +type Conditions struct { + Text string `xml:",chardata"` + NotBefore string `xml:"NotBefore,attr"` + NotOnOrAfter string `xml:"NotOnOrAfter,attr"` + AudienceRestrictionCondition AudienceRestrictionCondition `xml:"AudienceRestrictionCondition"` +} + +type AudienceRestrictionCondition struct { + Text string `xml:",chardata"` + Audience Text `xml:"Audience"` +} + +type AttributeStatement struct { + Text string `xml:",chardata"` + Subject Subject `xml:"Subject"` + Attribute []Attribute `xml:"Attribute"` +} + +type Subject struct { + Text string `xml:",chardata"` + NameIdentifier NameIdentifier `xml:"NameIdentifier"` + SubjectConfirmation SubjectConfirmation `xml:"SubjectConfirmation"` +} + +type NameIdentifier struct { + Text string `xml:",chardata"` + Format string `xml:"Format,attr"` +} + +type SubjectConfirmation struct { + Text string `xml:",chardata"` + ConfirmationMethod Text `xml:"ConfirmationMethod"` +} + +type Attribute struct { + Text string `xml:",chardata"` + AttributeName string `xml:"AttributeName,attr"` + AttributeNamespace string `xml:"AttributeNamespace,attr"` + AttributeValue Text `xml:"AttributeValue"` +} + +type AuthenticationStatement struct { + Text string `xml:",chardata"` + AuthenticationMethod string `xml:"AuthenticationMethod,attr"` + AuthenticationInstant string `xml:"AuthenticationInstant,attr"` + Subject Subject `xml:"Subject"` +} + +type Signature struct { + Text string `xml:",chardata"` + Ds string `xml:"ds,attr"` + SignedInfo SignedInfo `xml:"SignedInfo"` + SignatureValue Text `xml:"SignatureValue"` + KeyInfo KeyInfo `xml:"KeyInfo"` +} + +type SignedInfo struct { + Text string `xml:",chardata"` + CanonicalizationMethod Method `xml:"CanonicalizationMethod"` + SignatureMethod Method `xml:"SignatureMethod"` + Reference Reference `xml:"Reference"` +} + +type Method struct { + Text string `xml:",chardata"` + Algorithm string `xml:"Algorithm,attr"` +} + +type Reference struct { + Text string `xml:",chardata"` + URI string `xml:"URI,attr"` + Transforms Transforms `xml:"Transforms"` + DigestMethod Method `xml:"DigestMethod"` + DigestValue Text `xml:"DigestValue"` +} + +type Transforms struct { + Text string `xml:",chardata"` + Transform []Method `xml:"Transform"` +} + +type KeyInfo struct { + Text string `xml:",chardata"` + Xmlns string `xml:"xmlns,attr"` + X509Data X509Data `xml:"X509Data"` +} + +type X509Data struct { + Text string `xml:",chardata"` + X509Certificate Text `xml:"X509Certificate"` +} + +type RequestedAttachedReference struct { + Text string `xml:",chardata"` + SecurityTokenReference SecurityTokenReference `xml:"SecurityTokenReference"` +} + +type SecurityTokenReference struct { + Text string `xml:",chardata"` + TokenType string `xml:"TokenType,attr"` + O string `xml:"o,attr"` + K string `xml:"k,attr"` + KeyIdentifier KeyIdentifier `xml:"KeyIdentifier"` +} + +type KeyIdentifier struct { + Text string `xml:",chardata"` + ValueType string `xml:"ValueType,attr"` +} + +type RequestedUnattachedReference struct { + Text string `xml:",chardata"` + SecurityTokenReference SecurityTokenReference `xml:"SecurityTokenReference"` +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/version_string.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/version_string.go new file mode 100644 index 00000000000..6fe5efa8a9a --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/version_string.go @@ -0,0 +1,25 @@ +// Code generated by "stringer -type=Version"; DO NOT EDIT. + +package defs + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[TrustUnknown-0] + _ = x[Trust2005-1] + _ = x[Trust13-2] +} + +const _Version_name = "TrustUnknownTrust2005Trust13" + +var _Version_index = [...]uint8{0, 12, 21, 28} + +func (i Version) String() string { + if i < 0 || i >= Version(len(_Version_index)-1) { + return "Version(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _Version_name[_Version_index[i]:_Version_index[i+1]] +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/wstrust_endpoint.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/wstrust_endpoint.go new file mode 100644 index 00000000000..8fad5efb5de --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/wstrust_endpoint.go @@ -0,0 +1,199 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package defs + +import ( + "encoding/xml" + "fmt" + "time" + + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority" + uuid "github.com/google/uuid" +) + +//go:generate stringer -type=Version + +type Version int + +const ( + TrustUnknown Version = iota + Trust2005 + Trust13 +) + +// Endpoint represents a WSTrust endpoint. +type Endpoint struct { + // Version is the version of the endpoint. + Version Version + // URL is the URL of the endpoint. + URL string +} + +type wsTrustTokenRequestEnvelope struct { + XMLName xml.Name `xml:"s:Envelope"` + Text string `xml:",chardata"` + S string `xml:"xmlns:s,attr"` + Wsa string `xml:"xmlns:wsa,attr"` + Wsu string `xml:"xmlns:wsu,attr"` + Header struct { + Text string `xml:",chardata"` + Action struct { + Text string `xml:",chardata"` + MustUnderstand string `xml:"s:mustUnderstand,attr"` + } `xml:"wsa:Action"` + MessageID struct { + Text string `xml:",chardata"` + } `xml:"wsa:messageID"` + ReplyTo struct { + Text string `xml:",chardata"` + Address struct { + Text string `xml:",chardata"` + } `xml:"wsa:Address"` + } `xml:"wsa:ReplyTo"` + To struct { + Text string `xml:",chardata"` + MustUnderstand string `xml:"s:mustUnderstand,attr"` + } `xml:"wsa:To"` + Security struct { + Text string `xml:",chardata"` + MustUnderstand string `xml:"s:mustUnderstand,attr"` + Wsse string `xml:"xmlns:wsse,attr"` + Timestamp struct { + Text string `xml:",chardata"` + ID string `xml:"wsu:Id,attr"` + Created struct { + Text string `xml:",chardata"` + } `xml:"wsu:Created"` + Expires struct { + Text string `xml:",chardata"` + } `xml:"wsu:Expires"` + } `xml:"wsu:Timestamp"` + UsernameToken struct { + Text string `xml:",chardata"` + ID string `xml:"wsu:Id,attr"` + Username struct { + Text string `xml:",chardata"` + } `xml:"wsse:Username"` + Password struct { + Text string `xml:",chardata"` + } `xml:"wsse:Password"` + } `xml:"wsse:UsernameToken"` + } `xml:"wsse:Security"` + } `xml:"s:Header"` + Body struct { + Text string `xml:",chardata"` + RequestSecurityToken struct { + Text string `xml:",chardata"` + Wst string `xml:"xmlns:wst,attr"` + AppliesTo struct { + Text string `xml:",chardata"` + Wsp string `xml:"xmlns:wsp,attr"` + EndpointReference struct { + Text string `xml:",chardata"` + Address struct { + Text string `xml:",chardata"` + } `xml:"wsa:Address"` + } `xml:"wsa:EndpointReference"` + } `xml:"wsp:AppliesTo"` + KeyType struct { + Text string `xml:",chardata"` + } `xml:"wst:KeyType"` + RequestType struct { + Text string `xml:",chardata"` + } `xml:"wst:RequestType"` + } `xml:"wst:RequestSecurityToken"` + } `xml:"s:Body"` +} + +func buildTimeString(t time.Time) string { + // Golang time formats are weird: https://stackoverflow.com/questions/20234104/how-to-format-current-time-using-a-yyyymmddhhmmss-format + return t.Format("2006-01-02T15:04:05.000Z") +} + +func (wte *Endpoint) buildTokenRequestMessage(authType authority.AuthorizeType, cloudAudienceURN string, username string, password string) (string, error) { + var soapAction string + var trustNamespace string + var keyType string + var requestType string + + createdTime := time.Now().UTC() + expiresTime := createdTime.Add(10 * time.Minute) + + switch wte.Version { + case Trust2005: + soapAction = trust2005Spec + trustNamespace = "http://schemas.xmlsoap.org/ws/2005/02/trust" + keyType = "http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey" + requestType = "http://schemas.xmlsoap.org/ws/2005/02/trust/Issue" + case Trust13: + soapAction = trust13Spec + trustNamespace = "http://docs.oasis-open.org/ws-sx/ws-trust/200512" + keyType = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer" + requestType = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue" + default: + return "", fmt.Errorf("buildTokenRequestMessage had Version == %q, which is not recognized", wte.Version) + } + + var envelope wsTrustTokenRequestEnvelope + + messageUUID := uuid.New() + + envelope.S = "http://www.w3.org/2003/05/soap-envelope" + envelope.Wsa = "http://www.w3.org/2005/08/addressing" + envelope.Wsu = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" + + envelope.Header.Action.MustUnderstand = "1" + envelope.Header.Action.Text = soapAction + envelope.Header.MessageID.Text = "urn:uuid:" + messageUUID.String() + envelope.Header.ReplyTo.Address.Text = "http://www.w3.org/2005/08/addressing/anonymous" + envelope.Header.To.MustUnderstand = "1" + envelope.Header.To.Text = wte.URL + + switch authType { + case authority.ATUnknown: + return "", fmt.Errorf("buildTokenRequestMessage had no authority type(%v)", authType) + case authority.ATUsernamePassword: + endpointUUID := uuid.New() + + var trustID string + if wte.Version == Trust2005 { + trustID = "UnPwSecTok2005-" + endpointUUID.String() + } else { + trustID = "UnPwSecTok13-" + endpointUUID.String() + } + + envelope.Header.Security.MustUnderstand = "1" + envelope.Header.Security.Wsse = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" + envelope.Header.Security.Timestamp.ID = "MSATimeStamp" + envelope.Header.Security.Timestamp.Created.Text = buildTimeString(createdTime) + envelope.Header.Security.Timestamp.Expires.Text = buildTimeString(expiresTime) + envelope.Header.Security.UsernameToken.ID = trustID + envelope.Header.Security.UsernameToken.Username.Text = username + envelope.Header.Security.UsernameToken.Password.Text = password + default: + // This is just to note that we don't do anything for other cases. + // We aren't missing anything I know of. + } + + envelope.Body.RequestSecurityToken.Wst = trustNamespace + envelope.Body.RequestSecurityToken.AppliesTo.Wsp = "http://schemas.xmlsoap.org/ws/2004/09/policy" + envelope.Body.RequestSecurityToken.AppliesTo.EndpointReference.Address.Text = cloudAudienceURN + envelope.Body.RequestSecurityToken.KeyType.Text = keyType + envelope.Body.RequestSecurityToken.RequestType.Text = requestType + + output, err := xml.Marshal(envelope) + if err != nil { + return "", err + } + + return string(output), nil +} + +func (wte *Endpoint) BuildTokenRequestMessageWIA(cloudAudienceURN string) (string, error) { + return wte.buildTokenRequestMessage(authority.ATWindowsIntegrated, cloudAudienceURN, "", "") +} + +func (wte *Endpoint) BuildTokenRequestMessageUsernamePassword(cloudAudienceURN string, username string, password string) (string, error) { + return wte.buildTokenRequestMessage(authority.ATUsernamePassword, cloudAudienceURN, username, password) +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/wstrust_mex_document.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/wstrust_mex_document.go new file mode 100644 index 00000000000..e3d19886ebc --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs/wstrust_mex_document.go @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package defs + +import ( + "errors" + "fmt" + "strings" +) + +//go:generate stringer -type=endpointType + +type endpointType int + +const ( + etUnknown endpointType = iota + etUsernamePassword + etWindowsTransport +) + +type wsEndpointData struct { + Version Version + EndpointType endpointType +} + +const trust13Spec string = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue" +const trust2005Spec string = "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue" + +type MexDocument struct { + UsernamePasswordEndpoint Endpoint + WindowsTransportEndpoint Endpoint + policies map[string]endpointType + bindings map[string]wsEndpointData +} + +func updateEndpoint(cached *Endpoint, found Endpoint) { + if cached == nil || cached.Version == TrustUnknown { + *cached = found + return + } + if (*cached).Version == Trust2005 && found.Version == Trust13 { + *cached = found + return + } +} + +// TODO(msal): Someone needs to write tests for everything below. + +// NewFromDef creates a new MexDocument. +func NewFromDef(defs Definitions) (MexDocument, error) { + policies, err := policies(defs) + if err != nil { + return MexDocument{}, err + } + + bindings, err := bindings(defs, policies) + if err != nil { + return MexDocument{}, err + } + + userPass, windows, err := endpoints(defs, bindings) + if err != nil { + return MexDocument{}, err + } + + return MexDocument{ + UsernamePasswordEndpoint: userPass, + WindowsTransportEndpoint: windows, + policies: policies, + bindings: bindings, + }, nil +} + +func policies(defs Definitions) (map[string]endpointType, error) { + policies := make(map[string]endpointType, len(defs.Policy)) + + for _, policy := range defs.Policy { + if policy.ExactlyOne.All.NegotiateAuthentication.XMLName.Local != "" { + if policy.ExactlyOne.All.TransportBinding.SP != "" && policy.ID != "" { + policies["#"+policy.ID] = etWindowsTransport + } + } + + if policy.ExactlyOne.All.SignedEncryptedSupportingTokens.Policy.UsernameToken.Policy.WSSUsernameToken10.XMLName.Local != "" { + if policy.ExactlyOne.All.TransportBinding.SP != "" && policy.ID != "" { + policies["#"+policy.ID] = etUsernamePassword + } + } + if policy.ExactlyOne.All.SignedSupportingTokens.Policy.UsernameToken.Policy.WSSUsernameToken10.XMLName.Local != "" { + if policy.ExactlyOne.All.TransportBinding.SP != "" && policy.ID != "" { + policies["#"+policy.ID] = etUsernamePassword + } + } + } + + if len(policies) == 0 { + return policies, errors.New("no policies for mex document") + } + + return policies, nil +} + +func bindings(defs Definitions, policies map[string]endpointType) (map[string]wsEndpointData, error) { + bindings := make(map[string]wsEndpointData, len(defs.Binding)) + + for _, binding := range defs.Binding { + policyName := binding.PolicyReference.URI + transport := binding.Binding.Transport + + if transport == "http://schemas.xmlsoap.org/soap/http" { + if policy, ok := policies[policyName]; ok { + bindingName := binding.Name + specVersion := binding.Operation.Operation.SoapAction + + if specVersion == trust13Spec { + bindings[bindingName] = wsEndpointData{Trust13, policy} + } else if specVersion == trust2005Spec { + bindings[bindingName] = wsEndpointData{Trust2005, policy} + } else { + return nil, errors.New("found unknown spec version in mex document") + } + } + } + } + return bindings, nil +} + +func endpoints(defs Definitions, bindings map[string]wsEndpointData) (userPass, windows Endpoint, err error) { + for _, port := range defs.Service.Port { + bindingName := port.Binding + + index := strings.Index(bindingName, ":") + if index != -1 { + bindingName = bindingName[index+1:] + } + + if binding, ok := bindings[bindingName]; ok { + url := strings.TrimSpace(port.EndpointReference.Address.Text) + if url == "" { + return Endpoint{}, Endpoint{}, fmt.Errorf("MexDocument cannot have blank URL endpoint") + } + if binding.Version == TrustUnknown { + return Endpoint{}, Endpoint{}, fmt.Errorf("endpoint version unknown") + } + endpoint := Endpoint{Version: binding.Version, URL: url} + + switch binding.EndpointType { + case etUsernamePassword: + updateEndpoint(&userPass, endpoint) + case etWindowsTransport: + updateEndpoint(&windows, endpoint) + default: + return Endpoint{}, Endpoint{}, errors.New("found unknown port type in MEX document") + } + } + } + return userPass, windows, nil +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/wstrust.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/wstrust.go new file mode 100644 index 00000000000..47cd4c692d6 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/wstrust.go @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +/* +Package wstrust provides a client for communicating with a WSTrust (https://en.wikipedia.org/wiki/WS-Trust#:~:text=WS%2DTrust%20is%20a%20WS,in%20a%20secure%20message%20exchange.) +for the purposes of extracting metadata from the service. This data can be used to acquire +tokens using the accesstokens.Client.GetAccessTokenFromSamlGrant() call. +*/ +package wstrust + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/grant" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs" +) + +type xmlCaller interface { + XMLCall(ctx context.Context, endpoint string, headers http.Header, qv url.Values, resp interface{}) error + SOAPCall(ctx context.Context, endpoint, action string, headers http.Header, qv url.Values, body string, resp interface{}) error +} + +type SamlTokenInfo struct { + AssertionType string // Should be either constants SAMLV1Grant or SAMLV2Grant. + Assertion string +} + +// Client represents the REST calls to get tokens from token generator backends. +type Client struct { + // Comm provides the HTTP transport client. + Comm xmlCaller +} + +// TODO(msal): This allows me to call Mex without having a real Def file on line 45. +// This would fail because policies() would not find a policy. This is easy enough to +// fix in test data, but.... Definitions is defined with built in structs. That needs +// to be pulled apart and until then I have this hack in. +var newFromDef = defs.NewFromDef + +// Mex provides metadata about a wstrust service. +func (c Client) Mex(ctx context.Context, federationMetadataURL string) (defs.MexDocument, error) { + resp := defs.Definitions{} + err := c.Comm.XMLCall( + ctx, + federationMetadataURL, + http.Header{}, + nil, + &resp, + ) + if err != nil { + return defs.MexDocument{}, err + } + + return newFromDef(resp) +} + +const ( + SoapActionDefault = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue" + + // Note: Commented out because this action is not supported. It was in the original code + // but only used in a switch where it errored. Since there was only one value, a default + // worked better. However, buildTokenRequestMessage() had 2005 support. I'm not actually + // sure what's going on here. It like we have half support. For now this is here just + // for documentation purposes in case we are going to add support. + // + // SoapActionWSTrust2005 = "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue" +) + +// SAMLTokenInfo provides SAML information that is used to generate a SAML token. +func (c Client) SAMLTokenInfo(ctx context.Context, authParameters authority.AuthParams, cloudAudienceURN string, endpoint defs.Endpoint) (SamlTokenInfo, error) { + var wsTrustRequestMessage string + var err error + + switch authParameters.AuthorizationType { + case authority.ATWindowsIntegrated: + wsTrustRequestMessage, err = endpoint.BuildTokenRequestMessageWIA(cloudAudienceURN) + if err != nil { + return SamlTokenInfo{}, err + } + case authority.ATUsernamePassword: + wsTrustRequestMessage, err = endpoint.BuildTokenRequestMessageUsernamePassword( + cloudAudienceURN, authParameters.Username, authParameters.Password) + if err != nil { + return SamlTokenInfo{}, err + } + default: + return SamlTokenInfo{}, fmt.Errorf("unknown auth type %v", authParameters.AuthorizationType) + } + + var soapAction string + switch endpoint.Version { + case defs.Trust13: + soapAction = SoapActionDefault + case defs.Trust2005: + return SamlTokenInfo{}, errors.New("WS Trust 2005 support is not implemented") + default: + return SamlTokenInfo{}, fmt.Errorf("the SOAP endpoint for a wstrust call had an invalid version: %v", endpoint.Version) + } + + resp := defs.SAMLDefinitions{} + err = c.Comm.SOAPCall(ctx, endpoint.URL, soapAction, http.Header{}, nil, wsTrustRequestMessage, &resp) + if err != nil { + return SamlTokenInfo{}, err + } + + return c.samlAssertion(resp) +} + +const ( + samlv1Assertion = "urn:oasis:names:tc:SAML:1.0:assertion" + samlv2Assertion = "urn:oasis:names:tc:SAML:2.0:assertion" +) + +func (c Client) samlAssertion(def defs.SAMLDefinitions) (SamlTokenInfo, error) { + for _, tokenResponse := range def.Body.RequestSecurityTokenResponseCollection.RequestSecurityTokenResponse { + token := tokenResponse.RequestedSecurityToken + if token.Assertion.XMLName.Local != "" { + assertion := token.AssertionRawXML + + samlVersion := token.Assertion.Saml + switch samlVersion { + case samlv1Assertion: + return SamlTokenInfo{AssertionType: grant.SAMLV1, Assertion: assertion}, nil + case samlv2Assertion: + return SamlTokenInfo{AssertionType: grant.SAMLV2, Assertion: assertion}, nil + } + return SamlTokenInfo{}, fmt.Errorf("couldn't parse SAML assertion, version unknown: %q", samlVersion) + } + } + return SamlTokenInfo{}, errors.New("unknown WS-Trust version") +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/resolvers.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/resolvers.go new file mode 100644 index 00000000000..0ade411797a --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/resolvers.go @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +// TODO(msal): Write some tests. The original code this came from didn't have tests and I'm too +// tired at this point to do it. It, like many other *Manager code I found was broken because +// they didn't have mutex protection. + +package oauth + +import ( + "context" + "errors" + "fmt" + "strings" + "sync" + + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority" +) + +// ADFS is an active directory federation service authority type. +const ADFS = "ADFS" + +type cacheEntry struct { + Endpoints authority.Endpoints + ValidForDomainsInList map[string]bool +} + +func createcacheEntry(endpoints authority.Endpoints) cacheEntry { + return cacheEntry{endpoints, map[string]bool{}} +} + +// AuthorityEndpoint retrieves endpoints from an authority for auth and token acquisition. +type authorityEndpoint struct { + rest *ops.REST + + mu sync.Mutex + cache map[string]cacheEntry +} + +// newAuthorityEndpoint is the constructor for AuthorityEndpoint. +func newAuthorityEndpoint(rest *ops.REST) *authorityEndpoint { + m := &authorityEndpoint{rest: rest, cache: map[string]cacheEntry{}} + return m +} + +// ResolveEndpoints gets the authorization and token endpoints and creates an AuthorityEndpoints instance +func (m *authorityEndpoint) ResolveEndpoints(ctx context.Context, authorityInfo authority.Info, userPrincipalName string) (authority.Endpoints, error) { + + if endpoints, found := m.cachedEndpoints(authorityInfo, userPrincipalName); found { + return endpoints, nil + } + + endpoint, err := m.openIDConfigurationEndpoint(ctx, authorityInfo, userPrincipalName) + if err != nil { + return authority.Endpoints{}, err + } + + resp, err := m.rest.Authority().GetTenantDiscoveryResponse(ctx, endpoint) + if err != nil { + return authority.Endpoints{}, err + } + if err := resp.Validate(); err != nil { + return authority.Endpoints{}, fmt.Errorf("ResolveEndpoints(): %w", err) + } + + tenant := authorityInfo.Tenant + + endpoints := authority.NewEndpoints( + strings.Replace(resp.AuthorizationEndpoint, "{tenant}", tenant, -1), + strings.Replace(resp.TokenEndpoint, "{tenant}", tenant, -1), + strings.Replace(resp.Issuer, "{tenant}", tenant, -1), + authorityInfo.Host) + + m.addCachedEndpoints(authorityInfo, userPrincipalName, endpoints) + + return endpoints, nil +} + +// cachedEndpoints returns a the cached endpoints if they exists. If not, we return false. +func (m *authorityEndpoint) cachedEndpoints(authorityInfo authority.Info, userPrincipalName string) (authority.Endpoints, bool) { + m.mu.Lock() + defer m.mu.Unlock() + + if cacheEntry, ok := m.cache[authorityInfo.CanonicalAuthorityURI]; ok { + if authorityInfo.AuthorityType == ADFS { + domain, err := adfsDomainFromUpn(userPrincipalName) + if err == nil { + if _, ok := cacheEntry.ValidForDomainsInList[domain]; ok { + return cacheEntry.Endpoints, true + } + } + } + return cacheEntry.Endpoints, true + } + return authority.Endpoints{}, false +} + +func (m *authorityEndpoint) addCachedEndpoints(authorityInfo authority.Info, userPrincipalName string, endpoints authority.Endpoints) { + m.mu.Lock() + defer m.mu.Unlock() + + updatedCacheEntry := createcacheEntry(endpoints) + + if authorityInfo.AuthorityType == ADFS { + // Since we're here, we've made a call to the backend. We want to ensure we're caching + // the latest values from the server. + if cacheEntry, ok := m.cache[authorityInfo.CanonicalAuthorityURI]; ok { + for k := range cacheEntry.ValidForDomainsInList { + updatedCacheEntry.ValidForDomainsInList[k] = true + } + } + domain, err := adfsDomainFromUpn(userPrincipalName) + if err == nil { + updatedCacheEntry.ValidForDomainsInList[domain] = true + } + } + + m.cache[authorityInfo.CanonicalAuthorityURI] = updatedCacheEntry +} + +func (m *authorityEndpoint) openIDConfigurationEndpoint(ctx context.Context, authorityInfo authority.Info, userPrincipalName string) (string, error) { + if authorityInfo.Tenant == "adfs" { + return fmt.Sprintf("https://%s/adfs/.well-known/openid-configuration", authorityInfo.Host), nil + } else if authorityInfo.ValidateAuthority && !authority.TrustedHost(authorityInfo.Host) { + resp, err := m.rest.Authority().AADInstanceDiscovery(ctx, authorityInfo) + if err != nil { + return "", err + } + return resp.TenantDiscoveryEndpoint, nil + } else if authorityInfo.Region != "" { + resp, err := m.rest.Authority().AADInstanceDiscovery(ctx, authorityInfo) + if err != nil { + return "", err + } + return resp.TenantDiscoveryEndpoint, nil + + } + + return authorityInfo.CanonicalAuthorityURI + "v2.0/.well-known/openid-configuration", nil +} + +func adfsDomainFromUpn(userPrincipalName string) (string, error) { + parts := strings.Split(userPrincipalName, "@") + if len(parts) < 2 { + return "", errors.New("no @ present in user principal name") + } + return parts[1], nil +} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/options/options.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/options/options.go new file mode 100644 index 00000000000..4561d72db4d --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/options/options.go @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package options + +import ( + "errors" + "fmt" +) + +// CallOption implements an optional argument to a method call. See +// https://blog.devgenius.io/go-call-option-that-can-be-used-with-multiple-methods-6c81734f3dbe +// for an explanation of the usage pattern. +type CallOption interface { + Do(any) error + callOption() +} + +// ApplyOptions applies all the callOptions to options. options must be a pointer to a struct and +// callOptions must be a list of objects that implement CallOption. +func ApplyOptions[O, C any](options O, callOptions []C) error { + for _, o := range callOptions { + if t, ok := any(o).(CallOption); !ok { + return fmt.Errorf("unexpected option type %T", o) + } else if err := t.Do(options); err != nil { + return err + } + } + return nil +} + +// NewCallOption returns a new CallOption whose Do() method calls function "f". +func NewCallOption(f func(any) error) CallOption { + if f == nil { + // This isn't a practical concern because only an MSAL maintainer can get + // us here, by implementing a do-nothing option. But if someone does that, + // the below ensures the method invoked with the option returns an error. + return callOption(func(any) error { + return errors.New("invalid option: missing implementation") + }) + } + return callOption(f) +} + +// callOption is an adapter for a function to a CallOption +type callOption func(any) error + +func (c callOption) Do(a any) error { + return c(a) +} + +func (callOption) callOption() {} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/shared/shared.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/shared/shared.go new file mode 100644 index 00000000000..f7e12a71bf3 --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/shared/shared.go @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +package shared + +import ( + "net/http" + "reflect" + "strings" +) + +const ( + // CacheKeySeparator is used in creating the keys of the cache. + CacheKeySeparator = "-" +) + +type Account struct { + HomeAccountID string `json:"home_account_id,omitempty"` + Environment string `json:"environment,omitempty"` + Realm string `json:"realm,omitempty"` + LocalAccountID string `json:"local_account_id,omitempty"` + AuthorityType string `json:"authority_type,omitempty"` + PreferredUsername string `json:"username,omitempty"` + GivenName string `json:"given_name,omitempty"` + FamilyName string `json:"family_name,omitempty"` + MiddleName string `json:"middle_name,omitempty"` + Name string `json:"name,omitempty"` + AlternativeID string `json:"alternative_account_id,omitempty"` + RawClientInfo string `json:"client_info,omitempty"` + UserAssertionHash string `json:"user_assertion_hash,omitempty"` + + AdditionalFields map[string]interface{} +} + +// NewAccount creates an account. +func NewAccount(homeAccountID, env, realm, localAccountID, authorityType, username string) Account { + return Account{ + HomeAccountID: homeAccountID, + Environment: env, + Realm: realm, + LocalAccountID: localAccountID, + AuthorityType: authorityType, + PreferredUsername: username, + } +} + +// Key creates the key for storing accounts in the cache. +func (acc Account) Key() string { + return strings.Join([]string{acc.HomeAccountID, acc.Environment, acc.Realm}, CacheKeySeparator) +} + +// IsZero checks the zero value of account. +func (acc Account) IsZero() bool { + v := reflect.ValueOf(acc) + for i := 0; i < v.NumField(); i++ { + field := v.Field(i) + if !field.IsZero() { + switch field.Kind() { + case reflect.Map, reflect.Slice: + if field.Len() == 0 { + continue + } + } + return false + } + } + return true +} + +// DefaultClient is our default shared HTTP client. +var DefaultClient = &http.Client{} diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/version/version.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/version/version.go new file mode 100644 index 00000000000..c3651e630be --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/version/version.go @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +// Package version keeps the version number of the client package. +package version + +// Version is the version of this client package that is communicated to the server. +const Version = "0.8.1" diff --git a/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/public/public.go b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/public/public.go new file mode 100644 index 00000000000..0a3ffafff4a --- /dev/null +++ b/vendor/github.com/AzureAD/microsoft-authentication-library-for-go/apps/public/public.go @@ -0,0 +1,716 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +/* +Package public provides a client for authentication of "public" applications. A "public" +application is defined as an app that runs on client devices (android, ios, windows, linux, ...). +These devices are "untrusted" and access resources via web APIs that must authenticate. +*/ +package public + +/* +Design note: + +public.Client uses client.Base as an embedded type. client.Base statically assigns its attributes +during creation. As it doesn't have any pointers in it, anything borrowed from it, such as +Base.AuthParams is a copy that is free to be manipulated here. +*/ + +// TODO(msal): This should have example code for each method on client using Go's example doc framework. +// base usage details should be includee in the package documentation. + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "fmt" + "net/url" + "strconv" + + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/cache" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/local" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/options" + "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/shared" + "github.com/google/uuid" + "github.com/pkg/browser" +) + +// AuthResult contains the results of one token acquisition operation. +// For details see https://aka.ms/msal-net-authenticationresult +type AuthResult = base.AuthResult + +type Account = shared.Account + +// Options configures the Client's behavior. +type Options struct { + // Accessor controls cache persistence. By default there is no cache persistence. + // This can be set with the WithCache() option. + Accessor cache.ExportReplace + + // The host of the Azure Active Directory authority. The default is https://login.microsoftonline.com/common. + // This can be changed with the WithAuthority() option. + Authority string + + // The HTTP client used for making requests. + // It defaults to a shared http.Client. + HTTPClient ops.HTTPClient + + capabilities []string + + disableInstanceDiscovery bool +} + +func (p *Options) validate() error { + u, err := url.Parse(p.Authority) + if err != nil { + return fmt.Errorf("Authority options cannot be URL parsed: %w", err) + } + if u.Scheme != "https" { + return fmt.Errorf("Authority(%s) did not start with https://", u.String()) + } + return nil +} + +// Option is an optional argument to the New constructor. +type Option func(o *Options) + +// WithAuthority allows for a custom authority to be set. This must be a valid https url. +func WithAuthority(authority string) Option { + return func(o *Options) { + o.Authority = authority + } +} + +// WithCache allows you to set some type of cache for storing authentication tokens. +func WithCache(accessor cache.ExportReplace) Option { + return func(o *Options) { + o.Accessor = accessor + } +} + +// WithClientCapabilities allows configuring one or more client capabilities such as "CP1" +func WithClientCapabilities(capabilities []string) Option { + return func(o *Options) { + // there's no danger of sharing the slice's underlying memory with the application because + // this slice is simply passed to base.WithClientCapabilities, which copies its data + o.capabilities = capabilities + } +} + +// WithHTTPClient allows for a custom HTTP client to be set. +func WithHTTPClient(httpClient ops.HTTPClient) Option { + return func(o *Options) { + o.HTTPClient = httpClient + } +} + +// WithInstanceDiscovery set to false to disable authority validation (to support private cloud scenarios) +func WithInstanceDiscovery(enabled bool) Option { + return func(o *Options) { + o.disableInstanceDiscovery = !enabled + } +} + +// Client is a representation of authentication client for public applications as defined in the +// package doc. For more information, visit https://docs.microsoft.com/azure/active-directory/develop/msal-client-applications. +type Client struct { + base base.Client +} + +// New is the constructor for Client. +func New(clientID string, options ...Option) (Client, error) { + opts := Options{ + Authority: base.AuthorityPublicCloud, + HTTPClient: shared.DefaultClient, + } + + for _, o := range options { + o(&opts) + } + if err := opts.validate(); err != nil { + return Client{}, err + } + + base, err := base.New(clientID, opts.Authority, oauth.New(opts.HTTPClient), base.WithCacheAccessor(opts.Accessor), base.WithClientCapabilities(opts.capabilities), base.WithInstanceDiscovery(!opts.disableInstanceDiscovery)) + if err != nil { + return Client{}, err + } + return Client{base}, nil +} + +// createAuthCodeURLOptions contains options for CreateAuthCodeURL +type createAuthCodeURLOptions struct { + claims, loginHint, tenantID, domainHint string +} + +// CreateAuthCodeURLOption is implemented by options for CreateAuthCodeURL +type CreateAuthCodeURLOption interface { + createAuthCodeURLOption() +} + +// CreateAuthCodeURL creates a URL used to acquire an authorization code. +// +// Options: [WithClaims], [WithDomainHint], [WithLoginHint], [WithTenantID] +func (pca Client) CreateAuthCodeURL(ctx context.Context, clientID, redirectURI string, scopes []string, opts ...CreateAuthCodeURLOption) (string, error) { + o := createAuthCodeURLOptions{} + if err := options.ApplyOptions(&o, opts); err != nil { + return "", err + } + ap, err := pca.base.AuthParams.WithTenant(o.tenantID) + if err != nil { + return "", err + } + ap.Claims = o.claims + ap.LoginHint = o.loginHint + ap.DomainHint = o.domainHint + return pca.base.AuthCodeURL(ctx, clientID, redirectURI, scopes, ap) +} + +// WithClaims sets additional claims to request for the token, such as those required by conditional access policies. +// Use this option when Azure AD returned a claims challenge for a prior request. The argument must be decoded. +// This option is valid for any token acquisition method. +func WithClaims(claims string) interface { + AcquireByAuthCodeOption + AcquireByDeviceCodeOption + AcquireByUsernamePasswordOption + AcquireInteractiveOption + AcquireSilentOption + CreateAuthCodeURLOption + options.CallOption +} { + return struct { + AcquireByAuthCodeOption + AcquireByDeviceCodeOption + AcquireByUsernamePasswordOption + AcquireInteractiveOption + AcquireSilentOption + CreateAuthCodeURLOption + options.CallOption + }{ + CallOption: options.NewCallOption( + func(a any) error { + switch t := a.(type) { + case *AcquireTokenByAuthCodeOptions: + t.claims = claims + case *acquireTokenByDeviceCodeOptions: + t.claims = claims + case *acquireTokenByUsernamePasswordOptions: + t.claims = claims + case *AcquireTokenSilentOptions: + t.claims = claims + case *createAuthCodeURLOptions: + t.claims = claims + case *InteractiveAuthOptions: + t.claims = claims + default: + return fmt.Errorf("unexpected options type %T", a) + } + return nil + }, + ), + } +} + +// WithTenantID specifies a tenant for a single authentication. It may be different than the tenant set in [New] by [WithAuthority]. +// This option is valid for any token acquisition method. +func WithTenantID(tenantID string) interface { + AcquireByAuthCodeOption + AcquireByDeviceCodeOption + AcquireByUsernamePasswordOption + AcquireInteractiveOption + AcquireSilentOption + CreateAuthCodeURLOption + options.CallOption +} { + return struct { + AcquireByAuthCodeOption + AcquireByDeviceCodeOption + AcquireByUsernamePasswordOption + AcquireInteractiveOption + AcquireSilentOption + CreateAuthCodeURLOption + options.CallOption + }{ + CallOption: options.NewCallOption( + func(a any) error { + switch t := a.(type) { + case *AcquireTokenByAuthCodeOptions: + t.tenantID = tenantID + case *acquireTokenByDeviceCodeOptions: + t.tenantID = tenantID + case *acquireTokenByUsernamePasswordOptions: + t.tenantID = tenantID + case *AcquireTokenSilentOptions: + t.tenantID = tenantID + case *createAuthCodeURLOptions: + t.tenantID = tenantID + case *InteractiveAuthOptions: + t.tenantID = tenantID + default: + return fmt.Errorf("unexpected options type %T", a) + } + return nil + }, + ), + } +} + +// AcquireTokenSilentOptions are all the optional settings to an AcquireTokenSilent() call. +// These are set by using various AcquireTokenSilentOption functions. +type AcquireTokenSilentOptions struct { + // Account represents the account to use. To set, use the WithSilentAccount() option. + Account Account + + claims, tenantID string +} + +// AcquireSilentOption is implemented by options for AcquireTokenSilent +type AcquireSilentOption interface { + acquireSilentOption() +} + +// AcquireTokenSilentOption changes options inside AcquireTokenSilentOptions used in .AcquireTokenSilent(). +type AcquireTokenSilentOption func(a *AcquireTokenSilentOptions) + +func (AcquireTokenSilentOption) acquireSilentOption() {} + +// WithSilentAccount uses the passed account during an AcquireTokenSilent() call. +func WithSilentAccount(account Account) interface { + AcquireSilentOption + options.CallOption +} { + return struct { + AcquireSilentOption + options.CallOption + }{ + CallOption: options.NewCallOption( + func(a any) error { + switch t := a.(type) { + case *AcquireTokenSilentOptions: + t.Account = account + default: + return fmt.Errorf("unexpected options type %T", a) + } + return nil + }, + ), + } +} + +// AcquireTokenSilent acquires a token from either the cache or using a refresh token. +// +// Options: [WithClaims], [WithSilentAccount], [WithTenantID] +func (pca Client) AcquireTokenSilent(ctx context.Context, scopes []string, opts ...AcquireSilentOption) (AuthResult, error) { + o := AcquireTokenSilentOptions{} + if err := options.ApplyOptions(&o, opts); err != nil { + return AuthResult{}, err + } + + silentParameters := base.AcquireTokenSilentParameters{ + Scopes: scopes, + Account: o.Account, + Claims: o.claims, + RequestType: accesstokens.ATPublic, + IsAppCache: false, + TenantID: o.tenantID, + } + + return pca.base.AcquireTokenSilent(ctx, silentParameters) +} + +// acquireTokenByUsernamePasswordOptions contains optional configuration for AcquireTokenByUsernamePassword +type acquireTokenByUsernamePasswordOptions struct { + claims, tenantID string +} + +// AcquireByUsernamePasswordOption is implemented by options for AcquireTokenByUsernamePassword +type AcquireByUsernamePasswordOption interface { + acquireByUsernamePasswordOption() +} + +// AcquireTokenByUsernamePassword acquires a security token from the authority, via Username/Password Authentication. +// NOTE: this flow is NOT recommended. +// +// Options: [WithClaims], [WithTenantID] +func (pca Client) AcquireTokenByUsernamePassword(ctx context.Context, scopes []string, username, password string, opts ...AcquireByUsernamePasswordOption) (AuthResult, error) { + o := acquireTokenByUsernamePasswordOptions{} + if err := options.ApplyOptions(&o, opts); err != nil { + return AuthResult{}, err + } + authParams, err := pca.base.AuthParams.WithTenant(o.tenantID) + if err != nil { + return AuthResult{}, err + } + authParams.Scopes = scopes + authParams.AuthorizationType = authority.ATUsernamePassword + authParams.Claims = o.claims + authParams.Username = username + authParams.Password = password + + token, err := pca.base.Token.UsernamePassword(ctx, authParams) + if err != nil { + return AuthResult{}, err + } + return pca.base.AuthResultFromToken(ctx, authParams, token, true) +} + +type DeviceCodeResult = accesstokens.DeviceCodeResult + +// DeviceCode provides the results of the device code flows first stage (containing the code) +// that must be entered on the second device and provides a method to retrieve the AuthenticationResult +// once that code has been entered and verified. +type DeviceCode struct { + // Result holds the information about the device code (such as the code). + Result DeviceCodeResult + + authParams authority.AuthParams + client Client + dc oauth.DeviceCode +} + +// AuthenticationResult retreives the AuthenticationResult once the user enters the code +// on the second device. Until then it blocks until the .AcquireTokenByDeviceCode() context +// is cancelled or the token expires. +func (d DeviceCode) AuthenticationResult(ctx context.Context) (AuthResult, error) { + token, err := d.dc.Token(ctx) + if err != nil { + return AuthResult{}, err + } + return d.client.base.AuthResultFromToken(ctx, d.authParams, token, true) +} + +// acquireTokenByDeviceCodeOptions contains optional configuration for AcquireTokenByDeviceCode +type acquireTokenByDeviceCodeOptions struct { + claims, tenantID string +} + +// AcquireByDeviceCodeOption is implemented by options for AcquireTokenByDeviceCode +type AcquireByDeviceCodeOption interface { + acquireByDeviceCodeOptions() +} + +// AcquireTokenByDeviceCode acquires a security token from the authority, by acquiring a device code and using that to acquire the token. +// Users need to create an AcquireTokenDeviceCodeParameters instance and pass it in. +// +// Options: [WithClaims], [WithTenantID] +func (pca Client) AcquireTokenByDeviceCode(ctx context.Context, scopes []string, opts ...AcquireByDeviceCodeOption) (DeviceCode, error) { + o := acquireTokenByDeviceCodeOptions{} + if err := options.ApplyOptions(&o, opts); err != nil { + return DeviceCode{}, err + } + authParams, err := pca.base.AuthParams.WithTenant(o.tenantID) + if err != nil { + return DeviceCode{}, err + } + authParams.Scopes = scopes + authParams.AuthorizationType = authority.ATDeviceCode + authParams.Claims = o.claims + + dc, err := pca.base.Token.DeviceCode(ctx, authParams) + if err != nil { + return DeviceCode{}, err + } + + return DeviceCode{Result: dc.Result, authParams: authParams, client: pca, dc: dc}, nil +} + +// AcquireTokenByAuthCodeOptions contains the optional parameters used to acquire an access token using the authorization code flow. +type AcquireTokenByAuthCodeOptions struct { + Challenge string + + claims, tenantID string +} + +// AcquireByAuthCodeOption is implemented by options for AcquireTokenByAuthCode +type AcquireByAuthCodeOption interface { + acquireByAuthCodeOption() +} + +// AcquireTokenByAuthCodeOption changes options inside AcquireTokenByAuthCodeOptions used in .AcquireTokenByAuthCode(). +type AcquireTokenByAuthCodeOption func(a *AcquireTokenByAuthCodeOptions) + +func (AcquireTokenByAuthCodeOption) acquireByAuthCodeOption() {} + +// WithChallenge allows you to provide a code for the .AcquireTokenByAuthCode() call. +func WithChallenge(challenge string) interface { + AcquireByAuthCodeOption + options.CallOption +} { + return struct { + AcquireByAuthCodeOption + options.CallOption + }{ + CallOption: options.NewCallOption( + func(a any) error { + switch t := a.(type) { + case *AcquireTokenByAuthCodeOptions: + t.Challenge = challenge + default: + return fmt.Errorf("unexpected options type %T", a) + } + return nil + }, + ), + } +} + +// AcquireTokenByAuthCode is a request to acquire a security token from the authority, using an authorization code. +// The specified redirect URI must be the same URI that was used when the authorization code was requested. +// +// Options: [WithChallenge], [WithClaims], [WithTenantID] +func (pca Client) AcquireTokenByAuthCode(ctx context.Context, code string, redirectURI string, scopes []string, opts ...AcquireByAuthCodeOption) (AuthResult, error) { + o := AcquireTokenByAuthCodeOptions{} + if err := options.ApplyOptions(&o, opts); err != nil { + return AuthResult{}, err + } + + params := base.AcquireTokenAuthCodeParameters{ + Scopes: scopes, + Code: code, + Challenge: o.Challenge, + Claims: o.claims, + AppType: accesstokens.ATPublic, + RedirectURI: redirectURI, + TenantID: o.tenantID, + } + + return pca.base.AcquireTokenByAuthCode(ctx, params) +} + +// Accounts gets all the accounts in the token cache. +// If there are no accounts in the cache the returned slice is empty. +func (pca Client) Accounts() []Account { + return pca.base.AllAccounts() +} + +// RemoveAccount signs the account out and forgets account from token cache. +func (pca Client) RemoveAccount(account Account) error { + pca.base.RemoveAccount(account) + return nil +} + +// InteractiveAuthOptions contains the optional parameters used to acquire an access token for interactive auth code flow. +type InteractiveAuthOptions struct { + // Used to specify a custom port for the local server. http://localhost:portnumber + // All other URI components are ignored. + RedirectURI string + + claims, loginHint, tenantID, domainHint string +} + +// AcquireInteractiveOption is implemented by options for AcquireTokenInteractive +type AcquireInteractiveOption interface { + acquireInteractiveOption() +} + +// InteractiveAuthOption changes options inside InteractiveAuthOptions used in .AcquireTokenInteractive(). +type InteractiveAuthOption func(*InteractiveAuthOptions) + +func (InteractiveAuthOption) acquireInteractiveOption() {} + +// WithLoginHint pre-populates the login prompt with a username. +func WithLoginHint(username string) interface { + AcquireInteractiveOption + CreateAuthCodeURLOption + options.CallOption +} { + return struct { + AcquireInteractiveOption + CreateAuthCodeURLOption + options.CallOption + }{ + CallOption: options.NewCallOption( + func(a any) error { + switch t := a.(type) { + case *createAuthCodeURLOptions: + t.loginHint = username + case *InteractiveAuthOptions: + t.loginHint = username + default: + return fmt.Errorf("unexpected options type %T", a) + } + return nil + }, + ), + } +} + +// WithDomainHint adds the IdP domain as domain_hint query parameter in the auth url. +func WithDomainHint(domain string) interface { + AcquireInteractiveOption + CreateAuthCodeURLOption + options.CallOption +} { + return struct { + AcquireInteractiveOption + CreateAuthCodeURLOption + options.CallOption + }{ + CallOption: options.NewCallOption( + func(a any) error { + switch t := a.(type) { + case *createAuthCodeURLOptions: + t.domainHint = domain + case *InteractiveAuthOptions: + t.domainHint = domain + default: + return fmt.Errorf("unexpected options type %T", a) + } + return nil + }, + ), + } +} + +// WithRedirectURI uses the specified redirect URI for interactive auth. +func WithRedirectURI(redirectURI string) interface { + AcquireInteractiveOption + options.CallOption +} { + return struct { + AcquireInteractiveOption + options.CallOption + }{ + CallOption: options.NewCallOption( + func(a any) error { + switch t := a.(type) { + case *InteractiveAuthOptions: + t.RedirectURI = redirectURI + default: + return fmt.Errorf("unexpected options type %T", a) + } + return nil + }, + ), + } +} + +// AcquireTokenInteractive acquires a security token from the authority using the default web browser to select the account. +// https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-authentication-flows#interactive-and-non-interactive-authentication +// +// Options: [WithDomainHint], [WithLoginHint], [WithRedirectURI], [WithTenantID] +func (pca Client) AcquireTokenInteractive(ctx context.Context, scopes []string, opts ...AcquireInteractiveOption) (AuthResult, error) { + o := InteractiveAuthOptions{} + if err := options.ApplyOptions(&o, opts); err != nil { + return AuthResult{}, err + } + // the code verifier is a random 32-byte sequence that's been base-64 encoded without padding. + // it's used to prevent MitM attacks during auth code flow, see https://tools.ietf.org/html/rfc7636 + cv, challenge, err := codeVerifier() + if err != nil { + return AuthResult{}, err + } + var redirectURL *url.URL + if o.RedirectURI != "" { + redirectURL, err = url.Parse(o.RedirectURI) + if err != nil { + return AuthResult{}, err + } + } + authParams, err := pca.base.AuthParams.WithTenant(o.tenantID) + if err != nil { + return AuthResult{}, err + } + authParams.Scopes = scopes + authParams.AuthorizationType = authority.ATInteractive + authParams.Claims = o.claims + authParams.CodeChallenge = challenge + authParams.CodeChallengeMethod = "S256" + authParams.LoginHint = o.loginHint + authParams.DomainHint = o.domainHint + authParams.State = uuid.New().String() + authParams.Prompt = "select_account" + res, err := pca.browserLogin(ctx, redirectURL, authParams) + if err != nil { + return AuthResult{}, err + } + authParams.Redirecturi = res.redirectURI + + req, err := accesstokens.NewCodeChallengeRequest(authParams, accesstokens.ATPublic, nil, res.authCode, cv) + if err != nil { + return AuthResult{}, err + } + + token, err := pca.base.Token.AuthCode(ctx, req) + if err != nil { + return AuthResult{}, err + } + + return pca.base.AuthResultFromToken(ctx, authParams, token, true) +} + +type interactiveAuthResult struct { + authCode string + redirectURI string +} + +// provides a test hook to simulate opening a browser +var browserOpenURL = func(authURL string) error { + return browser.OpenURL(authURL) +} + +// parses the port number from the provided URL. +// returns 0 if nil or no port is specified. +func parsePort(u *url.URL) (int, error) { + if u == nil { + return 0, nil + } + p := u.Port() + if p == "" { + return 0, nil + } + return strconv.Atoi(p) +} + +// browserLogin launches the system browser for interactive login +func (pca Client) browserLogin(ctx context.Context, redirectURI *url.URL, params authority.AuthParams) (interactiveAuthResult, error) { + // start local redirect server so login can call us back + port, err := parsePort(redirectURI) + if err != nil { + return interactiveAuthResult{}, err + } + srv, err := local.New(params.State, port) + if err != nil { + return interactiveAuthResult{}, err + } + defer srv.Shutdown() + params.Scopes = accesstokens.AppendDefaultScopes(params) + authURL, err := pca.base.AuthCodeURL(ctx, params.ClientID, srv.Addr, params.Scopes, params) + if err != nil { + return interactiveAuthResult{}, err + } + // open browser window so user can select credentials + if err := browserOpenURL(authURL); err != nil { + return interactiveAuthResult{}, err + } + // now wait until the logic calls us back + res := srv.Result(ctx) + if res.Err != nil { + return interactiveAuthResult{}, res.Err + } + return interactiveAuthResult{ + authCode: res.Code, + redirectURI: srv.Addr, + }, nil +} + +// creates a code verifier string along with its SHA256 hash which +// is used as the challenge when requesting an auth code. +// used in interactive auth flow for PKCE. +func codeVerifier() (codeVerifier string, challenge string, err error) { + cvBytes := make([]byte, 32) + if _, err = rand.Read(cvBytes); err != nil { + return + } + codeVerifier = base64.RawURLEncoding.EncodeToString(cvBytes) + // for PKCE, create a hash of the code verifier + cvh := sha256.Sum256([]byte(codeVerifier)) + challenge = base64.RawURLEncoding.EncodeToString(cvh[:]) + return +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go index 260a37cbbab..86db488defa 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go @@ -9,7 +9,7 @@ to refresh the credentials will be synchronized. But, the SDK is unable to ensure synchronous usage of the AssumeRoleProvider if the value is shared between multiple Credentials, Sessions or service clients. -Assume Role +# Assume Role To assume an IAM role using STS with the SDK you can create a new Credentials with the SDKs's stscreds package. @@ -27,7 +27,7 @@ with the SDKs's stscreds package. // from assumed role. svc := s3.New(sess, &aws.Config{Credentials: creds}) -Assume Role with static MFA Token +# Assume Role with static MFA Token To assume an IAM role with a MFA token you can either specify a MFA token code directly or provide a function to prompt the user each time the credentials @@ -49,7 +49,7 @@ credentials. // from assumed role. svc := s3.New(sess, &aws.Config{Credentials: creds}) -Assume Role with MFA Token Provider +# Assume Role with MFA Token Provider To assume an IAM role with MFA for longer running tasks where the credentials may need to be refreshed setting the TokenProvider field of AssumeRoleProvider @@ -74,7 +74,6 @@ single Credentials with an AssumeRoleProvider can be shared safely. // Create service client value configured for credentials // from assumed role. svc := s3.New(sess, &aws.Config{Credentials: creds}) - */ package stscreds @@ -199,6 +198,10 @@ type AssumeRoleProvider struct { // or an Amazon Resource Name (ARN) for a virtual device (such as arn:aws:iam::123456789012:mfa/user). SerialNumber *string + // The SourceIdentity which is used to identity a persistent identity through the whole session. + // For more details see https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_monitor.html + SourceIdentity *string + // The value provided by the MFA device, if the trust policy of the role being // assumed requires MFA (that is, if the policy includes a condition that tests // for MFA). If the role being assumed requires MFA and if the TokenCode value @@ -320,6 +323,7 @@ func (p *AssumeRoleProvider) RetrieveWithContext(ctx credentials.Context) (crede Tags: p.Tags, PolicyArns: p.PolicyArns, TransitiveTagKeys: p.TransitiveTagKeys, + SourceIdentity: p.SourceIdentity, } if p.Policy != nil { input.Policy = p.Policy diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go index debf74510cb..2e19166282d 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go @@ -13,6 +13,7 @@ const ( AwsUsGovPartitionID = "aws-us-gov" // AWS GovCloud (US) partition. AwsIsoPartitionID = "aws-iso" // AWS ISO (US) partition. AwsIsoBPartitionID = "aws-iso-b" // AWS ISOB (US) partition. + AwsIsoEPartitionID = "aws-iso-e" // AWS ISOE (Europe) partition. ) // AWS Standard partition's regions. @@ -69,8 +70,11 @@ const ( UsIsobEast1RegionID = "us-isob-east-1" // US ISOB East (Ohio). ) +// AWS ISOE (Europe) partition's regions. +const () + // DefaultResolver returns an Endpoint resolver that will be able -// to resolve endpoints for: AWS Standard, AWS China, AWS GovCloud (US), AWS ISO (US), and AWS ISOB (US). +// to resolve endpoints for: AWS Standard, AWS China, AWS GovCloud (US), AWS ISO (US), AWS ISOB (US), and AWS ISOE (Europe). // // Use DefaultPartitions() to get the list of the default partitions. func DefaultResolver() Resolver { @@ -78,7 +82,7 @@ func DefaultResolver() Resolver { } // DefaultPartitions returns a list of the partitions the SDK is bundled -// with. The available partitions are: AWS Standard, AWS China, AWS GovCloud (US), AWS ISO (US), and AWS ISOB (US). +// with. The available partitions are: AWS Standard, AWS China, AWS GovCloud (US), AWS ISO (US), AWS ISOB (US), and AWS ISOE (Europe). // // partitions := endpoints.DefaultPartitions // for _, p := range partitions { @@ -94,6 +98,7 @@ var defaultPartitions = partitions{ awsusgovPartition, awsisoPartition, awsisobPartition, + awsisoePartition, } // AwsPartition returns the Resolver for AWS Standard. @@ -1867,6 +1872,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -2074,6 +2082,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "me-central-1", + }: endpoint{}, endpointKey{ Region: "me-south-1", }: endpoint{}, @@ -3256,6 +3267,12 @@ var awsPartition = partition{ endpointKey{ Region: "ap-northeast-1", }: endpoint{}, + endpointKey{ + Region: "ap-northeast-2", + }: endpoint{}, + endpointKey{ + Region: "ap-south-1", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, @@ -3274,6 +3291,12 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-2", }: endpoint{}, + endpointKey{ + Region: "eu-west-3", + }: endpoint{}, + endpointKey{ + Region: "sa-east-1", + }: endpoint{}, endpointKey{ Region: "us-east-1", }: endpoint{}, @@ -3317,12 +3340,18 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-central-2", + }: endpoint{}, endpointKey{ Region: "eu-north-1", }: endpoint{}, @@ -3356,6 +3385,9 @@ var awsPartition = partition{ endpointKey{ Region: "us-east-2", }: endpoint{}, + endpointKey{ + Region: "us-west-1", + }: endpoint{}, endpointKey{ Region: "us-west-2", }: endpoint{}, @@ -3576,6 +3608,12 @@ var awsPartition = partition{ }: endpoint{ Hostname: "athena-fips.us-east-1.amazonaws.com", }, + endpointKey{ + Region: "us-east-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{ + Hostname: "athena-fips.us-east-1.api.aws", + }, endpointKey{ Region: "us-east-2", }: endpoint{}, @@ -3591,6 +3629,12 @@ var awsPartition = partition{ }: endpoint{ Hostname: "athena-fips.us-east-2.amazonaws.com", }, + endpointKey{ + Region: "us-east-2", + Variant: fipsVariant | dualStackVariant, + }: endpoint{ + Hostname: "athena-fips.us-east-2.api.aws", + }, endpointKey{ Region: "us-west-1", }: endpoint{}, @@ -3606,6 +3650,12 @@ var awsPartition = partition{ }: endpoint{ Hostname: "athena-fips.us-west-1.amazonaws.com", }, + endpointKey{ + Region: "us-west-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{ + Hostname: "athena-fips.us-west-1.api.aws", + }, endpointKey{ Region: "us-west-2", }: endpoint{}, @@ -3621,6 +3671,12 @@ var awsPartition = partition{ }: endpoint{ Hostname: "athena-fips.us-west-2.amazonaws.com", }, + endpointKey{ + Region: "us-west-2", + Variant: fipsVariant | dualStackVariant, + }: endpoint{ + Hostname: "athena-fips.us-west-2.api.aws", + }, }, }, "auditmanager": service{ @@ -3860,6 +3916,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -4033,6 +4092,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -5230,6 +5292,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -5901,6 +5966,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-north-1", }: endpoint{}, + endpointKey{ + Region: "eu-south-1", + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, @@ -6041,6 +6109,15 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "fips-us-west-1", + }: endpoint{ + Hostname: "cognito-identity-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "fips-us-west-2", }: endpoint{ @@ -6077,6 +6154,12 @@ var awsPartition = partition{ endpointKey{ Region: "us-west-1", }: endpoint{}, + endpointKey{ + Region: "us-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "cognito-identity-fips.us-west-1.amazonaws.com", + }, endpointKey{ Region: "us-west-2", }: endpoint{}, @@ -6746,12 +6829,42 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-2", }: endpoint{}, + endpointKey{ + Region: "fips-us-east-1", + }: endpoint{ + Hostname: "connect-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-2", + }: endpoint{ + Hostname: "connect-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "us-east-1", }: endpoint{}, + endpointKey{ + Region: "us-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "connect-fips.us-east-1.amazonaws.com", + }, endpointKey{ Region: "us-west-2", }: endpoint{}, + endpointKey{ + Region: "us-west-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "connect-fips.us-west-2.amazonaws.com", + }, }, }, "connect-campaigns": service{ @@ -6833,12 +6946,21 @@ var awsPartition = partition{ }, "controltower": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "af-south-1", + }: endpoint{}, + endpointKey{ + Region: "ap-east-1", + }: endpoint{}, endpointKey{ Region: "ap-northeast-1", }: endpoint{}, endpointKey{ Region: "ap-northeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-northeast-3", + }: endpoint{}, endpointKey{ Region: "ap-south-1", }: endpoint{}, @@ -6848,6 +6970,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-3", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -6872,6 +6997,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-north-1", }: endpoint{}, + endpointKey{ + Region: "eu-south-1", + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, @@ -6881,6 +7009,9 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "me-south-1", + }: endpoint{}, endpointKey{ Region: "sa-east-1", }: endpoint{}, @@ -6920,6 +7051,24 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "us-west-1", + }: endpoint{}, + endpointKey{ + Region: "us-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "controltower-fips.us-west-1.amazonaws.com", + }, + endpointKey{ + Region: "us-west-1-fips", + }: endpoint{ + Hostname: "controltower-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "us-west-2", }: endpoint{}, @@ -7464,6 +7613,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -7664,6 +7816,12 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "devops-guru-fips.ca-central-1.amazonaws.com", + }, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -7679,6 +7837,15 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "fips-ca-central-1", + }: endpoint{ + Hostname: "devops-guru-fips.ca-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "fips-us-east-1", }: endpoint{ @@ -7697,6 +7864,15 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "fips-us-west-1", + }: endpoint{ + Hostname: "devops-guru-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "fips-us-west-2", }: endpoint{ @@ -7730,6 +7906,12 @@ var awsPartition = partition{ endpointKey{ Region: "us-west-1", }: endpoint{}, + endpointKey{ + Region: "us-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "devops-guru-fips.us-west-1.amazonaws.com", + }, endpointKey{ Region: "us-west-2", }: endpoint{}, @@ -10724,6 +10906,9 @@ var awsPartition = partition{ }, "emr-serverless": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "ap-east-1", + }: endpoint{}, endpointKey{ Region: "ap-northeast-1", }: endpoint{}, @@ -10808,6 +10993,9 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "me-south-1", + }: endpoint{}, endpointKey{ Region: "sa-east-1", }: endpoint{}, @@ -11473,6 +11661,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -11978,6 +12169,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -12960,6 +13154,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -13606,21 +13803,11 @@ var awsPartition = partition{ }: endpoint{ Hostname: "internetmonitor.ap-northeast-2.api.aws", }, - endpointKey{ - Region: "ap-northeast-3", - }: endpoint{ - Hostname: "internetmonitor.ap-northeast-3.api.aws", - }, endpointKey{ Region: "ap-south-1", }: endpoint{ Hostname: "internetmonitor.ap-south-1.api.aws", }, - endpointKey{ - Region: "ap-south-2", - }: endpoint{ - Hostname: "internetmonitor.ap-south-2.api.aws", - }, endpointKey{ Region: "ap-southeast-1", }: endpoint{ @@ -13631,16 +13818,6 @@ var awsPartition = partition{ }: endpoint{ Hostname: "internetmonitor.ap-southeast-2.api.aws", }, - endpointKey{ - Region: "ap-southeast-3", - }: endpoint{ - Hostname: "internetmonitor.ap-southeast-3.api.aws", - }, - endpointKey{ - Region: "ap-southeast-4", - }: endpoint{ - Hostname: "internetmonitor.ap-southeast-4.api.aws", - }, endpointKey{ Region: "ca-central-1", }: endpoint{ @@ -13651,11 +13828,6 @@ var awsPartition = partition{ }: endpoint{ Hostname: "internetmonitor.eu-central-1.api.aws", }, - endpointKey{ - Region: "eu-central-2", - }: endpoint{ - Hostname: "internetmonitor.eu-central-2.api.aws", - }, endpointKey{ Region: "eu-north-1", }: endpoint{ @@ -13666,11 +13838,6 @@ var awsPartition = partition{ }: endpoint{ Hostname: "internetmonitor.eu-south-1.api.aws", }, - endpointKey{ - Region: "eu-south-2", - }: endpoint{ - Hostname: "internetmonitor.eu-south-2.api.aws", - }, endpointKey{ Region: "eu-west-1", }: endpoint{ @@ -13686,11 +13853,6 @@ var awsPartition = partition{ }: endpoint{ Hostname: "internetmonitor.eu-west-3.api.aws", }, - endpointKey{ - Region: "me-central-1", - }: endpoint{ - Hostname: "internetmonitor.me-central-1.api.aws", - }, endpointKey{ Region: "me-south-1", }: endpoint{ @@ -13724,13 +13886,6 @@ var awsPartition = partition{ }, }, "iot": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - CredentialScope: credentialScope{ - Service: "execute-api", - }, - }, - }, Endpoints: serviceEndpoints{ endpointKey{ Region: "ap-east-1", @@ -13778,45 +13933,35 @@ var awsPartition = partition{ Region: "fips-ca-central-1", }: endpoint{ Hostname: "iot-fips.ca-central-1.amazonaws.com", - CredentialScope: credentialScope{ - Service: "execute-api", - }, + Deprecated: boxedTrue, }, endpointKey{ Region: "fips-us-east-1", }: endpoint{ Hostname: "iot-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Service: "execute-api", - }, + Deprecated: boxedTrue, }, endpointKey{ Region: "fips-us-east-2", }: endpoint{ Hostname: "iot-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Service: "execute-api", - }, + Deprecated: boxedTrue, }, endpointKey{ Region: "fips-us-west-1", }: endpoint{ Hostname: "iot-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Service: "execute-api", - }, + Deprecated: boxedTrue, }, endpointKey{ Region: "fips-us-west-2", }: endpoint{ Hostname: "iot-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Service: "execute-api", - }, + Deprecated: boxedTrue, }, endpointKey{ @@ -14656,9 +14801,18 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "kafka-fips.ca-central-1.amazonaws.com", + }, endpointKey{ Region: "eu-central-1", }: endpoint{}, @@ -14683,6 +14837,51 @@ var awsPartition = partition{ endpointKey{ Region: "eu-west-3", }: endpoint{}, + endpointKey{ + Region: "fips-ca-central-1", + }: endpoint{ + Hostname: "kafka-fips.ca-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-east-1", + }: endpoint{ + Hostname: "kafka-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-east-2", + }: endpoint{ + Hostname: "kafka-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-1", + }: endpoint{ + Hostname: "kafka-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-2", + }: endpoint{ + Hostname: "kafka-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -14695,15 +14894,39 @@ var awsPartition = partition{ endpointKey{ Region: "us-east-1", }: endpoint{}, + endpointKey{ + Region: "us-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "kafka-fips.us-east-1.amazonaws.com", + }, endpointKey{ Region: "us-east-2", }: endpoint{}, + endpointKey{ + Region: "us-east-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "kafka-fips.us-east-2.amazonaws.com", + }, endpointKey{ Region: "us-west-1", }: endpoint{}, + endpointKey{ + Region: "us-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "kafka-fips.us-west-1.amazonaws.com", + }, endpointKey{ Region: "us-west-2", }: endpoint{}, + endpointKey{ + Region: "us-west-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "kafka-fips.us-west-2.amazonaws.com", + }, }, }, "kafkaconnect": service{ @@ -15151,6 +15374,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -15624,6 +15850,14 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "il-central-1-fips", + }: endpoint{ + Hostname: "kms-fips.il-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "il-central-1", + }, + }, endpointKey{ Region: "me-central-1", }: endpoint{}, @@ -17582,6 +17816,55 @@ var awsPartition = partition{ }: endpoint{}, }, }, + "mediapackagev2": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "ap-northeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-2", + }: endpoint{}, + endpointKey{ + Region: "ap-south-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-2", + }: endpoint{}, + endpointKey{ + Region: "eu-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-north-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-2", + }: endpoint{}, + endpointKey{ + Region: "eu-west-3", + }: endpoint{}, + endpointKey{ + Region: "sa-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-2", + }: endpoint{}, + endpointKey{ + Region: "us-west-1", + }: endpoint{}, + endpointKey{ + Region: "us-west-2", + }: endpoint{}, + }, + }, "mediastore": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -17862,6 +18145,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-south-1", }: endpoint{}, + endpointKey{ + Region: "ap-south-2", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, @@ -17871,6 +18157,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -18413,6 +18702,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-south-1", }: endpoint{}, + endpointKey{ + Region: "ap-south-2", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, @@ -18422,18 +18714,27 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, endpointKey{ Region: "eu-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-central-2", + }: endpoint{}, endpointKey{ Region: "eu-north-1", }: endpoint{}, endpointKey{ Region: "eu-south-1", }: endpoint{}, + endpointKey{ + Region: "eu-south-2", + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, @@ -19336,6 +19637,40 @@ var awsPartition = partition{ }, }, }, + "osis": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "ap-northeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-2", + }: endpoint{}, + endpointKey{ + Region: "eu-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-2", + }: endpoint{}, + endpointKey{ + Region: "us-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-2", + }: endpoint{}, + endpointKey{ + Region: "us-west-1", + }: endpoint{}, + endpointKey{ + Region: "us-west-2", + }: endpoint{}, + }, + }, "outposts": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -20203,18 +20538,63 @@ var awsPartition = partition{ endpointKey{ Region: "ca-central-1", }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "profile-fips.ca-central-1.amazonaws.com", + }, endpointKey{ Region: "eu-central-1", }: endpoint{}, endpointKey{ Region: "eu-west-2", }: endpoint{}, + endpointKey{ + Region: "fips-ca-central-1", + }: endpoint{ + Hostname: "profile-fips.ca-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-east-1", + }: endpoint{ + Hostname: "profile-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-2", + }: endpoint{ + Hostname: "profile-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "us-east-1", }: endpoint{}, + endpointKey{ + Region: "us-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "profile-fips.us-east-1.amazonaws.com", + }, endpointKey{ Region: "us-west-2", }: endpoint{}, + endpointKey{ + Region: "us-west-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "profile-fips.us-west-2.amazonaws.com", + }, }, }, "projects.iot1click": service{ @@ -21688,16 +22068,6 @@ var awsPartition = partition{ }, }, Endpoints: serviceEndpoints{ - endpointKey{ - Region: "af-south-1", - }: endpoint{ - Hostname: "resource-explorer-2.af-south-1.api.aws", - }, - endpointKey{ - Region: "ap-east-1", - }: endpoint{ - Hostname: "resource-explorer-2.ap-east-1.api.aws", - }, endpointKey{ Region: "ap-northeast-1", }: endpoint{ @@ -22128,6 +22498,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -22362,6 +22735,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -23912,6 +24288,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-southeast-3", }: endpoint{}, + endpointKey{ + Region: "ap-southeast-4", + }: endpoint{}, endpointKey{ Region: "ca-central-1", }: endpoint{}, @@ -24027,6 +24406,12 @@ var awsPartition = partition{ endpointKey{ Region: "ap-northeast-1", }: endpoint{}, + endpointKey{ + Region: "ap-northeast-2", + }: endpoint{}, + endpointKey{ + Region: "ap-south-1", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, @@ -24051,6 +24436,9 @@ var awsPartition = partition{ endpointKey{ Region: "us-east-2", }: endpoint{}, + endpointKey{ + Region: "us-west-1", + }: endpoint{}, endpointKey{ Region: "us-west-2", }: endpoint{}, @@ -25007,6 +25395,130 @@ var awsPartition = partition{ }, }, }, + "signer": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "af-south-1", + }: endpoint{}, + endpointKey{ + Region: "ap-east-1", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-northeast-2", + }: endpoint{}, + endpointKey{ + Region: "ap-south-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-2", + }: endpoint{}, + endpointKey{ + Region: "ca-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-central-1", + }: endpoint{}, + endpointKey{ + Region: "eu-north-1", + }: endpoint{}, + endpointKey{ + Region: "eu-south-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-1", + }: endpoint{}, + endpointKey{ + Region: "eu-west-2", + }: endpoint{}, + endpointKey{ + Region: "eu-west-3", + }: endpoint{}, + endpointKey{ + Region: "fips-us-east-1", + }: endpoint{ + Hostname: "signer-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-east-2", + }: endpoint{ + Hostname: "signer-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-1", + }: endpoint{ + Hostname: "signer-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-west-2", + }: endpoint{ + Hostname: "signer-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "me-south-1", + }: endpoint{}, + endpointKey{ + Region: "sa-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "signer-fips.us-east-1.amazonaws.com", + }, + endpointKey{ + Region: "us-east-2", + }: endpoint{}, + endpointKey{ + Region: "us-east-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "signer-fips.us-east-2.amazonaws.com", + }, + endpointKey{ + Region: "us-west-1", + }: endpoint{}, + endpointKey{ + Region: "us-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "signer-fips.us-west-1.amazonaws.com", + }, + endpointKey{ + Region: "us-west-2", + }: endpoint{}, + endpointKey{ + Region: "us-west-2", + Variant: fipsVariant, + }: endpoint{ + Hostname: "signer-fips.us-west-2.amazonaws.com", + }, + }, + }, "simspaceweaver": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -27517,12 +28029,21 @@ var awsPartition = partition{ }, "transcribestreaming": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "af-south-1", + }: endpoint{}, endpointKey{ Region: "ap-northeast-1", }: endpoint{}, endpointKey{ Region: "ap-northeast-2", }: endpoint{}, + endpointKey{ + Region: "ap-south-1", + }: endpoint{}, + endpointKey{ + Region: "ap-southeast-1", + }: endpoint{}, endpointKey{ Region: "ap-southeast-2", }: endpoint{}, @@ -27680,6 +28201,9 @@ var awsPartition = partition{ endpointKey{ Region: "ap-south-1", }: endpoint{}, + endpointKey{ + Region: "ap-south-2", + }: endpoint{}, endpointKey{ Region: "ap-southeast-1", }: endpoint{}, @@ -27701,12 +28225,18 @@ var awsPartition = partition{ endpointKey{ Region: "eu-central-1", }: endpoint{}, + endpointKey{ + Region: "eu-central-2", + }: endpoint{}, endpointKey{ Region: "eu-north-1", }: endpoint{}, endpointKey{ Region: "eu-south-1", }: endpoint{}, + endpointKey{ + Region: "eu-south-2", + }: endpoint{}, endpointKey{ Region: "eu-west-1", }: endpoint{}, @@ -28665,6 +29195,14 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "fips-il-central-1", + }: endpoint{ + Hostname: "waf-regional-fips.il-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "il-central-1", + }, + }, endpointKey{ Region: "fips-me-central-1", }: endpoint{ @@ -29371,6 +29909,14 @@ var awsPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "fips-il-central-1", + }: endpoint{ + Hostname: "wafv2-fips.il-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "il-central-1", + }, + }, endpointKey{ Region: "fips-me-central-1", }: endpoint{ @@ -30087,6 +30633,16 @@ var awscnPartition = partition{ }: endpoint{}, }, }, + "airflow": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "cn-north-1", + }: endpoint{}, + endpointKey{ + Region: "cn-northwest-1", + }: endpoint{}, + }, + }, "api.ecr": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -30731,6 +31287,16 @@ var awscnPartition = partition{ }: endpoint{}, }, }, + "emr-serverless": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "cn-north-1", + }: endpoint{}, + endpointKey{ + Region: "cn-northwest-1", + }: endpoint{}, + }, + }, "es": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -30922,13 +31488,6 @@ var awscnPartition = partition{ }, }, "iot": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - CredentialScope: credentialScope{ - Service: "execute-api", - }, - }, - }, Endpoints: serviceEndpoints{ endpointKey{ Region: "cn-north-1", @@ -31095,6 +31654,16 @@ var awscnPartition = partition{ }: endpoint{}, }, }, + "license-manager-linux-subscriptions": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "cn-north-1", + }: endpoint{}, + endpointKey{ + Region: "cn-northwest-1", + }: endpoint{}, + }, + }, "logs": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -31532,6 +32101,16 @@ var awscnPartition = partition{ }: endpoint{}, }, }, + "signer": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "cn-north-1", + }: endpoint{}, + endpointKey{ + Region: "cn-northwest-1", + }: endpoint{}, + }, + }, "sms": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -32426,13 +33005,45 @@ var awsusgovPartition = partition{ endpointKey{ Region: "us-gov-east-1", }: endpoint{ + Hostname: "application-autoscaling.us-gov-east-1.amazonaws.com", Protocols: []string{"http", "https"}, }, + endpointKey{ + Region: "us-gov-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "application-autoscaling.us-gov-east-1.amazonaws.com", + Protocols: []string{"http", "https"}, + }, + endpointKey{ + Region: "us-gov-east-1-fips", + }: endpoint{ + Hostname: "application-autoscaling.us-gov-east-1.amazonaws.com", + Protocols: []string{"http", "https"}, + + Deprecated: boxedTrue, + }, endpointKey{ Region: "us-gov-west-1", }: endpoint{ + Hostname: "application-autoscaling.us-gov-west-1.amazonaws.com", + Protocols: []string{"http", "https"}, + }, + endpointKey{ + Region: "us-gov-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "application-autoscaling.us-gov-west-1.amazonaws.com", Protocols: []string{"http", "https"}, }, + endpointKey{ + Region: "us-gov-west-1-fips", + }: endpoint{ + Hostname: "application-autoscaling.us-gov-west-1.amazonaws.com", + Protocols: []string{"http", "https"}, + + Deprecated: boxedTrue, + }, }, }, "applicationinsights": service{ @@ -32547,6 +33158,12 @@ var awsusgovPartition = partition{ }: endpoint{ Hostname: "athena-fips.us-gov-east-1.amazonaws.com", }, + endpointKey{ + Region: "us-gov-east-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{ + Hostname: "athena-fips.us-gov-east-1.api.aws", + }, endpointKey{ Region: "us-gov-west-1", }: endpoint{}, @@ -32562,6 +33179,12 @@ var awsusgovPartition = partition{ }: endpoint{ Hostname: "athena-fips.us-gov-west-1.amazonaws.com", }, + endpointKey{ + Region: "us-gov-west-1", + Variant: fipsVariant | dualStackVariant, + }: endpoint{ + Hostname: "athena-fips.us-gov-west-1.api.aws", + }, }, }, "autoscaling": service{ @@ -33059,6 +33682,9 @@ var awsusgovPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "us-gov-east-1", + }: endpoint{}, endpointKey{ Region: "us-gov-west-1", }: endpoint{}, @@ -33233,9 +33859,24 @@ var awsusgovPartition = partition{ }, "connect": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-gov-west-1", + }: endpoint{ + Hostname: "connect.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "us-gov-west-1", }: endpoint{}, + endpointKey{ + Region: "us-gov-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "connect.us-gov-west-1.amazonaws.com", + }, }, }, "controltower": service{ @@ -34753,30 +35394,19 @@ var awsusgovPartition = partition{ }, }, "iot": service{ - Defaults: endpointDefaults{ - defaultKey{}: endpoint{ - CredentialScope: credentialScope{ - Service: "execute-api", - }, - }, - }, Endpoints: serviceEndpoints{ endpointKey{ Region: "fips-us-gov-east-1", }: endpoint{ Hostname: "iot-fips.us-gov-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Service: "execute-api", - }, + Deprecated: boxedTrue, }, endpointKey{ Region: "fips-us-gov-west-1", }: endpoint{ Hostname: "iot-fips.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Service: "execute-api", - }, + Deprecated: boxedTrue, }, endpointKey{ @@ -34947,10 +35577,56 @@ var awsusgovPartition = partition{ Endpoints: serviceEndpoints{ endpointKey{ Region: "us-gov-east-1", - }: endpoint{}, + }: endpoint{ + Hostname: "kafka.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + endpointKey{ + Region: "us-gov-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "kafka.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + endpointKey{ + Region: "us-gov-east-1-fips", + }: endpoint{ + Hostname: "kafka.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "us-gov-west-1", - }: endpoint{}, + }: endpoint{ + Hostname: "kafka.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + endpointKey{ + Region: "us-gov-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "kafka.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + endpointKey{ + Region: "us-gov-west-1-fips", + }: endpoint{ + Hostname: "kafka.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + Deprecated: boxedTrue, + }, }, }, "kendra": service{ @@ -35383,6 +36059,46 @@ var awsusgovPartition = partition{ }: endpoint{}, }, }, + "mgn": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-gov-east-1", + }: endpoint{ + Hostname: "mgn-fips.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "fips-us-gov-west-1", + }: endpoint{ + Hostname: "mgn-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "us-gov-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-gov-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "mgn-fips.us-gov-east-1.amazonaws.com", + }, + endpointKey{ + Region: "us-gov-west-1", + }: endpoint{}, + endpointKey{ + Region: "us-gov-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "mgn-fips.us-gov-west-1.amazonaws.com", + }, + }, + }, "models.lex": service{ Defaults: endpointDefaults{ defaultKey{}: endpoint{ @@ -36143,9 +36859,35 @@ var awsusgovPartition = partition{ endpointKey{ Region: "us-gov-east-1", }: endpoint{}, + endpointKey{ + Region: "us-gov-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "route53resolver.us-gov-east-1.amazonaws.com", + }, + endpointKey{ + Region: "us-gov-east-1-fips", + }: endpoint{ + Hostname: "route53resolver.us-gov-east-1.amazonaws.com", + + Deprecated: boxedTrue, + }, endpointKey{ Region: "us-gov-west-1", }: endpoint{}, + endpointKey{ + Region: "us-gov-west-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "route53resolver.us-gov-west-1.amazonaws.com", + }, + endpointKey{ + Region: "us-gov-west-1-fips", + }: endpoint{ + Hostname: "route53resolver.us-gov-west-1.amazonaws.com", + + Deprecated: boxedTrue, + }, }, }, "runtime.lex": service{ @@ -36906,14 +37648,14 @@ var awsusgovPartition = partition{ endpointKey{ Region: "us-gov-west-1", }: endpoint{ - Protocols: []string{"http", "https"}, + Protocols: []string{"https"}, }, endpointKey{ Region: "us-gov-west-1", Variant: fipsVariant, }: endpoint{ Hostname: "sns.us-gov-west-1.amazonaws.com", - Protocols: []string{"http", "https"}, + Protocols: []string{"https"}, }, }, }, @@ -37645,6 +38387,15 @@ var awsusgovPartition = partition{ }, "workspaces": service{ Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-gov-east-1", + }: endpoint{ + Hostname: "workspaces-fips.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + Deprecated: boxedTrue, + }, endpointKey{ Region: "fips-us-gov-west-1", }: endpoint{ @@ -37654,6 +38405,15 @@ var awsusgovPartition = partition{ }, Deprecated: boxedTrue, }, + endpointKey{ + Region: "us-gov-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-gov-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "workspaces-fips.us-gov-east-1.amazonaws.com", + }, endpointKey{ Region: "us-gov-west-1", }: endpoint{}, @@ -37816,6 +38576,13 @@ var awsisoPartition = partition{ }: endpoint{}, }, }, + "athena": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "us-iso-east-1", + }: endpoint{}, + }, + }, "autoscaling": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -37828,6 +38595,16 @@ var awsisoPartition = partition{ }: endpoint{}, }, }, + "cloudcontrolapi": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "us-iso-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-iso-west-1", + }: endpoint{}, + }, + }, "cloudformation": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -38251,6 +39028,9 @@ var awsisoPartition = partition{ endpointKey{ Region: "us-iso-east-1", }: endpoint{}, + endpointKey{ + Region: "us-iso-west-1", + }: endpoint{}, }, }, "logs": service{ @@ -38311,6 +39091,28 @@ var awsisoPartition = partition{ }: endpoint{}, }, }, + "rbin": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-iso-east-1", + }: endpoint{ + Hostname: "rbin-fips.us-iso-east-1.c2s.ic.gov", + CredentialScope: credentialScope{ + Region: "us-iso-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "us-iso-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-iso-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "rbin-fips.us-iso-east-1.c2s.ic.gov", + }, + }, + }, "rds": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -38350,6 +39152,9 @@ var awsisoPartition = partition{ endpointKey{ Region: "us-iso-east-1", }: endpoint{}, + endpointKey{ + Region: "us-iso-west-1", + }: endpoint{}, }, }, "runtime.sagemaker": service{ @@ -38503,6 +39308,9 @@ var awsisoPartition = partition{ endpointKey{ Region: "us-iso-east-1", }: endpoint{}, + endpointKey{ + Region: "us-iso-west-1", + }: endpoint{}, }, }, "transcribe": service{ @@ -38972,6 +39780,28 @@ var awsisobPartition = partition{ }: endpoint{}, }, }, + "rbin": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "fips-us-isob-east-1", + }: endpoint{ + Hostname: "rbin-fips.us-isob-east-1.sc2s.sgov.gov", + CredentialScope: credentialScope{ + Region: "us-isob-east-1", + }, + Deprecated: boxedTrue, + }, + endpointKey{ + Region: "us-isob-east-1", + }: endpoint{}, + endpointKey{ + Region: "us-isob-east-1", + Variant: fipsVariant, + }: endpoint{ + Hostname: "rbin-fips.us-isob-east-1.sc2s.sgov.gov", + }, + }, + }, "rds": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -39027,6 +39857,13 @@ var awsisobPartition = partition{ }: endpoint{}, }, }, + "secretsmanager": service{ + Endpoints: serviceEndpoints{ + endpointKey{ + Region: "us-isob-east-1", + }: endpoint{}, + }, + }, "snowball": service{ Endpoints: serviceEndpoints{ endpointKey{ @@ -39138,3 +39975,37 @@ var awsisobPartition = partition{ }, }, } + +// AwsIsoEPartition returns the Resolver for AWS ISOE (Europe). +func AwsIsoEPartition() Partition { + return awsisoePartition.Partition() +} + +var awsisoePartition = partition{ + ID: "aws-iso-e", + Name: "AWS ISOE (Europe)", + DNSSuffix: "cloud.adc-e.uk", + RegionRegex: regionRegex{ + Regexp: func() *regexp.Regexp { + reg, _ := regexp.Compile("^eu\\-isoe\\-\\w+\\-\\d+$") + return reg + }(), + }, + Defaults: endpointDefaults{ + defaultKey{}: endpoint{ + Hostname: "{service}.{region}.{dnsSuffix}", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + defaultKey{ + Variant: fipsVariant, + }: endpoint{ + Hostname: "{service}-fips.{region}.{dnsSuffix}", + DNSSuffix: "cloud.adc-e.uk", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + }, + Regions: regions{}, + Services: services{}, +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go index 4d78162c034..0240bd0be35 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go @@ -3,7 +3,7 @@ // Provides request signing for request that need to be signed with // AWS V4 Signatures. // -// Standalone Signer +// # Standalone Signer // // Generally using the signer outside of the SDK should not require any additional // logic when using Go v1.5 or higher. The signer does this by taking advantage @@ -14,10 +14,10 @@ // The signer will first check the URL.Opaque field, and use its value if set. // The signer does require the URL.Opaque field to be set in the form of: // -// "///" +// "///" // -// // e.g. -// "//example.com/some/path" +// // e.g. +// "//example.com/some/path" // // The leading "//" and hostname are required or the URL.Opaque escaping will // not work correctly. @@ -695,7 +695,8 @@ func (ctx *signingCtx) buildBodyDigest() error { includeSHA256Header := ctx.unsignedPayload || ctx.ServiceName == "s3" || ctx.ServiceName == "s3-object-lambda" || - ctx.ServiceName == "glacier" + ctx.ServiceName == "glacier" || + ctx.ServiceName == "s3-outposts" s3Presign := ctx.isPresign && (ctx.ServiceName == "s3" || diff --git a/vendor/github.com/aws/aws-sdk-go/aws/version.go b/vendor/github.com/aws/aws-sdk-go/aws/version.go index f34d398202f..2b410cc8906 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/version.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/version.go @@ -5,4 +5,4 @@ package aws const SDKName = "aws-sdk-go" // SDKVersion is the version of this SDK -const SDKVersion = "1.44.245" +const SDKVersion = "1.44.276" diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/restjson/unmarshal_error.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/restjson/unmarshal_error.go index 4fffd0427ba..5366a646d9c 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/restjson/unmarshal_error.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/restjson/unmarshal_error.go @@ -2,6 +2,7 @@ package restjson import ( "bytes" + "encoding/json" "io" "io/ioutil" "net/http" @@ -40,54 +41,30 @@ func (u *UnmarshalTypedError) UnmarshalError( resp *http.Response, respMeta protocol.ResponseMetadata, ) (error, error) { - - code := resp.Header.Get(errorTypeHeader) - msg := resp.Header.Get(errorMessageHeader) - - body := resp.Body - if len(code) == 0 || len(msg) == 0 { - // If unable to get code from HTTP headers have to parse JSON message - // to determine what kind of exception this will be. - var buf bytes.Buffer - var jsonErr jsonErrorResponse - teeReader := io.TeeReader(resp.Body, &buf) - err := jsonutil.UnmarshalJSONError(&jsonErr, teeReader) - if err != nil { - return nil, err - } - - body = ioutil.NopCloser(&buf) - if len(code) == 0 { - code = jsonErr.Code - } - msg = jsonErr.Message + code, msg, err := unmarshalErrorInfo(resp) + if err != nil { + return nil, err } - // If code has colon separators remove them so can compare against modeled - // exception names. - code = strings.SplitN(code, ":", 2)[0] - - if fn, ok := u.exceptions[code]; ok { - // If exception code is know, use associated constructor to get a value - // for the exception that the JSON body can be unmarshaled into. - v := fn(respMeta) - if err := jsonutil.UnmarshalJSONCaseInsensitive(v, body); err != nil { - return nil, err - } + fn, ok := u.exceptions[code] + if !ok { + return awserr.NewRequestFailure( + awserr.New(code, msg, nil), + respMeta.StatusCode, + respMeta.RequestID, + ), nil + } - if err := rest.UnmarshalResponse(resp, v, true); err != nil { - return nil, err - } + v := fn(respMeta) + if err := jsonutil.UnmarshalJSONCaseInsensitive(v, resp.Body); err != nil { + return nil, err + } - return v, nil + if err := rest.UnmarshalResponse(resp, v, true); err != nil { + return nil, err } - // fallback to unmodeled generic exceptions - return awserr.NewRequestFailure( - awserr.New(code, msg, nil), - respMeta.StatusCode, - respMeta.RequestID, - ), nil + return v, nil } // UnmarshalErrorHandler is a named request handler for unmarshaling restjson @@ -101,36 +78,80 @@ var UnmarshalErrorHandler = request.NamedHandler{ func UnmarshalError(r *request.Request) { defer r.HTTPResponse.Body.Close() - var jsonErr jsonErrorResponse - err := jsonutil.UnmarshalJSONError(&jsonErr, r.HTTPResponse.Body) + code, msg, err := unmarshalErrorInfo(r.HTTPResponse) if err != nil { r.Error = awserr.NewRequestFailure( - awserr.New(request.ErrCodeSerialization, - "failed to unmarshal response error", err), + awserr.New(request.ErrCodeSerialization, "failed to unmarshal response error", err), r.HTTPResponse.StatusCode, r.RequestID, ) return } - code := r.HTTPResponse.Header.Get(errorTypeHeader) - if code == "" { - code = jsonErr.Code - } - msg := r.HTTPResponse.Header.Get(errorMessageHeader) - if msg == "" { - msg = jsonErr.Message - } - - code = strings.SplitN(code, ":", 2)[0] r.Error = awserr.NewRequestFailure( - awserr.New(code, jsonErr.Message, nil), + awserr.New(code, msg, nil), r.HTTPResponse.StatusCode, r.RequestID, ) } type jsonErrorResponse struct { + Type string `json:"__type"` Code string `json:"code"` Message string `json:"message"` } + +func (j *jsonErrorResponse) SanitizedCode() string { + code := j.Code + if len(j.Type) > 0 { + code = j.Type + } + return sanitizeCode(code) +} + +// Remove superfluous components from a restJson error code. +// - If a : character is present, then take only the contents before the +// first : character in the value. +// - If a # character is present, then take only the contents after the first +// # character in the value. +// +// All of the following error values resolve to FooError: +// - FooError +// - FooError:http://internal.amazon.com/coral/com.amazon.coral.validate/ +// - aws.protocoltests.restjson#FooError +// - aws.protocoltests.restjson#FooError:http://internal.amazon.com/coral/com.amazon.coral.validate/ +func sanitizeCode(code string) string { + noColon := strings.SplitN(code, ":", 2)[0] + hashSplit := strings.SplitN(noColon, "#", 2) + return hashSplit[len(hashSplit)-1] +} + +// attempt to garner error details from the response, preferring header values +// when present +func unmarshalErrorInfo(resp *http.Response) (code string, msg string, err error) { + code = sanitizeCode(resp.Header.Get(errorTypeHeader)) + msg = resp.Header.Get(errorMessageHeader) + if len(code) > 0 && len(msg) > 0 { + return + } + + // a modeled error will have to be re-deserialized later, so the body must + // be preserved + var buf bytes.Buffer + tee := io.TeeReader(resp.Body, &buf) + defer func() { resp.Body = ioutil.NopCloser(&buf) }() + + var jsonErr jsonErrorResponse + if decodeErr := json.NewDecoder(tee).Decode(&jsonErr); decodeErr != nil && decodeErr != io.EOF { + err = awserr.NewUnmarshalError(decodeErr, "failed to decode response body", buf.Bytes()) + return + } + + if len(code) == 0 { + code = jsonErr.SanitizedCode() + } + if len(msg) == 0 { + msg = jsonErr.Message + } + return +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/ec2/api.go b/vendor/github.com/aws/aws-sdk-go/service/ec2/api.go index 1ed7b2921c2..994d221d318 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ec2/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ec2/api.go @@ -2725,9 +2725,8 @@ func (c *EC2) AttachVerifiedAccessTrustProviderRequest(input *AttachVerifiedAcce // AttachVerifiedAccessTrustProvider API operation for Amazon Elastic Compute Cloud. // -// A trust provider is a third-party entity that creates, maintains, and manages -// identity information for users and devices. One or more trust providers can -// be attached to an Amazon Web Services Verified Access instance. +// Attaches the specified Amazon Web Services Verified Access trust provider +// to the specified Amazon Web Services Verified Access instance. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -10070,10 +10069,9 @@ func (c *EC2) CreateVerifiedAccessGroupRequest(input *CreateVerifiedAccessGroupI // // An Amazon Web Services Verified Access group is a collection of Amazon Web // Services Verified Access endpoints who's associated applications have similar -// security requirements. Each instance within an Amazon Web Services Verified -// Access group shares an Amazon Web Services Verified Access policy. For example, -// you can group all Amazon Web Services Verified Access instances associated -// with “sales” applications together and use one common Amazon Web Services +// security requirements. Each instance within a Verified Access group shares +// an Verified Access policy. For example, you can group all Verified Access +// instances associated with "sales" applications together and use one common // Verified Access policy. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -10224,9 +10222,8 @@ func (c *EC2) CreateVerifiedAccessTrustProviderRequest(input *CreateVerifiedAcce // // A trust provider is a third-party entity that creates, maintains, and manages // identity information for users and devices. When an application request is -// made, the identity information sent by the trust provider will be evaluated -// by Amazon Web Services Verified Access, before allowing or denying the application -// request. +// made, the identity information sent by the trust provider is evaluated by +// Verified Access before allowing or denying the application request. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -31874,7 +31871,7 @@ func (c *EC2) DescribeVerifiedAccessEndpointsRequest(input *DescribeVerifiedAcce // DescribeVerifiedAccessEndpoints API operation for Amazon Elastic Compute Cloud. // -// Describe Amazon Web Services Verified Access endpoints. +// Describes the specified Amazon Web Services Verified Access endpoints. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -32004,7 +32001,7 @@ func (c *EC2) DescribeVerifiedAccessGroupsRequest(input *DescribeVerifiedAccessG // DescribeVerifiedAccessGroups API operation for Amazon Elastic Compute Cloud. // -// Describe details of existing Verified Access groups. +// Describes the specified Verified Access groups. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -32134,8 +32131,7 @@ func (c *EC2) DescribeVerifiedAccessInstanceLoggingConfigurationsRequest(input * // DescribeVerifiedAccessInstanceLoggingConfigurations API operation for Amazon Elastic Compute Cloud. // -// Describes the current logging configuration for the Amazon Web Services Verified -// Access instances. +// Describes the specified Amazon Web Services Verified Access instances. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -32265,7 +32261,7 @@ func (c *EC2) DescribeVerifiedAccessInstancesRequest(input *DescribeVerifiedAcce // DescribeVerifiedAccessInstances API operation for Amazon Elastic Compute Cloud. // -// Describe Verified Access instances. +// Describes the specified Amazon Web Services Verified Access instances. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -32395,7 +32391,7 @@ func (c *EC2) DescribeVerifiedAccessTrustProvidersRequest(input *DescribeVerifie // DescribeVerifiedAccessTrustProviders API operation for Amazon Elastic Compute Cloud. // -// Describe details of existing Verified Access trust providers. +// Describes the specified Amazon Web Services Verified Access trust providers. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -34704,7 +34700,8 @@ func (c *EC2) DetachVerifiedAccessTrustProviderRequest(input *DetachVerifiedAcce // DetachVerifiedAccessTrustProvider API operation for Amazon Elastic Compute Cloud. // -// Detach a trust provider from an Amazon Web Services Verified Access instance. +// Detaches the specified Amazon Web Services Verified Access trust provider +// from the specified Amazon Web Services Verified Access instance. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -40888,6 +40885,12 @@ func (c *EC2) GetNetworkInsightsAccessScopeAnalysisFindingsRequest(input *GetNet Name: opGetNetworkInsightsAccessScopeAnalysisFindings, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -40931,6 +40934,57 @@ func (c *EC2) GetNetworkInsightsAccessScopeAnalysisFindingsWithContext(ctx aws.C return out, req.Send() } +// GetNetworkInsightsAccessScopeAnalysisFindingsPages iterates over the pages of a GetNetworkInsightsAccessScopeAnalysisFindings operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetNetworkInsightsAccessScopeAnalysisFindings method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a GetNetworkInsightsAccessScopeAnalysisFindings operation. +// pageNum := 0 +// err := client.GetNetworkInsightsAccessScopeAnalysisFindingsPages(params, +// func(page *ec2.GetNetworkInsightsAccessScopeAnalysisFindingsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +func (c *EC2) GetNetworkInsightsAccessScopeAnalysisFindingsPages(input *GetNetworkInsightsAccessScopeAnalysisFindingsInput, fn func(*GetNetworkInsightsAccessScopeAnalysisFindingsOutput, bool) bool) error { + return c.GetNetworkInsightsAccessScopeAnalysisFindingsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetNetworkInsightsAccessScopeAnalysisFindingsPagesWithContext same as GetNetworkInsightsAccessScopeAnalysisFindingsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *EC2) GetNetworkInsightsAccessScopeAnalysisFindingsPagesWithContext(ctx aws.Context, input *GetNetworkInsightsAccessScopeAnalysisFindingsInput, fn func(*GetNetworkInsightsAccessScopeAnalysisFindingsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetNetworkInsightsAccessScopeAnalysisFindingsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetNetworkInsightsAccessScopeAnalysisFindingsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*GetNetworkInsightsAccessScopeAnalysisFindingsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opGetNetworkInsightsAccessScopeContent = "GetNetworkInsightsAccessScopeContent" // GetNetworkInsightsAccessScopeContentRequest generates a "aws/request.Request" representing the @@ -44638,10 +44692,10 @@ func (c *EC2) ModifyInstanceAttributeRequest(input *ModifyInstanceAttributeInput // only one attribute at a time. // // Note: Using this action to change the security groups associated with an -// elastic network interface (ENI) attached to an instance in a VPC can result -// in an error if the instance has more than one ENI. To change the security -// groups associated with an ENI attached to an instance that has multiple ENIs, -// we recommend that you use the ModifyNetworkInterfaceAttribute action. +// elastic network interface (ENI) attached to an instance can result in an +// error if the instance has more than one ENI. To change the security groups +// associated with an ENI attached to an instance that has multiple ENIs, we +// recommend that you use the ModifyNetworkInterfaceAttribute action. // // To modify some attributes, the instance must be stopped. For more information, // see Modify a stopped instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_ChangingAttributesWhileInstanceStopped.html) @@ -46040,10 +46094,6 @@ func (c *EC2) ModifyReservedInstancesRequest(input *ModifyReservedInstancesInput // For more information, see Modifying Reserved Instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ri-modifying.html) // in the Amazon EC2 User Guide. // -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. -// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -46994,7 +47044,8 @@ func (c *EC2) ModifyVerifiedAccessEndpointRequest(input *ModifyVerifiedAccessEnd // ModifyVerifiedAccessEndpoint API operation for Amazon Elastic Compute Cloud. // -// Modifies the configuration of an Amazon Web Services Verified Access endpoint. +// Modifies the configuration of the specified Amazon Web Services Verified +// Access endpoint. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -47067,7 +47118,7 @@ func (c *EC2) ModifyVerifiedAccessEndpointPolicyRequest(input *ModifyVerifiedAcc // ModifyVerifiedAccessEndpointPolicy API operation for Amazon Elastic Compute Cloud. // -// Modifies the specified Verified Access endpoint policy. +// Modifies the specified Amazon Web Services Verified Access endpoint policy. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -47140,7 +47191,7 @@ func (c *EC2) ModifyVerifiedAccessGroupRequest(input *ModifyVerifiedAccessGroupI // ModifyVerifiedAccessGroup API operation for Amazon Elastic Compute Cloud. // -// Modifies the specified Verified Access group configuration. +// Modifies the specified Amazon Web Services Verified Access group configuration. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -47213,7 +47264,7 @@ func (c *EC2) ModifyVerifiedAccessGroupPolicyRequest(input *ModifyVerifiedAccess // ModifyVerifiedAccessGroupPolicy API operation for Amazon Elastic Compute Cloud. // -// Modifies the specified Verified Access group policy. +// Modifies the specified Amazon Web Services Verified Access group policy. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -47286,7 +47337,8 @@ func (c *EC2) ModifyVerifiedAccessInstanceRequest(input *ModifyVerifiedAccessIns // ModifyVerifiedAccessInstance API operation for Amazon Elastic Compute Cloud. // -// Modifies the configuration of the specified Verified Access instance. +// Modifies the configuration of the specified Amazon Web Services Verified +// Access instance. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -49243,10 +49295,6 @@ func (c *EC2) PurchaseReservedInstancesOfferingRequest(input *PurchaseReservedIn // and Reserved Instance Marketplace (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ri-market-general.html) // in the Amazon EC2 User Guide. // -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon Elastic Compute Cloud User Guide. -// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -51217,10 +51265,6 @@ func (c *EC2) RequestSpotInstancesRequest(input *RequestSpotInstancesInput) (req // see Which is the best Spot request method to use? (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-best-practices.html#which-spot-request-method-to-use) // in the Amazon EC2 User Guide for Linux Instances. // -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon EC2 User Guide for Linux Instances. -// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -52482,20 +52526,13 @@ func (c *EC2) RunInstancesRequest(input *RunInstancesInput) (req *request.Reques // You can specify a number of options, or leave the default options. The following // rules apply: // -// - [EC2-VPC] If you don't specify a subnet ID, we choose a default subnet -// from your default VPC for you. If you don't have a default VPC, you must -// specify a subnet ID in the request. -// -// - [EC2-Classic] If don't specify an Availability Zone, we choose one for -// you. +// - If you don't specify a subnet ID, we choose a default subnet from your +// default VPC for you. If you don't have a default VPC, you must specify +// a subnet ID in the request. // -// - Some instance types must be launched into a VPC. If you do not have -// a default VPC, or if you do not specify a subnet ID, the request fails. -// For more information, see Instance types available only in a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-vpc.html#vpc-only-instance-types). -// -// - [EC2-VPC] All instances have a network interface with a primary private -// IPv4 address. If you don't specify this address, we choose one from the -// IPv4 range of your subnet. +// - All instances have a network interface with a primary private IPv4 address. +// If you don't specify this address, we choose one from the IPv4 range of +// your subnet. // // - Not all instance types support IPv6 addresses. For more information, // see Instance types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html). @@ -52529,10 +52566,6 @@ func (c *EC2) RunInstancesRequest(input *RunInstancesInput) (req *request.Reques // (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_InstanceStraightToTerminated.html), // and Troubleshooting connecting to your instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesConnecting.html). // -// We are retiring EC2-Classic. We recommend that you migrate from EC2-Classic -// to a VPC. For more information, see Migrate from EC2-Classic to a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) -// in the Amazon EC2 User Guide. -// // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. @@ -60191,12 +60224,12 @@ type AttachVerifiedAccessTrustProviderInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The ID of the Amazon Web Services Verified Access instance. + // The ID of the Verified Access instance. // // VerifiedAccessInstanceId is a required field VerifiedAccessInstanceId *string `type:"string" required:"true"` - // The ID of the Amazon Web Services Verified Access trust provider. + // The ID of the Verified Access trust provider. // // VerifiedAccessTrustProviderId is a required field VerifiedAccessTrustProviderId *string `type:"string" required:"true"` @@ -60263,10 +60296,10 @@ func (s *AttachVerifiedAccessTrustProviderInput) SetVerifiedAccessTrustProviderI type AttachVerifiedAccessTrustProviderOutput struct { _ struct{} `type:"structure"` - // The ID of the Amazon Web Services Verified Access instance. + // The ID of the Verified Access instance. VerifiedAccessInstance *VerifiedAccessInstance `locationName:"verifiedAccessInstance" type:"structure"` - // The ID of the Amazon Web Services Verified Access trust provider. + // The ID of the Verified Access trust provider. VerifiedAccessTrustProvider *VerifiedAccessTrustProvider `locationName:"verifiedAccessTrustProvider" type:"structure"` } @@ -62959,7 +62992,7 @@ type CancelSpotInstanceRequestsInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` - // One or more Spot Instance request IDs. + // The IDs of the Spot Instance requests. // // SpotInstanceRequestIds is a required field SpotInstanceRequestIds []*string `locationName:"SpotInstanceRequestId" locationNameList:"SpotInstanceRequestId" type:"list" required:"true"` @@ -63012,7 +63045,7 @@ func (s *CancelSpotInstanceRequestsInput) SetSpotInstanceRequestIds(v []*string) type CancelSpotInstanceRequestsOutput struct { _ struct{} `type:"structure"` - // One or more Spot Instance requests. + // The Spot Instance requests. CancelledSpotInstanceRequests []*CancelledSpotInstanceRequest `locationName:"spotInstanceRequestSet" locationNameList:"item" type:"list"` } @@ -66781,6 +66814,9 @@ func (s *CopySnapshotOutput) SetTags(v []*Tag) *CopySnapshotOutput { type CpuOptions struct { _ struct{} `type:"structure"` + // Indicates whether the instance is enabled for AMD SEV-SNP. + AmdSevSnp *string `locationName:"amdSevSnp" type:"string" enum:"AmdSevSnpSpecification"` + // The number of CPU cores for the instance. CoreCount *int64 `locationName:"coreCount" type:"integer"` @@ -66806,6 +66842,12 @@ func (s CpuOptions) GoString() string { return s.String() } +// SetAmdSevSnp sets the AmdSevSnp field's value. +func (s *CpuOptions) SetAmdSevSnp(v string) *CpuOptions { + s.AmdSevSnp = &v + return s +} + // SetCoreCount sets the CoreCount field's value. func (s *CpuOptions) SetCoreCount(v int64) *CpuOptions { s.CoreCount = &v @@ -66823,6 +66865,10 @@ func (s *CpuOptions) SetThreadsPerCore(v int64) *CpuOptions { type CpuOptionsRequest struct { _ struct{} `type:"structure"` + // Indicates whether to enable the instance for AMD SEV-SNP. AMD SEV-SNP is + // supported with M6a, R6a, and C6a instance types only. + AmdSevSnp *string `type:"string" enum:"AmdSevSnpSpecification"` + // The number of CPU cores for the instance. CoreCount *int64 `type:"integer"` @@ -66849,6 +66895,12 @@ func (s CpuOptionsRequest) GoString() string { return s.String() } +// SetAmdSevSnp sets the AmdSevSnp field's value. +func (s *CpuOptionsRequest) SetAmdSevSnp(v string) *CpuOptionsRequest { + s.AmdSevSnp = &v + return s +} + // SetCoreCount sets the CoreCount field's value. func (s *CpuOptionsRequest) SetCoreCount(v int64) *CpuOptionsRequest { s.CoreCount = &v @@ -70825,12 +70877,8 @@ type CreateLaunchTemplateInput struct { // The information for the launch template. // - // LaunchTemplateData is a sensitive parameter and its value will be - // replaced with "sensitive" in string returned by CreateLaunchTemplateInput's - // String and GoString methods. - // // LaunchTemplateData is a required field - LaunchTemplateData *RequestLaunchTemplateData `type:"structure" required:"true" sensitive:"true"` + LaunchTemplateData *RequestLaunchTemplateData `type:"structure" required:"true"` // A name for the launch template. // @@ -70987,12 +71035,8 @@ type CreateLaunchTemplateVersionInput struct { // The information for the launch template. // - // LaunchTemplateData is a sensitive parameter and its value will be - // replaced with "sensitive" in string returned by CreateLaunchTemplateVersionInput's - // String and GoString methods. - // // LaunchTemplateData is a required field - LaunchTemplateData *RequestLaunchTemplateData `type:"structure" required:"true" sensitive:"true"` + LaunchTemplateData *RequestLaunchTemplateData `type:"structure" required:"true"` // The ID of the launch template. // @@ -77032,7 +77076,8 @@ func (s *CreateTransitGatewayVpcAttachmentRequestOptions) SetIpv6Support(v strin return s } -// Options for a network interface-type endpoint. +// Describes the network interface options when creating an Amazon Web Services +// Verified Access endpoint using the network-interface type. type CreateVerifiedAccessEndpointEniOptions struct { _ struct{} `type:"structure"` @@ -77103,7 +77148,7 @@ type CreateVerifiedAccessEndpointInput struct { // ApplicationDomain is a required field ApplicationDomain *string `type:"string" required:"true"` - // The Amazon Web Services network component Verified Access attaches to. + // The type of attachment. // // AttachmentType is a required field AttachmentType *string `type:"string" required:"true" enum:"VerifiedAccessEndpointAttachmentType"` @@ -77113,7 +77158,7 @@ type CreateVerifiedAccessEndpointInput struct { // (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html). ClientToken *string `type:"string" idempotencyToken:"true"` - // A description for the Amazon Web Services Verified Access endpoint. + // A description for the Verified Access endpoint. Description *string `type:"string"` // The ARN of the public TLS/SSL certificate in Amazon Web Services Certificate @@ -77129,33 +77174,32 @@ type CreateVerifiedAccessEndpointInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // A custom identifier that gets prepended to a DNS name that is generated for + // A custom identifier that is prepended to the DNS name that is generated for // the endpoint. // // EndpointDomainPrefix is a required field EndpointDomainPrefix *string `type:"string" required:"true"` - // The type of Amazon Web Services Verified Access endpoint to create. + // The type of Verified Access endpoint to create. // // EndpointType is a required field EndpointType *string `type:"string" required:"true" enum:"VerifiedAccessEndpointType"` - // The load balancer details if creating the Amazon Web Services Verified Access - // endpoint as load-balancertype. + // The load balancer details. This parameter is required if the endpoint type + // is load-balancer. LoadBalancerOptions *CreateVerifiedAccessEndpointLoadBalancerOptions `type:"structure"` - // The network interface details if creating the Amazon Web Services Verified - // Access endpoint as network-interfacetype. + // The network interface details. This parameter is required if the endpoint + // type is network-interface. NetworkInterfaceOptions *CreateVerifiedAccessEndpointEniOptions `type:"structure"` - // The Amazon Web Services Verified Access policy document. + // The Verified Access policy document. PolicyDocument *string `type:"string"` - // The Amazon EC2 security groups to associate with the Amazon Web Services - // Verified Access endpoint. + // The IDs of the security groups to associate with the Verified Access endpoint. SecurityGroupIds []*string `locationName:"SecurityGroupId" locationNameList:"item" type:"list"` - // The tags to assign to the Amazon Web Services Verified Access endpoint. + // The tags to assign to the Verified Access endpoint. TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` // The ID of the Verified Access group to associate the endpoint with. @@ -77304,8 +77348,8 @@ func (s *CreateVerifiedAccessEndpointInput) SetVerifiedAccessGroupId(v string) * return s } -// Describes a load balancer when creating an Amazon Web Services Verified Access -// endpoint using the load-balancer type. +// Describes the load balancer options when creating an Amazon Web Services +// Verified Access endpoint using the load-balancer type. type CreateVerifiedAccessEndpointLoadBalancerOptions struct { _ struct{} `type:"structure"` @@ -77380,7 +77424,7 @@ func (s *CreateVerifiedAccessEndpointLoadBalancerOptions) SetSubnetIds(v []*stri type CreateVerifiedAccessEndpointOutput struct { _ struct{} `type:"structure"` - // The ID of the Amazon Web Services Verified Access endpoint. + // The ID of the Verified Access endpoint. VerifiedAccessEndpoint *VerifiedAccessEndpoint `locationName:"verifiedAccessEndpoint" type:"structure"` } @@ -77416,7 +77460,7 @@ type CreateVerifiedAccessGroupInput struct { // (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html). ClientToken *string `type:"string" idempotencyToken:"true"` - // A description for the Amazon Web Services Verified Access group. + // A description for the Verified Access group. Description *string `type:"string"` // Checks whether you have the required permissions for the action, without @@ -77425,13 +77469,13 @@ type CreateVerifiedAccessGroupInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The Amazon Web Services Verified Access policy document. + // The Verified Access policy document. PolicyDocument *string `type:"string"` - // The tags to assign to the Amazon Web Services Verified Access group. + // The tags to assign to the Verified Access group. TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` - // The ID of the Amazon Web Services Verified Access instance. + // The ID of the Verified Access instance. // // VerifiedAccessInstanceId is a required field VerifiedAccessInstanceId *string `type:"string" required:"true"` @@ -77543,7 +77587,7 @@ type CreateVerifiedAccessInstanceInput struct { // (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html). ClientToken *string `type:"string" idempotencyToken:"true"` - // A description for the Amazon Web Services Verified Access instance. + // A description for the Verified Access instance. Description *string `type:"string"` // Checks whether you have the required permissions for the action, without @@ -77552,7 +77596,7 @@ type CreateVerifiedAccessInstanceInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The tags to assign to the Amazon Web Services Verified Access instance. + // The tags to assign to the Verified Access instance. TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` } @@ -77601,7 +77645,7 @@ func (s *CreateVerifiedAccessInstanceInput) SetTagSpecifications(v []*TagSpecifi type CreateVerifiedAccessInstanceOutput struct { _ struct{} `type:"structure"` - // The ID of the Amazon Web Services Verified Access instance. + // The ID of the Verified Access instance. VerifiedAccessInstance *VerifiedAccessInstance `locationName:"verifiedAccessInstance" type:"structure"` } @@ -77629,7 +77673,8 @@ func (s *CreateVerifiedAccessInstanceOutput) SetVerifiedAccessInstance(v *Verifi return s } -// Options for a device-identity type trust provider. +// Describes the options when creating an Amazon Web Services Verified Access +// trust provider using the device type. type CreateVerifiedAccessTrustProviderDeviceOptions struct { _ struct{} `type:"structure"` @@ -77669,13 +77714,15 @@ type CreateVerifiedAccessTrustProviderInput struct { // (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html). ClientToken *string `type:"string" idempotencyToken:"true"` - // A description for the Amazon Web Services Verified Access trust provider. + // A description for the Verified Access trust provider. Description *string `type:"string"` - // The options for device identity based trust providers. + // The options for a device-based trust provider. This parameter is required + // when the provider type is device. DeviceOptions *CreateVerifiedAccessTrustProviderDeviceOptions `type:"structure"` - // The type of device-based trust provider. + // The type of device-based trust provider. This parameter is required when + // the provider type is device. DeviceTrustProviderType *string `type:"string" enum:"DeviceTrustProviderType"` // Checks whether you have the required permissions for the action, without @@ -77684,7 +77731,8 @@ type CreateVerifiedAccessTrustProviderInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The OpenID Connect details for an oidc-type, user-identity based trust provider. + // The options for a OpenID Connect-compatible user-identity trust provider. + // This parameter is required when the provider type is user. OidcOptions *CreateVerifiedAccessTrustProviderOidcOptions `type:"structure"` // The identifier to be used when working with policy rules. @@ -77692,15 +77740,16 @@ type CreateVerifiedAccessTrustProviderInput struct { // PolicyReferenceName is a required field PolicyReferenceName *string `type:"string" required:"true"` - // The tags to assign to the Amazon Web Services Verified Access trust provider. + // The tags to assign to the Verified Access trust provider. TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` - // The type of trust provider can be either user or device-based. + // The type of trust provider. // // TrustProviderType is a required field TrustProviderType *string `type:"string" required:"true" enum:"TrustProviderType"` - // The type of user-based trust provider. + // The type of user-based trust provider. This parameter is required when the + // provider type is user. UserTrustProviderType *string `type:"string" enum:"UserTrustProviderType"` } @@ -77798,7 +77847,8 @@ func (s *CreateVerifiedAccessTrustProviderInput) SetUserTrustProviderType(v stri return s } -// Options for an OIDC-based, user-identity type trust provider. +// Describes the options when creating an Amazon Web Services Verified Access +// trust provider using the user type. type CreateVerifiedAccessTrustProviderOidcOptions struct { _ struct{} `type:"structure"` @@ -77809,7 +77859,11 @@ type CreateVerifiedAccessTrustProviderOidcOptions struct { ClientId *string `type:"string"` // The client secret. - ClientSecret *string `type:"string"` + // + // ClientSecret is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by CreateVerifiedAccessTrustProviderOidcOptions's + // String and GoString methods. + ClientSecret *string `type:"string" sensitive:"true"` // The OIDC issuer. Issuer *string `type:"string"` @@ -77889,7 +77943,7 @@ func (s *CreateVerifiedAccessTrustProviderOidcOptions) SetUserInfoEndpoint(v str type CreateVerifiedAccessTrustProviderOutput struct { _ struct{} `type:"structure"` - // The ID of the Amazon Web Services Verified Access trust provider. + // The ID of the Verified Access trust provider. VerifiedAccessTrustProvider *VerifiedAccessTrustProvider `locationName:"verifiedAccessTrustProvider" type:"structure"` } @@ -85553,7 +85607,7 @@ type DeleteVerifiedAccessEndpointInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The ID of the Amazon Web Services Verified Access endpoint. + // The ID of the Verified Access endpoint. // // VerifiedAccessEndpointId is a required field VerifiedAccessEndpointId *string `type:"string" required:"true"` @@ -85611,7 +85665,7 @@ func (s *DeleteVerifiedAccessEndpointInput) SetVerifiedAccessEndpointId(v string type DeleteVerifiedAccessEndpointOutput struct { _ struct{} `type:"structure"` - // The ID of the Amazon Web Services Verified Access endpoint. + // The ID of the Verified Access endpoint. VerifiedAccessEndpoint *VerifiedAccessEndpoint `locationName:"verifiedAccessEndpoint" type:"structure"` } @@ -85653,7 +85707,7 @@ type DeleteVerifiedAccessGroupInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The ID of the Amazon Web Services Verified Access group. + // The ID of the Verified Access group. // // VerifiedAccessGroupId is a required field VerifiedAccessGroupId *string `type:"string" required:"true"` @@ -85711,7 +85765,7 @@ func (s *DeleteVerifiedAccessGroupInput) SetVerifiedAccessGroupId(v string) *Del type DeleteVerifiedAccessGroupOutput struct { _ struct{} `type:"structure"` - // The ID of the Amazon Web Services Verified Access group. + // The ID of the Verified Access group. VerifiedAccessGroup *VerifiedAccessGroup `locationName:"verifiedAccessGroup" type:"structure"` } @@ -85753,7 +85807,7 @@ type DeleteVerifiedAccessInstanceInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The ID of the Amazon Web Services Verified Access instance. + // The ID of the Verified Access instance. // // VerifiedAccessInstanceId is a required field VerifiedAccessInstanceId *string `type:"string" required:"true"` @@ -85811,7 +85865,7 @@ func (s *DeleteVerifiedAccessInstanceInput) SetVerifiedAccessInstanceId(v string type DeleteVerifiedAccessInstanceOutput struct { _ struct{} `type:"structure"` - // The ID of the Amazon Web Services Verified Access instance. + // The ID of the Verified Access instance. VerifiedAccessInstance *VerifiedAccessInstance `locationName:"verifiedAccessInstance" type:"structure"` } @@ -85853,7 +85907,7 @@ type DeleteVerifiedAccessTrustProviderInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The ID of the Amazon Web Services Verified Access trust provider. + // The ID of the Verified Access trust provider. // // VerifiedAccessTrustProviderId is a required field VerifiedAccessTrustProviderId *string `type:"string" required:"true"` @@ -85911,7 +85965,7 @@ func (s *DeleteVerifiedAccessTrustProviderInput) SetVerifiedAccessTrustProviderI type DeleteVerifiedAccessTrustProviderOutput struct { _ struct{} `type:"structure"` - // The ID of the Amazon Web Services Verified Access trust provider. + // The ID of the Verified Access trust provider. VerifiedAccessTrustProvider *VerifiedAccessTrustProvider `locationName:"verifiedAccessTrustProvider" type:"structure"` } @@ -87094,7 +87148,9 @@ type DeregisterInstanceEventNotificationAttributesInput struct { DryRun *bool `type:"boolean"` // Information about the tag keys to deregister. - InstanceTagAttribute *DeregisterInstanceTagAttributeRequest `type:"structure"` + // + // InstanceTagAttribute is a required field + InstanceTagAttribute *DeregisterInstanceTagAttributeRequest `type:"structure" required:"true"` } // String returns the string representation. @@ -87115,6 +87171,19 @@ func (s DeregisterInstanceEventNotificationAttributesInput) GoString() string { return s.String() } +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeregisterInstanceEventNotificationAttributesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeregisterInstanceEventNotificationAttributesInput"} + if s.InstanceTagAttribute == nil { + invalidParams.Add(request.NewErrParamRequired("InstanceTagAttribute")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + // SetDryRun sets the DryRun field's value. func (s *DeregisterInstanceEventNotificationAttributesInput) SetDryRun(v bool) *DeregisterInstanceEventNotificationAttributesInput { s.DryRun = &v @@ -94400,8 +94469,8 @@ type DescribeInstanceTypesInput struct { // One or more filters. Filter names and values are case-sensitive. // - // * auto-recovery-supported - Indicates whether auto recovery is supported - // (true | false). + // * auto-recovery-supported - Indicates whether Amazon CloudWatch action + // based recovery is supported (true | false). // // * bare-metal - Indicates whether it is a bare metal instance type (true // | false). @@ -94690,12 +94759,6 @@ type DescribeInstancesInput struct { // // * dns-name - The public DNS name of the instance. // - // * group-id - The ID of the security group for the instance. EC2-Classic - // only. - // - // * group-name - The name of the security group for the instance. EC2-Classic - // only. - // // * hibernation-options.configured - A Boolean that indicates whether the // instance is enabled for hibernation. A value of true means that the instance // is enabled for hibernation. @@ -99700,16 +99763,11 @@ type DescribeReservedInstancesInput struct { // // * scope - The scope of the Reserved Instance (Region or Availability Zone). // - // * product-description - The Reserved Instance product platform description. - // Instances that include (Amazon VPC) in the product platform description - // will only be displayed to EC2-Classic account holders and are for use - // with Amazon VPC (Linux/UNIX | Linux/UNIX (Amazon VPC) | SUSE Linux | SUSE - // Linux (Amazon VPC) | Red Hat Enterprise Linux | Red Hat Enterprise Linux - // (Amazon VPC) | Red Hat Enterprise Linux with HA (Amazon VPC) | Windows - // | Windows (Amazon VPC) | Windows with SQL Server Standard | Windows with - // SQL Server Standard (Amazon VPC) | Windows with SQL Server Web | Windows - // with SQL Server Web (Amazon VPC) | Windows with SQL Server Enterprise - // | Windows with SQL Server Enterprise (Amazon VPC)). + // * product-description - The Reserved Instance product platform description + // (Linux/UNIX | Linux with SQL Server Standard | Linux with SQL Server Web + // | Linux with SQL Server Enterprise | SUSE Linux | Red Hat Enterprise Linux + // | Red Hat Enterprise Linux with HA | Windows | Windows with SQL Server + // Standard | Windows with SQL Server Web | Windows with SQL Server Enterprise). // // * reserved-instances-id - The ID of the Reserved Instance. // @@ -99911,9 +99969,6 @@ type DescribeReservedInstancesModificationsInput struct { // * modification-result.target-configuration.instance-type - The instance // type of the new Reserved Instances. // - // * modification-result.target-configuration.platform - The network platform - // of the new Reserved Instances (EC2-Classic | EC2-VPC). - // // * reserved-instances-id - The ID of the Reserved Instances modified. // // * reserved-instances-modification-id - The ID of the modification request. @@ -100042,16 +100097,11 @@ type DescribeReservedInstancesOfferingsInput struct { // all offerings from both Amazon Web Services and the Reserved Instance // Marketplace are listed. // - // * product-description - The Reserved Instance product platform description. - // Instances that include (Amazon VPC) in the product platform description - // will only be displayed to EC2-Classic account holders and are for use - // with Amazon VPC. (Linux/UNIX | Linux/UNIX (Amazon VPC) | SUSE Linux | - // SUSE Linux (Amazon VPC) | Red Hat Enterprise Linux | Red Hat Enterprise - // Linux (Amazon VPC) | Red Hat Enterprise Linux with HA (Amazon VPC) | Windows - // | Windows (Amazon VPC) | Windows with SQL Server Standard | Windows with - // SQL Server Standard (Amazon VPC) | Windows with SQL Server Web | Windows - // with SQL Server Web (Amazon VPC) | Windows with SQL Server Enterprise - // | Windows with SQL Server Enterprise (Amazon VPC)) + // * product-description - The Reserved Instance product platform description + // (Linux/UNIX | Linux with SQL Server Standard | Linux with SQL Server Web + // | Linux with SQL Server Enterprise | SUSE Linux | Red Hat Enterprise Linux + // | Red Hat Enterprise Linux with HA | Windows | Windows with SQL Server + // Standard | Windows with SQL Server Web | Windows with SQL Server Enterprise). // // * reserved-instances-offering-id - The Reserved Instances offering ID. // @@ -100512,8 +100562,6 @@ type DescribeScheduledInstanceAvailabilityInput struct { // // * instance-type - The instance type (for example, c4.large). // - // * network-platform - The network platform (EC2-Classic or EC2-VPC). - // // * platform - The platform (Linux/UNIX or Windows). Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` @@ -100694,8 +100742,6 @@ type DescribeScheduledInstancesInput struct { // // * instance-type - The instance type (for example, c4.large). // - // * network-platform - The network platform (EC2-Classic or EC2-VPC). - // // * platform - The platform (Linux/UNIX or Windows). Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` @@ -102167,7 +102213,7 @@ type DescribeSpotInstanceRequestsInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` - // One or more filters. + // The filters. // // * availability-zone-group - The Availability Zone group. // @@ -102284,7 +102330,7 @@ type DescribeSpotInstanceRequestsInput struct { // from the end of the items returned by the previous request. NextToken *string `type:"string"` - // One or more Spot Instance request IDs. + // The IDs of the Spot Instance requests. SpotInstanceRequestIds []*string `locationName:"SpotInstanceRequestId" locationNameList:"SpotInstanceRequestId" type:"list"` } @@ -102344,7 +102390,7 @@ type DescribeSpotInstanceRequestsOutput struct { // value is null when there are no more items to return. NextToken *string `locationName:"nextToken" type:"string"` - // One or more Spot Instance requests. + // The Spot Instance requests. SpotInstanceRequests []*SpotInstanceRequest `locationName:"spotInstanceRequestSet" locationNameList:"item" type:"list"` } @@ -102395,7 +102441,7 @@ type DescribeSpotPriceHistoryInput struct { // the price history data, in UTC format (for example, YYYY-MM-DDTHH:MM:SSZ). EndTime *time.Time `locationName:"endTime" type:"timestamp"` - // One or more filters. + // The filters. // // * availability-zone - The Availability Zone for which prices should be // returned. @@ -105087,13 +105133,13 @@ type DescribeVerifiedAccessEndpointsInput struct { // The token for the next page of results. NextToken *string `type:"string"` - // The ID of the Amazon Web Services Verified Access endpoint. + // The ID of the Verified Access endpoint. VerifiedAccessEndpointIds []*string `locationName:"VerifiedAccessEndpointId" locationNameList:"item" type:"list"` - // The ID of the Amazon Web Services Verified Access group. + // The ID of the Verified Access group. VerifiedAccessGroupId *string `type:"string"` - // The ID of the Amazon Web Services Verified Access instance. + // The ID of the Verified Access instance. VerifiedAccessInstanceId *string `type:"string"` } @@ -105177,7 +105223,7 @@ type DescribeVerifiedAccessEndpointsOutput struct { // when there are no more results to return. NextToken *string `locationName:"nextToken" type:"string"` - // The ID of the Amazon Web Services Verified Access endpoint. + // The ID of the Verified Access endpoint. VerifiedAccessEndpoints []*VerifiedAccessEndpoint `locationName:"verifiedAccessEndpointSet" locationNameList:"item" type:"list"` } @@ -105230,10 +105276,10 @@ type DescribeVerifiedAccessGroupsInput struct { // The token for the next page of results. NextToken *string `type:"string"` - // The ID of the Amazon Web Services Verified Access groups. + // The ID of the Verified Access groups. VerifiedAccessGroupIds []*string `locationName:"VerifiedAccessGroupId" locationNameList:"item" type:"list"` - // The ID of the Amazon Web Services Verified Access instance. + // The ID of the Verified Access instance. VerifiedAccessInstanceId *string `type:"string"` } @@ -105364,7 +105410,7 @@ type DescribeVerifiedAccessInstanceLoggingConfigurationsInput struct { // The token for the next page of results. NextToken *string `type:"string"` - // The IDs of the Amazon Web Services Verified Access instances. + // The IDs of the Verified Access instances. VerifiedAccessInstanceIds []*string `locationName:"VerifiedAccessInstanceId" locationNameList:"item" type:"list"` } @@ -105432,8 +105478,7 @@ func (s *DescribeVerifiedAccessInstanceLoggingConfigurationsInput) SetVerifiedAc type DescribeVerifiedAccessInstanceLoggingConfigurationsOutput struct { _ struct{} `type:"structure"` - // The current logging configuration for the Amazon Web Services Verified Access - // instances. + // The current logging configuration for the Verified Access instances. LoggingConfigurations []*VerifiedAccessInstanceLoggingConfiguration `locationName:"loggingConfigurationSet" locationNameList:"item" type:"list"` // The token to use to retrieve the next page of results. This value is null @@ -105490,7 +105535,7 @@ type DescribeVerifiedAccessInstancesInput struct { // The token for the next page of results. NextToken *string `type:"string"` - // The IDs of the Amazon Web Services Verified Access instances. + // The IDs of the Verified Access instances. VerifiedAccessInstanceIds []*string `locationName:"VerifiedAccessInstanceId" locationNameList:"item" type:"list"` } @@ -105562,7 +105607,7 @@ type DescribeVerifiedAccessInstancesOutput struct { // when there are no more results to return. NextToken *string `locationName:"nextToken" type:"string"` - // The IDs of the Amazon Web Services Verified Access instances. + // The IDs of the Verified Access instances. VerifiedAccessInstances []*VerifiedAccessInstance `locationName:"verifiedAccessInstanceSet" locationNameList:"item" type:"list"` } @@ -105615,7 +105660,7 @@ type DescribeVerifiedAccessTrustProvidersInput struct { // The token for the next page of results. NextToken *string `type:"string"` - // The IDs of the Amazon Web Services Verified Access trust providers. + // The IDs of the Verified Access trust providers. VerifiedAccessTrustProviderIds []*string `locationName:"VerifiedAccessTrustProviderId" locationNameList:"item" type:"list"` } @@ -105687,7 +105732,7 @@ type DescribeVerifiedAccessTrustProvidersOutput struct { // when there are no more results to return. NextToken *string `locationName:"nextToken" type:"string"` - // The IDs of the Amazon Web Services Verified Access trust providers. + // The IDs of the Verified Access trust providers. VerifiedAccessTrustProviders []*VerifiedAccessTrustProvider `locationName:"verifiedAccessTrustProviderSet" locationNameList:"item" type:"list"` } @@ -108428,12 +108473,12 @@ type DetachVerifiedAccessTrustProviderInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The ID of the Amazon Web Services Verified Access instance. + // The ID of the Verified Access instance. // // VerifiedAccessInstanceId is a required field VerifiedAccessInstanceId *string `type:"string" required:"true"` - // The ID of the Amazon Web Services Verified Access trust provider. + // The ID of the Verified Access trust provider. // // VerifiedAccessTrustProviderId is a required field VerifiedAccessTrustProviderId *string `type:"string" required:"true"` @@ -108500,10 +108545,10 @@ func (s *DetachVerifiedAccessTrustProviderInput) SetVerifiedAccessTrustProviderI type DetachVerifiedAccessTrustProviderOutput struct { _ struct{} `type:"structure"` - // The ID of the Amazon Web Services Verified Access instance. + // The ID of the Verified Access instance. VerifiedAccessInstance *VerifiedAccessInstance `locationName:"verifiedAccessInstance" type:"structure"` - // The ID of the Amazon Web Services Verified Access trust provider. + // The ID of the Verified Access trust provider. VerifiedAccessTrustProvider *VerifiedAccessTrustProvider `locationName:"verifiedAccessTrustProvider" type:"structure"` } @@ -108724,8 +108769,8 @@ func (s DetachVpnGatewayOutput) GoString() string { return s.String() } -// Options for an Amazon Web Services Verified Access device-identity based -// trust provider. +// Describes the options for an Amazon Web Services Verified Access device-identity +// based trust provider. type DeviceOptions struct { _ struct{} `type:"structure"` @@ -111789,7 +111834,11 @@ type DiskImageDescription struct { // // For information about the import manifest referenced by this API action, // see VM Import Manifest (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/manifest.html). - ImportManifestUrl *string `locationName:"importManifestUrl" type:"string"` + // + // ImportManifestUrl is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by DiskImageDescription's + // String and GoString methods. + ImportManifestUrl *string `locationName:"importManifestUrl" type:"string" sensitive:"true"` // The size of the disk image, in GiB. Size *int64 `locationName:"size" type:"long"` @@ -123716,7 +123765,7 @@ type GetVerifiedAccessEndpointPolicyInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The ID of the Amazon Web Services Verified Access endpoint. + // The ID of the Verified Access endpoint. // // VerifiedAccessEndpointId is a required field VerifiedAccessEndpointId *string `type:"string" required:"true"` @@ -123768,7 +123817,7 @@ func (s *GetVerifiedAccessEndpointPolicyInput) SetVerifiedAccessEndpointId(v str type GetVerifiedAccessEndpointPolicyOutput struct { _ struct{} `type:"structure"` - // The Amazon Web Services Verified Access policy document. + // The Verified Access policy document. PolicyDocument *string `locationName:"policyDocument" type:"string"` // The status of the Verified Access policy. @@ -123814,7 +123863,7 @@ type GetVerifiedAccessGroupPolicyInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The ID of the Amazon Web Services Verified Access group. + // The ID of the Verified Access group. // // VerifiedAccessGroupId is a required field VerifiedAccessGroupId *string `type:"string" required:"true"` @@ -123866,7 +123915,7 @@ func (s *GetVerifiedAccessGroupPolicyInput) SetVerifiedAccessGroupId(v string) * type GetVerifiedAccessGroupPolicyOutput struct { _ struct{} `type:"structure"` - // The Amazon Web Services Verified Access policy document. + // The Verified Access policy document. PolicyDocument *string `locationName:"policyDocument" type:"string"` // The status of the Verified Access policy. @@ -125853,7 +125902,11 @@ type ImageDiskContainer struct { // The URL to the Amazon S3-based disk image being imported. The URL can either // be a https URL (https://..) or an Amazon S3 URL (s3://..) - Url *string `type:"string"` + // + // Url is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by ImageDiskContainer's + // String and GoString methods. + Url *string `type:"string" sensitive:"true"` // The S3 bucket for the disk image. UserBucket *UserBucket `type:"structure"` @@ -127913,7 +127966,7 @@ type Instance struct { // The monitoring for the instance. Monitoring *Monitoring `locationName:"monitoring" type:"structure"` - // [EC2-VPC] The network interfaces for the instance. + // The network interfaces for the instance. NetworkInterfaces []*InstanceNetworkInterface `locationName:"networkInterfaceSet" locationNameList:"item" type:"list"` // The Amazon Resource Name (ARN) of the Outpost. @@ -127930,14 +127983,14 @@ type Instance struct { // in the Amazon EC2 User Guide. PlatformDetails *string `locationName:"platformDetails" type:"string"` - // (IPv4 only) The private DNS hostname name assigned to the instance. This + // [IPv4 only] The private DNS hostname name assigned to the instance. This // DNS hostname can only be used inside the Amazon EC2 network. This name is // not available until the instance enters the running state. // - // [EC2-VPC] The Amazon-provided DNS server resolves Amazon-provided private - // DNS hostnames if you've enabled DNS resolution and DNS hostnames in your - // VPC. If you are not using the Amazon-provided DNS server in your VPC, your - // custom domain name servers must resolve the hostname as appropriate. + // The Amazon-provided DNS server resolves Amazon-provided private DNS hostnames + // if you've enabled DNS resolution and DNS hostnames in your VPC. If you are + // not using the Amazon-provided DNS server in your VPC, your custom domain + // name servers must resolve the hostname as appropriate. PrivateDnsName *string `locationName:"privateDnsName" type:"string"` // The options for the instance hostname. @@ -127949,9 +128002,9 @@ type Instance struct { // The product codes attached to this instance, if applicable. ProductCodes []*ProductCode `locationName:"productCodes" locationNameList:"item" type:"list"` - // (IPv4 only) The public DNS name assigned to the instance. This name is not - // available until the instance enters the running state. For EC2-VPC, this - // name is only available if you've enabled DNS hostnames for your VPC. + // [IPv4 only] The public DNS name assigned to the instance. This name is not + // available until the instance enters the running state. This name is only + // available if you've enabled DNS hostnames for your VPC. PublicDnsName *string `locationName:"dnsName" type:"string"` // The public IPv4 address, or the Carrier IP address assigned to the instance, @@ -127993,7 +128046,7 @@ type Instance struct { // The reason for the most recent state transition. This might be an empty string. StateTransitionReason *string `locationName:"reason" type:"string"` - // [EC2-VPC] The ID of the subnet in which the instance is running. + // The ID of the subnet in which the instance is running. SubnetId *string `locationName:"subnetId" type:"string"` // Any tags assigned to the instance. @@ -128015,7 +128068,7 @@ type Instance struct { // The virtualization type of the instance. VirtualizationType *string `locationName:"virtualizationType" type:"string" enum:"VirtualizationType"` - // [EC2-VPC] The ID of the VPC in which the instance is running. + // The ID of the VPC in which the instance is running. VpcId *string `locationName:"vpcId" type:"string"` } @@ -131808,7 +131861,7 @@ func (s *InstanceTagNotificationAttribute) SetInstanceTagKeys(v []*string) *Inst type InstanceTypeInfo struct { _ struct{} `type:"structure"` - // Indicates whether auto recovery is supported. + // Indicates whether Amazon CloudWatch action based recovery is supported. AutoRecoverySupported *bool `locationName:"autoRecoverySupported" type:"boolean"` // Indicates whether the instance is a bare metal instance type. @@ -134884,7 +134937,7 @@ type LaunchSpecification struct { // Deprecated. AddressingType *string `locationName:"addressingType" type:"string"` - // One or more block device mapping entries. + // The block device mapping entries. BlockDeviceMappings []*BlockDeviceMapping `locationName:"blockDeviceMapping" locationNameList:"item" type:"list"` // Indicates whether the instance is optimized for EBS I/O. This optimization @@ -134914,8 +134967,8 @@ type LaunchSpecification struct { // Describes the monitoring of an instance. Monitoring *RunInstancesMonitoringEnabled `locationName:"monitoring" type:"structure"` - // One or more network interfaces. If you specify a network interface, you must - // specify subnet IDs and security group IDs using the network interface. + // The network interfaces. If you specify a network interface, you must specify + // subnet IDs and security group IDs using the network interface. NetworkInterfaces []*InstanceNetworkInterfaceSpecification `locationName:"networkInterfaceSet" locationNameList:"item" type:"list"` // The placement information for the instance. @@ -134924,9 +134977,7 @@ type LaunchSpecification struct { // The ID of the RAM disk. RamdiskId *string `locationName:"ramdiskId" type:"string"` - // One or more security groups. When requesting instances in a VPC, you must - // specify the IDs of the security groups. When requesting instances in EC2-Classic, - // you can specify the names or the IDs of the security groups. + // The IDs of the security groups. SecurityGroups []*GroupIdentifier `locationName:"groupSet" locationNameList:"item" type:"list"` // The ID of the subnet in which to launch the instance. @@ -135464,6 +135515,9 @@ func (s *LaunchTemplateConfig) SetOverrides(v []*LaunchTemplateOverrides) *Launc type LaunchTemplateCpuOptions struct { _ struct{} `type:"structure"` + // Indicates whether the instance is enabled for AMD SEV-SNP. + AmdSevSnp *string `locationName:"amdSevSnp" type:"string" enum:"AmdSevSnpSpecification"` + // The number of CPU cores for the instance. CoreCount *int64 `locationName:"coreCount" type:"integer"` @@ -135489,6 +135543,12 @@ func (s LaunchTemplateCpuOptions) GoString() string { return s.String() } +// SetAmdSevSnp sets the AmdSevSnp field's value. +func (s *LaunchTemplateCpuOptions) SetAmdSevSnp(v string) *LaunchTemplateCpuOptions { + s.AmdSevSnp = &v + return s +} + // SetCoreCount sets the CoreCount field's value. func (s *LaunchTemplateCpuOptions) SetCoreCount(v int64) *LaunchTemplateCpuOptions { s.CoreCount = &v @@ -135506,6 +135566,10 @@ func (s *LaunchTemplateCpuOptions) SetThreadsPerCore(v int64) *LaunchTemplateCpu type LaunchTemplateCpuOptionsRequest struct { _ struct{} `type:"structure"` + // Indicates whether to enable the instance for AMD SEV-SNP. AMD SEV-SNP is + // supported with M6a, R6a, and C6a instance types only. + AmdSevSnp *string `type:"string" enum:"AmdSevSnpSpecification"` + // The number of CPU cores for the instance. CoreCount *int64 `type:"integer"` @@ -135532,6 +135596,12 @@ func (s LaunchTemplateCpuOptionsRequest) GoString() string { return s.String() } +// SetAmdSevSnp sets the AmdSevSnp field's value. +func (s *LaunchTemplateCpuOptionsRequest) SetAmdSevSnp(v string) *LaunchTemplateCpuOptionsRequest { + s.AmdSevSnp = &v + return s +} + // SetCoreCount sets the CoreCount field's value. func (s *LaunchTemplateCpuOptionsRequest) SetCoreCount(v int64) *LaunchTemplateCpuOptionsRequest { s.CoreCount = &v @@ -137075,8 +137145,8 @@ type LaunchTemplatePlacement struct { // Reserved for future use. SpreadDomain *string `locationName:"spreadDomain" type:"string"` - // The tenancy of the instance (if the instance is running in a VPC). An instance - // with a tenancy of dedicated runs on single-tenant hardware. + // The tenancy of the instance. An instance with a tenancy of dedicated runs + // on single-tenant hardware. Tenancy *string `locationName:"tenancy" type:"string" enum:"Tenancy"` } @@ -137184,8 +137254,8 @@ type LaunchTemplatePlacementRequest struct { // Reserved for future use. SpreadDomain *string `type:"string"` - // The tenancy of the instance (if the instance is running in a VPC). An instance - // with a tenancy of dedicated runs on single-tenant hardware. + // The tenancy of the instance. An instance with a tenancy of dedicated runs + // on single-tenant hardware. Tenancy *string `type:"string" enum:"Tenancy"` } @@ -141270,10 +141340,9 @@ type ModifyInstanceAttributeInput struct { // a PV instance can make it unreachable. EnaSupport *AttributeBooleanValue `locationName:"enaSupport" type:"structure"` - // [EC2-VPC] Replaces the security groups of the instance with the specified - // security groups. You must specify at least one security group, even if it's - // just the default security group for the VPC. You must specify the security - // group ID, not the security group name. + // Replaces the security groups of the instance with the specified security + // groups. You must specify the ID of at least one security group, even if it's + // just the default security group for the VPC. Groups []*string `locationName:"GroupId" locationNameList:"groupId" type:"list"` // The ID of the instance. @@ -145484,7 +145553,8 @@ func (s *ModifyTransitGatewayVpcAttachmentRequestOptions) SetIpv6Support(v strin return s } -// Options for a network-interface type Verified Access endpoint. +// Describes the options when modifying a Verified Access endpoint with the +// network-interface type. type ModifyVerifiedAccessEndpointEniOptions struct { _ struct{} `type:"structure"` @@ -145546,7 +145616,7 @@ type ModifyVerifiedAccessEndpointInput struct { // (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html). ClientToken *string `type:"string" idempotencyToken:"true"` - // A description for the Amazon Web Services Verified Access endpoint. + // A description for the Verified Access endpoint. Description *string `type:"string"` // Checks whether you have the required permissions for the action, without @@ -145555,19 +145625,18 @@ type ModifyVerifiedAccessEndpointInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The load balancer details if creating the Amazon Web Services Verified Access - // endpoint as load-balancertype. + // The load balancer details if creating the Verified Access endpoint as load-balancertype. LoadBalancerOptions *ModifyVerifiedAccessEndpointLoadBalancerOptions `type:"structure"` // The network interface options. NetworkInterfaceOptions *ModifyVerifiedAccessEndpointEniOptions `type:"structure"` - // The ID of the Amazon Web Services Verified Access endpoint. + // The ID of the Verified Access endpoint. // // VerifiedAccessEndpointId is a required field VerifiedAccessEndpointId *string `type:"string" required:"true"` - // The ID of the Amazon Web Services Verified Access group. + // The ID of the Verified Access group. VerifiedAccessGroupId *string `type:"string"` } @@ -145721,7 +145790,7 @@ func (s *ModifyVerifiedAccessEndpointLoadBalancerOptions) SetSubnetIds(v []*stri type ModifyVerifiedAccessEndpointOutput struct { _ struct{} `type:"structure"` - // The Amazon Web Services Verified Access endpoint details. + // The Verified Access endpoint details. VerifiedAccessEndpoint *VerifiedAccessEndpoint `locationName:"verifiedAccessEndpoint" type:"structure"` } @@ -145763,7 +145832,7 @@ type ModifyVerifiedAccessEndpointPolicyInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The Amazon Web Services Verified Access policy document. + // The Verified Access policy document. PolicyDocument *string `type:"string"` // The status of the Verified Access policy. @@ -145771,7 +145840,7 @@ type ModifyVerifiedAccessEndpointPolicyInput struct { // PolicyEnabled is a required field PolicyEnabled *bool `type:"boolean" required:"true"` - // The ID of the Amazon Web Services Verified Access endpoint. + // The ID of the Verified Access endpoint. // // VerifiedAccessEndpointId is a required field VerifiedAccessEndpointId *string `type:"string" required:"true"` @@ -145844,7 +145913,7 @@ func (s *ModifyVerifiedAccessEndpointPolicyInput) SetVerifiedAccessEndpointId(v type ModifyVerifiedAccessEndpointPolicyOutput struct { _ struct{} `type:"structure"` - // The Amazon Web Services Verified Access policy document. + // The Verified Access policy document. PolicyDocument *string `locationName:"policyDocument" type:"string"` // The status of the Verified Access policy. @@ -145889,7 +145958,7 @@ type ModifyVerifiedAccessGroupInput struct { // (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html). ClientToken *string `type:"string" idempotencyToken:"true"` - // A description for the Amazon Web Services Verified Access group. + // A description for the Verified Access group. Description *string `type:"string"` // Checks whether you have the required permissions for the action, without @@ -145898,12 +145967,12 @@ type ModifyVerifiedAccessGroupInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The ID of the Amazon Web Services Verified Access group. + // The ID of the Verified Access group. // // VerifiedAccessGroupId is a required field VerifiedAccessGroupId *string `type:"string" required:"true"` - // The ID of the Amazon Web Services Verified Access instance. + // The ID of the Verified Access instance. VerifiedAccessInstanceId *string `type:"string"` } @@ -145971,7 +146040,7 @@ func (s *ModifyVerifiedAccessGroupInput) SetVerifiedAccessInstanceId(v string) * type ModifyVerifiedAccessGroupOutput struct { _ struct{} `type:"structure"` - // Details of Amazon Web Services Verified Access group. + // Details of Verified Access group. VerifiedAccessGroup *VerifiedAccessGroup `locationName:"verifiedAccessGroup" type:"structure"` } @@ -146013,7 +146082,7 @@ type ModifyVerifiedAccessGroupPolicyInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The Amazon Web Services Verified Access policy document. + // The Verified Access policy document. PolicyDocument *string `type:"string"` // The status of the Verified Access policy. @@ -146021,7 +146090,7 @@ type ModifyVerifiedAccessGroupPolicyInput struct { // PolicyEnabled is a required field PolicyEnabled *bool `type:"boolean" required:"true"` - // The ID of the Amazon Web Services Verified Access group. + // The ID of the Verified Access group. // // VerifiedAccessGroupId is a required field VerifiedAccessGroupId *string `type:"string" required:"true"` @@ -146094,7 +146163,7 @@ func (s *ModifyVerifiedAccessGroupPolicyInput) SetVerifiedAccessGroupId(v string type ModifyVerifiedAccessGroupPolicyOutput struct { _ struct{} `type:"structure"` - // The Amazon Web Services Verified Access policy document. + // The Verified Access policy document. PolicyDocument *string `locationName:"policyDocument" type:"string"` // The status of the Verified Access policy. @@ -146139,7 +146208,7 @@ type ModifyVerifiedAccessInstanceInput struct { // (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html). ClientToken *string `type:"string" idempotencyToken:"true"` - // A description for the Amazon Web Services Verified Access instance. + // A description for the Verified Access instance. Description *string `type:"string"` // Checks whether you have the required permissions for the action, without @@ -146148,7 +146217,7 @@ type ModifyVerifiedAccessInstanceInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The ID of the Amazon Web Services Verified Access instance. + // The ID of the Verified Access instance. // // VerifiedAccessInstanceId is a required field VerifiedAccessInstanceId *string `type:"string" required:"true"` @@ -146212,7 +146281,7 @@ func (s *ModifyVerifiedAccessInstanceInput) SetVerifiedAccessInstanceId(v string type ModifyVerifiedAccessInstanceLoggingConfigurationInput struct { _ struct{} `type:"structure"` - // The configuration options for Amazon Web Services Verified Access instances. + // The configuration options for Verified Access instances. // // AccessLogs is a required field AccessLogs *VerifiedAccessLogOptions `type:"structure" required:"true"` @@ -146228,7 +146297,7 @@ type ModifyVerifiedAccessInstanceLoggingConfigurationInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The ID of the Amazon Web Services Verified Access instance. + // The ID of the Verified Access instance. // // VerifiedAccessInstanceId is a required field VerifiedAccessInstanceId *string `type:"string" required:"true"` @@ -146300,7 +146369,7 @@ func (s *ModifyVerifiedAccessInstanceLoggingConfigurationInput) SetVerifiedAcces type ModifyVerifiedAccessInstanceLoggingConfigurationOutput struct { _ struct{} `type:"structure"` - // The logging configuration for Amazon Web Services Verified Access instance. + // The logging configuration for the Verified Access instance. LoggingConfiguration *VerifiedAccessInstanceLoggingConfiguration `locationName:"loggingConfiguration" type:"structure"` } @@ -146331,7 +146400,7 @@ func (s *ModifyVerifiedAccessInstanceLoggingConfigurationOutput) SetLoggingConfi type ModifyVerifiedAccessInstanceOutput struct { _ struct{} `type:"structure"` - // The ID of the Amazon Web Services Verified Access instance. + // The ID of the Verified Access instance. VerifiedAccessInstance *VerifiedAccessInstance `locationName:"verifiedAccessInstance" type:"structure"` } @@ -146367,7 +146436,7 @@ type ModifyVerifiedAccessTrustProviderInput struct { // (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html). ClientToken *string `type:"string" idempotencyToken:"true"` - // A description for the Amazon Web Services Verified Access trust provider. + // A description for the Verified Access trust provider. Description *string `type:"string"` // Checks whether you have the required permissions for the action, without @@ -146376,10 +146445,10 @@ type ModifyVerifiedAccessTrustProviderInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The OpenID Connect details for an oidc-type, user-identity based trust provider. + // The options for an OpenID Connect-compatible user-identity trust provider. OidcOptions *ModifyVerifiedAccessTrustProviderOidcOptions `type:"structure"` - // The ID of the Amazon Web Services Verified Access trust provider. + // The ID of the Verified Access trust provider. // // VerifiedAccessTrustProviderId is a required field VerifiedAccessTrustProviderId *string `type:"string" required:"true"` @@ -146446,14 +146515,36 @@ func (s *ModifyVerifiedAccessTrustProviderInput) SetVerifiedAccessTrustProviderI return s } -// OpenID Connect options for an oidc-type, user-identity based trust provider. +// Options for an OpenID Connect-compatible user-identity trust provider. type ModifyVerifiedAccessTrustProviderOidcOptions struct { _ struct{} `type:"structure"` + // The OIDC authorization endpoint. + AuthorizationEndpoint *string `type:"string"` + + // The client identifier. + ClientId *string `type:"string"` + + // The client secret. + // + // ClientSecret is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by ModifyVerifiedAccessTrustProviderOidcOptions's + // String and GoString methods. + ClientSecret *string `type:"string" sensitive:"true"` + + // The OIDC issuer. + Issuer *string `type:"string"` + // OpenID Connect (OIDC) scopes are used by an application during authentication // to authorize access to a user's details. Each scope returns a specific set // of user attributes. Scope *string `type:"string"` + + // The OIDC token endpoint. + TokenEndpoint *string `type:"string"` + + // The OIDC user info endpoint. + UserInfoEndpoint *string `type:"string"` } // String returns the string representation. @@ -146474,16 +146565,52 @@ func (s ModifyVerifiedAccessTrustProviderOidcOptions) GoString() string { return s.String() } +// SetAuthorizationEndpoint sets the AuthorizationEndpoint field's value. +func (s *ModifyVerifiedAccessTrustProviderOidcOptions) SetAuthorizationEndpoint(v string) *ModifyVerifiedAccessTrustProviderOidcOptions { + s.AuthorizationEndpoint = &v + return s +} + +// SetClientId sets the ClientId field's value. +func (s *ModifyVerifiedAccessTrustProviderOidcOptions) SetClientId(v string) *ModifyVerifiedAccessTrustProviderOidcOptions { + s.ClientId = &v + return s +} + +// SetClientSecret sets the ClientSecret field's value. +func (s *ModifyVerifiedAccessTrustProviderOidcOptions) SetClientSecret(v string) *ModifyVerifiedAccessTrustProviderOidcOptions { + s.ClientSecret = &v + return s +} + +// SetIssuer sets the Issuer field's value. +func (s *ModifyVerifiedAccessTrustProviderOidcOptions) SetIssuer(v string) *ModifyVerifiedAccessTrustProviderOidcOptions { + s.Issuer = &v + return s +} + // SetScope sets the Scope field's value. func (s *ModifyVerifiedAccessTrustProviderOidcOptions) SetScope(v string) *ModifyVerifiedAccessTrustProviderOidcOptions { s.Scope = &v return s } +// SetTokenEndpoint sets the TokenEndpoint field's value. +func (s *ModifyVerifiedAccessTrustProviderOidcOptions) SetTokenEndpoint(v string) *ModifyVerifiedAccessTrustProviderOidcOptions { + s.TokenEndpoint = &v + return s +} + +// SetUserInfoEndpoint sets the UserInfoEndpoint field's value. +func (s *ModifyVerifiedAccessTrustProviderOidcOptions) SetUserInfoEndpoint(v string) *ModifyVerifiedAccessTrustProviderOidcOptions { + s.UserInfoEndpoint = &v + return s +} + type ModifyVerifiedAccessTrustProviderOutput struct { _ struct{} `type:"structure"` - // The ID of the Amazon Web Services Verified Access trust provider. + // The ID of the Verified Access trust provider. VerifiedAccessTrustProvider *VerifiedAccessTrustProvider `locationName:"verifiedAccessTrustProvider" type:"structure"` } @@ -151149,7 +151276,8 @@ func (s *NewDhcpConfiguration) SetValues(v []*string) *NewDhcpConfiguration { return s } -// Options for OIDC-based, user-identity type trust provider. +// Describes the options for an OpenID Connect-compatible user-identity trust +// provider. type OidcOptions struct { _ struct{} `type:"structure"` @@ -151160,7 +151288,11 @@ type OidcOptions struct { ClientId *string `locationName:"clientId" type:"string"` // The client secret. - ClientSecret *string `locationName:"clientSecret" type:"string"` + // + // ClientSecret is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by OidcOptions's + // String and GoString methods. + ClientSecret *string `locationName:"clientSecret" type:"string" sensitive:"true"` // The OIDC issuer. Issuer *string `locationName:"issuer" type:"string"` @@ -152725,8 +152857,8 @@ type Placement struct { // Reserved for future use. SpreadDomain *string `locationName:"spreadDomain" type:"string"` - // The tenancy of the instance (if the instance is running in a VPC). An instance - // with a tenancy of dedicated runs on single-tenant hardware. + // The tenancy of the instance. An instance with a tenancy of dedicated runs + // on single-tenant hardware. // // This parameter is not supported for CreateFleet (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet). // The host tenancy is not supported for ImportInstance (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportInstance.html) @@ -153729,6 +153861,10 @@ type ProcessorInfo struct { // The architectures supported by the instance type. SupportedArchitectures []*string `locationName:"supportedArchitectures" locationNameList:"item" type:"list" enum:"ArchitectureType"` + // Indicates whether the instance type supports AMD SEV-SNP. If the request + // returns amd-sev-snp, AMD SEV-SNP is supported. Otherwise, it is not supported. + SupportedFeatures []*string `locationName:"supportedFeatures" locationNameList:"item" type:"list" enum:"SupportedAdditionalProcessorFeature"` + // The speed of the processor, in GHz. SustainedClockSpeedInGhz *float64 `locationName:"sustainedClockSpeedInGhz" type:"double"` } @@ -153757,6 +153893,12 @@ func (s *ProcessorInfo) SetSupportedArchitectures(v []*string) *ProcessorInfo { return s } +// SetSupportedFeatures sets the SupportedFeatures field's value. +func (s *ProcessorInfo) SetSupportedFeatures(v []*string) *ProcessorInfo { + s.SupportedFeatures = v + return s +} + // SetSustainedClockSpeedInGhz sets the SustainedClockSpeedInGhz field's value. func (s *ProcessorInfo) SetSustainedClockSpeedInGhz(v float64) *ProcessorInfo { s.SustainedClockSpeedInGhz = &v @@ -155631,7 +155773,9 @@ type RegisterInstanceEventNotificationAttributesInput struct { DryRun *bool `type:"boolean"` // Information about the tag keys to register. - InstanceTagAttribute *RegisterInstanceTagAttributeRequest `type:"structure"` + // + // InstanceTagAttribute is a required field + InstanceTagAttribute *RegisterInstanceTagAttributeRequest `type:"structure" required:"true"` } // String returns the string representation. @@ -155652,6 +155796,19 @@ func (s RegisterInstanceEventNotificationAttributesInput) GoString() string { return s.String() } +// Validate inspects the fields of the type to determine if they are valid. +func (s *RegisterInstanceEventNotificationAttributesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "RegisterInstanceEventNotificationAttributesInput"} + if s.InstanceTagAttribute == nil { + invalidParams.Add(request.NewErrParamRequired("InstanceTagAttribute")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + // SetDryRun sets the DryRun field's value. func (s *RegisterInstanceEventNotificationAttributesInput) SetDryRun(v bool) *RegisterInstanceEventNotificationAttributesInput { s.DryRun = &v @@ -158114,7 +158271,7 @@ func (s *RequestIpamResourceTag) SetValue(v string) *RequestIpamResourceTag { // // You must specify at least one parameter for the launch template data. type RequestLaunchTemplateData struct { - _ struct{} `type:"structure" sensitive:"true"` + _ struct{} `type:"structure"` // The block device mapping. BlockDeviceMappings []*LaunchTemplateBlockDeviceMappingRequest `locationName:"BlockDeviceMapping" locationNameList:"BlockDeviceMapping" type:"list"` @@ -158188,8 +158345,14 @@ type RequestLaunchTemplateData struct { // // * resolve:ssm:parameter-name:label // - // For more information, see Use a Systems Manager parameter to find an AMI - // (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html#using-systems-manager-parameter-to-find-AMI) + // * resolve:ssm:public-parameter + // + // Currently, EC2 Fleet and Spot Fleet do not support specifying a Systems Manager + // parameter. If the launch template will be used by an EC2 Fleet or Spot Fleet, + // you must specify the AMI ID. + // + // For more information, see Use a Systems Manager parameter instead of an AMI + // ID (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/create-launch-template.html#use-an-ssm-parameter-instead-of-an-ami-id) // in the Amazon Elastic Compute Cloud User Guide. ImageId *string `type:"string"` @@ -158301,7 +158464,11 @@ type RequestLaunchTemplateData struct { // must be provided in the MIME multi-part archive format (https://cloudinit.readthedocs.io/en/latest/topics/format.html#mime-multi-part-archive). // For more information, see Amazon EC2 user data in launch templates (https://docs.aws.amazon.com/batch/latest/userguide/launch-templates.html) // in the Batch User Guide. - UserData *string `type:"string"` + // + // UserData is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by RequestLaunchTemplateData's + // String and GoString methods. + UserData *string `type:"string" sensitive:"true"` } // String returns the string representation. @@ -158859,7 +159026,7 @@ func (s *RequestSpotInstancesInput) SetValidUntil(v time.Time) *RequestSpotInsta type RequestSpotInstancesOutput struct { _ struct{} `type:"structure"` - // One or more Spot Instance requests. + // The Spot Instance requests. SpotInstanceRequests []*SpotInstanceRequest `locationName:"spotInstanceRequestSet" locationNameList:"item" type:"list"` } @@ -158894,8 +159061,8 @@ type RequestSpotLaunchSpecification struct { // Deprecated. AddressingType *string `locationName:"addressingType" type:"string"` - // One or more block device mapping entries. You can't specify both a snapshot - // ID and an encryption value. This is because only blank volumes can be encrypted + // The block device mapping entries. You can't specify both a snapshot ID and + // an encryption value. This is because only blank volumes can be encrypted // on creation. If a snapshot is the basis for a volume, it is not blank and // its encryption status is used for the volume encryption status. BlockDeviceMappings []*BlockDeviceMapping `locationName:"blockDeviceMapping" locationNameList:"item" type:"list"` @@ -158929,8 +159096,8 @@ type RequestSpotLaunchSpecification struct { // Default: Disabled Monitoring *RunInstancesMonitoringEnabled `locationName:"monitoring" type:"structure"` - // One or more network interfaces. If you specify a network interface, you must - // specify subnet IDs and security group IDs using the network interface. + // The network interfaces. If you specify a network interface, you must specify + // subnet IDs and security group IDs using the network interface. NetworkInterfaces []*InstanceNetworkInterfaceSpecification `locationName:"NetworkInterface" locationNameList:"item" type:"list"` // The placement information for the instance. @@ -158939,12 +159106,10 @@ type RequestSpotLaunchSpecification struct { // The ID of the RAM disk. RamdiskId *string `locationName:"ramdiskId" type:"string"` - // One or more security group IDs. + // The IDs of the security groups. SecurityGroupIds []*string `locationName:"SecurityGroupId" locationNameList:"item" type:"list"` - // One or more security groups. When requesting instances in a VPC, you must - // specify the IDs of the security groups. When requesting instances in EC2-Classic, - // you can specify the names or the IDs of the security groups. + // Not supported. SecurityGroups []*string `locationName:"SecurityGroup" locationNameList:"item" type:"list"` // The ID of the subnet in which to launch the instance. @@ -159094,7 +159259,7 @@ func (s *RequestSpotLaunchSpecification) SetUserData(v string) *RequestSpotLaunc type Reservation struct { _ struct{} `type:"structure"` - // [EC2-Classic only] The security groups. + // Not supported. Groups []*GroupIdentifier `locationName:"groupSet" locationNameList:"item" type:"list"` // The instances. @@ -159614,8 +159779,7 @@ type ReservedInstancesConfiguration struct { // The instance type for the modified Reserved Instances. InstanceType *string `locationName:"instanceType" type:"string" enum:"InstanceType"` - // The network platform of the modified Reserved Instances, which is either - // EC2-Classic or EC2-VPC. + // The network platform of the modified Reserved Instances. Platform *string `locationName:"platform" type:"string"` // Whether the Reserved Instance is applied to instances in a Region or instances @@ -162977,9 +163141,9 @@ type RunInstancesInput struct { // Default: m1.small InstanceType *string `type:"string" enum:"InstanceType"` - // [EC2-VPC] The number of IPv6 addresses to associate with the primary network - // interface. Amazon EC2 chooses the IPv6 addresses from the range of your subnet. - // You cannot specify this option and the option to assign specific IPv6 addresses + // The number of IPv6 addresses to associate with the primary network interface. + // Amazon EC2 chooses the IPv6 addresses from the range of your subnet. You + // cannot specify this option and the option to assign specific IPv6 addresses // in the same request. You can specify this option if you've specified a minimum // number of instances to launch. // @@ -162987,10 +163151,10 @@ type RunInstancesInput struct { // request. Ipv6AddressCount *int64 `type:"integer"` - // [EC2-VPC] The IPv6 addresses from the range of the subnet to associate with - // the primary network interface. You cannot specify this option and the option - // to assign a number of IPv6 addresses in the same request. You cannot specify - // this option if you've specified a minimum number of instances to launch. + // The IPv6 addresses from the range of the subnet to associate with the primary + // network interface. You cannot specify this option and the option to assign + // a number of IPv6 addresses in the same request. You cannot specify this option + // if you've specified a minimum number of instances to launch. // // You cannot specify this option and the network interfaces option in the same // request. @@ -163064,8 +163228,8 @@ type RunInstancesInput struct { // the subnet. PrivateDnsNameOptions *PrivateDnsNameOptionsRequest `type:"structure"` - // [EC2-VPC] The primary IPv4 address. You must specify a value from the IPv4 - // address range of the subnet. + // The primary IPv4 address. You must specify a value from the IPv4 address + // range of the subnet. // // Only one private IP address can be designated as primary. You can't specify // this option if you've specified the option to designate a private IP address @@ -163093,7 +163257,7 @@ type RunInstancesInput struct { // as part of the network interface. SecurityGroupIds []*string `locationName:"SecurityGroupId" locationNameList:"SecurityGroupId" type:"list"` - // [EC2-Classic, default VPC] The names of the security groups. + // [Default VPC] The names of the security groups. // // If you specify a network interface, you must specify any security groups // as part of the network interface. @@ -163101,7 +163265,7 @@ type RunInstancesInput struct { // Default: Amazon EC2 uses the default security group. SecurityGroups []*string `locationName:"SecurityGroup" locationNameList:"SecurityGroup" type:"list"` - // [EC2-VPC] The ID of the subnet to launch the instance into. + // The ID of the subnet to launch the instance into. // // If you specify a network interface, you must specify any subnets as part // of the network interface. @@ -163769,7 +163933,7 @@ type ScheduledInstance struct { // The instance type. InstanceType *string `locationName:"instanceType" type:"string"` - // The network platform (EC2-Classic or EC2-VPC). + // The network platform. NetworkPlatform *string `locationName:"networkPlatform" type:"string"` // The time for the next schedule to start. @@ -163934,7 +164098,7 @@ type ScheduledInstanceAvailability struct { // The minimum term. The only possible value is 365 days. MinTermDurationInDays *int64 `locationName:"minTermDurationInDays" type:"integer"` - // The network platform (EC2-Classic or EC2-VPC). + // The network platform. NetworkPlatform *string `locationName:"networkPlatform" type:"string"` // The platform (Linux/UNIX or Windows). @@ -166628,7 +166792,11 @@ type SnapshotDetail struct { StatusMessage *string `locationName:"statusMessage" type:"string"` // The URL used to access the disk image. - Url *string `locationName:"url" type:"string"` + // + // Url is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by SnapshotDetail's + // String and GoString methods. + Url *string `locationName:"url" type:"string" sensitive:"true"` // The Amazon S3 bucket for the disk image. UserBucket *UserBucketDetails `locationName:"userBucket" type:"structure"` @@ -166726,7 +166894,11 @@ type SnapshotDiskContainer struct { // The URL to the Amazon S3-based disk image being imported. It can either be // a https URL (https://..) or an Amazon S3 URL (s3://..). - Url *string `type:"string"` + // + // Url is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by SnapshotDiskContainer's + // String and GoString methods. + Url *string `type:"string" sensitive:"true"` // The Amazon S3 bucket for the disk image. UserBucket *UserBucket `type:"structure"` @@ -167001,7 +167173,11 @@ type SnapshotTaskDetail struct { StatusMessage *string `locationName:"statusMessage" type:"string"` // The URL of the disk image from which the snapshot is created. - Url *string `locationName:"url" type:"string"` + // + // Url is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by SnapshotTaskDetail's + // String and GoString methods. + Url *string `locationName:"url" type:"string" sensitive:"true"` // The Amazon S3 bucket for the disk image. UserBucket *UserBucketDetails `locationName:"userBucket" type:"structure"` @@ -167423,9 +167599,7 @@ type SpotFleetLaunchSpecification struct { // Resource Center and search for the kernel ID. RamdiskId *string `locationName:"ramdiskId" type:"string"` - // One or more security groups. When requesting instances in a VPC, you must - // specify the IDs of the security groups. When requesting instances in EC2-Classic, - // you can specify the names or the IDs of the security groups. + // The security groups. SecurityGroups []*GroupIdentifier `locationName:"groupSet" locationNameList:"item" type:"list"` // The maximum price per unit hour that you are willing to pay for a Spot Instance. @@ -177806,7 +177980,7 @@ type VerifiedAccessTrustProvider struct { // A description for the Amazon Web Services Verified Access trust provider. Description *string `locationName:"description" type:"string"` - // The options for device-identity type trust provider. + // The options for device-identity trust provider. DeviceOptions *DeviceOptions `locationName:"deviceOptions" type:"structure"` // The type of device-based trust provider. @@ -177815,7 +177989,7 @@ type VerifiedAccessTrustProvider struct { // The last updated time. LastUpdatedTime *string `locationName:"lastUpdatedTime" type:"string"` - // The OpenID Connect details for an oidc-type, user-identity based trust provider. + // The options for an OpenID Connect-compatible user-identity trust provider. OidcOptions *OidcOptions `locationName:"oidcOptions" type:"structure"` // The identifier to be used when working with policy rules. @@ -181167,6 +181341,22 @@ func AllowsMultipleInstanceTypes_Values() []string { } } +const ( + // AmdSevSnpSpecificationEnabled is a AmdSevSnpSpecification enum value + AmdSevSnpSpecificationEnabled = "enabled" + + // AmdSevSnpSpecificationDisabled is a AmdSevSnpSpecification enum value + AmdSevSnpSpecificationDisabled = "disabled" +) + +// AmdSevSnpSpecification_Values returns all elements of the AmdSevSnpSpecification enum +func AmdSevSnpSpecification_Values() []string { + return []string{ + AmdSevSnpSpecificationEnabled, + AmdSevSnpSpecificationDisabled, + } +} + const ( // AnalysisStatusRunning is a AnalysisStatus enum value AnalysisStatusRunning = "running" @@ -185600,6 +185790,39 @@ const ( // InstanceTypeR6idnMetal is a InstanceType enum value InstanceTypeR6idnMetal = "r6idn.metal" + + // InstanceTypeInf2Xlarge is a InstanceType enum value + InstanceTypeInf2Xlarge = "inf2.xlarge" + + // InstanceTypeInf28xlarge is a InstanceType enum value + InstanceTypeInf28xlarge = "inf2.8xlarge" + + // InstanceTypeInf224xlarge is a InstanceType enum value + InstanceTypeInf224xlarge = "inf2.24xlarge" + + // InstanceTypeInf248xlarge is a InstanceType enum value + InstanceTypeInf248xlarge = "inf2.48xlarge" + + // InstanceTypeTrn1n32xlarge is a InstanceType enum value + InstanceTypeTrn1n32xlarge = "trn1n.32xlarge" + + // InstanceTypeI4gLarge is a InstanceType enum value + InstanceTypeI4gLarge = "i4g.large" + + // InstanceTypeI4gXlarge is a InstanceType enum value + InstanceTypeI4gXlarge = "i4g.xlarge" + + // InstanceTypeI4g2xlarge is a InstanceType enum value + InstanceTypeI4g2xlarge = "i4g.2xlarge" + + // InstanceTypeI4g4xlarge is a InstanceType enum value + InstanceTypeI4g4xlarge = "i4g.4xlarge" + + // InstanceTypeI4g8xlarge is a InstanceType enum value + InstanceTypeI4g8xlarge = "i4g.8xlarge" + + // InstanceTypeI4g16xlarge is a InstanceType enum value + InstanceTypeI4g16xlarge = "i4g.16xlarge" ) // InstanceType_Values returns all elements of the InstanceType enum @@ -186248,6 +186471,17 @@ func InstanceType_Values() []string { InstanceTypeM6idnMetal, InstanceTypeR6inMetal, InstanceTypeR6idnMetal, + InstanceTypeInf2Xlarge, + InstanceTypeInf28xlarge, + InstanceTypeInf224xlarge, + InstanceTypeInf248xlarge, + InstanceTypeTrn1n32xlarge, + InstanceTypeI4gLarge, + InstanceTypeI4gXlarge, + InstanceTypeI4g2xlarge, + InstanceTypeI4g4xlarge, + InstanceTypeI4g8xlarge, + InstanceTypeI4g16xlarge, } } @@ -189123,6 +189357,18 @@ func SummaryStatus_Values() []string { } } +const ( + // SupportedAdditionalProcessorFeatureAmdSevSnp is a SupportedAdditionalProcessorFeature enum value + SupportedAdditionalProcessorFeatureAmdSevSnp = "amd-sev-snp" +) + +// SupportedAdditionalProcessorFeature_Values returns all elements of the SupportedAdditionalProcessorFeature enum +func SupportedAdditionalProcessorFeature_Values() []string { + return []string{ + SupportedAdditionalProcessorFeatureAmdSevSnp, + } +} + const ( // TargetCapacityUnitTypeVcpu is a TargetCapacityUnitType enum value TargetCapacityUnitTypeVcpu = "vcpu" diff --git a/vendor/github.com/aws/aws-sdk-go/service/ec2/customizations.go b/vendor/github.com/aws/aws-sdk-go/service/ec2/customizations.go index 5b5395356fa..621712d29f0 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ec2/customizations.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ec2/customizations.go @@ -11,6 +11,9 @@ import ( ) const ( + // ec2CopySnapshotPresignedUrlCustomization handler name + ec2CopySnapshotPresignedUrlCustomization = "ec2CopySnapshotPresignedUrl" + // customRetryerMinRetryDelay sets min retry delay customRetryerMinRetryDelay = 1 * time.Second @@ -21,7 +24,10 @@ const ( func init() { initRequest = func(r *request.Request) { if r.Operation.Name == opCopySnapshot { // fill the PresignedURL parameter - r.Handlers.Build.PushFront(fillPresignedURL) + r.Handlers.Build.PushFrontNamed(request.NamedHandler{ + Name: ec2CopySnapshotPresignedUrlCustomization, + Fn: fillPresignedURL, + }) } // only set the retryer on request if config doesn't have a retryer @@ -48,13 +54,15 @@ func fillPresignedURL(r *request.Request) { origParams := r.Params.(*CopySnapshotInput) - // Stop if PresignedURL/DestinationRegion is set - if origParams.PresignedUrl != nil || origParams.DestinationRegion != nil { + // Stop if PresignedURL is set + if origParams.PresignedUrl != nil { return } + // Always use config region as destination region for SDKs origParams.DestinationRegion = r.Config.Region - newParams := awsutil.CopyOf(r.Params).(*CopySnapshotInput) + + newParams := awsutil.CopyOf(origParams).(*CopySnapshotInput) // Create a new request based on the existing request. We will use this to // presign the CopySnapshot request against the source region. @@ -82,8 +90,12 @@ func fillPresignedURL(r *request.Request) { clientInfo.Endpoint = resolved.URL clientInfo.SigningRegion = resolved.SigningRegion + // Copy handlers without Presigned URL customization to avoid an infinite loop + handlersWithoutPresignCustomization := r.Handlers.Copy() + handlersWithoutPresignCustomization.Build.RemoveByName(ec2CopySnapshotPresignedUrlCustomization) + // Presign a CopySnapshot request with modified params - req := request.New(*cfg, clientInfo, r.Handlers, r.Retryer, r.Operation, newParams, r.Data) + req := request.New(*cfg, clientInfo, handlersWithoutPresignCustomization, r.Retryer, r.Operation, newParams, r.Data) url, err := req.Presign(5 * time.Minute) // 5 minutes should be enough. if err != nil { // bubble error back up to original request r.Error = err diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/api.go b/vendor/github.com/aws/aws-sdk-go/service/sts/api.go index 63729d0a78b..7ac6b93f442 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/sts/api.go @@ -85,9 +85,9 @@ func (c *STS) AssumeRoleRequest(input *AssumeRoleInput) (req *request.Request, o // assumed. For more information, see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) // in the IAM User Guide. // -// When you create a role, you create two policies: A role trust policy that -// specifies who can assume the role and a permissions policy that specifies -// what can be done with the role. You specify the trusted principal who is +// When you create a role, you create two policies: a role trust policy that +// specifies who can assume the role, and a permissions policy that specifies +// what can be done with the role. You specify the trusted principal that is // allowed to assume the role in the role trust policy. // // To assume a role from a different account, your Amazon Web Services account @@ -96,9 +96,9 @@ func (c *STS) AssumeRoleRequest(input *AssumeRoleInput) (req *request.Request, o // are allowed to delegate that access to users in the account. // // A user who wants to access a role in a different account must also have permissions -// that are delegated from the user account administrator. The administrator -// must attach a policy that allows the user to call AssumeRole for the ARN -// of the role in the other account. +// that are delegated from the account administrator. The administrator must +// attach a policy that allows the user to call AssumeRole for the ARN of the +// role in the other account. // // To allow a user to assume a role in the same account, you can do either of // the following: @@ -517,10 +517,8 @@ func (c *STS) AssumeRoleWithWebIdentityRequest(input *AssumeRoleWithWebIdentityI // a user. You can also supply the user with a consistent identity throughout // the lifetime of an application. // -// To learn more about Amazon Cognito, see Amazon Cognito Overview (https://docs.aws.amazon.com/mobile/sdkforandroid/developerguide/cognito-auth.html#d0e840) -// in Amazon Web Services SDK for Android Developer Guide and Amazon Cognito -// Overview (https://docs.aws.amazon.com/mobile/sdkforios/developerguide/cognito-auth.html#d0e664) -// in the Amazon Web Services SDK for iOS Developer Guide. +// To learn more about Amazon Cognito, see Amazon Cognito identity pools (https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity.html) +// in Amazon Cognito Developer Guide. // // Calling AssumeRoleWithWebIdentity does not require the use of Amazon Web // Services security credentials. Therefore, you can distribute an application @@ -984,11 +982,11 @@ func (c *STS) GetCallerIdentityRequest(input *GetCallerIdentityInput) (req *requ // call the operation. // // No permissions are required to perform this operation. If an administrator -// adds a policy to your IAM user or role that explicitly denies access to the -// sts:GetCallerIdentity action, you can still perform this operation. Permissions -// are not required because the same information is returned when an IAM user -// or role is denied access. To view an example response, see I Am Not Authorized -// to Perform: iam:DeleteVirtualMFADevice (https://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot_general.html#troubleshoot_general_access-denied-delete-mfa) +// attaches a policy to your identity that explicitly denies access to the sts:GetCallerIdentity +// action, you can still perform this operation. Permissions are not required +// because the same information is returned when access is denied. To view an +// example response, see I Am Not Authorized to Perform: iam:DeleteVirtualMFADevice +// (https://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot_general.html#troubleshoot_general_access-denied-delete-mfa) // in the IAM User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -1063,18 +1061,26 @@ func (c *STS) GetFederationTokenRequest(input *GetFederationTokenInput) (req *re // GetFederationToken API operation for AWS Security Token Service. // // Returns a set of temporary security credentials (consisting of an access -// key ID, a secret access key, and a security token) for a federated user. -// A typical use is in a proxy application that gets temporary security credentials -// on behalf of distributed applications inside a corporate network. You must -// call the GetFederationToken operation using the long-term security credentials -// of an IAM user. As a result, this call is appropriate in contexts where those -// credentials can be safely stored, usually in a server-based application. +// key ID, a secret access key, and a security token) for a user. A typical +// use is in a proxy application that gets temporary security credentials on +// behalf of distributed applications inside a corporate network. +// +// You must call the GetFederationToken operation using the long-term security +// credentials of an IAM user. As a result, this call is appropriate in contexts +// where those credentials can be safeguarded, usually in a server-based application. // For a comparison of GetFederationToken with the other API operations that // produce temporary credentials, see Requesting Temporary Security Credentials // (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) // and Comparing the Amazon Web Services STS API operations (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) // in the IAM User Guide. // +// Although it is possible to call GetFederationToken using the security credentials +// of an Amazon Web Services account root user rather than an IAM user that +// you create for the purpose of a proxy application, we do not recommend it. +// For more information, see Safeguard your root user credentials and don't +// use them for everyday tasks (https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#lock-away-credentials) +// in the IAM User Guide. +// // You can create a mobile-based or browser-based app that can authenticate // users using a web identity provider like Login with Amazon, Facebook, Google, // or an OpenID Connect-compatible identity provider. In this case, we recommend @@ -1083,21 +1089,13 @@ func (c *STS) GetFederationTokenRequest(input *GetFederationTokenInput) (req *re // (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_assumerolewithwebidentity) // in the IAM User Guide. // -// You can also call GetFederationToken using the security credentials of an -// Amazon Web Services account root user, but we do not recommend it. Instead, -// we recommend that you create an IAM user for the purpose of the proxy application. -// Then attach a policy to the IAM user that limits federated users to only -// the actions and resources that they need to access. For more information, -// see IAM Best Practices (https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) -// in the IAM User Guide. -// // # Session duration // // The temporary credentials are valid for the specified duration, from 900 // seconds (15 minutes) up to a maximum of 129,600 seconds (36 hours). The default // session duration is 43,200 seconds (12 hours). Temporary credentials obtained -// by using the Amazon Web Services account root user credentials have a maximum -// duration of 3,600 seconds (1 hour). +// by using the root user credentials have a maximum duration of 3,600 seconds +// (1 hour). // // # Permissions // @@ -1267,12 +1265,13 @@ func (c *STS) GetSessionTokenRequest(input *GetSessionTokenInput) (req *request. // or IAM user. The credentials consist of an access key ID, a secret access // key, and a security token. Typically, you use GetSessionToken if you want // to use MFA to protect programmatic calls to specific Amazon Web Services -// API operations like Amazon EC2 StopInstances. MFA-enabled IAM users would -// need to call GetSessionToken and submit an MFA code that is associated with -// their MFA device. Using the temporary security credentials that are returned -// from the call, IAM users can then make programmatic calls to API operations -// that require MFA authentication. If you do not supply a correct MFA code, -// then the API returns an access denied error. For a comparison of GetSessionToken +// API operations like Amazon EC2 StopInstances. +// +// MFA-enabled IAM users must call GetSessionToken and submit an MFA code that +// is associated with their MFA device. Using the temporary security credentials +// that the call returns, IAM users can then make programmatic calls to API +// operations that require MFA authentication. An incorrect MFA code causes +// the API to return an access denied error. For a comparison of GetSessionToken // with the other API operations that produce temporary credentials, see Requesting // Temporary Security Credentials (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) // and Comparing the Amazon Web Services STS API operations (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) @@ -1287,13 +1286,12 @@ func (c *STS) GetSessionTokenRequest(input *GetSessionTokenInput) (req *request. // # Session Duration // // The GetSessionToken operation must be called by using the long-term Amazon -// Web Services security credentials of the Amazon Web Services account root -// user or an IAM user. Credentials that are created by IAM users are valid -// for the duration that you specify. This duration can range from 900 seconds -// (15 minutes) up to a maximum of 129,600 seconds (36 hours), with a default -// of 43,200 seconds (12 hours). Credentials based on account credentials can -// range from 900 seconds (15 minutes) up to 3,600 seconds (1 hour), with a -// default of 1 hour. +// Web Services security credentials of an IAM user. Credentials that are created +// by IAM users are valid for the duration that you specify. This duration can +// range from 900 seconds (15 minutes) up to a maximum of 129,600 seconds (36 +// hours), with a default of 43,200 seconds (12 hours). Credentials based on +// account credentials can range from 900 seconds (15 minutes) up to 3,600 seconds +// (1 hour), with a default of 1 hour. // // # Permissions // @@ -1305,20 +1303,20 @@ func (c *STS) GetSessionTokenRequest(input *GetSessionTokenInput) (req *request. // // - You cannot call any STS API except AssumeRole or GetCallerIdentity. // -// We recommend that you do not call GetSessionToken with Amazon Web Services -// account root user credentials. Instead, follow our best practices (https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#create-iam-users) -// by creating one or more IAM users, giving them the necessary permissions, -// and using IAM users for everyday interaction with Amazon Web Services. +// The credentials that GetSessionToken returns are based on permissions associated +// with the IAM user whose credentials were used to call the operation. The +// temporary credentials have the same permissions as the IAM user. // -// The credentials that are returned by GetSessionToken are based on permissions -// associated with the user whose credentials were used to call the operation. -// If GetSessionToken is called using Amazon Web Services account root user -// credentials, the temporary credentials have root user permissions. Similarly, -// if GetSessionToken is called using the credentials of an IAM user, the temporary -// credentials have the same permissions as the IAM user. +// Although it is possible to call GetSessionToken using the security credentials +// of an Amazon Web Services account root user rather than an IAM user, we do +// not recommend it. If GetSessionToken is called using root user credentials, +// the temporary credentials have root user permissions. For more information, +// see Safeguard your root user credentials and don't use them for everyday +// tasks (https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#lock-away-credentials) +// in the IAM User Guide // // For more information about using GetSessionToken to create temporary credentials, -// go to Temporary Credentials for Users in Untrusted Environments (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_getsessiontoken) +// see Temporary Credentials for Users in Untrusted Environments (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_getsessiontoken) // in the IAM User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -1900,8 +1898,12 @@ type AssumeRoleWithSAMLInput struct { // For more information, see Configuring a Relying Party and Adding Claims (https://docs.aws.amazon.com/IAM/latest/UserGuide/create-role-saml-IdP-tasks.html) // in the IAM User Guide. // + // SAMLAssertion is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by AssumeRoleWithSAMLInput's + // String and GoString methods. + // // SAMLAssertion is a required field - SAMLAssertion *string `min:"4" type:"string" required:"true"` + SAMLAssertion *string `min:"4" type:"string" required:"true" sensitive:"true"` } // String returns the string representation. @@ -2036,7 +2038,7 @@ type AssumeRoleWithSAMLOutput struct { // IAM. // // The combination of NameQualifier and Subject can be used to uniquely identify - // a federated user. + // a user. // // The following pseudocode shows how the hash value is calculated: // @@ -2266,8 +2268,12 @@ type AssumeRoleWithWebIdentityInput struct { // the user who is using your application with a web identity provider before // the application makes an AssumeRoleWithWebIdentity call. // + // WebIdentityToken is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by AssumeRoleWithWebIdentityInput's + // String and GoString methods. + // // WebIdentityToken is a required field - WebIdentityToken *string `min:"4" type:"string" required:"true"` + WebIdentityToken *string `min:"4" type:"string" required:"true" sensitive:"true"` } // String returns the string representation. @@ -2573,8 +2579,12 @@ type Credentials struct { // The secret access key that can be used to sign requests. // + // SecretAccessKey is a sensitive parameter and its value will be + // replaced with "sensitive" in string returned by Credentials's + // String and GoString methods. + // // SecretAccessKey is a required field - SecretAccessKey *string `type:"string" required:"true"` + SecretAccessKey *string `type:"string" required:"true" sensitive:"true"` // The token that users must pass to the service API to use the temporary credentials. // @@ -2922,10 +2932,9 @@ type GetFederationTokenInput struct { // The duration, in seconds, that the session should last. Acceptable durations // for federation sessions range from 900 seconds (15 minutes) to 129,600 seconds // (36 hours), with 43,200 seconds (12 hours) as the default. Sessions obtained - // using Amazon Web Services account root user credentials are restricted to - // a maximum of 3,600 seconds (one hour). If the specified duration is longer - // than one hour, the session obtained by using root user credentials defaults - // to one hour. + // using root user credentials are restricted to a maximum of 3,600 seconds + // (one hour). If the specified duration is longer than one hour, the session + // obtained by using root user credentials defaults to one hour. DurationSeconds *int64 `min:"900" type:"integer"` // The name of the federated user. The name is used as an identifier for the diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/doc.go b/vendor/github.com/aws/aws-sdk-go/service/sts/doc.go index c40f5a2a52b..ea1d9eb0ccf 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/doc.go +++ b/vendor/github.com/aws/aws-sdk-go/service/sts/doc.go @@ -4,10 +4,9 @@ // requests to AWS Security Token Service. // // Security Token Service (STS) enables you to request temporary, limited-privilege -// credentials for Identity and Access Management (IAM) users or for users that -// you authenticate (federated users). This guide provides descriptions of the -// STS API. For more information about using this service, see Temporary Security -// Credentials (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html). +// credentials for users. This guide provides descriptions of the STS API. For +// more information about using this service, see Temporary Security Credentials +// (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html). // // See https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15 for more information on this service. // diff --git a/vendor/github.com/digitalocean/godo/CHANGELOG.md b/vendor/github.com/digitalocean/godo/CHANGELOG.md index 7233c389b06..9c1849b2c08 100644 --- a/vendor/github.com/digitalocean/godo/CHANGELOG.md +++ b/vendor/github.com/digitalocean/godo/CHANGELOG.md @@ -1,5 +1,12 @@ # Change Log +## [v1.99.0] - 2023-04-24 + +- #616 - @bentranter - Bump CI version for Go 1.20 +- #615 - @bentranter - Remove beta support for tokens API +- #604 - @dvigueras - Add support for "Validate a Container Registry Name" +- #613 - @ibilalkayy - updated the README file by showing up the build status icon + ## [v1.98.0] - 2023-03-09 - #608 - @anitgandhi - client: don't process body upon 204 response diff --git a/vendor/github.com/digitalocean/godo/README.md b/vendor/github.com/digitalocean/godo/README.md index 9a3ec2dad2c..4c9ee2d78f5 100644 --- a/vendor/github.com/digitalocean/godo/README.md +++ b/vendor/github.com/digitalocean/godo/README.md @@ -1,6 +1,6 @@ # Godo -[![Build Status](https://travis-ci.org/digitalocean/godo.svg)](https://travis-ci.org/digitalocean/godo) +[![GitHub Actions CI](https://github.com/digitalocean/godo/actions/workflows/ci.yml/badge.svg)](https://github.com/digitalocean/godo/actions/workflows/ci.yml) [![GoDoc](https://godoc.org/github.com/digitalocean/godo?status.svg)](https://godoc.org/github.com/digitalocean/godo) Godo is a Go client library for accessing the DigitalOcean V2 API. diff --git a/vendor/github.com/digitalocean/godo/godo.go b/vendor/github.com/digitalocean/godo/godo.go index 14fac268c3c..c48a5f788af 100644 --- a/vendor/github.com/digitalocean/godo/godo.go +++ b/vendor/github.com/digitalocean/godo/godo.go @@ -21,7 +21,7 @@ import ( ) const ( - libraryVersion = "1.98.0" + libraryVersion = "1.99.0" defaultBaseURL = "https://api.digitalocean.com/" userAgent = "godo/" + libraryVersion mediaType = "application/json" @@ -81,7 +81,6 @@ type Client struct { Storage StorageService StorageActions StorageActionsService Tags TagsService - Tokens TokensService UptimeChecks UptimeChecksService VPCs VPCsService @@ -252,7 +251,6 @@ func NewClient(httpClient *http.Client) *Client { c.Storage = &StorageServiceOp{client: c} c.StorageActions = &StorageActionsServiceOp{client: c} c.Tags = &TagsServiceOp{client: c} - c.Tokens = &TokensServiceOp{client: c} c.UptimeChecks = &UptimeChecksServiceOp{client: c} c.VPCs = &VPCsServiceOp{client: c} diff --git a/vendor/github.com/digitalocean/godo/registry.go b/vendor/github.com/digitalocean/godo/registry.go index 2fe9d2bd9fa..b0c24328180 100644 --- a/vendor/github.com/digitalocean/godo/registry.go +++ b/vendor/github.com/digitalocean/godo/registry.go @@ -37,6 +37,7 @@ type RegistryService interface { GetOptions(context.Context) (*RegistryOptions, *Response, error) GetSubscription(context.Context) (*RegistrySubscription, *Response, error) UpdateSubscription(context.Context, *RegistrySubscriptionUpdateRequest) (*RegistrySubscription, *Response, error) + ValidateName(context.Context, *RegistryValidateNameRequest) (*Response, error) } var _ RegistryService = &RegistryServiceOp{} @@ -233,6 +234,12 @@ type RegistrySubscriptionUpdateRequest struct { TierSlug string `json:"tier_slug"` } +// RegistryValidateNameRequest represents a request to validate that a +// container registry name is available for use. +type RegistryValidateNameRequest struct { + Name string `json:"name"` +} + // Get retrieves the details of a Registry. func (svc *RegistryServiceOp) Get(ctx context.Context) (*Registry, *Response, error) { req, err := svc.client.NewRequest(ctx, http.MethodGet, registryPath, nil) @@ -589,3 +596,17 @@ func (svc *RegistryServiceOp) UpdateSubscription(ctx context.Context, request *R } return root.Subscription, resp, nil } + +// ValidateName validates that a container registry name is available for use. +func (svc *RegistryServiceOp) ValidateName(ctx context.Context, request *RegistryValidateNameRequest) (*Response, error) { + path := fmt.Sprintf("%s/validate-name", registryPath) + req, err := svc.client.NewRequest(ctx, http.MethodPost, path, request) + if err != nil { + return nil, err + } + resp, err := svc.client.Do(ctx, req, nil) + if err != nil { + return resp, err + } + return resp, nil +} diff --git a/vendor/github.com/digitalocean/godo/tokens.go b/vendor/github.com/digitalocean/godo/tokens.go deleted file mode 100644 index 13aa418dff1..00000000000 --- a/vendor/github.com/digitalocean/godo/tokens.go +++ /dev/null @@ -1,228 +0,0 @@ -package godo - -import ( - "context" - "fmt" - "net/http" - "time" -) - -const ( - accessTokensBasePath = "v2/tokens" - tokenScopesBasePath = accessTokensBasePath + "/scopes" -) - -// TokensService is an interface for managing DigitalOcean API access tokens. -// It is not currently generally available. Follow the release notes for -// updates: https://docs.digitalocean.com/release-notes/api/ -type TokensService interface { - List(context.Context, *ListOptions) ([]Token, *Response, error) - Get(context.Context, int) (*Token, *Response, error) - Create(context.Context, *TokenCreateRequest) (*Token, *Response, error) - Update(context.Context, int, *TokenUpdateRequest) (*Token, *Response, error) - Revoke(context.Context, int) (*Response, error) - ListScopes(context.Context, *ListOptions) ([]TokenScope, *Response, error) - ListScopesByNamespace(context.Context, string, *ListOptions) ([]TokenScope, *Response, error) -} - -// TokensServiceOp handles communication with the tokens related methods of the -// DigitalOcean API. -type TokensServiceOp struct { - client *Client -} - -var _ TokensService = &TokensServiceOp{} - -// Token represents a DigitalOcean API token. -type Token struct { - ID int `json:"id"` - Name string `json:"name"` - Scopes []string `json:"scopes"` - ExpirySeconds *int `json:"expiry_seconds"` - CreatedAt time.Time `json:"created_at"` - LastUsedAt string `json:"last_used_at"` - - // AccessToken contains the actual Oauth token string. It is only included - // in the create response. - AccessToken string `json:"access_token,omitempty"` -} - -// tokenRoot represents a response from the DigitalOcean API -type tokenRoot struct { - Token *Token `json:"token"` -} - -type tokensRoot struct { - Tokens []Token `json:"tokens"` - Links *Links `json:"links"` - Meta *Meta `json:"meta"` -} - -// TokenCreateRequest represents a request to create a token. -type TokenCreateRequest struct { - Name string `json:"name"` - Scopes []string `json:"scopes"` - ExpirySeconds *int `json:"expiry_seconds,omitempty"` -} - -// TokenUpdateRequest represents a request to update a token. -type TokenUpdateRequest struct { - Name string `json:"name,omitempty"` - Scopes []string `json:"scopes,omitempty"` -} - -// TokenScope is a representation of a scope for the public API. -type TokenScope struct { - Name string `json:"name"` -} - -type tokenScopesRoot struct { - TokenScopes []TokenScope `json:"scopes"` - Links *Links `json:"links"` - Meta *Meta `json:"meta"` -} - -type tokenScopeNamespaceParam struct { - Namespace string `url:"namespace,omitempty"` -} - -// List all DigitalOcean API access tokens. -func (c TokensServiceOp) List(ctx context.Context, opt *ListOptions) ([]Token, *Response, error) { - path, err := addOptions(accessTokensBasePath, opt) - if err != nil { - return nil, nil, err - } - - req, err := c.client.NewRequest(ctx, http.MethodGet, path, nil) - if err != nil { - return nil, nil, err - } - - root := new(tokensRoot) - resp, err := c.client.Do(ctx, req, root) - if err != nil { - return nil, resp, err - } - if l := root.Links; l != nil { - resp.Links = l - } - if m := root.Meta; m != nil { - resp.Meta = m - } - - return root.Tokens, resp, err -} - -// Get a specific DigitalOcean API access token. -func (c TokensServiceOp) Get(ctx context.Context, tokenID int) (*Token, *Response, error) { - path := fmt.Sprintf("%s/%d", accessTokensBasePath, tokenID) - req, err := c.client.NewRequest(ctx, http.MethodGet, path, nil) - if err != nil { - return nil, nil, err - } - - root := new(tokenRoot) - resp, err := c.client.Do(ctx, req, root) - if err != nil { - return nil, resp, err - } - - return root.Token, resp, err -} - -// Create a new DigitalOcean API access token. -func (c TokensServiceOp) Create(ctx context.Context, createRequest *TokenCreateRequest) (*Token, *Response, error) { - req, err := c.client.NewRequest(ctx, http.MethodPost, accessTokensBasePath, createRequest) - if err != nil { - return nil, nil, err - } - - root := new(tokenRoot) - resp, err := c.client.Do(ctx, req, root) - if err != nil { - return nil, resp, err - } - - return root.Token, resp, err -} - -// Update the name or scopes of a specific DigitalOcean API access token. -func (c TokensServiceOp) Update(ctx context.Context, tokenID int, updateRequest *TokenUpdateRequest) (*Token, *Response, error) { - path := fmt.Sprintf("%s/%d", accessTokensBasePath, tokenID) - req, err := c.client.NewRequest(ctx, http.MethodPatch, path, updateRequest) - if err != nil { - return nil, nil, err - } - - root := new(tokenRoot) - resp, err := c.client.Do(ctx, req, root) - if err != nil { - return nil, resp, err - } - - return root.Token, resp, err -} - -// Revoke a specific DigitalOcean API access token. -func (c TokensServiceOp) Revoke(ctx context.Context, tokenID int) (*Response, error) { - path := fmt.Sprintf("%s/%d", accessTokensBasePath, tokenID) - req, err := c.client.NewRequest(ctx, http.MethodDelete, path, nil) - if err != nil { - return nil, err - } - - resp, err := c.client.Do(ctx, req, nil) - - return resp, err -} - -// ListScopes lists all available scopes that can be granted to a token. -func (c TokensServiceOp) ListScopes(ctx context.Context, opt *ListOptions) ([]TokenScope, *Response, error) { - path, err := addOptions(tokenScopesBasePath, opt) - if err != nil { - return nil, nil, err - } - - return listTokenScopes(ctx, c, path) -} - -// ListScopesByNamespace lists available scopes in a namespace that can be granted -// to a token (e.g. the namespace for the `droplet:read“ scope is `droplet`). -func (c TokensServiceOp) ListScopesByNamespace(ctx context.Context, namespace string, opt *ListOptions) ([]TokenScope, *Response, error) { - path, err := addOptions(tokenScopesBasePath, opt) - if err != nil { - return nil, nil, err - } - - namespaceOpt := tokenScopeNamespaceParam{ - Namespace: namespace, - } - - path, err = addOptions(path, namespaceOpt) - if err != nil { - return nil, nil, err - } - - return listTokenScopes(ctx, c, path) -} - -func listTokenScopes(ctx context.Context, c TokensServiceOp, path string) ([]TokenScope, *Response, error) { - req, err := c.client.NewRequest(ctx, http.MethodGet, path, nil) - if err != nil { - return nil, nil, err - } - - root := new(tokenScopesRoot) - resp, err := c.client.Do(ctx, req, root) - if err != nil { - return nil, resp, err - } - if l := root.Links; l != nil { - resp.Links = l - } - if m := root.Meta; m != nil { - resp.Meta = m - } - - return root.TokenScopes, resp, err -} diff --git a/vendor/github.com/docker/docker/AUTHORS b/vendor/github.com/docker/docker/AUTHORS index 0728bfe18f3..b3141819258 100644 --- a/vendor/github.com/docker/docker/AUTHORS +++ b/vendor/github.com/docker/docker/AUTHORS @@ -29,6 +29,7 @@ Adam Pointer Adam Singer Adam Walz Adam Williams +AdamKorcz Addam Hardy Aditi Rajagopal Aditya @@ -81,6 +82,7 @@ Alex Goodman Alex Nordlund Alex Olshansky Alex Samorukov +Alex Stockinger Alex Warhawk Alexander Artemenko Alexander Boyd @@ -198,6 +200,7 @@ Anusha Ragunathan Anyu Wang apocas Arash Deshmeh +arcosx ArikaChen Arko Dasgupta Arnaud Lefebvre @@ -241,6 +244,7 @@ Benjamin Atkin Benjamin Baker Benjamin Boudreau Benjamin Böhmke +Benjamin Wang Benjamin Yolken Benny Ng Benoit Chesneau @@ -634,6 +638,7 @@ Eng Zer Jun Enguerran Eohyung Lee epeterso +er0k Eric Barch Eric Curtin Eric G. Noriega @@ -754,6 +759,7 @@ Félix Baylac-Jacqué Félix Cantournet Gabe Rosenhouse Gabor Nagy +Gabriel Adrian Samfira Gabriel Goller Gabriel L. Somlo Gabriel Linder @@ -855,6 +861,7 @@ Hongbin Lu Hongxu Jia Honza Pokorny Hsing-Hui Hsu +Hsing-Yu (David) Chen hsinko <21551195@zju.edu.cn> Hu Keping Hu Tao @@ -887,6 +894,7 @@ Igor Dolzhikov Igor Karpovich Iliana Weller Ilkka Laukkanen +Illia Antypenko Illo Abdulrahim Ilya Dmitrichenko Ilya Gusev @@ -938,6 +946,7 @@ Jamie Hannaford Jamshid Afshar Jan Breig Jan Chren +Jan Garcia Jan Götte Jan Keromnes Jan Koprowski @@ -1206,6 +1215,7 @@ Kimbro Staken Kir Kolyshkin Kiran Gangadharan Kirill SIbirev +Kirk Easterson knappe Kohei Tsuruta Koichi Shiraishi @@ -1240,10 +1250,12 @@ Lars Kellogg-Stedman Lars R. Damerow Lars-Magnus Skog Laszlo Meszaros +Laura Brehm Laura Frank Laurent Bernaille Laurent Erignoux Laurie Voss +Leandro Motta Barros Leandro Siqueira Lee Calcote Lee Chao <932819864@qq.com> @@ -1563,6 +1575,7 @@ Nick Neisen Nick Parker Nick Payne Nick Russo +Nick Santos Nick Stenning Nick Stinemates Nick Wood @@ -1584,6 +1597,7 @@ NikolaMandic Nikolas Garofil Nikolay Edigaryev Nikolay Milovanov +ningmingxiao Nirmal Mehta Nishant Totla NIWA Hideyuki @@ -1615,6 +1629,7 @@ Omri Shiv Onur Filiz Oriol Francès Oscar Bonilla <6f6231@gmail.com> +oscar.chen <2972789494@qq.com> Oskar Niburski Otto Kekäläinen Ouyang Liduo @@ -1822,6 +1837,7 @@ Rory Hunter Rory McCune Ross Boucher Rovanion Luckey +Roy Reznik Royce Remer Rozhnov Alexandr Rudolph Gottesheim @@ -2271,6 +2287,7 @@ Xiaoyu Zhang xichengliudui <1693291525@qq.com> xiekeyang Ximo Guanter Gonzálbez +xin.li Xinbo Weng Xinfeng Liu Xinzi Zhou @@ -2282,6 +2299,7 @@ Yahya yalpul YAMADA Tsuyoshi Yamasaki Masahide +Yamazaki Masashi Yan Feng Yan Zhu Yang Bai diff --git a/vendor/github.com/docker/docker/api/common.go b/vendor/github.com/docker/docker/api/common.go index bee9b875a88..cba66bc462b 100644 --- a/vendor/github.com/docker/docker/api/common.go +++ b/vendor/github.com/docker/docker/api/common.go @@ -3,7 +3,7 @@ package api // import "github.com/docker/docker/api" // Common constants for daemon and client. const ( // DefaultVersion of Current REST API - DefaultVersion = "1.42" + DefaultVersion = "1.43" // NoBaseImageSpecifier is the symbol used by the FROM // command to specify that no base image is to be used. diff --git a/vendor/github.com/docker/docker/api/swagger.yaml b/vendor/github.com/docker/docker/api/swagger.yaml index afe7a8c371b..c2943888d75 100644 --- a/vendor/github.com/docker/docker/api/swagger.yaml +++ b/vendor/github.com/docker/docker/api/swagger.yaml @@ -19,10 +19,10 @@ produces: consumes: - "application/json" - "text/plain" -basePath: "/v1.42" +basePath: "/v1.43" info: title: "Docker Engine API" - version: "1.42" + version: "1.43" x-logo: url: "https://docs.docker.com/assets/images/logo-docker-main.png" description: | @@ -55,8 +55,8 @@ info: the URL is not supported by the daemon, a HTTP `400 Bad Request` error message is returned. - If you omit the version-prefix, the current version of the API (v1.42) is used. - For example, calling `/info` is the same as calling `/v1.42/info`. Using the + If you omit the version-prefix, the current version of the API (v1.43) is used. + For example, calling `/info` is the same as calling `/v1.43/info`. Using the API without a version-prefix is deprecated and will be removed in a future release. Engine releases in the near future should support this version of the API, @@ -976,6 +976,13 @@ definitions: items: type: "integer" minimum: 0 + Annotations: + type: "object" + description: | + Arbitrary non-identifying metadata attached to container and + provided to the runtime when the container is started. + additionalProperties: + type: "string" # Applicable to UNIX platforms CapAdd: @@ -1122,6 +1129,7 @@ definitions: remapping option is enabled. ShmSize: type: "integer" + format: "int64" description: | Size of `/dev/shm` in bytes. If omitted, the system uses 64MB. minimum: 0 @@ -1610,6 +1618,34 @@ definitions: "WorkDir": "/var/lib/docker/overlay2/ef749362d13333e65fc95c572eb525abbe0052e16e086cb64bc3b98ae9aa6d74/work" } + FilesystemChange: + description: | + Change in the container's filesystem. + type: "object" + required: [Path, Kind] + properties: + Path: + description: | + Path to file or directory that has changed. + type: "string" + x-nullable: false + Kind: + $ref: "#/definitions/ChangeType" + + ChangeType: + description: | + Kind of change + + Can be one of: + + - `0`: Modified ("C") + - `1`: Added ("A") + - `2`: Deleted ("D") + type: "integer" + format: "uint8" + enum: [0, 1, 2] + x-nullable: false + ImageInspect: description: | Information about an image in the local image cache. @@ -1746,15 +1782,14 @@ definitions: Total size of the image including all layers it is composed of. In versions of Docker before v1.10, this field was calculated from - the image itself and all of its parent images. Docker v1.10 and up - store images self-contained, and no longer use a parent-chain, making - this field an equivalent of the Size field. + the image itself and all of its parent images. Images are now stored + self-contained, and no longer use a parent-chain, making this field + an equivalent of the Size field. - This field is kept for backward compatibility, but may be removed in - a future version of the API. + > **Deprecated**: this field is kept for backward compatibility, but + > will be removed in API v1.44. type: "integer" format: "int64" - x-nullable: false example: 1239828 GraphDriver: $ref: "#/definitions/GraphDriverData" @@ -1802,7 +1837,6 @@ definitions: - Created - Size - SharedSize - - VirtualSize - Labels - Containers properties: @@ -1888,19 +1922,17 @@ definitions: x-nullable: false example: 1239828 VirtualSize: - description: | + description: |- Total size of the image including all layers it is composed of. In versions of Docker before v1.10, this field was calculated from - the image itself and all of its parent images. Docker v1.10 and up - store images self-contained, and no longer use a parent-chain, making - this field an equivalent of the Size field. + the image itself and all of its parent images. Images are now stored + self-contained, and no longer use a parent-chain, making this field + an equivalent of the Size field. - This field is kept for backward compatibility, but may be removed in - a future version of the API. + Deprecated: this field is kept for backward compatibility, and will be removed in API v1.44. type: "integer" format: "int64" - x-nullable: false example: 172064416 Labels: description: "User-defined key/value metadata." @@ -4652,7 +4684,8 @@ definitions: example: false OOMKilled: description: | - Whether this container has been killed because it ran out of memory. + Whether a process within this container has been killed because it ran + out of memory since the container was last started. type: "boolean" example: false Dead: @@ -5242,7 +5275,8 @@ definitions: SecurityOptions: description: | List of security features that are enabled on the daemon, such as - apparmor, seccomp, SELinux, user-namespaces (userns), and rootless. + apparmor, seccomp, SELinux, user-namespaces (userns), rootless and + no-new-privileges. Additional configuration options for each security feature may be present, and are included as a comma-separated list of key/value @@ -6875,9 +6909,9 @@ paths: Returns which files in a container's filesystem have been added, deleted, or modified. The `Kind` of modification can be one of: - - `0`: Modified - - `1`: Added - - `2`: Deleted + - `0`: Modified ("C") + - `1`: Added ("A") + - `2`: Deleted ("D") operationId: "ContainerChanges" produces: ["application/json"] responses: @@ -6886,22 +6920,7 @@ paths: schema: type: "array" items: - type: "object" - x-go-name: "ContainerChangeResponseItem" - title: "ContainerChangeResponseItem" - description: "change item in response to ContainerChanges operation" - required: [Path, Kind] - properties: - Path: - description: "Path to file that has changed" - type: "string" - x-nullable: false - Kind: - description: "Kind of change" - type: "integer" - format: "uint8" - enum: [0, 1, 2] - x-nullable: false + $ref: "#/definitions/FilesystemChange" examples: application/json: - Path: "/dev" @@ -8228,7 +8247,7 @@ paths: Available filters: - - `until=`: duration relative to daemon's time, during which build cache was not used, in Go's duration format (e.g., '24h') + - `until=` remove cache older than ``. The `` can be Unix timestamps, date formatted timestamps, or Go duration strings (e.g. `10m`, `1h30m`) computed relative to the daemon's local time. - `id=` - `parent=` - `type=` diff --git a/vendor/github.com/docker/docker/api/types/auth.go b/vendor/github.com/docker/docker/api/types/auth.go index ddf15bb182d..9ee329a2fba 100644 --- a/vendor/github.com/docker/docker/api/types/auth.go +++ b/vendor/github.com/docker/docker/api/types/auth.go @@ -1,22 +1,7 @@ package types // import "github.com/docker/docker/api/types" +import "github.com/docker/docker/api/types/registry" -// AuthConfig contains authorization information for connecting to a Registry -type AuthConfig struct { - Username string `json:"username,omitempty"` - Password string `json:"password,omitempty"` - Auth string `json:"auth,omitempty"` - - // Email is an optional value associated with the username. - // This field is deprecated and will be removed in a later - // version of docker. - Email string `json:"email,omitempty"` - - ServerAddress string `json:"serveraddress,omitempty"` - - // IdentityToken is used to authenticate the user and get - // an access token for the registry. - IdentityToken string `json:"identitytoken,omitempty"` - - // RegistryToken is a bearer token to be sent to a registry - RegistryToken string `json:"registrytoken,omitempty"` -} +// AuthConfig contains authorization information for connecting to a Registry. +// +// Deprecated: use github.com/docker/docker/api/types/registry.AuthConfig +type AuthConfig = registry.AuthConfig diff --git a/vendor/github.com/docker/docker/api/types/client.go b/vendor/github.com/docker/docker/api/types/client.go index 97aca023064..d8cd3061354 100644 --- a/vendor/github.com/docker/docker/api/types/client.go +++ b/vendor/github.com/docker/docker/api/types/client.go @@ -7,6 +7,7 @@ import ( "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/filters" + "github.com/docker/docker/api/types/registry" units "github.com/docker/go-units" ) @@ -180,7 +181,7 @@ type ImageBuildOptions struct { // at all (nil). See the parsing of buildArgs in // api/server/router/build/build_routes.go for even more info. BuildArgs map[string]*string - AuthConfigs map[string]AuthConfig + AuthConfigs map[string]registry.AuthConfig Context io.Reader Labels map[string]string // squash the resulting image's layers to the parent diff --git a/vendor/github.com/docker/docker/api/types/container/change_response_deprecated.go b/vendor/github.com/docker/docker/api/types/container/change_response_deprecated.go new file mode 100644 index 00000000000..6b4b47390d4 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/change_response_deprecated.go @@ -0,0 +1,6 @@ +package container + +// ContainerChangeResponseItem change item in response to ContainerChanges operation +// +// Deprecated: use [FilesystemChange]. +type ContainerChangeResponseItem = FilesystemChange diff --git a/vendor/github.com/docker/docker/api/types/container/change_type.go b/vendor/github.com/docker/docker/api/types/container/change_type.go new file mode 100644 index 00000000000..fe8d6d36966 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/change_type.go @@ -0,0 +1,15 @@ +package container + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +// ChangeType Kind of change +// +// Can be one of: +// +// - `0`: Modified ("C") +// - `1`: Added ("A") +// - `2`: Deleted ("D") +// +// swagger:model ChangeType +type ChangeType uint8 diff --git a/vendor/github.com/docker/docker/api/types/container/change_types.go b/vendor/github.com/docker/docker/api/types/container/change_types.go new file mode 100644 index 00000000000..3a3a83866ec --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/change_types.go @@ -0,0 +1,23 @@ +package container + +const ( + // ChangeModify represents the modify operation. + ChangeModify ChangeType = 0 + // ChangeAdd represents the add operation. + ChangeAdd ChangeType = 1 + // ChangeDelete represents the delete operation. + ChangeDelete ChangeType = 2 +) + +func (ct ChangeType) String() string { + switch ct { + case ChangeModify: + return "C" + case ChangeAdd: + return "A" + case ChangeDelete: + return "D" + default: + return "" + } +} diff --git a/vendor/github.com/docker/docker/api/types/container/container_changes.go b/vendor/github.com/docker/docker/api/types/container/container_changes.go deleted file mode 100644 index 16dd5019eef..00000000000 --- a/vendor/github.com/docker/docker/api/types/container/container_changes.go +++ /dev/null @@ -1,20 +0,0 @@ -package container // import "github.com/docker/docker/api/types/container" - -// ---------------------------------------------------------------------------- -// Code generated by `swagger generate operation`. DO NOT EDIT. -// -// See hack/generate-swagger-api.sh -// ---------------------------------------------------------------------------- - -// ContainerChangeResponseItem change item in response to ContainerChanges operation -// swagger:model ContainerChangeResponseItem -type ContainerChangeResponseItem struct { - - // Kind of change - // Required: true - Kind uint8 `json:"Kind"` - - // Path to file that has changed - // Required: true - Path string `json:"Path"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/deprecated.go b/vendor/github.com/docker/docker/api/types/container/deprecated.go deleted file mode 100644 index 0cb70e36381..00000000000 --- a/vendor/github.com/docker/docker/api/types/container/deprecated.go +++ /dev/null @@ -1,16 +0,0 @@ -package container // import "github.com/docker/docker/api/types/container" - -// ContainerCreateCreatedBody OK response to ContainerCreate operation -// -// Deprecated: use CreateResponse -type ContainerCreateCreatedBody = CreateResponse - -// ContainerWaitOKBody OK response to ContainerWait operation -// -// Deprecated: use WaitResponse -type ContainerWaitOKBody = WaitResponse - -// ContainerWaitOKBodyError container waiting error, if any -// -// Deprecated: use WaitExitError -type ContainerWaitOKBodyError = WaitExitError diff --git a/vendor/github.com/docker/docker/api/types/container/filesystem_change.go b/vendor/github.com/docker/docker/api/types/container/filesystem_change.go new file mode 100644 index 00000000000..9e9c2ad1d58 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/container/filesystem_change.go @@ -0,0 +1,19 @@ +package container + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +// FilesystemChange Change in the container's filesystem. +// +// swagger:model FilesystemChange +type FilesystemChange struct { + + // kind + // Required: true + Kind ChangeType `json:"Kind"` + + // Path to file or directory that has changed. + // + // Required: true + Path string `json:"Path"` +} diff --git a/vendor/github.com/docker/docker/api/types/container/host_config.go b/vendor/github.com/docker/docker/api/types/container/hostconfig.go similarity index 84% rename from vendor/github.com/docker/docker/api/types/container/host_config.go rename to vendor/github.com/docker/docker/api/types/container/hostconfig.go index 100f434ce7f..d4e6f55375a 100644 --- a/vendor/github.com/docker/docker/api/types/container/host_config.go +++ b/vendor/github.com/docker/docker/api/types/container/hostconfig.go @@ -101,7 +101,8 @@ func (n IpcMode) IsShareable() bool { // IsContainer indicates whether the container uses another container's ipc namespace. func (n IpcMode) IsContainer() bool { - return strings.HasPrefix(string(n), string(IPCModeContainer)+":") + _, ok := containerID(string(n)) + return ok } // IsNone indicates whether container IpcMode is set to "none". @@ -116,15 +117,14 @@ func (n IpcMode) IsEmpty() bool { // Valid indicates whether the ipc mode is valid. func (n IpcMode) Valid() bool { + // TODO(thaJeztah): align with PidMode, and consider container-mode without a container name/ID to be invalid. return n.IsEmpty() || n.IsNone() || n.IsPrivate() || n.IsHost() || n.IsShareable() || n.IsContainer() } // Container returns the name of the container ipc stack is going to be used. -func (n IpcMode) Container() string { - if n.IsContainer() { - return strings.TrimPrefix(string(n), string(IPCModeContainer)+":") - } - return "" +func (n IpcMode) Container() (idOrName string) { + idOrName, _ = containerID(string(n)) + return idOrName } // NetworkMode represents the container network stack. @@ -147,17 +147,14 @@ func (n NetworkMode) IsPrivate() bool { // IsContainer indicates whether container uses a container network stack. func (n NetworkMode) IsContainer() bool { - parts := strings.SplitN(string(n), ":", 2) - return len(parts) > 1 && parts[0] == "container" + _, ok := containerID(string(n)) + return ok } // ConnectedContainer is the id of the container which network this container is connected to. -func (n NetworkMode) ConnectedContainer() string { - parts := strings.SplitN(string(n), ":", 2) - if len(parts) > 1 { - return parts[1] - } - return "" +func (n NetworkMode) ConnectedContainer() (idOrName string) { + idOrName, _ = containerID(string(n)) + return idOrName } // UserDefined indicates user-created network @@ -178,18 +175,12 @@ func (n UsernsMode) IsHost() bool { // IsPrivate indicates whether the container uses the a private userns. func (n UsernsMode) IsPrivate() bool { - return !(n.IsHost()) + return !n.IsHost() } // Valid indicates whether the userns is valid. func (n UsernsMode) Valid() bool { - parts := strings.Split(string(n), ":") - switch mode := parts[0]; mode { - case "", "host": - default: - return false - } - return true + return n == "" || n.IsHost() } // CgroupSpec represents the cgroup to use for the container. @@ -197,22 +188,20 @@ type CgroupSpec string // IsContainer indicates whether the container is using another container cgroup func (c CgroupSpec) IsContainer() bool { - parts := strings.SplitN(string(c), ":", 2) - return len(parts) > 1 && parts[0] == "container" + _, ok := containerID(string(c)) + return ok } // Valid indicates whether the cgroup spec is valid. func (c CgroupSpec) Valid() bool { - return c.IsContainer() || c == "" + // TODO(thaJeztah): align with PidMode, and consider container-mode without a container name/ID to be invalid. + return c == "" || c.IsContainer() } -// Container returns the name of the container whose cgroup will be used. -func (c CgroupSpec) Container() string { - parts := strings.SplitN(string(c), ":", 2) - if len(parts) > 1 { - return parts[1] - } - return "" +// Container returns the ID or name of the container whose cgroup will be used. +func (c CgroupSpec) Container() (idOrName string) { + idOrName, _ = containerID(string(c)) + return idOrName } // UTSMode represents the UTS namespace of the container. @@ -220,7 +209,7 @@ type UTSMode string // IsPrivate indicates whether the container uses its private UTS namespace. func (n UTSMode) IsPrivate() bool { - return !(n.IsHost()) + return !n.IsHost() } // IsHost indicates whether the container uses the host's UTS namespace. @@ -230,13 +219,7 @@ func (n UTSMode) IsHost() bool { // Valid indicates whether the UTS namespace is valid. func (n UTSMode) Valid() bool { - parts := strings.Split(string(n), ":") - switch mode := parts[0]; mode { - case "", "host": - default: - return false - } - return true + return n == "" || n.IsHost() } // PidMode represents the pid namespace of the container. @@ -254,32 +237,19 @@ func (n PidMode) IsHost() bool { // IsContainer indicates whether the container uses a container's pid namespace. func (n PidMode) IsContainer() bool { - parts := strings.SplitN(string(n), ":", 2) - return len(parts) > 1 && parts[0] == "container" + _, ok := containerID(string(n)) + return ok } // Valid indicates whether the pid namespace is valid. func (n PidMode) Valid() bool { - parts := strings.Split(string(n), ":") - switch mode := parts[0]; mode { - case "", "host": - case "container": - if len(parts) != 2 || parts[1] == "" { - return false - } - default: - return false - } - return true + return n == "" || n.IsHost() || validContainer(string(n)) } // Container returns the name of the container whose pid namespace is going to be used. -func (n PidMode) Container() string { - parts := strings.SplitN(string(n), ":", 2) - if len(parts) > 1 { - return parts[1] - } - return "" +func (n PidMode) Container() (idOrName string) { + idOrName, _ = containerID(string(n)) + return idOrName } // DeviceRequest represents a request for devices from a device driver. @@ -408,16 +378,17 @@ type UpdateConfig struct { // Portable information *should* appear in Config. type HostConfig struct { // Applicable to all platforms - Binds []string // List of volume bindings for this container - ContainerIDFile string // File (path) where the containerId is written - LogConfig LogConfig // Configuration of the logs for this container - NetworkMode NetworkMode // Network mode to use for the container - PortBindings nat.PortMap // Port mapping between the exposed port (container) and the host - RestartPolicy RestartPolicy // Restart policy to be used for the container - AutoRemove bool // Automatically remove container when it exits - VolumeDriver string // Name of the volume driver used to mount volumes - VolumesFrom []string // List of volumes to take from other container - ConsoleSize [2]uint // Initial console size (height,width) + Binds []string // List of volume bindings for this container + ContainerIDFile string // File (path) where the containerId is written + LogConfig LogConfig // Configuration of the logs for this container + NetworkMode NetworkMode // Network mode to use for the container + PortBindings nat.PortMap // Port mapping between the exposed port (container) and the host + RestartPolicy RestartPolicy // Restart policy to be used for the container + AutoRemove bool // Automatically remove container when it exits + VolumeDriver string // Name of the volume driver used to mount volumes + VolumesFrom []string // List of volumes to take from other container + ConsoleSize [2]uint // Initial console size (height,width) + Annotations map[string]string `json:",omitempty"` // Arbitrary non-identifying metadata attached to container and provided to the runtime // Applicable to UNIX platforms CapAdd strslice.StrSlice // List of kernel capabilities to add to the container @@ -463,3 +434,23 @@ type HostConfig struct { // Run a custom init inside the container, if null, use the daemon's configured settings Init *bool `json:",omitempty"` } + +// containerID splits "container:" values. It returns the container +// ID or name, and whether an ID/name was found. It returns an empty string and +// a "false" if the value does not have a "container:" prefix. Further validation +// of the returned, including checking if the value is empty, should be handled +// by the caller. +func containerID(val string) (idOrName string, ok bool) { + k, v, hasSep := strings.Cut(val, ":") + if !hasSep || k != "container" { + return "", false + } + return v, true +} + +// validContainer checks if the given value is a "container:" mode with +// a non-empty name/ID. +func validContainer(val string) bool { + id, ok := containerID(val) + return ok && id != "" +} diff --git a/vendor/github.com/docker/docker/api/types/deprecated.go b/vendor/github.com/docker/docker/api/types/deprecated.go deleted file mode 100644 index 216d1df0ffa..00000000000 --- a/vendor/github.com/docker/docker/api/types/deprecated.go +++ /dev/null @@ -1,14 +0,0 @@ -package types // import "github.com/docker/docker/api/types" - -import "github.com/docker/docker/api/types/volume" - -// Volume volume -// -// Deprecated: use github.com/docker/docker/api/types/volume.Volume -type Volume = volume.Volume - -// VolumeUsageData Usage details about the volume. This information is used by the -// `GET /system/df` endpoint, and omitted in other endpoints. -// -// Deprecated: use github.com/docker/docker/api/types/volume.UsageData -type VolumeUsageData = volume.UsageData diff --git a/vendor/github.com/docker/docker/api/types/filters/errors.go b/vendor/github.com/docker/docker/api/types/filters/errors.go new file mode 100644 index 00000000000..f52f6944089 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/filters/errors.go @@ -0,0 +1,37 @@ +package filters + +import "fmt" + +// invalidFilter indicates that the provided filter or its value is invalid +type invalidFilter struct { + Filter string + Value []string +} + +func (e invalidFilter) Error() string { + msg := "invalid filter" + if e.Filter != "" { + msg += " '" + e.Filter + if e.Value != nil { + msg = fmt.Sprintf("%s=%s", msg, e.Value) + } + msg += "'" + } + return msg +} + +// InvalidParameter marks this error as ErrInvalidParameter +func (e invalidFilter) InvalidParameter() {} + +// unreachableCode is an error indicating that the code path was not expected to be reached. +type unreachableCode struct { + Filter string + Value []string +} + +// System marks this error as ErrSystem +func (e unreachableCode) System() {} + +func (e unreachableCode) Error() string { + return fmt.Sprintf("unreachable code reached for filter: %q with values: %s", e.Filter, e.Value) +} diff --git a/vendor/github.com/docker/docker/api/types/filters/parse.go b/vendor/github.com/docker/docker/api/types/filters/parse.go index f8fe7940741..887648cf3e3 100644 --- a/vendor/github.com/docker/docker/api/types/filters/parse.go +++ b/vendor/github.com/docker/docker/api/types/filters/parse.go @@ -10,7 +10,6 @@ import ( "strings" "github.com/docker/docker/api/types/versions" - "github.com/pkg/errors" ) // Args stores a mapping of keys to a set of multiple values. @@ -99,7 +98,7 @@ func FromJSON(p string) (Args, error) { // Fallback to parsing arguments in the legacy slice format deprecated := map[string][]string{} if legacyErr := json.Unmarshal(raw, &deprecated); legacyErr != nil { - return args, invalidFilter{errors.Wrap(err, "invalid filter")} + return args, invalidFilter{} } args.fields = deprecatedArgs(deprecated) @@ -163,13 +162,13 @@ func (args Args) MatchKVList(key string, sources map[string]string) bool { } for value := range fieldValues { - testKV := strings.SplitN(value, "=", 2) + testK, testV, hasValue := strings.Cut(value, "=") - v, ok := sources[testKV[0]] + v, ok := sources[testK] if !ok { return false } - if len(testKV) == 2 && testKV[1] != v { + if hasValue && testV != v { return false } } @@ -196,6 +195,38 @@ func (args Args) Match(field, source string) bool { return false } +// GetBoolOrDefault returns a boolean value of the key if the key is present +// and is intepretable as a boolean value. Otherwise the default value is returned. +// Error is not nil only if the filter values are not valid boolean or are conflicting. +func (args Args) GetBoolOrDefault(key string, defaultValue bool) (bool, error) { + fieldValues, ok := args.fields[key] + + if !ok { + return defaultValue, nil + } + + if len(fieldValues) == 0 { + return defaultValue, invalidFilter{key, nil} + } + + isFalse := fieldValues["0"] || fieldValues["false"] + isTrue := fieldValues["1"] || fieldValues["true"] + + conflicting := isFalse && isTrue + invalid := !isFalse && !isTrue + + if conflicting || invalid { + return defaultValue, invalidFilter{key, args.Get(key)} + } else if isFalse { + return false, nil + } else if isTrue { + return true, nil + } + + // This code shouldn't be reached. + return defaultValue, unreachableCode{Filter: key, Value: args.Get(key)} +} + // ExactMatch returns true if the source matches exactly one of the values. func (args Args) ExactMatch(key, source string) bool { fieldValues, ok := args.fields[key] @@ -246,20 +277,12 @@ func (args Args) Contains(field string) bool { return ok } -type invalidFilter struct{ error } - -func (e invalidFilter) Error() string { - return e.error.Error() -} - -func (invalidFilter) InvalidParameter() {} - // Validate compared the set of accepted keys against the keys in the mapping. // An error is returned if any mapping keys are not in the accepted set. func (args Args) Validate(accepted map[string]bool) error { for name := range args.fields { if !accepted[name] { - return invalidFilter{errors.New("invalid filter '" + name + "'")} + return invalidFilter{name, nil} } } return nil diff --git a/vendor/github.com/docker/docker/api/types/image/opts.go b/vendor/github.com/docker/docker/api/types/image/opts.go new file mode 100644 index 00000000000..a24f9059ab4 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/image/opts.go @@ -0,0 +1,9 @@ +package image + +import specs "github.com/opencontainers/image-spec/specs-go/v1" + +// GetImageOpts holds parameters to inspect an image. +type GetImageOpts struct { + Platform *specs.Platform + Details bool +} diff --git a/vendor/github.com/docker/docker/api/types/image_summary.go b/vendor/github.com/docker/docker/api/types/image_summary.go index 90b983a25cc..0f6f144840e 100644 --- a/vendor/github.com/docker/docker/api/types/image_summary.go +++ b/vendor/github.com/docker/docker/api/types/image_summary.go @@ -85,13 +85,10 @@ type ImageSummary struct { // Total size of the image including all layers it is composed of. // // In versions of Docker before v1.10, this field was calculated from - // the image itself and all of its parent images. Docker v1.10 and up - // store images self-contained, and no longer use a parent-chain, making - // this field an equivalent of the Size field. + // the image itself and all of its parent images. Images are now stored + // self-contained, and no longer use a parent-chain, making this field + // an equivalent of the Size field. // - // This field is kept for backward compatibility, but may be removed in - // a future version of the API. - // - // Required: true - VirtualSize int64 `json:"VirtualSize"` + // Deprecated: this field is kept for backward compatibility, and will be removed in API v1.44. + VirtualSize int64 `json:"VirtualSize,omitempty"` } diff --git a/vendor/github.com/docker/docker/api/types/registry/authconfig.go b/vendor/github.com/docker/docker/api/types/registry/authconfig.go new file mode 100644 index 00000000000..97a924e3747 --- /dev/null +++ b/vendor/github.com/docker/docker/api/types/registry/authconfig.go @@ -0,0 +1,99 @@ +package registry // import "github.com/docker/docker/api/types/registry" +import ( + "encoding/base64" + "encoding/json" + "io" + "strings" + + "github.com/pkg/errors" +) + +// AuthHeader is the name of the header used to send encoded registry +// authorization credentials for registry operations (push/pull). +const AuthHeader = "X-Registry-Auth" + +// AuthConfig contains authorization information for connecting to a Registry. +type AuthConfig struct { + Username string `json:"username,omitempty"` + Password string `json:"password,omitempty"` + Auth string `json:"auth,omitempty"` + + // Email is an optional value associated with the username. + // This field is deprecated and will be removed in a later + // version of docker. + Email string `json:"email,omitempty"` + + ServerAddress string `json:"serveraddress,omitempty"` + + // IdentityToken is used to authenticate the user and get + // an access token for the registry. + IdentityToken string `json:"identitytoken,omitempty"` + + // RegistryToken is a bearer token to be sent to a registry + RegistryToken string `json:"registrytoken,omitempty"` +} + +// EncodeAuthConfig serializes the auth configuration as a base64url encoded +// RFC4648, section 5) JSON string for sending through the X-Registry-Auth header. +// +// For details on base64url encoding, see: +// - RFC4648, section 5: https://tools.ietf.org/html/rfc4648#section-5 +func EncodeAuthConfig(authConfig AuthConfig) (string, error) { + buf, err := json.Marshal(authConfig) + if err != nil { + return "", errInvalidParameter{err} + } + return base64.URLEncoding.EncodeToString(buf), nil +} + +// DecodeAuthConfig decodes base64url encoded (RFC4648, section 5) JSON +// authentication information as sent through the X-Registry-Auth header. +// +// This function always returns an AuthConfig, even if an error occurs. It is up +// to the caller to decide if authentication is required, and if the error can +// be ignored. +// +// For details on base64url encoding, see: +// - RFC4648, section 5: https://tools.ietf.org/html/rfc4648#section-5 +func DecodeAuthConfig(authEncoded string) (*AuthConfig, error) { + if authEncoded == "" { + return &AuthConfig{}, nil + } + + authJSON := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded)) + return decodeAuthConfigFromReader(authJSON) +} + +// DecodeAuthConfigBody decodes authentication information as sent as JSON in the +// body of a request. This function is to provide backward compatibility with old +// clients and API versions. Current clients and API versions expect authentication +// to be provided through the X-Registry-Auth header. +// +// Like DecodeAuthConfig, this function always returns an AuthConfig, even if an +// error occurs. It is up to the caller to decide if authentication is required, +// and if the error can be ignored. +func DecodeAuthConfigBody(rdr io.ReadCloser) (*AuthConfig, error) { + return decodeAuthConfigFromReader(rdr) +} + +func decodeAuthConfigFromReader(rdr io.Reader) (*AuthConfig, error) { + authConfig := &AuthConfig{} + if err := json.NewDecoder(rdr).Decode(authConfig); err != nil { + // always return an (empty) AuthConfig to increase compatibility with + // the existing API. + return &AuthConfig{}, invalid(err) + } + return authConfig, nil +} + +func invalid(err error) error { + return errInvalidParameter{errors.Wrap(err, "invalid X-Registry-Auth header")} +} + +type errInvalidParameter struct{ error } + +func (errInvalidParameter) InvalidParameter() {} + +func (e errInvalidParameter) Cause() error { return e.error } + +func (e errInvalidParameter) Unwrap() error { return e.error } diff --git a/vendor/github.com/docker/docker/api/types/time/timestamp.go b/vendor/github.com/docker/docker/api/types/time/timestamp.go index 2a74b7a5979..cab5c32e3ff 100644 --- a/vendor/github.com/docker/docker/api/types/time/timestamp.go +++ b/vendor/github.com/docker/docker/api/types/time/timestamp.go @@ -95,37 +95,37 @@ func GetTimestamp(value string, reference time.Time) (string, error) { return fmt.Sprintf("%d.%09d", t.Unix(), int64(t.Nanosecond())), nil } -// ParseTimestamps returns seconds and nanoseconds from a timestamp that has the -// format "%d.%09d", time.Unix(), int64(time.Nanosecond())) -// if the incoming nanosecond portion is longer or shorter than 9 digits it is -// converted to nanoseconds. The expectation is that the seconds and -// seconds will be used to create a time variable. For example: +// ParseTimestamps returns seconds and nanoseconds from a timestamp that has +// the format ("%d.%09d", time.Unix(), int64(time.Nanosecond())). +// If the incoming nanosecond portion is longer than 9 digits it is truncated. +// The expectation is that the seconds and nanoseconds will be used to create a +// time variable. For example: // -// seconds, nanoseconds, err := ParseTimestamp("1136073600.000000001",0) -// if err == nil since := time.Unix(seconds, nanoseconds) +// seconds, nanoseconds, _ := ParseTimestamp("1136073600.000000001",0) +// since := time.Unix(seconds, nanoseconds) // -// returns seconds as def(aultSeconds) if value == "" -func ParseTimestamps(value string, def int64) (int64, int64, error) { +// returns seconds as defaultSeconds if value == "" +func ParseTimestamps(value string, defaultSeconds int64) (seconds int64, nanoseconds int64, err error) { if value == "" { - return def, 0, nil + return defaultSeconds, 0, nil } return parseTimestamp(value) } -func parseTimestamp(value string) (int64, int64, error) { - sa := strings.SplitN(value, ".", 2) - s, err := strconv.ParseInt(sa[0], 10, 64) +func parseTimestamp(value string) (sec int64, nsec int64, err error) { + s, n, ok := strings.Cut(value, ".") + sec, err = strconv.ParseInt(s, 10, 64) if err != nil { - return s, 0, err + return sec, 0, err } - if len(sa) != 2 { - return s, 0, nil + if !ok { + return sec, 0, nil } - n, err := strconv.ParseInt(sa[1], 10, 64) + nsec, err = strconv.ParseInt(n, 10, 64) if err != nil { - return s, n, err + return sec, nsec, err } // should already be in nanoseconds but just in case convert n to nanoseconds - n = int64(float64(n) * math.Pow(float64(10), float64(9-len(sa[1])))) - return s, n, nil + nsec = int64(float64(nsec) * math.Pow(float64(10), float64(9-len(n)))) + return sec, nsec, nil } diff --git a/vendor/github.com/docker/docker/api/types/types.go b/vendor/github.com/docker/docker/api/types/types.go index 036405299ea..b413e020006 100644 --- a/vendor/github.com/docker/docker/api/types/types.go +++ b/vendor/github.com/docker/docker/api/types/types.go @@ -123,9 +123,8 @@ type ImageInspect struct { // store images self-contained, and no longer use a parent-chain, making // this field an equivalent of the Size field. // - // This field is kept for backward compatibility, but may be removed in - // a future version of the API. - VirtualSize int64 // TODO(thaJeztah): deprecate this field + // Deprecated: Unused in API 1.43 and up, but kept for backward compatibility with older API versions. + VirtualSize int64 `json:"VirtualSize,omitempty"` // GraphDriver holds information about the storage driver used to store the // container's and image's filesystem. @@ -297,8 +296,6 @@ type Info struct { Labels []string ExperimentalBuild bool ServerVersion string - ClusterStore string `json:",omitempty"` // Deprecated: host-discovery and overlay networks with external k/v stores are deprecated - ClusterAdvertise string `json:",omitempty"` // Deprecated: host-discovery and overlay networks with external k/v stores are deprecated Runtimes map[string]Runtime DefaultRuntime string Swarm swarm.Info @@ -350,20 +347,19 @@ func DecodeSecurityOptions(opts []string) ([]SecurityOpt, error) { continue } secopt := SecurityOpt{} - split := strings.Split(opt, ",") - for _, s := range split { - kv := strings.SplitN(s, "=", 2) - if len(kv) != 2 { + for _, s := range strings.Split(opt, ",") { + k, v, ok := strings.Cut(s, "=") + if !ok { return nil, fmt.Errorf("invalid security option %q", s) } - if kv[0] == "" || kv[1] == "" { + if k == "" || v == "" { return nil, errors.New("invalid empty security option") } - if kv[0] == "name" { - secopt.Name = kv[1] + if k == "name" { + secopt.Name = v continue } - secopt.Options = append(secopt.Options, KeyValue{Key: kv[0], Value: kv[1]}) + secopt.Options = append(secopt.Options, KeyValue{Key: k, Value: v}) } so = append(so, secopt) } @@ -656,12 +652,18 @@ type Checkpoint struct { // Runtime describes an OCI runtime type Runtime struct { - Path string `json:"path"` + // "Legacy" runtime configuration for runc-compatible runtimes. + + Path string `json:"path,omitempty"` Args []string `json:"runtimeArgs,omitempty"` + // Shimv2 runtime configuration. Mutually exclusive with the legacy config above. + + Type string `json:"runtimeType,omitempty"` + Options map[string]interface{} `json:"options,omitempty"` + // This is exposed here only for internal use - // It is not currently supported to specify custom shim configs - Shim *ShimConfig `json:"-"` + ShimConfig *ShimConfig `json:"-"` } // ShimConfig is used by runtime to configure containerd shims diff --git a/vendor/github.com/docker/docker/api/types/volume/deprecated.go b/vendor/github.com/docker/docker/api/types/volume/deprecated.go deleted file mode 100644 index ab622d8ccb4..00000000000 --- a/vendor/github.com/docker/docker/api/types/volume/deprecated.go +++ /dev/null @@ -1,11 +0,0 @@ -package volume // import "github.com/docker/docker/api/types/volume" - -// VolumeCreateBody Volume configuration -// -// Deprecated: use CreateOptions -type VolumeCreateBody = CreateOptions - -// VolumeListOKBody Volume list response -// -// Deprecated: use ListResponse -type VolumeListOKBody = ListResponse diff --git a/vendor/github.com/docker/docker/client/build_prune.go b/vendor/github.com/docker/docker/client/build_prune.go index 397d67cdcf1..2b6606236eb 100644 --- a/vendor/github.com/docker/docker/client/build_prune.go +++ b/vendor/github.com/docker/docker/client/build_prune.go @@ -3,8 +3,8 @@ package client // import "github.com/docker/docker/client" import ( "context" "encoding/json" - "fmt" "net/url" + "strconv" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/filters" @@ -23,12 +23,12 @@ func (cli *Client) BuildCachePrune(ctx context.Context, opts types.BuildCachePru if opts.All { query.Set("all", "1") } - query.Set("keep-storage", fmt.Sprintf("%d", opts.KeepStorage)) - filters, err := filters.ToJSON(opts.Filters) + query.Set("keep-storage", strconv.Itoa(int(opts.KeepStorage))) + f, err := filters.ToJSON(opts.Filters) if err != nil { return nil, errors.Wrap(err, "prune could not marshal filters option") } - query.Set("filters", filters) + query.Set("filters", f) serverResp, err := cli.post(ctx, "/build/prune", query, nil, nil) defer ensureReaderClosed(serverResp) @@ -38,7 +38,7 @@ func (cli *Client) BuildCachePrune(ctx context.Context, opts types.BuildCachePru } if err := json.NewDecoder(serverResp.body).Decode(&report); err != nil { - return nil, fmt.Errorf("Error retrieving disk usage: %v", err) + return nil, errors.Wrap(err, "error retrieving disk usage") } return &report, nil diff --git a/vendor/github.com/docker/docker/client/client.go b/vendor/github.com/docker/docker/client/client.go index 26a0fa27562..1c081a51ae6 100644 --- a/vendor/github.com/docker/docker/client/client.go +++ b/vendor/github.com/docker/docker/client/client.go @@ -6,9 +6,10 @@ https://docs.docker.com/engine/api/ # Usage -You use the library by creating a client object and calling methods on it. The -client can be created either from environment variables with NewClientWithOpts(client.FromEnv), -or configured manually with NewClient(). +You use the library by constructing a client object using [NewClientWithOpts] +and calling methods on it. The client can be configured from environment +variables by passing the [FromEnv] option, or configured manually by passing any +of the other available [Opts]. For example, to list running containers (the equivalent of "docker ps"): @@ -125,7 +126,12 @@ func CheckRedirect(req *http.Request, via []*http.Request) error { // client.WithAPIVersionNegotiation(), // ) func NewClientWithOpts(ops ...Opt) (*Client, error) { - client, err := defaultHTTPClient(DefaultDockerHost) + hostURL, err := ParseHostURL(DefaultDockerHost) + if err != nil { + return nil, err + } + + client, err := defaultHTTPClient(hostURL) if err != nil { return nil, err } @@ -133,8 +139,8 @@ func NewClientWithOpts(ops ...Opt) (*Client, error) { host: DefaultDockerHost, version: api.DefaultVersion, client: client, - proto: defaultProto, - addr: defaultAddr, + proto: hostURL.Scheme, + addr: hostURL.Host, } for _, op := range ops { @@ -160,13 +166,12 @@ func NewClientWithOpts(ops ...Opt) (*Client, error) { return c, nil } -func defaultHTTPClient(host string) (*http.Client, error) { - hostURL, err := ParseHostURL(host) +func defaultHTTPClient(hostURL *url.URL) (*http.Client, error) { + transport := &http.Transport{} + err := sockets.ConfigureTransport(transport, hostURL.Scheme, hostURL.Host) if err != nil { return nil, err } - transport := &http.Transport{} - _ = sockets.ConfigureTransport(transport, hostURL.Scheme, hostURL.Host) return &http.Client{ Transport: transport, CheckRedirect: CheckRedirect, @@ -282,13 +287,12 @@ func (cli *Client) HTTPClient() *http.Client { // ParseHostURL parses a url string, validates the string is a host url, and // returns the parsed URL func ParseHostURL(host string) (*url.URL, error) { - protoAddrParts := strings.SplitN(host, "://", 2) - if len(protoAddrParts) == 1 { + proto, addr, ok := strings.Cut(host, "://") + if !ok || addr == "" { return nil, errors.Errorf("unable to parse docker host `%s`", host) } var basePath string - proto, addr := protoAddrParts[0], protoAddrParts[1] if proto == "tcp" { parsed, err := url.Parse("tcp://" + addr) if err != nil { diff --git a/vendor/github.com/docker/docker/client/client_deprecated.go b/vendor/github.com/docker/docker/client/client_deprecated.go index 54cdfc29a84..9e366ce20d1 100644 --- a/vendor/github.com/docker/docker/client/client_deprecated.go +++ b/vendor/github.com/docker/docker/client/client_deprecated.go @@ -9,7 +9,11 @@ import "net/http" // It won't send any version information if the version number is empty. It is // highly recommended that you set a version or your client may break if the // server is upgraded. -// Deprecated: use NewClientWithOpts +// +// Deprecated: use [NewClientWithOpts] passing the [WithHost], [WithVersion], +// [WithHTTPClient] and [WithHTTPHeaders] options. We recommend enabling API +// version negotiation by passing the [WithAPIVersionNegotiation] option instead +// of WithVersion. func NewClient(host string, version string, client *http.Client, httpHeaders map[string]string) (*Client, error) { return NewClientWithOpts(WithHost(host), WithVersion(version), WithHTTPClient(client), WithHTTPHeaders(httpHeaders)) } @@ -17,7 +21,7 @@ func NewClient(host string, version string, client *http.Client, httpHeaders map // NewEnvClient initializes a new API client based on environment variables. // See FromEnv for a list of support environment variables. // -// Deprecated: use NewClientWithOpts(FromEnv) +// Deprecated: use [NewClientWithOpts] passing the [FromEnv] option. func NewEnvClient() (*Client, error) { return NewClientWithOpts(FromEnv) } diff --git a/vendor/github.com/docker/docker/client/client_unix.go b/vendor/github.com/docker/docker/client/client_unix.go index f0783f70858..319b738d3e2 100644 --- a/vendor/github.com/docker/docker/client/client_unix.go +++ b/vendor/github.com/docker/docker/client/client_unix.go @@ -1,11 +1,8 @@ -//go:build linux || freebsd || openbsd || netbsd || darwin || solaris || illumos || dragonfly -// +build linux freebsd openbsd netbsd darwin solaris illumos dragonfly +//go:build !windows +// +build !windows package client // import "github.com/docker/docker/client" // DefaultDockerHost defines OS-specific default host if the DOCKER_HOST // (EnvOverrideHost) environment variable is unset or empty. const DefaultDockerHost = "unix:///var/run/docker.sock" - -const defaultProto = "unix" -const defaultAddr = "/var/run/docker.sock" diff --git a/vendor/github.com/docker/docker/client/client_windows.go b/vendor/github.com/docker/docker/client/client_windows.go index 5abe60457d5..56572d1a27f 100644 --- a/vendor/github.com/docker/docker/client/client_windows.go +++ b/vendor/github.com/docker/docker/client/client_windows.go @@ -3,6 +3,3 @@ package client // import "github.com/docker/docker/client" // DefaultDockerHost defines OS-specific default host if the DOCKER_HOST // (EnvOverrideHost) environment variable is unset or empty. const DefaultDockerHost = "npipe:////./pipe/docker_engine" - -const defaultProto = "npipe" -const defaultAddr = "//./pipe/docker_engine" diff --git a/vendor/github.com/docker/docker/client/container_diff.go b/vendor/github.com/docker/docker/client/container_diff.go index 29dac8491df..c22c819a798 100644 --- a/vendor/github.com/docker/docker/client/container_diff.go +++ b/vendor/github.com/docker/docker/client/container_diff.go @@ -9,8 +9,8 @@ import ( ) // ContainerDiff shows differences in a container filesystem since it was started. -func (cli *Client) ContainerDiff(ctx context.Context, containerID string) ([]container.ContainerChangeResponseItem, error) { - var changes []container.ContainerChangeResponseItem +func (cli *Client) ContainerDiff(ctx context.Context, containerID string) ([]container.FilesystemChange, error) { + var changes []container.FilesystemChange serverResp, err := cli.get(ctx, "/containers/"+containerID+"/changes", url.Values{}, nil) defer ensureReaderClosed(serverResp) diff --git a/vendor/github.com/docker/docker/client/distribution_inspect.go b/vendor/github.com/docker/docker/client/distribution_inspect.go index 7f36c99a016..efab066d3bd 100644 --- a/vendor/github.com/docker/docker/client/distribution_inspect.go +++ b/vendor/github.com/docker/docker/client/distribution_inspect.go @@ -5,13 +5,13 @@ import ( "encoding/json" "net/url" - registrytypes "github.com/docker/docker/api/types/registry" + "github.com/docker/docker/api/types/registry" ) // DistributionInspect returns the image digest with the full manifest. -func (cli *Client) DistributionInspect(ctx context.Context, image, encodedRegistryAuth string) (registrytypes.DistributionInspect, error) { +func (cli *Client) DistributionInspect(ctx context.Context, image, encodedRegistryAuth string) (registry.DistributionInspect, error) { // Contact the registry to retrieve digest and platform information - var distributionInspect registrytypes.DistributionInspect + var distributionInspect registry.DistributionInspect if image == "" { return distributionInspect, objectNotFoundError{object: "distribution", id: image} } @@ -23,7 +23,7 @@ func (cli *Client) DistributionInspect(ctx context.Context, image, encodedRegist if encodedRegistryAuth != "" { headers = map[string][]string{ - "X-Registry-Auth": {encodedRegistryAuth}, + registry.AuthHeader: {encodedRegistryAuth}, } } diff --git a/vendor/github.com/docker/docker/client/errors.go b/vendor/github.com/docker/docker/client/errors.go index e5a8a865f9f..6878144c41e 100644 --- a/vendor/github.com/docker/docker/client/errors.go +++ b/vendor/github.com/docker/docker/client/errors.go @@ -58,31 +58,6 @@ func (e objectNotFoundError) Error() string { return fmt.Sprintf("Error: No such %s: %s", e.object, e.id) } -// IsErrUnauthorized returns true if the error is caused -// when a remote registry authentication fails -// -// Deprecated: use errdefs.IsUnauthorized -func IsErrUnauthorized(err error) bool { - return errdefs.IsUnauthorized(err) -} - -type pluginPermissionDenied struct { - name string -} - -func (e pluginPermissionDenied) Error() string { - return "Permission denied while installing plugin " + e.name -} - -// IsErrNotImplemented returns true if the error is a NotImplemented error. -// This is returned by the API when a requested feature has not been -// implemented. -// -// Deprecated: use errdefs.IsNotImplemented -func IsErrNotImplemented(err error) bool { - return errdefs.IsNotImplemented(err) -} - // NewVersionError returns an error if the APIVersion required // if less than the current supported version func (cli *Client) NewVersionError(APIrequired, feature string) error { diff --git a/vendor/github.com/docker/docker/client/image_create.go b/vendor/github.com/docker/docker/client/image_create.go index b1c0227775c..6a9b708f7d4 100644 --- a/vendor/github.com/docker/docker/client/image_create.go +++ b/vendor/github.com/docker/docker/client/image_create.go @@ -8,6 +8,7 @@ import ( "github.com/docker/distribution/reference" "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/registry" ) // ImageCreate creates a new image based on the parent options. @@ -32,6 +33,6 @@ func (cli *Client) ImageCreate(ctx context.Context, parentReference string, opti } func (cli *Client) tryImageCreate(ctx context.Context, query url.Values, registryAuth string) (serverResponse, error) { - headers := map[string][]string{"X-Registry-Auth": {registryAuth}} + headers := map[string][]string{registry.AuthHeader: {registryAuth}} return cli.post(ctx, "/images/create", query, nil, headers) } diff --git a/vendor/github.com/docker/docker/client/image_push.go b/vendor/github.com/docker/docker/client/image_push.go index 845580d4a4c..dd1b8f34716 100644 --- a/vendor/github.com/docker/docker/client/image_push.go +++ b/vendor/github.com/docker/docker/client/image_push.go @@ -8,6 +8,7 @@ import ( "github.com/docker/distribution/reference" "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/registry" "github.com/docker/docker/errdefs" ) @@ -49,6 +50,6 @@ func (cli *Client) ImagePush(ctx context.Context, image string, options types.Im } func (cli *Client) tryImagePush(ctx context.Context, imageID string, query url.Values, registryAuth string) (serverResponse, error) { - headers := map[string][]string{"X-Registry-Auth": {registryAuth}} + headers := map[string][]string{registry.AuthHeader: {registryAuth}} return cli.post(ctx, "/images/"+imageID+"/push", query, nil, headers) } diff --git a/vendor/github.com/docker/docker/client/image_search.go b/vendor/github.com/docker/docker/client/image_search.go index e69fa372258..5f0c49ed30c 100644 --- a/vendor/github.com/docker/docker/client/image_search.go +++ b/vendor/github.com/docker/docker/client/image_search.go @@ -48,6 +48,6 @@ func (cli *Client) ImageSearch(ctx context.Context, term string, options types.I } func (cli *Client) tryImageSearch(ctx context.Context, query url.Values, registryAuth string) (serverResponse, error) { - headers := map[string][]string{"X-Registry-Auth": {registryAuth}} + headers := map[string][]string{registry.AuthHeader: {registryAuth}} return cli.get(ctx, "/images/search", query, headers) } diff --git a/vendor/github.com/docker/docker/client/interface.go b/vendor/github.com/docker/docker/client/interface.go index e9c1ed722ee..64877d16416 100644 --- a/vendor/github.com/docker/docker/client/interface.go +++ b/vendor/github.com/docker/docker/client/interface.go @@ -48,7 +48,7 @@ type ContainerAPIClient interface { ContainerAttach(ctx context.Context, container string, options types.ContainerAttachOptions) (types.HijackedResponse, error) ContainerCommit(ctx context.Context, container string, options types.ContainerCommitOptions) (types.IDResponse, error) ContainerCreate(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, platform *specs.Platform, containerName string) (container.CreateResponse, error) - ContainerDiff(ctx context.Context, container string) ([]container.ContainerChangeResponseItem, error) + ContainerDiff(ctx context.Context, container string) ([]container.FilesystemChange, error) ContainerExecAttach(ctx context.Context, execID string, config types.ExecStartCheck) (types.HijackedResponse, error) ContainerExecCreate(ctx context.Context, container string, config types.ExecConfig) (types.IDResponse, error) ContainerExecInspect(ctx context.Context, execID string) (types.ContainerExecInspect, error) @@ -166,7 +166,7 @@ type SwarmAPIClient interface { type SystemAPIClient interface { Events(ctx context.Context, options types.EventsOptions) (<-chan events.Message, <-chan error) Info(ctx context.Context) (types.Info, error) - RegistryLogin(ctx context.Context, auth types.AuthConfig) (registry.AuthenticateOKBody, error) + RegistryLogin(ctx context.Context, auth registry.AuthConfig) (registry.AuthenticateOKBody, error) DiskUsage(ctx context.Context, options types.DiskUsageOptions) (types.DiskUsage, error) Ping(ctx context.Context) (types.Ping, error) } @@ -176,7 +176,7 @@ type VolumeAPIClient interface { VolumeCreate(ctx context.Context, options volume.CreateOptions) (volume.Volume, error) VolumeInspect(ctx context.Context, volumeID string) (volume.Volume, error) VolumeInspectWithRaw(ctx context.Context, volumeID string) (volume.Volume, []byte, error) - VolumeList(ctx context.Context, filter filters.Args) (volume.ListResponse, error) + VolumeList(ctx context.Context, options volume.ListOptions) (volume.ListResponse, error) VolumeRemove(ctx context.Context, volumeID string, force bool) error VolumesPrune(ctx context.Context, pruneFilter filters.Args) (types.VolumesPruneReport, error) VolumeUpdate(ctx context.Context, volumeID string, version swarm.Version, options volume.UpdateOptions) error diff --git a/vendor/github.com/docker/docker/client/login.go b/vendor/github.com/docker/docker/client/login.go index f0585206382..19e985e0b9c 100644 --- a/vendor/github.com/docker/docker/client/login.go +++ b/vendor/github.com/docker/docker/client/login.go @@ -5,13 +5,12 @@ import ( "encoding/json" "net/url" - "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/registry" ) // RegistryLogin authenticates the docker server with a given docker registry. // It returns unauthorizedError when the authentication fails. -func (cli *Client) RegistryLogin(ctx context.Context, auth types.AuthConfig) (registry.AuthenticateOKBody, error) { +func (cli *Client) RegistryLogin(ctx context.Context, auth registry.AuthConfig) (registry.AuthenticateOKBody, error) { resp, err := cli.post(ctx, "/auth", url.Values{}, auth, nil) defer ensureReaderClosed(resp) diff --git a/vendor/github.com/docker/docker/client/ping.go b/vendor/github.com/docker/docker/client/ping.go index 27e8695cb54..347ae71e027 100644 --- a/vendor/github.com/docker/docker/client/ping.go +++ b/vendor/github.com/docker/docker/client/ping.go @@ -64,10 +64,10 @@ func parsePingResponse(cli *Client, resp serverResponse) (types.Ping, error) { ping.BuilderVersion = types.BuilderVersion(bv) } if si := resp.header.Get("Swarm"); si != "" { - parts := strings.SplitN(si, "/", 2) + state, role, _ := strings.Cut(si, "/") ping.SwarmStatus = &swarm.Status{ - NodeState: swarm.LocalNodeState(parts[0]), - ControlAvailable: len(parts) == 2 && parts[1] == "manager", + NodeState: swarm.LocalNodeState(state), + ControlAvailable: role == "manager", } } err := cli.checkResponseErr(resp) diff --git a/vendor/github.com/docker/docker/client/plugin_install.go b/vendor/github.com/docker/docker/client/plugin_install.go index 012afe61cac..3a740ec4f60 100644 --- a/vendor/github.com/docker/docker/client/plugin_install.go +++ b/vendor/github.com/docker/docker/client/plugin_install.go @@ -8,6 +8,7 @@ import ( "github.com/docker/distribution/reference" "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/registry" "github.com/docker/docker/errdefs" "github.com/pkg/errors" ) @@ -67,12 +68,12 @@ func (cli *Client) PluginInstall(ctx context.Context, name string, options types } func (cli *Client) tryPluginPrivileges(ctx context.Context, query url.Values, registryAuth string) (serverResponse, error) { - headers := map[string][]string{"X-Registry-Auth": {registryAuth}} + headers := map[string][]string{registry.AuthHeader: {registryAuth}} return cli.get(ctx, "/plugins/privileges", query, headers) } func (cli *Client) tryPluginPull(ctx context.Context, query url.Values, privileges types.PluginPrivileges, registryAuth string) (serverResponse, error) { - headers := map[string][]string{"X-Registry-Auth": {registryAuth}} + headers := map[string][]string{registry.AuthHeader: {registryAuth}} return cli.post(ctx, "/plugins/pull", query, privileges, headers) } @@ -106,7 +107,7 @@ func (cli *Client) checkPluginPermissions(ctx context.Context, query url.Values, return nil, err } if !accept { - return nil, pluginPermissionDenied{options.RemoteRef} + return nil, errors.Errorf("permission denied while installing plugin %s", options.RemoteRef) } } return privileges, nil diff --git a/vendor/github.com/docker/docker/client/plugin_push.go b/vendor/github.com/docker/docker/client/plugin_push.go index d20bfe84479..18f9754c4c2 100644 --- a/vendor/github.com/docker/docker/client/plugin_push.go +++ b/vendor/github.com/docker/docker/client/plugin_push.go @@ -3,11 +3,13 @@ package client // import "github.com/docker/docker/client" import ( "context" "io" + + "github.com/docker/docker/api/types/registry" ) // PluginPush pushes a plugin to a registry func (cli *Client) PluginPush(ctx context.Context, name string, registryAuth string) (io.ReadCloser, error) { - headers := map[string][]string{"X-Registry-Auth": {registryAuth}} + headers := map[string][]string{registry.AuthHeader: {registryAuth}} resp, err := cli.post(ctx, "/plugins/"+name+"/push", nil, nil, headers) if err != nil { return nil, err diff --git a/vendor/github.com/docker/docker/client/plugin_upgrade.go b/vendor/github.com/docker/docker/client/plugin_upgrade.go index 115cea945ba..995d1fd2ca1 100644 --- a/vendor/github.com/docker/docker/client/plugin_upgrade.go +++ b/vendor/github.com/docker/docker/client/plugin_upgrade.go @@ -7,6 +7,7 @@ import ( "github.com/docker/distribution/reference" "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/registry" "github.com/pkg/errors" ) @@ -34,6 +35,6 @@ func (cli *Client) PluginUpgrade(ctx context.Context, name string, options types } func (cli *Client) tryPluginUpgrade(ctx context.Context, query url.Values, privileges types.PluginPrivileges, name, registryAuth string) (serverResponse, error) { - headers := map[string][]string{"X-Registry-Auth": {registryAuth}} + headers := map[string][]string{registry.AuthHeader: {registryAuth}} return cli.post(ctx, "/plugins/"+name+"/upgrade", query, privileges, headers) } diff --git a/vendor/github.com/docker/docker/client/service_create.go b/vendor/github.com/docker/docker/client/service_create.go index 23024d0f8fb..b6065b8eefd 100644 --- a/vendor/github.com/docker/docker/client/service_create.go +++ b/vendor/github.com/docker/docker/client/service_create.go @@ -8,6 +8,7 @@ import ( "github.com/docker/distribution/reference" "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/registry" "github.com/docker/docker/api/types/swarm" "github.com/opencontainers/go-digest" "github.com/pkg/errors" @@ -21,7 +22,7 @@ func (cli *Client) ServiceCreate(ctx context.Context, service swarm.ServiceSpec, } if options.EncodedRegistryAuth != "" { - headers["X-Registry-Auth"] = []string{options.EncodedRegistryAuth} + headers[registry.AuthHeader] = []string{options.EncodedRegistryAuth} } // Make sure containerSpec is not nil when no runtime is set or the runtime is set to container diff --git a/vendor/github.com/docker/docker/client/service_update.go b/vendor/github.com/docker/docker/client/service_update.go index 8014b862584..ff8cded8be3 100644 --- a/vendor/github.com/docker/docker/client/service_update.go +++ b/vendor/github.com/docker/docker/client/service_update.go @@ -6,6 +6,7 @@ import ( "net/url" "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/registry" "github.com/docker/docker/api/types/swarm" ) @@ -23,7 +24,7 @@ func (cli *Client) ServiceUpdate(ctx context.Context, serviceID string, version } if options.EncodedRegistryAuth != "" { - headers["X-Registry-Auth"] = []string{options.EncodedRegistryAuth} + headers[registry.AuthHeader] = []string{options.EncodedRegistryAuth} } if options.RegistryAuthFrom != "" { diff --git a/vendor/github.com/docker/docker/client/volume_list.go b/vendor/github.com/docker/docker/client/volume_list.go index d8204f8db5d..d5ea9827c72 100644 --- a/vendor/github.com/docker/docker/client/volume_list.go +++ b/vendor/github.com/docker/docker/client/volume_list.go @@ -10,13 +10,13 @@ import ( ) // VolumeList returns the volumes configured in the docker host. -func (cli *Client) VolumeList(ctx context.Context, filter filters.Args) (volume.ListResponse, error) { +func (cli *Client) VolumeList(ctx context.Context, options volume.ListOptions) (volume.ListResponse, error) { var volumes volume.ListResponse query := url.Values{} - if filter.Len() > 0 { + if options.Filters.Len() > 0 { //nolint:staticcheck // ignore SA1019 for old code - filterJSON, err := filters.ToParamWithVersion(cli.version, filter) + filterJSON, err := filters.ToParamWithVersion(cli.version, options.Filters) if err != nil { return volumes, err } diff --git a/vendor/github.com/envoyproxy/protoc-gen-validate/NOTICE b/vendor/github.com/envoyproxy/protoc-gen-validate/NOTICE deleted file mode 100644 index 60884a05905..00000000000 --- a/vendor/github.com/envoyproxy/protoc-gen-validate/NOTICE +++ /dev/null @@ -1,4 +0,0 @@ -protoc-gen-validate -Copyright 2019 Envoy Project Authors - -Licensed under Apache License 2.0. See LICENSE for terms. diff --git a/vendor/github.com/go-logr/logr/.golangci.yaml b/vendor/github.com/go-logr/logr/.golangci.yaml index 94ff801df1a..0cffafa7bf9 100644 --- a/vendor/github.com/go-logr/logr/.golangci.yaml +++ b/vendor/github.com/go-logr/logr/.golangci.yaml @@ -6,7 +6,6 @@ linters: disable-all: true enable: - asciicheck - - deadcode - errcheck - forcetypeassert - gocritic @@ -18,10 +17,8 @@ linters: - misspell - revive - staticcheck - - structcheck - typecheck - unused - - varcheck issues: exclude-use-default: false diff --git a/vendor/github.com/go-logr/logr/discard.go b/vendor/github.com/go-logr/logr/discard.go index 9d92a38f1d7..99fe8be93c1 100644 --- a/vendor/github.com/go-logr/logr/discard.go +++ b/vendor/github.com/go-logr/logr/discard.go @@ -20,35 +20,5 @@ package logr // used whenever the caller is not interested in the logs. Logger instances // produced by this function always compare as equal. func Discard() Logger { - return Logger{ - level: 0, - sink: discardLogSink{}, - } -} - -// discardLogSink is a LogSink that discards all messages. -type discardLogSink struct{} - -// Verify that it actually implements the interface -var _ LogSink = discardLogSink{} - -func (l discardLogSink) Init(RuntimeInfo) { -} - -func (l discardLogSink) Enabled(int) bool { - return false -} - -func (l discardLogSink) Info(int, string, ...interface{}) { -} - -func (l discardLogSink) Error(error, string, ...interface{}) { -} - -func (l discardLogSink) WithValues(...interface{}) LogSink { - return l -} - -func (l discardLogSink) WithName(string) LogSink { - return l + return New(nil) } diff --git a/vendor/github.com/go-logr/logr/funcr/funcr.go b/vendor/github.com/go-logr/logr/funcr/funcr.go index 7accdb0c400..e52f0cd01e2 100644 --- a/vendor/github.com/go-logr/logr/funcr/funcr.go +++ b/vendor/github.com/go-logr/logr/funcr/funcr.go @@ -21,13 +21,13 @@ limitations under the License. // github.com/go-logr/logr.LogSink with output through an arbitrary // "write" function. See New and NewJSON for details. // -// Custom LogSinks +// # Custom LogSinks // // For users who need more control, a funcr.Formatter can be embedded inside // your own custom LogSink implementation. This is useful when the LogSink // needs to implement additional methods, for example. // -// Formatting +// # Formatting // // This will respect logr.Marshaler, fmt.Stringer, and error interfaces for // values which are being logged. When rendering a struct, funcr will use Go's @@ -37,6 +37,7 @@ package funcr import ( "bytes" "encoding" + "encoding/json" "fmt" "path/filepath" "reflect" @@ -217,7 +218,7 @@ func newFormatter(opts Options, outfmt outputFormat) Formatter { prefix: "", values: nil, depth: 0, - opts: opts, + opts: &opts, } return f } @@ -231,7 +232,7 @@ type Formatter struct { values []interface{} valuesStr string depth int - opts Options + opts *Options } // outputFormat indicates which outputFormat to use. @@ -447,6 +448,7 @@ func (f Formatter) prettyWithFlags(value interface{}, flags uint32, depth int) s if flags&flagRawStruct == 0 { buf.WriteByte('{') } + printComma := false // testing i>0 is not enough because of JSON omitted fields for i := 0; i < t.NumField(); i++ { fld := t.Field(i) if fld.PkgPath != "" { @@ -478,9 +480,10 @@ func (f Formatter) prettyWithFlags(value interface{}, flags uint32, depth int) s if omitempty && isEmpty(v.Field(i)) { continue } - if i > 0 { + if printComma { buf.WriteByte(',') } + printComma = true // if we got here, we are rendering a field if fld.Anonymous && fld.Type.Kind() == reflect.Struct && name == "" { buf.WriteString(f.prettyWithFlags(v.Field(i).Interface(), flags|flagRawStruct, depth+1)) continue @@ -500,6 +503,20 @@ func (f Formatter) prettyWithFlags(value interface{}, flags uint32, depth int) s } return buf.String() case reflect.Slice, reflect.Array: + // If this is outputing as JSON make sure this isn't really a json.RawMessage. + // If so just emit "as-is" and don't pretty it as that will just print + // it as [X,Y,Z,...] which isn't terribly useful vs the string form you really want. + if f.outputFormat == outputJSON { + if rm, ok := value.(json.RawMessage); ok { + // If it's empty make sure we emit an empty value as the array style would below. + if len(rm) > 0 { + buf.Write(rm) + } else { + buf.WriteString("null") + } + return buf.String() + } + } buf.WriteByte('[') for i := 0; i < v.Len(); i++ { if i > 0 { diff --git a/vendor/github.com/go-logr/logr/logr.go b/vendor/github.com/go-logr/logr/logr.go index c3b56b3d2c5..e027aea3fd3 100644 --- a/vendor/github.com/go-logr/logr/logr.go +++ b/vendor/github.com/go-logr/logr/logr.go @@ -21,7 +21,7 @@ limitations under the License. // to back that API. Packages in the Go ecosystem can depend on this package, // while callers can implement logging with whatever backend is appropriate. // -// Usage +// # Usage // // Logging is done using a Logger instance. Logger is a concrete type with // methods, which defers the actual logging to a LogSink interface. The main @@ -30,16 +30,20 @@ limitations under the License. // "structured logging". // // With Go's standard log package, we might write: -// log.Printf("setting target value %s", targetValue) +// +// log.Printf("setting target value %s", targetValue) // // With logr's structured logging, we'd write: -// logger.Info("setting target", "value", targetValue) +// +// logger.Info("setting target", "value", targetValue) // // Errors are much the same. Instead of: -// log.Printf("failed to open the pod bay door for user %s: %v", user, err) +// +// log.Printf("failed to open the pod bay door for user %s: %v", user, err) // // We'd write: -// logger.Error(err, "failed to open the pod bay door", "user", user) +// +// logger.Error(err, "failed to open the pod bay door", "user", user) // // Info() and Error() are very similar, but they are separate methods so that // LogSink implementations can choose to do things like attach additional @@ -47,7 +51,7 @@ limitations under the License. // always logged, regardless of the current verbosity. If there is no error // instance available, passing nil is valid. // -// Verbosity +// # Verbosity // // Often we want to log information only when the application in "verbose // mode". To write log lines that are more verbose, Logger has a V() method. @@ -58,20 +62,22 @@ limitations under the License. // Error messages do not have a verbosity level and are always logged. // // Where we might have written: -// if flVerbose >= 2 { -// log.Printf("an unusual thing happened") -// } +// +// if flVerbose >= 2 { +// log.Printf("an unusual thing happened") +// } // // We can write: -// logger.V(2).Info("an unusual thing happened") // -// Logger Names +// logger.V(2).Info("an unusual thing happened") +// +// # Logger Names // // Logger instances can have name strings so that all messages logged through // that instance have additional context. For example, you might want to add // a subsystem name: // -// logger.WithName("compactor").Info("started", "time", time.Now()) +// logger.WithName("compactor").Info("started", "time", time.Now()) // // The WithName() method returns a new Logger, which can be passed to // constructors or other functions for further use. Repeated use of WithName() @@ -82,25 +88,27 @@ limitations under the License. // joining operation (e.g. whitespace, commas, periods, slashes, brackets, // quotes, etc). // -// Saved Values +// # Saved Values // // Logger instances can store any number of key/value pairs, which will be // logged alongside all messages logged through that instance. For example, // you might want to create a Logger instance per managed object: // // With the standard log package, we might write: -// log.Printf("decided to set field foo to value %q for object %s/%s", -// targetValue, object.Namespace, object.Name) +// +// log.Printf("decided to set field foo to value %q for object %s/%s", +// targetValue, object.Namespace, object.Name) // // With logr we'd write: -// // Elsewhere: set up the logger to log the object name. -// obj.logger = mainLogger.WithValues( -// "name", obj.name, "namespace", obj.namespace) // -// // later on... -// obj.logger.Info("setting foo", "value", targetValue) +// // Elsewhere: set up the logger to log the object name. +// obj.logger = mainLogger.WithValues( +// "name", obj.name, "namespace", obj.namespace) +// +// // later on... +// obj.logger.Info("setting foo", "value", targetValue) // -// Best Practices +// # Best Practices // // Logger has very few hard rules, with the goal that LogSink implementations // might have a lot of freedom to differentiate. There are, however, some @@ -124,15 +132,15 @@ limitations under the License. // around. For cases where passing a logger is optional, a pointer to Logger // should be used. // -// Key Naming Conventions +// # Key Naming Conventions // // Keys are not strictly required to conform to any specification or regex, but // it is recommended that they: -// * be human-readable and meaningful (not auto-generated or simple ordinals) -// * be constant (not dependent on input data) -// * contain only printable characters -// * not contain whitespace or punctuation -// * use lower case for simple keys and lowerCamelCase for more complex ones +// - be human-readable and meaningful (not auto-generated or simple ordinals) +// - be constant (not dependent on input data) +// - contain only printable characters +// - not contain whitespace or punctuation +// - use lower case for simple keys and lowerCamelCase for more complex ones // // These guidelines help ensure that log data is processed properly regardless // of the log implementation. For example, log implementations will try to @@ -141,51 +149,54 @@ limitations under the License. // While users are generally free to use key names of their choice, it's // generally best to avoid using the following keys, as they're frequently used // by implementations: -// * "caller": the calling information (file/line) of a particular log line -// * "error": the underlying error value in the `Error` method -// * "level": the log level -// * "logger": the name of the associated logger -// * "msg": the log message -// * "stacktrace": the stack trace associated with a particular log line or -// error (often from the `Error` message) -// * "ts": the timestamp for a log line +// - "caller": the calling information (file/line) of a particular log line +// - "error": the underlying error value in the `Error` method +// - "level": the log level +// - "logger": the name of the associated logger +// - "msg": the log message +// - "stacktrace": the stack trace associated with a particular log line or +// error (often from the `Error` message) +// - "ts": the timestamp for a log line // // Implementations are encouraged to make use of these keys to represent the // above concepts, when necessary (for example, in a pure-JSON output form, it // would be necessary to represent at least message and timestamp as ordinary // named values). // -// Break Glass +// # Break Glass // // Implementations may choose to give callers access to the underlying // logging implementation. The recommended pattern for this is: -// // Underlier exposes access to the underlying logging implementation. -// // Since callers only have a logr.Logger, they have to know which -// // implementation is in use, so this interface is less of an abstraction -// // and more of way to test type conversion. -// type Underlier interface { -// GetUnderlying() -// } +// +// // Underlier exposes access to the underlying logging implementation. +// // Since callers only have a logr.Logger, they have to know which +// // implementation is in use, so this interface is less of an abstraction +// // and more of way to test type conversion. +// type Underlier interface { +// GetUnderlying() +// } // // Logger grants access to the sink to enable type assertions like this: -// func DoSomethingWithImpl(log logr.Logger) { -// if underlier, ok := log.GetSink()(impl.Underlier) { -// implLogger := underlier.GetUnderlying() -// ... -// } -// } +// +// func DoSomethingWithImpl(log logr.Logger) { +// if underlier, ok := log.GetSink().(impl.Underlier); ok { +// implLogger := underlier.GetUnderlying() +// ... +// } +// } // // Custom `With*` functions can be implemented by copying the complete // Logger struct and replacing the sink in the copy: -// // WithFooBar changes the foobar parameter in the log sink and returns a -// // new logger with that modified sink. It does nothing for loggers where -// // the sink doesn't support that parameter. -// func WithFoobar(log logr.Logger, foobar int) logr.Logger { -// if foobarLogSink, ok := log.GetSink()(FoobarSink); ok { -// log = log.WithSink(foobarLogSink.WithFooBar(foobar)) -// } -// return log -// } +// +// // WithFooBar changes the foobar parameter in the log sink and returns a +// // new logger with that modified sink. It does nothing for loggers where +// // the sink doesn't support that parameter. +// func WithFoobar(log logr.Logger, foobar int) logr.Logger { +// if foobarLogSink, ok := log.GetSink().(FoobarSink); ok { +// log = log.WithSink(foobarLogSink.WithFooBar(foobar)) +// } +// return log +// } // // Don't use New to construct a new Logger with a LogSink retrieved from an // existing Logger. Source code attribution might not work correctly and @@ -201,11 +212,14 @@ import ( ) // New returns a new Logger instance. This is primarily used by libraries -// implementing LogSink, rather than end users. +// implementing LogSink, rather than end users. Passing a nil sink will create +// a Logger which discards all log lines. func New(sink LogSink) Logger { logger := Logger{} logger.setSink(sink) - sink.Init(runtimeInfo) + if sink != nil { + sink.Init(runtimeInfo) + } return logger } @@ -244,7 +258,7 @@ type Logger struct { // Enabled tests whether this Logger is enabled. For example, commandline // flags might be used to set the logging verbosity and disable some info logs. func (l Logger) Enabled() bool { - return l.sink.Enabled(l.level) + return l.sink != nil && l.sink.Enabled(l.level) } // Info logs a non-error message with the given key/value pairs as context. @@ -254,6 +268,9 @@ func (l Logger) Enabled() bool { // information. The key/value pairs must alternate string keys and arbitrary // values. func (l Logger) Info(msg string, keysAndValues ...interface{}) { + if l.sink == nil { + return + } if l.Enabled() { if withHelper, ok := l.sink.(CallStackHelperLogSink); ok { withHelper.GetCallStackHelper()() @@ -273,6 +290,9 @@ func (l Logger) Info(msg string, keysAndValues ...interface{}) { // triggered this log line, if present. The err parameter is optional // and nil may be passed instead of an error instance. func (l Logger) Error(err error, msg string, keysAndValues ...interface{}) { + if l.sink == nil { + return + } if withHelper, ok := l.sink.(CallStackHelperLogSink); ok { withHelper.GetCallStackHelper()() } @@ -284,6 +304,9 @@ func (l Logger) Error(err error, msg string, keysAndValues ...interface{}) { // level means a log message is less important. Negative V-levels are treated // as 0. func (l Logger) V(level int) Logger { + if l.sink == nil { + return l + } if level < 0 { level = 0 } @@ -294,6 +317,9 @@ func (l Logger) V(level int) Logger { // WithValues returns a new Logger instance with additional key/value pairs. // See Info for documentation on how key/value pairs work. func (l Logger) WithValues(keysAndValues ...interface{}) Logger { + if l.sink == nil { + return l + } l.setSink(l.sink.WithValues(keysAndValues...)) return l } @@ -304,6 +330,9 @@ func (l Logger) WithValues(keysAndValues ...interface{}) Logger { // contain only letters, digits, and hyphens (see the package documentation for // more information). func (l Logger) WithName(name string) Logger { + if l.sink == nil { + return l + } l.setSink(l.sink.WithName(name)) return l } @@ -324,6 +353,9 @@ func (l Logger) WithName(name string) Logger { // WithCallDepth(1) because it works with implementions that support the // CallDepthLogSink and/or CallStackHelperLogSink interfaces. func (l Logger) WithCallDepth(depth int) Logger { + if l.sink == nil { + return l + } if withCallDepth, ok := l.sink.(CallDepthLogSink); ok { l.setSink(withCallDepth.WithCallDepth(depth)) } @@ -345,6 +377,9 @@ func (l Logger) WithCallDepth(depth int) Logger { // implementation does not support either of these, the original Logger will be // returned. func (l Logger) WithCallStackHelper() (func(), Logger) { + if l.sink == nil { + return func() {}, l + } var helper func() if withCallDepth, ok := l.sink.(CallDepthLogSink); ok { l.setSink(withCallDepth.WithCallDepth(1)) @@ -357,6 +392,11 @@ func (l Logger) WithCallStackHelper() (func(), Logger) { return helper, l } +// IsZero returns true if this logger is an uninitialized zero value +func (l Logger) IsZero() bool { + return l.sink == nil +} + // contextKey is how we find Loggers in a context.Context. type contextKey struct{} @@ -442,7 +482,7 @@ type LogSink interface { WithName(name string) LogSink } -// CallDepthLogSink represents a Logger that knows how to climb the call stack +// CallDepthLogSink represents a LogSink that knows how to climb the call stack // to identify the original call site and can offset the depth by a specified // number of frames. This is useful for users who have helper functions // between the "real" call site and the actual calls to Logger methods. @@ -467,7 +507,7 @@ type CallDepthLogSink interface { WithCallDepth(depth int) LogSink } -// CallStackHelperLogSink represents a Logger that knows how to climb +// CallStackHelperLogSink represents a LogSink that knows how to climb // the call stack to identify the original call site and can skip // intermediate helper functions if they mark themselves as // helper. Go's testing package uses that approach. diff --git a/vendor/github.com/golang/glog/glog.go b/vendor/github.com/golang/glog/glog.go index 718c34f886e..e108ae8b4f8 100644 --- a/vendor/github.com/golang/glog/glog.go +++ b/vendor/github.com/golang/glog/glog.go @@ -1,6 +1,6 @@ -// Go support for leveled logs, analogous to https://code.google.com/p/google-glog/ +// Go support for leveled logs, analogous to https://github.com/google/glog. // -// Copyright 2013 Google Inc. All Rights Reserved. +// Copyright 2023 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -50,15 +50,15 @@ // Log files will be written to this directory instead of the // default temporary directory. // -// Other flags provide aids to debugging. +// Other flags provide aids to debugging. // // -log_backtrace_at="" -// When set to a file and line number holding a logging statement, -// such as +// A comma-separated list of file and line numbers holding a logging +// statement, such as // -log_backtrace_at=gopherflakes.go:234 -// a stack trace will be written to the Info log whenever execution -// hits that statement. (Unlike with -vmodule, the ".go" must be -// present.) +// A stack trace will be written to the Info log whenever execution +// hits one of these statements. (Unlike with -vmodule, the ".go" +// must bepresent.) // -v=0 // Enable V-leveled logging at the specified level. // -vmodule="" @@ -66,100 +66,47 @@ // where pattern is a literal file name (minus the ".go" suffix) or // "glob" pattern and N is a V level. For instance, // -vmodule=gopher*=3 -// sets the V level to 3 in all Go files whose names begin "gopher". -// +// sets the V level to 3 in all Go files whose names begin with "gopher", +// and +// -vmodule=/path/to/glog/glog_test=1 +// sets the V level to 1 in the Go file /path/to/glog/glog_test.go. +// If a glob pattern contains a slash, it is matched against the full path, +// and the file name. Otherwise, the pattern is +// matched only against the file's basename. When both -vmodule and -v +// are specified, the -vmodule values take precedence for the specified +// modules. package glog +// This file contains the parts of the log package that are shared among all +// implementations (file, envelope, and appengine). + import ( - "bufio" "bytes" "errors" - "flag" "fmt" - "io" stdLog "log" "os" - "path/filepath" + "reflect" "runtime" + "runtime/pprof" "strconv" - "strings" "sync" "sync/atomic" + "syscall" "time" -) - -// severity identifies the sort of log: info, warning etc. It also implements -// the flag.Value interface. The -stderrthreshold flag is of type severity and -// should be modified only through the flag.Value interface. The values match -// the corresponding constants in C++. -type severity int32 // sync/atomic int32 -// These constants identify the log levels in order of increasing severity. -// A message written to a high-severity log file is also written to each -// lower-severity log file. -const ( - infoLog severity = iota - warningLog - errorLog - fatalLog - numSeverity = 4 + "github.com/golang/glog/internal/logsink" + "github.com/golang/glog/internal/stackdump" ) -const severityChar = "IWEF" - -var severityName = []string{ - infoLog: "INFO", - warningLog: "WARNING", - errorLog: "ERROR", - fatalLog: "FATAL", -} - -// get returns the value of the severity. -func (s *severity) get() severity { - return severity(atomic.LoadInt32((*int32)(s))) -} - -// set sets the value of the severity. -func (s *severity) set(val severity) { - atomic.StoreInt32((*int32)(s), int32(val)) -} - -// String is part of the flag.Value interface. -func (s *severity) String() string { - return strconv.FormatInt(int64(*s), 10) -} - -// Get is part of the flag.Value interface. -func (s *severity) Get() interface{} { - return *s -} +var timeNow = time.Now // Stubbed out for testing. -// Set is part of the flag.Value interface. -func (s *severity) Set(value string) error { - var threshold severity - // Is it a known name? - if v, ok := severityByName(value); ok { - threshold = v - } else { - v, err := strconv.Atoi(value) - if err != nil { - return err - } - threshold = severity(v) - } - logging.stderrThreshold.set(threshold) - return nil -} +// MaxSize is the maximum size of a log file in bytes. +var MaxSize uint64 = 1024 * 1024 * 1800 -func severityByName(s string) (severity, bool) { - s = strings.ToUpper(s) - for i, name := range severityName { - if name == s { - return severity(i), true - } - } - return 0, false -} +// ErrNoLog is the error we return if no log file has yet been created +// for the specified log type. +var ErrNoLog = errors.New("log file not yet created") // OutputStats tracks the number of output lines and bytes written. type OutputStats struct { @@ -183,724 +130,99 @@ var Stats struct { Info, Warning, Error OutputStats } -var severityStats = [numSeverity]*OutputStats{ - infoLog: &Stats.Info, - warningLog: &Stats.Warning, - errorLog: &Stats.Error, +var severityStats = [...]*OutputStats{ + logsink.Info: &Stats.Info, + logsink.Warning: &Stats.Warning, + logsink.Error: &Stats.Error, + logsink.Fatal: nil, } -// Level is exported because it appears in the arguments to V and is -// the type of the v flag, which can be set programmatically. -// It's a distinct type because we want to discriminate it from logType. -// Variables of type level are only changed under logging.mu. -// The -v flag is read only with atomic ops, so the state of the logging -// module is consistent. - -// Level is treated as a sync/atomic int32. - -// Level specifies a level of verbosity for V logs. *Level implements -// flag.Value; the -v flag is of type Level and should be modified -// only through the flag.Value interface. +// Level specifies a level of verbosity for V logs. The -v flag is of type +// Level and should be modified only through the flag.Value interface. type Level int32 -// get returns the value of the Level. -func (l *Level) get() Level { - return Level(atomic.LoadInt32((*int32)(l))) -} - -// set sets the value of the Level. -func (l *Level) set(val Level) { - atomic.StoreInt32((*int32)(l), int32(val)) -} - -// String is part of the flag.Value interface. -func (l *Level) String() string { - return strconv.FormatInt(int64(*l), 10) -} +var metaPool sync.Pool // Pool of *logsink.Meta. -// Get is part of the flag.Value interface. -func (l *Level) Get() interface{} { - return *l -} - -// Set is part of the flag.Value interface. -func (l *Level) Set(value string) error { - v, err := strconv.Atoi(value) - if err != nil { - return err - } - logging.mu.Lock() - defer logging.mu.Unlock() - logging.setVState(Level(v), logging.vmodule.filter, false) - return nil -} - -// moduleSpec represents the setting of the -vmodule flag. -type moduleSpec struct { - filter []modulePat -} - -// modulePat contains a filter for the -vmodule flag. -// It holds a verbosity level and a file pattern to match. -type modulePat struct { - pattern string - literal bool // The pattern is a literal string - level Level -} - -// match reports whether the file matches the pattern. It uses a string -// comparison if the pattern contains no metacharacters. -func (m *modulePat) match(file string) bool { - if m.literal { - return file == m.pattern - } - match, _ := filepath.Match(m.pattern, file) - return match -} - -func (m *moduleSpec) String() string { - // Lock because the type is not atomic. TODO: clean this up. - logging.mu.Lock() - defer logging.mu.Unlock() - var b bytes.Buffer - for i, f := range m.filter { - if i > 0 { - b.WriteRune(',') - } - fmt.Fprintf(&b, "%s=%d", f.pattern, f.level) +// metaPoolGet returns a *logsink.Meta from metaPool as both an interface and a +// pointer, allocating a new one if necessary. (Returning the interface value +// directly avoids an allocation if there was an existing pointer in the pool.) +func metaPoolGet() (any, *logsink.Meta) { + if metai := metaPool.Get(); metai != nil { + return metai, metai.(*logsink.Meta) } - return b.String() -} - -// Get is part of the (Go 1.2) flag.Getter interface. It always returns nil for this flag type since the -// struct is not exported. -func (m *moduleSpec) Get() interface{} { - return nil + meta := new(logsink.Meta) + return meta, meta } -var errVmoduleSyntax = errors.New("syntax error: expect comma-separated list of filename=N") - -// Syntax: -vmodule=recordio=2,file=1,gfs*=3 -func (m *moduleSpec) Set(value string) error { - var filter []modulePat - for _, pat := range strings.Split(value, ",") { - if len(pat) == 0 { - // Empty strings such as from a trailing comma can be ignored. - continue - } - patLev := strings.Split(pat, "=") - if len(patLev) != 2 || len(patLev[0]) == 0 || len(patLev[1]) == 0 { - return errVmoduleSyntax - } - pattern := patLev[0] - v, err := strconv.Atoi(patLev[1]) - if err != nil { - return errors.New("syntax error: expect comma-separated list of filename=N") - } - if v < 0 { - return errors.New("negative value for vmodule level") - } - if v == 0 { - continue // Ignore. It's harmless but no point in paying the overhead. - } - // TODO: check syntax of filter? - filter = append(filter, modulePat{pattern, isLiteral(pattern), Level(v)}) - } - logging.mu.Lock() - defer logging.mu.Unlock() - logging.setVState(logging.verbosity, filter, true) - return nil -} - -// isLiteral reports whether the pattern is a literal string, that is, has no metacharacters -// that require filepath.Match to be called to match the pattern. -func isLiteral(pattern string) bool { - return !strings.ContainsAny(pattern, `\*?[]`) -} - -// traceLocation represents the setting of the -log_backtrace_at flag. -type traceLocation struct { - file string - line int -} - -// isSet reports whether the trace location has been specified. -// logging.mu is held. -func (t *traceLocation) isSet() bool { - return t.line > 0 -} +type stack bool -// match reports whether the specified file and line matches the trace location. -// The argument file name is the full path, not the basename specified in the flag. -// logging.mu is held. -func (t *traceLocation) match(file string, line int) bool { - if t.line != line { - return false - } - if i := strings.LastIndex(file, "/"); i >= 0 { - file = file[i+1:] - } - return t.file == file -} - -func (t *traceLocation) String() string { - // Lock because the type is not atomic. TODO: clean this up. - logging.mu.Lock() - defer logging.mu.Unlock() - return fmt.Sprintf("%s:%d", t.file, t.line) -} - -// Get is part of the (Go 1.2) flag.Getter interface. It always returns nil for this flag type since the -// struct is not exported -func (t *traceLocation) Get() interface{} { - return nil -} - -var errTraceSyntax = errors.New("syntax error: expect file.go:234") - -// Syntax: -log_backtrace_at=gopherflakes.go:234 -// Note that unlike vmodule the file extension is included here. -func (t *traceLocation) Set(value string) error { - if value == "" { - // Unset. - t.line = 0 - t.file = "" - } - fields := strings.Split(value, ":") - if len(fields) != 2 { - return errTraceSyntax - } - file, line := fields[0], fields[1] - if !strings.Contains(file, ".") { - return errTraceSyntax - } - v, err := strconv.Atoi(line) - if err != nil { - return errTraceSyntax - } - if v <= 0 { - return errors.New("negative or zero value for level") - } - logging.mu.Lock() - defer logging.mu.Unlock() - t.line = v - t.file = file - return nil -} - -// flushSyncWriter is the interface satisfied by logging destinations. -type flushSyncWriter interface { - Flush() error - Sync() error - io.Writer -} - -func init() { - flag.BoolVar(&logging.toStderr, "logtostderr", false, "log to standard error instead of files") - flag.BoolVar(&logging.alsoToStderr, "alsologtostderr", false, "log to standard error as well as files") - flag.Var(&logging.verbosity, "v", "log level for V logs") - flag.Var(&logging.stderrThreshold, "stderrthreshold", "logs at or above this threshold go to stderr") - flag.Var(&logging.vmodule, "vmodule", "comma-separated list of pattern=N settings for file-filtered logging") - flag.Var(&logging.traceLocation, "log_backtrace_at", "when logging hits line file:N, emit a stack trace") - - // Default stderrThreshold is ERROR. - logging.stderrThreshold = errorLog - - logging.setVState(0, nil, false) - go logging.flushDaemon() -} - -// Flush flushes all pending log I/O. -func Flush() { - logging.lockAndFlushAll() -} - -// loggingT collects all the global state of the logging setup. -type loggingT struct { - // Boolean flags. Not handled atomically because the flag.Value interface - // does not let us avoid the =true, and that shorthand is necessary for - // compatibility. TODO: does this matter enough to fix? Seems unlikely. - toStderr bool // The -logtostderr flag. - alsoToStderr bool // The -alsologtostderr flag. - - // Level flag. Handled atomically. - stderrThreshold severity // The -stderrthreshold flag. - - // freeList is a list of byte buffers, maintained under freeListMu. - freeList *buffer - // freeListMu maintains the free list. It is separate from the main mutex - // so buffers can be grabbed and printed to without holding the main lock, - // for better parallelization. - freeListMu sync.Mutex - - // mu protects the remaining elements of this structure and is - // used to synchronize logging. - mu sync.Mutex - // file holds writer for each of the log types. - file [numSeverity]flushSyncWriter - // pcs is used in V to avoid an allocation when computing the caller's PC. - pcs [1]uintptr - // vmap is a cache of the V Level for each V() call site, identified by PC. - // It is wiped whenever the vmodule flag changes state. - vmap map[uintptr]Level - // filterLength stores the length of the vmodule filter chain. If greater - // than zero, it means vmodule is enabled. It may be read safely - // using sync.LoadInt32, but is only modified under mu. - filterLength int32 - // traceLocation is the state of the -log_backtrace_at flag. - traceLocation traceLocation - // These flags are modified only under lock, although verbosity may be fetched - // safely using atomic.LoadInt32. - vmodule moduleSpec // The state of the -vmodule flag. - verbosity Level // V logging level, the value of the -v flag/ -} - -// buffer holds a byte Buffer for reuse. The zero value is ready for use. -type buffer struct { - bytes.Buffer - tmp [64]byte // temporary byte array for creating headers. - next *buffer -} - -var logging loggingT - -// setVState sets a consistent state for V logging. -// l.mu is held. -func (l *loggingT) setVState(verbosity Level, filter []modulePat, setFilter bool) { - // Turn verbosity off so V will not fire while we are in transition. - logging.verbosity.set(0) - // Ditto for filter length. - atomic.StoreInt32(&logging.filterLength, 0) - - // Set the new filters and wipe the pc->Level map if the filter has changed. - if setFilter { - logging.vmodule.filter = filter - logging.vmap = make(map[uintptr]Level) - } - - // Things are consistent now, so enable filtering and verbosity. - // They are enabled in order opposite to that in V. - atomic.StoreInt32(&logging.filterLength, int32(len(filter))) - logging.verbosity.set(verbosity) -} - -// getBuffer returns a new, ready-to-use buffer. -func (l *loggingT) getBuffer() *buffer { - l.freeListMu.Lock() - b := l.freeList - if b != nil { - l.freeList = b.next - } - l.freeListMu.Unlock() - if b == nil { - b = new(buffer) - } else { - b.next = nil - b.Reset() - } - return b -} - -// putBuffer returns a buffer to the free list. -func (l *loggingT) putBuffer(b *buffer) { - if b.Len() >= 256 { - // Let big buffers die a natural death. - return - } - l.freeListMu.Lock() - b.next = l.freeList - l.freeList = b - l.freeListMu.Unlock() -} - -var timeNow = time.Now // Stubbed out for testing. +const ( + noStack = stack(false) + withStack = stack(true) +) -/* -header formats a log header as defined by the C++ implementation. -It returns a buffer containing the formatted header and the user's file and line number. -The depth specifies how many stack frames above lives the source line to be identified in the log message. - -Log lines have this form: - Lmmdd hh:mm:ss.uuuuuu threadid file:line] msg... -where the fields are defined as follows: - L A single character, representing the log level (eg 'I' for INFO) - mm The month (zero padded; ie May is '05') - dd The day (zero padded) - hh:mm:ss.uuuuuu Time in hours, minutes and fractional seconds - threadid The space-padded thread ID as returned by GetTID() - file The file name - line The line number - msg The user-supplied message -*/ -func (l *loggingT) header(s severity, depth int) (*buffer, string, int) { - _, file, line, ok := runtime.Caller(3 + depth) +func appendBacktrace(depth int, format string, args []any) (string, []any) { + // Capture a backtrace as a stackdump.Stack (both text and PC slice). + // Structured log sinks can extract the backtrace in whichever format they + // prefer (PCs or text), and Text sinks will include it as just another part + // of the log message. + // + // Use depth instead of depth+1 so that the backtrace always includes the + // log function itself - otherwise the reason for the trace appearing in the + // log may not be obvious to the reader. + dump := stackdump.Caller(depth) + + // Add an arg and an entry in the format string for the stack dump. + // + // Copy the "args" slice to avoid a rare but serious aliasing bug + // (corrupting the caller's slice if they passed it to a non-Fatal call + // using "..."). + format = format + "\n\n%v\n" + args = append(append([]any(nil), args...), dump) + + return format, args +} + +// logf writes a log message for a log function call (or log function wrapper) +// at the given depth in the current goroutine's stack. +func logf(depth int, severity logsink.Severity, verbose bool, stack stack, format string, args ...any) { + now := timeNow() + _, file, line, ok := runtime.Caller(depth + 1) if !ok { file = "???" line = 1 - } else { - slash := strings.LastIndex(file, "/") - if slash >= 0 { - file = file[slash+1:] - } } - return l.formatHeader(s, file, line), file, line -} -// formatHeader formats a log header using the provided file name and line number. -func (l *loggingT) formatHeader(s severity, file string, line int) *buffer { - now := timeNow() - if line < 0 { - line = 0 // not a real line number, but acceptable to someDigits + if stack == withStack || backtraceAt(file, line) { + format, args = appendBacktrace(depth+1, format, args) } - if s > fatalLog { - s = infoLog // for safety. - } - buf := l.getBuffer() - - // Avoid Fprintf, for speed. The format is so simple that we can do it quickly by hand. - // It's worth about 3X. Fprintf is hard. - _, month, day := now.Date() - hour, minute, second := now.Clock() - // Lmmdd hh:mm:ss.uuuuuu threadid file:line] - buf.tmp[0] = severityChar[s] - buf.twoDigits(1, int(month)) - buf.twoDigits(3, day) - buf.tmp[5] = ' ' - buf.twoDigits(6, hour) - buf.tmp[8] = ':' - buf.twoDigits(9, minute) - buf.tmp[11] = ':' - buf.twoDigits(12, second) - buf.tmp[14] = '.' - buf.nDigits(6, 15, now.Nanosecond()/1000, '0') - buf.tmp[21] = ' ' - buf.nDigits(7, 22, pid, ' ') // TODO: should be TID - buf.tmp[29] = ' ' - buf.Write(buf.tmp[:30]) - buf.WriteString(file) - buf.tmp[0] = ':' - n := buf.someDigits(1, line) - buf.tmp[n+1] = ']' - buf.tmp[n+2] = ' ' - buf.Write(buf.tmp[:n+3]) - return buf -} - -// Some custom tiny helper functions to print the log header efficiently. - -const digits = "0123456789" -// twoDigits formats a zero-prefixed two-digit integer at buf.tmp[i]. -func (buf *buffer) twoDigits(i, d int) { - buf.tmp[i+1] = digits[d%10] - d /= 10 - buf.tmp[i] = digits[d%10] -} - -// nDigits formats an n-digit integer at buf.tmp[i], -// padding with pad on the left. -// It assumes d >= 0. -func (buf *buffer) nDigits(n, i, d int, pad byte) { - j := n - 1 - for ; j >= 0 && d > 0; j-- { - buf.tmp[i+j] = digits[d%10] - d /= 10 - } - for ; j >= 0; j-- { - buf.tmp[i+j] = pad - } -} - -// someDigits formats a zero-prefixed variable-width integer at buf.tmp[i]. -func (buf *buffer) someDigits(i, d int) int { - // Print into the top, then copy down. We know there's space for at least - // a 10-digit number. - j := len(buf.tmp) - for { - j-- - buf.tmp[j] = digits[d%10] - d /= 10 - if d == 0 { - break - } + metai, meta := metaPoolGet() + *meta = logsink.Meta{ + Time: now, + File: file, + Line: line, + Depth: depth + 1, + Severity: severity, + Verbose: verbose, + Thread: int64(pid), } - return copy(buf.tmp[i:], buf.tmp[j:]) + sinkf(meta, format, args...) + metaPool.Put(metai) } -func (l *loggingT) println(s severity, args ...interface{}) { - buf, file, line := l.header(s, 0) - fmt.Fprintln(buf, args...) - l.output(s, buf, file, line, false) -} - -func (l *loggingT) print(s severity, args ...interface{}) { - l.printDepth(s, 1, args...) -} - -func (l *loggingT) printDepth(s severity, depth int, args ...interface{}) { - buf, file, line := l.header(s, depth) - fmt.Fprint(buf, args...) - if buf.Bytes()[buf.Len()-1] != '\n' { - buf.WriteByte('\n') - } - l.output(s, buf, file, line, false) -} - -func (l *loggingT) printf(s severity, format string, args ...interface{}) { - buf, file, line := l.header(s, 0) - fmt.Fprintf(buf, format, args...) - if buf.Bytes()[buf.Len()-1] != '\n' { - buf.WriteByte('\n') - } - l.output(s, buf, file, line, false) -} - -// printWithFileLine behaves like print but uses the provided file and line number. If -// alsoLogToStderr is true, the log message always appears on standard error; it -// will also appear in the log file unless --logtostderr is set. -func (l *loggingT) printWithFileLine(s severity, file string, line int, alsoToStderr bool, args ...interface{}) { - buf := l.formatHeader(s, file, line) - fmt.Fprint(buf, args...) - if buf.Bytes()[buf.Len()-1] != '\n' { - buf.WriteByte('\n') - } - l.output(s, buf, file, line, alsoToStderr) -} - -// output writes the data to the log files and releases the buffer. -func (l *loggingT) output(s severity, buf *buffer, file string, line int, alsoToStderr bool) { - l.mu.Lock() - if l.traceLocation.isSet() { - if l.traceLocation.match(file, line) { - buf.Write(stacks(false)) - } - } - data := buf.Bytes() - if !flag.Parsed() { - os.Stderr.Write([]byte("ERROR: logging before flag.Parse: ")) - os.Stderr.Write(data) - } else if l.toStderr { - os.Stderr.Write(data) - } else { - if alsoToStderr || l.alsoToStderr || s >= l.stderrThreshold.get() { - os.Stderr.Write(data) - } - if l.file[s] == nil { - if err := l.createFiles(s); err != nil { - os.Stderr.Write(data) // Make sure the message appears somewhere. - l.exit(err) - } - } - switch s { - case fatalLog: - l.file[fatalLog].Write(data) - fallthrough - case errorLog: - l.file[errorLog].Write(data) - fallthrough - case warningLog: - l.file[warningLog].Write(data) - fallthrough - case infoLog: - l.file[infoLog].Write(data) - } - } - if s == fatalLog { - // If we got here via Exit rather than Fatal, print no stacks. - if atomic.LoadUint32(&fatalNoStacks) > 0 { - l.mu.Unlock() - timeoutFlush(10 * time.Second) - os.Exit(1) - } - // Dump all goroutine stacks before exiting. - // First, make sure we see the trace for the current goroutine on standard error. - // If -logtostderr has been specified, the loop below will do that anyway - // as the first stack in the full dump. - if !l.toStderr { - os.Stderr.Write(stacks(false)) - } - // Write the stack trace for all goroutines to the files. - trace := stacks(true) - logExitFunc = func(error) {} // If we get a write error, we'll still exit below. - for log := fatalLog; log >= infoLog; log-- { - if f := l.file[log]; f != nil { // Can be nil if -logtostderr is set. - f.Write(trace) - } - } - l.mu.Unlock() - timeoutFlush(10 * time.Second) - os.Exit(255) // C++ uses -1, which is silly because it's anded with 255 anyway. - } - l.putBuffer(buf) - l.mu.Unlock() - if stats := severityStats[s]; stats != nil { +func sinkf(meta *logsink.Meta, format string, args ...any) { + meta.Depth++ + n, err := logsink.Printf(meta, format, args...) + if stats := severityStats[meta.Severity]; stats != nil { atomic.AddInt64(&stats.lines, 1) - atomic.AddInt64(&stats.bytes, int64(len(data))) - } -} - -// timeoutFlush calls Flush and returns when it completes or after timeout -// elapses, whichever happens first. This is needed because the hooks invoked -// by Flush may deadlock when glog.Fatal is called from a hook that holds -// a lock. -func timeoutFlush(timeout time.Duration) { - done := make(chan bool, 1) - go func() { - Flush() // calls logging.lockAndFlushAll() - done <- true - }() - select { - case <-done: - case <-time.After(timeout): - fmt.Fprintln(os.Stderr, "glog: Flush took longer than", timeout) - } -} - -// stacks is a wrapper for runtime.Stack that attempts to recover the data for all goroutines. -func stacks(all bool) []byte { - // We don't know how big the traces are, so grow a few times if they don't fit. Start large, though. - n := 10000 - if all { - n = 100000 - } - var trace []byte - for i := 0; i < 5; i++ { - trace = make([]byte, n) - nbytes := runtime.Stack(trace, all) - if nbytes < len(trace) { - return trace[:nbytes] - } - n *= 2 - } - return trace -} - -// logExitFunc provides a simple mechanism to override the default behavior -// of exiting on error. Used in testing and to guarantee we reach a required exit -// for fatal logs. Instead, exit could be a function rather than a method but that -// would make its use clumsier. -var logExitFunc func(error) - -// exit is called if there is trouble creating or writing log files. -// It flushes the logs and exits the program; there's no point in hanging around. -// l.mu is held. -func (l *loggingT) exit(err error) { - fmt.Fprintf(os.Stderr, "log: exiting because of error: %s\n", err) - // If logExitFunc is set, we do that instead of exiting. - if logExitFunc != nil { - logExitFunc(err) - return - } - l.flushAll() - os.Exit(2) -} - -// syncBuffer joins a bufio.Writer to its underlying file, providing access to the -// file's Sync method and providing a wrapper for the Write method that provides log -// file rotation. There are conflicting methods, so the file cannot be embedded. -// l.mu is held for all its methods. -type syncBuffer struct { - logger *loggingT - *bufio.Writer - file *os.File - sev severity - nbytes uint64 // The number of bytes written to this file -} - -func (sb *syncBuffer) Sync() error { - return sb.file.Sync() -} - -func (sb *syncBuffer) Write(p []byte) (n int, err error) { - if sb.nbytes+uint64(len(p)) >= MaxSize { - if err := sb.rotateFile(time.Now()); err != nil { - sb.logger.exit(err) - } + atomic.AddInt64(&stats.bytes, int64(n)) } - n, err = sb.Writer.Write(p) - sb.nbytes += uint64(n) - if err != nil { - sb.logger.exit(err) - } - return -} -// rotateFile closes the syncBuffer's file and starts a new one. -func (sb *syncBuffer) rotateFile(now time.Time) error { - if sb.file != nil { - sb.Flush() - sb.file.Close() - } - var err error - sb.file, _, err = create(severityName[sb.sev], now) - sb.nbytes = 0 if err != nil { - return err - } - - sb.Writer = bufio.NewWriterSize(sb.file, bufferSize) - - // Write header. - var buf bytes.Buffer - fmt.Fprintf(&buf, "Log file created at: %s\n", now.Format("2006/01/02 15:04:05")) - fmt.Fprintf(&buf, "Running on machine: %s\n", host) - fmt.Fprintf(&buf, "Binary: Built with %s %s for %s/%s\n", runtime.Compiler, runtime.Version(), runtime.GOOS, runtime.GOARCH) - fmt.Fprintf(&buf, "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu threadid file:line] msg\n") - n, err := sb.file.Write(buf.Bytes()) - sb.nbytes += uint64(n) - return err -} - -// bufferSize sizes the buffer associated with each log file. It's large -// so that log records can accumulate without the logging thread blocking -// on disk I/O. The flushDaemon will block instead. -const bufferSize = 256 * 1024 - -// createFiles creates all the log files for severity from sev down to infoLog. -// l.mu is held. -func (l *loggingT) createFiles(sev severity) error { - now := time.Now() - // Files are created in decreasing severity order, so as soon as we find one - // has already been created, we can stop. - for s := sev; s >= infoLog && l.file[s] == nil; s-- { - sb := &syncBuffer{ - logger: l, - sev: s, - } - if err := sb.rotateFile(now); err != nil { - return err - } - l.file[s] = sb - } - return nil -} - -const flushInterval = 30 * time.Second - -// flushDaemon periodically flushes the log file buffers. -func (l *loggingT) flushDaemon() { - for range time.NewTicker(flushInterval).C { - l.lockAndFlushAll() - } -} - -// lockAndFlushAll is like flushAll but locks l.mu first. -func (l *loggingT) lockAndFlushAll() { - l.mu.Lock() - l.flushAll() - l.mu.Unlock() -} - -// flushAll flushes all the logs and attempts to "sync" their data to disk. -// l.mu is held. -func (l *loggingT) flushAll() { - // Flush from fatal down, in case there's trouble flushing. - for s := fatalLog; s >= infoLog; s-- { - file := l.file[s] - if file != nil { - file.Flush() // ignore error - file.Sync() // ignore error - } + logsink.Printf(meta, "glog: exiting because of error: %s", err) + sinks.file.Flush() + os.Exit(2) } } @@ -912,9 +234,9 @@ func (l *loggingT) flushAll() { // Valid names are "INFO", "WARNING", "ERROR", and "FATAL". If the name is not // recognized, CopyStandardLogTo panics. func CopyStandardLogTo(name string) { - sev, ok := severityByName(name) - if !ok { - panic(fmt.Sprintf("log.CopyStandardLogTo(%q): unrecognized severity name", name)) + sev, err := logsink.ParseSeverity(name) + if err != nil { + panic(fmt.Sprintf("log.CopyStandardLogTo(%q): %v", name, err)) } // Set a log format that captures the user's file and line: // d.go:23: message @@ -922,9 +244,22 @@ func CopyStandardLogTo(name string) { stdLog.SetOutput(logBridge(sev)) } +// NewStandardLogger returns a Logger that writes to the Google logs for the +// named and lower severities. +// +// Valid names are "INFO", "WARNING", "ERROR", and "FATAL". If the name is not +// recognized, NewStandardLogger panics. +func NewStandardLogger(name string) *stdLog.Logger { + sev, err := logsink.ParseSeverity(name) + if err != nil { + panic(fmt.Sprintf("log.NewStandardLogger(%q): %v", name, err)) + } + return stdLog.New(logBridge(sev), "", stdLog.Lshortfile) +} + // logBridge provides the Write method that enables CopyStandardLogTo to connect // Go's standard logs to the logs provided by this package. -type logBridge severity +type logBridge logsink.Severity // Write parses the standard logging line and passes its components to the // logger for severity(lb). @@ -946,36 +281,72 @@ func (lb logBridge) Write(b []byte) (n int, err error) { line = 1 } } - // printWithFileLine with alsoToStderr=true, so standard log messages - // always appear on standard error. - logging.printWithFileLine(severity(lb), file, line, true, text) + + // The depth below hard-codes details of how stdlog gets here. The alternative would be to walk + // up the stack looking for src/log/log.go but that seems like it would be + // unfortunately slow. + const stdLogDepth = 4 + + metai, meta := metaPoolGet() + *meta = logsink.Meta{ + Time: timeNow(), + File: file, + Line: line, + Depth: stdLogDepth, + Severity: logsink.Severity(lb), + Thread: int64(pid), + } + + format := "%s" + args := []any{text} + if backtraceAt(file, line) { + format, args = appendBacktrace(meta.Depth, format, args) + } + + sinkf(meta, format, args...) + metaPool.Put(metai) + return len(b), nil } -// setV computes and remembers the V level for a given PC -// when vmodule is enabled. -// File pattern matching takes the basename of the file, stripped -// of its .go suffix, and uses filepath.Match, which is a little more -// general than the *? matching used in C++. -// l.mu is held. -func (l *loggingT) setV(pc uintptr) Level { - fn := runtime.FuncForPC(pc) - file, _ := fn.FileLine(pc) - // The file is something like /a/b/c/d.go. We want just the d. - if strings.HasSuffix(file, ".go") { - file = file[:len(file)-3] +// defaultFormat returns a fmt.Printf format specifier that formats its +// arguments as if they were passed to fmt.Print. +func defaultFormat(args []any) string { + n := len(args) + switch n { + case 0: + return "" + case 1: + return "%v" + } + + b := make([]byte, 0, n*3-1) + wasString := true // Suppress leading space. + for _, arg := range args { + isString := arg != nil && reflect.TypeOf(arg).Kind() == reflect.String + if wasString || isString { + b = append(b, "%v"...) + } else { + b = append(b, " %v"...) + } + wasString = isString } - if slash := strings.LastIndex(file, "/"); slash >= 0 { - file = file[slash+1:] + return string(b) +} + +// lnFormat returns a fmt.Printf format specifier that formats its arguments +// as if they were passed to fmt.Println. +func lnFormat(args []any) string { + if len(args) == 0 { + return "\n" } - for _, filter := range l.vmodule.filter { - if filter.match(file) { - l.vmap[pc] = filter.level - return filter.level - } + + b := make([]byte, 0, len(args)*3) + for range args { + b = append(b, "%v "...) } - l.vmap[pc] = 0 - return 0 + b[len(b)-1] = '\n' // Replace the last space with a newline. + return string(b) } // Verbose is a boolean type that implements Infof (like Printf) etc. @@ -986,9 +357,13 @@ type Verbose bool // The returned value is a boolean of type Verbose, which implements Info, Infoln // and Infof. These methods will write to the Info log if called. // Thus, one may write either +// // if glog.V(2) { glog.Info("log this") } +// // or +// // glog.V(2).Info("log this") +// // The second form is shorter but the first is cheaper if logging is off because it does // not evaluate its arguments. // @@ -997,184 +372,250 @@ type Verbose bool // V is at most the value of -v, or of -vmodule for the source file containing the // call, the V call will log. func V(level Level) Verbose { - // This function tries hard to be cheap unless there's work to do. - // The fast path is two atomic loads and compares. + return VDepth(1, level) +} - // Here is a cheap but safe test to see if V logging is enabled globally. - if logging.verbosity.get() >= level { - return Verbose(true) - } +// VDepth acts as V but uses depth to determine which call frame to check vmodule for. +// VDepth(0, level) is the same as V(level). +func VDepth(depth int, level Level) Verbose { + return Verbose(verboseEnabled(depth+1, level)) +} - // It's off globally but it vmodule may still be set. - // Here is another cheap but safe test to see if vmodule is enabled. - if atomic.LoadInt32(&logging.filterLength) > 0 { - // Now we need a proper lock to use the logging structure. The pcs field - // is shared so we must lock before accessing it. This is fairly expensive, - // but if V logging is enabled we're slow anyway. - logging.mu.Lock() - defer logging.mu.Unlock() - if runtime.Callers(2, logging.pcs[:]) == 0 { - return Verbose(false) - } - v, ok := logging.vmap[logging.pcs[0]] - if !ok { - v = logging.setV(logging.pcs[0]) - } - return Verbose(v >= level) +// Info is equivalent to the global Info function, guarded by the value of v. +// See the documentation of V for usage. +func (v Verbose) Info(args ...any) { + v.InfoDepth(1, args...) +} + +// InfoDepth is equivalent to the global InfoDepth function, guarded by the value of v. +// See the documentation of V for usage. +func (v Verbose) InfoDepth(depth int, args ...any) { + if v { + logf(depth+1, logsink.Info, true, noStack, defaultFormat(args), args...) } - return Verbose(false) } -// Info is equivalent to the global Info function, guarded by the value of v. +// InfoDepthf is equivalent to the global InfoDepthf function, guarded by the value of v. // See the documentation of V for usage. -func (v Verbose) Info(args ...interface{}) { +func (v Verbose) InfoDepthf(depth int, format string, args ...any) { if v { - logging.print(infoLog, args...) + logf(depth+1, logsink.Info, true, noStack, format, args...) } } // Infoln is equivalent to the global Infoln function, guarded by the value of v. // See the documentation of V for usage. -func (v Verbose) Infoln(args ...interface{}) { +func (v Verbose) Infoln(args ...any) { if v { - logging.println(infoLog, args...) + logf(1, logsink.Info, true, noStack, lnFormat(args), args...) } } // Infof is equivalent to the global Infof function, guarded by the value of v. // See the documentation of V for usage. -func (v Verbose) Infof(format string, args ...interface{}) { +func (v Verbose) Infof(format string, args ...any) { if v { - logging.printf(infoLog, format, args...) + logf(1, logsink.Info, true, noStack, format, args...) } } // Info logs to the INFO log. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing. -func Info(args ...interface{}) { - logging.print(infoLog, args...) +func Info(args ...any) { + InfoDepth(1, args...) +} + +// InfoDepth calls Info from a different depth in the call stack. +// This enables a callee to emit logs that use the callsite information of its caller +// or any other callers in the stack. When depth == 0, the original callee's line +// information is emitted. When depth > 0, depth frames are skipped in the call stack +// and the final frame is treated like the original callee to Info. +func InfoDepth(depth int, args ...any) { + logf(depth+1, logsink.Info, false, noStack, defaultFormat(args), args...) } -// InfoDepth acts as Info but uses depth to determine which call frame to log. -// InfoDepth(0, "msg") is the same as Info("msg"). -func InfoDepth(depth int, args ...interface{}) { - logging.printDepth(infoLog, depth, args...) +// InfoDepthf acts as InfoDepth but with format string. +func InfoDepthf(depth int, format string, args ...any) { + logf(depth+1, logsink.Info, false, noStack, format, args...) } // Infoln logs to the INFO log. // Arguments are handled in the manner of fmt.Println; a newline is appended if missing. -func Infoln(args ...interface{}) { - logging.println(infoLog, args...) +func Infoln(args ...any) { + logf(1, logsink.Info, false, noStack, lnFormat(args), args...) } // Infof logs to the INFO log. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. -func Infof(format string, args ...interface{}) { - logging.printf(infoLog, format, args...) +func Infof(format string, args ...any) { + logf(1, logsink.Info, false, noStack, format, args...) } // Warning logs to the WARNING and INFO logs. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing. -func Warning(args ...interface{}) { - logging.print(warningLog, args...) +func Warning(args ...any) { + WarningDepth(1, args...) } // WarningDepth acts as Warning but uses depth to determine which call frame to log. // WarningDepth(0, "msg") is the same as Warning("msg"). -func WarningDepth(depth int, args ...interface{}) { - logging.printDepth(warningLog, depth, args...) +func WarningDepth(depth int, args ...any) { + logf(depth+1, logsink.Warning, false, noStack, defaultFormat(args), args...) +} + +// WarningDepthf acts as Warningf but uses depth to determine which call frame to log. +// WarningDepthf(0, "msg") is the same as Warningf("msg"). +func WarningDepthf(depth int, format string, args ...any) { + logf(depth+1, logsink.Warning, false, noStack, format, args...) } // Warningln logs to the WARNING and INFO logs. // Arguments are handled in the manner of fmt.Println; a newline is appended if missing. -func Warningln(args ...interface{}) { - logging.println(warningLog, args...) +func Warningln(args ...any) { + logf(1, logsink.Warning, false, noStack, lnFormat(args), args...) } // Warningf logs to the WARNING and INFO logs. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. -func Warningf(format string, args ...interface{}) { - logging.printf(warningLog, format, args...) +func Warningf(format string, args ...any) { + logf(1, logsink.Warning, false, noStack, format, args...) } // Error logs to the ERROR, WARNING, and INFO logs. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing. -func Error(args ...interface{}) { - logging.print(errorLog, args...) +func Error(args ...any) { + ErrorDepth(1, args...) } // ErrorDepth acts as Error but uses depth to determine which call frame to log. // ErrorDepth(0, "msg") is the same as Error("msg"). -func ErrorDepth(depth int, args ...interface{}) { - logging.printDepth(errorLog, depth, args...) +func ErrorDepth(depth int, args ...any) { + logf(depth+1, logsink.Error, false, noStack, defaultFormat(args), args...) +} + +// ErrorDepthf acts as Errorf but uses depth to determine which call frame to log. +// ErrorDepthf(0, "msg") is the same as Errorf("msg"). +func ErrorDepthf(depth int, format string, args ...any) { + logf(depth+1, logsink.Error, false, noStack, format, args...) } // Errorln logs to the ERROR, WARNING, and INFO logs. // Arguments are handled in the manner of fmt.Println; a newline is appended if missing. -func Errorln(args ...interface{}) { - logging.println(errorLog, args...) +func Errorln(args ...any) { + logf(1, logsink.Error, false, noStack, lnFormat(args), args...) } // Errorf logs to the ERROR, WARNING, and INFO logs. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. -func Errorf(format string, args ...interface{}) { - logging.printf(errorLog, format, args...) +func Errorf(format string, args ...any) { + logf(1, logsink.Error, false, noStack, format, args...) +} + +func fatalf(depth int, format string, args ...any) { + logf(depth+1, logsink.Fatal, false, withStack, format, args...) + sinks.file.Flush() + + err := abortProcess() // Should not return. + + // Failed to abort the process using signals. Dump a stack trace and exit. + Errorf("abortProcess returned unexpectedly: %v", err) + sinks.file.Flush() + pprof.Lookup("goroutine").WriteTo(os.Stderr, 1) + os.Exit(2) // Exit with the same code as the default SIGABRT handler. +} + +// abortProcess attempts to kill the current process in a way that will dump the +// currently-running goroutines someplace useful (Coroner or stderr). +// +// It does this by sending SIGABRT to the current process. Unfortunately, the +// signal may or may not be delivered to the current thread; in order to do that +// portably, we would need to add a cgo dependency and call pthread_kill. +// +// If successful, abortProcess does not return. +func abortProcess() error { + p, err := os.FindProcess(os.Getpid()) + if err != nil { + return err + } + if err := p.Signal(syscall.SIGABRT); err != nil { + return err + } + + // Sent the signal. Now we wait for it to arrive and any SIGABRT handlers to + // run (and eventually terminate the process themselves). + // + // We could just "select{}" here, but there's an outside chance that would + // trigger the runtime's deadlock detector if there happen not to be any + // background goroutines running. So we'll sleep a while first to give + // the signal some time. + time.Sleep(10 * time.Second) + select {} } // Fatal logs to the FATAL, ERROR, WARNING, and INFO logs, -// including a stack trace of all running goroutines, then calls os.Exit(255). +// including a stack trace of all running goroutines, then calls os.Exit(2). // Arguments are handled in the manner of fmt.Print; a newline is appended if missing. -func Fatal(args ...interface{}) { - logging.print(fatalLog, args...) +func Fatal(args ...any) { + FatalDepth(1, args...) } // FatalDepth acts as Fatal but uses depth to determine which call frame to log. // FatalDepth(0, "msg") is the same as Fatal("msg"). -func FatalDepth(depth int, args ...interface{}) { - logging.printDepth(fatalLog, depth, args...) +func FatalDepth(depth int, args ...any) { + fatalf(depth+1, defaultFormat(args), args...) +} + +// FatalDepthf acts as Fatalf but uses depth to determine which call frame to log. +// FatalDepthf(0, "msg") is the same as Fatalf("msg"). +func FatalDepthf(depth int, format string, args ...any) { + fatalf(depth+1, format, args...) } // Fatalln logs to the FATAL, ERROR, WARNING, and INFO logs, -// including a stack trace of all running goroutines, then calls os.Exit(255). +// including a stack trace of all running goroutines, then calls os.Exit(2). // Arguments are handled in the manner of fmt.Println; a newline is appended if missing. -func Fatalln(args ...interface{}) { - logging.println(fatalLog, args...) +func Fatalln(args ...any) { + fatalf(1, lnFormat(args), args...) } // Fatalf logs to the FATAL, ERROR, WARNING, and INFO logs, -// including a stack trace of all running goroutines, then calls os.Exit(255). +// including a stack trace of all running goroutines, then calls os.Exit(2). // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. -func Fatalf(format string, args ...interface{}) { - logging.printf(fatalLog, format, args...) +func Fatalf(format string, args ...any) { + fatalf(1, format, args...) } -// fatalNoStacks is non-zero if we are to exit without dumping goroutine stacks. -// It allows Exit and relatives to use the Fatal logs. -var fatalNoStacks uint32 +func exitf(depth int, format string, args ...any) { + logf(depth+1, logsink.Fatal, false, noStack, format, args...) + sinks.file.Flush() + os.Exit(1) +} // Exit logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1). // Arguments are handled in the manner of fmt.Print; a newline is appended if missing. -func Exit(args ...interface{}) { - atomic.StoreUint32(&fatalNoStacks, 1) - logging.print(fatalLog, args...) +func Exit(args ...any) { + ExitDepth(1, args...) } // ExitDepth acts as Exit but uses depth to determine which call frame to log. // ExitDepth(0, "msg") is the same as Exit("msg"). -func ExitDepth(depth int, args ...interface{}) { - atomic.StoreUint32(&fatalNoStacks, 1) - logging.printDepth(fatalLog, depth, args...) +func ExitDepth(depth int, args ...any) { + exitf(depth+1, defaultFormat(args), args...) +} + +// ExitDepthf acts as Exitf but uses depth to determine which call frame to log. +// ExitDepthf(0, "msg") is the same as Exitf("msg"). +func ExitDepthf(depth int, format string, args ...any) { + exitf(depth+1, format, args...) } // Exitln logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1). -func Exitln(args ...interface{}) { - atomic.StoreUint32(&fatalNoStacks, 1) - logging.println(fatalLog, args...) +func Exitln(args ...any) { + exitf(1, lnFormat(args), args...) } // Exitf logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1). // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. -func Exitf(format string, args ...interface{}) { - atomic.StoreUint32(&fatalNoStacks, 1) - logging.printf(fatalLog, format, args...) +func Exitf(format string, args ...any) { + exitf(1, format, args...) } diff --git a/vendor/github.com/golang/glog/glog_file.go b/vendor/github.com/golang/glog/glog_file.go index 65075d28111..af1c934b820 100644 --- a/vendor/github.com/golang/glog/glog_file.go +++ b/vendor/github.com/golang/glog/glog_file.go @@ -1,6 +1,6 @@ -// Go support for leveled logs, analogous to https://code.google.com/p/google-glog/ +// Go support for leveled logs, analogous to https://github.com/google/glog. // -// Copyright 2013 Google Inc. All Rights Reserved. +// Copyright 2023 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,26 +19,34 @@ package glog import ( + "bufio" + "bytes" "errors" "flag" "fmt" + "io" "os" "os/user" "path/filepath" + "runtime" "strings" "sync" "time" -) -// MaxSize is the maximum size of a log file in bytes. -var MaxSize uint64 = 1024 * 1024 * 1800 + "github.com/golang/glog/internal/logsink" +) // logDirs lists the candidate directories for new log files. var logDirs []string -// If non-empty, overrides the choice of directory in which to write logs. -// See createLogDirs for the full list of possible destinations. -var logDir = flag.String("log_dir", "", "If non-empty, write log files in this directory") +var ( + // If non-empty, overrides the choice of directory in which to write logs. + // See createLogDirs for the full list of possible destinations. + logDir = flag.String("log_dir", "", "If non-empty, write log files in this directory") + logLink = flag.String("log_link", "", "If non-empty, add symbolic links in this directory to the log files") + logBufLevel = flag.Int("logbuflevel", int(logsink.Info), "Buffer log messages logged at this level or lower"+ + " (-1 means don't buffer; 0 means buffer INFO only; ...). Has limited applicability on non-prod platforms.") +) func createLogDirs() { if *logDir != "" { @@ -64,9 +72,17 @@ func init() { if err == nil { userName = current.Username } - - // Sanitize userName since it may contain filepath separators on Windows. - userName = strings.Replace(userName, `\`, "_", -1) + // Sanitize userName since it is used to construct file paths. + userName = strings.Map(func(r rune) rune { + switch { + case r >= 'a' && r <= 'z': + case r >= 'A' && r <= 'Z': + case r >= '0' && r <= '9': + default: + return '_' + } + return r + }, userName) } // shortHostname returns its argument, truncating at the first period. @@ -122,3 +138,270 @@ func create(tag string, t time.Time) (f *os.File, filename string, err error) { } return nil, "", fmt.Errorf("log: cannot create log: %v", lastErr) } + +// flushSyncWriter is the interface satisfied by logging destinations. +type flushSyncWriter interface { + Flush() error + Sync() error + io.Writer + filenames() []string +} + +var sinks struct { + stderr stderrSink + file fileSink +} + +func init() { + sinks.stderr.w = os.Stderr + + // Register stderr first: that way if we crash during file-writing at least + // the log will have gone somewhere. + logsink.TextSinks = append(logsink.TextSinks, &sinks.stderr, &sinks.file) + + sinks.file.flushChan = make(chan logsink.Severity, 1) + go sinks.file.flushDaemon() +} + +// stderrSink is a logsink.Text that writes log entries to stderr +// if they meet certain conditions. +type stderrSink struct { + mu sync.Mutex + w io.Writer +} + +// Enabled implements logsink.Text.Enabled. It returns true if any of the +// various stderr flags are enabled for logs of the given severity, if the log +// message is from the standard "log" package, or if google.Init has not yet run +// (and hence file logging is not yet initialized). +func (s *stderrSink) Enabled(m *logsink.Meta) bool { + return toStderr || alsoToStderr || m.Severity >= stderrThreshold.get() +} + +// Emit implements logsink.Text.Emit. +func (s *stderrSink) Emit(m *logsink.Meta, data []byte) (n int, err error) { + s.mu.Lock() + defer s.mu.Unlock() + + dn, err := s.w.Write(data) + n += dn + return n, err +} + +// severityWriters is an array of flushSyncWriter with a value for each +// logsink.Severity. +type severityWriters [4]flushSyncWriter + +// fileSink is a logsink.Text that prints to a set of Google log files. +type fileSink struct { + mu sync.Mutex + // file holds writer for each of the log types. + file severityWriters + flushChan chan logsink.Severity +} + +// Enabled implements logsink.Text.Enabled. It returns true if google.Init +// has run and both --disable_log_to_disk and --logtostderr are false. +func (s *fileSink) Enabled(m *logsink.Meta) bool { + return !toStderr +} + +// Emit implements logsink.Text.Emit +func (s *fileSink) Emit(m *logsink.Meta, data []byte) (n int, err error) { + s.mu.Lock() + defer s.mu.Unlock() + + if err = s.createMissingFiles(m.Severity); err != nil { + return 0, err + } + for sev := m.Severity; sev >= logsink.Info; sev-- { + if _, fErr := s.file[sev].Write(data); fErr != nil && err == nil { + err = fErr // Take the first error. + } + } + n = len(data) + if int(m.Severity) > *logBufLevel { + select { + case s.flushChan <- m.Severity: + default: + } + } + + return n, err +} + +// syncBuffer joins a bufio.Writer to its underlying file, providing access to the +// file's Sync method and providing a wrapper for the Write method that provides log +// file rotation. There are conflicting methods, so the file cannot be embedded. +// s.mu is held for all its methods. +type syncBuffer struct { + sink *fileSink + *bufio.Writer + file *os.File + names []string + sev logsink.Severity + nbytes uint64 // The number of bytes written to this file +} + +func (sb *syncBuffer) Sync() error { + return sb.file.Sync() +} + +func (sb *syncBuffer) Write(p []byte) (n int, err error) { + if sb.nbytes+uint64(len(p)) >= MaxSize { + if err := sb.rotateFile(time.Now()); err != nil { + return 0, err + } + } + n, err = sb.Writer.Write(p) + sb.nbytes += uint64(n) + return n, err +} + +func (sb *syncBuffer) filenames() []string { + return sb.names +} + +const footer = "\nCONTINUED IN NEXT FILE\n" + +// rotateFile closes the syncBuffer's file and starts a new one. +func (sb *syncBuffer) rotateFile(now time.Time) error { + var err error + pn := "" + file, name, err := create(sb.sev.String(), now) + + if sb.file != nil { + // The current log file becomes the previous log at the end of + // this block, so save its name for use in the header of the next + // file. + pn = sb.file.Name() + sb.Flush() + // If there's an existing file, write a footer with the name of + // the next file in the chain, followed by the constant string + // \nCONTINUED IN NEXT FILE\n to make continuation detection simple. + sb.file.Write([]byte("Next log: ")) + sb.file.Write([]byte(name)) + sb.file.Write([]byte(footer)) + sb.file.Close() + } + + sb.file = file + sb.names = append(sb.names, name) + sb.nbytes = 0 + if err != nil { + return err + } + + sb.Writer = bufio.NewWriterSize(sb.file, bufferSize) + + // Write header. + var buf bytes.Buffer + fmt.Fprintf(&buf, "Log file created at: %s\n", now.Format("2006/01/02 15:04:05")) + fmt.Fprintf(&buf, "Running on machine: %s\n", host) + fmt.Fprintf(&buf, "Binary: Built with %s %s for %s/%s\n", runtime.Compiler, runtime.Version(), runtime.GOOS, runtime.GOARCH) + fmt.Fprintf(&buf, "Previous log: %s\n", pn) + fmt.Fprintf(&buf, "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu threadid file:line] msg\n") + n, err := sb.file.Write(buf.Bytes()) + sb.nbytes += uint64(n) + return err +} + +// bufferSize sizes the buffer associated with each log file. It's large +// so that log records can accumulate without the logging thread blocking +// on disk I/O. The flushDaemon will block instead. +const bufferSize = 256 * 1024 + +// createMissingFiles creates all the log files for severity from infoLog up to +// upTo that have not already been created. +// s.mu is held. +func (s *fileSink) createMissingFiles(upTo logsink.Severity) error { + if s.file[upTo] != nil { + return nil + } + now := time.Now() + // Files are created in increasing severity order, so we can be assured that + // if a high severity logfile exists, then so do all of lower severity. + for sev := logsink.Info; sev <= upTo; sev++ { + if s.file[sev] != nil { + continue + } + sb := &syncBuffer{ + sink: s, + sev: sev, + } + if err := sb.rotateFile(now); err != nil { + return err + } + s.file[sev] = sb + } + return nil +} + +// flushDaemon periodically flushes the log file buffers. +func (s *fileSink) flushDaemon() { + tick := time.NewTicker(30 * time.Second) + defer tick.Stop() + for { + select { + case <-tick.C: + s.Flush() + case sev := <-s.flushChan: + s.flush(sev) + } + } +} + +// Flush flushes all pending log I/O. +func Flush() { + sinks.file.Flush() +} + +// Flush flushes all the logs and attempts to "sync" their data to disk. +func (s *fileSink) Flush() error { + return s.flush(logsink.Info) +} + +// flush flushes all logs of severity threshold or greater. +func (s *fileSink) flush(threshold logsink.Severity) error { + s.mu.Lock() + defer s.mu.Unlock() + + var firstErr error + updateErr := func(err error) { + if err != nil && firstErr == nil { + firstErr = err + } + } + + // Flush from fatal down, in case there's trouble flushing. + for sev := logsink.Fatal; sev >= threshold; sev-- { + file := s.file[sev] + if file != nil { + updateErr(file.Flush()) + updateErr(file.Sync()) + } + } + + return firstErr +} + +// Names returns the names of the log files holding the FATAL, ERROR, +// WARNING, or INFO logs. Returns ErrNoLog if the log for the given +// level doesn't exist (e.g. because no messages of that level have been +// written). This may return multiple names if the log type requested +// has rolled over. +func Names(s string) ([]string, error) { + severity, err := logsink.ParseSeverity(s) + if err != nil { + return nil, err + } + + sinks.file.mu.Lock() + defer sinks.file.mu.Unlock() + f := sinks.file.file[severity] + if f == nil { + return nil, ErrNoLog + } + + return f.filenames(), nil +} diff --git a/vendor/github.com/golang/glog/glog_flags.go b/vendor/github.com/golang/glog/glog_flags.go new file mode 100644 index 00000000000..3060e54d9dc --- /dev/null +++ b/vendor/github.com/golang/glog/glog_flags.go @@ -0,0 +1,395 @@ +// Go support for leveled logs, analogous to https://github.com/google/glog. +// +// Copyright 2023 Google Inc. All Rights Reserved. +// +// 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 glog + +import ( + "bytes" + "errors" + "flag" + "fmt" + "path/filepath" + "runtime" + "strconv" + "strings" + "sync" + "sync/atomic" + + "github.com/golang/glog/internal/logsink" +) + +// modulePat contains a filter for the -vmodule flag. +// It holds a verbosity level and a file pattern to match. +type modulePat struct { + pattern string + literal bool // The pattern is a literal string + full bool // The pattern wants to match the full path + level Level +} + +// match reports whether the file matches the pattern. It uses a string +// comparison if the pattern contains no metacharacters. +func (m *modulePat) match(full, file string) bool { + if m.literal { + if m.full { + return full == m.pattern + } + return file == m.pattern + } + if m.full { + match, _ := filepath.Match(m.pattern, full) + return match + } + match, _ := filepath.Match(m.pattern, file) + return match +} + +// isLiteral reports whether the pattern is a literal string, that is, has no metacharacters +// that require filepath.Match to be called to match the pattern. +func isLiteral(pattern string) bool { + return !strings.ContainsAny(pattern, `\*?[]`) +} + +// isFull reports whether the pattern matches the full file path, that is, +// whether it contains /. +func isFull(pattern string) bool { + return strings.ContainsRune(pattern, '/') +} + +// verboseFlags represents the setting of the -v and -vmodule flags. +type verboseFlags struct { + // moduleLevelCache is a sync.Map storing the -vmodule Level for each V() + // call site, identified by PC. If there is no matching -vmodule filter, + // the cached value is exactly v. moduleLevelCache is replaced with a new + // Map whenever the -vmodule or -v flag changes state. + moduleLevelCache atomic.Value + + // mu guards all fields below. + mu sync.Mutex + + // v stores the value of the -v flag. It may be read safely using + // sync.LoadInt32, but is only modified under mu. + v Level + + // module stores the parsed -vmodule flag. + module []modulePat + + // moduleLength caches len(module). If greater than zero, it + // means vmodule is enabled. It may be read safely using sync.LoadInt32, but + // is only modified under mu. + moduleLength int32 +} + +// NOTE: For compatibility with the open-sourced v1 version of this +// package (github.com/golang/glog) we need to retain that flag.Level +// implements the flag.Value interface. See also go/log-vs-glog. + +// String is part of the flag.Value interface. +func (l *Level) String() string { + return strconv.FormatInt(int64(l.Get().(Level)), 10) +} + +// Get is part of the flag.Value interface. +func (l *Level) Get() any { + if l == &vflags.v { + // l is the value registered for the -v flag. + return Level(atomic.LoadInt32((*int32)(l))) + } + return *l +} + +// Set is part of the flag.Value interface. +func (l *Level) Set(value string) error { + v, err := strconv.Atoi(value) + if err != nil { + return err + } + if l == &vflags.v { + // l is the value registered for the -v flag. + vflags.mu.Lock() + defer vflags.mu.Unlock() + vflags.moduleLevelCache.Store(&sync.Map{}) + atomic.StoreInt32((*int32)(l), int32(v)) + return nil + } + *l = Level(v) + return nil +} + +// vModuleFlag is the flag.Value for the --vmodule flag. +type vModuleFlag struct{ *verboseFlags } + +func (f vModuleFlag) String() string { + f.mu.Lock() + defer f.mu.Unlock() + + var b bytes.Buffer + for i, f := range f.module { + if i > 0 { + b.WriteRune(',') + } + fmt.Fprintf(&b, "%s=%d", f.pattern, f.level) + } + return b.String() +} + +// Get returns nil for this flag type since the struct is not exported. +func (f vModuleFlag) Get() any { return nil } + +var errVmoduleSyntax = errors.New("syntax error: expect comma-separated list of filename=N") + +// Syntax: -vmodule=recordio=2,foo/bar/baz=1,gfs*=3 +func (f vModuleFlag) Set(value string) error { + var filter []modulePat + for _, pat := range strings.Split(value, ",") { + if len(pat) == 0 { + // Empty strings such as from a trailing comma can be ignored. + continue + } + patLev := strings.Split(pat, "=") + if len(patLev) != 2 || len(patLev[0]) == 0 || len(patLev[1]) == 0 { + return errVmoduleSyntax + } + pattern := patLev[0] + v, err := strconv.Atoi(patLev[1]) + if err != nil { + return errors.New("syntax error: expect comma-separated list of filename=N") + } + // TODO: check syntax of filter? + filter = append(filter, modulePat{pattern, isLiteral(pattern), isFull(pattern), Level(v)}) + } + + f.mu.Lock() + defer f.mu.Unlock() + f.module = filter + atomic.StoreInt32((*int32)(&f.moduleLength), int32(len(f.module))) + f.moduleLevelCache.Store(&sync.Map{}) + return nil +} + +func (f *verboseFlags) levelForPC(pc uintptr) Level { + if level, ok := f.moduleLevelCache.Load().(*sync.Map).Load(pc); ok { + return level.(Level) + } + + f.mu.Lock() + defer f.mu.Unlock() + level := Level(f.v) + fn := runtime.FuncForPC(pc) + file, _ := fn.FileLine(pc) + // The file is something like /a/b/c/d.go. We want just the d for + // regular matches, /a/b/c/d for full matches. + if strings.HasSuffix(file, ".go") { + file = file[:len(file)-3] + } + full := file + if slash := strings.LastIndex(file, "/"); slash >= 0 { + file = file[slash+1:] + } + for _, filter := range f.module { + if filter.match(full, file) { + level = filter.level + break // Use the first matching level. + } + } + f.moduleLevelCache.Load().(*sync.Map).Store(pc, level) + return level +} + +func (f *verboseFlags) enabled(callerDepth int, level Level) bool { + if atomic.LoadInt32(&f.moduleLength) == 0 { + // No vmodule values specified, so compare against v level. + return Level(atomic.LoadInt32((*int32)(&f.v))) >= level + } + + pcs := [1]uintptr{} + if runtime.Callers(callerDepth+2, pcs[:]) < 1 { + return false + } + frame, _ := runtime.CallersFrames(pcs[:]).Next() + return f.levelForPC(frame.Entry) >= level +} + +// traceLocation represents an entry in the -log_backtrace_at flag. +type traceLocation struct { + file string + line int +} + +var errTraceSyntax = errors.New("syntax error: expect file.go:234") + +func parseTraceLocation(value string) (traceLocation, error) { + fields := strings.Split(value, ":") + if len(fields) != 2 { + return traceLocation{}, errTraceSyntax + } + file, lineStr := fields[0], fields[1] + if !strings.Contains(file, ".") { + return traceLocation{}, errTraceSyntax + } + line, err := strconv.Atoi(lineStr) + if err != nil { + return traceLocation{}, errTraceSyntax + } + if line < 0 { + return traceLocation{}, errors.New("negative value for line") + } + return traceLocation{file, line}, nil +} + +// match reports whether the specified file and line matches the trace location. +// The argument file name is the full path, not the basename specified in the flag. +func (t traceLocation) match(file string, line int) bool { + if t.line != line { + return false + } + if i := strings.LastIndex(file, "/"); i >= 0 { + file = file[i+1:] + } + return t.file == file +} + +func (t traceLocation) String() string { + return fmt.Sprintf("%s:%d", t.file, t.line) +} + +// traceLocations represents the -log_backtrace_at flag. +// Syntax: -log_backtrace_at=recordio.go:234,sstable.go:456 +// Note that unlike vmodule the file extension is included here. +type traceLocations struct { + mu sync.Mutex + locsLen int32 // Safe for atomic read without mu. + locs []traceLocation +} + +func (t *traceLocations) String() string { + t.mu.Lock() + defer t.mu.Unlock() + + var buf bytes.Buffer + for i, tl := range t.locs { + if i > 0 { + buf.WriteString(",") + } + buf.WriteString(tl.String()) + } + return buf.String() +} + +// Get always returns nil for this flag type since the struct is not exported +func (t *traceLocations) Get() any { return nil } + +func (t *traceLocations) Set(value string) error { + var locs []traceLocation + for _, s := range strings.Split(value, ",") { + if s == "" { + continue + } + loc, err := parseTraceLocation(s) + if err != nil { + return err + } + locs = append(locs, loc) + } + + t.mu.Lock() + defer t.mu.Unlock() + atomic.StoreInt32(&t.locsLen, int32(len(locs))) + t.locs = locs + return nil +} + +func (t *traceLocations) match(file string, line int) bool { + if atomic.LoadInt32(&t.locsLen) == 0 { + return false + } + + t.mu.Lock() + defer t.mu.Unlock() + for _, tl := range t.locs { + if tl.match(file, line) { + return true + } + } + return false +} + +// severityFlag is an atomic flag.Value implementation for logsink.Severity. +type severityFlag int32 + +func (s *severityFlag) get() logsink.Severity { + return logsink.Severity(atomic.LoadInt32((*int32)(s))) +} +func (s *severityFlag) String() string { return strconv.FormatInt(int64(*s), 10) } +func (s *severityFlag) Get() any { return s.get() } +func (s *severityFlag) Set(value string) error { + threshold, err := logsink.ParseSeverity(value) + if err != nil { + // Not a severity name. Try a raw number. + v, err := strconv.Atoi(value) + if err != nil { + return err + } + threshold = logsink.Severity(v) + if threshold < logsink.Info || threshold > logsink.Fatal { + return fmt.Errorf("Severity %d out of range (min %d, max %d).", v, logsink.Info, logsink.Fatal) + } + } + atomic.StoreInt32((*int32)(s), int32(threshold)) + return nil +} + +var ( + vflags verboseFlags // The -v and -vmodule flags. + + logBacktraceAt traceLocations // The -log_backtrace_at flag. + + // Boolean flags. Not handled atomically because the flag.Value interface + // does not let us avoid the =true, and that shorthand is necessary for + // compatibility. TODO: does this matter enough to fix? Seems unlikely. + toStderr bool // The -logtostderr flag. + alsoToStderr bool // The -alsologtostderr flag. + + stderrThreshold severityFlag // The -stderrthreshold flag. +) + +// verboseEnabled returns whether the caller at the given depth should emit +// verbose logs at the given level, with depth 0 identifying the caller of +// verboseEnabled. +func verboseEnabled(callerDepth int, level Level) bool { + return vflags.enabled(callerDepth+1, level) +} + +// backtraceAt returns whether the logging call at the given function and line +// should also emit a backtrace of the current call stack. +func backtraceAt(file string, line int) bool { + return logBacktraceAt.match(file, line) +} + +func init() { + vflags.moduleLevelCache.Store(&sync.Map{}) + + flag.Var(&vflags.v, "v", "log level for V logs") + flag.Var(vModuleFlag{&vflags}, "vmodule", "comma-separated list of pattern=N settings for file-filtered logging") + + flag.Var(&logBacktraceAt, "log_backtrace_at", "when logging hits line file:N, emit a stack trace") + + stderrThreshold = severityFlag(logsink.Error) + + flag.BoolVar(&toStderr, "logtostderr", false, "log to standard error instead of files") + flag.BoolVar(&alsoToStderr, "alsologtostderr", false, "log to standard error as well as files") + flag.Var(&stderrThreshold, "stderrthreshold", "logs at or above this threshold go to stderr") +} diff --git a/vendor/github.com/golang/glog/internal/logsink/logsink.go b/vendor/github.com/golang/glog/internal/logsink/logsink.go new file mode 100644 index 00000000000..53758e1c9f5 --- /dev/null +++ b/vendor/github.com/golang/glog/internal/logsink/logsink.go @@ -0,0 +1,387 @@ +// Copyright 2023 Google Inc. All Rights Reserved. +// +// 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 logsink + +import ( + "bytes" + "fmt" + "strconv" + "strings" + "sync" + "time" + + "github.com/golang/glog/internal/stackdump" +) + +// MaxLogMessageLen is the limit on length of a formatted log message, including +// the standard line prefix and trailing newline. +// +// Chosen to match C++ glog. +const MaxLogMessageLen = 15000 + +// A Severity is a severity at which a message can be logged. +type Severity int8 + +// These constants identify the log levels in order of increasing severity. +// A message written to a high-severity log file is also written to each +// lower-severity log file. +const ( + Info Severity = iota + Warning + Error + + // Fatal contains logs written immediately before the process terminates. + // + // Sink implementations should not terminate the process themselves: the log + // package will perform any necessary cleanup and terminate the process as + // appropriate. + Fatal +) + +func (s Severity) String() string { + switch s { + case Info: + return "INFO" + case Warning: + return "WARNING" + case Error: + return "ERROR" + case Fatal: + return "FATAL" + } + return fmt.Sprintf("%T(%d)", s, s) +} + +// ParseSeverity returns the case-insensitive Severity value for the given string. +func ParseSeverity(name string) (Severity, error) { + name = strings.ToUpper(name) + for s := Info; s <= Fatal; s++ { + if s.String() == name { + return s, nil + } + } + return -1, fmt.Errorf("logsink: invalid severity %q", name) +} + +// Meta is metadata about a logging call. +type Meta struct { + // Time is the time at which the log call was made. + Time time.Time + + // File is the source file from which the log entry originates. + File string + // Line is the line offset within the source file. + Line int + // Depth is the number of stack frames between the logsink and the log call. + Depth int + + Severity Severity + + // Verbose indicates whether the call was made via "log.V". Log entries below + // the current verbosity threshold are not sent to the sink. + Verbose bool + + // Thread ID. This can be populated with a thread ID from another source, + // such as a system we are importing logs from. In the normal case, this + // will be set to the process ID (PID), since Go doesn't have threads. + Thread int64 + + // Stack trace starting in the logging function. May be nil. + // A logsink should implement the StackWanter interface to request this. + // + // Even if WantStack returns false, this field may be set (e.g. if another + // sink wants a stack trace). + Stack *stackdump.Stack +} + +// Structured is a logging destination that accepts structured data as input. +type Structured interface { + // Printf formats according to a fmt.Printf format specifier and writes a log + // entry. The precise result of formatting depends on the sink, but should + // aim for consistency with fmt.Printf. + // + // Printf returns the number of bytes occupied by the log entry, which + // may not be equal to the total number of bytes written. + // + // Printf returns any error encountered *if* it is severe enough that the log + // package should terminate the process. + // + // The sink must not modify the *Meta parameter, nor reference it after + // Printf has returned: it may be reused in subsequent calls. + Printf(meta *Meta, format string, a ...any) (n int, err error) +} + +// StackWanter can be implemented by a logsink.Structured to indicate that it +// wants a stack trace to accompany at least some of the log messages it receives. +type StackWanter interface { + // WantStack returns true if the sink requires a stack trace for a log message + // with this metadata. + // + // NOTE: Returning true implies that meta.Stack will be non-nil. Returning + // false does NOT imply that meta.Stack will be nil. + WantStack(meta *Meta) bool +} + +// Text is a logging destination that accepts pre-formatted log lines (instead of +// structured data). +type Text interface { + // Enabled returns whether this sink should output messages for the given + // Meta. If the sink returns false for a given Meta, the Printf function will + // not call Emit on it for the corresponding log message. + Enabled(*Meta) bool + + // Emit writes a pre-formatted text log entry (including any applicable + // header) to the log. It returns the number of bytes occupied by the entry + // (which may differ from the length of the passed-in slice). + // + // Emit returns any error encountered *if* it is severe enough that the log + // package should terminate the process. + // + // The sink must not modify the *Meta parameter, nor reference it after + // Printf has returned: it may be reused in subsequent calls. + // + // NOTE: When developing a text sink, keep in mind the surface in which the + // logs will be displayed, and whether it's important that the sink be + // resistent to tampering in the style of b/211428300. Standard text sinks + // (like `stderrSink`) do not protect against this (e.g. by escaping + // characters) because the cases where they would show user-influenced bytes + // are vanishingly small. + Emit(*Meta, []byte) (n int, err error) +} + +// bufs is a pool of *bytes.Buffer used in formatting log entries. +var bufs sync.Pool // Pool of *bytes.Buffer. + +// textPrintf formats a text log entry and emits it to all specified Text sinks. +// +// The returned n is the maximum across all Emit calls. +// The returned err is the first non-nil error encountered. +// Sinks that are disabled by configuration should return (0, nil). +func textPrintf(m *Meta, textSinks []Text, format string, args ...any) (n int, err error) { + // We expect at most file, stderr, and perhaps syslog. If there are more, + // we'll end up allocating - no big deal. + const maxExpectedTextSinks = 3 + var noAllocSinks [maxExpectedTextSinks]Text + + sinks := noAllocSinks[:0] + for _, s := range textSinks { + if s.Enabled(m) { + sinks = append(sinks, s) + } + } + if len(sinks) == 0 && m.Severity != Fatal { + return 0, nil // No TextSinks specified; don't bother formatting. + } + + bufi := bufs.Get() + var buf *bytes.Buffer + if bufi == nil { + buf = bytes.NewBuffer(nil) + bufi = buf + } else { + buf = bufi.(*bytes.Buffer) + buf.Reset() + } + + // Lmmdd hh:mm:ss.uuuuuu PID/GID file:line] + // + // The "PID" entry arguably ought to be TID for consistency with other + // environments, but TID is not meaningful in a Go program due to the + // multiplexing of goroutines across threads. + // + // Avoid Fprintf, for speed. The format is so simple that we can do it quickly by hand. + // It's worth about 3X. Fprintf is hard. + const severityChar = "IWEF" + buf.WriteByte(severityChar[m.Severity]) + + _, month, day := m.Time.Date() + hour, minute, second := m.Time.Clock() + twoDigits(buf, int(month)) + twoDigits(buf, day) + buf.WriteByte(' ') + twoDigits(buf, hour) + buf.WriteByte(':') + twoDigits(buf, minute) + buf.WriteByte(':') + twoDigits(buf, second) + buf.WriteByte('.') + nDigits(buf, 6, uint64(m.Time.Nanosecond()/1000), '0') + buf.WriteByte(' ') + + nDigits(buf, 7, uint64(m.Thread), ' ') + buf.WriteByte(' ') + + { + file := m.File + if i := strings.LastIndex(file, "/"); i >= 0 { + file = file[i+1:] + } + buf.WriteString(file) + } + + buf.WriteByte(':') + { + var tmp [19]byte + buf.Write(strconv.AppendInt(tmp[:0], int64(m.Line), 10)) + } + buf.WriteString("] ") + + msgStart := buf.Len() + fmt.Fprintf(buf, format, args...) + if buf.Len() > MaxLogMessageLen-1 { + buf.Truncate(MaxLogMessageLen - 1) + } + msgEnd := buf.Len() + if b := buf.Bytes(); b[len(b)-1] != '\n' { + buf.WriteByte('\n') + } + + for _, s := range sinks { + sn, sErr := s.Emit(m, buf.Bytes()) + if sn > n { + n = sn + } + if sErr != nil && err == nil { + err = sErr + } + } + + if m.Severity == Fatal { + savedM := *m + fatalMessageStore(savedEntry{ + meta: &savedM, + msg: buf.Bytes()[msgStart:msgEnd], + }) + } else { + bufs.Put(bufi) + } + return n, err +} + +const digits = "0123456789" + +// twoDigits formats a zero-prefixed two-digit integer to buf. +func twoDigits(buf *bytes.Buffer, d int) { + buf.WriteByte(digits[(d/10)%10]) + buf.WriteByte(digits[d%10]) +} + +// nDigits formats an n-digit integer to buf, padding with pad on the left. It +// assumes d != 0. +func nDigits(buf *bytes.Buffer, n int, d uint64, pad byte) { + var tmp [20]byte + + cutoff := len(tmp) - n + j := len(tmp) - 1 + for ; d > 0; j-- { + tmp[j] = digits[d%10] + d /= 10 + } + for ; j >= cutoff; j-- { + tmp[j] = pad + } + j++ + buf.Write(tmp[j:]) +} + +// Printf writes a log entry to all registered TextSinks in this package, then +// to all registered StructuredSinks. +// +// The returned n is the maximum across all Emit and Printf calls. +// The returned err is the first non-nil error encountered. +// Sinks that are disabled by configuration should return (0, nil). +func Printf(m *Meta, format string, args ...any) (n int, err error) { + m.Depth++ + n, err = textPrintf(m, TextSinks, format, args...) + + for _, sink := range StructuredSinks { + // TODO: Support TextSinks that implement StackWanter? + if sw, ok := sink.(StackWanter); ok && sw.WantStack(m) { + if m.Stack == nil { + // First, try to find a stacktrace in args, otherwise generate one. + for _, arg := range args { + if stack, ok := arg.(stackdump.Stack); ok { + m.Stack = &stack + break + } + } + if m.Stack == nil { + stack := stackdump.Caller( /* skipDepth = */ m.Depth) + m.Stack = &stack + } + } + } + sn, sErr := sink.Printf(m, format, args...) + if sn > n { + n = sn + } + if sErr != nil && err == nil { + err = sErr + } + } + return n, err +} + +// The sets of sinks to which logs should be written. +// +// These must only be modified during package init, and are read-only thereafter. +var ( + // StructuredSinks is the set of Structured sink instances to which logs + // should be written. + StructuredSinks []Structured + + // TextSinks is the set of Text sink instances to which logs should be + // written. + // + // These are registered separately from Structured sink implementations to + // avoid the need to repeat the work of formatting a message for each Text + // sink that writes it. The package-level Printf function writes to both sets + // independenty, so a given log destination should only register a Structured + // *or* a Text sink (not both). + TextSinks []Text +) + +type savedEntry struct { + meta *Meta + msg []byte +} + +// StructuredTextWrapper is a Structured sink which forwards logs to a set of Text sinks. +// +// The purpose of this sink is to allow applications to intercept logging calls before they are +// serialized and sent to Text sinks. For example, if one needs to redact PII from logging +// arguments before they reach STDERR, one solution would be to do the redacting in a Structured +// sink that forwards logs to a StructuredTextWrapper instance, and make STDERR a child of that +// StructuredTextWrapper instance. This is how one could set this up in their application: +// +// func init() { +// +// wrapper := logsink.StructuredTextWrapper{TextSinks: logsink.TextSinks} +// // sanitizersink will intercept logs and remove PII +// sanitizer := sanitizersink{Sink: &wrapper} +// logsink.StructuredSinks = append(logsink.StructuredSinks, &sanitizer) +// logsink.TextSinks = nil +// +// } +type StructuredTextWrapper struct { + // TextSinks is the set of Text sinks that should receive logs from this + // StructuredTextWrapper instance. + TextSinks []Text +} + +// Printf forwards logs to all Text sinks registered in the StructuredTextWrapper. +func (w *StructuredTextWrapper) Printf(meta *Meta, format string, args ...any) (n int, err error) { + return textPrintf(meta, w.TextSinks, format, args...) +} diff --git a/vendor/github.com/golang/glog/internal/logsink/logsink_fatal.go b/vendor/github.com/golang/glog/internal/logsink/logsink_fatal.go new file mode 100644 index 00000000000..3dc269abc21 --- /dev/null +++ b/vendor/github.com/golang/glog/internal/logsink/logsink_fatal.go @@ -0,0 +1,35 @@ +package logsink + +import ( + "sync/atomic" + "unsafe" +) + +func fatalMessageStore(e savedEntry) { + // Only put a new one in if we haven't assigned before. + atomic.CompareAndSwapPointer(&fatalMessage, nil, unsafe.Pointer(&e)) +} + +var fatalMessage unsafe.Pointer // savedEntry stored with CompareAndSwapPointer + +// FatalMessage returns the Meta and message contents of the first message +// logged with Fatal severity, or false if none has occurred. +func FatalMessage() (*Meta, []byte, bool) { + e := (*savedEntry)(atomic.LoadPointer(&fatalMessage)) + if e == nil { + return nil, nil, false + } + return e.meta, e.msg, true +} + +// DoNotUseRacyFatalMessage is FatalMessage, but worse. +// +//go:norace +//go:nosplit +func DoNotUseRacyFatalMessage() (*Meta, []byte, bool) { + e := (*savedEntry)(fatalMessage) + if e == nil { + return nil, nil, false + } + return e.meta, e.msg, true +} diff --git a/vendor/github.com/golang/glog/internal/stackdump/stackdump.go b/vendor/github.com/golang/glog/internal/stackdump/stackdump.go new file mode 100644 index 00000000000..3427c9d6bd0 --- /dev/null +++ b/vendor/github.com/golang/glog/internal/stackdump/stackdump.go @@ -0,0 +1,127 @@ +// Copyright 2023 Google Inc. All Rights Reserved. +// +// 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 stackdump provides wrappers for runtime.Stack and runtime.Callers +// with uniform support for skipping caller frames. +// +// ⚠ Unlike the functions in the runtime package, these may allocate a +// non-trivial quantity of memory: use them with care. ⚠ +package stackdump + +import ( + "bytes" + "runtime" +) + +// runtimeStackSelfFrames is 1 if runtime.Stack includes the call to +// runtime.Stack itself or 0 if it does not. +// +// As of 2016-04-27, the gccgo compiler includes runtime.Stack but the gc +// compiler does not. +var runtimeStackSelfFrames = func() int { + for n := 1 << 10; n < 1<<20; n *= 2 { + buf := make([]byte, n) + n := runtime.Stack(buf, false) + if bytes.Contains(buf[:n], []byte("runtime.Stack")) { + return 1 + } else if n < len(buf) || bytes.Count(buf, []byte("\n")) >= 3 { + return 0 + } + } + return 0 +}() + +// Stack is a stack dump for a single goroutine. +type Stack struct { + // Text is a representation of the stack dump in a human-readable format. + Text []byte + + // PC is a representation of the stack dump using raw program counter values. + PC []uintptr +} + +func (s Stack) String() string { return string(s.Text) } + +// Caller returns the Stack dump for the calling goroutine, starting skipDepth +// frames before the caller of Caller. (Caller(0) provides a dump starting at +// the caller of this function.) +func Caller(skipDepth int) Stack { + return Stack{ + Text: CallerText(skipDepth + 1), + PC: CallerPC(skipDepth + 1), + } +} + +// CallerText returns a textual dump of the stack starting skipDepth frames before +// the caller. (CallerText(0) provides a dump starting at the caller of this +// function.) +func CallerText(skipDepth int) []byte { + for n := 1 << 10; ; n *= 2 { + buf := make([]byte, n) + n := runtime.Stack(buf, false) + if n < len(buf) { + return pruneFrames(skipDepth+1+runtimeStackSelfFrames, buf[:n]) + } + } +} + +// CallerPC returns a dump of the program counters of the stack starting +// skipDepth frames before the caller. (CallerPC(0) provides a dump starting at +// the caller of this function.) +func CallerPC(skipDepth int) []uintptr { + for n := 1 << 8; ; n *= 2 { + buf := make([]uintptr, n) + n := runtime.Callers(skipDepth+2, buf) + if n < len(buf) { + return buf[:n] + } + } +} + +// pruneFrames removes the topmost skipDepth frames of the first goroutine in a +// textual stack dump. It overwrites the passed-in slice. +// +// If there are fewer than skipDepth frames in the first goroutine's stack, +// pruneFrames prunes it to an empty stack and leaves the remaining contents +// intact. +func pruneFrames(skipDepth int, stack []byte) []byte { + headerLen := 0 + for i, c := range stack { + if c == '\n' { + headerLen = i + 1 + break + } + } + if headerLen == 0 { + return stack // No header line - not a well-formed stack trace. + } + + skipLen := headerLen + skipNewlines := skipDepth * 2 + for ; skipLen < len(stack) && skipNewlines > 0; skipLen++ { + c := stack[skipLen] + if c != '\n' { + continue + } + skipNewlines-- + skipLen++ + if skipNewlines == 0 || skipLen == len(stack) || stack[skipLen] == '\n' { + break + } + } + + pruned := stack[skipLen-headerLen:] + copy(pruned, stack[:headerLen]) + return pruned +} diff --git a/vendor/github.com/google/pprof/profile/encode.go b/vendor/github.com/google/pprof/profile/encode.go index c8a1beb8a8c..182c926b908 100644 --- a/vendor/github.com/google/pprof/profile/encode.go +++ b/vendor/github.com/google/pprof/profile/encode.go @@ -258,10 +258,10 @@ func (p *Profile) postDecode() error { // If this a main linux kernel mapping with a relocation symbol suffix // ("[kernel.kallsyms]_text"), extract said suffix. // It is fairly hacky to handle at this level, but the alternatives appear even worse. - if strings.HasPrefix(m.File, "[kernel.kallsyms]") { - m.KernelRelocationSymbol = strings.ReplaceAll(m.File, "[kernel.kallsyms]", "") + const prefix = "[kernel.kallsyms]" + if strings.HasPrefix(m.File, prefix) { + m.KernelRelocationSymbol = m.File[len(prefix):] } - } functions := make(map[uint64]*Function, len(p.Function)) diff --git a/vendor/github.com/gophercloud/gophercloud/CHANGELOG.md b/vendor/github.com/gophercloud/gophercloud/CHANGELOG.md index 9e2567b98b6..e737082d697 100644 --- a/vendor/github.com/gophercloud/gophercloud/CHANGELOG.md +++ b/vendor/github.com/gophercloud/gophercloud/CHANGELOG.md @@ -1,3 +1,28 @@ +## v1.4.0 (2023-05-25) + +New features and improvements: + +* [GH-2465](https://github.com/gophercloud/gophercloud/pull/2465) keystone: add v3 limits update operation +* [GH-2596](https://github.com/gophercloud/gophercloud/pull/2596) keystone: add v3 limits get operation +* [GH-2618](https://github.com/gophercloud/gophercloud/pull/2618) keystone: add v3 limits delete operation +* [GH-2616](https://github.com/gophercloud/gophercloud/pull/2616) Add CRUD support for register limit APIs +* [GH-2610](https://github.com/gophercloud/gophercloud/pull/2610) Add PUT/HEAD/DELETE for identity/v3/OS-INHERIT +* [GH-2597](https://github.com/gophercloud/gophercloud/pull/2597) Add validation and optimise objects.BulkDelete +* [GH-2602](https://github.com/gophercloud/gophercloud/pull/2602) [swift v1]: introduce a TempURLKey argument for objects.CreateTempURLOpts struct +* [GH-2623](https://github.com/gophercloud/gophercloud/pull/2623) Add the ability to remove ingress/egress policies from fwaas_v2 groups +* [GH-2625](https://github.com/gophercloud/gophercloud/pull/2625) neutron: Support trunk_details extension + +CI changes: + +* [GH-2608](https://github.com/gophercloud/gophercloud/pull/2608) Drop train and ussuri jobs +* [GH-2589](https://github.com/gophercloud/gophercloud/pull/2589) Bump EmilienM/devstack-action from 0.10 to 0.11 +* [GH-2604](https://github.com/gophercloud/gophercloud/pull/2604) Bump mheap/github-action-required-labels from 3 to 4 +* [GH-2620](https://github.com/gophercloud/gophercloud/pull/2620) Pin goimport dep to a version that works with go 1.14 +* [GH-2619](https://github.com/gophercloud/gophercloud/pull/2619) Fix version comparison for acceptance tests +* [GH-2627](https://github.com/gophercloud/gophercloud/pull/2627) Limits: Fix ToDo to create registered limit and use it +* [GH-2629](https://github.com/gophercloud/gophercloud/pull/2629) [manila]: Add share from snapshot restore functional test + + ## v1.3.0 (2023-03-28) * [GH-2464](https://github.com/gophercloud/gophercloud/pull/2464) keystone: add v3 limits create operation diff --git a/vendor/github.com/gophercloud/gophercloud/provider_client.go b/vendor/github.com/gophercloud/gophercloud/provider_client.go index c603d6dbe32..12273d80491 100644 --- a/vendor/github.com/gophercloud/gophercloud/provider_client.go +++ b/vendor/github.com/gophercloud/gophercloud/provider_client.go @@ -14,7 +14,7 @@ import ( // DefaultUserAgent is the default User-Agent string set in the request header. const ( - DefaultUserAgent = "gophercloud/v1.3.0" + DefaultUserAgent = "gophercloud/v1.4.0" DefaultMaxBackoffRetries = 60 ) diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/parse.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/parse.go index 65ffcf5cf87..52a8561f0f9 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/parse.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/parse.go @@ -167,7 +167,7 @@ func (p *parser) segment() (segment, error) { if err != nil { return nil, fmt.Errorf("segment neither wildcards, literal or variable: %w", err) } - return v, nil + return v, err } func (p *parser) literal() (segment, error) { @@ -192,7 +192,7 @@ func (p *parser) variable() (segment, error) { if _, err := p.accept("="); err == nil { segs, err = p.segments() if err != nil { - return nil, fmt.Errorf("invalid segment in variable %q: %w", path, err) + return nil, fmt.Errorf("invalid segment in variable %q: %v", path, err) } } else { segs = []segment{wildcard{}} @@ -219,7 +219,7 @@ func (p *parser) fieldPath() (string, error) { } c, err := p.accept(typeIdent) if err != nil { - return "", fmt.Errorf("invalid field path component: %w", err) + return "", fmt.Errorf("invalid field path component: %v", err) } components = append(components, c) } diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/context.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/context.go index 31553e7848a..5ab5b3841da 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/context.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/context.go @@ -13,7 +13,6 @@ import ( "time" "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) @@ -100,38 +99,6 @@ func AnnotateIncomingContext(ctx context.Context, mux *ServeMux, req *http.Reque return metadata.NewIncomingContext(ctx, md), nil } -func isValidGRPCMetadataKey(key string) bool { - // Must be a valid gRPC "Header-Name" as defined here: - // https://github.com/grpc/grpc/blob/4b05dc88b724214d0c725c8e7442cbc7a61b1374/doc/PROTOCOL-HTTP2.md - // This means 0-9 a-z _ - . - // Only lowercase letters are valid in the wire protocol, but the client library will normalize - // uppercase ASCII to lowercase, so uppercase ASCII is also acceptable. - bytes := []byte(key) // gRPC validates strings on the byte level, not Unicode. - for _, ch := range bytes { - validLowercaseLetter := ch >= 'a' && ch <= 'z' - validUppercaseLetter := ch >= 'A' && ch <= 'Z' - validDigit := ch >= '0' && ch <= '9' - validOther := ch == '.' || ch == '-' || ch == '_' - if !validLowercaseLetter && !validUppercaseLetter && !validDigit && !validOther { - return false - } - } - return true -} - -func isValidGRPCMetadataTextValue(textValue string) bool { - // Must be a valid gRPC "ASCII-Value" as defined here: - // https://github.com/grpc/grpc/blob/4b05dc88b724214d0c725c8e7442cbc7a61b1374/doc/PROTOCOL-HTTP2.md - // This means printable ASCII (including/plus spaces); 0x20 to 0x7E inclusive. - bytes := []byte(textValue) // gRPC validates strings on the byte level, not Unicode. - for _, ch := range bytes { - if ch < 0x20 || ch > 0x7E { - return false - } - } - return true -} - func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcMethodName string, options ...AnnotateContextOption) (context.Context, metadata.MD, error) { ctx = withRPCMethod(ctx, rpcMethodName) for _, o := range options { @@ -154,10 +121,6 @@ func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcM pairs = append(pairs, "authorization", val) } if h, ok := mux.incomingHeaderMatcher(key); ok { - if !isValidGRPCMetadataKey(h) { - grpclog.Errorf("HTTP header name %q is not valid as gRPC metadata key; skipping", h) - continue - } // Handles "-bin" metadata in grpc, since grpc will do another base64 // encode before sending to server, we need to decode it first. if strings.HasSuffix(key, metadataHeaderBinarySuffix) { @@ -167,9 +130,6 @@ func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcM } val = string(b) - } else if !isValidGRPCMetadataTextValue(val) { - grpclog.Errorf("Value of HTTP header %q contains non-ASCII value (not valid as gRPC metadata): skipping", h) - continue } pairs = append(pairs, h, val) } diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_jsonpb.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_jsonpb.go index 51b8247da2a..524ea057ccb 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_jsonpb.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_jsonpb.go @@ -92,20 +92,23 @@ func (j *JSONPb) marshalNonProtoField(v interface{}) ([]byte, error) { if rv.Type().Elem().Implements(protoMessageType) { var buf bytes.Buffer - if err := buf.WriteByte('['); err != nil { + err := buf.WriteByte('[') + if err != nil { return nil, err } for i := 0; i < rv.Len(); i++ { if i != 0 { - if err := buf.WriteByte(','); err != nil { + err = buf.WriteByte(',') + if err != nil { return nil, err } } - if err := j.marshalTo(&buf, rv.Index(i).Interface().(proto.Message)); err != nil { + if err = j.marshalTo(&buf, rv.Index(i).Interface().(proto.Message)); err != nil { return nil, err } } - if err := buf.WriteByte(']'); err != nil { + err = buf.WriteByte(']') + if err != nil { return nil, err } @@ -114,16 +117,17 @@ func (j *JSONPb) marshalNonProtoField(v interface{}) ([]byte, error) { if rv.Type().Elem().Implements(typeProtoEnum) { var buf bytes.Buffer - if err := buf.WriteByte('['); err != nil { + err := buf.WriteByte('[') + if err != nil { return nil, err } for i := 0; i < rv.Len(); i++ { if i != 0 { - if err := buf.WriteByte(','); err != nil { + err = buf.WriteByte(',') + if err != nil { return nil, err } } - var err error if j.UseEnumNumbers { _, err = buf.WriteString(strconv.FormatInt(rv.Index(i).Int(), 10)) } else { @@ -133,7 +137,8 @@ func (j *JSONPb) marshalNonProtoField(v interface{}) ([]byte, error) { return nil, err } } - if err := buf.WriteByte(']'); err != nil { + err = buf.WriteByte(']') + if err != nil { return nil, err } @@ -214,7 +219,8 @@ func decodeJSONPb(d *json.Decoder, unmarshaler protojson.UnmarshalOptions, v int // Decode into bytes for marshalling var b json.RawMessage - if err := d.Decode(&b); err != nil { + err := d.Decode(&b) + if err != nil { return err } @@ -233,7 +239,8 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions if rv.Type().ConvertibleTo(typeProtoMessage) { // Decode into bytes for marshalling var b json.RawMessage - if err := d.Decode(&b); err != nil { + err := d.Decode(&b) + if err != nil { return err } diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/mux.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/mux.go index 139bbbad49c..9fb2960d959 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/mux.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/mux.go @@ -80,7 +80,7 @@ func WithForwardResponseOption(forwardResponseOption func(context.Context, http. } } -// WithUnescapingMode sets the escaping type. See the definitions of UnescapingMode +// WithEscapingType sets the escaping type. See the definitions of UnescapingMode // for more information. func WithUnescapingMode(mode UnescapingMode) ServeMuxOption { return func(serveMux *ServeMux) { @@ -101,9 +101,8 @@ func SetQueryParameterParser(queryParameterParser QueryParameterParser) ServeMux type HeaderMatcherFunc func(string) (string, bool) // DefaultHeaderMatcher is used to pass http request headers to/from gRPC context. This adds permanent HTTP header -// keys (as specified by the IANA, e.g: Accept, Cookie, Host) to the gRPC metadata with the grpcgateway- prefix. If you want to know which headers are considered permanent, you can view the isPermanentHTTPHeader function. -// HTTP headers that start with 'Grpc-Metadata-' are mapped to gRPC metadata after removing the prefix 'Grpc-Metadata-'. -// Other headers are not added to the gRPC metadata. +// keys (as specified by the IANA) to gRPC context with grpcgateway- prefix. HTTP headers that start with +// 'Grpc-Metadata-' are mapped to gRPC metadata after removing prefix 'Grpc-Metadata-'. func DefaultHeaderMatcher(key string) (string, bool) { switch key = textproto.CanonicalMIMEHeaderKey(key); { case isPermanentHTTPHeader(key): @@ -231,6 +230,7 @@ func WithHealthEndpointAt(healthCheckClient grpc_health_v1.HealthClient, endpoin w.Header().Set("Content-Type", "application/json") if resp.GetStatus() != grpc_health_v1.HealthCheckResponse_SERVING { + var err error switch resp.GetStatus() { case grpc_health_v1.HealthCheckResponse_NOT_SERVING, grpc_health_v1.HealthCheckResponse_UNKNOWN: err = status.Error(codes.Unavailable, resp.String()) diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/pattern.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/pattern.go index 8f90d15a562..df7cb81426a 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/pattern.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/pattern.go @@ -15,6 +15,8 @@ var ( ErrNotMatch = errors.New("not match to the path pattern") // ErrInvalidPattern indicates that the given definition of Pattern is not valid. ErrInvalidPattern = errors.New("invalid pattern") + // ErrMalformedSequence indicates that an escape sequence was malformed. + ErrMalformedSequence = errors.New("malformed escape sequence") ) type MalformedSequenceError string diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/query.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/query.go index 31ce33a7621..56b796e6f4d 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/query.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/query.go @@ -47,7 +47,8 @@ type DefaultQueryParser struct{} // A value is ignored if its key starts with one of the elements in "filter". func (*DefaultQueryParser) Parse(msg proto.Message, values url.Values, filter *utilities.DoubleArray) error { for key, values := range values { - if match := valuesKeyRegexp.FindStringSubmatch(key); len(match) == 3 { + match := valuesKeyRegexp.FindStringSubmatch(key) + if len(match) == 3 { key = match[1] values = append([]string{match[2]}, values...) } @@ -320,13 +321,15 @@ func parseMessage(msgDescriptor protoreflect.MessageDescriptor, value string) (p msg = fm case "google.protobuf.Value": var v structpb.Value - if err := protojson.Unmarshal([]byte(value), &v); err != nil { + err := protojson.Unmarshal([]byte(value), &v) + if err != nil { return protoreflect.Value{}, err } msg = &v case "google.protobuf.Struct": var v structpb.Struct - if err := protojson.Unmarshal([]byte(value), &v); err != nil { + err := protojson.Unmarshal([]byte(value), &v) + if err != nil { return protoreflect.Value{}, err } msg = &v diff --git a/vendor/github.com/hashicorp/consul/api/config_entry.go b/vendor/github.com/hashicorp/consul/api/config_entry.go index 4e9682ee6f8..7160d7d228b 100644 --- a/vendor/github.com/hashicorp/consul/api/config_entry.go +++ b/vendor/github.com/hashicorp/consul/api/config_entry.go @@ -35,6 +35,10 @@ const ( const ( BuiltinAWSLambdaExtension string = "builtin/aws/lambda" BuiltinLuaExtension string = "builtin/lua" + // BuiltinValidateExtension should not be exposed directly or accepted as a valid configured + // extension type, as it is only used indirectly via troubleshooting tools. It is included here + // for common reference alongside other builtin extensions. + BuiltinValidateExtension string = "builtin/proxy/validate" ) type ConfigEntry interface { @@ -254,6 +258,15 @@ type PassiveHealthCheck struct { // when an outlier status is detected through consecutive 5xx. // This setting can be used to disable ejection or to ramp it up slowly. EnforcingConsecutive5xx *uint32 `json:",omitempty" alias:"enforcing_consecutive_5xx"` + + // The maximum % of an upstream cluster that can be ejected due to outlier detection. + // Defaults to 10% but will eject at least one host regardless of the value. + MaxEjectionPercent *uint32 `json:",omitempty" alias:"max_ejection_percent"` + + // The base time that a host is ejected for. The real time is equal to the base time + // multiplied by the number of times the host has been ejected and is capped by + // max_ejection_time (Default 300s). Defaults to 30000ms or 30s. + BaseEjectionTime *time.Duration `json:",omitempty" alias:"base_ejection_time"` } // UpstreamLimits describes the limits that are associated with a specific diff --git a/vendor/github.com/hashicorp/consul/api/connect.go b/vendor/github.com/hashicorp/consul/api/connect.go index a40d1e2321a..1c1da9a3798 100644 --- a/vendor/github.com/hashicorp/consul/api/connect.go +++ b/vendor/github.com/hashicorp/consul/api/connect.go @@ -1,5 +1,8 @@ package api +// TelemetryCollectorName is the service name for the Consul Telemetry Collector +const TelemetryCollectorName string = "consul-telemetry-collector" + // Connect can be used to work with endpoints related to Connect, the // feature for securely connecting services within Consul. type Connect struct { diff --git a/vendor/github.com/hashicorp/nomad/api/allocations.go b/vendor/github.com/hashicorp/nomad/api/allocations.go index 0159a9e12e7..87f7d9b1160 100644 --- a/vendor/github.com/hashicorp/nomad/api/allocations.go +++ b/vendor/github.com/hashicorp/nomad/api/allocations.go @@ -326,6 +326,7 @@ func (a *Allocation) Stub() *AllocationListStub { TaskStates: a.TaskStates, DeploymentStatus: a.DeploymentStatus, FollowupEvalID: a.FollowupEvalID, + NextAllocation: a.NextAllocation, RescheduleTracker: a.RescheduleTracker, PreemptedAllocations: a.PreemptedAllocations, PreemptedByAllocation: a.PreemptedByAllocation, @@ -379,6 +380,7 @@ type AllocationListStub struct { TaskStates map[string]*TaskState DeploymentStatus *AllocDeploymentStatus FollowupEvalID string + NextAllocation string RescheduleTracker *RescheduleTracker PreemptedAllocations []string PreemptedByAllocation string diff --git a/vendor/github.com/hashicorp/nomad/api/api.go b/vendor/github.com/hashicorp/nomad/api/api.go index 1bf97f05f95..ac755e254f7 100644 --- a/vendor/github.com/hashicorp/nomad/api/api.go +++ b/vendor/github.com/hashicorp/nomad/api/api.go @@ -895,13 +895,16 @@ func (c *Client) websocket(endpoint string, q *QueryOptions) (*websocket.Conn, * conn, resp, err := dialer.Dial(rhttp.URL.String(), rhttp.Header) // check resp status code, as it's more informative than handshake error we get from ws library - if resp != nil && resp.StatusCode != 101 { + if resp != nil && resp.StatusCode != http.StatusSwitchingProtocols { var buf bytes.Buffer if resp.Header.Get("Content-Encoding") == "gzip" { greader, err := gzip.NewReader(resp.Body) if err != nil { - return nil, nil, fmt.Errorf("Unexpected response code: %d", resp.StatusCode) + return nil, nil, newUnexpectedResponseError( + fromStatusCode(resp.StatusCode), + withExpectedStatuses([]int{http.StatusSwitchingProtocols}), + withError(err)) } io.Copy(&buf, greader) } else { @@ -909,7 +912,11 @@ func (c *Client) websocket(endpoint string, q *QueryOptions) (*websocket.Conn, * } resp.Body.Close() - return nil, nil, fmt.Errorf("Unexpected response code: %d (%s)", resp.StatusCode, buf.Bytes()) + return nil, nil, newUnexpectedResponseError( + fromStatusCode(resp.StatusCode), + withExpectedStatuses([]int{http.StatusSwitchingProtocols}), + withBody(fmt.Sprint(buf.Bytes())), + ) } return conn, resp, err @@ -1129,24 +1136,6 @@ func encodeBody(obj interface{}) (io.Reader, error) { return buf, nil } -// requireOK is used to wrap doRequest and check for a 200 -func requireOK(d time.Duration, resp *http.Response, e error) (time.Duration, *http.Response, error) { - if e != nil { - if resp != nil { - resp.Body.Close() - } - return d, nil, e - } - if resp.StatusCode != 200 { - var buf bytes.Buffer - _, _ = io.Copy(&buf, resp.Body) - _ = resp.Body.Close() - body := strings.TrimSpace(buf.String()) - return d, nil, fmt.Errorf("Unexpected response code: %d (%s)", resp.StatusCode, body) - } - return d, resp, nil -} - // Context returns the context used for canceling HTTP requests related to this query func (o *QueryOptions) Context() context.Context { if o != nil && o.ctx != nil { diff --git a/vendor/github.com/hashicorp/nomad/api/contexts/contexts.go b/vendor/github.com/hashicorp/nomad/api/contexts/contexts.go index 2ce523a72dc..5176f5b8290 100644 --- a/vendor/github.com/hashicorp/nomad/api/contexts/contexts.go +++ b/vendor/github.com/hashicorp/nomad/api/contexts/contexts.go @@ -15,6 +15,7 @@ const ( Evals Context = "evals" Jobs Context = "jobs" Nodes Context = "nodes" + NodePools Context = "node_pools" Namespaces Context = "namespaces" Quotas Context = "quotas" Recommendations Context = "recommendations" diff --git a/vendor/github.com/hashicorp/nomad/api/error_unexpected_response.go b/vendor/github.com/hashicorp/nomad/api/error_unexpected_response.go new file mode 100644 index 00000000000..b843fc7ab9e --- /dev/null +++ b/vendor/github.com/hashicorp/nomad/api/error_unexpected_response.go @@ -0,0 +1,178 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +package api + +import ( + "bytes" + "fmt" + "io" + "net/http" + "strings" + "time" + + "golang.org/x/exp/slices" +) + +// UnexpectedResponseError tracks the components for API errors encountered when +// requireOK and requireStatusIn's conditions are not met. +type UnexpectedResponseError struct { + expected []int + statusCode int + statusText string + body string + err error + additional error +} + +func (e UnexpectedResponseError) HasExpectedStatuses() bool { return len(e.expected) > 0 } +func (e UnexpectedResponseError) ExpectedStatuses() []int { return e.expected } +func (e UnexpectedResponseError) HasStatusCode() bool { return e.statusCode != 0 } +func (e UnexpectedResponseError) StatusCode() int { return e.statusCode } +func (e UnexpectedResponseError) HasStatusText() bool { return e.statusText != "" } +func (e UnexpectedResponseError) StatusText() string { return e.statusText } +func (e UnexpectedResponseError) HasBody() bool { return e.body != "" } +func (e UnexpectedResponseError) Body() string { return e.body } +func (e UnexpectedResponseError) HasError() bool { return e.err != nil } +func (e UnexpectedResponseError) Unwrap() error { return e.err } +func (e UnexpectedResponseError) HasAdditional() bool { return e.additional != nil } +func (e UnexpectedResponseError) Additional() error { return e.additional } +func newUnexpectedResponseError(src unexpectedResponseErrorSource, opts ...unexpectedResponseErrorOption) UnexpectedResponseError { + nErr := src() + for _, opt := range opts { + opt(nErr) + } + if nErr.statusText == "" { + // the stdlib's http.StatusText function is a good place to start + nErr.statusFromCode(http.StatusText) + } + + return *nErr +} + +// Use textual representation of the given integer code. Called when status text +// is not set using the WithStatusText option. +func (e UnexpectedResponseError) statusFromCode(f func(int) string) { + e.statusText = f(e.statusCode) + if !e.HasStatusText() { + e.statusText = "unknown status code" + } +} + +func (e UnexpectedResponseError) Error() string { + var eTxt strings.Builder + eTxt.WriteString("Unexpected response code") + if e.HasBody() || e.HasStatusCode() { + eTxt.WriteString(": ") + } + if e.HasStatusCode() { + eTxt.WriteString(fmt.Sprint(e.statusCode)) + if e.HasBody() { + eTxt.WriteRune(' ') + } + } + if e.HasBody() { + eTxt.WriteString(fmt.Sprintf("(%s)", e.body)) + } + + if e.HasAdditional() { + eTxt.WriteString(fmt.Sprintf(". Additionally, an error occurred while constructing this error (%s); the body might be truncated or missing.", e.additional.Error())) + } + + return eTxt.String() +} + +// UnexpectedResponseErrorOptions are functions passed to NewUnexpectedResponseError +// to customize the created error. +type unexpectedResponseErrorOption func(*UnexpectedResponseError) + +// withError allows the addition of a Go error that may have been encountered +// while processing the response. For example, if there is an error constructing +// the gzip reader to process a gzip-encoded response body. +func withError(e error) unexpectedResponseErrorOption { + return func(u *UnexpectedResponseError) { u.err = e } +} + +// withBody overwrites the Body value with the provided custom value +func withBody(b string) unexpectedResponseErrorOption { + return func(u *UnexpectedResponseError) { u.body = b } +} + +// withStatusText overwrites the StatusText value the provided custom value +func withStatusText(st string) unexpectedResponseErrorOption { + return func(u *UnexpectedResponseError) { u.statusText = st } +} + +// withExpectedStatuses provides a list of statuses that the receiving function +// expected to receive. This can be used by API callers to provide more feedback +// to end-users. +func withExpectedStatuses(s []int) unexpectedResponseErrorOption { + return func(u *UnexpectedResponseError) { u.expected = slices.Clone(s) } +} + +// unexpectedResponseErrorSource provides the basis for a NewUnexpectedResponseError. +type unexpectedResponseErrorSource func() *UnexpectedResponseError + +// fromHTTPResponse read an open HTTP response, drains and closes its body as +// the data for the UnexpectedResponseError. +func fromHTTPResponse(resp *http.Response) unexpectedResponseErrorSource { + return func() *UnexpectedResponseError { + u := new(UnexpectedResponseError) + + if resp != nil { + // collect and close the body + var buf bytes.Buffer + if _, e := io.Copy(&buf, resp.Body); e != nil { + u.additional = e + } + + // Body has been tested as safe to close more than once + _ = resp.Body.Close() + body := strings.TrimSpace(buf.String()) + + // make and return the error + u.statusCode = resp.StatusCode + u.statusText = strings.TrimSpace(strings.TrimPrefix(resp.Status, fmt.Sprint(resp.StatusCode))) + u.body = body + } + return u + } +} + +// fromStatusCode attempts to resolve the status code to status text using +// the resolving function provided inside of the NewUnexpectedResponseError +// implementation. +func fromStatusCode(sc int) unexpectedResponseErrorSource { + return func() *UnexpectedResponseError { return &UnexpectedResponseError{statusCode: sc} } +} + +// doRequestWrapper is a function that wraps the client's doRequest method +// and can be used to provide error and response handling +type doRequestWrapper = func(time.Duration, *http.Response, error) (time.Duration, *http.Response, error) + +// requireOK is used to wrap doRequest and check for a 200 +func requireOK(d time.Duration, resp *http.Response, e error) (time.Duration, *http.Response, error) { + f := requireStatusIn(http.StatusOK) + return f(d, resp, e) +} + +// requireStatusIn is a doRequestWrapper generator that takes expected HTTP +// response codes and validates that the received response code is among them +func requireStatusIn(statuses ...int) doRequestWrapper { + return func(d time.Duration, resp *http.Response, e error) (time.Duration, *http.Response, error) { + if e != nil { + if resp != nil { + _ = resp.Body.Close() + } + return d, nil, e + } + + for _, status := range statuses { + if resp.StatusCode == status { + return d, resp, nil + } + } + + return d, nil, newUnexpectedResponseError(fromHTTPResponse(resp), withExpectedStatuses(statuses)) + } +} diff --git a/vendor/github.com/hashicorp/nomad/api/jobs.go b/vendor/github.com/hashicorp/nomad/api/jobs.go index 64b25c7108f..f768b351044 100644 --- a/vendor/github.com/hashicorp/nomad/api/jobs.go +++ b/vendor/github.com/hashicorp/nomad/api/jobs.go @@ -29,6 +29,9 @@ const ( // on all clients. JobTypeSysbatch = "sysbatch" + // JobDefaultPriority is the default priority if not specified. + JobDefaultPriority = 50 + // PeriodicSpecCron is used for a cron spec. PeriodicSpecCron = "cron" @@ -790,9 +793,11 @@ func (m *Multiregion) Copy() *Multiregion { copyRegion.Name = region.Name copyRegion.Count = pointerOf(*region.Count) copyRegion.Datacenters = append(copyRegion.Datacenters, region.Datacenters...) + copyRegion.NodePool = region.NodePool for k, v := range region.Meta { copyRegion.Meta[k] = v } + copy.Regions = append(copy.Regions, copyRegion) } return copy @@ -807,6 +812,7 @@ type MultiregionRegion struct { Name string `hcl:",label"` Count *int `hcl:"count,optional"` Datacenters []string `hcl:"datacenters,optional"` + NodePool string `hcl:"node_pool,optional"` Meta map[string]string `hcl:"meta,block"` } @@ -940,6 +946,7 @@ type Job struct { Priority *int `hcl:"priority,optional"` AllAtOnce *bool `mapstructure:"all_at_once" hcl:"all_at_once,optional"` Datacenters []string `hcl:"datacenters,optional"` + NodePool *string `hcl:"node_pool,optional"` Constraints []*Constraint `hcl:"constraint,block"` Affinities []*Affinity `hcl:"affinity,block"` TaskGroups []*TaskGroup `hcl:"group,block"` @@ -1003,7 +1010,7 @@ func (j *Job) Canonicalize() { j.Namespace = pointerOf(DefaultNamespace) } if j.Priority == nil { - j.Priority = pointerOf(0) + j.Priority = pointerOf(JobDefaultPriority) } if j.Stop == nil { j.Stop = pointerOf(false) @@ -1011,8 +1018,8 @@ func (j *Job) Canonicalize() { if j.Region == nil { j.Region = pointerOf(GlobalRegion) } - if j.Namespace == nil { - j.Namespace = pointerOf("default") + if j.NodePool == nil { + j.NodePool = pointerOf(NodePoolDefault) } if j.Type == nil { j.Type = pointerOf("service") diff --git a/vendor/github.com/hashicorp/nomad/api/node_pools.go b/vendor/github.com/hashicorp/nomad/api/node_pools.go new file mode 100644 index 00000000000..37ecf155523 --- /dev/null +++ b/vendor/github.com/hashicorp/nomad/api/node_pools.go @@ -0,0 +1,105 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +package api + +import ( + "errors" + "net/url" +) + +const ( + // NodePoolAll is the node pool that always includes all nodes. + NodePoolAll = "all" + + // NodePoolDefault is the default node pool. + NodePoolDefault = "default" +) + +// NodePools is used to access node pools endpoints. +type NodePools struct { + client *Client +} + +// NodePools returns a handle on the node pools endpoints. +func (c *Client) NodePools() *NodePools { + return &NodePools{client: c} +} + +// List is used to list all node pools. +func (n *NodePools) List(q *QueryOptions) ([]*NodePool, *QueryMeta, error) { + var resp []*NodePool + qm, err := n.client.query("/v1/node/pools", &resp, q) + if err != nil { + return nil, nil, err + } + return resp, qm, nil +} + +// PrefixList is used to list node pools that match a given prefix. +func (n *NodePools) PrefixList(prefix string, q *QueryOptions) ([]*NodePool, *QueryMeta, error) { + if q == nil { + q = &QueryOptions{} + } + q.Prefix = prefix + return n.List(q) +} + +// Info is used to fetch details of a specific node pool. +func (n *NodePools) Info(name string, q *QueryOptions) (*NodePool, *QueryMeta, error) { + if name == "" { + return nil, nil, errors.New("missing node pool name") + } + + var resp NodePool + qm, err := n.client.query("/v1/node/pool/"+url.PathEscape(name), &resp, q) + if err != nil { + return nil, nil, err + } + return &resp, qm, nil +} + +// Register is used to create or update a node pool. +func (n *NodePools) Register(pool *NodePool, w *WriteOptions) (*WriteMeta, error) { + if pool == nil { + return nil, errors.New("missing node pool") + } + if pool.Name == "" { + return nil, errors.New("missing node pool name") + } + + wm, err := n.client.put("/v1/node/pools", pool, nil, w) + if err != nil { + return nil, err + } + return wm, nil +} + +// Delete is used to delete a node pool. +func (n *NodePools) Delete(name string, w *WriteOptions) (*WriteMeta, error) { + if name == "" { + return nil, errors.New("missing node pool name") + } + + wm, err := n.client.delete("/v1/node/pool/"+url.PathEscape(name), nil, nil, w) + if err != nil { + return nil, err + } + return wm, nil +} + +// NodePool is used to serialize a node pool. +type NodePool struct { + Name string `hcl:"name,label"` + Description string `hcl:"description,optional"` + Meta map[string]string `hcl:"meta,block"` + SchedulerConfiguration *NodePoolSchedulerConfiguration `hcl:"scheduler_configuration,block"` + CreateIndex uint64 + ModifyIndex uint64 +} + +// NodePoolSchedulerConfiguration is used to serialize the scheduler +// configuration of a node pool. +type NodePoolSchedulerConfiguration struct { + SchedulerAlgorithm SchedulerAlgorithm `hcl:"scheduler_algorithm,optional"` +} diff --git a/vendor/github.com/hashicorp/nomad/api/nodes.go b/vendor/github.com/hashicorp/nomad/api/nodes.go index dfc5646be09..697c7d731d3 100644 --- a/vendor/github.com/hashicorp/nomad/api/nodes.go +++ b/vendor/github.com/hashicorp/nomad/api/nodes.go @@ -553,6 +553,7 @@ type Node struct { Links map[string]string Meta map[string]string NodeClass string + NodePool string CgroupParent string Drain bool DrainStrategy *DrainStrategy @@ -914,6 +915,7 @@ type NodeListStub struct { Datacenter string Name string NodeClass string + NodePool string Version string Drain bool SchedulingEligibility string diff --git a/vendor/github.com/hashicorp/nomad/api/operator.go b/vendor/github.com/hashicorp/nomad/api/operator.go index ba8d41cecd4..32faf354661 100644 --- a/vendor/github.com/hashicorp/nomad/api/operator.go +++ b/vendor/github.com/hashicorp/nomad/api/operator.go @@ -6,8 +6,8 @@ package api import ( "encoding/json" "errors" - "fmt" "io" + "net/http" "strconv" "strings" "time" @@ -341,13 +341,15 @@ func (op *Operator) LicenseGet(q *QueryOptions) (*LicenseReply, *QueryMeta, erro } defer resp.Body.Close() - if resp.StatusCode == 204 { + if resp.StatusCode == http.StatusNoContent { return nil, nil, errors.New("Nomad Enterprise only endpoint") } - if resp.StatusCode != 200 { - body, _ := io.ReadAll(resp.Body) - return nil, nil, fmt.Errorf("Unexpected response code: %d (%s)", resp.StatusCode, body) + if resp.StatusCode != http.StatusOK { + return nil, nil, newUnexpectedResponseError( + fromHTTPResponse(resp), + withExpectedStatuses([]int{http.StatusOK, http.StatusNoContent}), + ) } err = json.NewDecoder(resp.Body).Decode(&reply) diff --git a/vendor/github.com/hashicorp/nomad/api/services.go b/vendor/github.com/hashicorp/nomad/api/services.go index 450236547b5..95f02781006 100644 --- a/vendor/github.com/hashicorp/nomad/api/services.go +++ b/vendor/github.com/hashicorp/nomad/api/services.go @@ -212,6 +212,7 @@ type ServiceCheck struct { Interval time.Duration `hcl:"interval,optional"` Timeout time.Duration `hcl:"timeout,optional"` InitialStatus string `mapstructure:"initial_status" hcl:"initial_status,optional"` + TLSServerName string `mapstructure:"tls_server_name" hcl:"tls_server_name,optional"` TLSSkipVerify bool `mapstructure:"tls_skip_verify" hcl:"tls_skip_verify,optional"` Header map[string][]string `hcl:"header,block"` Method string `hcl:"method,optional"` diff --git a/vendor/github.com/hashicorp/nomad/api/tasks.go b/vendor/github.com/hashicorp/nomad/api/tasks.go index e928b3a0418..65344290510 100644 --- a/vendor/github.com/hashicorp/nomad/api/tasks.go +++ b/vendor/github.com/hashicorp/nomad/api/tasks.go @@ -641,12 +641,19 @@ func (g *TaskGroup) AddSpread(s *Spread) *TaskGroup { type LogConfig struct { MaxFiles *int `mapstructure:"max_files" hcl:"max_files,optional"` MaxFileSizeMB *int `mapstructure:"max_file_size" hcl:"max_file_size,optional"` + + // COMPAT(1.6.0): Enabled had to be swapped for Disabled to fix a backwards + // compatibility bug when restoring pre-1.5.4 jobs. Remove in 1.6.0 + Enabled *bool `mapstructure:"enabled" hcl:"enabled,optional"` + + Disabled *bool `mapstructure:"disabled" hcl:"disabled,optional"` } func DefaultLogConfig() *LogConfig { return &LogConfig{ MaxFiles: pointerOf(10), MaxFileSizeMB: pointerOf(10), + Disabled: pointerOf(false), } } @@ -657,6 +664,9 @@ func (l *LogConfig) Canonicalize() { if l.MaxFileSizeMB == nil { l.MaxFileSizeMB = pointerOf(10) } + if l.Disabled == nil { + l.Disabled = pointerOf(false) + } } // DispatchPayloadConfig configures how a task gets its input from a job dispatch diff --git a/vendor/github.com/hashicorp/nomad/api/variables.go b/vendor/github.com/hashicorp/nomad/api/variables.go index 91dc13cf460..86458c13ae1 100644 --- a/vendor/github.com/hashicorp/nomad/api/variables.go +++ b/vendor/github.com/hashicorp/nomad/api/variables.go @@ -4,14 +4,11 @@ package api import ( - "bytes" "encoding/json" "errors" "fmt" - "io" "net/http" "strings" - "time" ) const ( @@ -457,39 +454,3 @@ type ErrCASConflict struct { func (e ErrCASConflict) Error() string { return fmt.Sprintf("cas conflict: expected ModifyIndex %v; found %v", e.CheckIndex, e.Conflict.ModifyIndex) } - -// doRequestWrapper is a function that wraps the client's doRequest method -// and can be used to provide error and response handling -type doRequestWrapper = func(time.Duration, *http.Response, error) (time.Duration, *http.Response, error) - -// requireStatusIn is a doRequestWrapper generator that takes expected HTTP -// response codes and validates that the received response code is among them -func requireStatusIn(statuses ...int) doRequestWrapper { - fn := func(d time.Duration, resp *http.Response, e error) (time.Duration, *http.Response, error) { - if e != nil { - if resp != nil { - _ = resp.Body.Close() - } - return d, nil, e - } - - for _, status := range statuses { - if resp.StatusCode == status { - return d, resp, nil - } - } - - return d, nil, generateUnexpectedResponseCodeError(resp) - } - return fn -} - -// generateUnexpectedResponseCodeError creates a standardized error -// when the the API client's newRequest method receives an unexpected -// HTTP response code when accessing the variable's HTTP API -func generateUnexpectedResponseCodeError(resp *http.Response) error { - var buf bytes.Buffer - _, _ = io.Copy(&buf, resp.Body) - _ = resp.Body.Close() - return fmt.Errorf("Unexpected response code: %d (%s)", resp.StatusCode, buf.Bytes()) -} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/certificate.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/certificate.go index 62785523170..e56e141558c 100644 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/certificate.go +++ b/vendor/github.com/hetznercloud/hcloud-go/hcloud/certificate.go @@ -260,7 +260,7 @@ func (o CertificateCreateOpts) validateUploaded() error { return nil } -// Create creates a new certificate uploaded certificate. +// Create creates a new uploaded certificate. // // Create returns an error for certificates of any other type. Use // CreateCertificate to create such certificates. diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/hcloud.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/hcloud.go index 7adc8745afe..55f7bf9f2ac 100644 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/hcloud.go +++ b/vendor/github.com/hetznercloud/hcloud-go/hcloud/hcloud.go @@ -2,4 +2,4 @@ package hcloud // Version is the library's version following Semantic Versioning. -const Version = "1.42.0" // x-release-please-version +const Version = "1.45.1" // x-release-please-version diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/iso.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/iso.go index d5814cb8023..d0a2a137f5a 100644 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/iso.go +++ b/vendor/github.com/hetznercloud/hcloud-go/hcloud/iso.go @@ -134,10 +134,12 @@ func (c *ISOClient) List(ctx context.Context, opts ISOListOpts) ([]*ISO, *Respon // All returns all ISOs. func (c *ISOClient) All(ctx context.Context) ([]*ISO, error) { - allISOs := []*ISO{} + return c.AllWithOpts(ctx, ISOListOpts{ListOpts: ListOpts{PerPage: 50}}) +} - opts := ISOListOpts{} - opts.PerPage = 50 +// AllWithOpts returns all ISOs for the given options. +func (c *ISOClient) AllWithOpts(ctx context.Context, opts ISOListOpts) ([]*ISO, error) { + allISOs := make([]*ISO, 0) err := c.client.all(func(page int) (*Response, error) { opts.Page = page diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/primary_ip.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/primary_ip.go index e328b9b36ad..c478241d120 100644 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/primary_ip.go +++ b/vendor/github.com/hetznercloud/hcloud-go/hcloud/primary_ip.go @@ -43,6 +43,32 @@ type PrimaryIPDNSPTR struct { IP string } +// changeDNSPtr changes or resets the reverse DNS pointer for a IP address. +// Pass a nil ptr to reset the reverse DNS pointer to its default value. +func (p *PrimaryIP) changeDNSPtr(ctx context.Context, client *Client, ip net.IP, ptr *string) (*Action, *Response, error) { + reqBody := schema.PrimaryIPActionChangeDNSPtrRequest{ + IP: ip.String(), + DNSPtr: ptr, + } + reqBodyData, err := json.Marshal(reqBody) + if err != nil { + return nil, nil, err + } + + path := fmt.Sprintf("/primary_ips/%d/actions/change_dns_ptr", p.ID) + req, err := client.NewRequest(ctx, "POST", path, bytes.NewReader(reqBodyData)) + if err != nil { + return nil, nil, err + } + + var respBody PrimaryIPChangeDNSPtrResult + resp, err := client.Do(req, &respBody) + if err != nil { + return nil, resp, err + } + return ActionFromSchema(respBody.Action), resp, nil +} + // GetDNSPtrForIP searches for the dns assigned to the given IP address. // It returns an error if there is no dns set for the given IP address. func (p *PrimaryIP) GetDNSPtrForIP(ip net.IP) (string, error) { diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema.go index b72db88d2f0..fb2079faf26 100644 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema.go +++ b/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema.go @@ -278,15 +278,16 @@ func ServerPrivateNetFromSchema(s schema.ServerPrivateNet) ServerPrivateNet { // ServerTypeFromSchema converts a schema.ServerType to a ServerType. func ServerTypeFromSchema(s schema.ServerType) *ServerType { st := &ServerType{ - ID: s.ID, - Name: s.Name, - Description: s.Description, - Cores: s.Cores, - Memory: s.Memory, - Disk: s.Disk, - StorageType: StorageType(s.StorageType), - CPUType: CPUType(s.CPUType), - Architecture: Architecture(s.Architecture), + ID: s.ID, + Name: s.Name, + Description: s.Description, + Cores: s.Cores, + Memory: s.Memory, + Disk: s.Disk, + StorageType: StorageType(s.StorageType), + CPUType: CPUType(s.CPUType), + Architecture: Architecture(s.Architecture), + IncludedTraffic: s.IncludedTraffic, } for _, price := range s.Prices { st.Pricings = append(st.Pricings, ServerTypeLocationPricing{ diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/primary_ip.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/primary_ip.go index d232a732d19..f6c7229a2b4 100644 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/primary_ip.go +++ b/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/primary_ip.go @@ -53,3 +53,10 @@ type PrimaryIPListResult struct { type PrimaryIPUpdateResult struct { PrimaryIP PrimaryIP `json:"primary_ip"` } + +// PrimaryIPActionChangeDNSPtrRequest defines the schema for the request to +// change a Primary IP's reverse DNS pointer. +type PrimaryIPActionChangeDNSPtrRequest struct { + IP string `json:"ip"` + DNSPtr *string `json:"dns_ptr"` +} diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/server_type.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/server_type.go index e2fe2f72615..1294a00517f 100644 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/server_type.go +++ b/vendor/github.com/hetznercloud/hcloud-go/hcloud/schema/server_type.go @@ -2,16 +2,17 @@ package schema // ServerType defines the schema of a server type. type ServerType struct { - ID int `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Cores int `json:"cores"` - Memory float32 `json:"memory"` - Disk int `json:"disk"` - StorageType string `json:"storage_type"` - CPUType string `json:"cpu_type"` - Architecture string `json:"architecture"` - Prices []PricingServerTypePrice `json:"prices"` + ID int `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + Cores int `json:"cores"` + Memory float32 `json:"memory"` + Disk int `json:"disk"` + StorageType string `json:"storage_type"` + CPUType string `json:"cpu_type"` + Architecture string `json:"architecture"` + IncludedTraffic int64 `json:"included_traffic"` + Prices []PricingServerTypePrice `json:"prices"` } // ServerTypeListResponse defines the schema of the response when diff --git a/vendor/github.com/hetznercloud/hcloud-go/hcloud/server_type.go b/vendor/github.com/hetznercloud/hcloud-go/hcloud/server_type.go index 37ebb7f0903..2a5c90a5ce1 100644 --- a/vendor/github.com/hetznercloud/hcloud-go/hcloud/server_type.go +++ b/vendor/github.com/hetznercloud/hcloud-go/hcloud/server_type.go @@ -20,7 +20,9 @@ type ServerType struct { StorageType StorageType CPUType CPUType Architecture Architecture - Pricings []ServerTypeLocationPricing + // IncludedTraffic is the free traffic per month in bytes + IncludedTraffic int64 + Pricings []ServerTypeLocationPricing } // StorageType specifies the type of storage. diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/README.md b/vendor/github.com/ionos-cloud/sdk-go/v6/README.md index f020bdf4333..48ab1f3881f 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/README.md +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/README.md @@ -352,7 +352,6 @@ KubernetesApi | [**K8sPut**](docs/api/KubernetesApi.md#k8sput) | **Put** /k8s/{k KubernetesApi | [**K8sVersionsDefaultGet**](docs/api/KubernetesApi.md#k8sversionsdefaultget) | **Get** /k8s/versions/default | Get Default Kubernetes Version KubernetesApi | [**K8sVersionsGet**](docs/api/KubernetesApi.md#k8sversionsget) | **Get** /k8s/versions | Get Kubernetes Versions LANsApi | [**DatacentersLansDelete**](docs/api/LANsApi.md#datacenterslansdelete) | **Delete** /datacenters/{datacenterId}/lans/{lanId} | Delete LANs -LANsApi | [**DatacentersLansEnableIpv6**](docs/api/LANsApi.md#datacenterslansenableipv6) | **Post** /datacenters/{datacenterId}/lans/enable-ipv6 | Enable IPv6 in the current Virtual Datacenter LANsApi | [**DatacentersLansFindById**](docs/api/LANsApi.md#datacenterslansfindbyid) | **Get** /datacenters/{datacenterId}/lans/{lanId} | Retrieve LANs LANsApi | [**DatacentersLansGet**](docs/api/LANsApi.md#datacenterslansget) | **Get** /datacenters/{datacenterId}/lans | List LANs LANsApi | [**DatacentersLansNicsFindById**](docs/api/LANsApi.md#datacenterslansnicsfindbyid) | **Get** /datacenters/{datacenterId}/lans/{lanId}/nics/{nicId} | Retrieve attached NICs @@ -620,7 +619,9 @@ All URIs are relative to *https://api.ionos.com/cloudapi/v6* - [Lan](docs/models/Lan) - [LanEntities](docs/models/LanEntities) - [LanNics](docs/models/LanNics) + - [LanPost](docs/models/LanPost) - [LanProperties](docs/models/LanProperties) + - [LanPropertiesPost](docs/models/LanPropertiesPost) - [Lans](docs/models/Lans) - [Loadbalancer](docs/models/Loadbalancer) - [LoadbalancerEntities](docs/models/LoadbalancerEntities) diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/api_lans.go b/vendor/github.com/ionos-cloud/sdk-go/v6/api_lans.go index 07560c52865..75e864a530f 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/api_lans.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/api_lans.go @@ -192,167 +192,6 @@ func (a *LANsApiService) DatacentersLansDeleteExecute(r ApiDatacentersLansDelete return localVarAPIResponse, nil } -type ApiDatacentersLansEnableIpv6Request struct { - ctx _context.Context - ApiService *LANsApiService - datacenterId string - pretty *bool - depth *int32 - xContractNumber *int32 -} - -func (r ApiDatacentersLansEnableIpv6Request) Pretty(pretty bool) ApiDatacentersLansEnableIpv6Request { - r.pretty = &pretty - return r -} -func (r ApiDatacentersLansEnableIpv6Request) Depth(depth int32) ApiDatacentersLansEnableIpv6Request { - r.depth = &depth - return r -} -func (r ApiDatacentersLansEnableIpv6Request) XContractNumber(xContractNumber int32) ApiDatacentersLansEnableIpv6Request { - r.xContractNumber = &xContractNumber - return r -} - -func (r ApiDatacentersLansEnableIpv6Request) Execute() (*APIResponse, error) { - return r.ApiService.DatacentersLansEnableIpv6Execute(r) -} - -/* - * DatacentersLansEnableIpv6 Enable IPv6 in the current Virtual Datacenter - * Enable IPv6 for all NICs in the current Virtual Datacenter. - * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - * @param datacenterId The unique ID of the data center. - * @return ApiDatacentersLansEnableIpv6Request - */ -func (a *LANsApiService) DatacentersLansEnableIpv6(ctx _context.Context, datacenterId string) ApiDatacentersLansEnableIpv6Request { - return ApiDatacentersLansEnableIpv6Request{ - ApiService: a, - ctx: ctx, - datacenterId: datacenterId, - } -} - -/* - * Execute executes the request - */ -func (a *LANsApiService) DatacentersLansEnableIpv6Execute(r ApiDatacentersLansEnableIpv6Request) (*APIResponse, error) { - var ( - localVarHTTPMethod = _nethttp.MethodPost - localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte - ) - - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "LANsApiService.DatacentersLansEnableIpv6") - if err != nil { - return nil, GenericOpenAPIError{error: err.Error()} - } - - localVarPath := localBasePath + "/datacenters/{datacenterId}/lans/enable-ipv6" - localVarPath = strings.Replace(localVarPath, "{"+"datacenterId"+"}", _neturl.PathEscape(parameterToString(r.datacenterId, "")), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := _neturl.Values{} - localVarFormParams := _neturl.Values{} - - if r.pretty != nil { - localVarQueryParams.Add("pretty", parameterToString(*r.pretty, "")) - } else { - defaultQueryParam := a.client.cfg.DefaultQueryParams.Get("pretty") - if defaultQueryParam == "" { - localVarQueryParams.Add("pretty", parameterToString(true, "")) - } - } - if r.depth != nil { - localVarQueryParams.Add("depth", parameterToString(*r.depth, "")) - } else { - defaultQueryParam := a.client.cfg.DefaultQueryParams.Get("depth") - if defaultQueryParam == "" { - localVarQueryParams.Add("depth", parameterToString(0, "")) - } - } - - // to determine the Content-Type header - localVarHTTPContentTypes := []string{} - - // set Content-Type header - localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) - if localVarHTTPContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHTTPContentType - } - - // to determine the Accept header - localVarHTTPHeaderAccepts := []string{"*/*"} - - // set Accept header - localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) - if localVarHTTPHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept - } - if r.xContractNumber != nil { - localVarHeaderParams["X-Contract-Number"] = parameterToString(*r.xContractNumber, "") - } - if r.ctx != nil { - // API Key Authentication - if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { - if apiKey, ok := auth["Token Authentication"]; ok { - var key string - if apiKey.Prefix != "" { - key = apiKey.Prefix + " " + apiKey.Key - } else { - key = apiKey.Key - } - localVarHeaderParams["Authorization"] = key - } - } - } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) - if err != nil { - return nil, err - } - - localVarHTTPResponse, httpRequestTime, err := a.client.callAPI(req) - - localVarAPIResponse := &APIResponse{ - Response: localVarHTTPResponse, - Method: localVarHTTPMethod, - RequestURL: localVarPath, - RequestTime: httpRequestTime, - Operation: "DatacentersLansEnableIpv6", - } - - if err != nil || localVarHTTPResponse == nil { - return localVarAPIResponse, err - } - - localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) - localVarHTTPResponse.Body.Close() - localVarAPIResponse.Payload = localVarBody - if err != nil { - return localVarAPIResponse, err - } - - if localVarHTTPResponse.StatusCode >= 300 { - newErr := GenericOpenAPIError{ - statusCode: localVarHTTPResponse.StatusCode, - body: localVarBody, - error: fmt.Sprintf(FormatStringErr, localVarHTTPResponse.Status, string(localVarBody)), - } - var v Error - err = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = fmt.Sprintf(FormatStringErr, localVarHTTPResponse.Status, err.Error()) - return localVarAPIResponse, newErr - } - newErr.model = v - return localVarAPIResponse, newErr - } - - return localVarAPIResponse, nil -} - type ApiDatacentersLansFindByIdRequest struct { ctx _context.Context ApiService *LANsApiService @@ -1563,13 +1402,13 @@ type ApiDatacentersLansPostRequest struct { ctx _context.Context ApiService *LANsApiService datacenterId string - lan *Lan + lan *LanPost pretty *bool depth *int32 xContractNumber *int32 } -func (r ApiDatacentersLansPostRequest) Lan(lan Lan) ApiDatacentersLansPostRequest { +func (r ApiDatacentersLansPostRequest) Lan(lan LanPost) ApiDatacentersLansPostRequest { r.lan = &lan return r } @@ -1586,7 +1425,7 @@ func (r ApiDatacentersLansPostRequest) XContractNumber(xContractNumber int32) Ap return r } -func (r ApiDatacentersLansPostRequest) Execute() (Lan, *APIResponse, error) { +func (r ApiDatacentersLansPostRequest) Execute() (LanPost, *APIResponse, error) { return r.ApiService.DatacentersLansPostExecute(r) } @@ -1607,16 +1446,16 @@ func (a *LANsApiService) DatacentersLansPost(ctx _context.Context, datacenterId /* * Execute executes the request - * @return Lan + * @return LanPost */ -func (a *LANsApiService) DatacentersLansPostExecute(r ApiDatacentersLansPostRequest) (Lan, *APIResponse, error) { +func (a *LANsApiService) DatacentersLansPostExecute(r ApiDatacentersLansPostRequest) (LanPost, *APIResponse, error) { var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} localVarFormFileName string localVarFileName string localVarFileBytes []byte - localVarReturnValue Lan + localVarReturnValue LanPost ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "LANsApiService.DatacentersLansPost") diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/client.go b/vendor/github.com/ionos-cloud/sdk-go/v6/client.go index 0bbdf2a6db7..09747ffdddf 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/client.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/client.go @@ -53,7 +53,7 @@ const ( RequestStatusFailed = "FAILED" RequestStatusDone = "DONE" - Version = "6.1.6" + Version = "6.1.7" ) // Constants for APIs diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/configuration.go b/vendor/github.com/ionos-cloud/sdk-go/v6/configuration.go index d6ef150c2bf..0da20bd00db 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/configuration.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/configuration.go @@ -130,7 +130,7 @@ func NewConfiguration(username, password, token, hostUrl string) *Configuration cfg := &Configuration{ DefaultHeader: make(map[string]string), DefaultQueryParams: url.Values{}, - UserAgent: "ionos-cloud-sdk-go/v6.1.6", + UserAgent: "ionos-cloud-sdk-go/v6.1.7", Debug: false, Username: username, Password: password, diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer.go index a63fe3431db..61cf511883f 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer.go @@ -16,15 +16,15 @@ import ( // ApplicationLoadBalancer struct for ApplicationLoadBalancer type ApplicationLoadBalancer struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Entities *ApplicationLoadBalancerEntities `json:"entities,omitempty"` // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *ApplicationLoadBalancerProperties `json:"properties"` - Entities *ApplicationLoadBalancerEntities `json:"entities,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewApplicationLoadBalancer instantiates a new ApplicationLoadBalancer object @@ -47,114 +47,114 @@ func NewApplicationLoadBalancerWithDefaults() *ApplicationLoadBalancer { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancer) GetId() *string { +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancer) GetEntities() *ApplicationLoadBalancerEntities { if o == nil { return nil } - return o.Id + return o.Entities } -// GetIdOk returns a tuple with the Id field value +// GetEntitiesOk returns a tuple with the Entities field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancer) GetIdOk() (*string, bool) { +func (o *ApplicationLoadBalancer) GetEntitiesOk() (*ApplicationLoadBalancerEntities, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Entities, true } -// SetId sets field value -func (o *ApplicationLoadBalancer) SetId(v string) { +// SetEntities sets field value +func (o *ApplicationLoadBalancer) SetEntities(v ApplicationLoadBalancerEntities) { - o.Id = &v + o.Entities = &v } -// HasId returns a boolean if a field has been set. -func (o *ApplicationLoadBalancer) HasId() bool { - if o != nil && o.Id != nil { +// HasEntities returns a boolean if a field has been set. +func (o *ApplicationLoadBalancer) HasEntities() bool { + if o != nil && o.Entities != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *ApplicationLoadBalancer) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancer) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancer) GetTypeOk() (*Type, bool) { +func (o *ApplicationLoadBalancer) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *ApplicationLoadBalancer) SetType(v Type) { +// SetHref sets field value +func (o *ApplicationLoadBalancer) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *ApplicationLoadBalancer) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *ApplicationLoadBalancer) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancer) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancer) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancer) GetHrefOk() (*string, bool) { +func (o *ApplicationLoadBalancer) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *ApplicationLoadBalancer) SetHref(v string) { +// SetId sets field value +func (o *ApplicationLoadBalancer) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *ApplicationLoadBalancer) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *ApplicationLoadBalancer) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -162,7 +162,7 @@ func (o *ApplicationLoadBalancer) HasHref() bool { } // GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned +// If the value is explicit nil, nil is returned func (o *ApplicationLoadBalancer) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil @@ -200,7 +200,7 @@ func (o *ApplicationLoadBalancer) HasMetadata() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for ApplicationLoadBalancerProperties will be returned +// If the value is explicit nil, nil is returned func (o *ApplicationLoadBalancer) GetProperties() *ApplicationLoadBalancerProperties { if o == nil { return nil @@ -237,38 +237,38 @@ func (o *ApplicationLoadBalancer) HasProperties() bool { return false } -// GetEntities returns the Entities field value -// If the value is explicit nil, the zero value for ApplicationLoadBalancerEntities will be returned -func (o *ApplicationLoadBalancer) GetEntities() *ApplicationLoadBalancerEntities { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancer) GetType() *Type { if o == nil { return nil } - return o.Entities + return o.Type } -// GetEntitiesOk returns a tuple with the Entities field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancer) GetEntitiesOk() (*ApplicationLoadBalancerEntities, bool) { +func (o *ApplicationLoadBalancer) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Entities, true + return o.Type, true } -// SetEntities sets field value -func (o *ApplicationLoadBalancer) SetEntities(v ApplicationLoadBalancerEntities) { +// SetType sets field value +func (o *ApplicationLoadBalancer) SetType(v Type) { - o.Entities = &v + o.Type = &v } -// HasEntities returns a boolean if a field has been set. -func (o *ApplicationLoadBalancer) HasEntities() bool { - if o != nil && o.Entities != nil { +// HasType returns a boolean if a field has been set. +func (o *ApplicationLoadBalancer) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -277,24 +277,30 @@ func (o *ApplicationLoadBalancer) HasEntities() bool { func (o ApplicationLoadBalancer) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Entities != nil { + toSerialize["entities"] = o.Entities } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } - if o.Entities != nil { - toSerialize["entities"] = o.Entities + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_entities.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_entities.go index d8cd1a1528c..425fceaa1ed 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_entities.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_entities.go @@ -38,7 +38,7 @@ func NewApplicationLoadBalancerEntitiesWithDefaults() *ApplicationLoadBalancerEn } // GetForwardingrules returns the Forwardingrules field value -// If the value is explicit nil, the zero value for ApplicationLoadBalancerForwardingRules will be returned +// If the value is explicit nil, nil is returned func (o *ApplicationLoadBalancerEntities) GetForwardingrules() *ApplicationLoadBalancerForwardingRules { if o == nil { return nil @@ -80,6 +80,7 @@ func (o ApplicationLoadBalancerEntities) MarshalJSON() ([]byte, error) { if o.Forwardingrules != nil { toSerialize["forwardingrules"] = o.Forwardingrules } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rule.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rule.go index 34c30dfc600..e9e1bd5c917 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rule.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rule.go @@ -16,14 +16,14 @@ import ( // ApplicationLoadBalancerForwardingRule struct for ApplicationLoadBalancerForwardingRule type ApplicationLoadBalancerForwardingRule struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *ApplicationLoadBalancerForwardingRuleProperties `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewApplicationLoadBalancerForwardingRule instantiates a new ApplicationLoadBalancerForwardingRule object @@ -46,190 +46,190 @@ func NewApplicationLoadBalancerForwardingRuleWithDefaults() *ApplicationLoadBala return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerForwardingRule) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRule) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRule) GetIdOk() (*string, bool) { +func (o *ApplicationLoadBalancerForwardingRule) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *ApplicationLoadBalancerForwardingRule) SetId(v string) { +// SetHref sets field value +func (o *ApplicationLoadBalancerForwardingRule) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRule) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRule) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *ApplicationLoadBalancerForwardingRule) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRule) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRule) GetTypeOk() (*Type, bool) { +func (o *ApplicationLoadBalancerForwardingRule) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *ApplicationLoadBalancerForwardingRule) SetType(v Type) { +// SetId sets field value +func (o *ApplicationLoadBalancerForwardingRule) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRule) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRule) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerForwardingRule) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRule) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRule) GetHrefOk() (*string, bool) { +func (o *ApplicationLoadBalancerForwardingRule) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *ApplicationLoadBalancerForwardingRule) SetHref(v string) { +// SetMetadata sets field value +func (o *ApplicationLoadBalancerForwardingRule) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRule) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRule) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *ApplicationLoadBalancerForwardingRule) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRule) GetProperties() *ApplicationLoadBalancerForwardingRuleProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRule) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *ApplicationLoadBalancerForwardingRule) GetPropertiesOk() (*ApplicationLoadBalancerForwardingRuleProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *ApplicationLoadBalancerForwardingRule) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *ApplicationLoadBalancerForwardingRule) SetProperties(v ApplicationLoadBalancerForwardingRuleProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRule) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRule) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for ApplicationLoadBalancerForwardingRuleProperties will be returned -func (o *ApplicationLoadBalancerForwardingRule) GetProperties() *ApplicationLoadBalancerForwardingRuleProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRule) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRule) GetPropertiesOk() (*ApplicationLoadBalancerForwardingRuleProperties, bool) { +func (o *ApplicationLoadBalancerForwardingRule) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *ApplicationLoadBalancerForwardingRule) SetProperties(v ApplicationLoadBalancerForwardingRuleProperties) { +// SetType sets field value +func (o *ApplicationLoadBalancerForwardingRule) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRule) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRule) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *ApplicationLoadBalancerForwardingRule) HasProperties() bool { func (o ApplicationLoadBalancerForwardingRule) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rule_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rule_properties.go index f73da694f06..b5adc750a9a 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rule_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rule_properties.go @@ -16,33 +16,33 @@ import ( // ApplicationLoadBalancerForwardingRuleProperties struct for ApplicationLoadBalancerForwardingRuleProperties type ApplicationLoadBalancerForwardingRuleProperties struct { - // The name of the Application Load Balancer forwarding rule. - Name *string `json:"name"` - // The balancing protocol. - Protocol *string `json:"protocol"` + // The maximum time in milliseconds to wait for the client to acknowledge or send data; default is 50,000 (50 seconds). + ClientTimeout *int32 `json:"clientTimeout,omitempty"` + // An array of items in the collection. The original order of rules is preserved during processing, except that rules of the 'FORWARD' type are processed after the rules with other defined actions. The relative order of the 'FORWARD' type rules is also preserved during the processing. + HttpRules *[]ApplicationLoadBalancerHttpRule `json:"httpRules,omitempty"` // The listening (inbound) IP. ListenerIp *string `json:"listenerIp"` // The listening (inbound) port number; the valid range is 1 to 65535. ListenerPort *int32 `json:"listenerPort"` - // The maximum time in milliseconds to wait for the client to acknowledge or send data; default is 50,000 (50 seconds). - ClientTimeout *int32 `json:"clientTimeout,omitempty"` + // The name of the Application Load Balancer forwarding rule. + Name *string `json:"name"` + // The balancing protocol. + Protocol *string `json:"protocol"` // Array of items in the collection. ServerCertificates *[]string `json:"serverCertificates,omitempty"` - // An array of items in the collection. The original order of rules is preserved during processing, except that rules of the 'FORWARD' type are processed after the rules with other defined actions. The relative order of the 'FORWARD' type rules is also preserved during the processing. - HttpRules *[]ApplicationLoadBalancerHttpRule `json:"httpRules,omitempty"` } // NewApplicationLoadBalancerForwardingRuleProperties instantiates a new ApplicationLoadBalancerForwardingRuleProperties object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewApplicationLoadBalancerForwardingRuleProperties(name string, protocol string, listenerIp string, listenerPort int32) *ApplicationLoadBalancerForwardingRuleProperties { +func NewApplicationLoadBalancerForwardingRuleProperties(listenerIp string, listenerPort int32, name string, protocol string) *ApplicationLoadBalancerForwardingRuleProperties { this := ApplicationLoadBalancerForwardingRuleProperties{} - this.Name = &name - this.Protocol = &protocol this.ListenerIp = &listenerIp this.ListenerPort = &listenerPort + this.Name = &name + this.Protocol = &protocol return &this } @@ -55,76 +55,76 @@ func NewApplicationLoadBalancerForwardingRulePropertiesWithDefaults() *Applicati return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerForwardingRuleProperties) GetName() *string { +// GetClientTimeout returns the ClientTimeout field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRuleProperties) GetClientTimeout() *int32 { if o == nil { return nil } - return o.Name + return o.ClientTimeout } -// GetNameOk returns a tuple with the Name field value +// GetClientTimeoutOk returns a tuple with the ClientTimeout field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRuleProperties) GetNameOk() (*string, bool) { +func (o *ApplicationLoadBalancerForwardingRuleProperties) GetClientTimeoutOk() (*int32, bool) { if o == nil { return nil, false } - return o.Name, true + return o.ClientTimeout, true } -// SetName sets field value -func (o *ApplicationLoadBalancerForwardingRuleProperties) SetName(v string) { +// SetClientTimeout sets field value +func (o *ApplicationLoadBalancerForwardingRuleProperties) SetClientTimeout(v int32) { - o.Name = &v + o.ClientTimeout = &v } -// HasName returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRuleProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasClientTimeout returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRuleProperties) HasClientTimeout() bool { + if o != nil && o.ClientTimeout != nil { return true } return false } -// GetProtocol returns the Protocol field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerForwardingRuleProperties) GetProtocol() *string { +// GetHttpRules returns the HttpRules field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRuleProperties) GetHttpRules() *[]ApplicationLoadBalancerHttpRule { if o == nil { return nil } - return o.Protocol + return o.HttpRules } -// GetProtocolOk returns a tuple with the Protocol field value +// GetHttpRulesOk returns a tuple with the HttpRules field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRuleProperties) GetProtocolOk() (*string, bool) { +func (o *ApplicationLoadBalancerForwardingRuleProperties) GetHttpRulesOk() (*[]ApplicationLoadBalancerHttpRule, bool) { if o == nil { return nil, false } - return o.Protocol, true + return o.HttpRules, true } -// SetProtocol sets field value -func (o *ApplicationLoadBalancerForwardingRuleProperties) SetProtocol(v string) { +// SetHttpRules sets field value +func (o *ApplicationLoadBalancerForwardingRuleProperties) SetHttpRules(v []ApplicationLoadBalancerHttpRule) { - o.Protocol = &v + o.HttpRules = &v } -// HasProtocol returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRuleProperties) HasProtocol() bool { - if o != nil && o.Protocol != nil { +// HasHttpRules returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRuleProperties) HasHttpRules() bool { + if o != nil && o.HttpRules != nil { return true } @@ -132,7 +132,7 @@ func (o *ApplicationLoadBalancerForwardingRuleProperties) HasProtocol() bool { } // GetListenerIp returns the ListenerIp field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *ApplicationLoadBalancerForwardingRuleProperties) GetListenerIp() *string { if o == nil { return nil @@ -170,7 +170,7 @@ func (o *ApplicationLoadBalancerForwardingRuleProperties) HasListenerIp() bool { } // GetListenerPort returns the ListenerPort field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *ApplicationLoadBalancerForwardingRuleProperties) GetListenerPort() *int32 { if o == nil { return nil @@ -207,114 +207,114 @@ func (o *ApplicationLoadBalancerForwardingRuleProperties) HasListenerPort() bool return false } -// GetClientTimeout returns the ClientTimeout field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ApplicationLoadBalancerForwardingRuleProperties) GetClientTimeout() *int32 { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRuleProperties) GetName() *string { if o == nil { return nil } - return o.ClientTimeout + return o.Name } -// GetClientTimeoutOk returns a tuple with the ClientTimeout field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRuleProperties) GetClientTimeoutOk() (*int32, bool) { +func (o *ApplicationLoadBalancerForwardingRuleProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.ClientTimeout, true + return o.Name, true } -// SetClientTimeout sets field value -func (o *ApplicationLoadBalancerForwardingRuleProperties) SetClientTimeout(v int32) { +// SetName sets field value +func (o *ApplicationLoadBalancerForwardingRuleProperties) SetName(v string) { - o.ClientTimeout = &v + o.Name = &v } -// HasClientTimeout returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRuleProperties) HasClientTimeout() bool { - if o != nil && o.ClientTimeout != nil { +// HasName returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRuleProperties) HasName() bool { + if o != nil && o.Name != nil { return true } return false } -// GetServerCertificates returns the ServerCertificates field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *ApplicationLoadBalancerForwardingRuleProperties) GetServerCertificates() *[]string { +// GetProtocol returns the Protocol field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRuleProperties) GetProtocol() *string { if o == nil { return nil } - return o.ServerCertificates + return o.Protocol } -// GetServerCertificatesOk returns a tuple with the ServerCertificates field value +// GetProtocolOk returns a tuple with the Protocol field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRuleProperties) GetServerCertificatesOk() (*[]string, bool) { +func (o *ApplicationLoadBalancerForwardingRuleProperties) GetProtocolOk() (*string, bool) { if o == nil { return nil, false } - return o.ServerCertificates, true + return o.Protocol, true } -// SetServerCertificates sets field value -func (o *ApplicationLoadBalancerForwardingRuleProperties) SetServerCertificates(v []string) { +// SetProtocol sets field value +func (o *ApplicationLoadBalancerForwardingRuleProperties) SetProtocol(v string) { - o.ServerCertificates = &v + o.Protocol = &v } -// HasServerCertificates returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRuleProperties) HasServerCertificates() bool { - if o != nil && o.ServerCertificates != nil { +// HasProtocol returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRuleProperties) HasProtocol() bool { + if o != nil && o.Protocol != nil { return true } return false } -// GetHttpRules returns the HttpRules field value -// If the value is explicit nil, the zero value for []ApplicationLoadBalancerHttpRule will be returned -func (o *ApplicationLoadBalancerForwardingRuleProperties) GetHttpRules() *[]ApplicationLoadBalancerHttpRule { +// GetServerCertificates returns the ServerCertificates field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRuleProperties) GetServerCertificates() *[]string { if o == nil { return nil } - return o.HttpRules + return o.ServerCertificates } -// GetHttpRulesOk returns a tuple with the HttpRules field value +// GetServerCertificatesOk returns a tuple with the ServerCertificates field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRuleProperties) GetHttpRulesOk() (*[]ApplicationLoadBalancerHttpRule, bool) { +func (o *ApplicationLoadBalancerForwardingRuleProperties) GetServerCertificatesOk() (*[]string, bool) { if o == nil { return nil, false } - return o.HttpRules, true + return o.ServerCertificates, true } -// SetHttpRules sets field value -func (o *ApplicationLoadBalancerForwardingRuleProperties) SetHttpRules(v []ApplicationLoadBalancerHttpRule) { +// SetServerCertificates sets field value +func (o *ApplicationLoadBalancerForwardingRuleProperties) SetServerCertificates(v []string) { - o.HttpRules = &v + o.ServerCertificates = &v } -// HasHttpRules returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRuleProperties) HasHttpRules() bool { - if o != nil && o.HttpRules != nil { +// HasServerCertificates returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRuleProperties) HasServerCertificates() bool { + if o != nil && o.ServerCertificates != nil { return true } @@ -323,27 +323,34 @@ func (o *ApplicationLoadBalancerForwardingRuleProperties) HasHttpRules() bool { func (o ApplicationLoadBalancerForwardingRuleProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name + if o.ClientTimeout != nil { + toSerialize["clientTimeout"] = o.ClientTimeout } - if o.Protocol != nil { - toSerialize["protocol"] = o.Protocol + + if o.HttpRules != nil { + toSerialize["httpRules"] = o.HttpRules } + if o.ListenerIp != nil { toSerialize["listenerIp"] = o.ListenerIp } + if o.ListenerPort != nil { toSerialize["listenerPort"] = o.ListenerPort } - if o.ClientTimeout != nil { - toSerialize["clientTimeout"] = o.ClientTimeout + + if o.Name != nil { + toSerialize["name"] = o.Name + } + + if o.Protocol != nil { + toSerialize["protocol"] = o.Protocol } + if o.ServerCertificates != nil { toSerialize["serverCertificates"] = o.ServerCertificates } - if o.HttpRules != nil { - toSerialize["httpRules"] = o.HttpRules - } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rule_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rule_put.go index 0328b229cc1..d5e6f649a8e 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rule_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rule_put.go @@ -16,13 +16,13 @@ import ( // ApplicationLoadBalancerForwardingRulePut struct for ApplicationLoadBalancerForwardingRulePut type ApplicationLoadBalancerForwardingRulePut struct { + // The URL to the object representation (absolute path). + Href *string `json:"href,omitempty"` // The resource's unique identifier. - Id *string `json:"id,omitempty"` + Id *string `json:"id,omitempty"` + Properties *ApplicationLoadBalancerForwardingRuleProperties `json:"properties"` // The type of object that has been created. Type *Type `json:"type,omitempty"` - // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` - Properties *ApplicationLoadBalancerForwardingRuleProperties `json:"properties"` } // NewApplicationLoadBalancerForwardingRulePut instantiates a new ApplicationLoadBalancerForwardingRulePut object @@ -45,152 +45,152 @@ func NewApplicationLoadBalancerForwardingRulePutWithDefaults() *ApplicationLoadB return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerForwardingRulePut) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRulePut) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRulePut) GetIdOk() (*string, bool) { +func (o *ApplicationLoadBalancerForwardingRulePut) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *ApplicationLoadBalancerForwardingRulePut) SetId(v string) { +// SetHref sets field value +func (o *ApplicationLoadBalancerForwardingRulePut) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRulePut) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRulePut) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *ApplicationLoadBalancerForwardingRulePut) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRulePut) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRulePut) GetTypeOk() (*Type, bool) { +func (o *ApplicationLoadBalancerForwardingRulePut) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *ApplicationLoadBalancerForwardingRulePut) SetType(v Type) { +// SetId sets field value +func (o *ApplicationLoadBalancerForwardingRulePut) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRulePut) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRulePut) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerForwardingRulePut) GetHref() *string { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRulePut) GetProperties() *ApplicationLoadBalancerForwardingRuleProperties { if o == nil { return nil } - return o.Href + return o.Properties } -// GetHrefOk returns a tuple with the Href field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRulePut) GetHrefOk() (*string, bool) { +func (o *ApplicationLoadBalancerForwardingRulePut) GetPropertiesOk() (*ApplicationLoadBalancerForwardingRuleProperties, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Properties, true } -// SetHref sets field value -func (o *ApplicationLoadBalancerForwardingRulePut) SetHref(v string) { +// SetProperties sets field value +func (o *ApplicationLoadBalancerForwardingRulePut) SetProperties(v ApplicationLoadBalancerForwardingRuleProperties) { - o.Href = &v + o.Properties = &v } -// HasHref returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRulePut) HasHref() bool { - if o != nil && o.Href != nil { +// HasProperties returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRulePut) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for ApplicationLoadBalancerForwardingRuleProperties will be returned -func (o *ApplicationLoadBalancerForwardingRulePut) GetProperties() *ApplicationLoadBalancerForwardingRuleProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRulePut) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRulePut) GetPropertiesOk() (*ApplicationLoadBalancerForwardingRuleProperties, bool) { +func (o *ApplicationLoadBalancerForwardingRulePut) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *ApplicationLoadBalancerForwardingRulePut) SetProperties(v ApplicationLoadBalancerForwardingRuleProperties) { +// SetType sets field value +func (o *ApplicationLoadBalancerForwardingRulePut) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRulePut) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRulePut) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -199,18 +199,22 @@ func (o *ApplicationLoadBalancerForwardingRulePut) HasProperties() bool { func (o ApplicationLoadBalancerForwardingRulePut) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rules.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rules.go index 14b1f86e574..aae71997f3c 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rules.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_forwarding_rules.go @@ -16,19 +16,19 @@ import ( // ApplicationLoadBalancerForwardingRules struct for ApplicationLoadBalancerForwardingRules type ApplicationLoadBalancerForwardingRules struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // The URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]ApplicationLoadBalancerForwardingRule `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewApplicationLoadBalancerForwardingRules instantiates a new ApplicationLoadBalancerForwardingRules object @@ -49,114 +49,114 @@ func NewApplicationLoadBalancerForwardingRulesWithDefaults() *ApplicationLoadBal return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerForwardingRules) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRules) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRules) GetIdOk() (*string, bool) { +func (o *ApplicationLoadBalancerForwardingRules) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *ApplicationLoadBalancerForwardingRules) SetId(v string) { +// SetLinks sets field value +func (o *ApplicationLoadBalancerForwardingRules) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRules) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRules) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *ApplicationLoadBalancerForwardingRules) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRules) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRules) GetTypeOk() (*Type, bool) { +func (o *ApplicationLoadBalancerForwardingRules) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *ApplicationLoadBalancerForwardingRules) SetType(v Type) { +// SetHref sets field value +func (o *ApplicationLoadBalancerForwardingRules) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRules) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRules) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerForwardingRules) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRules) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRules) GetHrefOk() (*string, bool) { +func (o *ApplicationLoadBalancerForwardingRules) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *ApplicationLoadBalancerForwardingRules) SetHref(v string) { +// SetId sets field value +func (o *ApplicationLoadBalancerForwardingRules) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRules) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRules) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *ApplicationLoadBalancerForwardingRules) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []ApplicationLoadBalancerForwardingRule will be returned +// If the value is explicit nil, nil is returned func (o *ApplicationLoadBalancerForwardingRules) GetItems() *[]ApplicationLoadBalancerForwardingRule { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *ApplicationLoadBalancerForwardingRules) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *ApplicationLoadBalancerForwardingRules) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRules) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRules) GetOffsetOk() (*float32, bool) { +func (o *ApplicationLoadBalancerForwardingRules) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *ApplicationLoadBalancerForwardingRules) SetOffset(v float32) { +// SetLimit sets field value +func (o *ApplicationLoadBalancerForwardingRules) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRules) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRules) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *ApplicationLoadBalancerForwardingRules) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRules) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRules) GetLimitOk() (*float32, bool) { +func (o *ApplicationLoadBalancerForwardingRules) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *ApplicationLoadBalancerForwardingRules) SetLimit(v float32) { +// SetOffset sets field value +func (o *ApplicationLoadBalancerForwardingRules) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRules) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRules) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *ApplicationLoadBalancerForwardingRules) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerForwardingRules) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerForwardingRules) GetLinksOk() (*PaginationLinks, bool) { +func (o *ApplicationLoadBalancerForwardingRules) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *ApplicationLoadBalancerForwardingRules) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *ApplicationLoadBalancerForwardingRules) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerForwardingRules) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerForwardingRules) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *ApplicationLoadBalancerForwardingRules) HasLinks() bool { func (o ApplicationLoadBalancerForwardingRules) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_http_rule.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_http_rule.go index 9c117202ee0..1d52893f52e 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_http_rule.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_http_rule.go @@ -16,24 +16,24 @@ import ( // ApplicationLoadBalancerHttpRule struct for ApplicationLoadBalancerHttpRule type ApplicationLoadBalancerHttpRule struct { - // The unique name of the Application Load Balancer HTTP rule. - Name *string `json:"name"` - // The HTTP rule type. - Type *string `json:"type"` - // The ID of the target group; this parameter is mandatory and is valid only for 'FORWARD' actions. - TargetGroup *string `json:"targetGroup,omitempty"` + // An array of items in the collection. The action will be executed only if each condition is met; the rule will always be applied if no conditions are set. + Conditions *[]ApplicationLoadBalancerHttpRuleCondition `json:"conditions,omitempty"` + // Specifies the content type and is valid only for 'STATIC' actions. + ContentType *string `json:"contentType,omitempty"` // Indicates whether the query part of the URI should be dropped and is valid only for 'REDIRECT' actions. Default value is 'FALSE', the redirect URI does not contain any query parameters. DropQuery *bool `json:"dropQuery,omitempty"` // The location for the redirection; this parameter is mandatory and valid only for 'REDIRECT' actions. Location *string `json:"location,omitempty"` - // The status code is for 'REDIRECT' and 'STATIC' actions only. If the HTTP rule is 'REDIRECT' the valid values are: 301, 302, 303, 307, 308; default value is '301'. If the HTTP rule is 'STATIC' the valid values are from the range 200-599; default value is '503'. - StatusCode *int32 `json:"statusCode,omitempty"` + // The unique name of the Application Load Balancer HTTP rule. + Name *string `json:"name"` // The response message of the request; this parameter is mandatory for 'STATIC' actions. ResponseMessage *string `json:"responseMessage,omitempty"` - // Specifies the content type and is valid only for 'STATIC' actions. - ContentType *string `json:"contentType,omitempty"` - // An array of items in the collection. The action will be executed only if each condition is met; the rule will always be applied if no conditions are set. - Conditions *[]ApplicationLoadBalancerHttpRuleCondition `json:"conditions,omitempty"` + // The status code is for 'REDIRECT' and 'STATIC' actions only. If the HTTP rule is 'REDIRECT' the valid values are: 301, 302, 303, 307, 308; default value is '301'. If the HTTP rule is 'STATIC' the valid values are from the range 200-599; default value is '503'. + StatusCode *int32 `json:"statusCode,omitempty"` + // The ID of the target group; this parameter is mandatory and is valid only for 'FORWARD' actions. + TargetGroup *string `json:"targetGroup,omitempty"` + // The HTTP rule type. + Type *string `json:"type"` } // NewApplicationLoadBalancerHttpRule instantiates a new ApplicationLoadBalancerHttpRule object @@ -57,114 +57,76 @@ func NewApplicationLoadBalancerHttpRuleWithDefaults() *ApplicationLoadBalancerHt return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerHttpRule) GetName() *string { - if o == nil { - return nil - } - - return o.Name - -} - -// GetNameOk returns a tuple with the Name field value -// and a boolean to check if the value has been set. -// NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerHttpRule) GetNameOk() (*string, bool) { - if o == nil { - return nil, false - } - - return o.Name, true -} - -// SetName sets field value -func (o *ApplicationLoadBalancerHttpRule) SetName(v string) { - - o.Name = &v - -} - -// HasName returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerHttpRule) HasName() bool { - if o != nil && o.Name != nil { - return true - } - - return false -} - -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerHttpRule) GetType() *string { +// GetConditions returns the Conditions field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerHttpRule) GetConditions() *[]ApplicationLoadBalancerHttpRuleCondition { if o == nil { return nil } - return o.Type + return o.Conditions } -// GetTypeOk returns a tuple with the Type field value +// GetConditionsOk returns a tuple with the Conditions field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerHttpRule) GetTypeOk() (*string, bool) { +func (o *ApplicationLoadBalancerHttpRule) GetConditionsOk() (*[]ApplicationLoadBalancerHttpRuleCondition, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Conditions, true } -// SetType sets field value -func (o *ApplicationLoadBalancerHttpRule) SetType(v string) { +// SetConditions sets field value +func (o *ApplicationLoadBalancerHttpRule) SetConditions(v []ApplicationLoadBalancerHttpRuleCondition) { - o.Type = &v + o.Conditions = &v } -// HasType returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerHttpRule) HasType() bool { - if o != nil && o.Type != nil { +// HasConditions returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerHttpRule) HasConditions() bool { + if o != nil && o.Conditions != nil { return true } return false } -// GetTargetGroup returns the TargetGroup field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerHttpRule) GetTargetGroup() *string { +// GetContentType returns the ContentType field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerHttpRule) GetContentType() *string { if o == nil { return nil } - return o.TargetGroup + return o.ContentType } -// GetTargetGroupOk returns a tuple with the TargetGroup field value +// GetContentTypeOk returns a tuple with the ContentType field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerHttpRule) GetTargetGroupOk() (*string, bool) { +func (o *ApplicationLoadBalancerHttpRule) GetContentTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.TargetGroup, true + return o.ContentType, true } -// SetTargetGroup sets field value -func (o *ApplicationLoadBalancerHttpRule) SetTargetGroup(v string) { +// SetContentType sets field value +func (o *ApplicationLoadBalancerHttpRule) SetContentType(v string) { - o.TargetGroup = &v + o.ContentType = &v } -// HasTargetGroup returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerHttpRule) HasTargetGroup() bool { - if o != nil && o.TargetGroup != nil { +// HasContentType returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerHttpRule) HasContentType() bool { + if o != nil && o.ContentType != nil { return true } @@ -172,7 +134,7 @@ func (o *ApplicationLoadBalancerHttpRule) HasTargetGroup() bool { } // GetDropQuery returns the DropQuery field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *ApplicationLoadBalancerHttpRule) GetDropQuery() *bool { if o == nil { return nil @@ -210,7 +172,7 @@ func (o *ApplicationLoadBalancerHttpRule) HasDropQuery() bool { } // GetLocation returns the Location field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *ApplicationLoadBalancerHttpRule) GetLocation() *string { if o == nil { return nil @@ -247,38 +209,38 @@ func (o *ApplicationLoadBalancerHttpRule) HasLocation() bool { return false } -// GetStatusCode returns the StatusCode field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ApplicationLoadBalancerHttpRule) GetStatusCode() *int32 { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerHttpRule) GetName() *string { if o == nil { return nil } - return o.StatusCode + return o.Name } -// GetStatusCodeOk returns a tuple with the StatusCode field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerHttpRule) GetStatusCodeOk() (*int32, bool) { +func (o *ApplicationLoadBalancerHttpRule) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.StatusCode, true + return o.Name, true } -// SetStatusCode sets field value -func (o *ApplicationLoadBalancerHttpRule) SetStatusCode(v int32) { +// SetName sets field value +func (o *ApplicationLoadBalancerHttpRule) SetName(v string) { - o.StatusCode = &v + o.Name = &v } -// HasStatusCode returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerHttpRule) HasStatusCode() bool { - if o != nil && o.StatusCode != nil { +// HasName returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerHttpRule) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -286,7 +248,7 @@ func (o *ApplicationLoadBalancerHttpRule) HasStatusCode() bool { } // GetResponseMessage returns the ResponseMessage field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *ApplicationLoadBalancerHttpRule) GetResponseMessage() *string { if o == nil { return nil @@ -323,76 +285,114 @@ func (o *ApplicationLoadBalancerHttpRule) HasResponseMessage() bool { return false } -// GetContentType returns the ContentType field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerHttpRule) GetContentType() *string { +// GetStatusCode returns the StatusCode field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerHttpRule) GetStatusCode() *int32 { if o == nil { return nil } - return o.ContentType + return o.StatusCode } -// GetContentTypeOk returns a tuple with the ContentType field value +// GetStatusCodeOk returns a tuple with the StatusCode field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerHttpRule) GetContentTypeOk() (*string, bool) { +func (o *ApplicationLoadBalancerHttpRule) GetStatusCodeOk() (*int32, bool) { if o == nil { return nil, false } - return o.ContentType, true + return o.StatusCode, true } -// SetContentType sets field value -func (o *ApplicationLoadBalancerHttpRule) SetContentType(v string) { +// SetStatusCode sets field value +func (o *ApplicationLoadBalancerHttpRule) SetStatusCode(v int32) { - o.ContentType = &v + o.StatusCode = &v } -// HasContentType returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerHttpRule) HasContentType() bool { - if o != nil && o.ContentType != nil { +// HasStatusCode returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerHttpRule) HasStatusCode() bool { + if o != nil && o.StatusCode != nil { return true } return false } -// GetConditions returns the Conditions field value -// If the value is explicit nil, the zero value for []ApplicationLoadBalancerHttpRuleCondition will be returned -func (o *ApplicationLoadBalancerHttpRule) GetConditions() *[]ApplicationLoadBalancerHttpRuleCondition { +// GetTargetGroup returns the TargetGroup field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerHttpRule) GetTargetGroup() *string { if o == nil { return nil } - return o.Conditions + return o.TargetGroup } -// GetConditionsOk returns a tuple with the Conditions field value +// GetTargetGroupOk returns a tuple with the TargetGroup field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerHttpRule) GetConditionsOk() (*[]ApplicationLoadBalancerHttpRuleCondition, bool) { +func (o *ApplicationLoadBalancerHttpRule) GetTargetGroupOk() (*string, bool) { if o == nil { return nil, false } - return o.Conditions, true + return o.TargetGroup, true } -// SetConditions sets field value -func (o *ApplicationLoadBalancerHttpRule) SetConditions(v []ApplicationLoadBalancerHttpRuleCondition) { +// SetTargetGroup sets field value +func (o *ApplicationLoadBalancerHttpRule) SetTargetGroup(v string) { - o.Conditions = &v + o.TargetGroup = &v } -// HasConditions returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerHttpRule) HasConditions() bool { - if o != nil && o.Conditions != nil { +// HasTargetGroup returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerHttpRule) HasTargetGroup() bool { + if o != nil && o.TargetGroup != nil { + return true + } + + return false +} + +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerHttpRule) GetType() *string { + if o == nil { + return nil + } + + return o.Type + +} + +// GetTypeOk returns a tuple with the Type field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *ApplicationLoadBalancerHttpRule) GetTypeOk() (*string, bool) { + if o == nil { + return nil, false + } + + return o.Type, true +} + +// SetType sets field value +func (o *ApplicationLoadBalancerHttpRule) SetType(v string) { + + o.Type = &v + +} + +// HasType returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerHttpRule) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -401,33 +401,42 @@ func (o *ApplicationLoadBalancerHttpRule) HasConditions() bool { func (o ApplicationLoadBalancerHttpRule) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Conditions != nil { + toSerialize["conditions"] = o.Conditions } - if o.TargetGroup != nil { - toSerialize["targetGroup"] = o.TargetGroup + + if o.ContentType != nil { + toSerialize["contentType"] = o.ContentType } + if o.DropQuery != nil { toSerialize["dropQuery"] = o.DropQuery } + if o.Location != nil { toSerialize["location"] = o.Location } - if o.StatusCode != nil { - toSerialize["statusCode"] = o.StatusCode + + if o.Name != nil { + toSerialize["name"] = o.Name } + if o.ResponseMessage != nil { toSerialize["responseMessage"] = o.ResponseMessage } - if o.ContentType != nil { - toSerialize["contentType"] = o.ContentType + + if o.StatusCode != nil { + toSerialize["statusCode"] = o.StatusCode } - if o.Conditions != nil { - toSerialize["conditions"] = o.Conditions + + if o.TargetGroup != nil { + toSerialize["targetGroup"] = o.TargetGroup } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_http_rule_condition.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_http_rule_condition.go index a61e46532ff..a2b12adfd33 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_http_rule_condition.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_http_rule_condition.go @@ -16,14 +16,14 @@ import ( // ApplicationLoadBalancerHttpRuleCondition struct for ApplicationLoadBalancerHttpRuleCondition type ApplicationLoadBalancerHttpRuleCondition struct { - // The HTTP rule condition type. - Type *string `json:"type"` // The matching rule for the HTTP rule condition attribute; this parameter is mandatory for 'HEADER', 'PATH', 'QUERY', 'METHOD', 'HOST', and 'COOKIE' types. It must be 'null' if the type is 'SOURCE_IP'. Condition *string `json:"condition"` - // Specifies whether the condition should be negated; the default value is 'FALSE'. - Negate *bool `json:"negate,omitempty"` // The key can only be set when the HTTP rule condition type is 'COOKIES', 'HEADER', or 'QUERY'. For the type 'PATH', 'METHOD', 'HOST', or 'SOURCE_IP' the value must be 'null'. Key *string `json:"key,omitempty"` + // Specifies whether the condition should be negated; the default value is 'FALSE'. + Negate *bool `json:"negate,omitempty"` + // The HTTP rule condition type. + Type *string `json:"type"` // This parameter is mandatory for the conditions 'CONTAINS', 'EQUALS', 'MATCHES', 'STARTS_WITH', 'ENDS_WITH', or if the type is 'SOURCE_IP'. Specify a valid CIDR. If the condition is 'EXISTS', the value must be 'null'. Value *string `json:"value,omitempty"` } @@ -32,11 +32,11 @@ type ApplicationLoadBalancerHttpRuleCondition struct { // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewApplicationLoadBalancerHttpRuleCondition(type_ string, condition string) *ApplicationLoadBalancerHttpRuleCondition { +func NewApplicationLoadBalancerHttpRuleCondition(condition string, type_ string) *ApplicationLoadBalancerHttpRuleCondition { this := ApplicationLoadBalancerHttpRuleCondition{} - this.Type = &type_ this.Condition = &condition + this.Type = &type_ return &this } @@ -49,76 +49,76 @@ func NewApplicationLoadBalancerHttpRuleConditionWithDefaults() *ApplicationLoadB return &this } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerHttpRuleCondition) GetType() *string { +// GetCondition returns the Condition field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerHttpRuleCondition) GetCondition() *string { if o == nil { return nil } - return o.Type + return o.Condition } -// GetTypeOk returns a tuple with the Type field value +// GetConditionOk returns a tuple with the Condition field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerHttpRuleCondition) GetTypeOk() (*string, bool) { +func (o *ApplicationLoadBalancerHttpRuleCondition) GetConditionOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Condition, true } -// SetType sets field value -func (o *ApplicationLoadBalancerHttpRuleCondition) SetType(v string) { +// SetCondition sets field value +func (o *ApplicationLoadBalancerHttpRuleCondition) SetCondition(v string) { - o.Type = &v + o.Condition = &v } -// HasType returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerHttpRuleCondition) HasType() bool { - if o != nil && o.Type != nil { +// HasCondition returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerHttpRuleCondition) HasCondition() bool { + if o != nil && o.Condition != nil { return true } return false } -// GetCondition returns the Condition field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerHttpRuleCondition) GetCondition() *string { +// GetKey returns the Key field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerHttpRuleCondition) GetKey() *string { if o == nil { return nil } - return o.Condition + return o.Key } -// GetConditionOk returns a tuple with the Condition field value +// GetKeyOk returns a tuple with the Key field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerHttpRuleCondition) GetConditionOk() (*string, bool) { +func (o *ApplicationLoadBalancerHttpRuleCondition) GetKeyOk() (*string, bool) { if o == nil { return nil, false } - return o.Condition, true + return o.Key, true } -// SetCondition sets field value -func (o *ApplicationLoadBalancerHttpRuleCondition) SetCondition(v string) { +// SetKey sets field value +func (o *ApplicationLoadBalancerHttpRuleCondition) SetKey(v string) { - o.Condition = &v + o.Key = &v } -// HasCondition returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerHttpRuleCondition) HasCondition() bool { - if o != nil && o.Condition != nil { +// HasKey returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerHttpRuleCondition) HasKey() bool { + if o != nil && o.Key != nil { return true } @@ -126,7 +126,7 @@ func (o *ApplicationLoadBalancerHttpRuleCondition) HasCondition() bool { } // GetNegate returns the Negate field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *ApplicationLoadBalancerHttpRuleCondition) GetNegate() *bool { if o == nil { return nil @@ -163,38 +163,38 @@ func (o *ApplicationLoadBalancerHttpRuleCondition) HasNegate() bool { return false } -// GetKey returns the Key field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerHttpRuleCondition) GetKey() *string { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerHttpRuleCondition) GetType() *string { if o == nil { return nil } - return o.Key + return o.Type } -// GetKeyOk returns a tuple with the Key field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerHttpRuleCondition) GetKeyOk() (*string, bool) { +func (o *ApplicationLoadBalancerHttpRuleCondition) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Key, true + return o.Type, true } -// SetKey sets field value -func (o *ApplicationLoadBalancerHttpRuleCondition) SetKey(v string) { +// SetType sets field value +func (o *ApplicationLoadBalancerHttpRuleCondition) SetType(v string) { - o.Key = &v + o.Type = &v } -// HasKey returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerHttpRuleCondition) HasKey() bool { - if o != nil && o.Key != nil { +// HasType returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerHttpRuleCondition) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -202,7 +202,7 @@ func (o *ApplicationLoadBalancerHttpRuleCondition) HasKey() bool { } // GetValue returns the Value field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *ApplicationLoadBalancerHttpRuleCondition) GetValue() *string { if o == nil { return nil @@ -241,21 +241,26 @@ func (o *ApplicationLoadBalancerHttpRuleCondition) HasValue() bool { func (o ApplicationLoadBalancerHttpRuleCondition) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Condition != nil { toSerialize["condition"] = o.Condition } + + if o.Key != nil { + toSerialize["key"] = o.Key + } + if o.Negate != nil { toSerialize["negate"] = o.Negate } - if o.Key != nil { - toSerialize["key"] = o.Key + + if o.Type != nil { + toSerialize["type"] = o.Type } + if o.Value != nil { toSerialize["value"] = o.Value } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_properties.go index 5055570bd07..8c62ecc1031 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_properties.go @@ -16,27 +16,27 @@ import ( // ApplicationLoadBalancerProperties struct for ApplicationLoadBalancerProperties type ApplicationLoadBalancerProperties struct { - // The Application Load Balancer name. - Name *string `json:"name"` - // The ID of the listening (inbound) LAN. - ListenerLan *int32 `json:"listenerLan"` // Collection of the Application Load Balancer IP addresses. (Inbound and outbound) IPs of the 'listenerLan' are customer-reserved public IPs for the public load balancers, and private IPs for the private load balancers. Ips *[]string `json:"ips,omitempty"` - // The ID of the balanced private target LAN (outbound). - TargetLan *int32 `json:"targetLan"` // Collection of private IP addresses with the subnet mask of the Application Load Balancer. IPs must contain valid a subnet mask. If no IP is provided, the system will generate an IP with /24 subnet. LbPrivateIps *[]string `json:"lbPrivateIps,omitempty"` + // The ID of the listening (inbound) LAN. + ListenerLan *int32 `json:"listenerLan"` + // The Application Load Balancer name. + Name *string `json:"name"` + // The ID of the balanced private target LAN (outbound). + TargetLan *int32 `json:"targetLan"` } // NewApplicationLoadBalancerProperties instantiates a new ApplicationLoadBalancerProperties object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewApplicationLoadBalancerProperties(name string, listenerLan int32, targetLan int32) *ApplicationLoadBalancerProperties { +func NewApplicationLoadBalancerProperties(listenerLan int32, name string, targetLan int32) *ApplicationLoadBalancerProperties { this := ApplicationLoadBalancerProperties{} - this.Name = &name this.ListenerLan = &listenerLan + this.Name = &name this.TargetLan = &targetLan return &this @@ -50,38 +50,76 @@ func NewApplicationLoadBalancerPropertiesWithDefaults() *ApplicationLoadBalancer return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerProperties) GetName() *string { +// GetIps returns the Ips field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerProperties) GetIps() *[]string { if o == nil { return nil } - return o.Name + return o.Ips } -// GetNameOk returns a tuple with the Name field value +// GetIpsOk returns a tuple with the Ips field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerProperties) GetNameOk() (*string, bool) { +func (o *ApplicationLoadBalancerProperties) GetIpsOk() (*[]string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.Ips, true } -// SetName sets field value -func (o *ApplicationLoadBalancerProperties) SetName(v string) { +// SetIps sets field value +func (o *ApplicationLoadBalancerProperties) SetIps(v []string) { - o.Name = &v + o.Ips = &v } -// HasName returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasIps returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerProperties) HasIps() bool { + if o != nil && o.Ips != nil { + return true + } + + return false +} + +// GetLbPrivateIps returns the LbPrivateIps field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerProperties) GetLbPrivateIps() *[]string { + if o == nil { + return nil + } + + return o.LbPrivateIps + +} + +// GetLbPrivateIpsOk returns a tuple with the LbPrivateIps field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *ApplicationLoadBalancerProperties) GetLbPrivateIpsOk() (*[]string, bool) { + if o == nil { + return nil, false + } + + return o.LbPrivateIps, true +} + +// SetLbPrivateIps sets field value +func (o *ApplicationLoadBalancerProperties) SetLbPrivateIps(v []string) { + + o.LbPrivateIps = &v + +} + +// HasLbPrivateIps returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerProperties) HasLbPrivateIps() bool { + if o != nil && o.LbPrivateIps != nil { return true } @@ -89,7 +127,7 @@ func (o *ApplicationLoadBalancerProperties) HasName() bool { } // GetListenerLan returns the ListenerLan field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *ApplicationLoadBalancerProperties) GetListenerLan() *int32 { if o == nil { return nil @@ -126,38 +164,38 @@ func (o *ApplicationLoadBalancerProperties) HasListenerLan() bool { return false } -// GetIps returns the Ips field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *ApplicationLoadBalancerProperties) GetIps() *[]string { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerProperties) GetName() *string { if o == nil { return nil } - return o.Ips + return o.Name } -// GetIpsOk returns a tuple with the Ips field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerProperties) GetIpsOk() (*[]string, bool) { +func (o *ApplicationLoadBalancerProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.Ips, true + return o.Name, true } -// SetIps sets field value -func (o *ApplicationLoadBalancerProperties) SetIps(v []string) { +// SetName sets field value +func (o *ApplicationLoadBalancerProperties) SetName(v string) { - o.Ips = &v + o.Name = &v } -// HasIps returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerProperties) HasIps() bool { - if o != nil && o.Ips != nil { +// HasName returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerProperties) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -165,7 +203,7 @@ func (o *ApplicationLoadBalancerProperties) HasIps() bool { } // GetTargetLan returns the TargetLan field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *ApplicationLoadBalancerProperties) GetTargetLan() *int32 { if o == nil { return nil @@ -202,61 +240,28 @@ func (o *ApplicationLoadBalancerProperties) HasTargetLan() bool { return false } -// GetLbPrivateIps returns the LbPrivateIps field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *ApplicationLoadBalancerProperties) GetLbPrivateIps() *[]string { - if o == nil { - return nil +func (o ApplicationLoadBalancerProperties) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if o.Ips != nil { + toSerialize["ips"] = o.Ips } - return o.LbPrivateIps - -} - -// GetLbPrivateIpsOk returns a tuple with the LbPrivateIps field value -// and a boolean to check if the value has been set. -// NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerProperties) GetLbPrivateIpsOk() (*[]string, bool) { - if o == nil { - return nil, false + if o.LbPrivateIps != nil { + toSerialize["lbPrivateIps"] = o.LbPrivateIps } - return o.LbPrivateIps, true -} - -// SetLbPrivateIps sets field value -func (o *ApplicationLoadBalancerProperties) SetLbPrivateIps(v []string) { - - o.LbPrivateIps = &v - -} - -// HasLbPrivateIps returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerProperties) HasLbPrivateIps() bool { - if o != nil && o.LbPrivateIps != nil { - return true + if o.ListenerLan != nil { + toSerialize["listenerLan"] = o.ListenerLan } - return false -} - -func (o ApplicationLoadBalancerProperties) MarshalJSON() ([]byte, error) { - toSerialize := map[string]interface{}{} if o.Name != nil { toSerialize["name"] = o.Name } - if o.ListenerLan != nil { - toSerialize["listenerLan"] = o.ListenerLan - } - if o.Ips != nil { - toSerialize["ips"] = o.Ips - } + if o.TargetLan != nil { toSerialize["targetLan"] = o.TargetLan } - if o.LbPrivateIps != nil { - toSerialize["lbPrivateIps"] = o.LbPrivateIps - } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_put.go index ce188b2d816..79a5fa1c708 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancer_put.go @@ -16,13 +16,13 @@ import ( // ApplicationLoadBalancerPut struct for ApplicationLoadBalancerPut type ApplicationLoadBalancerPut struct { + // The URL to the object representation (absolute path). + Href *string `json:"href,omitempty"` // The resource's unique identifier. - Id *string `json:"id,omitempty"` + Id *string `json:"id,omitempty"` + Properties *ApplicationLoadBalancerProperties `json:"properties"` // The type of object that has been created. Type *Type `json:"type,omitempty"` - // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` - Properties *ApplicationLoadBalancerProperties `json:"properties"` } // NewApplicationLoadBalancerPut instantiates a new ApplicationLoadBalancerPut object @@ -45,152 +45,152 @@ func NewApplicationLoadBalancerPutWithDefaults() *ApplicationLoadBalancerPut { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerPut) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerPut) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerPut) GetIdOk() (*string, bool) { +func (o *ApplicationLoadBalancerPut) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *ApplicationLoadBalancerPut) SetId(v string) { +// SetHref sets field value +func (o *ApplicationLoadBalancerPut) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerPut) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerPut) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *ApplicationLoadBalancerPut) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerPut) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerPut) GetTypeOk() (*Type, bool) { +func (o *ApplicationLoadBalancerPut) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *ApplicationLoadBalancerPut) SetType(v Type) { +// SetId sets field value +func (o *ApplicationLoadBalancerPut) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerPut) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerPut) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancerPut) GetHref() *string { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerPut) GetProperties() *ApplicationLoadBalancerProperties { if o == nil { return nil } - return o.Href + return o.Properties } -// GetHrefOk returns a tuple with the Href field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerPut) GetHrefOk() (*string, bool) { +func (o *ApplicationLoadBalancerPut) GetPropertiesOk() (*ApplicationLoadBalancerProperties, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Properties, true } -// SetHref sets field value -func (o *ApplicationLoadBalancerPut) SetHref(v string) { +// SetProperties sets field value +func (o *ApplicationLoadBalancerPut) SetProperties(v ApplicationLoadBalancerProperties) { - o.Href = &v + o.Properties = &v } -// HasHref returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerPut) HasHref() bool { - if o != nil && o.Href != nil { +// HasProperties returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerPut) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for ApplicationLoadBalancerProperties will be returned -func (o *ApplicationLoadBalancerPut) GetProperties() *ApplicationLoadBalancerProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancerPut) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancerPut) GetPropertiesOk() (*ApplicationLoadBalancerProperties, bool) { +func (o *ApplicationLoadBalancerPut) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *ApplicationLoadBalancerPut) SetProperties(v ApplicationLoadBalancerProperties) { +// SetType sets field value +func (o *ApplicationLoadBalancerPut) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *ApplicationLoadBalancerPut) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *ApplicationLoadBalancerPut) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -199,18 +199,22 @@ func (o *ApplicationLoadBalancerPut) HasProperties() bool { func (o ApplicationLoadBalancerPut) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancers.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancers.go index a3eff3d6ae9..a2f3a9e04c1 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancers.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_application_load_balancers.go @@ -16,19 +16,19 @@ import ( // ApplicationLoadBalancers struct for ApplicationLoadBalancers type ApplicationLoadBalancers struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // The URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]ApplicationLoadBalancer `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewApplicationLoadBalancers instantiates a new ApplicationLoadBalancers object @@ -49,114 +49,114 @@ func NewApplicationLoadBalancersWithDefaults() *ApplicationLoadBalancers { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancers) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancers) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancers) GetIdOk() (*string, bool) { +func (o *ApplicationLoadBalancers) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *ApplicationLoadBalancers) SetId(v string) { +// SetLinks sets field value +func (o *ApplicationLoadBalancers) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *ApplicationLoadBalancers) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *ApplicationLoadBalancers) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *ApplicationLoadBalancers) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancers) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancers) GetTypeOk() (*Type, bool) { +func (o *ApplicationLoadBalancers) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *ApplicationLoadBalancers) SetType(v Type) { +// SetHref sets field value +func (o *ApplicationLoadBalancers) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *ApplicationLoadBalancers) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *ApplicationLoadBalancers) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ApplicationLoadBalancers) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancers) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancers) GetHrefOk() (*string, bool) { +func (o *ApplicationLoadBalancers) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *ApplicationLoadBalancers) SetHref(v string) { +// SetId sets field value +func (o *ApplicationLoadBalancers) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *ApplicationLoadBalancers) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *ApplicationLoadBalancers) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *ApplicationLoadBalancers) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []ApplicationLoadBalancer will be returned +// If the value is explicit nil, nil is returned func (o *ApplicationLoadBalancers) GetItems() *[]ApplicationLoadBalancer { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *ApplicationLoadBalancers) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *ApplicationLoadBalancers) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancers) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancers) GetOffsetOk() (*float32, bool) { +func (o *ApplicationLoadBalancers) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *ApplicationLoadBalancers) SetOffset(v float32) { +// SetLimit sets field value +func (o *ApplicationLoadBalancers) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *ApplicationLoadBalancers) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *ApplicationLoadBalancers) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *ApplicationLoadBalancers) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancers) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancers) GetLimitOk() (*float32, bool) { +func (o *ApplicationLoadBalancers) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *ApplicationLoadBalancers) SetLimit(v float32) { +// SetOffset sets field value +func (o *ApplicationLoadBalancers) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *ApplicationLoadBalancers) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *ApplicationLoadBalancers) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *ApplicationLoadBalancers) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *ApplicationLoadBalancers) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ApplicationLoadBalancers) GetLinksOk() (*PaginationLinks, bool) { +func (o *ApplicationLoadBalancers) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *ApplicationLoadBalancers) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *ApplicationLoadBalancers) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *ApplicationLoadBalancers) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *ApplicationLoadBalancers) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *ApplicationLoadBalancers) HasLinks() bool { func (o ApplicationLoadBalancers) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_attached_volumes.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_attached_volumes.go index 3791f488e5f..fdd81e42551 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_attached_volumes.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_attached_volumes.go @@ -16,19 +16,19 @@ import ( // AttachedVolumes struct for AttachedVolumes type AttachedVolumes struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // The URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Volume `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewAttachedVolumes instantiates a new AttachedVolumes object @@ -49,114 +49,114 @@ func NewAttachedVolumesWithDefaults() *AttachedVolumes { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *AttachedVolumes) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *AttachedVolumes) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *AttachedVolumes) GetIdOk() (*string, bool) { +func (o *AttachedVolumes) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *AttachedVolumes) SetId(v string) { +// SetLinks sets field value +func (o *AttachedVolumes) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *AttachedVolumes) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *AttachedVolumes) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *AttachedVolumes) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *AttachedVolumes) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *AttachedVolumes) GetTypeOk() (*Type, bool) { +func (o *AttachedVolumes) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *AttachedVolumes) SetType(v Type) { +// SetHref sets field value +func (o *AttachedVolumes) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *AttachedVolumes) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *AttachedVolumes) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *AttachedVolumes) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *AttachedVolumes) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *AttachedVolumes) GetHrefOk() (*string, bool) { +func (o *AttachedVolumes) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *AttachedVolumes) SetHref(v string) { +// SetId sets field value +func (o *AttachedVolumes) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *AttachedVolumes) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *AttachedVolumes) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *AttachedVolumes) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Volume will be returned +// If the value is explicit nil, nil is returned func (o *AttachedVolumes) GetItems() *[]Volume { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *AttachedVolumes) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *AttachedVolumes) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *AttachedVolumes) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *AttachedVolumes) GetOffsetOk() (*float32, bool) { +func (o *AttachedVolumes) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *AttachedVolumes) SetOffset(v float32) { +// SetLimit sets field value +func (o *AttachedVolumes) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *AttachedVolumes) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *AttachedVolumes) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *AttachedVolumes) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *AttachedVolumes) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *AttachedVolumes) GetLimitOk() (*float32, bool) { +func (o *AttachedVolumes) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *AttachedVolumes) SetLimit(v float32) { +// SetOffset sets field value +func (o *AttachedVolumes) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *AttachedVolumes) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *AttachedVolumes) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *AttachedVolumes) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *AttachedVolumes) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *AttachedVolumes) GetLinksOk() (*PaginationLinks, bool) { +func (o *AttachedVolumes) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *AttachedVolumes) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *AttachedVolumes) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *AttachedVolumes) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *AttachedVolumes) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *AttachedVolumes) HasLinks() bool { func (o AttachedVolumes) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_unit.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_unit.go index bc9197db953..6f1ff7c4746 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_unit.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_unit.go @@ -16,14 +16,14 @@ import ( // BackupUnit struct for BackupUnit type BackupUnit struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *string `json:"type,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *BackupUnitProperties `json:"properties"` + // The type of object that has been created. + Type *string `json:"type,omitempty"` } // NewBackupUnit instantiates a new BackupUnit object @@ -46,190 +46,190 @@ func NewBackupUnitWithDefaults() *BackupUnit { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *BackupUnit) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *BackupUnit) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BackupUnit) GetIdOk() (*string, bool) { +func (o *BackupUnit) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *BackupUnit) SetId(v string) { +// SetHref sets field value +func (o *BackupUnit) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *BackupUnit) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *BackupUnit) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *BackupUnit) GetType() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *BackupUnit) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BackupUnit) GetTypeOk() (*string, bool) { +func (o *BackupUnit) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *BackupUnit) SetType(v string) { +// SetId sets field value +func (o *BackupUnit) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *BackupUnit) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *BackupUnit) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *BackupUnit) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *BackupUnit) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BackupUnit) GetHrefOk() (*string, bool) { +func (o *BackupUnit) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *BackupUnit) SetHref(v string) { +// SetMetadata sets field value +func (o *BackupUnit) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *BackupUnit) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *BackupUnit) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *BackupUnit) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *BackupUnit) GetProperties() *BackupUnitProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BackupUnit) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *BackupUnit) GetPropertiesOk() (*BackupUnitProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *BackupUnit) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *BackupUnit) SetProperties(v BackupUnitProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *BackupUnit) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *BackupUnit) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for BackupUnitProperties will be returned -func (o *BackupUnit) GetProperties() *BackupUnitProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *BackupUnit) GetType() *string { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BackupUnit) GetPropertiesOk() (*BackupUnitProperties, bool) { +func (o *BackupUnit) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *BackupUnit) SetProperties(v BackupUnitProperties) { +// SetType sets field value +func (o *BackupUnit) SetType(v string) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *BackupUnit) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *BackupUnit) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *BackupUnit) HasProperties() bool { func (o BackupUnit) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_unit_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_unit_properties.go index 45b5584e28b..64698d35608 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_unit_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_unit_properties.go @@ -16,12 +16,12 @@ import ( // BackupUnitProperties struct for BackupUnitProperties type BackupUnitProperties struct { + // The email associated with the backup unit. Bear in mind that this email does not be the same email as of the user. + Email *string `json:"email,omitempty"` // The name of the resource (alphanumeric characters only). Name *string `json:"name"` // The password associated with that resource. Password *string `json:"password,omitempty"` - // The email associated with the backup unit. Bear in mind that this email does not be the same email as of the user. - Email *string `json:"email,omitempty"` } // NewBackupUnitProperties instantiates a new BackupUnitProperties object @@ -44,114 +44,114 @@ func NewBackupUnitPropertiesWithDefaults() *BackupUnitProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *BackupUnitProperties) GetName() *string { +// GetEmail returns the Email field value +// If the value is explicit nil, nil is returned +func (o *BackupUnitProperties) GetEmail() *string { if o == nil { return nil } - return o.Name + return o.Email } -// GetNameOk returns a tuple with the Name field value +// GetEmailOk returns a tuple with the Email field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BackupUnitProperties) GetNameOk() (*string, bool) { +func (o *BackupUnitProperties) GetEmailOk() (*string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.Email, true } -// SetName sets field value -func (o *BackupUnitProperties) SetName(v string) { +// SetEmail sets field value +func (o *BackupUnitProperties) SetEmail(v string) { - o.Name = &v + o.Email = &v } -// HasName returns a boolean if a field has been set. -func (o *BackupUnitProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasEmail returns a boolean if a field has been set. +func (o *BackupUnitProperties) HasEmail() bool { + if o != nil && o.Email != nil { return true } return false } -// GetPassword returns the Password field value -// If the value is explicit nil, the zero value for string will be returned -func (o *BackupUnitProperties) GetPassword() *string { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *BackupUnitProperties) GetName() *string { if o == nil { return nil } - return o.Password + return o.Name } -// GetPasswordOk returns a tuple with the Password field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BackupUnitProperties) GetPasswordOk() (*string, bool) { +func (o *BackupUnitProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.Password, true + return o.Name, true } -// SetPassword sets field value -func (o *BackupUnitProperties) SetPassword(v string) { +// SetName sets field value +func (o *BackupUnitProperties) SetName(v string) { - o.Password = &v + o.Name = &v } -// HasPassword returns a boolean if a field has been set. -func (o *BackupUnitProperties) HasPassword() bool { - if o != nil && o.Password != nil { +// HasName returns a boolean if a field has been set. +func (o *BackupUnitProperties) HasName() bool { + if o != nil && o.Name != nil { return true } return false } -// GetEmail returns the Email field value -// If the value is explicit nil, the zero value for string will be returned -func (o *BackupUnitProperties) GetEmail() *string { +// GetPassword returns the Password field value +// If the value is explicit nil, nil is returned +func (o *BackupUnitProperties) GetPassword() *string { if o == nil { return nil } - return o.Email + return o.Password } -// GetEmailOk returns a tuple with the Email field value +// GetPasswordOk returns a tuple with the Password field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BackupUnitProperties) GetEmailOk() (*string, bool) { +func (o *BackupUnitProperties) GetPasswordOk() (*string, bool) { if o == nil { return nil, false } - return o.Email, true + return o.Password, true } -// SetEmail sets field value -func (o *BackupUnitProperties) SetEmail(v string) { +// SetPassword sets field value +func (o *BackupUnitProperties) SetPassword(v string) { - o.Email = &v + o.Password = &v } -// HasEmail returns a boolean if a field has been set. -func (o *BackupUnitProperties) HasEmail() bool { - if o != nil && o.Email != nil { +// HasPassword returns a boolean if a field has been set. +func (o *BackupUnitProperties) HasPassword() bool { + if o != nil && o.Password != nil { return true } @@ -160,15 +160,18 @@ func (o *BackupUnitProperties) HasEmail() bool { func (o BackupUnitProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} + if o.Email != nil { + toSerialize["email"] = o.Email + } + if o.Name != nil { toSerialize["name"] = o.Name } + if o.Password != nil { toSerialize["password"] = o.Password } - if o.Email != nil { - toSerialize["email"] = o.Email - } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_unit_sso.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_unit_sso.go index f493bf950c8..ea6ba4159b5 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_unit_sso.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_unit_sso.go @@ -39,7 +39,7 @@ func NewBackupUnitSSOWithDefaults() *BackupUnitSSO { } // GetSsoUrl returns the SsoUrl field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *BackupUnitSSO) GetSsoUrl() *string { if o == nil { return nil @@ -81,6 +81,7 @@ func (o BackupUnitSSO) MarshalJSON() ([]byte, error) { if o.SsoUrl != nil { toSerialize["ssoUrl"] = o.SsoUrl } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_units.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_units.go index 6023f94e15a..280d50c6110 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_units.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_backup_units.go @@ -16,14 +16,14 @@ import ( // BackupUnits struct for BackupUnits type BackupUnits struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *string `json:"type,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]BackupUnit `json:"items,omitempty"` + // The type of object that has been created. + Type *string `json:"type,omitempty"` } // NewBackupUnits instantiates a new BackupUnits object @@ -44,152 +44,152 @@ func NewBackupUnitsWithDefaults() *BackupUnits { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *BackupUnits) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *BackupUnits) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BackupUnits) GetIdOk() (*string, bool) { +func (o *BackupUnits) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *BackupUnits) SetId(v string) { +// SetHref sets field value +func (o *BackupUnits) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *BackupUnits) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *BackupUnits) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *BackupUnits) GetType() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *BackupUnits) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BackupUnits) GetTypeOk() (*string, bool) { +func (o *BackupUnits) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *BackupUnits) SetType(v string) { +// SetId sets field value +func (o *BackupUnits) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *BackupUnits) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *BackupUnits) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *BackupUnits) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *BackupUnits) GetItems() *[]BackupUnit { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BackupUnits) GetHrefOk() (*string, bool) { +func (o *BackupUnits) GetItemsOk() (*[]BackupUnit, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *BackupUnits) SetHref(v string) { +// SetItems sets field value +func (o *BackupUnits) SetItems(v []BackupUnit) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *BackupUnits) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *BackupUnits) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []BackupUnit will be returned -func (o *BackupUnits) GetItems() *[]BackupUnit { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *BackupUnits) GetType() *string { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BackupUnits) GetItemsOk() (*[]BackupUnit, bool) { +func (o *BackupUnits) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *BackupUnits) SetItems(v []BackupUnit) { +// SetType sets field value +func (o *BackupUnits) SetType(v string) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *BackupUnits) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *BackupUnits) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *BackupUnits) HasItems() bool { func (o BackupUnits) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_balanced_nics.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_balanced_nics.go index feef17f6267..f9338b5784a 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_balanced_nics.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_balanced_nics.go @@ -16,19 +16,19 @@ import ( // BalancedNics struct for BalancedNics type BalancedNics struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Nic `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewBalancedNics instantiates a new BalancedNics object @@ -49,114 +49,114 @@ func NewBalancedNicsWithDefaults() *BalancedNics { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *BalancedNics) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *BalancedNics) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BalancedNics) GetIdOk() (*string, bool) { +func (o *BalancedNics) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *BalancedNics) SetId(v string) { +// SetLinks sets field value +func (o *BalancedNics) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *BalancedNics) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *BalancedNics) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *BalancedNics) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *BalancedNics) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BalancedNics) GetTypeOk() (*Type, bool) { +func (o *BalancedNics) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *BalancedNics) SetType(v Type) { +// SetHref sets field value +func (o *BalancedNics) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *BalancedNics) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *BalancedNics) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *BalancedNics) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *BalancedNics) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BalancedNics) GetHrefOk() (*string, bool) { +func (o *BalancedNics) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *BalancedNics) SetHref(v string) { +// SetId sets field value +func (o *BalancedNics) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *BalancedNics) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *BalancedNics) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *BalancedNics) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Nic will be returned +// If the value is explicit nil, nil is returned func (o *BalancedNics) GetItems() *[]Nic { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *BalancedNics) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *BalancedNics) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *BalancedNics) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BalancedNics) GetOffsetOk() (*float32, bool) { +func (o *BalancedNics) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *BalancedNics) SetOffset(v float32) { +// SetLimit sets field value +func (o *BalancedNics) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *BalancedNics) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *BalancedNics) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *BalancedNics) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *BalancedNics) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BalancedNics) GetLimitOk() (*float32, bool) { +func (o *BalancedNics) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *BalancedNics) SetLimit(v float32) { +// SetOffset sets field value +func (o *BalancedNics) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *BalancedNics) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *BalancedNics) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *BalancedNics) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *BalancedNics) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *BalancedNics) GetLinksOk() (*PaginationLinks, bool) { +func (o *BalancedNics) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *BalancedNics) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *BalancedNics) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *BalancedNics) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *BalancedNics) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *BalancedNics) HasLinks() bool { func (o BalancedNics) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_cdroms.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_cdroms.go index 4d2bb9a8536..86289fa1deb 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_cdroms.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_cdroms.go @@ -16,19 +16,19 @@ import ( // Cdroms struct for Cdroms type Cdroms struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Image `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewCdroms instantiates a new Cdroms object @@ -49,114 +49,114 @@ func NewCdromsWithDefaults() *Cdroms { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Cdroms) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *Cdroms) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Cdroms) GetIdOk() (*string, bool) { +func (o *Cdroms) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *Cdroms) SetId(v string) { +// SetLinks sets field value +func (o *Cdroms) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *Cdroms) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *Cdroms) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Cdroms) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Cdroms) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Cdroms) GetTypeOk() (*Type, bool) { +func (o *Cdroms) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Cdroms) SetType(v Type) { +// SetHref sets field value +func (o *Cdroms) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Cdroms) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Cdroms) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Cdroms) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Cdroms) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Cdroms) GetHrefOk() (*string, bool) { +func (o *Cdroms) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Cdroms) SetHref(v string) { +// SetId sets field value +func (o *Cdroms) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Cdroms) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Cdroms) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *Cdroms) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Image will be returned +// If the value is explicit nil, nil is returned func (o *Cdroms) GetItems() *[]Image { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *Cdroms) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Cdroms) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *Cdroms) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Cdroms) GetOffsetOk() (*float32, bool) { +func (o *Cdroms) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *Cdroms) SetOffset(v float32) { +// SetLimit sets field value +func (o *Cdroms) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *Cdroms) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *Cdroms) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Cdroms) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *Cdroms) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Cdroms) GetLimitOk() (*float32, bool) { +func (o *Cdroms) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *Cdroms) SetLimit(v float32) { +// SetOffset sets field value +func (o *Cdroms) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *Cdroms) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *Cdroms) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *Cdroms) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Cdroms) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Cdroms) GetLinksOk() (*PaginationLinks, bool) { +func (o *Cdroms) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *Cdroms) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *Cdroms) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *Cdroms) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *Cdroms) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *Cdroms) HasLinks() bool { func (o Cdroms) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_connectable_datacenter.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_connectable_datacenter.go index 6b8a5f4cd81..778a5bdd097 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_connectable_datacenter.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_connectable_datacenter.go @@ -17,8 +17,8 @@ import ( // ConnectableDatacenter struct for ConnectableDatacenter type ConnectableDatacenter struct { Id *string `json:"id,omitempty"` - Name *string `json:"name,omitempty"` Location *string `json:"location,omitempty"` + Name *string `json:"name,omitempty"` } // NewConnectableDatacenter instantiates a new ConnectableDatacenter object @@ -40,7 +40,7 @@ func NewConnectableDatacenterWithDefaults() *ConnectableDatacenter { } // GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *ConnectableDatacenter) GetId() *string { if o == nil { return nil @@ -77,76 +77,76 @@ func (o *ConnectableDatacenter) HasId() bool { return false } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ConnectableDatacenter) GetName() *string { +// GetLocation returns the Location field value +// If the value is explicit nil, nil is returned +func (o *ConnectableDatacenter) GetLocation() *string { if o == nil { return nil } - return o.Name + return o.Location } -// GetNameOk returns a tuple with the Name field value +// GetLocationOk returns a tuple with the Location field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ConnectableDatacenter) GetNameOk() (*string, bool) { +func (o *ConnectableDatacenter) GetLocationOk() (*string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.Location, true } -// SetName sets field value -func (o *ConnectableDatacenter) SetName(v string) { +// SetLocation sets field value +func (o *ConnectableDatacenter) SetLocation(v string) { - o.Name = &v + o.Location = &v } -// HasName returns a boolean if a field has been set. -func (o *ConnectableDatacenter) HasName() bool { - if o != nil && o.Name != nil { +// HasLocation returns a boolean if a field has been set. +func (o *ConnectableDatacenter) HasLocation() bool { + if o != nil && o.Location != nil { return true } return false } -// GetLocation returns the Location field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ConnectableDatacenter) GetLocation() *string { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *ConnectableDatacenter) GetName() *string { if o == nil { return nil } - return o.Location + return o.Name } -// GetLocationOk returns a tuple with the Location field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ConnectableDatacenter) GetLocationOk() (*string, bool) { +func (o *ConnectableDatacenter) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.Location, true + return o.Name, true } -// SetLocation sets field value -func (o *ConnectableDatacenter) SetLocation(v string) { +// SetName sets field value +func (o *ConnectableDatacenter) SetName(v string) { - o.Location = &v + o.Name = &v } -// HasLocation returns a boolean if a field has been set. -func (o *ConnectableDatacenter) HasLocation() bool { - if o != nil && o.Location != nil { +// HasName returns a boolean if a field has been set. +func (o *ConnectableDatacenter) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -158,12 +158,15 @@ func (o ConnectableDatacenter) MarshalJSON() ([]byte, error) { if o.Id != nil { toSerialize["id"] = o.Id } - if o.Name != nil { - toSerialize["name"] = o.Name - } + if o.Location != nil { toSerialize["location"] = o.Location } + + if o.Name != nil { + toSerialize["name"] = o.Name + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_contract.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_contract.go index e1e05792e97..d3ce413e191 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_contract.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_contract.go @@ -16,9 +16,9 @@ import ( // Contract struct for Contract type Contract struct { - // The type of the resource. - Type *Type `json:"type,omitempty"` Properties *ContractProperties `json:"properties"` + // The type of the resource. + Type *Type `json:"type,omitempty"` } // NewContract instantiates a new Contract object @@ -41,76 +41,76 @@ func NewContractWithDefaults() *Contract { return &this } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Contract) GetType() *Type { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *Contract) GetProperties() *ContractProperties { if o == nil { return nil } - return o.Type + return o.Properties } -// GetTypeOk returns a tuple with the Type field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Contract) GetTypeOk() (*Type, bool) { +func (o *Contract) GetPropertiesOk() (*ContractProperties, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Properties, true } -// SetType sets field value -func (o *Contract) SetType(v Type) { +// SetProperties sets field value +func (o *Contract) SetProperties(v ContractProperties) { - o.Type = &v + o.Properties = &v } -// HasType returns a boolean if a field has been set. -func (o *Contract) HasType() bool { - if o != nil && o.Type != nil { +// HasProperties returns a boolean if a field has been set. +func (o *Contract) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for ContractProperties will be returned -func (o *Contract) GetProperties() *ContractProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Contract) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Contract) GetPropertiesOk() (*ContractProperties, bool) { +func (o *Contract) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *Contract) SetProperties(v ContractProperties) { +// SetType sets field value +func (o *Contract) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *Contract) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *Contract) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -119,12 +119,14 @@ func (o *Contract) HasProperties() bool { func (o Contract) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_contract_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_contract_properties.go index 522f6182974..a579ea3b789 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_contract_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_contract_properties.go @@ -20,11 +20,11 @@ type ContractProperties struct { ContractNumber *int64 `json:"contractNumber,omitempty"` // The contract owner's user name. Owner *string `json:"owner,omitempty"` - // The contract status. - Status *string `json:"status,omitempty"` // The registration domain of the contract. RegDomain *string `json:"regDomain,omitempty"` ResourceLimits *ResourceLimits `json:"resourceLimits,omitempty"` + // The contract status. + Status *string `json:"status,omitempty"` } // NewContractProperties instantiates a new ContractProperties object @@ -46,7 +46,7 @@ func NewContractPropertiesWithDefaults() *ContractProperties { } // GetContractNumber returns the ContractNumber field value -// If the value is explicit nil, the zero value for int64 will be returned +// If the value is explicit nil, nil is returned func (o *ContractProperties) GetContractNumber() *int64 { if o == nil { return nil @@ -84,7 +84,7 @@ func (o *ContractProperties) HasContractNumber() bool { } // GetOwner returns the Owner field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *ContractProperties) GetOwner() *string { if o == nil { return nil @@ -121,114 +121,114 @@ func (o *ContractProperties) HasOwner() bool { return false } -// GetStatus returns the Status field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ContractProperties) GetStatus() *string { +// GetRegDomain returns the RegDomain field value +// If the value is explicit nil, nil is returned +func (o *ContractProperties) GetRegDomain() *string { if o == nil { return nil } - return o.Status + return o.RegDomain } -// GetStatusOk returns a tuple with the Status field value +// GetRegDomainOk returns a tuple with the RegDomain field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ContractProperties) GetStatusOk() (*string, bool) { +func (o *ContractProperties) GetRegDomainOk() (*string, bool) { if o == nil { return nil, false } - return o.Status, true + return o.RegDomain, true } -// SetStatus sets field value -func (o *ContractProperties) SetStatus(v string) { +// SetRegDomain sets field value +func (o *ContractProperties) SetRegDomain(v string) { - o.Status = &v + o.RegDomain = &v } -// HasStatus returns a boolean if a field has been set. -func (o *ContractProperties) HasStatus() bool { - if o != nil && o.Status != nil { +// HasRegDomain returns a boolean if a field has been set. +func (o *ContractProperties) HasRegDomain() bool { + if o != nil && o.RegDomain != nil { return true } return false } -// GetRegDomain returns the RegDomain field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ContractProperties) GetRegDomain() *string { +// GetResourceLimits returns the ResourceLimits field value +// If the value is explicit nil, nil is returned +func (o *ContractProperties) GetResourceLimits() *ResourceLimits { if o == nil { return nil } - return o.RegDomain + return o.ResourceLimits } -// GetRegDomainOk returns a tuple with the RegDomain field value +// GetResourceLimitsOk returns a tuple with the ResourceLimits field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ContractProperties) GetRegDomainOk() (*string, bool) { +func (o *ContractProperties) GetResourceLimitsOk() (*ResourceLimits, bool) { if o == nil { return nil, false } - return o.RegDomain, true + return o.ResourceLimits, true } -// SetRegDomain sets field value -func (o *ContractProperties) SetRegDomain(v string) { +// SetResourceLimits sets field value +func (o *ContractProperties) SetResourceLimits(v ResourceLimits) { - o.RegDomain = &v + o.ResourceLimits = &v } -// HasRegDomain returns a boolean if a field has been set. -func (o *ContractProperties) HasRegDomain() bool { - if o != nil && o.RegDomain != nil { +// HasResourceLimits returns a boolean if a field has been set. +func (o *ContractProperties) HasResourceLimits() bool { + if o != nil && o.ResourceLimits != nil { return true } return false } -// GetResourceLimits returns the ResourceLimits field value -// If the value is explicit nil, the zero value for ResourceLimits will be returned -func (o *ContractProperties) GetResourceLimits() *ResourceLimits { +// GetStatus returns the Status field value +// If the value is explicit nil, nil is returned +func (o *ContractProperties) GetStatus() *string { if o == nil { return nil } - return o.ResourceLimits + return o.Status } -// GetResourceLimitsOk returns a tuple with the ResourceLimits field value +// GetStatusOk returns a tuple with the Status field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ContractProperties) GetResourceLimitsOk() (*ResourceLimits, bool) { +func (o *ContractProperties) GetStatusOk() (*string, bool) { if o == nil { return nil, false } - return o.ResourceLimits, true + return o.Status, true } -// SetResourceLimits sets field value -func (o *ContractProperties) SetResourceLimits(v ResourceLimits) { +// SetStatus sets field value +func (o *ContractProperties) SetStatus(v string) { - o.ResourceLimits = &v + o.Status = &v } -// HasResourceLimits returns a boolean if a field has been set. -func (o *ContractProperties) HasResourceLimits() bool { - if o != nil && o.ResourceLimits != nil { +// HasStatus returns a boolean if a field has been set. +func (o *ContractProperties) HasStatus() bool { + if o != nil && o.Status != nil { return true } @@ -240,18 +240,23 @@ func (o ContractProperties) MarshalJSON() ([]byte, error) { if o.ContractNumber != nil { toSerialize["contractNumber"] = o.ContractNumber } + if o.Owner != nil { toSerialize["owner"] = o.Owner } - if o.Status != nil { - toSerialize["status"] = o.Status - } + if o.RegDomain != nil { toSerialize["regDomain"] = o.RegDomain } + if o.ResourceLimits != nil { toSerialize["resourceLimits"] = o.ResourceLimits } + + if o.Status != nil { + toSerialize["status"] = o.Status + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_contracts.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_contracts.go index c6fc46e310e..61e2f9aa961 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_contracts.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_contracts.go @@ -16,14 +16,14 @@ import ( // Contracts struct for Contracts type Contracts struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // The URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Contract `json:"items,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewContracts instantiates a new Contracts object @@ -44,152 +44,152 @@ func NewContractsWithDefaults() *Contracts { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Contracts) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Contracts) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Contracts) GetIdOk() (*string, bool) { +func (o *Contracts) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Contracts) SetId(v string) { +// SetHref sets field value +func (o *Contracts) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Contracts) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Contracts) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Contracts) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Contracts) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Contracts) GetTypeOk() (*Type, bool) { +func (o *Contracts) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Contracts) SetType(v Type) { +// SetId sets field value +func (o *Contracts) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Contracts) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Contracts) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Contracts) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *Contracts) GetItems() *[]Contract { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Contracts) GetHrefOk() (*string, bool) { +func (o *Contracts) GetItemsOk() (*[]Contract, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *Contracts) SetHref(v string) { +// SetItems sets field value +func (o *Contracts) SetItems(v []Contract) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *Contracts) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *Contracts) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Contract will be returned -func (o *Contracts) GetItems() *[]Contract { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Contracts) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Contracts) GetItemsOk() (*[]Contract, bool) { +func (o *Contracts) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *Contracts) SetItems(v []Contract) { +// SetType sets field value +func (o *Contracts) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *Contracts) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *Contracts) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *Contracts) HasItems() bool { func (o Contracts) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_cpu_architecture_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_cpu_architecture_properties.go index 80c6b6c2411..c86a3899dea 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_cpu_architecture_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_cpu_architecture_properties.go @@ -45,7 +45,7 @@ func NewCpuArchitecturePropertiesWithDefaults() *CpuArchitectureProperties { } // GetCpuFamily returns the CpuFamily field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *CpuArchitectureProperties) GetCpuFamily() *string { if o == nil { return nil @@ -83,7 +83,7 @@ func (o *CpuArchitectureProperties) HasCpuFamily() bool { } // GetMaxCores returns the MaxCores field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *CpuArchitectureProperties) GetMaxCores() *int32 { if o == nil { return nil @@ -121,7 +121,7 @@ func (o *CpuArchitectureProperties) HasMaxCores() bool { } // GetMaxRam returns the MaxRam field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *CpuArchitectureProperties) GetMaxRam() *int32 { if o == nil { return nil @@ -159,7 +159,7 @@ func (o *CpuArchitectureProperties) HasMaxRam() bool { } // GetVendor returns the Vendor field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *CpuArchitectureProperties) GetVendor() *string { if o == nil { return nil @@ -201,15 +201,19 @@ func (o CpuArchitectureProperties) MarshalJSON() ([]byte, error) { if o.CpuFamily != nil { toSerialize["cpuFamily"] = o.CpuFamily } + if o.MaxCores != nil { toSerialize["maxCores"] = o.MaxCores } + if o.MaxRam != nil { toSerialize["maxRam"] = o.MaxRam } + if o.Vendor != nil { toSerialize["vendor"] = o.Vendor } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_data_center_entities.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_data_center_entities.go index 65fa3ee3d1d..2ac821f85da 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_data_center_entities.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_data_center_entities.go @@ -16,12 +16,12 @@ import ( // DataCenterEntities struct for DataCenterEntities type DataCenterEntities struct { - Servers *Servers `json:"servers,omitempty"` - Volumes *Volumes `json:"volumes,omitempty"` - Loadbalancers *Loadbalancers `json:"loadbalancers,omitempty"` Lans *Lans `json:"lans,omitempty"` - Networkloadbalancers *NetworkLoadBalancers `json:"networkloadbalancers,omitempty"` + Loadbalancers *Loadbalancers `json:"loadbalancers,omitempty"` Natgateways *NatGateways `json:"natgateways,omitempty"` + Networkloadbalancers *NetworkLoadBalancers `json:"networkloadbalancers,omitempty"` + Servers *Servers `json:"servers,omitempty"` + Volumes *Volumes `json:"volumes,omitempty"` } // NewDataCenterEntities instantiates a new DataCenterEntities object @@ -42,228 +42,228 @@ func NewDataCenterEntitiesWithDefaults() *DataCenterEntities { return &this } -// GetServers returns the Servers field value -// If the value is explicit nil, the zero value for Servers will be returned -func (o *DataCenterEntities) GetServers() *Servers { +// GetLans returns the Lans field value +// If the value is explicit nil, nil is returned +func (o *DataCenterEntities) GetLans() *Lans { if o == nil { return nil } - return o.Servers + return o.Lans } -// GetServersOk returns a tuple with the Servers field value +// GetLansOk returns a tuple with the Lans field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *DataCenterEntities) GetServersOk() (*Servers, bool) { +func (o *DataCenterEntities) GetLansOk() (*Lans, bool) { if o == nil { return nil, false } - return o.Servers, true + return o.Lans, true } -// SetServers sets field value -func (o *DataCenterEntities) SetServers(v Servers) { +// SetLans sets field value +func (o *DataCenterEntities) SetLans(v Lans) { - o.Servers = &v + o.Lans = &v } -// HasServers returns a boolean if a field has been set. -func (o *DataCenterEntities) HasServers() bool { - if o != nil && o.Servers != nil { +// HasLans returns a boolean if a field has been set. +func (o *DataCenterEntities) HasLans() bool { + if o != nil && o.Lans != nil { return true } return false } -// GetVolumes returns the Volumes field value -// If the value is explicit nil, the zero value for Volumes will be returned -func (o *DataCenterEntities) GetVolumes() *Volumes { +// GetLoadbalancers returns the Loadbalancers field value +// If the value is explicit nil, nil is returned +func (o *DataCenterEntities) GetLoadbalancers() *Loadbalancers { if o == nil { return nil } - return o.Volumes + return o.Loadbalancers } -// GetVolumesOk returns a tuple with the Volumes field value +// GetLoadbalancersOk returns a tuple with the Loadbalancers field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *DataCenterEntities) GetVolumesOk() (*Volumes, bool) { +func (o *DataCenterEntities) GetLoadbalancersOk() (*Loadbalancers, bool) { if o == nil { return nil, false } - return o.Volumes, true + return o.Loadbalancers, true } -// SetVolumes sets field value -func (o *DataCenterEntities) SetVolumes(v Volumes) { +// SetLoadbalancers sets field value +func (o *DataCenterEntities) SetLoadbalancers(v Loadbalancers) { - o.Volumes = &v + o.Loadbalancers = &v } -// HasVolumes returns a boolean if a field has been set. -func (o *DataCenterEntities) HasVolumes() bool { - if o != nil && o.Volumes != nil { +// HasLoadbalancers returns a boolean if a field has been set. +func (o *DataCenterEntities) HasLoadbalancers() bool { + if o != nil && o.Loadbalancers != nil { return true } return false } -// GetLoadbalancers returns the Loadbalancers field value -// If the value is explicit nil, the zero value for Loadbalancers will be returned -func (o *DataCenterEntities) GetLoadbalancers() *Loadbalancers { +// GetNatgateways returns the Natgateways field value +// If the value is explicit nil, nil is returned +func (o *DataCenterEntities) GetNatgateways() *NatGateways { if o == nil { return nil } - return o.Loadbalancers + return o.Natgateways } -// GetLoadbalancersOk returns a tuple with the Loadbalancers field value +// GetNatgatewaysOk returns a tuple with the Natgateways field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *DataCenterEntities) GetLoadbalancersOk() (*Loadbalancers, bool) { +func (o *DataCenterEntities) GetNatgatewaysOk() (*NatGateways, bool) { if o == nil { return nil, false } - return o.Loadbalancers, true + return o.Natgateways, true } -// SetLoadbalancers sets field value -func (o *DataCenterEntities) SetLoadbalancers(v Loadbalancers) { +// SetNatgateways sets field value +func (o *DataCenterEntities) SetNatgateways(v NatGateways) { - o.Loadbalancers = &v + o.Natgateways = &v } -// HasLoadbalancers returns a boolean if a field has been set. -func (o *DataCenterEntities) HasLoadbalancers() bool { - if o != nil && o.Loadbalancers != nil { +// HasNatgateways returns a boolean if a field has been set. +func (o *DataCenterEntities) HasNatgateways() bool { + if o != nil && o.Natgateways != nil { return true } return false } -// GetLans returns the Lans field value -// If the value is explicit nil, the zero value for Lans will be returned -func (o *DataCenterEntities) GetLans() *Lans { +// GetNetworkloadbalancers returns the Networkloadbalancers field value +// If the value is explicit nil, nil is returned +func (o *DataCenterEntities) GetNetworkloadbalancers() *NetworkLoadBalancers { if o == nil { return nil } - return o.Lans + return o.Networkloadbalancers } -// GetLansOk returns a tuple with the Lans field value +// GetNetworkloadbalancersOk returns a tuple with the Networkloadbalancers field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *DataCenterEntities) GetLansOk() (*Lans, bool) { +func (o *DataCenterEntities) GetNetworkloadbalancersOk() (*NetworkLoadBalancers, bool) { if o == nil { return nil, false } - return o.Lans, true + return o.Networkloadbalancers, true } -// SetLans sets field value -func (o *DataCenterEntities) SetLans(v Lans) { +// SetNetworkloadbalancers sets field value +func (o *DataCenterEntities) SetNetworkloadbalancers(v NetworkLoadBalancers) { - o.Lans = &v + o.Networkloadbalancers = &v } -// HasLans returns a boolean if a field has been set. -func (o *DataCenterEntities) HasLans() bool { - if o != nil && o.Lans != nil { +// HasNetworkloadbalancers returns a boolean if a field has been set. +func (o *DataCenterEntities) HasNetworkloadbalancers() bool { + if o != nil && o.Networkloadbalancers != nil { return true } return false } -// GetNetworkloadbalancers returns the Networkloadbalancers field value -// If the value is explicit nil, the zero value for NetworkLoadBalancers will be returned -func (o *DataCenterEntities) GetNetworkloadbalancers() *NetworkLoadBalancers { +// GetServers returns the Servers field value +// If the value is explicit nil, nil is returned +func (o *DataCenterEntities) GetServers() *Servers { if o == nil { return nil } - return o.Networkloadbalancers + return o.Servers } -// GetNetworkloadbalancersOk returns a tuple with the Networkloadbalancers field value +// GetServersOk returns a tuple with the Servers field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *DataCenterEntities) GetNetworkloadbalancersOk() (*NetworkLoadBalancers, bool) { +func (o *DataCenterEntities) GetServersOk() (*Servers, bool) { if o == nil { return nil, false } - return o.Networkloadbalancers, true + return o.Servers, true } -// SetNetworkloadbalancers sets field value -func (o *DataCenterEntities) SetNetworkloadbalancers(v NetworkLoadBalancers) { +// SetServers sets field value +func (o *DataCenterEntities) SetServers(v Servers) { - o.Networkloadbalancers = &v + o.Servers = &v } -// HasNetworkloadbalancers returns a boolean if a field has been set. -func (o *DataCenterEntities) HasNetworkloadbalancers() bool { - if o != nil && o.Networkloadbalancers != nil { +// HasServers returns a boolean if a field has been set. +func (o *DataCenterEntities) HasServers() bool { + if o != nil && o.Servers != nil { return true } return false } -// GetNatgateways returns the Natgateways field value -// If the value is explicit nil, the zero value for NatGateways will be returned -func (o *DataCenterEntities) GetNatgateways() *NatGateways { +// GetVolumes returns the Volumes field value +// If the value is explicit nil, nil is returned +func (o *DataCenterEntities) GetVolumes() *Volumes { if o == nil { return nil } - return o.Natgateways + return o.Volumes } -// GetNatgatewaysOk returns a tuple with the Natgateways field value +// GetVolumesOk returns a tuple with the Volumes field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *DataCenterEntities) GetNatgatewaysOk() (*NatGateways, bool) { +func (o *DataCenterEntities) GetVolumesOk() (*Volumes, bool) { if o == nil { return nil, false } - return o.Natgateways, true + return o.Volumes, true } -// SetNatgateways sets field value -func (o *DataCenterEntities) SetNatgateways(v NatGateways) { +// SetVolumes sets field value +func (o *DataCenterEntities) SetVolumes(v Volumes) { - o.Natgateways = &v + o.Volumes = &v } -// HasNatgateways returns a boolean if a field has been set. -func (o *DataCenterEntities) HasNatgateways() bool { - if o != nil && o.Natgateways != nil { +// HasVolumes returns a boolean if a field has been set. +func (o *DataCenterEntities) HasVolumes() bool { + if o != nil && o.Volumes != nil { return true } @@ -272,24 +272,30 @@ func (o *DataCenterEntities) HasNatgateways() bool { func (o DataCenterEntities) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Servers != nil { - toSerialize["servers"] = o.Servers - } - if o.Volumes != nil { - toSerialize["volumes"] = o.Volumes + if o.Lans != nil { + toSerialize["lans"] = o.Lans } + if o.Loadbalancers != nil { toSerialize["loadbalancers"] = o.Loadbalancers } - if o.Lans != nil { - toSerialize["lans"] = o.Lans + + if o.Natgateways != nil { + toSerialize["natgateways"] = o.Natgateways } + if o.Networkloadbalancers != nil { toSerialize["networkloadbalancers"] = o.Networkloadbalancers } - if o.Natgateways != nil { - toSerialize["natgateways"] = o.Natgateways + + if o.Servers != nil { + toSerialize["servers"] = o.Servers } + + if o.Volumes != nil { + toSerialize["volumes"] = o.Volumes + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenter.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenter.go index 45a4e9d7dac..9b53f656c72 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenter.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenter.go @@ -16,15 +16,15 @@ import ( // Datacenter struct for Datacenter type Datacenter struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Entities *DataCenterEntities `json:"entities,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *DatacenterProperties `json:"properties"` - Entities *DataCenterEntities `json:"entities,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewDatacenter instantiates a new Datacenter object @@ -47,114 +47,114 @@ func NewDatacenterWithDefaults() *Datacenter { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Datacenter) GetId() *string { +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *Datacenter) GetEntities() *DataCenterEntities { if o == nil { return nil } - return o.Id + return o.Entities } -// GetIdOk returns a tuple with the Id field value +// GetEntitiesOk returns a tuple with the Entities field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Datacenter) GetIdOk() (*string, bool) { +func (o *Datacenter) GetEntitiesOk() (*DataCenterEntities, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Entities, true } -// SetId sets field value -func (o *Datacenter) SetId(v string) { +// SetEntities sets field value +func (o *Datacenter) SetEntities(v DataCenterEntities) { - o.Id = &v + o.Entities = &v } -// HasId returns a boolean if a field has been set. -func (o *Datacenter) HasId() bool { - if o != nil && o.Id != nil { +// HasEntities returns a boolean if a field has been set. +func (o *Datacenter) HasEntities() bool { + if o != nil && o.Entities != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Datacenter) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Datacenter) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Datacenter) GetTypeOk() (*Type, bool) { +func (o *Datacenter) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Datacenter) SetType(v Type) { +// SetHref sets field value +func (o *Datacenter) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Datacenter) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Datacenter) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Datacenter) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Datacenter) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Datacenter) GetHrefOk() (*string, bool) { +func (o *Datacenter) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Datacenter) SetHref(v string) { +// SetId sets field value +func (o *Datacenter) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Datacenter) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Datacenter) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -162,7 +162,7 @@ func (o *Datacenter) HasHref() bool { } // GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned +// If the value is explicit nil, nil is returned func (o *Datacenter) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil @@ -200,7 +200,7 @@ func (o *Datacenter) HasMetadata() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for DatacenterProperties will be returned +// If the value is explicit nil, nil is returned func (o *Datacenter) GetProperties() *DatacenterProperties { if o == nil { return nil @@ -237,38 +237,38 @@ func (o *Datacenter) HasProperties() bool { return false } -// GetEntities returns the Entities field value -// If the value is explicit nil, the zero value for DataCenterEntities will be returned -func (o *Datacenter) GetEntities() *DataCenterEntities { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Datacenter) GetType() *Type { if o == nil { return nil } - return o.Entities + return o.Type } -// GetEntitiesOk returns a tuple with the Entities field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Datacenter) GetEntitiesOk() (*DataCenterEntities, bool) { +func (o *Datacenter) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Entities, true + return o.Type, true } -// SetEntities sets field value -func (o *Datacenter) SetEntities(v DataCenterEntities) { +// SetType sets field value +func (o *Datacenter) SetType(v Type) { - o.Entities = &v + o.Type = &v } -// HasEntities returns a boolean if a field has been set. -func (o *Datacenter) HasEntities() bool { - if o != nil && o.Entities != nil { +// HasType returns a boolean if a field has been set. +func (o *Datacenter) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -277,24 +277,30 @@ func (o *Datacenter) HasEntities() bool { func (o Datacenter) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Entities != nil { + toSerialize["entities"] = o.Entities } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } - if o.Entities != nil { - toSerialize["entities"] = o.Entities + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenter_element_metadata.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenter_element_metadata.go index 3034ac67d30..d0d262ff511 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenter_element_metadata.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenter_element_metadata.go @@ -17,20 +17,20 @@ import ( // DatacenterElementMetadata struct for DatacenterElementMetadata type DatacenterElementMetadata struct { - // Resource's Entity Tag as defined in http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11 Entity Tag is also added as an 'ETag response header to requests which don't use 'depth' parameter. - Etag *string `json:"etag,omitempty"` - // The last time the resource was created. - CreatedDate *IonosTime // The user who created the resource. CreatedBy *string `json:"createdBy,omitempty"` // The unique ID of the user who created the resource. CreatedByUserId *string `json:"createdByUserId,omitempty"` - // The last time the resource was modified. - LastModifiedDate *IonosTime + // The last time the resource was created. + CreatedDate *IonosTime + // Resource's Entity Tag as defined in http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11 Entity Tag is also added as an 'ETag response header to requests which don't use 'depth' parameter. + Etag *string `json:"etag,omitempty"` // The user who last modified the resource. LastModifiedBy *string `json:"lastModifiedBy,omitempty"` // The unique ID of the user who last modified the resource. LastModifiedByUserId *string `json:"lastModifiedByUserId,omitempty"` + // The last time the resource was modified. + LastModifiedDate *IonosTime // State of the resource. *AVAILABLE* There are no pending modification requests for this item; *BUSY* There is at least one modification request pending and all following requests will be queued; *INACTIVE* Resource has been de-provisioned; *DEPLOYING* Resource state DEPLOYING - relevant for Kubernetes cluster/nodepool; *ACTIVE* Resource state ACTIVE - relevant for Kubernetes cluster/nodepool; *FAILED* Resource state FAILED - relevant for Kubernetes cluster/nodepool; *SUSPENDED* Resource state SUSPENDED - relevant for Kubernetes cluster/nodepool; *FAILED_SUSPENDED* Resource state FAILED_SUSPENDED - relevant for Kubernetes cluster; *UPDATING* Resource state UPDATING - relevant for Kubernetes cluster/nodepool; *FAILED_UPDATING* Resource state FAILED_UPDATING - relevant for Kubernetes cluster/nodepool; *DESTROYING* Resource state DESTROYING - relevant for Kubernetes cluster; *FAILED_DESTROYING* Resource state FAILED_DESTROYING - relevant for Kubernetes cluster/nodepool; *TERMINATED* Resource state TERMINATED - relevant for Kubernetes cluster/nodepool; *HIBERNATING* Resource state HIBERNATING - relevant for Kubernetes cluster/nodepool; *FAILED_HIBERNATING* Resource state FAILED_HIBERNATING - relevant for Kubernetes cluster/nodepool; *MAINTENANCE* Resource state MAINTENANCE - relevant for Kubernetes cluster/nodepool; *FAILED_HIBERNATING* Resource state FAILED_HIBERNATING - relevant for Kubernetes cluster/nodepool. State *string `json:"state,omitempty"` } @@ -53,91 +53,8 @@ func NewDatacenterElementMetadataWithDefaults() *DatacenterElementMetadata { return &this } -// GetEtag returns the Etag field value -// If the value is explicit nil, the zero value for string will be returned -func (o *DatacenterElementMetadata) GetEtag() *string { - if o == nil { - return nil - } - - return o.Etag - -} - -// GetEtagOk returns a tuple with the Etag field value -// and a boolean to check if the value has been set. -// NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *DatacenterElementMetadata) GetEtagOk() (*string, bool) { - if o == nil { - return nil, false - } - - return o.Etag, true -} - -// SetEtag sets field value -func (o *DatacenterElementMetadata) SetEtag(v string) { - - o.Etag = &v - -} - -// HasEtag returns a boolean if a field has been set. -func (o *DatacenterElementMetadata) HasEtag() bool { - if o != nil && o.Etag != nil { - return true - } - - return false -} - -// GetCreatedDate returns the CreatedDate field value -// If the value is explicit nil, the zero value for time.Time will be returned -func (o *DatacenterElementMetadata) GetCreatedDate() *time.Time { - if o == nil { - return nil - } - - if o.CreatedDate == nil { - return nil - } - return &o.CreatedDate.Time - -} - -// GetCreatedDateOk returns a tuple with the CreatedDate field value -// and a boolean to check if the value has been set. -// NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *DatacenterElementMetadata) GetCreatedDateOk() (*time.Time, bool) { - if o == nil { - return nil, false - } - - if o.CreatedDate == nil { - return nil, false - } - return &o.CreatedDate.Time, true - -} - -// SetCreatedDate sets field value -func (o *DatacenterElementMetadata) SetCreatedDate(v time.Time) { - - o.CreatedDate = &IonosTime{v} - -} - -// HasCreatedDate returns a boolean if a field has been set. -func (o *DatacenterElementMetadata) HasCreatedDate() bool { - if o != nil && o.CreatedDate != nil { - return true - } - - return false -} - // GetCreatedBy returns the CreatedBy field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *DatacenterElementMetadata) GetCreatedBy() *string { if o == nil { return nil @@ -175,7 +92,7 @@ func (o *DatacenterElementMetadata) HasCreatedBy() bool { } // GetCreatedByUserId returns the CreatedByUserId field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *DatacenterElementMetadata) GetCreatedByUserId() *string { if o == nil { return nil @@ -212,45 +129,83 @@ func (o *DatacenterElementMetadata) HasCreatedByUserId() bool { return false } -// GetLastModifiedDate returns the LastModifiedDate field value -// If the value is explicit nil, the zero value for time.Time will be returned -func (o *DatacenterElementMetadata) GetLastModifiedDate() *time.Time { +// GetCreatedDate returns the CreatedDate field value +// If the value is explicit nil, nil is returned +func (o *DatacenterElementMetadata) GetCreatedDate() *time.Time { if o == nil { return nil } - if o.LastModifiedDate == nil { + if o.CreatedDate == nil { return nil } - return &o.LastModifiedDate.Time + return &o.CreatedDate.Time } -// GetLastModifiedDateOk returns a tuple with the LastModifiedDate field value +// GetCreatedDateOk returns a tuple with the CreatedDate field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *DatacenterElementMetadata) GetLastModifiedDateOk() (*time.Time, bool) { +func (o *DatacenterElementMetadata) GetCreatedDateOk() (*time.Time, bool) { if o == nil { return nil, false } - if o.LastModifiedDate == nil { + if o.CreatedDate == nil { return nil, false } - return &o.LastModifiedDate.Time, true + return &o.CreatedDate.Time, true } -// SetLastModifiedDate sets field value -func (o *DatacenterElementMetadata) SetLastModifiedDate(v time.Time) { +// SetCreatedDate sets field value +func (o *DatacenterElementMetadata) SetCreatedDate(v time.Time) { - o.LastModifiedDate = &IonosTime{v} + o.CreatedDate = &IonosTime{v} } -// HasLastModifiedDate returns a boolean if a field has been set. -func (o *DatacenterElementMetadata) HasLastModifiedDate() bool { - if o != nil && o.LastModifiedDate != nil { +// HasCreatedDate returns a boolean if a field has been set. +func (o *DatacenterElementMetadata) HasCreatedDate() bool { + if o != nil && o.CreatedDate != nil { + return true + } + + return false +} + +// GetEtag returns the Etag field value +// If the value is explicit nil, nil is returned +func (o *DatacenterElementMetadata) GetEtag() *string { + if o == nil { + return nil + } + + return o.Etag + +} + +// GetEtagOk returns a tuple with the Etag field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *DatacenterElementMetadata) GetEtagOk() (*string, bool) { + if o == nil { + return nil, false + } + + return o.Etag, true +} + +// SetEtag sets field value +func (o *DatacenterElementMetadata) SetEtag(v string) { + + o.Etag = &v + +} + +// HasEtag returns a boolean if a field has been set. +func (o *DatacenterElementMetadata) HasEtag() bool { + if o != nil && o.Etag != nil { return true } @@ -258,7 +213,7 @@ func (o *DatacenterElementMetadata) HasLastModifiedDate() bool { } // GetLastModifiedBy returns the LastModifiedBy field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *DatacenterElementMetadata) GetLastModifiedBy() *string { if o == nil { return nil @@ -296,7 +251,7 @@ func (o *DatacenterElementMetadata) HasLastModifiedBy() bool { } // GetLastModifiedByUserId returns the LastModifiedByUserId field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *DatacenterElementMetadata) GetLastModifiedByUserId() *string { if o == nil { return nil @@ -333,8 +288,53 @@ func (o *DatacenterElementMetadata) HasLastModifiedByUserId() bool { return false } +// GetLastModifiedDate returns the LastModifiedDate field value +// If the value is explicit nil, nil is returned +func (o *DatacenterElementMetadata) GetLastModifiedDate() *time.Time { + if o == nil { + return nil + } + + if o.LastModifiedDate == nil { + return nil + } + return &o.LastModifiedDate.Time + +} + +// GetLastModifiedDateOk returns a tuple with the LastModifiedDate field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *DatacenterElementMetadata) GetLastModifiedDateOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + + if o.LastModifiedDate == nil { + return nil, false + } + return &o.LastModifiedDate.Time, true + +} + +// SetLastModifiedDate sets field value +func (o *DatacenterElementMetadata) SetLastModifiedDate(v time.Time) { + + o.LastModifiedDate = &IonosTime{v} + +} + +// HasLastModifiedDate returns a boolean if a field has been set. +func (o *DatacenterElementMetadata) HasLastModifiedDate() bool { + if o != nil && o.LastModifiedDate != nil { + return true + } + + return false +} + // GetState returns the State field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *DatacenterElementMetadata) GetState() *string { if o == nil { return nil @@ -373,30 +373,38 @@ func (o *DatacenterElementMetadata) HasState() bool { func (o DatacenterElementMetadata) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Etag != nil { - toSerialize["etag"] = o.Etag - } - if o.CreatedDate != nil { - toSerialize["createdDate"] = o.CreatedDate - } if o.CreatedBy != nil { toSerialize["createdBy"] = o.CreatedBy } + if o.CreatedByUserId != nil { toSerialize["createdByUserId"] = o.CreatedByUserId } - if o.LastModifiedDate != nil { - toSerialize["lastModifiedDate"] = o.LastModifiedDate + + if o.CreatedDate != nil { + toSerialize["createdDate"] = o.CreatedDate } + + if o.Etag != nil { + toSerialize["etag"] = o.Etag + } + if o.LastModifiedBy != nil { toSerialize["lastModifiedBy"] = o.LastModifiedBy } + if o.LastModifiedByUserId != nil { toSerialize["lastModifiedByUserId"] = o.LastModifiedByUserId } + + if o.LastModifiedDate != nil { + toSerialize["lastModifiedDate"] = o.LastModifiedDate + } + if o.State != nil { toSerialize["state"] = o.State } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenter_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenter_properties.go index 7ea45724220..18e81f828e9 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenter_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenter_properties.go @@ -16,20 +16,20 @@ import ( // DatacenterProperties struct for DatacenterProperties type DatacenterProperties struct { - // The name of the resource. - Name *string `json:"name,omitempty"` + // Array of features and CPU families available in a location + CpuArchitecture *[]CpuArchitectureProperties `json:"cpuArchitecture,omitempty"` // A description for the datacenter, such as staging, production. Description *string `json:"description,omitempty"` - // The physical location where the datacenter will be created. This will be where all of your servers live. Property cannot be modified after datacenter creation (disallowed in update requests). - Location *string `json:"location"` - // The version of the data center; incremented with every change. - Version *int32 `json:"version,omitempty"` // List of features supported by the location where this data center is provisioned. Features *[]string `json:"features,omitempty"` + // The physical location where the datacenter will be created. This will be where all of your servers live. Property cannot be modified after datacenter creation (disallowed in update requests). + Location *string `json:"location"` + // The name of the resource. + Name *string `json:"name,omitempty"` // Boolean value representing if the data center requires extra protection, such as two-step verification. SecAuthProtection *bool `json:"secAuthProtection,omitempty"` - // Array of features and CPU families available in a location - CpuArchitecture *[]CpuArchitectureProperties `json:"cpuArchitecture,omitempty"` + // The version of the data center; incremented with every change. + Version *int32 `json:"version,omitempty"` } // NewDatacenterProperties instantiates a new DatacenterProperties object @@ -52,38 +52,38 @@ func NewDatacenterPropertiesWithDefaults() *DatacenterProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *DatacenterProperties) GetName() *string { +// GetCpuArchitecture returns the CpuArchitecture field value +// If the value is explicit nil, nil is returned +func (o *DatacenterProperties) GetCpuArchitecture() *[]CpuArchitectureProperties { if o == nil { return nil } - return o.Name + return o.CpuArchitecture } -// GetNameOk returns a tuple with the Name field value +// GetCpuArchitectureOk returns a tuple with the CpuArchitecture field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *DatacenterProperties) GetNameOk() (*string, bool) { +func (o *DatacenterProperties) GetCpuArchitectureOk() (*[]CpuArchitectureProperties, bool) { if o == nil { return nil, false } - return o.Name, true + return o.CpuArchitecture, true } -// SetName sets field value -func (o *DatacenterProperties) SetName(v string) { +// SetCpuArchitecture sets field value +func (o *DatacenterProperties) SetCpuArchitecture(v []CpuArchitectureProperties) { - o.Name = &v + o.CpuArchitecture = &v } -// HasName returns a boolean if a field has been set. -func (o *DatacenterProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasCpuArchitecture returns a boolean if a field has been set. +func (o *DatacenterProperties) HasCpuArchitecture() bool { + if o != nil && o.CpuArchitecture != nil { return true } @@ -91,7 +91,7 @@ func (o *DatacenterProperties) HasName() bool { } // GetDescription returns the Description field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *DatacenterProperties) GetDescription() *string { if o == nil { return nil @@ -128,114 +128,114 @@ func (o *DatacenterProperties) HasDescription() bool { return false } -// GetLocation returns the Location field value -// If the value is explicit nil, the zero value for string will be returned -func (o *DatacenterProperties) GetLocation() *string { +// GetFeatures returns the Features field value +// If the value is explicit nil, nil is returned +func (o *DatacenterProperties) GetFeatures() *[]string { if o == nil { return nil } - return o.Location + return o.Features } -// GetLocationOk returns a tuple with the Location field value +// GetFeaturesOk returns a tuple with the Features field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *DatacenterProperties) GetLocationOk() (*string, bool) { +func (o *DatacenterProperties) GetFeaturesOk() (*[]string, bool) { if o == nil { return nil, false } - return o.Location, true + return o.Features, true } -// SetLocation sets field value -func (o *DatacenterProperties) SetLocation(v string) { +// SetFeatures sets field value +func (o *DatacenterProperties) SetFeatures(v []string) { - o.Location = &v + o.Features = &v } -// HasLocation returns a boolean if a field has been set. -func (o *DatacenterProperties) HasLocation() bool { - if o != nil && o.Location != nil { +// HasFeatures returns a boolean if a field has been set. +func (o *DatacenterProperties) HasFeatures() bool { + if o != nil && o.Features != nil { return true } return false } -// GetVersion returns the Version field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *DatacenterProperties) GetVersion() *int32 { +// GetLocation returns the Location field value +// If the value is explicit nil, nil is returned +func (o *DatacenterProperties) GetLocation() *string { if o == nil { return nil } - return o.Version + return o.Location } -// GetVersionOk returns a tuple with the Version field value +// GetLocationOk returns a tuple with the Location field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *DatacenterProperties) GetVersionOk() (*int32, bool) { +func (o *DatacenterProperties) GetLocationOk() (*string, bool) { if o == nil { return nil, false } - return o.Version, true + return o.Location, true } -// SetVersion sets field value -func (o *DatacenterProperties) SetVersion(v int32) { +// SetLocation sets field value +func (o *DatacenterProperties) SetLocation(v string) { - o.Version = &v + o.Location = &v } -// HasVersion returns a boolean if a field has been set. -func (o *DatacenterProperties) HasVersion() bool { - if o != nil && o.Version != nil { +// HasLocation returns a boolean if a field has been set. +func (o *DatacenterProperties) HasLocation() bool { + if o != nil && o.Location != nil { return true } return false } -// GetFeatures returns the Features field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *DatacenterProperties) GetFeatures() *[]string { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *DatacenterProperties) GetName() *string { if o == nil { return nil } - return o.Features + return o.Name } -// GetFeaturesOk returns a tuple with the Features field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *DatacenterProperties) GetFeaturesOk() (*[]string, bool) { +func (o *DatacenterProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.Features, true + return o.Name, true } -// SetFeatures sets field value -func (o *DatacenterProperties) SetFeatures(v []string) { +// SetName sets field value +func (o *DatacenterProperties) SetName(v string) { - o.Features = &v + o.Name = &v } -// HasFeatures returns a boolean if a field has been set. -func (o *DatacenterProperties) HasFeatures() bool { - if o != nil && o.Features != nil { +// HasName returns a boolean if a field has been set. +func (o *DatacenterProperties) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -243,7 +243,7 @@ func (o *DatacenterProperties) HasFeatures() bool { } // GetSecAuthProtection returns the SecAuthProtection field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *DatacenterProperties) GetSecAuthProtection() *bool { if o == nil { return nil @@ -280,38 +280,38 @@ func (o *DatacenterProperties) HasSecAuthProtection() bool { return false } -// GetCpuArchitecture returns the CpuArchitecture field value -// If the value is explicit nil, the zero value for []CpuArchitectureProperties will be returned -func (o *DatacenterProperties) GetCpuArchitecture() *[]CpuArchitectureProperties { +// GetVersion returns the Version field value +// If the value is explicit nil, nil is returned +func (o *DatacenterProperties) GetVersion() *int32 { if o == nil { return nil } - return o.CpuArchitecture + return o.Version } -// GetCpuArchitectureOk returns a tuple with the CpuArchitecture field value +// GetVersionOk returns a tuple with the Version field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *DatacenterProperties) GetCpuArchitectureOk() (*[]CpuArchitectureProperties, bool) { +func (o *DatacenterProperties) GetVersionOk() (*int32, bool) { if o == nil { return nil, false } - return o.CpuArchitecture, true + return o.Version, true } -// SetCpuArchitecture sets field value -func (o *DatacenterProperties) SetCpuArchitecture(v []CpuArchitectureProperties) { +// SetVersion sets field value +func (o *DatacenterProperties) SetVersion(v int32) { - o.CpuArchitecture = &v + o.Version = &v } -// HasCpuArchitecture returns a boolean if a field has been set. -func (o *DatacenterProperties) HasCpuArchitecture() bool { - if o != nil && o.CpuArchitecture != nil { +// HasVersion returns a boolean if a field has been set. +func (o *DatacenterProperties) HasVersion() bool { + if o != nil && o.Version != nil { return true } @@ -320,27 +320,34 @@ func (o *DatacenterProperties) HasCpuArchitecture() bool { func (o DatacenterProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name + if o.CpuArchitecture != nil { + toSerialize["cpuArchitecture"] = o.CpuArchitecture } + if o.Description != nil { toSerialize["description"] = o.Description } + + if o.Features != nil { + toSerialize["features"] = o.Features + } + if o.Location != nil { toSerialize["location"] = o.Location } - if o.Version != nil { - toSerialize["version"] = o.Version - } - if o.Features != nil { - toSerialize["features"] = o.Features + + if o.Name != nil { + toSerialize["name"] = o.Name } + if o.SecAuthProtection != nil { toSerialize["secAuthProtection"] = o.SecAuthProtection } - if o.CpuArchitecture != nil { - toSerialize["cpuArchitecture"] = o.CpuArchitecture + + if o.Version != nil { + toSerialize["version"] = o.Version } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenters.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenters.go index 28911601f0c..43c00c3c7da 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenters.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_datacenters.go @@ -16,19 +16,19 @@ import ( // Datacenters struct for Datacenters type Datacenters struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Datacenter `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewDatacenters instantiates a new Datacenters object @@ -49,114 +49,114 @@ func NewDatacentersWithDefaults() *Datacenters { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Datacenters) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *Datacenters) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Datacenters) GetIdOk() (*string, bool) { +func (o *Datacenters) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *Datacenters) SetId(v string) { +// SetLinks sets field value +func (o *Datacenters) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *Datacenters) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *Datacenters) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Datacenters) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Datacenters) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Datacenters) GetTypeOk() (*Type, bool) { +func (o *Datacenters) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Datacenters) SetType(v Type) { +// SetHref sets field value +func (o *Datacenters) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Datacenters) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Datacenters) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Datacenters) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Datacenters) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Datacenters) GetHrefOk() (*string, bool) { +func (o *Datacenters) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Datacenters) SetHref(v string) { +// SetId sets field value +func (o *Datacenters) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Datacenters) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Datacenters) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *Datacenters) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Datacenter will be returned +// If the value is explicit nil, nil is returned func (o *Datacenters) GetItems() *[]Datacenter { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *Datacenters) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Datacenters) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *Datacenters) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Datacenters) GetOffsetOk() (*float32, bool) { +func (o *Datacenters) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *Datacenters) SetOffset(v float32) { +// SetLimit sets field value +func (o *Datacenters) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *Datacenters) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *Datacenters) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Datacenters) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *Datacenters) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Datacenters) GetLimitOk() (*float32, bool) { +func (o *Datacenters) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *Datacenters) SetLimit(v float32) { +// SetOffset sets field value +func (o *Datacenters) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *Datacenters) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *Datacenters) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *Datacenters) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Datacenters) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Datacenters) GetLinksOk() (*PaginationLinks, bool) { +func (o *Datacenters) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *Datacenters) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *Datacenters) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *Datacenters) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *Datacenters) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *Datacenters) HasLinks() bool { func (o Datacenters) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_error.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_error.go index a383952b792..d5e52dd39b0 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_error.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_error.go @@ -40,7 +40,7 @@ func NewErrorWithDefaults() *Error { } // GetHttpStatus returns the HttpStatus field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *Error) GetHttpStatus() *int32 { if o == nil { return nil @@ -78,7 +78,7 @@ func (o *Error) HasHttpStatus() bool { } // GetMessages returns the Messages field value -// If the value is explicit nil, the zero value for []ErrorMessage will be returned +// If the value is explicit nil, nil is returned func (o *Error) GetMessages() *[]ErrorMessage { if o == nil { return nil @@ -120,9 +120,11 @@ func (o Error) MarshalJSON() ([]byte, error) { if o.HttpStatus != nil { toSerialize["httpStatus"] = o.HttpStatus } + if o.Messages != nil { toSerialize["messages"] = o.Messages } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_error_message.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_error_message.go index f3044d977df..d567be376c3 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_error_message.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_error_message.go @@ -41,7 +41,7 @@ func NewErrorMessageWithDefaults() *ErrorMessage { } // GetErrorCode returns the ErrorCode field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *ErrorMessage) GetErrorCode() *string { if o == nil { return nil @@ -79,7 +79,7 @@ func (o *ErrorMessage) HasErrorCode() bool { } // GetMessage returns the Message field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *ErrorMessage) GetMessage() *string { if o == nil { return nil @@ -121,9 +121,11 @@ func (o ErrorMessage) MarshalJSON() ([]byte, error) { if o.ErrorCode != nil { toSerialize["errorCode"] = o.ErrorCode } + if o.Message != nil { toSerialize["message"] = o.Message } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_firewall_rule.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_firewall_rule.go index 6b472e4e913..88f0f5ead32 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_firewall_rule.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_firewall_rule.go @@ -16,14 +16,14 @@ import ( // FirewallRule struct for FirewallRule type FirewallRule struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *FirewallruleProperties `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewFirewallRule instantiates a new FirewallRule object @@ -46,190 +46,190 @@ func NewFirewallRuleWithDefaults() *FirewallRule { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FirewallRule) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *FirewallRule) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallRule) GetIdOk() (*string, bool) { +func (o *FirewallRule) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *FirewallRule) SetId(v string) { +// SetHref sets field value +func (o *FirewallRule) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *FirewallRule) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *FirewallRule) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *FirewallRule) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *FirewallRule) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallRule) GetTypeOk() (*Type, bool) { +func (o *FirewallRule) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *FirewallRule) SetType(v Type) { +// SetId sets field value +func (o *FirewallRule) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *FirewallRule) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *FirewallRule) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FirewallRule) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *FirewallRule) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallRule) GetHrefOk() (*string, bool) { +func (o *FirewallRule) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *FirewallRule) SetHref(v string) { +// SetMetadata sets field value +func (o *FirewallRule) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *FirewallRule) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *FirewallRule) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *FirewallRule) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *FirewallRule) GetProperties() *FirewallruleProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallRule) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *FirewallRule) GetPropertiesOk() (*FirewallruleProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *FirewallRule) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *FirewallRule) SetProperties(v FirewallruleProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *FirewallRule) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *FirewallRule) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for FirewallruleProperties will be returned -func (o *FirewallRule) GetProperties() *FirewallruleProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *FirewallRule) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallRule) GetPropertiesOk() (*FirewallruleProperties, bool) { +func (o *FirewallRule) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *FirewallRule) SetProperties(v FirewallruleProperties) { +// SetType sets field value +func (o *FirewallRule) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *FirewallRule) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *FirewallRule) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *FirewallRule) HasProperties() bool { func (o FirewallRule) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_firewall_rules.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_firewall_rules.go index f3b572931ca..5701dda1200 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_firewall_rules.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_firewall_rules.go @@ -16,19 +16,19 @@ import ( // FirewallRules struct for FirewallRules type FirewallRules struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]FirewallRule `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewFirewallRules instantiates a new FirewallRules object @@ -49,114 +49,114 @@ func NewFirewallRulesWithDefaults() *FirewallRules { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FirewallRules) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *FirewallRules) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallRules) GetIdOk() (*string, bool) { +func (o *FirewallRules) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *FirewallRules) SetId(v string) { +// SetLinks sets field value +func (o *FirewallRules) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *FirewallRules) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *FirewallRules) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *FirewallRules) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *FirewallRules) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallRules) GetTypeOk() (*Type, bool) { +func (o *FirewallRules) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *FirewallRules) SetType(v Type) { +// SetHref sets field value +func (o *FirewallRules) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *FirewallRules) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *FirewallRules) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FirewallRules) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *FirewallRules) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallRules) GetHrefOk() (*string, bool) { +func (o *FirewallRules) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *FirewallRules) SetHref(v string) { +// SetId sets field value +func (o *FirewallRules) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *FirewallRules) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *FirewallRules) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *FirewallRules) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []FirewallRule will be returned +// If the value is explicit nil, nil is returned func (o *FirewallRules) GetItems() *[]FirewallRule { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *FirewallRules) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *FirewallRules) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *FirewallRules) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallRules) GetOffsetOk() (*float32, bool) { +func (o *FirewallRules) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *FirewallRules) SetOffset(v float32) { +// SetLimit sets field value +func (o *FirewallRules) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *FirewallRules) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *FirewallRules) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *FirewallRules) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *FirewallRules) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallRules) GetLimitOk() (*float32, bool) { +func (o *FirewallRules) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *FirewallRules) SetLimit(v float32) { +// SetOffset sets field value +func (o *FirewallRules) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *FirewallRules) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *FirewallRules) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *FirewallRules) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *FirewallRules) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallRules) GetLinksOk() (*PaginationLinks, bool) { +func (o *FirewallRules) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *FirewallRules) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *FirewallRules) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *FirewallRules) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *FirewallRules) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *FirewallRules) HasLinks() bool { func (o FirewallRules) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_firewallrule_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_firewallrule_properties.go index 640cd23fb58..0e5de49b3b3 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_firewallrule_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_firewallrule_properties.go @@ -16,26 +16,32 @@ import ( // FirewallruleProperties struct for FirewallruleProperties type FirewallruleProperties struct { + // Defines the allowed code (from 0 to 254) if protocol ICMP or ICMPv6 is chosen. Value null allows all codes. + // to set this field to `nil` in order to be marshalled, the explicit nil address `Nilint32` can be used, or the setter `SetIcmpCodeNil` + IcmpCode *int32 `json:"icmpCode,omitempty"` + // Defines the allowed type (from 0 to 254) if the protocol ICMP or ICMPv6 is chosen. Value null allows all types. + // to set this field to `nil` in order to be marshalled, the explicit nil address `Nilint32` can be used, or the setter `SetIcmpTypeNil` + IcmpType *int32 `json:"icmpType,omitempty"` + // The IP version for this rule. If sourceIp or targetIp are specified, you can omit this value - the IP version will then be deduced from the IP address(es) used; if you specify it anyway, it must match the specified IP address(es). If neither sourceIp nor targetIp are specified, this rule allows traffic only for the specified IP version. If neither sourceIp, targetIp nor ipVersion are specified, this rule will only allow IPv4 traffic. + // to set this field to `nil` in order to be marshalled, the explicit nil address `Nilstring` can be used, or the setter `SetIpVersionNil` + IpVersion *string `json:"ipVersion,omitempty"` // The name of the resource. Name *string `json:"name,omitempty"` + // Defines the end range of the allowed port (from 1 to 65534) if the protocol TCP or UDP is chosen. Leave portRangeStart and portRangeEnd null to allow all ports. + PortRangeEnd *int32 `json:"portRangeEnd,omitempty"` + // Defines the start range of the allowed port (from 1 to 65534) if protocol TCP or UDP is chosen. Leave portRangeStart and portRangeEnd value null to allow all ports. + PortRangeStart *int32 `json:"portRangeStart,omitempty"` // The protocol for the rule. Property cannot be modified after it is created (disallowed in update requests). Protocol *string `json:"protocol"` - // Only traffic originating from the respective MAC address is allowed. Valid format: aa:bb:cc:dd:ee:ff. Value null allows traffic from any MAC address. - SourceMac *string `json:"sourceMac,omitempty"` - // The IP version for this rule. If sourceIp or targetIp are specified, you can omit this value - the IP version will then be deduced from the IP address(es) used; if you specify it anyway, it must match the specified IP address(es). If neither sourceIp nor targetIp are specified, this rule allows traffic only for the specified IP version. If neither sourceIp, targetIp nor ipVersion are specified, this rule will only allow IPv4 traffic. - IpVersion *string `json:"ipVersion,omitempty"` // Only traffic originating from the respective IP address (or CIDR block) is allowed. Value null allows traffic from any IP address (according to the selected ipVersion). + // to set this field to `nil` in order to be marshalled, the explicit nil address `Nilstring` can be used, or the setter `SetSourceIpNil` SourceIp *string `json:"sourceIp,omitempty"` + // Only traffic originating from the respective MAC address is allowed. Valid format: aa:bb:cc:dd:ee:ff. Value null allows traffic from any MAC address. + // to set this field to `nil` in order to be marshalled, the explicit nil address `Nilstring` can be used, or the setter `SetSourceMacNil` + SourceMac *string `json:"sourceMac,omitempty"` // If the target NIC has multiple IP addresses, only the traffic directed to the respective IP address (or CIDR block) of the NIC is allowed. Value null allows traffic to any target IP address (according to the selected ipVersion). + // to set this field to `nil` in order to be marshalled, the explicit nil address `Nilstring` can be used, or the setter `SetTargetIpNil` TargetIp *string `json:"targetIp,omitempty"` - // Defines the allowed code (from 0 to 254) if protocol ICMP or ICMPv6 is chosen. Value null allows all codes. - IcmpCode *int32 `json:"icmpCode,omitempty"` - // Defines the allowed type (from 0 to 254) if the protocol ICMP or ICMPv6 is chosen. Value null allows all types. - IcmpType *int32 `json:"icmpType,omitempty"` - // Defines the start range of the allowed port (from 1 to 65534) if protocol TCP or UDP is chosen. Leave portRangeStart and portRangeEnd value null to allow all ports. - PortRangeStart *int32 `json:"portRangeStart,omitempty"` - // Defines the end range of the allowed port (from 1 to 65534) if the protocol TCP or UDP is chosen. Leave portRangeStart and portRangeEnd null to allow all ports. - PortRangeEnd *int32 `json:"portRangeEnd,omitempty"` // The type of the firewall rule. If not specified, the default INGRESS value is used. Type *string `json:"type,omitempty"` } @@ -60,380 +66,410 @@ func NewFirewallrulePropertiesWithDefaults() *FirewallruleProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FirewallruleProperties) GetName() *string { +// GetIcmpCode returns the IcmpCode field value +// If the value is explicit nil, nil is returned +func (o *FirewallruleProperties) GetIcmpCode() *int32 { if o == nil { return nil } - return o.Name + return o.IcmpCode } -// GetNameOk returns a tuple with the Name field value +// GetIcmpCodeOk returns a tuple with the IcmpCode field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallruleProperties) GetNameOk() (*string, bool) { +func (o *FirewallruleProperties) GetIcmpCodeOk() (*int32, bool) { if o == nil { return nil, false } - return o.Name, true + return o.IcmpCode, true } -// SetName sets field value -func (o *FirewallruleProperties) SetName(v string) { +// SetIcmpCode sets field value +func (o *FirewallruleProperties) SetIcmpCode(v int32) { - o.Name = &v + o.IcmpCode = &v } -// HasName returns a boolean if a field has been set. -func (o *FirewallruleProperties) HasName() bool { - if o != nil && o.Name != nil { +// sets IcmpCode to the explicit address that will be encoded as nil when marshaled +func (o *FirewallruleProperties) SetIcmpCodeNil() { + o.IcmpCode = &Nilint32 +} + +// HasIcmpCode returns a boolean if a field has been set. +func (o *FirewallruleProperties) HasIcmpCode() bool { + if o != nil && o.IcmpCode != nil { return true } return false } -// GetProtocol returns the Protocol field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FirewallruleProperties) GetProtocol() *string { +// GetIcmpType returns the IcmpType field value +// If the value is explicit nil, nil is returned +func (o *FirewallruleProperties) GetIcmpType() *int32 { if o == nil { return nil } - return o.Protocol + return o.IcmpType } -// GetProtocolOk returns a tuple with the Protocol field value +// GetIcmpTypeOk returns a tuple with the IcmpType field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallruleProperties) GetProtocolOk() (*string, bool) { +func (o *FirewallruleProperties) GetIcmpTypeOk() (*int32, bool) { if o == nil { return nil, false } - return o.Protocol, true + return o.IcmpType, true } -// SetProtocol sets field value -func (o *FirewallruleProperties) SetProtocol(v string) { +// SetIcmpType sets field value +func (o *FirewallruleProperties) SetIcmpType(v int32) { - o.Protocol = &v + o.IcmpType = &v } -// HasProtocol returns a boolean if a field has been set. -func (o *FirewallruleProperties) HasProtocol() bool { - if o != nil && o.Protocol != nil { +// sets IcmpType to the explicit address that will be encoded as nil when marshaled +func (o *FirewallruleProperties) SetIcmpTypeNil() { + o.IcmpType = &Nilint32 +} + +// HasIcmpType returns a boolean if a field has been set. +func (o *FirewallruleProperties) HasIcmpType() bool { + if o != nil && o.IcmpType != nil { return true } return false } -// GetSourceMac returns the SourceMac field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FirewallruleProperties) GetSourceMac() *string { +// GetIpVersion returns the IpVersion field value +// If the value is explicit nil, nil is returned +func (o *FirewallruleProperties) GetIpVersion() *string { if o == nil { return nil } - return o.SourceMac + return o.IpVersion } -// GetSourceMacOk returns a tuple with the SourceMac field value +// GetIpVersionOk returns a tuple with the IpVersion field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallruleProperties) GetSourceMacOk() (*string, bool) { +func (o *FirewallruleProperties) GetIpVersionOk() (*string, bool) { if o == nil { return nil, false } - return o.SourceMac, true + return o.IpVersion, true } -// SetSourceMac sets field value -func (o *FirewallruleProperties) SetSourceMac(v string) { +// SetIpVersion sets field value +func (o *FirewallruleProperties) SetIpVersion(v string) { - o.SourceMac = &v + o.IpVersion = &v } -// HasSourceMac returns a boolean if a field has been set. -func (o *FirewallruleProperties) HasSourceMac() bool { - if o != nil && o.SourceMac != nil { +// sets IpVersion to the explicit address that will be encoded as nil when marshaled +func (o *FirewallruleProperties) SetIpVersionNil() { + o.IpVersion = &Nilstring +} + +// HasIpVersion returns a boolean if a field has been set. +func (o *FirewallruleProperties) HasIpVersion() bool { + if o != nil && o.IpVersion != nil { return true } return false } -// GetIpVersion returns the IpVersion field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FirewallruleProperties) GetIpVersion() *string { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *FirewallruleProperties) GetName() *string { if o == nil { return nil } - return o.IpVersion + return o.Name } -// GetIpVersionOk returns a tuple with the IpVersion field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallruleProperties) GetIpVersionOk() (*string, bool) { +func (o *FirewallruleProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.IpVersion, true + return o.Name, true } -// SetIpVersion sets field value -func (o *FirewallruleProperties) SetIpVersion(v string) { +// SetName sets field value +func (o *FirewallruleProperties) SetName(v string) { - o.IpVersion = &v + o.Name = &v } -// HasIpVersion returns a boolean if a field has been set. -func (o *FirewallruleProperties) HasIpVersion() bool { - if o != nil && o.IpVersion != nil { +// HasName returns a boolean if a field has been set. +func (o *FirewallruleProperties) HasName() bool { + if o != nil && o.Name != nil { return true } return false } -// GetSourceIp returns the SourceIp field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FirewallruleProperties) GetSourceIp() *string { +// GetPortRangeEnd returns the PortRangeEnd field value +// If the value is explicit nil, nil is returned +func (o *FirewallruleProperties) GetPortRangeEnd() *int32 { if o == nil { return nil } - return o.SourceIp + return o.PortRangeEnd } -// GetSourceIpOk returns a tuple with the SourceIp field value +// GetPortRangeEndOk returns a tuple with the PortRangeEnd field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallruleProperties) GetSourceIpOk() (*string, bool) { +func (o *FirewallruleProperties) GetPortRangeEndOk() (*int32, bool) { if o == nil { return nil, false } - return o.SourceIp, true + return o.PortRangeEnd, true } -// SetSourceIp sets field value -func (o *FirewallruleProperties) SetSourceIp(v string) { +// SetPortRangeEnd sets field value +func (o *FirewallruleProperties) SetPortRangeEnd(v int32) { - o.SourceIp = &v + o.PortRangeEnd = &v } -// HasSourceIp returns a boolean if a field has been set. -func (o *FirewallruleProperties) HasSourceIp() bool { - if o != nil && o.SourceIp != nil { +// HasPortRangeEnd returns a boolean if a field has been set. +func (o *FirewallruleProperties) HasPortRangeEnd() bool { + if o != nil && o.PortRangeEnd != nil { return true } return false } -// GetTargetIp returns the TargetIp field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FirewallruleProperties) GetTargetIp() *string { +// GetPortRangeStart returns the PortRangeStart field value +// If the value is explicit nil, nil is returned +func (o *FirewallruleProperties) GetPortRangeStart() *int32 { if o == nil { return nil } - return o.TargetIp + return o.PortRangeStart } -// GetTargetIpOk returns a tuple with the TargetIp field value +// GetPortRangeStartOk returns a tuple with the PortRangeStart field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallruleProperties) GetTargetIpOk() (*string, bool) { +func (o *FirewallruleProperties) GetPortRangeStartOk() (*int32, bool) { if o == nil { return nil, false } - return o.TargetIp, true + return o.PortRangeStart, true } -// SetTargetIp sets field value -func (o *FirewallruleProperties) SetTargetIp(v string) { +// SetPortRangeStart sets field value +func (o *FirewallruleProperties) SetPortRangeStart(v int32) { - o.TargetIp = &v + o.PortRangeStart = &v } -// HasTargetIp returns a boolean if a field has been set. -func (o *FirewallruleProperties) HasTargetIp() bool { - if o != nil && o.TargetIp != nil { +// HasPortRangeStart returns a boolean if a field has been set. +func (o *FirewallruleProperties) HasPortRangeStart() bool { + if o != nil && o.PortRangeStart != nil { return true } return false } -// GetIcmpCode returns the IcmpCode field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *FirewallruleProperties) GetIcmpCode() *int32 { +// GetProtocol returns the Protocol field value +// If the value is explicit nil, nil is returned +func (o *FirewallruleProperties) GetProtocol() *string { if o == nil { return nil } - return o.IcmpCode + return o.Protocol } -// GetIcmpCodeOk returns a tuple with the IcmpCode field value +// GetProtocolOk returns a tuple with the Protocol field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallruleProperties) GetIcmpCodeOk() (*int32, bool) { +func (o *FirewallruleProperties) GetProtocolOk() (*string, bool) { if o == nil { return nil, false } - return o.IcmpCode, true + return o.Protocol, true } -// SetIcmpCode sets field value -func (o *FirewallruleProperties) SetIcmpCode(v int32) { +// SetProtocol sets field value +func (o *FirewallruleProperties) SetProtocol(v string) { - o.IcmpCode = &v + o.Protocol = &v } -// HasIcmpCode returns a boolean if a field has been set. -func (o *FirewallruleProperties) HasIcmpCode() bool { - if o != nil && o.IcmpCode != nil { +// HasProtocol returns a boolean if a field has been set. +func (o *FirewallruleProperties) HasProtocol() bool { + if o != nil && o.Protocol != nil { return true } return false } -// GetIcmpType returns the IcmpType field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *FirewallruleProperties) GetIcmpType() *int32 { +// GetSourceIp returns the SourceIp field value +// If the value is explicit nil, nil is returned +func (o *FirewallruleProperties) GetSourceIp() *string { if o == nil { return nil } - return o.IcmpType + return o.SourceIp } -// GetIcmpTypeOk returns a tuple with the IcmpType field value +// GetSourceIpOk returns a tuple with the SourceIp field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallruleProperties) GetIcmpTypeOk() (*int32, bool) { +func (o *FirewallruleProperties) GetSourceIpOk() (*string, bool) { if o == nil { return nil, false } - return o.IcmpType, true + return o.SourceIp, true } -// SetIcmpType sets field value -func (o *FirewallruleProperties) SetIcmpType(v int32) { +// SetSourceIp sets field value +func (o *FirewallruleProperties) SetSourceIp(v string) { - o.IcmpType = &v + o.SourceIp = &v } -// HasIcmpType returns a boolean if a field has been set. -func (o *FirewallruleProperties) HasIcmpType() bool { - if o != nil && o.IcmpType != nil { +// sets SourceIp to the explicit address that will be encoded as nil when marshaled +func (o *FirewallruleProperties) SetSourceIpNil() { + o.SourceIp = &Nilstring +} + +// HasSourceIp returns a boolean if a field has been set. +func (o *FirewallruleProperties) HasSourceIp() bool { + if o != nil && o.SourceIp != nil { return true } return false } -// GetPortRangeStart returns the PortRangeStart field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *FirewallruleProperties) GetPortRangeStart() *int32 { +// GetSourceMac returns the SourceMac field value +// If the value is explicit nil, nil is returned +func (o *FirewallruleProperties) GetSourceMac() *string { if o == nil { return nil } - return o.PortRangeStart + return o.SourceMac } -// GetPortRangeStartOk returns a tuple with the PortRangeStart field value +// GetSourceMacOk returns a tuple with the SourceMac field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallruleProperties) GetPortRangeStartOk() (*int32, bool) { +func (o *FirewallruleProperties) GetSourceMacOk() (*string, bool) { if o == nil { return nil, false } - return o.PortRangeStart, true + return o.SourceMac, true } -// SetPortRangeStart sets field value -func (o *FirewallruleProperties) SetPortRangeStart(v int32) { +// SetSourceMac sets field value +func (o *FirewallruleProperties) SetSourceMac(v string) { - o.PortRangeStart = &v + o.SourceMac = &v } -// HasPortRangeStart returns a boolean if a field has been set. -func (o *FirewallruleProperties) HasPortRangeStart() bool { - if o != nil && o.PortRangeStart != nil { +// sets SourceMac to the explicit address that will be encoded as nil when marshaled +func (o *FirewallruleProperties) SetSourceMacNil() { + o.SourceMac = &Nilstring +} + +// HasSourceMac returns a boolean if a field has been set. +func (o *FirewallruleProperties) HasSourceMac() bool { + if o != nil && o.SourceMac != nil { return true } return false } -// GetPortRangeEnd returns the PortRangeEnd field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *FirewallruleProperties) GetPortRangeEnd() *int32 { +// GetTargetIp returns the TargetIp field value +// If the value is explicit nil, nil is returned +func (o *FirewallruleProperties) GetTargetIp() *string { if o == nil { return nil } - return o.PortRangeEnd + return o.TargetIp } -// GetPortRangeEndOk returns a tuple with the PortRangeEnd field value +// GetTargetIpOk returns a tuple with the TargetIp field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FirewallruleProperties) GetPortRangeEndOk() (*int32, bool) { +func (o *FirewallruleProperties) GetTargetIpOk() (*string, bool) { if o == nil { return nil, false } - return o.PortRangeEnd, true + return o.TargetIp, true } -// SetPortRangeEnd sets field value -func (o *FirewallruleProperties) SetPortRangeEnd(v int32) { +// SetTargetIp sets field value +func (o *FirewallruleProperties) SetTargetIp(v string) { - o.PortRangeEnd = &v + o.TargetIp = &v } -// HasPortRangeEnd returns a boolean if a field has been set. -func (o *FirewallruleProperties) HasPortRangeEnd() bool { - if o != nil && o.PortRangeEnd != nil { +// sets TargetIp to the explicit address that will be encoded as nil when marshaled +func (o *FirewallruleProperties) SetTargetIpNil() { + o.TargetIp = &Nilstring +} + +// HasTargetIp returns a boolean if a field has been set. +func (o *FirewallruleProperties) HasTargetIp() bool { + if o != nil && o.TargetIp != nil { return true } @@ -441,7 +477,7 @@ func (o *FirewallruleProperties) HasPortRangeEnd() bool { } // GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *FirewallruleProperties) GetType() *string { if o == nil { return nil @@ -480,29 +516,61 @@ func (o *FirewallruleProperties) HasType() bool { func (o FirewallruleProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} + + if o.IcmpCode == &Nilint32 { + toSerialize["icmpCode"] = nil + } else if o.IcmpCode != nil { + toSerialize["icmpCode"] = o.IcmpCode + } + + if o.IcmpType == &Nilint32 { + toSerialize["icmpType"] = nil + } else if o.IcmpType != nil { + toSerialize["icmpType"] = o.IcmpType + } + + if o.IpVersion == &Nilstring { + toSerialize["ipVersion"] = nil + } else if o.IpVersion != nil { + toSerialize["ipVersion"] = o.IpVersion + } if o.Name != nil { toSerialize["name"] = o.Name } + + if o.PortRangeEnd != nil { + toSerialize["portRangeEnd"] = o.PortRangeEnd + } + + if o.PortRangeStart != nil { + toSerialize["portRangeStart"] = o.PortRangeStart + } + if o.Protocol != nil { toSerialize["protocol"] = o.Protocol } - toSerialize["sourceMac"] = o.SourceMac - if o.IpVersion != nil { - toSerialize["ipVersion"] = o.IpVersion + + if o.SourceIp == &Nilstring { + toSerialize["sourceIp"] = nil + } else if o.SourceIp != nil { + toSerialize["sourceIp"] = o.SourceIp } - toSerialize["sourceIp"] = o.SourceIp - toSerialize["targetIp"] = o.TargetIp - toSerialize["icmpCode"] = o.IcmpCode - toSerialize["icmpType"] = o.IcmpType - if o.PortRangeStart != nil { - toSerialize["portRangeStart"] = o.PortRangeStart + + if o.SourceMac == &Nilstring { + toSerialize["sourceMac"] = nil + } else if o.SourceMac != nil { + toSerialize["sourceMac"] = o.SourceMac } - if o.PortRangeEnd != nil { - toSerialize["portRangeEnd"] = o.PortRangeEnd + + if o.TargetIp == &Nilstring { + toSerialize["targetIp"] = nil + } else if o.TargetIp != nil { + toSerialize["targetIp"] = o.TargetIp } if o.Type != nil { toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_log.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_log.go index e8d74517f14..6e441240889 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_log.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_log.go @@ -16,14 +16,14 @@ import ( // FlowLog struct for FlowLog type FlowLog struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *FlowLogProperties `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewFlowLog instantiates a new FlowLog object @@ -46,190 +46,190 @@ func NewFlowLogWithDefaults() *FlowLog { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FlowLog) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *FlowLog) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLog) GetIdOk() (*string, bool) { +func (o *FlowLog) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *FlowLog) SetId(v string) { +// SetHref sets field value +func (o *FlowLog) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *FlowLog) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *FlowLog) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *FlowLog) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *FlowLog) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLog) GetTypeOk() (*Type, bool) { +func (o *FlowLog) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *FlowLog) SetType(v Type) { +// SetId sets field value +func (o *FlowLog) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *FlowLog) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *FlowLog) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FlowLog) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *FlowLog) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLog) GetHrefOk() (*string, bool) { +func (o *FlowLog) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *FlowLog) SetHref(v string) { +// SetMetadata sets field value +func (o *FlowLog) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *FlowLog) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *FlowLog) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *FlowLog) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *FlowLog) GetProperties() *FlowLogProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLog) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *FlowLog) GetPropertiesOk() (*FlowLogProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *FlowLog) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *FlowLog) SetProperties(v FlowLogProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *FlowLog) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *FlowLog) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for FlowLogProperties will be returned -func (o *FlowLog) GetProperties() *FlowLogProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *FlowLog) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLog) GetPropertiesOk() (*FlowLogProperties, bool) { +func (o *FlowLog) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *FlowLog) SetProperties(v FlowLogProperties) { +// SetType sets field value +func (o *FlowLog) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *FlowLog) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *FlowLog) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *FlowLog) HasProperties() bool { func (o FlowLog) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_log_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_log_properties.go index dca17c21480..0f2a3b202c5 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_log_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_log_properties.go @@ -16,27 +16,27 @@ import ( // FlowLogProperties struct for FlowLogProperties type FlowLogProperties struct { - // The resource name. - Name *string `json:"name"` // Specifies the traffic action pattern. Action *string `json:"action"` - // Specifies the traffic direction pattern. - Direction *string `json:"direction"` // The S3 bucket name of an existing IONOS Cloud S3 bucket. Bucket *string `json:"bucket"` + // Specifies the traffic direction pattern. + Direction *string `json:"direction"` + // The resource name. + Name *string `json:"name"` } // NewFlowLogProperties instantiates a new FlowLogProperties object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewFlowLogProperties(name string, action string, direction string, bucket string) *FlowLogProperties { +func NewFlowLogProperties(action string, bucket string, direction string, name string) *FlowLogProperties { this := FlowLogProperties{} - this.Name = &name this.Action = &action - this.Direction = &direction this.Bucket = &bucket + this.Direction = &direction + this.Name = &name return &this } @@ -49,76 +49,76 @@ func NewFlowLogPropertiesWithDefaults() *FlowLogProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FlowLogProperties) GetName() *string { +// GetAction returns the Action field value +// If the value is explicit nil, nil is returned +func (o *FlowLogProperties) GetAction() *string { if o == nil { return nil } - return o.Name + return o.Action } -// GetNameOk returns a tuple with the Name field value +// GetActionOk returns a tuple with the Action field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLogProperties) GetNameOk() (*string, bool) { +func (o *FlowLogProperties) GetActionOk() (*string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.Action, true } -// SetName sets field value -func (o *FlowLogProperties) SetName(v string) { +// SetAction sets field value +func (o *FlowLogProperties) SetAction(v string) { - o.Name = &v + o.Action = &v } -// HasName returns a boolean if a field has been set. -func (o *FlowLogProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasAction returns a boolean if a field has been set. +func (o *FlowLogProperties) HasAction() bool { + if o != nil && o.Action != nil { return true } return false } -// GetAction returns the Action field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FlowLogProperties) GetAction() *string { +// GetBucket returns the Bucket field value +// If the value is explicit nil, nil is returned +func (o *FlowLogProperties) GetBucket() *string { if o == nil { return nil } - return o.Action + return o.Bucket } -// GetActionOk returns a tuple with the Action field value +// GetBucketOk returns a tuple with the Bucket field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLogProperties) GetActionOk() (*string, bool) { +func (o *FlowLogProperties) GetBucketOk() (*string, bool) { if o == nil { return nil, false } - return o.Action, true + return o.Bucket, true } -// SetAction sets field value -func (o *FlowLogProperties) SetAction(v string) { +// SetBucket sets field value +func (o *FlowLogProperties) SetBucket(v string) { - o.Action = &v + o.Bucket = &v } -// HasAction returns a boolean if a field has been set. -func (o *FlowLogProperties) HasAction() bool { - if o != nil && o.Action != nil { +// HasBucket returns a boolean if a field has been set. +func (o *FlowLogProperties) HasBucket() bool { + if o != nil && o.Bucket != nil { return true } @@ -126,7 +126,7 @@ func (o *FlowLogProperties) HasAction() bool { } // GetDirection returns the Direction field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *FlowLogProperties) GetDirection() *string { if o == nil { return nil @@ -163,38 +163,38 @@ func (o *FlowLogProperties) HasDirection() bool { return false } -// GetBucket returns the Bucket field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FlowLogProperties) GetBucket() *string { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *FlowLogProperties) GetName() *string { if o == nil { return nil } - return o.Bucket + return o.Name } -// GetBucketOk returns a tuple with the Bucket field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLogProperties) GetBucketOk() (*string, bool) { +func (o *FlowLogProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.Bucket, true + return o.Name, true } -// SetBucket sets field value -func (o *FlowLogProperties) SetBucket(v string) { +// SetName sets field value +func (o *FlowLogProperties) SetName(v string) { - o.Bucket = &v + o.Name = &v } -// HasBucket returns a boolean if a field has been set. -func (o *FlowLogProperties) HasBucket() bool { - if o != nil && o.Bucket != nil { +// HasName returns a boolean if a field has been set. +func (o *FlowLogProperties) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -203,18 +203,22 @@ func (o *FlowLogProperties) HasBucket() bool { func (o FlowLogProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name - } if o.Action != nil { toSerialize["action"] = o.Action } + + if o.Bucket != nil { + toSerialize["bucket"] = o.Bucket + } + if o.Direction != nil { toSerialize["direction"] = o.Direction } - if o.Bucket != nil { - toSerialize["bucket"] = o.Bucket + + if o.Name != nil { + toSerialize["name"] = o.Name } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_log_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_log_put.go index 8f9b7f77781..7fe84d71f66 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_log_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_log_put.go @@ -16,13 +16,13 @@ import ( // FlowLogPut struct for FlowLogPut type FlowLogPut struct { + // URL to the object representation (absolute path). + Href *string `json:"href,omitempty"` // The resource's unique identifier. - Id *string `json:"id,omitempty"` + Id *string `json:"id,omitempty"` + Properties *FlowLogProperties `json:"properties"` // The type of object that has been created. Type *Type `json:"type,omitempty"` - // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` - Properties *FlowLogProperties `json:"properties"` } // NewFlowLogPut instantiates a new FlowLogPut object @@ -45,152 +45,152 @@ func NewFlowLogPutWithDefaults() *FlowLogPut { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FlowLogPut) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *FlowLogPut) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLogPut) GetIdOk() (*string, bool) { +func (o *FlowLogPut) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *FlowLogPut) SetId(v string) { +// SetHref sets field value +func (o *FlowLogPut) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *FlowLogPut) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *FlowLogPut) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *FlowLogPut) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *FlowLogPut) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLogPut) GetTypeOk() (*Type, bool) { +func (o *FlowLogPut) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *FlowLogPut) SetType(v Type) { +// SetId sets field value +func (o *FlowLogPut) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *FlowLogPut) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *FlowLogPut) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FlowLogPut) GetHref() *string { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *FlowLogPut) GetProperties() *FlowLogProperties { if o == nil { return nil } - return o.Href + return o.Properties } -// GetHrefOk returns a tuple with the Href field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLogPut) GetHrefOk() (*string, bool) { +func (o *FlowLogPut) GetPropertiesOk() (*FlowLogProperties, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Properties, true } -// SetHref sets field value -func (o *FlowLogPut) SetHref(v string) { +// SetProperties sets field value +func (o *FlowLogPut) SetProperties(v FlowLogProperties) { - o.Href = &v + o.Properties = &v } -// HasHref returns a boolean if a field has been set. -func (o *FlowLogPut) HasHref() bool { - if o != nil && o.Href != nil { +// HasProperties returns a boolean if a field has been set. +func (o *FlowLogPut) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for FlowLogProperties will be returned -func (o *FlowLogPut) GetProperties() *FlowLogProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *FlowLogPut) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLogPut) GetPropertiesOk() (*FlowLogProperties, bool) { +func (o *FlowLogPut) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *FlowLogPut) SetProperties(v FlowLogProperties) { +// SetType sets field value +func (o *FlowLogPut) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *FlowLogPut) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *FlowLogPut) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -199,18 +199,22 @@ func (o *FlowLogPut) HasProperties() bool { func (o FlowLogPut) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_logs.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_logs.go index 48f070e31ce..653d925ab21 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_logs.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_flow_logs.go @@ -16,19 +16,19 @@ import ( // FlowLogs struct for FlowLogs type FlowLogs struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // The URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]FlowLog `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewFlowLogs instantiates a new FlowLogs object @@ -49,114 +49,114 @@ func NewFlowLogsWithDefaults() *FlowLogs { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FlowLogs) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *FlowLogs) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLogs) GetIdOk() (*string, bool) { +func (o *FlowLogs) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *FlowLogs) SetId(v string) { +// SetLinks sets field value +func (o *FlowLogs) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *FlowLogs) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *FlowLogs) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *FlowLogs) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *FlowLogs) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLogs) GetTypeOk() (*Type, bool) { +func (o *FlowLogs) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *FlowLogs) SetType(v Type) { +// SetHref sets field value +func (o *FlowLogs) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *FlowLogs) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *FlowLogs) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *FlowLogs) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *FlowLogs) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLogs) GetHrefOk() (*string, bool) { +func (o *FlowLogs) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *FlowLogs) SetHref(v string) { +// SetId sets field value +func (o *FlowLogs) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *FlowLogs) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *FlowLogs) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *FlowLogs) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []FlowLog will be returned +// If the value is explicit nil, nil is returned func (o *FlowLogs) GetItems() *[]FlowLog { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *FlowLogs) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *FlowLogs) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *FlowLogs) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLogs) GetOffsetOk() (*float32, bool) { +func (o *FlowLogs) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *FlowLogs) SetOffset(v float32) { +// SetLimit sets field value +func (o *FlowLogs) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *FlowLogs) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *FlowLogs) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *FlowLogs) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *FlowLogs) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLogs) GetLimitOk() (*float32, bool) { +func (o *FlowLogs) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *FlowLogs) SetLimit(v float32) { +// SetOffset sets field value +func (o *FlowLogs) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *FlowLogs) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *FlowLogs) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *FlowLogs) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *FlowLogs) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *FlowLogs) GetLinksOk() (*PaginationLinks, bool) { +func (o *FlowLogs) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *FlowLogs) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *FlowLogs) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *FlowLogs) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *FlowLogs) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *FlowLogs) HasLinks() bool { func (o FlowLogs) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group.go index a1e9b6781a9..1509dd460de 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group.go @@ -16,14 +16,14 @@ import ( // Group struct for Group type Group struct { + Entities *GroupEntities `json:"entities,omitempty"` + // URL to the object representation (absolute path). + Href *string `json:"href,omitempty"` // The resource's unique identifier. - Id *string `json:"id,omitempty"` + Id *string `json:"id,omitempty"` + Properties *GroupProperties `json:"properties"` // The type of the resource. Type *Type `json:"type,omitempty"` - // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` - Properties *GroupProperties `json:"properties"` - Entities *GroupEntities `json:"entities,omitempty"` } // NewGroup instantiates a new Group object @@ -46,114 +46,114 @@ func NewGroupWithDefaults() *Group { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Group) GetId() *string { +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *Group) GetEntities() *GroupEntities { if o == nil { return nil } - return o.Id + return o.Entities } -// GetIdOk returns a tuple with the Id field value +// GetEntitiesOk returns a tuple with the Entities field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Group) GetIdOk() (*string, bool) { +func (o *Group) GetEntitiesOk() (*GroupEntities, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Entities, true } -// SetId sets field value -func (o *Group) SetId(v string) { +// SetEntities sets field value +func (o *Group) SetEntities(v GroupEntities) { - o.Id = &v + o.Entities = &v } -// HasId returns a boolean if a field has been set. -func (o *Group) HasId() bool { - if o != nil && o.Id != nil { +// HasEntities returns a boolean if a field has been set. +func (o *Group) HasEntities() bool { + if o != nil && o.Entities != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Group) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Group) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Group) GetTypeOk() (*Type, bool) { +func (o *Group) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Group) SetType(v Type) { +// SetHref sets field value +func (o *Group) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Group) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Group) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Group) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Group) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Group) GetHrefOk() (*string, bool) { +func (o *Group) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Group) SetHref(v string) { +// SetId sets field value +func (o *Group) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Group) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Group) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -161,7 +161,7 @@ func (o *Group) HasHref() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for GroupProperties will be returned +// If the value is explicit nil, nil is returned func (o *Group) GetProperties() *GroupProperties { if o == nil { return nil @@ -198,38 +198,38 @@ func (o *Group) HasProperties() bool { return false } -// GetEntities returns the Entities field value -// If the value is explicit nil, the zero value for GroupEntities will be returned -func (o *Group) GetEntities() *GroupEntities { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Group) GetType() *Type { if o == nil { return nil } - return o.Entities + return o.Type } -// GetEntitiesOk returns a tuple with the Entities field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Group) GetEntitiesOk() (*GroupEntities, bool) { +func (o *Group) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Entities, true + return o.Type, true } -// SetEntities sets field value -func (o *Group) SetEntities(v GroupEntities) { +// SetType sets field value +func (o *Group) SetType(v Type) { - o.Entities = &v + o.Type = &v } -// HasEntities returns a boolean if a field has been set. -func (o *Group) HasEntities() bool { - if o != nil && o.Entities != nil { +// HasType returns a boolean if a field has been set. +func (o *Group) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *Group) HasEntities() bool { func (o Group) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Entities != nil { + toSerialize["entities"] = o.Entities } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Properties != nil { toSerialize["properties"] = o.Properties } - if o.Entities != nil { - toSerialize["entities"] = o.Entities + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_entities.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_entities.go index 067e84cac6d..f9e91462267 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_entities.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_entities.go @@ -16,8 +16,8 @@ import ( // GroupEntities struct for GroupEntities type GroupEntities struct { - Users *GroupMembers `json:"users,omitempty"` Resources *ResourceGroups `json:"resources,omitempty"` + Users *GroupMembers `json:"users,omitempty"` } // NewGroupEntities instantiates a new GroupEntities object @@ -38,76 +38,76 @@ func NewGroupEntitiesWithDefaults() *GroupEntities { return &this } -// GetUsers returns the Users field value -// If the value is explicit nil, the zero value for GroupMembers will be returned -func (o *GroupEntities) GetUsers() *GroupMembers { +// GetResources returns the Resources field value +// If the value is explicit nil, nil is returned +func (o *GroupEntities) GetResources() *ResourceGroups { if o == nil { return nil } - return o.Users + return o.Resources } -// GetUsersOk returns a tuple with the Users field value +// GetResourcesOk returns a tuple with the Resources field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupEntities) GetUsersOk() (*GroupMembers, bool) { +func (o *GroupEntities) GetResourcesOk() (*ResourceGroups, bool) { if o == nil { return nil, false } - return o.Users, true + return o.Resources, true } -// SetUsers sets field value -func (o *GroupEntities) SetUsers(v GroupMembers) { +// SetResources sets field value +func (o *GroupEntities) SetResources(v ResourceGroups) { - o.Users = &v + o.Resources = &v } -// HasUsers returns a boolean if a field has been set. -func (o *GroupEntities) HasUsers() bool { - if o != nil && o.Users != nil { +// HasResources returns a boolean if a field has been set. +func (o *GroupEntities) HasResources() bool { + if o != nil && o.Resources != nil { return true } return false } -// GetResources returns the Resources field value -// If the value is explicit nil, the zero value for ResourceGroups will be returned -func (o *GroupEntities) GetResources() *ResourceGroups { +// GetUsers returns the Users field value +// If the value is explicit nil, nil is returned +func (o *GroupEntities) GetUsers() *GroupMembers { if o == nil { return nil } - return o.Resources + return o.Users } -// GetResourcesOk returns a tuple with the Resources field value +// GetUsersOk returns a tuple with the Users field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupEntities) GetResourcesOk() (*ResourceGroups, bool) { +func (o *GroupEntities) GetUsersOk() (*GroupMembers, bool) { if o == nil { return nil, false } - return o.Resources, true + return o.Users, true } -// SetResources sets field value -func (o *GroupEntities) SetResources(v ResourceGroups) { +// SetUsers sets field value +func (o *GroupEntities) SetUsers(v GroupMembers) { - o.Resources = &v + o.Users = &v } -// HasResources returns a boolean if a field has been set. -func (o *GroupEntities) HasResources() bool { - if o != nil && o.Resources != nil { +// HasUsers returns a boolean if a field has been set. +func (o *GroupEntities) HasUsers() bool { + if o != nil && o.Users != nil { return true } @@ -116,12 +116,14 @@ func (o *GroupEntities) HasResources() bool { func (o GroupEntities) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Users != nil { - toSerialize["users"] = o.Users - } if o.Resources != nil { toSerialize["resources"] = o.Resources } + + if o.Users != nil { + toSerialize["users"] = o.Users + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_members.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_members.go index c38d7c018f7..a4a750e784e 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_members.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_members.go @@ -16,14 +16,14 @@ import ( // GroupMembers struct for GroupMembers type GroupMembers struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]User `json:"items,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewGroupMembers instantiates a new GroupMembers object @@ -44,152 +44,152 @@ func NewGroupMembersWithDefaults() *GroupMembers { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *GroupMembers) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *GroupMembers) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupMembers) GetIdOk() (*string, bool) { +func (o *GroupMembers) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *GroupMembers) SetId(v string) { +// SetHref sets field value +func (o *GroupMembers) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *GroupMembers) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *GroupMembers) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *GroupMembers) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *GroupMembers) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupMembers) GetTypeOk() (*Type, bool) { +func (o *GroupMembers) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *GroupMembers) SetType(v Type) { +// SetId sets field value +func (o *GroupMembers) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *GroupMembers) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *GroupMembers) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *GroupMembers) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *GroupMembers) GetItems() *[]User { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupMembers) GetHrefOk() (*string, bool) { +func (o *GroupMembers) GetItemsOk() (*[]User, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *GroupMembers) SetHref(v string) { +// SetItems sets field value +func (o *GroupMembers) SetItems(v []User) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *GroupMembers) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *GroupMembers) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []User will be returned -func (o *GroupMembers) GetItems() *[]User { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *GroupMembers) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupMembers) GetItemsOk() (*[]User, bool) { +func (o *GroupMembers) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *GroupMembers) SetItems(v []User) { +// SetType sets field value +func (o *GroupMembers) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *GroupMembers) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *GroupMembers) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *GroupMembers) HasItems() bool { func (o GroupMembers) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_properties.go index c4c55d9b17a..d73cb668b84 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_properties.go @@ -16,40 +16,40 @@ import ( // GroupProperties struct for GroupProperties type GroupProperties struct { - // The name of the resource. - Name *string `json:"name,omitempty"` - // Create data center privilege. - CreateDataCenter *bool `json:"createDataCenter,omitempty"` - // Create snapshot privilege. - CreateSnapshot *bool `json:"createSnapshot,omitempty"` - // Reserve IP block privilege. - ReserveIp *bool `json:"reserveIp,omitempty"` // Activity log access privilege. AccessActivityLog *bool `json:"accessActivityLog,omitempty"` - // Create pcc privilege. - CreatePcc *bool `json:"createPcc,omitempty"` - // S3 privilege. - S3Privilege *bool `json:"s3Privilege,omitempty"` + // Privilege for a group to access and manage certificates. + AccessAndManageCertificates *bool `json:"accessAndManageCertificates,omitempty"` + // Privilege for a group to access and manage dns records. + AccessAndManageDns *bool `json:"accessAndManageDns,omitempty"` + // Privilege for a group to access and manage monitoring related functionality (access metrics, CRUD on alarms, alarm-actions etc) using Monotoring-as-a-Service (MaaS). + AccessAndManageMonitoring *bool `json:"accessAndManageMonitoring,omitempty"` // Create backup unit privilege. CreateBackupUnit *bool `json:"createBackupUnit,omitempty"` + // Create data center privilege. + CreateDataCenter *bool `json:"createDataCenter,omitempty"` + // Create Flow Logs privilege. + CreateFlowLog *bool `json:"createFlowLog,omitempty"` // Create internet access privilege. CreateInternetAccess *bool `json:"createInternetAccess,omitempty"` // Create Kubernetes cluster privilege. CreateK8sCluster *bool `json:"createK8sCluster,omitempty"` - // Create Flow Logs privilege. - CreateFlowLog *bool `json:"createFlowLog,omitempty"` - // Privilege for a group to access and manage monitoring related functionality (access metrics, CRUD on alarms, alarm-actions etc) using Monotoring-as-a-Service (MaaS). - AccessAndManageMonitoring *bool `json:"accessAndManageMonitoring,omitempty"` - // Privilege for a group to access and manage certificates. - AccessAndManageCertificates *bool `json:"accessAndManageCertificates,omitempty"` + // Create pcc privilege. + CreatePcc *bool `json:"createPcc,omitempty"` + // Create snapshot privilege. + CreateSnapshot *bool `json:"createSnapshot,omitempty"` // Privilege for a group to manage DBaaS related functionality. ManageDBaaS *bool `json:"manageDBaaS,omitempty"` - // Privilege for a group to access and manage dns records. - AccessAndManageDns *bool `json:"accessAndManageDns,omitempty"` + // Privilege for a group to access and manage the Data Platform. + ManageDataplatform *bool `json:"manageDataplatform,omitempty"` // Privilege for group accessing container registry related functionality. ManageRegistry *bool `json:"manageRegistry,omitempty"` - // Privilege for a group to access and manage Data Platform. - ManageDataplatform *bool `json:"manageDataplatform,omitempty"` + // The name of the resource. + Name *string `json:"name,omitempty"` + // Reserve IP block privilege. + ReserveIp *bool `json:"reserveIp,omitempty"` + // S3 privilege. + S3Privilege *bool `json:"s3Privilege,omitempty"` } // NewGroupProperties instantiates a new GroupProperties object @@ -70,304 +70,266 @@ func NewGroupPropertiesWithDefaults() *GroupProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *GroupProperties) GetName() *string { - if o == nil { - return nil - } - - return o.Name - -} - -// GetNameOk returns a tuple with the Name field value -// and a boolean to check if the value has been set. -// NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupProperties) GetNameOk() (*string, bool) { - if o == nil { - return nil, false - } - - return o.Name, true -} - -// SetName sets field value -func (o *GroupProperties) SetName(v string) { - - o.Name = &v - -} - -// HasName returns a boolean if a field has been set. -func (o *GroupProperties) HasName() bool { - if o != nil && o.Name != nil { - return true - } - - return false -} - -// GetCreateDataCenter returns the CreateDataCenter field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *GroupProperties) GetCreateDataCenter() *bool { +// GetAccessActivityLog returns the AccessActivityLog field value +// If the value is explicit nil, nil is returned +func (o *GroupProperties) GetAccessActivityLog() *bool { if o == nil { return nil } - return o.CreateDataCenter + return o.AccessActivityLog } -// GetCreateDataCenterOk returns a tuple with the CreateDataCenter field value +// GetAccessActivityLogOk returns a tuple with the AccessActivityLog field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupProperties) GetCreateDataCenterOk() (*bool, bool) { +func (o *GroupProperties) GetAccessActivityLogOk() (*bool, bool) { if o == nil { return nil, false } - return o.CreateDataCenter, true + return o.AccessActivityLog, true } -// SetCreateDataCenter sets field value -func (o *GroupProperties) SetCreateDataCenter(v bool) { +// SetAccessActivityLog sets field value +func (o *GroupProperties) SetAccessActivityLog(v bool) { - o.CreateDataCenter = &v + o.AccessActivityLog = &v } -// HasCreateDataCenter returns a boolean if a field has been set. -func (o *GroupProperties) HasCreateDataCenter() bool { - if o != nil && o.CreateDataCenter != nil { +// HasAccessActivityLog returns a boolean if a field has been set. +func (o *GroupProperties) HasAccessActivityLog() bool { + if o != nil && o.AccessActivityLog != nil { return true } return false } -// GetCreateSnapshot returns the CreateSnapshot field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *GroupProperties) GetCreateSnapshot() *bool { +// GetAccessAndManageCertificates returns the AccessAndManageCertificates field value +// If the value is explicit nil, nil is returned +func (o *GroupProperties) GetAccessAndManageCertificates() *bool { if o == nil { return nil } - return o.CreateSnapshot + return o.AccessAndManageCertificates } -// GetCreateSnapshotOk returns a tuple with the CreateSnapshot field value +// GetAccessAndManageCertificatesOk returns a tuple with the AccessAndManageCertificates field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupProperties) GetCreateSnapshotOk() (*bool, bool) { +func (o *GroupProperties) GetAccessAndManageCertificatesOk() (*bool, bool) { if o == nil { return nil, false } - return o.CreateSnapshot, true + return o.AccessAndManageCertificates, true } -// SetCreateSnapshot sets field value -func (o *GroupProperties) SetCreateSnapshot(v bool) { +// SetAccessAndManageCertificates sets field value +func (o *GroupProperties) SetAccessAndManageCertificates(v bool) { - o.CreateSnapshot = &v + o.AccessAndManageCertificates = &v } -// HasCreateSnapshot returns a boolean if a field has been set. -func (o *GroupProperties) HasCreateSnapshot() bool { - if o != nil && o.CreateSnapshot != nil { +// HasAccessAndManageCertificates returns a boolean if a field has been set. +func (o *GroupProperties) HasAccessAndManageCertificates() bool { + if o != nil && o.AccessAndManageCertificates != nil { return true } return false } -// GetReserveIp returns the ReserveIp field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *GroupProperties) GetReserveIp() *bool { +// GetAccessAndManageDns returns the AccessAndManageDns field value +// If the value is explicit nil, nil is returned +func (o *GroupProperties) GetAccessAndManageDns() *bool { if o == nil { return nil } - return o.ReserveIp + return o.AccessAndManageDns } -// GetReserveIpOk returns a tuple with the ReserveIp field value +// GetAccessAndManageDnsOk returns a tuple with the AccessAndManageDns field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupProperties) GetReserveIpOk() (*bool, bool) { +func (o *GroupProperties) GetAccessAndManageDnsOk() (*bool, bool) { if o == nil { return nil, false } - return o.ReserveIp, true + return o.AccessAndManageDns, true } -// SetReserveIp sets field value -func (o *GroupProperties) SetReserveIp(v bool) { +// SetAccessAndManageDns sets field value +func (o *GroupProperties) SetAccessAndManageDns(v bool) { - o.ReserveIp = &v + o.AccessAndManageDns = &v } -// HasReserveIp returns a boolean if a field has been set. -func (o *GroupProperties) HasReserveIp() bool { - if o != nil && o.ReserveIp != nil { +// HasAccessAndManageDns returns a boolean if a field has been set. +func (o *GroupProperties) HasAccessAndManageDns() bool { + if o != nil && o.AccessAndManageDns != nil { return true } return false } -// GetAccessActivityLog returns the AccessActivityLog field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *GroupProperties) GetAccessActivityLog() *bool { +// GetAccessAndManageMonitoring returns the AccessAndManageMonitoring field value +// If the value is explicit nil, nil is returned +func (o *GroupProperties) GetAccessAndManageMonitoring() *bool { if o == nil { return nil } - return o.AccessActivityLog + return o.AccessAndManageMonitoring } -// GetAccessActivityLogOk returns a tuple with the AccessActivityLog field value +// GetAccessAndManageMonitoringOk returns a tuple with the AccessAndManageMonitoring field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupProperties) GetAccessActivityLogOk() (*bool, bool) { +func (o *GroupProperties) GetAccessAndManageMonitoringOk() (*bool, bool) { if o == nil { return nil, false } - return o.AccessActivityLog, true + return o.AccessAndManageMonitoring, true } -// SetAccessActivityLog sets field value -func (o *GroupProperties) SetAccessActivityLog(v bool) { +// SetAccessAndManageMonitoring sets field value +func (o *GroupProperties) SetAccessAndManageMonitoring(v bool) { - o.AccessActivityLog = &v + o.AccessAndManageMonitoring = &v } -// HasAccessActivityLog returns a boolean if a field has been set. -func (o *GroupProperties) HasAccessActivityLog() bool { - if o != nil && o.AccessActivityLog != nil { +// HasAccessAndManageMonitoring returns a boolean if a field has been set. +func (o *GroupProperties) HasAccessAndManageMonitoring() bool { + if o != nil && o.AccessAndManageMonitoring != nil { return true } return false } -// GetCreatePcc returns the CreatePcc field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *GroupProperties) GetCreatePcc() *bool { +// GetCreateBackupUnit returns the CreateBackupUnit field value +// If the value is explicit nil, nil is returned +func (o *GroupProperties) GetCreateBackupUnit() *bool { if o == nil { return nil } - return o.CreatePcc + return o.CreateBackupUnit } -// GetCreatePccOk returns a tuple with the CreatePcc field value +// GetCreateBackupUnitOk returns a tuple with the CreateBackupUnit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupProperties) GetCreatePccOk() (*bool, bool) { +func (o *GroupProperties) GetCreateBackupUnitOk() (*bool, bool) { if o == nil { return nil, false } - return o.CreatePcc, true + return o.CreateBackupUnit, true } -// SetCreatePcc sets field value -func (o *GroupProperties) SetCreatePcc(v bool) { +// SetCreateBackupUnit sets field value +func (o *GroupProperties) SetCreateBackupUnit(v bool) { - o.CreatePcc = &v + o.CreateBackupUnit = &v } -// HasCreatePcc returns a boolean if a field has been set. -func (o *GroupProperties) HasCreatePcc() bool { - if o != nil && o.CreatePcc != nil { +// HasCreateBackupUnit returns a boolean if a field has been set. +func (o *GroupProperties) HasCreateBackupUnit() bool { + if o != nil && o.CreateBackupUnit != nil { return true } return false } -// GetS3Privilege returns the S3Privilege field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *GroupProperties) GetS3Privilege() *bool { +// GetCreateDataCenter returns the CreateDataCenter field value +// If the value is explicit nil, nil is returned +func (o *GroupProperties) GetCreateDataCenter() *bool { if o == nil { return nil } - return o.S3Privilege + return o.CreateDataCenter } -// GetS3PrivilegeOk returns a tuple with the S3Privilege field value +// GetCreateDataCenterOk returns a tuple with the CreateDataCenter field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupProperties) GetS3PrivilegeOk() (*bool, bool) { +func (o *GroupProperties) GetCreateDataCenterOk() (*bool, bool) { if o == nil { return nil, false } - return o.S3Privilege, true + return o.CreateDataCenter, true } -// SetS3Privilege sets field value -func (o *GroupProperties) SetS3Privilege(v bool) { +// SetCreateDataCenter sets field value +func (o *GroupProperties) SetCreateDataCenter(v bool) { - o.S3Privilege = &v + o.CreateDataCenter = &v } -// HasS3Privilege returns a boolean if a field has been set. -func (o *GroupProperties) HasS3Privilege() bool { - if o != nil && o.S3Privilege != nil { +// HasCreateDataCenter returns a boolean if a field has been set. +func (o *GroupProperties) HasCreateDataCenter() bool { + if o != nil && o.CreateDataCenter != nil { return true } return false } -// GetCreateBackupUnit returns the CreateBackupUnit field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *GroupProperties) GetCreateBackupUnit() *bool { +// GetCreateFlowLog returns the CreateFlowLog field value +// If the value is explicit nil, nil is returned +func (o *GroupProperties) GetCreateFlowLog() *bool { if o == nil { return nil } - return o.CreateBackupUnit + return o.CreateFlowLog } -// GetCreateBackupUnitOk returns a tuple with the CreateBackupUnit field value +// GetCreateFlowLogOk returns a tuple with the CreateFlowLog field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupProperties) GetCreateBackupUnitOk() (*bool, bool) { +func (o *GroupProperties) GetCreateFlowLogOk() (*bool, bool) { if o == nil { return nil, false } - return o.CreateBackupUnit, true + return o.CreateFlowLog, true } -// SetCreateBackupUnit sets field value -func (o *GroupProperties) SetCreateBackupUnit(v bool) { +// SetCreateFlowLog sets field value +func (o *GroupProperties) SetCreateFlowLog(v bool) { - o.CreateBackupUnit = &v + o.CreateFlowLog = &v } -// HasCreateBackupUnit returns a boolean if a field has been set. -func (o *GroupProperties) HasCreateBackupUnit() bool { - if o != nil && o.CreateBackupUnit != nil { +// HasCreateFlowLog returns a boolean if a field has been set. +func (o *GroupProperties) HasCreateFlowLog() bool { + if o != nil && o.CreateFlowLog != nil { return true } @@ -375,7 +337,7 @@ func (o *GroupProperties) HasCreateBackupUnit() bool { } // GetCreateInternetAccess returns the CreateInternetAccess field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *GroupProperties) GetCreateInternetAccess() *bool { if o == nil { return nil @@ -413,7 +375,7 @@ func (o *GroupProperties) HasCreateInternetAccess() bool { } // GetCreateK8sCluster returns the CreateK8sCluster field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *GroupProperties) GetCreateK8sCluster() *bool { if o == nil { return nil @@ -450,114 +412,76 @@ func (o *GroupProperties) HasCreateK8sCluster() bool { return false } -// GetCreateFlowLog returns the CreateFlowLog field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *GroupProperties) GetCreateFlowLog() *bool { +// GetCreatePcc returns the CreatePcc field value +// If the value is explicit nil, nil is returned +func (o *GroupProperties) GetCreatePcc() *bool { if o == nil { return nil } - return o.CreateFlowLog + return o.CreatePcc } -// GetCreateFlowLogOk returns a tuple with the CreateFlowLog field value +// GetCreatePccOk returns a tuple with the CreatePcc field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupProperties) GetCreateFlowLogOk() (*bool, bool) { - if o == nil { - return nil, false - } - - return o.CreateFlowLog, true -} - -// SetCreateFlowLog sets field value -func (o *GroupProperties) SetCreateFlowLog(v bool) { - - o.CreateFlowLog = &v - -} - -// HasCreateFlowLog returns a boolean if a field has been set. -func (o *GroupProperties) HasCreateFlowLog() bool { - if o != nil && o.CreateFlowLog != nil { - return true - } - - return false -} - -// GetAccessAndManageMonitoring returns the AccessAndManageMonitoring field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *GroupProperties) GetAccessAndManageMonitoring() *bool { - if o == nil { - return nil - } - - return o.AccessAndManageMonitoring - -} - -// GetAccessAndManageMonitoringOk returns a tuple with the AccessAndManageMonitoring field value -// and a boolean to check if the value has been set. -// NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupProperties) GetAccessAndManageMonitoringOk() (*bool, bool) { +func (o *GroupProperties) GetCreatePccOk() (*bool, bool) { if o == nil { return nil, false } - return o.AccessAndManageMonitoring, true + return o.CreatePcc, true } -// SetAccessAndManageMonitoring sets field value -func (o *GroupProperties) SetAccessAndManageMonitoring(v bool) { +// SetCreatePcc sets field value +func (o *GroupProperties) SetCreatePcc(v bool) { - o.AccessAndManageMonitoring = &v + o.CreatePcc = &v } -// HasAccessAndManageMonitoring returns a boolean if a field has been set. -func (o *GroupProperties) HasAccessAndManageMonitoring() bool { - if o != nil && o.AccessAndManageMonitoring != nil { +// HasCreatePcc returns a boolean if a field has been set. +func (o *GroupProperties) HasCreatePcc() bool { + if o != nil && o.CreatePcc != nil { return true } return false } -// GetAccessAndManageCertificates returns the AccessAndManageCertificates field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *GroupProperties) GetAccessAndManageCertificates() *bool { +// GetCreateSnapshot returns the CreateSnapshot field value +// If the value is explicit nil, nil is returned +func (o *GroupProperties) GetCreateSnapshot() *bool { if o == nil { return nil } - return o.AccessAndManageCertificates + return o.CreateSnapshot } -// GetAccessAndManageCertificatesOk returns a tuple with the AccessAndManageCertificates field value +// GetCreateSnapshotOk returns a tuple with the CreateSnapshot field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupProperties) GetAccessAndManageCertificatesOk() (*bool, bool) { +func (o *GroupProperties) GetCreateSnapshotOk() (*bool, bool) { if o == nil { return nil, false } - return o.AccessAndManageCertificates, true + return o.CreateSnapshot, true } -// SetAccessAndManageCertificates sets field value -func (o *GroupProperties) SetAccessAndManageCertificates(v bool) { +// SetCreateSnapshot sets field value +func (o *GroupProperties) SetCreateSnapshot(v bool) { - o.AccessAndManageCertificates = &v + o.CreateSnapshot = &v } -// HasAccessAndManageCertificates returns a boolean if a field has been set. -func (o *GroupProperties) HasAccessAndManageCertificates() bool { - if o != nil && o.AccessAndManageCertificates != nil { +// HasCreateSnapshot returns a boolean if a field has been set. +func (o *GroupProperties) HasCreateSnapshot() bool { + if o != nil && o.CreateSnapshot != nil { return true } @@ -565,7 +489,7 @@ func (o *GroupProperties) HasAccessAndManageCertificates() bool { } // GetManageDBaaS returns the ManageDBaaS field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *GroupProperties) GetManageDBaaS() *bool { if o == nil { return nil @@ -602,38 +526,38 @@ func (o *GroupProperties) HasManageDBaaS() bool { return false } -// GetAccessAndManageDns returns the AccessAndManageDns field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *GroupProperties) GetAccessAndManageDns() *bool { +// GetManageDataplatform returns the ManageDataplatform field value +// If the value is explicit nil, nil is returned +func (o *GroupProperties) GetManageDataplatform() *bool { if o == nil { return nil } - return o.AccessAndManageDns + return o.ManageDataplatform } -// GetAccessAndManageDnsOk returns a tuple with the AccessAndManageDns field value +// GetManageDataplatformOk returns a tuple with the ManageDataplatform field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupProperties) GetAccessAndManageDnsOk() (*bool, bool) { +func (o *GroupProperties) GetManageDataplatformOk() (*bool, bool) { if o == nil { return nil, false } - return o.AccessAndManageDns, true + return o.ManageDataplatform, true } -// SetAccessAndManageDns sets field value -func (o *GroupProperties) SetAccessAndManageDns(v bool) { +// SetManageDataplatform sets field value +func (o *GroupProperties) SetManageDataplatform(v bool) { - o.AccessAndManageDns = &v + o.ManageDataplatform = &v } -// HasAccessAndManageDns returns a boolean if a field has been set. -func (o *GroupProperties) HasAccessAndManageDns() bool { - if o != nil && o.AccessAndManageDns != nil { +// HasManageDataplatform returns a boolean if a field has been set. +func (o *GroupProperties) HasManageDataplatform() bool { + if o != nil && o.ManageDataplatform != nil { return true } @@ -641,7 +565,7 @@ func (o *GroupProperties) HasAccessAndManageDns() bool { } // GetManageRegistry returns the ManageRegistry field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *GroupProperties) GetManageRegistry() *bool { if o == nil { return nil @@ -678,97 +602,190 @@ func (o *GroupProperties) HasManageRegistry() bool { return false } -// GetManageDataplatform returns the ManageDataplatform field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *GroupProperties) GetManageDataplatform() *bool { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *GroupProperties) GetName() *string { if o == nil { return nil } - return o.ManageDataplatform + return o.Name } -// GetManageDataplatformOk returns a tuple with the ManageDataplatform field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupProperties) GetManageDataplatformOk() (*bool, bool) { +func (o *GroupProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.ManageDataplatform, true + return o.Name, true } -// SetManageDataplatform sets field value -func (o *GroupProperties) SetManageDataplatform(v bool) { +// SetName sets field value +func (o *GroupProperties) SetName(v string) { - o.ManageDataplatform = &v + o.Name = &v } -// HasManageDataplatform returns a boolean if a field has been set. -func (o *GroupProperties) HasManageDataplatform() bool { - if o != nil && o.ManageDataplatform != nil { +// HasName returns a boolean if a field has been set. +func (o *GroupProperties) HasName() bool { + if o != nil && o.Name != nil { return true } return false } -func (o GroupProperties) MarshalJSON() ([]byte, error) { - toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name +// GetReserveIp returns the ReserveIp field value +// If the value is explicit nil, nil is returned +func (o *GroupProperties) GetReserveIp() *bool { + if o == nil { + return nil } - if o.CreateDataCenter != nil { - toSerialize["createDataCenter"] = o.CreateDataCenter + + return o.ReserveIp + +} + +// GetReserveIpOk returns a tuple with the ReserveIp field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *GroupProperties) GetReserveIpOk() (*bool, bool) { + if o == nil { + return nil, false } - if o.CreateSnapshot != nil { - toSerialize["createSnapshot"] = o.CreateSnapshot + + return o.ReserveIp, true +} + +// SetReserveIp sets field value +func (o *GroupProperties) SetReserveIp(v bool) { + + o.ReserveIp = &v + +} + +// HasReserveIp returns a boolean if a field has been set. +func (o *GroupProperties) HasReserveIp() bool { + if o != nil && o.ReserveIp != nil { + return true } - if o.ReserveIp != nil { - toSerialize["reserveIp"] = o.ReserveIp + + return false +} + +// GetS3Privilege returns the S3Privilege field value +// If the value is explicit nil, nil is returned +func (o *GroupProperties) GetS3Privilege() *bool { + if o == nil { + return nil + } + + return o.S3Privilege + +} + +// GetS3PrivilegeOk returns a tuple with the S3Privilege field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *GroupProperties) GetS3PrivilegeOk() (*bool, bool) { + if o == nil { + return nil, false + } + + return o.S3Privilege, true +} + +// SetS3Privilege sets field value +func (o *GroupProperties) SetS3Privilege(v bool) { + + o.S3Privilege = &v + +} + +// HasS3Privilege returns a boolean if a field has been set. +func (o *GroupProperties) HasS3Privilege() bool { + if o != nil && o.S3Privilege != nil { + return true } + + return false +} + +func (o GroupProperties) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} if o.AccessActivityLog != nil { toSerialize["accessActivityLog"] = o.AccessActivityLog } - if o.CreatePcc != nil { - toSerialize["createPcc"] = o.CreatePcc + + if o.AccessAndManageCertificates != nil { + toSerialize["accessAndManageCertificates"] = o.AccessAndManageCertificates } - if o.S3Privilege != nil { - toSerialize["s3Privilege"] = o.S3Privilege + + if o.AccessAndManageDns != nil { + toSerialize["accessAndManageDns"] = o.AccessAndManageDns } + + if o.AccessAndManageMonitoring != nil { + toSerialize["accessAndManageMonitoring"] = o.AccessAndManageMonitoring + } + if o.CreateBackupUnit != nil { toSerialize["createBackupUnit"] = o.CreateBackupUnit } + + if o.CreateDataCenter != nil { + toSerialize["createDataCenter"] = o.CreateDataCenter + } + + if o.CreateFlowLog != nil { + toSerialize["createFlowLog"] = o.CreateFlowLog + } + if o.CreateInternetAccess != nil { toSerialize["createInternetAccess"] = o.CreateInternetAccess } + if o.CreateK8sCluster != nil { toSerialize["createK8sCluster"] = o.CreateK8sCluster } - if o.CreateFlowLog != nil { - toSerialize["createFlowLog"] = o.CreateFlowLog - } - if o.AccessAndManageMonitoring != nil { - toSerialize["accessAndManageMonitoring"] = o.AccessAndManageMonitoring + + if o.CreatePcc != nil { + toSerialize["createPcc"] = o.CreatePcc } - if o.AccessAndManageCertificates != nil { - toSerialize["accessAndManageCertificates"] = o.AccessAndManageCertificates + + if o.CreateSnapshot != nil { + toSerialize["createSnapshot"] = o.CreateSnapshot } + if o.ManageDBaaS != nil { toSerialize["manageDBaaS"] = o.ManageDBaaS } - if o.AccessAndManageDns != nil { - toSerialize["accessAndManageDns"] = o.AccessAndManageDns + + if o.ManageDataplatform != nil { + toSerialize["manageDataplatform"] = o.ManageDataplatform } + if o.ManageRegistry != nil { toSerialize["manageRegistry"] = o.ManageRegistry } - if o.ManageDataplatform != nil { - toSerialize["manageDataplatform"] = o.ManageDataplatform + + if o.Name != nil { + toSerialize["name"] = o.Name + } + + if o.ReserveIp != nil { + toSerialize["reserveIp"] = o.ReserveIp + } + + if o.S3Privilege != nil { + toSerialize["s3Privilege"] = o.S3Privilege } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_share.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_share.go index a25a874a379..ae84478aa82 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_share.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_share.go @@ -16,13 +16,13 @@ import ( // GroupShare struct for GroupShare type GroupShare struct { + // URL to the object representation (absolute path). + Href *string `json:"href,omitempty"` // The resource's unique identifier. - Id *string `json:"id,omitempty"` + Id *string `json:"id,omitempty"` + Properties *GroupShareProperties `json:"properties"` // resource as generic type Type *Type `json:"type,omitempty"` - // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` - Properties *GroupShareProperties `json:"properties"` } // NewGroupShare instantiates a new GroupShare object @@ -45,152 +45,152 @@ func NewGroupShareWithDefaults() *GroupShare { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *GroupShare) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *GroupShare) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupShare) GetIdOk() (*string, bool) { +func (o *GroupShare) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *GroupShare) SetId(v string) { +// SetHref sets field value +func (o *GroupShare) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *GroupShare) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *GroupShare) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *GroupShare) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *GroupShare) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupShare) GetTypeOk() (*Type, bool) { +func (o *GroupShare) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *GroupShare) SetType(v Type) { +// SetId sets field value +func (o *GroupShare) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *GroupShare) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *GroupShare) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *GroupShare) GetHref() *string { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *GroupShare) GetProperties() *GroupShareProperties { if o == nil { return nil } - return o.Href + return o.Properties } -// GetHrefOk returns a tuple with the Href field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupShare) GetHrefOk() (*string, bool) { +func (o *GroupShare) GetPropertiesOk() (*GroupShareProperties, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Properties, true } -// SetHref sets field value -func (o *GroupShare) SetHref(v string) { +// SetProperties sets field value +func (o *GroupShare) SetProperties(v GroupShareProperties) { - o.Href = &v + o.Properties = &v } -// HasHref returns a boolean if a field has been set. -func (o *GroupShare) HasHref() bool { - if o != nil && o.Href != nil { +// HasProperties returns a boolean if a field has been set. +func (o *GroupShare) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for GroupShareProperties will be returned -func (o *GroupShare) GetProperties() *GroupShareProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *GroupShare) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupShare) GetPropertiesOk() (*GroupShareProperties, bool) { +func (o *GroupShare) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *GroupShare) SetProperties(v GroupShareProperties) { +// SetType sets field value +func (o *GroupShare) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *GroupShare) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *GroupShare) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -199,18 +199,22 @@ func (o *GroupShare) HasProperties() bool { func (o GroupShare) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_share_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_share_properties.go index 5e356c127b1..1ca06267f7c 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_share_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_share_properties.go @@ -41,7 +41,7 @@ func NewGroupSharePropertiesWithDefaults() *GroupShareProperties { } // GetEditPrivilege returns the EditPrivilege field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *GroupShareProperties) GetEditPrivilege() *bool { if o == nil { return nil @@ -79,7 +79,7 @@ func (o *GroupShareProperties) HasEditPrivilege() bool { } // GetSharePrivilege returns the SharePrivilege field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *GroupShareProperties) GetSharePrivilege() *bool { if o == nil { return nil @@ -121,9 +121,11 @@ func (o GroupShareProperties) MarshalJSON() ([]byte, error) { if o.EditPrivilege != nil { toSerialize["editPrivilege"] = o.EditPrivilege } + if o.SharePrivilege != nil { toSerialize["sharePrivilege"] = o.SharePrivilege } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_shares.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_shares.go index 6735473c872..091da39c5f2 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_shares.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_shares.go @@ -16,14 +16,14 @@ import ( // GroupShares struct for GroupShares type GroupShares struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // Share representing groups and resource relationship - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]GroupShare `json:"items,omitempty"` + // Share representing groups and resource relationship + Type *Type `json:"type,omitempty"` } // NewGroupShares instantiates a new GroupShares object @@ -44,152 +44,152 @@ func NewGroupSharesWithDefaults() *GroupShares { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *GroupShares) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *GroupShares) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupShares) GetIdOk() (*string, bool) { +func (o *GroupShares) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *GroupShares) SetId(v string) { +// SetHref sets field value +func (o *GroupShares) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *GroupShares) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *GroupShares) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *GroupShares) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *GroupShares) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupShares) GetTypeOk() (*Type, bool) { +func (o *GroupShares) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *GroupShares) SetType(v Type) { +// SetId sets field value +func (o *GroupShares) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *GroupShares) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *GroupShares) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *GroupShares) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *GroupShares) GetItems() *[]GroupShare { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupShares) GetHrefOk() (*string, bool) { +func (o *GroupShares) GetItemsOk() (*[]GroupShare, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *GroupShares) SetHref(v string) { +// SetItems sets field value +func (o *GroupShares) SetItems(v []GroupShare) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *GroupShares) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *GroupShares) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []GroupShare will be returned -func (o *GroupShares) GetItems() *[]GroupShare { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *GroupShares) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupShares) GetItemsOk() (*[]GroupShare, bool) { +func (o *GroupShares) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *GroupShares) SetItems(v []GroupShare) { +// SetType sets field value +func (o *GroupShares) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *GroupShares) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *GroupShares) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *GroupShares) HasItems() bool { func (o GroupShares) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_users.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_users.go index a2fb51bc2bb..4a4f075c1ea 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_users.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_group_users.go @@ -16,14 +16,14 @@ import ( // GroupUsers Collection of the groups the user is a member of. type GroupUsers struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of the resource. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Group `json:"items,omitempty"` + // The type of the resource. + Type *Type `json:"type,omitempty"` } // NewGroupUsers instantiates a new GroupUsers object @@ -44,152 +44,152 @@ func NewGroupUsersWithDefaults() *GroupUsers { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *GroupUsers) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *GroupUsers) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupUsers) GetIdOk() (*string, bool) { +func (o *GroupUsers) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *GroupUsers) SetId(v string) { +// SetHref sets field value +func (o *GroupUsers) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *GroupUsers) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *GroupUsers) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *GroupUsers) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *GroupUsers) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupUsers) GetTypeOk() (*Type, bool) { +func (o *GroupUsers) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *GroupUsers) SetType(v Type) { +// SetId sets field value +func (o *GroupUsers) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *GroupUsers) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *GroupUsers) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *GroupUsers) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *GroupUsers) GetItems() *[]Group { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupUsers) GetHrefOk() (*string, bool) { +func (o *GroupUsers) GetItemsOk() (*[]Group, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *GroupUsers) SetHref(v string) { +// SetItems sets field value +func (o *GroupUsers) SetItems(v []Group) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *GroupUsers) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *GroupUsers) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Group will be returned -func (o *GroupUsers) GetItems() *[]Group { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *GroupUsers) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *GroupUsers) GetItemsOk() (*[]Group, bool) { +func (o *GroupUsers) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *GroupUsers) SetItems(v []Group) { +// SetType sets field value +func (o *GroupUsers) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *GroupUsers) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *GroupUsers) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *GroupUsers) HasItems() bool { func (o GroupUsers) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_groups.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_groups.go index 85df0a37de4..578d27c1c90 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_groups.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_groups.go @@ -16,14 +16,14 @@ import ( // Groups struct for Groups type Groups struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of the resource. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Group `json:"items,omitempty"` + // The type of the resource. + Type *Type `json:"type,omitempty"` } // NewGroups instantiates a new Groups object @@ -44,152 +44,152 @@ func NewGroupsWithDefaults() *Groups { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Groups) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Groups) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Groups) GetIdOk() (*string, bool) { +func (o *Groups) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Groups) SetId(v string) { +// SetHref sets field value +func (o *Groups) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Groups) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Groups) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Groups) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Groups) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Groups) GetTypeOk() (*Type, bool) { +func (o *Groups) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Groups) SetType(v Type) { +// SetId sets field value +func (o *Groups) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Groups) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Groups) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Groups) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *Groups) GetItems() *[]Group { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Groups) GetHrefOk() (*string, bool) { +func (o *Groups) GetItemsOk() (*[]Group, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *Groups) SetHref(v string) { +// SetItems sets field value +func (o *Groups) SetItems(v []Group) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *Groups) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *Groups) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Group will be returned -func (o *Groups) GetItems() *[]Group { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Groups) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Groups) GetItemsOk() (*[]Group, bool) { +func (o *Groups) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *Groups) SetItems(v []Group) { +// SetType sets field value +func (o *Groups) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *Groups) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *Groups) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *Groups) HasItems() bool { func (o Groups) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_image.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_image.go index 747a0e9493c..962c8e2e85c 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_image.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_image.go @@ -16,14 +16,14 @@ import ( // Image struct for Image type Image struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *ImageProperties `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewImage instantiates a new Image object @@ -46,190 +46,190 @@ func NewImageWithDefaults() *Image { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Image) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Image) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Image) GetIdOk() (*string, bool) { +func (o *Image) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Image) SetId(v string) { +// SetHref sets field value +func (o *Image) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Image) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Image) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Image) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Image) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Image) GetTypeOk() (*Type, bool) { +func (o *Image) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Image) SetType(v Type) { +// SetId sets field value +func (o *Image) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Image) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Image) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Image) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *Image) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Image) GetHrefOk() (*string, bool) { +func (o *Image) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *Image) SetHref(v string) { +// SetMetadata sets field value +func (o *Image) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *Image) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *Image) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *Image) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *Image) GetProperties() *ImageProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Image) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *Image) GetPropertiesOk() (*ImageProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *Image) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *Image) SetProperties(v ImageProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *Image) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *Image) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for ImageProperties will be returned -func (o *Image) GetProperties() *ImageProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Image) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Image) GetPropertiesOk() (*ImageProperties, bool) { +func (o *Image) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *Image) SetProperties(v ImageProperties) { +// SetType sets field value +func (o *Image) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *Image) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *Image) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *Image) HasProperties() bool { func (o Image) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_image_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_image_properties.go index 2ab0f5a65ce..f6059779e40 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_image_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_image_properties.go @@ -16,44 +16,44 @@ import ( // ImageProperties struct for ImageProperties type ImageProperties struct { - // The resource name. - Name *string `json:"name,omitempty"` - // Human-readable description. - Description *string `json:"description,omitempty"` - // The location of this image/snapshot. - Location *string `json:"location,omitempty"` - // The image size in GB. - Size *float32 `json:"size,omitempty"` + // Cloud init compatibility. + CloudInit *string `json:"cloudInit,omitempty"` // Hot-plug capable CPU (no reboot required). CpuHotPlug *bool `json:"cpuHotPlug,omitempty"` // Hot-unplug capable CPU (no reboot required). CpuHotUnplug *bool `json:"cpuHotUnplug,omitempty"` - // Hot-plug capable RAM (no reboot required). - RamHotPlug *bool `json:"ramHotPlug,omitempty"` - // Hot-unplug capable RAM (no reboot required). - RamHotUnplug *bool `json:"ramHotUnplug,omitempty"` - // Hot-plug capable NIC (no reboot required). - NicHotPlug *bool `json:"nicHotPlug,omitempty"` - // Hot-unplug capable NIC (no reboot required). - NicHotUnplug *bool `json:"nicHotUnplug,omitempty"` - // Hot-plug capable Virt-IO drive (no reboot required). - DiscVirtioHotPlug *bool `json:"discVirtioHotPlug,omitempty"` - // Hot-unplug capable Virt-IO drive (no reboot required). Not supported with Windows VMs. - DiscVirtioHotUnplug *bool `json:"discVirtioHotUnplug,omitempty"` + // Human-readable description. + Description *string `json:"description,omitempty"` // Hot-plug capable SCSI drive (no reboot required). DiscScsiHotPlug *bool `json:"discScsiHotPlug,omitempty"` // Hot-unplug capable SCSI drive (no reboot required). Not supported with Windows VMs. DiscScsiHotUnplug *bool `json:"discScsiHotUnplug,omitempty"` - // The OS type of this image. - LicenceType *string `json:"licenceType"` + // Hot-plug capable Virt-IO drive (no reboot required). + DiscVirtioHotPlug *bool `json:"discVirtioHotPlug,omitempty"` + // Hot-unplug capable Virt-IO drive (no reboot required). Not supported with Windows VMs. + DiscVirtioHotUnplug *bool `json:"discVirtioHotUnplug,omitempty"` + // List of image aliases mapped for this image + ImageAliases *[]string `json:"imageAliases,omitempty"` // The image type. ImageType *string `json:"imageType,omitempty"` + // The OS type of this image. + LicenceType *string `json:"licenceType"` + // The location of this image/snapshot. + Location *string `json:"location,omitempty"` + // The resource name. + Name *string `json:"name,omitempty"` + // Hot-plug capable NIC (no reboot required). + NicHotPlug *bool `json:"nicHotPlug,omitempty"` + // Hot-unplug capable NIC (no reboot required). + NicHotUnplug *bool `json:"nicHotUnplug,omitempty"` // Indicates whether the image is part of a public repository. Public *bool `json:"public,omitempty"` - // List of image aliases mapped for this image - ImageAliases *[]string `json:"imageAliases,omitempty"` - // Cloud init compatibility. - CloudInit *string `json:"cloudInit,omitempty"` + // Hot-plug capable RAM (no reboot required). + RamHotPlug *bool `json:"ramHotPlug,omitempty"` + // Hot-unplug capable RAM (no reboot required). + RamHotUnplug *bool `json:"ramHotUnplug,omitempty"` + // The image size in GB. + Size *float32 `json:"size,omitempty"` } // NewImageProperties instantiates a new ImageProperties object @@ -76,722 +76,722 @@ func NewImagePropertiesWithDefaults() *ImageProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ImageProperties) GetName() *string { +// GetCloudInit returns the CloudInit field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetCloudInit() *string { if o == nil { return nil } - return o.Name + return o.CloudInit } -// GetNameOk returns a tuple with the Name field value +// GetCloudInitOk returns a tuple with the CloudInit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetNameOk() (*string, bool) { +func (o *ImageProperties) GetCloudInitOk() (*string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.CloudInit, true } -// SetName sets field value -func (o *ImageProperties) SetName(v string) { +// SetCloudInit sets field value +func (o *ImageProperties) SetCloudInit(v string) { - o.Name = &v + o.CloudInit = &v } -// HasName returns a boolean if a field has been set. -func (o *ImageProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasCloudInit returns a boolean if a field has been set. +func (o *ImageProperties) HasCloudInit() bool { + if o != nil && o.CloudInit != nil { return true } return false } -// GetDescription returns the Description field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ImageProperties) GetDescription() *string { +// GetCpuHotPlug returns the CpuHotPlug field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetCpuHotPlug() *bool { if o == nil { return nil } - return o.Description + return o.CpuHotPlug } -// GetDescriptionOk returns a tuple with the Description field value +// GetCpuHotPlugOk returns a tuple with the CpuHotPlug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetDescriptionOk() (*string, bool) { +func (o *ImageProperties) GetCpuHotPlugOk() (*bool, bool) { if o == nil { return nil, false } - return o.Description, true + return o.CpuHotPlug, true } -// SetDescription sets field value -func (o *ImageProperties) SetDescription(v string) { +// SetCpuHotPlug sets field value +func (o *ImageProperties) SetCpuHotPlug(v bool) { - o.Description = &v + o.CpuHotPlug = &v } -// HasDescription returns a boolean if a field has been set. -func (o *ImageProperties) HasDescription() bool { - if o != nil && o.Description != nil { +// HasCpuHotPlug returns a boolean if a field has been set. +func (o *ImageProperties) HasCpuHotPlug() bool { + if o != nil && o.CpuHotPlug != nil { return true } return false } -// GetLocation returns the Location field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ImageProperties) GetLocation() *string { +// GetCpuHotUnplug returns the CpuHotUnplug field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetCpuHotUnplug() *bool { if o == nil { return nil } - return o.Location + return o.CpuHotUnplug } -// GetLocationOk returns a tuple with the Location field value +// GetCpuHotUnplugOk returns a tuple with the CpuHotUnplug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetLocationOk() (*string, bool) { +func (o *ImageProperties) GetCpuHotUnplugOk() (*bool, bool) { if o == nil { return nil, false } - return o.Location, true + return o.CpuHotUnplug, true } -// SetLocation sets field value -func (o *ImageProperties) SetLocation(v string) { +// SetCpuHotUnplug sets field value +func (o *ImageProperties) SetCpuHotUnplug(v bool) { - o.Location = &v + o.CpuHotUnplug = &v } -// HasLocation returns a boolean if a field has been set. -func (o *ImageProperties) HasLocation() bool { - if o != nil && o.Location != nil { +// HasCpuHotUnplug returns a boolean if a field has been set. +func (o *ImageProperties) HasCpuHotUnplug() bool { + if o != nil && o.CpuHotUnplug != nil { return true } return false } -// GetSize returns the Size field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *ImageProperties) GetSize() *float32 { +// GetDescription returns the Description field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetDescription() *string { if o == nil { return nil } - return o.Size + return o.Description } -// GetSizeOk returns a tuple with the Size field value +// GetDescriptionOk returns a tuple with the Description field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetSizeOk() (*float32, bool) { +func (o *ImageProperties) GetDescriptionOk() (*string, bool) { if o == nil { return nil, false } - return o.Size, true + return o.Description, true } -// SetSize sets field value -func (o *ImageProperties) SetSize(v float32) { +// SetDescription sets field value +func (o *ImageProperties) SetDescription(v string) { - o.Size = &v + o.Description = &v } -// HasSize returns a boolean if a field has been set. -func (o *ImageProperties) HasSize() bool { - if o != nil && o.Size != nil { +// HasDescription returns a boolean if a field has been set. +func (o *ImageProperties) HasDescription() bool { + if o != nil && o.Description != nil { return true } return false } -// GetCpuHotPlug returns the CpuHotPlug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *ImageProperties) GetCpuHotPlug() *bool { +// GetDiscScsiHotPlug returns the DiscScsiHotPlug field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetDiscScsiHotPlug() *bool { if o == nil { return nil } - return o.CpuHotPlug + return o.DiscScsiHotPlug } -// GetCpuHotPlugOk returns a tuple with the CpuHotPlug field value +// GetDiscScsiHotPlugOk returns a tuple with the DiscScsiHotPlug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetCpuHotPlugOk() (*bool, bool) { +func (o *ImageProperties) GetDiscScsiHotPlugOk() (*bool, bool) { if o == nil { return nil, false } - return o.CpuHotPlug, true + return o.DiscScsiHotPlug, true } -// SetCpuHotPlug sets field value -func (o *ImageProperties) SetCpuHotPlug(v bool) { +// SetDiscScsiHotPlug sets field value +func (o *ImageProperties) SetDiscScsiHotPlug(v bool) { - o.CpuHotPlug = &v + o.DiscScsiHotPlug = &v } -// HasCpuHotPlug returns a boolean if a field has been set. -func (o *ImageProperties) HasCpuHotPlug() bool { - if o != nil && o.CpuHotPlug != nil { +// HasDiscScsiHotPlug returns a boolean if a field has been set. +func (o *ImageProperties) HasDiscScsiHotPlug() bool { + if o != nil && o.DiscScsiHotPlug != nil { return true } return false } -// GetCpuHotUnplug returns the CpuHotUnplug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *ImageProperties) GetCpuHotUnplug() *bool { +// GetDiscScsiHotUnplug returns the DiscScsiHotUnplug field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetDiscScsiHotUnplug() *bool { if o == nil { return nil } - return o.CpuHotUnplug + return o.DiscScsiHotUnplug } -// GetCpuHotUnplugOk returns a tuple with the CpuHotUnplug field value +// GetDiscScsiHotUnplugOk returns a tuple with the DiscScsiHotUnplug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetCpuHotUnplugOk() (*bool, bool) { +func (o *ImageProperties) GetDiscScsiHotUnplugOk() (*bool, bool) { if o == nil { return nil, false } - return o.CpuHotUnplug, true + return o.DiscScsiHotUnplug, true } -// SetCpuHotUnplug sets field value -func (o *ImageProperties) SetCpuHotUnplug(v bool) { +// SetDiscScsiHotUnplug sets field value +func (o *ImageProperties) SetDiscScsiHotUnplug(v bool) { - o.CpuHotUnplug = &v + o.DiscScsiHotUnplug = &v } -// HasCpuHotUnplug returns a boolean if a field has been set. -func (o *ImageProperties) HasCpuHotUnplug() bool { - if o != nil && o.CpuHotUnplug != nil { +// HasDiscScsiHotUnplug returns a boolean if a field has been set. +func (o *ImageProperties) HasDiscScsiHotUnplug() bool { + if o != nil && o.DiscScsiHotUnplug != nil { return true } return false } -// GetRamHotPlug returns the RamHotPlug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *ImageProperties) GetRamHotPlug() *bool { +// GetDiscVirtioHotPlug returns the DiscVirtioHotPlug field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetDiscVirtioHotPlug() *bool { if o == nil { return nil } - return o.RamHotPlug + return o.DiscVirtioHotPlug } -// GetRamHotPlugOk returns a tuple with the RamHotPlug field value +// GetDiscVirtioHotPlugOk returns a tuple with the DiscVirtioHotPlug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetRamHotPlugOk() (*bool, bool) { +func (o *ImageProperties) GetDiscVirtioHotPlugOk() (*bool, bool) { if o == nil { return nil, false } - return o.RamHotPlug, true + return o.DiscVirtioHotPlug, true } -// SetRamHotPlug sets field value -func (o *ImageProperties) SetRamHotPlug(v bool) { +// SetDiscVirtioHotPlug sets field value +func (o *ImageProperties) SetDiscVirtioHotPlug(v bool) { - o.RamHotPlug = &v + o.DiscVirtioHotPlug = &v } -// HasRamHotPlug returns a boolean if a field has been set. -func (o *ImageProperties) HasRamHotPlug() bool { - if o != nil && o.RamHotPlug != nil { +// HasDiscVirtioHotPlug returns a boolean if a field has been set. +func (o *ImageProperties) HasDiscVirtioHotPlug() bool { + if o != nil && o.DiscVirtioHotPlug != nil { return true } return false } -// GetRamHotUnplug returns the RamHotUnplug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *ImageProperties) GetRamHotUnplug() *bool { +// GetDiscVirtioHotUnplug returns the DiscVirtioHotUnplug field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetDiscVirtioHotUnplug() *bool { if o == nil { return nil } - return o.RamHotUnplug + return o.DiscVirtioHotUnplug } -// GetRamHotUnplugOk returns a tuple with the RamHotUnplug field value +// GetDiscVirtioHotUnplugOk returns a tuple with the DiscVirtioHotUnplug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetRamHotUnplugOk() (*bool, bool) { +func (o *ImageProperties) GetDiscVirtioHotUnplugOk() (*bool, bool) { if o == nil { return nil, false } - return o.RamHotUnplug, true + return o.DiscVirtioHotUnplug, true } -// SetRamHotUnplug sets field value -func (o *ImageProperties) SetRamHotUnplug(v bool) { +// SetDiscVirtioHotUnplug sets field value +func (o *ImageProperties) SetDiscVirtioHotUnplug(v bool) { - o.RamHotUnplug = &v + o.DiscVirtioHotUnplug = &v } -// HasRamHotUnplug returns a boolean if a field has been set. -func (o *ImageProperties) HasRamHotUnplug() bool { - if o != nil && o.RamHotUnplug != nil { +// HasDiscVirtioHotUnplug returns a boolean if a field has been set. +func (o *ImageProperties) HasDiscVirtioHotUnplug() bool { + if o != nil && o.DiscVirtioHotUnplug != nil { return true } return false } -// GetNicHotPlug returns the NicHotPlug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *ImageProperties) GetNicHotPlug() *bool { +// GetImageAliases returns the ImageAliases field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetImageAliases() *[]string { if o == nil { return nil } - return o.NicHotPlug + return o.ImageAliases } -// GetNicHotPlugOk returns a tuple with the NicHotPlug field value +// GetImageAliasesOk returns a tuple with the ImageAliases field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetNicHotPlugOk() (*bool, bool) { +func (o *ImageProperties) GetImageAliasesOk() (*[]string, bool) { if o == nil { return nil, false } - return o.NicHotPlug, true + return o.ImageAliases, true } -// SetNicHotPlug sets field value -func (o *ImageProperties) SetNicHotPlug(v bool) { +// SetImageAliases sets field value +func (o *ImageProperties) SetImageAliases(v []string) { - o.NicHotPlug = &v + o.ImageAliases = &v } -// HasNicHotPlug returns a boolean if a field has been set. -func (o *ImageProperties) HasNicHotPlug() bool { - if o != nil && o.NicHotPlug != nil { +// HasImageAliases returns a boolean if a field has been set. +func (o *ImageProperties) HasImageAliases() bool { + if o != nil && o.ImageAliases != nil { return true } return false } -// GetNicHotUnplug returns the NicHotUnplug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *ImageProperties) GetNicHotUnplug() *bool { +// GetImageType returns the ImageType field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetImageType() *string { if o == nil { return nil } - return o.NicHotUnplug + return o.ImageType } -// GetNicHotUnplugOk returns a tuple with the NicHotUnplug field value +// GetImageTypeOk returns a tuple with the ImageType field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetNicHotUnplugOk() (*bool, bool) { +func (o *ImageProperties) GetImageTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.NicHotUnplug, true + return o.ImageType, true } -// SetNicHotUnplug sets field value -func (o *ImageProperties) SetNicHotUnplug(v bool) { +// SetImageType sets field value +func (o *ImageProperties) SetImageType(v string) { - o.NicHotUnplug = &v + o.ImageType = &v } -// HasNicHotUnplug returns a boolean if a field has been set. -func (o *ImageProperties) HasNicHotUnplug() bool { - if o != nil && o.NicHotUnplug != nil { +// HasImageType returns a boolean if a field has been set. +func (o *ImageProperties) HasImageType() bool { + if o != nil && o.ImageType != nil { return true } return false } -// GetDiscVirtioHotPlug returns the DiscVirtioHotPlug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *ImageProperties) GetDiscVirtioHotPlug() *bool { +// GetLicenceType returns the LicenceType field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetLicenceType() *string { if o == nil { return nil } - return o.DiscVirtioHotPlug + return o.LicenceType } -// GetDiscVirtioHotPlugOk returns a tuple with the DiscVirtioHotPlug field value +// GetLicenceTypeOk returns a tuple with the LicenceType field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetDiscVirtioHotPlugOk() (*bool, bool) { +func (o *ImageProperties) GetLicenceTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.DiscVirtioHotPlug, true + return o.LicenceType, true } -// SetDiscVirtioHotPlug sets field value -func (o *ImageProperties) SetDiscVirtioHotPlug(v bool) { +// SetLicenceType sets field value +func (o *ImageProperties) SetLicenceType(v string) { - o.DiscVirtioHotPlug = &v + o.LicenceType = &v } -// HasDiscVirtioHotPlug returns a boolean if a field has been set. -func (o *ImageProperties) HasDiscVirtioHotPlug() bool { - if o != nil && o.DiscVirtioHotPlug != nil { +// HasLicenceType returns a boolean if a field has been set. +func (o *ImageProperties) HasLicenceType() bool { + if o != nil && o.LicenceType != nil { return true } return false } -// GetDiscVirtioHotUnplug returns the DiscVirtioHotUnplug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *ImageProperties) GetDiscVirtioHotUnplug() *bool { +// GetLocation returns the Location field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetLocation() *string { if o == nil { return nil } - return o.DiscVirtioHotUnplug + return o.Location } -// GetDiscVirtioHotUnplugOk returns a tuple with the DiscVirtioHotUnplug field value +// GetLocationOk returns a tuple with the Location field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetDiscVirtioHotUnplugOk() (*bool, bool) { +func (o *ImageProperties) GetLocationOk() (*string, bool) { if o == nil { return nil, false } - return o.DiscVirtioHotUnplug, true + return o.Location, true } -// SetDiscVirtioHotUnplug sets field value -func (o *ImageProperties) SetDiscVirtioHotUnplug(v bool) { +// SetLocation sets field value +func (o *ImageProperties) SetLocation(v string) { - o.DiscVirtioHotUnplug = &v + o.Location = &v } -// HasDiscVirtioHotUnplug returns a boolean if a field has been set. -func (o *ImageProperties) HasDiscVirtioHotUnplug() bool { - if o != nil && o.DiscVirtioHotUnplug != nil { +// HasLocation returns a boolean if a field has been set. +func (o *ImageProperties) HasLocation() bool { + if o != nil && o.Location != nil { return true } return false } -// GetDiscScsiHotPlug returns the DiscScsiHotPlug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *ImageProperties) GetDiscScsiHotPlug() *bool { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetName() *string { if o == nil { return nil } - return o.DiscScsiHotPlug + return o.Name } -// GetDiscScsiHotPlugOk returns a tuple with the DiscScsiHotPlug field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetDiscScsiHotPlugOk() (*bool, bool) { +func (o *ImageProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.DiscScsiHotPlug, true + return o.Name, true } -// SetDiscScsiHotPlug sets field value -func (o *ImageProperties) SetDiscScsiHotPlug(v bool) { +// SetName sets field value +func (o *ImageProperties) SetName(v string) { - o.DiscScsiHotPlug = &v + o.Name = &v } -// HasDiscScsiHotPlug returns a boolean if a field has been set. -func (o *ImageProperties) HasDiscScsiHotPlug() bool { - if o != nil && o.DiscScsiHotPlug != nil { +// HasName returns a boolean if a field has been set. +func (o *ImageProperties) HasName() bool { + if o != nil && o.Name != nil { return true } return false } -// GetDiscScsiHotUnplug returns the DiscScsiHotUnplug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *ImageProperties) GetDiscScsiHotUnplug() *bool { +// GetNicHotPlug returns the NicHotPlug field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetNicHotPlug() *bool { if o == nil { return nil } - return o.DiscScsiHotUnplug + return o.NicHotPlug } -// GetDiscScsiHotUnplugOk returns a tuple with the DiscScsiHotUnplug field value +// GetNicHotPlugOk returns a tuple with the NicHotPlug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetDiscScsiHotUnplugOk() (*bool, bool) { +func (o *ImageProperties) GetNicHotPlugOk() (*bool, bool) { if o == nil { return nil, false } - return o.DiscScsiHotUnplug, true + return o.NicHotPlug, true } -// SetDiscScsiHotUnplug sets field value -func (o *ImageProperties) SetDiscScsiHotUnplug(v bool) { +// SetNicHotPlug sets field value +func (o *ImageProperties) SetNicHotPlug(v bool) { - o.DiscScsiHotUnplug = &v + o.NicHotPlug = &v } -// HasDiscScsiHotUnplug returns a boolean if a field has been set. -func (o *ImageProperties) HasDiscScsiHotUnplug() bool { - if o != nil && o.DiscScsiHotUnplug != nil { +// HasNicHotPlug returns a boolean if a field has been set. +func (o *ImageProperties) HasNicHotPlug() bool { + if o != nil && o.NicHotPlug != nil { return true } return false } -// GetLicenceType returns the LicenceType field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ImageProperties) GetLicenceType() *string { +// GetNicHotUnplug returns the NicHotUnplug field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetNicHotUnplug() *bool { if o == nil { return nil } - return o.LicenceType + return o.NicHotUnplug } -// GetLicenceTypeOk returns a tuple with the LicenceType field value +// GetNicHotUnplugOk returns a tuple with the NicHotUnplug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetLicenceTypeOk() (*string, bool) { +func (o *ImageProperties) GetNicHotUnplugOk() (*bool, bool) { if o == nil { return nil, false } - return o.LicenceType, true + return o.NicHotUnplug, true } -// SetLicenceType sets field value -func (o *ImageProperties) SetLicenceType(v string) { +// SetNicHotUnplug sets field value +func (o *ImageProperties) SetNicHotUnplug(v bool) { - o.LicenceType = &v + o.NicHotUnplug = &v } -// HasLicenceType returns a boolean if a field has been set. -func (o *ImageProperties) HasLicenceType() bool { - if o != nil && o.LicenceType != nil { +// HasNicHotUnplug returns a boolean if a field has been set. +func (o *ImageProperties) HasNicHotUnplug() bool { + if o != nil && o.NicHotUnplug != nil { return true } return false } -// GetImageType returns the ImageType field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ImageProperties) GetImageType() *string { +// GetPublic returns the Public field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetPublic() *bool { if o == nil { return nil } - return o.ImageType + return o.Public } -// GetImageTypeOk returns a tuple with the ImageType field value +// GetPublicOk returns a tuple with the Public field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetImageTypeOk() (*string, bool) { +func (o *ImageProperties) GetPublicOk() (*bool, bool) { if o == nil { return nil, false } - return o.ImageType, true + return o.Public, true } -// SetImageType sets field value -func (o *ImageProperties) SetImageType(v string) { +// SetPublic sets field value +func (o *ImageProperties) SetPublic(v bool) { - o.ImageType = &v + o.Public = &v } -// HasImageType returns a boolean if a field has been set. -func (o *ImageProperties) HasImageType() bool { - if o != nil && o.ImageType != nil { +// HasPublic returns a boolean if a field has been set. +func (o *ImageProperties) HasPublic() bool { + if o != nil && o.Public != nil { return true } return false } -// GetPublic returns the Public field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *ImageProperties) GetPublic() *bool { +// GetRamHotPlug returns the RamHotPlug field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetRamHotPlug() *bool { if o == nil { return nil } - return o.Public + return o.RamHotPlug } -// GetPublicOk returns a tuple with the Public field value +// GetRamHotPlugOk returns a tuple with the RamHotPlug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetPublicOk() (*bool, bool) { +func (o *ImageProperties) GetRamHotPlugOk() (*bool, bool) { if o == nil { return nil, false } - return o.Public, true + return o.RamHotPlug, true } -// SetPublic sets field value -func (o *ImageProperties) SetPublic(v bool) { +// SetRamHotPlug sets field value +func (o *ImageProperties) SetRamHotPlug(v bool) { - o.Public = &v + o.RamHotPlug = &v } -// HasPublic returns a boolean if a field has been set. -func (o *ImageProperties) HasPublic() bool { - if o != nil && o.Public != nil { +// HasRamHotPlug returns a boolean if a field has been set. +func (o *ImageProperties) HasRamHotPlug() bool { + if o != nil && o.RamHotPlug != nil { return true } return false } -// GetImageAliases returns the ImageAliases field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *ImageProperties) GetImageAliases() *[]string { +// GetRamHotUnplug returns the RamHotUnplug field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetRamHotUnplug() *bool { if o == nil { return nil } - return o.ImageAliases + return o.RamHotUnplug } -// GetImageAliasesOk returns a tuple with the ImageAliases field value +// GetRamHotUnplugOk returns a tuple with the RamHotUnplug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetImageAliasesOk() (*[]string, bool) { +func (o *ImageProperties) GetRamHotUnplugOk() (*bool, bool) { if o == nil { return nil, false } - return o.ImageAliases, true + return o.RamHotUnplug, true } -// SetImageAliases sets field value -func (o *ImageProperties) SetImageAliases(v []string) { +// SetRamHotUnplug sets field value +func (o *ImageProperties) SetRamHotUnplug(v bool) { - o.ImageAliases = &v + o.RamHotUnplug = &v } -// HasImageAliases returns a boolean if a field has been set. -func (o *ImageProperties) HasImageAliases() bool { - if o != nil && o.ImageAliases != nil { +// HasRamHotUnplug returns a boolean if a field has been set. +func (o *ImageProperties) HasRamHotUnplug() bool { + if o != nil && o.RamHotUnplug != nil { return true } return false } -// GetCloudInit returns the CloudInit field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ImageProperties) GetCloudInit() *string { +// GetSize returns the Size field value +// If the value is explicit nil, nil is returned +func (o *ImageProperties) GetSize() *float32 { if o == nil { return nil } - return o.CloudInit + return o.Size } -// GetCloudInitOk returns a tuple with the CloudInit field value +// GetSizeOk returns a tuple with the Size field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ImageProperties) GetCloudInitOk() (*string, bool) { +func (o *ImageProperties) GetSizeOk() (*float32, bool) { if o == nil { return nil, false } - return o.CloudInit, true + return o.Size, true } -// SetCloudInit sets field value -func (o *ImageProperties) SetCloudInit(v string) { +// SetSize sets field value +func (o *ImageProperties) SetSize(v float32) { - o.CloudInit = &v + o.Size = &v } -// HasCloudInit returns a boolean if a field has been set. -func (o *ImageProperties) HasCloudInit() bool { - if o != nil && o.CloudInit != nil { +// HasSize returns a boolean if a field has been set. +func (o *ImageProperties) HasSize() bool { + if o != nil && o.Size != nil { return true } @@ -800,63 +800,82 @@ func (o *ImageProperties) HasCloudInit() bool { func (o ImageProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name - } - if o.Description != nil { - toSerialize["description"] = o.Description - } - if o.Location != nil { - toSerialize["location"] = o.Location - } - if o.Size != nil { - toSerialize["size"] = o.Size + if o.CloudInit != nil { + toSerialize["cloudInit"] = o.CloudInit } + if o.CpuHotPlug != nil { toSerialize["cpuHotPlug"] = o.CpuHotPlug } + if o.CpuHotUnplug != nil { toSerialize["cpuHotUnplug"] = o.CpuHotUnplug } - if o.RamHotPlug != nil { - toSerialize["ramHotPlug"] = o.RamHotPlug - } - if o.RamHotUnplug != nil { - toSerialize["ramHotUnplug"] = o.RamHotUnplug + + if o.Description != nil { + toSerialize["description"] = o.Description } - if o.NicHotPlug != nil { - toSerialize["nicHotPlug"] = o.NicHotPlug + + if o.DiscScsiHotPlug != nil { + toSerialize["discScsiHotPlug"] = o.DiscScsiHotPlug } - if o.NicHotUnplug != nil { - toSerialize["nicHotUnplug"] = o.NicHotUnplug + + if o.DiscScsiHotUnplug != nil { + toSerialize["discScsiHotUnplug"] = o.DiscScsiHotUnplug } + if o.DiscVirtioHotPlug != nil { toSerialize["discVirtioHotPlug"] = o.DiscVirtioHotPlug } + if o.DiscVirtioHotUnplug != nil { toSerialize["discVirtioHotUnplug"] = o.DiscVirtioHotUnplug } - if o.DiscScsiHotPlug != nil { - toSerialize["discScsiHotPlug"] = o.DiscScsiHotPlug + + if o.ImageAliases != nil { + toSerialize["imageAliases"] = o.ImageAliases } - if o.DiscScsiHotUnplug != nil { - toSerialize["discScsiHotUnplug"] = o.DiscScsiHotUnplug + + if o.ImageType != nil { + toSerialize["imageType"] = o.ImageType } + if o.LicenceType != nil { toSerialize["licenceType"] = o.LicenceType } - if o.ImageType != nil { - toSerialize["imageType"] = o.ImageType + + if o.Location != nil { + toSerialize["location"] = o.Location + } + + if o.Name != nil { + toSerialize["name"] = o.Name + } + + if o.NicHotPlug != nil { + toSerialize["nicHotPlug"] = o.NicHotPlug } + + if o.NicHotUnplug != nil { + toSerialize["nicHotUnplug"] = o.NicHotUnplug + } + if o.Public != nil { toSerialize["public"] = o.Public } - if o.ImageAliases != nil { - toSerialize["imageAliases"] = o.ImageAliases + + if o.RamHotPlug != nil { + toSerialize["ramHotPlug"] = o.RamHotPlug } - if o.CloudInit != nil { - toSerialize["cloudInit"] = o.CloudInit + + if o.RamHotUnplug != nil { + toSerialize["ramHotUnplug"] = o.RamHotUnplug } + + if o.Size != nil { + toSerialize["size"] = o.Size + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_images.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_images.go index ff496fb196f..1cec4020e6e 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_images.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_images.go @@ -16,14 +16,14 @@ import ( // Images struct for Images type Images struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // The URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Image `json:"items,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewImages instantiates a new Images object @@ -44,152 +44,152 @@ func NewImagesWithDefaults() *Images { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Images) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Images) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Images) GetIdOk() (*string, bool) { +func (o *Images) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Images) SetId(v string) { +// SetHref sets field value +func (o *Images) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Images) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Images) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Images) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Images) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Images) GetTypeOk() (*Type, bool) { +func (o *Images) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Images) SetType(v Type) { +// SetId sets field value +func (o *Images) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Images) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Images) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Images) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *Images) GetItems() *[]Image { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Images) GetHrefOk() (*string, bool) { +func (o *Images) GetItemsOk() (*[]Image, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *Images) SetHref(v string) { +// SetItems sets field value +func (o *Images) SetItems(v []Image) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *Images) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *Images) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Image will be returned -func (o *Images) GetItems() *[]Image { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Images) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Images) GetItemsOk() (*[]Image, bool) { +func (o *Images) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *Images) SetItems(v []Image) { +// SetType sets field value +func (o *Images) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *Images) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *Images) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *Images) HasItems() bool { func (o Images) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_info.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_info.go index 19f4a146768..2ada276b579 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_info.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_info.go @@ -43,7 +43,7 @@ func NewInfoWithDefaults() *Info { } // GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *Info) GetHref() *string { if o == nil { return nil @@ -81,7 +81,7 @@ func (o *Info) HasHref() bool { } // GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *Info) GetName() *string { if o == nil { return nil @@ -119,7 +119,7 @@ func (o *Info) HasName() bool { } // GetVersion returns the Version field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *Info) GetVersion() *string { if o == nil { return nil @@ -161,12 +161,15 @@ func (o Info) MarshalJSON() ([]byte, error) { if o.Href != nil { toSerialize["href"] = o.Href } + if o.Name != nil { toSerialize["name"] = o.Name } + if o.Version != nil { toSerialize["version"] = o.Version } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_block.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_block.go index af07f6fb18f..c7e16a0f215 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_block.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_block.go @@ -16,14 +16,14 @@ import ( // IpBlock struct for IpBlock type IpBlock struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *IpBlockProperties `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewIpBlock instantiates a new IpBlock object @@ -46,190 +46,190 @@ func NewIpBlockWithDefaults() *IpBlock { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *IpBlock) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *IpBlock) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlock) GetIdOk() (*string, bool) { +func (o *IpBlock) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *IpBlock) SetId(v string) { +// SetHref sets field value +func (o *IpBlock) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *IpBlock) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *IpBlock) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *IpBlock) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *IpBlock) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlock) GetTypeOk() (*Type, bool) { +func (o *IpBlock) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *IpBlock) SetType(v Type) { +// SetId sets field value +func (o *IpBlock) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *IpBlock) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *IpBlock) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *IpBlock) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *IpBlock) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlock) GetHrefOk() (*string, bool) { +func (o *IpBlock) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *IpBlock) SetHref(v string) { +// SetMetadata sets field value +func (o *IpBlock) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *IpBlock) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *IpBlock) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *IpBlock) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *IpBlock) GetProperties() *IpBlockProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlock) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *IpBlock) GetPropertiesOk() (*IpBlockProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *IpBlock) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *IpBlock) SetProperties(v IpBlockProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *IpBlock) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *IpBlock) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for IpBlockProperties will be returned -func (o *IpBlock) GetProperties() *IpBlockProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *IpBlock) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlock) GetPropertiesOk() (*IpBlockProperties, bool) { +func (o *IpBlock) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *IpBlock) SetProperties(v IpBlockProperties) { +// SetType sets field value +func (o *IpBlock) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *IpBlock) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *IpBlock) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *IpBlock) HasProperties() bool { func (o IpBlock) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_block_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_block_properties.go index 4f732b53b2a..19c3ed75734 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_block_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_block_properties.go @@ -16,16 +16,16 @@ import ( // IpBlockProperties struct for IpBlockProperties type IpBlockProperties struct { + // Read-Only attribute. Lists consumption detail for an individual IP + IpConsumers *[]IpConsumer `json:"ipConsumers,omitempty"` // Collection of IPs, associated with the IP Block. Ips *[]string `json:"ips,omitempty"` // Location of that IP block. Property cannot be modified after it is created (disallowed in update requests). Location *string `json:"location"` - // The size of the IP block. - Size *int32 `json:"size"` // The name of the resource. Name *string `json:"name,omitempty"` - // Read-Only attribute. Lists consumption detail for an individual IP - IpConsumers *[]IpConsumer `json:"ipConsumers,omitempty"` + // The size of the IP block. + Size *int32 `json:"size"` } // NewIpBlockProperties instantiates a new IpBlockProperties object @@ -49,114 +49,114 @@ func NewIpBlockPropertiesWithDefaults() *IpBlockProperties { return &this } -// GetIps returns the Ips field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *IpBlockProperties) GetIps() *[]string { +// GetIpConsumers returns the IpConsumers field value +// If the value is explicit nil, nil is returned +func (o *IpBlockProperties) GetIpConsumers() *[]IpConsumer { if o == nil { return nil } - return o.Ips + return o.IpConsumers } -// GetIpsOk returns a tuple with the Ips field value +// GetIpConsumersOk returns a tuple with the IpConsumers field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlockProperties) GetIpsOk() (*[]string, bool) { +func (o *IpBlockProperties) GetIpConsumersOk() (*[]IpConsumer, bool) { if o == nil { return nil, false } - return o.Ips, true + return o.IpConsumers, true } -// SetIps sets field value -func (o *IpBlockProperties) SetIps(v []string) { +// SetIpConsumers sets field value +func (o *IpBlockProperties) SetIpConsumers(v []IpConsumer) { - o.Ips = &v + o.IpConsumers = &v } -// HasIps returns a boolean if a field has been set. -func (o *IpBlockProperties) HasIps() bool { - if o != nil && o.Ips != nil { +// HasIpConsumers returns a boolean if a field has been set. +func (o *IpBlockProperties) HasIpConsumers() bool { + if o != nil && o.IpConsumers != nil { return true } return false } -// GetLocation returns the Location field value -// If the value is explicit nil, the zero value for string will be returned -func (o *IpBlockProperties) GetLocation() *string { +// GetIps returns the Ips field value +// If the value is explicit nil, nil is returned +func (o *IpBlockProperties) GetIps() *[]string { if o == nil { return nil } - return o.Location + return o.Ips } -// GetLocationOk returns a tuple with the Location field value +// GetIpsOk returns a tuple with the Ips field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlockProperties) GetLocationOk() (*string, bool) { +func (o *IpBlockProperties) GetIpsOk() (*[]string, bool) { if o == nil { return nil, false } - return o.Location, true + return o.Ips, true } -// SetLocation sets field value -func (o *IpBlockProperties) SetLocation(v string) { +// SetIps sets field value +func (o *IpBlockProperties) SetIps(v []string) { - o.Location = &v + o.Ips = &v } -// HasLocation returns a boolean if a field has been set. -func (o *IpBlockProperties) HasLocation() bool { - if o != nil && o.Location != nil { +// HasIps returns a boolean if a field has been set. +func (o *IpBlockProperties) HasIps() bool { + if o != nil && o.Ips != nil { return true } return false } -// GetSize returns the Size field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *IpBlockProperties) GetSize() *int32 { +// GetLocation returns the Location field value +// If the value is explicit nil, nil is returned +func (o *IpBlockProperties) GetLocation() *string { if o == nil { return nil } - return o.Size + return o.Location } -// GetSizeOk returns a tuple with the Size field value +// GetLocationOk returns a tuple with the Location field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlockProperties) GetSizeOk() (*int32, bool) { +func (o *IpBlockProperties) GetLocationOk() (*string, bool) { if o == nil { return nil, false } - return o.Size, true + return o.Location, true } -// SetSize sets field value -func (o *IpBlockProperties) SetSize(v int32) { +// SetLocation sets field value +func (o *IpBlockProperties) SetLocation(v string) { - o.Size = &v + o.Location = &v } -// HasSize returns a boolean if a field has been set. -func (o *IpBlockProperties) HasSize() bool { - if o != nil && o.Size != nil { +// HasLocation returns a boolean if a field has been set. +func (o *IpBlockProperties) HasLocation() bool { + if o != nil && o.Location != nil { return true } @@ -164,7 +164,7 @@ func (o *IpBlockProperties) HasSize() bool { } // GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *IpBlockProperties) GetName() *string { if o == nil { return nil @@ -201,38 +201,38 @@ func (o *IpBlockProperties) HasName() bool { return false } -// GetIpConsumers returns the IpConsumers field value -// If the value is explicit nil, the zero value for []IpConsumer will be returned -func (o *IpBlockProperties) GetIpConsumers() *[]IpConsumer { +// GetSize returns the Size field value +// If the value is explicit nil, nil is returned +func (o *IpBlockProperties) GetSize() *int32 { if o == nil { return nil } - return o.IpConsumers + return o.Size } -// GetIpConsumersOk returns a tuple with the IpConsumers field value +// GetSizeOk returns a tuple with the Size field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlockProperties) GetIpConsumersOk() (*[]IpConsumer, bool) { +func (o *IpBlockProperties) GetSizeOk() (*int32, bool) { if o == nil { return nil, false } - return o.IpConsumers, true + return o.Size, true } -// SetIpConsumers sets field value -func (o *IpBlockProperties) SetIpConsumers(v []IpConsumer) { +// SetSize sets field value +func (o *IpBlockProperties) SetSize(v int32) { - o.IpConsumers = &v + o.Size = &v } -// HasIpConsumers returns a boolean if a field has been set. -func (o *IpBlockProperties) HasIpConsumers() bool { - if o != nil && o.IpConsumers != nil { +// HasSize returns a boolean if a field has been set. +func (o *IpBlockProperties) HasSize() bool { + if o != nil && o.Size != nil { return true } @@ -241,21 +241,26 @@ func (o *IpBlockProperties) HasIpConsumers() bool { func (o IpBlockProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} + if o.IpConsumers != nil { + toSerialize["ipConsumers"] = o.IpConsumers + } + if o.Ips != nil { toSerialize["ips"] = o.Ips } + if o.Location != nil { toSerialize["location"] = o.Location } - if o.Size != nil { - toSerialize["size"] = o.Size - } + if o.Name != nil { toSerialize["name"] = o.Name } - if o.IpConsumers != nil { - toSerialize["ipConsumers"] = o.IpConsumers + + if o.Size != nil { + toSerialize["size"] = o.Size } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_blocks.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_blocks.go index 010dc17fea0..117235c82c8 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_blocks.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_blocks.go @@ -16,19 +16,19 @@ import ( // IpBlocks struct for IpBlocks type IpBlocks struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]IpBlock `json:"items,omitempty"` + // The limit, specified in the request (if not specified, the endpoint's default pagination limit is used). + Limit *float32 `json:"limit,omitempty"` // The offset, specified in the request (if not is specified, 0 is used by default). Offset *float32 `json:"offset,omitempty"` - // The limit, specified in the request (if not specified, the endpoint's default pagination limit is used). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewIpBlocks instantiates a new IpBlocks object @@ -49,114 +49,114 @@ func NewIpBlocksWithDefaults() *IpBlocks { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *IpBlocks) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *IpBlocks) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlocks) GetIdOk() (*string, bool) { +func (o *IpBlocks) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *IpBlocks) SetId(v string) { +// SetLinks sets field value +func (o *IpBlocks) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *IpBlocks) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *IpBlocks) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *IpBlocks) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *IpBlocks) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlocks) GetTypeOk() (*Type, bool) { +func (o *IpBlocks) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *IpBlocks) SetType(v Type) { +// SetHref sets field value +func (o *IpBlocks) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *IpBlocks) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *IpBlocks) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *IpBlocks) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *IpBlocks) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlocks) GetHrefOk() (*string, bool) { +func (o *IpBlocks) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *IpBlocks) SetHref(v string) { +// SetId sets field value +func (o *IpBlocks) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *IpBlocks) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *IpBlocks) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *IpBlocks) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []IpBlock will be returned +// If the value is explicit nil, nil is returned func (o *IpBlocks) GetItems() *[]IpBlock { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *IpBlocks) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *IpBlocks) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *IpBlocks) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlocks) GetOffsetOk() (*float32, bool) { +func (o *IpBlocks) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *IpBlocks) SetOffset(v float32) { +// SetLimit sets field value +func (o *IpBlocks) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *IpBlocks) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *IpBlocks) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *IpBlocks) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *IpBlocks) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlocks) GetLimitOk() (*float32, bool) { +func (o *IpBlocks) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *IpBlocks) SetLimit(v float32) { +// SetOffset sets field value +func (o *IpBlocks) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *IpBlocks) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *IpBlocks) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *IpBlocks) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *IpBlocks) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpBlocks) GetLinksOk() (*PaginationLinks, bool) { +func (o *IpBlocks) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *IpBlocks) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *IpBlocks) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *IpBlocks) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *IpBlocks) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *IpBlocks) HasLinks() bool { func (o IpBlocks) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_consumer.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_consumer.go index a0e9e55c6d7..e405979fe2b 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_consumer.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_consumer.go @@ -16,15 +16,15 @@ import ( // IpConsumer struct for IpConsumer type IpConsumer struct { + DatacenterId *string `json:"datacenterId,omitempty"` + DatacenterName *string `json:"datacenterName,omitempty"` Ip *string `json:"ip,omitempty"` + K8sClusterUuid *string `json:"k8sClusterUuid,omitempty"` + K8sNodePoolUuid *string `json:"k8sNodePoolUuid,omitempty"` Mac *string `json:"mac,omitempty"` NicId *string `json:"nicId,omitempty"` ServerId *string `json:"serverId,omitempty"` ServerName *string `json:"serverName,omitempty"` - DatacenterId *string `json:"datacenterId,omitempty"` - DatacenterName *string `json:"datacenterName,omitempty"` - K8sNodePoolUuid *string `json:"k8sNodePoolUuid,omitempty"` - K8sClusterUuid *string `json:"k8sClusterUuid,omitempty"` } // NewIpConsumer instantiates a new IpConsumer object @@ -45,342 +45,342 @@ func NewIpConsumerWithDefaults() *IpConsumer { return &this } -// GetIp returns the Ip field value -// If the value is explicit nil, the zero value for string will be returned -func (o *IpConsumer) GetIp() *string { +// GetDatacenterId returns the DatacenterId field value +// If the value is explicit nil, nil is returned +func (o *IpConsumer) GetDatacenterId() *string { if o == nil { return nil } - return o.Ip + return o.DatacenterId } -// GetIpOk returns a tuple with the Ip field value +// GetDatacenterIdOk returns a tuple with the DatacenterId field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpConsumer) GetIpOk() (*string, bool) { +func (o *IpConsumer) GetDatacenterIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Ip, true + return o.DatacenterId, true } -// SetIp sets field value -func (o *IpConsumer) SetIp(v string) { +// SetDatacenterId sets field value +func (o *IpConsumer) SetDatacenterId(v string) { - o.Ip = &v + o.DatacenterId = &v } -// HasIp returns a boolean if a field has been set. -func (o *IpConsumer) HasIp() bool { - if o != nil && o.Ip != nil { +// HasDatacenterId returns a boolean if a field has been set. +func (o *IpConsumer) HasDatacenterId() bool { + if o != nil && o.DatacenterId != nil { return true } return false } -// GetMac returns the Mac field value -// If the value is explicit nil, the zero value for string will be returned -func (o *IpConsumer) GetMac() *string { +// GetDatacenterName returns the DatacenterName field value +// If the value is explicit nil, nil is returned +func (o *IpConsumer) GetDatacenterName() *string { if o == nil { return nil } - return o.Mac + return o.DatacenterName } -// GetMacOk returns a tuple with the Mac field value +// GetDatacenterNameOk returns a tuple with the DatacenterName field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpConsumer) GetMacOk() (*string, bool) { +func (o *IpConsumer) GetDatacenterNameOk() (*string, bool) { if o == nil { return nil, false } - return o.Mac, true + return o.DatacenterName, true } -// SetMac sets field value -func (o *IpConsumer) SetMac(v string) { +// SetDatacenterName sets field value +func (o *IpConsumer) SetDatacenterName(v string) { - o.Mac = &v + o.DatacenterName = &v } -// HasMac returns a boolean if a field has been set. -func (o *IpConsumer) HasMac() bool { - if o != nil && o.Mac != nil { +// HasDatacenterName returns a boolean if a field has been set. +func (o *IpConsumer) HasDatacenterName() bool { + if o != nil && o.DatacenterName != nil { return true } return false } -// GetNicId returns the NicId field value -// If the value is explicit nil, the zero value for string will be returned -func (o *IpConsumer) GetNicId() *string { +// GetIp returns the Ip field value +// If the value is explicit nil, nil is returned +func (o *IpConsumer) GetIp() *string { if o == nil { return nil } - return o.NicId + return o.Ip } -// GetNicIdOk returns a tuple with the NicId field value +// GetIpOk returns a tuple with the Ip field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpConsumer) GetNicIdOk() (*string, bool) { +func (o *IpConsumer) GetIpOk() (*string, bool) { if o == nil { return nil, false } - return o.NicId, true + return o.Ip, true } -// SetNicId sets field value -func (o *IpConsumer) SetNicId(v string) { +// SetIp sets field value +func (o *IpConsumer) SetIp(v string) { - o.NicId = &v + o.Ip = &v } -// HasNicId returns a boolean if a field has been set. -func (o *IpConsumer) HasNicId() bool { - if o != nil && o.NicId != nil { +// HasIp returns a boolean if a field has been set. +func (o *IpConsumer) HasIp() bool { + if o != nil && o.Ip != nil { return true } return false } -// GetServerId returns the ServerId field value -// If the value is explicit nil, the zero value for string will be returned -func (o *IpConsumer) GetServerId() *string { +// GetK8sClusterUuid returns the K8sClusterUuid field value +// If the value is explicit nil, nil is returned +func (o *IpConsumer) GetK8sClusterUuid() *string { if o == nil { return nil } - return o.ServerId + return o.K8sClusterUuid } -// GetServerIdOk returns a tuple with the ServerId field value +// GetK8sClusterUuidOk returns a tuple with the K8sClusterUuid field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpConsumer) GetServerIdOk() (*string, bool) { +func (o *IpConsumer) GetK8sClusterUuidOk() (*string, bool) { if o == nil { return nil, false } - return o.ServerId, true + return o.K8sClusterUuid, true } -// SetServerId sets field value -func (o *IpConsumer) SetServerId(v string) { +// SetK8sClusterUuid sets field value +func (o *IpConsumer) SetK8sClusterUuid(v string) { - o.ServerId = &v + o.K8sClusterUuid = &v } -// HasServerId returns a boolean if a field has been set. -func (o *IpConsumer) HasServerId() bool { - if o != nil && o.ServerId != nil { +// HasK8sClusterUuid returns a boolean if a field has been set. +func (o *IpConsumer) HasK8sClusterUuid() bool { + if o != nil && o.K8sClusterUuid != nil { return true } return false } -// GetServerName returns the ServerName field value -// If the value is explicit nil, the zero value for string will be returned -func (o *IpConsumer) GetServerName() *string { +// GetK8sNodePoolUuid returns the K8sNodePoolUuid field value +// If the value is explicit nil, nil is returned +func (o *IpConsumer) GetK8sNodePoolUuid() *string { if o == nil { return nil } - return o.ServerName + return o.K8sNodePoolUuid } -// GetServerNameOk returns a tuple with the ServerName field value +// GetK8sNodePoolUuidOk returns a tuple with the K8sNodePoolUuid field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpConsumer) GetServerNameOk() (*string, bool) { +func (o *IpConsumer) GetK8sNodePoolUuidOk() (*string, bool) { if o == nil { return nil, false } - return o.ServerName, true + return o.K8sNodePoolUuid, true } -// SetServerName sets field value -func (o *IpConsumer) SetServerName(v string) { +// SetK8sNodePoolUuid sets field value +func (o *IpConsumer) SetK8sNodePoolUuid(v string) { - o.ServerName = &v + o.K8sNodePoolUuid = &v } -// HasServerName returns a boolean if a field has been set. -func (o *IpConsumer) HasServerName() bool { - if o != nil && o.ServerName != nil { +// HasK8sNodePoolUuid returns a boolean if a field has been set. +func (o *IpConsumer) HasK8sNodePoolUuid() bool { + if o != nil && o.K8sNodePoolUuid != nil { return true } return false } -// GetDatacenterId returns the DatacenterId field value -// If the value is explicit nil, the zero value for string will be returned -func (o *IpConsumer) GetDatacenterId() *string { +// GetMac returns the Mac field value +// If the value is explicit nil, nil is returned +func (o *IpConsumer) GetMac() *string { if o == nil { return nil } - return o.DatacenterId + return o.Mac } -// GetDatacenterIdOk returns a tuple with the DatacenterId field value +// GetMacOk returns a tuple with the Mac field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpConsumer) GetDatacenterIdOk() (*string, bool) { +func (o *IpConsumer) GetMacOk() (*string, bool) { if o == nil { return nil, false } - return o.DatacenterId, true + return o.Mac, true } -// SetDatacenterId sets field value -func (o *IpConsumer) SetDatacenterId(v string) { +// SetMac sets field value +func (o *IpConsumer) SetMac(v string) { - o.DatacenterId = &v + o.Mac = &v } -// HasDatacenterId returns a boolean if a field has been set. -func (o *IpConsumer) HasDatacenterId() bool { - if o != nil && o.DatacenterId != nil { +// HasMac returns a boolean if a field has been set. +func (o *IpConsumer) HasMac() bool { + if o != nil && o.Mac != nil { return true } return false } -// GetDatacenterName returns the DatacenterName field value -// If the value is explicit nil, the zero value for string will be returned -func (o *IpConsumer) GetDatacenterName() *string { +// GetNicId returns the NicId field value +// If the value is explicit nil, nil is returned +func (o *IpConsumer) GetNicId() *string { if o == nil { return nil } - return o.DatacenterName + return o.NicId } -// GetDatacenterNameOk returns a tuple with the DatacenterName field value +// GetNicIdOk returns a tuple with the NicId field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpConsumer) GetDatacenterNameOk() (*string, bool) { +func (o *IpConsumer) GetNicIdOk() (*string, bool) { if o == nil { return nil, false } - return o.DatacenterName, true + return o.NicId, true } -// SetDatacenterName sets field value -func (o *IpConsumer) SetDatacenterName(v string) { +// SetNicId sets field value +func (o *IpConsumer) SetNicId(v string) { - o.DatacenterName = &v + o.NicId = &v } -// HasDatacenterName returns a boolean if a field has been set. -func (o *IpConsumer) HasDatacenterName() bool { - if o != nil && o.DatacenterName != nil { +// HasNicId returns a boolean if a field has been set. +func (o *IpConsumer) HasNicId() bool { + if o != nil && o.NicId != nil { return true } return false } -// GetK8sNodePoolUuid returns the K8sNodePoolUuid field value -// If the value is explicit nil, the zero value for string will be returned -func (o *IpConsumer) GetK8sNodePoolUuid() *string { +// GetServerId returns the ServerId field value +// If the value is explicit nil, nil is returned +func (o *IpConsumer) GetServerId() *string { if o == nil { return nil } - return o.K8sNodePoolUuid + return o.ServerId } -// GetK8sNodePoolUuidOk returns a tuple with the K8sNodePoolUuid field value +// GetServerIdOk returns a tuple with the ServerId field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpConsumer) GetK8sNodePoolUuidOk() (*string, bool) { +func (o *IpConsumer) GetServerIdOk() (*string, bool) { if o == nil { return nil, false } - return o.K8sNodePoolUuid, true + return o.ServerId, true } -// SetK8sNodePoolUuid sets field value -func (o *IpConsumer) SetK8sNodePoolUuid(v string) { +// SetServerId sets field value +func (o *IpConsumer) SetServerId(v string) { - o.K8sNodePoolUuid = &v + o.ServerId = &v } -// HasK8sNodePoolUuid returns a boolean if a field has been set. -func (o *IpConsumer) HasK8sNodePoolUuid() bool { - if o != nil && o.K8sNodePoolUuid != nil { +// HasServerId returns a boolean if a field has been set. +func (o *IpConsumer) HasServerId() bool { + if o != nil && o.ServerId != nil { return true } return false } -// GetK8sClusterUuid returns the K8sClusterUuid field value -// If the value is explicit nil, the zero value for string will be returned -func (o *IpConsumer) GetK8sClusterUuid() *string { +// GetServerName returns the ServerName field value +// If the value is explicit nil, nil is returned +func (o *IpConsumer) GetServerName() *string { if o == nil { return nil } - return o.K8sClusterUuid + return o.ServerName } -// GetK8sClusterUuidOk returns a tuple with the K8sClusterUuid field value +// GetServerNameOk returns a tuple with the ServerName field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *IpConsumer) GetK8sClusterUuidOk() (*string, bool) { +func (o *IpConsumer) GetServerNameOk() (*string, bool) { if o == nil { return nil, false } - return o.K8sClusterUuid, true + return o.ServerName, true } -// SetK8sClusterUuid sets field value -func (o *IpConsumer) SetK8sClusterUuid(v string) { +// SetServerName sets field value +func (o *IpConsumer) SetServerName(v string) { - o.K8sClusterUuid = &v + o.ServerName = &v } -// HasK8sClusterUuid returns a boolean if a field has been set. -func (o *IpConsumer) HasK8sClusterUuid() bool { - if o != nil && o.K8sClusterUuid != nil { +// HasServerName returns a boolean if a field has been set. +func (o *IpConsumer) HasServerName() bool { + if o != nil && o.ServerName != nil { return true } @@ -389,33 +389,42 @@ func (o *IpConsumer) HasK8sClusterUuid() bool { func (o IpConsumer) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} + if o.DatacenterId != nil { + toSerialize["datacenterId"] = o.DatacenterId + } + + if o.DatacenterName != nil { + toSerialize["datacenterName"] = o.DatacenterName + } + if o.Ip != nil { toSerialize["ip"] = o.Ip } + + if o.K8sClusterUuid != nil { + toSerialize["k8sClusterUuid"] = o.K8sClusterUuid + } + + if o.K8sNodePoolUuid != nil { + toSerialize["k8sNodePoolUuid"] = o.K8sNodePoolUuid + } + if o.Mac != nil { toSerialize["mac"] = o.Mac } + if o.NicId != nil { toSerialize["nicId"] = o.NicId } + if o.ServerId != nil { toSerialize["serverId"] = o.ServerId } + if o.ServerName != nil { toSerialize["serverName"] = o.ServerName } - if o.DatacenterId != nil { - toSerialize["datacenterId"] = o.DatacenterId - } - if o.DatacenterName != nil { - toSerialize["datacenterName"] = o.DatacenterName - } - if o.K8sNodePoolUuid != nil { - toSerialize["k8sNodePoolUuid"] = o.K8sNodePoolUuid - } - if o.K8sClusterUuid != nil { - toSerialize["k8sClusterUuid"] = o.K8sClusterUuid - } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_failover.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_failover.go index 16677e73e1a..60c902a97dc 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_failover.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_ip_failover.go @@ -39,7 +39,7 @@ func NewIPFailoverWithDefaults() *IPFailover { } // GetIp returns the Ip field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *IPFailover) GetIp() *string { if o == nil { return nil @@ -77,7 +77,7 @@ func (o *IPFailover) HasIp() bool { } // GetNicUuid returns the NicUuid field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *IPFailover) GetNicUuid() *string { if o == nil { return nil @@ -119,9 +119,11 @@ func (o IPFailover) MarshalJSON() ([]byte, error) { if o.Ip != nil { toSerialize["ip"] = o.Ip } + if o.NicUuid != nil { toSerialize["nicUuid"] = o.NicUuid } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_auto_scaling.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_auto_scaling.go index 24f95d7b3f8..49d9b3e8642 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_auto_scaling.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_auto_scaling.go @@ -16,21 +16,21 @@ import ( // KubernetesAutoScaling struct for KubernetesAutoScaling type KubernetesAutoScaling struct { - // The minimum number of working nodes that the managed node pool can scale must be >= 1 and >= nodeCount. Required if autoScaling is specified. - MinNodeCount *int32 `json:"minNodeCount"` // The maximum number of worker nodes that the managed node pool can scale in. Must be >= minNodeCount and must be >= nodeCount. Required if autoScaling is specified. MaxNodeCount *int32 `json:"maxNodeCount"` + // The minimum number of working nodes that the managed node pool can scale must be >= 1 and >= nodeCount. Required if autoScaling is specified. + MinNodeCount *int32 `json:"minNodeCount"` } // NewKubernetesAutoScaling instantiates a new KubernetesAutoScaling object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewKubernetesAutoScaling(minNodeCount int32, maxNodeCount int32) *KubernetesAutoScaling { +func NewKubernetesAutoScaling(maxNodeCount int32, minNodeCount int32) *KubernetesAutoScaling { this := KubernetesAutoScaling{} - this.MinNodeCount = &minNodeCount this.MaxNodeCount = &maxNodeCount + this.MinNodeCount = &minNodeCount return &this } @@ -43,76 +43,76 @@ func NewKubernetesAutoScalingWithDefaults() *KubernetesAutoScaling { return &this } -// GetMinNodeCount returns the MinNodeCount field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *KubernetesAutoScaling) GetMinNodeCount() *int32 { +// GetMaxNodeCount returns the MaxNodeCount field value +// If the value is explicit nil, nil is returned +func (o *KubernetesAutoScaling) GetMaxNodeCount() *int32 { if o == nil { return nil } - return o.MinNodeCount + return o.MaxNodeCount } -// GetMinNodeCountOk returns a tuple with the MinNodeCount field value +// GetMaxNodeCountOk returns a tuple with the MaxNodeCount field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesAutoScaling) GetMinNodeCountOk() (*int32, bool) { +func (o *KubernetesAutoScaling) GetMaxNodeCountOk() (*int32, bool) { if o == nil { return nil, false } - return o.MinNodeCount, true + return o.MaxNodeCount, true } -// SetMinNodeCount sets field value -func (o *KubernetesAutoScaling) SetMinNodeCount(v int32) { +// SetMaxNodeCount sets field value +func (o *KubernetesAutoScaling) SetMaxNodeCount(v int32) { - o.MinNodeCount = &v + o.MaxNodeCount = &v } -// HasMinNodeCount returns a boolean if a field has been set. -func (o *KubernetesAutoScaling) HasMinNodeCount() bool { - if o != nil && o.MinNodeCount != nil { +// HasMaxNodeCount returns a boolean if a field has been set. +func (o *KubernetesAutoScaling) HasMaxNodeCount() bool { + if o != nil && o.MaxNodeCount != nil { return true } return false } -// GetMaxNodeCount returns the MaxNodeCount field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *KubernetesAutoScaling) GetMaxNodeCount() *int32 { +// GetMinNodeCount returns the MinNodeCount field value +// If the value is explicit nil, nil is returned +func (o *KubernetesAutoScaling) GetMinNodeCount() *int32 { if o == nil { return nil } - return o.MaxNodeCount + return o.MinNodeCount } -// GetMaxNodeCountOk returns a tuple with the MaxNodeCount field value +// GetMinNodeCountOk returns a tuple with the MinNodeCount field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesAutoScaling) GetMaxNodeCountOk() (*int32, bool) { +func (o *KubernetesAutoScaling) GetMinNodeCountOk() (*int32, bool) { if o == nil { return nil, false } - return o.MaxNodeCount, true + return o.MinNodeCount, true } -// SetMaxNodeCount sets field value -func (o *KubernetesAutoScaling) SetMaxNodeCount(v int32) { +// SetMinNodeCount sets field value +func (o *KubernetesAutoScaling) SetMinNodeCount(v int32) { - o.MaxNodeCount = &v + o.MinNodeCount = &v } -// HasMaxNodeCount returns a boolean if a field has been set. -func (o *KubernetesAutoScaling) HasMaxNodeCount() bool { - if o != nil && o.MaxNodeCount != nil { +// HasMinNodeCount returns a boolean if a field has been set. +func (o *KubernetesAutoScaling) HasMinNodeCount() bool { + if o != nil && o.MinNodeCount != nil { return true } @@ -121,12 +121,14 @@ func (o *KubernetesAutoScaling) HasMaxNodeCount() bool { func (o KubernetesAutoScaling) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.MinNodeCount != nil { - toSerialize["minNodeCount"] = o.MinNodeCount - } if o.MaxNodeCount != nil { toSerialize["maxNodeCount"] = o.MaxNodeCount } + + if o.MinNodeCount != nil { + toSerialize["minNodeCount"] = o.MinNodeCount + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster.go index 631bda92295..994a6ac2849 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster.go @@ -16,15 +16,15 @@ import ( // KubernetesCluster struct for KubernetesCluster type KubernetesCluster struct { - // The resource unique identifier. - Id *string `json:"id,omitempty"` - // The object type. - Type *string `json:"type,omitempty"` + Entities *KubernetesClusterEntities `json:"entities,omitempty"` // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *KubernetesClusterProperties `json:"properties"` - Entities *KubernetesClusterEntities `json:"entities,omitempty"` + // The object type. + Type *string `json:"type,omitempty"` } // NewKubernetesCluster instantiates a new KubernetesCluster object @@ -47,114 +47,114 @@ func NewKubernetesClusterWithDefaults() *KubernetesCluster { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesCluster) GetId() *string { +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *KubernetesCluster) GetEntities() *KubernetesClusterEntities { if o == nil { return nil } - return o.Id + return o.Entities } -// GetIdOk returns a tuple with the Id field value +// GetEntitiesOk returns a tuple with the Entities field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesCluster) GetIdOk() (*string, bool) { +func (o *KubernetesCluster) GetEntitiesOk() (*KubernetesClusterEntities, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Entities, true } -// SetId sets field value -func (o *KubernetesCluster) SetId(v string) { +// SetEntities sets field value +func (o *KubernetesCluster) SetEntities(v KubernetesClusterEntities) { - o.Id = &v + o.Entities = &v } -// HasId returns a boolean if a field has been set. -func (o *KubernetesCluster) HasId() bool { - if o != nil && o.Id != nil { +// HasEntities returns a boolean if a field has been set. +func (o *KubernetesCluster) HasEntities() bool { + if o != nil && o.Entities != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesCluster) GetType() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *KubernetesCluster) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesCluster) GetTypeOk() (*string, bool) { +func (o *KubernetesCluster) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *KubernetesCluster) SetType(v string) { +// SetHref sets field value +func (o *KubernetesCluster) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *KubernetesCluster) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *KubernetesCluster) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesCluster) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *KubernetesCluster) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesCluster) GetHrefOk() (*string, bool) { +func (o *KubernetesCluster) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *KubernetesCluster) SetHref(v string) { +// SetId sets field value +func (o *KubernetesCluster) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *KubernetesCluster) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *KubernetesCluster) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -162,7 +162,7 @@ func (o *KubernetesCluster) HasHref() bool { } // GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesCluster) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil @@ -200,7 +200,7 @@ func (o *KubernetesCluster) HasMetadata() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for KubernetesClusterProperties will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesCluster) GetProperties() *KubernetesClusterProperties { if o == nil { return nil @@ -237,38 +237,38 @@ func (o *KubernetesCluster) HasProperties() bool { return false } -// GetEntities returns the Entities field value -// If the value is explicit nil, the zero value for KubernetesClusterEntities will be returned -func (o *KubernetesCluster) GetEntities() *KubernetesClusterEntities { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *KubernetesCluster) GetType() *string { if o == nil { return nil } - return o.Entities + return o.Type } -// GetEntitiesOk returns a tuple with the Entities field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesCluster) GetEntitiesOk() (*KubernetesClusterEntities, bool) { +func (o *KubernetesCluster) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Entities, true + return o.Type, true } -// SetEntities sets field value -func (o *KubernetesCluster) SetEntities(v KubernetesClusterEntities) { +// SetType sets field value +func (o *KubernetesCluster) SetType(v string) { - o.Entities = &v + o.Type = &v } -// HasEntities returns a boolean if a field has been set. -func (o *KubernetesCluster) HasEntities() bool { - if o != nil && o.Entities != nil { +// HasType returns a boolean if a field has been set. +func (o *KubernetesCluster) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -277,24 +277,30 @@ func (o *KubernetesCluster) HasEntities() bool { func (o KubernetesCluster) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Entities != nil { + toSerialize["entities"] = o.Entities } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } - if o.Entities != nil { - toSerialize["entities"] = o.Entities + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_entities.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_entities.go index 3e5dbaf4dbe..0e7daca3465 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_entities.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_entities.go @@ -38,7 +38,7 @@ func NewKubernetesClusterEntitiesWithDefaults() *KubernetesClusterEntities { } // GetNodepools returns the Nodepools field value -// If the value is explicit nil, the zero value for KubernetesNodePools will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesClusterEntities) GetNodepools() *KubernetesNodePools { if o == nil { return nil @@ -80,6 +80,7 @@ func (o KubernetesClusterEntities) MarshalJSON() ([]byte, error) { if o.Nodepools != nil { toSerialize["nodepools"] = o.Nodepools } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_for_post.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_for_post.go index 1fbe331ad03..cf2d02e6209 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_for_post.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_for_post.go @@ -16,15 +16,15 @@ import ( // KubernetesClusterForPost struct for KubernetesClusterForPost type KubernetesClusterForPost struct { - // The resource unique identifier. - Id *string `json:"id,omitempty"` - // The object type. - Type *string `json:"type,omitempty"` + Entities *KubernetesClusterEntities `json:"entities,omitempty"` // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *KubernetesClusterPropertiesForPost `json:"properties"` - Entities *KubernetesClusterEntities `json:"entities,omitempty"` + // The object type. + Type *string `json:"type,omitempty"` } // NewKubernetesClusterForPost instantiates a new KubernetesClusterForPost object @@ -47,114 +47,114 @@ func NewKubernetesClusterForPostWithDefaults() *KubernetesClusterForPost { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesClusterForPost) GetId() *string { +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterForPost) GetEntities() *KubernetesClusterEntities { if o == nil { return nil } - return o.Id + return o.Entities } -// GetIdOk returns a tuple with the Id field value +// GetEntitiesOk returns a tuple with the Entities field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterForPost) GetIdOk() (*string, bool) { +func (o *KubernetesClusterForPost) GetEntitiesOk() (*KubernetesClusterEntities, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Entities, true } -// SetId sets field value -func (o *KubernetesClusterForPost) SetId(v string) { +// SetEntities sets field value +func (o *KubernetesClusterForPost) SetEntities(v KubernetesClusterEntities) { - o.Id = &v + o.Entities = &v } -// HasId returns a boolean if a field has been set. -func (o *KubernetesClusterForPost) HasId() bool { - if o != nil && o.Id != nil { +// HasEntities returns a boolean if a field has been set. +func (o *KubernetesClusterForPost) HasEntities() bool { + if o != nil && o.Entities != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesClusterForPost) GetType() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterForPost) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterForPost) GetTypeOk() (*string, bool) { +func (o *KubernetesClusterForPost) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *KubernetesClusterForPost) SetType(v string) { +// SetHref sets field value +func (o *KubernetesClusterForPost) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *KubernetesClusterForPost) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *KubernetesClusterForPost) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesClusterForPost) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterForPost) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterForPost) GetHrefOk() (*string, bool) { +func (o *KubernetesClusterForPost) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *KubernetesClusterForPost) SetHref(v string) { +// SetId sets field value +func (o *KubernetesClusterForPost) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *KubernetesClusterForPost) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *KubernetesClusterForPost) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -162,7 +162,7 @@ func (o *KubernetesClusterForPost) HasHref() bool { } // GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesClusterForPost) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil @@ -200,7 +200,7 @@ func (o *KubernetesClusterForPost) HasMetadata() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for KubernetesClusterPropertiesForPost will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesClusterForPost) GetProperties() *KubernetesClusterPropertiesForPost { if o == nil { return nil @@ -237,38 +237,38 @@ func (o *KubernetesClusterForPost) HasProperties() bool { return false } -// GetEntities returns the Entities field value -// If the value is explicit nil, the zero value for KubernetesClusterEntities will be returned -func (o *KubernetesClusterForPost) GetEntities() *KubernetesClusterEntities { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterForPost) GetType() *string { if o == nil { return nil } - return o.Entities + return o.Type } -// GetEntitiesOk returns a tuple with the Entities field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterForPost) GetEntitiesOk() (*KubernetesClusterEntities, bool) { +func (o *KubernetesClusterForPost) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Entities, true + return o.Type, true } -// SetEntities sets field value -func (o *KubernetesClusterForPost) SetEntities(v KubernetesClusterEntities) { +// SetType sets field value +func (o *KubernetesClusterForPost) SetType(v string) { - o.Entities = &v + o.Type = &v } -// HasEntities returns a boolean if a field has been set. -func (o *KubernetesClusterForPost) HasEntities() bool { - if o != nil && o.Entities != nil { +// HasType returns a boolean if a field has been set. +func (o *KubernetesClusterForPost) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -277,24 +277,30 @@ func (o *KubernetesClusterForPost) HasEntities() bool { func (o KubernetesClusterForPost) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Entities != nil { + toSerialize["entities"] = o.Entities } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } - if o.Entities != nil { - toSerialize["entities"] = o.Entities + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_for_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_for_put.go index 2873bf5c860..6edf7ca5fcc 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_for_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_for_put.go @@ -16,15 +16,15 @@ import ( // KubernetesClusterForPut struct for KubernetesClusterForPut type KubernetesClusterForPut struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object. - Type *string `json:"type,omitempty"` + Entities *KubernetesClusterEntities `json:"entities,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *KubernetesClusterPropertiesForPut `json:"properties"` - Entities *KubernetesClusterEntities `json:"entities,omitempty"` + // The type of object. + Type *string `json:"type,omitempty"` } // NewKubernetesClusterForPut instantiates a new KubernetesClusterForPut object @@ -47,114 +47,114 @@ func NewKubernetesClusterForPutWithDefaults() *KubernetesClusterForPut { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesClusterForPut) GetId() *string { +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterForPut) GetEntities() *KubernetesClusterEntities { if o == nil { return nil } - return o.Id + return o.Entities } -// GetIdOk returns a tuple with the Id field value +// GetEntitiesOk returns a tuple with the Entities field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterForPut) GetIdOk() (*string, bool) { +func (o *KubernetesClusterForPut) GetEntitiesOk() (*KubernetesClusterEntities, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Entities, true } -// SetId sets field value -func (o *KubernetesClusterForPut) SetId(v string) { +// SetEntities sets field value +func (o *KubernetesClusterForPut) SetEntities(v KubernetesClusterEntities) { - o.Id = &v + o.Entities = &v } -// HasId returns a boolean if a field has been set. -func (o *KubernetesClusterForPut) HasId() bool { - if o != nil && o.Id != nil { +// HasEntities returns a boolean if a field has been set. +func (o *KubernetesClusterForPut) HasEntities() bool { + if o != nil && o.Entities != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesClusterForPut) GetType() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterForPut) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterForPut) GetTypeOk() (*string, bool) { +func (o *KubernetesClusterForPut) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *KubernetesClusterForPut) SetType(v string) { +// SetHref sets field value +func (o *KubernetesClusterForPut) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *KubernetesClusterForPut) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *KubernetesClusterForPut) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesClusterForPut) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterForPut) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterForPut) GetHrefOk() (*string, bool) { +func (o *KubernetesClusterForPut) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *KubernetesClusterForPut) SetHref(v string) { +// SetId sets field value +func (o *KubernetesClusterForPut) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *KubernetesClusterForPut) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *KubernetesClusterForPut) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -162,7 +162,7 @@ func (o *KubernetesClusterForPut) HasHref() bool { } // GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesClusterForPut) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil @@ -200,7 +200,7 @@ func (o *KubernetesClusterForPut) HasMetadata() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for KubernetesClusterPropertiesForPut will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesClusterForPut) GetProperties() *KubernetesClusterPropertiesForPut { if o == nil { return nil @@ -237,38 +237,38 @@ func (o *KubernetesClusterForPut) HasProperties() bool { return false } -// GetEntities returns the Entities field value -// If the value is explicit nil, the zero value for KubernetesClusterEntities will be returned -func (o *KubernetesClusterForPut) GetEntities() *KubernetesClusterEntities { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterForPut) GetType() *string { if o == nil { return nil } - return o.Entities + return o.Type } -// GetEntitiesOk returns a tuple with the Entities field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterForPut) GetEntitiesOk() (*KubernetesClusterEntities, bool) { +func (o *KubernetesClusterForPut) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Entities, true + return o.Type, true } -// SetEntities sets field value -func (o *KubernetesClusterForPut) SetEntities(v KubernetesClusterEntities) { +// SetType sets field value +func (o *KubernetesClusterForPut) SetType(v string) { - o.Entities = &v + o.Type = &v } -// HasEntities returns a boolean if a field has been set. -func (o *KubernetesClusterForPut) HasEntities() bool { - if o != nil && o.Entities != nil { +// HasType returns a boolean if a field has been set. +func (o *KubernetesClusterForPut) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -277,24 +277,30 @@ func (o *KubernetesClusterForPut) HasEntities() bool { func (o KubernetesClusterForPut) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Entities != nil { + toSerialize["entities"] = o.Entities } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } - if o.Entities != nil { - toSerialize["entities"] = o.Entities + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_properties.go index d887173623f..66956d3f7bd 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_properties.go @@ -16,19 +16,19 @@ import ( // KubernetesClusterProperties struct for KubernetesClusterProperties type KubernetesClusterProperties struct { - // A Kubernetes cluster name. Valid Kubernetes cluster name must be 63 characters or less and must be empty or begin and end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between. - Name *string `json:"name"` + // Access to the K8s API server is restricted to these CIDRs. Traffic, internal to the cluster, is not affected by this restriction. If no allowlist is specified, access is not restricted. If an IP without subnet mask is provided, the default value is used: 32 for IPv4 and 128 for IPv6. + ApiSubnetAllowList *[]string `json:"apiSubnetAllowList,omitempty"` + // List of available versions for upgrading the cluster + AvailableUpgradeVersions *[]string `json:"availableUpgradeVersions,omitempty"` // The Kubernetes version the cluster is running. This imposes restrictions on what Kubernetes versions can be run in a cluster's nodepools. Additionally, not all Kubernetes versions are viable upgrade targets for all prior versions. K8sVersion *string `json:"k8sVersion,omitempty"` MaintenanceWindow *KubernetesMaintenanceWindow `json:"maintenanceWindow,omitempty"` - // List of available versions for upgrading the cluster - AvailableUpgradeVersions *[]string `json:"availableUpgradeVersions,omitempty"` - // List of versions that may be used for node pools under this cluster - ViableNodePoolVersions *[]string `json:"viableNodePoolVersions,omitempty"` - // Access to the K8s API server is restricted to these CIDRs. Traffic, internal to the cluster, is not affected by this restriction. If no allowlist is specified, access is not restricted. If an IP without subnet mask is provided, the default value is used: 32 for IPv4 and 128 for IPv6. - ApiSubnetAllowList *[]string `json:"apiSubnetAllowList,omitempty"` + // A Kubernetes cluster name. Valid Kubernetes cluster name must be 63 characters or less and must be empty or begin and end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between. + Name *string `json:"name"` // List of S3 bucket configured for K8s usage. For now it contains only an S3 bucket used to store K8s API audit logs S3Buckets *[]S3Bucket `json:"s3Buckets,omitempty"` + // List of versions that may be used for node pools under this cluster + ViableNodePoolVersions *[]string `json:"viableNodePoolVersions,omitempty"` } // NewKubernetesClusterProperties instantiates a new KubernetesClusterProperties object @@ -51,266 +51,266 @@ func NewKubernetesClusterPropertiesWithDefaults() *KubernetesClusterProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesClusterProperties) GetName() *string { +// GetApiSubnetAllowList returns the ApiSubnetAllowList field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterProperties) GetApiSubnetAllowList() *[]string { if o == nil { return nil } - return o.Name + return o.ApiSubnetAllowList } -// GetNameOk returns a tuple with the Name field value +// GetApiSubnetAllowListOk returns a tuple with the ApiSubnetAllowList field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterProperties) GetNameOk() (*string, bool) { +func (o *KubernetesClusterProperties) GetApiSubnetAllowListOk() (*[]string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.ApiSubnetAllowList, true } -// SetName sets field value -func (o *KubernetesClusterProperties) SetName(v string) { +// SetApiSubnetAllowList sets field value +func (o *KubernetesClusterProperties) SetApiSubnetAllowList(v []string) { - o.Name = &v + o.ApiSubnetAllowList = &v } -// HasName returns a boolean if a field has been set. -func (o *KubernetesClusterProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasApiSubnetAllowList returns a boolean if a field has been set. +func (o *KubernetesClusterProperties) HasApiSubnetAllowList() bool { + if o != nil && o.ApiSubnetAllowList != nil { return true } return false } -// GetK8sVersion returns the K8sVersion field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesClusterProperties) GetK8sVersion() *string { +// GetAvailableUpgradeVersions returns the AvailableUpgradeVersions field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterProperties) GetAvailableUpgradeVersions() *[]string { if o == nil { return nil } - return o.K8sVersion + return o.AvailableUpgradeVersions } -// GetK8sVersionOk returns a tuple with the K8sVersion field value +// GetAvailableUpgradeVersionsOk returns a tuple with the AvailableUpgradeVersions field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterProperties) GetK8sVersionOk() (*string, bool) { +func (o *KubernetesClusterProperties) GetAvailableUpgradeVersionsOk() (*[]string, bool) { if o == nil { return nil, false } - return o.K8sVersion, true + return o.AvailableUpgradeVersions, true } -// SetK8sVersion sets field value -func (o *KubernetesClusterProperties) SetK8sVersion(v string) { +// SetAvailableUpgradeVersions sets field value +func (o *KubernetesClusterProperties) SetAvailableUpgradeVersions(v []string) { - o.K8sVersion = &v + o.AvailableUpgradeVersions = &v } -// HasK8sVersion returns a boolean if a field has been set. -func (o *KubernetesClusterProperties) HasK8sVersion() bool { - if o != nil && o.K8sVersion != nil { +// HasAvailableUpgradeVersions returns a boolean if a field has been set. +func (o *KubernetesClusterProperties) HasAvailableUpgradeVersions() bool { + if o != nil && o.AvailableUpgradeVersions != nil { return true } return false } -// GetMaintenanceWindow returns the MaintenanceWindow field value -// If the value is explicit nil, the zero value for KubernetesMaintenanceWindow will be returned -func (o *KubernetesClusterProperties) GetMaintenanceWindow() *KubernetesMaintenanceWindow { +// GetK8sVersion returns the K8sVersion field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterProperties) GetK8sVersion() *string { if o == nil { return nil } - return o.MaintenanceWindow + return o.K8sVersion } -// GetMaintenanceWindowOk returns a tuple with the MaintenanceWindow field value +// GetK8sVersionOk returns a tuple with the K8sVersion field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterProperties) GetMaintenanceWindowOk() (*KubernetesMaintenanceWindow, bool) { +func (o *KubernetesClusterProperties) GetK8sVersionOk() (*string, bool) { if o == nil { return nil, false } - return o.MaintenanceWindow, true + return o.K8sVersion, true } -// SetMaintenanceWindow sets field value -func (o *KubernetesClusterProperties) SetMaintenanceWindow(v KubernetesMaintenanceWindow) { +// SetK8sVersion sets field value +func (o *KubernetesClusterProperties) SetK8sVersion(v string) { - o.MaintenanceWindow = &v + o.K8sVersion = &v } -// HasMaintenanceWindow returns a boolean if a field has been set. -func (o *KubernetesClusterProperties) HasMaintenanceWindow() bool { - if o != nil && o.MaintenanceWindow != nil { +// HasK8sVersion returns a boolean if a field has been set. +func (o *KubernetesClusterProperties) HasK8sVersion() bool { + if o != nil && o.K8sVersion != nil { return true } return false } -// GetAvailableUpgradeVersions returns the AvailableUpgradeVersions field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *KubernetesClusterProperties) GetAvailableUpgradeVersions() *[]string { +// GetMaintenanceWindow returns the MaintenanceWindow field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterProperties) GetMaintenanceWindow() *KubernetesMaintenanceWindow { if o == nil { return nil } - return o.AvailableUpgradeVersions + return o.MaintenanceWindow } -// GetAvailableUpgradeVersionsOk returns a tuple with the AvailableUpgradeVersions field value +// GetMaintenanceWindowOk returns a tuple with the MaintenanceWindow field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterProperties) GetAvailableUpgradeVersionsOk() (*[]string, bool) { +func (o *KubernetesClusterProperties) GetMaintenanceWindowOk() (*KubernetesMaintenanceWindow, bool) { if o == nil { return nil, false } - return o.AvailableUpgradeVersions, true + return o.MaintenanceWindow, true } -// SetAvailableUpgradeVersions sets field value -func (o *KubernetesClusterProperties) SetAvailableUpgradeVersions(v []string) { +// SetMaintenanceWindow sets field value +func (o *KubernetesClusterProperties) SetMaintenanceWindow(v KubernetesMaintenanceWindow) { - o.AvailableUpgradeVersions = &v + o.MaintenanceWindow = &v } -// HasAvailableUpgradeVersions returns a boolean if a field has been set. -func (o *KubernetesClusterProperties) HasAvailableUpgradeVersions() bool { - if o != nil && o.AvailableUpgradeVersions != nil { +// HasMaintenanceWindow returns a boolean if a field has been set. +func (o *KubernetesClusterProperties) HasMaintenanceWindow() bool { + if o != nil && o.MaintenanceWindow != nil { return true } return false } -// GetViableNodePoolVersions returns the ViableNodePoolVersions field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *KubernetesClusterProperties) GetViableNodePoolVersions() *[]string { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterProperties) GetName() *string { if o == nil { return nil } - return o.ViableNodePoolVersions + return o.Name } -// GetViableNodePoolVersionsOk returns a tuple with the ViableNodePoolVersions field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterProperties) GetViableNodePoolVersionsOk() (*[]string, bool) { +func (o *KubernetesClusterProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.ViableNodePoolVersions, true + return o.Name, true } -// SetViableNodePoolVersions sets field value -func (o *KubernetesClusterProperties) SetViableNodePoolVersions(v []string) { +// SetName sets field value +func (o *KubernetesClusterProperties) SetName(v string) { - o.ViableNodePoolVersions = &v + o.Name = &v } -// HasViableNodePoolVersions returns a boolean if a field has been set. -func (o *KubernetesClusterProperties) HasViableNodePoolVersions() bool { - if o != nil && o.ViableNodePoolVersions != nil { +// HasName returns a boolean if a field has been set. +func (o *KubernetesClusterProperties) HasName() bool { + if o != nil && o.Name != nil { return true } return false } -// GetApiSubnetAllowList returns the ApiSubnetAllowList field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *KubernetesClusterProperties) GetApiSubnetAllowList() *[]string { +// GetS3Buckets returns the S3Buckets field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterProperties) GetS3Buckets() *[]S3Bucket { if o == nil { return nil } - return o.ApiSubnetAllowList + return o.S3Buckets } -// GetApiSubnetAllowListOk returns a tuple with the ApiSubnetAllowList field value +// GetS3BucketsOk returns a tuple with the S3Buckets field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterProperties) GetApiSubnetAllowListOk() (*[]string, bool) { +func (o *KubernetesClusterProperties) GetS3BucketsOk() (*[]S3Bucket, bool) { if o == nil { return nil, false } - return o.ApiSubnetAllowList, true + return o.S3Buckets, true } -// SetApiSubnetAllowList sets field value -func (o *KubernetesClusterProperties) SetApiSubnetAllowList(v []string) { +// SetS3Buckets sets field value +func (o *KubernetesClusterProperties) SetS3Buckets(v []S3Bucket) { - o.ApiSubnetAllowList = &v + o.S3Buckets = &v } -// HasApiSubnetAllowList returns a boolean if a field has been set. -func (o *KubernetesClusterProperties) HasApiSubnetAllowList() bool { - if o != nil && o.ApiSubnetAllowList != nil { +// HasS3Buckets returns a boolean if a field has been set. +func (o *KubernetesClusterProperties) HasS3Buckets() bool { + if o != nil && o.S3Buckets != nil { return true } return false } -// GetS3Buckets returns the S3Buckets field value -// If the value is explicit nil, the zero value for []S3Bucket will be returned -func (o *KubernetesClusterProperties) GetS3Buckets() *[]S3Bucket { +// GetViableNodePoolVersions returns the ViableNodePoolVersions field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterProperties) GetViableNodePoolVersions() *[]string { if o == nil { return nil } - return o.S3Buckets + return o.ViableNodePoolVersions } -// GetS3BucketsOk returns a tuple with the S3Buckets field value +// GetViableNodePoolVersionsOk returns a tuple with the ViableNodePoolVersions field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterProperties) GetS3BucketsOk() (*[]S3Bucket, bool) { +func (o *KubernetesClusterProperties) GetViableNodePoolVersionsOk() (*[]string, bool) { if o == nil { return nil, false } - return o.S3Buckets, true + return o.ViableNodePoolVersions, true } -// SetS3Buckets sets field value -func (o *KubernetesClusterProperties) SetS3Buckets(v []S3Bucket) { +// SetViableNodePoolVersions sets field value +func (o *KubernetesClusterProperties) SetViableNodePoolVersions(v []string) { - o.S3Buckets = &v + o.ViableNodePoolVersions = &v } -// HasS3Buckets returns a boolean if a field has been set. -func (o *KubernetesClusterProperties) HasS3Buckets() bool { - if o != nil && o.S3Buckets != nil { +// HasViableNodePoolVersions returns a boolean if a field has been set. +func (o *KubernetesClusterProperties) HasViableNodePoolVersions() bool { + if o != nil && o.ViableNodePoolVersions != nil { return true } @@ -319,27 +319,34 @@ func (o *KubernetesClusterProperties) HasS3Buckets() bool { func (o KubernetesClusterProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name + if o.ApiSubnetAllowList != nil { + toSerialize["apiSubnetAllowList"] = o.ApiSubnetAllowList + } + + if o.AvailableUpgradeVersions != nil { + toSerialize["availableUpgradeVersions"] = o.AvailableUpgradeVersions } + if o.K8sVersion != nil { toSerialize["k8sVersion"] = o.K8sVersion } + if o.MaintenanceWindow != nil { toSerialize["maintenanceWindow"] = o.MaintenanceWindow } - if o.AvailableUpgradeVersions != nil { - toSerialize["availableUpgradeVersions"] = o.AvailableUpgradeVersions - } - if o.ViableNodePoolVersions != nil { - toSerialize["viableNodePoolVersions"] = o.ViableNodePoolVersions - } - if o.ApiSubnetAllowList != nil { - toSerialize["apiSubnetAllowList"] = o.ApiSubnetAllowList + + if o.Name != nil { + toSerialize["name"] = o.Name } + if o.S3Buckets != nil { toSerialize["s3Buckets"] = o.S3Buckets } + + if o.ViableNodePoolVersions != nil { + toSerialize["viableNodePoolVersions"] = o.ViableNodePoolVersions + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_properties_for_post.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_properties_for_post.go index b44a3227aeb..9215373b9ce 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_properties_for_post.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_properties_for_post.go @@ -16,13 +16,13 @@ import ( // KubernetesClusterPropertiesForPost struct for KubernetesClusterPropertiesForPost type KubernetesClusterPropertiesForPost struct { - // A Kubernetes cluster name. Valid Kubernetes cluster name must be 63 characters or less and must be empty or begin and end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between. - Name *string `json:"name"` + // Access to the K8s API server is restricted to these CIDRs. Intra-cluster traffic is not affected by this restriction. If no AllowList is specified, access is not limited. If an IP is specified without a subnet mask, the default value is 32 for IPv4 and 128 for IPv6. + ApiSubnetAllowList *[]string `json:"apiSubnetAllowList,omitempty"` // The Kubernetes version that the cluster is running. This limits which Kubernetes versions can run in a cluster's node pools. Also, not all Kubernetes versions are suitable upgrade targets for all earlier versions. K8sVersion *string `json:"k8sVersion,omitempty"` MaintenanceWindow *KubernetesMaintenanceWindow `json:"maintenanceWindow,omitempty"` - // Access to the K8s API server is restricted to these CIDRs. Intra-cluster traffic is not affected by this restriction. If no AllowList is specified, access is not limited. If an IP is specified without a subnet mask, the default value is 32 for IPv4 and 128 for IPv6. - ApiSubnetAllowList *[]string `json:"apiSubnetAllowList,omitempty"` + // A Kubernetes cluster name. Valid Kubernetes cluster name must be 63 characters or less and must be empty or begin and end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between. + Name *string `json:"name"` // List of S3 buckets configured for K8s usage. At the moment, it contains only one S3 bucket that is used to store K8s API audit logs. S3Buckets *[]S3Bucket `json:"s3Buckets,omitempty"` } @@ -47,38 +47,38 @@ func NewKubernetesClusterPropertiesForPostWithDefaults() *KubernetesClusterPrope return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesClusterPropertiesForPost) GetName() *string { +// GetApiSubnetAllowList returns the ApiSubnetAllowList field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterPropertiesForPost) GetApiSubnetAllowList() *[]string { if o == nil { return nil } - return o.Name + return o.ApiSubnetAllowList } -// GetNameOk returns a tuple with the Name field value +// GetApiSubnetAllowListOk returns a tuple with the ApiSubnetAllowList field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterPropertiesForPost) GetNameOk() (*string, bool) { +func (o *KubernetesClusterPropertiesForPost) GetApiSubnetAllowListOk() (*[]string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.ApiSubnetAllowList, true } -// SetName sets field value -func (o *KubernetesClusterPropertiesForPost) SetName(v string) { +// SetApiSubnetAllowList sets field value +func (o *KubernetesClusterPropertiesForPost) SetApiSubnetAllowList(v []string) { - o.Name = &v + o.ApiSubnetAllowList = &v } -// HasName returns a boolean if a field has been set. -func (o *KubernetesClusterPropertiesForPost) HasName() bool { - if o != nil && o.Name != nil { +// HasApiSubnetAllowList returns a boolean if a field has been set. +func (o *KubernetesClusterPropertiesForPost) HasApiSubnetAllowList() bool { + if o != nil && o.ApiSubnetAllowList != nil { return true } @@ -86,7 +86,7 @@ func (o *KubernetesClusterPropertiesForPost) HasName() bool { } // GetK8sVersion returns the K8sVersion field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesClusterPropertiesForPost) GetK8sVersion() *string { if o == nil { return nil @@ -124,7 +124,7 @@ func (o *KubernetesClusterPropertiesForPost) HasK8sVersion() bool { } // GetMaintenanceWindow returns the MaintenanceWindow field value -// If the value is explicit nil, the zero value for KubernetesMaintenanceWindow will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesClusterPropertiesForPost) GetMaintenanceWindow() *KubernetesMaintenanceWindow { if o == nil { return nil @@ -161,38 +161,38 @@ func (o *KubernetesClusterPropertiesForPost) HasMaintenanceWindow() bool { return false } -// GetApiSubnetAllowList returns the ApiSubnetAllowList field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *KubernetesClusterPropertiesForPost) GetApiSubnetAllowList() *[]string { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterPropertiesForPost) GetName() *string { if o == nil { return nil } - return o.ApiSubnetAllowList + return o.Name } -// GetApiSubnetAllowListOk returns a tuple with the ApiSubnetAllowList field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterPropertiesForPost) GetApiSubnetAllowListOk() (*[]string, bool) { +func (o *KubernetesClusterPropertiesForPost) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.ApiSubnetAllowList, true + return o.Name, true } -// SetApiSubnetAllowList sets field value -func (o *KubernetesClusterPropertiesForPost) SetApiSubnetAllowList(v []string) { +// SetName sets field value +func (o *KubernetesClusterPropertiesForPost) SetName(v string) { - o.ApiSubnetAllowList = &v + o.Name = &v } -// HasApiSubnetAllowList returns a boolean if a field has been set. -func (o *KubernetesClusterPropertiesForPost) HasApiSubnetAllowList() bool { - if o != nil && o.ApiSubnetAllowList != nil { +// HasName returns a boolean if a field has been set. +func (o *KubernetesClusterPropertiesForPost) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -200,7 +200,7 @@ func (o *KubernetesClusterPropertiesForPost) HasApiSubnetAllowList() bool { } // GetS3Buckets returns the S3Buckets field value -// If the value is explicit nil, the zero value for []S3Bucket will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesClusterPropertiesForPost) GetS3Buckets() *[]S3Bucket { if o == nil { return nil @@ -239,21 +239,26 @@ func (o *KubernetesClusterPropertiesForPost) HasS3Buckets() bool { func (o KubernetesClusterPropertiesForPost) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name + if o.ApiSubnetAllowList != nil { + toSerialize["apiSubnetAllowList"] = o.ApiSubnetAllowList } + if o.K8sVersion != nil { toSerialize["k8sVersion"] = o.K8sVersion } + if o.MaintenanceWindow != nil { toSerialize["maintenanceWindow"] = o.MaintenanceWindow } - if o.ApiSubnetAllowList != nil { - toSerialize["apiSubnetAllowList"] = o.ApiSubnetAllowList + + if o.Name != nil { + toSerialize["name"] = o.Name } + if o.S3Buckets != nil { toSerialize["s3Buckets"] = o.S3Buckets } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_properties_for_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_properties_for_put.go index c2b9d44cdea..b2bc4980d7c 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_properties_for_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_cluster_properties_for_put.go @@ -16,13 +16,13 @@ import ( // KubernetesClusterPropertiesForPut struct for KubernetesClusterPropertiesForPut type KubernetesClusterPropertiesForPut struct { - // A Kubernetes cluster name. Valid Kubernetes cluster name must be 63 characters or less and must be empty or begin and end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between. - Name *string `json:"name"` + // Access to the K8s API server is restricted to these CIDRs. Intra-cluster traffic is not affected by this restriction. If no AllowList is specified, access is not limited. If an IP is specified without a subnet mask, the default value is 32 for IPv4 and 128 for IPv6. + ApiSubnetAllowList *[]string `json:"apiSubnetAllowList,omitempty"` // The Kubernetes version that the cluster is running. This limits which Kubernetes versions can run in a cluster's node pools. Also, not all Kubernetes versions are suitable upgrade targets for all earlier versions. K8sVersion *string `json:"k8sVersion,omitempty"` MaintenanceWindow *KubernetesMaintenanceWindow `json:"maintenanceWindow,omitempty"` - // Access to the K8s API server is restricted to these CIDRs. Intra-cluster traffic is not affected by this restriction. If no AllowList is specified, access is not limited. If an IP is specified without a subnet mask, the default value is 32 for IPv4 and 128 for IPv6. - ApiSubnetAllowList *[]string `json:"apiSubnetAllowList,omitempty"` + // A Kubernetes cluster name. Valid Kubernetes cluster name must be 63 characters or less and must be empty or begin and end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between. + Name *string `json:"name"` // List of S3 buckets configured for K8s usage. At the moment, it contains only one S3 bucket that is used to store K8s API audit logs. S3Buckets *[]S3Bucket `json:"s3Buckets,omitempty"` } @@ -47,38 +47,38 @@ func NewKubernetesClusterPropertiesForPutWithDefaults() *KubernetesClusterProper return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesClusterPropertiesForPut) GetName() *string { +// GetApiSubnetAllowList returns the ApiSubnetAllowList field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterPropertiesForPut) GetApiSubnetAllowList() *[]string { if o == nil { return nil } - return o.Name + return o.ApiSubnetAllowList } -// GetNameOk returns a tuple with the Name field value +// GetApiSubnetAllowListOk returns a tuple with the ApiSubnetAllowList field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterPropertiesForPut) GetNameOk() (*string, bool) { +func (o *KubernetesClusterPropertiesForPut) GetApiSubnetAllowListOk() (*[]string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.ApiSubnetAllowList, true } -// SetName sets field value -func (o *KubernetesClusterPropertiesForPut) SetName(v string) { +// SetApiSubnetAllowList sets field value +func (o *KubernetesClusterPropertiesForPut) SetApiSubnetAllowList(v []string) { - o.Name = &v + o.ApiSubnetAllowList = &v } -// HasName returns a boolean if a field has been set. -func (o *KubernetesClusterPropertiesForPut) HasName() bool { - if o != nil && o.Name != nil { +// HasApiSubnetAllowList returns a boolean if a field has been set. +func (o *KubernetesClusterPropertiesForPut) HasApiSubnetAllowList() bool { + if o != nil && o.ApiSubnetAllowList != nil { return true } @@ -86,7 +86,7 @@ func (o *KubernetesClusterPropertiesForPut) HasName() bool { } // GetK8sVersion returns the K8sVersion field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesClusterPropertiesForPut) GetK8sVersion() *string { if o == nil { return nil @@ -124,7 +124,7 @@ func (o *KubernetesClusterPropertiesForPut) HasK8sVersion() bool { } // GetMaintenanceWindow returns the MaintenanceWindow field value -// If the value is explicit nil, the zero value for KubernetesMaintenanceWindow will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesClusterPropertiesForPut) GetMaintenanceWindow() *KubernetesMaintenanceWindow { if o == nil { return nil @@ -161,38 +161,38 @@ func (o *KubernetesClusterPropertiesForPut) HasMaintenanceWindow() bool { return false } -// GetApiSubnetAllowList returns the ApiSubnetAllowList field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *KubernetesClusterPropertiesForPut) GetApiSubnetAllowList() *[]string { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusterPropertiesForPut) GetName() *string { if o == nil { return nil } - return o.ApiSubnetAllowList + return o.Name } -// GetApiSubnetAllowListOk returns a tuple with the ApiSubnetAllowList field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusterPropertiesForPut) GetApiSubnetAllowListOk() (*[]string, bool) { +func (o *KubernetesClusterPropertiesForPut) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.ApiSubnetAllowList, true + return o.Name, true } -// SetApiSubnetAllowList sets field value -func (o *KubernetesClusterPropertiesForPut) SetApiSubnetAllowList(v []string) { +// SetName sets field value +func (o *KubernetesClusterPropertiesForPut) SetName(v string) { - o.ApiSubnetAllowList = &v + o.Name = &v } -// HasApiSubnetAllowList returns a boolean if a field has been set. -func (o *KubernetesClusterPropertiesForPut) HasApiSubnetAllowList() bool { - if o != nil && o.ApiSubnetAllowList != nil { +// HasName returns a boolean if a field has been set. +func (o *KubernetesClusterPropertiesForPut) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -200,7 +200,7 @@ func (o *KubernetesClusterPropertiesForPut) HasApiSubnetAllowList() bool { } // GetS3Buckets returns the S3Buckets field value -// If the value is explicit nil, the zero value for []S3Bucket will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesClusterPropertiesForPut) GetS3Buckets() *[]S3Bucket { if o == nil { return nil @@ -239,21 +239,26 @@ func (o *KubernetesClusterPropertiesForPut) HasS3Buckets() bool { func (o KubernetesClusterPropertiesForPut) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name + if o.ApiSubnetAllowList != nil { + toSerialize["apiSubnetAllowList"] = o.ApiSubnetAllowList } + if o.K8sVersion != nil { toSerialize["k8sVersion"] = o.K8sVersion } + if o.MaintenanceWindow != nil { toSerialize["maintenanceWindow"] = o.MaintenanceWindow } - if o.ApiSubnetAllowList != nil { - toSerialize["apiSubnetAllowList"] = o.ApiSubnetAllowList + + if o.Name != nil { + toSerialize["name"] = o.Name } + if o.S3Buckets != nil { toSerialize["s3Buckets"] = o.S3Buckets } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_clusters.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_clusters.go index f1416d0eb8f..84f19c35cc5 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_clusters.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_clusters.go @@ -16,14 +16,14 @@ import ( // KubernetesClusters struct for KubernetesClusters type KubernetesClusters struct { - // The unique representation of the K8s cluster as a resource collection. - Id *string `json:"id,omitempty"` - // The resource type within a collection. - Type *string `json:"type,omitempty"` // The URL to the collection representation (absolute path). Href *string `json:"href,omitempty"` + // The unique representation of the K8s cluster as a resource collection. + Id *string `json:"id,omitempty"` // Array of K8s clusters in the collection. Items *[]KubernetesCluster `json:"items,omitempty"` + // The resource type within a collection. + Type *string `json:"type,omitempty"` } // NewKubernetesClusters instantiates a new KubernetesClusters object @@ -44,152 +44,152 @@ func NewKubernetesClustersWithDefaults() *KubernetesClusters { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesClusters) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusters) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusters) GetIdOk() (*string, bool) { +func (o *KubernetesClusters) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *KubernetesClusters) SetId(v string) { +// SetHref sets field value +func (o *KubernetesClusters) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *KubernetesClusters) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *KubernetesClusters) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesClusters) GetType() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusters) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusters) GetTypeOk() (*string, bool) { +func (o *KubernetesClusters) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *KubernetesClusters) SetType(v string) { +// SetId sets field value +func (o *KubernetesClusters) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *KubernetesClusters) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *KubernetesClusters) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesClusters) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusters) GetItems() *[]KubernetesCluster { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusters) GetHrefOk() (*string, bool) { +func (o *KubernetesClusters) GetItemsOk() (*[]KubernetesCluster, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *KubernetesClusters) SetHref(v string) { +// SetItems sets field value +func (o *KubernetesClusters) SetItems(v []KubernetesCluster) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *KubernetesClusters) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *KubernetesClusters) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []KubernetesCluster will be returned -func (o *KubernetesClusters) GetItems() *[]KubernetesCluster { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *KubernetesClusters) GetType() *string { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesClusters) GetItemsOk() (*[]KubernetesCluster, bool) { +func (o *KubernetesClusters) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *KubernetesClusters) SetItems(v []KubernetesCluster) { +// SetType sets field value +func (o *KubernetesClusters) SetType(v string) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *KubernetesClusters) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *KubernetesClusters) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *KubernetesClusters) HasItems() bool { func (o KubernetesClusters) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_maintenance_window.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_maintenance_window.go index d5decee54ca..86d57625344 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_maintenance_window.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_maintenance_window.go @@ -44,7 +44,7 @@ func NewKubernetesMaintenanceWindowWithDefaults() *KubernetesMaintenanceWindow { } // GetDayOfTheWeek returns the DayOfTheWeek field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesMaintenanceWindow) GetDayOfTheWeek() *string { if o == nil { return nil @@ -82,7 +82,7 @@ func (o *KubernetesMaintenanceWindow) HasDayOfTheWeek() bool { } // GetTime returns the Time field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesMaintenanceWindow) GetTime() *string { if o == nil { return nil @@ -124,9 +124,11 @@ func (o KubernetesMaintenanceWindow) MarshalJSON() ([]byte, error) { if o.DayOfTheWeek != nil { toSerialize["dayOfTheWeek"] = o.DayOfTheWeek } + if o.Time != nil { toSerialize["time"] = o.Time } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node.go index 936864aeca7..512c52312df 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node.go @@ -16,14 +16,14 @@ import ( // KubernetesNode struct for KubernetesNode type KubernetesNode struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The object type. - Type *string `json:"type,omitempty"` // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *KubernetesNodeMetadata `json:"metadata,omitempty"` Properties *KubernetesNodeProperties `json:"properties"` + // The object type. + Type *string `json:"type,omitempty"` } // NewKubernetesNode instantiates a new KubernetesNode object @@ -46,190 +46,190 @@ func NewKubernetesNodeWithDefaults() *KubernetesNode { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNode) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNode) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNode) GetIdOk() (*string, bool) { +func (o *KubernetesNode) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *KubernetesNode) SetId(v string) { +// SetHref sets field value +func (o *KubernetesNode) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *KubernetesNode) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *KubernetesNode) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNode) GetType() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNode) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNode) GetTypeOk() (*string, bool) { +func (o *KubernetesNode) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *KubernetesNode) SetType(v string) { +// SetId sets field value +func (o *KubernetesNode) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *KubernetesNode) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *KubernetesNode) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNode) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNode) GetMetadata() *KubernetesNodeMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNode) GetHrefOk() (*string, bool) { +func (o *KubernetesNode) GetMetadataOk() (*KubernetesNodeMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *KubernetesNode) SetHref(v string) { +// SetMetadata sets field value +func (o *KubernetesNode) SetMetadata(v KubernetesNodeMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *KubernetesNode) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *KubernetesNode) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for KubernetesNodeMetadata will be returned -func (o *KubernetesNode) GetMetadata() *KubernetesNodeMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNode) GetProperties() *KubernetesNodeProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNode) GetMetadataOk() (*KubernetesNodeMetadata, bool) { +func (o *KubernetesNode) GetPropertiesOk() (*KubernetesNodeProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *KubernetesNode) SetMetadata(v KubernetesNodeMetadata) { +// SetProperties sets field value +func (o *KubernetesNode) SetProperties(v KubernetesNodeProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *KubernetesNode) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *KubernetesNode) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for KubernetesNodeProperties will be returned -func (o *KubernetesNode) GetProperties() *KubernetesNodeProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNode) GetType() *string { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNode) GetPropertiesOk() (*KubernetesNodeProperties, bool) { +func (o *KubernetesNode) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *KubernetesNode) SetProperties(v KubernetesNodeProperties) { +// SetType sets field value +func (o *KubernetesNode) SetType(v string) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *KubernetesNode) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *KubernetesNode) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *KubernetesNode) HasProperties() bool { func (o KubernetesNode) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_metadata.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_metadata.go index 8110ddd61aa..3915ed80386 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_metadata.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_metadata.go @@ -17,16 +17,16 @@ import ( // KubernetesNodeMetadata struct for KubernetesNodeMetadata type KubernetesNodeMetadata struct { - // The resource entity tag as defined in http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11 Entity tags are also added as 'ETag' response headers to requests that do not use the 'depth' parameter. - Etag *string `json:"etag,omitempty"` // The date the resource was created. CreatedDate *IonosTime + // The resource entity tag as defined in http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11 Entity tags are also added as 'ETag' response headers to requests that do not use the 'depth' parameter. + Etag *string `json:"etag,omitempty"` // The date the resource was last modified. LastModifiedDate *IonosTime - // The resource state. - State *string `json:"state,omitempty"` // The date when the software on the node was last updated. LastSoftwareUpdatedDate *IonosTime + // The resource state. + State *string `json:"state,omitempty"` } // NewKubernetesNodeMetadata instantiates a new KubernetesNodeMetadata object @@ -47,83 +47,83 @@ func NewKubernetesNodeMetadataWithDefaults() *KubernetesNodeMetadata { return &this } -// GetEtag returns the Etag field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodeMetadata) GetEtag() *string { +// GetCreatedDate returns the CreatedDate field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodeMetadata) GetCreatedDate() *time.Time { if o == nil { return nil } - return o.Etag + if o.CreatedDate == nil { + return nil + } + return &o.CreatedDate.Time } -// GetEtagOk returns a tuple with the Etag field value +// GetCreatedDateOk returns a tuple with the CreatedDate field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodeMetadata) GetEtagOk() (*string, bool) { +func (o *KubernetesNodeMetadata) GetCreatedDateOk() (*time.Time, bool) { if o == nil { return nil, false } - return o.Etag, true + if o.CreatedDate == nil { + return nil, false + } + return &o.CreatedDate.Time, true + } -// SetEtag sets field value -func (o *KubernetesNodeMetadata) SetEtag(v string) { +// SetCreatedDate sets field value +func (o *KubernetesNodeMetadata) SetCreatedDate(v time.Time) { - o.Etag = &v + o.CreatedDate = &IonosTime{v} } -// HasEtag returns a boolean if a field has been set. -func (o *KubernetesNodeMetadata) HasEtag() bool { - if o != nil && o.Etag != nil { +// HasCreatedDate returns a boolean if a field has been set. +func (o *KubernetesNodeMetadata) HasCreatedDate() bool { + if o != nil && o.CreatedDate != nil { return true } return false } -// GetCreatedDate returns the CreatedDate field value -// If the value is explicit nil, the zero value for time.Time will be returned -func (o *KubernetesNodeMetadata) GetCreatedDate() *time.Time { +// GetEtag returns the Etag field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodeMetadata) GetEtag() *string { if o == nil { return nil } - if o.CreatedDate == nil { - return nil - } - return &o.CreatedDate.Time + return o.Etag } -// GetCreatedDateOk returns a tuple with the CreatedDate field value +// GetEtagOk returns a tuple with the Etag field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodeMetadata) GetCreatedDateOk() (*time.Time, bool) { +func (o *KubernetesNodeMetadata) GetEtagOk() (*string, bool) { if o == nil { return nil, false } - if o.CreatedDate == nil { - return nil, false - } - return &o.CreatedDate.Time, true - + return o.Etag, true } -// SetCreatedDate sets field value -func (o *KubernetesNodeMetadata) SetCreatedDate(v time.Time) { +// SetEtag sets field value +func (o *KubernetesNodeMetadata) SetEtag(v string) { - o.CreatedDate = &IonosTime{v} + o.Etag = &v } -// HasCreatedDate returns a boolean if a field has been set. -func (o *KubernetesNodeMetadata) HasCreatedDate() bool { - if o != nil && o.CreatedDate != nil { +// HasEtag returns a boolean if a field has been set. +func (o *KubernetesNodeMetadata) HasEtag() bool { + if o != nil && o.Etag != nil { return true } @@ -131,7 +131,7 @@ func (o *KubernetesNodeMetadata) HasCreatedDate() bool { } // GetLastModifiedDate returns the LastModifiedDate field value -// If the value is explicit nil, the zero value for time.Time will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesNodeMetadata) GetLastModifiedDate() *time.Time { if o == nil { return nil @@ -175,83 +175,83 @@ func (o *KubernetesNodeMetadata) HasLastModifiedDate() bool { return false } -// GetState returns the State field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodeMetadata) GetState() *string { +// GetLastSoftwareUpdatedDate returns the LastSoftwareUpdatedDate field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodeMetadata) GetLastSoftwareUpdatedDate() *time.Time { if o == nil { return nil } - return o.State + if o.LastSoftwareUpdatedDate == nil { + return nil + } + return &o.LastSoftwareUpdatedDate.Time } -// GetStateOk returns a tuple with the State field value +// GetLastSoftwareUpdatedDateOk returns a tuple with the LastSoftwareUpdatedDate field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodeMetadata) GetStateOk() (*string, bool) { +func (o *KubernetesNodeMetadata) GetLastSoftwareUpdatedDateOk() (*time.Time, bool) { if o == nil { return nil, false } - return o.State, true + if o.LastSoftwareUpdatedDate == nil { + return nil, false + } + return &o.LastSoftwareUpdatedDate.Time, true + } -// SetState sets field value -func (o *KubernetesNodeMetadata) SetState(v string) { +// SetLastSoftwareUpdatedDate sets field value +func (o *KubernetesNodeMetadata) SetLastSoftwareUpdatedDate(v time.Time) { - o.State = &v + o.LastSoftwareUpdatedDate = &IonosTime{v} } -// HasState returns a boolean if a field has been set. -func (o *KubernetesNodeMetadata) HasState() bool { - if o != nil && o.State != nil { +// HasLastSoftwareUpdatedDate returns a boolean if a field has been set. +func (o *KubernetesNodeMetadata) HasLastSoftwareUpdatedDate() bool { + if o != nil && o.LastSoftwareUpdatedDate != nil { return true } return false } -// GetLastSoftwareUpdatedDate returns the LastSoftwareUpdatedDate field value -// If the value is explicit nil, the zero value for time.Time will be returned -func (o *KubernetesNodeMetadata) GetLastSoftwareUpdatedDate() *time.Time { +// GetState returns the State field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodeMetadata) GetState() *string { if o == nil { return nil } - if o.LastSoftwareUpdatedDate == nil { - return nil - } - return &o.LastSoftwareUpdatedDate.Time + return o.State } -// GetLastSoftwareUpdatedDateOk returns a tuple with the LastSoftwareUpdatedDate field value +// GetStateOk returns a tuple with the State field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodeMetadata) GetLastSoftwareUpdatedDateOk() (*time.Time, bool) { +func (o *KubernetesNodeMetadata) GetStateOk() (*string, bool) { if o == nil { return nil, false } - if o.LastSoftwareUpdatedDate == nil { - return nil, false - } - return &o.LastSoftwareUpdatedDate.Time, true - + return o.State, true } -// SetLastSoftwareUpdatedDate sets field value -func (o *KubernetesNodeMetadata) SetLastSoftwareUpdatedDate(v time.Time) { +// SetState sets field value +func (o *KubernetesNodeMetadata) SetState(v string) { - o.LastSoftwareUpdatedDate = &IonosTime{v} + o.State = &v } -// HasLastSoftwareUpdatedDate returns a boolean if a field has been set. -func (o *KubernetesNodeMetadata) HasLastSoftwareUpdatedDate() bool { - if o != nil && o.LastSoftwareUpdatedDate != nil { +// HasState returns a boolean if a field has been set. +func (o *KubernetesNodeMetadata) HasState() bool { + if o != nil && o.State != nil { return true } @@ -260,21 +260,26 @@ func (o *KubernetesNodeMetadata) HasLastSoftwareUpdatedDate() bool { func (o KubernetesNodeMetadata) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Etag != nil { - toSerialize["etag"] = o.Etag - } if o.CreatedDate != nil { toSerialize["createdDate"] = o.CreatedDate } + + if o.Etag != nil { + toSerialize["etag"] = o.Etag + } + if o.LastModifiedDate != nil { toSerialize["lastModifiedDate"] = o.LastModifiedDate } - if o.State != nil { - toSerialize["state"] = o.State - } + if o.LastSoftwareUpdatedDate != nil { toSerialize["lastSoftwareUpdatedDate"] = o.LastSoftwareUpdatedDate } + + if o.State != nil { + toSerialize["state"] = o.State + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool.go index a634f0a8b65..9649a8ad842 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool.go @@ -16,14 +16,14 @@ import ( // KubernetesNodePool struct for KubernetesNodePool type KubernetesNodePool struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The object type. - Type *string `json:"type,omitempty"` // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *KubernetesNodePoolProperties `json:"properties"` + // The object type. + Type *string `json:"type,omitempty"` } // NewKubernetesNodePool instantiates a new KubernetesNodePool object @@ -46,190 +46,190 @@ func NewKubernetesNodePoolWithDefaults() *KubernetesNodePool { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePool) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePool) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePool) GetIdOk() (*string, bool) { +func (o *KubernetesNodePool) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *KubernetesNodePool) SetId(v string) { +// SetHref sets field value +func (o *KubernetesNodePool) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *KubernetesNodePool) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *KubernetesNodePool) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePool) GetType() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePool) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePool) GetTypeOk() (*string, bool) { +func (o *KubernetesNodePool) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *KubernetesNodePool) SetType(v string) { +// SetId sets field value +func (o *KubernetesNodePool) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *KubernetesNodePool) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *KubernetesNodePool) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePool) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePool) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePool) GetHrefOk() (*string, bool) { +func (o *KubernetesNodePool) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *KubernetesNodePool) SetHref(v string) { +// SetMetadata sets field value +func (o *KubernetesNodePool) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *KubernetesNodePool) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *KubernetesNodePool) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *KubernetesNodePool) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePool) GetProperties() *KubernetesNodePoolProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePool) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *KubernetesNodePool) GetPropertiesOk() (*KubernetesNodePoolProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *KubernetesNodePool) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *KubernetesNodePool) SetProperties(v KubernetesNodePoolProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *KubernetesNodePool) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *KubernetesNodePool) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for KubernetesNodePoolProperties will be returned -func (o *KubernetesNodePool) GetProperties() *KubernetesNodePoolProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePool) GetType() *string { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePool) GetPropertiesOk() (*KubernetesNodePoolProperties, bool) { +func (o *KubernetesNodePool) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *KubernetesNodePool) SetProperties(v KubernetesNodePoolProperties) { +// SetType sets field value +func (o *KubernetesNodePool) SetType(v string) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *KubernetesNodePool) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *KubernetesNodePool) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *KubernetesNodePool) HasProperties() bool { func (o KubernetesNodePool) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_for_post.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_for_post.go index 9a89d3d18bc..afeef99c7c7 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_for_post.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_for_post.go @@ -16,14 +16,14 @@ import ( // KubernetesNodePoolForPost struct for KubernetesNodePoolForPost type KubernetesNodePoolForPost struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The object type. - Type *string `json:"type,omitempty"` // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *KubernetesNodePoolPropertiesForPost `json:"properties"` + // The object type. + Type *string `json:"type,omitempty"` } // NewKubernetesNodePoolForPost instantiates a new KubernetesNodePoolForPost object @@ -46,190 +46,190 @@ func NewKubernetesNodePoolForPostWithDefaults() *KubernetesNodePoolForPost { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolForPost) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolForPost) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolForPost) GetIdOk() (*string, bool) { +func (o *KubernetesNodePoolForPost) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *KubernetesNodePoolForPost) SetId(v string) { +// SetHref sets field value +func (o *KubernetesNodePoolForPost) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *KubernetesNodePoolForPost) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *KubernetesNodePoolForPost) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolForPost) GetType() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolForPost) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolForPost) GetTypeOk() (*string, bool) { +func (o *KubernetesNodePoolForPost) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *KubernetesNodePoolForPost) SetType(v string) { +// SetId sets field value +func (o *KubernetesNodePoolForPost) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *KubernetesNodePoolForPost) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *KubernetesNodePoolForPost) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolForPost) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolForPost) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolForPost) GetHrefOk() (*string, bool) { +func (o *KubernetesNodePoolForPost) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *KubernetesNodePoolForPost) SetHref(v string) { +// SetMetadata sets field value +func (o *KubernetesNodePoolForPost) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *KubernetesNodePoolForPost) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *KubernetesNodePoolForPost) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *KubernetesNodePoolForPost) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolForPost) GetProperties() *KubernetesNodePoolPropertiesForPost { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolForPost) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *KubernetesNodePoolForPost) GetPropertiesOk() (*KubernetesNodePoolPropertiesForPost, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *KubernetesNodePoolForPost) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *KubernetesNodePoolForPost) SetProperties(v KubernetesNodePoolPropertiesForPost) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *KubernetesNodePoolForPost) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *KubernetesNodePoolForPost) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for KubernetesNodePoolPropertiesForPost will be returned -func (o *KubernetesNodePoolForPost) GetProperties() *KubernetesNodePoolPropertiesForPost { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolForPost) GetType() *string { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolForPost) GetPropertiesOk() (*KubernetesNodePoolPropertiesForPost, bool) { +func (o *KubernetesNodePoolForPost) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *KubernetesNodePoolForPost) SetProperties(v KubernetesNodePoolPropertiesForPost) { +// SetType sets field value +func (o *KubernetesNodePoolForPost) SetType(v string) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *KubernetesNodePoolForPost) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *KubernetesNodePoolForPost) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *KubernetesNodePoolForPost) HasProperties() bool { func (o KubernetesNodePoolForPost) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_for_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_for_put.go index 10fa4f29057..94df03dd911 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_for_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_for_put.go @@ -16,14 +16,14 @@ import ( // KubernetesNodePoolForPut struct for KubernetesNodePoolForPut type KubernetesNodePoolForPut struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The object type. - Type *string `json:"type,omitempty"` // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *KubernetesNodePoolPropertiesForPut `json:"properties"` + // The object type. + Type *string `json:"type,omitempty"` } // NewKubernetesNodePoolForPut instantiates a new KubernetesNodePoolForPut object @@ -46,190 +46,190 @@ func NewKubernetesNodePoolForPutWithDefaults() *KubernetesNodePoolForPut { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolForPut) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolForPut) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolForPut) GetIdOk() (*string, bool) { +func (o *KubernetesNodePoolForPut) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *KubernetesNodePoolForPut) SetId(v string) { +// SetHref sets field value +func (o *KubernetesNodePoolForPut) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *KubernetesNodePoolForPut) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *KubernetesNodePoolForPut) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolForPut) GetType() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolForPut) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolForPut) GetTypeOk() (*string, bool) { +func (o *KubernetesNodePoolForPut) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *KubernetesNodePoolForPut) SetType(v string) { +// SetId sets field value +func (o *KubernetesNodePoolForPut) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *KubernetesNodePoolForPut) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *KubernetesNodePoolForPut) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolForPut) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolForPut) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolForPut) GetHrefOk() (*string, bool) { +func (o *KubernetesNodePoolForPut) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *KubernetesNodePoolForPut) SetHref(v string) { +// SetMetadata sets field value +func (o *KubernetesNodePoolForPut) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *KubernetesNodePoolForPut) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *KubernetesNodePoolForPut) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *KubernetesNodePoolForPut) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolForPut) GetProperties() *KubernetesNodePoolPropertiesForPut { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolForPut) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *KubernetesNodePoolForPut) GetPropertiesOk() (*KubernetesNodePoolPropertiesForPut, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *KubernetesNodePoolForPut) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *KubernetesNodePoolForPut) SetProperties(v KubernetesNodePoolPropertiesForPut) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *KubernetesNodePoolForPut) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *KubernetesNodePoolForPut) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for KubernetesNodePoolPropertiesForPut will be returned -func (o *KubernetesNodePoolForPut) GetProperties() *KubernetesNodePoolPropertiesForPut { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolForPut) GetType() *string { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolForPut) GetPropertiesOk() (*KubernetesNodePoolPropertiesForPut, bool) { +func (o *KubernetesNodePoolForPut) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *KubernetesNodePoolForPut) SetProperties(v KubernetesNodePoolPropertiesForPut) { +// SetType sets field value +func (o *KubernetesNodePoolForPut) SetType(v string) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *KubernetesNodePoolForPut) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *KubernetesNodePoolForPut) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *KubernetesNodePoolForPut) HasProperties() bool { func (o KubernetesNodePoolForPut) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_lan.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_lan.go index 012c0f4b7c6..926f1498aad 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_lan.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_lan.go @@ -18,10 +18,10 @@ import ( type KubernetesNodePoolLan struct { // The datacenter ID, requires system privileges, for internal usage only DatacenterId *string `json:"datacenterId,omitempty"` - // The LAN ID of an existing LAN at the related data center - Id *int32 `json:"id"` // Specifies whether the Kubernetes node pool LAN reserves an IP with DHCP. Dhcp *bool `json:"dhcp,omitempty"` + // The LAN ID of an existing LAN at the related data center + Id *int32 `json:"id"` // The array of additional LANs attached to worker nodes. Routes *[]KubernetesNodePoolLanRoutes `json:"routes,omitempty"` } @@ -47,7 +47,7 @@ func NewKubernetesNodePoolLanWithDefaults() *KubernetesNodePoolLan { } // GetDatacenterId returns the DatacenterId field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesNodePoolLan) GetDatacenterId() *string { if o == nil { return nil @@ -84,76 +84,76 @@ func (o *KubernetesNodePoolLan) HasDatacenterId() bool { return false } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *KubernetesNodePoolLan) GetId() *int32 { +// GetDhcp returns the Dhcp field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolLan) GetDhcp() *bool { if o == nil { return nil } - return o.Id + return o.Dhcp } -// GetIdOk returns a tuple with the Id field value +// GetDhcpOk returns a tuple with the Dhcp field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolLan) GetIdOk() (*int32, bool) { +func (o *KubernetesNodePoolLan) GetDhcpOk() (*bool, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Dhcp, true } -// SetId sets field value -func (o *KubernetesNodePoolLan) SetId(v int32) { +// SetDhcp sets field value +func (o *KubernetesNodePoolLan) SetDhcp(v bool) { - o.Id = &v + o.Dhcp = &v } -// HasId returns a boolean if a field has been set. -func (o *KubernetesNodePoolLan) HasId() bool { - if o != nil && o.Id != nil { +// HasDhcp returns a boolean if a field has been set. +func (o *KubernetesNodePoolLan) HasDhcp() bool { + if o != nil && o.Dhcp != nil { return true } return false } -// GetDhcp returns the Dhcp field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *KubernetesNodePoolLan) GetDhcp() *bool { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolLan) GetId() *int32 { if o == nil { return nil } - return o.Dhcp + return o.Id } -// GetDhcpOk returns a tuple with the Dhcp field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolLan) GetDhcpOk() (*bool, bool) { +func (o *KubernetesNodePoolLan) GetIdOk() (*int32, bool) { if o == nil { return nil, false } - return o.Dhcp, true + return o.Id, true } -// SetDhcp sets field value -func (o *KubernetesNodePoolLan) SetDhcp(v bool) { +// SetId sets field value +func (o *KubernetesNodePoolLan) SetId(v int32) { - o.Dhcp = &v + o.Id = &v } -// HasDhcp returns a boolean if a field has been set. -func (o *KubernetesNodePoolLan) HasDhcp() bool { - if o != nil && o.Dhcp != nil { +// HasId returns a boolean if a field has been set. +func (o *KubernetesNodePoolLan) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -161,7 +161,7 @@ func (o *KubernetesNodePoolLan) HasDhcp() bool { } // GetRoutes returns the Routes field value -// If the value is explicit nil, the zero value for []KubernetesNodePoolLanRoutes will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesNodePoolLan) GetRoutes() *[]KubernetesNodePoolLanRoutes { if o == nil { return nil @@ -203,15 +203,19 @@ func (o KubernetesNodePoolLan) MarshalJSON() ([]byte, error) { if o.DatacenterId != nil { toSerialize["datacenterId"] = o.DatacenterId } - if o.Id != nil { - toSerialize["id"] = o.Id - } + if o.Dhcp != nil { toSerialize["dhcp"] = o.Dhcp } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Routes != nil { toSerialize["routes"] = o.Routes } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_lan_routes.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_lan_routes.go index 0d57c45927f..7ba035e4473 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_lan_routes.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_lan_routes.go @@ -16,10 +16,10 @@ import ( // KubernetesNodePoolLanRoutes struct for KubernetesNodePoolLanRoutes type KubernetesNodePoolLanRoutes struct { - // IPv4 or IPv6 CIDR to be routed via the interface. - Network *string `json:"network,omitempty"` // IPv4 or IPv6 Gateway IP for the route. GatewayIp *string `json:"gatewayIp,omitempty"` + // IPv4 or IPv6 CIDR to be routed via the interface. + Network *string `json:"network,omitempty"` } // NewKubernetesNodePoolLanRoutes instantiates a new KubernetesNodePoolLanRoutes object @@ -40,76 +40,76 @@ func NewKubernetesNodePoolLanRoutesWithDefaults() *KubernetesNodePoolLanRoutes { return &this } -// GetNetwork returns the Network field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolLanRoutes) GetNetwork() *string { +// GetGatewayIp returns the GatewayIp field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolLanRoutes) GetGatewayIp() *string { if o == nil { return nil } - return o.Network + return o.GatewayIp } -// GetNetworkOk returns a tuple with the Network field value +// GetGatewayIpOk returns a tuple with the GatewayIp field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolLanRoutes) GetNetworkOk() (*string, bool) { +func (o *KubernetesNodePoolLanRoutes) GetGatewayIpOk() (*string, bool) { if o == nil { return nil, false } - return o.Network, true + return o.GatewayIp, true } -// SetNetwork sets field value -func (o *KubernetesNodePoolLanRoutes) SetNetwork(v string) { +// SetGatewayIp sets field value +func (o *KubernetesNodePoolLanRoutes) SetGatewayIp(v string) { - o.Network = &v + o.GatewayIp = &v } -// HasNetwork returns a boolean if a field has been set. -func (o *KubernetesNodePoolLanRoutes) HasNetwork() bool { - if o != nil && o.Network != nil { +// HasGatewayIp returns a boolean if a field has been set. +func (o *KubernetesNodePoolLanRoutes) HasGatewayIp() bool { + if o != nil && o.GatewayIp != nil { return true } return false } -// GetGatewayIp returns the GatewayIp field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolLanRoutes) GetGatewayIp() *string { +// GetNetwork returns the Network field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolLanRoutes) GetNetwork() *string { if o == nil { return nil } - return o.GatewayIp + return o.Network } -// GetGatewayIpOk returns a tuple with the GatewayIp field value +// GetNetworkOk returns a tuple with the Network field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolLanRoutes) GetGatewayIpOk() (*string, bool) { +func (o *KubernetesNodePoolLanRoutes) GetNetworkOk() (*string, bool) { if o == nil { return nil, false } - return o.GatewayIp, true + return o.Network, true } -// SetGatewayIp sets field value -func (o *KubernetesNodePoolLanRoutes) SetGatewayIp(v string) { +// SetNetwork sets field value +func (o *KubernetesNodePoolLanRoutes) SetNetwork(v string) { - o.GatewayIp = &v + o.Network = &v } -// HasGatewayIp returns a boolean if a field has been set. -func (o *KubernetesNodePoolLanRoutes) HasGatewayIp() bool { - if o != nil && o.GatewayIp != nil { +// HasNetwork returns a boolean if a field has been set. +func (o *KubernetesNodePoolLanRoutes) HasNetwork() bool { + if o != nil && o.Network != nil { return true } @@ -118,12 +118,14 @@ func (o *KubernetesNodePoolLanRoutes) HasGatewayIp() bool { func (o KubernetesNodePoolLanRoutes) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Network != nil { - toSerialize["network"] = o.Network - } if o.GatewayIp != nil { toSerialize["gatewayIp"] = o.GatewayIp } + + if o.Network != nil { + toSerialize["network"] = o.Network + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_properties.go index 5e18701de76..376120c0c3b 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_properties.go @@ -16,56 +16,56 @@ import ( // KubernetesNodePoolProperties struct for KubernetesNodePoolProperties type KubernetesNodePoolProperties struct { - // A Kubernetes node pool name. Valid Kubernetes node pool name must be 63 characters or less and must be empty or begin and end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between. - Name *string `json:"name"` + // The annotations attached to the node pool. + Annotations *map[string]string `json:"annotations,omitempty"` + AutoScaling *KubernetesAutoScaling `json:"autoScaling,omitempty"` + // The availability zone in which the target VM should be provisioned. + AvailabilityZone *string `json:"availabilityZone"` + // The list of available versions for upgrading the node pool. + AvailableUpgradeVersions *[]string `json:"availableUpgradeVersions,omitempty"` + // The total number of cores for the nodes. + CoresCount *int32 `json:"coresCount"` + // The CPU type for the nodes. + CpuFamily *string `json:"cpuFamily"` // The unique identifier of the VDC where the worker nodes of the node pool are provisioned.Note that the data center is located in the exact place where the parent cluster of the node pool is located. DatacenterId *string `json:"datacenterId"` + // The Kubernetes version running in the node pool. Note that this imposes restrictions on which Kubernetes versions can run in the node pools of a cluster. Also, not all Kubernetes versions are suitable upgrade targets for all earlier versions. + K8sVersion *string `json:"k8sVersion,omitempty"` + // The labels attached to the node pool. + Labels *map[string]string `json:"labels,omitempty"` + // The array of existing private LANs to attach to worker nodes. + Lans *[]KubernetesNodePoolLan `json:"lans,omitempty"` + MaintenanceWindow *KubernetesMaintenanceWindow `json:"maintenanceWindow,omitempty"` + // A Kubernetes node pool name. Valid Kubernetes node pool name must be 63 characters or less and must be empty or begin and end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between. + Name *string `json:"name"` // The number of worker nodes of the node pool. NodeCount *int32 `json:"nodeCount"` - // The CPU type for the nodes. - CpuFamily *string `json:"cpuFamily"` - // The total number of cores for the nodes. - CoresCount *int32 `json:"coresCount"` + // Optional array of reserved public IP addresses to be used by the nodes. The IPs must be from the exact location of the node pool's data center. If autoscaling is used, the array must contain one more IP than the maximum possible number of nodes (nodeCount+1 for a fixed number of nodes or maxNodeCount+1). The extra IP is used when the nodes are rebuilt. + PublicIps *[]string `json:"publicIps,omitempty"` // The RAM size for the nodes. Must be specified in multiples of 1024 MB, with a minimum size of 2048 MB. RamSize *int32 `json:"ramSize"` - // The availability zone in which the target VM should be provisioned. - AvailabilityZone *string `json:"availabilityZone"` - // The storage type for the nodes. - StorageType *string `json:"storageType"` // The allocated volume size in GB. The allocated volume size in GB. To achieve good performance, we recommend a size greater than 100GB for SSD. StorageSize *int32 `json:"storageSize"` - // The Kubernetes version running in the node pool. Note that this imposes restrictions on which Kubernetes versions can run in the node pools of a cluster. Also, not all Kubernetes versions are suitable upgrade targets for all earlier versions. - K8sVersion *string `json:"k8sVersion,omitempty"` - MaintenanceWindow *KubernetesMaintenanceWindow `json:"maintenanceWindow,omitempty"` - AutoScaling *KubernetesAutoScaling `json:"autoScaling,omitempty"` - // The array of existing private LANs to attach to worker nodes. - Lans *[]KubernetesNodePoolLan `json:"lans,omitempty"` - // The labels attached to the node pool. - Labels *map[string]string `json:"labels,omitempty"` - // The annotations attached to the node pool. - Annotations *map[string]string `json:"annotations,omitempty"` - // Optional array of reserved public IP addresses to be used by the nodes. The IPs must be from the exact location of the node pool's data center. If autoscaling is used, the array must contain one more IP than the maximum possible number of nodes (nodeCount+1 for a fixed number of nodes or maxNodeCount+1). The extra IP is used when the nodes are rebuilt. - PublicIps *[]string `json:"publicIps,omitempty"` - // The list of available versions for upgrading the node pool. - AvailableUpgradeVersions *[]string `json:"availableUpgradeVersions,omitempty"` + // The storage type for the nodes. + StorageType *string `json:"storageType"` } // NewKubernetesNodePoolProperties instantiates a new KubernetesNodePoolProperties object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewKubernetesNodePoolProperties(name string, datacenterId string, nodeCount int32, cpuFamily string, coresCount int32, ramSize int32, availabilityZone string, storageType string, storageSize int32) *KubernetesNodePoolProperties { +func NewKubernetesNodePoolProperties(availabilityZone string, coresCount int32, cpuFamily string, datacenterId string, name string, nodeCount int32, ramSize int32, storageSize int32, storageType string) *KubernetesNodePoolProperties { this := KubernetesNodePoolProperties{} - this.Name = &name + this.AvailabilityZone = &availabilityZone + this.CoresCount = &coresCount + this.CpuFamily = &cpuFamily this.DatacenterId = &datacenterId + this.Name = &name this.NodeCount = &nodeCount - this.CpuFamily = &cpuFamily - this.CoresCount = &coresCount this.RamSize = &ramSize - this.AvailabilityZone = &availabilityZone - this.StorageType = &storageType this.StorageSize = &storageSize + this.StorageType = &storageType return &this } @@ -78,152 +78,152 @@ func NewKubernetesNodePoolPropertiesWithDefaults() *KubernetesNodePoolProperties return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolProperties) GetName() *string { +// GetAnnotations returns the Annotations field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetAnnotations() *map[string]string { if o == nil { return nil } - return o.Name + return o.Annotations } -// GetNameOk returns a tuple with the Name field value +// GetAnnotationsOk returns a tuple with the Annotations field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetNameOk() (*string, bool) { +func (o *KubernetesNodePoolProperties) GetAnnotationsOk() (*map[string]string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.Annotations, true } -// SetName sets field value -func (o *KubernetesNodePoolProperties) SetName(v string) { +// SetAnnotations sets field value +func (o *KubernetesNodePoolProperties) SetAnnotations(v map[string]string) { - o.Name = &v + o.Annotations = &v } -// HasName returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasAnnotations returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasAnnotations() bool { + if o != nil && o.Annotations != nil { return true } return false } -// GetDatacenterId returns the DatacenterId field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolProperties) GetDatacenterId() *string { +// GetAutoScaling returns the AutoScaling field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetAutoScaling() *KubernetesAutoScaling { if o == nil { return nil } - return o.DatacenterId + return o.AutoScaling } -// GetDatacenterIdOk returns a tuple with the DatacenterId field value +// GetAutoScalingOk returns a tuple with the AutoScaling field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetDatacenterIdOk() (*string, bool) { +func (o *KubernetesNodePoolProperties) GetAutoScalingOk() (*KubernetesAutoScaling, bool) { if o == nil { return nil, false } - return o.DatacenterId, true + return o.AutoScaling, true } -// SetDatacenterId sets field value -func (o *KubernetesNodePoolProperties) SetDatacenterId(v string) { +// SetAutoScaling sets field value +func (o *KubernetesNodePoolProperties) SetAutoScaling(v KubernetesAutoScaling) { - o.DatacenterId = &v + o.AutoScaling = &v } -// HasDatacenterId returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasDatacenterId() bool { - if o != nil && o.DatacenterId != nil { +// HasAutoScaling returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasAutoScaling() bool { + if o != nil && o.AutoScaling != nil { return true } return false } -// GetNodeCount returns the NodeCount field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *KubernetesNodePoolProperties) GetNodeCount() *int32 { +// GetAvailabilityZone returns the AvailabilityZone field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetAvailabilityZone() *string { if o == nil { return nil } - return o.NodeCount + return o.AvailabilityZone } -// GetNodeCountOk returns a tuple with the NodeCount field value +// GetAvailabilityZoneOk returns a tuple with the AvailabilityZone field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetNodeCountOk() (*int32, bool) { +func (o *KubernetesNodePoolProperties) GetAvailabilityZoneOk() (*string, bool) { if o == nil { return nil, false } - return o.NodeCount, true + return o.AvailabilityZone, true } -// SetNodeCount sets field value -func (o *KubernetesNodePoolProperties) SetNodeCount(v int32) { +// SetAvailabilityZone sets field value +func (o *KubernetesNodePoolProperties) SetAvailabilityZone(v string) { - o.NodeCount = &v + o.AvailabilityZone = &v } -// HasNodeCount returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasNodeCount() bool { - if o != nil && o.NodeCount != nil { +// HasAvailabilityZone returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasAvailabilityZone() bool { + if o != nil && o.AvailabilityZone != nil { return true } return false } -// GetCpuFamily returns the CpuFamily field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolProperties) GetCpuFamily() *string { +// GetAvailableUpgradeVersions returns the AvailableUpgradeVersions field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetAvailableUpgradeVersions() *[]string { if o == nil { return nil } - return o.CpuFamily + return o.AvailableUpgradeVersions } -// GetCpuFamilyOk returns a tuple with the CpuFamily field value +// GetAvailableUpgradeVersionsOk returns a tuple with the AvailableUpgradeVersions field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetCpuFamilyOk() (*string, bool) { +func (o *KubernetesNodePoolProperties) GetAvailableUpgradeVersionsOk() (*[]string, bool) { if o == nil { return nil, false } - return o.CpuFamily, true + return o.AvailableUpgradeVersions, true } -// SetCpuFamily sets field value -func (o *KubernetesNodePoolProperties) SetCpuFamily(v string) { +// SetAvailableUpgradeVersions sets field value +func (o *KubernetesNodePoolProperties) SetAvailableUpgradeVersions(v []string) { - o.CpuFamily = &v + o.AvailableUpgradeVersions = &v } -// HasCpuFamily returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasCpuFamily() bool { - if o != nil && o.CpuFamily != nil { +// HasAvailableUpgradeVersions returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasAvailableUpgradeVersions() bool { + if o != nil && o.AvailableUpgradeVersions != nil { return true } @@ -231,7 +231,7 @@ func (o *KubernetesNodePoolProperties) HasCpuFamily() bool { } // GetCoresCount returns the CoresCount field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesNodePoolProperties) GetCoresCount() *int32 { if o == nil { return nil @@ -268,190 +268,190 @@ func (o *KubernetesNodePoolProperties) HasCoresCount() bool { return false } -// GetRamSize returns the RamSize field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *KubernetesNodePoolProperties) GetRamSize() *int32 { +// GetCpuFamily returns the CpuFamily field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetCpuFamily() *string { if o == nil { return nil } - return o.RamSize + return o.CpuFamily } -// GetRamSizeOk returns a tuple with the RamSize field value +// GetCpuFamilyOk returns a tuple with the CpuFamily field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetRamSizeOk() (*int32, bool) { +func (o *KubernetesNodePoolProperties) GetCpuFamilyOk() (*string, bool) { if o == nil { return nil, false } - return o.RamSize, true + return o.CpuFamily, true } -// SetRamSize sets field value -func (o *KubernetesNodePoolProperties) SetRamSize(v int32) { +// SetCpuFamily sets field value +func (o *KubernetesNodePoolProperties) SetCpuFamily(v string) { - o.RamSize = &v + o.CpuFamily = &v } -// HasRamSize returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasRamSize() bool { - if o != nil && o.RamSize != nil { +// HasCpuFamily returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasCpuFamily() bool { + if o != nil && o.CpuFamily != nil { return true } return false } -// GetAvailabilityZone returns the AvailabilityZone field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolProperties) GetAvailabilityZone() *string { +// GetDatacenterId returns the DatacenterId field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetDatacenterId() *string { if o == nil { return nil } - return o.AvailabilityZone + return o.DatacenterId } -// GetAvailabilityZoneOk returns a tuple with the AvailabilityZone field value +// GetDatacenterIdOk returns a tuple with the DatacenterId field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetAvailabilityZoneOk() (*string, bool) { +func (o *KubernetesNodePoolProperties) GetDatacenterIdOk() (*string, bool) { if o == nil { return nil, false } - return o.AvailabilityZone, true + return o.DatacenterId, true } -// SetAvailabilityZone sets field value -func (o *KubernetesNodePoolProperties) SetAvailabilityZone(v string) { +// SetDatacenterId sets field value +func (o *KubernetesNodePoolProperties) SetDatacenterId(v string) { - o.AvailabilityZone = &v + o.DatacenterId = &v } -// HasAvailabilityZone returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasAvailabilityZone() bool { - if o != nil && o.AvailabilityZone != nil { +// HasDatacenterId returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasDatacenterId() bool { + if o != nil && o.DatacenterId != nil { return true } return false } -// GetStorageType returns the StorageType field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolProperties) GetStorageType() *string { +// GetK8sVersion returns the K8sVersion field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetK8sVersion() *string { if o == nil { return nil } - return o.StorageType + return o.K8sVersion } -// GetStorageTypeOk returns a tuple with the StorageType field value +// GetK8sVersionOk returns a tuple with the K8sVersion field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetStorageTypeOk() (*string, bool) { +func (o *KubernetesNodePoolProperties) GetK8sVersionOk() (*string, bool) { if o == nil { return nil, false } - return o.StorageType, true + return o.K8sVersion, true } -// SetStorageType sets field value -func (o *KubernetesNodePoolProperties) SetStorageType(v string) { +// SetK8sVersion sets field value +func (o *KubernetesNodePoolProperties) SetK8sVersion(v string) { - o.StorageType = &v + o.K8sVersion = &v } -// HasStorageType returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasStorageType() bool { - if o != nil && o.StorageType != nil { +// HasK8sVersion returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasK8sVersion() bool { + if o != nil && o.K8sVersion != nil { return true } return false } -// GetStorageSize returns the StorageSize field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *KubernetesNodePoolProperties) GetStorageSize() *int32 { +// GetLabels returns the Labels field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetLabels() *map[string]string { if o == nil { return nil } - return o.StorageSize + return o.Labels } -// GetStorageSizeOk returns a tuple with the StorageSize field value +// GetLabelsOk returns a tuple with the Labels field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetStorageSizeOk() (*int32, bool) { +func (o *KubernetesNodePoolProperties) GetLabelsOk() (*map[string]string, bool) { if o == nil { return nil, false } - return o.StorageSize, true + return o.Labels, true } -// SetStorageSize sets field value -func (o *KubernetesNodePoolProperties) SetStorageSize(v int32) { +// SetLabels sets field value +func (o *KubernetesNodePoolProperties) SetLabels(v map[string]string) { - o.StorageSize = &v + o.Labels = &v } -// HasStorageSize returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasStorageSize() bool { - if o != nil && o.StorageSize != nil { +// HasLabels returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasLabels() bool { + if o != nil && o.Labels != nil { return true } return false } -// GetK8sVersion returns the K8sVersion field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolProperties) GetK8sVersion() *string { +// GetLans returns the Lans field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetLans() *[]KubernetesNodePoolLan { if o == nil { return nil } - return o.K8sVersion + return o.Lans } -// GetK8sVersionOk returns a tuple with the K8sVersion field value +// GetLansOk returns a tuple with the Lans field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetK8sVersionOk() (*string, bool) { +func (o *KubernetesNodePoolProperties) GetLansOk() (*[]KubernetesNodePoolLan, bool) { if o == nil { return nil, false } - return o.K8sVersion, true + return o.Lans, true } -// SetK8sVersion sets field value -func (o *KubernetesNodePoolProperties) SetK8sVersion(v string) { +// SetLans sets field value +func (o *KubernetesNodePoolProperties) SetLans(v []KubernetesNodePoolLan) { - o.K8sVersion = &v + o.Lans = &v } -// HasK8sVersion returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasK8sVersion() bool { - if o != nil && o.K8sVersion != nil { +// HasLans returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasLans() bool { + if o != nil && o.Lans != nil { return true } @@ -459,7 +459,7 @@ func (o *KubernetesNodePoolProperties) HasK8sVersion() bool { } // GetMaintenanceWindow returns the MaintenanceWindow field value -// If the value is explicit nil, the zero value for KubernetesMaintenanceWindow will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesNodePoolProperties) GetMaintenanceWindow() *KubernetesMaintenanceWindow { if o == nil { return nil @@ -496,228 +496,228 @@ func (o *KubernetesNodePoolProperties) HasMaintenanceWindow() bool { return false } -// GetAutoScaling returns the AutoScaling field value -// If the value is explicit nil, the zero value for KubernetesAutoScaling will be returned -func (o *KubernetesNodePoolProperties) GetAutoScaling() *KubernetesAutoScaling { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetName() *string { if o == nil { return nil } - return o.AutoScaling + return o.Name } -// GetAutoScalingOk returns a tuple with the AutoScaling field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetAutoScalingOk() (*KubernetesAutoScaling, bool) { +func (o *KubernetesNodePoolProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.AutoScaling, true + return o.Name, true } -// SetAutoScaling sets field value -func (o *KubernetesNodePoolProperties) SetAutoScaling(v KubernetesAutoScaling) { +// SetName sets field value +func (o *KubernetesNodePoolProperties) SetName(v string) { - o.AutoScaling = &v + o.Name = &v } -// HasAutoScaling returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasAutoScaling() bool { - if o != nil && o.AutoScaling != nil { +// HasName returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasName() bool { + if o != nil && o.Name != nil { return true } return false } -// GetLans returns the Lans field value -// If the value is explicit nil, the zero value for []KubernetesNodePoolLan will be returned -func (o *KubernetesNodePoolProperties) GetLans() *[]KubernetesNodePoolLan { +// GetNodeCount returns the NodeCount field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetNodeCount() *int32 { if o == nil { return nil } - return o.Lans + return o.NodeCount } -// GetLansOk returns a tuple with the Lans field value +// GetNodeCountOk returns a tuple with the NodeCount field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetLansOk() (*[]KubernetesNodePoolLan, bool) { +func (o *KubernetesNodePoolProperties) GetNodeCountOk() (*int32, bool) { if o == nil { return nil, false } - return o.Lans, true + return o.NodeCount, true } -// SetLans sets field value -func (o *KubernetesNodePoolProperties) SetLans(v []KubernetesNodePoolLan) { +// SetNodeCount sets field value +func (o *KubernetesNodePoolProperties) SetNodeCount(v int32) { - o.Lans = &v + o.NodeCount = &v } -// HasLans returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasLans() bool { - if o != nil && o.Lans != nil { +// HasNodeCount returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasNodeCount() bool { + if o != nil && o.NodeCount != nil { return true } return false } -// GetLabels returns the Labels field value -// If the value is explicit nil, the zero value for map[string]string will be returned -func (o *KubernetesNodePoolProperties) GetLabels() *map[string]string { +// GetPublicIps returns the PublicIps field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetPublicIps() *[]string { if o == nil { return nil } - return o.Labels + return o.PublicIps } -// GetLabelsOk returns a tuple with the Labels field value +// GetPublicIpsOk returns a tuple with the PublicIps field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetLabelsOk() (*map[string]string, bool) { +func (o *KubernetesNodePoolProperties) GetPublicIpsOk() (*[]string, bool) { if o == nil { return nil, false } - return o.Labels, true + return o.PublicIps, true } -// SetLabels sets field value -func (o *KubernetesNodePoolProperties) SetLabels(v map[string]string) { +// SetPublicIps sets field value +func (o *KubernetesNodePoolProperties) SetPublicIps(v []string) { - o.Labels = &v + o.PublicIps = &v } -// HasLabels returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasLabels() bool { - if o != nil && o.Labels != nil { +// HasPublicIps returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasPublicIps() bool { + if o != nil && o.PublicIps != nil { return true } return false } -// GetAnnotations returns the Annotations field value -// If the value is explicit nil, the zero value for map[string]string will be returned -func (o *KubernetesNodePoolProperties) GetAnnotations() *map[string]string { +// GetRamSize returns the RamSize field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetRamSize() *int32 { if o == nil { return nil } - return o.Annotations + return o.RamSize } -// GetAnnotationsOk returns a tuple with the Annotations field value +// GetRamSizeOk returns a tuple with the RamSize field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetAnnotationsOk() (*map[string]string, bool) { +func (o *KubernetesNodePoolProperties) GetRamSizeOk() (*int32, bool) { if o == nil { return nil, false } - return o.Annotations, true + return o.RamSize, true } -// SetAnnotations sets field value -func (o *KubernetesNodePoolProperties) SetAnnotations(v map[string]string) { +// SetRamSize sets field value +func (o *KubernetesNodePoolProperties) SetRamSize(v int32) { - o.Annotations = &v + o.RamSize = &v } -// HasAnnotations returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasAnnotations() bool { - if o != nil && o.Annotations != nil { +// HasRamSize returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasRamSize() bool { + if o != nil && o.RamSize != nil { return true } return false } -// GetPublicIps returns the PublicIps field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *KubernetesNodePoolProperties) GetPublicIps() *[]string { +// GetStorageSize returns the StorageSize field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetStorageSize() *int32 { if o == nil { return nil } - return o.PublicIps + return o.StorageSize } -// GetPublicIpsOk returns a tuple with the PublicIps field value +// GetStorageSizeOk returns a tuple with the StorageSize field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetPublicIpsOk() (*[]string, bool) { +func (o *KubernetesNodePoolProperties) GetStorageSizeOk() (*int32, bool) { if o == nil { return nil, false } - return o.PublicIps, true + return o.StorageSize, true } -// SetPublicIps sets field value -func (o *KubernetesNodePoolProperties) SetPublicIps(v []string) { +// SetStorageSize sets field value +func (o *KubernetesNodePoolProperties) SetStorageSize(v int32) { - o.PublicIps = &v + o.StorageSize = &v } -// HasPublicIps returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasPublicIps() bool { - if o != nil && o.PublicIps != nil { +// HasStorageSize returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasStorageSize() bool { + if o != nil && o.StorageSize != nil { return true } return false } -// GetAvailableUpgradeVersions returns the AvailableUpgradeVersions field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *KubernetesNodePoolProperties) GetAvailableUpgradeVersions() *[]string { +// GetStorageType returns the StorageType field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolProperties) GetStorageType() *string { if o == nil { return nil } - return o.AvailableUpgradeVersions + return o.StorageType } -// GetAvailableUpgradeVersionsOk returns a tuple with the AvailableUpgradeVersions field value +// GetStorageTypeOk returns a tuple with the StorageType field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolProperties) GetAvailableUpgradeVersionsOk() (*[]string, bool) { +func (o *KubernetesNodePoolProperties) GetStorageTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.AvailableUpgradeVersions, true + return o.StorageType, true } -// SetAvailableUpgradeVersions sets field value -func (o *KubernetesNodePoolProperties) SetAvailableUpgradeVersions(v []string) { +// SetStorageType sets field value +func (o *KubernetesNodePoolProperties) SetStorageType(v string) { - o.AvailableUpgradeVersions = &v + o.StorageType = &v } -// HasAvailableUpgradeVersions returns a boolean if a field has been set. -func (o *KubernetesNodePoolProperties) HasAvailableUpgradeVersions() bool { - if o != nil && o.AvailableUpgradeVersions != nil { +// HasStorageType returns a boolean if a field has been set. +func (o *KubernetesNodePoolProperties) HasStorageType() bool { + if o != nil && o.StorageType != nil { return true } @@ -726,57 +726,74 @@ func (o *KubernetesNodePoolProperties) HasAvailableUpgradeVersions() bool { func (o KubernetesNodePoolProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name + if o.Annotations != nil { + toSerialize["annotations"] = o.Annotations } - if o.DatacenterId != nil { - toSerialize["datacenterId"] = o.DatacenterId + + if o.AutoScaling != nil { + toSerialize["autoScaling"] = o.AutoScaling } - if o.NodeCount != nil { - toSerialize["nodeCount"] = o.NodeCount + + if o.AvailabilityZone != nil { + toSerialize["availabilityZone"] = o.AvailabilityZone } - if o.CpuFamily != nil { - toSerialize["cpuFamily"] = o.CpuFamily + + if o.AvailableUpgradeVersions != nil { + toSerialize["availableUpgradeVersions"] = o.AvailableUpgradeVersions } + if o.CoresCount != nil { toSerialize["coresCount"] = o.CoresCount } - if o.RamSize != nil { - toSerialize["ramSize"] = o.RamSize - } - if o.AvailabilityZone != nil { - toSerialize["availabilityZone"] = o.AvailabilityZone - } - if o.StorageType != nil { - toSerialize["storageType"] = o.StorageType + + if o.CpuFamily != nil { + toSerialize["cpuFamily"] = o.CpuFamily } - if o.StorageSize != nil { - toSerialize["storageSize"] = o.StorageSize + + if o.DatacenterId != nil { + toSerialize["datacenterId"] = o.DatacenterId } + if o.K8sVersion != nil { toSerialize["k8sVersion"] = o.K8sVersion } - if o.MaintenanceWindow != nil { - toSerialize["maintenanceWindow"] = o.MaintenanceWindow - } - if o.AutoScaling != nil { - toSerialize["autoScaling"] = o.AutoScaling + + if o.Labels != nil { + toSerialize["labels"] = o.Labels } + if o.Lans != nil { toSerialize["lans"] = o.Lans } - if o.Labels != nil { - toSerialize["labels"] = o.Labels + + if o.MaintenanceWindow != nil { + toSerialize["maintenanceWindow"] = o.MaintenanceWindow } - if o.Annotations != nil { - toSerialize["annotations"] = o.Annotations + + if o.Name != nil { + toSerialize["name"] = o.Name + } + + if o.NodeCount != nil { + toSerialize["nodeCount"] = o.NodeCount } + if o.PublicIps != nil { toSerialize["publicIps"] = o.PublicIps } - if o.AvailableUpgradeVersions != nil { - toSerialize["availableUpgradeVersions"] = o.AvailableUpgradeVersions + + if o.RamSize != nil { + toSerialize["ramSize"] = o.RamSize } + + if o.StorageSize != nil { + toSerialize["storageSize"] = o.StorageSize + } + + if o.StorageType != nil { + toSerialize["storageType"] = o.StorageType + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_properties_for_post.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_properties_for_post.go index dff10d33854..c55191cfa07 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_properties_for_post.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_properties_for_post.go @@ -16,54 +16,54 @@ import ( // KubernetesNodePoolPropertiesForPost struct for KubernetesNodePoolPropertiesForPost type KubernetesNodePoolPropertiesForPost struct { - // A Kubernetes node pool name. Valid Kubernetes node pool name must be 63 characters or less and must be empty or begin and end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between. - Name *string `json:"name"` + // The annotations attached to the node pool. + Annotations *map[string]string `json:"annotations,omitempty"` + AutoScaling *KubernetesAutoScaling `json:"autoScaling,omitempty"` + // The availability zone in which the target VM should be provisioned. + AvailabilityZone *string `json:"availabilityZone"` + // The total number of cores for the nodes. + CoresCount *int32 `json:"coresCount"` + // The CPU type for the nodes. + CpuFamily *string `json:"cpuFamily"` // The unique identifier of the VDC where the worker nodes of the node pool are provisioned.Note that the data center is located in the exact place where the parent cluster of the node pool is located. DatacenterId *string `json:"datacenterId"` + // The Kubernetes version running in the node pool. Note that this imposes restrictions on which Kubernetes versions can run in the node pools of a cluster. Also, not all Kubernetes versions are suitable upgrade targets for all earlier versions. + K8sVersion *string `json:"k8sVersion,omitempty"` + // The labels attached to the node pool. + Labels *map[string]string `json:"labels,omitempty"` + // The array of existing private LANs to attach to worker nodes. + Lans *[]KubernetesNodePoolLan `json:"lans,omitempty"` + MaintenanceWindow *KubernetesMaintenanceWindow `json:"maintenanceWindow,omitempty"` + // A Kubernetes node pool name. Valid Kubernetes node pool name must be 63 characters or less and must be empty or begin and end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between. + Name *string `json:"name"` // The number of worker nodes of the node pool. NodeCount *int32 `json:"nodeCount"` - // The CPU type for the nodes. - CpuFamily *string `json:"cpuFamily"` - // The total number of cores for the nodes. - CoresCount *int32 `json:"coresCount"` + // Optional array of reserved public IP addresses to be used by the nodes. The IPs must be from the exact location of the node pool's data center. If autoscaling is used, the array must contain one more IP than the maximum possible number of nodes (nodeCount+1 for a fixed number of nodes or maxNodeCount+1). The extra IP is used when the nodes are rebuilt. + PublicIps *[]string `json:"publicIps,omitempty"` // The RAM size for the nodes. Must be specified in multiples of 1024 MB, with a minimum size of 2048 MB. RamSize *int32 `json:"ramSize"` - // The availability zone in which the target VM should be provisioned. - AvailabilityZone *string `json:"availabilityZone"` - // The storage type for the nodes. - StorageType *string `json:"storageType"` // The allocated volume size in GB. The allocated volume size in GB. To achieve good performance, we recommend a size greater than 100GB for SSD. StorageSize *int32 `json:"storageSize"` - // The Kubernetes version running in the node pool. Note that this imposes restrictions on which Kubernetes versions can run in the node pools of a cluster. Also, not all Kubernetes versions are suitable upgrade targets for all earlier versions. - K8sVersion *string `json:"k8sVersion,omitempty"` - MaintenanceWindow *KubernetesMaintenanceWindow `json:"maintenanceWindow,omitempty"` - AutoScaling *KubernetesAutoScaling `json:"autoScaling,omitempty"` - // The array of existing private LANs to attach to worker nodes. - Lans *[]KubernetesNodePoolLan `json:"lans,omitempty"` - // The labels attached to the node pool. - Labels *map[string]string `json:"labels,omitempty"` - // The annotations attached to the node pool. - Annotations *map[string]string `json:"annotations,omitempty"` - // Optional array of reserved public IP addresses to be used by the nodes. The IPs must be from the exact location of the node pool's data center. If autoscaling is used, the array must contain one more IP than the maximum possible number of nodes (nodeCount+1 for a fixed number of nodes or maxNodeCount+1). The extra IP is used when the nodes are rebuilt. - PublicIps *[]string `json:"publicIps,omitempty"` + // The storage type for the nodes. + StorageType *string `json:"storageType"` } // NewKubernetesNodePoolPropertiesForPost instantiates a new KubernetesNodePoolPropertiesForPost object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewKubernetesNodePoolPropertiesForPost(name string, datacenterId string, nodeCount int32, cpuFamily string, coresCount int32, ramSize int32, availabilityZone string, storageType string, storageSize int32) *KubernetesNodePoolPropertiesForPost { +func NewKubernetesNodePoolPropertiesForPost(availabilityZone string, coresCount int32, cpuFamily string, datacenterId string, name string, nodeCount int32, ramSize int32, storageSize int32, storageType string) *KubernetesNodePoolPropertiesForPost { this := KubernetesNodePoolPropertiesForPost{} - this.Name = &name + this.AvailabilityZone = &availabilityZone + this.CoresCount = &coresCount + this.CpuFamily = &cpuFamily this.DatacenterId = &datacenterId + this.Name = &name this.NodeCount = &nodeCount - this.CpuFamily = &cpuFamily - this.CoresCount = &coresCount this.RamSize = &ramSize - this.AvailabilityZone = &availabilityZone - this.StorageType = &storageType this.StorageSize = &storageSize + this.StorageType = &storageType return &this } @@ -76,608 +76,608 @@ func NewKubernetesNodePoolPropertiesForPostWithDefaults() *KubernetesNodePoolPro return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetName() *string { +// GetAnnotations returns the Annotations field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetAnnotations() *map[string]string { if o == nil { return nil } - return o.Name + return o.Annotations } -// GetNameOk returns a tuple with the Name field value +// GetAnnotationsOk returns a tuple with the Annotations field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetNameOk() (*string, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetAnnotationsOk() (*map[string]string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.Annotations, true } -// SetName sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetName(v string) { +// SetAnnotations sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetAnnotations(v map[string]string) { - o.Name = &v + o.Annotations = &v } -// HasName returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasName() bool { - if o != nil && o.Name != nil { +// HasAnnotations returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasAnnotations() bool { + if o != nil && o.Annotations != nil { return true } return false } -// GetDatacenterId returns the DatacenterId field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetDatacenterId() *string { +// GetAutoScaling returns the AutoScaling field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetAutoScaling() *KubernetesAutoScaling { if o == nil { return nil } - return o.DatacenterId + return o.AutoScaling } -// GetDatacenterIdOk returns a tuple with the DatacenterId field value +// GetAutoScalingOk returns a tuple with the AutoScaling field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetDatacenterIdOk() (*string, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetAutoScalingOk() (*KubernetesAutoScaling, bool) { if o == nil { return nil, false } - return o.DatacenterId, true + return o.AutoScaling, true } -// SetDatacenterId sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetDatacenterId(v string) { +// SetAutoScaling sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetAutoScaling(v KubernetesAutoScaling) { - o.DatacenterId = &v + o.AutoScaling = &v } -// HasDatacenterId returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasDatacenterId() bool { - if o != nil && o.DatacenterId != nil { +// HasAutoScaling returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasAutoScaling() bool { + if o != nil && o.AutoScaling != nil { return true } return false } -// GetNodeCount returns the NodeCount field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetNodeCount() *int32 { +// GetAvailabilityZone returns the AvailabilityZone field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetAvailabilityZone() *string { if o == nil { return nil } - return o.NodeCount + return o.AvailabilityZone } -// GetNodeCountOk returns a tuple with the NodeCount field value +// GetAvailabilityZoneOk returns a tuple with the AvailabilityZone field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetNodeCountOk() (*int32, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetAvailabilityZoneOk() (*string, bool) { if o == nil { return nil, false } - return o.NodeCount, true + return o.AvailabilityZone, true } -// SetNodeCount sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetNodeCount(v int32) { +// SetAvailabilityZone sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetAvailabilityZone(v string) { - o.NodeCount = &v + o.AvailabilityZone = &v } -// HasNodeCount returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasNodeCount() bool { - if o != nil && o.NodeCount != nil { +// HasAvailabilityZone returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasAvailabilityZone() bool { + if o != nil && o.AvailabilityZone != nil { return true } return false } -// GetCpuFamily returns the CpuFamily field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetCpuFamily() *string { +// GetCoresCount returns the CoresCount field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetCoresCount() *int32 { if o == nil { return nil } - return o.CpuFamily + return o.CoresCount } -// GetCpuFamilyOk returns a tuple with the CpuFamily field value +// GetCoresCountOk returns a tuple with the CoresCount field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetCpuFamilyOk() (*string, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetCoresCountOk() (*int32, bool) { if o == nil { return nil, false } - return o.CpuFamily, true + return o.CoresCount, true } -// SetCpuFamily sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetCpuFamily(v string) { +// SetCoresCount sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetCoresCount(v int32) { - o.CpuFamily = &v + o.CoresCount = &v } -// HasCpuFamily returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasCpuFamily() bool { - if o != nil && o.CpuFamily != nil { +// HasCoresCount returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasCoresCount() bool { + if o != nil && o.CoresCount != nil { return true } return false } -// GetCoresCount returns the CoresCount field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetCoresCount() *int32 { +// GetCpuFamily returns the CpuFamily field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetCpuFamily() *string { if o == nil { return nil } - return o.CoresCount + return o.CpuFamily } -// GetCoresCountOk returns a tuple with the CoresCount field value +// GetCpuFamilyOk returns a tuple with the CpuFamily field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetCoresCountOk() (*int32, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetCpuFamilyOk() (*string, bool) { if o == nil { return nil, false } - return o.CoresCount, true + return o.CpuFamily, true } -// SetCoresCount sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetCoresCount(v int32) { +// SetCpuFamily sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetCpuFamily(v string) { - o.CoresCount = &v + o.CpuFamily = &v } -// HasCoresCount returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasCoresCount() bool { - if o != nil && o.CoresCount != nil { +// HasCpuFamily returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasCpuFamily() bool { + if o != nil && o.CpuFamily != nil { return true } return false } -// GetRamSize returns the RamSize field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetRamSize() *int32 { +// GetDatacenterId returns the DatacenterId field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetDatacenterId() *string { if o == nil { return nil } - return o.RamSize + return o.DatacenterId } -// GetRamSizeOk returns a tuple with the RamSize field value +// GetDatacenterIdOk returns a tuple with the DatacenterId field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetRamSizeOk() (*int32, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetDatacenterIdOk() (*string, bool) { if o == nil { return nil, false } - return o.RamSize, true + return o.DatacenterId, true } -// SetRamSize sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetRamSize(v int32) { +// SetDatacenterId sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetDatacenterId(v string) { - o.RamSize = &v + o.DatacenterId = &v } -// HasRamSize returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasRamSize() bool { - if o != nil && o.RamSize != nil { +// HasDatacenterId returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasDatacenterId() bool { + if o != nil && o.DatacenterId != nil { return true } return false } -// GetAvailabilityZone returns the AvailabilityZone field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetAvailabilityZone() *string { +// GetK8sVersion returns the K8sVersion field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetK8sVersion() *string { if o == nil { return nil } - return o.AvailabilityZone + return o.K8sVersion } -// GetAvailabilityZoneOk returns a tuple with the AvailabilityZone field value +// GetK8sVersionOk returns a tuple with the K8sVersion field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetAvailabilityZoneOk() (*string, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetK8sVersionOk() (*string, bool) { if o == nil { return nil, false } - return o.AvailabilityZone, true + return o.K8sVersion, true } -// SetAvailabilityZone sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetAvailabilityZone(v string) { +// SetK8sVersion sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetK8sVersion(v string) { - o.AvailabilityZone = &v + o.K8sVersion = &v } -// HasAvailabilityZone returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasAvailabilityZone() bool { - if o != nil && o.AvailabilityZone != nil { +// HasK8sVersion returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasK8sVersion() bool { + if o != nil && o.K8sVersion != nil { return true } return false } -// GetStorageType returns the StorageType field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetStorageType() *string { +// GetLabels returns the Labels field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetLabels() *map[string]string { if o == nil { return nil } - return o.StorageType + return o.Labels } -// GetStorageTypeOk returns a tuple with the StorageType field value +// GetLabelsOk returns a tuple with the Labels field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetStorageTypeOk() (*string, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetLabelsOk() (*map[string]string, bool) { if o == nil { return nil, false } - return o.StorageType, true + return o.Labels, true } -// SetStorageType sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetStorageType(v string) { +// SetLabels sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetLabels(v map[string]string) { - o.StorageType = &v + o.Labels = &v } -// HasStorageType returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasStorageType() bool { - if o != nil && o.StorageType != nil { +// HasLabels returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasLabels() bool { + if o != nil && o.Labels != nil { return true } return false } -// GetStorageSize returns the StorageSize field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetStorageSize() *int32 { +// GetLans returns the Lans field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetLans() *[]KubernetesNodePoolLan { if o == nil { return nil } - return o.StorageSize + return o.Lans } -// GetStorageSizeOk returns a tuple with the StorageSize field value +// GetLansOk returns a tuple with the Lans field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetStorageSizeOk() (*int32, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetLansOk() (*[]KubernetesNodePoolLan, bool) { if o == nil { return nil, false } - return o.StorageSize, true + return o.Lans, true } -// SetStorageSize sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetStorageSize(v int32) { +// SetLans sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetLans(v []KubernetesNodePoolLan) { - o.StorageSize = &v + o.Lans = &v } -// HasStorageSize returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasStorageSize() bool { - if o != nil && o.StorageSize != nil { +// HasLans returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasLans() bool { + if o != nil && o.Lans != nil { return true } return false } -// GetK8sVersion returns the K8sVersion field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetK8sVersion() *string { +// GetMaintenanceWindow returns the MaintenanceWindow field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetMaintenanceWindow() *KubernetesMaintenanceWindow { if o == nil { return nil } - return o.K8sVersion + return o.MaintenanceWindow } -// GetK8sVersionOk returns a tuple with the K8sVersion field value +// GetMaintenanceWindowOk returns a tuple with the MaintenanceWindow field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetK8sVersionOk() (*string, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetMaintenanceWindowOk() (*KubernetesMaintenanceWindow, bool) { if o == nil { return nil, false } - return o.K8sVersion, true + return o.MaintenanceWindow, true } -// SetK8sVersion sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetK8sVersion(v string) { +// SetMaintenanceWindow sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetMaintenanceWindow(v KubernetesMaintenanceWindow) { - o.K8sVersion = &v + o.MaintenanceWindow = &v } -// HasK8sVersion returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasK8sVersion() bool { - if o != nil && o.K8sVersion != nil { +// HasMaintenanceWindow returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasMaintenanceWindow() bool { + if o != nil && o.MaintenanceWindow != nil { return true } return false } -// GetMaintenanceWindow returns the MaintenanceWindow field value -// If the value is explicit nil, the zero value for KubernetesMaintenanceWindow will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetMaintenanceWindow() *KubernetesMaintenanceWindow { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetName() *string { if o == nil { return nil } - return o.MaintenanceWindow + return o.Name } -// GetMaintenanceWindowOk returns a tuple with the MaintenanceWindow field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetMaintenanceWindowOk() (*KubernetesMaintenanceWindow, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.MaintenanceWindow, true + return o.Name, true } -// SetMaintenanceWindow sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetMaintenanceWindow(v KubernetesMaintenanceWindow) { +// SetName sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetName(v string) { - o.MaintenanceWindow = &v + o.Name = &v } -// HasMaintenanceWindow returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasMaintenanceWindow() bool { - if o != nil && o.MaintenanceWindow != nil { +// HasName returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasName() bool { + if o != nil && o.Name != nil { return true } return false } -// GetAutoScaling returns the AutoScaling field value -// If the value is explicit nil, the zero value for KubernetesAutoScaling will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetAutoScaling() *KubernetesAutoScaling { +// GetNodeCount returns the NodeCount field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetNodeCount() *int32 { if o == nil { return nil } - return o.AutoScaling + return o.NodeCount } -// GetAutoScalingOk returns a tuple with the AutoScaling field value +// GetNodeCountOk returns a tuple with the NodeCount field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetAutoScalingOk() (*KubernetesAutoScaling, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetNodeCountOk() (*int32, bool) { if o == nil { return nil, false } - return o.AutoScaling, true + return o.NodeCount, true } -// SetAutoScaling sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetAutoScaling(v KubernetesAutoScaling) { +// SetNodeCount sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetNodeCount(v int32) { - o.AutoScaling = &v + o.NodeCount = &v } -// HasAutoScaling returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasAutoScaling() bool { - if o != nil && o.AutoScaling != nil { +// HasNodeCount returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasNodeCount() bool { + if o != nil && o.NodeCount != nil { return true } return false } -// GetLans returns the Lans field value -// If the value is explicit nil, the zero value for []KubernetesNodePoolLan will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetLans() *[]KubernetesNodePoolLan { +// GetPublicIps returns the PublicIps field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetPublicIps() *[]string { if o == nil { return nil } - return o.Lans + return o.PublicIps } -// GetLansOk returns a tuple with the Lans field value +// GetPublicIpsOk returns a tuple with the PublicIps field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetLansOk() (*[]KubernetesNodePoolLan, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetPublicIpsOk() (*[]string, bool) { if o == nil { return nil, false } - return o.Lans, true + return o.PublicIps, true } -// SetLans sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetLans(v []KubernetesNodePoolLan) { +// SetPublicIps sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetPublicIps(v []string) { - o.Lans = &v + o.PublicIps = &v } -// HasLans returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasLans() bool { - if o != nil && o.Lans != nil { +// HasPublicIps returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasPublicIps() bool { + if o != nil && o.PublicIps != nil { return true } return false } -// GetLabels returns the Labels field value -// If the value is explicit nil, the zero value for map[string]string will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetLabels() *map[string]string { +// GetRamSize returns the RamSize field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetRamSize() *int32 { if o == nil { return nil } - return o.Labels + return o.RamSize } -// GetLabelsOk returns a tuple with the Labels field value +// GetRamSizeOk returns a tuple with the RamSize field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetLabelsOk() (*map[string]string, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetRamSizeOk() (*int32, bool) { if o == nil { return nil, false } - return o.Labels, true + return o.RamSize, true } -// SetLabels sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetLabels(v map[string]string) { +// SetRamSize sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetRamSize(v int32) { - o.Labels = &v + o.RamSize = &v } -// HasLabels returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasLabels() bool { - if o != nil && o.Labels != nil { +// HasRamSize returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasRamSize() bool { + if o != nil && o.RamSize != nil { return true } return false } -// GetAnnotations returns the Annotations field value -// If the value is explicit nil, the zero value for map[string]string will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetAnnotations() *map[string]string { +// GetStorageSize returns the StorageSize field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetStorageSize() *int32 { if o == nil { return nil } - return o.Annotations + return o.StorageSize } -// GetAnnotationsOk returns a tuple with the Annotations field value +// GetStorageSizeOk returns a tuple with the StorageSize field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetAnnotationsOk() (*map[string]string, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetStorageSizeOk() (*int32, bool) { if o == nil { return nil, false } - return o.Annotations, true + return o.StorageSize, true } -// SetAnnotations sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetAnnotations(v map[string]string) { +// SetStorageSize sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetStorageSize(v int32) { - o.Annotations = &v + o.StorageSize = &v } -// HasAnnotations returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasAnnotations() bool { - if o != nil && o.Annotations != nil { +// HasStorageSize returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasStorageSize() bool { + if o != nil && o.StorageSize != nil { return true } return false } -// GetPublicIps returns the PublicIps field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetPublicIps() *[]string { +// GetStorageType returns the StorageType field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPost) GetStorageType() *string { if o == nil { return nil } - return o.PublicIps + return o.StorageType } -// GetPublicIpsOk returns a tuple with the PublicIps field value +// GetStorageTypeOk returns a tuple with the StorageType field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPost) GetPublicIpsOk() (*[]string, bool) { +func (o *KubernetesNodePoolPropertiesForPost) GetStorageTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.PublicIps, true + return o.StorageType, true } -// SetPublicIps sets field value -func (o *KubernetesNodePoolPropertiesForPost) SetPublicIps(v []string) { +// SetStorageType sets field value +func (o *KubernetesNodePoolPropertiesForPost) SetStorageType(v string) { - o.PublicIps = &v + o.StorageType = &v } -// HasPublicIps returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPost) HasPublicIps() bool { - if o != nil && o.PublicIps != nil { +// HasStorageType returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPost) HasStorageType() bool { + if o != nil && o.StorageType != nil { return true } @@ -686,54 +686,70 @@ func (o *KubernetesNodePoolPropertiesForPost) HasPublicIps() bool { func (o KubernetesNodePoolPropertiesForPost) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name - } - if o.DatacenterId != nil { - toSerialize["datacenterId"] = o.DatacenterId + if o.Annotations != nil { + toSerialize["annotations"] = o.Annotations } - if o.NodeCount != nil { - toSerialize["nodeCount"] = o.NodeCount + + if o.AutoScaling != nil { + toSerialize["autoScaling"] = o.AutoScaling } - if o.CpuFamily != nil { - toSerialize["cpuFamily"] = o.CpuFamily + + if o.AvailabilityZone != nil { + toSerialize["availabilityZone"] = o.AvailabilityZone } + if o.CoresCount != nil { toSerialize["coresCount"] = o.CoresCount } - if o.RamSize != nil { - toSerialize["ramSize"] = o.RamSize - } - if o.AvailabilityZone != nil { - toSerialize["availabilityZone"] = o.AvailabilityZone - } - if o.StorageType != nil { - toSerialize["storageType"] = o.StorageType + + if o.CpuFamily != nil { + toSerialize["cpuFamily"] = o.CpuFamily } - if o.StorageSize != nil { - toSerialize["storageSize"] = o.StorageSize + + if o.DatacenterId != nil { + toSerialize["datacenterId"] = o.DatacenterId } + if o.K8sVersion != nil { toSerialize["k8sVersion"] = o.K8sVersion } - if o.MaintenanceWindow != nil { - toSerialize["maintenanceWindow"] = o.MaintenanceWindow - } - if o.AutoScaling != nil { - toSerialize["autoScaling"] = o.AutoScaling + + if o.Labels != nil { + toSerialize["labels"] = o.Labels } + if o.Lans != nil { toSerialize["lans"] = o.Lans } - if o.Labels != nil { - toSerialize["labels"] = o.Labels + + if o.MaintenanceWindow != nil { + toSerialize["maintenanceWindow"] = o.MaintenanceWindow } - if o.Annotations != nil { - toSerialize["annotations"] = o.Annotations + + if o.Name != nil { + toSerialize["name"] = o.Name } + + if o.NodeCount != nil { + toSerialize["nodeCount"] = o.NodeCount + } + if o.PublicIps != nil { toSerialize["publicIps"] = o.PublicIps } + + if o.RamSize != nil { + toSerialize["ramSize"] = o.RamSize + } + + if o.StorageSize != nil { + toSerialize["storageSize"] = o.StorageSize + } + + if o.StorageType != nil { + toSerialize["storageType"] = o.StorageType + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_properties_for_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_properties_for_put.go index 88c31def64e..3e82ea9c496 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_properties_for_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pool_properties_for_put.go @@ -16,20 +16,20 @@ import ( // KubernetesNodePoolPropertiesForPut struct for KubernetesNodePoolPropertiesForPut type KubernetesNodePoolPropertiesForPut struct { + // The annotations attached to the node pool. + Annotations *map[string]string `json:"annotations,omitempty"` + AutoScaling *KubernetesAutoScaling `json:"autoScaling,omitempty"` + // The Kubernetes version running in the node pool. Note that this imposes restrictions on which Kubernetes versions can run in the node pools of a cluster. Also, not all Kubernetes versions are suitable upgrade targets for all earlier versions. + K8sVersion *string `json:"k8sVersion,omitempty"` + // The labels attached to the node pool. + Labels *map[string]string `json:"labels,omitempty"` + // The array of existing private LANs to attach to worker nodes. + Lans *[]KubernetesNodePoolLan `json:"lans,omitempty"` + MaintenanceWindow *KubernetesMaintenanceWindow `json:"maintenanceWindow,omitempty"` // A Kubernetes node pool name. Valid Kubernetes node pool name must be 63 characters or less and must be empty or begin and end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between. Name *string `json:"name,omitempty"` // The number of worker nodes of the node pool. NodeCount *int32 `json:"nodeCount"` - // The Kubernetes version running in the node pool. Note that this imposes restrictions on which Kubernetes versions can run in the node pools of a cluster. Also, not all Kubernetes versions are suitable upgrade targets for all earlier versions. - K8sVersion *string `json:"k8sVersion,omitempty"` - MaintenanceWindow *KubernetesMaintenanceWindow `json:"maintenanceWindow,omitempty"` - AutoScaling *KubernetesAutoScaling `json:"autoScaling,omitempty"` - // The array of existing private LANs to attach to worker nodes. - Lans *[]KubernetesNodePoolLan `json:"lans,omitempty"` - // The labels attached to the node pool. - Labels *map[string]string `json:"labels,omitempty"` - // The annotations attached to the node pool. - Annotations *map[string]string `json:"annotations,omitempty"` // Optional array of reserved public IP addresses to be used by the nodes. The IPs must be from the exact location of the node pool's data center. If autoscaling is used, the array must contain one more IP than the maximum possible number of nodes (nodeCount+1 for a fixed number of nodes or maxNodeCount+1). The extra IP is used when the nodes are rebuilt. PublicIps *[]string `json:"publicIps,omitempty"` } @@ -54,76 +54,76 @@ func NewKubernetesNodePoolPropertiesForPutWithDefaults() *KubernetesNodePoolProp return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePoolPropertiesForPut) GetName() *string { +// GetAnnotations returns the Annotations field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPut) GetAnnotations() *map[string]string { if o == nil { return nil } - return o.Name + return o.Annotations } -// GetNameOk returns a tuple with the Name field value +// GetAnnotationsOk returns a tuple with the Annotations field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPut) GetNameOk() (*string, bool) { +func (o *KubernetesNodePoolPropertiesForPut) GetAnnotationsOk() (*map[string]string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.Annotations, true } -// SetName sets field value -func (o *KubernetesNodePoolPropertiesForPut) SetName(v string) { +// SetAnnotations sets field value +func (o *KubernetesNodePoolPropertiesForPut) SetAnnotations(v map[string]string) { - o.Name = &v + o.Annotations = &v } -// HasName returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPut) HasName() bool { - if o != nil && o.Name != nil { +// HasAnnotations returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPut) HasAnnotations() bool { + if o != nil && o.Annotations != nil { return true } return false } -// GetNodeCount returns the NodeCount field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *KubernetesNodePoolPropertiesForPut) GetNodeCount() *int32 { +// GetAutoScaling returns the AutoScaling field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPut) GetAutoScaling() *KubernetesAutoScaling { if o == nil { return nil } - return o.NodeCount + return o.AutoScaling } -// GetNodeCountOk returns a tuple with the NodeCount field value +// GetAutoScalingOk returns a tuple with the AutoScaling field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPut) GetNodeCountOk() (*int32, bool) { +func (o *KubernetesNodePoolPropertiesForPut) GetAutoScalingOk() (*KubernetesAutoScaling, bool) { if o == nil { return nil, false } - return o.NodeCount, true + return o.AutoScaling, true } -// SetNodeCount sets field value -func (o *KubernetesNodePoolPropertiesForPut) SetNodeCount(v int32) { +// SetAutoScaling sets field value +func (o *KubernetesNodePoolPropertiesForPut) SetAutoScaling(v KubernetesAutoScaling) { - o.NodeCount = &v + o.AutoScaling = &v } -// HasNodeCount returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPut) HasNodeCount() bool { - if o != nil && o.NodeCount != nil { +// HasAutoScaling returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPut) HasAutoScaling() bool { + if o != nil && o.AutoScaling != nil { return true } @@ -131,7 +131,7 @@ func (o *KubernetesNodePoolPropertiesForPut) HasNodeCount() bool { } // GetK8sVersion returns the K8sVersion field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesNodePoolPropertiesForPut) GetK8sVersion() *string { if o == nil { return nil @@ -168,190 +168,190 @@ func (o *KubernetesNodePoolPropertiesForPut) HasK8sVersion() bool { return false } -// GetMaintenanceWindow returns the MaintenanceWindow field value -// If the value is explicit nil, the zero value for KubernetesMaintenanceWindow will be returned -func (o *KubernetesNodePoolPropertiesForPut) GetMaintenanceWindow() *KubernetesMaintenanceWindow { +// GetLabels returns the Labels field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPut) GetLabels() *map[string]string { if o == nil { return nil } - return o.MaintenanceWindow + return o.Labels } -// GetMaintenanceWindowOk returns a tuple with the MaintenanceWindow field value +// GetLabelsOk returns a tuple with the Labels field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPut) GetMaintenanceWindowOk() (*KubernetesMaintenanceWindow, bool) { +func (o *KubernetesNodePoolPropertiesForPut) GetLabelsOk() (*map[string]string, bool) { if o == nil { return nil, false } - return o.MaintenanceWindow, true + return o.Labels, true } -// SetMaintenanceWindow sets field value -func (o *KubernetesNodePoolPropertiesForPut) SetMaintenanceWindow(v KubernetesMaintenanceWindow) { +// SetLabels sets field value +func (o *KubernetesNodePoolPropertiesForPut) SetLabels(v map[string]string) { - o.MaintenanceWindow = &v + o.Labels = &v } -// HasMaintenanceWindow returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPut) HasMaintenanceWindow() bool { - if o != nil && o.MaintenanceWindow != nil { +// HasLabels returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPut) HasLabels() bool { + if o != nil && o.Labels != nil { return true } return false } -// GetAutoScaling returns the AutoScaling field value -// If the value is explicit nil, the zero value for KubernetesAutoScaling will be returned -func (o *KubernetesNodePoolPropertiesForPut) GetAutoScaling() *KubernetesAutoScaling { +// GetLans returns the Lans field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPut) GetLans() *[]KubernetesNodePoolLan { if o == nil { return nil } - return o.AutoScaling + return o.Lans } -// GetAutoScalingOk returns a tuple with the AutoScaling field value +// GetLansOk returns a tuple with the Lans field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPut) GetAutoScalingOk() (*KubernetesAutoScaling, bool) { +func (o *KubernetesNodePoolPropertiesForPut) GetLansOk() (*[]KubernetesNodePoolLan, bool) { if o == nil { return nil, false } - return o.AutoScaling, true + return o.Lans, true } -// SetAutoScaling sets field value -func (o *KubernetesNodePoolPropertiesForPut) SetAutoScaling(v KubernetesAutoScaling) { +// SetLans sets field value +func (o *KubernetesNodePoolPropertiesForPut) SetLans(v []KubernetesNodePoolLan) { - o.AutoScaling = &v + o.Lans = &v } -// HasAutoScaling returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPut) HasAutoScaling() bool { - if o != nil && o.AutoScaling != nil { +// HasLans returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPut) HasLans() bool { + if o != nil && o.Lans != nil { return true } return false } -// GetLans returns the Lans field value -// If the value is explicit nil, the zero value for []KubernetesNodePoolLan will be returned -func (o *KubernetesNodePoolPropertiesForPut) GetLans() *[]KubernetesNodePoolLan { +// GetMaintenanceWindow returns the MaintenanceWindow field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPut) GetMaintenanceWindow() *KubernetesMaintenanceWindow { if o == nil { return nil } - return o.Lans + return o.MaintenanceWindow } -// GetLansOk returns a tuple with the Lans field value +// GetMaintenanceWindowOk returns a tuple with the MaintenanceWindow field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPut) GetLansOk() (*[]KubernetesNodePoolLan, bool) { +func (o *KubernetesNodePoolPropertiesForPut) GetMaintenanceWindowOk() (*KubernetesMaintenanceWindow, bool) { if o == nil { return nil, false } - return o.Lans, true + return o.MaintenanceWindow, true } -// SetLans sets field value -func (o *KubernetesNodePoolPropertiesForPut) SetLans(v []KubernetesNodePoolLan) { +// SetMaintenanceWindow sets field value +func (o *KubernetesNodePoolPropertiesForPut) SetMaintenanceWindow(v KubernetesMaintenanceWindow) { - o.Lans = &v + o.MaintenanceWindow = &v } -// HasLans returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPut) HasLans() bool { - if o != nil && o.Lans != nil { +// HasMaintenanceWindow returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPut) HasMaintenanceWindow() bool { + if o != nil && o.MaintenanceWindow != nil { return true } return false } -// GetLabels returns the Labels field value -// If the value is explicit nil, the zero value for map[string]string will be returned -func (o *KubernetesNodePoolPropertiesForPut) GetLabels() *map[string]string { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPut) GetName() *string { if o == nil { return nil } - return o.Labels + return o.Name } -// GetLabelsOk returns a tuple with the Labels field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPut) GetLabelsOk() (*map[string]string, bool) { +func (o *KubernetesNodePoolPropertiesForPut) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.Labels, true + return o.Name, true } -// SetLabels sets field value -func (o *KubernetesNodePoolPropertiesForPut) SetLabels(v map[string]string) { +// SetName sets field value +func (o *KubernetesNodePoolPropertiesForPut) SetName(v string) { - o.Labels = &v + o.Name = &v } -// HasLabels returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPut) HasLabels() bool { - if o != nil && o.Labels != nil { +// HasName returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPut) HasName() bool { + if o != nil && o.Name != nil { return true } return false } -// GetAnnotations returns the Annotations field value -// If the value is explicit nil, the zero value for map[string]string will be returned -func (o *KubernetesNodePoolPropertiesForPut) GetAnnotations() *map[string]string { +// GetNodeCount returns the NodeCount field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePoolPropertiesForPut) GetNodeCount() *int32 { if o == nil { return nil } - return o.Annotations + return o.NodeCount } -// GetAnnotationsOk returns a tuple with the Annotations field value +// GetNodeCountOk returns a tuple with the NodeCount field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePoolPropertiesForPut) GetAnnotationsOk() (*map[string]string, bool) { +func (o *KubernetesNodePoolPropertiesForPut) GetNodeCountOk() (*int32, bool) { if o == nil { return nil, false } - return o.Annotations, true + return o.NodeCount, true } -// SetAnnotations sets field value -func (o *KubernetesNodePoolPropertiesForPut) SetAnnotations(v map[string]string) { +// SetNodeCount sets field value +func (o *KubernetesNodePoolPropertiesForPut) SetNodeCount(v int32) { - o.Annotations = &v + o.NodeCount = &v } -// HasAnnotations returns a boolean if a field has been set. -func (o *KubernetesNodePoolPropertiesForPut) HasAnnotations() bool { - if o != nil && o.Annotations != nil { +// HasNodeCount returns a boolean if a field has been set. +func (o *KubernetesNodePoolPropertiesForPut) HasNodeCount() bool { + if o != nil && o.NodeCount != nil { return true } @@ -359,7 +359,7 @@ func (o *KubernetesNodePoolPropertiesForPut) HasAnnotations() bool { } // GetPublicIps returns the PublicIps field value -// If the value is explicit nil, the zero value for []string will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesNodePoolPropertiesForPut) GetPublicIps() *[]string { if o == nil { return nil @@ -398,33 +398,42 @@ func (o *KubernetesNodePoolPropertiesForPut) HasPublicIps() bool { func (o KubernetesNodePoolPropertiesForPut) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name + if o.Annotations != nil { + toSerialize["annotations"] = o.Annotations } - if o.NodeCount != nil { - toSerialize["nodeCount"] = o.NodeCount + + if o.AutoScaling != nil { + toSerialize["autoScaling"] = o.AutoScaling } + if o.K8sVersion != nil { toSerialize["k8sVersion"] = o.K8sVersion } - if o.MaintenanceWindow != nil { - toSerialize["maintenanceWindow"] = o.MaintenanceWindow - } - if o.AutoScaling != nil { - toSerialize["autoScaling"] = o.AutoScaling + + if o.Labels != nil { + toSerialize["labels"] = o.Labels } + if o.Lans != nil { toSerialize["lans"] = o.Lans } - if o.Labels != nil { - toSerialize["labels"] = o.Labels + + if o.MaintenanceWindow != nil { + toSerialize["maintenanceWindow"] = o.MaintenanceWindow } - if o.Annotations != nil { - toSerialize["annotations"] = o.Annotations + + if o.Name != nil { + toSerialize["name"] = o.Name } + + if o.NodeCount != nil { + toSerialize["nodeCount"] = o.NodeCount + } + if o.PublicIps != nil { toSerialize["publicIps"] = o.PublicIps } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pools.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pools.go index 61df80e6dba..50ebf55680c 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pools.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_pools.go @@ -16,14 +16,14 @@ import ( // KubernetesNodePools struct for KubernetesNodePools type KubernetesNodePools struct { - // A unique representation of the Kubernetes node pool as a resource collection. - Id *string `json:"id,omitempty"` - // The resource type within a collection. - Type *string `json:"type,omitempty"` // The URL to the collection representation (absolute path). Href *string `json:"href,omitempty"` + // A unique representation of the Kubernetes node pool as a resource collection. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]KubernetesNodePool `json:"items,omitempty"` + // The resource type within a collection. + Type *string `json:"type,omitempty"` } // NewKubernetesNodePools instantiates a new KubernetesNodePools object @@ -44,152 +44,152 @@ func NewKubernetesNodePoolsWithDefaults() *KubernetesNodePools { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePools) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePools) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePools) GetIdOk() (*string, bool) { +func (o *KubernetesNodePools) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *KubernetesNodePools) SetId(v string) { +// SetHref sets field value +func (o *KubernetesNodePools) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *KubernetesNodePools) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *KubernetesNodePools) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePools) GetType() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePools) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePools) GetTypeOk() (*string, bool) { +func (o *KubernetesNodePools) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *KubernetesNodePools) SetType(v string) { +// SetId sets field value +func (o *KubernetesNodePools) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *KubernetesNodePools) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *KubernetesNodePools) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodePools) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePools) GetItems() *[]KubernetesNodePool { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePools) GetHrefOk() (*string, bool) { +func (o *KubernetesNodePools) GetItemsOk() (*[]KubernetesNodePool, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *KubernetesNodePools) SetHref(v string) { +// SetItems sets field value +func (o *KubernetesNodePools) SetItems(v []KubernetesNodePool) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *KubernetesNodePools) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *KubernetesNodePools) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []KubernetesNodePool will be returned -func (o *KubernetesNodePools) GetItems() *[]KubernetesNodePool { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodePools) GetType() *string { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodePools) GetItemsOk() (*[]KubernetesNodePool, bool) { +func (o *KubernetesNodePools) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *KubernetesNodePools) SetItems(v []KubernetesNodePool) { +// SetType sets field value +func (o *KubernetesNodePools) SetType(v string) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *KubernetesNodePools) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *KubernetesNodePools) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *KubernetesNodePools) HasItems() bool { func (o KubernetesNodePools) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_properties.go index 652521484c2..e5f67c963a9 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_node_properties.go @@ -16,25 +16,25 @@ import ( // KubernetesNodeProperties struct for KubernetesNodeProperties type KubernetesNodeProperties struct { + // The Kubernetes version running in the node pool. Note that this imposes restrictions on which Kubernetes versions can run in the node pools of a cluster. Also, not all Kubernetes versions are suitable upgrade targets for all earlier versions. + K8sVersion *string `json:"k8sVersion"` // The Kubernetes node name. Name *string `json:"name"` - // The public IP associated with the node. - PublicIP *string `json:"publicIP,omitempty"` // The private IP associated with the node. PrivateIP *string `json:"privateIP,omitempty"` - // The Kubernetes version running in the node pool. Note that this imposes restrictions on which Kubernetes versions can run in the node pools of a cluster. Also, not all Kubernetes versions are suitable upgrade targets for all earlier versions. - K8sVersion *string `json:"k8sVersion"` + // The public IP associated with the node. + PublicIP *string `json:"publicIP,omitempty"` } // NewKubernetesNodeProperties instantiates a new KubernetesNodeProperties object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewKubernetesNodeProperties(name string, k8sVersion string) *KubernetesNodeProperties { +func NewKubernetesNodeProperties(k8sVersion string, name string) *KubernetesNodeProperties { this := KubernetesNodeProperties{} - this.Name = &name this.K8sVersion = &k8sVersion + this.Name = &name return &this } @@ -47,76 +47,76 @@ func NewKubernetesNodePropertiesWithDefaults() *KubernetesNodeProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodeProperties) GetName() *string { +// GetK8sVersion returns the K8sVersion field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodeProperties) GetK8sVersion() *string { if o == nil { return nil } - return o.Name + return o.K8sVersion } -// GetNameOk returns a tuple with the Name field value +// GetK8sVersionOk returns a tuple with the K8sVersion field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodeProperties) GetNameOk() (*string, bool) { +func (o *KubernetesNodeProperties) GetK8sVersionOk() (*string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.K8sVersion, true } -// SetName sets field value -func (o *KubernetesNodeProperties) SetName(v string) { +// SetK8sVersion sets field value +func (o *KubernetesNodeProperties) SetK8sVersion(v string) { - o.Name = &v + o.K8sVersion = &v } -// HasName returns a boolean if a field has been set. -func (o *KubernetesNodeProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasK8sVersion returns a boolean if a field has been set. +func (o *KubernetesNodeProperties) HasK8sVersion() bool { + if o != nil && o.K8sVersion != nil { return true } return false } -// GetPublicIP returns the PublicIP field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodeProperties) GetPublicIP() *string { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodeProperties) GetName() *string { if o == nil { return nil } - return o.PublicIP + return o.Name } -// GetPublicIPOk returns a tuple with the PublicIP field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodeProperties) GetPublicIPOk() (*string, bool) { +func (o *KubernetesNodeProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.PublicIP, true + return o.Name, true } -// SetPublicIP sets field value -func (o *KubernetesNodeProperties) SetPublicIP(v string) { +// SetName sets field value +func (o *KubernetesNodeProperties) SetName(v string) { - o.PublicIP = &v + o.Name = &v } -// HasPublicIP returns a boolean if a field has been set. -func (o *KubernetesNodeProperties) HasPublicIP() bool { - if o != nil && o.PublicIP != nil { +// HasName returns a boolean if a field has been set. +func (o *KubernetesNodeProperties) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -124,7 +124,7 @@ func (o *KubernetesNodeProperties) HasPublicIP() bool { } // GetPrivateIP returns the PrivateIP field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *KubernetesNodeProperties) GetPrivateIP() *string { if o == nil { return nil @@ -161,38 +161,38 @@ func (o *KubernetesNodeProperties) HasPrivateIP() bool { return false } -// GetK8sVersion returns the K8sVersion field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodeProperties) GetK8sVersion() *string { +// GetPublicIP returns the PublicIP field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodeProperties) GetPublicIP() *string { if o == nil { return nil } - return o.K8sVersion + return o.PublicIP } -// GetK8sVersionOk returns a tuple with the K8sVersion field value +// GetPublicIPOk returns a tuple with the PublicIP field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodeProperties) GetK8sVersionOk() (*string, bool) { +func (o *KubernetesNodeProperties) GetPublicIPOk() (*string, bool) { if o == nil { return nil, false } - return o.K8sVersion, true + return o.PublicIP, true } -// SetK8sVersion sets field value -func (o *KubernetesNodeProperties) SetK8sVersion(v string) { +// SetPublicIP sets field value +func (o *KubernetesNodeProperties) SetPublicIP(v string) { - o.K8sVersion = &v + o.PublicIP = &v } -// HasK8sVersion returns a boolean if a field has been set. -func (o *KubernetesNodeProperties) HasK8sVersion() bool { - if o != nil && o.K8sVersion != nil { +// HasPublicIP returns a boolean if a field has been set. +func (o *KubernetesNodeProperties) HasPublicIP() bool { + if o != nil && o.PublicIP != nil { return true } @@ -201,18 +201,22 @@ func (o *KubernetesNodeProperties) HasK8sVersion() bool { func (o KubernetesNodeProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} + if o.K8sVersion != nil { + toSerialize["k8sVersion"] = o.K8sVersion + } + if o.Name != nil { toSerialize["name"] = o.Name } - if o.PublicIP != nil { - toSerialize["publicIP"] = o.PublicIP - } + if o.PrivateIP != nil { toSerialize["privateIP"] = o.PrivateIP } - if o.K8sVersion != nil { - toSerialize["k8sVersion"] = o.K8sVersion + + if o.PublicIP != nil { + toSerialize["publicIP"] = o.PublicIP } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_nodes.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_nodes.go index e54f0c8d0dd..a96c038486a 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_nodes.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_kubernetes_nodes.go @@ -16,14 +16,14 @@ import ( // KubernetesNodes struct for KubernetesNodes type KubernetesNodes struct { - // A unique representation of the Kubernetes node pool as a resource collection. - Id *string `json:"id,omitempty"` - // The resource type within a collection. - Type *string `json:"type,omitempty"` // The URL to the collection representation (absolute path). Href *string `json:"href,omitempty"` + // A unique representation of the Kubernetes node pool as a resource collection. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]KubernetesNode `json:"items,omitempty"` + // The resource type within a collection. + Type *string `json:"type,omitempty"` } // NewKubernetesNodes instantiates a new KubernetesNodes object @@ -44,152 +44,152 @@ func NewKubernetesNodesWithDefaults() *KubernetesNodes { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodes) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodes) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodes) GetIdOk() (*string, bool) { +func (o *KubernetesNodes) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *KubernetesNodes) SetId(v string) { +// SetHref sets field value +func (o *KubernetesNodes) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *KubernetesNodes) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *KubernetesNodes) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodes) GetType() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodes) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodes) GetTypeOk() (*string, bool) { +func (o *KubernetesNodes) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *KubernetesNodes) SetType(v string) { +// SetId sets field value +func (o *KubernetesNodes) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *KubernetesNodes) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *KubernetesNodes) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *KubernetesNodes) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodes) GetItems() *[]KubernetesNode { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodes) GetHrefOk() (*string, bool) { +func (o *KubernetesNodes) GetItemsOk() (*[]KubernetesNode, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *KubernetesNodes) SetHref(v string) { +// SetItems sets field value +func (o *KubernetesNodes) SetItems(v []KubernetesNode) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *KubernetesNodes) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *KubernetesNodes) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []KubernetesNode will be returned -func (o *KubernetesNodes) GetItems() *[]KubernetesNode { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *KubernetesNodes) GetType() *string { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *KubernetesNodes) GetItemsOk() (*[]KubernetesNode, bool) { +func (o *KubernetesNodes) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *KubernetesNodes) SetItems(v []KubernetesNode) { +// SetType sets field value +func (o *KubernetesNodes) SetType(v string) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *KubernetesNodes) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *KubernetesNodes) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *KubernetesNodes) HasItems() bool { func (o KubernetesNodes) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_label.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_label.go index c162e676334..f28f2af5936 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_label.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_label.go @@ -16,14 +16,14 @@ import ( // Label struct for Label type Label struct { - // Label is identified using standard URN. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *string `json:"type,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // Label is identified using standard URN. + Id *string `json:"id,omitempty"` Metadata *NoStateMetaData `json:"metadata,omitempty"` Properties *LabelProperties `json:"properties"` + // The type of object that has been created. + Type *string `json:"type,omitempty"` } // NewLabel instantiates a new Label object @@ -46,190 +46,190 @@ func NewLabelWithDefaults() *Label { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Label) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Label) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Label) GetIdOk() (*string, bool) { +func (o *Label) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Label) SetId(v string) { +// SetHref sets field value +func (o *Label) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Label) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Label) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Label) GetType() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Label) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Label) GetTypeOk() (*string, bool) { +func (o *Label) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Label) SetType(v string) { +// SetId sets field value +func (o *Label) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Label) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Label) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Label) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *Label) GetMetadata() *NoStateMetaData { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Label) GetHrefOk() (*string, bool) { +func (o *Label) GetMetadataOk() (*NoStateMetaData, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *Label) SetHref(v string) { +// SetMetadata sets field value +func (o *Label) SetMetadata(v NoStateMetaData) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *Label) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *Label) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for NoStateMetaData will be returned -func (o *Label) GetMetadata() *NoStateMetaData { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *Label) GetProperties() *LabelProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Label) GetMetadataOk() (*NoStateMetaData, bool) { +func (o *Label) GetPropertiesOk() (*LabelProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *Label) SetMetadata(v NoStateMetaData) { +// SetProperties sets field value +func (o *Label) SetProperties(v LabelProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *Label) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *Label) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for LabelProperties will be returned -func (o *Label) GetProperties() *LabelProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Label) GetType() *string { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Label) GetPropertiesOk() (*LabelProperties, bool) { +func (o *Label) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *Label) SetProperties(v LabelProperties) { +// SetType sets field value +func (o *Label) SetType(v string) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *Label) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *Label) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *Label) HasProperties() bool { func (o Label) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_properties.go index a7a0d794cf5..f561a5fb773 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_properties.go @@ -18,14 +18,14 @@ import ( type LabelProperties struct { // A label key Key *string `json:"key,omitempty"` - // A label value - Value *string `json:"value,omitempty"` + // URL to the Resource (absolute path) on which the label is applied. + ResourceHref *string `json:"resourceHref,omitempty"` // The ID of the resource. ResourceId *string `json:"resourceId,omitempty"` // The type of the resource on which the label is applied. ResourceType *string `json:"resourceType,omitempty"` - // URL to the Resource (absolute path) on which the label is applied. - ResourceHref *string `json:"resourceHref,omitempty"` + // A label value + Value *string `json:"value,omitempty"` } // NewLabelProperties instantiates a new LabelProperties object @@ -47,7 +47,7 @@ func NewLabelPropertiesWithDefaults() *LabelProperties { } // GetKey returns the Key field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *LabelProperties) GetKey() *string { if o == nil { return nil @@ -84,38 +84,38 @@ func (o *LabelProperties) HasKey() bool { return false } -// GetValue returns the Value field value -// If the value is explicit nil, the zero value for string will be returned -func (o *LabelProperties) GetValue() *string { +// GetResourceHref returns the ResourceHref field value +// If the value is explicit nil, nil is returned +func (o *LabelProperties) GetResourceHref() *string { if o == nil { return nil } - return o.Value + return o.ResourceHref } -// GetValueOk returns a tuple with the Value field value +// GetResourceHrefOk returns a tuple with the ResourceHref field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LabelProperties) GetValueOk() (*string, bool) { +func (o *LabelProperties) GetResourceHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Value, true + return o.ResourceHref, true } -// SetValue sets field value -func (o *LabelProperties) SetValue(v string) { +// SetResourceHref sets field value +func (o *LabelProperties) SetResourceHref(v string) { - o.Value = &v + o.ResourceHref = &v } -// HasValue returns a boolean if a field has been set. -func (o *LabelProperties) HasValue() bool { - if o != nil && o.Value != nil { +// HasResourceHref returns a boolean if a field has been set. +func (o *LabelProperties) HasResourceHref() bool { + if o != nil && o.ResourceHref != nil { return true } @@ -123,7 +123,7 @@ func (o *LabelProperties) HasValue() bool { } // GetResourceId returns the ResourceId field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *LabelProperties) GetResourceId() *string { if o == nil { return nil @@ -161,7 +161,7 @@ func (o *LabelProperties) HasResourceId() bool { } // GetResourceType returns the ResourceType field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *LabelProperties) GetResourceType() *string { if o == nil { return nil @@ -198,38 +198,38 @@ func (o *LabelProperties) HasResourceType() bool { return false } -// GetResourceHref returns the ResourceHref field value -// If the value is explicit nil, the zero value for string will be returned -func (o *LabelProperties) GetResourceHref() *string { +// GetValue returns the Value field value +// If the value is explicit nil, nil is returned +func (o *LabelProperties) GetValue() *string { if o == nil { return nil } - return o.ResourceHref + return o.Value } -// GetResourceHrefOk returns a tuple with the ResourceHref field value +// GetValueOk returns a tuple with the Value field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LabelProperties) GetResourceHrefOk() (*string, bool) { +func (o *LabelProperties) GetValueOk() (*string, bool) { if o == nil { return nil, false } - return o.ResourceHref, true + return o.Value, true } -// SetResourceHref sets field value -func (o *LabelProperties) SetResourceHref(v string) { +// SetValue sets field value +func (o *LabelProperties) SetValue(v string) { - o.ResourceHref = &v + o.Value = &v } -// HasResourceHref returns a boolean if a field has been set. -func (o *LabelProperties) HasResourceHref() bool { - if o != nil && o.ResourceHref != nil { +// HasValue returns a boolean if a field has been set. +func (o *LabelProperties) HasValue() bool { + if o != nil && o.Value != nil { return true } @@ -241,18 +241,23 @@ func (o LabelProperties) MarshalJSON() ([]byte, error) { if o.Key != nil { toSerialize["key"] = o.Key } - if o.Value != nil { - toSerialize["value"] = o.Value + + if o.ResourceHref != nil { + toSerialize["resourceHref"] = o.ResourceHref } + if o.ResourceId != nil { toSerialize["resourceId"] = o.ResourceId } + if o.ResourceType != nil { toSerialize["resourceType"] = o.ResourceType } - if o.ResourceHref != nil { - toSerialize["resourceHref"] = o.ResourceHref + + if o.Value != nil { + toSerialize["value"] = o.Value } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_resource.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_resource.go index 29ebef96dfe..9963122acc9 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_resource.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_resource.go @@ -16,14 +16,14 @@ import ( // LabelResource struct for LabelResource type LabelResource struct { - // Label on a resource is identified using label key. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *string `json:"type,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // Label on a resource is identified using label key. + Id *string `json:"id,omitempty"` Metadata *NoStateMetaData `json:"metadata,omitempty"` Properties *LabelResourceProperties `json:"properties"` + // The type of object that has been created. + Type *string `json:"type,omitempty"` } // NewLabelResource instantiates a new LabelResource object @@ -46,190 +46,190 @@ func NewLabelResourceWithDefaults() *LabelResource { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *LabelResource) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *LabelResource) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LabelResource) GetIdOk() (*string, bool) { +func (o *LabelResource) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *LabelResource) SetId(v string) { +// SetHref sets field value +func (o *LabelResource) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *LabelResource) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *LabelResource) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *LabelResource) GetType() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *LabelResource) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LabelResource) GetTypeOk() (*string, bool) { +func (o *LabelResource) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *LabelResource) SetType(v string) { +// SetId sets field value +func (o *LabelResource) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *LabelResource) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *LabelResource) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *LabelResource) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *LabelResource) GetMetadata() *NoStateMetaData { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LabelResource) GetHrefOk() (*string, bool) { +func (o *LabelResource) GetMetadataOk() (*NoStateMetaData, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *LabelResource) SetHref(v string) { +// SetMetadata sets field value +func (o *LabelResource) SetMetadata(v NoStateMetaData) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *LabelResource) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *LabelResource) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for NoStateMetaData will be returned -func (o *LabelResource) GetMetadata() *NoStateMetaData { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *LabelResource) GetProperties() *LabelResourceProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LabelResource) GetMetadataOk() (*NoStateMetaData, bool) { +func (o *LabelResource) GetPropertiesOk() (*LabelResourceProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *LabelResource) SetMetadata(v NoStateMetaData) { +// SetProperties sets field value +func (o *LabelResource) SetProperties(v LabelResourceProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *LabelResource) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *LabelResource) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for LabelResourceProperties will be returned -func (o *LabelResource) GetProperties() *LabelResourceProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *LabelResource) GetType() *string { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LabelResource) GetPropertiesOk() (*LabelResourceProperties, bool) { +func (o *LabelResource) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *LabelResource) SetProperties(v LabelResourceProperties) { +// SetType sets field value +func (o *LabelResource) SetType(v string) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *LabelResource) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *LabelResource) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *LabelResource) HasProperties() bool { func (o LabelResource) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_resource_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_resource_properties.go index ef0836dff59..e83bc0c9fcd 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_resource_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_resource_properties.go @@ -41,7 +41,7 @@ func NewLabelResourcePropertiesWithDefaults() *LabelResourceProperties { } // GetKey returns the Key field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *LabelResourceProperties) GetKey() *string { if o == nil { return nil @@ -79,7 +79,7 @@ func (o *LabelResourceProperties) HasKey() bool { } // GetValue returns the Value field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *LabelResourceProperties) GetValue() *string { if o == nil { return nil @@ -121,9 +121,11 @@ func (o LabelResourceProperties) MarshalJSON() ([]byte, error) { if o.Key != nil { toSerialize["key"] = o.Key } + if o.Value != nil { toSerialize["value"] = o.Value } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_resources.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_resources.go index 673f4f3283f..43bf07e052d 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_resources.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_label_resources.go @@ -16,19 +16,19 @@ import ( // LabelResources struct for LabelResources type LabelResources struct { - // A unique representation of the label as a resource collection. - Id *string `json:"id,omitempty"` - // The type of resource within a collection. - Type *string `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the collection representation (absolute path). Href *string `json:"href,omitempty"` + // A unique representation of the label as a resource collection. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]LabelResource `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of resource within a collection. + Type *string `json:"type,omitempty"` } // NewLabelResources instantiates a new LabelResources object @@ -49,114 +49,114 @@ func NewLabelResourcesWithDefaults() *LabelResources { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *LabelResources) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *LabelResources) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LabelResources) GetIdOk() (*string, bool) { +func (o *LabelResources) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *LabelResources) SetId(v string) { +// SetLinks sets field value +func (o *LabelResources) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *LabelResources) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *LabelResources) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *LabelResources) GetType() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *LabelResources) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LabelResources) GetTypeOk() (*string, bool) { +func (o *LabelResources) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *LabelResources) SetType(v string) { +// SetHref sets field value +func (o *LabelResources) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *LabelResources) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *LabelResources) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *LabelResources) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *LabelResources) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LabelResources) GetHrefOk() (*string, bool) { +func (o *LabelResources) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *LabelResources) SetHref(v string) { +// SetId sets field value +func (o *LabelResources) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *LabelResources) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *LabelResources) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *LabelResources) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []LabelResource will be returned +// If the value is explicit nil, nil is returned func (o *LabelResources) GetItems() *[]LabelResource { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *LabelResources) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *LabelResources) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *LabelResources) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LabelResources) GetOffsetOk() (*float32, bool) { +func (o *LabelResources) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *LabelResources) SetOffset(v float32) { +// SetLimit sets field value +func (o *LabelResources) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *LabelResources) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *LabelResources) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *LabelResources) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *LabelResources) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LabelResources) GetLimitOk() (*float32, bool) { +func (o *LabelResources) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *LabelResources) SetLimit(v float32) { +// SetOffset sets field value +func (o *LabelResources) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *LabelResources) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *LabelResources) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *LabelResources) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *LabelResources) GetType() *string { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LabelResources) GetLinksOk() (*PaginationLinks, bool) { +func (o *LabelResources) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *LabelResources) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *LabelResources) SetType(v string) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *LabelResources) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *LabelResources) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *LabelResources) HasLinks() bool { func (o LabelResources) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_labels.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_labels.go index d83bdbcfcd4..f2be7da33b5 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_labels.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_labels.go @@ -16,14 +16,14 @@ import ( // Labels struct for Labels type Labels struct { - // A unique representation of the label as a resource collection. - Id *string `json:"id,omitempty"` - // The type of resource within a collection. - Type *string `json:"type,omitempty"` // URL to the collection representation (absolute path). Href *string `json:"href,omitempty"` + // A unique representation of the label as a resource collection. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Label `json:"items,omitempty"` + // The type of resource within a collection. + Type *string `json:"type,omitempty"` } // NewLabels instantiates a new Labels object @@ -44,152 +44,152 @@ func NewLabelsWithDefaults() *Labels { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Labels) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Labels) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Labels) GetIdOk() (*string, bool) { +func (o *Labels) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Labels) SetId(v string) { +// SetHref sets field value +func (o *Labels) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Labels) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Labels) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Labels) GetType() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Labels) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Labels) GetTypeOk() (*string, bool) { +func (o *Labels) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Labels) SetType(v string) { +// SetId sets field value +func (o *Labels) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Labels) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Labels) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Labels) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *Labels) GetItems() *[]Label { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Labels) GetHrefOk() (*string, bool) { +func (o *Labels) GetItemsOk() (*[]Label, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *Labels) SetHref(v string) { +// SetItems sets field value +func (o *Labels) SetItems(v []Label) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *Labels) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *Labels) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Label will be returned -func (o *Labels) GetItems() *[]Label { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Labels) GetType() *string { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Labels) GetItemsOk() (*[]Label, bool) { +func (o *Labels) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *Labels) SetItems(v []Label) { +// SetType sets field value +func (o *Labels) SetType(v string) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *Labels) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *Labels) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *Labels) HasItems() bool { func (o Labels) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan.go index 120c2f17f53..09a44f4e375 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan.go @@ -16,15 +16,15 @@ import ( // Lan struct for Lan type Lan struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Entities *LanEntities `json:"entities,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *LanProperties `json:"properties"` - Entities *LanEntities `json:"entities,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewLan instantiates a new Lan object @@ -47,114 +47,114 @@ func NewLanWithDefaults() *Lan { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Lan) GetId() *string { +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *Lan) GetEntities() *LanEntities { if o == nil { return nil } - return o.Id + return o.Entities } -// GetIdOk returns a tuple with the Id field value +// GetEntitiesOk returns a tuple with the Entities field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Lan) GetIdOk() (*string, bool) { +func (o *Lan) GetEntitiesOk() (*LanEntities, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Entities, true } -// SetId sets field value -func (o *Lan) SetId(v string) { +// SetEntities sets field value +func (o *Lan) SetEntities(v LanEntities) { - o.Id = &v + o.Entities = &v } -// HasId returns a boolean if a field has been set. -func (o *Lan) HasId() bool { - if o != nil && o.Id != nil { +// HasEntities returns a boolean if a field has been set. +func (o *Lan) HasEntities() bool { + if o != nil && o.Entities != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Lan) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Lan) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Lan) GetTypeOk() (*Type, bool) { +func (o *Lan) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Lan) SetType(v Type) { +// SetHref sets field value +func (o *Lan) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Lan) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Lan) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Lan) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Lan) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Lan) GetHrefOk() (*string, bool) { +func (o *Lan) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Lan) SetHref(v string) { +// SetId sets field value +func (o *Lan) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Lan) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Lan) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -162,7 +162,7 @@ func (o *Lan) HasHref() bool { } // GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned +// If the value is explicit nil, nil is returned func (o *Lan) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil @@ -200,7 +200,7 @@ func (o *Lan) HasMetadata() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for LanProperties will be returned +// If the value is explicit nil, nil is returned func (o *Lan) GetProperties() *LanProperties { if o == nil { return nil @@ -237,38 +237,38 @@ func (o *Lan) HasProperties() bool { return false } -// GetEntities returns the Entities field value -// If the value is explicit nil, the zero value for LanEntities will be returned -func (o *Lan) GetEntities() *LanEntities { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Lan) GetType() *Type { if o == nil { return nil } - return o.Entities + return o.Type } -// GetEntitiesOk returns a tuple with the Entities field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Lan) GetEntitiesOk() (*LanEntities, bool) { +func (o *Lan) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Entities, true + return o.Type, true } -// SetEntities sets field value -func (o *Lan) SetEntities(v LanEntities) { +// SetType sets field value +func (o *Lan) SetType(v Type) { - o.Entities = &v + o.Type = &v } -// HasEntities returns a boolean if a field has been set. -func (o *Lan) HasEntities() bool { - if o != nil && o.Entities != nil { +// HasType returns a boolean if a field has been set. +func (o *Lan) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -277,24 +277,30 @@ func (o *Lan) HasEntities() bool { func (o Lan) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Entities != nil { + toSerialize["entities"] = o.Entities } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } - if o.Entities != nil { - toSerialize["entities"] = o.Entities + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_entities.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_entities.go index f4d242ac811..368746a4323 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_entities.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_entities.go @@ -38,7 +38,7 @@ func NewLanEntitiesWithDefaults() *LanEntities { } // GetNics returns the Nics field value -// If the value is explicit nil, the zero value for LanNics will be returned +// If the value is explicit nil, nil is returned func (o *LanEntities) GetNics() *LanNics { if o == nil { return nil @@ -80,6 +80,7 @@ func (o LanEntities) MarshalJSON() ([]byte, error) { if o.Nics != nil { toSerialize["nics"] = o.Nics } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_nics.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_nics.go index f348c1458a4..06cc683fe5f 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_nics.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_nics.go @@ -16,19 +16,19 @@ import ( // LanNics struct for LanNics type LanNics struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Nic `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewLanNics instantiates a new LanNics object @@ -49,114 +49,114 @@ func NewLanNicsWithDefaults() *LanNics { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *LanNics) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *LanNics) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LanNics) GetIdOk() (*string, bool) { +func (o *LanNics) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *LanNics) SetId(v string) { +// SetLinks sets field value +func (o *LanNics) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *LanNics) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *LanNics) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *LanNics) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *LanNics) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LanNics) GetTypeOk() (*Type, bool) { +func (o *LanNics) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *LanNics) SetType(v Type) { +// SetHref sets field value +func (o *LanNics) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *LanNics) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *LanNics) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *LanNics) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *LanNics) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LanNics) GetHrefOk() (*string, bool) { +func (o *LanNics) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *LanNics) SetHref(v string) { +// SetId sets field value +func (o *LanNics) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *LanNics) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *LanNics) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *LanNics) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Nic will be returned +// If the value is explicit nil, nil is returned func (o *LanNics) GetItems() *[]Nic { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *LanNics) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *LanNics) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *LanNics) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LanNics) GetOffsetOk() (*float32, bool) { +func (o *LanNics) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *LanNics) SetOffset(v float32) { +// SetLimit sets field value +func (o *LanNics) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *LanNics) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *LanNics) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *LanNics) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *LanNics) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LanNics) GetLimitOk() (*float32, bool) { +func (o *LanNics) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *LanNics) SetLimit(v float32) { +// SetOffset sets field value +func (o *LanNics) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *LanNics) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *LanNics) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *LanNics) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *LanNics) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LanNics) GetLinksOk() (*PaginationLinks, bool) { +func (o *LanNics) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *LanNics) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *LanNics) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *LanNics) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *LanNics) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *LanNics) HasLinks() bool { func (o LanNics) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_post.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_post.go new file mode 100644 index 00000000000..ce97f15f027 --- /dev/null +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_post.go @@ -0,0 +1,341 @@ +/* + * CLOUD API + * + * IONOS Enterprise-grade Infrastructure as a Service (IaaS) solutions can be managed through the Cloud API, in addition or as an alternative to the \"Data Center Designer\" (DCD) browser-based tool. Both methods employ consistent concepts and features, deliver similar power and flexibility, and can be used to perform a multitude of management tasks, including adding servers, volumes, configuring networks, and so on. + * + * API version: 6.0 + */ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package ionoscloud + +import ( + "encoding/json" +) + +// LanPost struct for LanPost +type LanPost struct { + Entities *LanEntities `json:"entities,omitempty"` + // URL to the object representation (absolute path). + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` + Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` + Properties *LanPropertiesPost `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` +} + +// NewLanPost instantiates a new LanPost object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewLanPost(properties LanPropertiesPost) *LanPost { + this := LanPost{} + + this.Properties = &properties + + return &this +} + +// NewLanPostWithDefaults instantiates a new LanPost object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewLanPostWithDefaults() *LanPost { + this := LanPost{} + return &this +} + +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *LanPost) GetEntities() *LanEntities { + if o == nil { + return nil + } + + return o.Entities + +} + +// GetEntitiesOk returns a tuple with the Entities field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *LanPost) GetEntitiesOk() (*LanEntities, bool) { + if o == nil { + return nil, false + } + + return o.Entities, true +} + +// SetEntities sets field value +func (o *LanPost) SetEntities(v LanEntities) { + + o.Entities = &v + +} + +// HasEntities returns a boolean if a field has been set. +func (o *LanPost) HasEntities() bool { + if o != nil && o.Entities != nil { + return true + } + + return false +} + +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *LanPost) GetHref() *string { + if o == nil { + return nil + } + + return o.Href + +} + +// GetHrefOk returns a tuple with the Href field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *LanPost) GetHrefOk() (*string, bool) { + if o == nil { + return nil, false + } + + return o.Href, true +} + +// SetHref sets field value +func (o *LanPost) SetHref(v string) { + + o.Href = &v + +} + +// HasHref returns a boolean if a field has been set. +func (o *LanPost) HasHref() bool { + if o != nil && o.Href != nil { + return true + } + + return false +} + +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *LanPost) GetId() *string { + if o == nil { + return nil + } + + return o.Id + +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *LanPost) GetIdOk() (*string, bool) { + if o == nil { + return nil, false + } + + return o.Id, true +} + +// SetId sets field value +func (o *LanPost) SetId(v string) { + + o.Id = &v + +} + +// HasId returns a boolean if a field has been set. +func (o *LanPost) HasId() bool { + if o != nil && o.Id != nil { + return true + } + + return false +} + +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *LanPost) GetMetadata() *DatacenterElementMetadata { + if o == nil { + return nil + } + + return o.Metadata + +} + +// GetMetadataOk returns a tuple with the Metadata field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *LanPost) GetMetadataOk() (*DatacenterElementMetadata, bool) { + if o == nil { + return nil, false + } + + return o.Metadata, true +} + +// SetMetadata sets field value +func (o *LanPost) SetMetadata(v DatacenterElementMetadata) { + + o.Metadata = &v + +} + +// HasMetadata returns a boolean if a field has been set. +func (o *LanPost) HasMetadata() bool { + if o != nil && o.Metadata != nil { + return true + } + + return false +} + +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *LanPost) GetProperties() *LanPropertiesPost { + if o == nil { + return nil + } + + return o.Properties + +} + +// GetPropertiesOk returns a tuple with the Properties field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *LanPost) GetPropertiesOk() (*LanPropertiesPost, bool) { + if o == nil { + return nil, false + } + + return o.Properties, true +} + +// SetProperties sets field value +func (o *LanPost) SetProperties(v LanPropertiesPost) { + + o.Properties = &v + +} + +// HasProperties returns a boolean if a field has been set. +func (o *LanPost) HasProperties() bool { + if o != nil && o.Properties != nil { + return true + } + + return false +} + +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *LanPost) GetType() *Type { + if o == nil { + return nil + } + + return o.Type + +} + +// GetTypeOk returns a tuple with the Type field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *LanPost) GetTypeOk() (*Type, bool) { + if o == nil { + return nil, false + } + + return o.Type, true +} + +// SetType sets field value +func (o *LanPost) SetType(v Type) { + + o.Type = &v + +} + +// HasType returns a boolean if a field has been set. +func (o *LanPost) HasType() bool { + if o != nil && o.Type != nil { + return true + } + + return false +} + +func (o LanPost) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if o.Entities != nil { + toSerialize["entities"] = o.Entities + } + + if o.Href != nil { + toSerialize["href"] = o.Href + } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + + if o.Metadata != nil { + toSerialize["metadata"] = o.Metadata + } + + if o.Properties != nil { + toSerialize["properties"] = o.Properties + } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + + return json.Marshal(toSerialize) +} + +type NullableLanPost struct { + value *LanPost + isSet bool +} + +func (v NullableLanPost) Get() *LanPost { + return v.value +} + +func (v *NullableLanPost) Set(val *LanPost) { + v.value = val + v.isSet = true +} + +func (v NullableLanPost) IsSet() bool { + return v.isSet +} + +func (v *NullableLanPost) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableLanPost(val *LanPost) *NullableLanPost { + return &NullableLanPost{value: val, isSet: true} +} + +func (v NullableLanPost) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableLanPost) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_properties.go index 763ced62b1d..47af4d21839 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_properties.go @@ -16,10 +16,10 @@ import ( // LanProperties struct for LanProperties type LanProperties struct { - // The name of the resource. - Name *string `json:"name,omitempty"` // IP failover configurations for lan IpFailover *[]IPFailover `json:"ipFailover,omitempty"` + // The name of the resource. + Name *string `json:"name,omitempty"` // The unique identifier of the private Cross-Connect the LAN is connected to, if any. Pcc *string `json:"pcc,omitempty"` // This LAN faces the public Internet. @@ -44,76 +44,76 @@ func NewLanPropertiesWithDefaults() *LanProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *LanProperties) GetName() *string { +// GetIpFailover returns the IpFailover field value +// If the value is explicit nil, nil is returned +func (o *LanProperties) GetIpFailover() *[]IPFailover { if o == nil { return nil } - return o.Name + return o.IpFailover } -// GetNameOk returns a tuple with the Name field value +// GetIpFailoverOk returns a tuple with the IpFailover field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LanProperties) GetNameOk() (*string, bool) { +func (o *LanProperties) GetIpFailoverOk() (*[]IPFailover, bool) { if o == nil { return nil, false } - return o.Name, true + return o.IpFailover, true } -// SetName sets field value -func (o *LanProperties) SetName(v string) { +// SetIpFailover sets field value +func (o *LanProperties) SetIpFailover(v []IPFailover) { - o.Name = &v + o.IpFailover = &v } -// HasName returns a boolean if a field has been set. -func (o *LanProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasIpFailover returns a boolean if a field has been set. +func (o *LanProperties) HasIpFailover() bool { + if o != nil && o.IpFailover != nil { return true } return false } -// GetIpFailover returns the IpFailover field value -// If the value is explicit nil, the zero value for []IPFailover will be returned -func (o *LanProperties) GetIpFailover() *[]IPFailover { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *LanProperties) GetName() *string { if o == nil { return nil } - return o.IpFailover + return o.Name } -// GetIpFailoverOk returns a tuple with the IpFailover field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LanProperties) GetIpFailoverOk() (*[]IPFailover, bool) { +func (o *LanProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.IpFailover, true + return o.Name, true } -// SetIpFailover sets field value -func (o *LanProperties) SetIpFailover(v []IPFailover) { +// SetName sets field value +func (o *LanProperties) SetName(v string) { - o.IpFailover = &v + o.Name = &v } -// HasIpFailover returns a boolean if a field has been set. -func (o *LanProperties) HasIpFailover() bool { - if o != nil && o.IpFailover != nil { +// HasName returns a boolean if a field has been set. +func (o *LanProperties) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -121,7 +121,7 @@ func (o *LanProperties) HasIpFailover() bool { } // GetPcc returns the Pcc field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *LanProperties) GetPcc() *string { if o == nil { return nil @@ -159,7 +159,7 @@ func (o *LanProperties) HasPcc() bool { } // GetPublic returns the Public field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *LanProperties) GetPublic() *bool { if o == nil { return nil @@ -198,18 +198,22 @@ func (o *LanProperties) HasPublic() bool { func (o LanProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name - } if o.IpFailover != nil { toSerialize["ipFailover"] = o.IpFailover } + + if o.Name != nil { + toSerialize["name"] = o.Name + } + if o.Pcc != nil { toSerialize["pcc"] = o.Pcc } + if o.Public != nil { toSerialize["public"] = o.Public } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_properties_post.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_properties_post.go new file mode 100644 index 00000000000..c9761d28952 --- /dev/null +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_lan_properties_post.go @@ -0,0 +1,254 @@ +/* + * CLOUD API + * + * IONOS Enterprise-grade Infrastructure as a Service (IaaS) solutions can be managed through the Cloud API, in addition or as an alternative to the \"Data Center Designer\" (DCD) browser-based tool. Both methods employ consistent concepts and features, deliver similar power and flexibility, and can be used to perform a multitude of management tasks, including adding servers, volumes, configuring networks, and so on. + * + * API version: 6.0 + */ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package ionoscloud + +import ( + "encoding/json" +) + +// LanPropertiesPost struct for LanPropertiesPost +type LanPropertiesPost struct { + // IP failover configurations for lan + IpFailover *[]IPFailover `json:"ipFailover,omitempty"` + // The name of the resource. + Name *string `json:"name,omitempty"` + // The unique identifier of the private Cross-Connect the LAN is connected to, if any. + Pcc *string `json:"pcc,omitempty"` + // This LAN faces the public Internet. + Public *bool `json:"public,omitempty"` +} + +// NewLanPropertiesPost instantiates a new LanPropertiesPost object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewLanPropertiesPost() *LanPropertiesPost { + this := LanPropertiesPost{} + + return &this +} + +// NewLanPropertiesPostWithDefaults instantiates a new LanPropertiesPost object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewLanPropertiesPostWithDefaults() *LanPropertiesPost { + this := LanPropertiesPost{} + return &this +} + +// GetIpFailover returns the IpFailover field value +// If the value is explicit nil, nil is returned +func (o *LanPropertiesPost) GetIpFailover() *[]IPFailover { + if o == nil { + return nil + } + + return o.IpFailover + +} + +// GetIpFailoverOk returns a tuple with the IpFailover field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *LanPropertiesPost) GetIpFailoverOk() (*[]IPFailover, bool) { + if o == nil { + return nil, false + } + + return o.IpFailover, true +} + +// SetIpFailover sets field value +func (o *LanPropertiesPost) SetIpFailover(v []IPFailover) { + + o.IpFailover = &v + +} + +// HasIpFailover returns a boolean if a field has been set. +func (o *LanPropertiesPost) HasIpFailover() bool { + if o != nil && o.IpFailover != nil { + return true + } + + return false +} + +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *LanPropertiesPost) GetName() *string { + if o == nil { + return nil + } + + return o.Name + +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *LanPropertiesPost) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + + return o.Name, true +} + +// SetName sets field value +func (o *LanPropertiesPost) SetName(v string) { + + o.Name = &v + +} + +// HasName returns a boolean if a field has been set. +func (o *LanPropertiesPost) HasName() bool { + if o != nil && o.Name != nil { + return true + } + + return false +} + +// GetPcc returns the Pcc field value +// If the value is explicit nil, nil is returned +func (o *LanPropertiesPost) GetPcc() *string { + if o == nil { + return nil + } + + return o.Pcc + +} + +// GetPccOk returns a tuple with the Pcc field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *LanPropertiesPost) GetPccOk() (*string, bool) { + if o == nil { + return nil, false + } + + return o.Pcc, true +} + +// SetPcc sets field value +func (o *LanPropertiesPost) SetPcc(v string) { + + o.Pcc = &v + +} + +// HasPcc returns a boolean if a field has been set. +func (o *LanPropertiesPost) HasPcc() bool { + if o != nil && o.Pcc != nil { + return true + } + + return false +} + +// GetPublic returns the Public field value +// If the value is explicit nil, nil is returned +func (o *LanPropertiesPost) GetPublic() *bool { + if o == nil { + return nil + } + + return o.Public + +} + +// GetPublicOk returns a tuple with the Public field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *LanPropertiesPost) GetPublicOk() (*bool, bool) { + if o == nil { + return nil, false + } + + return o.Public, true +} + +// SetPublic sets field value +func (o *LanPropertiesPost) SetPublic(v bool) { + + o.Public = &v + +} + +// HasPublic returns a boolean if a field has been set. +func (o *LanPropertiesPost) HasPublic() bool { + if o != nil && o.Public != nil { + return true + } + + return false +} + +func (o LanPropertiesPost) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if o.IpFailover != nil { + toSerialize["ipFailover"] = o.IpFailover + } + + if o.Name != nil { + toSerialize["name"] = o.Name + } + + if o.Pcc != nil { + toSerialize["pcc"] = o.Pcc + } + + if o.Public != nil { + toSerialize["public"] = o.Public + } + + return json.Marshal(toSerialize) +} + +type NullableLanPropertiesPost struct { + value *LanPropertiesPost + isSet bool +} + +func (v NullableLanPropertiesPost) Get() *LanPropertiesPost { + return v.value +} + +func (v *NullableLanPropertiesPost) Set(val *LanPropertiesPost) { + v.value = val + v.isSet = true +} + +func (v NullableLanPropertiesPost) IsSet() bool { + return v.isSet +} + +func (v *NullableLanPropertiesPost) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableLanPropertiesPost(val *LanPropertiesPost) *NullableLanPropertiesPost { + return &NullableLanPropertiesPost{value: val, isSet: true} +} + +func (v NullableLanPropertiesPost) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableLanPropertiesPost) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_lans.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_lans.go index 361b3809f92..b0ee52ca2fd 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_lans.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_lans.go @@ -16,19 +16,19 @@ import ( // Lans struct for Lans type Lans struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Lan `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewLans instantiates a new Lans object @@ -49,114 +49,114 @@ func NewLansWithDefaults() *Lans { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Lans) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *Lans) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Lans) GetIdOk() (*string, bool) { +func (o *Lans) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *Lans) SetId(v string) { +// SetLinks sets field value +func (o *Lans) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *Lans) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *Lans) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Lans) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Lans) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Lans) GetTypeOk() (*Type, bool) { +func (o *Lans) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Lans) SetType(v Type) { +// SetHref sets field value +func (o *Lans) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Lans) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Lans) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Lans) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Lans) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Lans) GetHrefOk() (*string, bool) { +func (o *Lans) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Lans) SetHref(v string) { +// SetId sets field value +func (o *Lans) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Lans) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Lans) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *Lans) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Lan will be returned +// If the value is explicit nil, nil is returned func (o *Lans) GetItems() *[]Lan { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *Lans) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Lans) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *Lans) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Lans) GetOffsetOk() (*float32, bool) { +func (o *Lans) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *Lans) SetOffset(v float32) { +// SetLimit sets field value +func (o *Lans) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *Lans) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *Lans) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Lans) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *Lans) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Lans) GetLimitOk() (*float32, bool) { +func (o *Lans) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *Lans) SetLimit(v float32) { +// SetOffset sets field value +func (o *Lans) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *Lans) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *Lans) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *Lans) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Lans) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Lans) GetLinksOk() (*PaginationLinks, bool) { +func (o *Lans) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *Lans) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *Lans) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *Lans) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *Lans) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *Lans) HasLinks() bool { func (o Lans) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancer.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancer.go index 822d7f1c38e..064e5eb9962 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancer.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancer.go @@ -16,15 +16,15 @@ import ( // Loadbalancer struct for Loadbalancer type Loadbalancer struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Entities *LoadbalancerEntities `json:"entities,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *LoadbalancerProperties `json:"properties"` - Entities *LoadbalancerEntities `json:"entities,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewLoadbalancer instantiates a new Loadbalancer object @@ -47,114 +47,114 @@ func NewLoadbalancerWithDefaults() *Loadbalancer { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Loadbalancer) GetId() *string { +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *Loadbalancer) GetEntities() *LoadbalancerEntities { if o == nil { return nil } - return o.Id + return o.Entities } -// GetIdOk returns a tuple with the Id field value +// GetEntitiesOk returns a tuple with the Entities field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Loadbalancer) GetIdOk() (*string, bool) { +func (o *Loadbalancer) GetEntitiesOk() (*LoadbalancerEntities, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Entities, true } -// SetId sets field value -func (o *Loadbalancer) SetId(v string) { +// SetEntities sets field value +func (o *Loadbalancer) SetEntities(v LoadbalancerEntities) { - o.Id = &v + o.Entities = &v } -// HasId returns a boolean if a field has been set. -func (o *Loadbalancer) HasId() bool { - if o != nil && o.Id != nil { +// HasEntities returns a boolean if a field has been set. +func (o *Loadbalancer) HasEntities() bool { + if o != nil && o.Entities != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Loadbalancer) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Loadbalancer) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Loadbalancer) GetTypeOk() (*Type, bool) { +func (o *Loadbalancer) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Loadbalancer) SetType(v Type) { +// SetHref sets field value +func (o *Loadbalancer) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Loadbalancer) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Loadbalancer) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Loadbalancer) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Loadbalancer) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Loadbalancer) GetHrefOk() (*string, bool) { +func (o *Loadbalancer) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Loadbalancer) SetHref(v string) { +// SetId sets field value +func (o *Loadbalancer) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Loadbalancer) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Loadbalancer) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -162,7 +162,7 @@ func (o *Loadbalancer) HasHref() bool { } // GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned +// If the value is explicit nil, nil is returned func (o *Loadbalancer) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil @@ -200,7 +200,7 @@ func (o *Loadbalancer) HasMetadata() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for LoadbalancerProperties will be returned +// If the value is explicit nil, nil is returned func (o *Loadbalancer) GetProperties() *LoadbalancerProperties { if o == nil { return nil @@ -237,38 +237,38 @@ func (o *Loadbalancer) HasProperties() bool { return false } -// GetEntities returns the Entities field value -// If the value is explicit nil, the zero value for LoadbalancerEntities will be returned -func (o *Loadbalancer) GetEntities() *LoadbalancerEntities { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Loadbalancer) GetType() *Type { if o == nil { return nil } - return o.Entities + return o.Type } -// GetEntitiesOk returns a tuple with the Entities field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Loadbalancer) GetEntitiesOk() (*LoadbalancerEntities, bool) { +func (o *Loadbalancer) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Entities, true + return o.Type, true } -// SetEntities sets field value -func (o *Loadbalancer) SetEntities(v LoadbalancerEntities) { +// SetType sets field value +func (o *Loadbalancer) SetType(v Type) { - o.Entities = &v + o.Type = &v } -// HasEntities returns a boolean if a field has been set. -func (o *Loadbalancer) HasEntities() bool { - if o != nil && o.Entities != nil { +// HasType returns a boolean if a field has been set. +func (o *Loadbalancer) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -277,24 +277,30 @@ func (o *Loadbalancer) HasEntities() bool { func (o Loadbalancer) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Entities != nil { + toSerialize["entities"] = o.Entities } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } - if o.Entities != nil { - toSerialize["entities"] = o.Entities + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancer_entities.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancer_entities.go index 129844dcbd8..8a4c5049c9a 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancer_entities.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancer_entities.go @@ -38,7 +38,7 @@ func NewLoadbalancerEntitiesWithDefaults() *LoadbalancerEntities { } // GetBalancednics returns the Balancednics field value -// If the value is explicit nil, the zero value for BalancedNics will be returned +// If the value is explicit nil, nil is returned func (o *LoadbalancerEntities) GetBalancednics() *BalancedNics { if o == nil { return nil @@ -80,6 +80,7 @@ func (o LoadbalancerEntities) MarshalJSON() ([]byte, error) { if o.Balancednics != nil { toSerialize["balancednics"] = o.Balancednics } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancer_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancer_properties.go index e6b9b02fb28..9d1f3cee7ea 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancer_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancer_properties.go @@ -16,12 +16,13 @@ import ( // LoadbalancerProperties struct for LoadbalancerProperties type LoadbalancerProperties struct { - // The name of the resource. - Name *string `json:"name,omitempty"` - // IPv4 address of the loadbalancer. All attached NICs will inherit this IP. Leaving value null will assign IP automatically. - Ip *string `json:"ip,omitempty"` // Indicates if the loadbalancer will reserve an IP using DHCP. Dhcp *bool `json:"dhcp,omitempty"` + // IPv4 address of the loadbalancer. All attached NICs will inherit this IP. Leaving value null will assign IP automatically. + // to set this field to `nil` in order to be marshalled, the explicit nil address `Nilstring` can be used, or the setter `SetIpNil` + Ip *string `json:"ip,omitempty"` + // The name of the resource. + Name *string `json:"name,omitempty"` } // NewLoadbalancerProperties instantiates a new LoadbalancerProperties object @@ -42,38 +43,38 @@ func NewLoadbalancerPropertiesWithDefaults() *LoadbalancerProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *LoadbalancerProperties) GetName() *string { +// GetDhcp returns the Dhcp field value +// If the value is explicit nil, nil is returned +func (o *LoadbalancerProperties) GetDhcp() *bool { if o == nil { return nil } - return o.Name + return o.Dhcp } -// GetNameOk returns a tuple with the Name field value +// GetDhcpOk returns a tuple with the Dhcp field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LoadbalancerProperties) GetNameOk() (*string, bool) { +func (o *LoadbalancerProperties) GetDhcpOk() (*bool, bool) { if o == nil { return nil, false } - return o.Name, true + return o.Dhcp, true } -// SetName sets field value -func (o *LoadbalancerProperties) SetName(v string) { +// SetDhcp sets field value +func (o *LoadbalancerProperties) SetDhcp(v bool) { - o.Name = &v + o.Dhcp = &v } -// HasName returns a boolean if a field has been set. -func (o *LoadbalancerProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasDhcp returns a boolean if a field has been set. +func (o *LoadbalancerProperties) HasDhcp() bool { + if o != nil && o.Dhcp != nil { return true } @@ -81,7 +82,7 @@ func (o *LoadbalancerProperties) HasName() bool { } // GetIp returns the Ip field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *LoadbalancerProperties) GetIp() *string { if o == nil { return nil @@ -109,6 +110,11 @@ func (o *LoadbalancerProperties) SetIp(v string) { } +// sets Ip to the explicit address that will be encoded as nil when marshaled +func (o *LoadbalancerProperties) SetIpNil() { + o.Ip = &Nilstring +} + // HasIp returns a boolean if a field has been set. func (o *LoadbalancerProperties) HasIp() bool { if o != nil && o.Ip != nil { @@ -118,38 +124,38 @@ func (o *LoadbalancerProperties) HasIp() bool { return false } -// GetDhcp returns the Dhcp field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *LoadbalancerProperties) GetDhcp() *bool { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *LoadbalancerProperties) GetName() *string { if o == nil { return nil } - return o.Dhcp + return o.Name } -// GetDhcpOk returns a tuple with the Dhcp field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LoadbalancerProperties) GetDhcpOk() (*bool, bool) { +func (o *LoadbalancerProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.Dhcp, true + return o.Name, true } -// SetDhcp sets field value -func (o *LoadbalancerProperties) SetDhcp(v bool) { +// SetName sets field value +func (o *LoadbalancerProperties) SetName(v string) { - o.Dhcp = &v + o.Name = &v } -// HasDhcp returns a boolean if a field has been set. -func (o *LoadbalancerProperties) HasDhcp() bool { - if o != nil && o.Dhcp != nil { +// HasName returns a boolean if a field has been set. +func (o *LoadbalancerProperties) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -158,13 +164,19 @@ func (o *LoadbalancerProperties) HasDhcp() bool { func (o LoadbalancerProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name - } - toSerialize["ip"] = o.Ip if o.Dhcp != nil { toSerialize["dhcp"] = o.Dhcp } + + if o.Ip == &Nilstring { + toSerialize["ip"] = nil + } else if o.Ip != nil { + toSerialize["ip"] = o.Ip + } + if o.Name != nil { + toSerialize["name"] = o.Name + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancers.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancers.go index 166560f99b0..267eba36f4d 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancers.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_loadbalancers.go @@ -16,19 +16,19 @@ import ( // Loadbalancers struct for Loadbalancers type Loadbalancers struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Loadbalancer `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewLoadbalancers instantiates a new Loadbalancers object @@ -49,114 +49,114 @@ func NewLoadbalancersWithDefaults() *Loadbalancers { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Loadbalancers) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *Loadbalancers) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Loadbalancers) GetIdOk() (*string, bool) { +func (o *Loadbalancers) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *Loadbalancers) SetId(v string) { +// SetLinks sets field value +func (o *Loadbalancers) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *Loadbalancers) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *Loadbalancers) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Loadbalancers) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Loadbalancers) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Loadbalancers) GetTypeOk() (*Type, bool) { +func (o *Loadbalancers) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Loadbalancers) SetType(v Type) { +// SetHref sets field value +func (o *Loadbalancers) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Loadbalancers) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Loadbalancers) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Loadbalancers) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Loadbalancers) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Loadbalancers) GetHrefOk() (*string, bool) { +func (o *Loadbalancers) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Loadbalancers) SetHref(v string) { +// SetId sets field value +func (o *Loadbalancers) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Loadbalancers) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Loadbalancers) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *Loadbalancers) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Loadbalancer will be returned +// If the value is explicit nil, nil is returned func (o *Loadbalancers) GetItems() *[]Loadbalancer { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *Loadbalancers) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Loadbalancers) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *Loadbalancers) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Loadbalancers) GetOffsetOk() (*float32, bool) { +func (o *Loadbalancers) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *Loadbalancers) SetOffset(v float32) { +// SetLimit sets field value +func (o *Loadbalancers) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *Loadbalancers) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *Loadbalancers) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Loadbalancers) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *Loadbalancers) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Loadbalancers) GetLimitOk() (*float32, bool) { +func (o *Loadbalancers) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *Loadbalancers) SetLimit(v float32) { +// SetOffset sets field value +func (o *Loadbalancers) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *Loadbalancers) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *Loadbalancers) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *Loadbalancers) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Loadbalancers) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Loadbalancers) GetLinksOk() (*PaginationLinks, bool) { +func (o *Loadbalancers) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *Loadbalancers) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *Loadbalancers) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *Loadbalancers) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *Loadbalancers) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *Loadbalancers) HasLinks() bool { func (o Loadbalancers) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_location.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_location.go index 59a250d4529..379723ff1a9 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_location.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_location.go @@ -16,14 +16,14 @@ import ( // Location struct for Location type Location struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *LocationProperties `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewLocation instantiates a new Location object @@ -46,190 +46,190 @@ func NewLocationWithDefaults() *Location { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Location) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Location) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Location) GetIdOk() (*string, bool) { +func (o *Location) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Location) SetId(v string) { +// SetHref sets field value +func (o *Location) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Location) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Location) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Location) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Location) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Location) GetTypeOk() (*Type, bool) { +func (o *Location) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Location) SetType(v Type) { +// SetId sets field value +func (o *Location) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Location) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Location) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Location) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *Location) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Location) GetHrefOk() (*string, bool) { +func (o *Location) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *Location) SetHref(v string) { +// SetMetadata sets field value +func (o *Location) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *Location) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *Location) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *Location) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *Location) GetProperties() *LocationProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Location) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *Location) GetPropertiesOk() (*LocationProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *Location) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *Location) SetProperties(v LocationProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *Location) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *Location) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for LocationProperties will be returned -func (o *Location) GetProperties() *LocationProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Location) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Location) GetPropertiesOk() (*LocationProperties, bool) { +func (o *Location) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *Location) SetProperties(v LocationProperties) { +// SetType sets field value +func (o *Location) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *Location) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *Location) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *Location) HasProperties() bool { func (o Location) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_location_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_location_properties.go index 9e8e623b606..95da4abb396 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_location_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_location_properties.go @@ -16,14 +16,14 @@ import ( // LocationProperties struct for LocationProperties type LocationProperties struct { - // The location name. - Name *string `json:"name,omitempty"` + // A list of available CPU types and related resources available in the location. + CpuArchitecture *[]CpuArchitectureProperties `json:"cpuArchitecture,omitempty"` // A list of available features in the location. Features *[]string `json:"features,omitempty"` // A list of image aliases available in the location. ImageAliases *[]string `json:"imageAliases,omitempty"` - // A list of available CPU types and related resources available in the location. - CpuArchitecture *[]CpuArchitectureProperties `json:"cpuArchitecture,omitempty"` + // The location name. + Name *string `json:"name,omitempty"` } // NewLocationProperties instantiates a new LocationProperties object @@ -44,38 +44,38 @@ func NewLocationPropertiesWithDefaults() *LocationProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *LocationProperties) GetName() *string { +// GetCpuArchitecture returns the CpuArchitecture field value +// If the value is explicit nil, nil is returned +func (o *LocationProperties) GetCpuArchitecture() *[]CpuArchitectureProperties { if o == nil { return nil } - return o.Name + return o.CpuArchitecture } -// GetNameOk returns a tuple with the Name field value +// GetCpuArchitectureOk returns a tuple with the CpuArchitecture field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LocationProperties) GetNameOk() (*string, bool) { +func (o *LocationProperties) GetCpuArchitectureOk() (*[]CpuArchitectureProperties, bool) { if o == nil { return nil, false } - return o.Name, true + return o.CpuArchitecture, true } -// SetName sets field value -func (o *LocationProperties) SetName(v string) { +// SetCpuArchitecture sets field value +func (o *LocationProperties) SetCpuArchitecture(v []CpuArchitectureProperties) { - o.Name = &v + o.CpuArchitecture = &v } -// HasName returns a boolean if a field has been set. -func (o *LocationProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasCpuArchitecture returns a boolean if a field has been set. +func (o *LocationProperties) HasCpuArchitecture() bool { + if o != nil && o.CpuArchitecture != nil { return true } @@ -83,7 +83,7 @@ func (o *LocationProperties) HasName() bool { } // GetFeatures returns the Features field value -// If the value is explicit nil, the zero value for []string will be returned +// If the value is explicit nil, nil is returned func (o *LocationProperties) GetFeatures() *[]string { if o == nil { return nil @@ -121,7 +121,7 @@ func (o *LocationProperties) HasFeatures() bool { } // GetImageAliases returns the ImageAliases field value -// If the value is explicit nil, the zero value for []string will be returned +// If the value is explicit nil, nil is returned func (o *LocationProperties) GetImageAliases() *[]string { if o == nil { return nil @@ -158,38 +158,38 @@ func (o *LocationProperties) HasImageAliases() bool { return false } -// GetCpuArchitecture returns the CpuArchitecture field value -// If the value is explicit nil, the zero value for []CpuArchitectureProperties will be returned -func (o *LocationProperties) GetCpuArchitecture() *[]CpuArchitectureProperties { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *LocationProperties) GetName() *string { if o == nil { return nil } - return o.CpuArchitecture + return o.Name } -// GetCpuArchitectureOk returns a tuple with the CpuArchitecture field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *LocationProperties) GetCpuArchitectureOk() (*[]CpuArchitectureProperties, bool) { +func (o *LocationProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.CpuArchitecture, true + return o.Name, true } -// SetCpuArchitecture sets field value -func (o *LocationProperties) SetCpuArchitecture(v []CpuArchitectureProperties) { +// SetName sets field value +func (o *LocationProperties) SetName(v string) { - o.CpuArchitecture = &v + o.Name = &v } -// HasCpuArchitecture returns a boolean if a field has been set. -func (o *LocationProperties) HasCpuArchitecture() bool { - if o != nil && o.CpuArchitecture != nil { +// HasName returns a boolean if a field has been set. +func (o *LocationProperties) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -198,18 +198,22 @@ func (o *LocationProperties) HasCpuArchitecture() bool { func (o LocationProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name + if o.CpuArchitecture != nil { + toSerialize["cpuArchitecture"] = o.CpuArchitecture } + if o.Features != nil { toSerialize["features"] = o.Features } + if o.ImageAliases != nil { toSerialize["imageAliases"] = o.ImageAliases } - if o.CpuArchitecture != nil { - toSerialize["cpuArchitecture"] = o.CpuArchitecture + + if o.Name != nil { + toSerialize["name"] = o.Name } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_locations.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_locations.go index ba9354acec7..d3311051b43 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_locations.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_locations.go @@ -16,14 +16,14 @@ import ( // Locations struct for Locations type Locations struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Location `json:"items,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewLocations instantiates a new Locations object @@ -44,152 +44,152 @@ func NewLocationsWithDefaults() *Locations { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Locations) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Locations) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Locations) GetIdOk() (*string, bool) { +func (o *Locations) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Locations) SetId(v string) { +// SetHref sets field value +func (o *Locations) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Locations) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Locations) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Locations) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Locations) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Locations) GetTypeOk() (*Type, bool) { +func (o *Locations) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Locations) SetType(v Type) { +// SetId sets field value +func (o *Locations) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Locations) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Locations) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Locations) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *Locations) GetItems() *[]Location { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Locations) GetHrefOk() (*string, bool) { +func (o *Locations) GetItemsOk() (*[]Location, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *Locations) SetHref(v string) { +// SetItems sets field value +func (o *Locations) SetItems(v []Location) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *Locations) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *Locations) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Location will be returned -func (o *Locations) GetItems() *[]Location { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Locations) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Locations) GetItemsOk() (*[]Location, bool) { +func (o *Locations) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *Locations) SetItems(v []Location) { +// SetType sets field value +func (o *Locations) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *Locations) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *Locations) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *Locations) HasItems() bool { func (o Locations) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway.go index 70f8e92a9bd..2feaa609f98 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway.go @@ -16,15 +16,15 @@ import ( // NatGateway struct for NatGateway type NatGateway struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Entities *NatGatewayEntities `json:"entities,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *NatGatewayProperties `json:"properties"` - Entities *NatGatewayEntities `json:"entities,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewNatGateway instantiates a new NatGateway object @@ -47,114 +47,114 @@ func NewNatGatewayWithDefaults() *NatGateway { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NatGateway) GetId() *string { +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *NatGateway) GetEntities() *NatGatewayEntities { if o == nil { return nil } - return o.Id + return o.Entities } -// GetIdOk returns a tuple with the Id field value +// GetEntitiesOk returns a tuple with the Entities field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGateway) GetIdOk() (*string, bool) { +func (o *NatGateway) GetEntitiesOk() (*NatGatewayEntities, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Entities, true } -// SetId sets field value -func (o *NatGateway) SetId(v string) { +// SetEntities sets field value +func (o *NatGateway) SetEntities(v NatGatewayEntities) { - o.Id = &v + o.Entities = &v } -// HasId returns a boolean if a field has been set. -func (o *NatGateway) HasId() bool { - if o != nil && o.Id != nil { +// HasEntities returns a boolean if a field has been set. +func (o *NatGateway) HasEntities() bool { + if o != nil && o.Entities != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *NatGateway) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *NatGateway) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGateway) GetTypeOk() (*Type, bool) { +func (o *NatGateway) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *NatGateway) SetType(v Type) { +// SetHref sets field value +func (o *NatGateway) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *NatGateway) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *NatGateway) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NatGateway) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *NatGateway) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGateway) GetHrefOk() (*string, bool) { +func (o *NatGateway) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *NatGateway) SetHref(v string) { +// SetId sets field value +func (o *NatGateway) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *NatGateway) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *NatGateway) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -162,7 +162,7 @@ func (o *NatGateway) HasHref() bool { } // GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned +// If the value is explicit nil, nil is returned func (o *NatGateway) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil @@ -200,7 +200,7 @@ func (o *NatGateway) HasMetadata() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for NatGatewayProperties will be returned +// If the value is explicit nil, nil is returned func (o *NatGateway) GetProperties() *NatGatewayProperties { if o == nil { return nil @@ -237,38 +237,38 @@ func (o *NatGateway) HasProperties() bool { return false } -// GetEntities returns the Entities field value -// If the value is explicit nil, the zero value for NatGatewayEntities will be returned -func (o *NatGateway) GetEntities() *NatGatewayEntities { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *NatGateway) GetType() *Type { if o == nil { return nil } - return o.Entities + return o.Type } -// GetEntitiesOk returns a tuple with the Entities field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGateway) GetEntitiesOk() (*NatGatewayEntities, bool) { +func (o *NatGateway) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Entities, true + return o.Type, true } -// SetEntities sets field value -func (o *NatGateway) SetEntities(v NatGatewayEntities) { +// SetType sets field value +func (o *NatGateway) SetType(v Type) { - o.Entities = &v + o.Type = &v } -// HasEntities returns a boolean if a field has been set. -func (o *NatGateway) HasEntities() bool { - if o != nil && o.Entities != nil { +// HasType returns a boolean if a field has been set. +func (o *NatGateway) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -277,24 +277,30 @@ func (o *NatGateway) HasEntities() bool { func (o NatGateway) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Entities != nil { + toSerialize["entities"] = o.Entities } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } - if o.Entities != nil { - toSerialize["entities"] = o.Entities + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_entities.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_entities.go index d51cb9543ce..94fae49c42a 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_entities.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_entities.go @@ -16,8 +16,8 @@ import ( // NatGatewayEntities struct for NatGatewayEntities type NatGatewayEntities struct { - Rules *NatGatewayRules `json:"rules,omitempty"` Flowlogs *FlowLogs `json:"flowlogs,omitempty"` + Rules *NatGatewayRules `json:"rules,omitempty"` } // NewNatGatewayEntities instantiates a new NatGatewayEntities object @@ -38,76 +38,76 @@ func NewNatGatewayEntitiesWithDefaults() *NatGatewayEntities { return &this } -// GetRules returns the Rules field value -// If the value is explicit nil, the zero value for NatGatewayRules will be returned -func (o *NatGatewayEntities) GetRules() *NatGatewayRules { +// GetFlowlogs returns the Flowlogs field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayEntities) GetFlowlogs() *FlowLogs { if o == nil { return nil } - return o.Rules + return o.Flowlogs } -// GetRulesOk returns a tuple with the Rules field value +// GetFlowlogsOk returns a tuple with the Flowlogs field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayEntities) GetRulesOk() (*NatGatewayRules, bool) { +func (o *NatGatewayEntities) GetFlowlogsOk() (*FlowLogs, bool) { if o == nil { return nil, false } - return o.Rules, true + return o.Flowlogs, true } -// SetRules sets field value -func (o *NatGatewayEntities) SetRules(v NatGatewayRules) { +// SetFlowlogs sets field value +func (o *NatGatewayEntities) SetFlowlogs(v FlowLogs) { - o.Rules = &v + o.Flowlogs = &v } -// HasRules returns a boolean if a field has been set. -func (o *NatGatewayEntities) HasRules() bool { - if o != nil && o.Rules != nil { +// HasFlowlogs returns a boolean if a field has been set. +func (o *NatGatewayEntities) HasFlowlogs() bool { + if o != nil && o.Flowlogs != nil { return true } return false } -// GetFlowlogs returns the Flowlogs field value -// If the value is explicit nil, the zero value for FlowLogs will be returned -func (o *NatGatewayEntities) GetFlowlogs() *FlowLogs { +// GetRules returns the Rules field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayEntities) GetRules() *NatGatewayRules { if o == nil { return nil } - return o.Flowlogs + return o.Rules } -// GetFlowlogsOk returns a tuple with the Flowlogs field value +// GetRulesOk returns a tuple with the Rules field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayEntities) GetFlowlogsOk() (*FlowLogs, bool) { +func (o *NatGatewayEntities) GetRulesOk() (*NatGatewayRules, bool) { if o == nil { return nil, false } - return o.Flowlogs, true + return o.Rules, true } -// SetFlowlogs sets field value -func (o *NatGatewayEntities) SetFlowlogs(v FlowLogs) { +// SetRules sets field value +func (o *NatGatewayEntities) SetRules(v NatGatewayRules) { - o.Flowlogs = &v + o.Rules = &v } -// HasFlowlogs returns a boolean if a field has been set. -func (o *NatGatewayEntities) HasFlowlogs() bool { - if o != nil && o.Flowlogs != nil { +// HasRules returns a boolean if a field has been set. +func (o *NatGatewayEntities) HasRules() bool { + if o != nil && o.Rules != nil { return true } @@ -116,12 +116,14 @@ func (o *NatGatewayEntities) HasFlowlogs() bool { func (o NatGatewayEntities) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Rules != nil { - toSerialize["rules"] = o.Rules - } if o.Flowlogs != nil { toSerialize["flowlogs"] = o.Flowlogs } + + if o.Rules != nil { + toSerialize["rules"] = o.Rules + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_lan_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_lan_properties.go index 007a57d6903..068b141bebb 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_lan_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_lan_properties.go @@ -16,10 +16,10 @@ import ( // NatGatewayLanProperties struct for NatGatewayLanProperties type NatGatewayLanProperties struct { - // Id for the LAN connected to the NAT Gateway - Id *int32 `json:"id"` // Collection of gateway IP addresses of the NAT Gateway. Will be auto-generated if not provided. Should ideally be an IP belonging to the same subnet as the LAN GatewayIps *[]string `json:"gatewayIps,omitempty"` + // Id for the LAN connected to the NAT Gateway + Id *int32 `json:"id"` } // NewNatGatewayLanProperties instantiates a new NatGatewayLanProperties object @@ -42,76 +42,76 @@ func NewNatGatewayLanPropertiesWithDefaults() *NatGatewayLanProperties { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *NatGatewayLanProperties) GetId() *int32 { +// GetGatewayIps returns the GatewayIps field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayLanProperties) GetGatewayIps() *[]string { if o == nil { return nil } - return o.Id + return o.GatewayIps } -// GetIdOk returns a tuple with the Id field value +// GetGatewayIpsOk returns a tuple with the GatewayIps field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayLanProperties) GetIdOk() (*int32, bool) { +func (o *NatGatewayLanProperties) GetGatewayIpsOk() (*[]string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.GatewayIps, true } -// SetId sets field value -func (o *NatGatewayLanProperties) SetId(v int32) { +// SetGatewayIps sets field value +func (o *NatGatewayLanProperties) SetGatewayIps(v []string) { - o.Id = &v + o.GatewayIps = &v } -// HasId returns a boolean if a field has been set. -func (o *NatGatewayLanProperties) HasId() bool { - if o != nil && o.Id != nil { +// HasGatewayIps returns a boolean if a field has been set. +func (o *NatGatewayLanProperties) HasGatewayIps() bool { + if o != nil && o.GatewayIps != nil { return true } return false } -// GetGatewayIps returns the GatewayIps field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *NatGatewayLanProperties) GetGatewayIps() *[]string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayLanProperties) GetId() *int32 { if o == nil { return nil } - return o.GatewayIps + return o.Id } -// GetGatewayIpsOk returns a tuple with the GatewayIps field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayLanProperties) GetGatewayIpsOk() (*[]string, bool) { +func (o *NatGatewayLanProperties) GetIdOk() (*int32, bool) { if o == nil { return nil, false } - return o.GatewayIps, true + return o.Id, true } -// SetGatewayIps sets field value -func (o *NatGatewayLanProperties) SetGatewayIps(v []string) { +// SetId sets field value +func (o *NatGatewayLanProperties) SetId(v int32) { - o.GatewayIps = &v + o.Id = &v } -// HasGatewayIps returns a boolean if a field has been set. -func (o *NatGatewayLanProperties) HasGatewayIps() bool { - if o != nil && o.GatewayIps != nil { +// HasId returns a boolean if a field has been set. +func (o *NatGatewayLanProperties) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -120,12 +120,14 @@ func (o *NatGatewayLanProperties) HasGatewayIps() bool { func (o NatGatewayLanProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } if o.GatewayIps != nil { toSerialize["gatewayIps"] = o.GatewayIps } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_properties.go index 6eea997ef31..ad784ad9f97 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_properties.go @@ -16,12 +16,12 @@ import ( // NatGatewayProperties struct for NatGatewayProperties type NatGatewayProperties struct { + // Collection of LANs connected to the NAT Gateway. IPs must contain a valid subnet mask. If no IP is provided, the system will generate an IP with /24 subnet. + Lans *[]NatGatewayLanProperties `json:"lans,omitempty"` // Name of the NAT Gateway. Name *string `json:"name"` // Collection of public IP addresses of the NAT Gateway. Should be customer reserved IP addresses in that location. PublicIps *[]string `json:"publicIps"` - // Collection of LANs connected to the NAT Gateway. IPs must contain a valid subnet mask. If no IP is provided, the system will generate an IP with /24 subnet. - Lans *[]NatGatewayLanProperties `json:"lans,omitempty"` } // NewNatGatewayProperties instantiates a new NatGatewayProperties object @@ -45,114 +45,114 @@ func NewNatGatewayPropertiesWithDefaults() *NatGatewayProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NatGatewayProperties) GetName() *string { +// GetLans returns the Lans field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayProperties) GetLans() *[]NatGatewayLanProperties { if o == nil { return nil } - return o.Name + return o.Lans } -// GetNameOk returns a tuple with the Name field value +// GetLansOk returns a tuple with the Lans field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayProperties) GetNameOk() (*string, bool) { +func (o *NatGatewayProperties) GetLansOk() (*[]NatGatewayLanProperties, bool) { if o == nil { return nil, false } - return o.Name, true + return o.Lans, true } -// SetName sets field value -func (o *NatGatewayProperties) SetName(v string) { +// SetLans sets field value +func (o *NatGatewayProperties) SetLans(v []NatGatewayLanProperties) { - o.Name = &v + o.Lans = &v } -// HasName returns a boolean if a field has been set. -func (o *NatGatewayProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasLans returns a boolean if a field has been set. +func (o *NatGatewayProperties) HasLans() bool { + if o != nil && o.Lans != nil { return true } return false } -// GetPublicIps returns the PublicIps field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *NatGatewayProperties) GetPublicIps() *[]string { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayProperties) GetName() *string { if o == nil { return nil } - return o.PublicIps + return o.Name } -// GetPublicIpsOk returns a tuple with the PublicIps field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayProperties) GetPublicIpsOk() (*[]string, bool) { +func (o *NatGatewayProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.PublicIps, true + return o.Name, true } -// SetPublicIps sets field value -func (o *NatGatewayProperties) SetPublicIps(v []string) { +// SetName sets field value +func (o *NatGatewayProperties) SetName(v string) { - o.PublicIps = &v + o.Name = &v } -// HasPublicIps returns a boolean if a field has been set. -func (o *NatGatewayProperties) HasPublicIps() bool { - if o != nil && o.PublicIps != nil { +// HasName returns a boolean if a field has been set. +func (o *NatGatewayProperties) HasName() bool { + if o != nil && o.Name != nil { return true } return false } -// GetLans returns the Lans field value -// If the value is explicit nil, the zero value for []NatGatewayLanProperties will be returned -func (o *NatGatewayProperties) GetLans() *[]NatGatewayLanProperties { +// GetPublicIps returns the PublicIps field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayProperties) GetPublicIps() *[]string { if o == nil { return nil } - return o.Lans + return o.PublicIps } -// GetLansOk returns a tuple with the Lans field value +// GetPublicIpsOk returns a tuple with the PublicIps field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayProperties) GetLansOk() (*[]NatGatewayLanProperties, bool) { +func (o *NatGatewayProperties) GetPublicIpsOk() (*[]string, bool) { if o == nil { return nil, false } - return o.Lans, true + return o.PublicIps, true } -// SetLans sets field value -func (o *NatGatewayProperties) SetLans(v []NatGatewayLanProperties) { +// SetPublicIps sets field value +func (o *NatGatewayProperties) SetPublicIps(v []string) { - o.Lans = &v + o.PublicIps = &v } -// HasLans returns a boolean if a field has been set. -func (o *NatGatewayProperties) HasLans() bool { - if o != nil && o.Lans != nil { +// HasPublicIps returns a boolean if a field has been set. +func (o *NatGatewayProperties) HasPublicIps() bool { + if o != nil && o.PublicIps != nil { return true } @@ -161,15 +161,18 @@ func (o *NatGatewayProperties) HasLans() bool { func (o NatGatewayProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} + if o.Lans != nil { + toSerialize["lans"] = o.Lans + } + if o.Name != nil { toSerialize["name"] = o.Name } + if o.PublicIps != nil { toSerialize["publicIps"] = o.PublicIps } - if o.Lans != nil { - toSerialize["lans"] = o.Lans - } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_put.go index cf9a8a0486f..5bd37720efb 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_put.go @@ -16,13 +16,13 @@ import ( // NatGatewayPut struct for NatGatewayPut type NatGatewayPut struct { + // URL to the object representation (absolute path). + Href *string `json:"href,omitempty"` // The resource's unique identifier. - Id *string `json:"id,omitempty"` + Id *string `json:"id,omitempty"` + Properties *NatGatewayProperties `json:"properties"` // The type of object that has been created. Type *Type `json:"type,omitempty"` - // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` - Properties *NatGatewayProperties `json:"properties"` } // NewNatGatewayPut instantiates a new NatGatewayPut object @@ -45,152 +45,152 @@ func NewNatGatewayPutWithDefaults() *NatGatewayPut { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NatGatewayPut) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayPut) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayPut) GetIdOk() (*string, bool) { +func (o *NatGatewayPut) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *NatGatewayPut) SetId(v string) { +// SetHref sets field value +func (o *NatGatewayPut) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *NatGatewayPut) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *NatGatewayPut) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *NatGatewayPut) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayPut) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayPut) GetTypeOk() (*Type, bool) { +func (o *NatGatewayPut) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *NatGatewayPut) SetType(v Type) { +// SetId sets field value +func (o *NatGatewayPut) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *NatGatewayPut) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *NatGatewayPut) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NatGatewayPut) GetHref() *string { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayPut) GetProperties() *NatGatewayProperties { if o == nil { return nil } - return o.Href + return o.Properties } -// GetHrefOk returns a tuple with the Href field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayPut) GetHrefOk() (*string, bool) { +func (o *NatGatewayPut) GetPropertiesOk() (*NatGatewayProperties, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Properties, true } -// SetHref sets field value -func (o *NatGatewayPut) SetHref(v string) { +// SetProperties sets field value +func (o *NatGatewayPut) SetProperties(v NatGatewayProperties) { - o.Href = &v + o.Properties = &v } -// HasHref returns a boolean if a field has been set. -func (o *NatGatewayPut) HasHref() bool { - if o != nil && o.Href != nil { +// HasProperties returns a boolean if a field has been set. +func (o *NatGatewayPut) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for NatGatewayProperties will be returned -func (o *NatGatewayPut) GetProperties() *NatGatewayProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayPut) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayPut) GetPropertiesOk() (*NatGatewayProperties, bool) { +func (o *NatGatewayPut) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *NatGatewayPut) SetProperties(v NatGatewayProperties) { +// SetType sets field value +func (o *NatGatewayPut) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *NatGatewayPut) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *NatGatewayPut) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -199,18 +199,22 @@ func (o *NatGatewayPut) HasProperties() bool { func (o NatGatewayPut) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rule.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rule.go index 42d20aac891..4693555cafa 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rule.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rule.go @@ -16,14 +16,14 @@ import ( // NatGatewayRule struct for NatGatewayRule type NatGatewayRule struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *NatGatewayRuleProperties `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewNatGatewayRule instantiates a new NatGatewayRule object @@ -46,190 +46,190 @@ func NewNatGatewayRuleWithDefaults() *NatGatewayRule { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NatGatewayRule) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRule) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRule) GetIdOk() (*string, bool) { +func (o *NatGatewayRule) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *NatGatewayRule) SetId(v string) { +// SetHref sets field value +func (o *NatGatewayRule) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *NatGatewayRule) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *NatGatewayRule) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *NatGatewayRule) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRule) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRule) GetTypeOk() (*Type, bool) { +func (o *NatGatewayRule) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *NatGatewayRule) SetType(v Type) { +// SetId sets field value +func (o *NatGatewayRule) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *NatGatewayRule) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *NatGatewayRule) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NatGatewayRule) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRule) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRule) GetHrefOk() (*string, bool) { +func (o *NatGatewayRule) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *NatGatewayRule) SetHref(v string) { +// SetMetadata sets field value +func (o *NatGatewayRule) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *NatGatewayRule) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *NatGatewayRule) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *NatGatewayRule) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRule) GetProperties() *NatGatewayRuleProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRule) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *NatGatewayRule) GetPropertiesOk() (*NatGatewayRuleProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *NatGatewayRule) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *NatGatewayRule) SetProperties(v NatGatewayRuleProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *NatGatewayRule) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *NatGatewayRule) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for NatGatewayRuleProperties will be returned -func (o *NatGatewayRule) GetProperties() *NatGatewayRuleProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRule) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRule) GetPropertiesOk() (*NatGatewayRuleProperties, bool) { +func (o *NatGatewayRule) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *NatGatewayRule) SetProperties(v NatGatewayRuleProperties) { +// SetType sets field value +func (o *NatGatewayRule) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *NatGatewayRule) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *NatGatewayRule) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *NatGatewayRule) HasProperties() bool { func (o NatGatewayRule) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rule_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rule_properties.go index 8b3da441e6c..32330acee59 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rule_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rule_properties.go @@ -18,29 +18,29 @@ import ( type NatGatewayRuleProperties struct { // The name of the NAT Gateway rule. Name *string `json:"name"` - // Type of the NAT Gateway rule. - Type *NatGatewayRuleType `json:"type,omitempty"` // Protocol of the NAT Gateway rule. Defaults to ALL. If protocol is 'ICMP' then targetPortRange start and end cannot be set. Protocol *NatGatewayRuleProtocol `json:"protocol,omitempty"` - // Source subnet of the NAT Gateway rule. For SNAT rules it specifies which packets this translation rule applies to based on the packets source IP address. - SourceSubnet *string `json:"sourceSubnet"` // Public IP address of the NAT Gateway rule. Specifies the address used for masking outgoing packets source address field. Should be one of the customer reserved IP address already configured on the NAT Gateway resource PublicIp *string `json:"publicIp"` - // Target or destination subnet of the NAT Gateway rule. For SNAT rules it specifies which packets this translation rule applies to based on the packets destination IP address. If none is provided, rule will match any address. - TargetSubnet *string `json:"targetSubnet,omitempty"` + // Source subnet of the NAT Gateway rule. For SNAT rules it specifies which packets this translation rule applies to based on the packets source IP address. + SourceSubnet *string `json:"sourceSubnet"` TargetPortRange *TargetPortRange `json:"targetPortRange,omitempty"` + // Target or destination subnet of the NAT Gateway rule. For SNAT rules it specifies which packets this translation rule applies to based on the packets destination IP address. If none is provided, rule will match any address. + TargetSubnet *string `json:"targetSubnet,omitempty"` + // Type of the NAT Gateway rule. + Type *NatGatewayRuleType `json:"type,omitempty"` } // NewNatGatewayRuleProperties instantiates a new NatGatewayRuleProperties object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewNatGatewayRuleProperties(name string, sourceSubnet string, publicIp string) *NatGatewayRuleProperties { +func NewNatGatewayRuleProperties(name string, publicIp string, sourceSubnet string) *NatGatewayRuleProperties { this := NatGatewayRuleProperties{} this.Name = &name - this.SourceSubnet = &sourceSubnet this.PublicIp = &publicIp + this.SourceSubnet = &sourceSubnet return &this } @@ -54,7 +54,7 @@ func NewNatGatewayRulePropertiesWithDefaults() *NatGatewayRuleProperties { } // GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *NatGatewayRuleProperties) GetName() *string { if o == nil { return nil @@ -91,76 +91,76 @@ func (o *NatGatewayRuleProperties) HasName() bool { return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for NatGatewayRuleType will be returned -func (o *NatGatewayRuleProperties) GetType() *NatGatewayRuleType { +// GetProtocol returns the Protocol field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRuleProperties) GetProtocol() *NatGatewayRuleProtocol { if o == nil { return nil } - return o.Type + return o.Protocol } -// GetTypeOk returns a tuple with the Type field value +// GetProtocolOk returns a tuple with the Protocol field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRuleProperties) GetTypeOk() (*NatGatewayRuleType, bool) { +func (o *NatGatewayRuleProperties) GetProtocolOk() (*NatGatewayRuleProtocol, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Protocol, true } -// SetType sets field value -func (o *NatGatewayRuleProperties) SetType(v NatGatewayRuleType) { +// SetProtocol sets field value +func (o *NatGatewayRuleProperties) SetProtocol(v NatGatewayRuleProtocol) { - o.Type = &v + o.Protocol = &v } -// HasType returns a boolean if a field has been set. -func (o *NatGatewayRuleProperties) HasType() bool { - if o != nil && o.Type != nil { +// HasProtocol returns a boolean if a field has been set. +func (o *NatGatewayRuleProperties) HasProtocol() bool { + if o != nil && o.Protocol != nil { return true } return false } -// GetProtocol returns the Protocol field value -// If the value is explicit nil, the zero value for NatGatewayRuleProtocol will be returned -func (o *NatGatewayRuleProperties) GetProtocol() *NatGatewayRuleProtocol { +// GetPublicIp returns the PublicIp field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRuleProperties) GetPublicIp() *string { if o == nil { return nil } - return o.Protocol + return o.PublicIp } -// GetProtocolOk returns a tuple with the Protocol field value +// GetPublicIpOk returns a tuple with the PublicIp field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRuleProperties) GetProtocolOk() (*NatGatewayRuleProtocol, bool) { +func (o *NatGatewayRuleProperties) GetPublicIpOk() (*string, bool) { if o == nil { return nil, false } - return o.Protocol, true + return o.PublicIp, true } -// SetProtocol sets field value -func (o *NatGatewayRuleProperties) SetProtocol(v NatGatewayRuleProtocol) { +// SetPublicIp sets field value +func (o *NatGatewayRuleProperties) SetPublicIp(v string) { - o.Protocol = &v + o.PublicIp = &v } -// HasProtocol returns a boolean if a field has been set. -func (o *NatGatewayRuleProperties) HasProtocol() bool { - if o != nil && o.Protocol != nil { +// HasPublicIp returns a boolean if a field has been set. +func (o *NatGatewayRuleProperties) HasPublicIp() bool { + if o != nil && o.PublicIp != nil { return true } @@ -168,7 +168,7 @@ func (o *NatGatewayRuleProperties) HasProtocol() bool { } // GetSourceSubnet returns the SourceSubnet field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *NatGatewayRuleProperties) GetSourceSubnet() *string { if o == nil { return nil @@ -205,38 +205,38 @@ func (o *NatGatewayRuleProperties) HasSourceSubnet() bool { return false } -// GetPublicIp returns the PublicIp field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NatGatewayRuleProperties) GetPublicIp() *string { +// GetTargetPortRange returns the TargetPortRange field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRuleProperties) GetTargetPortRange() *TargetPortRange { if o == nil { return nil } - return o.PublicIp + return o.TargetPortRange } -// GetPublicIpOk returns a tuple with the PublicIp field value +// GetTargetPortRangeOk returns a tuple with the TargetPortRange field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRuleProperties) GetPublicIpOk() (*string, bool) { +func (o *NatGatewayRuleProperties) GetTargetPortRangeOk() (*TargetPortRange, bool) { if o == nil { return nil, false } - return o.PublicIp, true + return o.TargetPortRange, true } -// SetPublicIp sets field value -func (o *NatGatewayRuleProperties) SetPublicIp(v string) { +// SetTargetPortRange sets field value +func (o *NatGatewayRuleProperties) SetTargetPortRange(v TargetPortRange) { - o.PublicIp = &v + o.TargetPortRange = &v } -// HasPublicIp returns a boolean if a field has been set. -func (o *NatGatewayRuleProperties) HasPublicIp() bool { - if o != nil && o.PublicIp != nil { +// HasTargetPortRange returns a boolean if a field has been set. +func (o *NatGatewayRuleProperties) HasTargetPortRange() bool { + if o != nil && o.TargetPortRange != nil { return true } @@ -244,7 +244,7 @@ func (o *NatGatewayRuleProperties) HasPublicIp() bool { } // GetTargetSubnet returns the TargetSubnet field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *NatGatewayRuleProperties) GetTargetSubnet() *string { if o == nil { return nil @@ -281,38 +281,38 @@ func (o *NatGatewayRuleProperties) HasTargetSubnet() bool { return false } -// GetTargetPortRange returns the TargetPortRange field value -// If the value is explicit nil, the zero value for TargetPortRange will be returned -func (o *NatGatewayRuleProperties) GetTargetPortRange() *TargetPortRange { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRuleProperties) GetType() *NatGatewayRuleType { if o == nil { return nil } - return o.TargetPortRange + return o.Type } -// GetTargetPortRangeOk returns a tuple with the TargetPortRange field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRuleProperties) GetTargetPortRangeOk() (*TargetPortRange, bool) { +func (o *NatGatewayRuleProperties) GetTypeOk() (*NatGatewayRuleType, bool) { if o == nil { return nil, false } - return o.TargetPortRange, true + return o.Type, true } -// SetTargetPortRange sets field value -func (o *NatGatewayRuleProperties) SetTargetPortRange(v TargetPortRange) { +// SetType sets field value +func (o *NatGatewayRuleProperties) SetType(v NatGatewayRuleType) { - o.TargetPortRange = &v + o.Type = &v } -// HasTargetPortRange returns a boolean if a field has been set. -func (o *NatGatewayRuleProperties) HasTargetPortRange() bool { - if o != nil && o.TargetPortRange != nil { +// HasType returns a boolean if a field has been set. +func (o *NatGatewayRuleProperties) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -324,24 +324,31 @@ func (o NatGatewayRuleProperties) MarshalJSON() ([]byte, error) { if o.Name != nil { toSerialize["name"] = o.Name } - if o.Type != nil { - toSerialize["type"] = o.Type - } + if o.Protocol != nil { toSerialize["protocol"] = o.Protocol } + + if o.PublicIp != nil { + toSerialize["publicIp"] = o.PublicIp + } + if o.SourceSubnet != nil { toSerialize["sourceSubnet"] = o.SourceSubnet } - if o.PublicIp != nil { - toSerialize["publicIp"] = o.PublicIp + + if o.TargetPortRange != nil { + toSerialize["targetPortRange"] = o.TargetPortRange } + if o.TargetSubnet != nil { toSerialize["targetSubnet"] = o.TargetSubnet } - if o.TargetPortRange != nil { - toSerialize["targetPortRange"] = o.TargetPortRange + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rule_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rule_put.go index 2f709351b0f..e0f92b4099e 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rule_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rule_put.go @@ -16,13 +16,13 @@ import ( // NatGatewayRulePut struct for NatGatewayRulePut type NatGatewayRulePut struct { + // URL to the object representation (absolute path). + Href *string `json:"href,omitempty"` // The resource's unique identifier. - Id *string `json:"id,omitempty"` + Id *string `json:"id,omitempty"` + Properties *NatGatewayRuleProperties `json:"properties"` // The type of object that has been created. Type *Type `json:"type,omitempty"` - // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` - Properties *NatGatewayRuleProperties `json:"properties"` } // NewNatGatewayRulePut instantiates a new NatGatewayRulePut object @@ -45,152 +45,152 @@ func NewNatGatewayRulePutWithDefaults() *NatGatewayRulePut { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NatGatewayRulePut) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRulePut) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRulePut) GetIdOk() (*string, bool) { +func (o *NatGatewayRulePut) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *NatGatewayRulePut) SetId(v string) { +// SetHref sets field value +func (o *NatGatewayRulePut) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *NatGatewayRulePut) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *NatGatewayRulePut) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *NatGatewayRulePut) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRulePut) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRulePut) GetTypeOk() (*Type, bool) { +func (o *NatGatewayRulePut) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *NatGatewayRulePut) SetType(v Type) { +// SetId sets field value +func (o *NatGatewayRulePut) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *NatGatewayRulePut) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *NatGatewayRulePut) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NatGatewayRulePut) GetHref() *string { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRulePut) GetProperties() *NatGatewayRuleProperties { if o == nil { return nil } - return o.Href + return o.Properties } -// GetHrefOk returns a tuple with the Href field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRulePut) GetHrefOk() (*string, bool) { +func (o *NatGatewayRulePut) GetPropertiesOk() (*NatGatewayRuleProperties, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Properties, true } -// SetHref sets field value -func (o *NatGatewayRulePut) SetHref(v string) { +// SetProperties sets field value +func (o *NatGatewayRulePut) SetProperties(v NatGatewayRuleProperties) { - o.Href = &v + o.Properties = &v } -// HasHref returns a boolean if a field has been set. -func (o *NatGatewayRulePut) HasHref() bool { - if o != nil && o.Href != nil { +// HasProperties returns a boolean if a field has been set. +func (o *NatGatewayRulePut) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for NatGatewayRuleProperties will be returned -func (o *NatGatewayRulePut) GetProperties() *NatGatewayRuleProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRulePut) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRulePut) GetPropertiesOk() (*NatGatewayRuleProperties, bool) { +func (o *NatGatewayRulePut) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *NatGatewayRulePut) SetProperties(v NatGatewayRuleProperties) { +// SetType sets field value +func (o *NatGatewayRulePut) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *NatGatewayRulePut) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *NatGatewayRulePut) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -199,18 +199,22 @@ func (o *NatGatewayRulePut) HasProperties() bool { func (o NatGatewayRulePut) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rules.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rules.go index 780bef1f9d8..9d3d4135331 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rules.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateway_rules.go @@ -16,14 +16,14 @@ import ( // NatGatewayRules struct for NatGatewayRules type NatGatewayRules struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]NatGatewayRule `json:"items,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewNatGatewayRules instantiates a new NatGatewayRules object @@ -44,152 +44,152 @@ func NewNatGatewayRulesWithDefaults() *NatGatewayRules { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NatGatewayRules) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRules) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRules) GetIdOk() (*string, bool) { +func (o *NatGatewayRules) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *NatGatewayRules) SetId(v string) { +// SetHref sets field value +func (o *NatGatewayRules) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *NatGatewayRules) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *NatGatewayRules) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *NatGatewayRules) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRules) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRules) GetTypeOk() (*Type, bool) { +func (o *NatGatewayRules) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *NatGatewayRules) SetType(v Type) { +// SetId sets field value +func (o *NatGatewayRules) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *NatGatewayRules) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *NatGatewayRules) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NatGatewayRules) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRules) GetItems() *[]NatGatewayRule { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRules) GetHrefOk() (*string, bool) { +func (o *NatGatewayRules) GetItemsOk() (*[]NatGatewayRule, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *NatGatewayRules) SetHref(v string) { +// SetItems sets field value +func (o *NatGatewayRules) SetItems(v []NatGatewayRule) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *NatGatewayRules) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *NatGatewayRules) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []NatGatewayRule will be returned -func (o *NatGatewayRules) GetItems() *[]NatGatewayRule { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *NatGatewayRules) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGatewayRules) GetItemsOk() (*[]NatGatewayRule, bool) { +func (o *NatGatewayRules) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *NatGatewayRules) SetItems(v []NatGatewayRule) { +// SetType sets field value +func (o *NatGatewayRules) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *NatGatewayRules) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *NatGatewayRules) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *NatGatewayRules) HasItems() bool { func (o NatGatewayRules) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateways.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateways.go index ea80671fe87..2139508ccc1 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateways.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nat_gateways.go @@ -16,19 +16,19 @@ import ( // NatGateways struct for NatGateways type NatGateways struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]NatGateway `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewNatGateways instantiates a new NatGateways object @@ -49,114 +49,114 @@ func NewNatGatewaysWithDefaults() *NatGateways { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NatGateways) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *NatGateways) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGateways) GetIdOk() (*string, bool) { +func (o *NatGateways) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *NatGateways) SetId(v string) { +// SetLinks sets field value +func (o *NatGateways) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *NatGateways) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *NatGateways) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *NatGateways) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *NatGateways) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGateways) GetTypeOk() (*Type, bool) { +func (o *NatGateways) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *NatGateways) SetType(v Type) { +// SetHref sets field value +func (o *NatGateways) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *NatGateways) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *NatGateways) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NatGateways) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *NatGateways) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGateways) GetHrefOk() (*string, bool) { +func (o *NatGateways) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *NatGateways) SetHref(v string) { +// SetId sets field value +func (o *NatGateways) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *NatGateways) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *NatGateways) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *NatGateways) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []NatGateway will be returned +// If the value is explicit nil, nil is returned func (o *NatGateways) GetItems() *[]NatGateway { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *NatGateways) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *NatGateways) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *NatGateways) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGateways) GetOffsetOk() (*float32, bool) { +func (o *NatGateways) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *NatGateways) SetOffset(v float32) { +// SetLimit sets field value +func (o *NatGateways) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *NatGateways) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *NatGateways) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *NatGateways) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *NatGateways) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGateways) GetLimitOk() (*float32, bool) { +func (o *NatGateways) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *NatGateways) SetLimit(v float32) { +// SetOffset sets field value +func (o *NatGateways) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *NatGateways) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *NatGateways) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *NatGateways) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *NatGateways) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NatGateways) GetLinksOk() (*PaginationLinks, bool) { +func (o *NatGateways) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *NatGateways) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *NatGateways) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *NatGateways) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *NatGateways) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *NatGateways) HasLinks() bool { func (o NatGateways) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer.go index 265e075faa2..efaed067d8e 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer.go @@ -16,15 +16,15 @@ import ( // NetworkLoadBalancer struct for NetworkLoadBalancer type NetworkLoadBalancer struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Entities *NetworkLoadBalancerEntities `json:"entities,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *NetworkLoadBalancerProperties `json:"properties"` - Entities *NetworkLoadBalancerEntities `json:"entities,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewNetworkLoadBalancer instantiates a new NetworkLoadBalancer object @@ -47,114 +47,114 @@ func NewNetworkLoadBalancerWithDefaults() *NetworkLoadBalancer { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancer) GetId() *string { +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancer) GetEntities() *NetworkLoadBalancerEntities { if o == nil { return nil } - return o.Id + return o.Entities } -// GetIdOk returns a tuple with the Id field value +// GetEntitiesOk returns a tuple with the Entities field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancer) GetIdOk() (*string, bool) { +func (o *NetworkLoadBalancer) GetEntitiesOk() (*NetworkLoadBalancerEntities, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Entities, true } -// SetId sets field value -func (o *NetworkLoadBalancer) SetId(v string) { +// SetEntities sets field value +func (o *NetworkLoadBalancer) SetEntities(v NetworkLoadBalancerEntities) { - o.Id = &v + o.Entities = &v } -// HasId returns a boolean if a field has been set. -func (o *NetworkLoadBalancer) HasId() bool { - if o != nil && o.Id != nil { +// HasEntities returns a boolean if a field has been set. +func (o *NetworkLoadBalancer) HasEntities() bool { + if o != nil && o.Entities != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *NetworkLoadBalancer) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancer) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancer) GetTypeOk() (*Type, bool) { +func (o *NetworkLoadBalancer) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *NetworkLoadBalancer) SetType(v Type) { +// SetHref sets field value +func (o *NetworkLoadBalancer) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *NetworkLoadBalancer) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *NetworkLoadBalancer) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancer) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancer) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancer) GetHrefOk() (*string, bool) { +func (o *NetworkLoadBalancer) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *NetworkLoadBalancer) SetHref(v string) { +// SetId sets field value +func (o *NetworkLoadBalancer) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *NetworkLoadBalancer) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *NetworkLoadBalancer) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -162,7 +162,7 @@ func (o *NetworkLoadBalancer) HasHref() bool { } // GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancer) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil @@ -200,7 +200,7 @@ func (o *NetworkLoadBalancer) HasMetadata() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for NetworkLoadBalancerProperties will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancer) GetProperties() *NetworkLoadBalancerProperties { if o == nil { return nil @@ -237,38 +237,38 @@ func (o *NetworkLoadBalancer) HasProperties() bool { return false } -// GetEntities returns the Entities field value -// If the value is explicit nil, the zero value for NetworkLoadBalancerEntities will be returned -func (o *NetworkLoadBalancer) GetEntities() *NetworkLoadBalancerEntities { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancer) GetType() *Type { if o == nil { return nil } - return o.Entities + return o.Type } -// GetEntitiesOk returns a tuple with the Entities field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancer) GetEntitiesOk() (*NetworkLoadBalancerEntities, bool) { +func (o *NetworkLoadBalancer) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Entities, true + return o.Type, true } -// SetEntities sets field value -func (o *NetworkLoadBalancer) SetEntities(v NetworkLoadBalancerEntities) { +// SetType sets field value +func (o *NetworkLoadBalancer) SetType(v Type) { - o.Entities = &v + o.Type = &v } -// HasEntities returns a boolean if a field has been set. -func (o *NetworkLoadBalancer) HasEntities() bool { - if o != nil && o.Entities != nil { +// HasType returns a boolean if a field has been set. +func (o *NetworkLoadBalancer) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -277,24 +277,30 @@ func (o *NetworkLoadBalancer) HasEntities() bool { func (o NetworkLoadBalancer) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Entities != nil { + toSerialize["entities"] = o.Entities } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } - if o.Entities != nil { - toSerialize["entities"] = o.Entities + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_entities.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_entities.go index 85dd3bbd6be..cdd74071c33 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_entities.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_entities.go @@ -39,7 +39,7 @@ func NewNetworkLoadBalancerEntitiesWithDefaults() *NetworkLoadBalancerEntities { } // GetFlowlogs returns the Flowlogs field value -// If the value is explicit nil, the zero value for FlowLogs will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerEntities) GetFlowlogs() *FlowLogs { if o == nil { return nil @@ -77,7 +77,7 @@ func (o *NetworkLoadBalancerEntities) HasFlowlogs() bool { } // GetForwardingrules returns the Forwardingrules field value -// If the value is explicit nil, the zero value for NetworkLoadBalancerForwardingRules will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerEntities) GetForwardingrules() *NetworkLoadBalancerForwardingRules { if o == nil { return nil @@ -119,9 +119,11 @@ func (o NetworkLoadBalancerEntities) MarshalJSON() ([]byte, error) { if o.Flowlogs != nil { toSerialize["flowlogs"] = o.Flowlogs } + if o.Forwardingrules != nil { toSerialize["forwardingrules"] = o.Forwardingrules } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule.go index 8f054c8855a..d5018315f1a 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule.go @@ -16,14 +16,14 @@ import ( // NetworkLoadBalancerForwardingRule struct for NetworkLoadBalancerForwardingRule type NetworkLoadBalancerForwardingRule struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *NetworkLoadBalancerForwardingRuleProperties `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewNetworkLoadBalancerForwardingRule instantiates a new NetworkLoadBalancerForwardingRule object @@ -46,190 +46,190 @@ func NewNetworkLoadBalancerForwardingRuleWithDefaults() *NetworkLoadBalancerForw return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancerForwardingRule) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRule) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRule) GetIdOk() (*string, bool) { +func (o *NetworkLoadBalancerForwardingRule) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *NetworkLoadBalancerForwardingRule) SetId(v string) { +// SetHref sets field value +func (o *NetworkLoadBalancerForwardingRule) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRule) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRule) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *NetworkLoadBalancerForwardingRule) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRule) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRule) GetTypeOk() (*Type, bool) { +func (o *NetworkLoadBalancerForwardingRule) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *NetworkLoadBalancerForwardingRule) SetType(v Type) { +// SetId sets field value +func (o *NetworkLoadBalancerForwardingRule) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRule) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRule) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancerForwardingRule) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRule) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRule) GetHrefOk() (*string, bool) { +func (o *NetworkLoadBalancerForwardingRule) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *NetworkLoadBalancerForwardingRule) SetHref(v string) { +// SetMetadata sets field value +func (o *NetworkLoadBalancerForwardingRule) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRule) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRule) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *NetworkLoadBalancerForwardingRule) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRule) GetProperties() *NetworkLoadBalancerForwardingRuleProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRule) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *NetworkLoadBalancerForwardingRule) GetPropertiesOk() (*NetworkLoadBalancerForwardingRuleProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *NetworkLoadBalancerForwardingRule) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *NetworkLoadBalancerForwardingRule) SetProperties(v NetworkLoadBalancerForwardingRuleProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRule) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRule) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for NetworkLoadBalancerForwardingRuleProperties will be returned -func (o *NetworkLoadBalancerForwardingRule) GetProperties() *NetworkLoadBalancerForwardingRuleProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRule) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRule) GetPropertiesOk() (*NetworkLoadBalancerForwardingRuleProperties, bool) { +func (o *NetworkLoadBalancerForwardingRule) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *NetworkLoadBalancerForwardingRule) SetProperties(v NetworkLoadBalancerForwardingRuleProperties) { +// SetType sets field value +func (o *NetworkLoadBalancerForwardingRule) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRule) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRule) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *NetworkLoadBalancerForwardingRule) HasProperties() bool { func (o NetworkLoadBalancerForwardingRule) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_health_check.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_health_check.go index 3fa9df4f4b4..cd16a13efc7 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_health_check.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_health_check.go @@ -20,10 +20,10 @@ type NetworkLoadBalancerForwardingRuleHealthCheck struct { ClientTimeout *int32 `json:"clientTimeout,omitempty"` // The maximum time in milliseconds to wait for a connection attempt to a target to succeed; default is 5000 (five seconds). ConnectTimeout *int32 `json:"connectTimeout,omitempty"` - // The maximum time in milliseconds that a target can remain inactive; default is 50,000 (50 seconds). - TargetTimeout *int32 `json:"targetTimeout,omitempty"` // The maximum number of attempts to reconnect to a target after a connection failure. Valid range is 0 to 65535 and default is three reconnection attempts. Retries *int32 `json:"retries,omitempty"` + // The maximum time in milliseconds that a target can remain inactive; default is 50,000 (50 seconds). + TargetTimeout *int32 `json:"targetTimeout,omitempty"` } // NewNetworkLoadBalancerForwardingRuleHealthCheck instantiates a new NetworkLoadBalancerForwardingRuleHealthCheck object @@ -45,7 +45,7 @@ func NewNetworkLoadBalancerForwardingRuleHealthCheckWithDefaults() *NetworkLoadB } // GetClientTimeout returns the ClientTimeout field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerForwardingRuleHealthCheck) GetClientTimeout() *int32 { if o == nil { return nil @@ -83,7 +83,7 @@ func (o *NetworkLoadBalancerForwardingRuleHealthCheck) HasClientTimeout() bool { } // GetConnectTimeout returns the ConnectTimeout field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerForwardingRuleHealthCheck) GetConnectTimeout() *int32 { if o == nil { return nil @@ -120,76 +120,76 @@ func (o *NetworkLoadBalancerForwardingRuleHealthCheck) HasConnectTimeout() bool return false } -// GetTargetTimeout returns the TargetTimeout field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *NetworkLoadBalancerForwardingRuleHealthCheck) GetTargetTimeout() *int32 { +// GetRetries returns the Retries field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRuleHealthCheck) GetRetries() *int32 { if o == nil { return nil } - return o.TargetTimeout + return o.Retries } -// GetTargetTimeoutOk returns a tuple with the TargetTimeout field value +// GetRetriesOk returns a tuple with the Retries field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRuleHealthCheck) GetTargetTimeoutOk() (*int32, bool) { +func (o *NetworkLoadBalancerForwardingRuleHealthCheck) GetRetriesOk() (*int32, bool) { if o == nil { return nil, false } - return o.TargetTimeout, true + return o.Retries, true } -// SetTargetTimeout sets field value -func (o *NetworkLoadBalancerForwardingRuleHealthCheck) SetTargetTimeout(v int32) { +// SetRetries sets field value +func (o *NetworkLoadBalancerForwardingRuleHealthCheck) SetRetries(v int32) { - o.TargetTimeout = &v + o.Retries = &v } -// HasTargetTimeout returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRuleHealthCheck) HasTargetTimeout() bool { - if o != nil && o.TargetTimeout != nil { +// HasRetries returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRuleHealthCheck) HasRetries() bool { + if o != nil && o.Retries != nil { return true } return false } -// GetRetries returns the Retries field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *NetworkLoadBalancerForwardingRuleHealthCheck) GetRetries() *int32 { +// GetTargetTimeout returns the TargetTimeout field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRuleHealthCheck) GetTargetTimeout() *int32 { if o == nil { return nil } - return o.Retries + return o.TargetTimeout } -// GetRetriesOk returns a tuple with the Retries field value +// GetTargetTimeoutOk returns a tuple with the TargetTimeout field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRuleHealthCheck) GetRetriesOk() (*int32, bool) { +func (o *NetworkLoadBalancerForwardingRuleHealthCheck) GetTargetTimeoutOk() (*int32, bool) { if o == nil { return nil, false } - return o.Retries, true + return o.TargetTimeout, true } -// SetRetries sets field value -func (o *NetworkLoadBalancerForwardingRuleHealthCheck) SetRetries(v int32) { +// SetTargetTimeout sets field value +func (o *NetworkLoadBalancerForwardingRuleHealthCheck) SetTargetTimeout(v int32) { - o.Retries = &v + o.TargetTimeout = &v } -// HasRetries returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRuleHealthCheck) HasRetries() bool { - if o != nil && o.Retries != nil { +// HasTargetTimeout returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRuleHealthCheck) HasTargetTimeout() bool { + if o != nil && o.TargetTimeout != nil { return true } @@ -201,15 +201,19 @@ func (o NetworkLoadBalancerForwardingRuleHealthCheck) MarshalJSON() ([]byte, err if o.ClientTimeout != nil { toSerialize["clientTimeout"] = o.ClientTimeout } + if o.ConnectTimeout != nil { toSerialize["connectTimeout"] = o.ConnectTimeout } - if o.TargetTimeout != nil { - toSerialize["targetTimeout"] = o.TargetTimeout - } + if o.Retries != nil { toSerialize["retries"] = o.Retries } + + if o.TargetTimeout != nil { + toSerialize["targetTimeout"] = o.TargetTimeout + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_properties.go index 35e45278725..c3131afa171 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_properties.go @@ -16,17 +16,17 @@ import ( // NetworkLoadBalancerForwardingRuleProperties struct for NetworkLoadBalancerForwardingRuleProperties type NetworkLoadBalancerForwardingRuleProperties struct { - // The name of the Network Load Balancer forwarding rule. - Name *string `json:"name"` // Balancing algorithm - Algorithm *string `json:"algorithm"` - // Balancing protocol - Protocol *string `json:"protocol"` + Algorithm *string `json:"algorithm"` + HealthCheck *NetworkLoadBalancerForwardingRuleHealthCheck `json:"healthCheck,omitempty"` // Listening (inbound) IP. ListenerIp *string `json:"listenerIp"` // Listening (inbound) port number; valid range is 1 to 65535. - ListenerPort *int32 `json:"listenerPort"` - HealthCheck *NetworkLoadBalancerForwardingRuleHealthCheck `json:"healthCheck,omitempty"` + ListenerPort *int32 `json:"listenerPort"` + // The name of the Network Load Balancer forwarding rule. + Name *string `json:"name"` + // Balancing protocol + Protocol *string `json:"protocol"` // Array of items in the collection. Targets *[]NetworkLoadBalancerForwardingRuleTarget `json:"targets"` } @@ -35,14 +35,14 @@ type NetworkLoadBalancerForwardingRuleProperties struct { // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewNetworkLoadBalancerForwardingRuleProperties(name string, algorithm string, protocol string, listenerIp string, listenerPort int32, targets []NetworkLoadBalancerForwardingRuleTarget) *NetworkLoadBalancerForwardingRuleProperties { +func NewNetworkLoadBalancerForwardingRuleProperties(algorithm string, listenerIp string, listenerPort int32, name string, protocol string, targets []NetworkLoadBalancerForwardingRuleTarget) *NetworkLoadBalancerForwardingRuleProperties { this := NetworkLoadBalancerForwardingRuleProperties{} - this.Name = &name this.Algorithm = &algorithm - this.Protocol = &protocol this.ListenerIp = &listenerIp this.ListenerPort = &listenerPort + this.Name = &name + this.Protocol = &protocol this.Targets = &targets return &this @@ -56,46 +56,8 @@ func NewNetworkLoadBalancerForwardingRulePropertiesWithDefaults() *NetworkLoadBa return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancerForwardingRuleProperties) GetName() *string { - if o == nil { - return nil - } - - return o.Name - -} - -// GetNameOk returns a tuple with the Name field value -// and a boolean to check if the value has been set. -// NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRuleProperties) GetNameOk() (*string, bool) { - if o == nil { - return nil, false - } - - return o.Name, true -} - -// SetName sets field value -func (o *NetworkLoadBalancerForwardingRuleProperties) SetName(v string) { - - o.Name = &v - -} - -// HasName returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRuleProperties) HasName() bool { - if o != nil && o.Name != nil { - return true - } - - return false -} - // GetAlgorithm returns the Algorithm field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerForwardingRuleProperties) GetAlgorithm() *string { if o == nil { return nil @@ -132,38 +94,38 @@ func (o *NetworkLoadBalancerForwardingRuleProperties) HasAlgorithm() bool { return false } -// GetProtocol returns the Protocol field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancerForwardingRuleProperties) GetProtocol() *string { +// GetHealthCheck returns the HealthCheck field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRuleProperties) GetHealthCheck() *NetworkLoadBalancerForwardingRuleHealthCheck { if o == nil { return nil } - return o.Protocol + return o.HealthCheck } -// GetProtocolOk returns a tuple with the Protocol field value +// GetHealthCheckOk returns a tuple with the HealthCheck field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRuleProperties) GetProtocolOk() (*string, bool) { +func (o *NetworkLoadBalancerForwardingRuleProperties) GetHealthCheckOk() (*NetworkLoadBalancerForwardingRuleHealthCheck, bool) { if o == nil { return nil, false } - return o.Protocol, true + return o.HealthCheck, true } -// SetProtocol sets field value -func (o *NetworkLoadBalancerForwardingRuleProperties) SetProtocol(v string) { +// SetHealthCheck sets field value +func (o *NetworkLoadBalancerForwardingRuleProperties) SetHealthCheck(v NetworkLoadBalancerForwardingRuleHealthCheck) { - o.Protocol = &v + o.HealthCheck = &v } -// HasProtocol returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRuleProperties) HasProtocol() bool { - if o != nil && o.Protocol != nil { +// HasHealthCheck returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRuleProperties) HasHealthCheck() bool { + if o != nil && o.HealthCheck != nil { return true } @@ -171,7 +133,7 @@ func (o *NetworkLoadBalancerForwardingRuleProperties) HasProtocol() bool { } // GetListenerIp returns the ListenerIp field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerForwardingRuleProperties) GetListenerIp() *string { if o == nil { return nil @@ -209,7 +171,7 @@ func (o *NetworkLoadBalancerForwardingRuleProperties) HasListenerIp() bool { } // GetListenerPort returns the ListenerPort field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerForwardingRuleProperties) GetListenerPort() *int32 { if o == nil { return nil @@ -246,38 +208,76 @@ func (o *NetworkLoadBalancerForwardingRuleProperties) HasListenerPort() bool { return false } -// GetHealthCheck returns the HealthCheck field value -// If the value is explicit nil, the zero value for NetworkLoadBalancerForwardingRuleHealthCheck will be returned -func (o *NetworkLoadBalancerForwardingRuleProperties) GetHealthCheck() *NetworkLoadBalancerForwardingRuleHealthCheck { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRuleProperties) GetName() *string { if o == nil { return nil } - return o.HealthCheck + return o.Name } -// GetHealthCheckOk returns a tuple with the HealthCheck field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRuleProperties) GetHealthCheckOk() (*NetworkLoadBalancerForwardingRuleHealthCheck, bool) { +func (o *NetworkLoadBalancerForwardingRuleProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.HealthCheck, true + return o.Name, true } -// SetHealthCheck sets field value -func (o *NetworkLoadBalancerForwardingRuleProperties) SetHealthCheck(v NetworkLoadBalancerForwardingRuleHealthCheck) { +// SetName sets field value +func (o *NetworkLoadBalancerForwardingRuleProperties) SetName(v string) { - o.HealthCheck = &v + o.Name = &v } -// HasHealthCheck returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRuleProperties) HasHealthCheck() bool { - if o != nil && o.HealthCheck != nil { +// HasName returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRuleProperties) HasName() bool { + if o != nil && o.Name != nil { + return true + } + + return false +} + +// GetProtocol returns the Protocol field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRuleProperties) GetProtocol() *string { + if o == nil { + return nil + } + + return o.Protocol + +} + +// GetProtocolOk returns a tuple with the Protocol field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *NetworkLoadBalancerForwardingRuleProperties) GetProtocolOk() (*string, bool) { + if o == nil { + return nil, false + } + + return o.Protocol, true +} + +// SetProtocol sets field value +func (o *NetworkLoadBalancerForwardingRuleProperties) SetProtocol(v string) { + + o.Protocol = &v + +} + +// HasProtocol returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRuleProperties) HasProtocol() bool { + if o != nil && o.Protocol != nil { return true } @@ -285,7 +285,7 @@ func (o *NetworkLoadBalancerForwardingRuleProperties) HasHealthCheck() bool { } // GetTargets returns the Targets field value -// If the value is explicit nil, the zero value for []NetworkLoadBalancerForwardingRuleTarget will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerForwardingRuleProperties) GetTargets() *[]NetworkLoadBalancerForwardingRuleTarget { if o == nil { return nil @@ -324,27 +324,34 @@ func (o *NetworkLoadBalancerForwardingRuleProperties) HasTargets() bool { func (o NetworkLoadBalancerForwardingRuleProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name - } if o.Algorithm != nil { toSerialize["algorithm"] = o.Algorithm } - if o.Protocol != nil { - toSerialize["protocol"] = o.Protocol + + if o.HealthCheck != nil { + toSerialize["healthCheck"] = o.HealthCheck } + if o.ListenerIp != nil { toSerialize["listenerIp"] = o.ListenerIp } + if o.ListenerPort != nil { toSerialize["listenerPort"] = o.ListenerPort } - if o.HealthCheck != nil { - toSerialize["healthCheck"] = o.HealthCheck + + if o.Name != nil { + toSerialize["name"] = o.Name } + + if o.Protocol != nil { + toSerialize["protocol"] = o.Protocol + } + if o.Targets != nil { toSerialize["targets"] = o.Targets } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_put.go index ee8f95aeae7..16c6e39bb7c 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_put.go @@ -16,13 +16,13 @@ import ( // NetworkLoadBalancerForwardingRulePut struct for NetworkLoadBalancerForwardingRulePut type NetworkLoadBalancerForwardingRulePut struct { + // URL to the object representation (absolute path). + Href *string `json:"href,omitempty"` // The resource's unique identifier. - Id *string `json:"id,omitempty"` + Id *string `json:"id,omitempty"` + Properties *NetworkLoadBalancerForwardingRuleProperties `json:"properties"` // The type of object that has been created. Type *Type `json:"type,omitempty"` - // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` - Properties *NetworkLoadBalancerForwardingRuleProperties `json:"properties"` } // NewNetworkLoadBalancerForwardingRulePut instantiates a new NetworkLoadBalancerForwardingRulePut object @@ -45,152 +45,152 @@ func NewNetworkLoadBalancerForwardingRulePutWithDefaults() *NetworkLoadBalancerF return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancerForwardingRulePut) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRulePut) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRulePut) GetIdOk() (*string, bool) { +func (o *NetworkLoadBalancerForwardingRulePut) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *NetworkLoadBalancerForwardingRulePut) SetId(v string) { +// SetHref sets field value +func (o *NetworkLoadBalancerForwardingRulePut) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRulePut) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRulePut) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *NetworkLoadBalancerForwardingRulePut) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRulePut) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRulePut) GetTypeOk() (*Type, bool) { +func (o *NetworkLoadBalancerForwardingRulePut) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *NetworkLoadBalancerForwardingRulePut) SetType(v Type) { +// SetId sets field value +func (o *NetworkLoadBalancerForwardingRulePut) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRulePut) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRulePut) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancerForwardingRulePut) GetHref() *string { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRulePut) GetProperties() *NetworkLoadBalancerForwardingRuleProperties { if o == nil { return nil } - return o.Href + return o.Properties } -// GetHrefOk returns a tuple with the Href field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRulePut) GetHrefOk() (*string, bool) { +func (o *NetworkLoadBalancerForwardingRulePut) GetPropertiesOk() (*NetworkLoadBalancerForwardingRuleProperties, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Properties, true } -// SetHref sets field value -func (o *NetworkLoadBalancerForwardingRulePut) SetHref(v string) { +// SetProperties sets field value +func (o *NetworkLoadBalancerForwardingRulePut) SetProperties(v NetworkLoadBalancerForwardingRuleProperties) { - o.Href = &v + o.Properties = &v } -// HasHref returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRulePut) HasHref() bool { - if o != nil && o.Href != nil { +// HasProperties returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRulePut) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for NetworkLoadBalancerForwardingRuleProperties will be returned -func (o *NetworkLoadBalancerForwardingRulePut) GetProperties() *NetworkLoadBalancerForwardingRuleProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRulePut) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRulePut) GetPropertiesOk() (*NetworkLoadBalancerForwardingRuleProperties, bool) { +func (o *NetworkLoadBalancerForwardingRulePut) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *NetworkLoadBalancerForwardingRulePut) SetProperties(v NetworkLoadBalancerForwardingRuleProperties) { +// SetType sets field value +func (o *NetworkLoadBalancerForwardingRulePut) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRulePut) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRulePut) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -199,18 +199,22 @@ func (o *NetworkLoadBalancerForwardingRulePut) HasProperties() bool { func (o NetworkLoadBalancerForwardingRulePut) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_target.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_target.go index 502d5bda87b..b1a9e448270 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_target.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_target.go @@ -16,13 +16,13 @@ import ( // NetworkLoadBalancerForwardingRuleTarget struct for NetworkLoadBalancerForwardingRuleTarget type NetworkLoadBalancerForwardingRuleTarget struct { + HealthCheck *NetworkLoadBalancerForwardingRuleTargetHealthCheck `json:"healthCheck,omitempty"` // The IP of the balanced target VM. Ip *string `json:"ip"` // The port of the balanced target service; valid range is 1 to 65535. Port *int32 `json:"port"` // Traffic is distributed in proportion to target weight, relative to the combined weight of all targets. A target with higher weight receives a greater share of traffic. Valid range is 0 to 256 and default is 1. Targets with weight of 0 do not participate in load balancing but still accept persistent connections. It is best to assign weights in the middle of the range to leave room for later adjustments. - Weight *int32 `json:"weight"` - HealthCheck *NetworkLoadBalancerForwardingRuleTargetHealthCheck `json:"healthCheck,omitempty"` + Weight *int32 `json:"weight"` } // NewNetworkLoadBalancerForwardingRuleTarget instantiates a new NetworkLoadBalancerForwardingRuleTarget object @@ -47,8 +47,46 @@ func NewNetworkLoadBalancerForwardingRuleTargetWithDefaults() *NetworkLoadBalanc return &this } +// GetHealthCheck returns the HealthCheck field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRuleTarget) GetHealthCheck() *NetworkLoadBalancerForwardingRuleTargetHealthCheck { + if o == nil { + return nil + } + + return o.HealthCheck + +} + +// GetHealthCheckOk returns a tuple with the HealthCheck field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *NetworkLoadBalancerForwardingRuleTarget) GetHealthCheckOk() (*NetworkLoadBalancerForwardingRuleTargetHealthCheck, bool) { + if o == nil { + return nil, false + } + + return o.HealthCheck, true +} + +// SetHealthCheck sets field value +func (o *NetworkLoadBalancerForwardingRuleTarget) SetHealthCheck(v NetworkLoadBalancerForwardingRuleTargetHealthCheck) { + + o.HealthCheck = &v + +} + +// HasHealthCheck returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRuleTarget) HasHealthCheck() bool { + if o != nil && o.HealthCheck != nil { + return true + } + + return false +} + // GetIp returns the Ip field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerForwardingRuleTarget) GetIp() *string { if o == nil { return nil @@ -86,7 +124,7 @@ func (o *NetworkLoadBalancerForwardingRuleTarget) HasIp() bool { } // GetPort returns the Port field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerForwardingRuleTarget) GetPort() *int32 { if o == nil { return nil @@ -124,7 +162,7 @@ func (o *NetworkLoadBalancerForwardingRuleTarget) HasPort() bool { } // GetWeight returns the Weight field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerForwardingRuleTarget) GetWeight() *int32 { if o == nil { return nil @@ -161,58 +199,24 @@ func (o *NetworkLoadBalancerForwardingRuleTarget) HasWeight() bool { return false } -// GetHealthCheck returns the HealthCheck field value -// If the value is explicit nil, the zero value for NetworkLoadBalancerForwardingRuleTargetHealthCheck will be returned -func (o *NetworkLoadBalancerForwardingRuleTarget) GetHealthCheck() *NetworkLoadBalancerForwardingRuleTargetHealthCheck { - if o == nil { - return nil - } - - return o.HealthCheck - -} - -// GetHealthCheckOk returns a tuple with the HealthCheck field value -// and a boolean to check if the value has been set. -// NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRuleTarget) GetHealthCheckOk() (*NetworkLoadBalancerForwardingRuleTargetHealthCheck, bool) { - if o == nil { - return nil, false - } - - return o.HealthCheck, true -} - -// SetHealthCheck sets field value -func (o *NetworkLoadBalancerForwardingRuleTarget) SetHealthCheck(v NetworkLoadBalancerForwardingRuleTargetHealthCheck) { - - o.HealthCheck = &v - -} - -// HasHealthCheck returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRuleTarget) HasHealthCheck() bool { - if o != nil && o.HealthCheck != nil { - return true - } - - return false -} - func (o NetworkLoadBalancerForwardingRuleTarget) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} + if o.HealthCheck != nil { + toSerialize["healthCheck"] = o.HealthCheck + } + if o.Ip != nil { toSerialize["ip"] = o.Ip } + if o.Port != nil { toSerialize["port"] = o.Port } + if o.Weight != nil { toSerialize["weight"] = o.Weight } - if o.HealthCheck != nil { - toSerialize["healthCheck"] = o.HealthCheck - } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_target_health_check.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_target_health_check.go index 8fac2b6dbd0..8d7e994a32c 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_target_health_check.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rule_target_health_check.go @@ -43,7 +43,7 @@ func NewNetworkLoadBalancerForwardingRuleTargetHealthCheckWithDefaults() *Networ } // GetCheck returns the Check field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerForwardingRuleTargetHealthCheck) GetCheck() *bool { if o == nil { return nil @@ -81,7 +81,7 @@ func (o *NetworkLoadBalancerForwardingRuleTargetHealthCheck) HasCheck() bool { } // GetCheckInterval returns the CheckInterval field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerForwardingRuleTargetHealthCheck) GetCheckInterval() *int32 { if o == nil { return nil @@ -119,7 +119,7 @@ func (o *NetworkLoadBalancerForwardingRuleTargetHealthCheck) HasCheckInterval() } // GetMaintenance returns the Maintenance field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerForwardingRuleTargetHealthCheck) GetMaintenance() *bool { if o == nil { return nil @@ -161,12 +161,15 @@ func (o NetworkLoadBalancerForwardingRuleTargetHealthCheck) MarshalJSON() ([]byt if o.Check != nil { toSerialize["check"] = o.Check } + if o.CheckInterval != nil { toSerialize["checkInterval"] = o.CheckInterval } + if o.Maintenance != nil { toSerialize["maintenance"] = o.Maintenance } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rules.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rules.go index a23c7740825..2668d63287e 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rules.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_forwarding_rules.go @@ -16,19 +16,19 @@ import ( // NetworkLoadBalancerForwardingRules struct for NetworkLoadBalancerForwardingRules type NetworkLoadBalancerForwardingRules struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]NetworkLoadBalancerForwardingRule `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewNetworkLoadBalancerForwardingRules instantiates a new NetworkLoadBalancerForwardingRules object @@ -49,114 +49,114 @@ func NewNetworkLoadBalancerForwardingRulesWithDefaults() *NetworkLoadBalancerFor return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancerForwardingRules) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRules) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRules) GetIdOk() (*string, bool) { +func (o *NetworkLoadBalancerForwardingRules) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *NetworkLoadBalancerForwardingRules) SetId(v string) { +// SetLinks sets field value +func (o *NetworkLoadBalancerForwardingRules) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRules) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRules) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *NetworkLoadBalancerForwardingRules) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRules) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRules) GetTypeOk() (*Type, bool) { +func (o *NetworkLoadBalancerForwardingRules) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *NetworkLoadBalancerForwardingRules) SetType(v Type) { +// SetHref sets field value +func (o *NetworkLoadBalancerForwardingRules) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRules) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRules) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancerForwardingRules) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRules) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRules) GetHrefOk() (*string, bool) { +func (o *NetworkLoadBalancerForwardingRules) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *NetworkLoadBalancerForwardingRules) SetHref(v string) { +// SetId sets field value +func (o *NetworkLoadBalancerForwardingRules) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRules) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRules) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *NetworkLoadBalancerForwardingRules) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []NetworkLoadBalancerForwardingRule will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerForwardingRules) GetItems() *[]NetworkLoadBalancerForwardingRule { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *NetworkLoadBalancerForwardingRules) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *NetworkLoadBalancerForwardingRules) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRules) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRules) GetOffsetOk() (*float32, bool) { +func (o *NetworkLoadBalancerForwardingRules) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *NetworkLoadBalancerForwardingRules) SetOffset(v float32) { +// SetLimit sets field value +func (o *NetworkLoadBalancerForwardingRules) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRules) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRules) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *NetworkLoadBalancerForwardingRules) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRules) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRules) GetLimitOk() (*float32, bool) { +func (o *NetworkLoadBalancerForwardingRules) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *NetworkLoadBalancerForwardingRules) SetLimit(v float32) { +// SetOffset sets field value +func (o *NetworkLoadBalancerForwardingRules) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRules) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRules) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *NetworkLoadBalancerForwardingRules) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerForwardingRules) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerForwardingRules) GetLinksOk() (*PaginationLinks, bool) { +func (o *NetworkLoadBalancerForwardingRules) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *NetworkLoadBalancerForwardingRules) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *NetworkLoadBalancerForwardingRules) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *NetworkLoadBalancerForwardingRules) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *NetworkLoadBalancerForwardingRules) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *NetworkLoadBalancerForwardingRules) HasLinks() bool { func (o NetworkLoadBalancerForwardingRules) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_properties.go index 94170d456e0..114b8b08a15 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_properties.go @@ -16,27 +16,27 @@ import ( // NetworkLoadBalancerProperties struct for NetworkLoadBalancerProperties type NetworkLoadBalancerProperties struct { - // The name of the Network Load Balancer. - Name *string `json:"name"` - // ID of the listening LAN (inbound). - ListenerLan *int32 `json:"listenerLan"` // Collection of the Network Load Balancer IP addresses. (Inbound and outbound) IPs of the listenerLan must be customer-reserved IPs for public Load Balancers, and private IPs for private Load Balancers. Ips *[]string `json:"ips,omitempty"` - // ID of the balanced private target LAN (outbound). - TargetLan *int32 `json:"targetLan"` // Collection of private IP addresses with subnet mask of the Network Load Balancer. IPs must contain a valid subnet mask. If no IP is provided, the system will generate an IP with /24 subnet. LbPrivateIps *[]string `json:"lbPrivateIps,omitempty"` + // ID of the listening LAN (inbound). + ListenerLan *int32 `json:"listenerLan"` + // The name of the Network Load Balancer. + Name *string `json:"name"` + // ID of the balanced private target LAN (outbound). + TargetLan *int32 `json:"targetLan"` } // NewNetworkLoadBalancerProperties instantiates a new NetworkLoadBalancerProperties object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewNetworkLoadBalancerProperties(name string, listenerLan int32, targetLan int32) *NetworkLoadBalancerProperties { +func NewNetworkLoadBalancerProperties(listenerLan int32, name string, targetLan int32) *NetworkLoadBalancerProperties { this := NetworkLoadBalancerProperties{} - this.Name = &name this.ListenerLan = &listenerLan + this.Name = &name this.TargetLan = &targetLan return &this @@ -50,38 +50,76 @@ func NewNetworkLoadBalancerPropertiesWithDefaults() *NetworkLoadBalancerProperti return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancerProperties) GetName() *string { +// GetIps returns the Ips field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerProperties) GetIps() *[]string { if o == nil { return nil } - return o.Name + return o.Ips } -// GetNameOk returns a tuple with the Name field value +// GetIpsOk returns a tuple with the Ips field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerProperties) GetNameOk() (*string, bool) { +func (o *NetworkLoadBalancerProperties) GetIpsOk() (*[]string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.Ips, true } -// SetName sets field value -func (o *NetworkLoadBalancerProperties) SetName(v string) { +// SetIps sets field value +func (o *NetworkLoadBalancerProperties) SetIps(v []string) { - o.Name = &v + o.Ips = &v } -// HasName returns a boolean if a field has been set. -func (o *NetworkLoadBalancerProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasIps returns a boolean if a field has been set. +func (o *NetworkLoadBalancerProperties) HasIps() bool { + if o != nil && o.Ips != nil { + return true + } + + return false +} + +// GetLbPrivateIps returns the LbPrivateIps field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerProperties) GetLbPrivateIps() *[]string { + if o == nil { + return nil + } + + return o.LbPrivateIps + +} + +// GetLbPrivateIpsOk returns a tuple with the LbPrivateIps field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *NetworkLoadBalancerProperties) GetLbPrivateIpsOk() (*[]string, bool) { + if o == nil { + return nil, false + } + + return o.LbPrivateIps, true +} + +// SetLbPrivateIps sets field value +func (o *NetworkLoadBalancerProperties) SetLbPrivateIps(v []string) { + + o.LbPrivateIps = &v + +} + +// HasLbPrivateIps returns a boolean if a field has been set. +func (o *NetworkLoadBalancerProperties) HasLbPrivateIps() bool { + if o != nil && o.LbPrivateIps != nil { return true } @@ -89,7 +127,7 @@ func (o *NetworkLoadBalancerProperties) HasName() bool { } // GetListenerLan returns the ListenerLan field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerProperties) GetListenerLan() *int32 { if o == nil { return nil @@ -126,38 +164,38 @@ func (o *NetworkLoadBalancerProperties) HasListenerLan() bool { return false } -// GetIps returns the Ips field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *NetworkLoadBalancerProperties) GetIps() *[]string { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerProperties) GetName() *string { if o == nil { return nil } - return o.Ips + return o.Name } -// GetIpsOk returns a tuple with the Ips field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerProperties) GetIpsOk() (*[]string, bool) { +func (o *NetworkLoadBalancerProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.Ips, true + return o.Name, true } -// SetIps sets field value -func (o *NetworkLoadBalancerProperties) SetIps(v []string) { +// SetName sets field value +func (o *NetworkLoadBalancerProperties) SetName(v string) { - o.Ips = &v + o.Name = &v } -// HasIps returns a boolean if a field has been set. -func (o *NetworkLoadBalancerProperties) HasIps() bool { - if o != nil && o.Ips != nil { +// HasName returns a boolean if a field has been set. +func (o *NetworkLoadBalancerProperties) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -165,7 +203,7 @@ func (o *NetworkLoadBalancerProperties) HasIps() bool { } // GetTargetLan returns the TargetLan field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancerProperties) GetTargetLan() *int32 { if o == nil { return nil @@ -202,61 +240,28 @@ func (o *NetworkLoadBalancerProperties) HasTargetLan() bool { return false } -// GetLbPrivateIps returns the LbPrivateIps field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *NetworkLoadBalancerProperties) GetLbPrivateIps() *[]string { - if o == nil { - return nil +func (o NetworkLoadBalancerProperties) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if o.Ips != nil { + toSerialize["ips"] = o.Ips } - return o.LbPrivateIps - -} - -// GetLbPrivateIpsOk returns a tuple with the LbPrivateIps field value -// and a boolean to check if the value has been set. -// NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerProperties) GetLbPrivateIpsOk() (*[]string, bool) { - if o == nil { - return nil, false + if o.LbPrivateIps != nil { + toSerialize["lbPrivateIps"] = o.LbPrivateIps } - return o.LbPrivateIps, true -} - -// SetLbPrivateIps sets field value -func (o *NetworkLoadBalancerProperties) SetLbPrivateIps(v []string) { - - o.LbPrivateIps = &v - -} - -// HasLbPrivateIps returns a boolean if a field has been set. -func (o *NetworkLoadBalancerProperties) HasLbPrivateIps() bool { - if o != nil && o.LbPrivateIps != nil { - return true + if o.ListenerLan != nil { + toSerialize["listenerLan"] = o.ListenerLan } - return false -} - -func (o NetworkLoadBalancerProperties) MarshalJSON() ([]byte, error) { - toSerialize := map[string]interface{}{} if o.Name != nil { toSerialize["name"] = o.Name } - if o.ListenerLan != nil { - toSerialize["listenerLan"] = o.ListenerLan - } - if o.Ips != nil { - toSerialize["ips"] = o.Ips - } + if o.TargetLan != nil { toSerialize["targetLan"] = o.TargetLan } - if o.LbPrivateIps != nil { - toSerialize["lbPrivateIps"] = o.LbPrivateIps - } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_put.go index 05bde508cbb..ec4deb54b3a 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancer_put.go @@ -16,13 +16,13 @@ import ( // NetworkLoadBalancerPut struct for NetworkLoadBalancerPut type NetworkLoadBalancerPut struct { + // URL to the object representation (absolute path). + Href *string `json:"href,omitempty"` // The resource's unique identifier. - Id *string `json:"id,omitempty"` + Id *string `json:"id,omitempty"` + Properties *NetworkLoadBalancerProperties `json:"properties"` // The type of object that has been created. Type *Type `json:"type,omitempty"` - // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` - Properties *NetworkLoadBalancerProperties `json:"properties"` } // NewNetworkLoadBalancerPut instantiates a new NetworkLoadBalancerPut object @@ -45,152 +45,152 @@ func NewNetworkLoadBalancerPutWithDefaults() *NetworkLoadBalancerPut { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancerPut) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerPut) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerPut) GetIdOk() (*string, bool) { +func (o *NetworkLoadBalancerPut) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *NetworkLoadBalancerPut) SetId(v string) { +// SetHref sets field value +func (o *NetworkLoadBalancerPut) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *NetworkLoadBalancerPut) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *NetworkLoadBalancerPut) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *NetworkLoadBalancerPut) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerPut) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerPut) GetTypeOk() (*Type, bool) { +func (o *NetworkLoadBalancerPut) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *NetworkLoadBalancerPut) SetType(v Type) { +// SetId sets field value +func (o *NetworkLoadBalancerPut) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *NetworkLoadBalancerPut) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *NetworkLoadBalancerPut) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancerPut) GetHref() *string { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerPut) GetProperties() *NetworkLoadBalancerProperties { if o == nil { return nil } - return o.Href + return o.Properties } -// GetHrefOk returns a tuple with the Href field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerPut) GetHrefOk() (*string, bool) { +func (o *NetworkLoadBalancerPut) GetPropertiesOk() (*NetworkLoadBalancerProperties, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Properties, true } -// SetHref sets field value -func (o *NetworkLoadBalancerPut) SetHref(v string) { +// SetProperties sets field value +func (o *NetworkLoadBalancerPut) SetProperties(v NetworkLoadBalancerProperties) { - o.Href = &v + o.Properties = &v } -// HasHref returns a boolean if a field has been set. -func (o *NetworkLoadBalancerPut) HasHref() bool { - if o != nil && o.Href != nil { +// HasProperties returns a boolean if a field has been set. +func (o *NetworkLoadBalancerPut) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for NetworkLoadBalancerProperties will be returned -func (o *NetworkLoadBalancerPut) GetProperties() *NetworkLoadBalancerProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancerPut) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancerPut) GetPropertiesOk() (*NetworkLoadBalancerProperties, bool) { +func (o *NetworkLoadBalancerPut) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *NetworkLoadBalancerPut) SetProperties(v NetworkLoadBalancerProperties) { +// SetType sets field value +func (o *NetworkLoadBalancerPut) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *NetworkLoadBalancerPut) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *NetworkLoadBalancerPut) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -199,18 +199,22 @@ func (o *NetworkLoadBalancerPut) HasProperties() bool { func (o NetworkLoadBalancerPut) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancers.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancers.go index 91bbe63e1fb..b4ccbbc8734 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancers.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_network_load_balancers.go @@ -16,19 +16,19 @@ import ( // NetworkLoadBalancers struct for NetworkLoadBalancers type NetworkLoadBalancers struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]NetworkLoadBalancer `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewNetworkLoadBalancers instantiates a new NetworkLoadBalancers object @@ -49,114 +49,114 @@ func NewNetworkLoadBalancersWithDefaults() *NetworkLoadBalancers { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancers) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancers) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancers) GetIdOk() (*string, bool) { +func (o *NetworkLoadBalancers) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *NetworkLoadBalancers) SetId(v string) { +// SetLinks sets field value +func (o *NetworkLoadBalancers) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *NetworkLoadBalancers) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *NetworkLoadBalancers) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *NetworkLoadBalancers) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancers) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancers) GetTypeOk() (*Type, bool) { +func (o *NetworkLoadBalancers) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *NetworkLoadBalancers) SetType(v Type) { +// SetHref sets field value +func (o *NetworkLoadBalancers) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *NetworkLoadBalancers) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *NetworkLoadBalancers) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NetworkLoadBalancers) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancers) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancers) GetHrefOk() (*string, bool) { +func (o *NetworkLoadBalancers) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *NetworkLoadBalancers) SetHref(v string) { +// SetId sets field value +func (o *NetworkLoadBalancers) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *NetworkLoadBalancers) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *NetworkLoadBalancers) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *NetworkLoadBalancers) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []NetworkLoadBalancer will be returned +// If the value is explicit nil, nil is returned func (o *NetworkLoadBalancers) GetItems() *[]NetworkLoadBalancer { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *NetworkLoadBalancers) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *NetworkLoadBalancers) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancers) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancers) GetOffsetOk() (*float32, bool) { +func (o *NetworkLoadBalancers) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *NetworkLoadBalancers) SetOffset(v float32) { +// SetLimit sets field value +func (o *NetworkLoadBalancers) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *NetworkLoadBalancers) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *NetworkLoadBalancers) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *NetworkLoadBalancers) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancers) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancers) GetLimitOk() (*float32, bool) { +func (o *NetworkLoadBalancers) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *NetworkLoadBalancers) SetLimit(v float32) { +// SetOffset sets field value +func (o *NetworkLoadBalancers) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *NetworkLoadBalancers) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *NetworkLoadBalancers) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *NetworkLoadBalancers) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *NetworkLoadBalancers) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NetworkLoadBalancers) GetLinksOk() (*PaginationLinks, bool) { +func (o *NetworkLoadBalancers) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *NetworkLoadBalancers) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *NetworkLoadBalancers) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *NetworkLoadBalancers) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *NetworkLoadBalancers) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *NetworkLoadBalancers) HasLinks() bool { func (o NetworkLoadBalancers) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic.go index 9d8378c6f32..6a9c05537b2 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic.go @@ -16,15 +16,15 @@ import ( // Nic struct for Nic type Nic struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Entities *NicEntities `json:"entities,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *NicProperties `json:"properties"` - Entities *NicEntities `json:"entities,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewNic instantiates a new Nic object @@ -47,114 +47,114 @@ func NewNicWithDefaults() *Nic { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Nic) GetId() *string { +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *Nic) GetEntities() *NicEntities { if o == nil { return nil } - return o.Id + return o.Entities } -// GetIdOk returns a tuple with the Id field value +// GetEntitiesOk returns a tuple with the Entities field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Nic) GetIdOk() (*string, bool) { +func (o *Nic) GetEntitiesOk() (*NicEntities, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Entities, true } -// SetId sets field value -func (o *Nic) SetId(v string) { +// SetEntities sets field value +func (o *Nic) SetEntities(v NicEntities) { - o.Id = &v + o.Entities = &v } -// HasId returns a boolean if a field has been set. -func (o *Nic) HasId() bool { - if o != nil && o.Id != nil { +// HasEntities returns a boolean if a field has been set. +func (o *Nic) HasEntities() bool { + if o != nil && o.Entities != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Nic) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Nic) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Nic) GetTypeOk() (*Type, bool) { +func (o *Nic) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Nic) SetType(v Type) { +// SetHref sets field value +func (o *Nic) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Nic) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Nic) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Nic) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Nic) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Nic) GetHrefOk() (*string, bool) { +func (o *Nic) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Nic) SetHref(v string) { +// SetId sets field value +func (o *Nic) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Nic) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Nic) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -162,7 +162,7 @@ func (o *Nic) HasHref() bool { } // GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned +// If the value is explicit nil, nil is returned func (o *Nic) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil @@ -200,7 +200,7 @@ func (o *Nic) HasMetadata() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for NicProperties will be returned +// If the value is explicit nil, nil is returned func (o *Nic) GetProperties() *NicProperties { if o == nil { return nil @@ -237,38 +237,38 @@ func (o *Nic) HasProperties() bool { return false } -// GetEntities returns the Entities field value -// If the value is explicit nil, the zero value for NicEntities will be returned -func (o *Nic) GetEntities() *NicEntities { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Nic) GetType() *Type { if o == nil { return nil } - return o.Entities + return o.Type } -// GetEntitiesOk returns a tuple with the Entities field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Nic) GetEntitiesOk() (*NicEntities, bool) { +func (o *Nic) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Entities, true + return o.Type, true } -// SetEntities sets field value -func (o *Nic) SetEntities(v NicEntities) { +// SetType sets field value +func (o *Nic) SetType(v Type) { - o.Entities = &v + o.Type = &v } -// HasEntities returns a boolean if a field has been set. -func (o *Nic) HasEntities() bool { - if o != nil && o.Entities != nil { +// HasType returns a boolean if a field has been set. +func (o *Nic) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -277,24 +277,30 @@ func (o *Nic) HasEntities() bool { func (o Nic) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Entities != nil { + toSerialize["entities"] = o.Entities } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } - if o.Entities != nil { - toSerialize["entities"] = o.Entities + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic_entities.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic_entities.go index b1a5553a7e8..ab19ab4ac91 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic_entities.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic_entities.go @@ -16,8 +16,8 @@ import ( // NicEntities struct for NicEntities type NicEntities struct { - Flowlogs *FlowLogs `json:"flowlogs,omitempty"` Firewallrules *FirewallRules `json:"firewallrules,omitempty"` + Flowlogs *FlowLogs `json:"flowlogs,omitempty"` } // NewNicEntities instantiates a new NicEntities object @@ -38,76 +38,76 @@ func NewNicEntitiesWithDefaults() *NicEntities { return &this } -// GetFlowlogs returns the Flowlogs field value -// If the value is explicit nil, the zero value for FlowLogs will be returned -func (o *NicEntities) GetFlowlogs() *FlowLogs { +// GetFirewallrules returns the Firewallrules field value +// If the value is explicit nil, nil is returned +func (o *NicEntities) GetFirewallrules() *FirewallRules { if o == nil { return nil } - return o.Flowlogs + return o.Firewallrules } -// GetFlowlogsOk returns a tuple with the Flowlogs field value +// GetFirewallrulesOk returns a tuple with the Firewallrules field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NicEntities) GetFlowlogsOk() (*FlowLogs, bool) { +func (o *NicEntities) GetFirewallrulesOk() (*FirewallRules, bool) { if o == nil { return nil, false } - return o.Flowlogs, true + return o.Firewallrules, true } -// SetFlowlogs sets field value -func (o *NicEntities) SetFlowlogs(v FlowLogs) { +// SetFirewallrules sets field value +func (o *NicEntities) SetFirewallrules(v FirewallRules) { - o.Flowlogs = &v + o.Firewallrules = &v } -// HasFlowlogs returns a boolean if a field has been set. -func (o *NicEntities) HasFlowlogs() bool { - if o != nil && o.Flowlogs != nil { +// HasFirewallrules returns a boolean if a field has been set. +func (o *NicEntities) HasFirewallrules() bool { + if o != nil && o.Firewallrules != nil { return true } return false } -// GetFirewallrules returns the Firewallrules field value -// If the value is explicit nil, the zero value for FirewallRules will be returned -func (o *NicEntities) GetFirewallrules() *FirewallRules { +// GetFlowlogs returns the Flowlogs field value +// If the value is explicit nil, nil is returned +func (o *NicEntities) GetFlowlogs() *FlowLogs { if o == nil { return nil } - return o.Firewallrules + return o.Flowlogs } -// GetFirewallrulesOk returns a tuple with the Firewallrules field value +// GetFlowlogsOk returns a tuple with the Flowlogs field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NicEntities) GetFirewallrulesOk() (*FirewallRules, bool) { +func (o *NicEntities) GetFlowlogsOk() (*FlowLogs, bool) { if o == nil { return nil, false } - return o.Firewallrules, true + return o.Flowlogs, true } -// SetFirewallrules sets field value -func (o *NicEntities) SetFirewallrules(v FirewallRules) { +// SetFlowlogs sets field value +func (o *NicEntities) SetFlowlogs(v FlowLogs) { - o.Firewallrules = &v + o.Flowlogs = &v } -// HasFirewallrules returns a boolean if a field has been set. -func (o *NicEntities) HasFirewallrules() bool { - if o != nil && o.Firewallrules != nil { +// HasFlowlogs returns a boolean if a field has been set. +func (o *NicEntities) HasFlowlogs() bool { + if o != nil && o.Flowlogs != nil { return true } @@ -116,12 +116,14 @@ func (o *NicEntities) HasFirewallrules() bool { func (o NicEntities) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Flowlogs != nil { - toSerialize["flowlogs"] = o.Flowlogs - } if o.Firewallrules != nil { toSerialize["firewallrules"] = o.Firewallrules } + + if o.Flowlogs != nil { + toSerialize["flowlogs"] = o.Flowlogs + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic_properties.go index 20d0323ace0..f59a5d86278 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic_properties.go @@ -16,24 +16,27 @@ import ( // NicProperties struct for NicProperties type NicProperties struct { - // The name of the resource. - Name *string `json:"name,omitempty"` - // The MAC address of the NIC. - Mac *string `json:"mac,omitempty"` - // Collection of IP addresses, assigned to the NIC. Explicitly assigned public IPs need to come from reserved IP blocks. Passing value null or empty array will assign an IP address automatically. - Ips *[]string `json:"ips,omitempty"` + // The Logical Unit Number (LUN) of the storage volume. Null if this NIC was created using Cloud API and no DCD changes were performed on the Datacenter. + DeviceNumber *int32 `json:"deviceNumber,omitempty"` // Indicates if the NIC will reserve an IP using DHCP. Dhcp *bool `json:"dhcp,omitempty"` - // The LAN ID the NIC will be on. If the LAN ID does not exist, it will be implicitly created. - Lan *int32 `json:"lan"` // Activate or deactivate the firewall. By default, an active firewall without any defined rules will block all incoming network traffic except for the firewall rules that explicitly allows certain protocols, IP addresses and ports. FirewallActive *bool `json:"firewallActive,omitempty"` // The type of firewall rules that will be allowed on the NIC. If not specified, the default INGRESS value is used. FirewallType *string `json:"firewallType,omitempty"` - // The Logical Unit Number (LUN) of the storage volume. Null if this NIC was created using Cloud API and no DCD changes were performed on the Datacenter. - DeviceNumber *int32 `json:"deviceNumber,omitempty"` + // Collection of IP addresses, assigned to the NIC. Explicitly assigned public IPs need to come from reserved IP blocks. Passing value null or empty array will assign an IP address automatically. + // to set this field to `nil` in order to be marshalled, the explicit nil address `Nil[]string` can be used, or the setter `SetIpsNil` + Ips *[]string `json:"ips,omitempty"` + // The LAN ID the NIC will be on. If the LAN ID does not exist, it will be implicitly created. + Lan *int32 `json:"lan"` + // The MAC address of the NIC. + Mac *string `json:"mac,omitempty"` + // The name of the resource. + Name *string `json:"name,omitempty"` // The PCI slot number for the NIC. PciSlot *int32 `json:"pciSlot,omitempty"` + // The vnet ID that belongs to this NIC; Requires system privileges + Vnet *string `json:"vnet,omitempty"` } // NewNicProperties instantiates a new NicProperties object @@ -60,304 +63,304 @@ func NewNicPropertiesWithDefaults() *NicProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NicProperties) GetName() *string { +// GetDeviceNumber returns the DeviceNumber field value +// If the value is explicit nil, nil is returned +func (o *NicProperties) GetDeviceNumber() *int32 { if o == nil { return nil } - return o.Name + return o.DeviceNumber } -// GetNameOk returns a tuple with the Name field value +// GetDeviceNumberOk returns a tuple with the DeviceNumber field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NicProperties) GetNameOk() (*string, bool) { +func (o *NicProperties) GetDeviceNumberOk() (*int32, bool) { if o == nil { return nil, false } - return o.Name, true + return o.DeviceNumber, true } -// SetName sets field value -func (o *NicProperties) SetName(v string) { +// SetDeviceNumber sets field value +func (o *NicProperties) SetDeviceNumber(v int32) { - o.Name = &v + o.DeviceNumber = &v } -// HasName returns a boolean if a field has been set. -func (o *NicProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasDeviceNumber returns a boolean if a field has been set. +func (o *NicProperties) HasDeviceNumber() bool { + if o != nil && o.DeviceNumber != nil { return true } return false } -// GetMac returns the Mac field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NicProperties) GetMac() *string { +// GetDhcp returns the Dhcp field value +// If the value is explicit nil, nil is returned +func (o *NicProperties) GetDhcp() *bool { if o == nil { return nil } - return o.Mac + return o.Dhcp } -// GetMacOk returns a tuple with the Mac field value +// GetDhcpOk returns a tuple with the Dhcp field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NicProperties) GetMacOk() (*string, bool) { +func (o *NicProperties) GetDhcpOk() (*bool, bool) { if o == nil { return nil, false } - return o.Mac, true + return o.Dhcp, true } -// SetMac sets field value -func (o *NicProperties) SetMac(v string) { +// SetDhcp sets field value +func (o *NicProperties) SetDhcp(v bool) { - o.Mac = &v + o.Dhcp = &v } -// HasMac returns a boolean if a field has been set. -func (o *NicProperties) HasMac() bool { - if o != nil && o.Mac != nil { +// HasDhcp returns a boolean if a field has been set. +func (o *NicProperties) HasDhcp() bool { + if o != nil && o.Dhcp != nil { return true } return false } -// GetIps returns the Ips field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *NicProperties) GetIps() *[]string { +// GetFirewallActive returns the FirewallActive field value +// If the value is explicit nil, nil is returned +func (o *NicProperties) GetFirewallActive() *bool { if o == nil { return nil } - return o.Ips + return o.FirewallActive } -// GetIpsOk returns a tuple with the Ips field value +// GetFirewallActiveOk returns a tuple with the FirewallActive field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NicProperties) GetIpsOk() (*[]string, bool) { +func (o *NicProperties) GetFirewallActiveOk() (*bool, bool) { if o == nil { return nil, false } - return o.Ips, true + return o.FirewallActive, true } -// SetIps sets field value -func (o *NicProperties) SetIps(v []string) { +// SetFirewallActive sets field value +func (o *NicProperties) SetFirewallActive(v bool) { - o.Ips = &v + o.FirewallActive = &v } -// HasIps returns a boolean if a field has been set. -func (o *NicProperties) HasIps() bool { - if o != nil && o.Ips != nil { +// HasFirewallActive returns a boolean if a field has been set. +func (o *NicProperties) HasFirewallActive() bool { + if o != nil && o.FirewallActive != nil { return true } return false } -// GetDhcp returns the Dhcp field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *NicProperties) GetDhcp() *bool { +// GetFirewallType returns the FirewallType field value +// If the value is explicit nil, nil is returned +func (o *NicProperties) GetFirewallType() *string { if o == nil { return nil } - return o.Dhcp + return o.FirewallType } -// GetDhcpOk returns a tuple with the Dhcp field value +// GetFirewallTypeOk returns a tuple with the FirewallType field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NicProperties) GetDhcpOk() (*bool, bool) { +func (o *NicProperties) GetFirewallTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Dhcp, true + return o.FirewallType, true } -// SetDhcp sets field value -func (o *NicProperties) SetDhcp(v bool) { +// SetFirewallType sets field value +func (o *NicProperties) SetFirewallType(v string) { - o.Dhcp = &v + o.FirewallType = &v } -// HasDhcp returns a boolean if a field has been set. -func (o *NicProperties) HasDhcp() bool { - if o != nil && o.Dhcp != nil { +// HasFirewallType returns a boolean if a field has been set. +func (o *NicProperties) HasFirewallType() bool { + if o != nil && o.FirewallType != nil { return true } return false } -// GetLan returns the Lan field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *NicProperties) GetLan() *int32 { +// GetIps returns the Ips field value +// If the value is explicit nil, nil is returned +func (o *NicProperties) GetIps() *[]string { if o == nil { return nil } - return o.Lan + return o.Ips } -// GetLanOk returns a tuple with the Lan field value +// GetIpsOk returns a tuple with the Ips field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NicProperties) GetLanOk() (*int32, bool) { +func (o *NicProperties) GetIpsOk() (*[]string, bool) { if o == nil { return nil, false } - return o.Lan, true + return o.Ips, true } -// SetLan sets field value -func (o *NicProperties) SetLan(v int32) { +// SetIps sets field value +func (o *NicProperties) SetIps(v []string) { - o.Lan = &v + o.Ips = &v } -// HasLan returns a boolean if a field has been set. -func (o *NicProperties) HasLan() bool { - if o != nil && o.Lan != nil { +// HasIps returns a boolean if a field has been set. +func (o *NicProperties) HasIps() bool { + if o != nil && o.Ips != nil { return true } return false } -// GetFirewallActive returns the FirewallActive field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *NicProperties) GetFirewallActive() *bool { +// GetLan returns the Lan field value +// If the value is explicit nil, nil is returned +func (o *NicProperties) GetLan() *int32 { if o == nil { return nil } - return o.FirewallActive + return o.Lan } -// GetFirewallActiveOk returns a tuple with the FirewallActive field value +// GetLanOk returns a tuple with the Lan field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NicProperties) GetFirewallActiveOk() (*bool, bool) { +func (o *NicProperties) GetLanOk() (*int32, bool) { if o == nil { return nil, false } - return o.FirewallActive, true + return o.Lan, true } -// SetFirewallActive sets field value -func (o *NicProperties) SetFirewallActive(v bool) { +// SetLan sets field value +func (o *NicProperties) SetLan(v int32) { - o.FirewallActive = &v + o.Lan = &v } -// HasFirewallActive returns a boolean if a field has been set. -func (o *NicProperties) HasFirewallActive() bool { - if o != nil && o.FirewallActive != nil { +// HasLan returns a boolean if a field has been set. +func (o *NicProperties) HasLan() bool { + if o != nil && o.Lan != nil { return true } return false } -// GetFirewallType returns the FirewallType field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NicProperties) GetFirewallType() *string { +// GetMac returns the Mac field value +// If the value is explicit nil, nil is returned +func (o *NicProperties) GetMac() *string { if o == nil { return nil } - return o.FirewallType + return o.Mac } -// GetFirewallTypeOk returns a tuple with the FirewallType field value +// GetMacOk returns a tuple with the Mac field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NicProperties) GetFirewallTypeOk() (*string, bool) { +func (o *NicProperties) GetMacOk() (*string, bool) { if o == nil { return nil, false } - return o.FirewallType, true + return o.Mac, true } -// SetFirewallType sets field value -func (o *NicProperties) SetFirewallType(v string) { +// SetMac sets field value +func (o *NicProperties) SetMac(v string) { - o.FirewallType = &v + o.Mac = &v } -// HasFirewallType returns a boolean if a field has been set. -func (o *NicProperties) HasFirewallType() bool { - if o != nil && o.FirewallType != nil { +// HasMac returns a boolean if a field has been set. +func (o *NicProperties) HasMac() bool { + if o != nil && o.Mac != nil { return true } return false } -// GetDeviceNumber returns the DeviceNumber field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *NicProperties) GetDeviceNumber() *int32 { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *NicProperties) GetName() *string { if o == nil { return nil } - return o.DeviceNumber + return o.Name } -// GetDeviceNumberOk returns a tuple with the DeviceNumber field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NicProperties) GetDeviceNumberOk() (*int32, bool) { +func (o *NicProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.DeviceNumber, true + return o.Name, true } -// SetDeviceNumber sets field value -func (o *NicProperties) SetDeviceNumber(v int32) { +// SetName sets field value +func (o *NicProperties) SetName(v string) { - o.DeviceNumber = &v + o.Name = &v } -// HasDeviceNumber returns a boolean if a field has been set. -func (o *NicProperties) HasDeviceNumber() bool { - if o != nil && o.DeviceNumber != nil { +// HasName returns a boolean if a field has been set. +func (o *NicProperties) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -365,7 +368,7 @@ func (o *NicProperties) HasDeviceNumber() bool { } // GetPciSlot returns the PciSlot field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *NicProperties) GetPciSlot() *int32 { if o == nil { return nil @@ -402,33 +405,85 @@ func (o *NicProperties) HasPciSlot() bool { return false } +// GetVnet returns the Vnet field value +// If the value is explicit nil, nil is returned +func (o *NicProperties) GetVnet() *string { + if o == nil { + return nil + } + + return o.Vnet + +} + +// GetVnetOk returns a tuple with the Vnet field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *NicProperties) GetVnetOk() (*string, bool) { + if o == nil { + return nil, false + } + + return o.Vnet, true +} + +// SetVnet sets field value +func (o *NicProperties) SetVnet(v string) { + + o.Vnet = &v + +} + +// HasVnet returns a boolean if a field has been set. +func (o *NicProperties) HasVnet() bool { + if o != nil && o.Vnet != nil { + return true + } + + return false +} + func (o NicProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name - } - if o.Mac != nil { - toSerialize["mac"] = o.Mac + if o.DeviceNumber != nil { + toSerialize["deviceNumber"] = o.DeviceNumber } - toSerialize["ips"] = o.Ips + if o.Dhcp != nil { toSerialize["dhcp"] = o.Dhcp } - if o.Lan != nil { - toSerialize["lan"] = o.Lan - } + if o.FirewallActive != nil { toSerialize["firewallActive"] = o.FirewallActive } + if o.FirewallType != nil { toSerialize["firewallType"] = o.FirewallType } - if o.DeviceNumber != nil { - toSerialize["deviceNumber"] = o.DeviceNumber + + if o.Ips != nil { + toSerialize["ips"] = o.Ips + } + if o.Lan != nil { + toSerialize["lan"] = o.Lan + } + + if o.Mac != nil { + toSerialize["mac"] = o.Mac } + + if o.Name != nil { + toSerialize["name"] = o.Name + } + if o.PciSlot != nil { toSerialize["pciSlot"] = o.PciSlot } + + if o.Vnet != nil { + toSerialize["vnet"] = o.Vnet + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic_put.go index e37c81075e9..0029a6eab01 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nic_put.go @@ -16,13 +16,13 @@ import ( // NicPut struct for NicPut type NicPut struct { + // URL to the object representation (absolute path). + Href *string `json:"href,omitempty"` // The resource's unique identifier. - Id *string `json:"id,omitempty"` + Id *string `json:"id,omitempty"` + Properties *NicProperties `json:"properties"` // The type of object that has been created. Type *Type `json:"type,omitempty"` - // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` - Properties *NicProperties `json:"properties"` } // NewNicPut instantiates a new NicPut object @@ -45,152 +45,152 @@ func NewNicPutWithDefaults() *NicPut { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NicPut) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *NicPut) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NicPut) GetIdOk() (*string, bool) { +func (o *NicPut) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *NicPut) SetId(v string) { +// SetHref sets field value +func (o *NicPut) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *NicPut) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *NicPut) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *NicPut) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *NicPut) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NicPut) GetTypeOk() (*Type, bool) { +func (o *NicPut) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *NicPut) SetType(v Type) { +// SetId sets field value +func (o *NicPut) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *NicPut) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *NicPut) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NicPut) GetHref() *string { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *NicPut) GetProperties() *NicProperties { if o == nil { return nil } - return o.Href + return o.Properties } -// GetHrefOk returns a tuple with the Href field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NicPut) GetHrefOk() (*string, bool) { +func (o *NicPut) GetPropertiesOk() (*NicProperties, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Properties, true } -// SetHref sets field value -func (o *NicPut) SetHref(v string) { +// SetProperties sets field value +func (o *NicPut) SetProperties(v NicProperties) { - o.Href = &v + o.Properties = &v } -// HasHref returns a boolean if a field has been set. -func (o *NicPut) HasHref() bool { - if o != nil && o.Href != nil { +// HasProperties returns a boolean if a field has been set. +func (o *NicPut) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for NicProperties will be returned -func (o *NicPut) GetProperties() *NicProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *NicPut) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NicPut) GetPropertiesOk() (*NicProperties, bool) { +func (o *NicPut) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *NicPut) SetProperties(v NicProperties) { +// SetType sets field value +func (o *NicPut) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *NicPut) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *NicPut) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -199,18 +199,22 @@ func (o *NicPut) HasProperties() bool { func (o NicPut) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nics.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nics.go index 80ff9957fbb..6fe1220a488 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_nics.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_nics.go @@ -16,19 +16,19 @@ import ( // Nics struct for Nics type Nics struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Nic `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewNics instantiates a new Nics object @@ -49,114 +49,114 @@ func NewNicsWithDefaults() *Nics { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Nics) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *Nics) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Nics) GetIdOk() (*string, bool) { +func (o *Nics) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *Nics) SetId(v string) { +// SetLinks sets field value +func (o *Nics) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *Nics) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *Nics) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Nics) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Nics) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Nics) GetTypeOk() (*Type, bool) { +func (o *Nics) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Nics) SetType(v Type) { +// SetHref sets field value +func (o *Nics) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Nics) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Nics) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Nics) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Nics) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Nics) GetHrefOk() (*string, bool) { +func (o *Nics) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Nics) SetHref(v string) { +// SetId sets field value +func (o *Nics) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Nics) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Nics) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *Nics) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Nic will be returned +// If the value is explicit nil, nil is returned func (o *Nics) GetItems() *[]Nic { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *Nics) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Nics) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *Nics) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Nics) GetOffsetOk() (*float32, bool) { +func (o *Nics) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *Nics) SetOffset(v float32) { +// SetLimit sets field value +func (o *Nics) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *Nics) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *Nics) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Nics) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *Nics) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Nics) GetLimitOk() (*float32, bool) { +func (o *Nics) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *Nics) SetLimit(v float32) { +// SetOffset sets field value +func (o *Nics) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *Nics) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *Nics) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *Nics) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Nics) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Nics) GetLinksOk() (*PaginationLinks, bool) { +func (o *Nics) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *Nics) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *Nics) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *Nics) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *Nics) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *Nics) HasLinks() bool { func (o Nics) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_no_state_meta_data.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_no_state_meta_data.go index 4d1488a1de2..bf6d643dd42 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_no_state_meta_data.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_no_state_meta_data.go @@ -17,20 +17,20 @@ import ( // NoStateMetaData struct for NoStateMetaData type NoStateMetaData struct { - // Resource's Entity Tag as defined in http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11 Entity Tag is also added as an 'ETag response header to requests which don't use 'depth' parameter. - Etag *string `json:"etag,omitempty"` - // The time when the resource was created. - CreatedDate *IonosTime // The user who has created the resource. CreatedBy *string `json:"createdBy,omitempty"` // The unique ID of the user who created the resource. CreatedByUserId *string `json:"createdByUserId,omitempty"` - // The last time the resource was modified. - LastModifiedDate *IonosTime + // The time when the resource was created. + CreatedDate *IonosTime + // Resource's Entity Tag as defined in http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11 Entity Tag is also added as an 'ETag response header to requests which don't use 'depth' parameter. + Etag *string `json:"etag,omitempty"` // The user who last modified the resource. LastModifiedBy *string `json:"lastModifiedBy,omitempty"` // The unique ID of the user who last modified the resource. LastModifiedByUserId *string `json:"lastModifiedByUserId,omitempty"` + // The last time the resource was modified. + LastModifiedDate *IonosTime } // NewNoStateMetaData instantiates a new NoStateMetaData object @@ -51,91 +51,8 @@ func NewNoStateMetaDataWithDefaults() *NoStateMetaData { return &this } -// GetEtag returns the Etag field value -// If the value is explicit nil, the zero value for string will be returned -func (o *NoStateMetaData) GetEtag() *string { - if o == nil { - return nil - } - - return o.Etag - -} - -// GetEtagOk returns a tuple with the Etag field value -// and a boolean to check if the value has been set. -// NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NoStateMetaData) GetEtagOk() (*string, bool) { - if o == nil { - return nil, false - } - - return o.Etag, true -} - -// SetEtag sets field value -func (o *NoStateMetaData) SetEtag(v string) { - - o.Etag = &v - -} - -// HasEtag returns a boolean if a field has been set. -func (o *NoStateMetaData) HasEtag() bool { - if o != nil && o.Etag != nil { - return true - } - - return false -} - -// GetCreatedDate returns the CreatedDate field value -// If the value is explicit nil, the zero value for time.Time will be returned -func (o *NoStateMetaData) GetCreatedDate() *time.Time { - if o == nil { - return nil - } - - if o.CreatedDate == nil { - return nil - } - return &o.CreatedDate.Time - -} - -// GetCreatedDateOk returns a tuple with the CreatedDate field value -// and a boolean to check if the value has been set. -// NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NoStateMetaData) GetCreatedDateOk() (*time.Time, bool) { - if o == nil { - return nil, false - } - - if o.CreatedDate == nil { - return nil, false - } - return &o.CreatedDate.Time, true - -} - -// SetCreatedDate sets field value -func (o *NoStateMetaData) SetCreatedDate(v time.Time) { - - o.CreatedDate = &IonosTime{v} - -} - -// HasCreatedDate returns a boolean if a field has been set. -func (o *NoStateMetaData) HasCreatedDate() bool { - if o != nil && o.CreatedDate != nil { - return true - } - - return false -} - // GetCreatedBy returns the CreatedBy field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *NoStateMetaData) GetCreatedBy() *string { if o == nil { return nil @@ -173,7 +90,7 @@ func (o *NoStateMetaData) HasCreatedBy() bool { } // GetCreatedByUserId returns the CreatedByUserId field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *NoStateMetaData) GetCreatedByUserId() *string { if o == nil { return nil @@ -210,45 +127,83 @@ func (o *NoStateMetaData) HasCreatedByUserId() bool { return false } -// GetLastModifiedDate returns the LastModifiedDate field value -// If the value is explicit nil, the zero value for time.Time will be returned -func (o *NoStateMetaData) GetLastModifiedDate() *time.Time { +// GetCreatedDate returns the CreatedDate field value +// If the value is explicit nil, nil is returned +func (o *NoStateMetaData) GetCreatedDate() *time.Time { if o == nil { return nil } - if o.LastModifiedDate == nil { + if o.CreatedDate == nil { return nil } - return &o.LastModifiedDate.Time + return &o.CreatedDate.Time } -// GetLastModifiedDateOk returns a tuple with the LastModifiedDate field value +// GetCreatedDateOk returns a tuple with the CreatedDate field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *NoStateMetaData) GetLastModifiedDateOk() (*time.Time, bool) { +func (o *NoStateMetaData) GetCreatedDateOk() (*time.Time, bool) { if o == nil { return nil, false } - if o.LastModifiedDate == nil { + if o.CreatedDate == nil { return nil, false } - return &o.LastModifiedDate.Time, true + return &o.CreatedDate.Time, true } -// SetLastModifiedDate sets field value -func (o *NoStateMetaData) SetLastModifiedDate(v time.Time) { +// SetCreatedDate sets field value +func (o *NoStateMetaData) SetCreatedDate(v time.Time) { - o.LastModifiedDate = &IonosTime{v} + o.CreatedDate = &IonosTime{v} } -// HasLastModifiedDate returns a boolean if a field has been set. -func (o *NoStateMetaData) HasLastModifiedDate() bool { - if o != nil && o.LastModifiedDate != nil { +// HasCreatedDate returns a boolean if a field has been set. +func (o *NoStateMetaData) HasCreatedDate() bool { + if o != nil && o.CreatedDate != nil { + return true + } + + return false +} + +// GetEtag returns the Etag field value +// If the value is explicit nil, nil is returned +func (o *NoStateMetaData) GetEtag() *string { + if o == nil { + return nil + } + + return o.Etag + +} + +// GetEtagOk returns a tuple with the Etag field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *NoStateMetaData) GetEtagOk() (*string, bool) { + if o == nil { + return nil, false + } + + return o.Etag, true +} + +// SetEtag sets field value +func (o *NoStateMetaData) SetEtag(v string) { + + o.Etag = &v + +} + +// HasEtag returns a boolean if a field has been set. +func (o *NoStateMetaData) HasEtag() bool { + if o != nil && o.Etag != nil { return true } @@ -256,7 +211,7 @@ func (o *NoStateMetaData) HasLastModifiedDate() bool { } // GetLastModifiedBy returns the LastModifiedBy field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *NoStateMetaData) GetLastModifiedBy() *string { if o == nil { return nil @@ -294,7 +249,7 @@ func (o *NoStateMetaData) HasLastModifiedBy() bool { } // GetLastModifiedByUserId returns the LastModifiedByUserId field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *NoStateMetaData) GetLastModifiedByUserId() *string { if o == nil { return nil @@ -331,29 +286,81 @@ func (o *NoStateMetaData) HasLastModifiedByUserId() bool { return false } -func (o NoStateMetaData) MarshalJSON() ([]byte, error) { - toSerialize := map[string]interface{}{} - if o.Etag != nil { - toSerialize["etag"] = o.Etag +// GetLastModifiedDate returns the LastModifiedDate field value +// If the value is explicit nil, nil is returned +func (o *NoStateMetaData) GetLastModifiedDate() *time.Time { + if o == nil { + return nil } - if o.CreatedDate != nil { - toSerialize["createdDate"] = o.CreatedDate + + if o.LastModifiedDate == nil { + return nil + } + return &o.LastModifiedDate.Time + +} + +// GetLastModifiedDateOk returns a tuple with the LastModifiedDate field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *NoStateMetaData) GetLastModifiedDateOk() (*time.Time, bool) { + if o == nil { + return nil, false + } + + if o.LastModifiedDate == nil { + return nil, false + } + return &o.LastModifiedDate.Time, true + +} + +// SetLastModifiedDate sets field value +func (o *NoStateMetaData) SetLastModifiedDate(v time.Time) { + + o.LastModifiedDate = &IonosTime{v} + +} + +// HasLastModifiedDate returns a boolean if a field has been set. +func (o *NoStateMetaData) HasLastModifiedDate() bool { + if o != nil && o.LastModifiedDate != nil { + return true } + + return false +} + +func (o NoStateMetaData) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} if o.CreatedBy != nil { toSerialize["createdBy"] = o.CreatedBy } + if o.CreatedByUserId != nil { toSerialize["createdByUserId"] = o.CreatedByUserId } - if o.LastModifiedDate != nil { - toSerialize["lastModifiedDate"] = o.LastModifiedDate + + if o.CreatedDate != nil { + toSerialize["createdDate"] = o.CreatedDate + } + + if o.Etag != nil { + toSerialize["etag"] = o.Etag } + if o.LastModifiedBy != nil { toSerialize["lastModifiedBy"] = o.LastModifiedBy } + if o.LastModifiedByUserId != nil { toSerialize["lastModifiedByUserId"] = o.LastModifiedByUserId } + + if o.LastModifiedDate != nil { + toSerialize["lastModifiedDate"] = o.LastModifiedDate + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_pagination_links.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_pagination_links.go index fa3c76dee8d..5b8bef3043f 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_pagination_links.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_pagination_links.go @@ -16,12 +16,12 @@ import ( // PaginationLinks struct for PaginationLinks type PaginationLinks struct { + // URL (with offset and limit parameters) of the next page; only present if offset + limit is less than the total number of elements. + Next *string `json:"next,omitempty"` // URL (with offset and limit parameters) of the previous page; only present if offset is greater than 0. Prev *string `json:"prev,omitempty"` // URL (with offset and limit parameters) of the current page. Self *string `json:"self,omitempty"` - // URL (with offset and limit parameters) of the next page; only present if offset + limit is less than the total number of elements. - Next *string `json:"next,omitempty"` } // NewPaginationLinks instantiates a new PaginationLinks object @@ -42,114 +42,114 @@ func NewPaginationLinksWithDefaults() *PaginationLinks { return &this } -// GetPrev returns the Prev field value -// If the value is explicit nil, the zero value for string will be returned -func (o *PaginationLinks) GetPrev() *string { +// GetNext returns the Next field value +// If the value is explicit nil, nil is returned +func (o *PaginationLinks) GetNext() *string { if o == nil { return nil } - return o.Prev + return o.Next } -// GetPrevOk returns a tuple with the Prev field value +// GetNextOk returns a tuple with the Next field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PaginationLinks) GetPrevOk() (*string, bool) { +func (o *PaginationLinks) GetNextOk() (*string, bool) { if o == nil { return nil, false } - return o.Prev, true + return o.Next, true } -// SetPrev sets field value -func (o *PaginationLinks) SetPrev(v string) { +// SetNext sets field value +func (o *PaginationLinks) SetNext(v string) { - o.Prev = &v + o.Next = &v } -// HasPrev returns a boolean if a field has been set. -func (o *PaginationLinks) HasPrev() bool { - if o != nil && o.Prev != nil { +// HasNext returns a boolean if a field has been set. +func (o *PaginationLinks) HasNext() bool { + if o != nil && o.Next != nil { return true } return false } -// GetSelf returns the Self field value -// If the value is explicit nil, the zero value for string will be returned -func (o *PaginationLinks) GetSelf() *string { +// GetPrev returns the Prev field value +// If the value is explicit nil, nil is returned +func (o *PaginationLinks) GetPrev() *string { if o == nil { return nil } - return o.Self + return o.Prev } -// GetSelfOk returns a tuple with the Self field value +// GetPrevOk returns a tuple with the Prev field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PaginationLinks) GetSelfOk() (*string, bool) { +func (o *PaginationLinks) GetPrevOk() (*string, bool) { if o == nil { return nil, false } - return o.Self, true + return o.Prev, true } -// SetSelf sets field value -func (o *PaginationLinks) SetSelf(v string) { +// SetPrev sets field value +func (o *PaginationLinks) SetPrev(v string) { - o.Self = &v + o.Prev = &v } -// HasSelf returns a boolean if a field has been set. -func (o *PaginationLinks) HasSelf() bool { - if o != nil && o.Self != nil { +// HasPrev returns a boolean if a field has been set. +func (o *PaginationLinks) HasPrev() bool { + if o != nil && o.Prev != nil { return true } return false } -// GetNext returns the Next field value -// If the value is explicit nil, the zero value for string will be returned -func (o *PaginationLinks) GetNext() *string { +// GetSelf returns the Self field value +// If the value is explicit nil, nil is returned +func (o *PaginationLinks) GetSelf() *string { if o == nil { return nil } - return o.Next + return o.Self } -// GetNextOk returns a tuple with the Next field value +// GetSelfOk returns a tuple with the Self field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PaginationLinks) GetNextOk() (*string, bool) { +func (o *PaginationLinks) GetSelfOk() (*string, bool) { if o == nil { return nil, false } - return o.Next, true + return o.Self, true } -// SetNext sets field value -func (o *PaginationLinks) SetNext(v string) { +// SetSelf sets field value +func (o *PaginationLinks) SetSelf(v string) { - o.Next = &v + o.Self = &v } -// HasNext returns a boolean if a field has been set. -func (o *PaginationLinks) HasNext() bool { - if o != nil && o.Next != nil { +// HasSelf returns a boolean if a field has been set. +func (o *PaginationLinks) HasSelf() bool { + if o != nil && o.Self != nil { return true } @@ -158,15 +158,18 @@ func (o *PaginationLinks) HasNext() bool { func (o PaginationLinks) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} + if o.Next != nil { + toSerialize["next"] = o.Next + } + if o.Prev != nil { toSerialize["prev"] = o.Prev } + if o.Self != nil { toSerialize["self"] = o.Self } - if o.Next != nil { - toSerialize["next"] = o.Next - } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_peer.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_peer.go index db7c562be66..582ff98a946 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_peer.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_peer.go @@ -16,11 +16,11 @@ import ( // Peer struct for Peer type Peer struct { - Id *string `json:"id,omitempty"` - Name *string `json:"name,omitempty"` DatacenterId *string `json:"datacenterId,omitempty"` DatacenterName *string `json:"datacenterName,omitempty"` + Id *string `json:"id,omitempty"` Location *string `json:"location,omitempty"` + Name *string `json:"name,omitempty"` } // NewPeer instantiates a new Peer object @@ -41,190 +41,190 @@ func NewPeerWithDefaults() *Peer { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Peer) GetId() *string { +// GetDatacenterId returns the DatacenterId field value +// If the value is explicit nil, nil is returned +func (o *Peer) GetDatacenterId() *string { if o == nil { return nil } - return o.Id + return o.DatacenterId } -// GetIdOk returns a tuple with the Id field value +// GetDatacenterIdOk returns a tuple with the DatacenterId field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Peer) GetIdOk() (*string, bool) { +func (o *Peer) GetDatacenterIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.DatacenterId, true } -// SetId sets field value -func (o *Peer) SetId(v string) { +// SetDatacenterId sets field value +func (o *Peer) SetDatacenterId(v string) { - o.Id = &v + o.DatacenterId = &v } -// HasId returns a boolean if a field has been set. -func (o *Peer) HasId() bool { - if o != nil && o.Id != nil { +// HasDatacenterId returns a boolean if a field has been set. +func (o *Peer) HasDatacenterId() bool { + if o != nil && o.DatacenterId != nil { return true } return false } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Peer) GetName() *string { +// GetDatacenterName returns the DatacenterName field value +// If the value is explicit nil, nil is returned +func (o *Peer) GetDatacenterName() *string { if o == nil { return nil } - return o.Name + return o.DatacenterName } -// GetNameOk returns a tuple with the Name field value +// GetDatacenterNameOk returns a tuple with the DatacenterName field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Peer) GetNameOk() (*string, bool) { +func (o *Peer) GetDatacenterNameOk() (*string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.DatacenterName, true } -// SetName sets field value -func (o *Peer) SetName(v string) { +// SetDatacenterName sets field value +func (o *Peer) SetDatacenterName(v string) { - o.Name = &v + o.DatacenterName = &v } -// HasName returns a boolean if a field has been set. -func (o *Peer) HasName() bool { - if o != nil && o.Name != nil { +// HasDatacenterName returns a boolean if a field has been set. +func (o *Peer) HasDatacenterName() bool { + if o != nil && o.DatacenterName != nil { return true } return false } -// GetDatacenterId returns the DatacenterId field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Peer) GetDatacenterId() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Peer) GetId() *string { if o == nil { return nil } - return o.DatacenterId + return o.Id } -// GetDatacenterIdOk returns a tuple with the DatacenterId field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Peer) GetDatacenterIdOk() (*string, bool) { +func (o *Peer) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.DatacenterId, true + return o.Id, true } -// SetDatacenterId sets field value -func (o *Peer) SetDatacenterId(v string) { +// SetId sets field value +func (o *Peer) SetId(v string) { - o.DatacenterId = &v + o.Id = &v } -// HasDatacenterId returns a boolean if a field has been set. -func (o *Peer) HasDatacenterId() bool { - if o != nil && o.DatacenterId != nil { +// HasId returns a boolean if a field has been set. +func (o *Peer) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetDatacenterName returns the DatacenterName field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Peer) GetDatacenterName() *string { +// GetLocation returns the Location field value +// If the value is explicit nil, nil is returned +func (o *Peer) GetLocation() *string { if o == nil { return nil } - return o.DatacenterName + return o.Location } -// GetDatacenterNameOk returns a tuple with the DatacenterName field value +// GetLocationOk returns a tuple with the Location field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Peer) GetDatacenterNameOk() (*string, bool) { +func (o *Peer) GetLocationOk() (*string, bool) { if o == nil { return nil, false } - return o.DatacenterName, true + return o.Location, true } -// SetDatacenterName sets field value -func (o *Peer) SetDatacenterName(v string) { +// SetLocation sets field value +func (o *Peer) SetLocation(v string) { - o.DatacenterName = &v + o.Location = &v } -// HasDatacenterName returns a boolean if a field has been set. -func (o *Peer) HasDatacenterName() bool { - if o != nil && o.DatacenterName != nil { +// HasLocation returns a boolean if a field has been set. +func (o *Peer) HasLocation() bool { + if o != nil && o.Location != nil { return true } return false } -// GetLocation returns the Location field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Peer) GetLocation() *string { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *Peer) GetName() *string { if o == nil { return nil } - return o.Location + return o.Name } -// GetLocationOk returns a tuple with the Location field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Peer) GetLocationOk() (*string, bool) { +func (o *Peer) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.Location, true + return o.Name, true } -// SetLocation sets field value -func (o *Peer) SetLocation(v string) { +// SetName sets field value +func (o *Peer) SetName(v string) { - o.Location = &v + o.Name = &v } -// HasLocation returns a boolean if a field has been set. -func (o *Peer) HasLocation() bool { - if o != nil && o.Location != nil { +// HasName returns a boolean if a field has been set. +func (o *Peer) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -233,21 +233,26 @@ func (o *Peer) HasLocation() bool { func (o Peer) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Name != nil { - toSerialize["name"] = o.Name - } if o.DatacenterId != nil { toSerialize["datacenterId"] = o.DatacenterId } + if o.DatacenterName != nil { toSerialize["datacenterName"] = o.DatacenterName } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Location != nil { toSerialize["location"] = o.Location } + + if o.Name != nil { + toSerialize["name"] = o.Name + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_private_cross_connect.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_private_cross_connect.go index f0aa7eb8f50..1a417e85c5e 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_private_cross_connect.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_private_cross_connect.go @@ -16,14 +16,14 @@ import ( // PrivateCrossConnect struct for PrivateCrossConnect type PrivateCrossConnect struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *PrivateCrossConnectProperties `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewPrivateCrossConnect instantiates a new PrivateCrossConnect object @@ -46,190 +46,190 @@ func NewPrivateCrossConnectWithDefaults() *PrivateCrossConnect { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *PrivateCrossConnect) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *PrivateCrossConnect) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PrivateCrossConnect) GetIdOk() (*string, bool) { +func (o *PrivateCrossConnect) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *PrivateCrossConnect) SetId(v string) { +// SetHref sets field value +func (o *PrivateCrossConnect) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *PrivateCrossConnect) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *PrivateCrossConnect) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *PrivateCrossConnect) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *PrivateCrossConnect) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PrivateCrossConnect) GetTypeOk() (*Type, bool) { +func (o *PrivateCrossConnect) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *PrivateCrossConnect) SetType(v Type) { +// SetId sets field value +func (o *PrivateCrossConnect) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *PrivateCrossConnect) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *PrivateCrossConnect) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *PrivateCrossConnect) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *PrivateCrossConnect) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PrivateCrossConnect) GetHrefOk() (*string, bool) { +func (o *PrivateCrossConnect) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *PrivateCrossConnect) SetHref(v string) { +// SetMetadata sets field value +func (o *PrivateCrossConnect) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *PrivateCrossConnect) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *PrivateCrossConnect) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *PrivateCrossConnect) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *PrivateCrossConnect) GetProperties() *PrivateCrossConnectProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PrivateCrossConnect) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *PrivateCrossConnect) GetPropertiesOk() (*PrivateCrossConnectProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *PrivateCrossConnect) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *PrivateCrossConnect) SetProperties(v PrivateCrossConnectProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *PrivateCrossConnect) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *PrivateCrossConnect) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for PrivateCrossConnectProperties will be returned -func (o *PrivateCrossConnect) GetProperties() *PrivateCrossConnectProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *PrivateCrossConnect) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PrivateCrossConnect) GetPropertiesOk() (*PrivateCrossConnectProperties, bool) { +func (o *PrivateCrossConnect) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *PrivateCrossConnect) SetProperties(v PrivateCrossConnectProperties) { +// SetType sets field value +func (o *PrivateCrossConnect) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *PrivateCrossConnect) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *PrivateCrossConnect) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *PrivateCrossConnect) HasProperties() bool { func (o PrivateCrossConnect) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_private_cross_connect_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_private_cross_connect_properties.go index a92dc80982e..864e5ada1ea 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_private_cross_connect_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_private_cross_connect_properties.go @@ -16,14 +16,14 @@ import ( // PrivateCrossConnectProperties struct for PrivateCrossConnectProperties type PrivateCrossConnectProperties struct { - // The name of the resource. - Name *string `json:"name,omitempty"` + // Read-Only attribute. Lists data centers that can be joined to this private Cross-Connect. + ConnectableDatacenters *[]ConnectableDatacenter `json:"connectableDatacenters,omitempty"` // Human-readable description. Description *string `json:"description,omitempty"` + // The name of the resource. + Name *string `json:"name,omitempty"` // Read-Only attribute. Lists LAN's joined to this private Cross-Connect. Peers *[]Peer `json:"peers,omitempty"` - // Read-Only attribute. Lists data centers that can be joined to this private Cross-Connect. - ConnectableDatacenters *[]ConnectableDatacenter `json:"connectableDatacenters,omitempty"` } // NewPrivateCrossConnectProperties instantiates a new PrivateCrossConnectProperties object @@ -44,38 +44,38 @@ func NewPrivateCrossConnectPropertiesWithDefaults() *PrivateCrossConnectProperti return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *PrivateCrossConnectProperties) GetName() *string { +// GetConnectableDatacenters returns the ConnectableDatacenters field value +// If the value is explicit nil, nil is returned +func (o *PrivateCrossConnectProperties) GetConnectableDatacenters() *[]ConnectableDatacenter { if o == nil { return nil } - return o.Name + return o.ConnectableDatacenters } -// GetNameOk returns a tuple with the Name field value +// GetConnectableDatacentersOk returns a tuple with the ConnectableDatacenters field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PrivateCrossConnectProperties) GetNameOk() (*string, bool) { +func (o *PrivateCrossConnectProperties) GetConnectableDatacentersOk() (*[]ConnectableDatacenter, bool) { if o == nil { return nil, false } - return o.Name, true + return o.ConnectableDatacenters, true } -// SetName sets field value -func (o *PrivateCrossConnectProperties) SetName(v string) { +// SetConnectableDatacenters sets field value +func (o *PrivateCrossConnectProperties) SetConnectableDatacenters(v []ConnectableDatacenter) { - o.Name = &v + o.ConnectableDatacenters = &v } -// HasName returns a boolean if a field has been set. -func (o *PrivateCrossConnectProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasConnectableDatacenters returns a boolean if a field has been set. +func (o *PrivateCrossConnectProperties) HasConnectableDatacenters() bool { + if o != nil && o.ConnectableDatacenters != nil { return true } @@ -83,7 +83,7 @@ func (o *PrivateCrossConnectProperties) HasName() bool { } // GetDescription returns the Description field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *PrivateCrossConnectProperties) GetDescription() *string { if o == nil { return nil @@ -120,76 +120,76 @@ func (o *PrivateCrossConnectProperties) HasDescription() bool { return false } -// GetPeers returns the Peers field value -// If the value is explicit nil, the zero value for []Peer will be returned -func (o *PrivateCrossConnectProperties) GetPeers() *[]Peer { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *PrivateCrossConnectProperties) GetName() *string { if o == nil { return nil } - return o.Peers + return o.Name } -// GetPeersOk returns a tuple with the Peers field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PrivateCrossConnectProperties) GetPeersOk() (*[]Peer, bool) { +func (o *PrivateCrossConnectProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.Peers, true + return o.Name, true } -// SetPeers sets field value -func (o *PrivateCrossConnectProperties) SetPeers(v []Peer) { +// SetName sets field value +func (o *PrivateCrossConnectProperties) SetName(v string) { - o.Peers = &v + o.Name = &v } -// HasPeers returns a boolean if a field has been set. -func (o *PrivateCrossConnectProperties) HasPeers() bool { - if o != nil && o.Peers != nil { +// HasName returns a boolean if a field has been set. +func (o *PrivateCrossConnectProperties) HasName() bool { + if o != nil && o.Name != nil { return true } return false } -// GetConnectableDatacenters returns the ConnectableDatacenters field value -// If the value is explicit nil, the zero value for []ConnectableDatacenter will be returned -func (o *PrivateCrossConnectProperties) GetConnectableDatacenters() *[]ConnectableDatacenter { +// GetPeers returns the Peers field value +// If the value is explicit nil, nil is returned +func (o *PrivateCrossConnectProperties) GetPeers() *[]Peer { if o == nil { return nil } - return o.ConnectableDatacenters + return o.Peers } -// GetConnectableDatacentersOk returns a tuple with the ConnectableDatacenters field value +// GetPeersOk returns a tuple with the Peers field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PrivateCrossConnectProperties) GetConnectableDatacentersOk() (*[]ConnectableDatacenter, bool) { +func (o *PrivateCrossConnectProperties) GetPeersOk() (*[]Peer, bool) { if o == nil { return nil, false } - return o.ConnectableDatacenters, true + return o.Peers, true } -// SetConnectableDatacenters sets field value -func (o *PrivateCrossConnectProperties) SetConnectableDatacenters(v []ConnectableDatacenter) { +// SetPeers sets field value +func (o *PrivateCrossConnectProperties) SetPeers(v []Peer) { - o.ConnectableDatacenters = &v + o.Peers = &v } -// HasConnectableDatacenters returns a boolean if a field has been set. -func (o *PrivateCrossConnectProperties) HasConnectableDatacenters() bool { - if o != nil && o.ConnectableDatacenters != nil { +// HasPeers returns a boolean if a field has been set. +func (o *PrivateCrossConnectProperties) HasPeers() bool { + if o != nil && o.Peers != nil { return true } @@ -198,18 +198,22 @@ func (o *PrivateCrossConnectProperties) HasConnectableDatacenters() bool { func (o PrivateCrossConnectProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name + if o.ConnectableDatacenters != nil { + toSerialize["connectableDatacenters"] = o.ConnectableDatacenters } + if o.Description != nil { toSerialize["description"] = o.Description } + + if o.Name != nil { + toSerialize["name"] = o.Name + } + if o.Peers != nil { toSerialize["peers"] = o.Peers } - if o.ConnectableDatacenters != nil { - toSerialize["connectableDatacenters"] = o.ConnectableDatacenters - } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_private_cross_connects.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_private_cross_connects.go index 7112f9a35aa..3c82ad39f7e 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_private_cross_connects.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_private_cross_connects.go @@ -16,14 +16,14 @@ import ( // PrivateCrossConnects struct for PrivateCrossConnects type PrivateCrossConnects struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]PrivateCrossConnect `json:"items,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewPrivateCrossConnects instantiates a new PrivateCrossConnects object @@ -44,152 +44,152 @@ func NewPrivateCrossConnectsWithDefaults() *PrivateCrossConnects { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *PrivateCrossConnects) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *PrivateCrossConnects) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PrivateCrossConnects) GetIdOk() (*string, bool) { +func (o *PrivateCrossConnects) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *PrivateCrossConnects) SetId(v string) { +// SetHref sets field value +func (o *PrivateCrossConnects) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *PrivateCrossConnects) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *PrivateCrossConnects) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *PrivateCrossConnects) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *PrivateCrossConnects) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PrivateCrossConnects) GetTypeOk() (*Type, bool) { +func (o *PrivateCrossConnects) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *PrivateCrossConnects) SetType(v Type) { +// SetId sets field value +func (o *PrivateCrossConnects) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *PrivateCrossConnects) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *PrivateCrossConnects) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *PrivateCrossConnects) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *PrivateCrossConnects) GetItems() *[]PrivateCrossConnect { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PrivateCrossConnects) GetHrefOk() (*string, bool) { +func (o *PrivateCrossConnects) GetItemsOk() (*[]PrivateCrossConnect, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *PrivateCrossConnects) SetHref(v string) { +// SetItems sets field value +func (o *PrivateCrossConnects) SetItems(v []PrivateCrossConnect) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *PrivateCrossConnects) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *PrivateCrossConnects) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []PrivateCrossConnect will be returned -func (o *PrivateCrossConnects) GetItems() *[]PrivateCrossConnect { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *PrivateCrossConnects) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *PrivateCrossConnects) GetItemsOk() (*[]PrivateCrossConnect, bool) { +func (o *PrivateCrossConnects) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *PrivateCrossConnects) SetItems(v []PrivateCrossConnect) { +// SetType sets field value +func (o *PrivateCrossConnects) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *PrivateCrossConnects) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *PrivateCrossConnects) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *PrivateCrossConnects) HasItems() bool { func (o PrivateCrossConnects) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_remote_console_url.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_remote_console_url.go index 4088c7a8c36..74f96ce383d 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_remote_console_url.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_remote_console_url.go @@ -39,7 +39,7 @@ func NewRemoteConsoleUrlWithDefaults() *RemoteConsoleUrl { } // GetUrl returns the Url field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *RemoteConsoleUrl) GetUrl() *string { if o == nil { return nil @@ -81,6 +81,7 @@ func (o RemoteConsoleUrl) MarshalJSON() ([]byte, error) { if o.Url != nil { toSerialize["url"] = o.Url } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_request.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_request.go index 5ac4f4851d1..adc351ff954 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_request.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_request.go @@ -16,14 +16,14 @@ import ( // Request struct for Request type Request struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *RequestMetadata `json:"metadata,omitempty"` Properties *RequestProperties `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewRequest instantiates a new Request object @@ -46,190 +46,190 @@ func NewRequestWithDefaults() *Request { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Request) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Request) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Request) GetIdOk() (*string, bool) { +func (o *Request) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Request) SetId(v string) { +// SetHref sets field value +func (o *Request) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Request) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Request) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Request) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Request) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Request) GetTypeOk() (*Type, bool) { +func (o *Request) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Request) SetType(v Type) { +// SetId sets field value +func (o *Request) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Request) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Request) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Request) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *Request) GetMetadata() *RequestMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Request) GetHrefOk() (*string, bool) { +func (o *Request) GetMetadataOk() (*RequestMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *Request) SetHref(v string) { +// SetMetadata sets field value +func (o *Request) SetMetadata(v RequestMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *Request) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *Request) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for RequestMetadata will be returned -func (o *Request) GetMetadata() *RequestMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *Request) GetProperties() *RequestProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Request) GetMetadataOk() (*RequestMetadata, bool) { +func (o *Request) GetPropertiesOk() (*RequestProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *Request) SetMetadata(v RequestMetadata) { +// SetProperties sets field value +func (o *Request) SetProperties(v RequestProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *Request) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *Request) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for RequestProperties will be returned -func (o *Request) GetProperties() *RequestProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Request) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Request) GetPropertiesOk() (*RequestProperties, bool) { +func (o *Request) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *Request) SetProperties(v RequestProperties) { +// SetType sets field value +func (o *Request) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *Request) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *Request) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *Request) HasProperties() bool { func (o Request) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_metadata.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_metadata.go index 3ea319b3132..1b634615ec4 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_metadata.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_metadata.go @@ -17,10 +17,10 @@ import ( // RequestMetadata struct for RequestMetadata type RequestMetadata struct { - // The last time the resource was created. - CreatedDate *IonosTime // The user who created the resource. CreatedBy *string `json:"createdBy,omitempty"` + // The last time the resource was created. + CreatedDate *IonosTime // Resource's Entity Tag as defined in http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11 Entity Tag is also added as an 'ETag response header to requests which don't use 'depth' parameter. Etag *string `json:"etag,omitempty"` RequestStatus *RequestStatus `json:"requestStatus,omitempty"` @@ -44,83 +44,83 @@ func NewRequestMetadataWithDefaults() *RequestMetadata { return &this } -// GetCreatedDate returns the CreatedDate field value -// If the value is explicit nil, the zero value for time.Time will be returned -func (o *RequestMetadata) GetCreatedDate() *time.Time { +// GetCreatedBy returns the CreatedBy field value +// If the value is explicit nil, nil is returned +func (o *RequestMetadata) GetCreatedBy() *string { if o == nil { return nil } - if o.CreatedDate == nil { - return nil - } - return &o.CreatedDate.Time + return o.CreatedBy } -// GetCreatedDateOk returns a tuple with the CreatedDate field value +// GetCreatedByOk returns a tuple with the CreatedBy field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *RequestMetadata) GetCreatedDateOk() (*time.Time, bool) { +func (o *RequestMetadata) GetCreatedByOk() (*string, bool) { if o == nil { return nil, false } - if o.CreatedDate == nil { - return nil, false - } - return &o.CreatedDate.Time, true - + return o.CreatedBy, true } -// SetCreatedDate sets field value -func (o *RequestMetadata) SetCreatedDate(v time.Time) { +// SetCreatedBy sets field value +func (o *RequestMetadata) SetCreatedBy(v string) { - o.CreatedDate = &IonosTime{v} + o.CreatedBy = &v } -// HasCreatedDate returns a boolean if a field has been set. -func (o *RequestMetadata) HasCreatedDate() bool { - if o != nil && o.CreatedDate != nil { +// HasCreatedBy returns a boolean if a field has been set. +func (o *RequestMetadata) HasCreatedBy() bool { + if o != nil && o.CreatedBy != nil { return true } return false } -// GetCreatedBy returns the CreatedBy field value -// If the value is explicit nil, the zero value for string will be returned -func (o *RequestMetadata) GetCreatedBy() *string { +// GetCreatedDate returns the CreatedDate field value +// If the value is explicit nil, nil is returned +func (o *RequestMetadata) GetCreatedDate() *time.Time { if o == nil { return nil } - return o.CreatedBy + if o.CreatedDate == nil { + return nil + } + return &o.CreatedDate.Time } -// GetCreatedByOk returns a tuple with the CreatedBy field value +// GetCreatedDateOk returns a tuple with the CreatedDate field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *RequestMetadata) GetCreatedByOk() (*string, bool) { +func (o *RequestMetadata) GetCreatedDateOk() (*time.Time, bool) { if o == nil { return nil, false } - return o.CreatedBy, true + if o.CreatedDate == nil { + return nil, false + } + return &o.CreatedDate.Time, true + } -// SetCreatedBy sets field value -func (o *RequestMetadata) SetCreatedBy(v string) { +// SetCreatedDate sets field value +func (o *RequestMetadata) SetCreatedDate(v time.Time) { - o.CreatedBy = &v + o.CreatedDate = &IonosTime{v} } -// HasCreatedBy returns a boolean if a field has been set. -func (o *RequestMetadata) HasCreatedBy() bool { - if o != nil && o.CreatedBy != nil { +// HasCreatedDate returns a boolean if a field has been set. +func (o *RequestMetadata) HasCreatedDate() bool { + if o != nil && o.CreatedDate != nil { return true } @@ -128,7 +128,7 @@ func (o *RequestMetadata) HasCreatedBy() bool { } // GetEtag returns the Etag field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *RequestMetadata) GetEtag() *string { if o == nil { return nil @@ -166,7 +166,7 @@ func (o *RequestMetadata) HasEtag() bool { } // GetRequestStatus returns the RequestStatus field value -// If the value is explicit nil, the zero value for RequestStatus will be returned +// If the value is explicit nil, nil is returned func (o *RequestMetadata) GetRequestStatus() *RequestStatus { if o == nil { return nil @@ -205,18 +205,22 @@ func (o *RequestMetadata) HasRequestStatus() bool { func (o RequestMetadata) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.CreatedDate != nil { - toSerialize["createdDate"] = o.CreatedDate - } if o.CreatedBy != nil { toSerialize["createdBy"] = o.CreatedBy } + + if o.CreatedDate != nil { + toSerialize["createdDate"] = o.CreatedDate + } + if o.Etag != nil { toSerialize["etag"] = o.Etag } + if o.RequestStatus != nil { toSerialize["requestStatus"] = o.RequestStatus } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_properties.go index 94d04093970..e43b39d983b 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_properties.go @@ -16,9 +16,9 @@ import ( // RequestProperties struct for RequestProperties type RequestProperties struct { - Method *string `json:"method,omitempty"` - Headers *map[string]string `json:"headers,omitempty"` Body *string `json:"body,omitempty"` + Headers *map[string]string `json:"headers,omitempty"` + Method *string `json:"method,omitempty"` Url *string `json:"url,omitempty"` } @@ -40,38 +40,38 @@ func NewRequestPropertiesWithDefaults() *RequestProperties { return &this } -// GetMethod returns the Method field value -// If the value is explicit nil, the zero value for string will be returned -func (o *RequestProperties) GetMethod() *string { +// GetBody returns the Body field value +// If the value is explicit nil, nil is returned +func (o *RequestProperties) GetBody() *string { if o == nil { return nil } - return o.Method + return o.Body } -// GetMethodOk returns a tuple with the Method field value +// GetBodyOk returns a tuple with the Body field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *RequestProperties) GetMethodOk() (*string, bool) { +func (o *RequestProperties) GetBodyOk() (*string, bool) { if o == nil { return nil, false } - return o.Method, true + return o.Body, true } -// SetMethod sets field value -func (o *RequestProperties) SetMethod(v string) { +// SetBody sets field value +func (o *RequestProperties) SetBody(v string) { - o.Method = &v + o.Body = &v } -// HasMethod returns a boolean if a field has been set. -func (o *RequestProperties) HasMethod() bool { - if o != nil && o.Method != nil { +// HasBody returns a boolean if a field has been set. +func (o *RequestProperties) HasBody() bool { + if o != nil && o.Body != nil { return true } @@ -79,7 +79,7 @@ func (o *RequestProperties) HasMethod() bool { } // GetHeaders returns the Headers field value -// If the value is explicit nil, the zero value for map[string]string will be returned +// If the value is explicit nil, nil is returned func (o *RequestProperties) GetHeaders() *map[string]string { if o == nil { return nil @@ -116,38 +116,38 @@ func (o *RequestProperties) HasHeaders() bool { return false } -// GetBody returns the Body field value -// If the value is explicit nil, the zero value for string will be returned -func (o *RequestProperties) GetBody() *string { +// GetMethod returns the Method field value +// If the value is explicit nil, nil is returned +func (o *RequestProperties) GetMethod() *string { if o == nil { return nil } - return o.Body + return o.Method } -// GetBodyOk returns a tuple with the Body field value +// GetMethodOk returns a tuple with the Method field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *RequestProperties) GetBodyOk() (*string, bool) { +func (o *RequestProperties) GetMethodOk() (*string, bool) { if o == nil { return nil, false } - return o.Body, true + return o.Method, true } -// SetBody sets field value -func (o *RequestProperties) SetBody(v string) { +// SetMethod sets field value +func (o *RequestProperties) SetMethod(v string) { - o.Body = &v + o.Method = &v } -// HasBody returns a boolean if a field has been set. -func (o *RequestProperties) HasBody() bool { - if o != nil && o.Body != nil { +// HasMethod returns a boolean if a field has been set. +func (o *RequestProperties) HasMethod() bool { + if o != nil && o.Method != nil { return true } @@ -155,7 +155,7 @@ func (o *RequestProperties) HasBody() bool { } // GetUrl returns the Url field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *RequestProperties) GetUrl() *string { if o == nil { return nil @@ -194,18 +194,22 @@ func (o *RequestProperties) HasUrl() bool { func (o RequestProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Method != nil { - toSerialize["method"] = o.Method + if o.Body != nil { + toSerialize["body"] = o.Body } + if o.Headers != nil { toSerialize["headers"] = o.Headers } - if o.Body != nil { - toSerialize["body"] = o.Body + + if o.Method != nil { + toSerialize["method"] = o.Method } + if o.Url != nil { toSerialize["url"] = o.Url } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_status.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_status.go index e772df8e640..f4ca3ceeffe 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_status.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_status.go @@ -16,13 +16,13 @@ import ( // RequestStatus struct for RequestStatus type RequestStatus struct { + // URL to the object representation (absolute path). + Href *string `json:"href,omitempty"` // The resource's unique identifier. - Id *string `json:"id,omitempty"` + Id *string `json:"id,omitempty"` + Metadata *RequestStatusMetadata `json:"metadata,omitempty"` // The type of object that has been created. Type *Type `json:"type,omitempty"` - // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` - Metadata *RequestStatusMetadata `json:"metadata,omitempty"` } // NewRequestStatus instantiates a new RequestStatus object @@ -43,152 +43,152 @@ func NewRequestStatusWithDefaults() *RequestStatus { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *RequestStatus) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *RequestStatus) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *RequestStatus) GetIdOk() (*string, bool) { +func (o *RequestStatus) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *RequestStatus) SetId(v string) { +// SetHref sets field value +func (o *RequestStatus) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *RequestStatus) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *RequestStatus) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *RequestStatus) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *RequestStatus) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *RequestStatus) GetTypeOk() (*Type, bool) { +func (o *RequestStatus) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *RequestStatus) SetType(v Type) { +// SetId sets field value +func (o *RequestStatus) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *RequestStatus) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *RequestStatus) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *RequestStatus) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *RequestStatus) GetMetadata() *RequestStatusMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *RequestStatus) GetHrefOk() (*string, bool) { +func (o *RequestStatus) GetMetadataOk() (*RequestStatusMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *RequestStatus) SetHref(v string) { +// SetMetadata sets field value +func (o *RequestStatus) SetMetadata(v RequestStatusMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *RequestStatus) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *RequestStatus) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for RequestStatusMetadata will be returned -func (o *RequestStatus) GetMetadata() *RequestStatusMetadata { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *RequestStatus) GetType() *Type { if o == nil { return nil } - return o.Metadata + return o.Type } -// GetMetadataOk returns a tuple with the Metadata field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *RequestStatus) GetMetadataOk() (*RequestStatusMetadata, bool) { +func (o *RequestStatus) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Type, true } -// SetMetadata sets field value -func (o *RequestStatus) SetMetadata(v RequestStatusMetadata) { +// SetType sets field value +func (o *RequestStatus) SetType(v Type) { - o.Metadata = &v + o.Type = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *RequestStatus) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasType returns a boolean if a field has been set. +func (o *RequestStatus) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -197,18 +197,22 @@ func (o *RequestStatus) HasMetadata() bool { func (o RequestStatus) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_status_metadata.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_status_metadata.go index ef97dbedb13..29b9967c852 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_status_metadata.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_status_metadata.go @@ -16,10 +16,10 @@ import ( // RequestStatusMetadata struct for RequestStatusMetadata type RequestStatusMetadata struct { - Status *string `json:"status,omitempty"` - Message *string `json:"message,omitempty"` // Resource's Entity Tag as defined in http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11 Entity Tag is also added as an 'ETag response header to requests which don't use 'depth' parameter. Etag *string `json:"etag,omitempty"` + Message *string `json:"message,omitempty"` + Status *string `json:"status,omitempty"` Targets *[]RequestTarget `json:"targets,omitempty"` } @@ -41,38 +41,38 @@ func NewRequestStatusMetadataWithDefaults() *RequestStatusMetadata { return &this } -// GetStatus returns the Status field value -// If the value is explicit nil, the zero value for string will be returned -func (o *RequestStatusMetadata) GetStatus() *string { +// GetEtag returns the Etag field value +// If the value is explicit nil, nil is returned +func (o *RequestStatusMetadata) GetEtag() *string { if o == nil { return nil } - return o.Status + return o.Etag } -// GetStatusOk returns a tuple with the Status field value +// GetEtagOk returns a tuple with the Etag field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *RequestStatusMetadata) GetStatusOk() (*string, bool) { +func (o *RequestStatusMetadata) GetEtagOk() (*string, bool) { if o == nil { return nil, false } - return o.Status, true + return o.Etag, true } -// SetStatus sets field value -func (o *RequestStatusMetadata) SetStatus(v string) { +// SetEtag sets field value +func (o *RequestStatusMetadata) SetEtag(v string) { - o.Status = &v + o.Etag = &v } -// HasStatus returns a boolean if a field has been set. -func (o *RequestStatusMetadata) HasStatus() bool { - if o != nil && o.Status != nil { +// HasEtag returns a boolean if a field has been set. +func (o *RequestStatusMetadata) HasEtag() bool { + if o != nil && o.Etag != nil { return true } @@ -80,7 +80,7 @@ func (o *RequestStatusMetadata) HasStatus() bool { } // GetMessage returns the Message field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *RequestStatusMetadata) GetMessage() *string { if o == nil { return nil @@ -117,38 +117,38 @@ func (o *RequestStatusMetadata) HasMessage() bool { return false } -// GetEtag returns the Etag field value -// If the value is explicit nil, the zero value for string will be returned -func (o *RequestStatusMetadata) GetEtag() *string { +// GetStatus returns the Status field value +// If the value is explicit nil, nil is returned +func (o *RequestStatusMetadata) GetStatus() *string { if o == nil { return nil } - return o.Etag + return o.Status } -// GetEtagOk returns a tuple with the Etag field value +// GetStatusOk returns a tuple with the Status field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *RequestStatusMetadata) GetEtagOk() (*string, bool) { +func (o *RequestStatusMetadata) GetStatusOk() (*string, bool) { if o == nil { return nil, false } - return o.Etag, true + return o.Status, true } -// SetEtag sets field value -func (o *RequestStatusMetadata) SetEtag(v string) { +// SetStatus sets field value +func (o *RequestStatusMetadata) SetStatus(v string) { - o.Etag = &v + o.Status = &v } -// HasEtag returns a boolean if a field has been set. -func (o *RequestStatusMetadata) HasEtag() bool { - if o != nil && o.Etag != nil { +// HasStatus returns a boolean if a field has been set. +func (o *RequestStatusMetadata) HasStatus() bool { + if o != nil && o.Status != nil { return true } @@ -156,7 +156,7 @@ func (o *RequestStatusMetadata) HasEtag() bool { } // GetTargets returns the Targets field value -// If the value is explicit nil, the zero value for []RequestTarget will be returned +// If the value is explicit nil, nil is returned func (o *RequestStatusMetadata) GetTargets() *[]RequestTarget { if o == nil { return nil @@ -195,18 +195,22 @@ func (o *RequestStatusMetadata) HasTargets() bool { func (o RequestStatusMetadata) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Status != nil { - toSerialize["status"] = o.Status + if o.Etag != nil { + toSerialize["etag"] = o.Etag } + if o.Message != nil { toSerialize["message"] = o.Message } - if o.Etag != nil { - toSerialize["etag"] = o.Etag + + if o.Status != nil { + toSerialize["status"] = o.Status } + if o.Targets != nil { toSerialize["targets"] = o.Targets } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_target.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_target.go index 590a5dfae8a..dc56f80ab63 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_target.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_request_target.go @@ -16,8 +16,8 @@ import ( // RequestTarget struct for RequestTarget type RequestTarget struct { - Target *ResourceReference `json:"target,omitempty"` Status *string `json:"status,omitempty"` + Target *ResourceReference `json:"target,omitempty"` } // NewRequestTarget instantiates a new RequestTarget object @@ -38,76 +38,76 @@ func NewRequestTargetWithDefaults() *RequestTarget { return &this } -// GetTarget returns the Target field value -// If the value is explicit nil, the zero value for ResourceReference will be returned -func (o *RequestTarget) GetTarget() *ResourceReference { +// GetStatus returns the Status field value +// If the value is explicit nil, nil is returned +func (o *RequestTarget) GetStatus() *string { if o == nil { return nil } - return o.Target + return o.Status } -// GetTargetOk returns a tuple with the Target field value +// GetStatusOk returns a tuple with the Status field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *RequestTarget) GetTargetOk() (*ResourceReference, bool) { +func (o *RequestTarget) GetStatusOk() (*string, bool) { if o == nil { return nil, false } - return o.Target, true + return o.Status, true } -// SetTarget sets field value -func (o *RequestTarget) SetTarget(v ResourceReference) { +// SetStatus sets field value +func (o *RequestTarget) SetStatus(v string) { - o.Target = &v + o.Status = &v } -// HasTarget returns a boolean if a field has been set. -func (o *RequestTarget) HasTarget() bool { - if o != nil && o.Target != nil { +// HasStatus returns a boolean if a field has been set. +func (o *RequestTarget) HasStatus() bool { + if o != nil && o.Status != nil { return true } return false } -// GetStatus returns the Status field value -// If the value is explicit nil, the zero value for string will be returned -func (o *RequestTarget) GetStatus() *string { +// GetTarget returns the Target field value +// If the value is explicit nil, nil is returned +func (o *RequestTarget) GetTarget() *ResourceReference { if o == nil { return nil } - return o.Status + return o.Target } -// GetStatusOk returns a tuple with the Status field value +// GetTargetOk returns a tuple with the Target field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *RequestTarget) GetStatusOk() (*string, bool) { +func (o *RequestTarget) GetTargetOk() (*ResourceReference, bool) { if o == nil { return nil, false } - return o.Status, true + return o.Target, true } -// SetStatus sets field value -func (o *RequestTarget) SetStatus(v string) { +// SetTarget sets field value +func (o *RequestTarget) SetTarget(v ResourceReference) { - o.Status = &v + o.Target = &v } -// HasStatus returns a boolean if a field has been set. -func (o *RequestTarget) HasStatus() bool { - if o != nil && o.Status != nil { +// HasTarget returns a boolean if a field has been set. +func (o *RequestTarget) HasTarget() bool { + if o != nil && o.Target != nil { return true } @@ -116,12 +116,14 @@ func (o *RequestTarget) HasStatus() bool { func (o RequestTarget) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Target != nil { - toSerialize["target"] = o.Target - } if o.Status != nil { toSerialize["status"] = o.Status } + + if o.Target != nil { + toSerialize["target"] = o.Target + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_requests.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_requests.go index 3d67bdc8188..0bf44ade828 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_requests.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_requests.go @@ -16,31 +16,31 @@ import ( // Requests struct for Requests type Requests struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Request `json:"items,omitempty"` + // The limit, specified in the request (if not specified, the endpoint's default pagination limit is used). + Limit *float32 `json:"limit"` // The offset, specified in the request (if not is specified, 0 is used by default). Offset *float32 `json:"offset"` - // The limit, specified in the request (if not specified, the endpoint's default pagination limit is used). - Limit *float32 `json:"limit"` - Links *PaginationLinks `json:"_links"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewRequests instantiates a new Requests object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewRequests(offset float32, limit float32, links PaginationLinks) *Requests { +func NewRequests(links PaginationLinks, limit float32, offset float32) *Requests { this := Requests{} - this.Offset = &offset - this.Limit = &limit this.Links = &links + this.Limit = &limit + this.Offset = &offset return &this } @@ -53,114 +53,114 @@ func NewRequestsWithDefaults() *Requests { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Requests) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *Requests) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Requests) GetIdOk() (*string, bool) { +func (o *Requests) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *Requests) SetId(v string) { +// SetLinks sets field value +func (o *Requests) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *Requests) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *Requests) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Requests) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Requests) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Requests) GetTypeOk() (*Type, bool) { +func (o *Requests) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Requests) SetType(v Type) { +// SetHref sets field value +func (o *Requests) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Requests) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Requests) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Requests) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Requests) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Requests) GetHrefOk() (*string, bool) { +func (o *Requests) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Requests) SetHref(v string) { +// SetId sets field value +func (o *Requests) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Requests) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Requests) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -168,7 +168,7 @@ func (o *Requests) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Request will be returned +// If the value is explicit nil, nil is returned func (o *Requests) GetItems() *[]Request { if o == nil { return nil @@ -205,114 +205,114 @@ func (o *Requests) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Requests) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *Requests) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Requests) GetOffsetOk() (*float32, bool) { +func (o *Requests) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *Requests) SetOffset(v float32) { +// SetLimit sets field value +func (o *Requests) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *Requests) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *Requests) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Requests) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *Requests) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Requests) GetLimitOk() (*float32, bool) { +func (o *Requests) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *Requests) SetLimit(v float32) { +// SetOffset sets field value +func (o *Requests) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *Requests) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *Requests) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *Requests) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Requests) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Requests) GetLinksOk() (*PaginationLinks, bool) { +func (o *Requests) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *Requests) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *Requests) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *Requests) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *Requests) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -321,27 +321,34 @@ func (o *Requests) HasLinks() bool { func (o Requests) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource.go index 1d370ce223e..82b8f739d8f 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource.go @@ -16,15 +16,15 @@ import ( // Resource datacenter resource representation type Resource struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of the resource. - Type *Type `json:"type,omitempty"` + Entities *ResourceEntities `json:"entities,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *ResourceProperties `json:"properties,omitempty"` - Entities *ResourceEntities `json:"entities,omitempty"` + // The type of the resource. + Type *Type `json:"type,omitempty"` } // NewResource instantiates a new Resource object @@ -45,114 +45,114 @@ func NewResourceWithDefaults() *Resource { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Resource) GetId() *string { +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *Resource) GetEntities() *ResourceEntities { if o == nil { return nil } - return o.Id + return o.Entities } -// GetIdOk returns a tuple with the Id field value +// GetEntitiesOk returns a tuple with the Entities field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Resource) GetIdOk() (*string, bool) { +func (o *Resource) GetEntitiesOk() (*ResourceEntities, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Entities, true } -// SetId sets field value -func (o *Resource) SetId(v string) { +// SetEntities sets field value +func (o *Resource) SetEntities(v ResourceEntities) { - o.Id = &v + o.Entities = &v } -// HasId returns a boolean if a field has been set. -func (o *Resource) HasId() bool { - if o != nil && o.Id != nil { +// HasEntities returns a boolean if a field has been set. +func (o *Resource) HasEntities() bool { + if o != nil && o.Entities != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Resource) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Resource) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Resource) GetTypeOk() (*Type, bool) { +func (o *Resource) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Resource) SetType(v Type) { +// SetHref sets field value +func (o *Resource) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Resource) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Resource) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Resource) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Resource) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Resource) GetHrefOk() (*string, bool) { +func (o *Resource) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Resource) SetHref(v string) { +// SetId sets field value +func (o *Resource) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Resource) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Resource) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -160,7 +160,7 @@ func (o *Resource) HasHref() bool { } // GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned +// If the value is explicit nil, nil is returned func (o *Resource) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil @@ -198,7 +198,7 @@ func (o *Resource) HasMetadata() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for ResourceProperties will be returned +// If the value is explicit nil, nil is returned func (o *Resource) GetProperties() *ResourceProperties { if o == nil { return nil @@ -235,38 +235,38 @@ func (o *Resource) HasProperties() bool { return false } -// GetEntities returns the Entities field value -// If the value is explicit nil, the zero value for ResourceEntities will be returned -func (o *Resource) GetEntities() *ResourceEntities { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Resource) GetType() *Type { if o == nil { return nil } - return o.Entities + return o.Type } -// GetEntitiesOk returns a tuple with the Entities field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Resource) GetEntitiesOk() (*ResourceEntities, bool) { +func (o *Resource) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Entities, true + return o.Type, true } -// SetEntities sets field value -func (o *Resource) SetEntities(v ResourceEntities) { +// SetType sets field value +func (o *Resource) SetType(v Type) { - o.Entities = &v + o.Type = &v } -// HasEntities returns a boolean if a field has been set. -func (o *Resource) HasEntities() bool { - if o != nil && o.Entities != nil { +// HasType returns a boolean if a field has been set. +func (o *Resource) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -275,24 +275,30 @@ func (o *Resource) HasEntities() bool { func (o Resource) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Entities != nil { + toSerialize["entities"] = o.Entities } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } - if o.Entities != nil { - toSerialize["entities"] = o.Entities + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_entities.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_entities.go index cc9f26acb02..735ffe73b17 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_entities.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_entities.go @@ -38,7 +38,7 @@ func NewResourceEntitiesWithDefaults() *ResourceEntities { } // GetGroups returns the Groups field value -// If the value is explicit nil, the zero value for ResourceGroups will be returned +// If the value is explicit nil, nil is returned func (o *ResourceEntities) GetGroups() *ResourceGroups { if o == nil { return nil @@ -80,6 +80,7 @@ func (o ResourceEntities) MarshalJSON() ([]byte, error) { if o.Groups != nil { toSerialize["groups"] = o.Groups } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_groups.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_groups.go index ae8939261cf..8d0a2a1a6a0 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_groups.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_groups.go @@ -16,14 +16,14 @@ import ( // ResourceGroups Resources assigned to this group. type ResourceGroups struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of the resource. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Resource `json:"items,omitempty"` + // The type of the resource. + Type *Type `json:"type,omitempty"` } // NewResourceGroups instantiates a new ResourceGroups object @@ -44,152 +44,152 @@ func NewResourceGroupsWithDefaults() *ResourceGroups { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ResourceGroups) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *ResourceGroups) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceGroups) GetIdOk() (*string, bool) { +func (o *ResourceGroups) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *ResourceGroups) SetId(v string) { +// SetHref sets field value +func (o *ResourceGroups) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *ResourceGroups) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *ResourceGroups) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *ResourceGroups) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *ResourceGroups) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceGroups) GetTypeOk() (*Type, bool) { +func (o *ResourceGroups) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *ResourceGroups) SetType(v Type) { +// SetId sets field value +func (o *ResourceGroups) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *ResourceGroups) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *ResourceGroups) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ResourceGroups) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *ResourceGroups) GetItems() *[]Resource { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceGroups) GetHrefOk() (*string, bool) { +func (o *ResourceGroups) GetItemsOk() (*[]Resource, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *ResourceGroups) SetHref(v string) { +// SetItems sets field value +func (o *ResourceGroups) SetItems(v []Resource) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *ResourceGroups) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *ResourceGroups) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Resource will be returned -func (o *ResourceGroups) GetItems() *[]Resource { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *ResourceGroups) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceGroups) GetItemsOk() (*[]Resource, bool) { +func (o *ResourceGroups) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *ResourceGroups) SetItems(v []Resource) { +// SetType sets field value +func (o *ResourceGroups) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *ResourceGroups) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *ResourceGroups) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *ResourceGroups) HasItems() bool { func (o ResourceGroups) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_limits.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_limits.go index 8dbbe386e6b..ca9ee840057 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_limits.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_limits.go @@ -16,81 +16,81 @@ import ( // ResourceLimits struct for ResourceLimits type ResourceLimits struct { - // The maximum number of CPU cores per server. - CoresPerServer *int32 `json:"coresPerServer"` // The maximum number of CPU cores per contract. CoresPerContract *int32 `json:"coresPerContract"` + // The maximum number of CPU cores per server. + CoresPerServer *int32 `json:"coresPerServer"` // The number of CPU cores provisioned. CoresProvisioned *int32 `json:"coresProvisioned"` - // The maximum amount of RAM (in MB) that can be provisioned for a particular server under this contract. - RamPerServer *int32 `json:"ramPerServer"` - // The maximum amount of RAM (in MB) that can be provisioned under this contract. - RamPerContract *int32 `json:"ramPerContract"` - // The amount of RAM (in MB) provisioned under this contract. - RamProvisioned *int32 `json:"ramProvisioned"` - // The maximum size (in MB) of an idividual hard disk volume. - HddLimitPerVolume *int64 `json:"hddLimitPerVolume"` + // The amount of DAS disk space (in MB) in a Cube server that is currently provisioned. + DasVolumeProvisioned *int64 `json:"dasVolumeProvisioned"` // The maximum amount of disk space (in MB) that can be provided under this contract. HddLimitPerContract *int64 `json:"hddLimitPerContract"` + // The maximum size (in MB) of an idividual hard disk volume. + HddLimitPerVolume *int64 `json:"hddLimitPerVolume"` // The amount of hard disk space (in MB) that is currently provisioned. HddVolumeProvisioned *int64 `json:"hddVolumeProvisioned"` - // The maximum size (in MB) of an individual solid state disk volume. - SsdLimitPerVolume *int64 `json:"ssdLimitPerVolume"` - // The maximum amount of solid state disk space (in MB) that can be provisioned under this contract. - SsdLimitPerContract *int64 `json:"ssdLimitPerContract"` - // The amount of solid state disk space (in MB) that is currently provisioned. - SsdVolumeProvisioned *int64 `json:"ssdVolumeProvisioned"` - // The amount of DAS disk space (in MB) in a Cube server that is currently provisioned. - DasVolumeProvisioned *int64 `json:"dasVolumeProvisioned"` - // The maximum number of static public IP addresses that can be reserved by this customer across contracts. - ReservableIps *int32 `json:"reservableIps"` - // The maximum number of static public IP addresses that can be reserved for this contract. - ReservedIpsOnContract *int32 `json:"reservedIpsOnContract"` - // The number of static public IP addresses in use. - ReservedIpsInUse *int32 `json:"reservedIpsInUse"` // The maximum number of Kubernetes clusters that can be created under this contract. K8sClusterLimitTotal *int32 `json:"k8sClusterLimitTotal"` // The amount of Kubernetes clusters that is currently provisioned. K8sClustersProvisioned *int32 `json:"k8sClustersProvisioned"` - // The NLB total limit. - NlbLimitTotal *int32 `json:"nlbLimitTotal"` - // The NLBs provisioned. - NlbProvisioned *int32 `json:"nlbProvisioned"` // The NAT Gateway total limit. NatGatewayLimitTotal *int32 `json:"natGatewayLimitTotal"` // The NAT Gateways provisioned. NatGatewayProvisioned *int32 `json:"natGatewayProvisioned"` + // The NLB total limit. + NlbLimitTotal *int32 `json:"nlbLimitTotal"` + // The NLBs provisioned. + NlbProvisioned *int32 `json:"nlbProvisioned"` + // The maximum amount of RAM (in MB) that can be provisioned under this contract. + RamPerContract *int32 `json:"ramPerContract"` + // The maximum amount of RAM (in MB) that can be provisioned for a particular server under this contract. + RamPerServer *int32 `json:"ramPerServer"` + // The amount of RAM (in MB) provisioned under this contract. + RamProvisioned *int32 `json:"ramProvisioned"` + // The maximum number of static public IP addresses that can be reserved by this customer across contracts. + ReservableIps *int32 `json:"reservableIps"` + // The number of static public IP addresses in use. + ReservedIpsInUse *int32 `json:"reservedIpsInUse"` + // The maximum number of static public IP addresses that can be reserved for this contract. + ReservedIpsOnContract *int32 `json:"reservedIpsOnContract"` + // The maximum amount of solid state disk space (in MB) that can be provisioned under this contract. + SsdLimitPerContract *int64 `json:"ssdLimitPerContract"` + // The maximum size (in MB) of an individual solid state disk volume. + SsdLimitPerVolume *int64 `json:"ssdLimitPerVolume"` + // The amount of solid state disk space (in MB) that is currently provisioned. + SsdVolumeProvisioned *int64 `json:"ssdVolumeProvisioned"` } // NewResourceLimits instantiates a new ResourceLimits object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewResourceLimits(coresPerServer int32, coresPerContract int32, coresProvisioned int32, ramPerServer int32, ramPerContract int32, ramProvisioned int32, hddLimitPerVolume int64, hddLimitPerContract int64, hddVolumeProvisioned int64, ssdLimitPerVolume int64, ssdLimitPerContract int64, ssdVolumeProvisioned int64, dasVolumeProvisioned int64, reservableIps int32, reservedIpsOnContract int32, reservedIpsInUse int32, k8sClusterLimitTotal int32, k8sClustersProvisioned int32, nlbLimitTotal int32, nlbProvisioned int32, natGatewayLimitTotal int32, natGatewayProvisioned int32) *ResourceLimits { +func NewResourceLimits(coresPerContract int32, coresPerServer int32, coresProvisioned int32, dasVolumeProvisioned int64, hddLimitPerContract int64, hddLimitPerVolume int64, hddVolumeProvisioned int64, k8sClusterLimitTotal int32, k8sClustersProvisioned int32, natGatewayLimitTotal int32, natGatewayProvisioned int32, nlbLimitTotal int32, nlbProvisioned int32, ramPerContract int32, ramPerServer int32, ramProvisioned int32, reservableIps int32, reservedIpsInUse int32, reservedIpsOnContract int32, ssdLimitPerContract int64, ssdLimitPerVolume int64, ssdVolumeProvisioned int64) *ResourceLimits { this := ResourceLimits{} - this.CoresPerServer = &coresPerServer this.CoresPerContract = &coresPerContract + this.CoresPerServer = &coresPerServer this.CoresProvisioned = &coresProvisioned - this.RamPerServer = &ramPerServer - this.RamPerContract = &ramPerContract - this.RamProvisioned = &ramProvisioned - this.HddLimitPerVolume = &hddLimitPerVolume + this.DasVolumeProvisioned = &dasVolumeProvisioned this.HddLimitPerContract = &hddLimitPerContract + this.HddLimitPerVolume = &hddLimitPerVolume this.HddVolumeProvisioned = &hddVolumeProvisioned - this.SsdLimitPerVolume = &ssdLimitPerVolume - this.SsdLimitPerContract = &ssdLimitPerContract - this.SsdVolumeProvisioned = &ssdVolumeProvisioned - this.DasVolumeProvisioned = &dasVolumeProvisioned - this.ReservableIps = &reservableIps - this.ReservedIpsOnContract = &reservedIpsOnContract - this.ReservedIpsInUse = &reservedIpsInUse this.K8sClusterLimitTotal = &k8sClusterLimitTotal this.K8sClustersProvisioned = &k8sClustersProvisioned - this.NlbLimitTotal = &nlbLimitTotal - this.NlbProvisioned = &nlbProvisioned this.NatGatewayLimitTotal = &natGatewayLimitTotal this.NatGatewayProvisioned = &natGatewayProvisioned + this.NlbLimitTotal = &nlbLimitTotal + this.NlbProvisioned = &nlbProvisioned + this.RamPerContract = &ramPerContract + this.RamPerServer = &ramPerServer + this.RamProvisioned = &ramProvisioned + this.ReservableIps = &reservableIps + this.ReservedIpsInUse = &reservedIpsInUse + this.ReservedIpsOnContract = &reservedIpsOnContract + this.SsdLimitPerContract = &ssdLimitPerContract + this.SsdLimitPerVolume = &ssdLimitPerVolume + this.SsdVolumeProvisioned = &ssdVolumeProvisioned return &this } @@ -103,76 +103,76 @@ func NewResourceLimitsWithDefaults() *ResourceLimits { return &this } -// GetCoresPerServer returns the CoresPerServer field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ResourceLimits) GetCoresPerServer() *int32 { +// GetCoresPerContract returns the CoresPerContract field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetCoresPerContract() *int32 { if o == nil { return nil } - return o.CoresPerServer + return o.CoresPerContract } -// GetCoresPerServerOk returns a tuple with the CoresPerServer field value +// GetCoresPerContractOk returns a tuple with the CoresPerContract field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetCoresPerServerOk() (*int32, bool) { +func (o *ResourceLimits) GetCoresPerContractOk() (*int32, bool) { if o == nil { return nil, false } - return o.CoresPerServer, true + return o.CoresPerContract, true } -// SetCoresPerServer sets field value -func (o *ResourceLimits) SetCoresPerServer(v int32) { +// SetCoresPerContract sets field value +func (o *ResourceLimits) SetCoresPerContract(v int32) { - o.CoresPerServer = &v + o.CoresPerContract = &v } -// HasCoresPerServer returns a boolean if a field has been set. -func (o *ResourceLimits) HasCoresPerServer() bool { - if o != nil && o.CoresPerServer != nil { +// HasCoresPerContract returns a boolean if a field has been set. +func (o *ResourceLimits) HasCoresPerContract() bool { + if o != nil && o.CoresPerContract != nil { return true } return false } -// GetCoresPerContract returns the CoresPerContract field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ResourceLimits) GetCoresPerContract() *int32 { +// GetCoresPerServer returns the CoresPerServer field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetCoresPerServer() *int32 { if o == nil { return nil } - return o.CoresPerContract + return o.CoresPerServer } -// GetCoresPerContractOk returns a tuple with the CoresPerContract field value +// GetCoresPerServerOk returns a tuple with the CoresPerServer field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetCoresPerContractOk() (*int32, bool) { +func (o *ResourceLimits) GetCoresPerServerOk() (*int32, bool) { if o == nil { return nil, false } - return o.CoresPerContract, true + return o.CoresPerServer, true } -// SetCoresPerContract sets field value -func (o *ResourceLimits) SetCoresPerContract(v int32) { +// SetCoresPerServer sets field value +func (o *ResourceLimits) SetCoresPerServer(v int32) { - o.CoresPerContract = &v + o.CoresPerServer = &v } -// HasCoresPerContract returns a boolean if a field has been set. -func (o *ResourceLimits) HasCoresPerContract() bool { - if o != nil && o.CoresPerContract != nil { +// HasCoresPerServer returns a boolean if a field has been set. +func (o *ResourceLimits) HasCoresPerServer() bool { + if o != nil && o.CoresPerServer != nil { return true } @@ -180,7 +180,7 @@ func (o *ResourceLimits) HasCoresPerContract() bool { } // GetCoresProvisioned returns the CoresProvisioned field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *ResourceLimits) GetCoresProvisioned() *int32 { if o == nil { return nil @@ -217,722 +217,722 @@ func (o *ResourceLimits) HasCoresProvisioned() bool { return false } -// GetRamPerServer returns the RamPerServer field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ResourceLimits) GetRamPerServer() *int32 { +// GetDasVolumeProvisioned returns the DasVolumeProvisioned field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetDasVolumeProvisioned() *int64 { if o == nil { return nil } - return o.RamPerServer + return o.DasVolumeProvisioned } -// GetRamPerServerOk returns a tuple with the RamPerServer field value +// GetDasVolumeProvisionedOk returns a tuple with the DasVolumeProvisioned field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetRamPerServerOk() (*int32, bool) { +func (o *ResourceLimits) GetDasVolumeProvisionedOk() (*int64, bool) { if o == nil { return nil, false } - return o.RamPerServer, true + return o.DasVolumeProvisioned, true } -// SetRamPerServer sets field value -func (o *ResourceLimits) SetRamPerServer(v int32) { +// SetDasVolumeProvisioned sets field value +func (o *ResourceLimits) SetDasVolumeProvisioned(v int64) { - o.RamPerServer = &v + o.DasVolumeProvisioned = &v } -// HasRamPerServer returns a boolean if a field has been set. -func (o *ResourceLimits) HasRamPerServer() bool { - if o != nil && o.RamPerServer != nil { +// HasDasVolumeProvisioned returns a boolean if a field has been set. +func (o *ResourceLimits) HasDasVolumeProvisioned() bool { + if o != nil && o.DasVolumeProvisioned != nil { return true } return false } -// GetRamPerContract returns the RamPerContract field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ResourceLimits) GetRamPerContract() *int32 { +// GetHddLimitPerContract returns the HddLimitPerContract field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetHddLimitPerContract() *int64 { if o == nil { return nil } - return o.RamPerContract + return o.HddLimitPerContract } -// GetRamPerContractOk returns a tuple with the RamPerContract field value +// GetHddLimitPerContractOk returns a tuple with the HddLimitPerContract field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetRamPerContractOk() (*int32, bool) { +func (o *ResourceLimits) GetHddLimitPerContractOk() (*int64, bool) { if o == nil { return nil, false } - return o.RamPerContract, true + return o.HddLimitPerContract, true } -// SetRamPerContract sets field value -func (o *ResourceLimits) SetRamPerContract(v int32) { +// SetHddLimitPerContract sets field value +func (o *ResourceLimits) SetHddLimitPerContract(v int64) { - o.RamPerContract = &v + o.HddLimitPerContract = &v } -// HasRamPerContract returns a boolean if a field has been set. -func (o *ResourceLimits) HasRamPerContract() bool { - if o != nil && o.RamPerContract != nil { +// HasHddLimitPerContract returns a boolean if a field has been set. +func (o *ResourceLimits) HasHddLimitPerContract() bool { + if o != nil && o.HddLimitPerContract != nil { return true } return false } -// GetRamProvisioned returns the RamProvisioned field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ResourceLimits) GetRamProvisioned() *int32 { +// GetHddLimitPerVolume returns the HddLimitPerVolume field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetHddLimitPerVolume() *int64 { if o == nil { return nil } - return o.RamProvisioned + return o.HddLimitPerVolume } -// GetRamProvisionedOk returns a tuple with the RamProvisioned field value +// GetHddLimitPerVolumeOk returns a tuple with the HddLimitPerVolume field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetRamProvisionedOk() (*int32, bool) { +func (o *ResourceLimits) GetHddLimitPerVolumeOk() (*int64, bool) { if o == nil { return nil, false } - return o.RamProvisioned, true + return o.HddLimitPerVolume, true } -// SetRamProvisioned sets field value -func (o *ResourceLimits) SetRamProvisioned(v int32) { +// SetHddLimitPerVolume sets field value +func (o *ResourceLimits) SetHddLimitPerVolume(v int64) { - o.RamProvisioned = &v + o.HddLimitPerVolume = &v } -// HasRamProvisioned returns a boolean if a field has been set. -func (o *ResourceLimits) HasRamProvisioned() bool { - if o != nil && o.RamProvisioned != nil { +// HasHddLimitPerVolume returns a boolean if a field has been set. +func (o *ResourceLimits) HasHddLimitPerVolume() bool { + if o != nil && o.HddLimitPerVolume != nil { return true } return false } -// GetHddLimitPerVolume returns the HddLimitPerVolume field value -// If the value is explicit nil, the zero value for int64 will be returned -func (o *ResourceLimits) GetHddLimitPerVolume() *int64 { +// GetHddVolumeProvisioned returns the HddVolumeProvisioned field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetHddVolumeProvisioned() *int64 { if o == nil { return nil } - return o.HddLimitPerVolume + return o.HddVolumeProvisioned } -// GetHddLimitPerVolumeOk returns a tuple with the HddLimitPerVolume field value +// GetHddVolumeProvisionedOk returns a tuple with the HddVolumeProvisioned field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetHddLimitPerVolumeOk() (*int64, bool) { +func (o *ResourceLimits) GetHddVolumeProvisionedOk() (*int64, bool) { if o == nil { return nil, false } - return o.HddLimitPerVolume, true + return o.HddVolumeProvisioned, true } -// SetHddLimitPerVolume sets field value -func (o *ResourceLimits) SetHddLimitPerVolume(v int64) { +// SetHddVolumeProvisioned sets field value +func (o *ResourceLimits) SetHddVolumeProvisioned(v int64) { - o.HddLimitPerVolume = &v + o.HddVolumeProvisioned = &v } -// HasHddLimitPerVolume returns a boolean if a field has been set. -func (o *ResourceLimits) HasHddLimitPerVolume() bool { - if o != nil && o.HddLimitPerVolume != nil { +// HasHddVolumeProvisioned returns a boolean if a field has been set. +func (o *ResourceLimits) HasHddVolumeProvisioned() bool { + if o != nil && o.HddVolumeProvisioned != nil { return true } return false } -// GetHddLimitPerContract returns the HddLimitPerContract field value -// If the value is explicit nil, the zero value for int64 will be returned -func (o *ResourceLimits) GetHddLimitPerContract() *int64 { +// GetK8sClusterLimitTotal returns the K8sClusterLimitTotal field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetK8sClusterLimitTotal() *int32 { if o == nil { return nil } - return o.HddLimitPerContract + return o.K8sClusterLimitTotal } -// GetHddLimitPerContractOk returns a tuple with the HddLimitPerContract field value +// GetK8sClusterLimitTotalOk returns a tuple with the K8sClusterLimitTotal field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetHddLimitPerContractOk() (*int64, bool) { +func (o *ResourceLimits) GetK8sClusterLimitTotalOk() (*int32, bool) { if o == nil { return nil, false } - return o.HddLimitPerContract, true + return o.K8sClusterLimitTotal, true } -// SetHddLimitPerContract sets field value -func (o *ResourceLimits) SetHddLimitPerContract(v int64) { +// SetK8sClusterLimitTotal sets field value +func (o *ResourceLimits) SetK8sClusterLimitTotal(v int32) { - o.HddLimitPerContract = &v + o.K8sClusterLimitTotal = &v } -// HasHddLimitPerContract returns a boolean if a field has been set. -func (o *ResourceLimits) HasHddLimitPerContract() bool { - if o != nil && o.HddLimitPerContract != nil { +// HasK8sClusterLimitTotal returns a boolean if a field has been set. +func (o *ResourceLimits) HasK8sClusterLimitTotal() bool { + if o != nil && o.K8sClusterLimitTotal != nil { return true } return false } -// GetHddVolumeProvisioned returns the HddVolumeProvisioned field value -// If the value is explicit nil, the zero value for int64 will be returned -func (o *ResourceLimits) GetHddVolumeProvisioned() *int64 { +// GetK8sClustersProvisioned returns the K8sClustersProvisioned field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetK8sClustersProvisioned() *int32 { if o == nil { return nil } - return o.HddVolumeProvisioned + return o.K8sClustersProvisioned } -// GetHddVolumeProvisionedOk returns a tuple with the HddVolumeProvisioned field value +// GetK8sClustersProvisionedOk returns a tuple with the K8sClustersProvisioned field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetHddVolumeProvisionedOk() (*int64, bool) { +func (o *ResourceLimits) GetK8sClustersProvisionedOk() (*int32, bool) { if o == nil { return nil, false } - return o.HddVolumeProvisioned, true + return o.K8sClustersProvisioned, true } -// SetHddVolumeProvisioned sets field value -func (o *ResourceLimits) SetHddVolumeProvisioned(v int64) { +// SetK8sClustersProvisioned sets field value +func (o *ResourceLimits) SetK8sClustersProvisioned(v int32) { - o.HddVolumeProvisioned = &v + o.K8sClustersProvisioned = &v } -// HasHddVolumeProvisioned returns a boolean if a field has been set. -func (o *ResourceLimits) HasHddVolumeProvisioned() bool { - if o != nil && o.HddVolumeProvisioned != nil { +// HasK8sClustersProvisioned returns a boolean if a field has been set. +func (o *ResourceLimits) HasK8sClustersProvisioned() bool { + if o != nil && o.K8sClustersProvisioned != nil { return true } return false } -// GetSsdLimitPerVolume returns the SsdLimitPerVolume field value -// If the value is explicit nil, the zero value for int64 will be returned -func (o *ResourceLimits) GetSsdLimitPerVolume() *int64 { +// GetNatGatewayLimitTotal returns the NatGatewayLimitTotal field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetNatGatewayLimitTotal() *int32 { if o == nil { return nil } - return o.SsdLimitPerVolume + return o.NatGatewayLimitTotal } -// GetSsdLimitPerVolumeOk returns a tuple with the SsdLimitPerVolume field value +// GetNatGatewayLimitTotalOk returns a tuple with the NatGatewayLimitTotal field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetSsdLimitPerVolumeOk() (*int64, bool) { +func (o *ResourceLimits) GetNatGatewayLimitTotalOk() (*int32, bool) { if o == nil { return nil, false } - return o.SsdLimitPerVolume, true + return o.NatGatewayLimitTotal, true } -// SetSsdLimitPerVolume sets field value -func (o *ResourceLimits) SetSsdLimitPerVolume(v int64) { +// SetNatGatewayLimitTotal sets field value +func (o *ResourceLimits) SetNatGatewayLimitTotal(v int32) { - o.SsdLimitPerVolume = &v + o.NatGatewayLimitTotal = &v } -// HasSsdLimitPerVolume returns a boolean if a field has been set. -func (o *ResourceLimits) HasSsdLimitPerVolume() bool { - if o != nil && o.SsdLimitPerVolume != nil { +// HasNatGatewayLimitTotal returns a boolean if a field has been set. +func (o *ResourceLimits) HasNatGatewayLimitTotal() bool { + if o != nil && o.NatGatewayLimitTotal != nil { return true } return false } -// GetSsdLimitPerContract returns the SsdLimitPerContract field value -// If the value is explicit nil, the zero value for int64 will be returned -func (o *ResourceLimits) GetSsdLimitPerContract() *int64 { +// GetNatGatewayProvisioned returns the NatGatewayProvisioned field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetNatGatewayProvisioned() *int32 { if o == nil { return nil } - return o.SsdLimitPerContract + return o.NatGatewayProvisioned } -// GetSsdLimitPerContractOk returns a tuple with the SsdLimitPerContract field value +// GetNatGatewayProvisionedOk returns a tuple with the NatGatewayProvisioned field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetSsdLimitPerContractOk() (*int64, bool) { +func (o *ResourceLimits) GetNatGatewayProvisionedOk() (*int32, bool) { if o == nil { return nil, false } - return o.SsdLimitPerContract, true + return o.NatGatewayProvisioned, true } -// SetSsdLimitPerContract sets field value -func (o *ResourceLimits) SetSsdLimitPerContract(v int64) { +// SetNatGatewayProvisioned sets field value +func (o *ResourceLimits) SetNatGatewayProvisioned(v int32) { - o.SsdLimitPerContract = &v + o.NatGatewayProvisioned = &v } -// HasSsdLimitPerContract returns a boolean if a field has been set. -func (o *ResourceLimits) HasSsdLimitPerContract() bool { - if o != nil && o.SsdLimitPerContract != nil { +// HasNatGatewayProvisioned returns a boolean if a field has been set. +func (o *ResourceLimits) HasNatGatewayProvisioned() bool { + if o != nil && o.NatGatewayProvisioned != nil { return true } return false } -// GetSsdVolumeProvisioned returns the SsdVolumeProvisioned field value -// If the value is explicit nil, the zero value for int64 will be returned -func (o *ResourceLimits) GetSsdVolumeProvisioned() *int64 { +// GetNlbLimitTotal returns the NlbLimitTotal field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetNlbLimitTotal() *int32 { if o == nil { return nil } - return o.SsdVolumeProvisioned + return o.NlbLimitTotal } -// GetSsdVolumeProvisionedOk returns a tuple with the SsdVolumeProvisioned field value +// GetNlbLimitTotalOk returns a tuple with the NlbLimitTotal field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetSsdVolumeProvisionedOk() (*int64, bool) { +func (o *ResourceLimits) GetNlbLimitTotalOk() (*int32, bool) { if o == nil { return nil, false } - return o.SsdVolumeProvisioned, true + return o.NlbLimitTotal, true } -// SetSsdVolumeProvisioned sets field value -func (o *ResourceLimits) SetSsdVolumeProvisioned(v int64) { +// SetNlbLimitTotal sets field value +func (o *ResourceLimits) SetNlbLimitTotal(v int32) { - o.SsdVolumeProvisioned = &v + o.NlbLimitTotal = &v } -// HasSsdVolumeProvisioned returns a boolean if a field has been set. -func (o *ResourceLimits) HasSsdVolumeProvisioned() bool { - if o != nil && o.SsdVolumeProvisioned != nil { +// HasNlbLimitTotal returns a boolean if a field has been set. +func (o *ResourceLimits) HasNlbLimitTotal() bool { + if o != nil && o.NlbLimitTotal != nil { return true } return false } -// GetDasVolumeProvisioned returns the DasVolumeProvisioned field value -// If the value is explicit nil, the zero value for int64 will be returned -func (o *ResourceLimits) GetDasVolumeProvisioned() *int64 { +// GetNlbProvisioned returns the NlbProvisioned field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetNlbProvisioned() *int32 { if o == nil { return nil } - return o.DasVolumeProvisioned + return o.NlbProvisioned } -// GetDasVolumeProvisionedOk returns a tuple with the DasVolumeProvisioned field value +// GetNlbProvisionedOk returns a tuple with the NlbProvisioned field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetDasVolumeProvisionedOk() (*int64, bool) { +func (o *ResourceLimits) GetNlbProvisionedOk() (*int32, bool) { if o == nil { return nil, false } - return o.DasVolumeProvisioned, true + return o.NlbProvisioned, true } -// SetDasVolumeProvisioned sets field value -func (o *ResourceLimits) SetDasVolumeProvisioned(v int64) { +// SetNlbProvisioned sets field value +func (o *ResourceLimits) SetNlbProvisioned(v int32) { - o.DasVolumeProvisioned = &v + o.NlbProvisioned = &v } -// HasDasVolumeProvisioned returns a boolean if a field has been set. -func (o *ResourceLimits) HasDasVolumeProvisioned() bool { - if o != nil && o.DasVolumeProvisioned != nil { +// HasNlbProvisioned returns a boolean if a field has been set. +func (o *ResourceLimits) HasNlbProvisioned() bool { + if o != nil && o.NlbProvisioned != nil { return true } return false } -// GetReservableIps returns the ReservableIps field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ResourceLimits) GetReservableIps() *int32 { +// GetRamPerContract returns the RamPerContract field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetRamPerContract() *int32 { if o == nil { return nil } - return o.ReservableIps + return o.RamPerContract } -// GetReservableIpsOk returns a tuple with the ReservableIps field value +// GetRamPerContractOk returns a tuple with the RamPerContract field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetReservableIpsOk() (*int32, bool) { +func (o *ResourceLimits) GetRamPerContractOk() (*int32, bool) { if o == nil { return nil, false } - return o.ReservableIps, true + return o.RamPerContract, true } -// SetReservableIps sets field value -func (o *ResourceLimits) SetReservableIps(v int32) { +// SetRamPerContract sets field value +func (o *ResourceLimits) SetRamPerContract(v int32) { - o.ReservableIps = &v + o.RamPerContract = &v } -// HasReservableIps returns a boolean if a field has been set. -func (o *ResourceLimits) HasReservableIps() bool { - if o != nil && o.ReservableIps != nil { +// HasRamPerContract returns a boolean if a field has been set. +func (o *ResourceLimits) HasRamPerContract() bool { + if o != nil && o.RamPerContract != nil { return true } return false } -// GetReservedIpsOnContract returns the ReservedIpsOnContract field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ResourceLimits) GetReservedIpsOnContract() *int32 { +// GetRamPerServer returns the RamPerServer field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetRamPerServer() *int32 { if o == nil { return nil } - return o.ReservedIpsOnContract + return o.RamPerServer } -// GetReservedIpsOnContractOk returns a tuple with the ReservedIpsOnContract field value +// GetRamPerServerOk returns a tuple with the RamPerServer field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetReservedIpsOnContractOk() (*int32, bool) { +func (o *ResourceLimits) GetRamPerServerOk() (*int32, bool) { if o == nil { return nil, false } - return o.ReservedIpsOnContract, true + return o.RamPerServer, true } -// SetReservedIpsOnContract sets field value -func (o *ResourceLimits) SetReservedIpsOnContract(v int32) { +// SetRamPerServer sets field value +func (o *ResourceLimits) SetRamPerServer(v int32) { - o.ReservedIpsOnContract = &v + o.RamPerServer = &v } -// HasReservedIpsOnContract returns a boolean if a field has been set. -func (o *ResourceLimits) HasReservedIpsOnContract() bool { - if o != nil && o.ReservedIpsOnContract != nil { +// HasRamPerServer returns a boolean if a field has been set. +func (o *ResourceLimits) HasRamPerServer() bool { + if o != nil && o.RamPerServer != nil { return true } return false } -// GetReservedIpsInUse returns the ReservedIpsInUse field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ResourceLimits) GetReservedIpsInUse() *int32 { +// GetRamProvisioned returns the RamProvisioned field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetRamProvisioned() *int32 { if o == nil { return nil } - return o.ReservedIpsInUse + return o.RamProvisioned } -// GetReservedIpsInUseOk returns a tuple with the ReservedIpsInUse field value +// GetRamProvisionedOk returns a tuple with the RamProvisioned field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetReservedIpsInUseOk() (*int32, bool) { +func (o *ResourceLimits) GetRamProvisionedOk() (*int32, bool) { if o == nil { return nil, false } - return o.ReservedIpsInUse, true + return o.RamProvisioned, true } -// SetReservedIpsInUse sets field value -func (o *ResourceLimits) SetReservedIpsInUse(v int32) { +// SetRamProvisioned sets field value +func (o *ResourceLimits) SetRamProvisioned(v int32) { - o.ReservedIpsInUse = &v + o.RamProvisioned = &v } -// HasReservedIpsInUse returns a boolean if a field has been set. -func (o *ResourceLimits) HasReservedIpsInUse() bool { - if o != nil && o.ReservedIpsInUse != nil { +// HasRamProvisioned returns a boolean if a field has been set. +func (o *ResourceLimits) HasRamProvisioned() bool { + if o != nil && o.RamProvisioned != nil { return true } return false } -// GetK8sClusterLimitTotal returns the K8sClusterLimitTotal field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ResourceLimits) GetK8sClusterLimitTotal() *int32 { +// GetReservableIps returns the ReservableIps field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetReservableIps() *int32 { if o == nil { return nil } - return o.K8sClusterLimitTotal + return o.ReservableIps } -// GetK8sClusterLimitTotalOk returns a tuple with the K8sClusterLimitTotal field value +// GetReservableIpsOk returns a tuple with the ReservableIps field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetK8sClusterLimitTotalOk() (*int32, bool) { +func (o *ResourceLimits) GetReservableIpsOk() (*int32, bool) { if o == nil { return nil, false } - return o.K8sClusterLimitTotal, true + return o.ReservableIps, true } -// SetK8sClusterLimitTotal sets field value -func (o *ResourceLimits) SetK8sClusterLimitTotal(v int32) { +// SetReservableIps sets field value +func (o *ResourceLimits) SetReservableIps(v int32) { - o.K8sClusterLimitTotal = &v + o.ReservableIps = &v } -// HasK8sClusterLimitTotal returns a boolean if a field has been set. -func (o *ResourceLimits) HasK8sClusterLimitTotal() bool { - if o != nil && o.K8sClusterLimitTotal != nil { +// HasReservableIps returns a boolean if a field has been set. +func (o *ResourceLimits) HasReservableIps() bool { + if o != nil && o.ReservableIps != nil { return true } return false } -// GetK8sClustersProvisioned returns the K8sClustersProvisioned field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ResourceLimits) GetK8sClustersProvisioned() *int32 { +// GetReservedIpsInUse returns the ReservedIpsInUse field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetReservedIpsInUse() *int32 { if o == nil { return nil } - return o.K8sClustersProvisioned + return o.ReservedIpsInUse } -// GetK8sClustersProvisionedOk returns a tuple with the K8sClustersProvisioned field value +// GetReservedIpsInUseOk returns a tuple with the ReservedIpsInUse field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetK8sClustersProvisionedOk() (*int32, bool) { +func (o *ResourceLimits) GetReservedIpsInUseOk() (*int32, bool) { if o == nil { return nil, false } - return o.K8sClustersProvisioned, true + return o.ReservedIpsInUse, true } -// SetK8sClustersProvisioned sets field value -func (o *ResourceLimits) SetK8sClustersProvisioned(v int32) { +// SetReservedIpsInUse sets field value +func (o *ResourceLimits) SetReservedIpsInUse(v int32) { - o.K8sClustersProvisioned = &v + o.ReservedIpsInUse = &v } -// HasK8sClustersProvisioned returns a boolean if a field has been set. -func (o *ResourceLimits) HasK8sClustersProvisioned() bool { - if o != nil && o.K8sClustersProvisioned != nil { +// HasReservedIpsInUse returns a boolean if a field has been set. +func (o *ResourceLimits) HasReservedIpsInUse() bool { + if o != nil && o.ReservedIpsInUse != nil { return true } return false } -// GetNlbLimitTotal returns the NlbLimitTotal field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ResourceLimits) GetNlbLimitTotal() *int32 { +// GetReservedIpsOnContract returns the ReservedIpsOnContract field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetReservedIpsOnContract() *int32 { if o == nil { return nil } - return o.NlbLimitTotal + return o.ReservedIpsOnContract } -// GetNlbLimitTotalOk returns a tuple with the NlbLimitTotal field value +// GetReservedIpsOnContractOk returns a tuple with the ReservedIpsOnContract field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetNlbLimitTotalOk() (*int32, bool) { +func (o *ResourceLimits) GetReservedIpsOnContractOk() (*int32, bool) { if o == nil { return nil, false } - return o.NlbLimitTotal, true + return o.ReservedIpsOnContract, true } -// SetNlbLimitTotal sets field value -func (o *ResourceLimits) SetNlbLimitTotal(v int32) { +// SetReservedIpsOnContract sets field value +func (o *ResourceLimits) SetReservedIpsOnContract(v int32) { - o.NlbLimitTotal = &v + o.ReservedIpsOnContract = &v } -// HasNlbLimitTotal returns a boolean if a field has been set. -func (o *ResourceLimits) HasNlbLimitTotal() bool { - if o != nil && o.NlbLimitTotal != nil { +// HasReservedIpsOnContract returns a boolean if a field has been set. +func (o *ResourceLimits) HasReservedIpsOnContract() bool { + if o != nil && o.ReservedIpsOnContract != nil { return true } return false } -// GetNlbProvisioned returns the NlbProvisioned field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ResourceLimits) GetNlbProvisioned() *int32 { +// GetSsdLimitPerContract returns the SsdLimitPerContract field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetSsdLimitPerContract() *int64 { if o == nil { return nil } - return o.NlbProvisioned + return o.SsdLimitPerContract } -// GetNlbProvisionedOk returns a tuple with the NlbProvisioned field value +// GetSsdLimitPerContractOk returns a tuple with the SsdLimitPerContract field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetNlbProvisionedOk() (*int32, bool) { +func (o *ResourceLimits) GetSsdLimitPerContractOk() (*int64, bool) { if o == nil { return nil, false } - return o.NlbProvisioned, true + return o.SsdLimitPerContract, true } -// SetNlbProvisioned sets field value -func (o *ResourceLimits) SetNlbProvisioned(v int32) { +// SetSsdLimitPerContract sets field value +func (o *ResourceLimits) SetSsdLimitPerContract(v int64) { - o.NlbProvisioned = &v + o.SsdLimitPerContract = &v } -// HasNlbProvisioned returns a boolean if a field has been set. -func (o *ResourceLimits) HasNlbProvisioned() bool { - if o != nil && o.NlbProvisioned != nil { +// HasSsdLimitPerContract returns a boolean if a field has been set. +func (o *ResourceLimits) HasSsdLimitPerContract() bool { + if o != nil && o.SsdLimitPerContract != nil { return true } return false } -// GetNatGatewayLimitTotal returns the NatGatewayLimitTotal field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ResourceLimits) GetNatGatewayLimitTotal() *int32 { +// GetSsdLimitPerVolume returns the SsdLimitPerVolume field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetSsdLimitPerVolume() *int64 { if o == nil { return nil } - return o.NatGatewayLimitTotal + return o.SsdLimitPerVolume } -// GetNatGatewayLimitTotalOk returns a tuple with the NatGatewayLimitTotal field value +// GetSsdLimitPerVolumeOk returns a tuple with the SsdLimitPerVolume field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetNatGatewayLimitTotalOk() (*int32, bool) { +func (o *ResourceLimits) GetSsdLimitPerVolumeOk() (*int64, bool) { if o == nil { return nil, false } - return o.NatGatewayLimitTotal, true + return o.SsdLimitPerVolume, true } -// SetNatGatewayLimitTotal sets field value -func (o *ResourceLimits) SetNatGatewayLimitTotal(v int32) { +// SetSsdLimitPerVolume sets field value +func (o *ResourceLimits) SetSsdLimitPerVolume(v int64) { - o.NatGatewayLimitTotal = &v + o.SsdLimitPerVolume = &v } -// HasNatGatewayLimitTotal returns a boolean if a field has been set. -func (o *ResourceLimits) HasNatGatewayLimitTotal() bool { - if o != nil && o.NatGatewayLimitTotal != nil { +// HasSsdLimitPerVolume returns a boolean if a field has been set. +func (o *ResourceLimits) HasSsdLimitPerVolume() bool { + if o != nil && o.SsdLimitPerVolume != nil { return true } return false } -// GetNatGatewayProvisioned returns the NatGatewayProvisioned field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ResourceLimits) GetNatGatewayProvisioned() *int32 { +// GetSsdVolumeProvisioned returns the SsdVolumeProvisioned field value +// If the value is explicit nil, nil is returned +func (o *ResourceLimits) GetSsdVolumeProvisioned() *int64 { if o == nil { return nil } - return o.NatGatewayProvisioned + return o.SsdVolumeProvisioned } -// GetNatGatewayProvisionedOk returns a tuple with the NatGatewayProvisioned field value +// GetSsdVolumeProvisionedOk returns a tuple with the SsdVolumeProvisioned field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceLimits) GetNatGatewayProvisionedOk() (*int32, bool) { +func (o *ResourceLimits) GetSsdVolumeProvisionedOk() (*int64, bool) { if o == nil { return nil, false } - return o.NatGatewayProvisioned, true + return o.SsdVolumeProvisioned, true } -// SetNatGatewayProvisioned sets field value -func (o *ResourceLimits) SetNatGatewayProvisioned(v int32) { +// SetSsdVolumeProvisioned sets field value +func (o *ResourceLimits) SetSsdVolumeProvisioned(v int64) { - o.NatGatewayProvisioned = &v + o.SsdVolumeProvisioned = &v } -// HasNatGatewayProvisioned returns a boolean if a field has been set. -func (o *ResourceLimits) HasNatGatewayProvisioned() bool { - if o != nil && o.NatGatewayProvisioned != nil { +// HasSsdVolumeProvisioned returns a boolean if a field has been set. +func (o *ResourceLimits) HasSsdVolumeProvisioned() bool { + if o != nil && o.SsdVolumeProvisioned != nil { return true } @@ -941,72 +941,94 @@ func (o *ResourceLimits) HasNatGatewayProvisioned() bool { func (o ResourceLimits) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.CoresPerServer != nil { - toSerialize["coresPerServer"] = o.CoresPerServer - } if o.CoresPerContract != nil { toSerialize["coresPerContract"] = o.CoresPerContract } + + if o.CoresPerServer != nil { + toSerialize["coresPerServer"] = o.CoresPerServer + } + if o.CoresProvisioned != nil { toSerialize["coresProvisioned"] = o.CoresProvisioned } - if o.RamPerServer != nil { - toSerialize["ramPerServer"] = o.RamPerServer - } - if o.RamPerContract != nil { - toSerialize["ramPerContract"] = o.RamPerContract + + if o.DasVolumeProvisioned != nil { + toSerialize["dasVolumeProvisioned"] = o.DasVolumeProvisioned } - if o.RamProvisioned != nil { - toSerialize["ramProvisioned"] = o.RamProvisioned + + if o.HddLimitPerContract != nil { + toSerialize["hddLimitPerContract"] = o.HddLimitPerContract } + if o.HddLimitPerVolume != nil { toSerialize["hddLimitPerVolume"] = o.HddLimitPerVolume } - if o.HddLimitPerContract != nil { - toSerialize["hddLimitPerContract"] = o.HddLimitPerContract - } + if o.HddVolumeProvisioned != nil { toSerialize["hddVolumeProvisioned"] = o.HddVolumeProvisioned } - if o.SsdLimitPerVolume != nil { - toSerialize["ssdLimitPerVolume"] = o.SsdLimitPerVolume - } - if o.SsdLimitPerContract != nil { - toSerialize["ssdLimitPerContract"] = o.SsdLimitPerContract - } - if o.SsdVolumeProvisioned != nil { - toSerialize["ssdVolumeProvisioned"] = o.SsdVolumeProvisioned - } - if o.DasVolumeProvisioned != nil { - toSerialize["dasVolumeProvisioned"] = o.DasVolumeProvisioned - } - if o.ReservableIps != nil { - toSerialize["reservableIps"] = o.ReservableIps - } - if o.ReservedIpsOnContract != nil { - toSerialize["reservedIpsOnContract"] = o.ReservedIpsOnContract - } - if o.ReservedIpsInUse != nil { - toSerialize["reservedIpsInUse"] = o.ReservedIpsInUse - } + if o.K8sClusterLimitTotal != nil { toSerialize["k8sClusterLimitTotal"] = o.K8sClusterLimitTotal } + if o.K8sClustersProvisioned != nil { toSerialize["k8sClustersProvisioned"] = o.K8sClustersProvisioned } + + if o.NatGatewayLimitTotal != nil { + toSerialize["natGatewayLimitTotal"] = o.NatGatewayLimitTotal + } + + if o.NatGatewayProvisioned != nil { + toSerialize["natGatewayProvisioned"] = o.NatGatewayProvisioned + } + if o.NlbLimitTotal != nil { toSerialize["nlbLimitTotal"] = o.NlbLimitTotal } + if o.NlbProvisioned != nil { toSerialize["nlbProvisioned"] = o.NlbProvisioned } - if o.NatGatewayLimitTotal != nil { - toSerialize["natGatewayLimitTotal"] = o.NatGatewayLimitTotal + + if o.RamPerContract != nil { + toSerialize["ramPerContract"] = o.RamPerContract } - if o.NatGatewayProvisioned != nil { - toSerialize["natGatewayProvisioned"] = o.NatGatewayProvisioned + + if o.RamPerServer != nil { + toSerialize["ramPerServer"] = o.RamPerServer } + + if o.RamProvisioned != nil { + toSerialize["ramProvisioned"] = o.RamProvisioned + } + + if o.ReservableIps != nil { + toSerialize["reservableIps"] = o.ReservableIps + } + + if o.ReservedIpsInUse != nil { + toSerialize["reservedIpsInUse"] = o.ReservedIpsInUse + } + + if o.ReservedIpsOnContract != nil { + toSerialize["reservedIpsOnContract"] = o.ReservedIpsOnContract + } + + if o.SsdLimitPerContract != nil { + toSerialize["ssdLimitPerContract"] = o.SsdLimitPerContract + } + + if o.SsdLimitPerVolume != nil { + toSerialize["ssdLimitPerVolume"] = o.SsdLimitPerVolume + } + + if o.SsdVolumeProvisioned != nil { + toSerialize["ssdVolumeProvisioned"] = o.SsdVolumeProvisioned + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_properties.go index b5b274a28eb..224350ec56c 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_properties.go @@ -41,7 +41,7 @@ func NewResourcePropertiesWithDefaults() *ResourceProperties { } // GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *ResourceProperties) GetName() *string { if o == nil { return nil @@ -79,7 +79,7 @@ func (o *ResourceProperties) HasName() bool { } // GetSecAuthProtection returns the SecAuthProtection field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *ResourceProperties) GetSecAuthProtection() *bool { if o == nil { return nil @@ -121,9 +121,11 @@ func (o ResourceProperties) MarshalJSON() ([]byte, error) { if o.Name != nil { toSerialize["name"] = o.Name } + if o.SecAuthProtection != nil { toSerialize["secAuthProtection"] = o.SecAuthProtection } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_reference.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_reference.go index 5732ab57016..6b58f76a354 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_reference.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resource_reference.go @@ -16,12 +16,12 @@ import ( // ResourceReference struct for ResourceReference type ResourceReference struct { + // URL to the object representation (absolute path). + Href *string `json:"href,omitempty"` // The resource's unique identifier. Id *string `json:"id"` // The type of object that has been created. Type *Type `json:"type,omitempty"` - // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` } // NewResourceReference instantiates a new ResourceReference object @@ -44,114 +44,114 @@ func NewResourceReferenceWithDefaults() *ResourceReference { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ResourceReference) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *ResourceReference) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceReference) GetIdOk() (*string, bool) { +func (o *ResourceReference) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *ResourceReference) SetId(v string) { +// SetHref sets field value +func (o *ResourceReference) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *ResourceReference) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *ResourceReference) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *ResourceReference) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *ResourceReference) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceReference) GetTypeOk() (*Type, bool) { +func (o *ResourceReference) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *ResourceReference) SetType(v Type) { +// SetId sets field value +func (o *ResourceReference) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *ResourceReference) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *ResourceReference) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ResourceReference) GetHref() *string { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *ResourceReference) GetType() *Type { if o == nil { return nil } - return o.Href + return o.Type } -// GetHrefOk returns a tuple with the Href field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourceReference) GetHrefOk() (*string, bool) { +func (o *ResourceReference) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Type, true } -// SetHref sets field value -func (o *ResourceReference) SetHref(v string) { +// SetType sets field value +func (o *ResourceReference) SetType(v Type) { - o.Href = &v + o.Type = &v } -// HasHref returns a boolean if a field has been set. -func (o *ResourceReference) HasHref() bool { - if o != nil && o.Href != nil { +// HasType returns a boolean if a field has been set. +func (o *ResourceReference) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -160,15 +160,18 @@ func (o *ResourceReference) HasHref() bool { func (o ResourceReference) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} + if o.Href != nil { + toSerialize["href"] = o.Href + } + if o.Id != nil { toSerialize["id"] = o.Id } + if o.Type != nil { toSerialize["type"] = o.Type } - if o.Href != nil { - toSerialize["href"] = o.Href - } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resources.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resources.go index 36b8beeabff..9db504339fb 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resources.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resources.go @@ -16,14 +16,14 @@ import ( // Resources Collection to represent the resource. type Resources struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of the resource. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Resource `json:"items,omitempty"` + // The type of the resource. + Type *Type `json:"type,omitempty"` } // NewResources instantiates a new Resources object @@ -44,152 +44,152 @@ func NewResourcesWithDefaults() *Resources { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Resources) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Resources) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Resources) GetIdOk() (*string, bool) { +func (o *Resources) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Resources) SetId(v string) { +// SetHref sets field value +func (o *Resources) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Resources) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Resources) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Resources) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Resources) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Resources) GetTypeOk() (*Type, bool) { +func (o *Resources) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Resources) SetType(v Type) { +// SetId sets field value +func (o *Resources) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Resources) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Resources) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Resources) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *Resources) GetItems() *[]Resource { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Resources) GetHrefOk() (*string, bool) { +func (o *Resources) GetItemsOk() (*[]Resource, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *Resources) SetHref(v string) { +// SetItems sets field value +func (o *Resources) SetItems(v []Resource) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *Resources) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *Resources) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Resource will be returned -func (o *Resources) GetItems() *[]Resource { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Resources) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Resources) GetItemsOk() (*[]Resource, bool) { +func (o *Resources) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *Resources) SetItems(v []Resource) { +// SetType sets field value +func (o *Resources) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *Resources) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *Resources) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *Resources) HasItems() bool { func (o Resources) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resources_users.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resources_users.go index 18de5cf52d4..e8772006c89 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_resources_users.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_resources_users.go @@ -16,14 +16,14 @@ import ( // ResourcesUsers Resources owned by a user. type ResourcesUsers struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of the resource. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Resource `json:"items,omitempty"` + // The type of the resource. + Type *Type `json:"type,omitempty"` } // NewResourcesUsers instantiates a new ResourcesUsers object @@ -44,152 +44,152 @@ func NewResourcesUsersWithDefaults() *ResourcesUsers { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ResourcesUsers) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *ResourcesUsers) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourcesUsers) GetIdOk() (*string, bool) { +func (o *ResourcesUsers) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *ResourcesUsers) SetId(v string) { +// SetHref sets field value +func (o *ResourcesUsers) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *ResourcesUsers) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *ResourcesUsers) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *ResourcesUsers) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *ResourcesUsers) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourcesUsers) GetTypeOk() (*Type, bool) { +func (o *ResourcesUsers) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *ResourcesUsers) SetType(v Type) { +// SetId sets field value +func (o *ResourcesUsers) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *ResourcesUsers) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *ResourcesUsers) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ResourcesUsers) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *ResourcesUsers) GetItems() *[]Resource { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourcesUsers) GetHrefOk() (*string, bool) { +func (o *ResourcesUsers) GetItemsOk() (*[]Resource, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *ResourcesUsers) SetHref(v string) { +// SetItems sets field value +func (o *ResourcesUsers) SetItems(v []Resource) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *ResourcesUsers) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *ResourcesUsers) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Resource will be returned -func (o *ResourcesUsers) GetItems() *[]Resource { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *ResourcesUsers) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ResourcesUsers) GetItemsOk() (*[]Resource, bool) { +func (o *ResourcesUsers) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *ResourcesUsers) SetItems(v []Resource) { +// SetType sets field value +func (o *ResourcesUsers) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *ResourcesUsers) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *ResourcesUsers) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *ResourcesUsers) HasItems() bool { func (o ResourcesUsers) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_bucket.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_bucket.go index bede8466735..5e263873ce6 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_bucket.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_bucket.go @@ -41,7 +41,7 @@ func NewS3BucketWithDefaults() *S3Bucket { } // GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *S3Bucket) GetName() *string { if o == nil { return nil @@ -83,6 +83,7 @@ func (o S3Bucket) MarshalJSON() ([]byte, error) { if o.Name != nil { toSerialize["name"] = o.Name } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_key.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_key.go index 5febf4192a4..ae9f00908b8 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_key.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_key.go @@ -16,14 +16,14 @@ import ( // S3Key struct for S3Key type S3Key struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of the resource. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *S3KeyMetadata `json:"metadata,omitempty"` Properties *S3KeyProperties `json:"properties"` + // The type of the resource. + Type *Type `json:"type,omitempty"` } // NewS3Key instantiates a new S3Key object @@ -46,190 +46,190 @@ func NewS3KeyWithDefaults() *S3Key { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *S3Key) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *S3Key) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *S3Key) GetIdOk() (*string, bool) { +func (o *S3Key) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *S3Key) SetId(v string) { +// SetHref sets field value +func (o *S3Key) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *S3Key) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *S3Key) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *S3Key) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *S3Key) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *S3Key) GetTypeOk() (*Type, bool) { +func (o *S3Key) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *S3Key) SetType(v Type) { +// SetId sets field value +func (o *S3Key) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *S3Key) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *S3Key) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *S3Key) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *S3Key) GetMetadata() *S3KeyMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *S3Key) GetHrefOk() (*string, bool) { +func (o *S3Key) GetMetadataOk() (*S3KeyMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *S3Key) SetHref(v string) { +// SetMetadata sets field value +func (o *S3Key) SetMetadata(v S3KeyMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *S3Key) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *S3Key) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for S3KeyMetadata will be returned -func (o *S3Key) GetMetadata() *S3KeyMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *S3Key) GetProperties() *S3KeyProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *S3Key) GetMetadataOk() (*S3KeyMetadata, bool) { +func (o *S3Key) GetPropertiesOk() (*S3KeyProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *S3Key) SetMetadata(v S3KeyMetadata) { +// SetProperties sets field value +func (o *S3Key) SetProperties(v S3KeyProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *S3Key) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *S3Key) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for S3KeyProperties will be returned -func (o *S3Key) GetProperties() *S3KeyProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *S3Key) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *S3Key) GetPropertiesOk() (*S3KeyProperties, bool) { +func (o *S3Key) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *S3Key) SetProperties(v S3KeyProperties) { +// SetType sets field value +func (o *S3Key) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *S3Key) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *S3Key) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *S3Key) HasProperties() bool { func (o S3Key) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_key_metadata.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_key_metadata.go index 83ecc8b4638..f090555e7d8 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_key_metadata.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_key_metadata.go @@ -17,10 +17,10 @@ import ( // S3KeyMetadata struct for S3KeyMetadata type S3KeyMetadata struct { - // Resource's Entity Tag as defined in http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11 Entity Tag is also added as an 'ETag response header to requests which don't use 'depth' parameter. - Etag *string `json:"etag,omitempty"` // The time when the S3 key was created. CreatedDate *IonosTime + // Resource's Entity Tag as defined in http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11 Entity Tag is also added as an 'ETag response header to requests which don't use 'depth' parameter. + Etag *string `json:"etag,omitempty"` } // NewS3KeyMetadata instantiates a new S3KeyMetadata object @@ -41,83 +41,83 @@ func NewS3KeyMetadataWithDefaults() *S3KeyMetadata { return &this } -// GetEtag returns the Etag field value -// If the value is explicit nil, the zero value for string will be returned -func (o *S3KeyMetadata) GetEtag() *string { +// GetCreatedDate returns the CreatedDate field value +// If the value is explicit nil, nil is returned +func (o *S3KeyMetadata) GetCreatedDate() *time.Time { if o == nil { return nil } - return o.Etag + if o.CreatedDate == nil { + return nil + } + return &o.CreatedDate.Time } -// GetEtagOk returns a tuple with the Etag field value +// GetCreatedDateOk returns a tuple with the CreatedDate field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *S3KeyMetadata) GetEtagOk() (*string, bool) { +func (o *S3KeyMetadata) GetCreatedDateOk() (*time.Time, bool) { if o == nil { return nil, false } - return o.Etag, true + if o.CreatedDate == nil { + return nil, false + } + return &o.CreatedDate.Time, true + } -// SetEtag sets field value -func (o *S3KeyMetadata) SetEtag(v string) { +// SetCreatedDate sets field value +func (o *S3KeyMetadata) SetCreatedDate(v time.Time) { - o.Etag = &v + o.CreatedDate = &IonosTime{v} } -// HasEtag returns a boolean if a field has been set. -func (o *S3KeyMetadata) HasEtag() bool { - if o != nil && o.Etag != nil { +// HasCreatedDate returns a boolean if a field has been set. +func (o *S3KeyMetadata) HasCreatedDate() bool { + if o != nil && o.CreatedDate != nil { return true } return false } -// GetCreatedDate returns the CreatedDate field value -// If the value is explicit nil, the zero value for time.Time will be returned -func (o *S3KeyMetadata) GetCreatedDate() *time.Time { +// GetEtag returns the Etag field value +// If the value is explicit nil, nil is returned +func (o *S3KeyMetadata) GetEtag() *string { if o == nil { return nil } - if o.CreatedDate == nil { - return nil - } - return &o.CreatedDate.Time + return o.Etag } -// GetCreatedDateOk returns a tuple with the CreatedDate field value +// GetEtagOk returns a tuple with the Etag field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *S3KeyMetadata) GetCreatedDateOk() (*time.Time, bool) { +func (o *S3KeyMetadata) GetEtagOk() (*string, bool) { if o == nil { return nil, false } - if o.CreatedDate == nil { - return nil, false - } - return &o.CreatedDate.Time, true - + return o.Etag, true } -// SetCreatedDate sets field value -func (o *S3KeyMetadata) SetCreatedDate(v time.Time) { +// SetEtag sets field value +func (o *S3KeyMetadata) SetEtag(v string) { - o.CreatedDate = &IonosTime{v} + o.Etag = &v } -// HasCreatedDate returns a boolean if a field has been set. -func (o *S3KeyMetadata) HasCreatedDate() bool { - if o != nil && o.CreatedDate != nil { +// HasEtag returns a boolean if a field has been set. +func (o *S3KeyMetadata) HasEtag() bool { + if o != nil && o.Etag != nil { return true } @@ -126,12 +126,14 @@ func (o *S3KeyMetadata) HasCreatedDate() bool { func (o S3KeyMetadata) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Etag != nil { - toSerialize["etag"] = o.Etag - } if o.CreatedDate != nil { toSerialize["createdDate"] = o.CreatedDate } + + if o.Etag != nil { + toSerialize["etag"] = o.Etag + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_key_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_key_properties.go index a3204d717c3..0cf12e77116 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_key_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_key_properties.go @@ -16,10 +16,10 @@ import ( // S3KeyProperties struct for S3KeyProperties type S3KeyProperties struct { - // Secret of the S3 key. - SecretKey *string `json:"secretKey,omitempty"` // Denotes weather the S3 key is active. Active *bool `json:"active,omitempty"` + // Secret of the S3 key. + SecretKey *string `json:"secretKey,omitempty"` } // NewS3KeyProperties instantiates a new S3KeyProperties object @@ -40,76 +40,76 @@ func NewS3KeyPropertiesWithDefaults() *S3KeyProperties { return &this } -// GetSecretKey returns the SecretKey field value -// If the value is explicit nil, the zero value for string will be returned -func (o *S3KeyProperties) GetSecretKey() *string { +// GetActive returns the Active field value +// If the value is explicit nil, nil is returned +func (o *S3KeyProperties) GetActive() *bool { if o == nil { return nil } - return o.SecretKey + return o.Active } -// GetSecretKeyOk returns a tuple with the SecretKey field value +// GetActiveOk returns a tuple with the Active field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *S3KeyProperties) GetSecretKeyOk() (*string, bool) { +func (o *S3KeyProperties) GetActiveOk() (*bool, bool) { if o == nil { return nil, false } - return o.SecretKey, true + return o.Active, true } -// SetSecretKey sets field value -func (o *S3KeyProperties) SetSecretKey(v string) { +// SetActive sets field value +func (o *S3KeyProperties) SetActive(v bool) { - o.SecretKey = &v + o.Active = &v } -// HasSecretKey returns a boolean if a field has been set. -func (o *S3KeyProperties) HasSecretKey() bool { - if o != nil && o.SecretKey != nil { +// HasActive returns a boolean if a field has been set. +func (o *S3KeyProperties) HasActive() bool { + if o != nil && o.Active != nil { return true } return false } -// GetActive returns the Active field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *S3KeyProperties) GetActive() *bool { +// GetSecretKey returns the SecretKey field value +// If the value is explicit nil, nil is returned +func (o *S3KeyProperties) GetSecretKey() *string { if o == nil { return nil } - return o.Active + return o.SecretKey } -// GetActiveOk returns a tuple with the Active field value +// GetSecretKeyOk returns a tuple with the SecretKey field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *S3KeyProperties) GetActiveOk() (*bool, bool) { +func (o *S3KeyProperties) GetSecretKeyOk() (*string, bool) { if o == nil { return nil, false } - return o.Active, true + return o.SecretKey, true } -// SetActive sets field value -func (o *S3KeyProperties) SetActive(v bool) { +// SetSecretKey sets field value +func (o *S3KeyProperties) SetSecretKey(v string) { - o.Active = &v + o.SecretKey = &v } -// HasActive returns a boolean if a field has been set. -func (o *S3KeyProperties) HasActive() bool { - if o != nil && o.Active != nil { +// HasSecretKey returns a boolean if a field has been set. +func (o *S3KeyProperties) HasSecretKey() bool { + if o != nil && o.SecretKey != nil { return true } @@ -118,12 +118,14 @@ func (o *S3KeyProperties) HasActive() bool { func (o S3KeyProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.SecretKey != nil { - toSerialize["secretKey"] = o.SecretKey - } if o.Active != nil { toSerialize["active"] = o.Active } + + if o.SecretKey != nil { + toSerialize["secretKey"] = o.SecretKey + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_keys.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_keys.go index a87bc2f76ac..d0ed78cc64b 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_keys.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_keys.go @@ -16,14 +16,14 @@ import ( // S3Keys struct for S3Keys type S3Keys struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of the resource. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]S3Key `json:"items,omitempty"` + // The type of the resource. + Type *Type `json:"type,omitempty"` } // NewS3Keys instantiates a new S3Keys object @@ -44,152 +44,152 @@ func NewS3KeysWithDefaults() *S3Keys { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *S3Keys) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *S3Keys) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *S3Keys) GetIdOk() (*string, bool) { +func (o *S3Keys) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *S3Keys) SetId(v string) { +// SetHref sets field value +func (o *S3Keys) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *S3Keys) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *S3Keys) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *S3Keys) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *S3Keys) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *S3Keys) GetTypeOk() (*Type, bool) { +func (o *S3Keys) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *S3Keys) SetType(v Type) { +// SetId sets field value +func (o *S3Keys) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *S3Keys) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *S3Keys) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *S3Keys) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *S3Keys) GetItems() *[]S3Key { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *S3Keys) GetHrefOk() (*string, bool) { +func (o *S3Keys) GetItemsOk() (*[]S3Key, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *S3Keys) SetHref(v string) { +// SetItems sets field value +func (o *S3Keys) SetItems(v []S3Key) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *S3Keys) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *S3Keys) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []S3Key will be returned -func (o *S3Keys) GetItems() *[]S3Key { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *S3Keys) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *S3Keys) GetItemsOk() (*[]S3Key, bool) { +func (o *S3Keys) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *S3Keys) SetItems(v []S3Key) { +// SetType sets field value +func (o *S3Keys) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *S3Keys) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *S3Keys) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *S3Keys) HasItems() bool { func (o S3Keys) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_object_storage_sso.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_object_storage_sso.go index 48eb4b166cb..809410a0487 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_object_storage_sso.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_s3_object_storage_sso.go @@ -39,7 +39,7 @@ func NewS3ObjectStorageSSOWithDefaults() *S3ObjectStorageSSO { } // GetSsoUrl returns the SsoUrl field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *S3ObjectStorageSSO) GetSsoUrl() *string { if o == nil { return nil @@ -81,6 +81,7 @@ func (o S3ObjectStorageSSO) MarshalJSON() ([]byte, error) { if o.SsoUrl != nil { toSerialize["ssoUrl"] = o.SsoUrl } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_server.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_server.go index ad75b98a165..4002c4bda88 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_server.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_server.go @@ -16,15 +16,15 @@ import ( // Server struct for Server type Server struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Entities *ServerEntities `json:"entities,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *ServerProperties `json:"properties"` - Entities *ServerEntities `json:"entities,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewServer instantiates a new Server object @@ -47,114 +47,114 @@ func NewServerWithDefaults() *Server { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Server) GetId() *string { +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *Server) GetEntities() *ServerEntities { if o == nil { return nil } - return o.Id + return o.Entities } -// GetIdOk returns a tuple with the Id field value +// GetEntitiesOk returns a tuple with the Entities field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Server) GetIdOk() (*string, bool) { +func (o *Server) GetEntitiesOk() (*ServerEntities, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Entities, true } -// SetId sets field value -func (o *Server) SetId(v string) { +// SetEntities sets field value +func (o *Server) SetEntities(v ServerEntities) { - o.Id = &v + o.Entities = &v } -// HasId returns a boolean if a field has been set. -func (o *Server) HasId() bool { - if o != nil && o.Id != nil { +// HasEntities returns a boolean if a field has been set. +func (o *Server) HasEntities() bool { + if o != nil && o.Entities != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Server) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Server) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Server) GetTypeOk() (*Type, bool) { +func (o *Server) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Server) SetType(v Type) { +// SetHref sets field value +func (o *Server) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Server) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Server) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Server) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Server) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Server) GetHrefOk() (*string, bool) { +func (o *Server) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Server) SetHref(v string) { +// SetId sets field value +func (o *Server) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Server) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Server) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -162,7 +162,7 @@ func (o *Server) HasHref() bool { } // GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned +// If the value is explicit nil, nil is returned func (o *Server) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil @@ -200,7 +200,7 @@ func (o *Server) HasMetadata() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for ServerProperties will be returned +// If the value is explicit nil, nil is returned func (o *Server) GetProperties() *ServerProperties { if o == nil { return nil @@ -237,38 +237,38 @@ func (o *Server) HasProperties() bool { return false } -// GetEntities returns the Entities field value -// If the value is explicit nil, the zero value for ServerEntities will be returned -func (o *Server) GetEntities() *ServerEntities { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Server) GetType() *Type { if o == nil { return nil } - return o.Entities + return o.Type } -// GetEntitiesOk returns a tuple with the Entities field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Server) GetEntitiesOk() (*ServerEntities, bool) { +func (o *Server) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Entities, true + return o.Type, true } -// SetEntities sets field value -func (o *Server) SetEntities(v ServerEntities) { +// SetType sets field value +func (o *Server) SetType(v Type) { - o.Entities = &v + o.Type = &v } -// HasEntities returns a boolean if a field has been set. -func (o *Server) HasEntities() bool { - if o != nil && o.Entities != nil { +// HasType returns a boolean if a field has been set. +func (o *Server) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -277,24 +277,30 @@ func (o *Server) HasEntities() bool { func (o Server) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Entities != nil { + toSerialize["entities"] = o.Entities } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } - if o.Entities != nil { - toSerialize["entities"] = o.Entities + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_server_entities.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_server_entities.go index fcb42fdb285..a2a8b8912d3 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_server_entities.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_server_entities.go @@ -17,8 +17,8 @@ import ( // ServerEntities struct for ServerEntities type ServerEntities struct { Cdroms *Cdroms `json:"cdroms,omitempty"` - Volumes *AttachedVolumes `json:"volumes,omitempty"` Nics *Nics `json:"nics,omitempty"` + Volumes *AttachedVolumes `json:"volumes,omitempty"` } // NewServerEntities instantiates a new ServerEntities object @@ -40,7 +40,7 @@ func NewServerEntitiesWithDefaults() *ServerEntities { } // GetCdroms returns the Cdroms field value -// If the value is explicit nil, the zero value for Cdroms will be returned +// If the value is explicit nil, nil is returned func (o *ServerEntities) GetCdroms() *Cdroms { if o == nil { return nil @@ -77,76 +77,76 @@ func (o *ServerEntities) HasCdroms() bool { return false } -// GetVolumes returns the Volumes field value -// If the value is explicit nil, the zero value for AttachedVolumes will be returned -func (o *ServerEntities) GetVolumes() *AttachedVolumes { +// GetNics returns the Nics field value +// If the value is explicit nil, nil is returned +func (o *ServerEntities) GetNics() *Nics { if o == nil { return nil } - return o.Volumes + return o.Nics } -// GetVolumesOk returns a tuple with the Volumes field value +// GetNicsOk returns a tuple with the Nics field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ServerEntities) GetVolumesOk() (*AttachedVolumes, bool) { +func (o *ServerEntities) GetNicsOk() (*Nics, bool) { if o == nil { return nil, false } - return o.Volumes, true + return o.Nics, true } -// SetVolumes sets field value -func (o *ServerEntities) SetVolumes(v AttachedVolumes) { +// SetNics sets field value +func (o *ServerEntities) SetNics(v Nics) { - o.Volumes = &v + o.Nics = &v } -// HasVolumes returns a boolean if a field has been set. -func (o *ServerEntities) HasVolumes() bool { - if o != nil && o.Volumes != nil { +// HasNics returns a boolean if a field has been set. +func (o *ServerEntities) HasNics() bool { + if o != nil && o.Nics != nil { return true } return false } -// GetNics returns the Nics field value -// If the value is explicit nil, the zero value for Nics will be returned -func (o *ServerEntities) GetNics() *Nics { +// GetVolumes returns the Volumes field value +// If the value is explicit nil, nil is returned +func (o *ServerEntities) GetVolumes() *AttachedVolumes { if o == nil { return nil } - return o.Nics + return o.Volumes } -// GetNicsOk returns a tuple with the Nics field value +// GetVolumesOk returns a tuple with the Volumes field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ServerEntities) GetNicsOk() (*Nics, bool) { +func (o *ServerEntities) GetVolumesOk() (*AttachedVolumes, bool) { if o == nil { return nil, false } - return o.Nics, true + return o.Volumes, true } -// SetNics sets field value -func (o *ServerEntities) SetNics(v Nics) { +// SetVolumes sets field value +func (o *ServerEntities) SetVolumes(v AttachedVolumes) { - o.Nics = &v + o.Volumes = &v } -// HasNics returns a boolean if a field has been set. -func (o *ServerEntities) HasNics() bool { - if o != nil && o.Nics != nil { +// HasVolumes returns a boolean if a field has been set. +func (o *ServerEntities) HasVolumes() bool { + if o != nil && o.Volumes != nil { return true } @@ -158,12 +158,15 @@ func (o ServerEntities) MarshalJSON() ([]byte, error) { if o.Cdroms != nil { toSerialize["cdroms"] = o.Cdroms } - if o.Volumes != nil { - toSerialize["volumes"] = o.Volumes - } + if o.Nics != nil { toSerialize["nics"] = o.Nics } + + if o.Volumes != nil { + toSerialize["volumes"] = o.Volumes + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_server_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_server_properties.go index 4f292cde92e..5b81d95518d 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_server_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_server_properties.go @@ -16,24 +16,26 @@ import ( // ServerProperties struct for ServerProperties type ServerProperties struct { - // The ID of the template for creating a CUBE server; the available templates for CUBE servers can be found on the templates resource. - TemplateUuid *string `json:"templateUuid,omitempty"` - // The name of the resource. - Name *string `json:"name,omitempty"` + // The availability zone in which the server should be provisioned. + AvailabilityZone *string `json:"availabilityZone,omitempty"` + BootCdrom *ResourceReference `json:"bootCdrom,omitempty"` + BootVolume *ResourceReference `json:"bootVolume,omitempty"` // The total number of cores for the enterprise server. Cores *int32 `json:"cores,omitempty"` - // The memory size for the enterprise server in MB, such as 2048. Size must be specified in multiples of 256 MB with a minimum of 256 MB; however, if you set ramHotPlug to TRUE then you must use a minimum of 1024 MB. If you set the RAM size more than 240GB, then ramHotPlug will be set to FALSE and can not be set to TRUE unless RAM size not set to less than 240GB. - Ram *int32 `json:"ram,omitempty"` - // The availability zone in which the server should be provisioned. - AvailabilityZone *string `json:"availabilityZone,omitempty"` - // Status of the virtual machine. - VmState *string `json:"vmState,omitempty"` - BootCdrom *ResourceReference `json:"bootCdrom,omitempty"` - BootVolume *ResourceReference `json:"bootVolume,omitempty"` // CPU architecture on which server gets provisioned; not all CPU architectures are available in all datacenter regions; available CPU architectures can be retrieved from the datacenter resource; must not be provided for CUBE servers. CpuFamily *string `json:"cpuFamily,omitempty"` - // Server type. + // The name of the resource. + Name *string `json:"name,omitempty"` + // The placement group ID that belongs to this server; Requires system privileges + PlacementGroupId *string `json:"placementGroupId,omitempty"` + // The memory size for the enterprise server in MB, such as 2048. Size must be specified in multiples of 256 MB with a minimum of 256 MB; however, if you set ramHotPlug to TRUE then you must use a minimum of 1024 MB. If you set the RAM size more than 240GB, then ramHotPlug will be set to FALSE and can not be set to TRUE unless RAM size not set to less than 240GB. + Ram *int32 `json:"ram,omitempty"` + // The ID of the template for creating a CUBE server; the available templates for CUBE servers can be found on the templates resource. + TemplateUuid *string `json:"templateUuid,omitempty"` + // Server type: CUBE or ENTERPRISE. Type *string `json:"type,omitempty"` + // Status of the virtual machine. + VmState *string `json:"vmState,omitempty"` } // NewServerProperties instantiates a new ServerProperties object @@ -54,342 +56,342 @@ func NewServerPropertiesWithDefaults() *ServerProperties { return &this } -// GetTemplateUuid returns the TemplateUuid field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ServerProperties) GetTemplateUuid() *string { +// GetAvailabilityZone returns the AvailabilityZone field value +// If the value is explicit nil, nil is returned +func (o *ServerProperties) GetAvailabilityZone() *string { if o == nil { return nil } - return o.TemplateUuid + return o.AvailabilityZone } -// GetTemplateUuidOk returns a tuple with the TemplateUuid field value +// GetAvailabilityZoneOk returns a tuple with the AvailabilityZone field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ServerProperties) GetTemplateUuidOk() (*string, bool) { +func (o *ServerProperties) GetAvailabilityZoneOk() (*string, bool) { if o == nil { return nil, false } - return o.TemplateUuid, true + return o.AvailabilityZone, true } -// SetTemplateUuid sets field value -func (o *ServerProperties) SetTemplateUuid(v string) { +// SetAvailabilityZone sets field value +func (o *ServerProperties) SetAvailabilityZone(v string) { - o.TemplateUuid = &v + o.AvailabilityZone = &v } -// HasTemplateUuid returns a boolean if a field has been set. -func (o *ServerProperties) HasTemplateUuid() bool { - if o != nil && o.TemplateUuid != nil { +// HasAvailabilityZone returns a boolean if a field has been set. +func (o *ServerProperties) HasAvailabilityZone() bool { + if o != nil && o.AvailabilityZone != nil { return true } return false } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ServerProperties) GetName() *string { +// GetBootCdrom returns the BootCdrom field value +// If the value is explicit nil, nil is returned +func (o *ServerProperties) GetBootCdrom() *ResourceReference { if o == nil { return nil } - return o.Name + return o.BootCdrom } -// GetNameOk returns a tuple with the Name field value +// GetBootCdromOk returns a tuple with the BootCdrom field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ServerProperties) GetNameOk() (*string, bool) { +func (o *ServerProperties) GetBootCdromOk() (*ResourceReference, bool) { if o == nil { return nil, false } - return o.Name, true + return o.BootCdrom, true } -// SetName sets field value -func (o *ServerProperties) SetName(v string) { +// SetBootCdrom sets field value +func (o *ServerProperties) SetBootCdrom(v ResourceReference) { - o.Name = &v + o.BootCdrom = &v } -// HasName returns a boolean if a field has been set. -func (o *ServerProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasBootCdrom returns a boolean if a field has been set. +func (o *ServerProperties) HasBootCdrom() bool { + if o != nil && o.BootCdrom != nil { return true } return false } -// GetCores returns the Cores field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ServerProperties) GetCores() *int32 { +// GetBootVolume returns the BootVolume field value +// If the value is explicit nil, nil is returned +func (o *ServerProperties) GetBootVolume() *ResourceReference { if o == nil { return nil } - return o.Cores + return o.BootVolume } -// GetCoresOk returns a tuple with the Cores field value +// GetBootVolumeOk returns a tuple with the BootVolume field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ServerProperties) GetCoresOk() (*int32, bool) { +func (o *ServerProperties) GetBootVolumeOk() (*ResourceReference, bool) { if o == nil { return nil, false } - return o.Cores, true + return o.BootVolume, true } -// SetCores sets field value -func (o *ServerProperties) SetCores(v int32) { +// SetBootVolume sets field value +func (o *ServerProperties) SetBootVolume(v ResourceReference) { - o.Cores = &v + o.BootVolume = &v } -// HasCores returns a boolean if a field has been set. -func (o *ServerProperties) HasCores() bool { - if o != nil && o.Cores != nil { +// HasBootVolume returns a boolean if a field has been set. +func (o *ServerProperties) HasBootVolume() bool { + if o != nil && o.BootVolume != nil { return true } return false } -// GetRam returns the Ram field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *ServerProperties) GetRam() *int32 { +// GetCores returns the Cores field value +// If the value is explicit nil, nil is returned +func (o *ServerProperties) GetCores() *int32 { if o == nil { return nil } - return o.Ram + return o.Cores } -// GetRamOk returns a tuple with the Ram field value +// GetCoresOk returns a tuple with the Cores field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ServerProperties) GetRamOk() (*int32, bool) { +func (o *ServerProperties) GetCoresOk() (*int32, bool) { if o == nil { return nil, false } - return o.Ram, true + return o.Cores, true } -// SetRam sets field value -func (o *ServerProperties) SetRam(v int32) { +// SetCores sets field value +func (o *ServerProperties) SetCores(v int32) { - o.Ram = &v + o.Cores = &v } -// HasRam returns a boolean if a field has been set. -func (o *ServerProperties) HasRam() bool { - if o != nil && o.Ram != nil { +// HasCores returns a boolean if a field has been set. +func (o *ServerProperties) HasCores() bool { + if o != nil && o.Cores != nil { return true } return false } -// GetAvailabilityZone returns the AvailabilityZone field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ServerProperties) GetAvailabilityZone() *string { +// GetCpuFamily returns the CpuFamily field value +// If the value is explicit nil, nil is returned +func (o *ServerProperties) GetCpuFamily() *string { if o == nil { return nil } - return o.AvailabilityZone + return o.CpuFamily } -// GetAvailabilityZoneOk returns a tuple with the AvailabilityZone field value +// GetCpuFamilyOk returns a tuple with the CpuFamily field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ServerProperties) GetAvailabilityZoneOk() (*string, bool) { +func (o *ServerProperties) GetCpuFamilyOk() (*string, bool) { if o == nil { return nil, false } - return o.AvailabilityZone, true + return o.CpuFamily, true } -// SetAvailabilityZone sets field value -func (o *ServerProperties) SetAvailabilityZone(v string) { +// SetCpuFamily sets field value +func (o *ServerProperties) SetCpuFamily(v string) { - o.AvailabilityZone = &v + o.CpuFamily = &v } -// HasAvailabilityZone returns a boolean if a field has been set. -func (o *ServerProperties) HasAvailabilityZone() bool { - if o != nil && o.AvailabilityZone != nil { +// HasCpuFamily returns a boolean if a field has been set. +func (o *ServerProperties) HasCpuFamily() bool { + if o != nil && o.CpuFamily != nil { return true } return false } -// GetVmState returns the VmState field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ServerProperties) GetVmState() *string { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *ServerProperties) GetName() *string { if o == nil { return nil } - return o.VmState + return o.Name } -// GetVmStateOk returns a tuple with the VmState field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ServerProperties) GetVmStateOk() (*string, bool) { +func (o *ServerProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.VmState, true + return o.Name, true } -// SetVmState sets field value -func (o *ServerProperties) SetVmState(v string) { +// SetName sets field value +func (o *ServerProperties) SetName(v string) { - o.VmState = &v + o.Name = &v } -// HasVmState returns a boolean if a field has been set. -func (o *ServerProperties) HasVmState() bool { - if o != nil && o.VmState != nil { +// HasName returns a boolean if a field has been set. +func (o *ServerProperties) HasName() bool { + if o != nil && o.Name != nil { return true } return false } -// GetBootCdrom returns the BootCdrom field value -// If the value is explicit nil, the zero value for ResourceReference will be returned -func (o *ServerProperties) GetBootCdrom() *ResourceReference { +// GetPlacementGroupId returns the PlacementGroupId field value +// If the value is explicit nil, nil is returned +func (o *ServerProperties) GetPlacementGroupId() *string { if o == nil { return nil } - return o.BootCdrom + return o.PlacementGroupId } -// GetBootCdromOk returns a tuple with the BootCdrom field value +// GetPlacementGroupIdOk returns a tuple with the PlacementGroupId field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ServerProperties) GetBootCdromOk() (*ResourceReference, bool) { +func (o *ServerProperties) GetPlacementGroupIdOk() (*string, bool) { if o == nil { return nil, false } - return o.BootCdrom, true + return o.PlacementGroupId, true } -// SetBootCdrom sets field value -func (o *ServerProperties) SetBootCdrom(v ResourceReference) { +// SetPlacementGroupId sets field value +func (o *ServerProperties) SetPlacementGroupId(v string) { - o.BootCdrom = &v + o.PlacementGroupId = &v } -// HasBootCdrom returns a boolean if a field has been set. -func (o *ServerProperties) HasBootCdrom() bool { - if o != nil && o.BootCdrom != nil { +// HasPlacementGroupId returns a boolean if a field has been set. +func (o *ServerProperties) HasPlacementGroupId() bool { + if o != nil && o.PlacementGroupId != nil { return true } return false } -// GetBootVolume returns the BootVolume field value -// If the value is explicit nil, the zero value for ResourceReference will be returned -func (o *ServerProperties) GetBootVolume() *ResourceReference { +// GetRam returns the Ram field value +// If the value is explicit nil, nil is returned +func (o *ServerProperties) GetRam() *int32 { if o == nil { return nil } - return o.BootVolume + return o.Ram } -// GetBootVolumeOk returns a tuple with the BootVolume field value +// GetRamOk returns a tuple with the Ram field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ServerProperties) GetBootVolumeOk() (*ResourceReference, bool) { +func (o *ServerProperties) GetRamOk() (*int32, bool) { if o == nil { return nil, false } - return o.BootVolume, true + return o.Ram, true } -// SetBootVolume sets field value -func (o *ServerProperties) SetBootVolume(v ResourceReference) { +// SetRam sets field value +func (o *ServerProperties) SetRam(v int32) { - o.BootVolume = &v + o.Ram = &v } -// HasBootVolume returns a boolean if a field has been set. -func (o *ServerProperties) HasBootVolume() bool { - if o != nil && o.BootVolume != nil { +// HasRam returns a boolean if a field has been set. +func (o *ServerProperties) HasRam() bool { + if o != nil && o.Ram != nil { return true } return false } -// GetCpuFamily returns the CpuFamily field value -// If the value is explicit nil, the zero value for string will be returned -func (o *ServerProperties) GetCpuFamily() *string { +// GetTemplateUuid returns the TemplateUuid field value +// If the value is explicit nil, nil is returned +func (o *ServerProperties) GetTemplateUuid() *string { if o == nil { return nil } - return o.CpuFamily + return o.TemplateUuid } -// GetCpuFamilyOk returns a tuple with the CpuFamily field value +// GetTemplateUuidOk returns a tuple with the TemplateUuid field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *ServerProperties) GetCpuFamilyOk() (*string, bool) { +func (o *ServerProperties) GetTemplateUuidOk() (*string, bool) { if o == nil { return nil, false } - return o.CpuFamily, true + return o.TemplateUuid, true } -// SetCpuFamily sets field value -func (o *ServerProperties) SetCpuFamily(v string) { +// SetTemplateUuid sets field value +func (o *ServerProperties) SetTemplateUuid(v string) { - o.CpuFamily = &v + o.TemplateUuid = &v } -// HasCpuFamily returns a boolean if a field has been set. -func (o *ServerProperties) HasCpuFamily() bool { - if o != nil && o.CpuFamily != nil { +// HasTemplateUuid returns a boolean if a field has been set. +func (o *ServerProperties) HasTemplateUuid() bool { + if o != nil && o.TemplateUuid != nil { return true } @@ -397,7 +399,7 @@ func (o *ServerProperties) HasCpuFamily() bool { } // GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *ServerProperties) GetType() *string { if o == nil { return nil @@ -434,38 +436,90 @@ func (o *ServerProperties) HasType() bool { return false } -func (o ServerProperties) MarshalJSON() ([]byte, error) { - toSerialize := map[string]interface{}{} - if o.TemplateUuid != nil { - toSerialize["templateUuid"] = o.TemplateUuid - } - if o.Name != nil { - toSerialize["name"] = o.Name +// GetVmState returns the VmState field value +// If the value is explicit nil, nil is returned +func (o *ServerProperties) GetVmState() *string { + if o == nil { + return nil } - if o.Cores != nil { - toSerialize["cores"] = o.Cores + + return o.VmState + +} + +// GetVmStateOk returns a tuple with the VmState field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *ServerProperties) GetVmStateOk() (*string, bool) { + if o == nil { + return nil, false } - if o.Ram != nil { - toSerialize["ram"] = o.Ram + + return o.VmState, true +} + +// SetVmState sets field value +func (o *ServerProperties) SetVmState(v string) { + + o.VmState = &v + +} + +// HasVmState returns a boolean if a field has been set. +func (o *ServerProperties) HasVmState() bool { + if o != nil && o.VmState != nil { + return true } + + return false +} + +func (o ServerProperties) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} if o.AvailabilityZone != nil { toSerialize["availabilityZone"] = o.AvailabilityZone } - if o.VmState != nil { - toSerialize["vmState"] = o.VmState - } + if o.BootCdrom != nil { toSerialize["bootCdrom"] = o.BootCdrom } + if o.BootVolume != nil { toSerialize["bootVolume"] = o.BootVolume } + + if o.Cores != nil { + toSerialize["cores"] = o.Cores + } + if o.CpuFamily != nil { toSerialize["cpuFamily"] = o.CpuFamily } + + if o.Name != nil { + toSerialize["name"] = o.Name + } + + if o.PlacementGroupId != nil { + toSerialize["placementGroupId"] = o.PlacementGroupId + } + + if o.Ram != nil { + toSerialize["ram"] = o.Ram + } + + if o.TemplateUuid != nil { + toSerialize["templateUuid"] = o.TemplateUuid + } + if o.Type != nil { toSerialize["type"] = o.Type } + + if o.VmState != nil { + toSerialize["vmState"] = o.VmState + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_servers.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_servers.go index 86fe0d2deea..789aeaeb575 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_servers.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_servers.go @@ -16,19 +16,19 @@ import ( // Servers struct for Servers type Servers struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Server `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewServers instantiates a new Servers object @@ -49,114 +49,114 @@ func NewServersWithDefaults() *Servers { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Servers) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *Servers) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Servers) GetIdOk() (*string, bool) { +func (o *Servers) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *Servers) SetId(v string) { +// SetLinks sets field value +func (o *Servers) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *Servers) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *Servers) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Servers) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Servers) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Servers) GetTypeOk() (*Type, bool) { +func (o *Servers) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Servers) SetType(v Type) { +// SetHref sets field value +func (o *Servers) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Servers) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Servers) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Servers) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Servers) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Servers) GetHrefOk() (*string, bool) { +func (o *Servers) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Servers) SetHref(v string) { +// SetId sets field value +func (o *Servers) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Servers) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Servers) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *Servers) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Server will be returned +// If the value is explicit nil, nil is returned func (o *Servers) GetItems() *[]Server { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *Servers) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Servers) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *Servers) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Servers) GetOffsetOk() (*float32, bool) { +func (o *Servers) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *Servers) SetOffset(v float32) { +// SetLimit sets field value +func (o *Servers) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *Servers) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *Servers) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Servers) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *Servers) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Servers) GetLimitOk() (*float32, bool) { +func (o *Servers) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *Servers) SetLimit(v float32) { +// SetOffset sets field value +func (o *Servers) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *Servers) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *Servers) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *Servers) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Servers) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Servers) GetLinksOk() (*PaginationLinks, bool) { +func (o *Servers) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *Servers) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *Servers) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *Servers) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *Servers) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *Servers) HasLinks() bool { func (o Servers) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_snapshot.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_snapshot.go index 56ebb960da8..c42cc05467e 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_snapshot.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_snapshot.go @@ -16,14 +16,14 @@ import ( // Snapshot struct for Snapshot type Snapshot struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *SnapshotProperties `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewSnapshot instantiates a new Snapshot object @@ -46,190 +46,190 @@ func NewSnapshotWithDefaults() *Snapshot { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Snapshot) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Snapshot) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Snapshot) GetIdOk() (*string, bool) { +func (o *Snapshot) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Snapshot) SetId(v string) { +// SetHref sets field value +func (o *Snapshot) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Snapshot) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Snapshot) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Snapshot) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Snapshot) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Snapshot) GetTypeOk() (*Type, bool) { +func (o *Snapshot) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Snapshot) SetType(v Type) { +// SetId sets field value +func (o *Snapshot) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Snapshot) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Snapshot) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Snapshot) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *Snapshot) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Snapshot) GetHrefOk() (*string, bool) { +func (o *Snapshot) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *Snapshot) SetHref(v string) { +// SetMetadata sets field value +func (o *Snapshot) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *Snapshot) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *Snapshot) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *Snapshot) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *Snapshot) GetProperties() *SnapshotProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Snapshot) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *Snapshot) GetPropertiesOk() (*SnapshotProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *Snapshot) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *Snapshot) SetProperties(v SnapshotProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *Snapshot) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *Snapshot) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for SnapshotProperties will be returned -func (o *Snapshot) GetProperties() *SnapshotProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Snapshot) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Snapshot) GetPropertiesOk() (*SnapshotProperties, bool) { +func (o *Snapshot) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *Snapshot) SetProperties(v SnapshotProperties) { +// SetType sets field value +func (o *Snapshot) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *Snapshot) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *Snapshot) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *Snapshot) HasProperties() bool { func (o Snapshot) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_snapshot_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_snapshot_properties.go index b42dca20cd5..5eb8cea6e68 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_snapshot_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_snapshot_properties.go @@ -16,38 +16,38 @@ import ( // SnapshotProperties struct for SnapshotProperties type SnapshotProperties struct { - // The name of the resource. - Name *string `json:"name,omitempty"` - // Human-readable description. - Description *string `json:"description,omitempty"` - // Location of that image/snapshot. - Location *string `json:"location,omitempty"` - // The size of the image in GB. - Size *float32 `json:"size,omitempty"` - // Boolean value representing if the snapshot requires extra protection, such as two-step verification. - SecAuthProtection *bool `json:"secAuthProtection,omitempty"` // Hot-plug capable CPU (no reboot required). CpuHotPlug *bool `json:"cpuHotPlug,omitempty"` // Hot-unplug capable CPU (no reboot required). CpuHotUnplug *bool `json:"cpuHotUnplug,omitempty"` - // Hot-plug capable RAM (no reboot required). - RamHotPlug *bool `json:"ramHotPlug,omitempty"` - // Hot-unplug capable RAM (no reboot required). - RamHotUnplug *bool `json:"ramHotUnplug,omitempty"` - // Hot-plug capable NIC (no reboot required). - NicHotPlug *bool `json:"nicHotPlug,omitempty"` - // Hot-unplug capable NIC (no reboot required). - NicHotUnplug *bool `json:"nicHotUnplug,omitempty"` - // Hot-plug capable Virt-IO drive (no reboot required). - DiscVirtioHotPlug *bool `json:"discVirtioHotPlug,omitempty"` - // Hot-unplug capable Virt-IO drive (no reboot required). Not supported with Windows VMs. - DiscVirtioHotUnplug *bool `json:"discVirtioHotUnplug,omitempty"` + // Human-readable description. + Description *string `json:"description,omitempty"` // Hot-plug capable SCSI drive (no reboot required). DiscScsiHotPlug *bool `json:"discScsiHotPlug,omitempty"` // Is capable of SCSI drive hot unplug (no reboot required). This works only for non-Windows virtual Machines. DiscScsiHotUnplug *bool `json:"discScsiHotUnplug,omitempty"` + // Hot-plug capable Virt-IO drive (no reboot required). + DiscVirtioHotPlug *bool `json:"discVirtioHotPlug,omitempty"` + // Hot-unplug capable Virt-IO drive (no reboot required). Not supported with Windows VMs. + DiscVirtioHotUnplug *bool `json:"discVirtioHotUnplug,omitempty"` // OS type of this snapshot LicenceType *string `json:"licenceType,omitempty"` + // Location of that image/snapshot. + Location *string `json:"location,omitempty"` + // The name of the resource. + Name *string `json:"name,omitempty"` + // Hot-plug capable NIC (no reboot required). + NicHotPlug *bool `json:"nicHotPlug,omitempty"` + // Hot-unplug capable NIC (no reboot required). + NicHotUnplug *bool `json:"nicHotUnplug,omitempty"` + // Hot-plug capable RAM (no reboot required). + RamHotPlug *bool `json:"ramHotPlug,omitempty"` + // Hot-unplug capable RAM (no reboot required). + RamHotUnplug *bool `json:"ramHotUnplug,omitempty"` + // Boolean value representing if the snapshot requires extra protection, such as two-step verification. + SecAuthProtection *bool `json:"secAuthProtection,omitempty"` + // The size of the image in GB. + Size *float32 `json:"size,omitempty"` } // NewSnapshotProperties instantiates a new SnapshotProperties object @@ -68,38 +68,76 @@ func NewSnapshotPropertiesWithDefaults() *SnapshotProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *SnapshotProperties) GetName() *string { +// GetCpuHotPlug returns the CpuHotPlug field value +// If the value is explicit nil, nil is returned +func (o *SnapshotProperties) GetCpuHotPlug() *bool { if o == nil { return nil } - return o.Name + return o.CpuHotPlug } -// GetNameOk returns a tuple with the Name field value +// GetCpuHotPlugOk returns a tuple with the CpuHotPlug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *SnapshotProperties) GetNameOk() (*string, bool) { +func (o *SnapshotProperties) GetCpuHotPlugOk() (*bool, bool) { if o == nil { return nil, false } - return o.Name, true + return o.CpuHotPlug, true } -// SetName sets field value -func (o *SnapshotProperties) SetName(v string) { +// SetCpuHotPlug sets field value +func (o *SnapshotProperties) SetCpuHotPlug(v bool) { - o.Name = &v + o.CpuHotPlug = &v } -// HasName returns a boolean if a field has been set. -func (o *SnapshotProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasCpuHotPlug returns a boolean if a field has been set. +func (o *SnapshotProperties) HasCpuHotPlug() bool { + if o != nil && o.CpuHotPlug != nil { + return true + } + + return false +} + +// GetCpuHotUnplug returns the CpuHotUnplug field value +// If the value is explicit nil, nil is returned +func (o *SnapshotProperties) GetCpuHotUnplug() *bool { + if o == nil { + return nil + } + + return o.CpuHotUnplug + +} + +// GetCpuHotUnplugOk returns a tuple with the CpuHotUnplug field value +// and a boolean to check if the value has been set. +// NOTE: If the value is an explicit nil, `nil, true` will be returned +func (o *SnapshotProperties) GetCpuHotUnplugOk() (*bool, bool) { + if o == nil { + return nil, false + } + + return o.CpuHotUnplug, true +} + +// SetCpuHotUnplug sets field value +func (o *SnapshotProperties) SetCpuHotUnplug(v bool) { + + o.CpuHotUnplug = &v + +} + +// HasCpuHotUnplug returns a boolean if a field has been set. +func (o *SnapshotProperties) HasCpuHotUnplug() bool { + if o != nil && o.CpuHotUnplug != nil { return true } @@ -107,7 +145,7 @@ func (o *SnapshotProperties) HasName() bool { } // GetDescription returns the Description field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *SnapshotProperties) GetDescription() *string { if o == nil { return nil @@ -144,266 +182,266 @@ func (o *SnapshotProperties) HasDescription() bool { return false } -// GetLocation returns the Location field value -// If the value is explicit nil, the zero value for string will be returned -func (o *SnapshotProperties) GetLocation() *string { +// GetDiscScsiHotPlug returns the DiscScsiHotPlug field value +// If the value is explicit nil, nil is returned +func (o *SnapshotProperties) GetDiscScsiHotPlug() *bool { if o == nil { return nil } - return o.Location + return o.DiscScsiHotPlug } -// GetLocationOk returns a tuple with the Location field value +// GetDiscScsiHotPlugOk returns a tuple with the DiscScsiHotPlug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *SnapshotProperties) GetLocationOk() (*string, bool) { +func (o *SnapshotProperties) GetDiscScsiHotPlugOk() (*bool, bool) { if o == nil { return nil, false } - return o.Location, true + return o.DiscScsiHotPlug, true } -// SetLocation sets field value -func (o *SnapshotProperties) SetLocation(v string) { +// SetDiscScsiHotPlug sets field value +func (o *SnapshotProperties) SetDiscScsiHotPlug(v bool) { - o.Location = &v + o.DiscScsiHotPlug = &v } -// HasLocation returns a boolean if a field has been set. -func (o *SnapshotProperties) HasLocation() bool { - if o != nil && o.Location != nil { +// HasDiscScsiHotPlug returns a boolean if a field has been set. +func (o *SnapshotProperties) HasDiscScsiHotPlug() bool { + if o != nil && o.DiscScsiHotPlug != nil { return true } return false } -// GetSize returns the Size field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *SnapshotProperties) GetSize() *float32 { +// GetDiscScsiHotUnplug returns the DiscScsiHotUnplug field value +// If the value is explicit nil, nil is returned +func (o *SnapshotProperties) GetDiscScsiHotUnplug() *bool { if o == nil { return nil } - return o.Size + return o.DiscScsiHotUnplug } -// GetSizeOk returns a tuple with the Size field value +// GetDiscScsiHotUnplugOk returns a tuple with the DiscScsiHotUnplug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *SnapshotProperties) GetSizeOk() (*float32, bool) { +func (o *SnapshotProperties) GetDiscScsiHotUnplugOk() (*bool, bool) { if o == nil { return nil, false } - return o.Size, true + return o.DiscScsiHotUnplug, true } -// SetSize sets field value -func (o *SnapshotProperties) SetSize(v float32) { +// SetDiscScsiHotUnplug sets field value +func (o *SnapshotProperties) SetDiscScsiHotUnplug(v bool) { - o.Size = &v + o.DiscScsiHotUnplug = &v } -// HasSize returns a boolean if a field has been set. -func (o *SnapshotProperties) HasSize() bool { - if o != nil && o.Size != nil { +// HasDiscScsiHotUnplug returns a boolean if a field has been set. +func (o *SnapshotProperties) HasDiscScsiHotUnplug() bool { + if o != nil && o.DiscScsiHotUnplug != nil { return true } return false } -// GetSecAuthProtection returns the SecAuthProtection field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *SnapshotProperties) GetSecAuthProtection() *bool { +// GetDiscVirtioHotPlug returns the DiscVirtioHotPlug field value +// If the value is explicit nil, nil is returned +func (o *SnapshotProperties) GetDiscVirtioHotPlug() *bool { if o == nil { return nil } - return o.SecAuthProtection + return o.DiscVirtioHotPlug } -// GetSecAuthProtectionOk returns a tuple with the SecAuthProtection field value +// GetDiscVirtioHotPlugOk returns a tuple with the DiscVirtioHotPlug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *SnapshotProperties) GetSecAuthProtectionOk() (*bool, bool) { +func (o *SnapshotProperties) GetDiscVirtioHotPlugOk() (*bool, bool) { if o == nil { return nil, false } - return o.SecAuthProtection, true + return o.DiscVirtioHotPlug, true } -// SetSecAuthProtection sets field value -func (o *SnapshotProperties) SetSecAuthProtection(v bool) { +// SetDiscVirtioHotPlug sets field value +func (o *SnapshotProperties) SetDiscVirtioHotPlug(v bool) { - o.SecAuthProtection = &v + o.DiscVirtioHotPlug = &v } -// HasSecAuthProtection returns a boolean if a field has been set. -func (o *SnapshotProperties) HasSecAuthProtection() bool { - if o != nil && o.SecAuthProtection != nil { +// HasDiscVirtioHotPlug returns a boolean if a field has been set. +func (o *SnapshotProperties) HasDiscVirtioHotPlug() bool { + if o != nil && o.DiscVirtioHotPlug != nil { return true } return false } -// GetCpuHotPlug returns the CpuHotPlug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *SnapshotProperties) GetCpuHotPlug() *bool { +// GetDiscVirtioHotUnplug returns the DiscVirtioHotUnplug field value +// If the value is explicit nil, nil is returned +func (o *SnapshotProperties) GetDiscVirtioHotUnplug() *bool { if o == nil { return nil } - return o.CpuHotPlug + return o.DiscVirtioHotUnplug } -// GetCpuHotPlugOk returns a tuple with the CpuHotPlug field value +// GetDiscVirtioHotUnplugOk returns a tuple with the DiscVirtioHotUnplug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *SnapshotProperties) GetCpuHotPlugOk() (*bool, bool) { +func (o *SnapshotProperties) GetDiscVirtioHotUnplugOk() (*bool, bool) { if o == nil { return nil, false } - return o.CpuHotPlug, true + return o.DiscVirtioHotUnplug, true } -// SetCpuHotPlug sets field value -func (o *SnapshotProperties) SetCpuHotPlug(v bool) { +// SetDiscVirtioHotUnplug sets field value +func (o *SnapshotProperties) SetDiscVirtioHotUnplug(v bool) { - o.CpuHotPlug = &v + o.DiscVirtioHotUnplug = &v } -// HasCpuHotPlug returns a boolean if a field has been set. -func (o *SnapshotProperties) HasCpuHotPlug() bool { - if o != nil && o.CpuHotPlug != nil { +// HasDiscVirtioHotUnplug returns a boolean if a field has been set. +func (o *SnapshotProperties) HasDiscVirtioHotUnplug() bool { + if o != nil && o.DiscVirtioHotUnplug != nil { return true } return false } -// GetCpuHotUnplug returns the CpuHotUnplug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *SnapshotProperties) GetCpuHotUnplug() *bool { +// GetLicenceType returns the LicenceType field value +// If the value is explicit nil, nil is returned +func (o *SnapshotProperties) GetLicenceType() *string { if o == nil { return nil } - return o.CpuHotUnplug + return o.LicenceType } -// GetCpuHotUnplugOk returns a tuple with the CpuHotUnplug field value +// GetLicenceTypeOk returns a tuple with the LicenceType field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *SnapshotProperties) GetCpuHotUnplugOk() (*bool, bool) { +func (o *SnapshotProperties) GetLicenceTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.CpuHotUnplug, true + return o.LicenceType, true } -// SetCpuHotUnplug sets field value -func (o *SnapshotProperties) SetCpuHotUnplug(v bool) { +// SetLicenceType sets field value +func (o *SnapshotProperties) SetLicenceType(v string) { - o.CpuHotUnplug = &v + o.LicenceType = &v } -// HasCpuHotUnplug returns a boolean if a field has been set. -func (o *SnapshotProperties) HasCpuHotUnplug() bool { - if o != nil && o.CpuHotUnplug != nil { +// HasLicenceType returns a boolean if a field has been set. +func (o *SnapshotProperties) HasLicenceType() bool { + if o != nil && o.LicenceType != nil { return true } return false } -// GetRamHotPlug returns the RamHotPlug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *SnapshotProperties) GetRamHotPlug() *bool { +// GetLocation returns the Location field value +// If the value is explicit nil, nil is returned +func (o *SnapshotProperties) GetLocation() *string { if o == nil { return nil } - return o.RamHotPlug + return o.Location } -// GetRamHotPlugOk returns a tuple with the RamHotPlug field value +// GetLocationOk returns a tuple with the Location field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *SnapshotProperties) GetRamHotPlugOk() (*bool, bool) { +func (o *SnapshotProperties) GetLocationOk() (*string, bool) { if o == nil { return nil, false } - return o.RamHotPlug, true + return o.Location, true } -// SetRamHotPlug sets field value -func (o *SnapshotProperties) SetRamHotPlug(v bool) { +// SetLocation sets field value +func (o *SnapshotProperties) SetLocation(v string) { - o.RamHotPlug = &v + o.Location = &v } -// HasRamHotPlug returns a boolean if a field has been set. -func (o *SnapshotProperties) HasRamHotPlug() bool { - if o != nil && o.RamHotPlug != nil { +// HasLocation returns a boolean if a field has been set. +func (o *SnapshotProperties) HasLocation() bool { + if o != nil && o.Location != nil { return true } return false } -// GetRamHotUnplug returns the RamHotUnplug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *SnapshotProperties) GetRamHotUnplug() *bool { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *SnapshotProperties) GetName() *string { if o == nil { return nil } - return o.RamHotUnplug + return o.Name } -// GetRamHotUnplugOk returns a tuple with the RamHotUnplug field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *SnapshotProperties) GetRamHotUnplugOk() (*bool, bool) { +func (o *SnapshotProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.RamHotUnplug, true + return o.Name, true } -// SetRamHotUnplug sets field value -func (o *SnapshotProperties) SetRamHotUnplug(v bool) { +// SetName sets field value +func (o *SnapshotProperties) SetName(v string) { - o.RamHotUnplug = &v + o.Name = &v } -// HasRamHotUnplug returns a boolean if a field has been set. -func (o *SnapshotProperties) HasRamHotUnplug() bool { - if o != nil && o.RamHotUnplug != nil { +// HasName returns a boolean if a field has been set. +func (o *SnapshotProperties) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -411,7 +449,7 @@ func (o *SnapshotProperties) HasRamHotUnplug() bool { } // GetNicHotPlug returns the NicHotPlug field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *SnapshotProperties) GetNicHotPlug() *bool { if o == nil { return nil @@ -449,7 +487,7 @@ func (o *SnapshotProperties) HasNicHotPlug() bool { } // GetNicHotUnplug returns the NicHotUnplug field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *SnapshotProperties) GetNicHotUnplug() *bool { if o == nil { return nil @@ -486,246 +524,224 @@ func (o *SnapshotProperties) HasNicHotUnplug() bool { return false } -// GetDiscVirtioHotPlug returns the DiscVirtioHotPlug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *SnapshotProperties) GetDiscVirtioHotPlug() *bool { +// GetRamHotPlug returns the RamHotPlug field value +// If the value is explicit nil, nil is returned +func (o *SnapshotProperties) GetRamHotPlug() *bool { if o == nil { return nil } - return o.DiscVirtioHotPlug + return o.RamHotPlug } -// GetDiscVirtioHotPlugOk returns a tuple with the DiscVirtioHotPlug field value +// GetRamHotPlugOk returns a tuple with the RamHotPlug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *SnapshotProperties) GetDiscVirtioHotPlugOk() (*bool, bool) { +func (o *SnapshotProperties) GetRamHotPlugOk() (*bool, bool) { if o == nil { return nil, false } - return o.DiscVirtioHotPlug, true + return o.RamHotPlug, true } -// SetDiscVirtioHotPlug sets field value -func (o *SnapshotProperties) SetDiscVirtioHotPlug(v bool) { +// SetRamHotPlug sets field value +func (o *SnapshotProperties) SetRamHotPlug(v bool) { - o.DiscVirtioHotPlug = &v + o.RamHotPlug = &v } -// HasDiscVirtioHotPlug returns a boolean if a field has been set. -func (o *SnapshotProperties) HasDiscVirtioHotPlug() bool { - if o != nil && o.DiscVirtioHotPlug != nil { +// HasRamHotPlug returns a boolean if a field has been set. +func (o *SnapshotProperties) HasRamHotPlug() bool { + if o != nil && o.RamHotPlug != nil { return true } return false } -// GetDiscVirtioHotUnplug returns the DiscVirtioHotUnplug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *SnapshotProperties) GetDiscVirtioHotUnplug() *bool { +// GetRamHotUnplug returns the RamHotUnplug field value +// If the value is explicit nil, nil is returned +func (o *SnapshotProperties) GetRamHotUnplug() *bool { if o == nil { return nil } - return o.DiscVirtioHotUnplug + return o.RamHotUnplug } -// GetDiscVirtioHotUnplugOk returns a tuple with the DiscVirtioHotUnplug field value +// GetRamHotUnplugOk returns a tuple with the RamHotUnplug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *SnapshotProperties) GetDiscVirtioHotUnplugOk() (*bool, bool) { +func (o *SnapshotProperties) GetRamHotUnplugOk() (*bool, bool) { if o == nil { return nil, false } - return o.DiscVirtioHotUnplug, true + return o.RamHotUnplug, true } -// SetDiscVirtioHotUnplug sets field value -func (o *SnapshotProperties) SetDiscVirtioHotUnplug(v bool) { +// SetRamHotUnplug sets field value +func (o *SnapshotProperties) SetRamHotUnplug(v bool) { - o.DiscVirtioHotUnplug = &v + o.RamHotUnplug = &v } -// HasDiscVirtioHotUnplug returns a boolean if a field has been set. -func (o *SnapshotProperties) HasDiscVirtioHotUnplug() bool { - if o != nil && o.DiscVirtioHotUnplug != nil { +// HasRamHotUnplug returns a boolean if a field has been set. +func (o *SnapshotProperties) HasRamHotUnplug() bool { + if o != nil && o.RamHotUnplug != nil { return true } return false } -// GetDiscScsiHotPlug returns the DiscScsiHotPlug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *SnapshotProperties) GetDiscScsiHotPlug() *bool { +// GetSecAuthProtection returns the SecAuthProtection field value +// If the value is explicit nil, nil is returned +func (o *SnapshotProperties) GetSecAuthProtection() *bool { if o == nil { return nil } - return o.DiscScsiHotPlug + return o.SecAuthProtection } -// GetDiscScsiHotPlugOk returns a tuple with the DiscScsiHotPlug field value +// GetSecAuthProtectionOk returns a tuple with the SecAuthProtection field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *SnapshotProperties) GetDiscScsiHotPlugOk() (*bool, bool) { +func (o *SnapshotProperties) GetSecAuthProtectionOk() (*bool, bool) { if o == nil { return nil, false } - return o.DiscScsiHotPlug, true + return o.SecAuthProtection, true } -// SetDiscScsiHotPlug sets field value -func (o *SnapshotProperties) SetDiscScsiHotPlug(v bool) { +// SetSecAuthProtection sets field value +func (o *SnapshotProperties) SetSecAuthProtection(v bool) { - o.DiscScsiHotPlug = &v + o.SecAuthProtection = &v } -// HasDiscScsiHotPlug returns a boolean if a field has been set. -func (o *SnapshotProperties) HasDiscScsiHotPlug() bool { - if o != nil && o.DiscScsiHotPlug != nil { +// HasSecAuthProtection returns a boolean if a field has been set. +func (o *SnapshotProperties) HasSecAuthProtection() bool { + if o != nil && o.SecAuthProtection != nil { return true } return false } -// GetDiscScsiHotUnplug returns the DiscScsiHotUnplug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *SnapshotProperties) GetDiscScsiHotUnplug() *bool { +// GetSize returns the Size field value +// If the value is explicit nil, nil is returned +func (o *SnapshotProperties) GetSize() *float32 { if o == nil { return nil } - return o.DiscScsiHotUnplug + return o.Size } -// GetDiscScsiHotUnplugOk returns a tuple with the DiscScsiHotUnplug field value +// GetSizeOk returns a tuple with the Size field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *SnapshotProperties) GetDiscScsiHotUnplugOk() (*bool, bool) { +func (o *SnapshotProperties) GetSizeOk() (*float32, bool) { if o == nil { return nil, false } - return o.DiscScsiHotUnplug, true + return o.Size, true } -// SetDiscScsiHotUnplug sets field value -func (o *SnapshotProperties) SetDiscScsiHotUnplug(v bool) { +// SetSize sets field value +func (o *SnapshotProperties) SetSize(v float32) { - o.DiscScsiHotUnplug = &v + o.Size = &v } -// HasDiscScsiHotUnplug returns a boolean if a field has been set. -func (o *SnapshotProperties) HasDiscScsiHotUnplug() bool { - if o != nil && o.DiscScsiHotUnplug != nil { +// HasSize returns a boolean if a field has been set. +func (o *SnapshotProperties) HasSize() bool { + if o != nil && o.Size != nil { return true } return false } -// GetLicenceType returns the LicenceType field value -// If the value is explicit nil, the zero value for string will be returned -func (o *SnapshotProperties) GetLicenceType() *string { - if o == nil { - return nil +func (o SnapshotProperties) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if o.CpuHotPlug != nil { + toSerialize["cpuHotPlug"] = o.CpuHotPlug } - return o.LicenceType - -} - -// GetLicenceTypeOk returns a tuple with the LicenceType field value -// and a boolean to check if the value has been set. -// NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *SnapshotProperties) GetLicenceTypeOk() (*string, bool) { - if o == nil { - return nil, false + if o.CpuHotUnplug != nil { + toSerialize["cpuHotUnplug"] = o.CpuHotUnplug } - return o.LicenceType, true -} - -// SetLicenceType sets field value -func (o *SnapshotProperties) SetLicenceType(v string) { - - o.LicenceType = &v + if o.Description != nil { + toSerialize["description"] = o.Description + } -} + if o.DiscScsiHotPlug != nil { + toSerialize["discScsiHotPlug"] = o.DiscScsiHotPlug + } -// HasLicenceType returns a boolean if a field has been set. -func (o *SnapshotProperties) HasLicenceType() bool { - if o != nil && o.LicenceType != nil { - return true + if o.DiscScsiHotUnplug != nil { + toSerialize["discScsiHotUnplug"] = o.DiscScsiHotUnplug } - return false -} + if o.DiscVirtioHotPlug != nil { + toSerialize["discVirtioHotPlug"] = o.DiscVirtioHotPlug + } -func (o SnapshotProperties) MarshalJSON() ([]byte, error) { - toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name + if o.DiscVirtioHotUnplug != nil { + toSerialize["discVirtioHotUnplug"] = o.DiscVirtioHotUnplug } - if o.Description != nil { - toSerialize["description"] = o.Description + + if o.LicenceType != nil { + toSerialize["licenceType"] = o.LicenceType } + if o.Location != nil { toSerialize["location"] = o.Location } - if o.Size != nil { - toSerialize["size"] = o.Size - } - if o.SecAuthProtection != nil { - toSerialize["secAuthProtection"] = o.SecAuthProtection - } - if o.CpuHotPlug != nil { - toSerialize["cpuHotPlug"] = o.CpuHotPlug - } - if o.CpuHotUnplug != nil { - toSerialize["cpuHotUnplug"] = o.CpuHotUnplug - } - if o.RamHotPlug != nil { - toSerialize["ramHotPlug"] = o.RamHotPlug - } - if o.RamHotUnplug != nil { - toSerialize["ramHotUnplug"] = o.RamHotUnplug + + if o.Name != nil { + toSerialize["name"] = o.Name } + if o.NicHotPlug != nil { toSerialize["nicHotPlug"] = o.NicHotPlug } + if o.NicHotUnplug != nil { toSerialize["nicHotUnplug"] = o.NicHotUnplug } - if o.DiscVirtioHotPlug != nil { - toSerialize["discVirtioHotPlug"] = o.DiscVirtioHotPlug - } - if o.DiscVirtioHotUnplug != nil { - toSerialize["discVirtioHotUnplug"] = o.DiscVirtioHotUnplug + + if o.RamHotPlug != nil { + toSerialize["ramHotPlug"] = o.RamHotPlug } - if o.DiscScsiHotPlug != nil { - toSerialize["discScsiHotPlug"] = o.DiscScsiHotPlug + + if o.RamHotUnplug != nil { + toSerialize["ramHotUnplug"] = o.RamHotUnplug } - if o.DiscScsiHotUnplug != nil { - toSerialize["discScsiHotUnplug"] = o.DiscScsiHotUnplug + + if o.SecAuthProtection != nil { + toSerialize["secAuthProtection"] = o.SecAuthProtection } - if o.LicenceType != nil { - toSerialize["licenceType"] = o.LicenceType + + if o.Size != nil { + toSerialize["size"] = o.Size } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_snapshots.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_snapshots.go index 8578d03ddaa..313d03e0927 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_snapshots.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_snapshots.go @@ -16,14 +16,14 @@ import ( // Snapshots struct for Snapshots type Snapshots struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Snapshot `json:"items,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewSnapshots instantiates a new Snapshots object @@ -44,152 +44,152 @@ func NewSnapshotsWithDefaults() *Snapshots { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Snapshots) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Snapshots) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Snapshots) GetIdOk() (*string, bool) { +func (o *Snapshots) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Snapshots) SetId(v string) { +// SetHref sets field value +func (o *Snapshots) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Snapshots) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Snapshots) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Snapshots) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Snapshots) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Snapshots) GetTypeOk() (*Type, bool) { +func (o *Snapshots) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Snapshots) SetType(v Type) { +// SetId sets field value +func (o *Snapshots) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Snapshots) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Snapshots) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Snapshots) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *Snapshots) GetItems() *[]Snapshot { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Snapshots) GetHrefOk() (*string, bool) { +func (o *Snapshots) GetItemsOk() (*[]Snapshot, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *Snapshots) SetHref(v string) { +// SetItems sets field value +func (o *Snapshots) SetItems(v []Snapshot) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *Snapshots) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *Snapshots) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Snapshot will be returned -func (o *Snapshots) GetItems() *[]Snapshot { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Snapshots) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Snapshots) GetItemsOk() (*[]Snapshot, bool) { +func (o *Snapshots) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *Snapshots) SetItems(v []Snapshot) { +// SetType sets field value +func (o *Snapshots) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *Snapshots) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *Snapshots) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *Snapshots) HasItems() bool { func (o Snapshots) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group.go index 95d71efeae1..cbfb0271f45 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group.go @@ -16,14 +16,14 @@ import ( // TargetGroup struct for TargetGroup type TargetGroup struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *TargetGroupProperties `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewTargetGroup instantiates a new TargetGroup object @@ -46,190 +46,190 @@ func NewTargetGroupWithDefaults() *TargetGroup { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *TargetGroup) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *TargetGroup) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroup) GetIdOk() (*string, bool) { +func (o *TargetGroup) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *TargetGroup) SetId(v string) { +// SetHref sets field value +func (o *TargetGroup) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *TargetGroup) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *TargetGroup) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *TargetGroup) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *TargetGroup) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroup) GetTypeOk() (*Type, bool) { +func (o *TargetGroup) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *TargetGroup) SetType(v Type) { +// SetId sets field value +func (o *TargetGroup) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *TargetGroup) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *TargetGroup) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *TargetGroup) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *TargetGroup) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroup) GetHrefOk() (*string, bool) { +func (o *TargetGroup) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *TargetGroup) SetHref(v string) { +// SetMetadata sets field value +func (o *TargetGroup) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *TargetGroup) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *TargetGroup) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *TargetGroup) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *TargetGroup) GetProperties() *TargetGroupProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroup) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *TargetGroup) GetPropertiesOk() (*TargetGroupProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *TargetGroup) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *TargetGroup) SetProperties(v TargetGroupProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *TargetGroup) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *TargetGroup) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for TargetGroupProperties will be returned -func (o *TargetGroup) GetProperties() *TargetGroupProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *TargetGroup) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroup) GetPropertiesOk() (*TargetGroupProperties, bool) { +func (o *TargetGroup) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *TargetGroup) SetProperties(v TargetGroupProperties) { +// SetType sets field value +func (o *TargetGroup) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *TargetGroup) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *TargetGroup) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *TargetGroup) HasProperties() bool { func (o TargetGroup) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_health_check.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_health_check.go index 5c8dfdfc6d3..70ca3dc637c 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_health_check.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_health_check.go @@ -16,10 +16,10 @@ import ( // TargetGroupHealthCheck struct for TargetGroupHealthCheck type TargetGroupHealthCheck struct { - // The maximum time in milliseconds is to wait for a target to respond to a check. For target VMs with a 'Check Interval' set, the smaller of the two values is used once the TCP connection is established. - CheckTimeout *int32 `json:"checkTimeout,omitempty"` // The interval in milliseconds between consecutive health checks; the default value is '2000'. CheckInterval *int32 `json:"checkInterval,omitempty"` + // The maximum time in milliseconds is to wait for a target to respond to a check. For target VMs with a 'Check Interval' set, the smaller of the two values is used once the TCP connection is established. + CheckTimeout *int32 `json:"checkTimeout,omitempty"` // The maximum number of attempts to reconnect to a target after a connection failure. The valid range is '0 to 65535'; the default value is '3'. Retries *int32 `json:"retries,omitempty"` } @@ -42,76 +42,76 @@ func NewTargetGroupHealthCheckWithDefaults() *TargetGroupHealthCheck { return &this } -// GetCheckTimeout returns the CheckTimeout field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *TargetGroupHealthCheck) GetCheckTimeout() *int32 { +// GetCheckInterval returns the CheckInterval field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupHealthCheck) GetCheckInterval() *int32 { if o == nil { return nil } - return o.CheckTimeout + return o.CheckInterval } -// GetCheckTimeoutOk returns a tuple with the CheckTimeout field value +// GetCheckIntervalOk returns a tuple with the CheckInterval field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupHealthCheck) GetCheckTimeoutOk() (*int32, bool) { +func (o *TargetGroupHealthCheck) GetCheckIntervalOk() (*int32, bool) { if o == nil { return nil, false } - return o.CheckTimeout, true + return o.CheckInterval, true } -// SetCheckTimeout sets field value -func (o *TargetGroupHealthCheck) SetCheckTimeout(v int32) { +// SetCheckInterval sets field value +func (o *TargetGroupHealthCheck) SetCheckInterval(v int32) { - o.CheckTimeout = &v + o.CheckInterval = &v } -// HasCheckTimeout returns a boolean if a field has been set. -func (o *TargetGroupHealthCheck) HasCheckTimeout() bool { - if o != nil && o.CheckTimeout != nil { +// HasCheckInterval returns a boolean if a field has been set. +func (o *TargetGroupHealthCheck) HasCheckInterval() bool { + if o != nil && o.CheckInterval != nil { return true } return false } -// GetCheckInterval returns the CheckInterval field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *TargetGroupHealthCheck) GetCheckInterval() *int32 { +// GetCheckTimeout returns the CheckTimeout field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupHealthCheck) GetCheckTimeout() *int32 { if o == nil { return nil } - return o.CheckInterval + return o.CheckTimeout } -// GetCheckIntervalOk returns a tuple with the CheckInterval field value +// GetCheckTimeoutOk returns a tuple with the CheckTimeout field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupHealthCheck) GetCheckIntervalOk() (*int32, bool) { +func (o *TargetGroupHealthCheck) GetCheckTimeoutOk() (*int32, bool) { if o == nil { return nil, false } - return o.CheckInterval, true + return o.CheckTimeout, true } -// SetCheckInterval sets field value -func (o *TargetGroupHealthCheck) SetCheckInterval(v int32) { +// SetCheckTimeout sets field value +func (o *TargetGroupHealthCheck) SetCheckTimeout(v int32) { - o.CheckInterval = &v + o.CheckTimeout = &v } -// HasCheckInterval returns a boolean if a field has been set. -func (o *TargetGroupHealthCheck) HasCheckInterval() bool { - if o != nil && o.CheckInterval != nil { +// HasCheckTimeout returns a boolean if a field has been set. +func (o *TargetGroupHealthCheck) HasCheckTimeout() bool { + if o != nil && o.CheckTimeout != nil { return true } @@ -119,7 +119,7 @@ func (o *TargetGroupHealthCheck) HasCheckInterval() bool { } // GetRetries returns the Retries field value -// If the value is explicit nil, the zero value for int32 will be returned +// If the value is explicit nil, nil is returned func (o *TargetGroupHealthCheck) GetRetries() *int32 { if o == nil { return nil @@ -158,15 +158,18 @@ func (o *TargetGroupHealthCheck) HasRetries() bool { func (o TargetGroupHealthCheck) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.CheckTimeout != nil { - toSerialize["checkTimeout"] = o.CheckTimeout - } if o.CheckInterval != nil { toSerialize["checkInterval"] = o.CheckInterval } + + if o.CheckTimeout != nil { + toSerialize["checkTimeout"] = o.CheckTimeout + } + if o.Retries != nil { toSerialize["retries"] = o.Retries } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_http_health_check.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_http_health_check.go index 274f7b91126..dc31f49508a 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_http_health_check.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_http_health_check.go @@ -16,18 +16,18 @@ import ( // TargetGroupHttpHealthCheck struct for TargetGroupHttpHealthCheck type TargetGroupHttpHealthCheck struct { - // The destination URL for HTTP the health check; the default is '/'. - Path *string `json:"path,omitempty"` - // The method used for the health check request. - Method *string `json:"method,omitempty"` // Specify the target's response type to match ALB's request. MatchType *string `json:"matchType"` - // The response returned by the request. It can be a status code or a response body depending on the definition of 'matchType'. - Response *string `json:"response"` - // Specifies whether to use a regular expression to parse the response body; the default value is 'FALSE'. By using regular expressions, you can flexibly customize the expected response from a healthy server. - Regex *bool `json:"regex,omitempty"` + // The method used for the health check request. + Method *string `json:"method,omitempty"` // Specifies whether to negate an individual entry; the default value is 'FALSE'. Negate *bool `json:"negate,omitempty"` + // The destination URL for HTTP the health check; the default is '/'. + Path *string `json:"path,omitempty"` + // Specifies whether to use a regular expression to parse the response body; the default value is 'FALSE'. By using regular expressions, you can flexibly customize the expected response from a healthy server. + Regex *bool `json:"regex,omitempty"` + // The response returned by the request. It can be a status code or a response body depending on the definition of 'matchType'. + Response *string `json:"response"` } // NewTargetGroupHttpHealthCheck instantiates a new TargetGroupHttpHealthCheck object @@ -51,38 +51,38 @@ func NewTargetGroupHttpHealthCheckWithDefaults() *TargetGroupHttpHealthCheck { return &this } -// GetPath returns the Path field value -// If the value is explicit nil, the zero value for string will be returned -func (o *TargetGroupHttpHealthCheck) GetPath() *string { +// GetMatchType returns the MatchType field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupHttpHealthCheck) GetMatchType() *string { if o == nil { return nil } - return o.Path + return o.MatchType } -// GetPathOk returns a tuple with the Path field value +// GetMatchTypeOk returns a tuple with the MatchType field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupHttpHealthCheck) GetPathOk() (*string, bool) { +func (o *TargetGroupHttpHealthCheck) GetMatchTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.Path, true + return o.MatchType, true } -// SetPath sets field value -func (o *TargetGroupHttpHealthCheck) SetPath(v string) { +// SetMatchType sets field value +func (o *TargetGroupHttpHealthCheck) SetMatchType(v string) { - o.Path = &v + o.MatchType = &v } -// HasPath returns a boolean if a field has been set. -func (o *TargetGroupHttpHealthCheck) HasPath() bool { - if o != nil && o.Path != nil { +// HasMatchType returns a boolean if a field has been set. +func (o *TargetGroupHttpHealthCheck) HasMatchType() bool { + if o != nil && o.MatchType != nil { return true } @@ -90,7 +90,7 @@ func (o *TargetGroupHttpHealthCheck) HasPath() bool { } // GetMethod returns the Method field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *TargetGroupHttpHealthCheck) GetMethod() *string { if o == nil { return nil @@ -127,76 +127,76 @@ func (o *TargetGroupHttpHealthCheck) HasMethod() bool { return false } -// GetMatchType returns the MatchType field value -// If the value is explicit nil, the zero value for string will be returned -func (o *TargetGroupHttpHealthCheck) GetMatchType() *string { +// GetNegate returns the Negate field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupHttpHealthCheck) GetNegate() *bool { if o == nil { return nil } - return o.MatchType + return o.Negate } -// GetMatchTypeOk returns a tuple with the MatchType field value +// GetNegateOk returns a tuple with the Negate field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupHttpHealthCheck) GetMatchTypeOk() (*string, bool) { +func (o *TargetGroupHttpHealthCheck) GetNegateOk() (*bool, bool) { if o == nil { return nil, false } - return o.MatchType, true + return o.Negate, true } -// SetMatchType sets field value -func (o *TargetGroupHttpHealthCheck) SetMatchType(v string) { +// SetNegate sets field value +func (o *TargetGroupHttpHealthCheck) SetNegate(v bool) { - o.MatchType = &v + o.Negate = &v } -// HasMatchType returns a boolean if a field has been set. -func (o *TargetGroupHttpHealthCheck) HasMatchType() bool { - if o != nil && o.MatchType != nil { +// HasNegate returns a boolean if a field has been set. +func (o *TargetGroupHttpHealthCheck) HasNegate() bool { + if o != nil && o.Negate != nil { return true } return false } -// GetResponse returns the Response field value -// If the value is explicit nil, the zero value for string will be returned -func (o *TargetGroupHttpHealthCheck) GetResponse() *string { +// GetPath returns the Path field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupHttpHealthCheck) GetPath() *string { if o == nil { return nil } - return o.Response + return o.Path } -// GetResponseOk returns a tuple with the Response field value +// GetPathOk returns a tuple with the Path field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupHttpHealthCheck) GetResponseOk() (*string, bool) { +func (o *TargetGroupHttpHealthCheck) GetPathOk() (*string, bool) { if o == nil { return nil, false } - return o.Response, true + return o.Path, true } -// SetResponse sets field value -func (o *TargetGroupHttpHealthCheck) SetResponse(v string) { +// SetPath sets field value +func (o *TargetGroupHttpHealthCheck) SetPath(v string) { - o.Response = &v + o.Path = &v } -// HasResponse returns a boolean if a field has been set. -func (o *TargetGroupHttpHealthCheck) HasResponse() bool { - if o != nil && o.Response != nil { +// HasPath returns a boolean if a field has been set. +func (o *TargetGroupHttpHealthCheck) HasPath() bool { + if o != nil && o.Path != nil { return true } @@ -204,7 +204,7 @@ func (o *TargetGroupHttpHealthCheck) HasResponse() bool { } // GetRegex returns the Regex field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *TargetGroupHttpHealthCheck) GetRegex() *bool { if o == nil { return nil @@ -241,38 +241,38 @@ func (o *TargetGroupHttpHealthCheck) HasRegex() bool { return false } -// GetNegate returns the Negate field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *TargetGroupHttpHealthCheck) GetNegate() *bool { +// GetResponse returns the Response field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupHttpHealthCheck) GetResponse() *string { if o == nil { return nil } - return o.Negate + return o.Response } -// GetNegateOk returns a tuple with the Negate field value +// GetResponseOk returns a tuple with the Response field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupHttpHealthCheck) GetNegateOk() (*bool, bool) { +func (o *TargetGroupHttpHealthCheck) GetResponseOk() (*string, bool) { if o == nil { return nil, false } - return o.Negate, true + return o.Response, true } -// SetNegate sets field value -func (o *TargetGroupHttpHealthCheck) SetNegate(v bool) { +// SetResponse sets field value +func (o *TargetGroupHttpHealthCheck) SetResponse(v string) { - o.Negate = &v + o.Response = &v } -// HasNegate returns a boolean if a field has been set. -func (o *TargetGroupHttpHealthCheck) HasNegate() bool { - if o != nil && o.Negate != nil { +// HasResponse returns a boolean if a field has been set. +func (o *TargetGroupHttpHealthCheck) HasResponse() bool { + if o != nil && o.Response != nil { return true } @@ -281,24 +281,30 @@ func (o *TargetGroupHttpHealthCheck) HasNegate() bool { func (o TargetGroupHttpHealthCheck) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Path != nil { - toSerialize["path"] = o.Path + if o.MatchType != nil { + toSerialize["matchType"] = o.MatchType } + if o.Method != nil { toSerialize["method"] = o.Method } - if o.MatchType != nil { - toSerialize["matchType"] = o.MatchType + + if o.Negate != nil { + toSerialize["negate"] = o.Negate } - if o.Response != nil { - toSerialize["response"] = o.Response + + if o.Path != nil { + toSerialize["path"] = o.Path } + if o.Regex != nil { toSerialize["regex"] = o.Regex } - if o.Negate != nil { - toSerialize["negate"] = o.Negate + + if o.Response != nil { + toSerialize["response"] = o.Response } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_properties.go index 3a79b8bc784..f14f3486fb5 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_properties.go @@ -16,27 +16,27 @@ import ( // TargetGroupProperties struct for TargetGroupProperties type TargetGroupProperties struct { + // The balancing algorithm. A balancing algorithm consists of predefined rules with the logic that a load balancer uses to distribute network traffic between servers. - **Round Robin**: Targets are served alternately according to their weighting. - **Least Connection**: The target with the least active connection is served. - **Random**: The targets are served based on a consistent pseudorandom algorithm. - **Source IP**: It is ensured that the same client IP address reaches the same target. + Algorithm *string `json:"algorithm"` + HealthCheck *TargetGroupHealthCheck `json:"healthCheck,omitempty"` + HttpHealthCheck *TargetGroupHttpHealthCheck `json:"httpHealthCheck,omitempty"` // The target group name. Name *string `json:"name"` - // The balancing algorithm. A balancing algorithm consists of predefined rules with the logic that a load balancer uses to distribute network traffic between servers. - **Round Robin**: Targets are served alternately according to their weighting. - **Least Connection**: The target with the least active connection is served. - **Random**: The targets are served based on a consistent pseudorandom algorithm. - **Source IP**: It is ensured that the same client IP address reaches the same target. - Algorithm *string `json:"algorithm"` // The forwarding protocol. Only the value 'HTTP' is allowed. Protocol *string `json:"protocol"` // Array of items in the collection. - Targets *[]TargetGroupTarget `json:"targets,omitempty"` - HealthCheck *TargetGroupHealthCheck `json:"healthCheck,omitempty"` - HttpHealthCheck *TargetGroupHttpHealthCheck `json:"httpHealthCheck,omitempty"` + Targets *[]TargetGroupTarget `json:"targets,omitempty"` } // NewTargetGroupProperties instantiates a new TargetGroupProperties object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewTargetGroupProperties(name string, algorithm string, protocol string) *TargetGroupProperties { +func NewTargetGroupProperties(algorithm string, name string, protocol string) *TargetGroupProperties { this := TargetGroupProperties{} - this.Name = &name this.Algorithm = &algorithm + this.Name = &name this.Protocol = &protocol return &this @@ -50,228 +50,228 @@ func NewTargetGroupPropertiesWithDefaults() *TargetGroupProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *TargetGroupProperties) GetName() *string { +// GetAlgorithm returns the Algorithm field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupProperties) GetAlgorithm() *string { if o == nil { return nil } - return o.Name + return o.Algorithm } -// GetNameOk returns a tuple with the Name field value +// GetAlgorithmOk returns a tuple with the Algorithm field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupProperties) GetNameOk() (*string, bool) { +func (o *TargetGroupProperties) GetAlgorithmOk() (*string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.Algorithm, true } -// SetName sets field value -func (o *TargetGroupProperties) SetName(v string) { +// SetAlgorithm sets field value +func (o *TargetGroupProperties) SetAlgorithm(v string) { - o.Name = &v + o.Algorithm = &v } -// HasName returns a boolean if a field has been set. -func (o *TargetGroupProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasAlgorithm returns a boolean if a field has been set. +func (o *TargetGroupProperties) HasAlgorithm() bool { + if o != nil && o.Algorithm != nil { return true } return false } -// GetAlgorithm returns the Algorithm field value -// If the value is explicit nil, the zero value for string will be returned -func (o *TargetGroupProperties) GetAlgorithm() *string { +// GetHealthCheck returns the HealthCheck field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupProperties) GetHealthCheck() *TargetGroupHealthCheck { if o == nil { return nil } - return o.Algorithm + return o.HealthCheck } -// GetAlgorithmOk returns a tuple with the Algorithm field value +// GetHealthCheckOk returns a tuple with the HealthCheck field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupProperties) GetAlgorithmOk() (*string, bool) { +func (o *TargetGroupProperties) GetHealthCheckOk() (*TargetGroupHealthCheck, bool) { if o == nil { return nil, false } - return o.Algorithm, true + return o.HealthCheck, true } -// SetAlgorithm sets field value -func (o *TargetGroupProperties) SetAlgorithm(v string) { +// SetHealthCheck sets field value +func (o *TargetGroupProperties) SetHealthCheck(v TargetGroupHealthCheck) { - o.Algorithm = &v + o.HealthCheck = &v } -// HasAlgorithm returns a boolean if a field has been set. -func (o *TargetGroupProperties) HasAlgorithm() bool { - if o != nil && o.Algorithm != nil { +// HasHealthCheck returns a boolean if a field has been set. +func (o *TargetGroupProperties) HasHealthCheck() bool { + if o != nil && o.HealthCheck != nil { return true } return false } -// GetProtocol returns the Protocol field value -// If the value is explicit nil, the zero value for string will be returned -func (o *TargetGroupProperties) GetProtocol() *string { +// GetHttpHealthCheck returns the HttpHealthCheck field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupProperties) GetHttpHealthCheck() *TargetGroupHttpHealthCheck { if o == nil { return nil } - return o.Protocol + return o.HttpHealthCheck } -// GetProtocolOk returns a tuple with the Protocol field value +// GetHttpHealthCheckOk returns a tuple with the HttpHealthCheck field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupProperties) GetProtocolOk() (*string, bool) { +func (o *TargetGroupProperties) GetHttpHealthCheckOk() (*TargetGroupHttpHealthCheck, bool) { if o == nil { return nil, false } - return o.Protocol, true + return o.HttpHealthCheck, true } -// SetProtocol sets field value -func (o *TargetGroupProperties) SetProtocol(v string) { +// SetHttpHealthCheck sets field value +func (o *TargetGroupProperties) SetHttpHealthCheck(v TargetGroupHttpHealthCheck) { - o.Protocol = &v + o.HttpHealthCheck = &v } -// HasProtocol returns a boolean if a field has been set. -func (o *TargetGroupProperties) HasProtocol() bool { - if o != nil && o.Protocol != nil { +// HasHttpHealthCheck returns a boolean if a field has been set. +func (o *TargetGroupProperties) HasHttpHealthCheck() bool { + if o != nil && o.HttpHealthCheck != nil { return true } return false } -// GetTargets returns the Targets field value -// If the value is explicit nil, the zero value for []TargetGroupTarget will be returned -func (o *TargetGroupProperties) GetTargets() *[]TargetGroupTarget { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupProperties) GetName() *string { if o == nil { return nil } - return o.Targets + return o.Name } -// GetTargetsOk returns a tuple with the Targets field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupProperties) GetTargetsOk() (*[]TargetGroupTarget, bool) { +func (o *TargetGroupProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.Targets, true + return o.Name, true } -// SetTargets sets field value -func (o *TargetGroupProperties) SetTargets(v []TargetGroupTarget) { +// SetName sets field value +func (o *TargetGroupProperties) SetName(v string) { - o.Targets = &v + o.Name = &v } -// HasTargets returns a boolean if a field has been set. -func (o *TargetGroupProperties) HasTargets() bool { - if o != nil && o.Targets != nil { +// HasName returns a boolean if a field has been set. +func (o *TargetGroupProperties) HasName() bool { + if o != nil && o.Name != nil { return true } return false } -// GetHealthCheck returns the HealthCheck field value -// If the value is explicit nil, the zero value for TargetGroupHealthCheck will be returned -func (o *TargetGroupProperties) GetHealthCheck() *TargetGroupHealthCheck { +// GetProtocol returns the Protocol field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupProperties) GetProtocol() *string { if o == nil { return nil } - return o.HealthCheck + return o.Protocol } -// GetHealthCheckOk returns a tuple with the HealthCheck field value +// GetProtocolOk returns a tuple with the Protocol field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupProperties) GetHealthCheckOk() (*TargetGroupHealthCheck, bool) { +func (o *TargetGroupProperties) GetProtocolOk() (*string, bool) { if o == nil { return nil, false } - return o.HealthCheck, true + return o.Protocol, true } -// SetHealthCheck sets field value -func (o *TargetGroupProperties) SetHealthCheck(v TargetGroupHealthCheck) { +// SetProtocol sets field value +func (o *TargetGroupProperties) SetProtocol(v string) { - o.HealthCheck = &v + o.Protocol = &v } -// HasHealthCheck returns a boolean if a field has been set. -func (o *TargetGroupProperties) HasHealthCheck() bool { - if o != nil && o.HealthCheck != nil { +// HasProtocol returns a boolean if a field has been set. +func (o *TargetGroupProperties) HasProtocol() bool { + if o != nil && o.Protocol != nil { return true } return false } -// GetHttpHealthCheck returns the HttpHealthCheck field value -// If the value is explicit nil, the zero value for TargetGroupHttpHealthCheck will be returned -func (o *TargetGroupProperties) GetHttpHealthCheck() *TargetGroupHttpHealthCheck { +// GetTargets returns the Targets field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupProperties) GetTargets() *[]TargetGroupTarget { if o == nil { return nil } - return o.HttpHealthCheck + return o.Targets } -// GetHttpHealthCheckOk returns a tuple with the HttpHealthCheck field value +// GetTargetsOk returns a tuple with the Targets field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupProperties) GetHttpHealthCheckOk() (*TargetGroupHttpHealthCheck, bool) { +func (o *TargetGroupProperties) GetTargetsOk() (*[]TargetGroupTarget, bool) { if o == nil { return nil, false } - return o.HttpHealthCheck, true + return o.Targets, true } -// SetHttpHealthCheck sets field value -func (o *TargetGroupProperties) SetHttpHealthCheck(v TargetGroupHttpHealthCheck) { +// SetTargets sets field value +func (o *TargetGroupProperties) SetTargets(v []TargetGroupTarget) { - o.HttpHealthCheck = &v + o.Targets = &v } -// HasHttpHealthCheck returns a boolean if a field has been set. -func (o *TargetGroupProperties) HasHttpHealthCheck() bool { - if o != nil && o.HttpHealthCheck != nil { +// HasTargets returns a boolean if a field has been set. +func (o *TargetGroupProperties) HasTargets() bool { + if o != nil && o.Targets != nil { return true } @@ -280,24 +280,30 @@ func (o *TargetGroupProperties) HasHttpHealthCheck() bool { func (o TargetGroupProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name - } if o.Algorithm != nil { toSerialize["algorithm"] = o.Algorithm } - if o.Protocol != nil { - toSerialize["protocol"] = o.Protocol - } - if o.Targets != nil { - toSerialize["targets"] = o.Targets - } + if o.HealthCheck != nil { toSerialize["healthCheck"] = o.HealthCheck } + if o.HttpHealthCheck != nil { toSerialize["httpHealthCheck"] = o.HttpHealthCheck } + + if o.Name != nil { + toSerialize["name"] = o.Name + } + + if o.Protocol != nil { + toSerialize["protocol"] = o.Protocol + } + + if o.Targets != nil { + toSerialize["targets"] = o.Targets + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_put.go index e5f5afd5624..b5f93b5652f 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_put.go @@ -16,13 +16,13 @@ import ( // TargetGroupPut struct for TargetGroupPut type TargetGroupPut struct { + // The URL to the object representation (absolute path). + Href *string `json:"href,omitempty"` // The resource's unique identifier. - Id *string `json:"id,omitempty"` + Id *string `json:"id,omitempty"` + Properties *TargetGroupProperties `json:"properties"` // The type of object that has been created. Type *Type `json:"type,omitempty"` - // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` - Properties *TargetGroupProperties `json:"properties"` } // NewTargetGroupPut instantiates a new TargetGroupPut object @@ -45,152 +45,152 @@ func NewTargetGroupPutWithDefaults() *TargetGroupPut { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *TargetGroupPut) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupPut) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupPut) GetIdOk() (*string, bool) { +func (o *TargetGroupPut) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *TargetGroupPut) SetId(v string) { +// SetHref sets field value +func (o *TargetGroupPut) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *TargetGroupPut) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *TargetGroupPut) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *TargetGroupPut) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupPut) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupPut) GetTypeOk() (*Type, bool) { +func (o *TargetGroupPut) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *TargetGroupPut) SetType(v Type) { +// SetId sets field value +func (o *TargetGroupPut) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *TargetGroupPut) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *TargetGroupPut) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *TargetGroupPut) GetHref() *string { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupPut) GetProperties() *TargetGroupProperties { if o == nil { return nil } - return o.Href + return o.Properties } -// GetHrefOk returns a tuple with the Href field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupPut) GetHrefOk() (*string, bool) { +func (o *TargetGroupPut) GetPropertiesOk() (*TargetGroupProperties, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Properties, true } -// SetHref sets field value -func (o *TargetGroupPut) SetHref(v string) { +// SetProperties sets field value +func (o *TargetGroupPut) SetProperties(v TargetGroupProperties) { - o.Href = &v + o.Properties = &v } -// HasHref returns a boolean if a field has been set. -func (o *TargetGroupPut) HasHref() bool { - if o != nil && o.Href != nil { +// HasProperties returns a boolean if a field has been set. +func (o *TargetGroupPut) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for TargetGroupProperties will be returned -func (o *TargetGroupPut) GetProperties() *TargetGroupProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupPut) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupPut) GetPropertiesOk() (*TargetGroupProperties, bool) { +func (o *TargetGroupPut) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *TargetGroupPut) SetProperties(v TargetGroupProperties) { +// SetType sets field value +func (o *TargetGroupPut) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *TargetGroupPut) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *TargetGroupPut) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -199,18 +199,22 @@ func (o *TargetGroupPut) HasProperties() bool { func (o TargetGroupPut) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_target.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_target.go index bad8c42d575..a9c9e2d9e4e 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_target.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_group_target.go @@ -16,16 +16,16 @@ import ( // TargetGroupTarget struct for TargetGroupTarget type TargetGroupTarget struct { + // When the health check is enabled, the target is available only when it accepts regular TCP or HTTP connection attempts for state checking. The state check consists of one connection attempt with the target's address and port. The default value is 'TRUE'. + HealthCheckEnabled *bool `json:"healthCheckEnabled,omitempty"` // The IP address of the balanced target. Ip *string `json:"ip"` + // When the maintenance mode is enabled, the target is prevented from receiving traffic; the default value is 'FALSE'. + MaintenanceEnabled *bool `json:"maintenanceEnabled,omitempty"` // The port of the balanced target service; the valid range is 1 to 65535. Port *int32 `json:"port"` // The traffic is distributed proportionally to target weight, which is the ratio of the total weight of all targets. A target with higher weight receives a larger share of traffic. The valid range is from 0 to 256; the default value is '1'. Targets with a weight of '0' do not participate in load balancing but still accept persistent connections. We recommend using values in the middle range to leave room for later adjustments. Weight *int32 `json:"weight"` - // When the health check is enabled, the target is available only when it accepts regular TCP or HTTP connection attempts for state checking. The state check consists of one connection attempt with the target's address and port. The default value is 'TRUE'. - HealthCheckEnabled *bool `json:"healthCheckEnabled,omitempty"` - // When the maintenance mode is enabled, the target is prevented from receiving traffic; the default value is 'FALSE'. - MaintenanceEnabled *bool `json:"maintenanceEnabled,omitempty"` } // NewTargetGroupTarget instantiates a new TargetGroupTarget object @@ -50,190 +50,190 @@ func NewTargetGroupTargetWithDefaults() *TargetGroupTarget { return &this } -// GetIp returns the Ip field value -// If the value is explicit nil, the zero value for string will be returned -func (o *TargetGroupTarget) GetIp() *string { +// GetHealthCheckEnabled returns the HealthCheckEnabled field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupTarget) GetHealthCheckEnabled() *bool { if o == nil { return nil } - return o.Ip + return o.HealthCheckEnabled } -// GetIpOk returns a tuple with the Ip field value +// GetHealthCheckEnabledOk returns a tuple with the HealthCheckEnabled field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupTarget) GetIpOk() (*string, bool) { +func (o *TargetGroupTarget) GetHealthCheckEnabledOk() (*bool, bool) { if o == nil { return nil, false } - return o.Ip, true + return o.HealthCheckEnabled, true } -// SetIp sets field value -func (o *TargetGroupTarget) SetIp(v string) { +// SetHealthCheckEnabled sets field value +func (o *TargetGroupTarget) SetHealthCheckEnabled(v bool) { - o.Ip = &v + o.HealthCheckEnabled = &v } -// HasIp returns a boolean if a field has been set. -func (o *TargetGroupTarget) HasIp() bool { - if o != nil && o.Ip != nil { +// HasHealthCheckEnabled returns a boolean if a field has been set. +func (o *TargetGroupTarget) HasHealthCheckEnabled() bool { + if o != nil && o.HealthCheckEnabled != nil { return true } return false } -// GetPort returns the Port field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *TargetGroupTarget) GetPort() *int32 { +// GetIp returns the Ip field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupTarget) GetIp() *string { if o == nil { return nil } - return o.Port + return o.Ip } -// GetPortOk returns a tuple with the Port field value +// GetIpOk returns a tuple with the Ip field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupTarget) GetPortOk() (*int32, bool) { +func (o *TargetGroupTarget) GetIpOk() (*string, bool) { if o == nil { return nil, false } - return o.Port, true + return o.Ip, true } -// SetPort sets field value -func (o *TargetGroupTarget) SetPort(v int32) { +// SetIp sets field value +func (o *TargetGroupTarget) SetIp(v string) { - o.Port = &v + o.Ip = &v } -// HasPort returns a boolean if a field has been set. -func (o *TargetGroupTarget) HasPort() bool { - if o != nil && o.Port != nil { +// HasIp returns a boolean if a field has been set. +func (o *TargetGroupTarget) HasIp() bool { + if o != nil && o.Ip != nil { return true } return false } -// GetWeight returns the Weight field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *TargetGroupTarget) GetWeight() *int32 { +// GetMaintenanceEnabled returns the MaintenanceEnabled field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupTarget) GetMaintenanceEnabled() *bool { if o == nil { return nil } - return o.Weight + return o.MaintenanceEnabled } -// GetWeightOk returns a tuple with the Weight field value +// GetMaintenanceEnabledOk returns a tuple with the MaintenanceEnabled field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupTarget) GetWeightOk() (*int32, bool) { +func (o *TargetGroupTarget) GetMaintenanceEnabledOk() (*bool, bool) { if o == nil { return nil, false } - return o.Weight, true + return o.MaintenanceEnabled, true } -// SetWeight sets field value -func (o *TargetGroupTarget) SetWeight(v int32) { +// SetMaintenanceEnabled sets field value +func (o *TargetGroupTarget) SetMaintenanceEnabled(v bool) { - o.Weight = &v + o.MaintenanceEnabled = &v } -// HasWeight returns a boolean if a field has been set. -func (o *TargetGroupTarget) HasWeight() bool { - if o != nil && o.Weight != nil { +// HasMaintenanceEnabled returns a boolean if a field has been set. +func (o *TargetGroupTarget) HasMaintenanceEnabled() bool { + if o != nil && o.MaintenanceEnabled != nil { return true } return false } -// GetHealthCheckEnabled returns the HealthCheckEnabled field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *TargetGroupTarget) GetHealthCheckEnabled() *bool { +// GetPort returns the Port field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupTarget) GetPort() *int32 { if o == nil { return nil } - return o.HealthCheckEnabled + return o.Port } -// GetHealthCheckEnabledOk returns a tuple with the HealthCheckEnabled field value +// GetPortOk returns a tuple with the Port field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupTarget) GetHealthCheckEnabledOk() (*bool, bool) { +func (o *TargetGroupTarget) GetPortOk() (*int32, bool) { if o == nil { return nil, false } - return o.HealthCheckEnabled, true + return o.Port, true } -// SetHealthCheckEnabled sets field value -func (o *TargetGroupTarget) SetHealthCheckEnabled(v bool) { +// SetPort sets field value +func (o *TargetGroupTarget) SetPort(v int32) { - o.HealthCheckEnabled = &v + o.Port = &v } -// HasHealthCheckEnabled returns a boolean if a field has been set. -func (o *TargetGroupTarget) HasHealthCheckEnabled() bool { - if o != nil && o.HealthCheckEnabled != nil { +// HasPort returns a boolean if a field has been set. +func (o *TargetGroupTarget) HasPort() bool { + if o != nil && o.Port != nil { return true } return false } -// GetMaintenanceEnabled returns the MaintenanceEnabled field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *TargetGroupTarget) GetMaintenanceEnabled() *bool { +// GetWeight returns the Weight field value +// If the value is explicit nil, nil is returned +func (o *TargetGroupTarget) GetWeight() *int32 { if o == nil { return nil } - return o.MaintenanceEnabled + return o.Weight } -// GetMaintenanceEnabledOk returns a tuple with the MaintenanceEnabled field value +// GetWeightOk returns a tuple with the Weight field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroupTarget) GetMaintenanceEnabledOk() (*bool, bool) { +func (o *TargetGroupTarget) GetWeightOk() (*int32, bool) { if o == nil { return nil, false } - return o.MaintenanceEnabled, true + return o.Weight, true } -// SetMaintenanceEnabled sets field value -func (o *TargetGroupTarget) SetMaintenanceEnabled(v bool) { +// SetWeight sets field value +func (o *TargetGroupTarget) SetWeight(v int32) { - o.MaintenanceEnabled = &v + o.Weight = &v } -// HasMaintenanceEnabled returns a boolean if a field has been set. -func (o *TargetGroupTarget) HasMaintenanceEnabled() bool { - if o != nil && o.MaintenanceEnabled != nil { +// HasWeight returns a boolean if a field has been set. +func (o *TargetGroupTarget) HasWeight() bool { + if o != nil && o.Weight != nil { return true } @@ -242,21 +242,26 @@ func (o *TargetGroupTarget) HasMaintenanceEnabled() bool { func (o TargetGroupTarget) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} + if o.HealthCheckEnabled != nil { + toSerialize["healthCheckEnabled"] = o.HealthCheckEnabled + } + if o.Ip != nil { toSerialize["ip"] = o.Ip } + + if o.MaintenanceEnabled != nil { + toSerialize["maintenanceEnabled"] = o.MaintenanceEnabled + } + if o.Port != nil { toSerialize["port"] = o.Port } + if o.Weight != nil { toSerialize["weight"] = o.Weight } - if o.HealthCheckEnabled != nil { - toSerialize["healthCheckEnabled"] = o.HealthCheckEnabled - } - if o.MaintenanceEnabled != nil { - toSerialize["maintenanceEnabled"] = o.MaintenanceEnabled - } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_groups.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_groups.go index ca5778f545b..521ca7b3fa3 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_groups.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_groups.go @@ -16,19 +16,19 @@ import ( // TargetGroups struct for TargetGroups type TargetGroups struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // The URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]TargetGroup `json:"items,omitempty"` + // The limit, specified in the request (if not specified, the endpoint's default pagination limit is used). + Limit *float32 `json:"limit,omitempty"` // The offset, specified in the request (if not is specified, 0 is used by default). Offset *float32 `json:"offset,omitempty"` - // The limit, specified in the request (if not specified, the endpoint's default pagination limit is used). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewTargetGroups instantiates a new TargetGroups object @@ -49,114 +49,114 @@ func NewTargetGroupsWithDefaults() *TargetGroups { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *TargetGroups) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *TargetGroups) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroups) GetIdOk() (*string, bool) { +func (o *TargetGroups) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *TargetGroups) SetId(v string) { +// SetLinks sets field value +func (o *TargetGroups) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *TargetGroups) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *TargetGroups) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *TargetGroups) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *TargetGroups) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroups) GetTypeOk() (*Type, bool) { +func (o *TargetGroups) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *TargetGroups) SetType(v Type) { +// SetHref sets field value +func (o *TargetGroups) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *TargetGroups) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *TargetGroups) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *TargetGroups) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *TargetGroups) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroups) GetHrefOk() (*string, bool) { +func (o *TargetGroups) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *TargetGroups) SetHref(v string) { +// SetId sets field value +func (o *TargetGroups) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *TargetGroups) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *TargetGroups) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *TargetGroups) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []TargetGroup will be returned +// If the value is explicit nil, nil is returned func (o *TargetGroups) GetItems() *[]TargetGroup { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *TargetGroups) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *TargetGroups) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *TargetGroups) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroups) GetOffsetOk() (*float32, bool) { +func (o *TargetGroups) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *TargetGroups) SetOffset(v float32) { +// SetLimit sets field value +func (o *TargetGroups) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *TargetGroups) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *TargetGroups) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *TargetGroups) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *TargetGroups) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroups) GetLimitOk() (*float32, bool) { +func (o *TargetGroups) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *TargetGroups) SetLimit(v float32) { +// SetOffset sets field value +func (o *TargetGroups) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *TargetGroups) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *TargetGroups) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *TargetGroups) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *TargetGroups) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetGroups) GetLinksOk() (*PaginationLinks, bool) { +func (o *TargetGroups) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *TargetGroups) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *TargetGroups) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *TargetGroups) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *TargetGroups) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *TargetGroups) HasLinks() bool { func (o TargetGroups) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_port_range.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_port_range.go index 9a1c39ea528..8c5281ed8a9 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_port_range.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_target_port_range.go @@ -16,10 +16,10 @@ import ( // TargetPortRange struct for TargetPortRange type TargetPortRange struct { - // Target port range start associated with the NAT Gateway rule. - Start *int32 `json:"start,omitempty"` // Target port range end associated with the NAT Gateway rule. End *int32 `json:"end,omitempty"` + // Target port range start associated with the NAT Gateway rule. + Start *int32 `json:"start,omitempty"` } // NewTargetPortRange instantiates a new TargetPortRange object @@ -40,76 +40,76 @@ func NewTargetPortRangeWithDefaults() *TargetPortRange { return &this } -// GetStart returns the Start field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *TargetPortRange) GetStart() *int32 { +// GetEnd returns the End field value +// If the value is explicit nil, nil is returned +func (o *TargetPortRange) GetEnd() *int32 { if o == nil { return nil } - return o.Start + return o.End } -// GetStartOk returns a tuple with the Start field value +// GetEndOk returns a tuple with the End field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetPortRange) GetStartOk() (*int32, bool) { +func (o *TargetPortRange) GetEndOk() (*int32, bool) { if o == nil { return nil, false } - return o.Start, true + return o.End, true } -// SetStart sets field value -func (o *TargetPortRange) SetStart(v int32) { +// SetEnd sets field value +func (o *TargetPortRange) SetEnd(v int32) { - o.Start = &v + o.End = &v } -// HasStart returns a boolean if a field has been set. -func (o *TargetPortRange) HasStart() bool { - if o != nil && o.Start != nil { +// HasEnd returns a boolean if a field has been set. +func (o *TargetPortRange) HasEnd() bool { + if o != nil && o.End != nil { return true } return false } -// GetEnd returns the End field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *TargetPortRange) GetEnd() *int32 { +// GetStart returns the Start field value +// If the value is explicit nil, nil is returned +func (o *TargetPortRange) GetStart() *int32 { if o == nil { return nil } - return o.End + return o.Start } -// GetEndOk returns a tuple with the End field value +// GetStartOk returns a tuple with the Start field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TargetPortRange) GetEndOk() (*int32, bool) { +func (o *TargetPortRange) GetStartOk() (*int32, bool) { if o == nil { return nil, false } - return o.End, true + return o.Start, true } -// SetEnd sets field value -func (o *TargetPortRange) SetEnd(v int32) { +// SetStart sets field value +func (o *TargetPortRange) SetStart(v int32) { - o.End = &v + o.Start = &v } -// HasEnd returns a boolean if a field has been set. -func (o *TargetPortRange) HasEnd() bool { - if o != nil && o.End != nil { +// HasStart returns a boolean if a field has been set. +func (o *TargetPortRange) HasStart() bool { + if o != nil && o.Start != nil { return true } @@ -118,12 +118,14 @@ func (o *TargetPortRange) HasEnd() bool { func (o TargetPortRange) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Start != nil { - toSerialize["start"] = o.Start - } if o.End != nil { toSerialize["end"] = o.End } + + if o.Start != nil { + toSerialize["start"] = o.Start + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_template.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_template.go index 48156f1066b..ad290d4090b 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_template.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_template.go @@ -16,14 +16,14 @@ import ( // Template struct for Template type Template struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *TemplateProperties `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewTemplate instantiates a new Template object @@ -46,190 +46,190 @@ func NewTemplateWithDefaults() *Template { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Template) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Template) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Template) GetIdOk() (*string, bool) { +func (o *Template) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Template) SetId(v string) { +// SetHref sets field value +func (o *Template) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Template) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Template) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Template) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Template) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Template) GetTypeOk() (*Type, bool) { +func (o *Template) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Template) SetType(v Type) { +// SetId sets field value +func (o *Template) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Template) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Template) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Template) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *Template) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Template) GetHrefOk() (*string, bool) { +func (o *Template) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *Template) SetHref(v string) { +// SetMetadata sets field value +func (o *Template) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *Template) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *Template) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *Template) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *Template) GetProperties() *TemplateProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Template) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *Template) GetPropertiesOk() (*TemplateProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *Template) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *Template) SetProperties(v TemplateProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *Template) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *Template) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for TemplateProperties will be returned -func (o *Template) GetProperties() *TemplateProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Template) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Template) GetPropertiesOk() (*TemplateProperties, bool) { +func (o *Template) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *Template) SetProperties(v TemplateProperties) { +// SetType sets field value +func (o *Template) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *Template) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *Template) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *Template) HasProperties() bool { func (o Template) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_template_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_template_properties.go index 5d661eee257..98d1150116a 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_template_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_template_properties.go @@ -16,10 +16,10 @@ import ( // TemplateProperties struct for TemplateProperties type TemplateProperties struct { - // The resource name. - Name *string `json:"name"` // The CPU cores count. Cores *float32 `json:"cores"` + // The resource name. + Name *string `json:"name"` // The RAM size in MB. Ram *float32 `json:"ram"` // The storage size in GB. @@ -30,11 +30,11 @@ type TemplateProperties struct { // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewTemplateProperties(name string, cores float32, ram float32, storageSize float32) *TemplateProperties { +func NewTemplateProperties(cores float32, name string, ram float32, storageSize float32) *TemplateProperties { this := TemplateProperties{} - this.Name = &name this.Cores = &cores + this.Name = &name this.Ram = &ram this.StorageSize = &storageSize @@ -49,76 +49,76 @@ func NewTemplatePropertiesWithDefaults() *TemplateProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *TemplateProperties) GetName() *string { +// GetCores returns the Cores field value +// If the value is explicit nil, nil is returned +func (o *TemplateProperties) GetCores() *float32 { if o == nil { return nil } - return o.Name + return o.Cores } -// GetNameOk returns a tuple with the Name field value +// GetCoresOk returns a tuple with the Cores field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TemplateProperties) GetNameOk() (*string, bool) { +func (o *TemplateProperties) GetCoresOk() (*float32, bool) { if o == nil { return nil, false } - return o.Name, true + return o.Cores, true } -// SetName sets field value -func (o *TemplateProperties) SetName(v string) { +// SetCores sets field value +func (o *TemplateProperties) SetCores(v float32) { - o.Name = &v + o.Cores = &v } -// HasName returns a boolean if a field has been set. -func (o *TemplateProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasCores returns a boolean if a field has been set. +func (o *TemplateProperties) HasCores() bool { + if o != nil && o.Cores != nil { return true } return false } -// GetCores returns the Cores field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *TemplateProperties) GetCores() *float32 { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *TemplateProperties) GetName() *string { if o == nil { return nil } - return o.Cores + return o.Name } -// GetCoresOk returns a tuple with the Cores field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *TemplateProperties) GetCoresOk() (*float32, bool) { +func (o *TemplateProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.Cores, true + return o.Name, true } -// SetCores sets field value -func (o *TemplateProperties) SetCores(v float32) { +// SetName sets field value +func (o *TemplateProperties) SetName(v string) { - o.Cores = &v + o.Name = &v } -// HasCores returns a boolean if a field has been set. -func (o *TemplateProperties) HasCores() bool { - if o != nil && o.Cores != nil { +// HasName returns a boolean if a field has been set. +func (o *TemplateProperties) HasName() bool { + if o != nil && o.Name != nil { return true } @@ -126,7 +126,7 @@ func (o *TemplateProperties) HasCores() bool { } // GetRam returns the Ram field value -// If the value is explicit nil, the zero value for float32 will be returned +// If the value is explicit nil, nil is returned func (o *TemplateProperties) GetRam() *float32 { if o == nil { return nil @@ -164,7 +164,7 @@ func (o *TemplateProperties) HasRam() bool { } // GetStorageSize returns the StorageSize field value -// If the value is explicit nil, the zero value for float32 will be returned +// If the value is explicit nil, nil is returned func (o *TemplateProperties) GetStorageSize() *float32 { if o == nil { return nil @@ -203,18 +203,22 @@ func (o *TemplateProperties) HasStorageSize() bool { func (o TemplateProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name - } if o.Cores != nil { toSerialize["cores"] = o.Cores } + + if o.Name != nil { + toSerialize["name"] = o.Name + } + if o.Ram != nil { toSerialize["ram"] = o.Ram } + if o.StorageSize != nil { toSerialize["storageSize"] = o.StorageSize } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_templates.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_templates.go index 1d6e9640ca7..c66eac10cc6 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_templates.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_templates.go @@ -16,14 +16,14 @@ import ( // Templates struct for Templates type Templates struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // The URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Template `json:"items,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewTemplates instantiates a new Templates object @@ -44,152 +44,152 @@ func NewTemplatesWithDefaults() *Templates { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Templates) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Templates) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Templates) GetIdOk() (*string, bool) { +func (o *Templates) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Templates) SetId(v string) { +// SetHref sets field value +func (o *Templates) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Templates) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Templates) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Templates) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Templates) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Templates) GetTypeOk() (*Type, bool) { +func (o *Templates) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Templates) SetType(v Type) { +// SetId sets field value +func (o *Templates) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Templates) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Templates) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Templates) GetHref() *string { +// GetItems returns the Items field value +// If the value is explicit nil, nil is returned +func (o *Templates) GetItems() *[]Template { if o == nil { return nil } - return o.Href + return o.Items } -// GetHrefOk returns a tuple with the Href field value +// GetItemsOk returns a tuple with the Items field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Templates) GetHrefOk() (*string, bool) { +func (o *Templates) GetItemsOk() (*[]Template, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Items, true } -// SetHref sets field value -func (o *Templates) SetHref(v string) { +// SetItems sets field value +func (o *Templates) SetItems(v []Template) { - o.Href = &v + o.Items = &v } -// HasHref returns a boolean if a field has been set. -func (o *Templates) HasHref() bool { - if o != nil && o.Href != nil { +// HasItems returns a boolean if a field has been set. +func (o *Templates) HasItems() bool { + if o != nil && o.Items != nil { return true } return false } -// GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Template will be returned -func (o *Templates) GetItems() *[]Template { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Templates) GetType() *Type { if o == nil { return nil } - return o.Items + return o.Type } -// GetItemsOk returns a tuple with the Items field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Templates) GetItemsOk() (*[]Template, bool) { +func (o *Templates) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Items, true + return o.Type, true } -// SetItems sets field value -func (o *Templates) SetItems(v []Template) { +// SetType sets field value +func (o *Templates) SetType(v Type) { - o.Items = &v + o.Type = &v } -// HasItems returns a boolean if a field has been set. -func (o *Templates) HasItems() bool { - if o != nil && o.Items != nil { +// HasType returns a boolean if a field has been set. +func (o *Templates) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -198,18 +198,22 @@ func (o *Templates) HasItems() bool { func (o Templates) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_token.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_token.go index 074e07ad673..c886b268073 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_token.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_token.go @@ -39,7 +39,7 @@ func NewTokenWithDefaults() *Token { } // GetToken returns the Token field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *Token) GetToken() *string { if o == nil { return nil @@ -81,6 +81,7 @@ func (o Token) MarshalJSON() ([]byte, error) { if o.Token != nil { toSerialize["token"] = o.Token } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_user.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_user.go index 14864be690f..38d1a9b063d 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_user.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_user.go @@ -16,15 +16,15 @@ import ( // User struct for User type User struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Entities *UsersEntities `json:"entities,omitempty"` // URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *UserMetadata `json:"metadata,omitempty"` Properties *UserProperties `json:"properties"` - Entities *UsersEntities `json:"entities,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewUser instantiates a new User object @@ -47,114 +47,114 @@ func NewUserWithDefaults() *User { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *User) GetId() *string { +// GetEntities returns the Entities field value +// If the value is explicit nil, nil is returned +func (o *User) GetEntities() *UsersEntities { if o == nil { return nil } - return o.Id + return o.Entities } -// GetIdOk returns a tuple with the Id field value +// GetEntitiesOk returns a tuple with the Entities field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *User) GetIdOk() (*string, bool) { +func (o *User) GetEntitiesOk() (*UsersEntities, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Entities, true } -// SetId sets field value -func (o *User) SetId(v string) { +// SetEntities sets field value +func (o *User) SetEntities(v UsersEntities) { - o.Id = &v + o.Entities = &v } -// HasId returns a boolean if a field has been set. -func (o *User) HasId() bool { - if o != nil && o.Id != nil { +// HasEntities returns a boolean if a field has been set. +func (o *User) HasEntities() bool { + if o != nil && o.Entities != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *User) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *User) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *User) GetTypeOk() (*Type, bool) { +func (o *User) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *User) SetType(v Type) { +// SetHref sets field value +func (o *User) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *User) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *User) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *User) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *User) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *User) GetHrefOk() (*string, bool) { +func (o *User) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *User) SetHref(v string) { +// SetId sets field value +func (o *User) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *User) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *User) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -162,7 +162,7 @@ func (o *User) HasHref() bool { } // GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for UserMetadata will be returned +// If the value is explicit nil, nil is returned func (o *User) GetMetadata() *UserMetadata { if o == nil { return nil @@ -200,7 +200,7 @@ func (o *User) HasMetadata() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for UserProperties will be returned +// If the value is explicit nil, nil is returned func (o *User) GetProperties() *UserProperties { if o == nil { return nil @@ -237,38 +237,38 @@ func (o *User) HasProperties() bool { return false } -// GetEntities returns the Entities field value -// If the value is explicit nil, the zero value for UsersEntities will be returned -func (o *User) GetEntities() *UsersEntities { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *User) GetType() *Type { if o == nil { return nil } - return o.Entities + return o.Type } -// GetEntitiesOk returns a tuple with the Entities field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *User) GetEntitiesOk() (*UsersEntities, bool) { +func (o *User) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Entities, true + return o.Type, true } -// SetEntities sets field value -func (o *User) SetEntities(v UsersEntities) { +// SetType sets field value +func (o *User) SetType(v Type) { - o.Entities = &v + o.Type = &v } -// HasEntities returns a boolean if a field has been set. -func (o *User) HasEntities() bool { - if o != nil && o.Entities != nil { +// HasType returns a boolean if a field has been set. +func (o *User) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -277,24 +277,30 @@ func (o *User) HasEntities() bool { func (o User) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Entities != nil { + toSerialize["entities"] = o.Entities } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } - if o.Entities != nil { - toSerialize["entities"] = o.Entities + + if o.Type != nil { + toSerialize["type"] = o.Type } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_metadata.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_metadata.go index da90dc00b89..de6738d715f 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_metadata.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_metadata.go @@ -17,10 +17,10 @@ import ( // UserMetadata struct for UserMetadata type UserMetadata struct { - // Resource's Entity Tag as defined in http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11 Entity Tag is also added as an 'ETag response header to requests which don't use 'depth' parameter. - Etag *string `json:"etag,omitempty"` // The time the user was created. CreatedDate *IonosTime + // Resource's Entity Tag as defined in http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11 Entity Tag is also added as an 'ETag response header to requests which don't use 'depth' parameter. + Etag *string `json:"etag,omitempty"` // The time of the last login by the user. LastLogin *IonosTime } @@ -43,83 +43,83 @@ func NewUserMetadataWithDefaults() *UserMetadata { return &this } -// GetEtag returns the Etag field value -// If the value is explicit nil, the zero value for string will be returned -func (o *UserMetadata) GetEtag() *string { +// GetCreatedDate returns the CreatedDate field value +// If the value is explicit nil, nil is returned +func (o *UserMetadata) GetCreatedDate() *time.Time { if o == nil { return nil } - return o.Etag + if o.CreatedDate == nil { + return nil + } + return &o.CreatedDate.Time } -// GetEtagOk returns a tuple with the Etag field value +// GetCreatedDateOk returns a tuple with the CreatedDate field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserMetadata) GetEtagOk() (*string, bool) { +func (o *UserMetadata) GetCreatedDateOk() (*time.Time, bool) { if o == nil { return nil, false } - return o.Etag, true + if o.CreatedDate == nil { + return nil, false + } + return &o.CreatedDate.Time, true + } -// SetEtag sets field value -func (o *UserMetadata) SetEtag(v string) { +// SetCreatedDate sets field value +func (o *UserMetadata) SetCreatedDate(v time.Time) { - o.Etag = &v + o.CreatedDate = &IonosTime{v} } -// HasEtag returns a boolean if a field has been set. -func (o *UserMetadata) HasEtag() bool { - if o != nil && o.Etag != nil { +// HasCreatedDate returns a boolean if a field has been set. +func (o *UserMetadata) HasCreatedDate() bool { + if o != nil && o.CreatedDate != nil { return true } return false } -// GetCreatedDate returns the CreatedDate field value -// If the value is explicit nil, the zero value for time.Time will be returned -func (o *UserMetadata) GetCreatedDate() *time.Time { +// GetEtag returns the Etag field value +// If the value is explicit nil, nil is returned +func (o *UserMetadata) GetEtag() *string { if o == nil { return nil } - if o.CreatedDate == nil { - return nil - } - return &o.CreatedDate.Time + return o.Etag } -// GetCreatedDateOk returns a tuple with the CreatedDate field value +// GetEtagOk returns a tuple with the Etag field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserMetadata) GetCreatedDateOk() (*time.Time, bool) { +func (o *UserMetadata) GetEtagOk() (*string, bool) { if o == nil { return nil, false } - if o.CreatedDate == nil { - return nil, false - } - return &o.CreatedDate.Time, true - + return o.Etag, true } -// SetCreatedDate sets field value -func (o *UserMetadata) SetCreatedDate(v time.Time) { +// SetEtag sets field value +func (o *UserMetadata) SetEtag(v string) { - o.CreatedDate = &IonosTime{v} + o.Etag = &v } -// HasCreatedDate returns a boolean if a field has been set. -func (o *UserMetadata) HasCreatedDate() bool { - if o != nil && o.CreatedDate != nil { +// HasEtag returns a boolean if a field has been set. +func (o *UserMetadata) HasEtag() bool { + if o != nil && o.Etag != nil { return true } @@ -127,7 +127,7 @@ func (o *UserMetadata) HasCreatedDate() bool { } // GetLastLogin returns the LastLogin field value -// If the value is explicit nil, the zero value for time.Time will be returned +// If the value is explicit nil, nil is returned func (o *UserMetadata) GetLastLogin() *time.Time { if o == nil { return nil @@ -173,15 +173,18 @@ func (o *UserMetadata) HasLastLogin() bool { func (o UserMetadata) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Etag != nil { - toSerialize["etag"] = o.Etag - } if o.CreatedDate != nil { toSerialize["createdDate"] = o.CreatedDate } + + if o.Etag != nil { + toSerialize["etag"] = o.Etag + } + if o.LastLogin != nil { toSerialize["lastLogin"] = o.LastLogin } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_post.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_post.go index 912dc339199..cfbe91439f2 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_post.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_post.go @@ -40,7 +40,7 @@ func NewUserPostWithDefaults() *UserPost { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for UserPropertiesPost will be returned +// If the value is explicit nil, nil is returned func (o *UserPost) GetProperties() *UserPropertiesPost { if o == nil { return nil @@ -82,6 +82,7 @@ func (o UserPost) MarshalJSON() ([]byte, error) { if o.Properties != nil { toSerialize["properties"] = o.Properties } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_properties.go index 6ff0ff0f00c..7fadd2b431f 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_properties.go @@ -16,22 +16,22 @@ import ( // UserProperties struct for UserProperties type UserProperties struct { - // The first name of the user. - Firstname *string `json:"firstname,omitempty"` - // The last name of the user. - Lastname *string `json:"lastname,omitempty"` - // The email address of the user. - Email *string `json:"email,omitempty"` + // Indicates if the user is active. + Active *bool `json:"active,omitempty"` // Indicates if the user has admin rights. Administrator *bool `json:"administrator,omitempty"` + // The email address of the user. + Email *string `json:"email,omitempty"` + // The first name of the user. + Firstname *string `json:"firstname,omitempty"` // Indicates if secure authentication should be forced on the user. ForceSecAuth *bool `json:"forceSecAuth,omitempty"` - // Indicates if secure authentication is active for the user. - SecAuthActive *bool `json:"secAuthActive,omitempty"` + // The last name of the user. + Lastname *string `json:"lastname,omitempty"` // Canonical (S3) ID of the user for a given identity. S3CanonicalUserId *string `json:"s3CanonicalUserId,omitempty"` - // Indicates if the user is active. - Active *bool `json:"active,omitempty"` + // Indicates if secure authentication is active for the user. + SecAuthActive *bool `json:"secAuthActive,omitempty"` } // NewUserProperties instantiates a new UserProperties object @@ -52,76 +52,76 @@ func NewUserPropertiesWithDefaults() *UserProperties { return &this } -// GetFirstname returns the Firstname field value -// If the value is explicit nil, the zero value for string will be returned -func (o *UserProperties) GetFirstname() *string { +// GetActive returns the Active field value +// If the value is explicit nil, nil is returned +func (o *UserProperties) GetActive() *bool { if o == nil { return nil } - return o.Firstname + return o.Active } -// GetFirstnameOk returns a tuple with the Firstname field value +// GetActiveOk returns a tuple with the Active field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserProperties) GetFirstnameOk() (*string, bool) { +func (o *UserProperties) GetActiveOk() (*bool, bool) { if o == nil { return nil, false } - return o.Firstname, true + return o.Active, true } -// SetFirstname sets field value -func (o *UserProperties) SetFirstname(v string) { +// SetActive sets field value +func (o *UserProperties) SetActive(v bool) { - o.Firstname = &v + o.Active = &v } -// HasFirstname returns a boolean if a field has been set. -func (o *UserProperties) HasFirstname() bool { - if o != nil && o.Firstname != nil { +// HasActive returns a boolean if a field has been set. +func (o *UserProperties) HasActive() bool { + if o != nil && o.Active != nil { return true } return false } -// GetLastname returns the Lastname field value -// If the value is explicit nil, the zero value for string will be returned -func (o *UserProperties) GetLastname() *string { +// GetAdministrator returns the Administrator field value +// If the value is explicit nil, nil is returned +func (o *UserProperties) GetAdministrator() *bool { if o == nil { return nil } - return o.Lastname + return o.Administrator } -// GetLastnameOk returns a tuple with the Lastname field value +// GetAdministratorOk returns a tuple with the Administrator field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserProperties) GetLastnameOk() (*string, bool) { +func (o *UserProperties) GetAdministratorOk() (*bool, bool) { if o == nil { return nil, false } - return o.Lastname, true + return o.Administrator, true } -// SetLastname sets field value -func (o *UserProperties) SetLastname(v string) { +// SetAdministrator sets field value +func (o *UserProperties) SetAdministrator(v bool) { - o.Lastname = &v + o.Administrator = &v } -// HasLastname returns a boolean if a field has been set. -func (o *UserProperties) HasLastname() bool { - if o != nil && o.Lastname != nil { +// HasAdministrator returns a boolean if a field has been set. +func (o *UserProperties) HasAdministrator() bool { + if o != nil && o.Administrator != nil { return true } @@ -129,7 +129,7 @@ func (o *UserProperties) HasLastname() bool { } // GetEmail returns the Email field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *UserProperties) GetEmail() *string { if o == nil { return nil @@ -166,38 +166,38 @@ func (o *UserProperties) HasEmail() bool { return false } -// GetAdministrator returns the Administrator field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *UserProperties) GetAdministrator() *bool { +// GetFirstname returns the Firstname field value +// If the value is explicit nil, nil is returned +func (o *UserProperties) GetFirstname() *string { if o == nil { return nil } - return o.Administrator + return o.Firstname } -// GetAdministratorOk returns a tuple with the Administrator field value +// GetFirstnameOk returns a tuple with the Firstname field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserProperties) GetAdministratorOk() (*bool, bool) { +func (o *UserProperties) GetFirstnameOk() (*string, bool) { if o == nil { return nil, false } - return o.Administrator, true + return o.Firstname, true } -// SetAdministrator sets field value -func (o *UserProperties) SetAdministrator(v bool) { +// SetFirstname sets field value +func (o *UserProperties) SetFirstname(v string) { - o.Administrator = &v + o.Firstname = &v } -// HasAdministrator returns a boolean if a field has been set. -func (o *UserProperties) HasAdministrator() bool { - if o != nil && o.Administrator != nil { +// HasFirstname returns a boolean if a field has been set. +func (o *UserProperties) HasFirstname() bool { + if o != nil && o.Firstname != nil { return true } @@ -205,7 +205,7 @@ func (o *UserProperties) HasAdministrator() bool { } // GetForceSecAuth returns the ForceSecAuth field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *UserProperties) GetForceSecAuth() *bool { if o == nil { return nil @@ -242,38 +242,38 @@ func (o *UserProperties) HasForceSecAuth() bool { return false } -// GetSecAuthActive returns the SecAuthActive field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *UserProperties) GetSecAuthActive() *bool { +// GetLastname returns the Lastname field value +// If the value is explicit nil, nil is returned +func (o *UserProperties) GetLastname() *string { if o == nil { return nil } - return o.SecAuthActive + return o.Lastname } -// GetSecAuthActiveOk returns a tuple with the SecAuthActive field value +// GetLastnameOk returns a tuple with the Lastname field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserProperties) GetSecAuthActiveOk() (*bool, bool) { +func (o *UserProperties) GetLastnameOk() (*string, bool) { if o == nil { return nil, false } - return o.SecAuthActive, true + return o.Lastname, true } -// SetSecAuthActive sets field value -func (o *UserProperties) SetSecAuthActive(v bool) { +// SetLastname sets field value +func (o *UserProperties) SetLastname(v string) { - o.SecAuthActive = &v + o.Lastname = &v } -// HasSecAuthActive returns a boolean if a field has been set. -func (o *UserProperties) HasSecAuthActive() bool { - if o != nil && o.SecAuthActive != nil { +// HasLastname returns a boolean if a field has been set. +func (o *UserProperties) HasLastname() bool { + if o != nil && o.Lastname != nil { return true } @@ -281,7 +281,7 @@ func (o *UserProperties) HasSecAuthActive() bool { } // GetS3CanonicalUserId returns the S3CanonicalUserId field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *UserProperties) GetS3CanonicalUserId() *string { if o == nil { return nil @@ -318,38 +318,38 @@ func (o *UserProperties) HasS3CanonicalUserId() bool { return false } -// GetActive returns the Active field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *UserProperties) GetActive() *bool { +// GetSecAuthActive returns the SecAuthActive field value +// If the value is explicit nil, nil is returned +func (o *UserProperties) GetSecAuthActive() *bool { if o == nil { return nil } - return o.Active + return o.SecAuthActive } -// GetActiveOk returns a tuple with the Active field value +// GetSecAuthActiveOk returns a tuple with the SecAuthActive field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserProperties) GetActiveOk() (*bool, bool) { +func (o *UserProperties) GetSecAuthActiveOk() (*bool, bool) { if o == nil { return nil, false } - return o.Active, true + return o.SecAuthActive, true } -// SetActive sets field value -func (o *UserProperties) SetActive(v bool) { +// SetSecAuthActive sets field value +func (o *UserProperties) SetSecAuthActive(v bool) { - o.Active = &v + o.SecAuthActive = &v } -// HasActive returns a boolean if a field has been set. -func (o *UserProperties) HasActive() bool { - if o != nil && o.Active != nil { +// HasSecAuthActive returns a boolean if a field has been set. +func (o *UserProperties) HasSecAuthActive() bool { + if o != nil && o.SecAuthActive != nil { return true } @@ -358,30 +358,38 @@ func (o *UserProperties) HasActive() bool { func (o UserProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Firstname != nil { - toSerialize["firstname"] = o.Firstname + if o.Active != nil { + toSerialize["active"] = o.Active } - if o.Lastname != nil { - toSerialize["lastname"] = o.Lastname + + if o.Administrator != nil { + toSerialize["administrator"] = o.Administrator } + if o.Email != nil { toSerialize["email"] = o.Email } - if o.Administrator != nil { - toSerialize["administrator"] = o.Administrator + + if o.Firstname != nil { + toSerialize["firstname"] = o.Firstname } + if o.ForceSecAuth != nil { toSerialize["forceSecAuth"] = o.ForceSecAuth } - if o.SecAuthActive != nil { - toSerialize["secAuthActive"] = o.SecAuthActive + + if o.Lastname != nil { + toSerialize["lastname"] = o.Lastname } + if o.S3CanonicalUserId != nil { toSerialize["s3CanonicalUserId"] = o.S3CanonicalUserId } - if o.Active != nil { - toSerialize["active"] = o.Active + + if o.SecAuthActive != nil { + toSerialize["secAuthActive"] = o.SecAuthActive } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_properties_post.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_properties_post.go index 463eb6dc3a3..fb4e9026f5b 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_properties_post.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_properties_post.go @@ -16,22 +16,22 @@ import ( // UserPropertiesPost struct for UserPropertiesPost type UserPropertiesPost struct { - // The first name of the user. - Firstname *string `json:"firstname,omitempty"` - // The last name of the user. - Lastname *string `json:"lastname,omitempty"` - // The email address of the user. - Email *string `json:"email,omitempty"` + // Indicates if the user is active. + Active *bool `json:"active,omitempty"` // Indicates if the user has admin rights. Administrator *bool `json:"administrator,omitempty"` + // The email address of the user. + Email *string `json:"email,omitempty"` + // The first name of the user. + Firstname *string `json:"firstname,omitempty"` // Indicates if secure authentication should be forced on the user. ForceSecAuth *bool `json:"forceSecAuth,omitempty"` - // Indicates if secure authentication is active for the user. - SecAuthActive *bool `json:"secAuthActive,omitempty"` + // The last name of the user. + Lastname *string `json:"lastname,omitempty"` // User password. Password *string `json:"password,omitempty"` - // Indicates if the user is active. - Active *bool `json:"active,omitempty"` + // Indicates if secure authentication is active for the user. + SecAuthActive *bool `json:"secAuthActive,omitempty"` } // NewUserPropertiesPost instantiates a new UserPropertiesPost object @@ -52,76 +52,76 @@ func NewUserPropertiesPostWithDefaults() *UserPropertiesPost { return &this } -// GetFirstname returns the Firstname field value -// If the value is explicit nil, the zero value for string will be returned -func (o *UserPropertiesPost) GetFirstname() *string { +// GetActive returns the Active field value +// If the value is explicit nil, nil is returned +func (o *UserPropertiesPost) GetActive() *bool { if o == nil { return nil } - return o.Firstname + return o.Active } -// GetFirstnameOk returns a tuple with the Firstname field value +// GetActiveOk returns a tuple with the Active field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserPropertiesPost) GetFirstnameOk() (*string, bool) { +func (o *UserPropertiesPost) GetActiveOk() (*bool, bool) { if o == nil { return nil, false } - return o.Firstname, true + return o.Active, true } -// SetFirstname sets field value -func (o *UserPropertiesPost) SetFirstname(v string) { +// SetActive sets field value +func (o *UserPropertiesPost) SetActive(v bool) { - o.Firstname = &v + o.Active = &v } -// HasFirstname returns a boolean if a field has been set. -func (o *UserPropertiesPost) HasFirstname() bool { - if o != nil && o.Firstname != nil { +// HasActive returns a boolean if a field has been set. +func (o *UserPropertiesPost) HasActive() bool { + if o != nil && o.Active != nil { return true } return false } -// GetLastname returns the Lastname field value -// If the value is explicit nil, the zero value for string will be returned -func (o *UserPropertiesPost) GetLastname() *string { +// GetAdministrator returns the Administrator field value +// If the value is explicit nil, nil is returned +func (o *UserPropertiesPost) GetAdministrator() *bool { if o == nil { return nil } - return o.Lastname + return o.Administrator } -// GetLastnameOk returns a tuple with the Lastname field value +// GetAdministratorOk returns a tuple with the Administrator field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserPropertiesPost) GetLastnameOk() (*string, bool) { +func (o *UserPropertiesPost) GetAdministratorOk() (*bool, bool) { if o == nil { return nil, false } - return o.Lastname, true + return o.Administrator, true } -// SetLastname sets field value -func (o *UserPropertiesPost) SetLastname(v string) { +// SetAdministrator sets field value +func (o *UserPropertiesPost) SetAdministrator(v bool) { - o.Lastname = &v + o.Administrator = &v } -// HasLastname returns a boolean if a field has been set. -func (o *UserPropertiesPost) HasLastname() bool { - if o != nil && o.Lastname != nil { +// HasAdministrator returns a boolean if a field has been set. +func (o *UserPropertiesPost) HasAdministrator() bool { + if o != nil && o.Administrator != nil { return true } @@ -129,7 +129,7 @@ func (o *UserPropertiesPost) HasLastname() bool { } // GetEmail returns the Email field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *UserPropertiesPost) GetEmail() *string { if o == nil { return nil @@ -166,38 +166,38 @@ func (o *UserPropertiesPost) HasEmail() bool { return false } -// GetAdministrator returns the Administrator field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *UserPropertiesPost) GetAdministrator() *bool { +// GetFirstname returns the Firstname field value +// If the value is explicit nil, nil is returned +func (o *UserPropertiesPost) GetFirstname() *string { if o == nil { return nil } - return o.Administrator + return o.Firstname } -// GetAdministratorOk returns a tuple with the Administrator field value +// GetFirstnameOk returns a tuple with the Firstname field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserPropertiesPost) GetAdministratorOk() (*bool, bool) { +func (o *UserPropertiesPost) GetFirstnameOk() (*string, bool) { if o == nil { return nil, false } - return o.Administrator, true + return o.Firstname, true } -// SetAdministrator sets field value -func (o *UserPropertiesPost) SetAdministrator(v bool) { +// SetFirstname sets field value +func (o *UserPropertiesPost) SetFirstname(v string) { - o.Administrator = &v + o.Firstname = &v } -// HasAdministrator returns a boolean if a field has been set. -func (o *UserPropertiesPost) HasAdministrator() bool { - if o != nil && o.Administrator != nil { +// HasFirstname returns a boolean if a field has been set. +func (o *UserPropertiesPost) HasFirstname() bool { + if o != nil && o.Firstname != nil { return true } @@ -205,7 +205,7 @@ func (o *UserPropertiesPost) HasAdministrator() bool { } // GetForceSecAuth returns the ForceSecAuth field value -// If the value is explicit nil, the zero value for bool will be returned +// If the value is explicit nil, nil is returned func (o *UserPropertiesPost) GetForceSecAuth() *bool { if o == nil { return nil @@ -242,38 +242,38 @@ func (o *UserPropertiesPost) HasForceSecAuth() bool { return false } -// GetSecAuthActive returns the SecAuthActive field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *UserPropertiesPost) GetSecAuthActive() *bool { +// GetLastname returns the Lastname field value +// If the value is explicit nil, nil is returned +func (o *UserPropertiesPost) GetLastname() *string { if o == nil { return nil } - return o.SecAuthActive + return o.Lastname } -// GetSecAuthActiveOk returns a tuple with the SecAuthActive field value +// GetLastnameOk returns a tuple with the Lastname field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserPropertiesPost) GetSecAuthActiveOk() (*bool, bool) { +func (o *UserPropertiesPost) GetLastnameOk() (*string, bool) { if o == nil { return nil, false } - return o.SecAuthActive, true + return o.Lastname, true } -// SetSecAuthActive sets field value -func (o *UserPropertiesPost) SetSecAuthActive(v bool) { +// SetLastname sets field value +func (o *UserPropertiesPost) SetLastname(v string) { - o.SecAuthActive = &v + o.Lastname = &v } -// HasSecAuthActive returns a boolean if a field has been set. -func (o *UserPropertiesPost) HasSecAuthActive() bool { - if o != nil && o.SecAuthActive != nil { +// HasLastname returns a boolean if a field has been set. +func (o *UserPropertiesPost) HasLastname() bool { + if o != nil && o.Lastname != nil { return true } @@ -281,7 +281,7 @@ func (o *UserPropertiesPost) HasSecAuthActive() bool { } // GetPassword returns the Password field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *UserPropertiesPost) GetPassword() *string { if o == nil { return nil @@ -318,38 +318,38 @@ func (o *UserPropertiesPost) HasPassword() bool { return false } -// GetActive returns the Active field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *UserPropertiesPost) GetActive() *bool { +// GetSecAuthActive returns the SecAuthActive field value +// If the value is explicit nil, nil is returned +func (o *UserPropertiesPost) GetSecAuthActive() *bool { if o == nil { return nil } - return o.Active + return o.SecAuthActive } -// GetActiveOk returns a tuple with the Active field value +// GetSecAuthActiveOk returns a tuple with the SecAuthActive field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserPropertiesPost) GetActiveOk() (*bool, bool) { +func (o *UserPropertiesPost) GetSecAuthActiveOk() (*bool, bool) { if o == nil { return nil, false } - return o.Active, true + return o.SecAuthActive, true } -// SetActive sets field value -func (o *UserPropertiesPost) SetActive(v bool) { +// SetSecAuthActive sets field value +func (o *UserPropertiesPost) SetSecAuthActive(v bool) { - o.Active = &v + o.SecAuthActive = &v } -// HasActive returns a boolean if a field has been set. -func (o *UserPropertiesPost) HasActive() bool { - if o != nil && o.Active != nil { +// HasSecAuthActive returns a boolean if a field has been set. +func (o *UserPropertiesPost) HasSecAuthActive() bool { + if o != nil && o.SecAuthActive != nil { return true } @@ -358,30 +358,38 @@ func (o *UserPropertiesPost) HasActive() bool { func (o UserPropertiesPost) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Firstname != nil { - toSerialize["firstname"] = o.Firstname + if o.Active != nil { + toSerialize["active"] = o.Active } - if o.Lastname != nil { - toSerialize["lastname"] = o.Lastname + + if o.Administrator != nil { + toSerialize["administrator"] = o.Administrator } + if o.Email != nil { toSerialize["email"] = o.Email } - if o.Administrator != nil { - toSerialize["administrator"] = o.Administrator + + if o.Firstname != nil { + toSerialize["firstname"] = o.Firstname } + if o.ForceSecAuth != nil { toSerialize["forceSecAuth"] = o.ForceSecAuth } - if o.SecAuthActive != nil { - toSerialize["secAuthActive"] = o.SecAuthActive + + if o.Lastname != nil { + toSerialize["lastname"] = o.Lastname } + if o.Password != nil { toSerialize["password"] = o.Password } - if o.Active != nil { - toSerialize["active"] = o.Active + + if o.SecAuthActive != nil { + toSerialize["secAuthActive"] = o.SecAuthActive } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_properties_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_properties_put.go index 778c3b0cfc5..d0ad92946ec 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_properties_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_properties_put.go @@ -16,22 +16,22 @@ import ( // UserPropertiesPut struct for UserPropertiesPut type UserPropertiesPut struct { + // Indicates if the user is active. + Active *bool `json:"active,omitempty"` + // Indicates if the user has admin rights. + Administrator *bool `json:"administrator,omitempty"` + // The email address of the user. + Email *string `json:"email,omitempty"` // The first name of the user. Firstname *string `json:"firstname,omitempty"` + // Indicates if secure authentication should be forced on the user. + ForceSecAuth *bool `json:"forceSecAuth,omitempty"` // The last name of the user. Lastname *string `json:"lastname,omitempty"` - // The email address of the user. - Email *string `json:"email,omitempty"` // password of the user Password *string `json:"password,omitempty"` - // Indicates if the user has admin rights. - Administrator *bool `json:"administrator,omitempty"` - // Indicates if secure authentication should be forced on the user. - ForceSecAuth *bool `json:"forceSecAuth,omitempty"` // Indicates if secure authentication is active for the user. SecAuthActive *bool `json:"secAuthActive,omitempty"` - // Indicates if the user is active. - Active *bool `json:"active,omitempty"` } // NewUserPropertiesPut instantiates a new UserPropertiesPut object @@ -52,76 +52,76 @@ func NewUserPropertiesPutWithDefaults() *UserPropertiesPut { return &this } -// GetFirstname returns the Firstname field value -// If the value is explicit nil, the zero value for string will be returned -func (o *UserPropertiesPut) GetFirstname() *string { +// GetActive returns the Active field value +// If the value is explicit nil, nil is returned +func (o *UserPropertiesPut) GetActive() *bool { if o == nil { return nil } - return o.Firstname + return o.Active } -// GetFirstnameOk returns a tuple with the Firstname field value +// GetActiveOk returns a tuple with the Active field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserPropertiesPut) GetFirstnameOk() (*string, bool) { +func (o *UserPropertiesPut) GetActiveOk() (*bool, bool) { if o == nil { return nil, false } - return o.Firstname, true + return o.Active, true } -// SetFirstname sets field value -func (o *UserPropertiesPut) SetFirstname(v string) { +// SetActive sets field value +func (o *UserPropertiesPut) SetActive(v bool) { - o.Firstname = &v + o.Active = &v } -// HasFirstname returns a boolean if a field has been set. -func (o *UserPropertiesPut) HasFirstname() bool { - if o != nil && o.Firstname != nil { +// HasActive returns a boolean if a field has been set. +func (o *UserPropertiesPut) HasActive() bool { + if o != nil && o.Active != nil { return true } return false } -// GetLastname returns the Lastname field value -// If the value is explicit nil, the zero value for string will be returned -func (o *UserPropertiesPut) GetLastname() *string { +// GetAdministrator returns the Administrator field value +// If the value is explicit nil, nil is returned +func (o *UserPropertiesPut) GetAdministrator() *bool { if o == nil { return nil } - return o.Lastname + return o.Administrator } -// GetLastnameOk returns a tuple with the Lastname field value +// GetAdministratorOk returns a tuple with the Administrator field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserPropertiesPut) GetLastnameOk() (*string, bool) { +func (o *UserPropertiesPut) GetAdministratorOk() (*bool, bool) { if o == nil { return nil, false } - return o.Lastname, true + return o.Administrator, true } -// SetLastname sets field value -func (o *UserPropertiesPut) SetLastname(v string) { +// SetAdministrator sets field value +func (o *UserPropertiesPut) SetAdministrator(v bool) { - o.Lastname = &v + o.Administrator = &v } -// HasLastname returns a boolean if a field has been set. -func (o *UserPropertiesPut) HasLastname() bool { - if o != nil && o.Lastname != nil { +// HasAdministrator returns a boolean if a field has been set. +func (o *UserPropertiesPut) HasAdministrator() bool { + if o != nil && o.Administrator != nil { return true } @@ -129,7 +129,7 @@ func (o *UserPropertiesPut) HasLastname() bool { } // GetEmail returns the Email field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *UserPropertiesPut) GetEmail() *string { if o == nil { return nil @@ -166,190 +166,190 @@ func (o *UserPropertiesPut) HasEmail() bool { return false } -// GetPassword returns the Password field value -// If the value is explicit nil, the zero value for string will be returned -func (o *UserPropertiesPut) GetPassword() *string { +// GetFirstname returns the Firstname field value +// If the value is explicit nil, nil is returned +func (o *UserPropertiesPut) GetFirstname() *string { if o == nil { return nil } - return o.Password + return o.Firstname } -// GetPasswordOk returns a tuple with the Password field value +// GetFirstnameOk returns a tuple with the Firstname field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserPropertiesPut) GetPasswordOk() (*string, bool) { +func (o *UserPropertiesPut) GetFirstnameOk() (*string, bool) { if o == nil { return nil, false } - return o.Password, true + return o.Firstname, true } -// SetPassword sets field value -func (o *UserPropertiesPut) SetPassword(v string) { +// SetFirstname sets field value +func (o *UserPropertiesPut) SetFirstname(v string) { - o.Password = &v + o.Firstname = &v } -// HasPassword returns a boolean if a field has been set. -func (o *UserPropertiesPut) HasPassword() bool { - if o != nil && o.Password != nil { +// HasFirstname returns a boolean if a field has been set. +func (o *UserPropertiesPut) HasFirstname() bool { + if o != nil && o.Firstname != nil { return true } return false } -// GetAdministrator returns the Administrator field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *UserPropertiesPut) GetAdministrator() *bool { +// GetForceSecAuth returns the ForceSecAuth field value +// If the value is explicit nil, nil is returned +func (o *UserPropertiesPut) GetForceSecAuth() *bool { if o == nil { return nil } - return o.Administrator + return o.ForceSecAuth } -// GetAdministratorOk returns a tuple with the Administrator field value +// GetForceSecAuthOk returns a tuple with the ForceSecAuth field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserPropertiesPut) GetAdministratorOk() (*bool, bool) { +func (o *UserPropertiesPut) GetForceSecAuthOk() (*bool, bool) { if o == nil { return nil, false } - return o.Administrator, true + return o.ForceSecAuth, true } -// SetAdministrator sets field value -func (o *UserPropertiesPut) SetAdministrator(v bool) { +// SetForceSecAuth sets field value +func (o *UserPropertiesPut) SetForceSecAuth(v bool) { - o.Administrator = &v + o.ForceSecAuth = &v } -// HasAdministrator returns a boolean if a field has been set. -func (o *UserPropertiesPut) HasAdministrator() bool { - if o != nil && o.Administrator != nil { +// HasForceSecAuth returns a boolean if a field has been set. +func (o *UserPropertiesPut) HasForceSecAuth() bool { + if o != nil && o.ForceSecAuth != nil { return true } return false } -// GetForceSecAuth returns the ForceSecAuth field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *UserPropertiesPut) GetForceSecAuth() *bool { +// GetLastname returns the Lastname field value +// If the value is explicit nil, nil is returned +func (o *UserPropertiesPut) GetLastname() *string { if o == nil { return nil } - return o.ForceSecAuth + return o.Lastname } -// GetForceSecAuthOk returns a tuple with the ForceSecAuth field value +// GetLastnameOk returns a tuple with the Lastname field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserPropertiesPut) GetForceSecAuthOk() (*bool, bool) { +func (o *UserPropertiesPut) GetLastnameOk() (*string, bool) { if o == nil { return nil, false } - return o.ForceSecAuth, true + return o.Lastname, true } -// SetForceSecAuth sets field value -func (o *UserPropertiesPut) SetForceSecAuth(v bool) { +// SetLastname sets field value +func (o *UserPropertiesPut) SetLastname(v string) { - o.ForceSecAuth = &v + o.Lastname = &v } -// HasForceSecAuth returns a boolean if a field has been set. -func (o *UserPropertiesPut) HasForceSecAuth() bool { - if o != nil && o.ForceSecAuth != nil { +// HasLastname returns a boolean if a field has been set. +func (o *UserPropertiesPut) HasLastname() bool { + if o != nil && o.Lastname != nil { return true } return false } -// GetSecAuthActive returns the SecAuthActive field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *UserPropertiesPut) GetSecAuthActive() *bool { +// GetPassword returns the Password field value +// If the value is explicit nil, nil is returned +func (o *UserPropertiesPut) GetPassword() *string { if o == nil { return nil } - return o.SecAuthActive + return o.Password } -// GetSecAuthActiveOk returns a tuple with the SecAuthActive field value +// GetPasswordOk returns a tuple with the Password field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserPropertiesPut) GetSecAuthActiveOk() (*bool, bool) { +func (o *UserPropertiesPut) GetPasswordOk() (*string, bool) { if o == nil { return nil, false } - return o.SecAuthActive, true + return o.Password, true } -// SetSecAuthActive sets field value -func (o *UserPropertiesPut) SetSecAuthActive(v bool) { +// SetPassword sets field value +func (o *UserPropertiesPut) SetPassword(v string) { - o.SecAuthActive = &v + o.Password = &v } -// HasSecAuthActive returns a boolean if a field has been set. -func (o *UserPropertiesPut) HasSecAuthActive() bool { - if o != nil && o.SecAuthActive != nil { +// HasPassword returns a boolean if a field has been set. +func (o *UserPropertiesPut) HasPassword() bool { + if o != nil && o.Password != nil { return true } return false } -// GetActive returns the Active field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *UserPropertiesPut) GetActive() *bool { +// GetSecAuthActive returns the SecAuthActive field value +// If the value is explicit nil, nil is returned +func (o *UserPropertiesPut) GetSecAuthActive() *bool { if o == nil { return nil } - return o.Active + return o.SecAuthActive } -// GetActiveOk returns a tuple with the Active field value +// GetSecAuthActiveOk returns a tuple with the SecAuthActive field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UserPropertiesPut) GetActiveOk() (*bool, bool) { +func (o *UserPropertiesPut) GetSecAuthActiveOk() (*bool, bool) { if o == nil { return nil, false } - return o.Active, true + return o.SecAuthActive, true } -// SetActive sets field value -func (o *UserPropertiesPut) SetActive(v bool) { +// SetSecAuthActive sets field value +func (o *UserPropertiesPut) SetSecAuthActive(v bool) { - o.Active = &v + o.SecAuthActive = &v } -// HasActive returns a boolean if a field has been set. -func (o *UserPropertiesPut) HasActive() bool { - if o != nil && o.Active != nil { +// HasSecAuthActive returns a boolean if a field has been set. +func (o *UserPropertiesPut) HasSecAuthActive() bool { + if o != nil && o.SecAuthActive != nil { return true } @@ -358,30 +358,38 @@ func (o *UserPropertiesPut) HasActive() bool { func (o UserPropertiesPut) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Firstname != nil { - toSerialize["firstname"] = o.Firstname + if o.Active != nil { + toSerialize["active"] = o.Active } - if o.Lastname != nil { - toSerialize["lastname"] = o.Lastname + + if o.Administrator != nil { + toSerialize["administrator"] = o.Administrator } + if o.Email != nil { toSerialize["email"] = o.Email } - if o.Password != nil { - toSerialize["password"] = o.Password - } - if o.Administrator != nil { - toSerialize["administrator"] = o.Administrator + + if o.Firstname != nil { + toSerialize["firstname"] = o.Firstname } + if o.ForceSecAuth != nil { toSerialize["forceSecAuth"] = o.ForceSecAuth } + + if o.Lastname != nil { + toSerialize["lastname"] = o.Lastname + } + + if o.Password != nil { + toSerialize["password"] = o.Password + } + if o.SecAuthActive != nil { toSerialize["secAuthActive"] = o.SecAuthActive } - if o.Active != nil { - toSerialize["active"] = o.Active - } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_put.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_put.go index b45261f2f44..9e0c992c990 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_put.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_user_put.go @@ -42,7 +42,7 @@ func NewUserPutWithDefaults() *UserPut { } // GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned +// If the value is explicit nil, nil is returned func (o *UserPut) GetId() *string { if o == nil { return nil @@ -80,7 +80,7 @@ func (o *UserPut) HasId() bool { } // GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for UserPropertiesPut will be returned +// If the value is explicit nil, nil is returned func (o *UserPut) GetProperties() *UserPropertiesPut { if o == nil { return nil @@ -122,9 +122,11 @@ func (o UserPut) MarshalJSON() ([]byte, error) { if o.Id != nil { toSerialize["id"] = o.Id } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_users.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_users.go index 0107d029b32..e67610e195f 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_users.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_users.go @@ -16,19 +16,19 @@ import ( // Users struct for Users type Users struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]User `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewUsers instantiates a new Users object @@ -49,114 +49,114 @@ func NewUsersWithDefaults() *Users { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Users) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *Users) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Users) GetIdOk() (*string, bool) { +func (o *Users) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *Users) SetId(v string) { +// SetLinks sets field value +func (o *Users) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *Users) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *Users) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Users) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Users) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Users) GetTypeOk() (*Type, bool) { +func (o *Users) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Users) SetType(v Type) { +// SetHref sets field value +func (o *Users) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Users) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Users) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Users) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Users) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Users) GetHrefOk() (*string, bool) { +func (o *Users) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Users) SetHref(v string) { +// SetId sets field value +func (o *Users) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Users) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Users) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *Users) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []User will be returned +// If the value is explicit nil, nil is returned func (o *Users) GetItems() *[]User { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *Users) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Users) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *Users) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Users) GetOffsetOk() (*float32, bool) { +func (o *Users) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *Users) SetOffset(v float32) { +// SetLimit sets field value +func (o *Users) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *Users) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *Users) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Users) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *Users) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Users) GetLimitOk() (*float32, bool) { +func (o *Users) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *Users) SetLimit(v float32) { +// SetOffset sets field value +func (o *Users) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *Users) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *Users) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *Users) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Users) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Users) GetLinksOk() (*PaginationLinks, bool) { +func (o *Users) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *Users) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *Users) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *Users) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *Users) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *Users) HasLinks() bool { func (o Users) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_users_entities.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_users_entities.go index 6c10d5a04b1..7619f661192 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_users_entities.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_users_entities.go @@ -16,8 +16,8 @@ import ( // UsersEntities struct for UsersEntities type UsersEntities struct { - Owns *ResourcesUsers `json:"owns,omitempty"` Groups *GroupUsers `json:"groups,omitempty"` + Owns *ResourcesUsers `json:"owns,omitempty"` } // NewUsersEntities instantiates a new UsersEntities object @@ -38,76 +38,76 @@ func NewUsersEntitiesWithDefaults() *UsersEntities { return &this } -// GetOwns returns the Owns field value -// If the value is explicit nil, the zero value for ResourcesUsers will be returned -func (o *UsersEntities) GetOwns() *ResourcesUsers { +// GetGroups returns the Groups field value +// If the value is explicit nil, nil is returned +func (o *UsersEntities) GetGroups() *GroupUsers { if o == nil { return nil } - return o.Owns + return o.Groups } -// GetOwnsOk returns a tuple with the Owns field value +// GetGroupsOk returns a tuple with the Groups field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UsersEntities) GetOwnsOk() (*ResourcesUsers, bool) { +func (o *UsersEntities) GetGroupsOk() (*GroupUsers, bool) { if o == nil { return nil, false } - return o.Owns, true + return o.Groups, true } -// SetOwns sets field value -func (o *UsersEntities) SetOwns(v ResourcesUsers) { +// SetGroups sets field value +func (o *UsersEntities) SetGroups(v GroupUsers) { - o.Owns = &v + o.Groups = &v } -// HasOwns returns a boolean if a field has been set. -func (o *UsersEntities) HasOwns() bool { - if o != nil && o.Owns != nil { +// HasGroups returns a boolean if a field has been set. +func (o *UsersEntities) HasGroups() bool { + if o != nil && o.Groups != nil { return true } return false } -// GetGroups returns the Groups field value -// If the value is explicit nil, the zero value for GroupUsers will be returned -func (o *UsersEntities) GetGroups() *GroupUsers { +// GetOwns returns the Owns field value +// If the value is explicit nil, nil is returned +func (o *UsersEntities) GetOwns() *ResourcesUsers { if o == nil { return nil } - return o.Groups + return o.Owns } -// GetGroupsOk returns a tuple with the Groups field value +// GetOwnsOk returns a tuple with the Owns field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *UsersEntities) GetGroupsOk() (*GroupUsers, bool) { +func (o *UsersEntities) GetOwnsOk() (*ResourcesUsers, bool) { if o == nil { return nil, false } - return o.Groups, true + return o.Owns, true } -// SetGroups sets field value -func (o *UsersEntities) SetGroups(v GroupUsers) { +// SetOwns sets field value +func (o *UsersEntities) SetOwns(v ResourcesUsers) { - o.Groups = &v + o.Owns = &v } -// HasGroups returns a boolean if a field has been set. -func (o *UsersEntities) HasGroups() bool { - if o != nil && o.Groups != nil { +// HasOwns returns a boolean if a field has been set. +func (o *UsersEntities) HasOwns() bool { + if o != nil && o.Owns != nil { return true } @@ -116,12 +116,14 @@ func (o *UsersEntities) HasGroups() bool { func (o UsersEntities) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Owns != nil { - toSerialize["owns"] = o.Owns - } if o.Groups != nil { toSerialize["groups"] = o.Groups } + + if o.Owns != nil { + toSerialize["owns"] = o.Owns + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_volume.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_volume.go index d0b7b862ede..59bf03f024d 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_volume.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_volume.go @@ -16,14 +16,14 @@ import ( // Volume struct for Volume type Volume struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` // The URL to the object representation (absolute path). - Href *string `json:"href,omitempty"` + Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` Metadata *DatacenterElementMetadata `json:"metadata,omitempty"` Properties *VolumeProperties `json:"properties"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewVolume instantiates a new Volume object @@ -46,190 +46,190 @@ func NewVolumeWithDefaults() *Volume { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Volume) GetId() *string { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Volume) GetHref() *string { if o == nil { return nil } - return o.Id + return o.Href } -// GetIdOk returns a tuple with the Id field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Volume) GetIdOk() (*string, bool) { +func (o *Volume) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Href, true } -// SetId sets field value -func (o *Volume) SetId(v string) { +// SetHref sets field value +func (o *Volume) SetHref(v string) { - o.Id = &v + o.Href = &v } -// HasId returns a boolean if a field has been set. -func (o *Volume) HasId() bool { - if o != nil && o.Id != nil { +// HasHref returns a boolean if a field has been set. +func (o *Volume) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Volume) GetType() *Type { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Volume) GetId() *string { if o == nil { return nil } - return o.Type + return o.Id } -// GetTypeOk returns a tuple with the Type field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Volume) GetTypeOk() (*Type, bool) { +func (o *Volume) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Id, true } -// SetType sets field value -func (o *Volume) SetType(v Type) { +// SetId sets field value +func (o *Volume) SetId(v string) { - o.Type = &v + o.Id = &v } -// HasType returns a boolean if a field has been set. -func (o *Volume) HasType() bool { - if o != nil && o.Type != nil { +// HasId returns a boolean if a field has been set. +func (o *Volume) HasId() bool { + if o != nil && o.Id != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Volume) GetHref() *string { +// GetMetadata returns the Metadata field value +// If the value is explicit nil, nil is returned +func (o *Volume) GetMetadata() *DatacenterElementMetadata { if o == nil { return nil } - return o.Href + return o.Metadata } -// GetHrefOk returns a tuple with the Href field value +// GetMetadataOk returns a tuple with the Metadata field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Volume) GetHrefOk() (*string, bool) { +func (o *Volume) GetMetadataOk() (*DatacenterElementMetadata, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Metadata, true } -// SetHref sets field value -func (o *Volume) SetHref(v string) { +// SetMetadata sets field value +func (o *Volume) SetMetadata(v DatacenterElementMetadata) { - o.Href = &v + o.Metadata = &v } -// HasHref returns a boolean if a field has been set. -func (o *Volume) HasHref() bool { - if o != nil && o.Href != nil { +// HasMetadata returns a boolean if a field has been set. +func (o *Volume) HasMetadata() bool { + if o != nil && o.Metadata != nil { return true } return false } -// GetMetadata returns the Metadata field value -// If the value is explicit nil, the zero value for DatacenterElementMetadata will be returned -func (o *Volume) GetMetadata() *DatacenterElementMetadata { +// GetProperties returns the Properties field value +// If the value is explicit nil, nil is returned +func (o *Volume) GetProperties() *VolumeProperties { if o == nil { return nil } - return o.Metadata + return o.Properties } -// GetMetadataOk returns a tuple with the Metadata field value +// GetPropertiesOk returns a tuple with the Properties field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Volume) GetMetadataOk() (*DatacenterElementMetadata, bool) { +func (o *Volume) GetPropertiesOk() (*VolumeProperties, bool) { if o == nil { return nil, false } - return o.Metadata, true + return o.Properties, true } -// SetMetadata sets field value -func (o *Volume) SetMetadata(v DatacenterElementMetadata) { +// SetProperties sets field value +func (o *Volume) SetProperties(v VolumeProperties) { - o.Metadata = &v + o.Properties = &v } -// HasMetadata returns a boolean if a field has been set. -func (o *Volume) HasMetadata() bool { - if o != nil && o.Metadata != nil { +// HasProperties returns a boolean if a field has been set. +func (o *Volume) HasProperties() bool { + if o != nil && o.Properties != nil { return true } return false } -// GetProperties returns the Properties field value -// If the value is explicit nil, the zero value for VolumeProperties will be returned -func (o *Volume) GetProperties() *VolumeProperties { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Volume) GetType() *Type { if o == nil { return nil } - return o.Properties + return o.Type } -// GetPropertiesOk returns a tuple with the Properties field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Volume) GetPropertiesOk() (*VolumeProperties, bool) { +func (o *Volume) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Properties, true + return o.Type, true } -// SetProperties sets field value -func (o *Volume) SetProperties(v VolumeProperties) { +// SetType sets field value +func (o *Volume) SetType(v Type) { - o.Properties = &v + o.Type = &v } -// HasProperties returns a boolean if a field has been set. -func (o *Volume) HasProperties() bool { - if o != nil && o.Properties != nil { +// HasType returns a boolean if a field has been set. +func (o *Volume) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -238,21 +238,26 @@ func (o *Volume) HasProperties() bool { func (o Volume) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type - } if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } + if o.Properties != nil { toSerialize["properties"] = o.Properties } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_volume_properties.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_volume_properties.go index 15ed6a14860..6f6bc6b963e 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_volume_properties.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_volume_properties.go @@ -16,49 +16,50 @@ import ( // VolumeProperties struct for VolumeProperties type VolumeProperties struct { - // The name of the resource. - Name *string `json:"name,omitempty"` - // Hardware type of the volume. DAS (Direct Attached Storage) could be used only in a composite call with a Cube server. - Type *string `json:"type,omitempty"` - // The size of the volume in GB. - Size *float32 `json:"size"` // The availability zone in which the volume should be provisioned. The storage volume will be provisioned on as few physical storage devices as possible, but this cannot be guaranteed upfront. This is uavailable for DAS (Direct Attached Storage), and subject to availability for SSD. AvailabilityZone *string `json:"availabilityZone,omitempty"` + // The ID of the backup unit that the user has access to. The property is immutable and is only allowed to be set on creation of a new a volume. It is mandatory to provide either 'public image' or 'imageAlias' in conjunction with this property. + BackupunitId *string `json:"backupunitId,omitempty"` + // Determines whether the volume will be used as a boot volume. Set to `NONE`, the volume will not be used as boot volume. Set to `PRIMARY`, the volume will be used as boot volume and all other volumes must be set to `NONE`. Set to `AUTO` or `null` requires all volumes to be set to `AUTO` or `null`; this will use the legacy behavior, which is to use the volume as a boot volume only if there are no other volumes or cdrom devices. + // to set this field to `nil` in order to be marshalled, the explicit nil address `Nilstring` can be used, or the setter `SetBootOrderNil` + BootOrder *string `json:"bootOrder,omitempty"` + // The UUID of the attached server. + BootServer *string `json:"bootServer,omitempty"` + // The bus type for this volume; default is VIRTIO. + Bus *string `json:"bus,omitempty"` + // Hot-plug capable CPU (no reboot required). + CpuHotPlug *bool `json:"cpuHotPlug,omitempty"` + // The Logical Unit Number of the storage volume. Null for volumes, not mounted to a VM. + DeviceNumber *int64 `json:"deviceNumber,omitempty"` + // Hot-plug capable Virt-IO drive (no reboot required). + DiscVirtioHotPlug *bool `json:"discVirtioHotPlug,omitempty"` + // Hot-unplug capable Virt-IO drive (no reboot required). Not supported with Windows VMs. + DiscVirtioHotUnplug *bool `json:"discVirtioHotUnplug,omitempty"` // Image or snapshot ID to be used as template for this volume. - Image *string `json:"image,omitempty"` + Image *string `json:"image,omitempty"` + ImageAlias *string `json:"imageAlias,omitempty"` // Initial password to be set for installed OS. Works with public images only. Not modifiable, forbidden in update requests. Password rules allows all characters from a-z, A-Z, 0-9. ImagePassword *string `json:"imagePassword,omitempty"` - ImageAlias *string `json:"imageAlias,omitempty"` - // Public SSH keys are set on the image as authorized keys for appropriate SSH login to the instance using the corresponding private key. This field may only be set in creation requests. When reading, it always returns null. SSH keys are only supported if a public Linux image is used for the volume creation. - SshKeys *[]string `json:"sshKeys,omitempty"` - // The bus type for this volume; default is VIRTIO. - Bus *string `json:"bus,omitempty"` // OS type for this volume. LicenceType *string `json:"licenceType,omitempty"` - // Hot-plug capable CPU (no reboot required). - CpuHotPlug *bool `json:"cpuHotPlug,omitempty"` - // Hot-plug capable RAM (no reboot required). - RamHotPlug *bool `json:"ramHotPlug,omitempty"` + // The name of the resource. + Name *string `json:"name,omitempty"` // Hot-plug capable NIC (no reboot required). NicHotPlug *bool `json:"nicHotPlug,omitempty"` // Hot-unplug capable NIC (no reboot required). NicHotUnplug *bool `json:"nicHotUnplug,omitempty"` - // Hot-plug capable Virt-IO drive (no reboot required). - DiscVirtioHotPlug *bool `json:"discVirtioHotPlug,omitempty"` - // Hot-unplug capable Virt-IO drive (no reboot required). Not supported with Windows VMs. - DiscVirtioHotUnplug *bool `json:"discVirtioHotUnplug,omitempty"` - // The Logical Unit Number of the storage volume. Null for volumes, not mounted to a VM. - DeviceNumber *int64 `json:"deviceNumber,omitempty"` // The PCI slot number of the storage volume. Null for volumes, not mounted to a VM. PciSlot *int32 `json:"pciSlot,omitempty"` - // The ID of the backup unit that the user has access to. The property is immutable and is only allowed to be set on creation of a new a volume. It is mandatory to provide either 'public image' or 'imageAlias' in conjunction with this property. - BackupunitId *string `json:"backupunitId,omitempty"` + // Hot-plug capable RAM (no reboot required). + RamHotPlug *bool `json:"ramHotPlug,omitempty"` + // The size of the volume in GB. + Size *float32 `json:"size"` + // Public SSH keys are set on the image as authorized keys for appropriate SSH login to the instance using the corresponding private key. This field may only be set in creation requests. When reading, it always returns null. SSH keys are only supported if a public Linux image is used for the volume creation. + SshKeys *[]string `json:"sshKeys,omitempty"` + // Hardware type of the volume. DAS (Direct Attached Storage) could be used only in a composite call with a Cube server. + Type *string `json:"type,omitempty"` // The cloud-init configuration for the volume as base64 encoded string. The property is immutable and is only allowed to be set on creation of a new a volume. It is mandatory to provide either 'public image' or 'imageAlias' that has cloud-init compatibility in conjunction with this property. UserData *string `json:"userData,omitempty"` - // The UUID of the attached server. - BootServer *string `json:"bootServer,omitempty"` - // Determines whether the volume will be used as a boot volume. Set to `NONE`, the volume will not be used as boot volume. Set to `PRIMARY`, the volume will be used as boot volume and all other volumes must be set to `NONE`. Set to `AUTO` or `null` requires all volumes to be set to `AUTO` or `null`; this will use the legacy behavior, which is to use the volume as a boot volume only if there are no other volumes or cdrom devices. - BootOrder *string `json:"bootOrder,omitempty"` } // NewVolumeProperties instantiates a new VolumeProperties object @@ -68,9 +69,9 @@ type VolumeProperties struct { func NewVolumeProperties(size float32) *VolumeProperties { this := VolumeProperties{} - this.Size = &size var bootOrder = "AUTO" this.BootOrder = &bootOrder + this.Size = &size return &this } @@ -85,836 +86,841 @@ func NewVolumePropertiesWithDefaults() *VolumeProperties { return &this } -// GetName returns the Name field value -// If the value is explicit nil, the zero value for string will be returned -func (o *VolumeProperties) GetName() *string { +// GetAvailabilityZone returns the AvailabilityZone field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetAvailabilityZone() *string { if o == nil { return nil } - return o.Name + return o.AvailabilityZone } -// GetNameOk returns a tuple with the Name field value +// GetAvailabilityZoneOk returns a tuple with the AvailabilityZone field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetNameOk() (*string, bool) { +func (o *VolumeProperties) GetAvailabilityZoneOk() (*string, bool) { if o == nil { return nil, false } - return o.Name, true + return o.AvailabilityZone, true } -// SetName sets field value -func (o *VolumeProperties) SetName(v string) { +// SetAvailabilityZone sets field value +func (o *VolumeProperties) SetAvailabilityZone(v string) { - o.Name = &v + o.AvailabilityZone = &v } -// HasName returns a boolean if a field has been set. -func (o *VolumeProperties) HasName() bool { - if o != nil && o.Name != nil { +// HasAvailabilityZone returns a boolean if a field has been set. +func (o *VolumeProperties) HasAvailabilityZone() bool { + if o != nil && o.AvailabilityZone != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for string will be returned -func (o *VolumeProperties) GetType() *string { +// GetBackupunitId returns the BackupunitId field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetBackupunitId() *string { if o == nil { return nil } - return o.Type + return o.BackupunitId } -// GetTypeOk returns a tuple with the Type field value +// GetBackupunitIdOk returns a tuple with the BackupunitId field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetTypeOk() (*string, bool) { +func (o *VolumeProperties) GetBackupunitIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.BackupunitId, true } -// SetType sets field value -func (o *VolumeProperties) SetType(v string) { +// SetBackupunitId sets field value +func (o *VolumeProperties) SetBackupunitId(v string) { - o.Type = &v + o.BackupunitId = &v } -// HasType returns a boolean if a field has been set. -func (o *VolumeProperties) HasType() bool { - if o != nil && o.Type != nil { +// HasBackupunitId returns a boolean if a field has been set. +func (o *VolumeProperties) HasBackupunitId() bool { + if o != nil && o.BackupunitId != nil { return true } return false } -// GetSize returns the Size field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *VolumeProperties) GetSize() *float32 { +// GetBootOrder returns the BootOrder field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetBootOrder() *string { if o == nil { return nil } - return o.Size + return o.BootOrder } -// GetSizeOk returns a tuple with the Size field value +// GetBootOrderOk returns a tuple with the BootOrder field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetSizeOk() (*float32, bool) { +func (o *VolumeProperties) GetBootOrderOk() (*string, bool) { if o == nil { return nil, false } - return o.Size, true + return o.BootOrder, true } -// SetSize sets field value -func (o *VolumeProperties) SetSize(v float32) { +// SetBootOrder sets field value +func (o *VolumeProperties) SetBootOrder(v string) { - o.Size = &v + o.BootOrder = &v } -// HasSize returns a boolean if a field has been set. -func (o *VolumeProperties) HasSize() bool { - if o != nil && o.Size != nil { +// sets BootOrder to the explicit address that will be encoded as nil when marshaled +func (o *VolumeProperties) SetBootOrderNil() { + o.BootOrder = &Nilstring +} + +// HasBootOrder returns a boolean if a field has been set. +func (o *VolumeProperties) HasBootOrder() bool { + if o != nil && o.BootOrder != nil { return true } return false } -// GetAvailabilityZone returns the AvailabilityZone field value -// If the value is explicit nil, the zero value for string will be returned -func (o *VolumeProperties) GetAvailabilityZone() *string { +// GetBootServer returns the BootServer field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetBootServer() *string { if o == nil { return nil } - return o.AvailabilityZone + return o.BootServer } -// GetAvailabilityZoneOk returns a tuple with the AvailabilityZone field value +// GetBootServerOk returns a tuple with the BootServer field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetAvailabilityZoneOk() (*string, bool) { +func (o *VolumeProperties) GetBootServerOk() (*string, bool) { if o == nil { return nil, false } - return o.AvailabilityZone, true + return o.BootServer, true } -// SetAvailabilityZone sets field value -func (o *VolumeProperties) SetAvailabilityZone(v string) { +// SetBootServer sets field value +func (o *VolumeProperties) SetBootServer(v string) { - o.AvailabilityZone = &v + o.BootServer = &v } -// HasAvailabilityZone returns a boolean if a field has been set. -func (o *VolumeProperties) HasAvailabilityZone() bool { - if o != nil && o.AvailabilityZone != nil { +// HasBootServer returns a boolean if a field has been set. +func (o *VolumeProperties) HasBootServer() bool { + if o != nil && o.BootServer != nil { return true } return false } -// GetImage returns the Image field value -// If the value is explicit nil, the zero value for string will be returned -func (o *VolumeProperties) GetImage() *string { +// GetBus returns the Bus field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetBus() *string { if o == nil { return nil } - return o.Image + return o.Bus } -// GetImageOk returns a tuple with the Image field value +// GetBusOk returns a tuple with the Bus field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetImageOk() (*string, bool) { +func (o *VolumeProperties) GetBusOk() (*string, bool) { if o == nil { return nil, false } - return o.Image, true + return o.Bus, true } -// SetImage sets field value -func (o *VolumeProperties) SetImage(v string) { +// SetBus sets field value +func (o *VolumeProperties) SetBus(v string) { - o.Image = &v + o.Bus = &v } -// HasImage returns a boolean if a field has been set. -func (o *VolumeProperties) HasImage() bool { - if o != nil && o.Image != nil { +// HasBus returns a boolean if a field has been set. +func (o *VolumeProperties) HasBus() bool { + if o != nil && o.Bus != nil { return true } return false } -// GetImagePassword returns the ImagePassword field value -// If the value is explicit nil, the zero value for string will be returned -func (o *VolumeProperties) GetImagePassword() *string { +// GetCpuHotPlug returns the CpuHotPlug field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetCpuHotPlug() *bool { if o == nil { return nil } - return o.ImagePassword + return o.CpuHotPlug } -// GetImagePasswordOk returns a tuple with the ImagePassword field value +// GetCpuHotPlugOk returns a tuple with the CpuHotPlug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetImagePasswordOk() (*string, bool) { +func (o *VolumeProperties) GetCpuHotPlugOk() (*bool, bool) { if o == nil { return nil, false } - return o.ImagePassword, true + return o.CpuHotPlug, true } -// SetImagePassword sets field value -func (o *VolumeProperties) SetImagePassword(v string) { +// SetCpuHotPlug sets field value +func (o *VolumeProperties) SetCpuHotPlug(v bool) { - o.ImagePassword = &v + o.CpuHotPlug = &v } -// HasImagePassword returns a boolean if a field has been set. -func (o *VolumeProperties) HasImagePassword() bool { - if o != nil && o.ImagePassword != nil { +// HasCpuHotPlug returns a boolean if a field has been set. +func (o *VolumeProperties) HasCpuHotPlug() bool { + if o != nil && o.CpuHotPlug != nil { return true } return false } -// GetImageAlias returns the ImageAlias field value -// If the value is explicit nil, the zero value for string will be returned -func (o *VolumeProperties) GetImageAlias() *string { +// GetDeviceNumber returns the DeviceNumber field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetDeviceNumber() *int64 { if o == nil { return nil } - return o.ImageAlias + return o.DeviceNumber } -// GetImageAliasOk returns a tuple with the ImageAlias field value +// GetDeviceNumberOk returns a tuple with the DeviceNumber field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetImageAliasOk() (*string, bool) { +func (o *VolumeProperties) GetDeviceNumberOk() (*int64, bool) { if o == nil { return nil, false } - return o.ImageAlias, true + return o.DeviceNumber, true } -// SetImageAlias sets field value -func (o *VolumeProperties) SetImageAlias(v string) { +// SetDeviceNumber sets field value +func (o *VolumeProperties) SetDeviceNumber(v int64) { - o.ImageAlias = &v + o.DeviceNumber = &v } -// HasImageAlias returns a boolean if a field has been set. -func (o *VolumeProperties) HasImageAlias() bool { - if o != nil && o.ImageAlias != nil { +// HasDeviceNumber returns a boolean if a field has been set. +func (o *VolumeProperties) HasDeviceNumber() bool { + if o != nil && o.DeviceNumber != nil { return true } return false } -// GetSshKeys returns the SshKeys field value -// If the value is explicit nil, the zero value for []string will be returned -func (o *VolumeProperties) GetSshKeys() *[]string { +// GetDiscVirtioHotPlug returns the DiscVirtioHotPlug field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetDiscVirtioHotPlug() *bool { if o == nil { return nil } - return o.SshKeys + return o.DiscVirtioHotPlug } -// GetSshKeysOk returns a tuple with the SshKeys field value +// GetDiscVirtioHotPlugOk returns a tuple with the DiscVirtioHotPlug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetSshKeysOk() (*[]string, bool) { +func (o *VolumeProperties) GetDiscVirtioHotPlugOk() (*bool, bool) { if o == nil { return nil, false } - return o.SshKeys, true + return o.DiscVirtioHotPlug, true } -// SetSshKeys sets field value -func (o *VolumeProperties) SetSshKeys(v []string) { +// SetDiscVirtioHotPlug sets field value +func (o *VolumeProperties) SetDiscVirtioHotPlug(v bool) { - o.SshKeys = &v + o.DiscVirtioHotPlug = &v } -// HasSshKeys returns a boolean if a field has been set. -func (o *VolumeProperties) HasSshKeys() bool { - if o != nil && o.SshKeys != nil { +// HasDiscVirtioHotPlug returns a boolean if a field has been set. +func (o *VolumeProperties) HasDiscVirtioHotPlug() bool { + if o != nil && o.DiscVirtioHotPlug != nil { return true } return false } -// GetBus returns the Bus field value -// If the value is explicit nil, the zero value for string will be returned -func (o *VolumeProperties) GetBus() *string { +// GetDiscVirtioHotUnplug returns the DiscVirtioHotUnplug field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetDiscVirtioHotUnplug() *bool { if o == nil { return nil } - return o.Bus + return o.DiscVirtioHotUnplug } -// GetBusOk returns a tuple with the Bus field value +// GetDiscVirtioHotUnplugOk returns a tuple with the DiscVirtioHotUnplug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetBusOk() (*string, bool) { +func (o *VolumeProperties) GetDiscVirtioHotUnplugOk() (*bool, bool) { if o == nil { return nil, false } - return o.Bus, true + return o.DiscVirtioHotUnplug, true } -// SetBus sets field value -func (o *VolumeProperties) SetBus(v string) { +// SetDiscVirtioHotUnplug sets field value +func (o *VolumeProperties) SetDiscVirtioHotUnplug(v bool) { - o.Bus = &v + o.DiscVirtioHotUnplug = &v } -// HasBus returns a boolean if a field has been set. -func (o *VolumeProperties) HasBus() bool { - if o != nil && o.Bus != nil { +// HasDiscVirtioHotUnplug returns a boolean if a field has been set. +func (o *VolumeProperties) HasDiscVirtioHotUnplug() bool { + if o != nil && o.DiscVirtioHotUnplug != nil { return true } return false } -// GetLicenceType returns the LicenceType field value -// If the value is explicit nil, the zero value for string will be returned -func (o *VolumeProperties) GetLicenceType() *string { +// GetImage returns the Image field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetImage() *string { if o == nil { return nil } - return o.LicenceType + return o.Image } -// GetLicenceTypeOk returns a tuple with the LicenceType field value +// GetImageOk returns a tuple with the Image field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetLicenceTypeOk() (*string, bool) { +func (o *VolumeProperties) GetImageOk() (*string, bool) { if o == nil { return nil, false } - return o.LicenceType, true + return o.Image, true } -// SetLicenceType sets field value -func (o *VolumeProperties) SetLicenceType(v string) { +// SetImage sets field value +func (o *VolumeProperties) SetImage(v string) { - o.LicenceType = &v + o.Image = &v } -// HasLicenceType returns a boolean if a field has been set. -func (o *VolumeProperties) HasLicenceType() bool { - if o != nil && o.LicenceType != nil { +// HasImage returns a boolean if a field has been set. +func (o *VolumeProperties) HasImage() bool { + if o != nil && o.Image != nil { return true } return false } -// GetCpuHotPlug returns the CpuHotPlug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *VolumeProperties) GetCpuHotPlug() *bool { +// GetImageAlias returns the ImageAlias field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetImageAlias() *string { if o == nil { return nil } - return o.CpuHotPlug + return o.ImageAlias } -// GetCpuHotPlugOk returns a tuple with the CpuHotPlug field value +// GetImageAliasOk returns a tuple with the ImageAlias field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetCpuHotPlugOk() (*bool, bool) { +func (o *VolumeProperties) GetImageAliasOk() (*string, bool) { if o == nil { return nil, false } - return o.CpuHotPlug, true + return o.ImageAlias, true } -// SetCpuHotPlug sets field value -func (o *VolumeProperties) SetCpuHotPlug(v bool) { +// SetImageAlias sets field value +func (o *VolumeProperties) SetImageAlias(v string) { - o.CpuHotPlug = &v + o.ImageAlias = &v } -// HasCpuHotPlug returns a boolean if a field has been set. -func (o *VolumeProperties) HasCpuHotPlug() bool { - if o != nil && o.CpuHotPlug != nil { +// HasImageAlias returns a boolean if a field has been set. +func (o *VolumeProperties) HasImageAlias() bool { + if o != nil && o.ImageAlias != nil { return true } return false } -// GetRamHotPlug returns the RamHotPlug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *VolumeProperties) GetRamHotPlug() *bool { +// GetImagePassword returns the ImagePassword field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetImagePassword() *string { if o == nil { return nil } - return o.RamHotPlug + return o.ImagePassword } -// GetRamHotPlugOk returns a tuple with the RamHotPlug field value +// GetImagePasswordOk returns a tuple with the ImagePassword field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetRamHotPlugOk() (*bool, bool) { +func (o *VolumeProperties) GetImagePasswordOk() (*string, bool) { if o == nil { return nil, false } - return o.RamHotPlug, true + return o.ImagePassword, true } -// SetRamHotPlug sets field value -func (o *VolumeProperties) SetRamHotPlug(v bool) { +// SetImagePassword sets field value +func (o *VolumeProperties) SetImagePassword(v string) { - o.RamHotPlug = &v + o.ImagePassword = &v } -// HasRamHotPlug returns a boolean if a field has been set. -func (o *VolumeProperties) HasRamHotPlug() bool { - if o != nil && o.RamHotPlug != nil { +// HasImagePassword returns a boolean if a field has been set. +func (o *VolumeProperties) HasImagePassword() bool { + if o != nil && o.ImagePassword != nil { return true } return false } -// GetNicHotPlug returns the NicHotPlug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *VolumeProperties) GetNicHotPlug() *bool { +// GetLicenceType returns the LicenceType field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetLicenceType() *string { if o == nil { return nil } - return o.NicHotPlug + return o.LicenceType } -// GetNicHotPlugOk returns a tuple with the NicHotPlug field value +// GetLicenceTypeOk returns a tuple with the LicenceType field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetNicHotPlugOk() (*bool, bool) { +func (o *VolumeProperties) GetLicenceTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.NicHotPlug, true + return o.LicenceType, true } -// SetNicHotPlug sets field value -func (o *VolumeProperties) SetNicHotPlug(v bool) { +// SetLicenceType sets field value +func (o *VolumeProperties) SetLicenceType(v string) { - o.NicHotPlug = &v + o.LicenceType = &v } -// HasNicHotPlug returns a boolean if a field has been set. -func (o *VolumeProperties) HasNicHotPlug() bool { - if o != nil && o.NicHotPlug != nil { +// HasLicenceType returns a boolean if a field has been set. +func (o *VolumeProperties) HasLicenceType() bool { + if o != nil && o.LicenceType != nil { return true } return false } -// GetNicHotUnplug returns the NicHotUnplug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *VolumeProperties) GetNicHotUnplug() *bool { +// GetName returns the Name field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetName() *string { if o == nil { return nil } - return o.NicHotUnplug + return o.Name } -// GetNicHotUnplugOk returns a tuple with the NicHotUnplug field value +// GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetNicHotUnplugOk() (*bool, bool) { +func (o *VolumeProperties) GetNameOk() (*string, bool) { if o == nil { return nil, false } - return o.NicHotUnplug, true + return o.Name, true } -// SetNicHotUnplug sets field value -func (o *VolumeProperties) SetNicHotUnplug(v bool) { +// SetName sets field value +func (o *VolumeProperties) SetName(v string) { - o.NicHotUnplug = &v + o.Name = &v } -// HasNicHotUnplug returns a boolean if a field has been set. -func (o *VolumeProperties) HasNicHotUnplug() bool { - if o != nil && o.NicHotUnplug != nil { +// HasName returns a boolean if a field has been set. +func (o *VolumeProperties) HasName() bool { + if o != nil && o.Name != nil { return true } return false } -// GetDiscVirtioHotPlug returns the DiscVirtioHotPlug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *VolumeProperties) GetDiscVirtioHotPlug() *bool { +// GetNicHotPlug returns the NicHotPlug field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetNicHotPlug() *bool { if o == nil { return nil } - return o.DiscVirtioHotPlug + return o.NicHotPlug } -// GetDiscVirtioHotPlugOk returns a tuple with the DiscVirtioHotPlug field value +// GetNicHotPlugOk returns a tuple with the NicHotPlug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetDiscVirtioHotPlugOk() (*bool, bool) { +func (o *VolumeProperties) GetNicHotPlugOk() (*bool, bool) { if o == nil { return nil, false } - return o.DiscVirtioHotPlug, true + return o.NicHotPlug, true } -// SetDiscVirtioHotPlug sets field value -func (o *VolumeProperties) SetDiscVirtioHotPlug(v bool) { +// SetNicHotPlug sets field value +func (o *VolumeProperties) SetNicHotPlug(v bool) { - o.DiscVirtioHotPlug = &v + o.NicHotPlug = &v } -// HasDiscVirtioHotPlug returns a boolean if a field has been set. -func (o *VolumeProperties) HasDiscVirtioHotPlug() bool { - if o != nil && o.DiscVirtioHotPlug != nil { +// HasNicHotPlug returns a boolean if a field has been set. +func (o *VolumeProperties) HasNicHotPlug() bool { + if o != nil && o.NicHotPlug != nil { return true } return false } -// GetDiscVirtioHotUnplug returns the DiscVirtioHotUnplug field value -// If the value is explicit nil, the zero value for bool will be returned -func (o *VolumeProperties) GetDiscVirtioHotUnplug() *bool { +// GetNicHotUnplug returns the NicHotUnplug field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetNicHotUnplug() *bool { if o == nil { return nil } - return o.DiscVirtioHotUnplug + return o.NicHotUnplug } -// GetDiscVirtioHotUnplugOk returns a tuple with the DiscVirtioHotUnplug field value +// GetNicHotUnplugOk returns a tuple with the NicHotUnplug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetDiscVirtioHotUnplugOk() (*bool, bool) { +func (o *VolumeProperties) GetNicHotUnplugOk() (*bool, bool) { if o == nil { return nil, false } - return o.DiscVirtioHotUnplug, true + return o.NicHotUnplug, true } -// SetDiscVirtioHotUnplug sets field value -func (o *VolumeProperties) SetDiscVirtioHotUnplug(v bool) { +// SetNicHotUnplug sets field value +func (o *VolumeProperties) SetNicHotUnplug(v bool) { - o.DiscVirtioHotUnplug = &v + o.NicHotUnplug = &v } -// HasDiscVirtioHotUnplug returns a boolean if a field has been set. -func (o *VolumeProperties) HasDiscVirtioHotUnplug() bool { - if o != nil && o.DiscVirtioHotUnplug != nil { +// HasNicHotUnplug returns a boolean if a field has been set. +func (o *VolumeProperties) HasNicHotUnplug() bool { + if o != nil && o.NicHotUnplug != nil { return true } return false } -// GetDeviceNumber returns the DeviceNumber field value -// If the value is explicit nil, the zero value for int64 will be returned -func (o *VolumeProperties) GetDeviceNumber() *int64 { +// GetPciSlot returns the PciSlot field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetPciSlot() *int32 { if o == nil { return nil } - return o.DeviceNumber + return o.PciSlot } -// GetDeviceNumberOk returns a tuple with the DeviceNumber field value +// GetPciSlotOk returns a tuple with the PciSlot field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetDeviceNumberOk() (*int64, bool) { +func (o *VolumeProperties) GetPciSlotOk() (*int32, bool) { if o == nil { return nil, false } - return o.DeviceNumber, true + return o.PciSlot, true } -// SetDeviceNumber sets field value -func (o *VolumeProperties) SetDeviceNumber(v int64) { +// SetPciSlot sets field value +func (o *VolumeProperties) SetPciSlot(v int32) { - o.DeviceNumber = &v + o.PciSlot = &v } -// HasDeviceNumber returns a boolean if a field has been set. -func (o *VolumeProperties) HasDeviceNumber() bool { - if o != nil && o.DeviceNumber != nil { +// HasPciSlot returns a boolean if a field has been set. +func (o *VolumeProperties) HasPciSlot() bool { + if o != nil && o.PciSlot != nil { return true } return false } -// GetPciSlot returns the PciSlot field value -// If the value is explicit nil, the zero value for int32 will be returned -func (o *VolumeProperties) GetPciSlot() *int32 { +// GetRamHotPlug returns the RamHotPlug field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetRamHotPlug() *bool { if o == nil { return nil } - return o.PciSlot + return o.RamHotPlug } -// GetPciSlotOk returns a tuple with the PciSlot field value +// GetRamHotPlugOk returns a tuple with the RamHotPlug field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetPciSlotOk() (*int32, bool) { +func (o *VolumeProperties) GetRamHotPlugOk() (*bool, bool) { if o == nil { return nil, false } - return o.PciSlot, true + return o.RamHotPlug, true } -// SetPciSlot sets field value -func (o *VolumeProperties) SetPciSlot(v int32) { +// SetRamHotPlug sets field value +func (o *VolumeProperties) SetRamHotPlug(v bool) { - o.PciSlot = &v + o.RamHotPlug = &v } -// HasPciSlot returns a boolean if a field has been set. -func (o *VolumeProperties) HasPciSlot() bool { - if o != nil && o.PciSlot != nil { +// HasRamHotPlug returns a boolean if a field has been set. +func (o *VolumeProperties) HasRamHotPlug() bool { + if o != nil && o.RamHotPlug != nil { return true } return false } -// GetBackupunitId returns the BackupunitId field value -// If the value is explicit nil, the zero value for string will be returned -func (o *VolumeProperties) GetBackupunitId() *string { +// GetSize returns the Size field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetSize() *float32 { if o == nil { return nil } - return o.BackupunitId + return o.Size } -// GetBackupunitIdOk returns a tuple with the BackupunitId field value +// GetSizeOk returns a tuple with the Size field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetBackupunitIdOk() (*string, bool) { +func (o *VolumeProperties) GetSizeOk() (*float32, bool) { if o == nil { return nil, false } - return o.BackupunitId, true + return o.Size, true } -// SetBackupunitId sets field value -func (o *VolumeProperties) SetBackupunitId(v string) { +// SetSize sets field value +func (o *VolumeProperties) SetSize(v float32) { - o.BackupunitId = &v + o.Size = &v } -// HasBackupunitId returns a boolean if a field has been set. -func (o *VolumeProperties) HasBackupunitId() bool { - if o != nil && o.BackupunitId != nil { +// HasSize returns a boolean if a field has been set. +func (o *VolumeProperties) HasSize() bool { + if o != nil && o.Size != nil { return true } return false } -// GetUserData returns the UserData field value -// If the value is explicit nil, the zero value for string will be returned -func (o *VolumeProperties) GetUserData() *string { +// GetSshKeys returns the SshKeys field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetSshKeys() *[]string { if o == nil { return nil } - return o.UserData + return o.SshKeys } -// GetUserDataOk returns a tuple with the UserData field value +// GetSshKeysOk returns a tuple with the SshKeys field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetUserDataOk() (*string, bool) { +func (o *VolumeProperties) GetSshKeysOk() (*[]string, bool) { if o == nil { return nil, false } - return o.UserData, true + return o.SshKeys, true } -// SetUserData sets field value -func (o *VolumeProperties) SetUserData(v string) { +// SetSshKeys sets field value +func (o *VolumeProperties) SetSshKeys(v []string) { - o.UserData = &v + o.SshKeys = &v } -// HasUserData returns a boolean if a field has been set. -func (o *VolumeProperties) HasUserData() bool { - if o != nil && o.UserData != nil { +// HasSshKeys returns a boolean if a field has been set. +func (o *VolumeProperties) HasSshKeys() bool { + if o != nil && o.SshKeys != nil { return true } return false } -// GetBootServer returns the BootServer field value -// If the value is explicit nil, the zero value for string will be returned -func (o *VolumeProperties) GetBootServer() *string { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetType() *string { if o == nil { return nil } - return o.BootServer + return o.Type } -// GetBootServerOk returns a tuple with the BootServer field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetBootServerOk() (*string, bool) { +func (o *VolumeProperties) GetTypeOk() (*string, bool) { if o == nil { return nil, false } - return o.BootServer, true + return o.Type, true } -// SetBootServer sets field value -func (o *VolumeProperties) SetBootServer(v string) { +// SetType sets field value +func (o *VolumeProperties) SetType(v string) { - o.BootServer = &v + o.Type = &v } -// HasBootServer returns a boolean if a field has been set. -func (o *VolumeProperties) HasBootServer() bool { - if o != nil && o.BootServer != nil { +// HasType returns a boolean if a field has been set. +func (o *VolumeProperties) HasType() bool { + if o != nil && o.Type != nil { return true } return false } -// GetBootOrder returns the BootOrder field value -// If the value is explicit nil, the zero value for string will be returned -func (o *VolumeProperties) GetBootOrder() *string { +// GetUserData returns the UserData field value +// If the value is explicit nil, nil is returned +func (o *VolumeProperties) GetUserData() *string { if o == nil { return nil } - return o.BootOrder + return o.UserData } -// GetBootOrderOk returns a tuple with the BootOrder field value +// GetUserDataOk returns a tuple with the UserData field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *VolumeProperties) GetBootOrderOk() (*string, bool) { +func (o *VolumeProperties) GetUserDataOk() (*string, bool) { if o == nil { return nil, false } - return o.BootOrder, true + return o.UserData, true } -// SetBootOrder sets field value -func (o *VolumeProperties) SetBootOrder(v string) { +// SetUserData sets field value +func (o *VolumeProperties) SetUserData(v string) { - o.BootOrder = &v + o.UserData = &v } -// HasBootOrder returns a boolean if a field has been set. -func (o *VolumeProperties) HasBootOrder() bool { - if o != nil && o.BootOrder != nil { +// HasUserData returns a boolean if a field has been set. +func (o *VolumeProperties) HasUserData() bool { + if o != nil && o.UserData != nil { return true } @@ -923,70 +929,95 @@ func (o *VolumeProperties) HasBootOrder() bool { func (o VolumeProperties) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Name != nil { - toSerialize["name"] = o.Name + if o.AvailabilityZone != nil { + toSerialize["availabilityZone"] = o.AvailabilityZone } - if o.Type != nil { - toSerialize["type"] = o.Type + + if o.BackupunitId != nil { + toSerialize["backupunitId"] = o.BackupunitId } - if o.Size != nil { - toSerialize["size"] = o.Size + + if o.BootOrder == &Nilstring { + toSerialize["bootOrder"] = nil + } else if o.BootOrder != nil { + toSerialize["bootOrder"] = o.BootOrder } - if o.AvailabilityZone != nil { - toSerialize["availabilityZone"] = o.AvailabilityZone + if o.BootServer != nil { + toSerialize["bootServer"] = o.BootServer + } + + if o.Bus != nil { + toSerialize["bus"] = o.Bus + } + + if o.CpuHotPlug != nil { + toSerialize["cpuHotPlug"] = o.CpuHotPlug + } + + if o.DeviceNumber != nil { + toSerialize["deviceNumber"] = o.DeviceNumber + } + + if o.DiscVirtioHotPlug != nil { + toSerialize["discVirtioHotPlug"] = o.DiscVirtioHotPlug } + + if o.DiscVirtioHotUnplug != nil { + toSerialize["discVirtioHotUnplug"] = o.DiscVirtioHotUnplug + } + if o.Image != nil { toSerialize["image"] = o.Image } - if o.ImagePassword != nil { - toSerialize["imagePassword"] = o.ImagePassword - } + if o.ImageAlias != nil { toSerialize["imageAlias"] = o.ImageAlias } - if o.SshKeys != nil { - toSerialize["sshKeys"] = o.SshKeys - } - if o.Bus != nil { - toSerialize["bus"] = o.Bus + + if o.ImagePassword != nil { + toSerialize["imagePassword"] = o.ImagePassword } + if o.LicenceType != nil { toSerialize["licenceType"] = o.LicenceType } - if o.CpuHotPlug != nil { - toSerialize["cpuHotPlug"] = o.CpuHotPlug - } - if o.RamHotPlug != nil { - toSerialize["ramHotPlug"] = o.RamHotPlug + + if o.Name != nil { + toSerialize["name"] = o.Name } + if o.NicHotPlug != nil { toSerialize["nicHotPlug"] = o.NicHotPlug } + if o.NicHotUnplug != nil { toSerialize["nicHotUnplug"] = o.NicHotUnplug } - if o.DiscVirtioHotPlug != nil { - toSerialize["discVirtioHotPlug"] = o.DiscVirtioHotPlug + + if o.PciSlot != nil { + toSerialize["pciSlot"] = o.PciSlot } - if o.DiscVirtioHotUnplug != nil { - toSerialize["discVirtioHotUnplug"] = o.DiscVirtioHotUnplug + + if o.RamHotPlug != nil { + toSerialize["ramHotPlug"] = o.RamHotPlug } - if o.DeviceNumber != nil { - toSerialize["deviceNumber"] = o.DeviceNumber + + if o.Size != nil { + toSerialize["size"] = o.Size } - if o.PciSlot != nil { - toSerialize["pciSlot"] = o.PciSlot + + if o.SshKeys != nil { + toSerialize["sshKeys"] = o.SshKeys } - if o.BackupunitId != nil { - toSerialize["backupunitId"] = o.BackupunitId + + if o.Type != nil { + toSerialize["type"] = o.Type } + if o.UserData != nil { toSerialize["userData"] = o.UserData } - if o.BootServer != nil { - toSerialize["bootServer"] = o.BootServer - } - toSerialize["bootOrder"] = o.BootOrder + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/model_volumes.go b/vendor/github.com/ionos-cloud/sdk-go/v6/model_volumes.go index dfe753d8e6d..ec795374f24 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/model_volumes.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/model_volumes.go @@ -16,19 +16,19 @@ import ( // Volumes struct for Volumes type Volumes struct { - // The resource's unique identifier. - Id *string `json:"id,omitempty"` - // The type of object that has been created. - Type *Type `json:"type,omitempty"` + Links *PaginationLinks `json:"_links,omitempty"` // URL to the object representation (absolute path). Href *string `json:"href,omitempty"` + // The resource's unique identifier. + Id *string `json:"id,omitempty"` // Array of items in the collection. Items *[]Volume `json:"items,omitempty"` + // The limit (if specified in the request). + Limit *float32 `json:"limit,omitempty"` // The offset (if specified in the request). Offset *float32 `json:"offset,omitempty"` - // The limit (if specified in the request). - Limit *float32 `json:"limit,omitempty"` - Links *PaginationLinks `json:"_links,omitempty"` + // The type of object that has been created. + Type *Type `json:"type,omitempty"` } // NewVolumes instantiates a new Volumes object @@ -49,114 +49,114 @@ func NewVolumesWithDefaults() *Volumes { return &this } -// GetId returns the Id field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Volumes) GetId() *string { +// GetLinks returns the Links field value +// If the value is explicit nil, nil is returned +func (o *Volumes) GetLinks() *PaginationLinks { if o == nil { return nil } - return o.Id + return o.Links } -// GetIdOk returns a tuple with the Id field value +// GetLinksOk returns a tuple with the Links field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Volumes) GetIdOk() (*string, bool) { +func (o *Volumes) GetLinksOk() (*PaginationLinks, bool) { if o == nil { return nil, false } - return o.Id, true + return o.Links, true } -// SetId sets field value -func (o *Volumes) SetId(v string) { +// SetLinks sets field value +func (o *Volumes) SetLinks(v PaginationLinks) { - o.Id = &v + o.Links = &v } -// HasId returns a boolean if a field has been set. -func (o *Volumes) HasId() bool { - if o != nil && o.Id != nil { +// HasLinks returns a boolean if a field has been set. +func (o *Volumes) HasLinks() bool { + if o != nil && o.Links != nil { return true } return false } -// GetType returns the Type field value -// If the value is explicit nil, the zero value for Type will be returned -func (o *Volumes) GetType() *Type { +// GetHref returns the Href field value +// If the value is explicit nil, nil is returned +func (o *Volumes) GetHref() *string { if o == nil { return nil } - return o.Type + return o.Href } -// GetTypeOk returns a tuple with the Type field value +// GetHrefOk returns a tuple with the Href field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Volumes) GetTypeOk() (*Type, bool) { +func (o *Volumes) GetHrefOk() (*string, bool) { if o == nil { return nil, false } - return o.Type, true + return o.Href, true } -// SetType sets field value -func (o *Volumes) SetType(v Type) { +// SetHref sets field value +func (o *Volumes) SetHref(v string) { - o.Type = &v + o.Href = &v } -// HasType returns a boolean if a field has been set. -func (o *Volumes) HasType() bool { - if o != nil && o.Type != nil { +// HasHref returns a boolean if a field has been set. +func (o *Volumes) HasHref() bool { + if o != nil && o.Href != nil { return true } return false } -// GetHref returns the Href field value -// If the value is explicit nil, the zero value for string will be returned -func (o *Volumes) GetHref() *string { +// GetId returns the Id field value +// If the value is explicit nil, nil is returned +func (o *Volumes) GetId() *string { if o == nil { return nil } - return o.Href + return o.Id } -// GetHrefOk returns a tuple with the Href field value +// GetIdOk returns a tuple with the Id field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Volumes) GetHrefOk() (*string, bool) { +func (o *Volumes) GetIdOk() (*string, bool) { if o == nil { return nil, false } - return o.Href, true + return o.Id, true } -// SetHref sets field value -func (o *Volumes) SetHref(v string) { +// SetId sets field value +func (o *Volumes) SetId(v string) { - o.Href = &v + o.Id = &v } -// HasHref returns a boolean if a field has been set. -func (o *Volumes) HasHref() bool { - if o != nil && o.Href != nil { +// HasId returns a boolean if a field has been set. +func (o *Volumes) HasId() bool { + if o != nil && o.Id != nil { return true } @@ -164,7 +164,7 @@ func (o *Volumes) HasHref() bool { } // GetItems returns the Items field value -// If the value is explicit nil, the zero value for []Volume will be returned +// If the value is explicit nil, nil is returned func (o *Volumes) GetItems() *[]Volume { if o == nil { return nil @@ -201,114 +201,114 @@ func (o *Volumes) HasItems() bool { return false } -// GetOffset returns the Offset field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Volumes) GetOffset() *float32 { +// GetLimit returns the Limit field value +// If the value is explicit nil, nil is returned +func (o *Volumes) GetLimit() *float32 { if o == nil { return nil } - return o.Offset + return o.Limit } -// GetOffsetOk returns a tuple with the Offset field value +// GetLimitOk returns a tuple with the Limit field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Volumes) GetOffsetOk() (*float32, bool) { +func (o *Volumes) GetLimitOk() (*float32, bool) { if o == nil { return nil, false } - return o.Offset, true + return o.Limit, true } -// SetOffset sets field value -func (o *Volumes) SetOffset(v float32) { +// SetLimit sets field value +func (o *Volumes) SetLimit(v float32) { - o.Offset = &v + o.Limit = &v } -// HasOffset returns a boolean if a field has been set. -func (o *Volumes) HasOffset() bool { - if o != nil && o.Offset != nil { +// HasLimit returns a boolean if a field has been set. +func (o *Volumes) HasLimit() bool { + if o != nil && o.Limit != nil { return true } return false } -// GetLimit returns the Limit field value -// If the value is explicit nil, the zero value for float32 will be returned -func (o *Volumes) GetLimit() *float32 { +// GetOffset returns the Offset field value +// If the value is explicit nil, nil is returned +func (o *Volumes) GetOffset() *float32 { if o == nil { return nil } - return o.Limit + return o.Offset } -// GetLimitOk returns a tuple with the Limit field value +// GetOffsetOk returns a tuple with the Offset field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Volumes) GetLimitOk() (*float32, bool) { +func (o *Volumes) GetOffsetOk() (*float32, bool) { if o == nil { return nil, false } - return o.Limit, true + return o.Offset, true } -// SetLimit sets field value -func (o *Volumes) SetLimit(v float32) { +// SetOffset sets field value +func (o *Volumes) SetOffset(v float32) { - o.Limit = &v + o.Offset = &v } -// HasLimit returns a boolean if a field has been set. -func (o *Volumes) HasLimit() bool { - if o != nil && o.Limit != nil { +// HasOffset returns a boolean if a field has been set. +func (o *Volumes) HasOffset() bool { + if o != nil && o.Offset != nil { return true } return false } -// GetLinks returns the Links field value -// If the value is explicit nil, the zero value for PaginationLinks will be returned -func (o *Volumes) GetLinks() *PaginationLinks { +// GetType returns the Type field value +// If the value is explicit nil, nil is returned +func (o *Volumes) GetType() *Type { if o == nil { return nil } - return o.Links + return o.Type } -// GetLinksOk returns a tuple with the Links field value +// GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned -func (o *Volumes) GetLinksOk() (*PaginationLinks, bool) { +func (o *Volumes) GetTypeOk() (*Type, bool) { if o == nil { return nil, false } - return o.Links, true + return o.Type, true } -// SetLinks sets field value -func (o *Volumes) SetLinks(v PaginationLinks) { +// SetType sets field value +func (o *Volumes) SetType(v Type) { - o.Links = &v + o.Type = &v } -// HasLinks returns a boolean if a field has been set. -func (o *Volumes) HasLinks() bool { - if o != nil && o.Links != nil { +// HasType returns a boolean if a field has been set. +func (o *Volumes) HasType() bool { + if o != nil && o.Type != nil { return true } @@ -317,27 +317,34 @@ func (o *Volumes) HasLinks() bool { func (o Volumes) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} - if o.Id != nil { - toSerialize["id"] = o.Id - } - if o.Type != nil { - toSerialize["type"] = o.Type + if o.Links != nil { + toSerialize["_links"] = o.Links } + if o.Href != nil { toSerialize["href"] = o.Href } + + if o.Id != nil { + toSerialize["id"] = o.Id + } + if o.Items != nil { toSerialize["items"] = o.Items } - if o.Offset != nil { - toSerialize["offset"] = o.Offset - } + if o.Limit != nil { toSerialize["limit"] = o.Limit } - if o.Links != nil { - toSerialize["_links"] = o.Links + + if o.Offset != nil { + toSerialize["offset"] = o.Offset } + + if o.Type != nil { + toSerialize["type"] = o.Type + } + return json.Marshal(toSerialize) } diff --git a/vendor/github.com/ionos-cloud/sdk-go/v6/utils.go b/vendor/github.com/ionos-cloud/sdk-go/v6/utils.go index ee096c73151..e37bb71d8e6 100644 --- a/vendor/github.com/ionos-cloud/sdk-go/v6/utils.go +++ b/vendor/github.com/ionos-cloud/sdk-go/v6/utils.go @@ -17,6 +17,13 @@ import ( "time" ) +var ( + // used to set a nullable field to nil. This is a sentinel address that will be checked in the MarshalJson function. + // if set to this address, a nil value will be marshalled + Nilstring string = "<>" + Nilint32 int32 = -334455 +) + // ToPtr - returns a pointer to the given value. func ToPtr[T any](v T) *T { return &v diff --git a/vendor/github.com/kylelemons/godebug/LICENSE b/vendor/github.com/kylelemons/godebug/LICENSE new file mode 100644 index 00000000000..d6456956733 --- /dev/null +++ b/vendor/github.com/kylelemons/godebug/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/vendor/github.com/kylelemons/godebug/diff/diff.go b/vendor/github.com/kylelemons/godebug/diff/diff.go new file mode 100644 index 00000000000..200e596c625 --- /dev/null +++ b/vendor/github.com/kylelemons/godebug/diff/diff.go @@ -0,0 +1,186 @@ +// Copyright 2013 Google Inc. All rights reserved. +// +// 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 diff implements a linewise diff algorithm. +package diff + +import ( + "bytes" + "fmt" + "strings" +) + +// Chunk represents a piece of the diff. A chunk will not have both added and +// deleted lines. Equal lines are always after any added or deleted lines. +// A Chunk may or may not have any lines in it, especially for the first or last +// chunk in a computation. +type Chunk struct { + Added []string + Deleted []string + Equal []string +} + +func (c *Chunk) empty() bool { + return len(c.Added) == 0 && len(c.Deleted) == 0 && len(c.Equal) == 0 +} + +// Diff returns a string containing a line-by-line unified diff of the linewise +// changes required to make A into B. Each line is prefixed with '+', '-', or +// ' ' to indicate if it should be added, removed, or is correct respectively. +func Diff(A, B string) string { + aLines := strings.Split(A, "\n") + bLines := strings.Split(B, "\n") + + chunks := DiffChunks(aLines, bLines) + + buf := new(bytes.Buffer) + for _, c := range chunks { + for _, line := range c.Added { + fmt.Fprintf(buf, "+%s\n", line) + } + for _, line := range c.Deleted { + fmt.Fprintf(buf, "-%s\n", line) + } + for _, line := range c.Equal { + fmt.Fprintf(buf, " %s\n", line) + } + } + return strings.TrimRight(buf.String(), "\n") +} + +// DiffChunks uses an O(D(N+M)) shortest-edit-script algorithm +// to compute the edits required from A to B and returns the +// edit chunks. +func DiffChunks(a, b []string) []Chunk { + // algorithm: http://www.xmailserver.org/diff2.pdf + + // We'll need these quantities a lot. + alen, blen := len(a), len(b) // M, N + + // At most, it will require len(a) deletions and len(b) additions + // to transform a into b. + maxPath := alen + blen // MAX + if maxPath == 0 { + // degenerate case: two empty lists are the same + return nil + } + + // Store the endpoint of the path for diagonals. + // We store only the a index, because the b index on any diagonal + // (which we know during the loop below) is aidx-diag. + // endpoint[maxPath] represents the 0 diagonal. + // + // Stated differently: + // endpoint[d] contains the aidx of a furthest reaching path in diagonal d + endpoint := make([]int, 2*maxPath+1) // V + + saved := make([][]int, 0, 8) // Vs + save := func() { + dup := make([]int, len(endpoint)) + copy(dup, endpoint) + saved = append(saved, dup) + } + + var editDistance int // D +dLoop: + for editDistance = 0; editDistance <= maxPath; editDistance++ { + // The 0 diag(onal) represents equality of a and b. Each diagonal to + // the left is numbered one lower, to the right is one higher, from + // -alen to +blen. Negative diagonals favor differences from a, + // positive diagonals favor differences from b. The edit distance to a + // diagonal d cannot be shorter than d itself. + // + // The iterations of this loop cover either odds or evens, but not both, + // If odd indices are inputs, even indices are outputs and vice versa. + for diag := -editDistance; diag <= editDistance; diag += 2 { // k + var aidx int // x + switch { + case diag == -editDistance: + // This is a new diagonal; copy from previous iter + aidx = endpoint[maxPath-editDistance+1] + 0 + case diag == editDistance: + // This is a new diagonal; copy from previous iter + aidx = endpoint[maxPath+editDistance-1] + 1 + case endpoint[maxPath+diag+1] > endpoint[maxPath+diag-1]: + // diagonal d+1 was farther along, so use that + aidx = endpoint[maxPath+diag+1] + 0 + default: + // diagonal d-1 was farther (or the same), so use that + aidx = endpoint[maxPath+diag-1] + 1 + } + // On diagonal d, we can compute bidx from aidx. + bidx := aidx - diag // y + // See how far we can go on this diagonal before we find a difference. + for aidx < alen && bidx < blen && a[aidx] == b[bidx] { + aidx++ + bidx++ + } + // Store the end of the current edit chain. + endpoint[maxPath+diag] = aidx + // If we've found the end of both inputs, we're done! + if aidx >= alen && bidx >= blen { + save() // save the final path + break dLoop + } + } + save() // save the current path + } + if editDistance == 0 { + return nil + } + chunks := make([]Chunk, editDistance+1) + + x, y := alen, blen + for d := editDistance; d > 0; d-- { + endpoint := saved[d] + diag := x - y + insert := diag == -d || (diag != d && endpoint[maxPath+diag-1] < endpoint[maxPath+diag+1]) + + x1 := endpoint[maxPath+diag] + var x0, xM, kk int + if insert { + kk = diag + 1 + x0 = endpoint[maxPath+kk] + xM = x0 + } else { + kk = diag - 1 + x0 = endpoint[maxPath+kk] + xM = x0 + 1 + } + y0 := x0 - kk + + var c Chunk + if insert { + c.Added = b[y0:][:1] + } else { + c.Deleted = a[x0:][:1] + } + if xM < x1 { + c.Equal = a[xM:][:x1-xM] + } + + x, y = x0, y0 + chunks[d] = c + } + if x > 0 { + chunks[0].Equal = a[:x] + } + if chunks[0].empty() { + chunks = chunks[1:] + } + if len(chunks) == 0 { + return nil + } + return chunks +} diff --git a/vendor/github.com/kylelemons/godebug/pretty/.gitignore b/vendor/github.com/kylelemons/godebug/pretty/.gitignore new file mode 100644 index 00000000000..fa9a735da3c --- /dev/null +++ b/vendor/github.com/kylelemons/godebug/pretty/.gitignore @@ -0,0 +1,5 @@ +*.test +*.bench +*.golden +*.txt +*.prof diff --git a/vendor/github.com/kylelemons/godebug/pretty/doc.go b/vendor/github.com/kylelemons/godebug/pretty/doc.go new file mode 100644 index 00000000000..03b5718a70d --- /dev/null +++ b/vendor/github.com/kylelemons/godebug/pretty/doc.go @@ -0,0 +1,25 @@ +// Copyright 2013 Google Inc. All rights reserved. +// +// 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 pretty pretty-prints Go structures. +// +// This package uses reflection to examine a Go value and can +// print out in a nice, aligned fashion. It supports three +// modes (normal, compact, and extended) for advanced use. +// +// See the Reflect and Print examples for what the output looks like. +package pretty + +// TODO: +// - Catch cycles diff --git a/vendor/github.com/kylelemons/godebug/pretty/public.go b/vendor/github.com/kylelemons/godebug/pretty/public.go new file mode 100644 index 00000000000..fbc5d7abbf8 --- /dev/null +++ b/vendor/github.com/kylelemons/godebug/pretty/public.go @@ -0,0 +1,188 @@ +// Copyright 2013 Google Inc. All rights reserved. +// +// 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 pretty + +import ( + "bytes" + "fmt" + "io" + "net" + "reflect" + "time" + + "github.com/kylelemons/godebug/diff" +) + +// A Config represents optional configuration parameters for formatting. +// +// Some options, notably ShortList, dramatically increase the overhead +// of pretty-printing a value. +type Config struct { + // Verbosity options + Compact bool // One-line output. Overrides Diffable. + Diffable bool // Adds extra newlines for more easily diffable output. + + // Field and value options + IncludeUnexported bool // Include unexported fields in output + PrintStringers bool // Call String on a fmt.Stringer + PrintTextMarshalers bool // Call MarshalText on an encoding.TextMarshaler + SkipZeroFields bool // Skip struct fields that have a zero value. + + // Output transforms + ShortList int // Maximum character length for short lists if nonzero. + + // Type-specific overrides + // + // Formatter maps a type to a function that will provide a one-line string + // representation of the input value. Conceptually: + // Formatter[reflect.TypeOf(v)](v) = "v as a string" + // + // Note that the first argument need not explicitly match the type, it must + // merely be callable with it. + // + // When processing an input value, if its type exists as a key in Formatter: + // 1) If the value is nil, no stringification is performed. + // This allows overriding of PrintStringers and PrintTextMarshalers. + // 2) The value will be called with the input as its only argument. + // The function must return a string as its first return value. + // + // In addition to func literals, two common values for this will be: + // fmt.Sprint (function) func Sprint(...interface{}) string + // Type.String (method) func (Type) String() string + // + // Note that neither of these work if the String method is a pointer + // method and the input will be provided as a value. In that case, + // use a function that calls .String on the formal value parameter. + Formatter map[reflect.Type]interface{} + + // If TrackCycles is enabled, pretty will detect and track + // self-referential structures. If a self-referential structure (aka a + // "recursive" value) is detected, numbered placeholders will be emitted. + // + // Pointer tracking is disabled by default for performance reasons. + TrackCycles bool +} + +// Default Config objects +var ( + // DefaultFormatter is the default set of overrides for stringification. + DefaultFormatter = map[reflect.Type]interface{}{ + reflect.TypeOf(time.Time{}): fmt.Sprint, + reflect.TypeOf(net.IP{}): fmt.Sprint, + reflect.TypeOf((*error)(nil)).Elem(): fmt.Sprint, + } + + // CompareConfig is the default configuration used for Compare. + CompareConfig = &Config{ + Diffable: true, + IncludeUnexported: true, + Formatter: DefaultFormatter, + } + + // DefaultConfig is the default configuration used for all other top-level functions. + DefaultConfig = &Config{ + Formatter: DefaultFormatter, + } + + // CycleTracker is a convenience config for formatting and comparing recursive structures. + CycleTracker = &Config{ + Diffable: true, + Formatter: DefaultFormatter, + TrackCycles: true, + } +) + +func (cfg *Config) fprint(buf *bytes.Buffer, vals ...interface{}) { + ref := &reflector{ + Config: cfg, + } + if cfg.TrackCycles { + ref.pointerTracker = new(pointerTracker) + } + for i, val := range vals { + if i > 0 { + buf.WriteByte('\n') + } + newFormatter(cfg, buf).write(ref.val2node(reflect.ValueOf(val))) + } +} + +// Print writes the DefaultConfig representation of the given values to standard output. +func Print(vals ...interface{}) { + DefaultConfig.Print(vals...) +} + +// Print writes the configured presentation of the given values to standard output. +func (cfg *Config) Print(vals ...interface{}) { + fmt.Println(cfg.Sprint(vals...)) +} + +// Sprint returns a string representation of the given value according to the DefaultConfig. +func Sprint(vals ...interface{}) string { + return DefaultConfig.Sprint(vals...) +} + +// Sprint returns a string representation of the given value according to cfg. +func (cfg *Config) Sprint(vals ...interface{}) string { + buf := new(bytes.Buffer) + cfg.fprint(buf, vals...) + return buf.String() +} + +// Fprint writes the representation of the given value to the writer according to the DefaultConfig. +func Fprint(w io.Writer, vals ...interface{}) (n int64, err error) { + return DefaultConfig.Fprint(w, vals...) +} + +// Fprint writes the representation of the given value to the writer according to the cfg. +func (cfg *Config) Fprint(w io.Writer, vals ...interface{}) (n int64, err error) { + buf := new(bytes.Buffer) + cfg.fprint(buf, vals...) + return buf.WriteTo(w) +} + +// Compare returns a string containing a line-by-line unified diff of the +// values in a and b, using the CompareConfig. +// +// Each line in the output is prefixed with '+', '-', or ' ' to indicate which +// side it's from. Lines from the a side are marked with '-', lines from the +// b side are marked with '+' and lines that are the same on both sides are +// marked with ' '. +// +// The comparison is based on the intentionally-untyped output of Print, and as +// such this comparison is pretty forviving. In particular, if the types of or +// types within in a and b are different but have the same representation, +// Compare will not indicate any differences between them. +func Compare(a, b interface{}) string { + return CompareConfig.Compare(a, b) +} + +// Compare returns a string containing a line-by-line unified diff of the +// values in got and want according to the cfg. +// +// Each line in the output is prefixed with '+', '-', or ' ' to indicate which +// side it's from. Lines from the a side are marked with '-', lines from the +// b side are marked with '+' and lines that are the same on both sides are +// marked with ' '. +// +// The comparison is based on the intentionally-untyped output of Print, and as +// such this comparison is pretty forviving. In particular, if the types of or +// types within in a and b are different but have the same representation, +// Compare will not indicate any differences between them. +func (cfg *Config) Compare(a, b interface{}) string { + diffCfg := *cfg + diffCfg.Diffable = true + return diff.Diff(cfg.Sprint(a), cfg.Sprint(b)) +} diff --git a/vendor/github.com/kylelemons/godebug/pretty/reflect.go b/vendor/github.com/kylelemons/godebug/pretty/reflect.go new file mode 100644 index 00000000000..5cd30b7f036 --- /dev/null +++ b/vendor/github.com/kylelemons/godebug/pretty/reflect.go @@ -0,0 +1,241 @@ +// Copyright 2013 Google Inc. All rights reserved. +// +// 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 pretty + +import ( + "encoding" + "fmt" + "reflect" + "sort" +) + +func isZeroVal(val reflect.Value) bool { + if !val.CanInterface() { + return false + } + z := reflect.Zero(val.Type()).Interface() + return reflect.DeepEqual(val.Interface(), z) +} + +// pointerTracker is a helper for tracking pointer chasing to detect cycles. +type pointerTracker struct { + addrs map[uintptr]int // addr[address] = seen count + + lastID int + ids map[uintptr]int // ids[address] = id +} + +// track tracks following a reference (pointer, slice, map, etc). Every call to +// track should be paired with a call to untrack. +func (p *pointerTracker) track(ptr uintptr) { + if p.addrs == nil { + p.addrs = make(map[uintptr]int) + } + p.addrs[ptr]++ +} + +// untrack registers that we have backtracked over the reference to the pointer. +func (p *pointerTracker) untrack(ptr uintptr) { + p.addrs[ptr]-- + if p.addrs[ptr] == 0 { + delete(p.addrs, ptr) + } +} + +// seen returns whether the pointer was previously seen along this path. +func (p *pointerTracker) seen(ptr uintptr) bool { + _, ok := p.addrs[ptr] + return ok +} + +// keep allocates an ID for the given address and returns it. +func (p *pointerTracker) keep(ptr uintptr) int { + if p.ids == nil { + p.ids = make(map[uintptr]int) + } + if _, ok := p.ids[ptr]; !ok { + p.lastID++ + p.ids[ptr] = p.lastID + } + return p.ids[ptr] +} + +// id returns the ID for the given address. +func (p *pointerTracker) id(ptr uintptr) (int, bool) { + if p.ids == nil { + p.ids = make(map[uintptr]int) + } + id, ok := p.ids[ptr] + return id, ok +} + +// reflector adds local state to the recursive reflection logic. +type reflector struct { + *Config + *pointerTracker +} + +// follow handles following a possiblly-recursive reference to the given value +// from the given ptr address. +func (r *reflector) follow(ptr uintptr, val reflect.Value) node { + if r.pointerTracker == nil { + // Tracking disabled + return r.val2node(val) + } + + // If a parent already followed this, emit a reference marker + if r.seen(ptr) { + id := r.keep(ptr) + return ref{id} + } + + // Track the pointer we're following while on this recursive branch + r.track(ptr) + defer r.untrack(ptr) + n := r.val2node(val) + + // If the recursion used this ptr, wrap it with a target marker + if id, ok := r.id(ptr); ok { + return target{id, n} + } + + // Otherwise, return the node unadulterated + return n +} + +func (r *reflector) val2node(val reflect.Value) node { + if !val.IsValid() { + return rawVal("nil") + } + + if val.CanInterface() { + v := val.Interface() + if formatter, ok := r.Formatter[val.Type()]; ok { + if formatter != nil { + res := reflect.ValueOf(formatter).Call([]reflect.Value{val}) + return rawVal(res[0].Interface().(string)) + } + } else { + if s, ok := v.(fmt.Stringer); ok && r.PrintStringers { + return stringVal(s.String()) + } + if t, ok := v.(encoding.TextMarshaler); ok && r.PrintTextMarshalers { + if raw, err := t.MarshalText(); err == nil { // if NOT an error + return stringVal(string(raw)) + } + } + } + } + + switch kind := val.Kind(); kind { + case reflect.Ptr: + if val.IsNil() { + return rawVal("nil") + } + return r.follow(val.Pointer(), val.Elem()) + case reflect.Interface: + if val.IsNil() { + return rawVal("nil") + } + return r.val2node(val.Elem()) + case reflect.String: + return stringVal(val.String()) + case reflect.Slice: + n := list{} + length := val.Len() + ptr := val.Pointer() + for i := 0; i < length; i++ { + n = append(n, r.follow(ptr, val.Index(i))) + } + return n + case reflect.Array: + n := list{} + length := val.Len() + for i := 0; i < length; i++ { + n = append(n, r.val2node(val.Index(i))) + } + return n + case reflect.Map: + // Extract the keys and sort them for stable iteration + keys := val.MapKeys() + pairs := make([]mapPair, 0, len(keys)) + for _, key := range keys { + pairs = append(pairs, mapPair{ + key: new(formatter).compactString(r.val2node(key)), // can't be cyclic + value: val.MapIndex(key), + }) + } + sort.Sort(byKey(pairs)) + + // Process the keys into the final representation + ptr, n := val.Pointer(), keyvals{} + for _, pair := range pairs { + n = append(n, keyval{ + key: pair.key, + val: r.follow(ptr, pair.value), + }) + } + return n + case reflect.Struct: + n := keyvals{} + typ := val.Type() + fields := typ.NumField() + for i := 0; i < fields; i++ { + sf := typ.Field(i) + if !r.IncludeUnexported && sf.PkgPath != "" { + continue + } + field := val.Field(i) + if r.SkipZeroFields && isZeroVal(field) { + continue + } + n = append(n, keyval{sf.Name, r.val2node(field)}) + } + return n + case reflect.Bool: + if val.Bool() { + return rawVal("true") + } + return rawVal("false") + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return rawVal(fmt.Sprintf("%d", val.Int())) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + return rawVal(fmt.Sprintf("%d", val.Uint())) + case reflect.Uintptr: + return rawVal(fmt.Sprintf("0x%X", val.Uint())) + case reflect.Float32, reflect.Float64: + return rawVal(fmt.Sprintf("%v", val.Float())) + case reflect.Complex64, reflect.Complex128: + return rawVal(fmt.Sprintf("%v", val.Complex())) + } + + // Fall back to the default %#v if we can + if val.CanInterface() { + return rawVal(fmt.Sprintf("%#v", val.Interface())) + } + + return rawVal(val.String()) +} + +type mapPair struct { + key string + value reflect.Value +} + +type byKey []mapPair + +func (v byKey) Len() int { return len(v) } +func (v byKey) Swap(i, j int) { v[i], v[j] = v[j], v[i] } +func (v byKey) Less(i, j int) bool { return v[i].key < v[j].key } diff --git a/vendor/github.com/kylelemons/godebug/pretty/structure.go b/vendor/github.com/kylelemons/godebug/pretty/structure.go new file mode 100644 index 00000000000..d876f60cad2 --- /dev/null +++ b/vendor/github.com/kylelemons/godebug/pretty/structure.go @@ -0,0 +1,223 @@ +// Copyright 2013 Google Inc. All rights reserved. +// +// 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 pretty + +import ( + "bufio" + "bytes" + "fmt" + "io" + "strconv" + "strings" +) + +// a formatter stores stateful formatting information as well as being +// an io.Writer for simplicity. +type formatter struct { + *bufio.Writer + *Config + + // Self-referential structure tracking + tagNumbers map[int]int // tagNumbers[id] = <#n> +} + +// newFormatter creates a new buffered formatter. For the output to be written +// to the given writer, this must be accompanied by a call to write (or Flush). +func newFormatter(cfg *Config, w io.Writer) *formatter { + return &formatter{ + Writer: bufio.NewWriter(w), + Config: cfg, + tagNumbers: make(map[int]int), + } +} + +func (f *formatter) write(n node) { + defer f.Flush() + n.format(f, "") +} + +func (f *formatter) tagFor(id int) int { + if tag, ok := f.tagNumbers[id]; ok { + return tag + } + if f.tagNumbers == nil { + return 0 + } + tag := len(f.tagNumbers) + 1 + f.tagNumbers[id] = tag + return tag +} + +type node interface { + format(f *formatter, indent string) +} + +func (f *formatter) compactString(n node) string { + switch k := n.(type) { + case stringVal: + return string(k) + case rawVal: + return string(k) + } + + buf := new(bytes.Buffer) + f2 := newFormatter(&Config{Compact: true}, buf) + f2.tagNumbers = f.tagNumbers // reuse tagNumbers just in case + f2.write(n) + return buf.String() +} + +type stringVal string + +func (str stringVal) format(f *formatter, indent string) { + f.WriteString(strconv.Quote(string(str))) +} + +type rawVal string + +func (r rawVal) format(f *formatter, indent string) { + f.WriteString(string(r)) +} + +type keyval struct { + key string + val node +} + +type keyvals []keyval + +func (l keyvals) format(f *formatter, indent string) { + f.WriteByte('{') + + switch { + case f.Compact: + // All on one line: + for i, kv := range l { + if i > 0 { + f.WriteByte(',') + } + f.WriteString(kv.key) + f.WriteByte(':') + kv.val.format(f, indent) + } + case f.Diffable: + f.WriteByte('\n') + inner := indent + " " + // Each value gets its own line: + for _, kv := range l { + f.WriteString(inner) + f.WriteString(kv.key) + f.WriteString(": ") + kv.val.format(f, inner) + f.WriteString(",\n") + } + f.WriteString(indent) + default: + keyWidth := 0 + for _, kv := range l { + if kw := len(kv.key); kw > keyWidth { + keyWidth = kw + } + } + alignKey := indent + " " + alignValue := strings.Repeat(" ", keyWidth) + inner := alignKey + alignValue + " " + // First and last line shared with bracket: + for i, kv := range l { + if i > 0 { + f.WriteString(",\n") + f.WriteString(alignKey) + } + f.WriteString(kv.key) + f.WriteString(": ") + f.WriteString(alignValue[len(kv.key):]) + kv.val.format(f, inner) + } + } + + f.WriteByte('}') +} + +type list []node + +func (l list) format(f *formatter, indent string) { + if max := f.ShortList; max > 0 { + short := f.compactString(l) + if len(short) <= max { + f.WriteString(short) + return + } + } + + f.WriteByte('[') + + switch { + case f.Compact: + // All on one line: + for i, v := range l { + if i > 0 { + f.WriteByte(',') + } + v.format(f, indent) + } + case f.Diffable: + f.WriteByte('\n') + inner := indent + " " + // Each value gets its own line: + for _, v := range l { + f.WriteString(inner) + v.format(f, inner) + f.WriteString(",\n") + } + f.WriteString(indent) + default: + inner := indent + " " + // First and last line shared with bracket: + for i, v := range l { + if i > 0 { + f.WriteString(",\n") + f.WriteString(inner) + } + v.format(f, inner) + } + } + + f.WriteByte(']') +} + +type ref struct { + id int +} + +func (r ref) format(f *formatter, indent string) { + fmt.Fprintf(f, "", f.tagFor(r.id)) +} + +type target struct { + id int + value node +} + +func (t target) format(f *formatter, indent string) { + tag := fmt.Sprintf("<#%d> ", f.tagFor(t.id)) + switch { + case f.Diffable, f.Compact: + // no indent changes + default: + indent += strings.Repeat(" ", len(tag)) + } + f.WriteString(tag) + t.value.format(f, indent) +} diff --git a/vendor/github.com/linode/linodego/.golangci.yml b/vendor/github.com/linode/linodego/.golangci.yml index 40983e5b05f..26dd77cb5b0 100644 --- a/vendor/github.com/linode/linodego/.golangci.yml +++ b/vendor/github.com/linode/linodego/.golangci.yml @@ -29,6 +29,13 @@ linters-settings: linters: enable-all: true disable: + # deprecated linters + - deadcode + - ifshort + - varcheck + - nosnakecase + #################### + - bodyclose - contextcheck - nilerr @@ -71,4 +78,5 @@ linters: - cyclop - godot - exhaustive + - depguard fast: false diff --git a/vendor/github.com/linode/linodego/Makefile b/vendor/github.com/linode/linodego/Makefile index ebe4ecbc71b..960c1e43219 100644 --- a/vendor/github.com/linode/linodego/Makefile +++ b/vendor/github.com/linode/linodego/Makefile @@ -8,7 +8,7 @@ TEST_TIMEOUT := 5h SKIP_DOCKER ?= 0 GOLANGCILINT := golangci-lint -GOLANGCILINT_IMG := golangci/golangci-lint:v1.46.2-alpine +GOLANGCILINT_IMG := golangci/golangci-lint:latest GOLANGCILINT_ARGS := run LINODE_URL := https://api.linode.com/ diff --git a/vendor/github.com/linode/linodego/account_events.go b/vendor/github.com/linode/linodego/account_events.go index e8306a1ba9f..1373244865a 100644 --- a/vendor/github.com/linode/linodego/account_events.go +++ b/vendor/github.com/linode/linodego/account_events.go @@ -95,6 +95,7 @@ const ( ActionHostReboot EventAction = "host_reboot" ActionImageDelete EventAction = "image_delete" ActionImageUpdate EventAction = "image_update" + ActionImageUpload EventAction = "image_upload" ActionLassieReboot EventAction = "lassie_reboot" ActionLinodeAddIP EventAction = "linode_addip" ActionLinodeBoot EventAction = "linode_boot" diff --git a/vendor/github.com/linode/linodego/account_settings.go b/vendor/github.com/linode/linodego/account_settings.go index bf60162d059..9a4b1362b7d 100644 --- a/vendor/github.com/linode/linodego/account_settings.go +++ b/vendor/github.com/linode/linodego/account_settings.go @@ -29,6 +29,7 @@ type AccountSettingsUpdateOptions struct { BackupsEnabled *bool `json:"backups_enabled,omitempty"` // A plan name like "longview-3"..."longview-100", or a nil value for to cancel any existing subscription plan. + // Deprecated: Use PUT /longview/plan instead to update the LongviewSubscription LongviewSubscription *string `json:"longview_subscription,omitempty"` // The default network helper setting for all new Linodes and Linode Configs for all users on the account. diff --git a/vendor/github.com/linode/linodego/databases.go b/vendor/github.com/linode/linodego/databases.go index eace5fdc9ca..8fbb69ffbe4 100644 --- a/vendor/github.com/linode/linodego/databases.go +++ b/vendor/github.com/linode/linodego/databases.go @@ -34,7 +34,6 @@ const ( const ( DatabaseEngineTypeMySQL DatabaseEngineType = "mysql" - DatabaseEngineTypeMongo DatabaseEngineType = "mongodb" DatabaseEngineTypePostgres DatabaseEngineType = "postgresql" ) @@ -236,7 +235,7 @@ func (c *Client) ListDatabaseEngines(ctx context.Context, opts *ListOptions) ([] } // GetDatabaseEngine returns a specific Database Engine. This endpoint is cached by default. -func (c *Client) GetDatabaseEngine(ctx context.Context, opts *ListOptions, engineID string) (*DatabaseEngine, error) { +func (c *Client) GetDatabaseEngine(ctx context.Context, _ *ListOptions, engineID string) (*DatabaseEngine, error) { e := fmt.Sprintf("databases/engines/%s", engineID) if result := c.getCachedResponse(e); result != nil { @@ -279,7 +278,7 @@ func (c *Client) ListDatabaseTypes(ctx context.Context, opts *ListOptions) ([]Da } // GetDatabaseType returns a specific Database Type. This endpoint is cached by default. -func (c *Client) GetDatabaseType(ctx context.Context, opts *ListOptions, typeID string) (*DatabaseType, error) { +func (c *Client) GetDatabaseType(ctx context.Context, _ *ListOptions, typeID string) (*DatabaseType, error) { e := fmt.Sprintf("databases/types/%s", typeID) if result := c.getCachedResponse(e); result != nil { diff --git a/vendor/github.com/linode/linodego/go.work.sum b/vendor/github.com/linode/linodego/go.work.sum index ea20c135a67..aa831efea38 100644 --- a/vendor/github.com/linode/linodego/go.work.sum +++ b/vendor/github.com/linode/linodego/go.work.sum @@ -45,12 +45,13 @@ golang.org/x/sys v0.0.0-20190209173611-3b5209105503/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20191022100944-742c48ecaeb7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 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.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= -golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 h1:JGgROgKl9N8DuW20oFS5gxc+lE67/N3FcwmBPMe7ArY= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw= -golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= +golang.org/x/term v0.8.0 h1:n5xxQn2i3PC0yLAbjTpNT85q/Kgzcr2gIoX9OrJUols= +golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= golang.org/x/text v0.0.0-20160726164857-2910a502d2bf/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/tools v0.0.0-20181011042414-1f849cf54d09/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= diff --git a/vendor/github.com/linode/linodego/mongo.go b/vendor/github.com/linode/linodego/mongo.go deleted file mode 100644 index 47b83fdc0a6..00000000000 --- a/vendor/github.com/linode/linodego/mongo.go +++ /dev/null @@ -1,324 +0,0 @@ -package linodego - -import ( - "context" - "encoding/json" - "fmt" - "time" - - "github.com/go-resty/resty/v2" - "github.com/linode/linodego/internal/parseabletime" -) - -type MongoDatabaseTarget string - -const ( - MongoDatabaseTargetPrimary MongoDatabaseTarget = "primary" - MongoDatabaseTargetSecondary MongoDatabaseTarget = "secondary" -) - -type MongoCompressionType string - -const ( - MongoCompressionNone MongoCompressionType = "none" - MongoCompressionSnappy MongoCompressionType = "snappy" - MongoCompressionZlib MongoCompressionType = "zlib" -) - -type MongoStorageEngine string - -const ( - MongoStorageWiredTiger MongoStorageEngine = "wiredtiger" - MongoStorageMmapv1 MongoStorageEngine = "mmapv1" -) - -// A MongoDatabase is a instance of Linode Mongo Managed Databases -type MongoDatabase struct { - ID int `json:"id"` - Status DatabaseStatus `json:"status"` - Label string `json:"label"` - Region string `json:"region"` - Type string `json:"type"` - Engine string `json:"engine"` - Version string `json:"version"` - Encrypted bool `json:"encrypted"` - AllowList []string `json:"allow_list"` - Peers []string `json:"peers"` - Port int `json:"port"` - ReplicaSet string `json:"replica_set"` - SSLConnection bool `json:"ssl_connection"` - ClusterSize int `json:"cluster_size"` - Hosts DatabaseHost `json:"hosts"` - CompressionType MongoCompressionType `json:"compression_type"` - StorageEngine MongoStorageEngine `json:"storage_engine"` - Updates DatabaseMaintenanceWindow `json:"updates"` - Created *time.Time `json:"-"` - Updated *time.Time `json:"-"` -} - -func (d *MongoDatabase) UnmarshalJSON(b []byte) error { - type Mask MongoDatabase - - p := struct { - *Mask - Created *parseabletime.ParseableTime `json:"created"` - Updated *parseabletime.ParseableTime `json:"updated"` - }{ - Mask: (*Mask)(d), - } - - if err := json.Unmarshal(b, &p); err != nil { - return err - } - - d.Created = (*time.Time)(p.Created) - d.Updated = (*time.Time)(p.Updated) - return nil -} - -// MongoCreateOptions fields are used when creating a new Mongo Database -type MongoCreateOptions struct { - Label string `json:"label"` - Region string `json:"region"` - Type string `json:"type"` - Engine string `json:"engine"` - AllowList []string `json:"allow_list,omitempty"` - ClusterSize int `json:"cluster_size,omitempty"` - Encrypted bool `json:"encrypted,omitempty"` - SSLConnection bool `json:"ssl_connection,omitempty"` - CompressionType MongoCompressionType `json:"compression_type,omitempty"` - StorageEngine MongoStorageEngine `json:"storage_engine,omitempty"` -} - -// MongoUpdateOptions fields are used when altering the existing Mongo Database -type MongoUpdateOptions struct { - Label string `json:"label,omitempty"` - AllowList *[]string `json:"allow_list,omitempty"` - Updates *DatabaseMaintenanceWindow `json:"updates,omitempty"` -} - -// MongoDatabaseSSL is the SSL Certificate to access the Linode Managed Mongo Database -type MongoDatabaseSSL struct { - CACertificate []byte `json:"ca_certificate"` -} - -// MongoDatabaseCredential is the Root Credentials to access the Linode Managed Database -type MongoDatabaseCredential struct { - Username string `json:"username"` - Password string `json:"password"` -} - -type MongoDatabasesPagedResponse struct { - *PageOptions - Data []MongoDatabase `json:"data"` -} - -func (MongoDatabasesPagedResponse) endpoint(_ ...any) string { - return "databases/mongodb/instances" -} - -func (resp *MongoDatabasesPagedResponse) castResult(r *resty.Request, e string) (int, int, error) { - res, err := coupleAPIErrors(r.SetResult(MongoDatabasesPagedResponse{}).Get(e)) - if err != nil { - return 0, 0, err - } - castedRes := res.Result().(*MongoDatabasesPagedResponse) - resp.Data = append(resp.Data, castedRes.Data...) - return castedRes.Pages, castedRes.Results, nil -} - -// ListMongoDatabases lists all Mongo Databases associated with the account -func (c *Client) ListMongoDatabases(ctx context.Context, opts *ListOptions) ([]MongoDatabase, error) { - response := MongoDatabasesPagedResponse{} - - err := c.listHelper(ctx, &response, opts) - if err != nil { - return nil, err - } - - return response.Data, nil -} - -// MongoDatabaseBackup is information for interacting with a backup for the existing Mongo Database -type MongoDatabaseBackup struct { - ID int `json:"id"` - Label string `json:"label"` - Type string `json:"type"` - Created *time.Time `json:"-"` -} - -func (d *MongoDatabaseBackup) UnmarshalJSON(b []byte) error { - type Mask MongoDatabaseBackup - - p := struct { - *Mask - Created *parseabletime.ParseableTime `json:"created"` - }{ - Mask: (*Mask)(d), - } - - if err := json.Unmarshal(b, &p); err != nil { - return err - } - - d.Created = (*time.Time)(p.Created) - return nil -} - -// MongoBackupCreateOptions are options used for CreateMongoDatabaseBackup(...) -type MongoBackupCreateOptions struct { - Label string `json:"label"` - Target MongoDatabaseTarget `json:"target"` -} - -type MongoDatabaseBackupsPagedResponse struct { - *PageOptions - Data []MongoDatabaseBackup `json:"data"` -} - -func (MongoDatabaseBackupsPagedResponse) endpoint(ids ...any) string { - id := ids[0].(int) - return fmt.Sprintf("databases/mongodb/instances/%d/backups", id) -} - -func (resp *MongoDatabaseBackupsPagedResponse) castResult(r *resty.Request, e string) (int, int, error) { - res, err := coupleAPIErrors(r.SetResult(MongoDatabaseBackupsPagedResponse{}).Get(e)) - if err != nil { - return 0, 0, err - } - castedRes := res.Result().(*MongoDatabaseBackupsPagedResponse) - resp.Data = append(resp.Data, castedRes.Data...) - return castedRes.Pages, castedRes.Results, nil -} - -// ListMongoDatabaseBackups lists all Mongo Database Backups associated with the given Mongo Database -func (c *Client) ListMongoDatabaseBackups(ctx context.Context, databaseID int, opts *ListOptions) ([]MongoDatabaseBackup, error) { - response := MongoDatabaseBackupsPagedResponse{} - - err := c.listHelper(ctx, &response, opts, databaseID) - if err != nil { - return nil, err - } - - return response.Data, nil -} - -// GetMongoDatabase returns a single Mongo Database matching the id -func (c *Client) GetMongoDatabase(ctx context.Context, databaseID int) (*MongoDatabase, error) { - e := fmt.Sprintf("databases/mongodb/instances/%d", databaseID) - req := c.R(ctx).SetResult(&MongoDatabase{}) - r, err := coupleAPIErrors(req.Get(e)) - if err != nil { - return nil, err - } - - return r.Result().(*MongoDatabase), nil -} - -// CreateMongoDatabase creates a new Mongo Database using the createOpts as configuration, returns the new Mongo Database -func (c *Client) CreateMongoDatabase(ctx context.Context, opts MongoCreateOptions) (*MongoDatabase, error) { - body, err := json.Marshal(opts) - if err != nil { - return nil, err - } - - e := "databases/mongodb/instances" - req := c.R(ctx).SetResult(&MongoDatabase{}).SetBody(string(body)) - r, err := coupleAPIErrors(req.Post(e)) - if err != nil { - return nil, err - } - return r.Result().(*MongoDatabase), nil -} - -// DeleteMongoDatabase deletes an existing Mongo Database with the given id -func (c *Client) DeleteMongoDatabase(ctx context.Context, databaseID int) error { - e := fmt.Sprintf("databases/mongodb/instances/%d", databaseID) - _, err := coupleAPIErrors(c.R(ctx).Delete(e)) - return err -} - -// UpdateMongoDatabase updates the given Mongo Database with the provided opts, returns the MongoDatabase with the new settings -func (c *Client) UpdateMongoDatabase(ctx context.Context, databaseID int, opts MongoUpdateOptions) (*MongoDatabase, error) { - body, err := json.Marshal(opts) - if err != nil { - return nil, err - } - - e := fmt.Sprintf("databases/mongodb/instances/%d", databaseID) - req := c.R(ctx).SetResult(&MongoDatabase{}).SetBody(string(body)) - r, err := coupleAPIErrors(req.Put(e)) - if err != nil { - return nil, err - } - - return r.Result().(*MongoDatabase), nil -} - -// PatchMongoDatabase applies security patches and updates to the underlying operating system of the Managed Mongo Database -func (c *Client) PatchMongoDatabase(ctx context.Context, databaseID int) error { - e := fmt.Sprintf("databases/mongodb/instances/%d/patch", databaseID) - _, err := coupleAPIErrors(c.R(ctx).Post(e)) - return err -} - -// GetMongoDatabaseCredentials returns the Root Credentials for the given Mongo Database -func (c *Client) GetMongoDatabaseCredentials(ctx context.Context, databaseID int) (*MongoDatabaseCredential, error) { - e := fmt.Sprintf("databases/mongodb/instances/%d/credentials", databaseID) - req := c.R(ctx).SetResult(&MongoDatabaseCredential{}) - r, err := coupleAPIErrors(req.Get(e)) - if err != nil { - return nil, err - } - - return r.Result().(*MongoDatabaseCredential), nil -} - -// ResetMongoDatabaseCredentials returns the Root Credentials for the given Mongo Database (may take a few seconds to work) -func (c *Client) ResetMongoDatabaseCredentials(ctx context.Context, databaseID int) error { - e := fmt.Sprintf("databases/mongodb/instances/%d/credentials/reset", databaseID) - _, err := coupleAPIErrors(c.R(ctx).Post(e)) - return err -} - -// GetMongoDatabaseSSL returns the SSL Certificate for the given Mongo Database -func (c *Client) GetMongoDatabaseSSL(ctx context.Context, databaseID int) (*MongoDatabaseSSL, error) { - e := fmt.Sprintf("databases/mongodb/instances/%d/ssl", databaseID) - req := c.R(ctx).SetResult(&MongoDatabaseSSL{}) - r, err := coupleAPIErrors(req.Get(e)) - if err != nil { - return nil, err - } - - return r.Result().(*MongoDatabaseSSL), nil -} - -// GetMongoDatabaseBackup returns a specific Mongo Database Backup with the given ids -func (c *Client) GetMongoDatabaseBackup(ctx context.Context, databaseID int, backupID int) (*MongoDatabaseBackup, error) { - e := fmt.Sprintf("databases/mongodb/instances/%d/backups/%d", databaseID, backupID) - req := c.R(ctx).SetResult(&MongoDatabaseBackup{}) - r, err := coupleAPIErrors(req.Get(e)) - if err != nil { - return nil, err - } - - return r.Result().(*MongoDatabaseBackup), nil -} - -// RestoreMongoDatabaseBackup returns the given Mongo Database with the given Backup -func (c *Client) RestoreMongoDatabaseBackup(ctx context.Context, databaseID int, backupID int) error { - e := fmt.Sprintf("databases/mongodb/instances/%d/backups/%d/restore", databaseID, backupID) - _, err := coupleAPIErrors(c.R(ctx).Post(e)) - return err -} - -// CreateMongoDatabaseBackup creates a snapshot for the given Mongo database -func (c *Client) CreateMongoDatabaseBackup(ctx context.Context, databaseID int, opts MongoBackupCreateOptions) error { - body, err := json.Marshal(opts) - if err != nil { - return err - } - e := fmt.Sprintf("databases/mongodb/instances/%d/backups", databaseID) - _, err = coupleAPIErrors(c.R(ctx).SetBody(string(body)).Post(e)) - return err -} diff --git a/vendor/github.com/linode/linodego/pagination.go b/vendor/github.com/linode/linodego/pagination.go index 2de2cfe32dd..45313e72d78 100644 --- a/vendor/github.com/linode/linodego/pagination.go +++ b/vendor/github.com/linode/linodego/pagination.go @@ -16,16 +16,16 @@ import ( // PageOptions are the pagination parameters for List endpoints type PageOptions struct { - Page int `url:"page,omitempty" json:"page"` - Pages int `url:"pages,omitempty" json:"pages"` - Results int `url:"results,omitempty" json:"results"` + Page int `json:"page" url:"page,omitempty"` + Pages int `json:"pages" url:"pages,omitempty"` + Results int `json:"results" url:"results,omitempty"` } // ListOptions are the pagination and filtering (TODO) parameters for endpoints type ListOptions struct { *PageOptions - PageSize int - Filter string + PageSize int `json:"page_size"` + Filter string `json:"filter"` } // NewListOptions simplified construction of ListOptions using only diff --git a/vendor/github.com/linode/linodego/waitfor.go b/vendor/github.com/linode/linodego/waitfor.go index 60fbf9ec3e9..6f872962314 100644 --- a/vendor/github.com/linode/linodego/waitfor.go +++ b/vendor/github.com/linode/linodego/waitfor.go @@ -270,8 +270,15 @@ func (client Client) WaitForLKEClusterConditions( // WaitForEventFinished waits for an entity action to reach the 'finished' state // before returning. It will timeout with an error after timeoutSeconds. // If the event indicates a failure both the failed event and the error will be returned. -// nolint -func (client Client) WaitForEventFinished(ctx context.Context, id any, entityType EntityType, action EventAction, minStart time.Time, timeoutSeconds int) (*Event, error) { +//nolint +func (client Client) WaitForEventFinished( + ctx context.Context, + id any, + entityType EntityType, + action EventAction, + minStart time.Time, + timeoutSeconds int, +) (*Event, error) { titledEntityType := strings.Title(string(entityType)) filter := Filter{ Order: Descending, @@ -291,12 +298,11 @@ func (client Client) WaitForEventFinished(ctx context.Context, id any, entityTyp // All of the filter supported types have int ids filterableEntityID, err := strconv.Atoi(fmt.Sprintf("%v", id)) if err != nil { - return nil, fmt.Errorf("Error parsing Entity ID %q for optimized WaitForEventFinished EventType %q: %w", id, entityType, err) + return nil, fmt.Errorf("error parsing Entity ID %q for optimized "+ + "WaitForEventFinished EventType %q: %w", id, entityType, err) } filter.AddField(Eq, "entity.id", filterableEntityID) filter.AddField(Eq, "entity.type", entityType) - - // TODO: are we conformatable with pages = 0 with the event type and id filter? } ctx, cancel := context.WithTimeout(ctx, time.Duration(timeoutSeconds)*time.Second) @@ -369,8 +375,6 @@ func (client Client) WaitForEventFinished(ctx context.Context, id any, entityTyp continue } - // @TODO(displague) This event.Created check shouldn't be needed, but it appears - // that the ListEvents method is not populating it correctly if event.Created == nil { log.Printf("[WARN] event.Created is nil when API returned: %#+v", event.Created) } @@ -387,7 +391,7 @@ func (client Client) WaitForEventFinished(ctx context.Context, id any, entityTyp log.Printf("[INFO] %s %v action %s is finished", titledEntityType, id, action) return &event, nil } - // TODO(displague) can we bump the ticker to TimeRemaining/2 (>=1) when non-nil? + nextLog = fmt.Sprintf("[INFO] %s %v action %s is %s", titledEntityType, id, action, event.Status) } @@ -456,33 +460,6 @@ func (client Client) WaitForMySQLDatabaseBackup(ctx context.Context, dbID int, l } } -// WaitForMongoDatabaseBackup waits for the backup with the given label to be available. -func (client Client) WaitForMongoDatabaseBackup(ctx context.Context, dbID int, label string, timeoutSeconds int) (*MongoDatabaseBackup, error) { - ctx, cancel := context.WithTimeout(ctx, time.Duration(timeoutSeconds)*time.Second) - defer cancel() - - ticker := time.NewTicker(client.millisecondsPerPoll * time.Millisecond) - defer ticker.Stop() - - for { - select { - case <-ticker.C: - backups, err := client.ListMongoDatabaseBackups(ctx, dbID, nil) - if err != nil { - return nil, err - } - - for _, backup := range backups { - if backup.Label == label { - return &backup, nil - } - } - case <-ctx.Done(): - return nil, fmt.Errorf("failed to wait for backup %s: %w", label, ctx.Err()) - } - } -} - // WaitForPostgresDatabaseBackup waits for the backup with the given label to be available. func (client Client) WaitForPostgresDatabaseBackup(ctx context.Context, dbID int, label string, timeoutSeconds int) (*PostgresDatabaseBackup, error) { ctx, cancel := context.WithTimeout(ctx, time.Duration(timeoutSeconds)*time.Second) @@ -521,14 +498,6 @@ var databaseStatusHandlers = map[DatabaseEngineType]databaseStatusFunc{ return db.Status, nil }, - DatabaseEngineTypeMongo: func(ctx context.Context, client Client, dbID int) (DatabaseStatus, error) { - db, err := client.GetMongoDatabase(ctx, dbID) - if err != nil { - return "", err - } - - return db.Status, nil - }, DatabaseEngineTypePostgres: func(ctx context.Context, client Client, dbID int) (DatabaseStatus, error) { db, err := client.GetPostgresDatabase(ctx, dbID) if err != nil { @@ -726,3 +695,56 @@ func (p *EventPoller) WaitForFinished( } } } + +// WaitForResourceFree waits for a resource to have no running events. +func (client Client) WaitForResourceFree( + ctx context.Context, entityType EntityType, entityID any, timeoutSeconds int, +) error { + apiFilter := Filter{ + Order: Descending, + OrderBy: "created", + } + apiFilter.AddField(Eq, "entity.id", entityID) + apiFilter.AddField(Eq, "entity.type", entityType) + + filterStr, err := apiFilter.MarshalJSON() + if err != nil { + return fmt.Errorf("failed to create filter: %s", err) + } + + ctx, cancel := context.WithTimeout(ctx, time.Duration(timeoutSeconds)*time.Second) + defer cancel() + + ticker := time.NewTicker(client.millisecondsPerPoll * time.Millisecond) + defer ticker.Stop() + + // A helper function to determine whether a resource is busy + checkIsBusy := func(events []Event) bool { + for _, event := range events { + if event.Status == EventStarted || event.Status == EventScheduled { + return true + } + } + + return false + } + + for { + select { + case <-ticker.C: + events, err := client.ListEvents(ctx, &ListOptions{ + Filter: string(filterStr), + }) + if err != nil { + return fmt.Errorf("failed to list events: %s", err) + } + + if !checkIsBusy(events) { + return nil + } + + case <-ctx.Done(): + return fmt.Errorf("failed to wait for resource free: %s", ctx.Err()) + } + } +} diff --git a/vendor/github.com/miekg/dns/client.go b/vendor/github.com/miekg/dns/client.go index 9051ae00778..2cdd49af177 100644 --- a/vendor/github.com/miekg/dns/client.go +++ b/vendor/github.com/miekg/dns/client.go @@ -6,7 +6,6 @@ import ( "context" "crypto/tls" "encoding/binary" - "fmt" "io" "net" "strings" @@ -56,14 +55,20 @@ type Client struct { // Timeout is a cumulative timeout for dial, write and read, defaults to 0 (disabled) - overrides DialTimeout, ReadTimeout, // WriteTimeout when non-zero. Can be overridden with net.Dialer.Timeout (see Client.ExchangeWithDialer and // Client.Dialer) or context.Context.Deadline (see ExchangeContext) - Timeout time.Duration - DialTimeout time.Duration // net.DialTimeout, defaults to 2 seconds, or net.Dialer.Timeout if expiring earlier - overridden by Timeout when that value is non-zero - ReadTimeout time.Duration // net.Conn.SetReadTimeout value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero - WriteTimeout time.Duration // net.Conn.SetWriteTimeout value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero - TsigSecret map[string]string // secret(s) for Tsig map[], zonename must be in canonical form (lowercase, fqdn, see RFC 4034 Section 6.2) - TsigProvider TsigProvider // An implementation of the TsigProvider interface. If defined it replaces TsigSecret and is used for all TSIG operations. - SingleInflight bool // if true suppress multiple outstanding queries for the same Qname, Qtype and Qclass - group singleflight + Timeout time.Duration + DialTimeout time.Duration // net.DialTimeout, defaults to 2 seconds, or net.Dialer.Timeout if expiring earlier - overridden by Timeout when that value is non-zero + ReadTimeout time.Duration // net.Conn.SetReadTimeout value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero + WriteTimeout time.Duration // net.Conn.SetWriteTimeout value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero + TsigSecret map[string]string // secret(s) for Tsig map[], zonename must be in canonical form (lowercase, fqdn, see RFC 4034 Section 6.2) + TsigProvider TsigProvider // An implementation of the TsigProvider interface. If defined it replaces TsigSecret and is used for all TSIG operations. + + // SingleInflight previously serialised multiple concurrent queries for the + // same Qname, Qtype and Qclass to ensure only one would be in flight at a + // time. + // + // Deprecated: This is a no-op. Callers should implement their own in flight + // query caching if needed. See github.com/miekg/dns/issues/1449. + SingleInflight bool } // Exchange performs a synchronous UDP query. It sends the message m to the address @@ -185,26 +190,7 @@ func (c *Client) ExchangeWithConn(m *Msg, conn *Conn) (r *Msg, rtt time.Duration return c.exchangeWithConnContext(context.Background(), m, conn) } -func (c *Client) exchangeWithConnContext(ctx context.Context, m *Msg, conn *Conn) (r *Msg, rtt time.Duration, err error) { - if !c.SingleInflight { - return c.exchangeContext(ctx, m, conn) - } - - q := m.Question[0] - key := fmt.Sprintf("%s:%d:%d", q.Name, q.Qtype, q.Qclass) - r, rtt, err, shared := c.group.Do(key, func() (*Msg, time.Duration, error) { - // When we're doing singleflight we don't want one context cancellation, cancel _all_ outstanding queries. - // Hence we ignore the context and use Background(). - return c.exchangeContext(context.Background(), m, conn) - }) - if r != nil && shared { - r = r.Copy() - } - - return r, rtt, err -} - -func (c *Client) exchangeContext(ctx context.Context, m *Msg, co *Conn) (r *Msg, rtt time.Duration, err error) { +func (c *Client) exchangeWithConnContext(ctx context.Context, m *Msg, co *Conn) (r *Msg, rtt time.Duration, err error) { opt := m.IsEdns0() // If EDNS0 is used use that for size. if opt != nil && opt.UDPSize() >= MinMsgSize { diff --git a/vendor/github.com/miekg/dns/defaults.go b/vendor/github.com/miekg/dns/defaults.go index 75b17f0c1e4..c1558b79c3b 100644 --- a/vendor/github.com/miekg/dns/defaults.go +++ b/vendor/github.com/miekg/dns/defaults.go @@ -272,18 +272,24 @@ func IsMsg(buf []byte) error { // IsFqdn checks if a domain name is fully qualified. func IsFqdn(s string) bool { - s2 := strings.TrimSuffix(s, ".") - if s == s2 { + // Check for (and remove) a trailing dot, returning if there isn't one. + if s == "" || s[len(s)-1] != '.' { return false } + s = s[:len(s)-1] - i := strings.LastIndexFunc(s2, func(r rune) bool { + // If we don't have an escape sequence before the final dot, we know it's + // fully qualified and can return here. + if s == "" || s[len(s)-1] != '\\' { + return true + } + + // Otherwise we have to check if the dot is escaped or not by checking if + // there are an odd or even number of escape sequences before the dot. + i := strings.LastIndexFunc(s, func(r rune) bool { return r != '\\' }) - - // Test whether we have an even number of escape sequences before - // the dot or none. - return (len(s2)-i)%2 != 0 + return (len(s)-i)%2 != 0 } // IsRRset checks if a set of RRs is a valid RRset as defined by RFC 2181. diff --git a/vendor/github.com/miekg/dns/scan.go b/vendor/github.com/miekg/dns/scan.go index 57be9882772..3083c3e5f37 100644 --- a/vendor/github.com/miekg/dns/scan.go +++ b/vendor/github.com/miekg/dns/scan.go @@ -10,13 +10,13 @@ import ( "strings" ) -const maxTok = 2048 // Largest token we can return. +const maxTok = 512 // Token buffer start size, and growth size amount. // The maximum depth of $INCLUDE directives supported by the // ZoneParser API. const maxIncludeDepth = 7 -// Tokinize a RFC 1035 zone file. The tokenizer will normalize it: +// Tokenize a RFC 1035 zone file. The tokenizer will normalize it: // * Add ownernames if they are left blank; // * Suppress sequences of spaces; // * Make each RR fit on one line (_NEWLINE is send as last) @@ -765,8 +765,8 @@ func (zl *zlexer) Next() (lex, bool) { } var ( - str [maxTok]byte // Hold string text - com [maxTok]byte // Hold comment text + str = make([]byte, maxTok) // Hold string text + com = make([]byte, maxTok) // Hold comment text stri int // Offset in str (0 means empty) comi int // Offset in com (0 means empty) @@ -785,14 +785,12 @@ func (zl *zlexer) Next() (lex, bool) { l.line, l.column = zl.line, zl.column if stri >= len(str) { - l.token = "token length insufficient for parsing" - l.err = true - return *l, true + // if buffer length is insufficient, increase it. + str = append(str[:], make([]byte, maxTok)...) } if comi >= len(com) { - l.token = "comment length insufficient for parsing" - l.err = true - return *l, true + // if buffer length is insufficient, increase it. + com = append(com[:], make([]byte, maxTok)...) } switch x { @@ -816,7 +814,7 @@ func (zl *zlexer) Next() (lex, bool) { if stri == 0 { // Space directly in the beginning, handled in the grammar } else if zl.owner { - // If we have a string and its the first, make it an owner + // If we have a string and it's the first, make it an owner l.value = zOwner l.token = string(str[:stri]) diff --git a/vendor/github.com/miekg/dns/scan_rr.go b/vendor/github.com/miekg/dns/scan_rr.go index 2d44a3987a9..d08c8e6a72f 100644 --- a/vendor/github.com/miekg/dns/scan_rr.go +++ b/vendor/github.com/miekg/dns/scan_rr.go @@ -904,11 +904,18 @@ func (rr *RRSIG) parse(c *zlexer, o string) *ParseError { c.Next() // zBlank l, _ = c.Next() - i, e := strconv.ParseUint(l.token, 10, 8) - if e != nil || l.err { + if l.err { return &ParseError{"", "bad RRSIG Algorithm", l} } - rr.Algorithm = uint8(i) + i, e := strconv.ParseUint(l.token, 10, 8) + rr.Algorithm = uint8(i) // if 0 we'll check the mnemonic in the if + if e != nil { + v, ok := StringToAlgorithm[l.token] + if !ok { + return &ParseError{"", "bad RRSIG Algorithm", l} + } + rr.Algorithm = v + } c.Next() // zBlank l, _ = c.Next() diff --git a/vendor/github.com/miekg/dns/singleinflight.go b/vendor/github.com/miekg/dns/singleinflight.go deleted file mode 100644 index febcc300fe1..00000000000 --- a/vendor/github.com/miekg/dns/singleinflight.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Adapted for dns package usage by Miek Gieben. - -package dns - -import "sync" -import "time" - -// call is an in-flight or completed singleflight.Do call -type call struct { - wg sync.WaitGroup - val *Msg - rtt time.Duration - err error - dups int -} - -// singleflight represents a class of work and forms a namespace in -// which units of work can be executed with duplicate suppression. -type singleflight struct { - sync.Mutex // protects m - m map[string]*call // lazily initialized - - dontDeleteForTesting bool // this is only to be used by TestConcurrentExchanges -} - -// Do executes and returns the results of the given function, making -// sure that only one execution is in-flight for a given key at a -// time. If a duplicate comes in, the duplicate caller waits for the -// original to complete and receives the same results. -// The return value shared indicates whether v was given to multiple callers. -func (g *singleflight) Do(key string, fn func() (*Msg, time.Duration, error)) (v *Msg, rtt time.Duration, err error, shared bool) { - g.Lock() - if g.m == nil { - g.m = make(map[string]*call) - } - if c, ok := g.m[key]; ok { - c.dups++ - g.Unlock() - c.wg.Wait() - return c.val, c.rtt, c.err, true - } - c := new(call) - c.wg.Add(1) - g.m[key] = c - g.Unlock() - - c.val, c.rtt, c.err = fn() - c.wg.Done() - - if !g.dontDeleteForTesting { - g.Lock() - delete(g.m, key) - g.Unlock() - } - - return c.val, c.rtt, c.err, c.dups > 0 -} diff --git a/vendor/github.com/miekg/dns/version.go b/vendor/github.com/miekg/dns/version.go index f03a169c234..6094585d8b8 100644 --- a/vendor/github.com/miekg/dns/version.go +++ b/vendor/github.com/miekg/dns/version.go @@ -3,7 +3,7 @@ package dns import "fmt" // Version is current version of this library. -var Version = v{1, 1, 53} +var Version = v{1, 1, 54} // v holds the version of this library. type v struct { diff --git a/vendor/github.com/pkg/browser/LICENSE b/vendor/github.com/pkg/browser/LICENSE new file mode 100644 index 00000000000..65f78fb6291 --- /dev/null +++ b/vendor/github.com/pkg/browser/LICENSE @@ -0,0 +1,23 @@ +Copyright (c) 2014, Dave Cheney +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/pkg/browser/README.md b/vendor/github.com/pkg/browser/README.md new file mode 100644 index 00000000000..72b1976e303 --- /dev/null +++ b/vendor/github.com/pkg/browser/README.md @@ -0,0 +1,55 @@ + +# browser + import "github.com/pkg/browser" + +Package browser provides helpers to open files, readers, and urls in a browser window. + +The choice of which browser is started is entirely client dependant. + + + + + +## Variables +``` go +var Stderr io.Writer = os.Stderr +``` +Stderr is the io.Writer to which executed commands write standard error. + +``` go +var Stdout io.Writer = os.Stdout +``` +Stdout is the io.Writer to which executed commands write standard output. + + +## func OpenFile +``` go +func OpenFile(path string) error +``` +OpenFile opens new browser window for the file path. + + +## func OpenReader +``` go +func OpenReader(r io.Reader) error +``` +OpenReader consumes the contents of r and presents the +results in a new browser window. + + +## func OpenURL +``` go +func OpenURL(url string) error +``` +OpenURL opens a new browser window pointing to url. + + + + + + + + + +- - - +Generated by [godoc2md](http://godoc.org/github.com/davecheney/godoc2md) diff --git a/vendor/github.com/pkg/browser/browser.go b/vendor/github.com/pkg/browser/browser.go new file mode 100644 index 00000000000..d7969d74d80 --- /dev/null +++ b/vendor/github.com/pkg/browser/browser.go @@ -0,0 +1,57 @@ +// Package browser provides helpers to open files, readers, and urls in a browser window. +// +// The choice of which browser is started is entirely client dependant. +package browser + +import ( + "fmt" + "io" + "io/ioutil" + "os" + "os/exec" + "path/filepath" +) + +// Stdout is the io.Writer to which executed commands write standard output. +var Stdout io.Writer = os.Stdout + +// Stderr is the io.Writer to which executed commands write standard error. +var Stderr io.Writer = os.Stderr + +// OpenFile opens new browser window for the file path. +func OpenFile(path string) error { + path, err := filepath.Abs(path) + if err != nil { + return err + } + return OpenURL("file://" + path) +} + +// OpenReader consumes the contents of r and presents the +// results in a new browser window. +func OpenReader(r io.Reader) error { + f, err := ioutil.TempFile("", "browser.*.html") + if err != nil { + return fmt.Errorf("browser: could not create temporary file: %v", err) + } + if _, err := io.Copy(f, r); err != nil { + f.Close() + return fmt.Errorf("browser: caching temporary file failed: %v", err) + } + if err := f.Close(); err != nil { + return fmt.Errorf("browser: caching temporary file failed: %v", err) + } + return OpenFile(f.Name()) +} + +// OpenURL opens a new browser window pointing to url. +func OpenURL(url string) error { + return openBrowser(url) +} + +func runCmd(prog string, args ...string) error { + cmd := exec.Command(prog, args...) + cmd.Stdout = Stdout + cmd.Stderr = Stderr + return cmd.Run() +} diff --git a/vendor/github.com/pkg/browser/browser_darwin.go b/vendor/github.com/pkg/browser/browser_darwin.go new file mode 100644 index 00000000000..8507cf7c2b4 --- /dev/null +++ b/vendor/github.com/pkg/browser/browser_darwin.go @@ -0,0 +1,5 @@ +package browser + +func openBrowser(url string) error { + return runCmd("open", url) +} diff --git a/vendor/github.com/pkg/browser/browser_freebsd.go b/vendor/github.com/pkg/browser/browser_freebsd.go new file mode 100644 index 00000000000..4fc7ff0761b --- /dev/null +++ b/vendor/github.com/pkg/browser/browser_freebsd.go @@ -0,0 +1,14 @@ +package browser + +import ( + "errors" + "os/exec" +) + +func openBrowser(url string) error { + err := runCmd("xdg-open", url) + if e, ok := err.(*exec.Error); ok && e.Err == exec.ErrNotFound { + return errors.New("xdg-open: command not found - install xdg-utils from ports(8)") + } + return err +} diff --git a/vendor/github.com/pkg/browser/browser_linux.go b/vendor/github.com/pkg/browser/browser_linux.go new file mode 100644 index 00000000000..d26cdddf9c1 --- /dev/null +++ b/vendor/github.com/pkg/browser/browser_linux.go @@ -0,0 +1,21 @@ +package browser + +import ( + "os/exec" + "strings" +) + +func openBrowser(url string) error { + providers := []string{"xdg-open", "x-www-browser", "www-browser"} + + // There are multiple possible providers to open a browser on linux + // One of them is xdg-open, another is x-www-browser, then there's www-browser, etc. + // Look for one that exists and run it + for _, provider := range providers { + if _, err := exec.LookPath(provider); err == nil { + return runCmd(provider, url) + } + } + + return &exec.Error{Name: strings.Join(providers, ","), Err: exec.ErrNotFound} +} diff --git a/vendor/github.com/pkg/browser/browser_netbsd.go b/vendor/github.com/pkg/browser/browser_netbsd.go new file mode 100644 index 00000000000..65a5e5a2934 --- /dev/null +++ b/vendor/github.com/pkg/browser/browser_netbsd.go @@ -0,0 +1,14 @@ +package browser + +import ( + "errors" + "os/exec" +) + +func openBrowser(url string) error { + err := runCmd("xdg-open", url) + if e, ok := err.(*exec.Error); ok && e.Err == exec.ErrNotFound { + return errors.New("xdg-open: command not found - install xdg-utils from pkgsrc(7)") + } + return err +} diff --git a/vendor/github.com/pkg/browser/browser_openbsd.go b/vendor/github.com/pkg/browser/browser_openbsd.go new file mode 100644 index 00000000000..4fc7ff0761b --- /dev/null +++ b/vendor/github.com/pkg/browser/browser_openbsd.go @@ -0,0 +1,14 @@ +package browser + +import ( + "errors" + "os/exec" +) + +func openBrowser(url string) error { + err := runCmd("xdg-open", url) + if e, ok := err.(*exec.Error); ok && e.Err == exec.ErrNotFound { + return errors.New("xdg-open: command not found - install xdg-utils from ports(8)") + } + return err +} diff --git a/vendor/github.com/pkg/browser/browser_unsupported.go b/vendor/github.com/pkg/browser/browser_unsupported.go new file mode 100644 index 00000000000..7c5c17d34d2 --- /dev/null +++ b/vendor/github.com/pkg/browser/browser_unsupported.go @@ -0,0 +1,12 @@ +// +build !linux,!windows,!darwin,!openbsd,!freebsd,!netbsd + +package browser + +import ( + "fmt" + "runtime" +) + +func openBrowser(url string) error { + return fmt.Errorf("openBrowser: unsupported operating system: %v", runtime.GOOS) +} diff --git a/vendor/github.com/pkg/browser/browser_windows.go b/vendor/github.com/pkg/browser/browser_windows.go new file mode 100644 index 00000000000..63e192959a5 --- /dev/null +++ b/vendor/github.com/pkg/browser/browser_windows.go @@ -0,0 +1,7 @@ +package browser + +import "golang.org/x/sys/windows" + +func openBrowser(url string) error { + return windows.ShellExecute(0, nil, windows.StringToUTF16Ptr(url), nil, nil, windows.SW_SHOWNORMAL) +} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client.go index 61fc2e3d189..d3482c40ca7 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client.go @@ -78,7 +78,7 @@ func InstrumentRoundTripperCounter(counter *prometheus.CounterVec, next http.Rou for label, resolve := range rtOpts.extraLabelsFromCtx { l[label] = resolve(resp.Request.Context()) } - counter.With(l).(prometheus.ExemplarAdder).AddWithExemplar(1, rtOpts.getExemplarFn(r.Context())) + addWithExemplar(counter.With(l), 1, rtOpts.getExemplarFn(r.Context())) } return resp, err } @@ -122,7 +122,7 @@ func InstrumentRoundTripperDuration(obs prometheus.ObserverVec, next http.RoundT for label, resolve := range rtOpts.extraLabelsFromCtx { l[label] = resolve(resp.Request.Context()) } - obs.With(l).(prometheus.ExemplarObserver).ObserveWithExemplar(time.Since(start).Seconds(), rtOpts.getExemplarFn(r.Context())) + observeWithExemplar(obs.With(l), time.Since(start).Seconds(), rtOpts.getExemplarFn(r.Context())) } return resp, err } diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server.go index 71abd755324..3793036ad09 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server.go @@ -28,6 +28,26 @@ import ( // magicString is used for the hacky label test in checkLabels. Remove once fixed. const magicString = "zZgWfBxLqvG8kc8IMv3POi2Bb0tZI3vAnBx+gBaFi9FyPzB/CzKUer1yufDa" +// observeWithExemplar is a wrapper for [prometheus.ExemplarAdder.ExemplarObserver], +// which falls back to [prometheus.Observer.Observe] if no labels are provided. +func observeWithExemplar(obs prometheus.Observer, val float64, labels map[string]string) { + if labels == nil { + obs.Observe(val) + return + } + obs.(prometheus.ExemplarObserver).ObserveWithExemplar(val, labels) +} + +// addWithExemplar is a wrapper for [prometheus.ExemplarAdder.AddWithExemplar], +// which falls back to [prometheus.Counter.Add] if no labels are provided. +func addWithExemplar(obs prometheus.Counter, val float64, labels map[string]string) { + if labels == nil { + obs.Add(val) + return + } + obs.(prometheus.ExemplarAdder).AddWithExemplar(val, labels) +} + // InstrumentHandlerInFlight is a middleware that wraps the provided // http.Handler. It sets the provided prometheus.Gauge to the number of // requests currently handled by the wrapped http.Handler. @@ -80,7 +100,7 @@ func InstrumentHandlerDuration(obs prometheus.ObserverVec, next http.Handler, op for label, resolve := range hOpts.extraLabelsFromCtx { l[label] = resolve(r.Context()) } - obs.With(l).(prometheus.ExemplarObserver).ObserveWithExemplar(time.Since(now).Seconds(), hOpts.getExemplarFn(r.Context())) + observeWithExemplar(obs.With(l), time.Since(now).Seconds(), hOpts.getExemplarFn(r.Context())) } } @@ -91,7 +111,7 @@ func InstrumentHandlerDuration(obs prometheus.ObserverVec, next http.Handler, op for label, resolve := range hOpts.extraLabelsFromCtx { l[label] = resolve(r.Context()) } - obs.With(l).(prometheus.ExemplarObserver).ObserveWithExemplar(time.Since(now).Seconds(), hOpts.getExemplarFn(r.Context())) + observeWithExemplar(obs.With(l), time.Since(now).Seconds(), hOpts.getExemplarFn(r.Context())) } } @@ -130,7 +150,7 @@ func InstrumentHandlerCounter(counter *prometheus.CounterVec, next http.Handler, for label, resolve := range hOpts.extraLabelsFromCtx { l[label] = resolve(r.Context()) } - counter.With(l).(prometheus.ExemplarAdder).AddWithExemplar(1, hOpts.getExemplarFn(r.Context())) + addWithExemplar(counter.With(l), 1, hOpts.getExemplarFn(r.Context())) } } @@ -141,7 +161,7 @@ func InstrumentHandlerCounter(counter *prometheus.CounterVec, next http.Handler, for label, resolve := range hOpts.extraLabelsFromCtx { l[label] = resolve(r.Context()) } - counter.With(l).(prometheus.ExemplarAdder).AddWithExemplar(1, hOpts.getExemplarFn(r.Context())) + addWithExemplar(counter.With(l), 1, hOpts.getExemplarFn(r.Context())) } } @@ -183,7 +203,7 @@ func InstrumentHandlerTimeToWriteHeader(obs prometheus.ObserverVec, next http.Ha for label, resolve := range hOpts.extraLabelsFromCtx { l[label] = resolve(r.Context()) } - obs.With(l).(prometheus.ExemplarObserver).ObserveWithExemplar(time.Since(now).Seconds(), hOpts.getExemplarFn(r.Context())) + observeWithExemplar(obs.With(l), time.Since(now).Seconds(), hOpts.getExemplarFn(r.Context())) }) next.ServeHTTP(d, r) } @@ -227,7 +247,7 @@ func InstrumentHandlerRequestSize(obs prometheus.ObserverVec, next http.Handler, for label, resolve := range hOpts.extraLabelsFromCtx { l[label] = resolve(r.Context()) } - obs.With(l).(prometheus.ExemplarObserver).ObserveWithExemplar(float64(size), hOpts.getExemplarFn(r.Context())) + observeWithExemplar(obs.With(l), float64(size), hOpts.getExemplarFn(r.Context())) } } @@ -239,7 +259,7 @@ func InstrumentHandlerRequestSize(obs prometheus.ObserverVec, next http.Handler, for label, resolve := range hOpts.extraLabelsFromCtx { l[label] = resolve(r.Context()) } - obs.With(l).(prometheus.ExemplarObserver).ObserveWithExemplar(float64(size), hOpts.getExemplarFn(r.Context())) + observeWithExemplar(obs.With(l), float64(size), hOpts.getExemplarFn(r.Context())) } } @@ -279,7 +299,7 @@ func InstrumentHandlerResponseSize(obs prometheus.ObserverVec, next http.Handler for label, resolve := range hOpts.extraLabelsFromCtx { l[label] = resolve(r.Context()) } - obs.With(l).(prometheus.ExemplarObserver).ObserveWithExemplar(float64(d.Written()), hOpts.getExemplarFn(r.Context())) + observeWithExemplar(obs.With(l), float64(d.Written()), hOpts.getExemplarFn(r.Context())) }) } diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/option.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/option.go index af7403df4c0..5d4383aa14a 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/option.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/option.go @@ -66,9 +66,9 @@ func WithExtraMethods(methods ...string) Option { }) } -// WithExemplarFromContext adds allows to put a hook to all counter and histogram metrics. -// If the hook function returns non-nil labels, exemplars will be added for that request, otherwise metric -// will get instrumented without exemplar. +// WithExemplarFromContext allows to inject function that will get exemplar from context that will be put to counter and histogram metrics. +// If the function returns nil labels or the metric does not support exemplars, no exemplar will be added (noop), but +// metric will continue to observe/increment. func WithExemplarFromContext(getExemplarFn func(requestCtx context.Context) prometheus.Labels) Option { return optionApplyFunc(func(o *options) { o.getExemplarFn = getExemplarFn diff --git a/vendor/github.com/prometheus/client_model/go/metrics.pb.go b/vendor/github.com/prometheus/client_model/go/metrics.pb.go index 35904ea1986..2b5bca4b999 100644 --- a/vendor/github.com/prometheus/client_model/go/metrics.pb.go +++ b/vendor/github.com/prometheus/client_model/go/metrics.pb.go @@ -1,25 +1,38 @@ +// Copyright 2013 Prometheus Team +// 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. + // Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.30.0 +// protoc v3.20.3 // source: io/prometheus/client/metrics.proto package io_prometheus_client import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" - timestamp "github.com/golang/protobuf/ptypes/timestamp" - math "math" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + timestamppb "google.golang.org/protobuf/types/known/timestamppb" + reflect "reflect" + sync "sync" ) -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) type MetricType int32 @@ -38,23 +51,25 @@ const ( MetricType_GAUGE_HISTOGRAM MetricType = 5 ) -var MetricType_name = map[int32]string{ - 0: "COUNTER", - 1: "GAUGE", - 2: "SUMMARY", - 3: "UNTYPED", - 4: "HISTOGRAM", - 5: "GAUGE_HISTOGRAM", -} - -var MetricType_value = map[string]int32{ - "COUNTER": 0, - "GAUGE": 1, - "SUMMARY": 2, - "UNTYPED": 3, - "HISTOGRAM": 4, - "GAUGE_HISTOGRAM": 5, -} +// Enum value maps for MetricType. +var ( + MetricType_name = map[int32]string{ + 0: "COUNTER", + 1: "GAUGE", + 2: "SUMMARY", + 3: "UNTYPED", + 4: "HISTOGRAM", + 5: "GAUGE_HISTOGRAM", + } + MetricType_value = map[string]int32{ + "COUNTER": 0, + "GAUGE": 1, + "SUMMARY": 2, + "UNTYPED": 3, + "HISTOGRAM": 4, + "GAUGE_HISTOGRAM": 5, + } +) func (x MetricType) Enum() *MetricType { p := new(MetricType) @@ -63,449 +78,519 @@ func (x MetricType) Enum() *MetricType { } func (x MetricType) String() string { - return proto.EnumName(MetricType_name, int32(x)) + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } -func (x *MetricType) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(MetricType_value, data, "MetricType") +func (MetricType) Descriptor() protoreflect.EnumDescriptor { + return file_io_prometheus_client_metrics_proto_enumTypes[0].Descriptor() +} + +func (MetricType) Type() protoreflect.EnumType { + return &file_io_prometheus_client_metrics_proto_enumTypes[0] +} + +func (x MetricType) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Do not use. +func (x *MetricType) UnmarshalJSON(b []byte) error { + num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } - *x = MetricType(value) + *x = MetricType(num) return nil } +// Deprecated: Use MetricType.Descriptor instead. func (MetricType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_d1e5ddb18987a258, []int{0} + return file_io_prometheus_client_metrics_proto_rawDescGZIP(), []int{0} } type LabelPair struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Value *string `protobuf:"bytes,2,opt,name=value" json:"value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields -func (m *LabelPair) Reset() { *m = LabelPair{} } -func (m *LabelPair) String() string { return proto.CompactTextString(m) } -func (*LabelPair) ProtoMessage() {} -func (*LabelPair) Descriptor() ([]byte, []int) { - return fileDescriptor_d1e5ddb18987a258, []int{0} + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + Value *string `protobuf:"bytes,2,opt,name=value" json:"value,omitempty"` } -func (m *LabelPair) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_LabelPair.Unmarshal(m, b) -} -func (m *LabelPair) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_LabelPair.Marshal(b, m, deterministic) -} -func (m *LabelPair) XXX_Merge(src proto.Message) { - xxx_messageInfo_LabelPair.Merge(m, src) +func (x *LabelPair) Reset() { + *x = LabelPair{} + if protoimpl.UnsafeEnabled { + mi := &file_io_prometheus_client_metrics_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *LabelPair) XXX_Size() int { - return xxx_messageInfo_LabelPair.Size(m) + +func (x *LabelPair) String() string { + return protoimpl.X.MessageStringOf(x) } -func (m *LabelPair) XXX_DiscardUnknown() { - xxx_messageInfo_LabelPair.DiscardUnknown(m) + +func (*LabelPair) ProtoMessage() {} + +func (x *LabelPair) ProtoReflect() protoreflect.Message { + mi := &file_io_prometheus_client_metrics_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -var xxx_messageInfo_LabelPair proto.InternalMessageInfo +// Deprecated: Use LabelPair.ProtoReflect.Descriptor instead. +func (*LabelPair) Descriptor() ([]byte, []int) { + return file_io_prometheus_client_metrics_proto_rawDescGZIP(), []int{0} +} -func (m *LabelPair) GetName() string { - if m != nil && m.Name != nil { - return *m.Name +func (x *LabelPair) GetName() string { + if x != nil && x.Name != nil { + return *x.Name } return "" } -func (m *LabelPair) GetValue() string { - if m != nil && m.Value != nil { - return *m.Value +func (x *LabelPair) GetValue() string { + if x != nil && x.Value != nil { + return *x.Value } return "" } type Gauge struct { - Value *float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields -func (m *Gauge) Reset() { *m = Gauge{} } -func (m *Gauge) String() string { return proto.CompactTextString(m) } -func (*Gauge) ProtoMessage() {} -func (*Gauge) Descriptor() ([]byte, []int) { - return fileDescriptor_d1e5ddb18987a258, []int{1} + Value *float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"` } -func (m *Gauge) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Gauge.Unmarshal(m, b) -} -func (m *Gauge) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Gauge.Marshal(b, m, deterministic) -} -func (m *Gauge) XXX_Merge(src proto.Message) { - xxx_messageInfo_Gauge.Merge(m, src) +func (x *Gauge) Reset() { + *x = Gauge{} + if protoimpl.UnsafeEnabled { + mi := &file_io_prometheus_client_metrics_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *Gauge) XXX_Size() int { - return xxx_messageInfo_Gauge.Size(m) + +func (x *Gauge) String() string { + return protoimpl.X.MessageStringOf(x) } -func (m *Gauge) XXX_DiscardUnknown() { - xxx_messageInfo_Gauge.DiscardUnknown(m) + +func (*Gauge) ProtoMessage() {} + +func (x *Gauge) ProtoReflect() protoreflect.Message { + mi := &file_io_prometheus_client_metrics_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -var xxx_messageInfo_Gauge proto.InternalMessageInfo +// Deprecated: Use Gauge.ProtoReflect.Descriptor instead. +func (*Gauge) Descriptor() ([]byte, []int) { + return file_io_prometheus_client_metrics_proto_rawDescGZIP(), []int{1} +} -func (m *Gauge) GetValue() float64 { - if m != nil && m.Value != nil { - return *m.Value +func (x *Gauge) GetValue() float64 { + if x != nil && x.Value != nil { + return *x.Value } return 0 } type Counter struct { - Value *float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"` - Exemplar *Exemplar `protobuf:"bytes,2,opt,name=exemplar" json:"exemplar,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields -func (m *Counter) Reset() { *m = Counter{} } -func (m *Counter) String() string { return proto.CompactTextString(m) } -func (*Counter) ProtoMessage() {} -func (*Counter) Descriptor() ([]byte, []int) { - return fileDescriptor_d1e5ddb18987a258, []int{2} + Value *float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"` + Exemplar *Exemplar `protobuf:"bytes,2,opt,name=exemplar" json:"exemplar,omitempty"` } -func (m *Counter) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Counter.Unmarshal(m, b) -} -func (m *Counter) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Counter.Marshal(b, m, deterministic) -} -func (m *Counter) XXX_Merge(src proto.Message) { - xxx_messageInfo_Counter.Merge(m, src) +func (x *Counter) Reset() { + *x = Counter{} + if protoimpl.UnsafeEnabled { + mi := &file_io_prometheus_client_metrics_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *Counter) XXX_Size() int { - return xxx_messageInfo_Counter.Size(m) + +func (x *Counter) String() string { + return protoimpl.X.MessageStringOf(x) } -func (m *Counter) XXX_DiscardUnknown() { - xxx_messageInfo_Counter.DiscardUnknown(m) + +func (*Counter) ProtoMessage() {} + +func (x *Counter) ProtoReflect() protoreflect.Message { + mi := &file_io_prometheus_client_metrics_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -var xxx_messageInfo_Counter proto.InternalMessageInfo +// Deprecated: Use Counter.ProtoReflect.Descriptor instead. +func (*Counter) Descriptor() ([]byte, []int) { + return file_io_prometheus_client_metrics_proto_rawDescGZIP(), []int{2} +} -func (m *Counter) GetValue() float64 { - if m != nil && m.Value != nil { - return *m.Value +func (x *Counter) GetValue() float64 { + if x != nil && x.Value != nil { + return *x.Value } return 0 } -func (m *Counter) GetExemplar() *Exemplar { - if m != nil { - return m.Exemplar +func (x *Counter) GetExemplar() *Exemplar { + if x != nil { + return x.Exemplar } return nil } type Quantile struct { - Quantile *float64 `protobuf:"fixed64,1,opt,name=quantile" json:"quantile,omitempty"` - Value *float64 `protobuf:"fixed64,2,opt,name=value" json:"value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields -func (m *Quantile) Reset() { *m = Quantile{} } -func (m *Quantile) String() string { return proto.CompactTextString(m) } -func (*Quantile) ProtoMessage() {} -func (*Quantile) Descriptor() ([]byte, []int) { - return fileDescriptor_d1e5ddb18987a258, []int{3} + Quantile *float64 `protobuf:"fixed64,1,opt,name=quantile" json:"quantile,omitempty"` + Value *float64 `protobuf:"fixed64,2,opt,name=value" json:"value,omitempty"` } -func (m *Quantile) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Quantile.Unmarshal(m, b) -} -func (m *Quantile) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Quantile.Marshal(b, m, deterministic) -} -func (m *Quantile) XXX_Merge(src proto.Message) { - xxx_messageInfo_Quantile.Merge(m, src) +func (x *Quantile) Reset() { + *x = Quantile{} + if protoimpl.UnsafeEnabled { + mi := &file_io_prometheus_client_metrics_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *Quantile) XXX_Size() int { - return xxx_messageInfo_Quantile.Size(m) + +func (x *Quantile) String() string { + return protoimpl.X.MessageStringOf(x) } -func (m *Quantile) XXX_DiscardUnknown() { - xxx_messageInfo_Quantile.DiscardUnknown(m) + +func (*Quantile) ProtoMessage() {} + +func (x *Quantile) ProtoReflect() protoreflect.Message { + mi := &file_io_prometheus_client_metrics_proto_msgTypes[3] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -var xxx_messageInfo_Quantile proto.InternalMessageInfo +// Deprecated: Use Quantile.ProtoReflect.Descriptor instead. +func (*Quantile) Descriptor() ([]byte, []int) { + return file_io_prometheus_client_metrics_proto_rawDescGZIP(), []int{3} +} -func (m *Quantile) GetQuantile() float64 { - if m != nil && m.Quantile != nil { - return *m.Quantile +func (x *Quantile) GetQuantile() float64 { + if x != nil && x.Quantile != nil { + return *x.Quantile } return 0 } -func (m *Quantile) GetValue() float64 { - if m != nil && m.Value != nil { - return *m.Value +func (x *Quantile) GetValue() float64 { + if x != nil && x.Value != nil { + return *x.Value } return 0 } type Summary struct { - SampleCount *uint64 `protobuf:"varint,1,opt,name=sample_count,json=sampleCount" json:"sample_count,omitempty"` - SampleSum *float64 `protobuf:"fixed64,2,opt,name=sample_sum,json=sampleSum" json:"sample_sum,omitempty"` - Quantile []*Quantile `protobuf:"bytes,3,rep,name=quantile" json:"quantile,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields -func (m *Summary) Reset() { *m = Summary{} } -func (m *Summary) String() string { return proto.CompactTextString(m) } -func (*Summary) ProtoMessage() {} -func (*Summary) Descriptor() ([]byte, []int) { - return fileDescriptor_d1e5ddb18987a258, []int{4} + SampleCount *uint64 `protobuf:"varint,1,opt,name=sample_count,json=sampleCount" json:"sample_count,omitempty"` + SampleSum *float64 `protobuf:"fixed64,2,opt,name=sample_sum,json=sampleSum" json:"sample_sum,omitempty"` + Quantile []*Quantile `protobuf:"bytes,3,rep,name=quantile" json:"quantile,omitempty"` } -func (m *Summary) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Summary.Unmarshal(m, b) -} -func (m *Summary) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Summary.Marshal(b, m, deterministic) -} -func (m *Summary) XXX_Merge(src proto.Message) { - xxx_messageInfo_Summary.Merge(m, src) +func (x *Summary) Reset() { + *x = Summary{} + if protoimpl.UnsafeEnabled { + mi := &file_io_prometheus_client_metrics_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *Summary) XXX_Size() int { - return xxx_messageInfo_Summary.Size(m) + +func (x *Summary) String() string { + return protoimpl.X.MessageStringOf(x) } -func (m *Summary) XXX_DiscardUnknown() { - xxx_messageInfo_Summary.DiscardUnknown(m) + +func (*Summary) ProtoMessage() {} + +func (x *Summary) ProtoReflect() protoreflect.Message { + mi := &file_io_prometheus_client_metrics_proto_msgTypes[4] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -var xxx_messageInfo_Summary proto.InternalMessageInfo +// Deprecated: Use Summary.ProtoReflect.Descriptor instead. +func (*Summary) Descriptor() ([]byte, []int) { + return file_io_prometheus_client_metrics_proto_rawDescGZIP(), []int{4} +} -func (m *Summary) GetSampleCount() uint64 { - if m != nil && m.SampleCount != nil { - return *m.SampleCount +func (x *Summary) GetSampleCount() uint64 { + if x != nil && x.SampleCount != nil { + return *x.SampleCount } return 0 } -func (m *Summary) GetSampleSum() float64 { - if m != nil && m.SampleSum != nil { - return *m.SampleSum +func (x *Summary) GetSampleSum() float64 { + if x != nil && x.SampleSum != nil { + return *x.SampleSum } return 0 } -func (m *Summary) GetQuantile() []*Quantile { - if m != nil { - return m.Quantile +func (x *Summary) GetQuantile() []*Quantile { + if x != nil { + return x.Quantile } return nil } type Untyped struct { - Value *float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields -func (m *Untyped) Reset() { *m = Untyped{} } -func (m *Untyped) String() string { return proto.CompactTextString(m) } -func (*Untyped) ProtoMessage() {} -func (*Untyped) Descriptor() ([]byte, []int) { - return fileDescriptor_d1e5ddb18987a258, []int{5} + Value *float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"` } -func (m *Untyped) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Untyped.Unmarshal(m, b) -} -func (m *Untyped) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Untyped.Marshal(b, m, deterministic) -} -func (m *Untyped) XXX_Merge(src proto.Message) { - xxx_messageInfo_Untyped.Merge(m, src) +func (x *Untyped) Reset() { + *x = Untyped{} + if protoimpl.UnsafeEnabled { + mi := &file_io_prometheus_client_metrics_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *Untyped) XXX_Size() int { - return xxx_messageInfo_Untyped.Size(m) + +func (x *Untyped) String() string { + return protoimpl.X.MessageStringOf(x) } -func (m *Untyped) XXX_DiscardUnknown() { - xxx_messageInfo_Untyped.DiscardUnknown(m) + +func (*Untyped) ProtoMessage() {} + +func (x *Untyped) ProtoReflect() protoreflect.Message { + mi := &file_io_prometheus_client_metrics_proto_msgTypes[5] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -var xxx_messageInfo_Untyped proto.InternalMessageInfo +// Deprecated: Use Untyped.ProtoReflect.Descriptor instead. +func (*Untyped) Descriptor() ([]byte, []int) { + return file_io_prometheus_client_metrics_proto_rawDescGZIP(), []int{5} +} -func (m *Untyped) GetValue() float64 { - if m != nil && m.Value != nil { - return *m.Value +func (x *Untyped) GetValue() float64 { + if x != nil && x.Value != nil { + return *x.Value } return 0 } type Histogram struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + SampleCount *uint64 `protobuf:"varint,1,opt,name=sample_count,json=sampleCount" json:"sample_count,omitempty"` - SampleCountFloat *float64 `protobuf:"fixed64,4,opt,name=sample_count_float,json=sampleCountFloat" json:"sample_count_float,omitempty"` + SampleCountFloat *float64 `protobuf:"fixed64,4,opt,name=sample_count_float,json=sampleCountFloat" json:"sample_count_float,omitempty"` // Overrides sample_count if > 0. SampleSum *float64 `protobuf:"fixed64,2,opt,name=sample_sum,json=sampleSum" json:"sample_sum,omitempty"` // Buckets for the conventional histogram. - Bucket []*Bucket `protobuf:"bytes,3,rep,name=bucket" json:"bucket,omitempty"` + Bucket []*Bucket `protobuf:"bytes,3,rep,name=bucket" json:"bucket,omitempty"` // Ordered in increasing order of upper_bound, +Inf bucket is optional. // schema defines the bucket schema. Currently, valid numbers are -4 <= n <= 8. // They are all for base-2 bucket schemas, where 1 is a bucket boundary in each case, and // then each power of two is divided into 2^n logarithmic buckets. // Or in other words, each bucket boundary is the previous boundary times 2^(2^-n). // In the future, more bucket schemas may be added using numbers < -4 or > 8. Schema *int32 `protobuf:"zigzag32,5,opt,name=schema" json:"schema,omitempty"` - ZeroThreshold *float64 `protobuf:"fixed64,6,opt,name=zero_threshold,json=zeroThreshold" json:"zero_threshold,omitempty"` - ZeroCount *uint64 `protobuf:"varint,7,opt,name=zero_count,json=zeroCount" json:"zero_count,omitempty"` - ZeroCountFloat *float64 `protobuf:"fixed64,8,opt,name=zero_count_float,json=zeroCountFloat" json:"zero_count_float,omitempty"` + ZeroThreshold *float64 `protobuf:"fixed64,6,opt,name=zero_threshold,json=zeroThreshold" json:"zero_threshold,omitempty"` // Breadth of the zero bucket. + ZeroCount *uint64 `protobuf:"varint,7,opt,name=zero_count,json=zeroCount" json:"zero_count,omitempty"` // Count in zero bucket. + ZeroCountFloat *float64 `protobuf:"fixed64,8,opt,name=zero_count_float,json=zeroCountFloat" json:"zero_count_float,omitempty"` // Overrides sb_zero_count if > 0. // Negative buckets for the native histogram. NegativeSpan []*BucketSpan `protobuf:"bytes,9,rep,name=negative_span,json=negativeSpan" json:"negative_span,omitempty"` // Use either "negative_delta" or "negative_count", the former for // regular histograms with integer counts, the latter for float // histograms. - NegativeDelta []int64 `protobuf:"zigzag64,10,rep,name=negative_delta,json=negativeDelta" json:"negative_delta,omitempty"` - NegativeCount []float64 `protobuf:"fixed64,11,rep,name=negative_count,json=negativeCount" json:"negative_count,omitempty"` + NegativeDelta []int64 `protobuf:"zigzag64,10,rep,name=negative_delta,json=negativeDelta" json:"negative_delta,omitempty"` // Count delta of each bucket compared to previous one (or to zero for 1st bucket). + NegativeCount []float64 `protobuf:"fixed64,11,rep,name=negative_count,json=negativeCount" json:"negative_count,omitempty"` // Absolute count of each bucket. // Positive buckets for the native histogram. PositiveSpan []*BucketSpan `protobuf:"bytes,12,rep,name=positive_span,json=positiveSpan" json:"positive_span,omitempty"` // Use either "positive_delta" or "positive_count", the former for // regular histograms with integer counts, the latter for float // histograms. - PositiveDelta []int64 `protobuf:"zigzag64,13,rep,name=positive_delta,json=positiveDelta" json:"positive_delta,omitempty"` - PositiveCount []float64 `protobuf:"fixed64,14,rep,name=positive_count,json=positiveCount" json:"positive_count,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + PositiveDelta []int64 `protobuf:"zigzag64,13,rep,name=positive_delta,json=positiveDelta" json:"positive_delta,omitempty"` // Count delta of each bucket compared to previous one (or to zero for 1st bucket). + PositiveCount []float64 `protobuf:"fixed64,14,rep,name=positive_count,json=positiveCount" json:"positive_count,omitempty"` // Absolute count of each bucket. } -func (m *Histogram) Reset() { *m = Histogram{} } -func (m *Histogram) String() string { return proto.CompactTextString(m) } -func (*Histogram) ProtoMessage() {} -func (*Histogram) Descriptor() ([]byte, []int) { - return fileDescriptor_d1e5ddb18987a258, []int{6} +func (x *Histogram) Reset() { + *x = Histogram{} + if protoimpl.UnsafeEnabled { + mi := &file_io_prometheus_client_metrics_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *Histogram) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Histogram.Unmarshal(m, b) +func (x *Histogram) String() string { + return protoimpl.X.MessageStringOf(x) } -func (m *Histogram) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Histogram.Marshal(b, m, deterministic) -} -func (m *Histogram) XXX_Merge(src proto.Message) { - xxx_messageInfo_Histogram.Merge(m, src) -} -func (m *Histogram) XXX_Size() int { - return xxx_messageInfo_Histogram.Size(m) -} -func (m *Histogram) XXX_DiscardUnknown() { - xxx_messageInfo_Histogram.DiscardUnknown(m) + +func (*Histogram) ProtoMessage() {} + +func (x *Histogram) ProtoReflect() protoreflect.Message { + mi := &file_io_prometheus_client_metrics_proto_msgTypes[6] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -var xxx_messageInfo_Histogram proto.InternalMessageInfo +// Deprecated: Use Histogram.ProtoReflect.Descriptor instead. +func (*Histogram) Descriptor() ([]byte, []int) { + return file_io_prometheus_client_metrics_proto_rawDescGZIP(), []int{6} +} -func (m *Histogram) GetSampleCount() uint64 { - if m != nil && m.SampleCount != nil { - return *m.SampleCount +func (x *Histogram) GetSampleCount() uint64 { + if x != nil && x.SampleCount != nil { + return *x.SampleCount } return 0 } -func (m *Histogram) GetSampleCountFloat() float64 { - if m != nil && m.SampleCountFloat != nil { - return *m.SampleCountFloat +func (x *Histogram) GetSampleCountFloat() float64 { + if x != nil && x.SampleCountFloat != nil { + return *x.SampleCountFloat } return 0 } -func (m *Histogram) GetSampleSum() float64 { - if m != nil && m.SampleSum != nil { - return *m.SampleSum +func (x *Histogram) GetSampleSum() float64 { + if x != nil && x.SampleSum != nil { + return *x.SampleSum } return 0 } -func (m *Histogram) GetBucket() []*Bucket { - if m != nil { - return m.Bucket +func (x *Histogram) GetBucket() []*Bucket { + if x != nil { + return x.Bucket } return nil } -func (m *Histogram) GetSchema() int32 { - if m != nil && m.Schema != nil { - return *m.Schema +func (x *Histogram) GetSchema() int32 { + if x != nil && x.Schema != nil { + return *x.Schema } return 0 } -func (m *Histogram) GetZeroThreshold() float64 { - if m != nil && m.ZeroThreshold != nil { - return *m.ZeroThreshold +func (x *Histogram) GetZeroThreshold() float64 { + if x != nil && x.ZeroThreshold != nil { + return *x.ZeroThreshold } return 0 } -func (m *Histogram) GetZeroCount() uint64 { - if m != nil && m.ZeroCount != nil { - return *m.ZeroCount +func (x *Histogram) GetZeroCount() uint64 { + if x != nil && x.ZeroCount != nil { + return *x.ZeroCount } return 0 } -func (m *Histogram) GetZeroCountFloat() float64 { - if m != nil && m.ZeroCountFloat != nil { - return *m.ZeroCountFloat +func (x *Histogram) GetZeroCountFloat() float64 { + if x != nil && x.ZeroCountFloat != nil { + return *x.ZeroCountFloat } return 0 } -func (m *Histogram) GetNegativeSpan() []*BucketSpan { - if m != nil { - return m.NegativeSpan +func (x *Histogram) GetNegativeSpan() []*BucketSpan { + if x != nil { + return x.NegativeSpan } return nil } -func (m *Histogram) GetNegativeDelta() []int64 { - if m != nil { - return m.NegativeDelta +func (x *Histogram) GetNegativeDelta() []int64 { + if x != nil { + return x.NegativeDelta } return nil } -func (m *Histogram) GetNegativeCount() []float64 { - if m != nil { - return m.NegativeCount +func (x *Histogram) GetNegativeCount() []float64 { + if x != nil { + return x.NegativeCount } return nil } -func (m *Histogram) GetPositiveSpan() []*BucketSpan { - if m != nil { - return m.PositiveSpan +func (x *Histogram) GetPositiveSpan() []*BucketSpan { + if x != nil { + return x.PositiveSpan } return nil } -func (m *Histogram) GetPositiveDelta() []int64 { - if m != nil { - return m.PositiveDelta +func (x *Histogram) GetPositiveDelta() []int64 { + if x != nil { + return x.PositiveDelta } return nil } -func (m *Histogram) GetPositiveCount() []float64 { - if m != nil { - return m.PositiveCount +func (x *Histogram) GetPositiveCount() []float64 { + if x != nil { + return x.PositiveCount } return nil } @@ -513,64 +598,72 @@ func (m *Histogram) GetPositiveCount() []float64 { // A Bucket of a conventional histogram, each of which is treated as // an individual counter-like time series by Prometheus. type Bucket struct { - CumulativeCount *uint64 `protobuf:"varint,1,opt,name=cumulative_count,json=cumulativeCount" json:"cumulative_count,omitempty"` - CumulativeCountFloat *float64 `protobuf:"fixed64,4,opt,name=cumulative_count_float,json=cumulativeCountFloat" json:"cumulative_count_float,omitempty"` - UpperBound *float64 `protobuf:"fixed64,2,opt,name=upper_bound,json=upperBound" json:"upper_bound,omitempty"` + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + CumulativeCount *uint64 `protobuf:"varint,1,opt,name=cumulative_count,json=cumulativeCount" json:"cumulative_count,omitempty"` // Cumulative in increasing order. + CumulativeCountFloat *float64 `protobuf:"fixed64,4,opt,name=cumulative_count_float,json=cumulativeCountFloat" json:"cumulative_count_float,omitempty"` // Overrides cumulative_count if > 0. + UpperBound *float64 `protobuf:"fixed64,2,opt,name=upper_bound,json=upperBound" json:"upper_bound,omitempty"` // Inclusive. Exemplar *Exemplar `protobuf:"bytes,3,opt,name=exemplar" json:"exemplar,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` } -func (m *Bucket) Reset() { *m = Bucket{} } -func (m *Bucket) String() string { return proto.CompactTextString(m) } -func (*Bucket) ProtoMessage() {} -func (*Bucket) Descriptor() ([]byte, []int) { - return fileDescriptor_d1e5ddb18987a258, []int{7} +func (x *Bucket) Reset() { + *x = Bucket{} + if protoimpl.UnsafeEnabled { + mi := &file_io_prometheus_client_metrics_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *Bucket) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Bucket.Unmarshal(m, b) -} -func (m *Bucket) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Bucket.Marshal(b, m, deterministic) -} -func (m *Bucket) XXX_Merge(src proto.Message) { - xxx_messageInfo_Bucket.Merge(m, src) -} -func (m *Bucket) XXX_Size() int { - return xxx_messageInfo_Bucket.Size(m) +func (x *Bucket) String() string { + return protoimpl.X.MessageStringOf(x) } -func (m *Bucket) XXX_DiscardUnknown() { - xxx_messageInfo_Bucket.DiscardUnknown(m) + +func (*Bucket) ProtoMessage() {} + +func (x *Bucket) ProtoReflect() protoreflect.Message { + mi := &file_io_prometheus_client_metrics_proto_msgTypes[7] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -var xxx_messageInfo_Bucket proto.InternalMessageInfo +// Deprecated: Use Bucket.ProtoReflect.Descriptor instead. +func (*Bucket) Descriptor() ([]byte, []int) { + return file_io_prometheus_client_metrics_proto_rawDescGZIP(), []int{7} +} -func (m *Bucket) GetCumulativeCount() uint64 { - if m != nil && m.CumulativeCount != nil { - return *m.CumulativeCount +func (x *Bucket) GetCumulativeCount() uint64 { + if x != nil && x.CumulativeCount != nil { + return *x.CumulativeCount } return 0 } -func (m *Bucket) GetCumulativeCountFloat() float64 { - if m != nil && m.CumulativeCountFloat != nil { - return *m.CumulativeCountFloat +func (x *Bucket) GetCumulativeCountFloat() float64 { + if x != nil && x.CumulativeCountFloat != nil { + return *x.CumulativeCountFloat } return 0 } -func (m *Bucket) GetUpperBound() float64 { - if m != nil && m.UpperBound != nil { - return *m.UpperBound +func (x *Bucket) GetUpperBound() float64 { + if x != nil && x.UpperBound != nil { + return *x.UpperBound } return 0 } -func (m *Bucket) GetExemplar() *Exemplar { - if m != nil { - return m.Exemplar +func (x *Bucket) GetExemplar() *Exemplar { + if x != nil { + return x.Exemplar } return nil } @@ -582,333 +675,658 @@ func (m *Bucket) GetExemplar() *Exemplar { // structured here (with all the buckets in a single array separate // from the Spans). type BucketSpan struct { - Offset *int32 `protobuf:"zigzag32,1,opt,name=offset" json:"offset,omitempty"` - Length *uint32 `protobuf:"varint,2,opt,name=length" json:"length,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields -func (m *BucketSpan) Reset() { *m = BucketSpan{} } -func (m *BucketSpan) String() string { return proto.CompactTextString(m) } -func (*BucketSpan) ProtoMessage() {} -func (*BucketSpan) Descriptor() ([]byte, []int) { - return fileDescriptor_d1e5ddb18987a258, []int{8} + Offset *int32 `protobuf:"zigzag32,1,opt,name=offset" json:"offset,omitempty"` // Gap to previous span, or starting point for 1st span (which can be negative). + Length *uint32 `protobuf:"varint,2,opt,name=length" json:"length,omitempty"` // Length of consecutive buckets. } -func (m *BucketSpan) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_BucketSpan.Unmarshal(m, b) -} -func (m *BucketSpan) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_BucketSpan.Marshal(b, m, deterministic) -} -func (m *BucketSpan) XXX_Merge(src proto.Message) { - xxx_messageInfo_BucketSpan.Merge(m, src) +func (x *BucketSpan) Reset() { + *x = BucketSpan{} + if protoimpl.UnsafeEnabled { + mi := &file_io_prometheus_client_metrics_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *BucketSpan) XXX_Size() int { - return xxx_messageInfo_BucketSpan.Size(m) + +func (x *BucketSpan) String() string { + return protoimpl.X.MessageStringOf(x) } -func (m *BucketSpan) XXX_DiscardUnknown() { - xxx_messageInfo_BucketSpan.DiscardUnknown(m) + +func (*BucketSpan) ProtoMessage() {} + +func (x *BucketSpan) ProtoReflect() protoreflect.Message { + mi := &file_io_prometheus_client_metrics_proto_msgTypes[8] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -var xxx_messageInfo_BucketSpan proto.InternalMessageInfo +// Deprecated: Use BucketSpan.ProtoReflect.Descriptor instead. +func (*BucketSpan) Descriptor() ([]byte, []int) { + return file_io_prometheus_client_metrics_proto_rawDescGZIP(), []int{8} +} -func (m *BucketSpan) GetOffset() int32 { - if m != nil && m.Offset != nil { - return *m.Offset +func (x *BucketSpan) GetOffset() int32 { + if x != nil && x.Offset != nil { + return *x.Offset } return 0 } -func (m *BucketSpan) GetLength() uint32 { - if m != nil && m.Length != nil { - return *m.Length +func (x *BucketSpan) GetLength() uint32 { + if x != nil && x.Length != nil { + return *x.Length } return 0 } type Exemplar struct { - Label []*LabelPair `protobuf:"bytes,1,rep,name=label" json:"label,omitempty"` - Value *float64 `protobuf:"fixed64,2,opt,name=value" json:"value,omitempty"` - Timestamp *timestamp.Timestamp `protobuf:"bytes,3,opt,name=timestamp" json:"timestamp,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields -func (m *Exemplar) Reset() { *m = Exemplar{} } -func (m *Exemplar) String() string { return proto.CompactTextString(m) } -func (*Exemplar) ProtoMessage() {} -func (*Exemplar) Descriptor() ([]byte, []int) { - return fileDescriptor_d1e5ddb18987a258, []int{9} + Label []*LabelPair `protobuf:"bytes,1,rep,name=label" json:"label,omitempty"` + Value *float64 `protobuf:"fixed64,2,opt,name=value" json:"value,omitempty"` + Timestamp *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=timestamp" json:"timestamp,omitempty"` // OpenMetrics-style. } -func (m *Exemplar) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Exemplar.Unmarshal(m, b) -} -func (m *Exemplar) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Exemplar.Marshal(b, m, deterministic) -} -func (m *Exemplar) XXX_Merge(src proto.Message) { - xxx_messageInfo_Exemplar.Merge(m, src) +func (x *Exemplar) Reset() { + *x = Exemplar{} + if protoimpl.UnsafeEnabled { + mi := &file_io_prometheus_client_metrics_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *Exemplar) XXX_Size() int { - return xxx_messageInfo_Exemplar.Size(m) + +func (x *Exemplar) String() string { + return protoimpl.X.MessageStringOf(x) } -func (m *Exemplar) XXX_DiscardUnknown() { - xxx_messageInfo_Exemplar.DiscardUnknown(m) + +func (*Exemplar) ProtoMessage() {} + +func (x *Exemplar) ProtoReflect() protoreflect.Message { + mi := &file_io_prometheus_client_metrics_proto_msgTypes[9] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -var xxx_messageInfo_Exemplar proto.InternalMessageInfo +// Deprecated: Use Exemplar.ProtoReflect.Descriptor instead. +func (*Exemplar) Descriptor() ([]byte, []int) { + return file_io_prometheus_client_metrics_proto_rawDescGZIP(), []int{9} +} -func (m *Exemplar) GetLabel() []*LabelPair { - if m != nil { - return m.Label +func (x *Exemplar) GetLabel() []*LabelPair { + if x != nil { + return x.Label } return nil } -func (m *Exemplar) GetValue() float64 { - if m != nil && m.Value != nil { - return *m.Value +func (x *Exemplar) GetValue() float64 { + if x != nil && x.Value != nil { + return *x.Value } return 0 } -func (m *Exemplar) GetTimestamp() *timestamp.Timestamp { - if m != nil { - return m.Timestamp +func (x *Exemplar) GetTimestamp() *timestamppb.Timestamp { + if x != nil { + return x.Timestamp } return nil } type Metric struct { - Label []*LabelPair `protobuf:"bytes,1,rep,name=label" json:"label,omitempty"` - Gauge *Gauge `protobuf:"bytes,2,opt,name=gauge" json:"gauge,omitempty"` - Counter *Counter `protobuf:"bytes,3,opt,name=counter" json:"counter,omitempty"` - Summary *Summary `protobuf:"bytes,4,opt,name=summary" json:"summary,omitempty"` - Untyped *Untyped `protobuf:"bytes,5,opt,name=untyped" json:"untyped,omitempty"` - Histogram *Histogram `protobuf:"bytes,7,opt,name=histogram" json:"histogram,omitempty"` - TimestampMs *int64 `protobuf:"varint,6,opt,name=timestamp_ms,json=timestampMs" json:"timestamp_ms,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Metric) Reset() { *m = Metric{} } -func (m *Metric) String() string { return proto.CompactTextString(m) } -func (*Metric) ProtoMessage() {} -func (*Metric) Descriptor() ([]byte, []int) { - return fileDescriptor_d1e5ddb18987a258, []int{10} + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Label []*LabelPair `protobuf:"bytes,1,rep,name=label" json:"label,omitempty"` + Gauge *Gauge `protobuf:"bytes,2,opt,name=gauge" json:"gauge,omitempty"` + Counter *Counter `protobuf:"bytes,3,opt,name=counter" json:"counter,omitempty"` + Summary *Summary `protobuf:"bytes,4,opt,name=summary" json:"summary,omitempty"` + Untyped *Untyped `protobuf:"bytes,5,opt,name=untyped" json:"untyped,omitempty"` + Histogram *Histogram `protobuf:"bytes,7,opt,name=histogram" json:"histogram,omitempty"` + TimestampMs *int64 `protobuf:"varint,6,opt,name=timestamp_ms,json=timestampMs" json:"timestamp_ms,omitempty"` +} + +func (x *Metric) Reset() { + *x = Metric{} + if protoimpl.UnsafeEnabled { + mi := &file_io_prometheus_client_metrics_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *Metric) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Metric.Unmarshal(m, b) +func (x *Metric) String() string { + return protoimpl.X.MessageStringOf(x) } -func (m *Metric) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Metric.Marshal(b, m, deterministic) -} -func (m *Metric) XXX_Merge(src proto.Message) { - xxx_messageInfo_Metric.Merge(m, src) -} -func (m *Metric) XXX_Size() int { - return xxx_messageInfo_Metric.Size(m) -} -func (m *Metric) XXX_DiscardUnknown() { - xxx_messageInfo_Metric.DiscardUnknown(m) + +func (*Metric) ProtoMessage() {} + +func (x *Metric) ProtoReflect() protoreflect.Message { + mi := &file_io_prometheus_client_metrics_proto_msgTypes[10] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -var xxx_messageInfo_Metric proto.InternalMessageInfo +// Deprecated: Use Metric.ProtoReflect.Descriptor instead. +func (*Metric) Descriptor() ([]byte, []int) { + return file_io_prometheus_client_metrics_proto_rawDescGZIP(), []int{10} +} -func (m *Metric) GetLabel() []*LabelPair { - if m != nil { - return m.Label +func (x *Metric) GetLabel() []*LabelPair { + if x != nil { + return x.Label } return nil } -func (m *Metric) GetGauge() *Gauge { - if m != nil { - return m.Gauge +func (x *Metric) GetGauge() *Gauge { + if x != nil { + return x.Gauge } return nil } -func (m *Metric) GetCounter() *Counter { - if m != nil { - return m.Counter +func (x *Metric) GetCounter() *Counter { + if x != nil { + return x.Counter } return nil } -func (m *Metric) GetSummary() *Summary { - if m != nil { - return m.Summary +func (x *Metric) GetSummary() *Summary { + if x != nil { + return x.Summary } return nil } -func (m *Metric) GetUntyped() *Untyped { - if m != nil { - return m.Untyped +func (x *Metric) GetUntyped() *Untyped { + if x != nil { + return x.Untyped } return nil } -func (m *Metric) GetHistogram() *Histogram { - if m != nil { - return m.Histogram +func (x *Metric) GetHistogram() *Histogram { + if x != nil { + return x.Histogram } return nil } -func (m *Metric) GetTimestampMs() int64 { - if m != nil && m.TimestampMs != nil { - return *m.TimestampMs +func (x *Metric) GetTimestampMs() int64 { + if x != nil && x.TimestampMs != nil { + return *x.TimestampMs } return 0 } type MetricFamily struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Help *string `protobuf:"bytes,2,opt,name=help" json:"help,omitempty"` - Type *MetricType `protobuf:"varint,3,opt,name=type,enum=io.prometheus.client.MetricType" json:"type,omitempty"` - Metric []*Metric `protobuf:"bytes,4,rep,name=metric" json:"metric,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MetricFamily) Reset() { *m = MetricFamily{} } -func (m *MetricFamily) String() string { return proto.CompactTextString(m) } -func (*MetricFamily) ProtoMessage() {} -func (*MetricFamily) Descriptor() ([]byte, []int) { - return fileDescriptor_d1e5ddb18987a258, []int{11} + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + Help *string `protobuf:"bytes,2,opt,name=help" json:"help,omitempty"` + Type *MetricType `protobuf:"varint,3,opt,name=type,enum=io.prometheus.client.MetricType" json:"type,omitempty"` + Metric []*Metric `protobuf:"bytes,4,rep,name=metric" json:"metric,omitempty"` +} + +func (x *MetricFamily) Reset() { + *x = MetricFamily{} + if protoimpl.UnsafeEnabled { + mi := &file_io_prometheus_client_metrics_proto_msgTypes[11] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *MetricFamily) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MetricFamily.Unmarshal(m, b) -} -func (m *MetricFamily) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MetricFamily.Marshal(b, m, deterministic) -} -func (m *MetricFamily) XXX_Merge(src proto.Message) { - xxx_messageInfo_MetricFamily.Merge(m, src) -} -func (m *MetricFamily) XXX_Size() int { - return xxx_messageInfo_MetricFamily.Size(m) +func (x *MetricFamily) String() string { + return protoimpl.X.MessageStringOf(x) } -func (m *MetricFamily) XXX_DiscardUnknown() { - xxx_messageInfo_MetricFamily.DiscardUnknown(m) + +func (*MetricFamily) ProtoMessage() {} + +func (x *MetricFamily) ProtoReflect() protoreflect.Message { + mi := &file_io_prometheus_client_metrics_proto_msgTypes[11] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -var xxx_messageInfo_MetricFamily proto.InternalMessageInfo +// Deprecated: Use MetricFamily.ProtoReflect.Descriptor instead. +func (*MetricFamily) Descriptor() ([]byte, []int) { + return file_io_prometheus_client_metrics_proto_rawDescGZIP(), []int{11} +} -func (m *MetricFamily) GetName() string { - if m != nil && m.Name != nil { - return *m.Name +func (x *MetricFamily) GetName() string { + if x != nil && x.Name != nil { + return *x.Name } return "" } -func (m *MetricFamily) GetHelp() string { - if m != nil && m.Help != nil { - return *m.Help +func (x *MetricFamily) GetHelp() string { + if x != nil && x.Help != nil { + return *x.Help } return "" } -func (m *MetricFamily) GetType() MetricType { - if m != nil && m.Type != nil { - return *m.Type +func (x *MetricFamily) GetType() MetricType { + if x != nil && x.Type != nil { + return *x.Type } return MetricType_COUNTER } -func (m *MetricFamily) GetMetric() []*Metric { - if m != nil { - return m.Metric +func (x *MetricFamily) GetMetric() []*Metric { + if x != nil { + return x.Metric } return nil } -func init() { - proto.RegisterEnum("io.prometheus.client.MetricType", MetricType_name, MetricType_value) - proto.RegisterType((*LabelPair)(nil), "io.prometheus.client.LabelPair") - proto.RegisterType((*Gauge)(nil), "io.prometheus.client.Gauge") - proto.RegisterType((*Counter)(nil), "io.prometheus.client.Counter") - proto.RegisterType((*Quantile)(nil), "io.prometheus.client.Quantile") - proto.RegisterType((*Summary)(nil), "io.prometheus.client.Summary") - proto.RegisterType((*Untyped)(nil), "io.prometheus.client.Untyped") - proto.RegisterType((*Histogram)(nil), "io.prometheus.client.Histogram") - proto.RegisterType((*Bucket)(nil), "io.prometheus.client.Bucket") - proto.RegisterType((*BucketSpan)(nil), "io.prometheus.client.BucketSpan") - proto.RegisterType((*Exemplar)(nil), "io.prometheus.client.Exemplar") - proto.RegisterType((*Metric)(nil), "io.prometheus.client.Metric") - proto.RegisterType((*MetricFamily)(nil), "io.prometheus.client.MetricFamily") -} - -func init() { - proto.RegisterFile("io/prometheus/client/metrics.proto", fileDescriptor_d1e5ddb18987a258) -} - -var fileDescriptor_d1e5ddb18987a258 = []byte{ - // 896 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x56, 0xdd, 0x8e, 0xdb, 0x44, - 0x18, 0xc5, 0x9b, 0x5f, 0x7f, 0xd9, 0x6c, 0xd3, 0x61, 0x55, 0x59, 0x0b, 0xcb, 0x06, 0x4b, 0x48, - 0x0b, 0x42, 0x8e, 0x40, 0x5b, 0x81, 0x0a, 0x5c, 0xec, 0xb6, 0xe9, 0x16, 0x89, 0xb4, 0x65, 0x92, - 0x5c, 0x14, 0x2e, 0xac, 0x49, 0x32, 0xeb, 0x58, 0x78, 0x3c, 0xc6, 0x1e, 0x57, 0x2c, 0x2f, 0xc0, - 0x35, 0xaf, 0xc0, 0xc3, 0xf0, 0x22, 0x3c, 0x08, 0x68, 0xfe, 0xec, 0xdd, 0xe2, 0x94, 0xd2, 0x3b, - 0x7f, 0x67, 0xce, 0xf7, 0xcd, 0x39, 0xe3, 0xc9, 0x71, 0xc0, 0x8f, 0xf9, 0x24, 0xcb, 0x39, 0xa3, - 0x62, 0x4b, 0xcb, 0x62, 0xb2, 0x4e, 0x62, 0x9a, 0x8a, 0x09, 0xa3, 0x22, 0x8f, 0xd7, 0x45, 0x90, - 0xe5, 0x5c, 0x70, 0x74, 0x18, 0xf3, 0xa0, 0xe6, 0x04, 0x9a, 0x73, 0x74, 0x12, 0x71, 0x1e, 0x25, - 0x74, 0xa2, 0x38, 0xab, 0xf2, 0x6a, 0x22, 0x62, 0x46, 0x0b, 0x41, 0x58, 0xa6, 0xdb, 0xfc, 0xfb, - 0xe0, 0x7e, 0x47, 0x56, 0x34, 0x79, 0x4e, 0xe2, 0x1c, 0x21, 0x68, 0xa7, 0x84, 0x51, 0xcf, 0x19, - 0x3b, 0xa7, 0x2e, 0x56, 0xcf, 0xe8, 0x10, 0x3a, 0x2f, 0x49, 0x52, 0x52, 0x6f, 0x4f, 0x81, 0xba, - 0xf0, 0x8f, 0xa1, 0x73, 0x49, 0xca, 0xe8, 0xc6, 0xb2, 0xec, 0x71, 0xec, 0xf2, 0x8f, 0xd0, 0x7b, - 0xc8, 0xcb, 0x54, 0xd0, 0xbc, 0x99, 0x80, 0x1e, 0x40, 0x9f, 0xfe, 0x42, 0x59, 0x96, 0x90, 0x5c, - 0x0d, 0x1e, 0x7c, 0xfe, 0x41, 0xd0, 0x64, 0x20, 0x98, 0x1a, 0x16, 0xae, 0xf8, 0xfe, 0xd7, 0xd0, - 0xff, 0xbe, 0x24, 0xa9, 0x88, 0x13, 0x8a, 0x8e, 0xa0, 0xff, 0xb3, 0x79, 0x36, 0x1b, 0x54, 0xf5, - 0x6d, 0xe5, 0x95, 0xb4, 0xdf, 0x1c, 0xe8, 0xcd, 0x4b, 0xc6, 0x48, 0x7e, 0x8d, 0x3e, 0x84, 0xfd, - 0x82, 0xb0, 0x2c, 0xa1, 0xe1, 0x5a, 0xaa, 0x55, 0x13, 0xda, 0x78, 0xa0, 0x31, 0x65, 0x00, 0x1d, - 0x03, 0x18, 0x4a, 0x51, 0x32, 0x33, 0xc9, 0xd5, 0xc8, 0xbc, 0x64, 0xd2, 0x47, 0xb5, 0x7f, 0x6b, - 0xdc, 0xda, 0xed, 0xc3, 0x2a, 0xae, 0xf5, 0xf9, 0x27, 0xd0, 0x5b, 0xa6, 0xe2, 0x3a, 0xa3, 0x9b, - 0x1d, 0xa7, 0xf8, 0x57, 0x1b, 0xdc, 0x27, 0x71, 0x21, 0x78, 0x94, 0x13, 0xf6, 0x26, 0x62, 0x3f, - 0x05, 0x74, 0x93, 0x12, 0x5e, 0x25, 0x9c, 0x08, 0xaf, 0xad, 0x66, 0x8e, 0x6e, 0x10, 0x1f, 0x4b, - 0xfc, 0xbf, 0xac, 0x9d, 0x41, 0x77, 0x55, 0xae, 0x7f, 0xa2, 0xc2, 0x18, 0x7b, 0xbf, 0xd9, 0xd8, - 0x85, 0xe2, 0x60, 0xc3, 0x45, 0xf7, 0xa0, 0x5b, 0xac, 0xb7, 0x94, 0x11, 0xaf, 0x33, 0x76, 0x4e, - 0xef, 0x62, 0x53, 0xa1, 0x8f, 0xe0, 0xe0, 0x57, 0x9a, 0xf3, 0x50, 0x6c, 0x73, 0x5a, 0x6c, 0x79, - 0xb2, 0xf1, 0xba, 0x6a, 0xc3, 0xa1, 0x44, 0x17, 0x16, 0x94, 0x9a, 0x14, 0x4d, 0x5b, 0xec, 0x29, - 0x8b, 0xae, 0x44, 0xb4, 0xc1, 0x53, 0x18, 0xd5, 0xcb, 0xc6, 0x5e, 0x5f, 0xcd, 0x39, 0xa8, 0x48, - 0xda, 0xdc, 0x14, 0x86, 0x29, 0x8d, 0x88, 0x88, 0x5f, 0xd2, 0xb0, 0xc8, 0x48, 0xea, 0xb9, 0xca, - 0xc4, 0xf8, 0x75, 0x26, 0xe6, 0x19, 0x49, 0xf1, 0xbe, 0x6d, 0x93, 0x95, 0x94, 0x5d, 0x8d, 0xd9, - 0xd0, 0x44, 0x10, 0x0f, 0xc6, 0xad, 0x53, 0x84, 0xab, 0xe1, 0x8f, 0x24, 0x78, 0x8b, 0xa6, 0xa5, - 0x0f, 0xc6, 0x2d, 0xe9, 0xce, 0xa2, 0x5a, 0xfe, 0x14, 0x86, 0x19, 0x2f, 0xe2, 0x5a, 0xd4, 0xfe, - 0x9b, 0x8a, 0xb2, 0x6d, 0x56, 0x54, 0x35, 0x46, 0x8b, 0x1a, 0x6a, 0x51, 0x16, 0xad, 0x44, 0x55, - 0x34, 0x2d, 0xea, 0x40, 0x8b, 0xb2, 0xa8, 0x12, 0xe5, 0xff, 0xe9, 0x40, 0x57, 0x6f, 0x85, 0x3e, - 0x86, 0xd1, 0xba, 0x64, 0x65, 0x72, 0xd3, 0x88, 0xbe, 0x66, 0x77, 0x6a, 0x5c, 0x5b, 0x39, 0x83, - 0x7b, 0xaf, 0x52, 0x6f, 0x5d, 0xb7, 0xc3, 0x57, 0x1a, 0xf4, 0x5b, 0x39, 0x81, 0x41, 0x99, 0x65, - 0x34, 0x0f, 0x57, 0xbc, 0x4c, 0x37, 0xe6, 0xce, 0x81, 0x82, 0x2e, 0x24, 0x72, 0x2b, 0x17, 0x5a, - 0xff, 0x3b, 0x17, 0xa0, 0x3e, 0x32, 0x79, 0x11, 0xf9, 0xd5, 0x55, 0x41, 0xb5, 0x83, 0xbb, 0xd8, - 0x54, 0x12, 0x4f, 0x68, 0x1a, 0x89, 0xad, 0xda, 0x7d, 0x88, 0x4d, 0xe5, 0xff, 0xee, 0x40, 0xdf, - 0x0e, 0x45, 0xf7, 0xa1, 0x93, 0xc8, 0x54, 0xf4, 0x1c, 0xf5, 0x82, 0x4e, 0x9a, 0x35, 0x54, 0xc1, - 0x89, 0x35, 0xbb, 0x39, 0x71, 0xd0, 0x97, 0xe0, 0x56, 0xa9, 0x6b, 0x4c, 0x1d, 0x05, 0x3a, 0x97, - 0x03, 0x9b, 0xcb, 0xc1, 0xc2, 0x32, 0x70, 0x4d, 0xf6, 0xff, 0xde, 0x83, 0xee, 0x4c, 0xa5, 0xfc, - 0xdb, 0x2a, 0xfa, 0x0c, 0x3a, 0x91, 0xcc, 0x69, 0x13, 0xb2, 0xef, 0x35, 0xb7, 0xa9, 0x28, 0xc7, - 0x9a, 0x89, 0xbe, 0x80, 0xde, 0x5a, 0x67, 0xb7, 0x11, 0x7b, 0xdc, 0xdc, 0x64, 0x02, 0x1e, 0x5b, - 0xb6, 0x6c, 0x2c, 0x74, 0xb0, 0xaa, 0x3b, 0xb0, 0xb3, 0xd1, 0xa4, 0x2f, 0xb6, 0x6c, 0xd9, 0x58, - 0xea, 0x20, 0x54, 0xa1, 0xb1, 0xb3, 0xd1, 0xa4, 0x25, 0xb6, 0x6c, 0xf4, 0x0d, 0xb8, 0x5b, 0x9b, - 0x8f, 0x2a, 0x2c, 0x76, 0x1e, 0x4c, 0x15, 0xa3, 0xb8, 0xee, 0x90, 0x89, 0x5a, 0x9d, 0x75, 0xc8, - 0x0a, 0x95, 0x48, 0x2d, 0x3c, 0xa8, 0xb0, 0x59, 0xe1, 0xff, 0xe1, 0xc0, 0xbe, 0x7e, 0x03, 0x8f, - 0x09, 0x8b, 0x93, 0xeb, 0xc6, 0x4f, 0x24, 0x82, 0xf6, 0x96, 0x26, 0x99, 0xf9, 0x42, 0xaa, 0x67, - 0x74, 0x06, 0x6d, 0xa9, 0x51, 0x1d, 0xe1, 0xc1, 0xae, 0x5f, 0xb8, 0x9e, 0xbc, 0xb8, 0xce, 0x28, - 0x56, 0x6c, 0x99, 0xb9, 0xfa, 0xab, 0xee, 0xb5, 0x5f, 0x97, 0xb9, 0xba, 0x0f, 0x1b, 0xee, 0x27, - 0x2b, 0x80, 0x7a, 0x12, 0x1a, 0x40, 0xef, 0xe1, 0xb3, 0xe5, 0xd3, 0xc5, 0x14, 0x8f, 0xde, 0x41, - 0x2e, 0x74, 0x2e, 0xcf, 0x97, 0x97, 0xd3, 0x91, 0x23, 0xf1, 0xf9, 0x72, 0x36, 0x3b, 0xc7, 0x2f, - 0x46, 0x7b, 0xb2, 0x58, 0x3e, 0x5d, 0xbc, 0x78, 0x3e, 0x7d, 0x34, 0x6a, 0xa1, 0x21, 0xb8, 0x4f, - 0xbe, 0x9d, 0x2f, 0x9e, 0x5d, 0xe2, 0xf3, 0xd9, 0xa8, 0x8d, 0xde, 0x85, 0x3b, 0xaa, 0x27, 0xac, - 0xc1, 0xce, 0x05, 0x86, 0xc6, 0x3f, 0x18, 0x3f, 0x3c, 0x88, 0x62, 0xb1, 0x2d, 0x57, 0xc1, 0x9a, - 0xb3, 0x7f, 0xff, 0x45, 0x09, 0x19, 0xdf, 0xd0, 0x64, 0x12, 0xf1, 0xaf, 0x62, 0x1e, 0xd6, 0xab, - 0xa1, 0x5e, 0xfd, 0x27, 0x00, 0x00, 0xff, 0xff, 0x16, 0x77, 0x81, 0x98, 0xd7, 0x08, 0x00, 0x00, +var File_io_prometheus_client_metrics_proto protoreflect.FileDescriptor + +var file_io_prometheus_client_metrics_proto_rawDesc = []byte{ + 0x0a, 0x22, 0x69, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x6d, 0x65, 0x74, 0x68, 0x65, 0x75, 0x73, 0x2f, + 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x2f, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x2e, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x14, 0x69, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x6d, 0x65, 0x74, 0x68, + 0x65, 0x75, 0x73, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x1a, 0x1f, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x74, 0x69, 0x6d, 0x65, + 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x35, 0x0a, 0x09, 0x4c, + 0x61, 0x62, 0x65, 0x6c, 0x50, 0x61, 0x69, 0x72, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x14, 0x0a, 0x05, + 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, + 0x75, 0x65, 0x22, 0x1d, 0x0a, 0x05, 0x47, 0x61, 0x75, 0x67, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x76, + 0x61, 0x6c, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x01, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, + 0x65, 0x22, 0x5b, 0x0a, 0x07, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x65, 0x72, 0x12, 0x14, 0x0a, 0x05, + 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x01, 0x52, 0x05, 0x76, 0x61, 0x6c, + 0x75, 0x65, 0x12, 0x3a, 0x0a, 0x08, 0x65, 0x78, 0x65, 0x6d, 0x70, 0x6c, 0x61, 0x72, 0x18, 0x02, + 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1e, 0x2e, 0x69, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x6d, 0x65, 0x74, + 0x68, 0x65, 0x75, 0x73, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x2e, 0x45, 0x78, 0x65, 0x6d, + 0x70, 0x6c, 0x61, 0x72, 0x52, 0x08, 0x65, 0x78, 0x65, 0x6d, 0x70, 0x6c, 0x61, 0x72, 0x22, 0x3c, + 0x0a, 0x08, 0x51, 0x75, 0x61, 0x6e, 0x74, 0x69, 0x6c, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x71, 0x75, + 0x61, 0x6e, 0x74, 0x69, 0x6c, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x01, 0x52, 0x08, 0x71, 0x75, + 0x61, 0x6e, 0x74, 0x69, 0x6c, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, + 0x02, 0x20, 0x01, 0x28, 0x01, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0x87, 0x01, 0x0a, + 0x07, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x12, 0x21, 0x0a, 0x0c, 0x73, 0x61, 0x6d, 0x70, + 0x6c, 0x65, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0b, + 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x1d, 0x0a, 0x0a, 0x73, + 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x5f, 0x73, 0x75, 0x6d, 0x18, 0x02, 0x20, 0x01, 0x28, 0x01, 0x52, + 0x09, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x53, 0x75, 0x6d, 0x12, 0x3a, 0x0a, 0x08, 0x71, 0x75, + 0x61, 0x6e, 0x74, 0x69, 0x6c, 0x65, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1e, 0x2e, 0x69, + 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x6d, 0x65, 0x74, 0x68, 0x65, 0x75, 0x73, 0x2e, 0x63, 0x6c, 0x69, + 0x65, 0x6e, 0x74, 0x2e, 0x51, 0x75, 0x61, 0x6e, 0x74, 0x69, 0x6c, 0x65, 0x52, 0x08, 0x71, 0x75, + 0x61, 0x6e, 0x74, 0x69, 0x6c, 0x65, 0x22, 0x1f, 0x0a, 0x07, 0x55, 0x6e, 0x74, 0x79, 0x70, 0x65, + 0x64, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x01, + 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0xe3, 0x04, 0x0a, 0x09, 0x48, 0x69, 0x73, 0x74, + 0x6f, 0x67, 0x72, 0x61, 0x6d, 0x12, 0x21, 0x0a, 0x0c, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x5f, + 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0b, 0x73, 0x61, 0x6d, + 0x70, 0x6c, 0x65, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x2c, 0x0a, 0x12, 0x73, 0x61, 0x6d, 0x70, + 0x6c, 0x65, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x5f, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x18, 0x04, + 0x20, 0x01, 0x28, 0x01, 0x52, 0x10, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x43, 0x6f, 0x75, 0x6e, + 0x74, 0x46, 0x6c, 0x6f, 0x61, 0x74, 0x12, 0x1d, 0x0a, 0x0a, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x65, + 0x5f, 0x73, 0x75, 0x6d, 0x18, 0x02, 0x20, 0x01, 0x28, 0x01, 0x52, 0x09, 0x73, 0x61, 0x6d, 0x70, + 0x6c, 0x65, 0x53, 0x75, 0x6d, 0x12, 0x34, 0x0a, 0x06, 0x62, 0x75, 0x63, 0x6b, 0x65, 0x74, 0x18, + 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x69, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x6d, 0x65, + 0x74, 0x68, 0x65, 0x75, 0x73, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x2e, 0x42, 0x75, 0x63, + 0x6b, 0x65, 0x74, 0x52, 0x06, 0x62, 0x75, 0x63, 0x6b, 0x65, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x73, + 0x63, 0x68, 0x65, 0x6d, 0x61, 0x18, 0x05, 0x20, 0x01, 0x28, 0x11, 0x52, 0x06, 0x73, 0x63, 0x68, + 0x65, 0x6d, 0x61, 0x12, 0x25, 0x0a, 0x0e, 0x7a, 0x65, 0x72, 0x6f, 0x5f, 0x74, 0x68, 0x72, 0x65, + 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x18, 0x06, 0x20, 0x01, 0x28, 0x01, 0x52, 0x0d, 0x7a, 0x65, 0x72, + 0x6f, 0x54, 0x68, 0x72, 0x65, 0x73, 0x68, 0x6f, 0x6c, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x7a, 0x65, + 0x72, 0x6f, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x07, 0x20, 0x01, 0x28, 0x04, 0x52, 0x09, + 0x7a, 0x65, 0x72, 0x6f, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x28, 0x0a, 0x10, 0x7a, 0x65, 0x72, + 0x6f, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x5f, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x18, 0x08, 0x20, + 0x01, 0x28, 0x01, 0x52, 0x0e, 0x7a, 0x65, 0x72, 0x6f, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x46, 0x6c, + 0x6f, 0x61, 0x74, 0x12, 0x45, 0x0a, 0x0d, 0x6e, 0x65, 0x67, 0x61, 0x74, 0x69, 0x76, 0x65, 0x5f, + 0x73, 0x70, 0x61, 0x6e, 0x18, 0x09, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x20, 0x2e, 0x69, 0x6f, 0x2e, + 0x70, 0x72, 0x6f, 0x6d, 0x65, 0x74, 0x68, 0x65, 0x75, 0x73, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, + 0x74, 0x2e, 0x42, 0x75, 0x63, 0x6b, 0x65, 0x74, 0x53, 0x70, 0x61, 0x6e, 0x52, 0x0c, 0x6e, 0x65, + 0x67, 0x61, 0x74, 0x69, 0x76, 0x65, 0x53, 0x70, 0x61, 0x6e, 0x12, 0x25, 0x0a, 0x0e, 0x6e, 0x65, + 0x67, 0x61, 0x74, 0x69, 0x76, 0x65, 0x5f, 0x64, 0x65, 0x6c, 0x74, 0x61, 0x18, 0x0a, 0x20, 0x03, + 0x28, 0x12, 0x52, 0x0d, 0x6e, 0x65, 0x67, 0x61, 0x74, 0x69, 0x76, 0x65, 0x44, 0x65, 0x6c, 0x74, + 0x61, 0x12, 0x25, 0x0a, 0x0e, 0x6e, 0x65, 0x67, 0x61, 0x74, 0x69, 0x76, 0x65, 0x5f, 0x63, 0x6f, + 0x75, 0x6e, 0x74, 0x18, 0x0b, 0x20, 0x03, 0x28, 0x01, 0x52, 0x0d, 0x6e, 0x65, 0x67, 0x61, 0x74, + 0x69, 0x76, 0x65, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x45, 0x0a, 0x0d, 0x70, 0x6f, 0x73, 0x69, + 0x74, 0x69, 0x76, 0x65, 0x5f, 0x73, 0x70, 0x61, 0x6e, 0x18, 0x0c, 0x20, 0x03, 0x28, 0x0b, 0x32, + 0x20, 0x2e, 0x69, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x6d, 0x65, 0x74, 0x68, 0x65, 0x75, 0x73, 0x2e, + 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x2e, 0x42, 0x75, 0x63, 0x6b, 0x65, 0x74, 0x53, 0x70, 0x61, + 0x6e, 0x52, 0x0c, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x76, 0x65, 0x53, 0x70, 0x61, 0x6e, 0x12, + 0x25, 0x0a, 0x0e, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x76, 0x65, 0x5f, 0x64, 0x65, 0x6c, 0x74, + 0x61, 0x18, 0x0d, 0x20, 0x03, 0x28, 0x12, 0x52, 0x0d, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x76, + 0x65, 0x44, 0x65, 0x6c, 0x74, 0x61, 0x12, 0x25, 0x0a, 0x0e, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, + 0x76, 0x65, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x0e, 0x20, 0x03, 0x28, 0x01, 0x52, 0x0d, + 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x76, 0x65, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x22, 0xc6, 0x01, + 0x0a, 0x06, 0x42, 0x75, 0x63, 0x6b, 0x65, 0x74, 0x12, 0x29, 0x0a, 0x10, 0x63, 0x75, 0x6d, 0x75, + 0x6c, 0x61, 0x74, 0x69, 0x76, 0x65, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, + 0x28, 0x04, 0x52, 0x0f, 0x63, 0x75, 0x6d, 0x75, 0x6c, 0x61, 0x74, 0x69, 0x76, 0x65, 0x43, 0x6f, + 0x75, 0x6e, 0x74, 0x12, 0x34, 0x0a, 0x16, 0x63, 0x75, 0x6d, 0x75, 0x6c, 0x61, 0x74, 0x69, 0x76, + 0x65, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x5f, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x18, 0x04, 0x20, + 0x01, 0x28, 0x01, 0x52, 0x14, 0x63, 0x75, 0x6d, 0x75, 0x6c, 0x61, 0x74, 0x69, 0x76, 0x65, 0x43, + 0x6f, 0x75, 0x6e, 0x74, 0x46, 0x6c, 0x6f, 0x61, 0x74, 0x12, 0x1f, 0x0a, 0x0b, 0x75, 0x70, 0x70, + 0x65, 0x72, 0x5f, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x01, 0x52, 0x0a, + 0x75, 0x70, 0x70, 0x65, 0x72, 0x42, 0x6f, 0x75, 0x6e, 0x64, 0x12, 0x3a, 0x0a, 0x08, 0x65, 0x78, + 0x65, 0x6d, 0x70, 0x6c, 0x61, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1e, 0x2e, 0x69, + 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x6d, 0x65, 0x74, 0x68, 0x65, 0x75, 0x73, 0x2e, 0x63, 0x6c, 0x69, + 0x65, 0x6e, 0x74, 0x2e, 0x45, 0x78, 0x65, 0x6d, 0x70, 0x6c, 0x61, 0x72, 0x52, 0x08, 0x65, 0x78, + 0x65, 0x6d, 0x70, 0x6c, 0x61, 0x72, 0x22, 0x3c, 0x0a, 0x0a, 0x42, 0x75, 0x63, 0x6b, 0x65, 0x74, + 0x53, 0x70, 0x61, 0x6e, 0x12, 0x16, 0x0a, 0x06, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x18, 0x01, + 0x20, 0x01, 0x28, 0x11, 0x52, 0x06, 0x6f, 0x66, 0x66, 0x73, 0x65, 0x74, 0x12, 0x16, 0x0a, 0x06, + 0x6c, 0x65, 0x6e, 0x67, 0x74, 0x68, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x06, 0x6c, 0x65, + 0x6e, 0x67, 0x74, 0x68, 0x22, 0x91, 0x01, 0x0a, 0x08, 0x45, 0x78, 0x65, 0x6d, 0x70, 0x6c, 0x61, + 0x72, 0x12, 0x35, 0x0a, 0x05, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, + 0x32, 0x1f, 0x2e, 0x69, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x6d, 0x65, 0x74, 0x68, 0x65, 0x75, 0x73, + 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x2e, 0x4c, 0x61, 0x62, 0x65, 0x6c, 0x50, 0x61, 0x69, + 0x72, 0x52, 0x05, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, + 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x01, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x38, + 0x0a, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x03, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x74, + 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x22, 0xff, 0x02, 0x0a, 0x06, 0x4d, 0x65, 0x74, + 0x72, 0x69, 0x63, 0x12, 0x35, 0x0a, 0x05, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x18, 0x01, 0x20, 0x03, + 0x28, 0x0b, 0x32, 0x1f, 0x2e, 0x69, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x6d, 0x65, 0x74, 0x68, 0x65, + 0x75, 0x73, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x2e, 0x4c, 0x61, 0x62, 0x65, 0x6c, 0x50, + 0x61, 0x69, 0x72, 0x52, 0x05, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x12, 0x31, 0x0a, 0x05, 0x67, 0x61, + 0x75, 0x67, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x69, 0x6f, 0x2e, 0x70, + 0x72, 0x6f, 0x6d, 0x65, 0x74, 0x68, 0x65, 0x75, 0x73, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, + 0x2e, 0x47, 0x61, 0x75, 0x67, 0x65, 0x52, 0x05, 0x67, 0x61, 0x75, 0x67, 0x65, 0x12, 0x37, 0x0a, + 0x07, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x65, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1d, + 0x2e, 0x69, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x6d, 0x65, 0x74, 0x68, 0x65, 0x75, 0x73, 0x2e, 0x63, + 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x2e, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x65, 0x72, 0x52, 0x07, 0x63, + 0x6f, 0x75, 0x6e, 0x74, 0x65, 0x72, 0x12, 0x37, 0x0a, 0x07, 0x73, 0x75, 0x6d, 0x6d, 0x61, 0x72, + 0x79, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1d, 0x2e, 0x69, 0x6f, 0x2e, 0x70, 0x72, 0x6f, + 0x6d, 0x65, 0x74, 0x68, 0x65, 0x75, 0x73, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x2e, 0x53, + 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x07, 0x73, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x12, + 0x37, 0x0a, 0x07, 0x75, 0x6e, 0x74, 0x79, 0x70, 0x65, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, + 0x32, 0x1d, 0x2e, 0x69, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x6d, 0x65, 0x74, 0x68, 0x65, 0x75, 0x73, + 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x2e, 0x55, 0x6e, 0x74, 0x79, 0x70, 0x65, 0x64, 0x52, + 0x07, 0x75, 0x6e, 0x74, 0x79, 0x70, 0x65, 0x64, 0x12, 0x3d, 0x0a, 0x09, 0x68, 0x69, 0x73, 0x74, + 0x6f, 0x67, 0x72, 0x61, 0x6d, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1f, 0x2e, 0x69, 0x6f, + 0x2e, 0x70, 0x72, 0x6f, 0x6d, 0x65, 0x74, 0x68, 0x65, 0x75, 0x73, 0x2e, 0x63, 0x6c, 0x69, 0x65, + 0x6e, 0x74, 0x2e, 0x48, 0x69, 0x73, 0x74, 0x6f, 0x67, 0x72, 0x61, 0x6d, 0x52, 0x09, 0x68, 0x69, + 0x73, 0x74, 0x6f, 0x67, 0x72, 0x61, 0x6d, 0x12, 0x21, 0x0a, 0x0c, 0x74, 0x69, 0x6d, 0x65, 0x73, + 0x74, 0x61, 0x6d, 0x70, 0x5f, 0x6d, 0x73, 0x18, 0x06, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0b, 0x74, + 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x4d, 0x73, 0x22, 0xa2, 0x01, 0x0a, 0x0c, 0x4d, + 0x65, 0x74, 0x72, 0x69, 0x63, 0x46, 0x61, 0x6d, 0x69, 0x6c, 0x79, 0x12, 0x12, 0x0a, 0x04, 0x6e, + 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, + 0x12, 0x0a, 0x04, 0x68, 0x65, 0x6c, 0x70, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x68, + 0x65, 0x6c, 0x70, 0x12, 0x34, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, + 0x0e, 0x32, 0x20, 0x2e, 0x69, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x6d, 0x65, 0x74, 0x68, 0x65, 0x75, + 0x73, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x2e, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x54, + 0x79, 0x70, 0x65, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x34, 0x0a, 0x06, 0x6d, 0x65, 0x74, + 0x72, 0x69, 0x63, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x69, 0x6f, 0x2e, 0x70, + 0x72, 0x6f, 0x6d, 0x65, 0x74, 0x68, 0x65, 0x75, 0x73, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, + 0x2e, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x52, 0x06, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x2a, + 0x62, 0x0a, 0x0a, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x54, 0x79, 0x70, 0x65, 0x12, 0x0b, 0x0a, + 0x07, 0x43, 0x4f, 0x55, 0x4e, 0x54, 0x45, 0x52, 0x10, 0x00, 0x12, 0x09, 0x0a, 0x05, 0x47, 0x41, + 0x55, 0x47, 0x45, 0x10, 0x01, 0x12, 0x0b, 0x0a, 0x07, 0x53, 0x55, 0x4d, 0x4d, 0x41, 0x52, 0x59, + 0x10, 0x02, 0x12, 0x0b, 0x0a, 0x07, 0x55, 0x4e, 0x54, 0x59, 0x50, 0x45, 0x44, 0x10, 0x03, 0x12, + 0x0d, 0x0a, 0x09, 0x48, 0x49, 0x53, 0x54, 0x4f, 0x47, 0x52, 0x41, 0x4d, 0x10, 0x04, 0x12, 0x13, + 0x0a, 0x0f, 0x47, 0x41, 0x55, 0x47, 0x45, 0x5f, 0x48, 0x49, 0x53, 0x54, 0x4f, 0x47, 0x52, 0x41, + 0x4d, 0x10, 0x05, 0x42, 0x52, 0x0a, 0x14, 0x69, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x6d, 0x65, 0x74, + 0x68, 0x65, 0x75, 0x73, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5a, 0x3a, 0x67, 0x69, 0x74, + 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x70, 0x72, 0x6f, 0x6d, 0x65, 0x74, 0x68, 0x65, + 0x75, 0x73, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x6d, 0x6f, 0x64, 0x65, 0x6c, 0x2f, + 0x67, 0x6f, 0x3b, 0x69, 0x6f, 0x5f, 0x70, 0x72, 0x6f, 0x6d, 0x65, 0x74, 0x68, 0x65, 0x75, 0x73, + 0x5f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, +} + +var ( + file_io_prometheus_client_metrics_proto_rawDescOnce sync.Once + file_io_prometheus_client_metrics_proto_rawDescData = file_io_prometheus_client_metrics_proto_rawDesc +) + +func file_io_prometheus_client_metrics_proto_rawDescGZIP() []byte { + file_io_prometheus_client_metrics_proto_rawDescOnce.Do(func() { + file_io_prometheus_client_metrics_proto_rawDescData = protoimpl.X.CompressGZIP(file_io_prometheus_client_metrics_proto_rawDescData) + }) + return file_io_prometheus_client_metrics_proto_rawDescData +} + +var file_io_prometheus_client_metrics_proto_enumTypes = make([]protoimpl.EnumInfo, 1) +var file_io_prometheus_client_metrics_proto_msgTypes = make([]protoimpl.MessageInfo, 12) +var file_io_prometheus_client_metrics_proto_goTypes = []interface{}{ + (MetricType)(0), // 0: io.prometheus.client.MetricType + (*LabelPair)(nil), // 1: io.prometheus.client.LabelPair + (*Gauge)(nil), // 2: io.prometheus.client.Gauge + (*Counter)(nil), // 3: io.prometheus.client.Counter + (*Quantile)(nil), // 4: io.prometheus.client.Quantile + (*Summary)(nil), // 5: io.prometheus.client.Summary + (*Untyped)(nil), // 6: io.prometheus.client.Untyped + (*Histogram)(nil), // 7: io.prometheus.client.Histogram + (*Bucket)(nil), // 8: io.prometheus.client.Bucket + (*BucketSpan)(nil), // 9: io.prometheus.client.BucketSpan + (*Exemplar)(nil), // 10: io.prometheus.client.Exemplar + (*Metric)(nil), // 11: io.prometheus.client.Metric + (*MetricFamily)(nil), // 12: io.prometheus.client.MetricFamily + (*timestamppb.Timestamp)(nil), // 13: google.protobuf.Timestamp +} +var file_io_prometheus_client_metrics_proto_depIdxs = []int32{ + 10, // 0: io.prometheus.client.Counter.exemplar:type_name -> io.prometheus.client.Exemplar + 4, // 1: io.prometheus.client.Summary.quantile:type_name -> io.prometheus.client.Quantile + 8, // 2: io.prometheus.client.Histogram.bucket:type_name -> io.prometheus.client.Bucket + 9, // 3: io.prometheus.client.Histogram.negative_span:type_name -> io.prometheus.client.BucketSpan + 9, // 4: io.prometheus.client.Histogram.positive_span:type_name -> io.prometheus.client.BucketSpan + 10, // 5: io.prometheus.client.Bucket.exemplar:type_name -> io.prometheus.client.Exemplar + 1, // 6: io.prometheus.client.Exemplar.label:type_name -> io.prometheus.client.LabelPair + 13, // 7: io.prometheus.client.Exemplar.timestamp:type_name -> google.protobuf.Timestamp + 1, // 8: io.prometheus.client.Metric.label:type_name -> io.prometheus.client.LabelPair + 2, // 9: io.prometheus.client.Metric.gauge:type_name -> io.prometheus.client.Gauge + 3, // 10: io.prometheus.client.Metric.counter:type_name -> io.prometheus.client.Counter + 5, // 11: io.prometheus.client.Metric.summary:type_name -> io.prometheus.client.Summary + 6, // 12: io.prometheus.client.Metric.untyped:type_name -> io.prometheus.client.Untyped + 7, // 13: io.prometheus.client.Metric.histogram:type_name -> io.prometheus.client.Histogram + 0, // 14: io.prometheus.client.MetricFamily.type:type_name -> io.prometheus.client.MetricType + 11, // 15: io.prometheus.client.MetricFamily.metric:type_name -> io.prometheus.client.Metric + 16, // [16:16] is the sub-list for method output_type + 16, // [16:16] is the sub-list for method input_type + 16, // [16:16] is the sub-list for extension type_name + 16, // [16:16] is the sub-list for extension extendee + 0, // [0:16] is the sub-list for field type_name +} + +func init() { file_io_prometheus_client_metrics_proto_init() } +func file_io_prometheus_client_metrics_proto_init() { + if File_io_prometheus_client_metrics_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_io_prometheus_client_metrics_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*LabelPair); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_io_prometheus_client_metrics_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Gauge); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_io_prometheus_client_metrics_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Counter); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_io_prometheus_client_metrics_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Quantile); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_io_prometheus_client_metrics_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Summary); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_io_prometheus_client_metrics_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Untyped); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_io_prometheus_client_metrics_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Histogram); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_io_prometheus_client_metrics_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Bucket); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_io_prometheus_client_metrics_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*BucketSpan); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_io_prometheus_client_metrics_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Exemplar); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_io_prometheus_client_metrics_proto_msgTypes[10].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Metric); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_io_prometheus_client_metrics_proto_msgTypes[11].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*MetricFamily); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_io_prometheus_client_metrics_proto_rawDesc, + NumEnums: 1, + NumMessages: 12, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_io_prometheus_client_metrics_proto_goTypes, + DependencyIndexes: file_io_prometheus_client_metrics_proto_depIdxs, + EnumInfos: file_io_prometheus_client_metrics_proto_enumTypes, + MessageInfos: file_io_prometheus_client_metrics_proto_msgTypes, + }.Build() + File_io_prometheus_client_metrics_proto = out.File + file_io_prometheus_client_metrics_proto_rawDesc = nil + file_io_prometheus_client_metrics_proto_goTypes = nil + file_io_prometheus_client_metrics_proto_depIdxs = nil } diff --git a/vendor/github.com/prometheus/common/config/http_config.go b/vendor/github.com/prometheus/common/config/http_config.go index 73163206419..37aa966748b 100644 --- a/vendor/github.com/prometheus/common/config/http_config.go +++ b/vendor/github.com/prometheus/common/config/http_config.go @@ -579,8 +579,7 @@ func NewRoundTripperFromConfig(cfg HTTPClientConfig, name string, optFuncs ...HT // No need for a RoundTripper that reloads the CA file automatically. return newRT(tlsConfig) } - - return NewTLSRoundTripper(tlsConfig, cfg.TLSConfig.CAFile, cfg.TLSConfig.CertFile, cfg.TLSConfig.KeyFile, newRT) + return NewTLSRoundTripper(tlsConfig, cfg.TLSConfig.roundTripperSettings(), newRT) } type authorizationCredentialsRoundTripper struct { @@ -750,7 +749,7 @@ func (rt *oauth2RoundTripper) RoundTrip(req *http.Request) (*http.Response, erro if len(rt.config.TLSConfig.CAFile) == 0 { t, _ = tlsTransport(tlsConfig) } else { - t, err = NewTLSRoundTripper(tlsConfig, rt.config.TLSConfig.CAFile, rt.config.TLSConfig.CertFile, rt.config.TLSConfig.KeyFile, tlsTransport) + t, err = NewTLSRoundTripper(tlsConfig, rt.config.TLSConfig.roundTripperSettings(), tlsTransport) if err != nil { return nil, err } @@ -817,6 +816,10 @@ func cloneRequest(r *http.Request) *http.Request { // NewTLSConfig creates a new tls.Config from the given TLSConfig. func NewTLSConfig(cfg *TLSConfig) (*tls.Config, error) { + if err := cfg.Validate(); err != nil { + return nil, err + } + tlsConfig := &tls.Config{ InsecureSkipVerify: cfg.InsecureSkipVerify, MinVersion: uint16(cfg.MinVersion), @@ -831,7 +834,11 @@ func NewTLSConfig(cfg *TLSConfig) (*tls.Config, error) { // If a CA cert is provided then let's read it in so we can validate the // scrape target's certificate properly. - if len(cfg.CAFile) > 0 { + if len(cfg.CA) > 0 { + if !updateRootCA(tlsConfig, []byte(cfg.CA)) { + return nil, fmt.Errorf("unable to use inline CA cert") + } + } else if len(cfg.CAFile) > 0 { b, err := readCAFile(cfg.CAFile) if err != nil { return nil, err @@ -844,12 +851,9 @@ func NewTLSConfig(cfg *TLSConfig) (*tls.Config, error) { if len(cfg.ServerName) > 0 { tlsConfig.ServerName = cfg.ServerName } + // If a client cert & key is provided then configure TLS config accordingly. - if len(cfg.CertFile) > 0 && len(cfg.KeyFile) == 0 { - return nil, fmt.Errorf("client cert file %q specified without client key file", cfg.CertFile) - } else if len(cfg.KeyFile) > 0 && len(cfg.CertFile) == 0 { - return nil, fmt.Errorf("client key file %q specified without client cert file", cfg.KeyFile) - } else if len(cfg.CertFile) > 0 && len(cfg.KeyFile) > 0 { + if cfg.usingClientCert() && cfg.usingClientKey() { // Verify that client cert and key are valid. if _, err := cfg.getClientCertificate(nil); err != nil { return nil, err @@ -862,6 +866,12 @@ func NewTLSConfig(cfg *TLSConfig) (*tls.Config, error) { // TLSConfig configures the options for TLS connections. type TLSConfig struct { + // Text of the CA cert to use for the targets. + CA string `yaml:"ca,omitempty" json:"ca,omitempty"` + // Text of the client cert file for the targets. + Cert string `yaml:"cert,omitempty" json:"cert,omitempty"` + // Text of the client key file for the targets. + Key Secret `yaml:"key,omitempty" json:"key,omitempty"` // The CA cert to use for the targets. CAFile string `yaml:"ca_file,omitempty" json:"ca_file,omitempty"` // The client cert file for the targets. @@ -891,29 +901,77 @@ func (c *TLSConfig) SetDirectory(dir string) { // UnmarshalYAML implements the yaml.Unmarshaler interface. func (c *TLSConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { type plain TLSConfig - return unmarshal((*plain)(c)) + if err := unmarshal((*plain)(c)); err != nil { + return err + } + return c.Validate() } -// readCertAndKey reads the cert and key files from the disk. -func readCertAndKey(certFile, keyFile string) ([]byte, []byte, error) { - certData, err := os.ReadFile(certFile) - if err != nil { - return nil, nil, err +// Validate validates the TLSConfig to check that only one of the inlined or +// file-based fields for the TLS CA, client certificate, and client key are +// used. +func (c *TLSConfig) Validate() error { + if len(c.CA) > 0 && len(c.CAFile) > 0 { + return fmt.Errorf("at most one of ca and ca_file must be configured") + } + if len(c.Cert) > 0 && len(c.CertFile) > 0 { + return fmt.Errorf("at most one of cert and cert_file must be configured") + } + if len(c.Key) > 0 && len(c.KeyFile) > 0 { + return fmt.Errorf("at most one of key and key_file must be configured") } - keyData, err := os.ReadFile(keyFile) - if err != nil { - return nil, nil, err + if c.usingClientCert() && !c.usingClientKey() { + return fmt.Errorf("exactly one of key or key_file must be configured when a client certificate is configured") + } else if c.usingClientKey() && !c.usingClientCert() { + return fmt.Errorf("exactly one of cert or cert_file must be configured when a client key is configured") } - return certData, keyData, nil + return nil +} + +func (c *TLSConfig) usingClientCert() bool { + return len(c.Cert) > 0 || len(c.CertFile) > 0 +} + +func (c *TLSConfig) usingClientKey() bool { + return len(c.Key) > 0 || len(c.KeyFile) > 0 +} + +func (c *TLSConfig) roundTripperSettings() TLSRoundTripperSettings { + return TLSRoundTripperSettings{ + CA: c.CA, + CAFile: c.CAFile, + Cert: c.Cert, + CertFile: c.CertFile, + Key: string(c.Key), + KeyFile: c.KeyFile, + } } // getClientCertificate reads the pair of client cert and key from disk and returns a tls.Certificate. func (c *TLSConfig) getClientCertificate(_ *tls.CertificateRequestInfo) (*tls.Certificate, error) { - certData, keyData, err := readCertAndKey(c.CertFile, c.KeyFile) - if err != nil { - return nil, fmt.Errorf("unable to read specified client cert (%s) & key (%s): %s", c.CertFile, c.KeyFile, err) + var ( + certData, keyData []byte + err error + ) + + if c.CertFile != "" { + certData, err = os.ReadFile(c.CertFile) + if err != nil { + return nil, fmt.Errorf("unable to read specified client cert (%s): %s", c.CertFile, err) + } + } else { + certData = []byte(c.Cert) + } + + if c.KeyFile != "" { + keyData, err = os.ReadFile(c.KeyFile) + if err != nil { + return nil, fmt.Errorf("unable to read specified client key (%s): %s", c.KeyFile, err) + } + } else { + keyData = []byte(c.Key) } cert, err := tls.X509KeyPair(certData, keyData) @@ -946,30 +1004,32 @@ func updateRootCA(cfg *tls.Config, b []byte) bool { // tlsRoundTripper is a RoundTripper that updates automatically its TLS // configuration whenever the content of the CA file changes. type tlsRoundTripper struct { - caFile string - certFile string - keyFile string + settings TLSRoundTripperSettings // newRT returns a new RoundTripper. newRT func(*tls.Config) (http.RoundTripper, error) mtx sync.RWMutex rt http.RoundTripper - hashCAFile []byte - hashCertFile []byte - hashKeyFile []byte + hashCAData []byte + hashCertData []byte + hashKeyData []byte tlsConfig *tls.Config } +type TLSRoundTripperSettings struct { + CA, CAFile string + Cert, CertFile string + Key, KeyFile string +} + func NewTLSRoundTripper( cfg *tls.Config, - caFile, certFile, keyFile string, + settings TLSRoundTripperSettings, newRT func(*tls.Config) (http.RoundTripper, error), ) (http.RoundTripper, error) { t := &tlsRoundTripper{ - caFile: caFile, - certFile: certFile, - keyFile: keyFile, + settings: settings, newRT: newRT, tlsConfig: cfg, } @@ -979,7 +1039,7 @@ func NewTLSRoundTripper( return nil, err } t.rt = rt - _, t.hashCAFile, t.hashCertFile, t.hashKeyFile, err = t.getTLSFilesWithHash() + _, t.hashCAData, t.hashCertData, t.hashKeyData, err = t.getTLSDataWithHash() if err != nil { return nil, err } @@ -987,36 +1047,66 @@ func NewTLSRoundTripper( return t, nil } -func (t *tlsRoundTripper) getTLSFilesWithHash() ([]byte, []byte, []byte, []byte, error) { - b1, err := readCAFile(t.caFile) - if err != nil { - return nil, nil, nil, nil, err +func (t *tlsRoundTripper) getTLSDataWithHash() ([]byte, []byte, []byte, []byte, error) { + var ( + caBytes, certBytes, keyBytes []byte + + err error + ) + + if t.settings.CAFile != "" { + caBytes, err = os.ReadFile(t.settings.CAFile) + if err != nil { + return nil, nil, nil, nil, err + } + } else if t.settings.CA != "" { + caBytes = []byte(t.settings.CA) + } + + if t.settings.CertFile != "" { + certBytes, err = os.ReadFile(t.settings.CertFile) + if err != nil { + return nil, nil, nil, nil, err + } + } else if t.settings.Cert != "" { + certBytes = []byte(t.settings.Cert) } - h1 := sha256.Sum256(b1) - var h2, h3 [32]byte - if t.certFile != "" { - b2, b3, err := readCertAndKey(t.certFile, t.keyFile) + if t.settings.KeyFile != "" { + keyBytes, err = os.ReadFile(t.settings.KeyFile) if err != nil { return nil, nil, nil, nil, err } - h2, h3 = sha256.Sum256(b2), sha256.Sum256(b3) + } else if t.settings.Key != "" { + keyBytes = []byte(t.settings.Key) + } + + var caHash, certHash, keyHash [32]byte + + if len(caBytes) > 0 { + caHash = sha256.Sum256(caBytes) + } + if len(certBytes) > 0 { + certHash = sha256.Sum256(certBytes) + } + if len(keyBytes) > 0 { + keyHash = sha256.Sum256(keyBytes) } - return b1, h1[:], h2[:], h3[:], nil + return caBytes, caHash[:], certHash[:], keyHash[:], nil } // RoundTrip implements the http.RoundTrip interface. func (t *tlsRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { - caData, caHash, certHash, keyHash, err := t.getTLSFilesWithHash() + caData, caHash, certHash, keyHash, err := t.getTLSDataWithHash() if err != nil { return nil, err } t.mtx.RLock() - equal := bytes.Equal(caHash[:], t.hashCAFile) && - bytes.Equal(certHash[:], t.hashCertFile) && - bytes.Equal(keyHash[:], t.hashKeyFile) + equal := bytes.Equal(caHash[:], t.hashCAData) && + bytes.Equal(certHash[:], t.hashCertData) && + bytes.Equal(keyHash[:], t.hashKeyData) rt := t.rt t.mtx.RUnlock() if equal { @@ -1029,7 +1119,7 @@ func (t *tlsRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { // using GetClientCertificate. tlsConfig := t.tlsConfig.Clone() if !updateRootCA(tlsConfig, caData) { - return nil, fmt.Errorf("unable to use specified CA cert %s", t.caFile) + return nil, fmt.Errorf("unable to use specified CA cert %s", t.settings.CAFile) } rt, err = t.newRT(tlsConfig) if err != nil { @@ -1039,9 +1129,9 @@ func (t *tlsRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { t.mtx.Lock() t.rt = rt - t.hashCAFile = caHash[:] - t.hashCertFile = certHash[:] - t.hashKeyFile = keyHash[:] + t.hashCAData = caHash[:] + t.hashCertData = certHash[:] + t.hashKeyData = keyHash[:] t.mtx.Unlock() return rt.RoundTrip(req) diff --git a/vendor/github.com/prometheus/common/expfmt/decode.go b/vendor/github.com/prometheus/common/expfmt/decode.go index f4fc8845522..90639781513 100644 --- a/vendor/github.com/prometheus/common/expfmt/decode.go +++ b/vendor/github.com/prometheus/common/expfmt/decode.go @@ -132,7 +132,10 @@ func (d *textDecoder) Decode(v *dto.MetricFamily) error { } // Pick off one MetricFamily per Decode until there's nothing left. for key, fam := range d.fams { - *v = *fam + v.Name = fam.Name + v.Help = fam.Help + v.Type = fam.Type + v.Metric = fam.Metric delete(d.fams, key) return nil } diff --git a/vendor/github.com/prometheus/common/expfmt/encode.go b/vendor/github.com/prometheus/common/expfmt/encode.go index 64dc0eb40c2..7f611ffaad7 100644 --- a/vendor/github.com/prometheus/common/expfmt/encode.go +++ b/vendor/github.com/prometheus/common/expfmt/encode.go @@ -18,9 +18,9 @@ import ( "io" "net/http" - "github.com/golang/protobuf/proto" //nolint:staticcheck // Ignore SA1019. Need to keep deprecated package for compatibility. "github.com/matttproud/golang_protobuf_extensions/pbutil" "github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg" + "google.golang.org/protobuf/encoding/prototext" dto "github.com/prometheus/client_model/go" ) @@ -99,8 +99,11 @@ func NegotiateIncludingOpenMetrics(h http.Header) Format { if ac.Type == "text" && ac.SubType == "plain" && (ver == TextVersion || ver == "") { return FmtText } - if ac.Type+"/"+ac.SubType == OpenMetricsType && (ver == OpenMetricsVersion || ver == "") { - return FmtOpenMetrics + if ac.Type+"/"+ac.SubType == OpenMetricsType && (ver == OpenMetricsVersion_0_0_1 || ver == OpenMetricsVersion_1_0_0 || ver == "") { + if ver == OpenMetricsVersion_1_0_0 { + return FmtOpenMetrics_1_0_0 + } + return FmtOpenMetrics_0_0_1 } } return FmtText @@ -133,7 +136,7 @@ func NewEncoder(w io.Writer, format Format) Encoder { case FmtProtoText: return encoderCloser{ encode: func(v *dto.MetricFamily) error { - _, err := fmt.Fprintln(w, proto.MarshalTextString(v)) + _, err := fmt.Fprintln(w, prototext.Format(v)) return err }, close: func() error { return nil }, @@ -146,7 +149,7 @@ func NewEncoder(w io.Writer, format Format) Encoder { }, close: func() error { return nil }, } - case FmtOpenMetrics: + case FmtOpenMetrics_0_0_1, FmtOpenMetrics_1_0_0: return encoderCloser{ encode: func(v *dto.MetricFamily) error { _, err := MetricFamilyToOpenMetrics(w, v) diff --git a/vendor/github.com/prometheus/common/expfmt/expfmt.go b/vendor/github.com/prometheus/common/expfmt/expfmt.go index 0f176fa64f2..c4cb20f0d3e 100644 --- a/vendor/github.com/prometheus/common/expfmt/expfmt.go +++ b/vendor/github.com/prometheus/common/expfmt/expfmt.go @@ -19,20 +19,22 @@ type Format string // Constants to assemble the Content-Type values for the different wire protocols. const ( - TextVersion = "0.0.4" - ProtoType = `application/vnd.google.protobuf` - ProtoProtocol = `io.prometheus.client.MetricFamily` - ProtoFmt = ProtoType + "; proto=" + ProtoProtocol + ";" - OpenMetricsType = `application/openmetrics-text` - OpenMetricsVersion = "0.0.1" + TextVersion = "0.0.4" + ProtoType = `application/vnd.google.protobuf` + ProtoProtocol = `io.prometheus.client.MetricFamily` + ProtoFmt = ProtoType + "; proto=" + ProtoProtocol + ";" + OpenMetricsType = `application/openmetrics-text` + OpenMetricsVersion_0_0_1 = "0.0.1" + OpenMetricsVersion_1_0_0 = "1.0.0" // The Content-Type values for the different wire protocols. - FmtUnknown Format = `` - FmtText Format = `text/plain; version=` + TextVersion + `; charset=utf-8` - FmtProtoDelim Format = ProtoFmt + ` encoding=delimited` - FmtProtoText Format = ProtoFmt + ` encoding=text` - FmtProtoCompact Format = ProtoFmt + ` encoding=compact-text` - FmtOpenMetrics Format = OpenMetricsType + `; version=` + OpenMetricsVersion + `; charset=utf-8` + FmtUnknown Format = `` + FmtText Format = `text/plain; version=` + TextVersion + `; charset=utf-8` + FmtProtoDelim Format = ProtoFmt + ` encoding=delimited` + FmtProtoText Format = ProtoFmt + ` encoding=text` + FmtProtoCompact Format = ProtoFmt + ` encoding=compact-text` + FmtOpenMetrics_1_0_0 Format = OpenMetricsType + `; version=` + OpenMetricsVersion_1_0_0 + `; charset=utf-8` + FmtOpenMetrics_0_0_1 Format = OpenMetricsType + `; version=` + OpenMetricsVersion_0_0_1 + `; charset=utf-8` ) const ( diff --git a/vendor/github.com/prometheus/common/expfmt/text_parse.go b/vendor/github.com/prometheus/common/expfmt/text_parse.go index ac2482782c7..35db1cc9d73 100644 --- a/vendor/github.com/prometheus/common/expfmt/text_parse.go +++ b/vendor/github.com/prometheus/common/expfmt/text_parse.go @@ -24,8 +24,8 @@ import ( dto "github.com/prometheus/client_model/go" - "github.com/golang/protobuf/proto" //nolint:staticcheck // Ignore SA1019. Need to keep deprecated package for compatibility. "github.com/prometheus/common/model" + "google.golang.org/protobuf/proto" ) // A stateFn is a function that represents a state in a state machine. By diff --git a/vendor/github.com/prometheus/common/promlog/log.go b/vendor/github.com/prometheus/common/promlog/log.go index 35e95c89329..3ac7b3fdf12 100644 --- a/vendor/github.com/prometheus/common/promlog/log.go +++ b/vendor/github.com/prometheus/common/promlog/log.go @@ -111,13 +111,16 @@ type Config struct { // New returns a new leveled oklog logger. Each logged line will be annotated // with a timestamp. The output always goes to stderr. func New(config *Config) log.Logger { - var l log.Logger if config.Format != nil && config.Format.s == "json" { - l = log.NewJSONLogger(log.NewSyncWriter(os.Stderr)) - } else { - l = log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr)) + return NewWithLogger(log.NewJSONLogger(log.NewSyncWriter(os.Stderr)), config) } + return NewWithLogger(log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr)), config) +} + +// NewWithLogger returns a new leveled oklog logger with a custom log.Logger. +// Each logged line will be annotated with a timestamp. +func NewWithLogger(l log.Logger, config *Config) log.Logger { if config.Level != nil { l = log.With(l, "ts", timestampFormat, "caller", log.Caller(5)) l = level.NewFilter(l, config.Level.o) @@ -131,13 +134,17 @@ func New(config *Config) log.Logger { // with a timestamp. The output always goes to stderr. Some properties can be // changed, like the level. func NewDynamic(config *Config) *logger { - var l log.Logger if config.Format != nil && config.Format.s == "json" { - l = log.NewJSONLogger(log.NewSyncWriter(os.Stderr)) - } else { - l = log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr)) + return NewDynamicWithLogger(log.NewJSONLogger(log.NewSyncWriter(os.Stderr)), config) } + return NewDynamicWithLogger(log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr)), config) +} + +// NewDynamicWithLogger returns a new leveled logger with a custom io.Writer. +// Each logged line will be annotated with a timestamp. +// Some properties can be changed, like the level. +func NewDynamicWithLogger(l log.Logger, config *Config) *logger { lo := &logger{ base: l, leveled: l, diff --git a/vendor/github.com/prometheus/exporter-toolkit/web/landing_page.css b/vendor/github.com/prometheus/exporter-toolkit/web/landing_page.css index cc939eaf811..260bc8a0967 100644 --- a/vendor/github.com/prometheus/exporter-toolkit/web/landing_page.css +++ b/vendor/github.com/prometheus/exporter-toolkit/web/landing_page.css @@ -5,9 +5,14 @@ body { header { background-color: {{.HeaderColor}}; color: #fff; - font-size: 2rem; + font-size: 1rem; padding: 1rem; } main { padding: 1rem; } +label { + display: inline-block; + width: {{.Form.Width}}em; +} +{{.ExtraCSS}} diff --git a/vendor/github.com/prometheus/exporter-toolkit/web/landing_page.go b/vendor/github.com/prometheus/exporter-toolkit/web/landing_page.go index f0747ac3622..68266213edd 100644 --- a/vendor/github.com/prometheus/exporter-toolkit/web/landing_page.go +++ b/vendor/github.com/prometheus/exporter-toolkit/web/landing_page.go @@ -31,10 +31,29 @@ type LandingConfig struct { CSS string // CSS style tag for the landing page. Name string // The name of the exporter, generally suffixed by _exporter. Description string // A short description about the exporter. + Form LandingForm // A POST form. Links []LandingLinks // Links displayed on the landing page. + ExtraHTML string // Additional HTML to be embedded. + ExtraCSS string // Additional CSS to be embedded. Version string // The version displayed. } +// LandingForm provides a configuration struct for creating a POST form on the landing page. +type LandingForm struct { + Action string + Inputs []LandingFormInput + Width float64 +} + +// LandingFormInput represents a single form input field. +type LandingFormInput struct { + Label string + Type string + Name string + Placeholder string + Value string +} + type LandingLinks struct { Address string // The URL the link points to. Text string // The text of the link. @@ -54,6 +73,15 @@ var ( func NewLandingPage(c LandingConfig) (*LandingPageHandler, error) { var buf bytes.Buffer + + length := 0 + for _, input := range c.Form.Inputs { + inputLength := len(input.Label) + if inputLength > length { + length = inputLength + } + } + c.Form.Width = (float64(length) + 1) / 2 if c.CSS == "" { if c.HeaderColor == "" { // Default to Prometheus orange. @@ -78,5 +106,6 @@ func NewLandingPage(c LandingConfig) (*LandingPageHandler, error) { } func (h *LandingPageHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + w.Header().Add("Content-Type", "text/html; charset=UTF-8") w.Write(h.landingPage) } diff --git a/vendor/github.com/prometheus/exporter-toolkit/web/landing_page.html b/vendor/github.com/prometheus/exporter-toolkit/web/landing_page.html index 68c401702cf..4f2e1817729 100644 --- a/vendor/github.com/prometheus/exporter-toolkit/web/landing_page.html +++ b/vendor/github.com/prometheus/exporter-toolkit/web/landing_page.html @@ -19,6 +19,17 @@

    {{.Name}}

    {{ end }}
+ {{ if .Form.Action }} +
+
+ {{ range .Form.Inputs }} +  
+ {{ end }} + +
+
+ {{ end }} + {{ .ExtraHTML }} diff --git a/vendor/github.com/prometheus/exporter-toolkit/web/tls_config.go b/vendor/github.com/prometheus/exporter-toolkit/web/tls_config.go index 47bbca1747b..4ef31a3f9bf 100644 --- a/vendor/github.com/prometheus/exporter-toolkit/web/tls_config.go +++ b/vendor/github.com/prometheus/exporter-toolkit/web/tls_config.go @@ -33,6 +33,7 @@ import ( var ( errNoTLSConfig = errors.New("TLS config is not present") + ErrNoListeners = errors.New("no web listen address or systemd socket flag specified") ) type Config struct { @@ -51,6 +52,7 @@ type TLSConfig struct { MinVersion TLSVersion `yaml:"min_version"` MaxVersion TLSVersion `yaml:"max_version"` PreferServerCipherSuites bool `yaml:"prefer_server_cipher_suites"` + ClientAllowedSans []string `yaml:"client_allowed_sans"` } type FlagConfig struct { @@ -66,6 +68,36 @@ func (t *TLSConfig) SetDirectory(dir string) { t.ClientCAs = config_util.JoinDir(dir, t.ClientCAs) } +// VerifyPeerCertificate will check the SAN entries of the client cert if there is configuration for it +func (t *TLSConfig) VerifyPeerCertificate(rawCerts [][]byte, _ [][]*x509.Certificate) error { + // sender cert comes first, see https://www.rfc-editor.org/rfc/rfc5246#section-7.4.2 + cert, err := x509.ParseCertificate(rawCerts[0]) + if err != nil { + return fmt.Errorf("error parsing client certificate: %s", err) + } + + // Build up a slice of strings with all Subject Alternate Name values + sanValues := append(cert.DNSNames, cert.EmailAddresses...) + + for _, ip := range cert.IPAddresses { + sanValues = append(sanValues, ip.String()) + } + + for _, uri := range cert.URIs { + sanValues = append(sanValues, uri.String()) + } + + for _, sanValue := range sanValues { + for _, allowedSan := range t.ClientAllowedSans { + if sanValue == allowedSan { + return nil + } + } + } + + return fmt.Errorf("could not find allowed SANs in client cert, found: %v", t.ClientAllowedSans) +} + type HTTPConfig struct { HTTP2 bool `yaml:"http2"` Header map[string]string `yaml:"headers,omitempty"` @@ -163,6 +195,11 @@ func ConfigToTLSConfig(c *TLSConfig) (*tls.Config, error) { cfg.ClientCAs = clientCAPool } + if c.ClientAllowedSans != nil { + // verify that the client cert contains an allowed SAN + cfg.VerifyPeerCertificate = c.VerifyPeerCertificate + } + switch c.ClientAuth { case "RequestClientCert": cfg.ClientAuth = tls.RequestClientCert @@ -203,7 +240,11 @@ func ServeMultiple(listeners []net.Listener, server *http.Server, flags *FlagCon // WebSystemdSocket in the FlagConfig is true. The FlagConfig is also passed on // to ServeMultiple. func ListenAndServe(server *http.Server, flags *FlagConfig, logger log.Logger) error { - if *flags.WebSystemdSocket { + if flags.WebSystemdSocket == nil && (flags.WebListenAddresses == nil || len(*flags.WebListenAddresses) == 0) { + return ErrNoListeners + } + + if flags.WebSystemdSocket != nil && *flags.WebSystemdSocket { level.Info(logger).Log("msg", "Listening on systemd activated listeners instead of port listeners.") listeners, err := activation.Listeners() if err != nil { @@ -214,6 +255,7 @@ func ListenAndServe(server *http.Server, flags *FlagConfig, logger log.Logger) e } return ServeMultiple(listeners, server, flags, logger) } + listeners := make([]net.Listener, 0, len(*flags.WebListenAddresses)) for _, address := range *flags.WebListenAddresses { listener, err := net.Listen("tcp", address) diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/api/baremetal/v1/baremetal_sdk.go b/vendor/github.com/scaleway/scaleway-sdk-go/api/baremetal/v1/baremetal_sdk.go index 968bf54287d..028b39e2391 100644 --- a/vendor/github.com/scaleway/scaleway-sdk-go/api/baremetal/v1/baremetal_sdk.go +++ b/vendor/github.com/scaleway/scaleway-sdk-go/api/baremetal/v1/baremetal_sdk.go @@ -704,10 +704,12 @@ type OS struct { ServiceUser *OSOSField `json:"service_user"` // ServicePassword: object defining the password requirements to install the service. ServicePassword *OSOSField `json:"service_password"` - // Enabled: state of OS. + // Enabled: defines if the operating system is enabled or not. Enabled bool `json:"enabled"` // LicenseRequired: license required (check server options for pricing details). LicenseRequired bool `json:"license_required"` + // Allowed: defines if a specific Organization is allowed to install this OS type. + Allowed bool `json:"allowed"` } type OSOSField struct { @@ -945,7 +947,7 @@ type Setting struct { // Type: type of the setting. // Default value: unknown Type SettingType `json:"type"` - // ProjectID: ID of the project ID. + // ProjectID: ID of the Project ID. ProjectID string `json:"project_id"` // Enabled: defines whether the setting is enabled. Enabled bool `json:"enabled"` @@ -982,8 +984,8 @@ type ListServersRequest struct { OptionID *string `json:"-"` } -// ListServers: list Elastic Metal servers for an organization. -// List Elastic Metal servers for a specific organization. +// ListServers: list Elastic Metal servers for an Organization. +// List Elastic Metal servers for a specific Organization. func (s *API) ListServers(req *ListServersRequest, opts ...scw.RequestOption) (*ListServersResponse, error) { var err error @@ -2000,12 +2002,12 @@ type ListSettingsRequest struct { // OrderBy: sort order for items in the response. // Default value: created_at_asc OrderBy ListSettingsRequestOrderBy `json:"-"` - // ProjectID: ID of the project. + // ProjectID: ID of the Project. ProjectID *string `json:"-"` } // ListSettings: list all settings. -// Return all settings for a project ID. +// Return all settings for a Project ID. func (s *API) ListSettings(req *ListSettingsRequest, opts ...scw.RequestOption) (*ListSettingsResponse, error) { var err error @@ -2055,7 +2057,7 @@ type UpdateSettingRequest struct { } // UpdateSetting: update setting. -// Update a setting for a project ID (enable or disable). +// Update a setting for a Project ID (enable or disable). func (s *API) UpdateSetting(req *UpdateSettingRequest, opts ...scw.RequestOption) (*Setting, error) { var err error @@ -2150,8 +2152,8 @@ type GetOSRequest struct { OsID string `json:"-"` } -// GetOS: get an OS with an ID. -// Return specific OS for the ID. +// GetOS: get OS with an ID. +// Return the specific OS for the ID. func (s *API) GetOS(req *GetOSRequest, opts ...scw.RequestOption) (*OS, error) { var err error diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/api/instance/v1/instance_sdk.go b/vendor/github.com/scaleway/scaleway-sdk-go/api/instance/v1/instance_sdk.go index 0f4ddab9c3e..593af4530a3 100644 --- a/vendor/github.com/scaleway/scaleway-sdk-go/api/instance/v1/instance_sdk.go +++ b/vendor/github.com/scaleway/scaleway-sdk-go/api/instance/v1/instance_sdk.go @@ -750,30 +750,30 @@ func (enum *VolumeVolumeType) UnmarshalJSON(data []byte) error { // Bootscript: bootscript. type Bootscript struct { - // Bootcmdargs: the bootscript arguments. + // Bootcmdargs: bootscript arguments. Bootcmdargs string `json:"bootcmdargs"` - // Default: dispmay if the bootscript is the default bootscript if no other boot option is configured. + // Default: display if the bootscript is the default bootscript (if no other boot option is configured). Default bool `json:"default"` - // Dtb: provide information regarding a Device Tree Binary (dtb) for use with C1 servers. + // Dtb: provide information regarding a Device Tree Binary (DTB) for use with C1 servers. Dtb string `json:"dtb"` - // ID: the bootscript ID. + // ID: bootscript ID. ID string `json:"id"` - // Initrd: the initrd (initial ramdisk) configuration. + // Initrd: initrd (initial ramdisk) configuration. Initrd string `json:"initrd"` - // Kernel: the server kernel version. + // Kernel: instance kernel version. Kernel string `json:"kernel"` - // Organization: the bootscript organization ID. + // Organization: bootscript Organization ID. Organization string `json:"organization"` - // Project: the bootscript project ID. + // Project: bootscript Project ID. Project string `json:"project"` // Public: provide information if the bootscript is public. Public bool `json:"public"` - // Title: the bootscript title. + // Title: bootscript title. Title string `json:"title"` - // Arch: the bootscript arch. + // Arch: bootscript architecture. // Default value: x86_64 Arch Arch `json:"arch"` - // Zone: the zone in which is the bootscript. + // Zone: zone in which the bootscript is located. Zone scw.Zone `json:"zone"` } @@ -871,7 +871,9 @@ type GetPlacementGroupResponse struct { PlacementGroup *PlacementGroup `json:"placement_group"` } +// GetPlacementGroupServersResponse: get placement group servers response. type GetPlacementGroupServersResponse struct { + // Servers: instances attached to the placement group. Servers []*PlacementGroupServer `json:"servers"` } @@ -1022,17 +1024,17 @@ type ListServerUserDataResponse struct { // ListServersResponse: list servers response. type ListServersResponse struct { - // TotalCount: total number of servers. + // TotalCount: total number of Instances. TotalCount uint32 `json:"total_count"` - // Servers: list of servers. + // Servers: list of Instances. Servers []*Server `json:"servers"` } // ListServersTypesResponse: list servers types response. type ListServersTypesResponse struct { - // TotalCount: total number of server types. + // TotalCount: total number of Instance types. TotalCount uint32 `json:"total_count"` - // Servers: list of server types. + // Servers: list of Instance types. Servers map[string]*ServerType `json:"servers"` } @@ -1068,17 +1070,17 @@ type NullableStringValue struct { // PlacementGroup: placement group. type PlacementGroup struct { - // ID: the placement group unique ID. + // ID: placement group unique ID. ID string `json:"id"` - // Name: the placement group name. + // Name: placement group name. Name string `json:"name"` - // Organization: the placement group organization ID. + // Organization: placement group Organization ID. Organization string `json:"organization"` - // Project: the placement group project ID. + // Project: placement group Project ID. Project string `json:"project"` - // Tags: the placement group tags. + // Tags: placement group tags. Tags []string `json:"tags"` - // PolicyMode: select the failling mode when the placement cannot be respected, either optional or enforced. + // PolicyMode: select the failure mode when the placement cannot be respected, either optional or enforced. // Default value: optional PolicyMode PlacementGroupPolicyMode `json:"policy_mode"` // PolicyType: select the behavior of the placement group, either low_latency (group) or max_availability (spread). @@ -1086,73 +1088,75 @@ type PlacementGroup struct { PolicyType PlacementGroupPolicyType `json:"policy_type"` // PolicyRespected: returns true if the policy is respected, false otherwise. PolicyRespected bool `json:"policy_respected"` - // Zone: the zone in which is the placement group. + // Zone: zone in which the placement group is located. Zone scw.Zone `json:"zone"` } +// PlacementGroupServer: placement group server. type PlacementGroupServer struct { + // ID: instance UUID. ID string `json:"id"` - + // Name: instance name. Name string `json:"name"` - + // PolicyRespected: defines whether the placement group policy is respected (either 1 or 0). PolicyRespected bool `json:"policy_respected"` } // PrivateNIC: private nic. type PrivateNIC struct { - // ID: the private NIC unique ID. + // ID: private NIC unique ID. ID string `json:"id,omitempty"` - // ServerID: the server the private NIC is attached to. + // ServerID: instance to which the private NIC is attached. ServerID string `json:"server_id,omitempty"` - // PrivateNetworkID: the private network where the private NIC is attached. + // PrivateNetworkID: private Network the private NIC is attached to. PrivateNetworkID string `json:"private_network_id,omitempty"` - // MacAddress: the private NIC MAC address. + // MacAddress: private NIC MAC address. MacAddress string `json:"mac_address,omitempty"` - // State: the private NIC state. + // State: private NIC state. // Default value: available State PrivateNICState `json:"state,omitempty"` - // Tags: the private NIC tags. + // Tags: private NIC tags. Tags []string `json:"tags,omitempty"` } // SecurityGroup: security group. type SecurityGroup struct { - // ID: the security groups' unique ID. + // ID: security group unique ID. ID string `json:"id"` - // Name: the security groups name. + // Name: security group name. Name string `json:"name"` - // Description: the security groups description. + // Description: security group description. Description string `json:"description"` - // EnableDefaultSecurity: true if SMTP is blocked on IPv4 and IPv6. + // EnableDefaultSecurity: true if SMTP is blocked on IPv4 and IPv6. This feature is read only, please open a support ticket if you need to make it configurable. EnableDefaultSecurity bool `json:"enable_default_security"` - // InboundDefaultPolicy: the default inbound policy. + // InboundDefaultPolicy: default inbound policy. // Default value: accept InboundDefaultPolicy SecurityGroupPolicy `json:"inbound_default_policy"` - // OutboundDefaultPolicy: the default outbound policy. + // OutboundDefaultPolicy: default outbound policy. // Default value: accept OutboundDefaultPolicy SecurityGroupPolicy `json:"outbound_default_policy"` - // Organization: the security groups organization ID. + // Organization: security group Organization ID. Organization string `json:"organization"` - // Project: the security group project ID. + // Project: security group Project ID. Project string `json:"project"` - // Tags: the security group tags. + // Tags: security group tags. Tags []string `json:"tags"` - // Deprecated: OrganizationDefault: true if it is your default security group for this organization ID. + // Deprecated: OrganizationDefault: true if it is your default security group for this Organization ID. OrganizationDefault *bool `json:"organization_default,omitempty"` - // ProjectDefault: true if it is your default security group for this project ID. + // ProjectDefault: true if it is your default security group for this Project ID. ProjectDefault bool `json:"project_default"` - // CreationDate: the security group creation date. + // CreationDate: security group creation date. CreationDate *time.Time `json:"creation_date"` - // ModificationDate: the security group modification date. + // ModificationDate: security group modification date. ModificationDate *time.Time `json:"modification_date"` - // Servers: list of servers attached to this security group. + // Servers: list of Instances attached to this security group. Servers []*ServerSummary `json:"servers"` - // Stateful: true if the security group is stateful. + // Stateful: defines whether the security group is stateful. Stateful bool `json:"stateful"` // State: security group state. // Default value: available State SecurityGroupState `json:"state"` - // Zone: the zone in which is the security group. + // Zone: zone in which the security group is located. Zone scw.Zone `json:"zone"` } @@ -1192,73 +1196,73 @@ type SecurityGroupTemplate struct { // Server: server. type Server struct { - // ID: the server unique ID. + // ID: instance unique ID. ID string `json:"id"` - // Name: the server name. + // Name: instance name. Name string `json:"name"` - // Organization: the server organization ID. + // Organization: instance Organization ID. Organization string `json:"organization"` - // Project: the server project ID. + // Project: instance Project ID. Project string `json:"project"` - // AllowedActions: provide as list of allowed actions on the server. + // AllowedActions: list of allowed actions on the Instance. AllowedActions []ServerAction `json:"allowed_actions"` - // Tags: the server associated tags. + // Tags: tags associated with the Instance. Tags []string `json:"tags"` - // CommercialType: the server commercial type (eg. GP1-M). + // CommercialType: instance commercial type (eg. GP1-M). CommercialType string `json:"commercial_type"` - // CreationDate: the server creation date. + // CreationDate: instance creation date. CreationDate *time.Time `json:"creation_date"` // DynamicIPRequired: true if a dynamic IP is required. DynamicIPRequired bool `json:"dynamic_ip_required"` // EnableIPv6: true if IPv6 is enabled. EnableIPv6 bool `json:"enable_ipv6"` - // Hostname: the server host name. + // Hostname: instance host name. Hostname string `json:"hostname"` - // Image: provide information on the server image. + // Image: information about the Instance image. Image *Image `json:"image"` - // Protected: the server protection option is activated. + // Protected: defines whether the Instance protection option is activated. Protected bool `json:"protected"` - // PrivateIP: the server private IP address. + // PrivateIP: private IP address of the Instance. PrivateIP *string `json:"private_ip"` // PublicIP: information about the public IP. PublicIP *ServerIP `json:"public_ip"` - // ModificationDate: the server modification date. + // ModificationDate: instance modification date. ModificationDate *time.Time `json:"modification_date"` - // State: the server state. + // State: instance state. // Default value: running State ServerState `json:"state"` - // Location: the server location. + // Location: instance location. Location *ServerLocation `json:"location"` - // IPv6: the server IPv6 address. + // IPv6: instance IPv6 address. IPv6 *ServerIPv6 `json:"ipv6"` - // Deprecated: Bootscript: the server bootscript. + // Deprecated: Bootscript: instance bootscript. Bootscript *Bootscript `json:"bootscript,omitempty"` - // BootType: the server boot type. + // BootType: instance boot type. // Default value: local BootType BootType `json:"boot_type"` - // Volumes: the server volumes. + // Volumes: instance volumes. Volumes map[string]*VolumeServer `json:"volumes"` - // SecurityGroup: the server security group. + // SecurityGroup: instance security group. SecurityGroup *SecurityGroupSummary `json:"security_group"` - // Maintenances: the server planned maintenances. + // Maintenances: instance planned maintenance. Maintenances []*ServerMaintenance `json:"maintenances"` - // StateDetail: the server state_detail. + // StateDetail: detailed information about the Instance state. StateDetail string `json:"state_detail"` - // Arch: the server arch. + // Arch: instance architecture. // Default value: x86_64 Arch Arch `json:"arch"` - // PlacementGroup: the server placement group. + // PlacementGroup: instance placement group. PlacementGroup *PlacementGroup `json:"placement_group"` - // PrivateNics: the server private NICs. + // PrivateNics: instance private NICs. PrivateNics []*PrivateNIC `json:"private_nics"` - // Zone: the zone in which is the server. + // Zone: zone in which the Instance is located. Zone scw.Zone `json:"zone"` } // ServerActionRequestVolumeBackupTemplate: server action request. volume backup template. type ServerActionRequestVolumeBackupTemplate struct { - // VolumeType: the snapshot's volume type. - // Overrides the volume_type of the snapshot for this volume. + // VolumeType: snapshot's volume type. + // Overrides the `volume_type` of the snapshot for this volume. // If omitted, the volume type of the original volume will be used. // Default value: unknown_volume_type VolumeType SnapshotVolumeType `json:"volume_type,omitempty"` @@ -1270,9 +1274,9 @@ type ServerActionResponse struct { // ServerIP: server. ip. type ServerIP struct { - // ID: the unique ID of the IP address. + // ID: unique ID of the IP address. ID string `json:"id"` - // Address: the server public IPv4 IP-Address. + // Address: instance public IPv4 IP-Address. Address net.IP `json:"address"` // Dynamic: true if the IP address is dynamic. Dynamic bool `json:"dynamic"` @@ -1280,11 +1284,11 @@ type ServerIP struct { // ServerIPv6: server. ipv6. type ServerIPv6 struct { - // Address: the server IPv6 IP-Address. + // Address: instance IPv6 IP-Address. Address net.IP `json:"address"` - // Gateway: the IPv6 IP-addresses gateway. + // Gateway: iPv6 IP-addresses gateway. Gateway net.IP `json:"gateway"` - // Netmask: the IPv6 IP-addresses CIDR netmask. + // Netmask: iPv6 IP-addresses CIDR netmask. Netmask string `json:"netmask"` } @@ -1316,7 +1320,7 @@ type ServerType struct { MonthlyPrice *float32 `json:"monthly_price,omitempty"` // HourlyPrice: hourly price in Euro. HourlyPrice float32 `json:"hourly_price"` - // AltNames: alternative instance name if any. + // AltNames: alternative Instance name, if any. AltNames []string `json:"alt_names"` // PerVolumeConstraint: additional volume constraints. PerVolumeConstraint *ServerTypeVolumeConstraintsByType `json:"per_volume_constraint"` @@ -1331,9 +1335,9 @@ type ServerType struct { // Arch: CPU architecture. // Default value: x86_64 Arch Arch `json:"arch"` - // Baremetal: true if it is a baremetal instance. + // Baremetal: true if it is a baremetal Instance. Baremetal bool `json:"baremetal"` - // Network: network available for the instance. + // Network: network available for the Instance. Network *ServerTypeNetwork `json:"network"` // Capabilities: capabilities. Capabilities *ServerTypeCapabilities `json:"capabilities"` @@ -1341,7 +1345,7 @@ type ServerType struct { // ServerTypeCapabilities: server type. capabilities. type ServerTypeCapabilities struct { - // BlockStorage: true if server supports block storage. + // BlockStorage: defines whether the Instance supports block storage. BlockStorage *bool `json:"block_storage"` // BootTypes: list of supported boot types. BootTypes []BootType `json:"boot_types"` @@ -1385,7 +1389,9 @@ type SetPlacementGroupResponse struct { PlacementGroup *PlacementGroup `json:"placement_group"` } +// SetPlacementGroupServersResponse: set placement group servers response. type SetPlacementGroupServersResponse struct { + // Servers: instances attached to the placement group. Servers []*PlacementGroupServer `json:"servers"` } @@ -1402,7 +1408,7 @@ type SetSecurityGroupRulesRequestRule struct { // Direction: direction the rule applies to. // Default value: inbound Direction SecurityGroupRuleDirection `json:"direction"` - // IPRange: the range of IP address this rules applies to. + // IPRange: range of IP addresses these rules apply to. IPRange scw.IPNet `json:"ip_range"` // DestPortFrom: beginning of the range of ports this rule applies to (inclusive). This value will be set to null if protocol is ICMP or ANY. DestPortFrom *uint32 `json:"dest_port_from"` @@ -1422,64 +1428,64 @@ type SetSecurityGroupRulesResponse struct { // Snapshot: snapshot. type Snapshot struct { - // ID: the snapshot ID. + // ID: snapshot ID. ID string `json:"id"` - // Name: the snapshot name. + // Name: snapshot name. Name string `json:"name"` - // Organization: the snapshot organization ID. + // Organization: snapshot Organization ID. Organization string `json:"organization"` - // Project: the snapshot project ID. + // Project: snapshot Project ID. Project string `json:"project"` - // Tags: the snapshot tags. + // Tags: snapshot tags. Tags []string `json:"tags"` - // VolumeType: the snapshot volume type. + // VolumeType: snapshot volume type. // Default value: l_ssd VolumeType VolumeVolumeType `json:"volume_type"` - // Size: the snapshot size. + // Size: snapshot size. Size scw.Size `json:"size"` - // State: the snapshot state. + // State: snapshot state. // Default value: available State SnapshotState `json:"state"` - // BaseVolume: the volume on which the snapshot is based on. + // BaseVolume: volume on which the snapshot is based on. BaseVolume *SnapshotBaseVolume `json:"base_volume"` - // CreationDate: the snapshot creation date. + // CreationDate: snapshot creation date. CreationDate *time.Time `json:"creation_date"` - // ModificationDate: the snapshot modification date. + // ModificationDate: snapshot modification date. ModificationDate *time.Time `json:"modification_date"` - // Zone: the snapshot zone. + // Zone: snapshot zone. Zone scw.Zone `json:"zone"` - // ErrorReason: the reason for the failed snapshot import. + // ErrorReason: reason for the failed snapshot import. ErrorReason *string `json:"error_reason"` } // SnapshotBaseVolume: snapshot. base volume. type SnapshotBaseVolume struct { - // ID: the volume ID on which the snapshot is based on. + // ID: volume ID on which the snapshot is based. ID string `json:"id"` - // Name: the volume name on which the snapshot is based on. + // Name: volume name on which the snapshot is based on. Name string `json:"name"` } // Task: task. type Task struct { - // ID: the unique ID of the task. + // ID: unique ID of the task. ID string `json:"id"` - // Description: the description of the task. + // Description: description of the task. Description string `json:"description"` - // Progress: the progress of the task in percent. + // Progress: progress of the task in percent. Progress int32 `json:"progress"` - // StartedAt: the task start date. + // StartedAt: task start date. StartedAt *time.Time `json:"started_at"` - // TerminatedAt: the task end date. + // TerminatedAt: task end date. TerminatedAt *time.Time `json:"terminated_at"` - // Status: the task status. + // Status: task status. // Default value: pending Status TaskStatus `json:"status"` HrefFrom string `json:"href_from"` HrefResult string `json:"href_result"` - // Zone: the zone in which is the task. + // Zone: zone in which the task is excecuted. Zone scw.Zone `json:"zone"` } @@ -1491,7 +1497,9 @@ type UpdatePlacementGroupResponse struct { PlacementGroup *PlacementGroup `json:"placement_group"` } +// UpdatePlacementGroupServersResponse: update placement group servers response. type UpdatePlacementGroupServersResponse struct { + // Servers: instances attached to the placement group. Servers []*PlacementGroupServer `json:"servers"` } @@ -1505,33 +1513,33 @@ type UpdateVolumeResponse struct { // Volume: volume. type Volume struct { - // ID: the volume unique ID. + // ID: volume unique ID. ID string `json:"id"` - // Name: the volume name. + // Name: volume name. Name string `json:"name"` // Deprecated: ExportURI: show the volume NBD export URI. ExportURI *string `json:"export_uri"` - // Size: the volume disk size. + // Size: volume disk size. Size scw.Size `json:"size"` - // VolumeType: the volume type. + // VolumeType: volume type. // Default value: l_ssd VolumeType VolumeVolumeType `json:"volume_type"` - // CreationDate: the volume creation date. + // CreationDate: volume creation date. CreationDate *time.Time `json:"creation_date"` - // ModificationDate: the volume modification date. + // ModificationDate: volume modification date. ModificationDate *time.Time `json:"modification_date"` - // Organization: the volume organization ID. + // Organization: volume Organization ID. Organization string `json:"organization"` - // Project: the volume project ID. + // Project: volume Project ID. Project string `json:"project"` - // Tags: the volume tags. + // Tags: volume tags. Tags []string `json:"tags"` - // Server: the server attached to the volume. + // Server: instance attached to the volume. Server *ServerSummary `json:"server"` - // State: the volume state. + // State: volume state. // Default value: available State VolumeState `json:"state"` - // Zone: the zone in which is the volume. + // Zone: zone in which the volume is located. Zone scw.Zone `json:"zone"` } @@ -1567,7 +1575,7 @@ type VolumeServer struct { type VolumeServerTemplate struct { // ID: UUID of the volume. ID string `json:"id,omitempty"` - // Boot: force the server to boot on this volume. + // Boot: force the Instance to boot on this volume. // Default value: false Boot bool `json:"boot,omitempty"` // Name: name of the volume. @@ -1577,7 +1585,7 @@ type VolumeServerTemplate struct { // VolumeType: type of the volume. // Default value: l_ssd VolumeType VolumeVolumeType `json:"volume_type,omitempty"` - // BaseSnapshot: the ID of the snapshot on which this volume will be based. + // BaseSnapshot: ID of the snapshot on which this volume will be based. BaseSnapshot string `json:"base_snapshot,omitempty"` // Organization: organization ID of the volume. Organization string `json:"organization,omitempty"` @@ -1674,7 +1682,7 @@ type GetServerTypesAvailabilityRequest struct { } // GetServerTypesAvailability: get availability. -// Get availability for all server types. +// Get availability for all Instance types. func (s *API) GetServerTypesAvailability(req *GetServerTypesAvailabilityRequest, opts ...scw.RequestOption) (*GetServerTypesAvailabilityResponse, error) { var err error @@ -1721,8 +1729,8 @@ type ListServersTypesRequest struct { Page *int32 `json:"-"` } -// ListServersTypes: list server types. -// Get server types technical details. +// ListServersTypes: list Instance types. +// List available Instance types and their technical details. func (s *API) ListServersTypes(req *ListServersTypesRequest, opts ...scw.RequestOption) (*ListServersTypesResponse, error) { var err error @@ -1769,8 +1777,8 @@ type ListVolumesTypesRequest struct { Page *int32 `json:"-"` } -// ListVolumesTypes: list volumes types. -// Get volumes technical details. +// ListVolumesTypes: list volume types. +// List all volume types and their technical details. func (s *API) ListVolumesTypes(req *ListVolumesTypesRequest, opts ...scw.RequestOption) (*ListVolumesTypesResponse, error) { var err error @@ -1816,31 +1824,32 @@ type ListServersRequest struct { PerPage *uint32 `json:"-"` // Page: a positive integer to choose the page to return. Page *int32 `json:"-"` - // Organization: list only servers of this organization ID. + // Organization: list only Instances of this Organization ID. Organization *string `json:"-"` - // Project: list only servers of this project ID. + // Project: list only Instances of this Project ID. Project *string `json:"-"` - // Name: filter servers by name (for eg. "server1" will return "server100" and "server1" but not "foo"). + // Name: filter Instances by name (eg. "server1" will return "server100" and "server1" but not "foo"). Name *string `json:"-"` - // PrivateIP: list servers by private_ip. + // PrivateIP: list Instances by private_ip. PrivateIP *net.IP `json:"-"` - // WithoutIP: list servers that are not attached to a public IP. + // WithoutIP: list Instances that are not attached to a public IP. WithoutIP *bool `json:"-"` - // CommercialType: list servers of this commercial type. + // CommercialType: list Instances of this commercial type. CommercialType *string `json:"-"` - // State: list servers in this state. + // State: list Instances in this state. // Default value: running State *ServerState `json:"-"` - // Tags: list servers with these exact tags (to filter with several tags, use commas to separate them). + // Tags: list Instances with these exact tags (to filter with several tags, use commas to separate them). Tags []string `json:"-"` - // PrivateNetwork: list servers in this Private Network. + // PrivateNetwork: list Instances in this Private Network. PrivateNetwork *string `json:"-"` // Order: define the order of the returned servers. // Default value: creation_date_desc Order ListServersRequestOrder `json:"-"` } -// ListServers: list all servers. +// ListServers: list all Instances. +// List all Instances in a specified Availability Zone, e.g. `fr-par-1`. func (s *API) ListServers(req *ListServersRequest, opts ...scw.RequestOption) (*ListServersResponse, error) { var err error @@ -1893,58 +1902,42 @@ func (s *API) ListServers(req *ListServersRequest, opts ...scw.RequestOption) (* type CreateServerRequest struct { // Zone: zone to target. If none is passed will use default zone from the config. Zone scw.Zone `json:"-"` - // Name: the server name. + // Name: instance name. Name string `json:"name,omitempty"` - // DynamicIPRequired: define if a dynamic IP is required for the instance. + // DynamicIPRequired: define if a dynamic IP is required for the Instance. DynamicIPRequired *bool `json:"dynamic_ip_required,omitempty"` - // CommercialType: define the server commercial type (i.e. GP1-S). + // CommercialType: define the Instance commercial type (i.e. GP1-S). CommercialType string `json:"commercial_type,omitempty"` - // Image: the server image ID or label. + // Image: instance image ID or label. Image string `json:"image,omitempty"` - // Volumes: the volumes attached to the server. + // Volumes: volumes attached to the server. Volumes map[string]*VolumeServerTemplate `json:"volumes,omitempty"` // EnableIPv6: true if IPv6 is enabled on the server. EnableIPv6 bool `json:"enable_ipv6,omitempty"` - // PublicIP: the ID of the reserved IP to attach to the server. + // PublicIP: ID of the reserved IP to attach to the server. PublicIP *string `json:"public_ip,omitempty"` - // BootType: the boot type to use. + // BootType: boot type to use. // Default value: local BootType *BootType `json:"boot_type,omitempty"` - // Deprecated: Bootscript: the bootscript ID to use when `boot_type` is set to `bootscript`. + // Deprecated: Bootscript: bootscript ID to use when `boot_type` is set to `bootscript`. Bootscript *string `json:"bootscript,omitempty"` - // Deprecated: Organization: the server organization ID. + // Deprecated: Organization: instance Organization ID. // Precisely one of Organization, Project must be set. Organization *string `json:"organization,omitempty"` - // Project: the server project ID. + // Project: instance Project ID. // Precisely one of Organization, Project must be set. Project *string `json:"project,omitempty"` - // Tags: the server tags. + // Tags: instance tags. Tags []string `json:"tags,omitempty"` - // SecurityGroup: the security group ID. + // SecurityGroup: security group ID. SecurityGroup *string `json:"security_group,omitempty"` - // PlacementGroup: placement group ID if server must be part of a placement group. + // PlacementGroup: placement group ID if Instance must be part of a placement group. PlacementGroup *string `json:"placement_group,omitempty"` } -// createServer: create a server. -// The `volumes` key is a dictionary composed of the volume position as key and the volume parameters as value. -// Depending of the volume parameters, you can achieve different behaviours : -// -// Create a volume from a snapshot of an image : -// Optional : `volume_type`, `size`, `boot`. -// If the `size` parameter is not set, the size of the volume will equal the size of the corresponding snapshot of the image. -// -// Attach an existing volume : -// Required : `id`, `name`. -// Optional : `boot`. -// -// Create an empty volume : -// Required : `name`, `volume_type`, `size`. -// Optional : `organization`, `project`, `boot`. -// -// Create a volume from a snapshot : -// Required : `base_snapshot`, `name`, `volume_type`. -// Optional : `organization`, `project`, `boot`. +// createServer: create an Instance. +// Create a new Instance of the specified commercial type in the specified zone. Pay attention to the volumes parameter, which takes an object which can be used in different ways to achieve different behaviors. +// Get more information in the [Technical Information](#technical-information) section of the introduction. func (s *API) createServer(req *CreateServerRequest, opts ...scw.RequestOption) (*CreateServerResponse, error) { var err error @@ -1998,8 +1991,8 @@ type DeleteServerRequest struct { ServerID string `json:"-"` } -// DeleteServer: delete a server. -// Delete a server with the given ID. +// DeleteServer: delete an Instance. +// Delete the Instance with the specified ID. func (s *API) DeleteServer(req *DeleteServerRequest, opts ...scw.RequestOption) error { var err error @@ -2032,12 +2025,12 @@ func (s *API) DeleteServer(req *DeleteServerRequest, opts ...scw.RequestOption) type GetServerRequest struct { // Zone: zone to target. If none is passed will use default zone from the config. Zone scw.Zone `json:"-"` - // ServerID: UUID of the server you want to get. + // ServerID: UUID of the Instance you want to get. ServerID string `json:"-"` } -// GetServer: get a server. -// Get the details of a specified Server. +// GetServer: get an Instance. +// Get the details of a specified Instance. func (s *API) GetServer(req *GetServerRequest, opts ...scw.RequestOption) (*GetServerResponse, error) { var err error @@ -2072,64 +2065,64 @@ func (s *API) GetServer(req *GetServerRequest, opts ...scw.RequestOption) (*GetS type setServerRequest struct { // Zone: zone to target. If none is passed will use default zone from the config. Zone scw.Zone `json:"-"` - // ID: the server unique ID. + // ID: instance unique ID. ID string `json:"-"` - // Name: the server name. + // Name: instance name. Name string `json:"name"` - // Organization: the server organization ID. + // Organization: instance Organization ID. Organization string `json:"organization"` - // Project: the server project ID. + // Project: instance Project ID. Project string `json:"project"` - // AllowedActions: provide as list of allowed actions on the server. + // AllowedActions: provide a list of allowed actions on the server. AllowedActions []ServerAction `json:"allowed_actions"` - // Tags: the server associated tags. + // Tags: tags associated with the Instance. Tags *[]string `json:"tags"` - // CommercialType: the server commercial type (eg. GP1-M). + // CommercialType: instance commercial type (eg. GP1-M). CommercialType string `json:"commercial_type"` - // CreationDate: the server creation date. + // CreationDate: instance creation date. CreationDate *time.Time `json:"creation_date"` // DynamicIPRequired: true if a dynamic IP is required. DynamicIPRequired bool `json:"dynamic_ip_required"` // EnableIPv6: true if IPv6 is enabled. EnableIPv6 bool `json:"enable_ipv6"` - // Hostname: the server host name. + // Hostname: instance host name. Hostname string `json:"hostname"` - // Image: provide information on the server image. + // Image: provide information on the Instance image. Image *Image `json:"image"` - // Protected: the server protection option is activated. + // Protected: instance protection option is activated. Protected bool `json:"protected"` - // PrivateIP: the server private IP address. + // PrivateIP: instance private IP address. PrivateIP *string `json:"private_ip"` // PublicIP: information about the public IP. PublicIP *ServerIP `json:"public_ip"` - // ModificationDate: the server modification date. + // ModificationDate: instance modification date. ModificationDate *time.Time `json:"modification_date"` - // State: the server state. + // State: instance state. // Default value: running State ServerState `json:"state"` - // Location: the server location. + // Location: instance location. Location *ServerLocation `json:"location"` - // IPv6: the server IPv6 address. + // IPv6: instance IPv6 address. IPv6 *ServerIPv6 `json:"ipv6"` - // Deprecated: Bootscript: the server bootscript. + // Deprecated: Bootscript: instance bootscript. Bootscript *Bootscript `json:"bootscript"` - // BootType: the server boot type. + // BootType: instance boot type. // Default value: local BootType BootType `json:"boot_type"` - // Volumes: the server volumes. + // Volumes: instance volumes. Volumes map[string]*Volume `json:"volumes"` - // SecurityGroup: the server security group. + // SecurityGroup: instance security group. SecurityGroup *SecurityGroupSummary `json:"security_group"` - // Maintenances: the server planned maintenances. + // Maintenances: instance planned maintenances. Maintenances []*ServerMaintenance `json:"maintenances"` - // StateDetail: the server state_detail. + // StateDetail: instance state_detail. StateDetail string `json:"state_detail"` - // Arch: the server arch. + // Arch: instance architecture (refers to the CPU architecture used for the Instance, e.g. x86_64, arm64). // Default value: x86_64 Arch Arch `json:"arch"` - // PlacementGroup: the server placement group. + // PlacementGroup: instance placement group. PlacementGroup *PlacementGroup `json:"placement_group"` - // PrivateNics: the server private NICs. + // PrivateNics: instance private NICs. PrivateNics []*PrivateNIC `json:"private_nics"` } @@ -2182,13 +2175,13 @@ func (s *API) setServer(req *setServerRequest, opts ...scw.RequestOption) (*setS type UpdateServerRequest struct { // Zone: zone to target. If none is passed will use default zone from the config. Zone scw.Zone `json:"-"` - // ServerID: UUID of the server. + // ServerID: UUID of the Instance. ServerID string `json:"-"` - // Name: name of the server. + // Name: name of the Instance. Name *string `json:"name,omitempty"` // BootType: default value: local BootType *BootType `json:"boot_type,omitempty"` - // Tags: tags of the server. + // Tags: tags of the Instance. Tags *[]string `json:"tags,omitempty"` Volumes *map[string]*VolumeServerTemplate `json:"volumes,omitempty"` @@ -2202,13 +2195,14 @@ type UpdateServerRequest struct { Protected *bool `json:"protected,omitempty"` SecurityGroup *SecurityGroupTemplate `json:"security_group,omitempty"` - // PlacementGroup: placement group ID if server must be part of a placement group. + // PlacementGroup: placement group ID if Instance must be part of a placement group. PlacementGroup *NullableStringValue `json:"placement_group,omitempty"` - // PrivateNics: the server private NICs. + // PrivateNics: instance private NICs. PrivateNics []*PrivateNIC `json:"private_nics,omitempty"` } -// updateServer: update a server. +// updateServer: update an Instance. +// Update the Instance information, such as name, boot mode, or tags. func (s *API) updateServer(req *UpdateServerRequest, opts ...scw.RequestOption) (*UpdateServerResponse, error) { var err error @@ -2252,8 +2246,8 @@ type ListServerActionsRequest struct { ServerID string `json:"-"` } -// ListServerActions: list server actions. -// List all actions that can currently be performed on a server. +// ListServerActions: list Instance actions. +// List all actions (e.g. power on, power off, reboot) that can currently be performed on an Instance. func (s *API) ListServerActions(req *ListServerActionsRequest, opts ...scw.RequestOption) (*ListServerActionsResponse, error) { var err error @@ -2288,13 +2282,13 @@ func (s *API) ListServerActions(req *ListServerActionsRequest, opts ...scw.Reque type ServerActionRequest struct { // Zone: zone to target. If none is passed will use default zone from the config. Zone scw.Zone `json:"-"` - // ServerID: UUID of the server. + // ServerID: UUID of the Instance. ServerID string `json:"-"` - // Action: the action to perform on the server. + // Action: action to perform on the Instance. // Default value: poweron Action ServerAction `json:"action"` - // Name: the name of the backup you want to create. - // The name of the backup you want to create. + // Name: name of the backup you want to create. + // Name of the backup you want to create. // This field should only be specified when performing a backup action. Name *string `json:"name,omitempty"` // Volumes: for each volume UUID, the snapshot parameters of the volume. @@ -2304,7 +2298,18 @@ type ServerActionRequest struct { } // ServerAction: perform action. -// Perform power related actions on a server. Be wary that when terminating a server, all the attached volumes (local *and* block storage) are deleted. So, if you want to keep your local volumes, you must use the `archive` action instead of `terminate`. And if you want to keep block-storage volumes, **you must** detach it beforehand you issue the `terminate` call. For more information, read the [Volumes](#volumes-7e8a39) documentation. +// Perform an action on an Instance. +// Available actions are: +// * `poweron`: Start a stopped Instance. +// * `poweroff`: Fully stop the Instance and release the hypervisor slot. +// * `stop_in_place`: Stop the Instance, but keep the slot on the hypervisor. +// * `reboot`: Stop the instance and restart it. +// * `backup`: Create an image with all the volumes of an Instance. +// * `terminate`: Delete the Instance along with all attached volumes. +// +// Keep in mind that terminating an Instance will result in the deletion of all attached volumes, including local and block storage. +// If you want to preserve your local volumes, you should use the `archive` action instead of `terminate`. Similarly, if you want to keep your block storage volumes, you must first detach them before issuing the `terminate` command. +// For more information, read the [Volumes](#path-volumes-list-volumes) documentation. func (s *API) ServerAction(req *ServerActionRequest, opts ...scw.RequestOption) (*ServerActionResponse, error) { var err error @@ -2344,12 +2349,12 @@ func (s *API) ServerAction(req *ServerActionRequest, opts ...scw.RequestOption) type ListServerUserDataRequest struct { // Zone: zone to target. If none is passed will use default zone from the config. Zone scw.Zone `json:"-"` - // ServerID: UUID of the server. + // ServerID: UUID of the Instance. ServerID string `json:"-"` } // ListServerUserData: list user data. -// List all user data keys registered on a given server. +// List all user data keys registered on a specified Instance. func (s *API) ListServerUserData(req *ListServerUserDataRequest, opts ...scw.RequestOption) (*ListServerUserDataResponse, error) { var err error @@ -2384,14 +2389,14 @@ func (s *API) ListServerUserData(req *ListServerUserDataRequest, opts ...scw.Req type DeleteServerUserDataRequest struct { // Zone: zone to target. If none is passed will use default zone from the config. Zone scw.Zone `json:"-"` - // ServerID: UUID of the server. + // ServerID: UUID of the Instance. ServerID string `json:"-"` // Key: key of the user data to delete. Key string `json:"-"` } // DeleteServerUserData: delete user data. -// Delete the given key from a server user data. +// Delete the specified key from an Instance's user data. func (s *API) DeleteServerUserData(req *DeleteServerUserDataRequest, opts ...scw.RequestOption) error { var err error @@ -2446,8 +2451,8 @@ type ListImagesRequest struct { Tags *string `json:"-"` } -// ListImages: list instance images. -// List all images available in an account. +// ListImages: list Instance images. +// List all existing Instance images. func (s *API) ListImages(req *ListImagesRequest, opts ...scw.RequestOption) (*ListImagesResponse, error) { var err error @@ -2498,8 +2503,8 @@ type GetImageRequest struct { ImageID string `json:"-"` } -// GetImage: get an instance image. -// Get details of an image with the given ID. +// GetImage: get an Instance image. +// Get details of an image with the specified ID. func (s *API) GetImage(req *GetImageRequest, opts ...scw.RequestOption) (*GetImageResponse, error) { var err error @@ -2551,13 +2556,14 @@ type CreateImageRequest struct { // Project: project ID of the image. // Precisely one of Organization, Project must be set. Project *string `json:"project,omitempty"` - // Tags: the tags of the image. + // Tags: tags of the image. Tags []string `json:"tags,omitempty"` // Public: true to create a public image. Public *bool `json:"public,omitempty"` } -// CreateImage: create an instance image. +// CreateImage: create an Instance image. +// Create an Instance image from the specified snapshot ID. func (s *API) CreateImage(req *CreateImageRequest, opts ...scw.RequestOption) (*CreateImageResponse, error) { var err error @@ -2692,8 +2698,8 @@ type DeleteImageRequest struct { ImageID string `json:"-"` } -// DeleteImage: delete an instance image. -// Delete the image with the given ID. +// DeleteImage: delete an Instance image. +// Delete the image with the specified ID. func (s *API) DeleteImage(req *DeleteImageRequest, opts ...scw.RequestOption) error { var err error @@ -2741,6 +2747,7 @@ type ListSnapshotsRequest struct { } // ListSnapshots: list snapshots. +// List all snapshots of an Organization in a specified Availability Zone. func (s *API) ListSnapshots(req *ListSnapshotsRequest, opts ...scw.RequestOption) (*ListSnapshotsResponse, error) { var err error @@ -2789,7 +2796,7 @@ type CreateSnapshotRequest struct { Name string `json:"name,omitempty"` // VolumeID: UUID of the volume. VolumeID *string `json:"volume_id,omitempty"` - // Tags: the tags of the snapshot. + // Tags: tags of the snapshot. Tags []string `json:"tags,omitempty"` // Deprecated: Organization: organization ID of the snapshot. // Precisely one of Organization, Project must be set. @@ -2797,7 +2804,7 @@ type CreateSnapshotRequest struct { // Project: project ID of the snapshot. // Precisely one of Organization, Project must be set. Project *string `json:"project,omitempty"` - // VolumeType: the volume type of the snapshot. + // VolumeType: volume type of the snapshot. // Overrides the volume_type of the snapshot. // If omitted, the volume type of the original volume will be used. // Default value: unknown_volume_type @@ -2810,7 +2817,8 @@ type CreateSnapshotRequest struct { Size *scw.Size `json:"size,omitempty"` } -// CreateSnapshot: create a snapshot from a given volume or from a QCOW2 file. +// CreateSnapshot: create a snapshot from a specified volume or from a QCOW2 file. +// Create a snapshot from a specified volume or from a QCOW2 file in a specified Availability Zone. func (s *API) CreateSnapshot(req *CreateSnapshotRequest, opts ...scw.RequestOption) (*CreateSnapshotResponse, error) { var err error @@ -2865,7 +2873,7 @@ type GetSnapshotRequest struct { } // GetSnapshot: get a snapshot. -// Get details of a snapshot with the given ID. +// Get details of a snapshot with the specified ID. func (s *API) GetSnapshot(req *GetSnapshotRequest, opts ...scw.RequestOption) (*GetSnapshotResponse, error) { var err error @@ -2982,7 +2990,7 @@ type DeleteSnapshotRequest struct { } // DeleteSnapshot: delete a snapshot. -// Delete the snapshot with the given ID. +// Delete the snapshot with the specified ID. func (s *API) DeleteSnapshot(req *DeleteSnapshotRequest, opts ...scw.RequestOption) error { var err error @@ -3015,7 +3023,7 @@ func (s *API) DeleteSnapshot(req *DeleteSnapshotRequest, opts ...scw.RequestOpti type ExportSnapshotRequest struct { // Zone: zone to target. If none is passed will use default zone from the config. Zone scw.Zone `json:"-"` - // SnapshotID: the snapshot ID. + // SnapshotID: snapshot ID. SnapshotID string `json:"-"` // Bucket: s3 bucket name. Bucket string `json:"bucket,omitempty"` @@ -3024,7 +3032,7 @@ type ExportSnapshotRequest struct { } // ExportSnapshot: export a snapshot. -// Export a snapshot to a given S3 bucket in the same region. +// Export a snapshot to a specified S3 bucket in the same region. func (s *API) ExportSnapshot(req *ExportSnapshotRequest, opts ...scw.RequestOption) (*ExportSnapshotResponse, error) { var err error @@ -3072,9 +3080,9 @@ type ListVolumesRequest struct { PerPage *uint32 `json:"-"` // Page: a positive integer to choose the page to return. Page *int32 `json:"-"` - // Organization: filter volume by organization ID. + // Organization: filter volume by Organization ID. Organization *string `json:"-"` - // Project: filter volume by project ID. + // Project: filter volume by Project ID. Project *string `json:"-"` // Tags: filter volumes with these exact tags (to filter with several tags, use commas to separate them). Tags []string `json:"-"` @@ -3083,6 +3091,7 @@ type ListVolumesRequest struct { } // ListVolumes: list volumes. +// List volumes in the specified Availability Zone. You can filter the output by volume type. func (s *API) ListVolumes(req *ListVolumesRequest, opts ...scw.RequestOption) (*ListVolumesResponse, error) { var err error @@ -3130,31 +3139,32 @@ func (s *API) ListVolumes(req *ListVolumesRequest, opts ...scw.RequestOption) (* type CreateVolumeRequest struct { // Zone: zone to target. If none is passed will use default zone from the config. Zone scw.Zone `json:"-"` - // Name: the volume name. + // Name: volume name. Name string `json:"name,omitempty"` - // Deprecated: Organization: the volume organization ID. + // Deprecated: Organization: volume Organization ID. // Precisely one of Organization, Project must be set. Organization *string `json:"organization,omitempty"` - // Project: the volume project ID. + // Project: volume Project ID. // Precisely one of Organization, Project must be set. Project *string `json:"project,omitempty"` - // Tags: the volume tags. + // Tags: volume tags. Tags []string `json:"tags,omitempty"` - // VolumeType: the volume type. + // VolumeType: volume type. // Default value: l_ssd VolumeType VolumeVolumeType `json:"volume_type"` - // Size: the volume disk size, must be a multiple of 512. + // Size: volume disk size, must be a multiple of 512. // Precisely one of BaseSnapshot, BaseVolume, Size must be set. Size *scw.Size `json:"size,omitempty"` - // BaseVolume: the ID of the volume on which this volume will be based. + // BaseVolume: ID of the volume on which this volume will be based. // Precisely one of BaseSnapshot, BaseVolume, Size must be set. BaseVolume *string `json:"base_volume,omitempty"` - // BaseSnapshot: the ID of the snapshot on which this volume will be based. + // BaseSnapshot: ID of the snapshot on which this volume will be based. // Precisely one of BaseSnapshot, BaseVolume, Size must be set. BaseSnapshot *string `json:"base_snapshot,omitempty"` } // CreateVolume: create a volume. +// Create a volume of a specified type in an Availability Zone. func (s *API) CreateVolume(req *CreateVolumeRequest, opts ...scw.RequestOption) (*CreateVolumeResponse, error) { var err error @@ -3209,7 +3219,7 @@ type GetVolumeRequest struct { } // GetVolume: get a volume. -// Get details of a volume with the given ID. +// Get details of a volume with the specified ID. func (s *API) GetVolume(req *GetVolumeRequest, opts ...scw.RequestOption) (*GetVolumeResponse, error) { var err error @@ -3246,16 +3256,16 @@ type UpdateVolumeRequest struct { Zone scw.Zone `json:"-"` // VolumeID: UUID of the volume. VolumeID string `json:"-"` - // Name: the volume name. + // Name: volume name. Name *string `json:"name,omitempty"` - // Tags: the tags of the volume. + // Tags: tags of the volume. Tags *[]string `json:"tags,omitempty"` - // Size: the volume disk size, must be a multiple of 512. + // Size: volume disk size, must be a multiple of 512. Size *scw.Size `json:"size,omitempty"` } // UpdateVolume: update a volume. -// Replace name and/or size properties of given ID volume with the given value(s). Any volume name can be changed while, for now, only `b_ssd` volume growing is supported. +// Replace the name and/or size properties of a volume specified by its ID, with the specified value(s). Any volume name can be changed, however only `b_ssd` volumes can currently be increased in size. func (s *API) UpdateVolume(req *UpdateVolumeRequest, opts ...scw.RequestOption) (*UpdateVolumeResponse, error) { var err error @@ -3300,7 +3310,7 @@ type DeleteVolumeRequest struct { } // DeleteVolume: delete a volume. -// Delete the volume with the given ID. +// Delete the volume with the specified ID. func (s *API) DeleteVolume(req *DeleteVolumeRequest, opts ...scw.RequestOption) error { var err error @@ -3335,9 +3345,9 @@ type ListSecurityGroupsRequest struct { Zone scw.Zone `json:"-"` // Name: name of the security group. Name *string `json:"-"` - // Organization: the security group organization ID. + // Organization: security group Organization ID. Organization *string `json:"-"` - // Project: the security group project ID. + // Project: security group Project ID. Project *string `json:"-"` // Tags: list security groups with these exact tags (to filter with several tags, use commas to separate them). Tags []string `json:"-"` @@ -3351,7 +3361,7 @@ type ListSecurityGroupsRequest struct { } // ListSecurityGroups: list security groups. -// List all security groups available in an account. +// List all existing security groups. func (s *API) ListSecurityGroups(req *ListSecurityGroupsRequest, opts ...scw.RequestOption) (*ListSecurityGroupsResponse, error) { var err error @@ -3409,13 +3419,13 @@ type CreateSecurityGroupRequest struct { // Project: project ID the security group belong to. // Precisely one of Organization, Project must be set. Project *string `json:"project,omitempty"` - // Tags: the tags of the security group. + // Tags: tags of the security group. Tags []string `json:"tags,omitempty"` - // Deprecated: OrganizationDefault: whether this security group becomes the default security group for new instances. + // Deprecated: OrganizationDefault: defines whether this security group becomes the default security group for new Instances. // Default value: false // Precisely one of OrganizationDefault, ProjectDefault must be set. OrganizationDefault *bool `json:"organization_default,omitempty"` - // ProjectDefault: whether this security group becomes the default security group for new instances. + // ProjectDefault: whether this security group becomes the default security group for new Instances. // Default value: false // Precisely one of OrganizationDefault, ProjectDefault must be set. ProjectDefault *bool `json:"project_default,omitempty"` @@ -3428,11 +3438,12 @@ type CreateSecurityGroupRequest struct { // OutboundDefaultPolicy: default policy for outbound rules. // Default value: accept OutboundDefaultPolicy SecurityGroupPolicy `json:"outbound_default_policy"` - // EnableDefaultSecurity: true to block SMTP on IPv4 and IPv6. + // EnableDefaultSecurity: true to block SMTP on IPv4 and IPv6. This feature is read only, please open a support ticket if you need to make it configurable. EnableDefaultSecurity *bool `json:"enable_default_security,omitempty"` } // CreateSecurityGroup: create a security group. +// Create a security group with a specified name and description. func (s *API) CreateSecurityGroup(req *CreateSecurityGroupRequest, opts ...scw.RequestOption) (*CreateSecurityGroupResponse, error) { var err error @@ -3487,7 +3498,7 @@ type GetSecurityGroupRequest struct { } // GetSecurityGroup: get a security group. -// Get the details of a Security Group with the given ID. +// Get the details of a security group with the specified ID. func (s *API) GetSecurityGroup(req *GetSecurityGroupRequest, opts ...scw.RequestOption) (*GetSecurityGroupResponse, error) { var err error @@ -3527,6 +3538,7 @@ type DeleteSecurityGroupRequest struct { } // DeleteSecurityGroup: delete a security group. +// Delete a security group with the specified ID. func (s *API) DeleteSecurityGroup(req *DeleteSecurityGroupRequest, opts ...scw.RequestOption) error { var err error @@ -3559,35 +3571,35 @@ func (s *API) DeleteSecurityGroup(req *DeleteSecurityGroupRequest, opts ...scw.R type setSecurityGroupRequest struct { // Zone: zone to target. If none is passed will use default zone from the config. Zone scw.Zone `json:"-"` - // ID: the ID of the security group (will be ignored). + // ID: ID of the security group (will be ignored). ID string `json:"-"` - // Name: the name of the security group. + // Name: name of the security group. Name string `json:"name"` - // Tags: the tags of the security group. + // Tags: tags of the security group. Tags *[]string `json:"tags"` - // CreationDate: the creation date of the security group (will be ignored). + // CreationDate: creation date of the security group (will be ignored). CreationDate *time.Time `json:"creation_date"` - // ModificationDate: the modification date of the security group (will be ignored). + // ModificationDate: modification date of the security group (will be ignored). ModificationDate *time.Time `json:"modification_date"` - // Description: the description of the security group. + // Description: description of the security group. Description string `json:"description"` - // EnableDefaultSecurity: true to block SMTP on IPv4 and IPv6. + // EnableDefaultSecurity: true to block SMTP on IPv4 and IPv6. This feature is read only, please open a support ticket if you need to make it configurable. EnableDefaultSecurity bool `json:"enable_default_security"` - // InboundDefaultPolicy: the default inbound policy. + // InboundDefaultPolicy: default inbound policy. // Default value: accept InboundDefaultPolicy SecurityGroupPolicy `json:"inbound_default_policy"` - // OutboundDefaultPolicy: the default outbound policy. + // OutboundDefaultPolicy: default outbound policy. // Default value: accept OutboundDefaultPolicy SecurityGroupPolicy `json:"outbound_default_policy"` - // Organization: the security groups organization ID. + // Organization: security groups Organization ID. Organization string `json:"organization"` - // Project: the security group project ID. + // Project: security group Project ID. Project string `json:"project"` // Deprecated: OrganizationDefault: please use project_default instead. OrganizationDefault *bool `json:"organization_default"` - // ProjectDefault: true use this security group for future instances created in this project. + // ProjectDefault: true use this security group for future Instances created in this project. ProjectDefault bool `json:"project_default"` - // Servers: the servers attached to this security group. + // Servers: instances attached to this security group. Servers []*ServerSummary `json:"servers"` // Stateful: true to set the security group as stateful. Stateful bool `json:"stateful"` @@ -3688,6 +3700,7 @@ type ListSecurityGroupRulesRequest struct { } // ListSecurityGroupRules: list rules. +// List the rules of the a specified security group ID. func (s *API) ListSecurityGroupRules(req *ListSecurityGroupRulesRequest, opts ...scw.RequestOption) (*ListSecurityGroupRulesResponse, error) { var err error @@ -3742,17 +3755,18 @@ type CreateSecurityGroupRuleRequest struct { Action SecurityGroupRuleAction `json:"action"` IPRange scw.IPNet `json:"ip_range,omitempty"` - // DestPortFrom: the beginning of the range of ports to apply this rule to (inclusive). + // DestPortFrom: beginning of the range of ports to apply this rule to (inclusive). DestPortFrom *uint32 `json:"dest_port_from,omitempty"` - // DestPortTo: the end of the range of ports to apply this rule to (inclusive). + // DestPortTo: end of the range of ports to apply this rule to (inclusive). DestPortTo *uint32 `json:"dest_port_to,omitempty"` - // Position: the position of this rule in the security group rules list. + // Position: position of this rule in the security group rules list. Position uint32 `json:"position,omitempty"` // Editable: indicates if this rule is editable (will be ignored). Editable bool `json:"editable,omitempty"` } // CreateSecurityGroupRule: create rule. +// Create a rule in the specified security group ID. func (s *API) CreateSecurityGroupRule(req *CreateSecurityGroupRuleRequest, opts ...scw.RequestOption) (*CreateSecurityGroupRuleResponse, error) { var err error @@ -3799,7 +3813,7 @@ type SetSecurityGroupRulesRequest struct { } // SetSecurityGroupRules: update all the rules of a security group. -// Replaces the rules of the security group with the rules provided. This endpoint supports the update of existing rules, creation of new rules and deletion of existing rules when they are not passed in the request. +// Replaces the existing rules of the security group with the rules provided. This endpoint supports the update of existing rules, creation of new rules and deletion of existing rules when they are not passed in the request. func (s *API) SetSecurityGroupRules(req *SetSecurityGroupRulesRequest, opts ...scw.RequestOption) (*SetSecurityGroupRulesResponse, error) { var err error @@ -3846,7 +3860,7 @@ type DeleteSecurityGroupRuleRequest struct { } // DeleteSecurityGroupRule: delete rule. -// Delete a security group rule with the given ID. +// Delete a security group rule with the specified ID. func (s *API) DeleteSecurityGroupRule(req *DeleteSecurityGroupRuleRequest, opts ...scw.RequestOption) error { var err error @@ -3890,7 +3904,7 @@ type GetSecurityGroupRuleRequest struct { } // GetSecurityGroupRule: get rule. -// Get details of a security group rule with the given ID. +// Get details of a security group rule with the specified ID. func (s *API) GetSecurityGroupRule(req *GetSecurityGroupRuleRequest, opts ...scw.RequestOption) (*GetSecurityGroupRuleResponse, error) { var err error @@ -3954,6 +3968,7 @@ type setSecurityGroupRuleRequest struct { } // setSecurityGroupRule: update security group rule. +// Update the rule of a specified security group ID. func (s *API) setSecurityGroupRule(req *setSecurityGroupRuleRequest, opts ...scw.RequestOption) (*setSecurityGroupRuleResponse, error) { var err error @@ -4002,9 +4017,9 @@ type ListPlacementGroupsRequest struct { PerPage *uint32 `json:"-"` // Page: a positive integer to choose the page to return. Page *int32 `json:"-"` - // Organization: list only placement groups of this organization ID. + // Organization: list only placement groups of this Organization ID. Organization *string `json:"-"` - // Project: list only placement groups of this project ID. + // Project: list only placement groups of this Project ID. Project *string `json:"-"` // Tags: list placement groups with these exact tags (to filter with several tags, use commas to separate them). Tags []string `json:"-"` @@ -4013,7 +4028,7 @@ type ListPlacementGroupsRequest struct { } // ListPlacementGroups: list placement groups. -// List all placement groups. +// List all placement groups in a specified Availability Zone. func (s *API) ListPlacementGroups(req *ListPlacementGroupsRequest, opts ...scw.RequestOption) (*ListPlacementGroupsResponse, error) { var err error @@ -4068,18 +4083,18 @@ type CreatePlacementGroupRequest struct { // Project: project ID of the placement group. // Precisely one of Organization, Project must be set. Project *string `json:"project,omitempty"` - // Tags: the tags of the placement group. + // Tags: tags of the placement group. Tags []string `json:"tags,omitempty"` - // PolicyMode: the operating mode of the placement group. + // PolicyMode: operating mode of the placement group. // Default value: optional PolicyMode PlacementGroupPolicyMode `json:"policy_mode"` - // PolicyType: the policy type of the placement group. + // PolicyType: policy type of the placement group. // Default value: max_availability PolicyType PlacementGroupPolicyType `json:"policy_type"` } // CreatePlacementGroup: create a placement group. -// Create a new placement group. +// Create a new placement group in a specified Availability Zone. func (s *API) CreatePlacementGroup(req *CreatePlacementGroupRequest, opts ...scw.RequestOption) (*CreatePlacementGroupResponse, error) { var err error @@ -4134,7 +4149,7 @@ type GetPlacementGroupRequest struct { } // GetPlacementGroup: get a placement group. -// Get the given placement group. +// Get the specified placement group. func (s *API) GetPlacementGroup(req *GetPlacementGroupRequest, opts ...scw.RequestOption) (*GetPlacementGroupResponse, error) { var err error @@ -4186,7 +4201,7 @@ type SetPlacementGroupRequest struct { } // SetPlacementGroup: set placement group. -// Set all parameters of the given placement group. +// Set all parameters of the specified placement group. func (s *API) SetPlacementGroup(req *SetPlacementGroupRequest, opts ...scw.RequestOption) (*SetPlacementGroupResponse, error) { var err error @@ -4240,18 +4255,18 @@ type UpdatePlacementGroupRequest struct { PlacementGroupID string `json:"-"` // Name: name of the placement group. Name *string `json:"name,omitempty"` - // Tags: the tags of the placement group. + // Tags: tags of the placement group. Tags *[]string `json:"tags,omitempty"` - // PolicyMode: the operating mode of the placement group. + // PolicyMode: operating mode of the placement group. // Default value: optional PolicyMode *PlacementGroupPolicyMode `json:"policy_mode,omitempty"` - // PolicyType: the policy type of the placement group. + // PolicyType: policy type of the placement group. // Default value: max_availability PolicyType *PlacementGroupPolicyType `json:"policy_type,omitempty"` } // UpdatePlacementGroup: update a placement group. -// Update one or more parameter of the given placement group. +// Update one or more parameter of the specified placement group. func (s *API) UpdatePlacementGroup(req *UpdatePlacementGroupRequest, opts ...scw.RequestOption) (*UpdatePlacementGroupResponse, error) { var err error @@ -4295,7 +4310,7 @@ type DeletePlacementGroupRequest struct { PlacementGroupID string `json:"-"` } -// DeletePlacementGroup: delete the given placement group. +// DeletePlacementGroup: delete the specified placement group. func (s *API) DeletePlacementGroup(req *DeletePlacementGroupRequest, opts ...scw.RequestOption) error { var err error @@ -4328,12 +4343,12 @@ func (s *API) DeletePlacementGroup(req *DeletePlacementGroupRequest, opts ...scw type GetPlacementGroupServersRequest struct { // Zone: zone to target. If none is passed will use default zone from the config. Zone scw.Zone `json:"-"` - + // PlacementGroupID: UUID of the placement group you want to get. PlacementGroupID string `json:"-"` } // GetPlacementGroupServers: get placement group servers. -// Get all servers belonging to the given placement group. +// Get all Instances belonging to the specified placement group. func (s *API) GetPlacementGroupServers(req *GetPlacementGroupServersRequest, opts ...scw.RequestOption) (*GetPlacementGroupServersResponse, error) { var err error @@ -4368,14 +4383,14 @@ func (s *API) GetPlacementGroupServers(req *GetPlacementGroupServersRequest, opt type SetPlacementGroupServersRequest struct { // Zone: zone to target. If none is passed will use default zone from the config. Zone scw.Zone `json:"-"` - + // PlacementGroupID: UUID of the placement group you want to set. PlacementGroupID string `json:"-"` - + // Servers: an array of the Instances' UUIDs you want to configure. Servers []string `json:"servers"` } // SetPlacementGroupServers: set placement group servers. -// Set all servers belonging to the given placement group. +// Set all Instances belonging to the specified placement group. func (s *API) SetPlacementGroupServers(req *SetPlacementGroupServersRequest, opts ...scw.RequestOption) (*SetPlacementGroupServersResponse, error) { var err error @@ -4415,14 +4430,14 @@ func (s *API) SetPlacementGroupServers(req *SetPlacementGroupServersRequest, opt type UpdatePlacementGroupServersRequest struct { // Zone: zone to target. If none is passed will use default zone from the config. Zone scw.Zone `json:"-"` - // PlacementGroupID: UUID of the placement group. + // PlacementGroupID: UUID of the placement group you want to update. PlacementGroupID string `json:"-"` - + // Servers: an array of the Instances' UUIDs you want to configure. Servers []string `json:"servers,omitempty"` } // UpdatePlacementGroupServers: update placement group servers. -// Update all servers belonging to the given placement group. +// Update all Instances belonging to the specified placement group. func (s *API) UpdatePlacementGroupServers(req *UpdatePlacementGroupServersRequest, opts ...scw.RequestOption) (*UpdatePlacementGroupServersResponse, error) { var err error @@ -4462,9 +4477,9 @@ func (s *API) UpdatePlacementGroupServers(req *UpdatePlacementGroupServersReques type ListIPsRequest struct { // Zone: zone to target. If none is passed will use default zone from the config. Zone scw.Zone `json:"-"` - // Project: the project ID the IPs are reserved in. + // Project: project ID in which the IPs are reserved. Project *string `json:"-"` - // Organization: the organization ID the IPs are reserved in. + // Organization: organization ID in which the IPs are reserved. Organization *string `json:"-"` // Tags: filter IPs with these exact tags (to filter with several tags, use commas to separate them). Tags []string `json:"-"` @@ -4478,6 +4493,7 @@ type ListIPsRequest struct { } // ListIPs: list all flexible IPs. +// List all flexible IPs in a specified zone. func (s *API) ListIPs(req *ListIPsRequest, opts ...scw.RequestOption) (*ListIPsResponse, error) { var err error @@ -4524,19 +4540,20 @@ func (s *API) ListIPs(req *ListIPsRequest, opts ...scw.RequestOption) (*ListIPsR type CreateIPRequest struct { // Zone: zone to target. If none is passed will use default zone from the config. Zone scw.Zone `json:"-"` - // Deprecated: Organization: the organization ID the IP is reserved in. + // Deprecated: Organization: organization ID in which the IP is reserved. // Precisely one of Organization, Project must be set. Organization *string `json:"organization,omitempty"` - // Project: the project ID the IP is reserved in. + // Project: project ID in which the IP is reserved. // Precisely one of Organization, Project must be set. Project *string `json:"project,omitempty"` - // Tags: the tags of the IP. + // Tags: tags of the IP. Tags []string `json:"tags,omitempty"` - // Server: UUID of the server you want to attach the IP to. + // Server: UUID of the Instance you want to attach the IP to. Server *string `json:"server,omitempty"` } // CreateIP: reserve a flexible IP. +// Reserve a flexible IP and attach it to the specified Instance. func (s *API) CreateIP(req *CreateIPRequest, opts ...scw.RequestOption) (*CreateIPResponse, error) { var err error @@ -4582,12 +4599,12 @@ func (s *API) CreateIP(req *CreateIPRequest, opts ...scw.RequestOption) (*Create type GetIPRequest struct { // Zone: zone to target. If none is passed will use default zone from the config. Zone scw.Zone `json:"-"` - // IP: the IP ID or address to get. + // IP: IP ID or address to get. IP string `json:"-"` } // GetIP: get a flexible IP. -// Get details of an IP with the given ID or address. +// Get details of an IP with the specified ID or address. func (s *API) GetIP(req *GetIPRequest, opts ...scw.RequestOption) (*GetIPResponse, error) { var err error @@ -4633,6 +4650,7 @@ type UpdateIPRequest struct { } // UpdateIP: update a flexible IP. +// Update a flexible IP in the specified zone with the specified ID. func (s *API) UpdateIP(req *UpdateIPRequest, opts ...scw.RequestOption) (*UpdateIPResponse, error) { var err error @@ -4672,12 +4690,12 @@ func (s *API) UpdateIP(req *UpdateIPRequest, opts ...scw.RequestOption) (*Update type DeleteIPRequest struct { // Zone: zone to target. If none is passed will use default zone from the config. Zone scw.Zone `json:"-"` - // IP: the ID or the address of the IP to delete. + // IP: ID or address of the IP to delete. IP string `json:"-"` } // DeleteIP: delete a flexible IP. -// Delete the IP with the given ID. +// Delete the IP with the specified ID. func (s *API) DeleteIP(req *DeleteIPRequest, opts ...scw.RequestOption) error { var err error @@ -4710,9 +4728,9 @@ func (s *API) DeleteIP(req *DeleteIPRequest, opts ...scw.RequestOption) error { type ListPrivateNICsRequest struct { // Zone: zone to target. If none is passed will use default zone from the config. Zone scw.Zone `json:"-"` - // ServerID: the server the private NIC is attached to. + // ServerID: instance to which the private NIC is attached. ServerID string `json:"-"` - // Tags: the private NIC tags. + // Tags: private NIC tags. Tags []string `json:"-"` // PerPage: a positive integer lower or equal to 100 to select the number of items to return. // Default value: 50 @@ -4722,7 +4740,7 @@ type ListPrivateNICsRequest struct { } // ListPrivateNICs: list all private NICs. -// List all private NICs of a given server. +// List all private NICs of a specified Instance. func (s *API) ListPrivateNICs(req *ListPrivateNICsRequest, opts ...scw.RequestOption) (*ListPrivateNICsResponse, error) { var err error @@ -4770,15 +4788,15 @@ func (s *API) ListPrivateNICs(req *ListPrivateNICsRequest, opts ...scw.RequestOp type CreatePrivateNICRequest struct { // Zone: zone to target. If none is passed will use default zone from the config. Zone scw.Zone `json:"-"` - // ServerID: UUID of the server the private NIC will be attached to. + // ServerID: UUID of the Instance the private NIC will be attached to. ServerID string `json:"-"` // PrivateNetworkID: UUID of the private network where the private NIC will be attached. PrivateNetworkID string `json:"private_network_id,omitempty"` - // Tags: the private NIC tags. + // Tags: private NIC tags. Tags []string `json:"tags,omitempty"` } -// CreatePrivateNIC: create a private NIC connecting a server to a private network. +// CreatePrivateNIC: create a private NIC connecting an Instance to a Private Network. func (s *API) CreatePrivateNIC(req *CreatePrivateNICRequest, opts ...scw.RequestOption) (*CreatePrivateNICResponse, error) { var err error @@ -4818,9 +4836,9 @@ func (s *API) CreatePrivateNIC(req *CreatePrivateNICRequest, opts ...scw.Request type GetPrivateNICRequest struct { // Zone: zone to target. If none is passed will use default zone from the config. Zone scw.Zone `json:"-"` - // ServerID: the server the private NIC is attached to. + // ServerID: instance to which the private NIC is attached. ServerID string `json:"-"` - // PrivateNicID: the private NIC unique ID. + // PrivateNicID: private NIC unique ID. PrivateNicID string `json:"-"` } @@ -4864,16 +4882,16 @@ func (s *API) GetPrivateNIC(req *GetPrivateNICRequest, opts ...scw.RequestOption type UpdatePrivateNICRequest struct { // Zone: zone to target. If none is passed will use default zone from the config. Zone scw.Zone `json:"-"` - // ServerID: UUID of the server the private NIC will be attached to. + // ServerID: UUID of the Instance the private NIC will be attached to. ServerID string `json:"-"` - // PrivateNicID: the private NIC unique ID. + // PrivateNicID: private NIC unique ID. PrivateNicID string `json:"-"` // Tags: tags used to select private NIC/s. Tags *[]string `json:"tags,omitempty"` } // UpdatePrivateNIC: update a private NIC. -// Update one or more parameter/s to a given private NIC. +// Update one or more parameter(s) of a specified private NIC. func (s *API) UpdatePrivateNIC(req *UpdatePrivateNICRequest, opts ...scw.RequestOption) (*PrivateNIC, error) { var err error @@ -4917,9 +4935,9 @@ func (s *API) UpdatePrivateNIC(req *UpdatePrivateNICRequest, opts ...scw.Request type DeletePrivateNICRequest struct { // Zone: zone to target. If none is passed will use default zone from the config. Zone scw.Zone `json:"-"` - // ServerID: the server the private NIC is attached to. + // ServerID: instance to which the private NIC is attached. ServerID string `json:"-"` - // PrivateNicID: the private NIC unique ID. + // PrivateNicID: private NIC unique ID. PrivateNicID string `json:"-"` } @@ -5024,7 +5042,7 @@ type GetBootscriptRequest struct { } // Deprecated: GetBootscript: get bootscripts. -// Get details of a bootscript with the given ID. +// Get details of a bootscript with the specified ID. func (s *API) GetBootscript(req *GetBootscriptRequest, opts ...scw.RequestOption) (*GetBootscriptResponse, error) { var err error diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/internal/auth/access_key.go b/vendor/github.com/scaleway/scaleway-sdk-go/internal/auth/access_key.go new file mode 100644 index 00000000000..4f6b14d358f --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/internal/auth/access_key.go @@ -0,0 +1,21 @@ +package auth + +import "net/http" + +type AccessKeyOnly struct { + // auth config may contain an access key without being authenticated + AccessKey string +} + +// NewNoAuth return an auth with no authentication method +func NewAccessKeyOnly(accessKey string) *AccessKeyOnly { + return &AccessKeyOnly{accessKey} +} + +func (t *AccessKeyOnly) Headers() http.Header { + return http.Header{} +} + +func (t *AccessKeyOnly) AnonymizedHeaders() http.Header { + return http.Header{} +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/internal/auth/auth.go b/vendor/github.com/scaleway/scaleway-sdk-go/internal/auth/auth.go index f7ee31fcb0a..527504687b9 100644 --- a/vendor/github.com/scaleway/scaleway-sdk-go/internal/auth/auth.go +++ b/vendor/github.com/scaleway/scaleway-sdk-go/internal/auth/auth.go @@ -12,3 +12,18 @@ type Auth interface { // This method could be use for logging purpose. AnonymizedHeaders() http.Header } + +type headerAnonymizer func(header http.Header) http.Header + +var headerAnonymizers = []headerAnonymizer{ + AnonymizeTokenHeaders, + AnonymizeJWTHeaders, +} + +func AnonymizeHeaders(headers http.Header) http.Header { + for _, anonymizer := range headerAnonymizers { + headers = anonymizer(headers) + } + + return headers +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/internal/auth/jwt.go b/vendor/github.com/scaleway/scaleway-sdk-go/internal/auth/jwt.go new file mode 100644 index 00000000000..19c81d413f1 --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/internal/auth/jwt.go @@ -0,0 +1,55 @@ +package auth + +import ( + "net/http" + "strings" +) + +// JWT is the session token used in browser. +type JWT struct { + Token string +} + +// XSessionTokenHeader is Scaleway auth header for browser +const XSessionTokenHeader = "x-session-token" // #nosec G101 + +// NewJWT create a token authentication from a jwt +func NewJWT(token string) *JWT { + return &JWT{Token: token} +} + +// Headers returns headers that must be added to the http request +func (j *JWT) Headers() http.Header { + headers := http.Header{} + headers.Set(XSessionTokenHeader, j.Token) + return headers +} + +func AnonymizeJWTHeaders(headers http.Header) http.Header { + token := headers.Get(XSessionTokenHeader) + + if token != "" { + headers.Set(XSessionTokenHeader, HideJWT(token)) + } + + return headers +} + +// AnonymizedHeaders returns an anonymized version of Headers() +// This method could be used for logging purpose. +func (j *JWT) AnonymizedHeaders() http.Header { + return AnonymizeJWTHeaders(j.Headers()) +} + +func HideJWT(token string) string { + if len(token) == 0 { + return "" + } + // token should be (header).(payload).(signature) + lastDot := strings.LastIndex(token, ".") + if lastDot != -1 { + token = token[:lastDot] + } + + return token +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/internal/generic/fields.go b/vendor/github.com/scaleway/scaleway-sdk-go/internal/generic/fields.go new file mode 100644 index 00000000000..dc8011aec74 --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/internal/generic/fields.go @@ -0,0 +1,17 @@ +package generic + +import "reflect" + +// HasField returns true if given struct has a field with given name +// Also allow a slice, it will use the underlying type +func HasField(i interface{}, fieldName string) bool { + value := reflect.Indirect(reflect.ValueOf(i)) + typ := value.Type() + + if value.Kind() == reflect.Slice { + typ = indirectType(typ.Elem()) + } + + _, fieldExists := typ.FieldByName(fieldName) + return fieldExists +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/internal/generic/ptr.go b/vendor/github.com/scaleway/scaleway-sdk-go/internal/generic/ptr.go new file mode 100644 index 00000000000..a7c932058a8 --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/internal/generic/ptr.go @@ -0,0 +1,11 @@ +package generic + +import "reflect" + +func indirectType(typ reflect.Type) reflect.Type { + if typ.Kind() == reflect.Ptr { + return typ.Elem() + } + + return typ +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/scw/client.go b/vendor/github.com/scaleway/scaleway-sdk-go/scw/client.go index 6bff81eea92..01f3fa79a4c 100644 --- a/vendor/github.com/scaleway/scaleway-sdk-go/scw/client.go +++ b/vendor/github.com/scaleway/scaleway-sdk-go/scw/client.go @@ -141,7 +141,10 @@ func (c *Client) GetSecretKey() (secretKey string, exists bool) { func (c *Client) GetAccessKey() (accessKey string, exists bool) { if token, isToken := c.auth.(*auth.Token); isToken { return token.AccessKey, isToken + } else if token, isAccessKey := c.auth.(*auth.AccessKeyOnly); isAccessKey { + return token.AccessKey, isAccessKey } + return "", false } @@ -232,13 +235,12 @@ func (c *Client) do(req *ScalewayRequest, res interface{}) (sdkErr error) { if res != nil { contentType := httpResponse.Header.Get("Content-Type") - switch contentType { - case "application/json": + if strings.HasPrefix(contentType, "application/json") { err = json.NewDecoder(httpResponse.Body).Decode(&res) if err != nil { return errors.Wrap(err, "could not parse %s response body", contentType) } - default: + } else { buffer, isBuffer := res.(io.Writer) if !isBuffer { return errors.Wrap(err, "could not handle %s response body with %T result type", contentType, buffer) @@ -470,6 +472,10 @@ func (c *Client) doListRegions(req *ScalewayRequest, res interface{}, regions [] // sortSliceByZones sorts a slice of struct using a Zone field that should exist func sortSliceByZones(list interface{}, zones []Zone) { + if !generic.HasField(list, "Zone") { + return + } + zoneMap := map[Zone]int{} for i, zone := range zones { zoneMap[zone] = i @@ -481,6 +487,10 @@ func sortSliceByZones(list interface{}, zones []Zone) { // sortSliceByRegions sorts a slice of struct using a Region field that should exist func sortSliceByRegions(list interface{}, regions []Region) { + if !generic.HasField(list, "Region") { + return + } + regionMap := map[Region]int{} for i, region := range regions { regionMap[region] = i diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/scw/client_option.go b/vendor/github.com/scaleway/scaleway-sdk-go/scw/client_option.go index 73b1df24d38..482259c610f 100644 --- a/vendor/github.com/scaleway/scaleway-sdk-go/scw/client_option.go +++ b/vendor/github.com/scaleway/scaleway-sdk-go/scw/client_option.go @@ -38,6 +38,13 @@ func WithAuth(accessKey, secretKey string) ClientOption { } } +// WithJWT client option sets the client session token. +func WithJWT(token string) ClientOption { + return func(s *settings) { + s.token = auth.NewJWT(token) + } +} + // WithAPIURL client option overrides the API URL of the Scaleway API to the given URL. func WithAPIURL(apiURL string) ClientOption { return func(s *settings) { @@ -75,6 +82,7 @@ func WithProfile(p *Profile) ClientOption { accessKey := "" if p.AccessKey != nil { accessKey = *p.AccessKey + s.token = auth.NewAccessKeyOnly(accessKey) } if p.SecretKey != nil { @@ -111,7 +119,7 @@ func WithProfile(p *Profile) ClientOption { } } -// WithProfile client option configures a client from the environment variables. +// WithEnv client option configures a client from the environment variables. func WithEnv() ClientOption { return WithProfile(LoadEnvProfile()) } diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/scw/errors.go b/vendor/github.com/scaleway/scaleway-sdk-go/scw/errors.go index 4a5c6c1fd6c..3563b0de91c 100644 --- a/vendor/github.com/scaleway/scaleway-sdk-go/scw/errors.go +++ b/vendor/github.com/scaleway/scaleway-sdk-go/scw/errors.go @@ -102,7 +102,8 @@ func hasResponseError(res *http.Response) error { newErr.RawBody = body // The error content is not encoded in JSON, only returns HTTP data. - if res.Header.Get("Content-Type") != "application/json" { + contentType := res.Header.Get("Content-Type") + if !strings.HasPrefix(contentType, "application/json") { newErr.Message = res.Status return newErr } diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/scw/request.go b/vendor/github.com/scaleway/scaleway-sdk-go/scw/request.go index b9e57516b5e..a8832fd704b 100644 --- a/vendor/github.com/scaleway/scaleway-sdk-go/scw/request.go +++ b/vendor/github.com/scaleway/scaleway-sdk-go/scw/request.go @@ -28,29 +28,6 @@ type ScalewayRequest struct { regions []Region } -// getAllHeaders constructs a http.Header object and aggregates all headers into the object. -func (req *ScalewayRequest) getAllHeaders(token auth.Auth, userAgent string, anonymized bool) http.Header { - var allHeaders http.Header - if anonymized { - allHeaders = token.AnonymizedHeaders() - } else { - allHeaders = token.Headers() - } - - allHeaders.Set("User-Agent", userAgent) - if req.Body != nil { - allHeaders.Set("Content-Type", "application/json") - } - for key, value := range req.Headers { - allHeaders.Del(key) - for _, v := range value { - allHeaders.Add(key, v) - } - } - - return allHeaders -} - // getURL constructs a URL based on the base url and the client. func (req *ScalewayRequest) getURL(baseURL string) (*url.URL, error) { url, err := url.Parse(baseURL + req.Path) diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/scw/request_header.go b/vendor/github.com/scaleway/scaleway-sdk-go/scw/request_header.go new file mode 100644 index 00000000000..9a083be2d1f --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/scw/request_header.go @@ -0,0 +1,32 @@ +//go:build !wasm || !js + +package scw + +import ( + "net/http" + + "github.com/scaleway/scaleway-sdk-go/internal/auth" +) + +// getAllHeaders constructs a http.Header object and aggregates all headers into the object. +func (req *ScalewayRequest) getAllHeaders(token auth.Auth, userAgent string, anonymized bool) http.Header { + var allHeaders http.Header + if anonymized { + allHeaders = token.AnonymizedHeaders() + } else { + allHeaders = token.Headers() + } + + allHeaders.Set("User-Agent", userAgent) + if req.Body != nil { + allHeaders.Set("Content-Type", "application/json") + } + for key, value := range req.Headers { + allHeaders.Del(key) + for _, v := range value { + allHeaders.Add(key, v) + } + } + + return allHeaders +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/scw/request_header_wasm.go b/vendor/github.com/scaleway/scaleway-sdk-go/scw/request_header_wasm.go new file mode 100644 index 00000000000..662cc7bde60 --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/scw/request_header_wasm.go @@ -0,0 +1,32 @@ +//go:build wasm && js + +package scw + +import ( + "net/http" + + "github.com/scaleway/scaleway-sdk-go/internal/auth" +) + +// getAllHeaders constructs a http.Header object and aggregates all headers into the object. +func (req *ScalewayRequest) getAllHeaders(token auth.Auth, userAgent string, anonymized bool) http.Header { + var allHeaders http.Header + if anonymized { + allHeaders = token.AnonymizedHeaders() + } else { + allHeaders = token.Headers() + } + + allHeaders.Set("X-User-Agent", userAgent) + if req.Body != nil { + allHeaders.Set("Content-Type", "application/json") + } + for key, value := range req.Headers { + allHeaders.Del(key) + for _, v := range value { + allHeaders.Add(key, v) + } + } + + return allHeaders +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/scw/transport.go b/vendor/github.com/scaleway/scaleway-sdk-go/scw/transport.go index 35daaef7ac2..791a37393da 100644 --- a/vendor/github.com/scaleway/scaleway-sdk-go/scw/transport.go +++ b/vendor/github.com/scaleway/scaleway-sdk-go/scw/transport.go @@ -22,7 +22,7 @@ func (l *requestLoggerTransport) RoundTrip(request *http.Request) (*http.Respons originalHeaders := request.Header // Get anonymized headers - request.Header = auth.AnonymizeTokenHeaders(request.Header.Clone()) + request.Header = auth.AnonymizeHeaders(request.Header.Clone()) dump, err := httputil.DumpRequestOut(request, true) if err != nil { diff --git a/vendor/github.com/stretchr/objx/.codeclimate.yml b/vendor/github.com/stretchr/objx/.codeclimate.yml new file mode 100644 index 00000000000..559fa399c13 --- /dev/null +++ b/vendor/github.com/stretchr/objx/.codeclimate.yml @@ -0,0 +1,21 @@ +engines: + gofmt: + enabled: true + golint: + enabled: true + govet: + enabled: true + +exclude_patterns: +- ".github/" +- "vendor/" +- "codegen/" +- "*.yml" +- ".*.yml" +- "*.md" +- "Gopkg.*" +- "doc.go" +- "type_specific_codegen_test.go" +- "type_specific_codegen.go" +- ".gitignore" +- "LICENSE" diff --git a/vendor/github.com/stretchr/objx/.gitignore b/vendor/github.com/stretchr/objx/.gitignore new file mode 100644 index 00000000000..ea58090bd21 --- /dev/null +++ b/vendor/github.com/stretchr/objx/.gitignore @@ -0,0 +1,11 @@ +# Binaries for programs and plugins +*.exe +*.dll +*.so +*.dylib + +# Test binary, build with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out diff --git a/vendor/github.com/stretchr/objx/LICENSE b/vendor/github.com/stretchr/objx/LICENSE new file mode 100644 index 00000000000..44d4d9d5a7c --- /dev/null +++ b/vendor/github.com/stretchr/objx/LICENSE @@ -0,0 +1,22 @@ +The MIT License + +Copyright (c) 2014 Stretchr, Inc. +Copyright (c) 2017-2018 objx contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/stretchr/objx/README.md b/vendor/github.com/stretchr/objx/README.md new file mode 100644 index 00000000000..246660b21a9 --- /dev/null +++ b/vendor/github.com/stretchr/objx/README.md @@ -0,0 +1,80 @@ +# Objx +[![Build Status](https://travis-ci.org/stretchr/objx.svg?branch=master)](https://travis-ci.org/stretchr/objx) +[![Go Report Card](https://goreportcard.com/badge/github.com/stretchr/objx)](https://goreportcard.com/report/github.com/stretchr/objx) +[![Maintainability](https://api.codeclimate.com/v1/badges/1d64bc6c8474c2074f2b/maintainability)](https://codeclimate.com/github/stretchr/objx/maintainability) +[![Test Coverage](https://api.codeclimate.com/v1/badges/1d64bc6c8474c2074f2b/test_coverage)](https://codeclimate.com/github/stretchr/objx/test_coverage) +[![Sourcegraph](https://sourcegraph.com/github.com/stretchr/objx/-/badge.svg)](https://sourcegraph.com/github.com/stretchr/objx) +[![GoDoc](https://godoc.org/github.com/stretchr/objx?status.svg)](https://godoc.org/github.com/stretchr/objx) + +Objx - Go package for dealing with maps, slices, JSON and other data. + +Get started: + +- Install Objx with [one line of code](#installation), or [update it with another](#staying-up-to-date) +- Check out the API Documentation http://godoc.org/github.com/stretchr/objx + +## Overview +Objx provides the `objx.Map` type, which is a `map[string]interface{}` that exposes a powerful `Get` method (among others) that allows you to easily and quickly get access to data within the map, without having to worry too much about type assertions, missing data, default values etc. + +### Pattern +Objx uses a preditable pattern to make access data from within `map[string]interface{}` easy. Call one of the `objx.` functions to create your `objx.Map` to get going: + + m, err := objx.FromJSON(json) + +NOTE: Any methods or functions with the `Must` prefix will panic if something goes wrong, the rest will be optimistic and try to figure things out without panicking. + +Use `Get` to access the value you're interested in. You can use dot and array +notation too: + + m.Get("places[0].latlng") + +Once you have sought the `Value` you're interested in, you can use the `Is*` methods to determine its type. + + if m.Get("code").IsStr() { // Your code... } + +Or you can just assume the type, and use one of the strong type methods to extract the real value: + + m.Get("code").Int() + +If there's no value there (or if it's the wrong type) then a default value will be returned, or you can be explicit about the default value. + + Get("code").Int(-1) + +If you're dealing with a slice of data as a value, Objx provides many useful methods for iterating, manipulating and selecting that data. You can find out more by exploring the index below. + +### Reading data +A simple example of how to use Objx: + + // Use MustFromJSON to make an objx.Map from some JSON + m := objx.MustFromJSON(`{"name": "Mat", "age": 30}`) + + // Get the details + name := m.Get("name").Str() + age := m.Get("age").Int() + + // Get their nickname (or use their name if they don't have one) + nickname := m.Get("nickname").Str(name) + +### Ranging +Since `objx.Map` is a `map[string]interface{}` you can treat it as such. For example, to `range` the data, do what you would expect: + + m := objx.MustFromJSON(json) + for key, value := range m { + // Your code... + } + +## Installation +To install Objx, use go get: + + go get github.com/stretchr/objx + +### Staying up to date +To update Objx to the latest version, run: + + go get -u github.com/stretchr/objx + +### Supported go versions +We support the lastest three major Go versions, which are 1.10, 1.11 and 1.12 at the moment. + +## Contributing +Please feel free to submit issues, fork the repository and send pull requests! diff --git a/vendor/github.com/stretchr/objx/Taskfile.yml b/vendor/github.com/stretchr/objx/Taskfile.yml new file mode 100644 index 00000000000..7746f516da2 --- /dev/null +++ b/vendor/github.com/stretchr/objx/Taskfile.yml @@ -0,0 +1,30 @@ +version: '2' + +env: + GOFLAGS: -mod=vendor + +tasks: + default: + deps: [test] + + lint: + desc: Checks code style + cmds: + - gofmt -d -s *.go + - go vet ./... + silent: true + + lint-fix: + desc: Fixes code style + cmds: + - gofmt -w -s *.go + + test: + desc: Runs go tests + cmds: + - go test -race ./... + + test-coverage: + desc: Runs go tests and calculates test coverage + cmds: + - go test -race -coverprofile=c.out ./... diff --git a/vendor/github.com/stretchr/objx/accessors.go b/vendor/github.com/stretchr/objx/accessors.go new file mode 100644 index 00000000000..4c604558863 --- /dev/null +++ b/vendor/github.com/stretchr/objx/accessors.go @@ -0,0 +1,197 @@ +package objx + +import ( + "reflect" + "regexp" + "strconv" + "strings" +) + +const ( + // PathSeparator is the character used to separate the elements + // of the keypath. + // + // For example, `location.address.city` + PathSeparator string = "." + + // arrayAccesRegexString is the regex used to extract the array number + // from the access path + arrayAccesRegexString = `^(.+)\[([0-9]+)\]$` + + // mapAccessRegexString is the regex used to extract the map key + // from the access path + mapAccessRegexString = `^([^\[]*)\[([^\]]+)\](.*)$` +) + +// arrayAccesRegex is the compiled arrayAccesRegexString +var arrayAccesRegex = regexp.MustCompile(arrayAccesRegexString) + +// mapAccessRegex is the compiled mapAccessRegexString +var mapAccessRegex = regexp.MustCompile(mapAccessRegexString) + +// Get gets the value using the specified selector and +// returns it inside a new Obj object. +// +// If it cannot find the value, Get will return a nil +// value inside an instance of Obj. +// +// Get can only operate directly on map[string]interface{} and []interface. +// +// Example +// +// To access the title of the third chapter of the second book, do: +// +// o.Get("books[1].chapters[2].title") +func (m Map) Get(selector string) *Value { + rawObj := access(m, selector, nil, false) + return &Value{data: rawObj} +} + +// Set sets the value using the specified selector and +// returns the object on which Set was called. +// +// Set can only operate directly on map[string]interface{} and []interface +// +// Example +// +// To set the title of the third chapter of the second book, do: +// +// o.Set("books[1].chapters[2].title","Time to Go") +func (m Map) Set(selector string, value interface{}) Map { + access(m, selector, value, true) + return m +} + +// getIndex returns the index, which is hold in s by two braches. +// It also returns s withour the index part, e.g. name[1] will return (1, name). +// If no index is found, -1 is returned +func getIndex(s string) (int, string) { + arrayMatches := arrayAccesRegex.FindStringSubmatch(s) + if len(arrayMatches) > 0 { + // Get the key into the map + selector := arrayMatches[1] + // Get the index into the array at the key + // We know this cannt fail because arrayMatches[2] is an int for sure + index, _ := strconv.Atoi(arrayMatches[2]) + return index, selector + } + return -1, s +} + +// getKey returns the key which is held in s by two brackets. +// It also returns the next selector. +func getKey(s string) (string, string) { + selSegs := strings.SplitN(s, PathSeparator, 2) + thisSel := selSegs[0] + nextSel := "" + + if len(selSegs) > 1 { + nextSel = selSegs[1] + } + + mapMatches := mapAccessRegex.FindStringSubmatch(s) + if len(mapMatches) > 0 { + if _, err := strconv.Atoi(mapMatches[2]); err != nil { + thisSel = mapMatches[1] + nextSel = "[" + mapMatches[2] + "]" + mapMatches[3] + + if thisSel == "" { + thisSel = mapMatches[2] + nextSel = mapMatches[3] + } + + if nextSel == "" { + selSegs = []string{"", ""} + } else if nextSel[0] == '.' { + nextSel = nextSel[1:] + } + } + } + + return thisSel, nextSel +} + +// access accesses the object using the selector and performs the +// appropriate action. +func access(current interface{}, selector string, value interface{}, isSet bool) interface{} { + thisSel, nextSel := getKey(selector) + + indexes := []int{} + for strings.Contains(thisSel, "[") { + prevSel := thisSel + index := -1 + index, thisSel = getIndex(thisSel) + indexes = append(indexes, index) + if prevSel == thisSel { + break + } + } + + if curMap, ok := current.(Map); ok { + current = map[string]interface{}(curMap) + } + // get the object in question + switch current.(type) { + case map[string]interface{}: + curMSI := current.(map[string]interface{}) + if nextSel == "" && isSet { + curMSI[thisSel] = value + return nil + } + + _, ok := curMSI[thisSel].(map[string]interface{}) + if !ok { + _, ok = curMSI[thisSel].(Map) + } + + if (curMSI[thisSel] == nil || !ok) && len(indexes) == 0 && isSet { + curMSI[thisSel] = map[string]interface{}{} + } + + current = curMSI[thisSel] + default: + current = nil + } + + // do we need to access the item of an array? + if len(indexes) > 0 { + num := len(indexes) + for num > 0 { + num-- + index := indexes[num] + indexes = indexes[:num] + if array, ok := interSlice(current); ok { + if index < len(array) { + current = array[index] + } else { + current = nil + break + } + } + } + } + + if nextSel != "" { + current = access(current, nextSel, value, isSet) + } + return current +} + +func interSlice(slice interface{}) ([]interface{}, bool) { + if array, ok := slice.([]interface{}); ok { + return array, ok + } + + s := reflect.ValueOf(slice) + if s.Kind() != reflect.Slice { + return nil, false + } + + ret := make([]interface{}, s.Len()) + + for i := 0; i < s.Len(); i++ { + ret[i] = s.Index(i).Interface() + } + + return ret, true +} diff --git a/vendor/github.com/stretchr/objx/conversions.go b/vendor/github.com/stretchr/objx/conversions.go new file mode 100644 index 00000000000..080aa46e472 --- /dev/null +++ b/vendor/github.com/stretchr/objx/conversions.go @@ -0,0 +1,280 @@ +package objx + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "net/url" + "strconv" +) + +// SignatureSeparator is the character that is used to +// separate the Base64 string from the security signature. +const SignatureSeparator = "_" + +// URLValuesSliceKeySuffix is the character that is used to +// specify a suffic for slices parsed by URLValues. +// If the suffix is set to "[i]", then the index of the slice +// is used in place of i +// Ex: Suffix "[]" would have the form a[]=b&a[]=c +// OR Suffix "[i]" would have the form a[0]=b&a[1]=c +// OR Suffix "" would have the form a=b&a=c +var urlValuesSliceKeySuffix = "[]" + +const ( + URLValuesSliceKeySuffixEmpty = "" + URLValuesSliceKeySuffixArray = "[]" + URLValuesSliceKeySuffixIndex = "[i]" +) + +// SetURLValuesSliceKeySuffix sets the character that is used to +// specify a suffic for slices parsed by URLValues. +// If the suffix is set to "[i]", then the index of the slice +// is used in place of i +// Ex: Suffix "[]" would have the form a[]=b&a[]=c +// OR Suffix "[i]" would have the form a[0]=b&a[1]=c +// OR Suffix "" would have the form a=b&a=c +func SetURLValuesSliceKeySuffix(s string) error { + if s == URLValuesSliceKeySuffixEmpty || s == URLValuesSliceKeySuffixArray || s == URLValuesSliceKeySuffixIndex { + urlValuesSliceKeySuffix = s + return nil + } + + return errors.New("objx: Invalid URLValuesSliceKeySuffix provided.") +} + +// JSON converts the contained object to a JSON string +// representation +func (m Map) JSON() (string, error) { + for k, v := range m { + m[k] = cleanUp(v) + } + + result, err := json.Marshal(m) + if err != nil { + err = errors.New("objx: JSON encode failed with: " + err.Error()) + } + return string(result), err +} + +func cleanUpInterfaceArray(in []interface{}) []interface{} { + result := make([]interface{}, len(in)) + for i, v := range in { + result[i] = cleanUp(v) + } + return result +} + +func cleanUpInterfaceMap(in map[interface{}]interface{}) Map { + result := Map{} + for k, v := range in { + result[fmt.Sprintf("%v", k)] = cleanUp(v) + } + return result +} + +func cleanUpStringMap(in map[string]interface{}) Map { + result := Map{} + for k, v := range in { + result[k] = cleanUp(v) + } + return result +} + +func cleanUpMSIArray(in []map[string]interface{}) []Map { + result := make([]Map, len(in)) + for i, v := range in { + result[i] = cleanUpStringMap(v) + } + return result +} + +func cleanUpMapArray(in []Map) []Map { + result := make([]Map, len(in)) + for i, v := range in { + result[i] = cleanUpStringMap(v) + } + return result +} + +func cleanUp(v interface{}) interface{} { + switch v := v.(type) { + case []interface{}: + return cleanUpInterfaceArray(v) + case []map[string]interface{}: + return cleanUpMSIArray(v) + case map[interface{}]interface{}: + return cleanUpInterfaceMap(v) + case Map: + return cleanUpStringMap(v) + case []Map: + return cleanUpMapArray(v) + default: + return v + } +} + +// MustJSON converts the contained object to a JSON string +// representation and panics if there is an error +func (m Map) MustJSON() string { + result, err := m.JSON() + if err != nil { + panic(err.Error()) + } + return result +} + +// Base64 converts the contained object to a Base64 string +// representation of the JSON string representation +func (m Map) Base64() (string, error) { + var buf bytes.Buffer + + jsonData, err := m.JSON() + if err != nil { + return "", err + } + + encoder := base64.NewEncoder(base64.StdEncoding, &buf) + _, _ = encoder.Write([]byte(jsonData)) + _ = encoder.Close() + + return buf.String(), nil +} + +// MustBase64 converts the contained object to a Base64 string +// representation of the JSON string representation and panics +// if there is an error +func (m Map) MustBase64() string { + result, err := m.Base64() + if err != nil { + panic(err.Error()) + } + return result +} + +// SignedBase64 converts the contained object to a Base64 string +// representation of the JSON string representation and signs it +// using the provided key. +func (m Map) SignedBase64(key string) (string, error) { + base64, err := m.Base64() + if err != nil { + return "", err + } + + sig := HashWithKey(base64, key) + return base64 + SignatureSeparator + sig, nil +} + +// MustSignedBase64 converts the contained object to a Base64 string +// representation of the JSON string representation and signs it +// using the provided key and panics if there is an error +func (m Map) MustSignedBase64(key string) string { + result, err := m.SignedBase64(key) + if err != nil { + panic(err.Error()) + } + return result +} + +/* + URL Query + ------------------------------------------------ +*/ + +// URLValues creates a url.Values object from an Obj. This +// function requires that the wrapped object be a map[string]interface{} +func (m Map) URLValues() url.Values { + vals := make(url.Values) + + m.parseURLValues(m, vals, "") + + return vals +} + +func (m Map) parseURLValues(queryMap Map, vals url.Values, key string) { + useSliceIndex := false + if urlValuesSliceKeySuffix == "[i]" { + useSliceIndex = true + } + + for k, v := range queryMap { + val := &Value{data: v} + switch { + case val.IsObjxMap(): + if key == "" { + m.parseURLValues(val.ObjxMap(), vals, k) + } else { + m.parseURLValues(val.ObjxMap(), vals, key+"["+k+"]") + } + case val.IsObjxMapSlice(): + sliceKey := k + if key != "" { + sliceKey = key + "[" + k + "]" + } + + if useSliceIndex { + for i, sv := range val.MustObjxMapSlice() { + sk := sliceKey + "[" + strconv.FormatInt(int64(i), 10) + "]" + m.parseURLValues(sv, vals, sk) + } + } else { + sliceKey = sliceKey + urlValuesSliceKeySuffix + for _, sv := range val.MustObjxMapSlice() { + m.parseURLValues(sv, vals, sliceKey) + } + } + case val.IsMSISlice(): + sliceKey := k + if key != "" { + sliceKey = key + "[" + k + "]" + } + + if useSliceIndex { + for i, sv := range val.MustMSISlice() { + sk := sliceKey + "[" + strconv.FormatInt(int64(i), 10) + "]" + m.parseURLValues(New(sv), vals, sk) + } + } else { + sliceKey = sliceKey + urlValuesSliceKeySuffix + for _, sv := range val.MustMSISlice() { + m.parseURLValues(New(sv), vals, sliceKey) + } + } + case val.IsStrSlice(), val.IsBoolSlice(), + val.IsFloat32Slice(), val.IsFloat64Slice(), + val.IsIntSlice(), val.IsInt8Slice(), val.IsInt16Slice(), val.IsInt32Slice(), val.IsInt64Slice(), + val.IsUintSlice(), val.IsUint8Slice(), val.IsUint16Slice(), val.IsUint32Slice(), val.IsUint64Slice(): + + sliceKey := k + if key != "" { + sliceKey = key + "[" + k + "]" + } + + if useSliceIndex { + for i, sv := range val.StringSlice() { + sk := sliceKey + "[" + strconv.FormatInt(int64(i), 10) + "]" + vals.Set(sk, sv) + } + } else { + sliceKey = sliceKey + urlValuesSliceKeySuffix + vals[sliceKey] = val.StringSlice() + } + + default: + if key == "" { + vals.Set(k, val.String()) + } else { + vals.Set(key+"["+k+"]", val.String()) + } + } + } +} + +// URLQuery gets an encoded URL query representing the given +// Obj. This function requires that the wrapped object be a +// map[string]interface{} +func (m Map) URLQuery() (string, error) { + return m.URLValues().Encode(), nil +} diff --git a/vendor/github.com/stretchr/objx/doc.go b/vendor/github.com/stretchr/objx/doc.go new file mode 100644 index 00000000000..6d6af1a83ab --- /dev/null +++ b/vendor/github.com/stretchr/objx/doc.go @@ -0,0 +1,66 @@ +/* +Objx - Go package for dealing with maps, slices, JSON and other data. + +Overview + +Objx provides the `objx.Map` type, which is a `map[string]interface{}` that exposes +a powerful `Get` method (among others) that allows you to easily and quickly get +access to data within the map, without having to worry too much about type assertions, +missing data, default values etc. + +Pattern + +Objx uses a preditable pattern to make access data from within `map[string]interface{}` easy. +Call one of the `objx.` functions to create your `objx.Map` to get going: + + m, err := objx.FromJSON(json) + +NOTE: Any methods or functions with the `Must` prefix will panic if something goes wrong, +the rest will be optimistic and try to figure things out without panicking. + +Use `Get` to access the value you're interested in. You can use dot and array +notation too: + + m.Get("places[0].latlng") + +Once you have sought the `Value` you're interested in, you can use the `Is*` methods to determine its type. + + if m.Get("code").IsStr() { // Your code... } + +Or you can just assume the type, and use one of the strong type methods to extract the real value: + + m.Get("code").Int() + +If there's no value there (or if it's the wrong type) then a default value will be returned, +or you can be explicit about the default value. + + Get("code").Int(-1) + +If you're dealing with a slice of data as a value, Objx provides many useful methods for iterating, +manipulating and selecting that data. You can find out more by exploring the index below. + +Reading data + +A simple example of how to use Objx: + + // Use MustFromJSON to make an objx.Map from some JSON + m := objx.MustFromJSON(`{"name": "Mat", "age": 30}`) + + // Get the details + name := m.Get("name").Str() + age := m.Get("age").Int() + + // Get their nickname (or use their name if they don't have one) + nickname := m.Get("nickname").Str(name) + +Ranging + +Since `objx.Map` is a `map[string]interface{}` you can treat it as such. +For example, to `range` the data, do what you would expect: + + m := objx.MustFromJSON(json) + for key, value := range m { + // Your code... + } +*/ +package objx diff --git a/vendor/github.com/stretchr/objx/map.go b/vendor/github.com/stretchr/objx/map.go new file mode 100644 index 00000000000..a64712a08b5 --- /dev/null +++ b/vendor/github.com/stretchr/objx/map.go @@ -0,0 +1,215 @@ +package objx + +import ( + "encoding/base64" + "encoding/json" + "errors" + "io/ioutil" + "net/url" + "strings" +) + +// MSIConvertable is an interface that defines methods for converting your +// custom types to a map[string]interface{} representation. +type MSIConvertable interface { + // MSI gets a map[string]interface{} (msi) representing the + // object. + MSI() map[string]interface{} +} + +// Map provides extended functionality for working with +// untyped data, in particular map[string]interface (msi). +type Map map[string]interface{} + +// Value returns the internal value instance +func (m Map) Value() *Value { + return &Value{data: m} +} + +// Nil represents a nil Map. +var Nil = New(nil) + +// New creates a new Map containing the map[string]interface{} in the data argument. +// If the data argument is not a map[string]interface, New attempts to call the +// MSI() method on the MSIConvertable interface to create one. +func New(data interface{}) Map { + if _, ok := data.(map[string]interface{}); !ok { + if converter, ok := data.(MSIConvertable); ok { + data = converter.MSI() + } else { + return nil + } + } + return Map(data.(map[string]interface{})) +} + +// MSI creates a map[string]interface{} and puts it inside a new Map. +// +// The arguments follow a key, value pattern. +// +// +// Returns nil if any key argument is non-string or if there are an odd number of arguments. +// +// Example +// +// To easily create Maps: +// +// m := objx.MSI("name", "Mat", "age", 29, "subobj", objx.MSI("active", true)) +// +// // creates an Map equivalent to +// m := objx.Map{"name": "Mat", "age": 29, "subobj": objx.Map{"active": true}} +func MSI(keyAndValuePairs ...interface{}) Map { + newMap := Map{} + keyAndValuePairsLen := len(keyAndValuePairs) + if keyAndValuePairsLen%2 != 0 { + return nil + } + for i := 0; i < keyAndValuePairsLen; i = i + 2 { + key := keyAndValuePairs[i] + value := keyAndValuePairs[i+1] + + // make sure the key is a string + keyString, keyStringOK := key.(string) + if !keyStringOK { + return nil + } + newMap[keyString] = value + } + return newMap +} + +// ****** Conversion Constructors + +// MustFromJSON creates a new Map containing the data specified in the +// jsonString. +// +// Panics if the JSON is invalid. +func MustFromJSON(jsonString string) Map { + o, err := FromJSON(jsonString) + if err != nil { + panic("objx: MustFromJSON failed with error: " + err.Error()) + } + return o +} + +// MustFromJSONSlice creates a new slice of Map containing the data specified in the +// jsonString. Works with jsons with a top level array +// +// Panics if the JSON is invalid. +func MustFromJSONSlice(jsonString string) []Map { + slice, err := FromJSONSlice(jsonString) + if err != nil { + panic("objx: MustFromJSONSlice failed with error: " + err.Error()) + } + return slice +} + +// FromJSON creates a new Map containing the data specified in the +// jsonString. +// +// Returns an error if the JSON is invalid. +func FromJSON(jsonString string) (Map, error) { + var m Map + err := json.Unmarshal([]byte(jsonString), &m) + if err != nil { + return Nil, err + } + return m, nil +} + +// FromJSONSlice creates a new slice of Map containing the data specified in the +// jsonString. Works with jsons with a top level array +// +// Returns an error if the JSON is invalid. +func FromJSONSlice(jsonString string) ([]Map, error) { + var slice []Map + err := json.Unmarshal([]byte(jsonString), &slice) + if err != nil { + return nil, err + } + return slice, nil +} + +// FromBase64 creates a new Obj containing the data specified +// in the Base64 string. +// +// The string is an encoded JSON string returned by Base64 +func FromBase64(base64String string) (Map, error) { + decoder := base64.NewDecoder(base64.StdEncoding, strings.NewReader(base64String)) + decoded, err := ioutil.ReadAll(decoder) + if err != nil { + return nil, err + } + return FromJSON(string(decoded)) +} + +// MustFromBase64 creates a new Obj containing the data specified +// in the Base64 string and panics if there is an error. +// +// The string is an encoded JSON string returned by Base64 +func MustFromBase64(base64String string) Map { + result, err := FromBase64(base64String) + if err != nil { + panic("objx: MustFromBase64 failed with error: " + err.Error()) + } + return result +} + +// FromSignedBase64 creates a new Obj containing the data specified +// in the Base64 string. +// +// The string is an encoded JSON string returned by SignedBase64 +func FromSignedBase64(base64String, key string) (Map, error) { + parts := strings.Split(base64String, SignatureSeparator) + if len(parts) != 2 { + return nil, errors.New("objx: Signed base64 string is malformed") + } + + sig := HashWithKey(parts[0], key) + if parts[1] != sig { + return nil, errors.New("objx: Signature for base64 data does not match") + } + return FromBase64(parts[0]) +} + +// MustFromSignedBase64 creates a new Obj containing the data specified +// in the Base64 string and panics if there is an error. +// +// The string is an encoded JSON string returned by Base64 +func MustFromSignedBase64(base64String, key string) Map { + result, err := FromSignedBase64(base64String, key) + if err != nil { + panic("objx: MustFromSignedBase64 failed with error: " + err.Error()) + } + return result +} + +// FromURLQuery generates a new Obj by parsing the specified +// query. +// +// For queries with multiple values, the first value is selected. +func FromURLQuery(query string) (Map, error) { + vals, err := url.ParseQuery(query) + if err != nil { + return nil, err + } + m := Map{} + for k, vals := range vals { + m[k] = vals[0] + } + return m, nil +} + +// MustFromURLQuery generates a new Obj by parsing the specified +// query. +// +// For queries with multiple values, the first value is selected. +// +// Panics if it encounters an error +func MustFromURLQuery(query string) Map { + o, err := FromURLQuery(query) + if err != nil { + panic("objx: MustFromURLQuery failed with error: " + err.Error()) + } + return o +} diff --git a/vendor/github.com/stretchr/objx/mutations.go b/vendor/github.com/stretchr/objx/mutations.go new file mode 100644 index 00000000000..c3400a3f709 --- /dev/null +++ b/vendor/github.com/stretchr/objx/mutations.go @@ -0,0 +1,77 @@ +package objx + +// Exclude returns a new Map with the keys in the specified []string +// excluded. +func (m Map) Exclude(exclude []string) Map { + excluded := make(Map) + for k, v := range m { + if !contains(exclude, k) { + excluded[k] = v + } + } + return excluded +} + +// Copy creates a shallow copy of the Obj. +func (m Map) Copy() Map { + copied := Map{} + for k, v := range m { + copied[k] = v + } + return copied +} + +// Merge blends the specified map with a copy of this map and returns the result. +// +// Keys that appear in both will be selected from the specified map. +// This method requires that the wrapped object be a map[string]interface{} +func (m Map) Merge(merge Map) Map { + return m.Copy().MergeHere(merge) +} + +// MergeHere blends the specified map with this map and returns the current map. +// +// Keys that appear in both will be selected from the specified map. The original map +// will be modified. This method requires that +// the wrapped object be a map[string]interface{} +func (m Map) MergeHere(merge Map) Map { + for k, v := range merge { + m[k] = v + } + return m +} + +// Transform builds a new Obj giving the transformer a chance +// to change the keys and values as it goes. This method requires that +// the wrapped object be a map[string]interface{} +func (m Map) Transform(transformer func(key string, value interface{}) (string, interface{})) Map { + newMap := Map{} + for k, v := range m { + modifiedKey, modifiedVal := transformer(k, v) + newMap[modifiedKey] = modifiedVal + } + return newMap +} + +// TransformKeys builds a new map using the specified key mapping. +// +// Unspecified keys will be unaltered. +// This method requires that the wrapped object be a map[string]interface{} +func (m Map) TransformKeys(mapping map[string]string) Map { + return m.Transform(func(key string, value interface{}) (string, interface{}) { + if newKey, ok := mapping[key]; ok { + return newKey, value + } + return key, value + }) +} + +// Checks if a string slice contains a string +func contains(s []string, e string) bool { + for _, a := range s { + if a == e { + return true + } + } + return false +} diff --git a/vendor/github.com/stretchr/objx/security.go b/vendor/github.com/stretchr/objx/security.go new file mode 100644 index 00000000000..692be8e2a9f --- /dev/null +++ b/vendor/github.com/stretchr/objx/security.go @@ -0,0 +1,12 @@ +package objx + +import ( + "crypto/sha1" + "encoding/hex" +) + +// HashWithKey hashes the specified string using the security key +func HashWithKey(data, key string) string { + d := sha1.Sum([]byte(data + ":" + key)) + return hex.EncodeToString(d[:]) +} diff --git a/vendor/github.com/stretchr/objx/tests.go b/vendor/github.com/stretchr/objx/tests.go new file mode 100644 index 00000000000..d9e0b479a4c --- /dev/null +++ b/vendor/github.com/stretchr/objx/tests.go @@ -0,0 +1,17 @@ +package objx + +// Has gets whether there is something at the specified selector +// or not. +// +// If m is nil, Has will always return false. +func (m Map) Has(selector string) bool { + if m == nil { + return false + } + return !m.Get(selector).IsNil() +} + +// IsNil gets whether the data is nil or not. +func (v *Value) IsNil() bool { + return v == nil || v.data == nil +} diff --git a/vendor/github.com/stretchr/objx/type_specific.go b/vendor/github.com/stretchr/objx/type_specific.go new file mode 100644 index 00000000000..80f88d9fa29 --- /dev/null +++ b/vendor/github.com/stretchr/objx/type_specific.go @@ -0,0 +1,346 @@ +package objx + +/* + MSI (map[string]interface{} and []map[string]interface{}) +*/ + +// MSI gets the value as a map[string]interface{}, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) MSI(optionalDefault ...map[string]interface{}) map[string]interface{} { + if s, ok := v.data.(map[string]interface{}); ok { + return s + } + if s, ok := v.data.(Map); ok { + return map[string]interface{}(s) + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustMSI gets the value as a map[string]interface{}. +// +// Panics if the object is not a map[string]interface{}. +func (v *Value) MustMSI() map[string]interface{} { + if s, ok := v.data.(Map); ok { + return map[string]interface{}(s) + } + return v.data.(map[string]interface{}) +} + +// MSISlice gets the value as a []map[string]interface{}, returns the optionalDefault +// value or nil if the value is not a []map[string]interface{}. +func (v *Value) MSISlice(optionalDefault ...[]map[string]interface{}) []map[string]interface{} { + if s, ok := v.data.([]map[string]interface{}); ok { + return s + } + + s := v.ObjxMapSlice() + if s == nil { + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil + } + + result := make([]map[string]interface{}, len(s)) + for i := range s { + result[i] = s[i].Value().MSI() + } + return result +} + +// MustMSISlice gets the value as a []map[string]interface{}. +// +// Panics if the object is not a []map[string]interface{}. +func (v *Value) MustMSISlice() []map[string]interface{} { + if s := v.MSISlice(); s != nil { + return s + } + + return v.data.([]map[string]interface{}) +} + +// IsMSI gets whether the object contained is a map[string]interface{} or not. +func (v *Value) IsMSI() bool { + _, ok := v.data.(map[string]interface{}) + if !ok { + _, ok = v.data.(Map) + } + return ok +} + +// IsMSISlice gets whether the object contained is a []map[string]interface{} or not. +func (v *Value) IsMSISlice() bool { + _, ok := v.data.([]map[string]interface{}) + if !ok { + _, ok = v.data.([]Map) + if !ok { + s, ok := v.data.([]interface{}) + if ok { + for i := range s { + switch s[i].(type) { + case Map: + case map[string]interface{}: + default: + return false + } + } + return true + } + } + } + return ok +} + +// EachMSI calls the specified callback for each object +// in the []map[string]interface{}. +// +// Panics if the object is the wrong type. +func (v *Value) EachMSI(callback func(int, map[string]interface{}) bool) *Value { + for index, val := range v.MustMSISlice() { + carryon := callback(index, val) + if !carryon { + break + } + } + return v +} + +// WhereMSI uses the specified decider function to select items +// from the []map[string]interface{}. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereMSI(decider func(int, map[string]interface{}) bool) *Value { + var selected []map[string]interface{} + v.EachMSI(func(index int, val map[string]interface{}) bool { + shouldSelect := decider(index, val) + if !shouldSelect { + selected = append(selected, val) + } + return true + }) + return &Value{data: selected} +} + +// GroupMSI uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]map[string]interface{}. +func (v *Value) GroupMSI(grouper func(int, map[string]interface{}) string) *Value { + groups := make(map[string][]map[string]interface{}) + v.EachMSI(func(index int, val map[string]interface{}) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]map[string]interface{}, 0) + } + groups[group] = append(groups[group], val) + return true + }) + return &Value{data: groups} +} + +// ReplaceMSI uses the specified function to replace each map[string]interface{}s +// by iterating each item. The data in the returned result will be a +// []map[string]interface{} containing the replaced items. +func (v *Value) ReplaceMSI(replacer func(int, map[string]interface{}) map[string]interface{}) *Value { + arr := v.MustMSISlice() + replaced := make([]map[string]interface{}, len(arr)) + v.EachMSI(func(index int, val map[string]interface{}) bool { + replaced[index] = replacer(index, val) + return true + }) + return &Value{data: replaced} +} + +// CollectMSI uses the specified collector function to collect a value +// for each of the map[string]interface{}s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectMSI(collector func(int, map[string]interface{}) interface{}) *Value { + arr := v.MustMSISlice() + collected := make([]interface{}, len(arr)) + v.EachMSI(func(index int, val map[string]interface{}) bool { + collected[index] = collector(index, val) + return true + }) + return &Value{data: collected} +} + +/* + ObjxMap ((Map) and [](Map)) +*/ + +// ObjxMap gets the value as a (Map), returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) ObjxMap(optionalDefault ...(Map)) Map { + if s, ok := v.data.((Map)); ok { + return s + } + if s, ok := v.data.(map[string]interface{}); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return New(nil) +} + +// MustObjxMap gets the value as a (Map). +// +// Panics if the object is not a (Map). +func (v *Value) MustObjxMap() Map { + if s, ok := v.data.(map[string]interface{}); ok { + return s + } + return v.data.((Map)) +} + +// ObjxMapSlice gets the value as a [](Map), returns the optionalDefault +// value or nil if the value is not a [](Map). +func (v *Value) ObjxMapSlice(optionalDefault ...[](Map)) [](Map) { + if s, ok := v.data.([]Map); ok { + return s + } + + if s, ok := v.data.([]map[string]interface{}); ok { + result := make([]Map, len(s)) + for i := range s { + result[i] = s[i] + } + return result + } + + s, ok := v.data.([]interface{}) + if !ok { + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil + } + + result := make([]Map, len(s)) + for i := range s { + switch s[i].(type) { + case Map: + result[i] = s[i].(Map) + case map[string]interface{}: + result[i] = New(s[i]) + default: + return nil + } + } + return result +} + +// MustObjxMapSlice gets the value as a [](Map). +// +// Panics if the object is not a [](Map). +func (v *Value) MustObjxMapSlice() [](Map) { + if s := v.ObjxMapSlice(); s != nil { + return s + } + return v.data.([](Map)) +} + +// IsObjxMap gets whether the object contained is a (Map) or not. +func (v *Value) IsObjxMap() bool { + _, ok := v.data.((Map)) + if !ok { + _, ok = v.data.(map[string]interface{}) + } + return ok +} + +// IsObjxMapSlice gets whether the object contained is a [](Map) or not. +func (v *Value) IsObjxMapSlice() bool { + _, ok := v.data.([](Map)) + if !ok { + _, ok = v.data.([]map[string]interface{}) + if !ok { + s, ok := v.data.([]interface{}) + if ok { + for i := range s { + switch s[i].(type) { + case Map: + case map[string]interface{}: + default: + return false + } + } + return true + } + } + } + + return ok +} + +// EachObjxMap calls the specified callback for each object +// in the [](Map). +// +// Panics if the object is the wrong type. +func (v *Value) EachObjxMap(callback func(int, Map) bool) *Value { + for index, val := range v.MustObjxMapSlice() { + carryon := callback(index, val) + if !carryon { + break + } + } + return v +} + +// WhereObjxMap uses the specified decider function to select items +// from the [](Map). The object contained in the result will contain +// only the selected items. +func (v *Value) WhereObjxMap(decider func(int, Map) bool) *Value { + var selected [](Map) + v.EachObjxMap(func(index int, val Map) bool { + shouldSelect := decider(index, val) + if !shouldSelect { + selected = append(selected, val) + } + return true + }) + return &Value{data: selected} +} + +// GroupObjxMap uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][](Map). +func (v *Value) GroupObjxMap(grouper func(int, Map) string) *Value { + groups := make(map[string][](Map)) + v.EachObjxMap(func(index int, val Map) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([](Map), 0) + } + groups[group] = append(groups[group], val) + return true + }) + return &Value{data: groups} +} + +// ReplaceObjxMap uses the specified function to replace each (Map)s +// by iterating each item. The data in the returned result will be a +// [](Map) containing the replaced items. +func (v *Value) ReplaceObjxMap(replacer func(int, Map) Map) *Value { + arr := v.MustObjxMapSlice() + replaced := make([](Map), len(arr)) + v.EachObjxMap(func(index int, val Map) bool { + replaced[index] = replacer(index, val) + return true + }) + return &Value{data: replaced} +} + +// CollectObjxMap uses the specified collector function to collect a value +// for each of the (Map)s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectObjxMap(collector func(int, Map) interface{}) *Value { + arr := v.MustObjxMapSlice() + collected := make([]interface{}, len(arr)) + v.EachObjxMap(func(index int, val Map) bool { + collected[index] = collector(index, val) + return true + }) + return &Value{data: collected} +} diff --git a/vendor/github.com/stretchr/objx/type_specific_codegen.go b/vendor/github.com/stretchr/objx/type_specific_codegen.go new file mode 100644 index 00000000000..45850456e17 --- /dev/null +++ b/vendor/github.com/stretchr/objx/type_specific_codegen.go @@ -0,0 +1,2261 @@ +package objx + +/* + Inter (interface{} and []interface{}) +*/ + +// Inter gets the value as a interface{}, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Inter(optionalDefault ...interface{}) interface{} { + if s, ok := v.data.(interface{}); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustInter gets the value as a interface{}. +// +// Panics if the object is not a interface{}. +func (v *Value) MustInter() interface{} { + return v.data.(interface{}) +} + +// InterSlice gets the value as a []interface{}, returns the optionalDefault +// value or nil if the value is not a []interface{}. +func (v *Value) InterSlice(optionalDefault ...[]interface{}) []interface{} { + if s, ok := v.data.([]interface{}); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustInterSlice gets the value as a []interface{}. +// +// Panics if the object is not a []interface{}. +func (v *Value) MustInterSlice() []interface{} { + return v.data.([]interface{}) +} + +// IsInter gets whether the object contained is a interface{} or not. +func (v *Value) IsInter() bool { + _, ok := v.data.(interface{}) + return ok +} + +// IsInterSlice gets whether the object contained is a []interface{} or not. +func (v *Value) IsInterSlice() bool { + _, ok := v.data.([]interface{}) + return ok +} + +// EachInter calls the specified callback for each object +// in the []interface{}. +// +// Panics if the object is the wrong type. +func (v *Value) EachInter(callback func(int, interface{}) bool) *Value { + for index, val := range v.MustInterSlice() { + carryon := callback(index, val) + if !carryon { + break + } + } + return v +} + +// WhereInter uses the specified decider function to select items +// from the []interface{}. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereInter(decider func(int, interface{}) bool) *Value { + var selected []interface{} + v.EachInter(func(index int, val interface{}) bool { + shouldSelect := decider(index, val) + if !shouldSelect { + selected = append(selected, val) + } + return true + }) + return &Value{data: selected} +} + +// GroupInter uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]interface{}. +func (v *Value) GroupInter(grouper func(int, interface{}) string) *Value { + groups := make(map[string][]interface{}) + v.EachInter(func(index int, val interface{}) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]interface{}, 0) + } + groups[group] = append(groups[group], val) + return true + }) + return &Value{data: groups} +} + +// ReplaceInter uses the specified function to replace each interface{}s +// by iterating each item. The data in the returned result will be a +// []interface{} containing the replaced items. +func (v *Value) ReplaceInter(replacer func(int, interface{}) interface{}) *Value { + arr := v.MustInterSlice() + replaced := make([]interface{}, len(arr)) + v.EachInter(func(index int, val interface{}) bool { + replaced[index] = replacer(index, val) + return true + }) + return &Value{data: replaced} +} + +// CollectInter uses the specified collector function to collect a value +// for each of the interface{}s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectInter(collector func(int, interface{}) interface{}) *Value { + arr := v.MustInterSlice() + collected := make([]interface{}, len(arr)) + v.EachInter(func(index int, val interface{}) bool { + collected[index] = collector(index, val) + return true + }) + return &Value{data: collected} +} + +/* + Bool (bool and []bool) +*/ + +// Bool gets the value as a bool, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Bool(optionalDefault ...bool) bool { + if s, ok := v.data.(bool); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return false +} + +// MustBool gets the value as a bool. +// +// Panics if the object is not a bool. +func (v *Value) MustBool() bool { + return v.data.(bool) +} + +// BoolSlice gets the value as a []bool, returns the optionalDefault +// value or nil if the value is not a []bool. +func (v *Value) BoolSlice(optionalDefault ...[]bool) []bool { + if s, ok := v.data.([]bool); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustBoolSlice gets the value as a []bool. +// +// Panics if the object is not a []bool. +func (v *Value) MustBoolSlice() []bool { + return v.data.([]bool) +} + +// IsBool gets whether the object contained is a bool or not. +func (v *Value) IsBool() bool { + _, ok := v.data.(bool) + return ok +} + +// IsBoolSlice gets whether the object contained is a []bool or not. +func (v *Value) IsBoolSlice() bool { + _, ok := v.data.([]bool) + return ok +} + +// EachBool calls the specified callback for each object +// in the []bool. +// +// Panics if the object is the wrong type. +func (v *Value) EachBool(callback func(int, bool) bool) *Value { + for index, val := range v.MustBoolSlice() { + carryon := callback(index, val) + if !carryon { + break + } + } + return v +} + +// WhereBool uses the specified decider function to select items +// from the []bool. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereBool(decider func(int, bool) bool) *Value { + var selected []bool + v.EachBool(func(index int, val bool) bool { + shouldSelect := decider(index, val) + if !shouldSelect { + selected = append(selected, val) + } + return true + }) + return &Value{data: selected} +} + +// GroupBool uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]bool. +func (v *Value) GroupBool(grouper func(int, bool) string) *Value { + groups := make(map[string][]bool) + v.EachBool(func(index int, val bool) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]bool, 0) + } + groups[group] = append(groups[group], val) + return true + }) + return &Value{data: groups} +} + +// ReplaceBool uses the specified function to replace each bools +// by iterating each item. The data in the returned result will be a +// []bool containing the replaced items. +func (v *Value) ReplaceBool(replacer func(int, bool) bool) *Value { + arr := v.MustBoolSlice() + replaced := make([]bool, len(arr)) + v.EachBool(func(index int, val bool) bool { + replaced[index] = replacer(index, val) + return true + }) + return &Value{data: replaced} +} + +// CollectBool uses the specified collector function to collect a value +// for each of the bools in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectBool(collector func(int, bool) interface{}) *Value { + arr := v.MustBoolSlice() + collected := make([]interface{}, len(arr)) + v.EachBool(func(index int, val bool) bool { + collected[index] = collector(index, val) + return true + }) + return &Value{data: collected} +} + +/* + Str (string and []string) +*/ + +// Str gets the value as a string, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Str(optionalDefault ...string) string { + if s, ok := v.data.(string); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return "" +} + +// MustStr gets the value as a string. +// +// Panics if the object is not a string. +func (v *Value) MustStr() string { + return v.data.(string) +} + +// StrSlice gets the value as a []string, returns the optionalDefault +// value or nil if the value is not a []string. +func (v *Value) StrSlice(optionalDefault ...[]string) []string { + if s, ok := v.data.([]string); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustStrSlice gets the value as a []string. +// +// Panics if the object is not a []string. +func (v *Value) MustStrSlice() []string { + return v.data.([]string) +} + +// IsStr gets whether the object contained is a string or not. +func (v *Value) IsStr() bool { + _, ok := v.data.(string) + return ok +} + +// IsStrSlice gets whether the object contained is a []string or not. +func (v *Value) IsStrSlice() bool { + _, ok := v.data.([]string) + return ok +} + +// EachStr calls the specified callback for each object +// in the []string. +// +// Panics if the object is the wrong type. +func (v *Value) EachStr(callback func(int, string) bool) *Value { + for index, val := range v.MustStrSlice() { + carryon := callback(index, val) + if !carryon { + break + } + } + return v +} + +// WhereStr uses the specified decider function to select items +// from the []string. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereStr(decider func(int, string) bool) *Value { + var selected []string + v.EachStr(func(index int, val string) bool { + shouldSelect := decider(index, val) + if !shouldSelect { + selected = append(selected, val) + } + return true + }) + return &Value{data: selected} +} + +// GroupStr uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]string. +func (v *Value) GroupStr(grouper func(int, string) string) *Value { + groups := make(map[string][]string) + v.EachStr(func(index int, val string) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]string, 0) + } + groups[group] = append(groups[group], val) + return true + }) + return &Value{data: groups} +} + +// ReplaceStr uses the specified function to replace each strings +// by iterating each item. The data in the returned result will be a +// []string containing the replaced items. +func (v *Value) ReplaceStr(replacer func(int, string) string) *Value { + arr := v.MustStrSlice() + replaced := make([]string, len(arr)) + v.EachStr(func(index int, val string) bool { + replaced[index] = replacer(index, val) + return true + }) + return &Value{data: replaced} +} + +// CollectStr uses the specified collector function to collect a value +// for each of the strings in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectStr(collector func(int, string) interface{}) *Value { + arr := v.MustStrSlice() + collected := make([]interface{}, len(arr)) + v.EachStr(func(index int, val string) bool { + collected[index] = collector(index, val) + return true + }) + return &Value{data: collected} +} + +/* + Int (int and []int) +*/ + +// Int gets the value as a int, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Int(optionalDefault ...int) int { + if s, ok := v.data.(int); ok { + return s + } + if s, ok := v.data.(float64); ok { + if float64(int(s)) == s { + return int(s) + } + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustInt gets the value as a int. +// +// Panics if the object is not a int. +func (v *Value) MustInt() int { + if s, ok := v.data.(float64); ok { + if float64(int(s)) == s { + return int(s) + } + } + return v.data.(int) +} + +// IntSlice gets the value as a []int, returns the optionalDefault +// value or nil if the value is not a []int. +func (v *Value) IntSlice(optionalDefault ...[]int) []int { + if s, ok := v.data.([]int); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustIntSlice gets the value as a []int. +// +// Panics if the object is not a []int. +func (v *Value) MustIntSlice() []int { + return v.data.([]int) +} + +// IsInt gets whether the object contained is a int or not. +func (v *Value) IsInt() bool { + _, ok := v.data.(int) + return ok +} + +// IsIntSlice gets whether the object contained is a []int or not. +func (v *Value) IsIntSlice() bool { + _, ok := v.data.([]int) + return ok +} + +// EachInt calls the specified callback for each object +// in the []int. +// +// Panics if the object is the wrong type. +func (v *Value) EachInt(callback func(int, int) bool) *Value { + for index, val := range v.MustIntSlice() { + carryon := callback(index, val) + if !carryon { + break + } + } + return v +} + +// WhereInt uses the specified decider function to select items +// from the []int. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereInt(decider func(int, int) bool) *Value { + var selected []int + v.EachInt(func(index int, val int) bool { + shouldSelect := decider(index, val) + if !shouldSelect { + selected = append(selected, val) + } + return true + }) + return &Value{data: selected} +} + +// GroupInt uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]int. +func (v *Value) GroupInt(grouper func(int, int) string) *Value { + groups := make(map[string][]int) + v.EachInt(func(index int, val int) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]int, 0) + } + groups[group] = append(groups[group], val) + return true + }) + return &Value{data: groups} +} + +// ReplaceInt uses the specified function to replace each ints +// by iterating each item. The data in the returned result will be a +// []int containing the replaced items. +func (v *Value) ReplaceInt(replacer func(int, int) int) *Value { + arr := v.MustIntSlice() + replaced := make([]int, len(arr)) + v.EachInt(func(index int, val int) bool { + replaced[index] = replacer(index, val) + return true + }) + return &Value{data: replaced} +} + +// CollectInt uses the specified collector function to collect a value +// for each of the ints in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectInt(collector func(int, int) interface{}) *Value { + arr := v.MustIntSlice() + collected := make([]interface{}, len(arr)) + v.EachInt(func(index int, val int) bool { + collected[index] = collector(index, val) + return true + }) + return &Value{data: collected} +} + +/* + Int8 (int8 and []int8) +*/ + +// Int8 gets the value as a int8, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Int8(optionalDefault ...int8) int8 { + if s, ok := v.data.(int8); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustInt8 gets the value as a int8. +// +// Panics if the object is not a int8. +func (v *Value) MustInt8() int8 { + return v.data.(int8) +} + +// Int8Slice gets the value as a []int8, returns the optionalDefault +// value or nil if the value is not a []int8. +func (v *Value) Int8Slice(optionalDefault ...[]int8) []int8 { + if s, ok := v.data.([]int8); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustInt8Slice gets the value as a []int8. +// +// Panics if the object is not a []int8. +func (v *Value) MustInt8Slice() []int8 { + return v.data.([]int8) +} + +// IsInt8 gets whether the object contained is a int8 or not. +func (v *Value) IsInt8() bool { + _, ok := v.data.(int8) + return ok +} + +// IsInt8Slice gets whether the object contained is a []int8 or not. +func (v *Value) IsInt8Slice() bool { + _, ok := v.data.([]int8) + return ok +} + +// EachInt8 calls the specified callback for each object +// in the []int8. +// +// Panics if the object is the wrong type. +func (v *Value) EachInt8(callback func(int, int8) bool) *Value { + for index, val := range v.MustInt8Slice() { + carryon := callback(index, val) + if !carryon { + break + } + } + return v +} + +// WhereInt8 uses the specified decider function to select items +// from the []int8. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereInt8(decider func(int, int8) bool) *Value { + var selected []int8 + v.EachInt8(func(index int, val int8) bool { + shouldSelect := decider(index, val) + if !shouldSelect { + selected = append(selected, val) + } + return true + }) + return &Value{data: selected} +} + +// GroupInt8 uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]int8. +func (v *Value) GroupInt8(grouper func(int, int8) string) *Value { + groups := make(map[string][]int8) + v.EachInt8(func(index int, val int8) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]int8, 0) + } + groups[group] = append(groups[group], val) + return true + }) + return &Value{data: groups} +} + +// ReplaceInt8 uses the specified function to replace each int8s +// by iterating each item. The data in the returned result will be a +// []int8 containing the replaced items. +func (v *Value) ReplaceInt8(replacer func(int, int8) int8) *Value { + arr := v.MustInt8Slice() + replaced := make([]int8, len(arr)) + v.EachInt8(func(index int, val int8) bool { + replaced[index] = replacer(index, val) + return true + }) + return &Value{data: replaced} +} + +// CollectInt8 uses the specified collector function to collect a value +// for each of the int8s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectInt8(collector func(int, int8) interface{}) *Value { + arr := v.MustInt8Slice() + collected := make([]interface{}, len(arr)) + v.EachInt8(func(index int, val int8) bool { + collected[index] = collector(index, val) + return true + }) + return &Value{data: collected} +} + +/* + Int16 (int16 and []int16) +*/ + +// Int16 gets the value as a int16, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Int16(optionalDefault ...int16) int16 { + if s, ok := v.data.(int16); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustInt16 gets the value as a int16. +// +// Panics if the object is not a int16. +func (v *Value) MustInt16() int16 { + return v.data.(int16) +} + +// Int16Slice gets the value as a []int16, returns the optionalDefault +// value or nil if the value is not a []int16. +func (v *Value) Int16Slice(optionalDefault ...[]int16) []int16 { + if s, ok := v.data.([]int16); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustInt16Slice gets the value as a []int16. +// +// Panics if the object is not a []int16. +func (v *Value) MustInt16Slice() []int16 { + return v.data.([]int16) +} + +// IsInt16 gets whether the object contained is a int16 or not. +func (v *Value) IsInt16() bool { + _, ok := v.data.(int16) + return ok +} + +// IsInt16Slice gets whether the object contained is a []int16 or not. +func (v *Value) IsInt16Slice() bool { + _, ok := v.data.([]int16) + return ok +} + +// EachInt16 calls the specified callback for each object +// in the []int16. +// +// Panics if the object is the wrong type. +func (v *Value) EachInt16(callback func(int, int16) bool) *Value { + for index, val := range v.MustInt16Slice() { + carryon := callback(index, val) + if !carryon { + break + } + } + return v +} + +// WhereInt16 uses the specified decider function to select items +// from the []int16. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereInt16(decider func(int, int16) bool) *Value { + var selected []int16 + v.EachInt16(func(index int, val int16) bool { + shouldSelect := decider(index, val) + if !shouldSelect { + selected = append(selected, val) + } + return true + }) + return &Value{data: selected} +} + +// GroupInt16 uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]int16. +func (v *Value) GroupInt16(grouper func(int, int16) string) *Value { + groups := make(map[string][]int16) + v.EachInt16(func(index int, val int16) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]int16, 0) + } + groups[group] = append(groups[group], val) + return true + }) + return &Value{data: groups} +} + +// ReplaceInt16 uses the specified function to replace each int16s +// by iterating each item. The data in the returned result will be a +// []int16 containing the replaced items. +func (v *Value) ReplaceInt16(replacer func(int, int16) int16) *Value { + arr := v.MustInt16Slice() + replaced := make([]int16, len(arr)) + v.EachInt16(func(index int, val int16) bool { + replaced[index] = replacer(index, val) + return true + }) + return &Value{data: replaced} +} + +// CollectInt16 uses the specified collector function to collect a value +// for each of the int16s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectInt16(collector func(int, int16) interface{}) *Value { + arr := v.MustInt16Slice() + collected := make([]interface{}, len(arr)) + v.EachInt16(func(index int, val int16) bool { + collected[index] = collector(index, val) + return true + }) + return &Value{data: collected} +} + +/* + Int32 (int32 and []int32) +*/ + +// Int32 gets the value as a int32, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Int32(optionalDefault ...int32) int32 { + if s, ok := v.data.(int32); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustInt32 gets the value as a int32. +// +// Panics if the object is not a int32. +func (v *Value) MustInt32() int32 { + return v.data.(int32) +} + +// Int32Slice gets the value as a []int32, returns the optionalDefault +// value or nil if the value is not a []int32. +func (v *Value) Int32Slice(optionalDefault ...[]int32) []int32 { + if s, ok := v.data.([]int32); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustInt32Slice gets the value as a []int32. +// +// Panics if the object is not a []int32. +func (v *Value) MustInt32Slice() []int32 { + return v.data.([]int32) +} + +// IsInt32 gets whether the object contained is a int32 or not. +func (v *Value) IsInt32() bool { + _, ok := v.data.(int32) + return ok +} + +// IsInt32Slice gets whether the object contained is a []int32 or not. +func (v *Value) IsInt32Slice() bool { + _, ok := v.data.([]int32) + return ok +} + +// EachInt32 calls the specified callback for each object +// in the []int32. +// +// Panics if the object is the wrong type. +func (v *Value) EachInt32(callback func(int, int32) bool) *Value { + for index, val := range v.MustInt32Slice() { + carryon := callback(index, val) + if !carryon { + break + } + } + return v +} + +// WhereInt32 uses the specified decider function to select items +// from the []int32. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereInt32(decider func(int, int32) bool) *Value { + var selected []int32 + v.EachInt32(func(index int, val int32) bool { + shouldSelect := decider(index, val) + if !shouldSelect { + selected = append(selected, val) + } + return true + }) + return &Value{data: selected} +} + +// GroupInt32 uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]int32. +func (v *Value) GroupInt32(grouper func(int, int32) string) *Value { + groups := make(map[string][]int32) + v.EachInt32(func(index int, val int32) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]int32, 0) + } + groups[group] = append(groups[group], val) + return true + }) + return &Value{data: groups} +} + +// ReplaceInt32 uses the specified function to replace each int32s +// by iterating each item. The data in the returned result will be a +// []int32 containing the replaced items. +func (v *Value) ReplaceInt32(replacer func(int, int32) int32) *Value { + arr := v.MustInt32Slice() + replaced := make([]int32, len(arr)) + v.EachInt32(func(index int, val int32) bool { + replaced[index] = replacer(index, val) + return true + }) + return &Value{data: replaced} +} + +// CollectInt32 uses the specified collector function to collect a value +// for each of the int32s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectInt32(collector func(int, int32) interface{}) *Value { + arr := v.MustInt32Slice() + collected := make([]interface{}, len(arr)) + v.EachInt32(func(index int, val int32) bool { + collected[index] = collector(index, val) + return true + }) + return &Value{data: collected} +} + +/* + Int64 (int64 and []int64) +*/ + +// Int64 gets the value as a int64, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Int64(optionalDefault ...int64) int64 { + if s, ok := v.data.(int64); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustInt64 gets the value as a int64. +// +// Panics if the object is not a int64. +func (v *Value) MustInt64() int64 { + return v.data.(int64) +} + +// Int64Slice gets the value as a []int64, returns the optionalDefault +// value or nil if the value is not a []int64. +func (v *Value) Int64Slice(optionalDefault ...[]int64) []int64 { + if s, ok := v.data.([]int64); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustInt64Slice gets the value as a []int64. +// +// Panics if the object is not a []int64. +func (v *Value) MustInt64Slice() []int64 { + return v.data.([]int64) +} + +// IsInt64 gets whether the object contained is a int64 or not. +func (v *Value) IsInt64() bool { + _, ok := v.data.(int64) + return ok +} + +// IsInt64Slice gets whether the object contained is a []int64 or not. +func (v *Value) IsInt64Slice() bool { + _, ok := v.data.([]int64) + return ok +} + +// EachInt64 calls the specified callback for each object +// in the []int64. +// +// Panics if the object is the wrong type. +func (v *Value) EachInt64(callback func(int, int64) bool) *Value { + for index, val := range v.MustInt64Slice() { + carryon := callback(index, val) + if !carryon { + break + } + } + return v +} + +// WhereInt64 uses the specified decider function to select items +// from the []int64. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereInt64(decider func(int, int64) bool) *Value { + var selected []int64 + v.EachInt64(func(index int, val int64) bool { + shouldSelect := decider(index, val) + if !shouldSelect { + selected = append(selected, val) + } + return true + }) + return &Value{data: selected} +} + +// GroupInt64 uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]int64. +func (v *Value) GroupInt64(grouper func(int, int64) string) *Value { + groups := make(map[string][]int64) + v.EachInt64(func(index int, val int64) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]int64, 0) + } + groups[group] = append(groups[group], val) + return true + }) + return &Value{data: groups} +} + +// ReplaceInt64 uses the specified function to replace each int64s +// by iterating each item. The data in the returned result will be a +// []int64 containing the replaced items. +func (v *Value) ReplaceInt64(replacer func(int, int64) int64) *Value { + arr := v.MustInt64Slice() + replaced := make([]int64, len(arr)) + v.EachInt64(func(index int, val int64) bool { + replaced[index] = replacer(index, val) + return true + }) + return &Value{data: replaced} +} + +// CollectInt64 uses the specified collector function to collect a value +// for each of the int64s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectInt64(collector func(int, int64) interface{}) *Value { + arr := v.MustInt64Slice() + collected := make([]interface{}, len(arr)) + v.EachInt64(func(index int, val int64) bool { + collected[index] = collector(index, val) + return true + }) + return &Value{data: collected} +} + +/* + Uint (uint and []uint) +*/ + +// Uint gets the value as a uint, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Uint(optionalDefault ...uint) uint { + if s, ok := v.data.(uint); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustUint gets the value as a uint. +// +// Panics if the object is not a uint. +func (v *Value) MustUint() uint { + return v.data.(uint) +} + +// UintSlice gets the value as a []uint, returns the optionalDefault +// value or nil if the value is not a []uint. +func (v *Value) UintSlice(optionalDefault ...[]uint) []uint { + if s, ok := v.data.([]uint); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustUintSlice gets the value as a []uint. +// +// Panics if the object is not a []uint. +func (v *Value) MustUintSlice() []uint { + return v.data.([]uint) +} + +// IsUint gets whether the object contained is a uint or not. +func (v *Value) IsUint() bool { + _, ok := v.data.(uint) + return ok +} + +// IsUintSlice gets whether the object contained is a []uint or not. +func (v *Value) IsUintSlice() bool { + _, ok := v.data.([]uint) + return ok +} + +// EachUint calls the specified callback for each object +// in the []uint. +// +// Panics if the object is the wrong type. +func (v *Value) EachUint(callback func(int, uint) bool) *Value { + for index, val := range v.MustUintSlice() { + carryon := callback(index, val) + if !carryon { + break + } + } + return v +} + +// WhereUint uses the specified decider function to select items +// from the []uint. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereUint(decider func(int, uint) bool) *Value { + var selected []uint + v.EachUint(func(index int, val uint) bool { + shouldSelect := decider(index, val) + if !shouldSelect { + selected = append(selected, val) + } + return true + }) + return &Value{data: selected} +} + +// GroupUint uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]uint. +func (v *Value) GroupUint(grouper func(int, uint) string) *Value { + groups := make(map[string][]uint) + v.EachUint(func(index int, val uint) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]uint, 0) + } + groups[group] = append(groups[group], val) + return true + }) + return &Value{data: groups} +} + +// ReplaceUint uses the specified function to replace each uints +// by iterating each item. The data in the returned result will be a +// []uint containing the replaced items. +func (v *Value) ReplaceUint(replacer func(int, uint) uint) *Value { + arr := v.MustUintSlice() + replaced := make([]uint, len(arr)) + v.EachUint(func(index int, val uint) bool { + replaced[index] = replacer(index, val) + return true + }) + return &Value{data: replaced} +} + +// CollectUint uses the specified collector function to collect a value +// for each of the uints in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectUint(collector func(int, uint) interface{}) *Value { + arr := v.MustUintSlice() + collected := make([]interface{}, len(arr)) + v.EachUint(func(index int, val uint) bool { + collected[index] = collector(index, val) + return true + }) + return &Value{data: collected} +} + +/* + Uint8 (uint8 and []uint8) +*/ + +// Uint8 gets the value as a uint8, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Uint8(optionalDefault ...uint8) uint8 { + if s, ok := v.data.(uint8); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustUint8 gets the value as a uint8. +// +// Panics if the object is not a uint8. +func (v *Value) MustUint8() uint8 { + return v.data.(uint8) +} + +// Uint8Slice gets the value as a []uint8, returns the optionalDefault +// value or nil if the value is not a []uint8. +func (v *Value) Uint8Slice(optionalDefault ...[]uint8) []uint8 { + if s, ok := v.data.([]uint8); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustUint8Slice gets the value as a []uint8. +// +// Panics if the object is not a []uint8. +func (v *Value) MustUint8Slice() []uint8 { + return v.data.([]uint8) +} + +// IsUint8 gets whether the object contained is a uint8 or not. +func (v *Value) IsUint8() bool { + _, ok := v.data.(uint8) + return ok +} + +// IsUint8Slice gets whether the object contained is a []uint8 or not. +func (v *Value) IsUint8Slice() bool { + _, ok := v.data.([]uint8) + return ok +} + +// EachUint8 calls the specified callback for each object +// in the []uint8. +// +// Panics if the object is the wrong type. +func (v *Value) EachUint8(callback func(int, uint8) bool) *Value { + for index, val := range v.MustUint8Slice() { + carryon := callback(index, val) + if !carryon { + break + } + } + return v +} + +// WhereUint8 uses the specified decider function to select items +// from the []uint8. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereUint8(decider func(int, uint8) bool) *Value { + var selected []uint8 + v.EachUint8(func(index int, val uint8) bool { + shouldSelect := decider(index, val) + if !shouldSelect { + selected = append(selected, val) + } + return true + }) + return &Value{data: selected} +} + +// GroupUint8 uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]uint8. +func (v *Value) GroupUint8(grouper func(int, uint8) string) *Value { + groups := make(map[string][]uint8) + v.EachUint8(func(index int, val uint8) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]uint8, 0) + } + groups[group] = append(groups[group], val) + return true + }) + return &Value{data: groups} +} + +// ReplaceUint8 uses the specified function to replace each uint8s +// by iterating each item. The data in the returned result will be a +// []uint8 containing the replaced items. +func (v *Value) ReplaceUint8(replacer func(int, uint8) uint8) *Value { + arr := v.MustUint8Slice() + replaced := make([]uint8, len(arr)) + v.EachUint8(func(index int, val uint8) bool { + replaced[index] = replacer(index, val) + return true + }) + return &Value{data: replaced} +} + +// CollectUint8 uses the specified collector function to collect a value +// for each of the uint8s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectUint8(collector func(int, uint8) interface{}) *Value { + arr := v.MustUint8Slice() + collected := make([]interface{}, len(arr)) + v.EachUint8(func(index int, val uint8) bool { + collected[index] = collector(index, val) + return true + }) + return &Value{data: collected} +} + +/* + Uint16 (uint16 and []uint16) +*/ + +// Uint16 gets the value as a uint16, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Uint16(optionalDefault ...uint16) uint16 { + if s, ok := v.data.(uint16); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustUint16 gets the value as a uint16. +// +// Panics if the object is not a uint16. +func (v *Value) MustUint16() uint16 { + return v.data.(uint16) +} + +// Uint16Slice gets the value as a []uint16, returns the optionalDefault +// value or nil if the value is not a []uint16. +func (v *Value) Uint16Slice(optionalDefault ...[]uint16) []uint16 { + if s, ok := v.data.([]uint16); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustUint16Slice gets the value as a []uint16. +// +// Panics if the object is not a []uint16. +func (v *Value) MustUint16Slice() []uint16 { + return v.data.([]uint16) +} + +// IsUint16 gets whether the object contained is a uint16 or not. +func (v *Value) IsUint16() bool { + _, ok := v.data.(uint16) + return ok +} + +// IsUint16Slice gets whether the object contained is a []uint16 or not. +func (v *Value) IsUint16Slice() bool { + _, ok := v.data.([]uint16) + return ok +} + +// EachUint16 calls the specified callback for each object +// in the []uint16. +// +// Panics if the object is the wrong type. +func (v *Value) EachUint16(callback func(int, uint16) bool) *Value { + for index, val := range v.MustUint16Slice() { + carryon := callback(index, val) + if !carryon { + break + } + } + return v +} + +// WhereUint16 uses the specified decider function to select items +// from the []uint16. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereUint16(decider func(int, uint16) bool) *Value { + var selected []uint16 + v.EachUint16(func(index int, val uint16) bool { + shouldSelect := decider(index, val) + if !shouldSelect { + selected = append(selected, val) + } + return true + }) + return &Value{data: selected} +} + +// GroupUint16 uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]uint16. +func (v *Value) GroupUint16(grouper func(int, uint16) string) *Value { + groups := make(map[string][]uint16) + v.EachUint16(func(index int, val uint16) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]uint16, 0) + } + groups[group] = append(groups[group], val) + return true + }) + return &Value{data: groups} +} + +// ReplaceUint16 uses the specified function to replace each uint16s +// by iterating each item. The data in the returned result will be a +// []uint16 containing the replaced items. +func (v *Value) ReplaceUint16(replacer func(int, uint16) uint16) *Value { + arr := v.MustUint16Slice() + replaced := make([]uint16, len(arr)) + v.EachUint16(func(index int, val uint16) bool { + replaced[index] = replacer(index, val) + return true + }) + return &Value{data: replaced} +} + +// CollectUint16 uses the specified collector function to collect a value +// for each of the uint16s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectUint16(collector func(int, uint16) interface{}) *Value { + arr := v.MustUint16Slice() + collected := make([]interface{}, len(arr)) + v.EachUint16(func(index int, val uint16) bool { + collected[index] = collector(index, val) + return true + }) + return &Value{data: collected} +} + +/* + Uint32 (uint32 and []uint32) +*/ + +// Uint32 gets the value as a uint32, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Uint32(optionalDefault ...uint32) uint32 { + if s, ok := v.data.(uint32); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustUint32 gets the value as a uint32. +// +// Panics if the object is not a uint32. +func (v *Value) MustUint32() uint32 { + return v.data.(uint32) +} + +// Uint32Slice gets the value as a []uint32, returns the optionalDefault +// value or nil if the value is not a []uint32. +func (v *Value) Uint32Slice(optionalDefault ...[]uint32) []uint32 { + if s, ok := v.data.([]uint32); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustUint32Slice gets the value as a []uint32. +// +// Panics if the object is not a []uint32. +func (v *Value) MustUint32Slice() []uint32 { + return v.data.([]uint32) +} + +// IsUint32 gets whether the object contained is a uint32 or not. +func (v *Value) IsUint32() bool { + _, ok := v.data.(uint32) + return ok +} + +// IsUint32Slice gets whether the object contained is a []uint32 or not. +func (v *Value) IsUint32Slice() bool { + _, ok := v.data.([]uint32) + return ok +} + +// EachUint32 calls the specified callback for each object +// in the []uint32. +// +// Panics if the object is the wrong type. +func (v *Value) EachUint32(callback func(int, uint32) bool) *Value { + for index, val := range v.MustUint32Slice() { + carryon := callback(index, val) + if !carryon { + break + } + } + return v +} + +// WhereUint32 uses the specified decider function to select items +// from the []uint32. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereUint32(decider func(int, uint32) bool) *Value { + var selected []uint32 + v.EachUint32(func(index int, val uint32) bool { + shouldSelect := decider(index, val) + if !shouldSelect { + selected = append(selected, val) + } + return true + }) + return &Value{data: selected} +} + +// GroupUint32 uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]uint32. +func (v *Value) GroupUint32(grouper func(int, uint32) string) *Value { + groups := make(map[string][]uint32) + v.EachUint32(func(index int, val uint32) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]uint32, 0) + } + groups[group] = append(groups[group], val) + return true + }) + return &Value{data: groups} +} + +// ReplaceUint32 uses the specified function to replace each uint32s +// by iterating each item. The data in the returned result will be a +// []uint32 containing the replaced items. +func (v *Value) ReplaceUint32(replacer func(int, uint32) uint32) *Value { + arr := v.MustUint32Slice() + replaced := make([]uint32, len(arr)) + v.EachUint32(func(index int, val uint32) bool { + replaced[index] = replacer(index, val) + return true + }) + return &Value{data: replaced} +} + +// CollectUint32 uses the specified collector function to collect a value +// for each of the uint32s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectUint32(collector func(int, uint32) interface{}) *Value { + arr := v.MustUint32Slice() + collected := make([]interface{}, len(arr)) + v.EachUint32(func(index int, val uint32) bool { + collected[index] = collector(index, val) + return true + }) + return &Value{data: collected} +} + +/* + Uint64 (uint64 and []uint64) +*/ + +// Uint64 gets the value as a uint64, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Uint64(optionalDefault ...uint64) uint64 { + if s, ok := v.data.(uint64); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustUint64 gets the value as a uint64. +// +// Panics if the object is not a uint64. +func (v *Value) MustUint64() uint64 { + return v.data.(uint64) +} + +// Uint64Slice gets the value as a []uint64, returns the optionalDefault +// value or nil if the value is not a []uint64. +func (v *Value) Uint64Slice(optionalDefault ...[]uint64) []uint64 { + if s, ok := v.data.([]uint64); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustUint64Slice gets the value as a []uint64. +// +// Panics if the object is not a []uint64. +func (v *Value) MustUint64Slice() []uint64 { + return v.data.([]uint64) +} + +// IsUint64 gets whether the object contained is a uint64 or not. +func (v *Value) IsUint64() bool { + _, ok := v.data.(uint64) + return ok +} + +// IsUint64Slice gets whether the object contained is a []uint64 or not. +func (v *Value) IsUint64Slice() bool { + _, ok := v.data.([]uint64) + return ok +} + +// EachUint64 calls the specified callback for each object +// in the []uint64. +// +// Panics if the object is the wrong type. +func (v *Value) EachUint64(callback func(int, uint64) bool) *Value { + for index, val := range v.MustUint64Slice() { + carryon := callback(index, val) + if !carryon { + break + } + } + return v +} + +// WhereUint64 uses the specified decider function to select items +// from the []uint64. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereUint64(decider func(int, uint64) bool) *Value { + var selected []uint64 + v.EachUint64(func(index int, val uint64) bool { + shouldSelect := decider(index, val) + if !shouldSelect { + selected = append(selected, val) + } + return true + }) + return &Value{data: selected} +} + +// GroupUint64 uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]uint64. +func (v *Value) GroupUint64(grouper func(int, uint64) string) *Value { + groups := make(map[string][]uint64) + v.EachUint64(func(index int, val uint64) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]uint64, 0) + } + groups[group] = append(groups[group], val) + return true + }) + return &Value{data: groups} +} + +// ReplaceUint64 uses the specified function to replace each uint64s +// by iterating each item. The data in the returned result will be a +// []uint64 containing the replaced items. +func (v *Value) ReplaceUint64(replacer func(int, uint64) uint64) *Value { + arr := v.MustUint64Slice() + replaced := make([]uint64, len(arr)) + v.EachUint64(func(index int, val uint64) bool { + replaced[index] = replacer(index, val) + return true + }) + return &Value{data: replaced} +} + +// CollectUint64 uses the specified collector function to collect a value +// for each of the uint64s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectUint64(collector func(int, uint64) interface{}) *Value { + arr := v.MustUint64Slice() + collected := make([]interface{}, len(arr)) + v.EachUint64(func(index int, val uint64) bool { + collected[index] = collector(index, val) + return true + }) + return &Value{data: collected} +} + +/* + Uintptr (uintptr and []uintptr) +*/ + +// Uintptr gets the value as a uintptr, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Uintptr(optionalDefault ...uintptr) uintptr { + if s, ok := v.data.(uintptr); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustUintptr gets the value as a uintptr. +// +// Panics if the object is not a uintptr. +func (v *Value) MustUintptr() uintptr { + return v.data.(uintptr) +} + +// UintptrSlice gets the value as a []uintptr, returns the optionalDefault +// value or nil if the value is not a []uintptr. +func (v *Value) UintptrSlice(optionalDefault ...[]uintptr) []uintptr { + if s, ok := v.data.([]uintptr); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustUintptrSlice gets the value as a []uintptr. +// +// Panics if the object is not a []uintptr. +func (v *Value) MustUintptrSlice() []uintptr { + return v.data.([]uintptr) +} + +// IsUintptr gets whether the object contained is a uintptr or not. +func (v *Value) IsUintptr() bool { + _, ok := v.data.(uintptr) + return ok +} + +// IsUintptrSlice gets whether the object contained is a []uintptr or not. +func (v *Value) IsUintptrSlice() bool { + _, ok := v.data.([]uintptr) + return ok +} + +// EachUintptr calls the specified callback for each object +// in the []uintptr. +// +// Panics if the object is the wrong type. +func (v *Value) EachUintptr(callback func(int, uintptr) bool) *Value { + for index, val := range v.MustUintptrSlice() { + carryon := callback(index, val) + if !carryon { + break + } + } + return v +} + +// WhereUintptr uses the specified decider function to select items +// from the []uintptr. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereUintptr(decider func(int, uintptr) bool) *Value { + var selected []uintptr + v.EachUintptr(func(index int, val uintptr) bool { + shouldSelect := decider(index, val) + if !shouldSelect { + selected = append(selected, val) + } + return true + }) + return &Value{data: selected} +} + +// GroupUintptr uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]uintptr. +func (v *Value) GroupUintptr(grouper func(int, uintptr) string) *Value { + groups := make(map[string][]uintptr) + v.EachUintptr(func(index int, val uintptr) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]uintptr, 0) + } + groups[group] = append(groups[group], val) + return true + }) + return &Value{data: groups} +} + +// ReplaceUintptr uses the specified function to replace each uintptrs +// by iterating each item. The data in the returned result will be a +// []uintptr containing the replaced items. +func (v *Value) ReplaceUintptr(replacer func(int, uintptr) uintptr) *Value { + arr := v.MustUintptrSlice() + replaced := make([]uintptr, len(arr)) + v.EachUintptr(func(index int, val uintptr) bool { + replaced[index] = replacer(index, val) + return true + }) + return &Value{data: replaced} +} + +// CollectUintptr uses the specified collector function to collect a value +// for each of the uintptrs in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectUintptr(collector func(int, uintptr) interface{}) *Value { + arr := v.MustUintptrSlice() + collected := make([]interface{}, len(arr)) + v.EachUintptr(func(index int, val uintptr) bool { + collected[index] = collector(index, val) + return true + }) + return &Value{data: collected} +} + +/* + Float32 (float32 and []float32) +*/ + +// Float32 gets the value as a float32, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Float32(optionalDefault ...float32) float32 { + if s, ok := v.data.(float32); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustFloat32 gets the value as a float32. +// +// Panics if the object is not a float32. +func (v *Value) MustFloat32() float32 { + return v.data.(float32) +} + +// Float32Slice gets the value as a []float32, returns the optionalDefault +// value or nil if the value is not a []float32. +func (v *Value) Float32Slice(optionalDefault ...[]float32) []float32 { + if s, ok := v.data.([]float32); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustFloat32Slice gets the value as a []float32. +// +// Panics if the object is not a []float32. +func (v *Value) MustFloat32Slice() []float32 { + return v.data.([]float32) +} + +// IsFloat32 gets whether the object contained is a float32 or not. +func (v *Value) IsFloat32() bool { + _, ok := v.data.(float32) + return ok +} + +// IsFloat32Slice gets whether the object contained is a []float32 or not. +func (v *Value) IsFloat32Slice() bool { + _, ok := v.data.([]float32) + return ok +} + +// EachFloat32 calls the specified callback for each object +// in the []float32. +// +// Panics if the object is the wrong type. +func (v *Value) EachFloat32(callback func(int, float32) bool) *Value { + for index, val := range v.MustFloat32Slice() { + carryon := callback(index, val) + if !carryon { + break + } + } + return v +} + +// WhereFloat32 uses the specified decider function to select items +// from the []float32. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereFloat32(decider func(int, float32) bool) *Value { + var selected []float32 + v.EachFloat32(func(index int, val float32) bool { + shouldSelect := decider(index, val) + if !shouldSelect { + selected = append(selected, val) + } + return true + }) + return &Value{data: selected} +} + +// GroupFloat32 uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]float32. +func (v *Value) GroupFloat32(grouper func(int, float32) string) *Value { + groups := make(map[string][]float32) + v.EachFloat32(func(index int, val float32) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]float32, 0) + } + groups[group] = append(groups[group], val) + return true + }) + return &Value{data: groups} +} + +// ReplaceFloat32 uses the specified function to replace each float32s +// by iterating each item. The data in the returned result will be a +// []float32 containing the replaced items. +func (v *Value) ReplaceFloat32(replacer func(int, float32) float32) *Value { + arr := v.MustFloat32Slice() + replaced := make([]float32, len(arr)) + v.EachFloat32(func(index int, val float32) bool { + replaced[index] = replacer(index, val) + return true + }) + return &Value{data: replaced} +} + +// CollectFloat32 uses the specified collector function to collect a value +// for each of the float32s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectFloat32(collector func(int, float32) interface{}) *Value { + arr := v.MustFloat32Slice() + collected := make([]interface{}, len(arr)) + v.EachFloat32(func(index int, val float32) bool { + collected[index] = collector(index, val) + return true + }) + return &Value{data: collected} +} + +/* + Float64 (float64 and []float64) +*/ + +// Float64 gets the value as a float64, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Float64(optionalDefault ...float64) float64 { + if s, ok := v.data.(float64); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustFloat64 gets the value as a float64. +// +// Panics if the object is not a float64. +func (v *Value) MustFloat64() float64 { + return v.data.(float64) +} + +// Float64Slice gets the value as a []float64, returns the optionalDefault +// value or nil if the value is not a []float64. +func (v *Value) Float64Slice(optionalDefault ...[]float64) []float64 { + if s, ok := v.data.([]float64); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustFloat64Slice gets the value as a []float64. +// +// Panics if the object is not a []float64. +func (v *Value) MustFloat64Slice() []float64 { + return v.data.([]float64) +} + +// IsFloat64 gets whether the object contained is a float64 or not. +func (v *Value) IsFloat64() bool { + _, ok := v.data.(float64) + return ok +} + +// IsFloat64Slice gets whether the object contained is a []float64 or not. +func (v *Value) IsFloat64Slice() bool { + _, ok := v.data.([]float64) + return ok +} + +// EachFloat64 calls the specified callback for each object +// in the []float64. +// +// Panics if the object is the wrong type. +func (v *Value) EachFloat64(callback func(int, float64) bool) *Value { + for index, val := range v.MustFloat64Slice() { + carryon := callback(index, val) + if !carryon { + break + } + } + return v +} + +// WhereFloat64 uses the specified decider function to select items +// from the []float64. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereFloat64(decider func(int, float64) bool) *Value { + var selected []float64 + v.EachFloat64(func(index int, val float64) bool { + shouldSelect := decider(index, val) + if !shouldSelect { + selected = append(selected, val) + } + return true + }) + return &Value{data: selected} +} + +// GroupFloat64 uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]float64. +func (v *Value) GroupFloat64(grouper func(int, float64) string) *Value { + groups := make(map[string][]float64) + v.EachFloat64(func(index int, val float64) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]float64, 0) + } + groups[group] = append(groups[group], val) + return true + }) + return &Value{data: groups} +} + +// ReplaceFloat64 uses the specified function to replace each float64s +// by iterating each item. The data in the returned result will be a +// []float64 containing the replaced items. +func (v *Value) ReplaceFloat64(replacer func(int, float64) float64) *Value { + arr := v.MustFloat64Slice() + replaced := make([]float64, len(arr)) + v.EachFloat64(func(index int, val float64) bool { + replaced[index] = replacer(index, val) + return true + }) + return &Value{data: replaced} +} + +// CollectFloat64 uses the specified collector function to collect a value +// for each of the float64s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectFloat64(collector func(int, float64) interface{}) *Value { + arr := v.MustFloat64Slice() + collected := make([]interface{}, len(arr)) + v.EachFloat64(func(index int, val float64) bool { + collected[index] = collector(index, val) + return true + }) + return &Value{data: collected} +} + +/* + Complex64 (complex64 and []complex64) +*/ + +// Complex64 gets the value as a complex64, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Complex64(optionalDefault ...complex64) complex64 { + if s, ok := v.data.(complex64); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustComplex64 gets the value as a complex64. +// +// Panics if the object is not a complex64. +func (v *Value) MustComplex64() complex64 { + return v.data.(complex64) +} + +// Complex64Slice gets the value as a []complex64, returns the optionalDefault +// value or nil if the value is not a []complex64. +func (v *Value) Complex64Slice(optionalDefault ...[]complex64) []complex64 { + if s, ok := v.data.([]complex64); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustComplex64Slice gets the value as a []complex64. +// +// Panics if the object is not a []complex64. +func (v *Value) MustComplex64Slice() []complex64 { + return v.data.([]complex64) +} + +// IsComplex64 gets whether the object contained is a complex64 or not. +func (v *Value) IsComplex64() bool { + _, ok := v.data.(complex64) + return ok +} + +// IsComplex64Slice gets whether the object contained is a []complex64 or not. +func (v *Value) IsComplex64Slice() bool { + _, ok := v.data.([]complex64) + return ok +} + +// EachComplex64 calls the specified callback for each object +// in the []complex64. +// +// Panics if the object is the wrong type. +func (v *Value) EachComplex64(callback func(int, complex64) bool) *Value { + for index, val := range v.MustComplex64Slice() { + carryon := callback(index, val) + if !carryon { + break + } + } + return v +} + +// WhereComplex64 uses the specified decider function to select items +// from the []complex64. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereComplex64(decider func(int, complex64) bool) *Value { + var selected []complex64 + v.EachComplex64(func(index int, val complex64) bool { + shouldSelect := decider(index, val) + if !shouldSelect { + selected = append(selected, val) + } + return true + }) + return &Value{data: selected} +} + +// GroupComplex64 uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]complex64. +func (v *Value) GroupComplex64(grouper func(int, complex64) string) *Value { + groups := make(map[string][]complex64) + v.EachComplex64(func(index int, val complex64) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]complex64, 0) + } + groups[group] = append(groups[group], val) + return true + }) + return &Value{data: groups} +} + +// ReplaceComplex64 uses the specified function to replace each complex64s +// by iterating each item. The data in the returned result will be a +// []complex64 containing the replaced items. +func (v *Value) ReplaceComplex64(replacer func(int, complex64) complex64) *Value { + arr := v.MustComplex64Slice() + replaced := make([]complex64, len(arr)) + v.EachComplex64(func(index int, val complex64) bool { + replaced[index] = replacer(index, val) + return true + }) + return &Value{data: replaced} +} + +// CollectComplex64 uses the specified collector function to collect a value +// for each of the complex64s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectComplex64(collector func(int, complex64) interface{}) *Value { + arr := v.MustComplex64Slice() + collected := make([]interface{}, len(arr)) + v.EachComplex64(func(index int, val complex64) bool { + collected[index] = collector(index, val) + return true + }) + return &Value{data: collected} +} + +/* + Complex128 (complex128 and []complex128) +*/ + +// Complex128 gets the value as a complex128, returns the optionalDefault +// value or a system default object if the value is the wrong type. +func (v *Value) Complex128(optionalDefault ...complex128) complex128 { + if s, ok := v.data.(complex128); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return 0 +} + +// MustComplex128 gets the value as a complex128. +// +// Panics if the object is not a complex128. +func (v *Value) MustComplex128() complex128 { + return v.data.(complex128) +} + +// Complex128Slice gets the value as a []complex128, returns the optionalDefault +// value or nil if the value is not a []complex128. +func (v *Value) Complex128Slice(optionalDefault ...[]complex128) []complex128 { + if s, ok := v.data.([]complex128); ok { + return s + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + return nil +} + +// MustComplex128Slice gets the value as a []complex128. +// +// Panics if the object is not a []complex128. +func (v *Value) MustComplex128Slice() []complex128 { + return v.data.([]complex128) +} + +// IsComplex128 gets whether the object contained is a complex128 or not. +func (v *Value) IsComplex128() bool { + _, ok := v.data.(complex128) + return ok +} + +// IsComplex128Slice gets whether the object contained is a []complex128 or not. +func (v *Value) IsComplex128Slice() bool { + _, ok := v.data.([]complex128) + return ok +} + +// EachComplex128 calls the specified callback for each object +// in the []complex128. +// +// Panics if the object is the wrong type. +func (v *Value) EachComplex128(callback func(int, complex128) bool) *Value { + for index, val := range v.MustComplex128Slice() { + carryon := callback(index, val) + if !carryon { + break + } + } + return v +} + +// WhereComplex128 uses the specified decider function to select items +// from the []complex128. The object contained in the result will contain +// only the selected items. +func (v *Value) WhereComplex128(decider func(int, complex128) bool) *Value { + var selected []complex128 + v.EachComplex128(func(index int, val complex128) bool { + shouldSelect := decider(index, val) + if !shouldSelect { + selected = append(selected, val) + } + return true + }) + return &Value{data: selected} +} + +// GroupComplex128 uses the specified grouper function to group the items +// keyed by the return of the grouper. The object contained in the +// result will contain a map[string][]complex128. +func (v *Value) GroupComplex128(grouper func(int, complex128) string) *Value { + groups := make(map[string][]complex128) + v.EachComplex128(func(index int, val complex128) bool { + group := grouper(index, val) + if _, ok := groups[group]; !ok { + groups[group] = make([]complex128, 0) + } + groups[group] = append(groups[group], val) + return true + }) + return &Value{data: groups} +} + +// ReplaceComplex128 uses the specified function to replace each complex128s +// by iterating each item. The data in the returned result will be a +// []complex128 containing the replaced items. +func (v *Value) ReplaceComplex128(replacer func(int, complex128) complex128) *Value { + arr := v.MustComplex128Slice() + replaced := make([]complex128, len(arr)) + v.EachComplex128(func(index int, val complex128) bool { + replaced[index] = replacer(index, val) + return true + }) + return &Value{data: replaced} +} + +// CollectComplex128 uses the specified collector function to collect a value +// for each of the complex128s in the slice. The data returned will be a +// []interface{}. +func (v *Value) CollectComplex128(collector func(int, complex128) interface{}) *Value { + arr := v.MustComplex128Slice() + collected := make([]interface{}, len(arr)) + v.EachComplex128(func(index int, val complex128) bool { + collected[index] = collector(index, val) + return true + }) + return &Value{data: collected} +} diff --git a/vendor/github.com/stretchr/objx/value.go b/vendor/github.com/stretchr/objx/value.go new file mode 100644 index 00000000000..4e5f9b77e69 --- /dev/null +++ b/vendor/github.com/stretchr/objx/value.go @@ -0,0 +1,159 @@ +package objx + +import ( + "fmt" + "strconv" +) + +// Value provides methods for extracting interface{} data in various +// types. +type Value struct { + // data contains the raw data being managed by this Value + data interface{} +} + +// Data returns the raw data contained by this Value +func (v *Value) Data() interface{} { + return v.data +} + +// String returns the value always as a string +func (v *Value) String() string { + switch { + case v.IsNil(): + return "" + case v.IsStr(): + return v.Str() + case v.IsBool(): + return strconv.FormatBool(v.Bool()) + case v.IsFloat32(): + return strconv.FormatFloat(float64(v.Float32()), 'f', -1, 32) + case v.IsFloat64(): + return strconv.FormatFloat(v.Float64(), 'f', -1, 64) + case v.IsInt(): + return strconv.FormatInt(int64(v.Int()), 10) + case v.IsInt8(): + return strconv.FormatInt(int64(v.Int8()), 10) + case v.IsInt16(): + return strconv.FormatInt(int64(v.Int16()), 10) + case v.IsInt32(): + return strconv.FormatInt(int64(v.Int32()), 10) + case v.IsInt64(): + return strconv.FormatInt(v.Int64(), 10) + case v.IsUint(): + return strconv.FormatUint(uint64(v.Uint()), 10) + case v.IsUint8(): + return strconv.FormatUint(uint64(v.Uint8()), 10) + case v.IsUint16(): + return strconv.FormatUint(uint64(v.Uint16()), 10) + case v.IsUint32(): + return strconv.FormatUint(uint64(v.Uint32()), 10) + case v.IsUint64(): + return strconv.FormatUint(v.Uint64(), 10) + } + return fmt.Sprintf("%#v", v.Data()) +} + +// StringSlice returns the value always as a []string +func (v *Value) StringSlice(optionalDefault ...[]string) []string { + switch { + case v.IsStrSlice(): + return v.MustStrSlice() + case v.IsBoolSlice(): + slice := v.MustBoolSlice() + vals := make([]string, len(slice)) + for i, iv := range slice { + vals[i] = strconv.FormatBool(iv) + } + return vals + case v.IsFloat32Slice(): + slice := v.MustFloat32Slice() + vals := make([]string, len(slice)) + for i, iv := range slice { + vals[i] = strconv.FormatFloat(float64(iv), 'f', -1, 32) + } + return vals + case v.IsFloat64Slice(): + slice := v.MustFloat64Slice() + vals := make([]string, len(slice)) + for i, iv := range slice { + vals[i] = strconv.FormatFloat(iv, 'f', -1, 64) + } + return vals + case v.IsIntSlice(): + slice := v.MustIntSlice() + vals := make([]string, len(slice)) + for i, iv := range slice { + vals[i] = strconv.FormatInt(int64(iv), 10) + } + return vals + case v.IsInt8Slice(): + slice := v.MustInt8Slice() + vals := make([]string, len(slice)) + for i, iv := range slice { + vals[i] = strconv.FormatInt(int64(iv), 10) + } + return vals + case v.IsInt16Slice(): + slice := v.MustInt16Slice() + vals := make([]string, len(slice)) + for i, iv := range slice { + vals[i] = strconv.FormatInt(int64(iv), 10) + } + return vals + case v.IsInt32Slice(): + slice := v.MustInt32Slice() + vals := make([]string, len(slice)) + for i, iv := range slice { + vals[i] = strconv.FormatInt(int64(iv), 10) + } + return vals + case v.IsInt64Slice(): + slice := v.MustInt64Slice() + vals := make([]string, len(slice)) + for i, iv := range slice { + vals[i] = strconv.FormatInt(iv, 10) + } + return vals + case v.IsUintSlice(): + slice := v.MustUintSlice() + vals := make([]string, len(slice)) + for i, iv := range slice { + vals[i] = strconv.FormatUint(uint64(iv), 10) + } + return vals + case v.IsUint8Slice(): + slice := v.MustUint8Slice() + vals := make([]string, len(slice)) + for i, iv := range slice { + vals[i] = strconv.FormatUint(uint64(iv), 10) + } + return vals + case v.IsUint16Slice(): + slice := v.MustUint16Slice() + vals := make([]string, len(slice)) + for i, iv := range slice { + vals[i] = strconv.FormatUint(uint64(iv), 10) + } + return vals + case v.IsUint32Slice(): + slice := v.MustUint32Slice() + vals := make([]string, len(slice)) + for i, iv := range slice { + vals[i] = strconv.FormatUint(uint64(iv), 10) + } + return vals + case v.IsUint64Slice(): + slice := v.MustUint64Slice() + vals := make([]string, len(slice)) + for i, iv := range slice { + vals[i] = strconv.FormatUint(iv, 10) + } + return vals + } + if len(optionalDefault) == 1 { + return optionalDefault[0] + } + + return []string{} +} diff --git a/vendor/github.com/stretchr/testify/assert/assertion_compare.go b/vendor/github.com/stretchr/testify/assert/assertion_compare.go index 95d8e59da69..b774da88d86 100644 --- a/vendor/github.com/stretchr/testify/assert/assertion_compare.go +++ b/vendor/github.com/stretchr/testify/assert/assertion_compare.go @@ -352,9 +352,9 @@ func compare(obj1, obj2 interface{}, kind reflect.Kind) (CompareType, bool) { // Greater asserts that the first element is greater than the second // -// assert.Greater(t, 2, 1) -// assert.Greater(t, float64(2), float64(1)) -// assert.Greater(t, "b", "a") +// assert.Greater(t, 2, 1) +// assert.Greater(t, float64(2), float64(1)) +// assert.Greater(t, "b", "a") func Greater(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -364,10 +364,10 @@ func Greater(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface // GreaterOrEqual asserts that the first element is greater than or equal to the second // -// assert.GreaterOrEqual(t, 2, 1) -// assert.GreaterOrEqual(t, 2, 2) -// assert.GreaterOrEqual(t, "b", "a") -// assert.GreaterOrEqual(t, "b", "b") +// assert.GreaterOrEqual(t, 2, 1) +// assert.GreaterOrEqual(t, 2, 2) +// assert.GreaterOrEqual(t, "b", "a") +// assert.GreaterOrEqual(t, "b", "b") func GreaterOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -377,9 +377,9 @@ func GreaterOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...in // Less asserts that the first element is less than the second // -// assert.Less(t, 1, 2) -// assert.Less(t, float64(1), float64(2)) -// assert.Less(t, "a", "b") +// assert.Less(t, 1, 2) +// assert.Less(t, float64(1), float64(2)) +// assert.Less(t, "a", "b") func Less(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -389,10 +389,10 @@ func Less(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) // LessOrEqual asserts that the first element is less than or equal to the second // -// assert.LessOrEqual(t, 1, 2) -// assert.LessOrEqual(t, 2, 2) -// assert.LessOrEqual(t, "a", "b") -// assert.LessOrEqual(t, "b", "b") +// assert.LessOrEqual(t, 1, 2) +// assert.LessOrEqual(t, 2, 2) +// assert.LessOrEqual(t, "a", "b") +// assert.LessOrEqual(t, "b", "b") func LessOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -402,8 +402,8 @@ func LessOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...inter // Positive asserts that the specified element is positive // -// assert.Positive(t, 1) -// assert.Positive(t, 1.23) +// assert.Positive(t, 1) +// assert.Positive(t, 1.23) func Positive(t TestingT, e interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -414,8 +414,8 @@ func Positive(t TestingT, e interface{}, msgAndArgs ...interface{}) bool { // Negative asserts that the specified element is negative // -// assert.Negative(t, -1) -// assert.Negative(t, -1.23) +// assert.Negative(t, -1) +// assert.Negative(t, -1.23) func Negative(t TestingT, e interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() diff --git a/vendor/github.com/stretchr/testify/assert/assertion_format.go b/vendor/github.com/stretchr/testify/assert/assertion_format.go index 7880b8f9433..84dbd6c790b 100644 --- a/vendor/github.com/stretchr/testify/assert/assertion_format.go +++ b/vendor/github.com/stretchr/testify/assert/assertion_format.go @@ -22,9 +22,9 @@ func Conditionf(t TestingT, comp Comparison, msg string, args ...interface{}) bo // Containsf asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // -// assert.Containsf(t, "Hello World", "World", "error message %s", "formatted") -// assert.Containsf(t, ["Hello", "World"], "World", "error message %s", "formatted") -// assert.Containsf(t, {"Hello": "World"}, "Hello", "error message %s", "formatted") +// assert.Containsf(t, "Hello World", "World", "error message %s", "formatted") +// assert.Containsf(t, ["Hello", "World"], "World", "error message %s", "formatted") +// assert.Containsf(t, {"Hello": "World"}, "Hello", "error message %s", "formatted") func Containsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -56,7 +56,7 @@ func ElementsMatchf(t TestingT, listA interface{}, listB interface{}, msg string // Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // -// assert.Emptyf(t, obj, "error message %s", "formatted") +// assert.Emptyf(t, obj, "error message %s", "formatted") func Emptyf(t TestingT, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -66,7 +66,7 @@ func Emptyf(t TestingT, object interface{}, msg string, args ...interface{}) boo // Equalf asserts that two objects are equal. // -// assert.Equalf(t, 123, 123, "error message %s", "formatted") +// assert.Equalf(t, 123, 123, "error message %s", "formatted") // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality @@ -81,8 +81,8 @@ func Equalf(t TestingT, expected interface{}, actual interface{}, msg string, ar // EqualErrorf asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // -// actualObj, err := SomeFunction() -// assert.EqualErrorf(t, err, expectedErrorString, "error message %s", "formatted") +// actualObj, err := SomeFunction() +// assert.EqualErrorf(t, err, expectedErrorString, "error message %s", "formatted") func EqualErrorf(t TestingT, theError error, errString string, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -90,10 +90,27 @@ func EqualErrorf(t TestingT, theError error, errString string, msg string, args return EqualError(t, theError, errString, append([]interface{}{msg}, args...)...) } +// EqualExportedValuesf asserts that the types of two objects are equal and their public +// fields are also equal. This is useful for comparing structs that have private fields +// that could potentially differ. +// +// type S struct { +// Exported int +// notExported int +// } +// assert.EqualExportedValuesf(t, S{1, 2}, S{1, 3}, "error message %s", "formatted") => true +// assert.EqualExportedValuesf(t, S{1, 2}, S{2, 3}, "error message %s", "formatted") => false +func EqualExportedValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return EqualExportedValues(t, expected, actual, append([]interface{}{msg}, args...)...) +} + // EqualValuesf asserts that two objects are equal or convertable to the same types // and equal. // -// assert.EqualValuesf(t, uint32(123), int32(123), "error message %s", "formatted") +// assert.EqualValuesf(t, uint32(123), int32(123), "error message %s", "formatted") func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -103,10 +120,10 @@ func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg stri // Errorf asserts that a function returned an error (i.e. not `nil`). // -// actualObj, err := SomeFunction() -// if assert.Errorf(t, err, "error message %s", "formatted") { -// assert.Equal(t, expectedErrorf, err) -// } +// actualObj, err := SomeFunction() +// if assert.Errorf(t, err, "error message %s", "formatted") { +// assert.Equal(t, expectedErrorf, err) +// } func Errorf(t TestingT, err error, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -126,8 +143,8 @@ func ErrorAsf(t TestingT, err error, target interface{}, msg string, args ...int // ErrorContainsf asserts that a function returned an error (i.e. not `nil`) // and that the error contains the specified substring. // -// actualObj, err := SomeFunction() -// assert.ErrorContainsf(t, err, expectedErrorSubString, "error message %s", "formatted") +// actualObj, err := SomeFunction() +// assert.ErrorContainsf(t, err, expectedErrorSubString, "error message %s", "formatted") func ErrorContainsf(t TestingT, theError error, contains string, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -147,7 +164,7 @@ func ErrorIsf(t TestingT, err error, target error, msg string, args ...interface // Eventuallyf asserts that given condition will be met in waitFor time, // periodically checking target function each tick. // -// assert.Eventuallyf(t, func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") +// assert.Eventuallyf(t, func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") func Eventuallyf(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -155,9 +172,34 @@ func Eventuallyf(t TestingT, condition func() bool, waitFor time.Duration, tick return Eventually(t, condition, waitFor, tick, append([]interface{}{msg}, args...)...) } +// EventuallyWithTf asserts that given condition will be met in waitFor time, +// periodically checking target function each tick. In contrast to Eventually, +// it supplies a CollectT to the condition function, so that the condition +// function can use the CollectT to call other assertions. +// The condition is considered "met" if no errors are raised in a tick. +// The supplied CollectT collects all errors from one tick (if there are any). +// If the condition is not met before waitFor, the collected errors of +// the last tick are copied to t. +// +// externalValue := false +// go func() { +// time.Sleep(8*time.Second) +// externalValue = true +// }() +// assert.EventuallyWithTf(t, func(c *assert.CollectT, "error message %s", "formatted") { +// // add assertions as needed; any assertion failure will fail the current tick +// assert.True(c, externalValue, "expected 'externalValue' to be true") +// }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false") +func EventuallyWithTf(t TestingT, condition func(collect *CollectT), waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return EventuallyWithT(t, condition, waitFor, tick, append([]interface{}{msg}, args...)...) +} + // Exactlyf asserts that two objects are equal in value and type. // -// assert.Exactlyf(t, int32(123), int64(123), "error message %s", "formatted") +// assert.Exactlyf(t, int32(123), int64(123), "error message %s", "formatted") func Exactlyf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -183,7 +225,7 @@ func FailNowf(t TestingT, failureMessage string, msg string, args ...interface{} // Falsef asserts that the specified value is false. // -// assert.Falsef(t, myBool, "error message %s", "formatted") +// assert.Falsef(t, myBool, "error message %s", "formatted") func Falsef(t TestingT, value bool, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -202,9 +244,9 @@ func FileExistsf(t TestingT, path string, msg string, args ...interface{}) bool // Greaterf asserts that the first element is greater than the second // -// assert.Greaterf(t, 2, 1, "error message %s", "formatted") -// assert.Greaterf(t, float64(2), float64(1), "error message %s", "formatted") -// assert.Greaterf(t, "b", "a", "error message %s", "formatted") +// assert.Greaterf(t, 2, 1, "error message %s", "formatted") +// assert.Greaterf(t, float64(2), float64(1), "error message %s", "formatted") +// assert.Greaterf(t, "b", "a", "error message %s", "formatted") func Greaterf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -214,10 +256,10 @@ func Greaterf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...in // GreaterOrEqualf asserts that the first element is greater than or equal to the second // -// assert.GreaterOrEqualf(t, 2, 1, "error message %s", "formatted") -// assert.GreaterOrEqualf(t, 2, 2, "error message %s", "formatted") -// assert.GreaterOrEqualf(t, "b", "a", "error message %s", "formatted") -// assert.GreaterOrEqualf(t, "b", "b", "error message %s", "formatted") +// assert.GreaterOrEqualf(t, 2, 1, "error message %s", "formatted") +// assert.GreaterOrEqualf(t, 2, 2, "error message %s", "formatted") +// assert.GreaterOrEqualf(t, "b", "a", "error message %s", "formatted") +// assert.GreaterOrEqualf(t, "b", "b", "error message %s", "formatted") func GreaterOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -228,7 +270,7 @@ func GreaterOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, arg // HTTPBodyContainsf asserts that a specified handler returns a // body that contains a string. // -// assert.HTTPBodyContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// assert.HTTPBodyContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool { @@ -241,7 +283,7 @@ func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url // HTTPBodyNotContainsf asserts that a specified handler returns a // body that does not contain a string. // -// assert.HTTPBodyNotContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// assert.HTTPBodyNotContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool { @@ -253,7 +295,7 @@ func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, u // HTTPErrorf asserts that a specified handler returns an error status code. // -// assert.HTTPErrorf(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// assert.HTTPErrorf(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { @@ -265,7 +307,7 @@ func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, // HTTPRedirectf asserts that a specified handler returns a redirect status code. // -// assert.HTTPRedirectf(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// assert.HTTPRedirectf(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { @@ -277,7 +319,7 @@ func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url stri // HTTPStatusCodef asserts that a specified handler returns a specified status code. // -// assert.HTTPStatusCodef(t, myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted") +// assert.HTTPStatusCodef(t, myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPStatusCodef(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msg string, args ...interface{}) bool { @@ -289,7 +331,7 @@ func HTTPStatusCodef(t TestingT, handler http.HandlerFunc, method string, url st // HTTPSuccessf asserts that a specified handler returns a success status code. // -// assert.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") +// assert.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { @@ -301,7 +343,7 @@ func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url strin // Implementsf asserts that an object is implemented by the specified interface. // -// assert.Implementsf(t, (*MyInterface)(nil), new(MyObject), "error message %s", "formatted") +// assert.Implementsf(t, (*MyInterface)(nil), new(MyObject), "error message %s", "formatted") func Implementsf(t TestingT, interfaceObject interface{}, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -311,7 +353,7 @@ func Implementsf(t TestingT, interfaceObject interface{}, object interface{}, ms // InDeltaf asserts that the two numerals are within delta of each other. // -// assert.InDeltaf(t, math.Pi, 22/7.0, 0.01, "error message %s", "formatted") +// assert.InDeltaf(t, math.Pi, 22/7.0, 0.01, "error message %s", "formatted") func InDeltaf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -353,9 +395,9 @@ func InEpsilonSlicef(t TestingT, expected interface{}, actual interface{}, epsil // IsDecreasingf asserts that the collection is decreasing // -// assert.IsDecreasingf(t, []int{2, 1, 0}, "error message %s", "formatted") -// assert.IsDecreasingf(t, []float{2, 1}, "error message %s", "formatted") -// assert.IsDecreasingf(t, []string{"b", "a"}, "error message %s", "formatted") +// assert.IsDecreasingf(t, []int{2, 1, 0}, "error message %s", "formatted") +// assert.IsDecreasingf(t, []float{2, 1}, "error message %s", "formatted") +// assert.IsDecreasingf(t, []string{"b", "a"}, "error message %s", "formatted") func IsDecreasingf(t TestingT, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -365,9 +407,9 @@ func IsDecreasingf(t TestingT, object interface{}, msg string, args ...interface // IsIncreasingf asserts that the collection is increasing // -// assert.IsIncreasingf(t, []int{1, 2, 3}, "error message %s", "formatted") -// assert.IsIncreasingf(t, []float{1, 2}, "error message %s", "formatted") -// assert.IsIncreasingf(t, []string{"a", "b"}, "error message %s", "formatted") +// assert.IsIncreasingf(t, []int{1, 2, 3}, "error message %s", "formatted") +// assert.IsIncreasingf(t, []float{1, 2}, "error message %s", "formatted") +// assert.IsIncreasingf(t, []string{"a", "b"}, "error message %s", "formatted") func IsIncreasingf(t TestingT, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -377,9 +419,9 @@ func IsIncreasingf(t TestingT, object interface{}, msg string, args ...interface // IsNonDecreasingf asserts that the collection is not decreasing // -// assert.IsNonDecreasingf(t, []int{1, 1, 2}, "error message %s", "formatted") -// assert.IsNonDecreasingf(t, []float{1, 2}, "error message %s", "formatted") -// assert.IsNonDecreasingf(t, []string{"a", "b"}, "error message %s", "formatted") +// assert.IsNonDecreasingf(t, []int{1, 1, 2}, "error message %s", "formatted") +// assert.IsNonDecreasingf(t, []float{1, 2}, "error message %s", "formatted") +// assert.IsNonDecreasingf(t, []string{"a", "b"}, "error message %s", "formatted") func IsNonDecreasingf(t TestingT, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -389,9 +431,9 @@ func IsNonDecreasingf(t TestingT, object interface{}, msg string, args ...interf // IsNonIncreasingf asserts that the collection is not increasing // -// assert.IsNonIncreasingf(t, []int{2, 1, 1}, "error message %s", "formatted") -// assert.IsNonIncreasingf(t, []float{2, 1}, "error message %s", "formatted") -// assert.IsNonIncreasingf(t, []string{"b", "a"}, "error message %s", "formatted") +// assert.IsNonIncreasingf(t, []int{2, 1, 1}, "error message %s", "formatted") +// assert.IsNonIncreasingf(t, []float{2, 1}, "error message %s", "formatted") +// assert.IsNonIncreasingf(t, []string{"b", "a"}, "error message %s", "formatted") func IsNonIncreasingf(t TestingT, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -409,7 +451,7 @@ func IsTypef(t TestingT, expectedType interface{}, object interface{}, msg strin // JSONEqf asserts that two JSON strings are equivalent. // -// assert.JSONEqf(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") +// assert.JSONEqf(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") func JSONEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -420,7 +462,7 @@ func JSONEqf(t TestingT, expected string, actual string, msg string, args ...int // Lenf asserts that the specified object has specific length. // Lenf also fails if the object has a type that len() not accept. // -// assert.Lenf(t, mySlice, 3, "error message %s", "formatted") +// assert.Lenf(t, mySlice, 3, "error message %s", "formatted") func Lenf(t TestingT, object interface{}, length int, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -430,9 +472,9 @@ func Lenf(t TestingT, object interface{}, length int, msg string, args ...interf // Lessf asserts that the first element is less than the second // -// assert.Lessf(t, 1, 2, "error message %s", "formatted") -// assert.Lessf(t, float64(1), float64(2), "error message %s", "formatted") -// assert.Lessf(t, "a", "b", "error message %s", "formatted") +// assert.Lessf(t, 1, 2, "error message %s", "formatted") +// assert.Lessf(t, float64(1), float64(2), "error message %s", "formatted") +// assert.Lessf(t, "a", "b", "error message %s", "formatted") func Lessf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -442,10 +484,10 @@ func Lessf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...inter // LessOrEqualf asserts that the first element is less than or equal to the second // -// assert.LessOrEqualf(t, 1, 2, "error message %s", "formatted") -// assert.LessOrEqualf(t, 2, 2, "error message %s", "formatted") -// assert.LessOrEqualf(t, "a", "b", "error message %s", "formatted") -// assert.LessOrEqualf(t, "b", "b", "error message %s", "formatted") +// assert.LessOrEqualf(t, 1, 2, "error message %s", "formatted") +// assert.LessOrEqualf(t, 2, 2, "error message %s", "formatted") +// assert.LessOrEqualf(t, "a", "b", "error message %s", "formatted") +// assert.LessOrEqualf(t, "b", "b", "error message %s", "formatted") func LessOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -455,8 +497,8 @@ func LessOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, args . // Negativef asserts that the specified element is negative // -// assert.Negativef(t, -1, "error message %s", "formatted") -// assert.Negativef(t, -1.23, "error message %s", "formatted") +// assert.Negativef(t, -1, "error message %s", "formatted") +// assert.Negativef(t, -1.23, "error message %s", "formatted") func Negativef(t TestingT, e interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -467,7 +509,7 @@ func Negativef(t TestingT, e interface{}, msg string, args ...interface{}) bool // Neverf asserts that the given condition doesn't satisfy in waitFor time, // periodically checking the target function each tick. // -// assert.Neverf(t, func() bool { return false; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") +// assert.Neverf(t, func() bool { return false; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") func Neverf(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -477,7 +519,7 @@ func Neverf(t TestingT, condition func() bool, waitFor time.Duration, tick time. // Nilf asserts that the specified object is nil. // -// assert.Nilf(t, err, "error message %s", "formatted") +// assert.Nilf(t, err, "error message %s", "formatted") func Nilf(t TestingT, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -496,10 +538,10 @@ func NoDirExistsf(t TestingT, path string, msg string, args ...interface{}) bool // NoErrorf asserts that a function returned no error (i.e. `nil`). // -// actualObj, err := SomeFunction() -// if assert.NoErrorf(t, err, "error message %s", "formatted") { -// assert.Equal(t, expectedObj, actualObj) -// } +// actualObj, err := SomeFunction() +// if assert.NoErrorf(t, err, "error message %s", "formatted") { +// assert.Equal(t, expectedObj, actualObj) +// } func NoErrorf(t TestingT, err error, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -519,9 +561,9 @@ func NoFileExistsf(t TestingT, path string, msg string, args ...interface{}) boo // NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // -// assert.NotContainsf(t, "Hello World", "Earth", "error message %s", "formatted") -// assert.NotContainsf(t, ["Hello", "World"], "Earth", "error message %s", "formatted") -// assert.NotContainsf(t, {"Hello": "World"}, "Earth", "error message %s", "formatted") +// assert.NotContainsf(t, "Hello World", "Earth", "error message %s", "formatted") +// assert.NotContainsf(t, ["Hello", "World"], "Earth", "error message %s", "formatted") +// assert.NotContainsf(t, {"Hello": "World"}, "Earth", "error message %s", "formatted") func NotContainsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -532,9 +574,9 @@ func NotContainsf(t TestingT, s interface{}, contains interface{}, msg string, a // NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // -// if assert.NotEmptyf(t, obj, "error message %s", "formatted") { -// assert.Equal(t, "two", obj[1]) -// } +// if assert.NotEmptyf(t, obj, "error message %s", "formatted") { +// assert.Equal(t, "two", obj[1]) +// } func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -544,7 +586,7 @@ func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{}) // NotEqualf asserts that the specified values are NOT equal. // -// assert.NotEqualf(t, obj1, obj2, "error message %s", "formatted") +// assert.NotEqualf(t, obj1, obj2, "error message %s", "formatted") // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). @@ -557,7 +599,7 @@ func NotEqualf(t TestingT, expected interface{}, actual interface{}, msg string, // NotEqualValuesf asserts that two objects are not equal even when converted to the same type // -// assert.NotEqualValuesf(t, obj1, obj2, "error message %s", "formatted") +// assert.NotEqualValuesf(t, obj1, obj2, "error message %s", "formatted") func NotEqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -576,7 +618,7 @@ func NotErrorIsf(t TestingT, err error, target error, msg string, args ...interf // NotNilf asserts that the specified object is not nil. // -// assert.NotNilf(t, err, "error message %s", "formatted") +// assert.NotNilf(t, err, "error message %s", "formatted") func NotNilf(t TestingT, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -586,7 +628,7 @@ func NotNilf(t TestingT, object interface{}, msg string, args ...interface{}) bo // NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. // -// assert.NotPanicsf(t, func(){ RemainCalm() }, "error message %s", "formatted") +// assert.NotPanicsf(t, func(){ RemainCalm() }, "error message %s", "formatted") func NotPanicsf(t TestingT, f PanicTestFunc, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -596,8 +638,8 @@ func NotPanicsf(t TestingT, f PanicTestFunc, msg string, args ...interface{}) bo // NotRegexpf asserts that a specified regexp does not match a string. // -// assert.NotRegexpf(t, regexp.MustCompile("starts"), "it's starting", "error message %s", "formatted") -// assert.NotRegexpf(t, "^start", "it's not starting", "error message %s", "formatted") +// assert.NotRegexpf(t, regexp.MustCompile("starts"), "it's starting", "error message %s", "formatted") +// assert.NotRegexpf(t, "^start", "it's not starting", "error message %s", "formatted") func NotRegexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -607,7 +649,7 @@ func NotRegexpf(t TestingT, rx interface{}, str interface{}, msg string, args .. // NotSamef asserts that two pointers do not reference the same object. // -// assert.NotSamef(t, ptr1, ptr2, "error message %s", "formatted") +// assert.NotSamef(t, ptr1, ptr2, "error message %s", "formatted") // // Both arguments must be pointer variables. Pointer variable sameness is // determined based on the equality of both type and value. @@ -621,7 +663,7 @@ func NotSamef(t TestingT, expected interface{}, actual interface{}, msg string, // NotSubsetf asserts that the specified list(array, slice...) contains not all // elements given in the specified subset(array, slice...). // -// assert.NotSubsetf(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") +// assert.NotSubsetf(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") func NotSubsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -639,7 +681,7 @@ func NotZerof(t TestingT, i interface{}, msg string, args ...interface{}) bool { // Panicsf asserts that the code inside the specified PanicTestFunc panics. // -// assert.Panicsf(t, func(){ GoCrazy() }, "error message %s", "formatted") +// assert.Panicsf(t, func(){ GoCrazy() }, "error message %s", "formatted") func Panicsf(t TestingT, f PanicTestFunc, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -651,7 +693,7 @@ func Panicsf(t TestingT, f PanicTestFunc, msg string, args ...interface{}) bool // panics, and that the recovered panic value is an error that satisfies the // EqualError comparison. // -// assert.PanicsWithErrorf(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") +// assert.PanicsWithErrorf(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") func PanicsWithErrorf(t TestingT, errString string, f PanicTestFunc, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -662,7 +704,7 @@ func PanicsWithErrorf(t TestingT, errString string, f PanicTestFunc, msg string, // PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // -// assert.PanicsWithValuef(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") +// assert.PanicsWithValuef(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") func PanicsWithValuef(t TestingT, expected interface{}, f PanicTestFunc, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -672,8 +714,8 @@ func PanicsWithValuef(t TestingT, expected interface{}, f PanicTestFunc, msg str // Positivef asserts that the specified element is positive // -// assert.Positivef(t, 1, "error message %s", "formatted") -// assert.Positivef(t, 1.23, "error message %s", "formatted") +// assert.Positivef(t, 1, "error message %s", "formatted") +// assert.Positivef(t, 1.23, "error message %s", "formatted") func Positivef(t TestingT, e interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -683,8 +725,8 @@ func Positivef(t TestingT, e interface{}, msg string, args ...interface{}) bool // Regexpf asserts that a specified regexp matches a string. // -// assert.Regexpf(t, regexp.MustCompile("start"), "it's starting", "error message %s", "formatted") -// assert.Regexpf(t, "start...$", "it's not starting", "error message %s", "formatted") +// assert.Regexpf(t, regexp.MustCompile("start"), "it's starting", "error message %s", "formatted") +// assert.Regexpf(t, "start...$", "it's not starting", "error message %s", "formatted") func Regexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -694,7 +736,7 @@ func Regexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...in // Samef asserts that two pointers reference the same object. // -// assert.Samef(t, ptr1, ptr2, "error message %s", "formatted") +// assert.Samef(t, ptr1, ptr2, "error message %s", "formatted") // // Both arguments must be pointer variables. Pointer variable sameness is // determined based on the equality of both type and value. @@ -708,7 +750,7 @@ func Samef(t TestingT, expected interface{}, actual interface{}, msg string, arg // Subsetf asserts that the specified list(array, slice...) contains all // elements given in the specified subset(array, slice...). // -// assert.Subsetf(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") +// assert.Subsetf(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -718,7 +760,7 @@ func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args // Truef asserts that the specified value is true. // -// assert.Truef(t, myBool, "error message %s", "formatted") +// assert.Truef(t, myBool, "error message %s", "formatted") func Truef(t TestingT, value bool, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -728,7 +770,7 @@ func Truef(t TestingT, value bool, msg string, args ...interface{}) bool { // WithinDurationf asserts that the two times are within duration delta of each other. // -// assert.WithinDurationf(t, time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") +// assert.WithinDurationf(t, time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -738,7 +780,7 @@ func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta tim // WithinRangef asserts that a time is within a time range (inclusive). // -// assert.WithinRangef(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second), "error message %s", "formatted") +// assert.WithinRangef(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second), "error message %s", "formatted") func WithinRangef(t TestingT, actual time.Time, start time.Time, end time.Time, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() diff --git a/vendor/github.com/stretchr/testify/assert/assertion_forward.go b/vendor/github.com/stretchr/testify/assert/assertion_forward.go index 339515b8bfb..b1d94aec53c 100644 --- a/vendor/github.com/stretchr/testify/assert/assertion_forward.go +++ b/vendor/github.com/stretchr/testify/assert/assertion_forward.go @@ -30,9 +30,9 @@ func (a *Assertions) Conditionf(comp Comparison, msg string, args ...interface{} // Contains asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // -// a.Contains("Hello World", "World") -// a.Contains(["Hello", "World"], "World") -// a.Contains({"Hello": "World"}, "Hello") +// a.Contains("Hello World", "World") +// a.Contains(["Hello", "World"], "World") +// a.Contains({"Hello": "World"}, "Hello") func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -43,9 +43,9 @@ func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs .. // Containsf asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // -// a.Containsf("Hello World", "World", "error message %s", "formatted") -// a.Containsf(["Hello", "World"], "World", "error message %s", "formatted") -// a.Containsf({"Hello": "World"}, "Hello", "error message %s", "formatted") +// a.Containsf("Hello World", "World", "error message %s", "formatted") +// a.Containsf(["Hello", "World"], "World", "error message %s", "formatted") +// a.Containsf({"Hello": "World"}, "Hello", "error message %s", "formatted") func (a *Assertions) Containsf(s interface{}, contains interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -98,7 +98,7 @@ func (a *Assertions) ElementsMatchf(listA interface{}, listB interface{}, msg st // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // -// a.Empty(obj) +// a.Empty(obj) func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -109,7 +109,7 @@ func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) bool { // Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // -// a.Emptyf(obj, "error message %s", "formatted") +// a.Emptyf(obj, "error message %s", "formatted") func (a *Assertions) Emptyf(object interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -119,7 +119,7 @@ func (a *Assertions) Emptyf(object interface{}, msg string, args ...interface{}) // Equal asserts that two objects are equal. // -// a.Equal(123, 123) +// a.Equal(123, 123) // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality @@ -134,8 +134,8 @@ func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs // EqualError asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // -// actualObj, err := SomeFunction() -// a.EqualError(err, expectedErrorString) +// actualObj, err := SomeFunction() +// a.EqualError(err, expectedErrorString) func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -146,8 +146,8 @@ func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ... // EqualErrorf asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // -// actualObj, err := SomeFunction() -// a.EqualErrorf(err, expectedErrorString, "error message %s", "formatted") +// actualObj, err := SomeFunction() +// a.EqualErrorf(err, expectedErrorString, "error message %s", "formatted") func (a *Assertions) EqualErrorf(theError error, errString string, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -155,10 +155,44 @@ func (a *Assertions) EqualErrorf(theError error, errString string, msg string, a return EqualErrorf(a.t, theError, errString, msg, args...) } +// EqualExportedValues asserts that the types of two objects are equal and their public +// fields are also equal. This is useful for comparing structs that have private fields +// that could potentially differ. +// +// type S struct { +// Exported int +// notExported int +// } +// a.EqualExportedValues(S{1, 2}, S{1, 3}) => true +// a.EqualExportedValues(S{1, 2}, S{2, 3}) => false +func (a *Assertions) EqualExportedValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return EqualExportedValues(a.t, expected, actual, msgAndArgs...) +} + +// EqualExportedValuesf asserts that the types of two objects are equal and their public +// fields are also equal. This is useful for comparing structs that have private fields +// that could potentially differ. +// +// type S struct { +// Exported int +// notExported int +// } +// a.EqualExportedValuesf(S{1, 2}, S{1, 3}, "error message %s", "formatted") => true +// a.EqualExportedValuesf(S{1, 2}, S{2, 3}, "error message %s", "formatted") => false +func (a *Assertions) EqualExportedValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return EqualExportedValuesf(a.t, expected, actual, msg, args...) +} + // EqualValues asserts that two objects are equal or convertable to the same types // and equal. // -// a.EqualValues(uint32(123), int32(123)) +// a.EqualValues(uint32(123), int32(123)) func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -169,7 +203,7 @@ func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAn // EqualValuesf asserts that two objects are equal or convertable to the same types // and equal. // -// a.EqualValuesf(uint32(123), int32(123), "error message %s", "formatted") +// a.EqualValuesf(uint32(123), int32(123), "error message %s", "formatted") func (a *Assertions) EqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -179,7 +213,7 @@ func (a *Assertions) EqualValuesf(expected interface{}, actual interface{}, msg // Equalf asserts that two objects are equal. // -// a.Equalf(123, 123, "error message %s", "formatted") +// a.Equalf(123, 123, "error message %s", "formatted") // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality @@ -193,10 +227,10 @@ func (a *Assertions) Equalf(expected interface{}, actual interface{}, msg string // Error asserts that a function returned an error (i.e. not `nil`). // -// actualObj, err := SomeFunction() -// if a.Error(err) { -// assert.Equal(t, expectedError, err) -// } +// actualObj, err := SomeFunction() +// if a.Error(err) { +// assert.Equal(t, expectedError, err) +// } func (a *Assertions) Error(err error, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -225,8 +259,8 @@ func (a *Assertions) ErrorAsf(err error, target interface{}, msg string, args .. // ErrorContains asserts that a function returned an error (i.e. not `nil`) // and that the error contains the specified substring. // -// actualObj, err := SomeFunction() -// a.ErrorContains(err, expectedErrorSubString) +// actualObj, err := SomeFunction() +// a.ErrorContains(err, expectedErrorSubString) func (a *Assertions) ErrorContains(theError error, contains string, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -237,8 +271,8 @@ func (a *Assertions) ErrorContains(theError error, contains string, msgAndArgs . // ErrorContainsf asserts that a function returned an error (i.e. not `nil`) // and that the error contains the specified substring. // -// actualObj, err := SomeFunction() -// a.ErrorContainsf(err, expectedErrorSubString, "error message %s", "formatted") +// actualObj, err := SomeFunction() +// a.ErrorContainsf(err, expectedErrorSubString, "error message %s", "formatted") func (a *Assertions) ErrorContainsf(theError error, contains string, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -266,10 +300,10 @@ func (a *Assertions) ErrorIsf(err error, target error, msg string, args ...inter // Errorf asserts that a function returned an error (i.e. not `nil`). // -// actualObj, err := SomeFunction() -// if a.Errorf(err, "error message %s", "formatted") { -// assert.Equal(t, expectedErrorf, err) -// } +// actualObj, err := SomeFunction() +// if a.Errorf(err, "error message %s", "formatted") { +// assert.Equal(t, expectedErrorf, err) +// } func (a *Assertions) Errorf(err error, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -280,7 +314,7 @@ func (a *Assertions) Errorf(err error, msg string, args ...interface{}) bool { // Eventually asserts that given condition will be met in waitFor time, // periodically checking target function each tick. // -// a.Eventually(func() bool { return true; }, time.Second, 10*time.Millisecond) +// a.Eventually(func() bool { return true; }, time.Second, 10*time.Millisecond) func (a *Assertions) Eventually(condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -288,10 +322,60 @@ func (a *Assertions) Eventually(condition func() bool, waitFor time.Duration, ti return Eventually(a.t, condition, waitFor, tick, msgAndArgs...) } +// EventuallyWithT asserts that given condition will be met in waitFor time, +// periodically checking target function each tick. In contrast to Eventually, +// it supplies a CollectT to the condition function, so that the condition +// function can use the CollectT to call other assertions. +// The condition is considered "met" if no errors are raised in a tick. +// The supplied CollectT collects all errors from one tick (if there are any). +// If the condition is not met before waitFor, the collected errors of +// the last tick are copied to t. +// +// externalValue := false +// go func() { +// time.Sleep(8*time.Second) +// externalValue = true +// }() +// a.EventuallyWithT(func(c *assert.CollectT) { +// // add assertions as needed; any assertion failure will fail the current tick +// assert.True(c, externalValue, "expected 'externalValue' to be true") +// }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false") +func (a *Assertions) EventuallyWithT(condition func(collect *CollectT), waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return EventuallyWithT(a.t, condition, waitFor, tick, msgAndArgs...) +} + +// EventuallyWithTf asserts that given condition will be met in waitFor time, +// periodically checking target function each tick. In contrast to Eventually, +// it supplies a CollectT to the condition function, so that the condition +// function can use the CollectT to call other assertions. +// The condition is considered "met" if no errors are raised in a tick. +// The supplied CollectT collects all errors from one tick (if there are any). +// If the condition is not met before waitFor, the collected errors of +// the last tick are copied to t. +// +// externalValue := false +// go func() { +// time.Sleep(8*time.Second) +// externalValue = true +// }() +// a.EventuallyWithTf(func(c *assert.CollectT, "error message %s", "formatted") { +// // add assertions as needed; any assertion failure will fail the current tick +// assert.True(c, externalValue, "expected 'externalValue' to be true") +// }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false") +func (a *Assertions) EventuallyWithTf(condition func(collect *CollectT), waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + return EventuallyWithTf(a.t, condition, waitFor, tick, msg, args...) +} + // Eventuallyf asserts that given condition will be met in waitFor time, // periodically checking target function each tick. // -// a.Eventuallyf(func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") +// a.Eventuallyf(func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") func (a *Assertions) Eventuallyf(condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -301,7 +385,7 @@ func (a *Assertions) Eventuallyf(condition func() bool, waitFor time.Duration, t // Exactly asserts that two objects are equal in value and type. // -// a.Exactly(int32(123), int64(123)) +// a.Exactly(int32(123), int64(123)) func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -311,7 +395,7 @@ func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArg // Exactlyf asserts that two objects are equal in value and type. // -// a.Exactlyf(int32(123), int64(123), "error message %s", "formatted") +// a.Exactlyf(int32(123), int64(123), "error message %s", "formatted") func (a *Assertions) Exactlyf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -353,7 +437,7 @@ func (a *Assertions) Failf(failureMessage string, msg string, args ...interface{ // False asserts that the specified value is false. // -// a.False(myBool) +// a.False(myBool) func (a *Assertions) False(value bool, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -363,7 +447,7 @@ func (a *Assertions) False(value bool, msgAndArgs ...interface{}) bool { // Falsef asserts that the specified value is false. // -// a.Falsef(myBool, "error message %s", "formatted") +// a.Falsef(myBool, "error message %s", "formatted") func (a *Assertions) Falsef(value bool, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -391,9 +475,9 @@ func (a *Assertions) FileExistsf(path string, msg string, args ...interface{}) b // Greater asserts that the first element is greater than the second // -// a.Greater(2, 1) -// a.Greater(float64(2), float64(1)) -// a.Greater("b", "a") +// a.Greater(2, 1) +// a.Greater(float64(2), float64(1)) +// a.Greater("b", "a") func (a *Assertions) Greater(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -403,10 +487,10 @@ func (a *Assertions) Greater(e1 interface{}, e2 interface{}, msgAndArgs ...inter // GreaterOrEqual asserts that the first element is greater than or equal to the second // -// a.GreaterOrEqual(2, 1) -// a.GreaterOrEqual(2, 2) -// a.GreaterOrEqual("b", "a") -// a.GreaterOrEqual("b", "b") +// a.GreaterOrEqual(2, 1) +// a.GreaterOrEqual(2, 2) +// a.GreaterOrEqual("b", "a") +// a.GreaterOrEqual("b", "b") func (a *Assertions) GreaterOrEqual(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -416,10 +500,10 @@ func (a *Assertions) GreaterOrEqual(e1 interface{}, e2 interface{}, msgAndArgs . // GreaterOrEqualf asserts that the first element is greater than or equal to the second // -// a.GreaterOrEqualf(2, 1, "error message %s", "formatted") -// a.GreaterOrEqualf(2, 2, "error message %s", "formatted") -// a.GreaterOrEqualf("b", "a", "error message %s", "formatted") -// a.GreaterOrEqualf("b", "b", "error message %s", "formatted") +// a.GreaterOrEqualf(2, 1, "error message %s", "formatted") +// a.GreaterOrEqualf(2, 2, "error message %s", "formatted") +// a.GreaterOrEqualf("b", "a", "error message %s", "formatted") +// a.GreaterOrEqualf("b", "b", "error message %s", "formatted") func (a *Assertions) GreaterOrEqualf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -429,9 +513,9 @@ func (a *Assertions) GreaterOrEqualf(e1 interface{}, e2 interface{}, msg string, // Greaterf asserts that the first element is greater than the second // -// a.Greaterf(2, 1, "error message %s", "formatted") -// a.Greaterf(float64(2), float64(1), "error message %s", "formatted") -// a.Greaterf("b", "a", "error message %s", "formatted") +// a.Greaterf(2, 1, "error message %s", "formatted") +// a.Greaterf(float64(2), float64(1), "error message %s", "formatted") +// a.Greaterf("b", "a", "error message %s", "formatted") func (a *Assertions) Greaterf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -442,7 +526,7 @@ func (a *Assertions) Greaterf(e1 interface{}, e2 interface{}, msg string, args . // HTTPBodyContains asserts that a specified handler returns a // body that contains a string. // -// a.HTTPBodyContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") +// a.HTTPBodyContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool { @@ -455,7 +539,7 @@ func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, u // HTTPBodyContainsf asserts that a specified handler returns a // body that contains a string. // -// a.HTTPBodyContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// a.HTTPBodyContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool { @@ -468,7 +552,7 @@ func (a *Assertions) HTTPBodyContainsf(handler http.HandlerFunc, method string, // HTTPBodyNotContains asserts that a specified handler returns a // body that does not contain a string. // -// a.HTTPBodyNotContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") +// a.HTTPBodyNotContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool { @@ -481,7 +565,7 @@ func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string // HTTPBodyNotContainsf asserts that a specified handler returns a // body that does not contain a string. // -// a.HTTPBodyNotContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// a.HTTPBodyNotContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyNotContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool { @@ -493,7 +577,7 @@ func (a *Assertions) HTTPBodyNotContainsf(handler http.HandlerFunc, method strin // HTTPError asserts that a specified handler returns an error status code. // -// a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) bool { @@ -505,7 +589,7 @@ func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url stri // HTTPErrorf asserts that a specified handler returns an error status code. // -// a.HTTPErrorf(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// a.HTTPErrorf(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPErrorf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { @@ -517,7 +601,7 @@ func (a *Assertions) HTTPErrorf(handler http.HandlerFunc, method string, url str // HTTPRedirect asserts that a specified handler returns a redirect status code. // -// a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) bool { @@ -529,7 +613,7 @@ func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url s // HTTPRedirectf asserts that a specified handler returns a redirect status code. // -// a.HTTPRedirectf(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// a.HTTPRedirectf(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPRedirectf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { @@ -541,7 +625,7 @@ func (a *Assertions) HTTPRedirectf(handler http.HandlerFunc, method string, url // HTTPStatusCode asserts that a specified handler returns a specified status code. // -// a.HTTPStatusCode(myHandler, "GET", "/notImplemented", nil, 501) +// a.HTTPStatusCode(myHandler, "GET", "/notImplemented", nil, 501) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPStatusCode(handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msgAndArgs ...interface{}) bool { @@ -553,7 +637,7 @@ func (a *Assertions) HTTPStatusCode(handler http.HandlerFunc, method string, url // HTTPStatusCodef asserts that a specified handler returns a specified status code. // -// a.HTTPStatusCodef(myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted") +// a.HTTPStatusCodef(myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPStatusCodef(handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msg string, args ...interface{}) bool { @@ -565,7 +649,7 @@ func (a *Assertions) HTTPStatusCodef(handler http.HandlerFunc, method string, ur // HTTPSuccess asserts that a specified handler returns a success status code. // -// a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) +// a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) bool { @@ -577,7 +661,7 @@ func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url st // HTTPSuccessf asserts that a specified handler returns a success status code. // -// a.HTTPSuccessf(myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") +// a.HTTPSuccessf(myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPSuccessf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { @@ -589,7 +673,7 @@ func (a *Assertions) HTTPSuccessf(handler http.HandlerFunc, method string, url s // Implements asserts that an object is implemented by the specified interface. // -// a.Implements((*MyInterface)(nil), new(MyObject)) +// a.Implements((*MyInterface)(nil), new(MyObject)) func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -599,7 +683,7 @@ func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, // Implementsf asserts that an object is implemented by the specified interface. // -// a.Implementsf((*MyInterface)(nil), new(MyObject), "error message %s", "formatted") +// a.Implementsf((*MyInterface)(nil), new(MyObject), "error message %s", "formatted") func (a *Assertions) Implementsf(interfaceObject interface{}, object interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -609,7 +693,7 @@ func (a *Assertions) Implementsf(interfaceObject interface{}, object interface{} // InDelta asserts that the two numerals are within delta of each other. // -// a.InDelta(math.Pi, 22/7.0, 0.01) +// a.InDelta(math.Pi, 22/7.0, 0.01) func (a *Assertions) InDelta(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -651,7 +735,7 @@ func (a *Assertions) InDeltaSlicef(expected interface{}, actual interface{}, del // InDeltaf asserts that the two numerals are within delta of each other. // -// a.InDeltaf(math.Pi, 22/7.0, 0.01, "error message %s", "formatted") +// a.InDeltaf(math.Pi, 22/7.0, 0.01, "error message %s", "formatted") func (a *Assertions) InDeltaf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -693,9 +777,9 @@ func (a *Assertions) InEpsilonf(expected interface{}, actual interface{}, epsilo // IsDecreasing asserts that the collection is decreasing // -// a.IsDecreasing([]int{2, 1, 0}) -// a.IsDecreasing([]float{2, 1}) -// a.IsDecreasing([]string{"b", "a"}) +// a.IsDecreasing([]int{2, 1, 0}) +// a.IsDecreasing([]float{2, 1}) +// a.IsDecreasing([]string{"b", "a"}) func (a *Assertions) IsDecreasing(object interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -705,9 +789,9 @@ func (a *Assertions) IsDecreasing(object interface{}, msgAndArgs ...interface{}) // IsDecreasingf asserts that the collection is decreasing // -// a.IsDecreasingf([]int{2, 1, 0}, "error message %s", "formatted") -// a.IsDecreasingf([]float{2, 1}, "error message %s", "formatted") -// a.IsDecreasingf([]string{"b", "a"}, "error message %s", "formatted") +// a.IsDecreasingf([]int{2, 1, 0}, "error message %s", "formatted") +// a.IsDecreasingf([]float{2, 1}, "error message %s", "formatted") +// a.IsDecreasingf([]string{"b", "a"}, "error message %s", "formatted") func (a *Assertions) IsDecreasingf(object interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -717,9 +801,9 @@ func (a *Assertions) IsDecreasingf(object interface{}, msg string, args ...inter // IsIncreasing asserts that the collection is increasing // -// a.IsIncreasing([]int{1, 2, 3}) -// a.IsIncreasing([]float{1, 2}) -// a.IsIncreasing([]string{"a", "b"}) +// a.IsIncreasing([]int{1, 2, 3}) +// a.IsIncreasing([]float{1, 2}) +// a.IsIncreasing([]string{"a", "b"}) func (a *Assertions) IsIncreasing(object interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -729,9 +813,9 @@ func (a *Assertions) IsIncreasing(object interface{}, msgAndArgs ...interface{}) // IsIncreasingf asserts that the collection is increasing // -// a.IsIncreasingf([]int{1, 2, 3}, "error message %s", "formatted") -// a.IsIncreasingf([]float{1, 2}, "error message %s", "formatted") -// a.IsIncreasingf([]string{"a", "b"}, "error message %s", "formatted") +// a.IsIncreasingf([]int{1, 2, 3}, "error message %s", "formatted") +// a.IsIncreasingf([]float{1, 2}, "error message %s", "formatted") +// a.IsIncreasingf([]string{"a", "b"}, "error message %s", "formatted") func (a *Assertions) IsIncreasingf(object interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -741,9 +825,9 @@ func (a *Assertions) IsIncreasingf(object interface{}, msg string, args ...inter // IsNonDecreasing asserts that the collection is not decreasing // -// a.IsNonDecreasing([]int{1, 1, 2}) -// a.IsNonDecreasing([]float{1, 2}) -// a.IsNonDecreasing([]string{"a", "b"}) +// a.IsNonDecreasing([]int{1, 1, 2}) +// a.IsNonDecreasing([]float{1, 2}) +// a.IsNonDecreasing([]string{"a", "b"}) func (a *Assertions) IsNonDecreasing(object interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -753,9 +837,9 @@ func (a *Assertions) IsNonDecreasing(object interface{}, msgAndArgs ...interface // IsNonDecreasingf asserts that the collection is not decreasing // -// a.IsNonDecreasingf([]int{1, 1, 2}, "error message %s", "formatted") -// a.IsNonDecreasingf([]float{1, 2}, "error message %s", "formatted") -// a.IsNonDecreasingf([]string{"a", "b"}, "error message %s", "formatted") +// a.IsNonDecreasingf([]int{1, 1, 2}, "error message %s", "formatted") +// a.IsNonDecreasingf([]float{1, 2}, "error message %s", "formatted") +// a.IsNonDecreasingf([]string{"a", "b"}, "error message %s", "formatted") func (a *Assertions) IsNonDecreasingf(object interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -765,9 +849,9 @@ func (a *Assertions) IsNonDecreasingf(object interface{}, msg string, args ...in // IsNonIncreasing asserts that the collection is not increasing // -// a.IsNonIncreasing([]int{2, 1, 1}) -// a.IsNonIncreasing([]float{2, 1}) -// a.IsNonIncreasing([]string{"b", "a"}) +// a.IsNonIncreasing([]int{2, 1, 1}) +// a.IsNonIncreasing([]float{2, 1}) +// a.IsNonIncreasing([]string{"b", "a"}) func (a *Assertions) IsNonIncreasing(object interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -777,9 +861,9 @@ func (a *Assertions) IsNonIncreasing(object interface{}, msgAndArgs ...interface // IsNonIncreasingf asserts that the collection is not increasing // -// a.IsNonIncreasingf([]int{2, 1, 1}, "error message %s", "formatted") -// a.IsNonIncreasingf([]float{2, 1}, "error message %s", "formatted") -// a.IsNonIncreasingf([]string{"b", "a"}, "error message %s", "formatted") +// a.IsNonIncreasingf([]int{2, 1, 1}, "error message %s", "formatted") +// a.IsNonIncreasingf([]float{2, 1}, "error message %s", "formatted") +// a.IsNonIncreasingf([]string{"b", "a"}, "error message %s", "formatted") func (a *Assertions) IsNonIncreasingf(object interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -805,7 +889,7 @@ func (a *Assertions) IsTypef(expectedType interface{}, object interface{}, msg s // JSONEq asserts that two JSON strings are equivalent. // -// a.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) +// a.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -815,7 +899,7 @@ func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interf // JSONEqf asserts that two JSON strings are equivalent. // -// a.JSONEqf(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") +// a.JSONEqf(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") func (a *Assertions) JSONEqf(expected string, actual string, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -826,7 +910,7 @@ func (a *Assertions) JSONEqf(expected string, actual string, msg string, args .. // Len asserts that the specified object has specific length. // Len also fails if the object has a type that len() not accept. // -// a.Len(mySlice, 3) +// a.Len(mySlice, 3) func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -837,7 +921,7 @@ func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface // Lenf asserts that the specified object has specific length. // Lenf also fails if the object has a type that len() not accept. // -// a.Lenf(mySlice, 3, "error message %s", "formatted") +// a.Lenf(mySlice, 3, "error message %s", "formatted") func (a *Assertions) Lenf(object interface{}, length int, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -847,9 +931,9 @@ func (a *Assertions) Lenf(object interface{}, length int, msg string, args ...in // Less asserts that the first element is less than the second // -// a.Less(1, 2) -// a.Less(float64(1), float64(2)) -// a.Less("a", "b") +// a.Less(1, 2) +// a.Less(float64(1), float64(2)) +// a.Less("a", "b") func (a *Assertions) Less(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -859,10 +943,10 @@ func (a *Assertions) Less(e1 interface{}, e2 interface{}, msgAndArgs ...interfac // LessOrEqual asserts that the first element is less than or equal to the second // -// a.LessOrEqual(1, 2) -// a.LessOrEqual(2, 2) -// a.LessOrEqual("a", "b") -// a.LessOrEqual("b", "b") +// a.LessOrEqual(1, 2) +// a.LessOrEqual(2, 2) +// a.LessOrEqual("a", "b") +// a.LessOrEqual("b", "b") func (a *Assertions) LessOrEqual(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -872,10 +956,10 @@ func (a *Assertions) LessOrEqual(e1 interface{}, e2 interface{}, msgAndArgs ...i // LessOrEqualf asserts that the first element is less than or equal to the second // -// a.LessOrEqualf(1, 2, "error message %s", "formatted") -// a.LessOrEqualf(2, 2, "error message %s", "formatted") -// a.LessOrEqualf("a", "b", "error message %s", "formatted") -// a.LessOrEqualf("b", "b", "error message %s", "formatted") +// a.LessOrEqualf(1, 2, "error message %s", "formatted") +// a.LessOrEqualf(2, 2, "error message %s", "formatted") +// a.LessOrEqualf("a", "b", "error message %s", "formatted") +// a.LessOrEqualf("b", "b", "error message %s", "formatted") func (a *Assertions) LessOrEqualf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -885,9 +969,9 @@ func (a *Assertions) LessOrEqualf(e1 interface{}, e2 interface{}, msg string, ar // Lessf asserts that the first element is less than the second // -// a.Lessf(1, 2, "error message %s", "formatted") -// a.Lessf(float64(1), float64(2), "error message %s", "formatted") -// a.Lessf("a", "b", "error message %s", "formatted") +// a.Lessf(1, 2, "error message %s", "formatted") +// a.Lessf(float64(1), float64(2), "error message %s", "formatted") +// a.Lessf("a", "b", "error message %s", "formatted") func (a *Assertions) Lessf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -897,8 +981,8 @@ func (a *Assertions) Lessf(e1 interface{}, e2 interface{}, msg string, args ...i // Negative asserts that the specified element is negative // -// a.Negative(-1) -// a.Negative(-1.23) +// a.Negative(-1) +// a.Negative(-1.23) func (a *Assertions) Negative(e interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -908,8 +992,8 @@ func (a *Assertions) Negative(e interface{}, msgAndArgs ...interface{}) bool { // Negativef asserts that the specified element is negative // -// a.Negativef(-1, "error message %s", "formatted") -// a.Negativef(-1.23, "error message %s", "formatted") +// a.Negativef(-1, "error message %s", "formatted") +// a.Negativef(-1.23, "error message %s", "formatted") func (a *Assertions) Negativef(e interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -920,7 +1004,7 @@ func (a *Assertions) Negativef(e interface{}, msg string, args ...interface{}) b // Never asserts that the given condition doesn't satisfy in waitFor time, // periodically checking the target function each tick. // -// a.Never(func() bool { return false; }, time.Second, 10*time.Millisecond) +// a.Never(func() bool { return false; }, time.Second, 10*time.Millisecond) func (a *Assertions) Never(condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -931,7 +1015,7 @@ func (a *Assertions) Never(condition func() bool, waitFor time.Duration, tick ti // Neverf asserts that the given condition doesn't satisfy in waitFor time, // periodically checking the target function each tick. // -// a.Neverf(func() bool { return false; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") +// a.Neverf(func() bool { return false; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") func (a *Assertions) Neverf(condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -941,7 +1025,7 @@ func (a *Assertions) Neverf(condition func() bool, waitFor time.Duration, tick t // Nil asserts that the specified object is nil. // -// a.Nil(err) +// a.Nil(err) func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -951,7 +1035,7 @@ func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) bool { // Nilf asserts that the specified object is nil. // -// a.Nilf(err, "error message %s", "formatted") +// a.Nilf(err, "error message %s", "formatted") func (a *Assertions) Nilf(object interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -979,10 +1063,10 @@ func (a *Assertions) NoDirExistsf(path string, msg string, args ...interface{}) // NoError asserts that a function returned no error (i.e. `nil`). // -// actualObj, err := SomeFunction() -// if a.NoError(err) { -// assert.Equal(t, expectedObj, actualObj) -// } +// actualObj, err := SomeFunction() +// if a.NoError(err) { +// assert.Equal(t, expectedObj, actualObj) +// } func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -992,10 +1076,10 @@ func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) bool { // NoErrorf asserts that a function returned no error (i.e. `nil`). // -// actualObj, err := SomeFunction() -// if a.NoErrorf(err, "error message %s", "formatted") { -// assert.Equal(t, expectedObj, actualObj) -// } +// actualObj, err := SomeFunction() +// if a.NoErrorf(err, "error message %s", "formatted") { +// assert.Equal(t, expectedObj, actualObj) +// } func (a *Assertions) NoErrorf(err error, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1024,9 +1108,9 @@ func (a *Assertions) NoFileExistsf(path string, msg string, args ...interface{}) // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // -// a.NotContains("Hello World", "Earth") -// a.NotContains(["Hello", "World"], "Earth") -// a.NotContains({"Hello": "World"}, "Earth") +// a.NotContains("Hello World", "Earth") +// a.NotContains(["Hello", "World"], "Earth") +// a.NotContains({"Hello": "World"}, "Earth") func (a *Assertions) NotContains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1037,9 +1121,9 @@ func (a *Assertions) NotContains(s interface{}, contains interface{}, msgAndArgs // NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // -// a.NotContainsf("Hello World", "Earth", "error message %s", "formatted") -// a.NotContainsf(["Hello", "World"], "Earth", "error message %s", "formatted") -// a.NotContainsf({"Hello": "World"}, "Earth", "error message %s", "formatted") +// a.NotContainsf("Hello World", "Earth", "error message %s", "formatted") +// a.NotContainsf(["Hello", "World"], "Earth", "error message %s", "formatted") +// a.NotContainsf({"Hello": "World"}, "Earth", "error message %s", "formatted") func (a *Assertions) NotContainsf(s interface{}, contains interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1050,9 +1134,9 @@ func (a *Assertions) NotContainsf(s interface{}, contains interface{}, msg strin // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // -// if a.NotEmpty(obj) { -// assert.Equal(t, "two", obj[1]) -// } +// if a.NotEmpty(obj) { +// assert.Equal(t, "two", obj[1]) +// } func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1063,9 +1147,9 @@ func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) boo // NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // -// if a.NotEmptyf(obj, "error message %s", "formatted") { -// assert.Equal(t, "two", obj[1]) -// } +// if a.NotEmptyf(obj, "error message %s", "formatted") { +// assert.Equal(t, "two", obj[1]) +// } func (a *Assertions) NotEmptyf(object interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1075,7 +1159,7 @@ func (a *Assertions) NotEmptyf(object interface{}, msg string, args ...interface // NotEqual asserts that the specified values are NOT equal. // -// a.NotEqual(obj1, obj2) +// a.NotEqual(obj1, obj2) // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). @@ -1088,7 +1172,7 @@ func (a *Assertions) NotEqual(expected interface{}, actual interface{}, msgAndAr // NotEqualValues asserts that two objects are not equal even when converted to the same type // -// a.NotEqualValues(obj1, obj2) +// a.NotEqualValues(obj1, obj2) func (a *Assertions) NotEqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1098,7 +1182,7 @@ func (a *Assertions) NotEqualValues(expected interface{}, actual interface{}, ms // NotEqualValuesf asserts that two objects are not equal even when converted to the same type // -// a.NotEqualValuesf(obj1, obj2, "error message %s", "formatted") +// a.NotEqualValuesf(obj1, obj2, "error message %s", "formatted") func (a *Assertions) NotEqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1108,7 +1192,7 @@ func (a *Assertions) NotEqualValuesf(expected interface{}, actual interface{}, m // NotEqualf asserts that the specified values are NOT equal. // -// a.NotEqualf(obj1, obj2, "error message %s", "formatted") +// a.NotEqualf(obj1, obj2, "error message %s", "formatted") // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). @@ -1139,7 +1223,7 @@ func (a *Assertions) NotErrorIsf(err error, target error, msg string, args ...in // NotNil asserts that the specified object is not nil. // -// a.NotNil(err) +// a.NotNil(err) func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1149,7 +1233,7 @@ func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) bool // NotNilf asserts that the specified object is not nil. // -// a.NotNilf(err, "error message %s", "formatted") +// a.NotNilf(err, "error message %s", "formatted") func (a *Assertions) NotNilf(object interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1159,7 +1243,7 @@ func (a *Assertions) NotNilf(object interface{}, msg string, args ...interface{} // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. // -// a.NotPanics(func(){ RemainCalm() }) +// a.NotPanics(func(){ RemainCalm() }) func (a *Assertions) NotPanics(f PanicTestFunc, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1169,7 +1253,7 @@ func (a *Assertions) NotPanics(f PanicTestFunc, msgAndArgs ...interface{}) bool // NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. // -// a.NotPanicsf(func(){ RemainCalm() }, "error message %s", "formatted") +// a.NotPanicsf(func(){ RemainCalm() }, "error message %s", "formatted") func (a *Assertions) NotPanicsf(f PanicTestFunc, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1179,8 +1263,8 @@ func (a *Assertions) NotPanicsf(f PanicTestFunc, msg string, args ...interface{} // NotRegexp asserts that a specified regexp does not match a string. // -// a.NotRegexp(regexp.MustCompile("starts"), "it's starting") -// a.NotRegexp("^start", "it's not starting") +// a.NotRegexp(regexp.MustCompile("starts"), "it's starting") +// a.NotRegexp("^start", "it's not starting") func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1190,8 +1274,8 @@ func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...in // NotRegexpf asserts that a specified regexp does not match a string. // -// a.NotRegexpf(regexp.MustCompile("starts"), "it's starting", "error message %s", "formatted") -// a.NotRegexpf("^start", "it's not starting", "error message %s", "formatted") +// a.NotRegexpf(regexp.MustCompile("starts"), "it's starting", "error message %s", "formatted") +// a.NotRegexpf("^start", "it's not starting", "error message %s", "formatted") func (a *Assertions) NotRegexpf(rx interface{}, str interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1201,7 +1285,7 @@ func (a *Assertions) NotRegexpf(rx interface{}, str interface{}, msg string, arg // NotSame asserts that two pointers do not reference the same object. // -// a.NotSame(ptr1, ptr2) +// a.NotSame(ptr1, ptr2) // // Both arguments must be pointer variables. Pointer variable sameness is // determined based on the equality of both type and value. @@ -1214,7 +1298,7 @@ func (a *Assertions) NotSame(expected interface{}, actual interface{}, msgAndArg // NotSamef asserts that two pointers do not reference the same object. // -// a.NotSamef(ptr1, ptr2, "error message %s", "formatted") +// a.NotSamef(ptr1, ptr2, "error message %s", "formatted") // // Both arguments must be pointer variables. Pointer variable sameness is // determined based on the equality of both type and value. @@ -1228,7 +1312,7 @@ func (a *Assertions) NotSamef(expected interface{}, actual interface{}, msg stri // NotSubset asserts that the specified list(array, slice...) contains not all // elements given in the specified subset(array, slice...). // -// a.NotSubset([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") +// a.NotSubset([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") func (a *Assertions) NotSubset(list interface{}, subset interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1239,7 +1323,7 @@ func (a *Assertions) NotSubset(list interface{}, subset interface{}, msgAndArgs // NotSubsetf asserts that the specified list(array, slice...) contains not all // elements given in the specified subset(array, slice...). // -// a.NotSubsetf([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") +// a.NotSubsetf([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") func (a *Assertions) NotSubsetf(list interface{}, subset interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1265,7 +1349,7 @@ func (a *Assertions) NotZerof(i interface{}, msg string, args ...interface{}) bo // Panics asserts that the code inside the specified PanicTestFunc panics. // -// a.Panics(func(){ GoCrazy() }) +// a.Panics(func(){ GoCrazy() }) func (a *Assertions) Panics(f PanicTestFunc, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1277,7 +1361,7 @@ func (a *Assertions) Panics(f PanicTestFunc, msgAndArgs ...interface{}) bool { // panics, and that the recovered panic value is an error that satisfies the // EqualError comparison. // -// a.PanicsWithError("crazy error", func(){ GoCrazy() }) +// a.PanicsWithError("crazy error", func(){ GoCrazy() }) func (a *Assertions) PanicsWithError(errString string, f PanicTestFunc, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1289,7 +1373,7 @@ func (a *Assertions) PanicsWithError(errString string, f PanicTestFunc, msgAndAr // panics, and that the recovered panic value is an error that satisfies the // EqualError comparison. // -// a.PanicsWithErrorf("crazy error", func(){ GoCrazy() }, "error message %s", "formatted") +// a.PanicsWithErrorf("crazy error", func(){ GoCrazy() }, "error message %s", "formatted") func (a *Assertions) PanicsWithErrorf(errString string, f PanicTestFunc, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1300,7 +1384,7 @@ func (a *Assertions) PanicsWithErrorf(errString string, f PanicTestFunc, msg str // PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // -// a.PanicsWithValue("crazy error", func(){ GoCrazy() }) +// a.PanicsWithValue("crazy error", func(){ GoCrazy() }) func (a *Assertions) PanicsWithValue(expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1311,7 +1395,7 @@ func (a *Assertions) PanicsWithValue(expected interface{}, f PanicTestFunc, msgA // PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // -// a.PanicsWithValuef("crazy error", func(){ GoCrazy() }, "error message %s", "formatted") +// a.PanicsWithValuef("crazy error", func(){ GoCrazy() }, "error message %s", "formatted") func (a *Assertions) PanicsWithValuef(expected interface{}, f PanicTestFunc, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1321,7 +1405,7 @@ func (a *Assertions) PanicsWithValuef(expected interface{}, f PanicTestFunc, msg // Panicsf asserts that the code inside the specified PanicTestFunc panics. // -// a.Panicsf(func(){ GoCrazy() }, "error message %s", "formatted") +// a.Panicsf(func(){ GoCrazy() }, "error message %s", "formatted") func (a *Assertions) Panicsf(f PanicTestFunc, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1331,8 +1415,8 @@ func (a *Assertions) Panicsf(f PanicTestFunc, msg string, args ...interface{}) b // Positive asserts that the specified element is positive // -// a.Positive(1) -// a.Positive(1.23) +// a.Positive(1) +// a.Positive(1.23) func (a *Assertions) Positive(e interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1342,8 +1426,8 @@ func (a *Assertions) Positive(e interface{}, msgAndArgs ...interface{}) bool { // Positivef asserts that the specified element is positive // -// a.Positivef(1, "error message %s", "formatted") -// a.Positivef(1.23, "error message %s", "formatted") +// a.Positivef(1, "error message %s", "formatted") +// a.Positivef(1.23, "error message %s", "formatted") func (a *Assertions) Positivef(e interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1353,8 +1437,8 @@ func (a *Assertions) Positivef(e interface{}, msg string, args ...interface{}) b // Regexp asserts that a specified regexp matches a string. // -// a.Regexp(regexp.MustCompile("start"), "it's starting") -// a.Regexp("start...$", "it's not starting") +// a.Regexp(regexp.MustCompile("start"), "it's starting") +// a.Regexp("start...$", "it's not starting") func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1364,8 +1448,8 @@ func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...inter // Regexpf asserts that a specified regexp matches a string. // -// a.Regexpf(regexp.MustCompile("start"), "it's starting", "error message %s", "formatted") -// a.Regexpf("start...$", "it's not starting", "error message %s", "formatted") +// a.Regexpf(regexp.MustCompile("start"), "it's starting", "error message %s", "formatted") +// a.Regexpf("start...$", "it's not starting", "error message %s", "formatted") func (a *Assertions) Regexpf(rx interface{}, str interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1375,7 +1459,7 @@ func (a *Assertions) Regexpf(rx interface{}, str interface{}, msg string, args . // Same asserts that two pointers reference the same object. // -// a.Same(ptr1, ptr2) +// a.Same(ptr1, ptr2) // // Both arguments must be pointer variables. Pointer variable sameness is // determined based on the equality of both type and value. @@ -1388,7 +1472,7 @@ func (a *Assertions) Same(expected interface{}, actual interface{}, msgAndArgs . // Samef asserts that two pointers reference the same object. // -// a.Samef(ptr1, ptr2, "error message %s", "formatted") +// a.Samef(ptr1, ptr2, "error message %s", "formatted") // // Both arguments must be pointer variables. Pointer variable sameness is // determined based on the equality of both type and value. @@ -1402,7 +1486,7 @@ func (a *Assertions) Samef(expected interface{}, actual interface{}, msg string, // Subset asserts that the specified list(array, slice...) contains all // elements given in the specified subset(array, slice...). // -// a.Subset([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") +// a.Subset([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") func (a *Assertions) Subset(list interface{}, subset interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1413,7 +1497,7 @@ func (a *Assertions) Subset(list interface{}, subset interface{}, msgAndArgs ... // Subsetf asserts that the specified list(array, slice...) contains all // elements given in the specified subset(array, slice...). // -// a.Subsetf([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") +// a.Subsetf([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") func (a *Assertions) Subsetf(list interface{}, subset interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1423,7 +1507,7 @@ func (a *Assertions) Subsetf(list interface{}, subset interface{}, msg string, a // True asserts that the specified value is true. // -// a.True(myBool) +// a.True(myBool) func (a *Assertions) True(value bool, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1433,7 +1517,7 @@ func (a *Assertions) True(value bool, msgAndArgs ...interface{}) bool { // Truef asserts that the specified value is true. // -// a.Truef(myBool, "error message %s", "formatted") +// a.Truef(myBool, "error message %s", "formatted") func (a *Assertions) Truef(value bool, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1443,7 +1527,7 @@ func (a *Assertions) Truef(value bool, msg string, args ...interface{}) bool { // WithinDuration asserts that the two times are within duration delta of each other. // -// a.WithinDuration(time.Now(), time.Now(), 10*time.Second) +// a.WithinDuration(time.Now(), time.Now(), 10*time.Second) func (a *Assertions) WithinDuration(expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1453,7 +1537,7 @@ func (a *Assertions) WithinDuration(expected time.Time, actual time.Time, delta // WithinDurationf asserts that the two times are within duration delta of each other. // -// a.WithinDurationf(time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") +// a.WithinDurationf(time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") func (a *Assertions) WithinDurationf(expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1463,7 +1547,7 @@ func (a *Assertions) WithinDurationf(expected time.Time, actual time.Time, delta // WithinRange asserts that a time is within a time range (inclusive). // -// a.WithinRange(time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second)) +// a.WithinRange(time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second)) func (a *Assertions) WithinRange(actual time.Time, start time.Time, end time.Time, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1473,7 +1557,7 @@ func (a *Assertions) WithinRange(actual time.Time, start time.Time, end time.Tim // WithinRangef asserts that a time is within a time range (inclusive). // -// a.WithinRangef(time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second), "error message %s", "formatted") +// a.WithinRangef(time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second), "error message %s", "formatted") func (a *Assertions) WithinRangef(actual time.Time, start time.Time, end time.Time, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() diff --git a/vendor/github.com/stretchr/testify/assert/assertion_order.go b/vendor/github.com/stretchr/testify/assert/assertion_order.go index 75944878358..00df62a0599 100644 --- a/vendor/github.com/stretchr/testify/assert/assertion_order.go +++ b/vendor/github.com/stretchr/testify/assert/assertion_order.go @@ -46,36 +46,36 @@ func isOrdered(t TestingT, object interface{}, allowedComparesResults []CompareT // IsIncreasing asserts that the collection is increasing // -// assert.IsIncreasing(t, []int{1, 2, 3}) -// assert.IsIncreasing(t, []float{1, 2}) -// assert.IsIncreasing(t, []string{"a", "b"}) +// assert.IsIncreasing(t, []int{1, 2, 3}) +// assert.IsIncreasing(t, []float{1, 2}) +// assert.IsIncreasing(t, []string{"a", "b"}) func IsIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { return isOrdered(t, object, []CompareType{compareLess}, "\"%v\" is not less than \"%v\"", msgAndArgs...) } // IsNonIncreasing asserts that the collection is not increasing // -// assert.IsNonIncreasing(t, []int{2, 1, 1}) -// assert.IsNonIncreasing(t, []float{2, 1}) -// assert.IsNonIncreasing(t, []string{"b", "a"}) +// assert.IsNonIncreasing(t, []int{2, 1, 1}) +// assert.IsNonIncreasing(t, []float{2, 1}) +// assert.IsNonIncreasing(t, []string{"b", "a"}) func IsNonIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { return isOrdered(t, object, []CompareType{compareEqual, compareGreater}, "\"%v\" is not greater than or equal to \"%v\"", msgAndArgs...) } // IsDecreasing asserts that the collection is decreasing // -// assert.IsDecreasing(t, []int{2, 1, 0}) -// assert.IsDecreasing(t, []float{2, 1}) -// assert.IsDecreasing(t, []string{"b", "a"}) +// assert.IsDecreasing(t, []int{2, 1, 0}) +// assert.IsDecreasing(t, []float{2, 1}) +// assert.IsDecreasing(t, []string{"b", "a"}) func IsDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { return isOrdered(t, object, []CompareType{compareGreater}, "\"%v\" is not greater than \"%v\"", msgAndArgs...) } // IsNonDecreasing asserts that the collection is not decreasing // -// assert.IsNonDecreasing(t, []int{1, 1, 2}) -// assert.IsNonDecreasing(t, []float{1, 2}) -// assert.IsNonDecreasing(t, []string{"a", "b"}) +// assert.IsNonDecreasing(t, []int{1, 1, 2}) +// assert.IsNonDecreasing(t, []float{1, 2}) +// assert.IsNonDecreasing(t, []string{"a", "b"}) func IsNonDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { return isOrdered(t, object, []CompareType{compareLess, compareEqual}, "\"%v\" is not less than or equal to \"%v\"", msgAndArgs...) } diff --git a/vendor/github.com/stretchr/testify/assert/assertions.go b/vendor/github.com/stretchr/testify/assert/assertions.go index 2924cf3a149..a55d1bba926 100644 --- a/vendor/github.com/stretchr/testify/assert/assertions.go +++ b/vendor/github.com/stretchr/testify/assert/assertions.go @@ -75,6 +75,77 @@ func ObjectsAreEqual(expected, actual interface{}) bool { return bytes.Equal(exp, act) } +// copyExportedFields iterates downward through nested data structures and creates a copy +// that only contains the exported struct fields. +func copyExportedFields(expected interface{}) interface{} { + if isNil(expected) { + return expected + } + + expectedType := reflect.TypeOf(expected) + expectedKind := expectedType.Kind() + expectedValue := reflect.ValueOf(expected) + + switch expectedKind { + case reflect.Struct: + result := reflect.New(expectedType).Elem() + for i := 0; i < expectedType.NumField(); i++ { + field := expectedType.Field(i) + isExported := field.IsExported() + if isExported { + fieldValue := expectedValue.Field(i) + if isNil(fieldValue) || isNil(fieldValue.Interface()) { + continue + } + newValue := copyExportedFields(fieldValue.Interface()) + result.Field(i).Set(reflect.ValueOf(newValue)) + } + } + return result.Interface() + + case reflect.Ptr: + result := reflect.New(expectedType.Elem()) + unexportedRemoved := copyExportedFields(expectedValue.Elem().Interface()) + result.Elem().Set(reflect.ValueOf(unexportedRemoved)) + return result.Interface() + + case reflect.Array, reflect.Slice: + result := reflect.MakeSlice(expectedType, expectedValue.Len(), expectedValue.Len()) + for i := 0; i < expectedValue.Len(); i++ { + index := expectedValue.Index(i) + if isNil(index) { + continue + } + unexportedRemoved := copyExportedFields(index.Interface()) + result.Index(i).Set(reflect.ValueOf(unexportedRemoved)) + } + return result.Interface() + + case reflect.Map: + result := reflect.MakeMap(expectedType) + for _, k := range expectedValue.MapKeys() { + index := expectedValue.MapIndex(k) + unexportedRemoved := copyExportedFields(index.Interface()) + result.SetMapIndex(k, reflect.ValueOf(unexportedRemoved)) + } + return result.Interface() + + default: + return expected + } +} + +// ObjectsExportedFieldsAreEqual determines if the exported (public) fields of two objects are +// considered equal. This comparison of only exported fields is applied recursively to nested data +// structures. +// +// This function does no assertion of any kind. +func ObjectsExportedFieldsAreEqual(expected, actual interface{}) bool { + expectedCleaned := copyExportedFields(expected) + actualCleaned := copyExportedFields(actual) + return ObjectsAreEqualValues(expectedCleaned, actualCleaned) +} + // ObjectsAreEqualValues gets whether two objects are equal, or if their // values are equal. func ObjectsAreEqualValues(expected, actual interface{}) bool { @@ -271,7 +342,7 @@ type labeledContent struct { // labeledOutput returns a string consisting of the provided labeledContent. Each labeled output is appended in the following manner: // -// \t{{label}}:{{align_spaces}}\t{{content}}\n +// \t{{label}}:{{align_spaces}}\t{{content}}\n // // The initial carriage return is required to undo/erase any padding added by testing.T.Errorf. The "\t{{label}}:" is for the label. // If a label is shorter than the longest label provided, padding spaces are added to make all the labels match in length. Once this @@ -294,7 +365,7 @@ func labeledOutput(content ...labeledContent) string { // Implements asserts that an object is implemented by the specified interface. // -// assert.Implements(t, (*MyInterface)(nil), new(MyObject)) +// assert.Implements(t, (*MyInterface)(nil), new(MyObject)) func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -326,7 +397,7 @@ func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs // Equal asserts that two objects are equal. // -// assert.Equal(t, 123, 123) +// assert.Equal(t, 123, 123) // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality @@ -367,7 +438,7 @@ func validateEqualArgs(expected, actual interface{}) error { // Same asserts that two pointers reference the same object. // -// assert.Same(t, ptr1, ptr2) +// assert.Same(t, ptr1, ptr2) // // Both arguments must be pointer variables. Pointer variable sameness is // determined based on the equality of both type and value. @@ -387,7 +458,7 @@ func Same(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) b // NotSame asserts that two pointers do not reference the same object. // -// assert.NotSame(t, ptr1, ptr2) +// assert.NotSame(t, ptr1, ptr2) // // Both arguments must be pointer variables. Pointer variable sameness is // determined based on the equality of both type and value. @@ -455,7 +526,7 @@ func truncatingFormat(data interface{}) string { // EqualValues asserts that two objects are equal or convertable to the same types // and equal. // -// assert.EqualValues(t, uint32(123), int32(123)) +// assert.EqualValues(t, uint32(123), int32(123)) func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -473,9 +544,53 @@ func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interfa } +// EqualExportedValues asserts that the types of two objects are equal and their public +// fields are also equal. This is useful for comparing structs that have private fields +// that could potentially differ. +// +// type S struct { +// Exported int +// notExported int +// } +// assert.EqualExportedValues(t, S{1, 2}, S{1, 3}) => true +// assert.EqualExportedValues(t, S{1, 2}, S{2, 3}) => false +func EqualExportedValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + + aType := reflect.TypeOf(expected) + bType := reflect.TypeOf(actual) + + if aType != bType { + return Fail(t, fmt.Sprintf("Types expected to match exactly\n\t%v != %v", aType, bType), msgAndArgs...) + } + + if aType.Kind() != reflect.Struct { + return Fail(t, fmt.Sprintf("Types expected to both be struct \n\t%v != %v", aType.Kind(), reflect.Struct), msgAndArgs...) + } + + if bType.Kind() != reflect.Struct { + return Fail(t, fmt.Sprintf("Types expected to both be struct \n\t%v != %v", bType.Kind(), reflect.Struct), msgAndArgs...) + } + + expected = copyExportedFields(expected) + actual = copyExportedFields(actual) + + if !ObjectsAreEqualValues(expected, actual) { + diff := diff(expected, actual) + expected, actual = formatUnequalValues(expected, actual) + return Fail(t, fmt.Sprintf("Not equal (comparing only exported fields): \n"+ + "expected: %s\n"+ + "actual : %s%s", expected, actual, diff), msgAndArgs...) + } + + return true +} + // Exactly asserts that two objects are equal in value and type. // -// assert.Exactly(t, int32(123), int64(123)) +// assert.Exactly(t, int32(123), int64(123)) func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -494,7 +609,7 @@ func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{} // NotNil asserts that the specified object is not nil. // -// assert.NotNil(t, err) +// assert.NotNil(t, err) func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { if !isNil(object) { return true @@ -540,7 +655,7 @@ func isNil(object interface{}) bool { // Nil asserts that the specified object is nil. // -// assert.Nil(t, err) +// assert.Nil(t, err) func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { if isNil(object) { return true @@ -583,7 +698,7 @@ func isEmpty(object interface{}) bool { // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // -// assert.Empty(t, obj) +// assert.Empty(t, obj) func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { pass := isEmpty(object) if !pass { @@ -600,9 +715,9 @@ func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // -// if assert.NotEmpty(t, obj) { -// assert.Equal(t, "two", obj[1]) -// } +// if assert.NotEmpty(t, obj) { +// assert.Equal(t, "two", obj[1]) +// } func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { pass := !isEmpty(object) if !pass { @@ -631,7 +746,7 @@ func getLen(x interface{}) (ok bool, length int) { // Len asserts that the specified object has specific length. // Len also fails if the object has a type that len() not accept. // -// assert.Len(t, mySlice, 3) +// assert.Len(t, mySlice, 3) func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -649,7 +764,7 @@ func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) // True asserts that the specified value is true. // -// assert.True(t, myBool) +// assert.True(t, myBool) func True(t TestingT, value bool, msgAndArgs ...interface{}) bool { if !value { if h, ok := t.(tHelper); ok { @@ -664,7 +779,7 @@ func True(t TestingT, value bool, msgAndArgs ...interface{}) bool { // False asserts that the specified value is false. // -// assert.False(t, myBool) +// assert.False(t, myBool) func False(t TestingT, value bool, msgAndArgs ...interface{}) bool { if value { if h, ok := t.(tHelper); ok { @@ -679,7 +794,7 @@ func False(t TestingT, value bool, msgAndArgs ...interface{}) bool { // NotEqual asserts that the specified values are NOT equal. // -// assert.NotEqual(t, obj1, obj2) +// assert.NotEqual(t, obj1, obj2) // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). @@ -702,7 +817,7 @@ func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{ // NotEqualValues asserts that two objects are not equal even when converted to the same type // -// assert.NotEqualValues(t, obj1, obj2) +// assert.NotEqualValues(t, obj1, obj2) func NotEqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -761,9 +876,9 @@ func containsElement(list interface{}, element interface{}) (ok, found bool) { // Contains asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // -// assert.Contains(t, "Hello World", "World") -// assert.Contains(t, ["Hello", "World"], "World") -// assert.Contains(t, {"Hello": "World"}, "Hello") +// assert.Contains(t, "Hello World", "World") +// assert.Contains(t, ["Hello", "World"], "World") +// assert.Contains(t, {"Hello": "World"}, "Hello") func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -784,9 +899,9 @@ func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bo // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // -// assert.NotContains(t, "Hello World", "Earth") -// assert.NotContains(t, ["Hello", "World"], "Earth") -// assert.NotContains(t, {"Hello": "World"}, "Earth") +// assert.NotContains(t, "Hello World", "Earth") +// assert.NotContains(t, ["Hello", "World"], "Earth") +// assert.NotContains(t, {"Hello": "World"}, "Earth") func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -794,10 +909,10 @@ func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) ok, found := containsElement(s, contains) if !ok { - return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) + return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", s), msgAndArgs...) } if found { - return Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...) + return Fail(t, fmt.Sprintf("%#v should not contain %#v", s, contains), msgAndArgs...) } return true @@ -807,7 +922,7 @@ func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) // Subset asserts that the specified list(array, slice...) contains all // elements given in the specified subset(array, slice...). // -// assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") +// assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) { if h, ok := t.(tHelper); ok { h.Helper() @@ -863,7 +978,7 @@ func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok // NotSubset asserts that the specified list(array, slice...) contains not all // elements given in the specified subset(array, slice...). // -// assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") +// assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1048,7 +1163,7 @@ func didPanic(f PanicTestFunc) (didPanic bool, message interface{}, stack string // Panics asserts that the code inside the specified PanicTestFunc panics. // -// assert.Panics(t, func(){ GoCrazy() }) +// assert.Panics(t, func(){ GoCrazy() }) func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -1064,7 +1179,7 @@ func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { // PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // -// assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() }) +// assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() }) func PanicsWithValue(t TestingT, expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -1085,7 +1200,7 @@ func PanicsWithValue(t TestingT, expected interface{}, f PanicTestFunc, msgAndAr // panics, and that the recovered panic value is an error that satisfies the // EqualError comparison. // -// assert.PanicsWithError(t, "crazy error", func(){ GoCrazy() }) +// assert.PanicsWithError(t, "crazy error", func(){ GoCrazy() }) func PanicsWithError(t TestingT, errString string, f PanicTestFunc, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -1105,7 +1220,7 @@ func PanicsWithError(t TestingT, errString string, f PanicTestFunc, msgAndArgs . // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. // -// assert.NotPanics(t, func(){ RemainCalm() }) +// assert.NotPanics(t, func(){ RemainCalm() }) func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -1120,7 +1235,7 @@ func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { // WithinDuration asserts that the two times are within duration delta of each other. // -// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second) +// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second) func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -1136,7 +1251,7 @@ func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, // WithinRange asserts that a time is within a time range (inclusive). // -// assert.WithinRange(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second)) +// assert.WithinRange(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second)) func WithinRange(t TestingT, actual, start, end time.Time, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -1195,7 +1310,7 @@ func toFloat(x interface{}) (float64, bool) { // InDelta asserts that the two numerals are within delta of each other. // -// assert.InDelta(t, math.Pi, 22/7.0, 0.01) +// assert.InDelta(t, math.Pi, 22/7.0, 0.01) func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -1368,10 +1483,10 @@ func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, m // NoError asserts that a function returned no error (i.e. `nil`). // -// actualObj, err := SomeFunction() -// if assert.NoError(t, err) { -// assert.Equal(t, expectedObj, actualObj) -// } +// actualObj, err := SomeFunction() +// if assert.NoError(t, err) { +// assert.Equal(t, expectedObj, actualObj) +// } func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool { if err != nil { if h, ok := t.(tHelper); ok { @@ -1385,10 +1500,10 @@ func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool { // Error asserts that a function returned an error (i.e. not `nil`). // -// actualObj, err := SomeFunction() -// if assert.Error(t, err) { -// assert.Equal(t, expectedError, err) -// } +// actualObj, err := SomeFunction() +// if assert.Error(t, err) { +// assert.Equal(t, expectedError, err) +// } func Error(t TestingT, err error, msgAndArgs ...interface{}) bool { if err == nil { if h, ok := t.(tHelper); ok { @@ -1403,8 +1518,8 @@ func Error(t TestingT, err error, msgAndArgs ...interface{}) bool { // EqualError asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // -// actualObj, err := SomeFunction() -// assert.EqualError(t, err, expectedErrorString) +// actualObj, err := SomeFunction() +// assert.EqualError(t, err, expectedErrorString) func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -1426,8 +1541,8 @@ func EqualError(t TestingT, theError error, errString string, msgAndArgs ...inte // ErrorContains asserts that a function returned an error (i.e. not `nil`) // and that the error contains the specified substring. // -// actualObj, err := SomeFunction() -// assert.ErrorContains(t, err, expectedErrorSubString) +// actualObj, err := SomeFunction() +// assert.ErrorContains(t, err, expectedErrorSubString) func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -1460,8 +1575,8 @@ func matchRegexp(rx interface{}, str interface{}) bool { // Regexp asserts that a specified regexp matches a string. // -// assert.Regexp(t, regexp.MustCompile("start"), "it's starting") -// assert.Regexp(t, "start...$", "it's not starting") +// assert.Regexp(t, regexp.MustCompile("start"), "it's starting") +// assert.Regexp(t, "start...$", "it's not starting") func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -1478,8 +1593,8 @@ func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface // NotRegexp asserts that a specified regexp does not match a string. // -// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") -// assert.NotRegexp(t, "^start", "it's not starting") +// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") +// assert.NotRegexp(t, "^start", "it's not starting") func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -1591,7 +1706,7 @@ func NoDirExists(t TestingT, path string, msgAndArgs ...interface{}) bool { // JSONEq asserts that two JSON strings are equivalent. // -// assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) +// assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -1714,7 +1829,7 @@ type tHelper interface { // Eventually asserts that given condition will be met in waitFor time, // periodically checking target function each tick. // -// assert.Eventually(t, func() bool { return true; }, time.Second, 10*time.Millisecond) +// assert.Eventually(t, func() bool { return true; }, time.Second, 10*time.Millisecond) func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() @@ -1744,10 +1859,93 @@ func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick t } } +// CollectT implements the TestingT interface and collects all errors. +type CollectT struct { + errors []error +} + +// Errorf collects the error. +func (c *CollectT) Errorf(format string, args ...interface{}) { + c.errors = append(c.errors, fmt.Errorf(format, args...)) +} + +// FailNow panics. +func (c *CollectT) FailNow() { + panic("Assertion failed") +} + +// Reset clears the collected errors. +func (c *CollectT) Reset() { + c.errors = nil +} + +// Copy copies the collected errors to the supplied t. +func (c *CollectT) Copy(t TestingT) { + if tt, ok := t.(tHelper); ok { + tt.Helper() + } + for _, err := range c.errors { + t.Errorf("%v", err) + } +} + +// EventuallyWithT asserts that given condition will be met in waitFor time, +// periodically checking target function each tick. In contrast to Eventually, +// it supplies a CollectT to the condition function, so that the condition +// function can use the CollectT to call other assertions. +// The condition is considered "met" if no errors are raised in a tick. +// The supplied CollectT collects all errors from one tick (if there are any). +// If the condition is not met before waitFor, the collected errors of +// the last tick are copied to t. +// +// externalValue := false +// go func() { +// time.Sleep(8*time.Second) +// externalValue = true +// }() +// assert.EventuallyWithT(t, func(c *assert.CollectT) { +// // add assertions as needed; any assertion failure will fail the current tick +// assert.True(c, externalValue, "expected 'externalValue' to be true") +// }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false") +func EventuallyWithT(t TestingT, condition func(collect *CollectT), waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + + collect := new(CollectT) + ch := make(chan bool, 1) + + timer := time.NewTimer(waitFor) + defer timer.Stop() + + ticker := time.NewTicker(tick) + defer ticker.Stop() + + for tick := ticker.C; ; { + select { + case <-timer.C: + collect.Copy(t) + return Fail(t, "Condition never satisfied", msgAndArgs...) + case <-tick: + tick = nil + collect.Reset() + go func() { + condition(collect) + ch <- len(collect.errors) == 0 + }() + case v := <-ch: + if v { + return true + } + tick = ticker.C + } + } +} + // Never asserts that the given condition doesn't satisfy in waitFor time, // periodically checking the target function each tick. // -// assert.Never(t, func() bool { return false; }, time.Second, 10*time.Millisecond) +// assert.Never(t, func() bool { return false; }, time.Second, 10*time.Millisecond) func Never(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() diff --git a/vendor/github.com/stretchr/testify/assert/doc.go b/vendor/github.com/stretchr/testify/assert/doc.go index c9dccc4d6cd..4953981d387 100644 --- a/vendor/github.com/stretchr/testify/assert/doc.go +++ b/vendor/github.com/stretchr/testify/assert/doc.go @@ -1,39 +1,40 @@ // Package assert provides a set of comprehensive testing tools for use with the normal Go testing system. // -// Example Usage +// # Example Usage // // The following is a complete example using assert in a standard test function: -// import ( -// "testing" -// "github.com/stretchr/testify/assert" -// ) // -// func TestSomething(t *testing.T) { +// import ( +// "testing" +// "github.com/stretchr/testify/assert" +// ) // -// var a string = "Hello" -// var b string = "Hello" +// func TestSomething(t *testing.T) { // -// assert.Equal(t, a, b, "The two words should be the same.") +// var a string = "Hello" +// var b string = "Hello" // -// } +// assert.Equal(t, a, b, "The two words should be the same.") +// +// } // // if you assert many times, use the format below: // -// import ( -// "testing" -// "github.com/stretchr/testify/assert" -// ) +// import ( +// "testing" +// "github.com/stretchr/testify/assert" +// ) // -// func TestSomething(t *testing.T) { -// assert := assert.New(t) +// func TestSomething(t *testing.T) { +// assert := assert.New(t) // -// var a string = "Hello" -// var b string = "Hello" +// var a string = "Hello" +// var b string = "Hello" // -// assert.Equal(a, b, "The two words should be the same.") -// } +// assert.Equal(a, b, "The two words should be the same.") +// } // -// Assertions +// # Assertions // // Assertions allow you to easily write test code, and are global funcs in the `assert` package. // All assertion functions take, as the first argument, the `*testing.T` object provided by the diff --git a/vendor/github.com/stretchr/testify/assert/http_assertions.go b/vendor/github.com/stretchr/testify/assert/http_assertions.go index 4ed341dd289..d8038c28a75 100644 --- a/vendor/github.com/stretchr/testify/assert/http_assertions.go +++ b/vendor/github.com/stretchr/testify/assert/http_assertions.go @@ -23,7 +23,7 @@ func httpCode(handler http.HandlerFunc, method, url string, values url.Values) ( // HTTPSuccess asserts that a specified handler returns a success status code. // -// assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) +// assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) // // Returns whether the assertion was successful (true) or not (false). func HTTPSuccess(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool { @@ -45,7 +45,7 @@ func HTTPSuccess(t TestingT, handler http.HandlerFunc, method, url string, value // HTTPRedirect asserts that a specified handler returns a redirect status code. // -// assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPRedirect(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool { @@ -67,7 +67,7 @@ func HTTPRedirect(t TestingT, handler http.HandlerFunc, method, url string, valu // HTTPError asserts that a specified handler returns an error status code. // -// assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPError(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool { @@ -89,7 +89,7 @@ func HTTPError(t TestingT, handler http.HandlerFunc, method, url string, values // HTTPStatusCode asserts that a specified handler returns a specified status code. // -// assert.HTTPStatusCode(t, myHandler, "GET", "/notImplemented", nil, 501) +// assert.HTTPStatusCode(t, myHandler, "GET", "/notImplemented", nil, 501) // // Returns whether the assertion was successful (true) or not (false). func HTTPStatusCode(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, statuscode int, msgAndArgs ...interface{}) bool { @@ -124,7 +124,7 @@ func HTTPBody(handler http.HandlerFunc, method, url string, values url.Values) s // HTTPBodyContains asserts that a specified handler returns a // body that contains a string. // -// assert.HTTPBodyContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") +// assert.HTTPBodyContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool { @@ -144,7 +144,7 @@ func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method, url string, // HTTPBodyNotContains asserts that a specified handler returns a // body that does not contain a string. // -// assert.HTTPBodyNotContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") +// assert.HTTPBodyNotContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool { diff --git a/vendor/github.com/stretchr/testify/mock/doc.go b/vendor/github.com/stretchr/testify/mock/doc.go new file mode 100644 index 00000000000..d6b3c844cc8 --- /dev/null +++ b/vendor/github.com/stretchr/testify/mock/doc.go @@ -0,0 +1,44 @@ +// Package mock provides a system by which it is possible to mock your objects +// and verify calls are happening as expected. +// +// # Example Usage +// +// The mock package provides an object, Mock, that tracks activity on another object. It is usually +// embedded into a test object as shown below: +// +// type MyTestObject struct { +// // add a Mock object instance +// mock.Mock +// +// // other fields go here as normal +// } +// +// When implementing the methods of an interface, you wire your functions up +// to call the Mock.Called(args...) method, and return the appropriate values. +// +// For example, to mock a method that saves the name and age of a person and returns +// the year of their birth or an error, you might write this: +// +// func (o *MyTestObject) SavePersonDetails(firstname, lastname string, age int) (int, error) { +// args := o.Called(firstname, lastname, age) +// return args.Int(0), args.Error(1) +// } +// +// The Int, Error and Bool methods are examples of strongly typed getters that take the argument +// index position. Given this argument list: +// +// (12, true, "Something") +// +// You could read them out strongly typed like this: +// +// args.Int(0) +// args.Bool(1) +// args.String(2) +// +// For objects of your own type, use the generic Arguments.Get(index) method and make a type assertion: +// +// return args.Get(0).(*MyObject), args.Get(1).(*AnotherObjectOfMine) +// +// This may cause a panic if the object you are getting is nil (the type assertion will fail), in those +// cases you should check for nil first. +package mock diff --git a/vendor/github.com/stretchr/testify/mock/mock.go b/vendor/github.com/stretchr/testify/mock/mock.go new file mode 100644 index 00000000000..f4b42e44ffe --- /dev/null +++ b/vendor/github.com/stretchr/testify/mock/mock.go @@ -0,0 +1,1226 @@ +package mock + +import ( + "errors" + "fmt" + "path" + "reflect" + "regexp" + "runtime" + "strings" + "sync" + "time" + + "github.com/davecgh/go-spew/spew" + "github.com/pmezard/go-difflib/difflib" + "github.com/stretchr/objx" + + "github.com/stretchr/testify/assert" +) + +// TestingT is an interface wrapper around *testing.T +type TestingT interface { + Logf(format string, args ...interface{}) + Errorf(format string, args ...interface{}) + FailNow() +} + +/* + Call +*/ + +// Call represents a method call and is used for setting expectations, +// as well as recording activity. +type Call struct { + Parent *Mock + + // The name of the method that was or will be called. + Method string + + // Holds the arguments of the method. + Arguments Arguments + + // Holds the arguments that should be returned when + // this method is called. + ReturnArguments Arguments + + // Holds the caller info for the On() call + callerInfo []string + + // The number of times to return the return arguments when setting + // expectations. 0 means to always return the value. + Repeatability int + + // Amount of times this call has been called + totalCalls int + + // Call to this method can be optional + optional bool + + // Holds a channel that will be used to block the Return until it either + // receives a message or is closed. nil means it returns immediately. + WaitFor <-chan time.Time + + waitTime time.Duration + + // Holds a handler used to manipulate arguments content that are passed by + // reference. It's useful when mocking methods such as unmarshalers or + // decoders. + RunFn func(Arguments) + + // PanicMsg holds msg to be used to mock panic on the function call + // if the PanicMsg is set to a non nil string the function call will panic + // irrespective of other settings + PanicMsg *string + + // Calls which must be satisfied before this call can be + requires []*Call +} + +func newCall(parent *Mock, methodName string, callerInfo []string, methodArguments ...interface{}) *Call { + return &Call{ + Parent: parent, + Method: methodName, + Arguments: methodArguments, + ReturnArguments: make([]interface{}, 0), + callerInfo: callerInfo, + Repeatability: 0, + WaitFor: nil, + RunFn: nil, + PanicMsg: nil, + } +} + +func (c *Call) lock() { + c.Parent.mutex.Lock() +} + +func (c *Call) unlock() { + c.Parent.mutex.Unlock() +} + +// Return specifies the return arguments for the expectation. +// +// Mock.On("DoSomething").Return(errors.New("failed")) +func (c *Call) Return(returnArguments ...interface{}) *Call { + c.lock() + defer c.unlock() + + c.ReturnArguments = returnArguments + + return c +} + +// Panic specifies if the functon call should fail and the panic message +// +// Mock.On("DoSomething").Panic("test panic") +func (c *Call) Panic(msg string) *Call { + c.lock() + defer c.unlock() + + c.PanicMsg = &msg + + return c +} + +// Once indicates that that the mock should only return the value once. +// +// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Once() +func (c *Call) Once() *Call { + return c.Times(1) +} + +// Twice indicates that that the mock should only return the value twice. +// +// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Twice() +func (c *Call) Twice() *Call { + return c.Times(2) +} + +// Times indicates that that the mock should only return the indicated number +// of times. +// +// Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Times(5) +func (c *Call) Times(i int) *Call { + c.lock() + defer c.unlock() + c.Repeatability = i + return c +} + +// WaitUntil sets the channel that will block the mock's return until its closed +// or a message is received. +// +// Mock.On("MyMethod", arg1, arg2).WaitUntil(time.After(time.Second)) +func (c *Call) WaitUntil(w <-chan time.Time) *Call { + c.lock() + defer c.unlock() + c.WaitFor = w + return c +} + +// After sets how long to block until the call returns +// +// Mock.On("MyMethod", arg1, arg2).After(time.Second) +func (c *Call) After(d time.Duration) *Call { + c.lock() + defer c.unlock() + c.waitTime = d + return c +} + +// Run sets a handler to be called before returning. It can be used when +// mocking a method (such as an unmarshaler) that takes a pointer to a struct and +// sets properties in such struct +// +// Mock.On("Unmarshal", AnythingOfType("*map[string]interface{}")).Return().Run(func(args Arguments) { +// arg := args.Get(0).(*map[string]interface{}) +// arg["foo"] = "bar" +// }) +func (c *Call) Run(fn func(args Arguments)) *Call { + c.lock() + defer c.unlock() + c.RunFn = fn + return c +} + +// Maybe allows the method call to be optional. Not calling an optional method +// will not cause an error while asserting expectations +func (c *Call) Maybe() *Call { + c.lock() + defer c.unlock() + c.optional = true + return c +} + +// On chains a new expectation description onto the mocked interface. This +// allows syntax like. +// +// Mock. +// On("MyMethod", 1).Return(nil). +// On("MyOtherMethod", 'a', 'b', 'c').Return(errors.New("Some Error")) +// +//go:noinline +func (c *Call) On(methodName string, arguments ...interface{}) *Call { + return c.Parent.On(methodName, arguments...) +} + +// Unset removes a mock handler from being called. +// +// test.On("func", mock.Anything).Unset() +func (c *Call) Unset() *Call { + var unlockOnce sync.Once + + for _, arg := range c.Arguments { + if v := reflect.ValueOf(arg); v.Kind() == reflect.Func { + panic(fmt.Sprintf("cannot use Func in expectations. Use mock.AnythingOfType(\"%T\")", arg)) + } + } + + c.lock() + defer unlockOnce.Do(c.unlock) + + foundMatchingCall := false + + // in-place filter slice for calls to be removed - iterate from 0'th to last skipping unnecessary ones + var index int // write index + for _, call := range c.Parent.ExpectedCalls { + if call.Method == c.Method { + _, diffCount := call.Arguments.Diff(c.Arguments) + if diffCount == 0 { + foundMatchingCall = true + // Remove from ExpectedCalls - just skip it + continue + } + } + c.Parent.ExpectedCalls[index] = call + index++ + } + // trim slice up to last copied index + c.Parent.ExpectedCalls = c.Parent.ExpectedCalls[:index] + + if !foundMatchingCall { + unlockOnce.Do(c.unlock) + c.Parent.fail("\n\nmock: Could not find expected call\n-----------------------------\n\n%s\n\n", + callString(c.Method, c.Arguments, true), + ) + } + + return c +} + +// NotBefore indicates that the mock should only be called after the referenced +// calls have been called as expected. The referenced calls may be from the +// same mock instance and/or other mock instances. +// +// Mock.On("Do").Return(nil).Notbefore( +// Mock.On("Init").Return(nil) +// ) +func (c *Call) NotBefore(calls ...*Call) *Call { + c.lock() + defer c.unlock() + + for _, call := range calls { + if call.Parent == nil { + panic("not before calls must be created with Mock.On()") + } + } + + c.requires = append(c.requires, calls...) + return c +} + +// Mock is the workhorse used to track activity on another object. +// For an example of its usage, refer to the "Example Usage" section at the top +// of this document. +type Mock struct { + // Represents the calls that are expected of + // an object. + ExpectedCalls []*Call + + // Holds the calls that were made to this mocked object. + Calls []Call + + // test is An optional variable that holds the test struct, to be used when an + // invalid mock call was made. + test TestingT + + // TestData holds any data that might be useful for testing. Testify ignores + // this data completely allowing you to do whatever you like with it. + testData objx.Map + + mutex sync.Mutex +} + +// String provides a %v format string for Mock. +// Note: this is used implicitly by Arguments.Diff if a Mock is passed. +// It exists because go's default %v formatting traverses the struct +// without acquiring the mutex, which is detected by go test -race. +func (m *Mock) String() string { + return fmt.Sprintf("%[1]T<%[1]p>", m) +} + +// TestData holds any data that might be useful for testing. Testify ignores +// this data completely allowing you to do whatever you like with it. +func (m *Mock) TestData() objx.Map { + if m.testData == nil { + m.testData = make(objx.Map) + } + + return m.testData +} + +/* + Setting expectations +*/ + +// Test sets the test struct variable of the mock object +func (m *Mock) Test(t TestingT) { + m.mutex.Lock() + defer m.mutex.Unlock() + m.test = t +} + +// fail fails the current test with the given formatted format and args. +// In case that a test was defined, it uses the test APIs for failing a test, +// otherwise it uses panic. +func (m *Mock) fail(format string, args ...interface{}) { + m.mutex.Lock() + defer m.mutex.Unlock() + + if m.test == nil { + panic(fmt.Sprintf(format, args...)) + } + m.test.Errorf(format, args...) + m.test.FailNow() +} + +// On starts a description of an expectation of the specified method +// being called. +// +// Mock.On("MyMethod", arg1, arg2) +func (m *Mock) On(methodName string, arguments ...interface{}) *Call { + for _, arg := range arguments { + if v := reflect.ValueOf(arg); v.Kind() == reflect.Func { + panic(fmt.Sprintf("cannot use Func in expectations. Use mock.AnythingOfType(\"%T\")", arg)) + } + } + + m.mutex.Lock() + defer m.mutex.Unlock() + c := newCall(m, methodName, assert.CallerInfo(), arguments...) + m.ExpectedCalls = append(m.ExpectedCalls, c) + return c +} + +// /* +// Recording and responding to activity +// */ + +func (m *Mock) findExpectedCall(method string, arguments ...interface{}) (int, *Call) { + var expectedCall *Call + + for i, call := range m.ExpectedCalls { + if call.Method == method { + _, diffCount := call.Arguments.Diff(arguments) + if diffCount == 0 { + expectedCall = call + if call.Repeatability > -1 { + return i, call + } + } + } + } + + return -1, expectedCall +} + +type matchCandidate struct { + call *Call + mismatch string + diffCount int +} + +func (c matchCandidate) isBetterMatchThan(other matchCandidate) bool { + if c.call == nil { + return false + } + if other.call == nil { + return true + } + + if c.diffCount > other.diffCount { + return false + } + if c.diffCount < other.diffCount { + return true + } + + if c.call.Repeatability > 0 && other.call.Repeatability <= 0 { + return true + } + return false +} + +func (m *Mock) findClosestCall(method string, arguments ...interface{}) (*Call, string) { + var bestMatch matchCandidate + + for _, call := range m.expectedCalls() { + if call.Method == method { + + errInfo, tempDiffCount := call.Arguments.Diff(arguments) + tempCandidate := matchCandidate{ + call: call, + mismatch: errInfo, + diffCount: tempDiffCount, + } + if tempCandidate.isBetterMatchThan(bestMatch) { + bestMatch = tempCandidate + } + } + } + + return bestMatch.call, bestMatch.mismatch +} + +func callString(method string, arguments Arguments, includeArgumentValues bool) string { + var argValsString string + if includeArgumentValues { + var argVals []string + for argIndex, arg := range arguments { + if _, ok := arg.(*FunctionalOptionsArgument); ok { + argVals = append(argVals, fmt.Sprintf("%d: %s", argIndex, arg)) + continue + } + argVals = append(argVals, fmt.Sprintf("%d: %#v", argIndex, arg)) + } + argValsString = fmt.Sprintf("\n\t\t%s", strings.Join(argVals, "\n\t\t")) + } + + return fmt.Sprintf("%s(%s)%s", method, arguments.String(), argValsString) +} + +// Called tells the mock object that a method has been called, and gets an array +// of arguments to return. Panics if the call is unexpected (i.e. not preceded by +// appropriate .On .Return() calls) +// If Call.WaitFor is set, blocks until the channel is closed or receives a message. +func (m *Mock) Called(arguments ...interface{}) Arguments { + // get the calling function's name + pc, _, _, ok := runtime.Caller(1) + if !ok { + panic("Couldn't get the caller information") + } + functionPath := runtime.FuncForPC(pc).Name() + // Next four lines are required to use GCCGO function naming conventions. + // For Ex: github_com_docker_libkv_store_mock.WatchTree.pN39_github_com_docker_libkv_store_mock.Mock + // uses interface information unlike golang github.com/docker/libkv/store/mock.(*Mock).WatchTree + // With GCCGO we need to remove interface information starting from pN
. + re := regexp.MustCompile("\\.pN\\d+_") + if re.MatchString(functionPath) { + functionPath = re.Split(functionPath, -1)[0] + } + parts := strings.Split(functionPath, ".") + functionName := parts[len(parts)-1] + return m.MethodCalled(functionName, arguments...) +} + +// MethodCalled tells the mock object that the given method has been called, and gets +// an array of arguments to return. Panics if the call is unexpected (i.e. not preceded +// by appropriate .On .Return() calls) +// If Call.WaitFor is set, blocks until the channel is closed or receives a message. +func (m *Mock) MethodCalled(methodName string, arguments ...interface{}) Arguments { + m.mutex.Lock() + // TODO: could combine expected and closes in single loop + found, call := m.findExpectedCall(methodName, arguments...) + + if found < 0 { + // expected call found but it has already been called with repeatable times + if call != nil { + m.mutex.Unlock() + m.fail("\nassert: mock: The method has been called over %d times.\n\tEither do one more Mock.On(\"%s\").Return(...), or remove extra call.\n\tThis call was unexpected:\n\t\t%s\n\tat: %s", call.totalCalls, methodName, callString(methodName, arguments, true), assert.CallerInfo()) + } + // we have to fail here - because we don't know what to do + // as the return arguments. This is because: + // + // a) this is a totally unexpected call to this method, + // b) the arguments are not what was expected, or + // c) the developer has forgotten to add an accompanying On...Return pair. + closestCall, mismatch := m.findClosestCall(methodName, arguments...) + m.mutex.Unlock() + + if closestCall != nil { + m.fail("\n\nmock: Unexpected Method Call\n-----------------------------\n\n%s\n\nThe closest call I have is: \n\n%s\n\n%s\nDiff: %s", + callString(methodName, arguments, true), + callString(methodName, closestCall.Arguments, true), + diffArguments(closestCall.Arguments, arguments), + strings.TrimSpace(mismatch), + ) + } else { + m.fail("\nassert: mock: I don't know what to return because the method call was unexpected.\n\tEither do Mock.On(\"%s\").Return(...) first, or remove the %s() call.\n\tThis method was unexpected:\n\t\t%s\n\tat: %s", methodName, methodName, callString(methodName, arguments, true), assert.CallerInfo()) + } + } + + for _, requirement := range call.requires { + if satisfied, _ := requirement.Parent.checkExpectation(requirement); !satisfied { + m.mutex.Unlock() + m.fail("mock: Unexpected Method Call\n-----------------------------\n\n%s\n\nMust not be called before%s:\n\n%s", + callString(call.Method, call.Arguments, true), + func() (s string) { + if requirement.totalCalls > 0 { + s = " another call of" + } + if call.Parent != requirement.Parent { + s += " method from another mock instance" + } + return + }(), + callString(requirement.Method, requirement.Arguments, true), + ) + } + } + + if call.Repeatability == 1 { + call.Repeatability = -1 + } else if call.Repeatability > 1 { + call.Repeatability-- + } + call.totalCalls++ + + // add the call + m.Calls = append(m.Calls, *newCall(m, methodName, assert.CallerInfo(), arguments...)) + m.mutex.Unlock() + + // block if specified + if call.WaitFor != nil { + <-call.WaitFor + } else { + time.Sleep(call.waitTime) + } + + m.mutex.Lock() + panicMsg := call.PanicMsg + m.mutex.Unlock() + if panicMsg != nil { + panic(*panicMsg) + } + + m.mutex.Lock() + runFn := call.RunFn + m.mutex.Unlock() + + if runFn != nil { + runFn(arguments) + } + + m.mutex.Lock() + returnArgs := call.ReturnArguments + m.mutex.Unlock() + + return returnArgs +} + +/* + Assertions +*/ + +type assertExpectationser interface { + AssertExpectations(TestingT) bool +} + +// AssertExpectationsForObjects asserts that everything specified with On and Return +// of the specified objects was in fact called as expected. +// +// Calls may have occurred in any order. +func AssertExpectationsForObjects(t TestingT, testObjects ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + for _, obj := range testObjects { + if m, ok := obj.(*Mock); ok { + t.Logf("Deprecated mock.AssertExpectationsForObjects(myMock.Mock) use mock.AssertExpectationsForObjects(myMock)") + obj = m + } + m := obj.(assertExpectationser) + if !m.AssertExpectations(t) { + t.Logf("Expectations didn't match for Mock: %+v", reflect.TypeOf(m)) + return false + } + } + return true +} + +// AssertExpectations asserts that everything specified with On and Return was +// in fact called as expected. Calls may have occurred in any order. +func (m *Mock) AssertExpectations(t TestingT) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + + m.mutex.Lock() + defer m.mutex.Unlock() + var failedExpectations int + + // iterate through each expectation + expectedCalls := m.expectedCalls() + for _, expectedCall := range expectedCalls { + satisfied, reason := m.checkExpectation(expectedCall) + if !satisfied { + failedExpectations++ + } + t.Logf(reason) + } + + if failedExpectations != 0 { + t.Errorf("FAIL: %d out of %d expectation(s) were met.\n\tThe code you are testing needs to make %d more call(s).\n\tat: %s", len(expectedCalls)-failedExpectations, len(expectedCalls), failedExpectations, assert.CallerInfo()) + } + + return failedExpectations == 0 +} + +func (m *Mock) checkExpectation(call *Call) (bool, string) { + if !call.optional && !m.methodWasCalled(call.Method, call.Arguments) && call.totalCalls == 0 { + return false, fmt.Sprintf("FAIL:\t%s(%s)\n\t\tat: %s", call.Method, call.Arguments.String(), call.callerInfo) + } + if call.Repeatability > 0 { + return false, fmt.Sprintf("FAIL:\t%s(%s)\n\t\tat: %s", call.Method, call.Arguments.String(), call.callerInfo) + } + return true, fmt.Sprintf("PASS:\t%s(%s)", call.Method, call.Arguments.String()) +} + +// AssertNumberOfCalls asserts that the method was called expectedCalls times. +func (m *Mock) AssertNumberOfCalls(t TestingT, methodName string, expectedCalls int) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + m.mutex.Lock() + defer m.mutex.Unlock() + var actualCalls int + for _, call := range m.calls() { + if call.Method == methodName { + actualCalls++ + } + } + return assert.Equal(t, expectedCalls, actualCalls, fmt.Sprintf("Expected number of calls (%d) does not match the actual number of calls (%d).", expectedCalls, actualCalls)) +} + +// AssertCalled asserts that the method was called. +// It can produce a false result when an argument is a pointer type and the underlying value changed after calling the mocked method. +func (m *Mock) AssertCalled(t TestingT, methodName string, arguments ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + m.mutex.Lock() + defer m.mutex.Unlock() + if !m.methodWasCalled(methodName, arguments) { + var calledWithArgs []string + for _, call := range m.calls() { + calledWithArgs = append(calledWithArgs, fmt.Sprintf("%v", call.Arguments)) + } + if len(calledWithArgs) == 0 { + return assert.Fail(t, "Should have called with given arguments", + fmt.Sprintf("Expected %q to have been called with:\n%v\nbut no actual calls happened", methodName, arguments)) + } + return assert.Fail(t, "Should have called with given arguments", + fmt.Sprintf("Expected %q to have been called with:\n%v\nbut actual calls were:\n %v", methodName, arguments, strings.Join(calledWithArgs, "\n"))) + } + return true +} + +// AssertNotCalled asserts that the method was not called. +// It can produce a false result when an argument is a pointer type and the underlying value changed after calling the mocked method. +func (m *Mock) AssertNotCalled(t TestingT, methodName string, arguments ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + m.mutex.Lock() + defer m.mutex.Unlock() + if m.methodWasCalled(methodName, arguments) { + return assert.Fail(t, "Should not have called with given arguments", + fmt.Sprintf("Expected %q to not have been called with:\n%v\nbut actually it was.", methodName, arguments)) + } + return true +} + +// IsMethodCallable checking that the method can be called +// If the method was called more than `Repeatability` return false +func (m *Mock) IsMethodCallable(t TestingT, methodName string, arguments ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + m.mutex.Lock() + defer m.mutex.Unlock() + + for _, v := range m.ExpectedCalls { + if v.Method != methodName { + continue + } + if len(arguments) != len(v.Arguments) { + continue + } + if v.Repeatability < v.totalCalls { + continue + } + if isArgsEqual(v.Arguments, arguments) { + return true + } + } + return false +} + +// isArgsEqual compares arguments +func isArgsEqual(expected Arguments, args []interface{}) bool { + if len(expected) != len(args) { + return false + } + for i, v := range args { + if !reflect.DeepEqual(expected[i], v) { + return false + } + } + return true +} + +func (m *Mock) methodWasCalled(methodName string, expected []interface{}) bool { + for _, call := range m.calls() { + if call.Method == methodName { + + _, differences := Arguments(expected).Diff(call.Arguments) + + if differences == 0 { + // found the expected call + return true + } + + } + } + // we didn't find the expected call + return false +} + +func (m *Mock) expectedCalls() []*Call { + return append([]*Call{}, m.ExpectedCalls...) +} + +func (m *Mock) calls() []Call { + return append([]Call{}, m.Calls...) +} + +/* + Arguments +*/ + +// Arguments holds an array of method arguments or return values. +type Arguments []interface{} + +const ( + // Anything is used in Diff and Assert when the argument being tested + // shouldn't be taken into consideration. + Anything = "mock.Anything" +) + +// AnythingOfTypeArgument is a string that contains the type of an argument +// for use when type checking. Used in Diff and Assert. +type AnythingOfTypeArgument string + +// AnythingOfType returns an AnythingOfTypeArgument object containing the +// name of the type to check for. Used in Diff and Assert. +// +// For example: +// +// Assert(t, AnythingOfType("string"), AnythingOfType("int")) +func AnythingOfType(t string) AnythingOfTypeArgument { + return AnythingOfTypeArgument(t) +} + +// IsTypeArgument is a struct that contains the type of an argument +// for use when type checking. This is an alternative to AnythingOfType. +// Used in Diff and Assert. +type IsTypeArgument struct { + t interface{} +} + +// IsType returns an IsTypeArgument object containing the type to check for. +// You can provide a zero-value of the type to check. This is an +// alternative to AnythingOfType. Used in Diff and Assert. +// +// For example: +// Assert(t, IsType(""), IsType(0)) +func IsType(t interface{}) *IsTypeArgument { + return &IsTypeArgument{t: t} +} + +// FunctionalOptionsArgument is a struct that contains the type and value of an functional option argument +// for use when type checking. +type FunctionalOptionsArgument struct { + value interface{} +} + +// String returns the string representation of FunctionalOptionsArgument +func (f *FunctionalOptionsArgument) String() string { + var name string + tValue := reflect.ValueOf(f.value) + if tValue.Len() > 0 { + name = "[]" + reflect.TypeOf(tValue.Index(0).Interface()).String() + } + + return strings.Replace(fmt.Sprintf("%#v", f.value), "[]interface {}", name, 1) +} + +// FunctionalOptions returns an FunctionalOptionsArgument object containing the functional option type +// and the values to check of +// +// For example: +// Assert(t, FunctionalOptions("[]foo.FunctionalOption", foo.Opt1(), foo.Opt2())) +func FunctionalOptions(value ...interface{}) *FunctionalOptionsArgument { + return &FunctionalOptionsArgument{ + value: value, + } +} + +// argumentMatcher performs custom argument matching, returning whether or +// not the argument is matched by the expectation fixture function. +type argumentMatcher struct { + // fn is a function which accepts one argument, and returns a bool. + fn reflect.Value +} + +func (f argumentMatcher) Matches(argument interface{}) bool { + expectType := f.fn.Type().In(0) + expectTypeNilSupported := false + switch expectType.Kind() { + case reflect.Interface, reflect.Chan, reflect.Func, reflect.Map, reflect.Slice, reflect.Ptr: + expectTypeNilSupported = true + } + + argType := reflect.TypeOf(argument) + var arg reflect.Value + if argType == nil { + arg = reflect.New(expectType).Elem() + } else { + arg = reflect.ValueOf(argument) + } + + if argType == nil && !expectTypeNilSupported { + panic(errors.New("attempting to call matcher with nil for non-nil expected type")) + } + if argType == nil || argType.AssignableTo(expectType) { + result := f.fn.Call([]reflect.Value{arg}) + return result[0].Bool() + } + return false +} + +func (f argumentMatcher) String() string { + return fmt.Sprintf("func(%s) bool", f.fn.Type().In(0).String()) +} + +// MatchedBy can be used to match a mock call based on only certain properties +// from a complex struct or some calculation. It takes a function that will be +// evaluated with the called argument and will return true when there's a match +// and false otherwise. +// +// Example: +// m.On("Do", MatchedBy(func(req *http.Request) bool { return req.Host == "example.com" })) +// +// |fn|, must be a function accepting a single argument (of the expected type) +// which returns a bool. If |fn| doesn't match the required signature, +// MatchedBy() panics. +func MatchedBy(fn interface{}) argumentMatcher { + fnType := reflect.TypeOf(fn) + + if fnType.Kind() != reflect.Func { + panic(fmt.Sprintf("assert: arguments: %s is not a func", fn)) + } + if fnType.NumIn() != 1 { + panic(fmt.Sprintf("assert: arguments: %s does not take exactly one argument", fn)) + } + if fnType.NumOut() != 1 || fnType.Out(0).Kind() != reflect.Bool { + panic(fmt.Sprintf("assert: arguments: %s does not return a bool", fn)) + } + + return argumentMatcher{fn: reflect.ValueOf(fn)} +} + +// Get Returns the argument at the specified index. +func (args Arguments) Get(index int) interface{} { + if index+1 > len(args) { + panic(fmt.Sprintf("assert: arguments: Cannot call Get(%d) because there are %d argument(s).", index, len(args))) + } + return args[index] +} + +// Is gets whether the objects match the arguments specified. +func (args Arguments) Is(objects ...interface{}) bool { + for i, obj := range args { + if obj != objects[i] { + return false + } + } + return true +} + +// Diff gets a string describing the differences between the arguments +// and the specified objects. +// +// Returns the diff string and number of differences found. +func (args Arguments) Diff(objects []interface{}) (string, int) { + // TODO: could return string as error and nil for No difference + + output := "\n" + var differences int + + maxArgCount := len(args) + if len(objects) > maxArgCount { + maxArgCount = len(objects) + } + + for i := 0; i < maxArgCount; i++ { + var actual, expected interface{} + var actualFmt, expectedFmt string + + if len(objects) <= i { + actual = "(Missing)" + actualFmt = "(Missing)" + } else { + actual = objects[i] + actualFmt = fmt.Sprintf("(%[1]T=%[1]v)", actual) + } + + if len(args) <= i { + expected = "(Missing)" + expectedFmt = "(Missing)" + } else { + expected = args[i] + expectedFmt = fmt.Sprintf("(%[1]T=%[1]v)", expected) + } + + if matcher, ok := expected.(argumentMatcher); ok { + var matches bool + func() { + defer func() { + if r := recover(); r != nil { + actualFmt = fmt.Sprintf("panic in argument matcher: %v", r) + } + }() + matches = matcher.Matches(actual) + }() + if matches { + output = fmt.Sprintf("%s\t%d: PASS: %s matched by %s\n", output, i, actualFmt, matcher) + } else { + differences++ + output = fmt.Sprintf("%s\t%d: FAIL: %s not matched by %s\n", output, i, actualFmt, matcher) + } + } else if reflect.TypeOf(expected) == reflect.TypeOf((*AnythingOfTypeArgument)(nil)).Elem() { + // type checking + if reflect.TypeOf(actual).Name() != string(expected.(AnythingOfTypeArgument)) && reflect.TypeOf(actual).String() != string(expected.(AnythingOfTypeArgument)) { + // not match + differences++ + output = fmt.Sprintf("%s\t%d: FAIL: type %s != type %s - %s\n", output, i, expected, reflect.TypeOf(actual).Name(), actualFmt) + } + } else if reflect.TypeOf(expected) == reflect.TypeOf((*IsTypeArgument)(nil)) { + t := expected.(*IsTypeArgument).t + if reflect.TypeOf(t) != reflect.TypeOf(actual) { + differences++ + output = fmt.Sprintf("%s\t%d: FAIL: type %s != type %s - %s\n", output, i, reflect.TypeOf(t).Name(), reflect.TypeOf(actual).Name(), actualFmt) + } + } else if reflect.TypeOf(expected) == reflect.TypeOf((*FunctionalOptionsArgument)(nil)) { + t := expected.(*FunctionalOptionsArgument).value + + var name string + tValue := reflect.ValueOf(t) + if tValue.Len() > 0 { + name = "[]" + reflect.TypeOf(tValue.Index(0).Interface()).String() + } + + tName := reflect.TypeOf(t).Name() + if name != reflect.TypeOf(actual).String() && tValue.Len() != 0 { + differences++ + output = fmt.Sprintf("%s\t%d: FAIL: type %s != type %s - %s\n", output, i, tName, reflect.TypeOf(actual).Name(), actualFmt) + } else { + if ef, af := assertOpts(t, actual); ef == "" && af == "" { + // match + output = fmt.Sprintf("%s\t%d: PASS: %s == %s\n", output, i, tName, tName) + } else { + // not match + differences++ + output = fmt.Sprintf("%s\t%d: FAIL: %s != %s\n", output, i, af, ef) + } + } + } else { + // normal checking + + if assert.ObjectsAreEqual(expected, Anything) || assert.ObjectsAreEqual(actual, Anything) || assert.ObjectsAreEqual(actual, expected) { + // match + output = fmt.Sprintf("%s\t%d: PASS: %s == %s\n", output, i, actualFmt, expectedFmt) + } else { + // not match + differences++ + output = fmt.Sprintf("%s\t%d: FAIL: %s != %s\n", output, i, actualFmt, expectedFmt) + } + } + + } + + if differences == 0 { + return "No differences.", differences + } + + return output, differences +} + +// Assert compares the arguments with the specified objects and fails if +// they do not exactly match. +func (args Arguments) Assert(t TestingT, objects ...interface{}) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + + // get the differences + diff, diffCount := args.Diff(objects) + + if diffCount == 0 { + return true + } + + // there are differences... report them... + t.Logf(diff) + t.Errorf("%sArguments do not match.", assert.CallerInfo()) + + return false +} + +// String gets the argument at the specified index. Panics if there is no argument, or +// if the argument is of the wrong type. +// +// If no index is provided, String() returns a complete string representation +// of the arguments. +func (args Arguments) String(indexOrNil ...int) string { + if len(indexOrNil) == 0 { + // normal String() method - return a string representation of the args + var argsStr []string + for _, arg := range args { + argsStr = append(argsStr, fmt.Sprintf("%T", arg)) // handles nil nicely + } + return strings.Join(argsStr, ",") + } else if len(indexOrNil) == 1 { + // Index has been specified - get the argument at that index + index := indexOrNil[0] + var s string + var ok bool + if s, ok = args.Get(index).(string); !ok { + panic(fmt.Sprintf("assert: arguments: String(%d) failed because object wasn't correct type: %s", index, args.Get(index))) + } + return s + } + + panic(fmt.Sprintf("assert: arguments: Wrong number of arguments passed to String. Must be 0 or 1, not %d", len(indexOrNil))) +} + +// Int gets the argument at the specified index. Panics if there is no argument, or +// if the argument is of the wrong type. +func (args Arguments) Int(index int) int { + var s int + var ok bool + if s, ok = args.Get(index).(int); !ok { + panic(fmt.Sprintf("assert: arguments: Int(%d) failed because object wasn't correct type: %v", index, args.Get(index))) + } + return s +} + +// Error gets the argument at the specified index. Panics if there is no argument, or +// if the argument is of the wrong type. +func (args Arguments) Error(index int) error { + obj := args.Get(index) + var s error + var ok bool + if obj == nil { + return nil + } + if s, ok = obj.(error); !ok { + panic(fmt.Sprintf("assert: arguments: Error(%d) failed because object wasn't correct type: %v", index, args.Get(index))) + } + return s +} + +// Bool gets the argument at the specified index. Panics if there is no argument, or +// if the argument is of the wrong type. +func (args Arguments) Bool(index int) bool { + var s bool + var ok bool + if s, ok = args.Get(index).(bool); !ok { + panic(fmt.Sprintf("assert: arguments: Bool(%d) failed because object wasn't correct type: %v", index, args.Get(index))) + } + return s +} + +func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) { + t := reflect.TypeOf(v) + k := t.Kind() + + if k == reflect.Ptr { + t = t.Elem() + k = t.Kind() + } + return t, k +} + +func diffArguments(expected Arguments, actual Arguments) string { + if len(expected) != len(actual) { + return fmt.Sprintf("Provided %v arguments, mocked for %v arguments", len(expected), len(actual)) + } + + for x := range expected { + if diffString := diff(expected[x], actual[x]); diffString != "" { + return fmt.Sprintf("Difference found in argument %v:\n\n%s", x, diffString) + } + } + + return "" +} + +// diff returns a diff of both values as long as both are of the same type and +// are a struct, map, slice or array. Otherwise it returns an empty string. +func diff(expected interface{}, actual interface{}) string { + if expected == nil || actual == nil { + return "" + } + + et, ek := typeAndKind(expected) + at, _ := typeAndKind(actual) + + if et != at { + return "" + } + + if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array { + return "" + } + + e := spewConfig.Sdump(expected) + a := spewConfig.Sdump(actual) + + diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{ + A: difflib.SplitLines(e), + B: difflib.SplitLines(a), + FromFile: "Expected", + FromDate: "", + ToFile: "Actual", + ToDate: "", + Context: 1, + }) + + return diff +} + +var spewConfig = spew.ConfigState{ + Indent: " ", + DisablePointerAddresses: true, + DisableCapacities: true, + SortKeys: true, +} + +type tHelper interface { + Helper() +} + +func assertOpts(expected, actual interface{}) (expectedFmt, actualFmt string) { + expectedOpts := reflect.ValueOf(expected) + actualOpts := reflect.ValueOf(actual) + var expectedNames []string + for i := 0; i < expectedOpts.Len(); i++ { + expectedNames = append(expectedNames, funcName(expectedOpts.Index(i).Interface())) + } + var actualNames []string + for i := 0; i < actualOpts.Len(); i++ { + actualNames = append(actualNames, funcName(actualOpts.Index(i).Interface())) + } + if !assert.ObjectsAreEqual(expectedNames, actualNames) { + expectedFmt = fmt.Sprintf("%v", expectedNames) + actualFmt = fmt.Sprintf("%v", actualNames) + return + } + + for i := 0; i < expectedOpts.Len(); i++ { + expectedOpt := expectedOpts.Index(i).Interface() + actualOpt := actualOpts.Index(i).Interface() + + expectedFunc := expectedNames[i] + actualFunc := actualNames[i] + if expectedFunc != actualFunc { + expectedFmt = expectedFunc + actualFmt = actualFunc + return + } + + ot := reflect.TypeOf(expectedOpt) + var expectedValues []reflect.Value + var actualValues []reflect.Value + if ot.NumIn() == 0 { + return + } + + for i := 0; i < ot.NumIn(); i++ { + vt := ot.In(i).Elem() + expectedValues = append(expectedValues, reflect.New(vt)) + actualValues = append(actualValues, reflect.New(vt)) + } + + reflect.ValueOf(expectedOpt).Call(expectedValues) + reflect.ValueOf(actualOpt).Call(actualValues) + + for i := 0; i < ot.NumIn(); i++ { + if !assert.ObjectsAreEqual(expectedValues[i].Interface(), actualValues[i].Interface()) { + expectedFmt = fmt.Sprintf("%s %+v", expectedNames[i], expectedValues[i].Interface()) + actualFmt = fmt.Sprintf("%s %+v", expectedNames[i], actualValues[i].Interface()) + return + } + } + } + + return "", "" +} + +func funcName(opt interface{}) string { + n := runtime.FuncForPC(reflect.ValueOf(opt).Pointer()).Name() + return strings.TrimSuffix(path.Base(n), path.Ext(n)) +} diff --git a/vendor/github.com/stretchr/testify/require/doc.go b/vendor/github.com/stretchr/testify/require/doc.go index 169de39221c..96843472455 100644 --- a/vendor/github.com/stretchr/testify/require/doc.go +++ b/vendor/github.com/stretchr/testify/require/doc.go @@ -1,24 +1,25 @@ // Package require implements the same assertions as the `assert` package but // stops test execution when a test fails. // -// Example Usage +// # Example Usage // // The following is a complete example using require in a standard test function: -// import ( -// "testing" -// "github.com/stretchr/testify/require" -// ) // -// func TestSomething(t *testing.T) { +// import ( +// "testing" +// "github.com/stretchr/testify/require" +// ) // -// var a string = "Hello" -// var b string = "Hello" +// func TestSomething(t *testing.T) { // -// require.Equal(t, a, b, "The two words should be the same.") +// var a string = "Hello" +// var b string = "Hello" // -// } +// require.Equal(t, a, b, "The two words should be the same.") // -// Assertions +// } +// +// # Assertions // // The `require` package have same global functions as in the `assert` package, // but instead of returning a boolean result they call `t.FailNow()`. diff --git a/vendor/github.com/stretchr/testify/require/require.go b/vendor/github.com/stretchr/testify/require/require.go index 880853f5a2c..63f85214767 100644 --- a/vendor/github.com/stretchr/testify/require/require.go +++ b/vendor/github.com/stretchr/testify/require/require.go @@ -37,9 +37,9 @@ func Conditionf(t TestingT, comp assert.Comparison, msg string, args ...interfac // Contains asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // -// assert.Contains(t, "Hello World", "World") -// assert.Contains(t, ["Hello", "World"], "World") -// assert.Contains(t, {"Hello": "World"}, "Hello") +// assert.Contains(t, "Hello World", "World") +// assert.Contains(t, ["Hello", "World"], "World") +// assert.Contains(t, {"Hello": "World"}, "Hello") func Contains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -53,9 +53,9 @@ func Contains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...int // Containsf asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // -// assert.Containsf(t, "Hello World", "World", "error message %s", "formatted") -// assert.Containsf(t, ["Hello", "World"], "World", "error message %s", "formatted") -// assert.Containsf(t, {"Hello": "World"}, "Hello", "error message %s", "formatted") +// assert.Containsf(t, "Hello World", "World", "error message %s", "formatted") +// assert.Containsf(t, ["Hello", "World"], "World", "error message %s", "formatted") +// assert.Containsf(t, {"Hello": "World"}, "Hello", "error message %s", "formatted") func Containsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -123,7 +123,7 @@ func ElementsMatchf(t TestingT, listA interface{}, listB interface{}, msg string // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // -// assert.Empty(t, obj) +// assert.Empty(t, obj) func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -137,7 +137,7 @@ func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) { // Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // -// assert.Emptyf(t, obj, "error message %s", "formatted") +// assert.Emptyf(t, obj, "error message %s", "formatted") func Emptyf(t TestingT, object interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -150,7 +150,7 @@ func Emptyf(t TestingT, object interface{}, msg string, args ...interface{}) { // Equal asserts that two objects are equal. // -// assert.Equal(t, 123, 123) +// assert.Equal(t, 123, 123) // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality @@ -168,8 +168,8 @@ func Equal(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...i // EqualError asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // -// actualObj, err := SomeFunction() -// assert.EqualError(t, err, expectedErrorString) +// actualObj, err := SomeFunction() +// assert.EqualError(t, err, expectedErrorString) func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -183,8 +183,8 @@ func EqualError(t TestingT, theError error, errString string, msgAndArgs ...inte // EqualErrorf asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // -// actualObj, err := SomeFunction() -// assert.EqualErrorf(t, err, expectedErrorString, "error message %s", "formatted") +// actualObj, err := SomeFunction() +// assert.EqualErrorf(t, err, expectedErrorString, "error message %s", "formatted") func EqualErrorf(t TestingT, theError error, errString string, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -195,10 +195,50 @@ func EqualErrorf(t TestingT, theError error, errString string, msg string, args t.FailNow() } +// EqualExportedValues asserts that the types of two objects are equal and their public +// fields are also equal. This is useful for comparing structs that have private fields +// that could potentially differ. +// +// type S struct { +// Exported int +// notExported int +// } +// assert.EqualExportedValues(t, S{1, 2}, S{1, 3}) => true +// assert.EqualExportedValues(t, S{1, 2}, S{2, 3}) => false +func EqualExportedValues(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.EqualExportedValues(t, expected, actual, msgAndArgs...) { + return + } + t.FailNow() +} + +// EqualExportedValuesf asserts that the types of two objects are equal and their public +// fields are also equal. This is useful for comparing structs that have private fields +// that could potentially differ. +// +// type S struct { +// Exported int +// notExported int +// } +// assert.EqualExportedValuesf(t, S{1, 2}, S{1, 3}, "error message %s", "formatted") => true +// assert.EqualExportedValuesf(t, S{1, 2}, S{2, 3}, "error message %s", "formatted") => false +func EqualExportedValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.EqualExportedValuesf(t, expected, actual, msg, args...) { + return + } + t.FailNow() +} + // EqualValues asserts that two objects are equal or convertable to the same types // and equal. // -// assert.EqualValues(t, uint32(123), int32(123)) +// assert.EqualValues(t, uint32(123), int32(123)) func EqualValues(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -212,7 +252,7 @@ func EqualValues(t TestingT, expected interface{}, actual interface{}, msgAndArg // EqualValuesf asserts that two objects are equal or convertable to the same types // and equal. // -// assert.EqualValuesf(t, uint32(123), int32(123), "error message %s", "formatted") +// assert.EqualValuesf(t, uint32(123), int32(123), "error message %s", "formatted") func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -225,7 +265,7 @@ func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg stri // Equalf asserts that two objects are equal. // -// assert.Equalf(t, 123, 123, "error message %s", "formatted") +// assert.Equalf(t, 123, 123, "error message %s", "formatted") // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality @@ -242,10 +282,10 @@ func Equalf(t TestingT, expected interface{}, actual interface{}, msg string, ar // Error asserts that a function returned an error (i.e. not `nil`). // -// actualObj, err := SomeFunction() -// if assert.Error(t, err) { -// assert.Equal(t, expectedError, err) -// } +// actualObj, err := SomeFunction() +// if assert.Error(t, err) { +// assert.Equal(t, expectedError, err) +// } func Error(t TestingT, err error, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -283,8 +323,8 @@ func ErrorAsf(t TestingT, err error, target interface{}, msg string, args ...int // ErrorContains asserts that a function returned an error (i.e. not `nil`) // and that the error contains the specified substring. // -// actualObj, err := SomeFunction() -// assert.ErrorContains(t, err, expectedErrorSubString) +// actualObj, err := SomeFunction() +// assert.ErrorContains(t, err, expectedErrorSubString) func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -298,8 +338,8 @@ func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...in // ErrorContainsf asserts that a function returned an error (i.e. not `nil`) // and that the error contains the specified substring. // -// actualObj, err := SomeFunction() -// assert.ErrorContainsf(t, err, expectedErrorSubString, "error message %s", "formatted") +// actualObj, err := SomeFunction() +// assert.ErrorContainsf(t, err, expectedErrorSubString, "error message %s", "formatted") func ErrorContainsf(t TestingT, theError error, contains string, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -336,10 +376,10 @@ func ErrorIsf(t TestingT, err error, target error, msg string, args ...interface // Errorf asserts that a function returned an error (i.e. not `nil`). // -// actualObj, err := SomeFunction() -// if assert.Errorf(t, err, "error message %s", "formatted") { -// assert.Equal(t, expectedErrorf, err) -// } +// actualObj, err := SomeFunction() +// if assert.Errorf(t, err, "error message %s", "formatted") { +// assert.Equal(t, expectedErrorf, err) +// } func Errorf(t TestingT, err error, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -353,7 +393,7 @@ func Errorf(t TestingT, err error, msg string, args ...interface{}) { // Eventually asserts that given condition will be met in waitFor time, // periodically checking target function each tick. // -// assert.Eventually(t, func() bool { return true; }, time.Second, 10*time.Millisecond) +// assert.Eventually(t, func() bool { return true; }, time.Second, 10*time.Millisecond) func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -364,10 +404,66 @@ func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick t t.FailNow() } +// EventuallyWithT asserts that given condition will be met in waitFor time, +// periodically checking target function each tick. In contrast to Eventually, +// it supplies a CollectT to the condition function, so that the condition +// function can use the CollectT to call other assertions. +// The condition is considered "met" if no errors are raised in a tick. +// The supplied CollectT collects all errors from one tick (if there are any). +// If the condition is not met before waitFor, the collected errors of +// the last tick are copied to t. +// +// externalValue := false +// go func() { +// time.Sleep(8*time.Second) +// externalValue = true +// }() +// assert.EventuallyWithT(t, func(c *assert.CollectT) { +// // add assertions as needed; any assertion failure will fail the current tick +// assert.True(c, externalValue, "expected 'externalValue' to be true") +// }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false") +func EventuallyWithT(t TestingT, condition func(collect *assert.CollectT), waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.EventuallyWithT(t, condition, waitFor, tick, msgAndArgs...) { + return + } + t.FailNow() +} + +// EventuallyWithTf asserts that given condition will be met in waitFor time, +// periodically checking target function each tick. In contrast to Eventually, +// it supplies a CollectT to the condition function, so that the condition +// function can use the CollectT to call other assertions. +// The condition is considered "met" if no errors are raised in a tick. +// The supplied CollectT collects all errors from one tick (if there are any). +// If the condition is not met before waitFor, the collected errors of +// the last tick are copied to t. +// +// externalValue := false +// go func() { +// time.Sleep(8*time.Second) +// externalValue = true +// }() +// assert.EventuallyWithTf(t, func(c *assert.CollectT, "error message %s", "formatted") { +// // add assertions as needed; any assertion failure will fail the current tick +// assert.True(c, externalValue, "expected 'externalValue' to be true") +// }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false") +func EventuallyWithTf(t TestingT, condition func(collect *assert.CollectT), waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) { + if h, ok := t.(tHelper); ok { + h.Helper() + } + if assert.EventuallyWithTf(t, condition, waitFor, tick, msg, args...) { + return + } + t.FailNow() +} + // Eventuallyf asserts that given condition will be met in waitFor time, // periodically checking target function each tick. // -// assert.Eventuallyf(t, func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") +// assert.Eventuallyf(t, func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") func Eventuallyf(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -380,7 +476,7 @@ func Eventuallyf(t TestingT, condition func() bool, waitFor time.Duration, tick // Exactly asserts that two objects are equal in value and type. // -// assert.Exactly(t, int32(123), int64(123)) +// assert.Exactly(t, int32(123), int64(123)) func Exactly(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -393,7 +489,7 @@ func Exactly(t TestingT, expected interface{}, actual interface{}, msgAndArgs .. // Exactlyf asserts that two objects are equal in value and type. // -// assert.Exactlyf(t, int32(123), int64(123), "error message %s", "formatted") +// assert.Exactlyf(t, int32(123), int64(123), "error message %s", "formatted") func Exactlyf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -450,7 +546,7 @@ func Failf(t TestingT, failureMessage string, msg string, args ...interface{}) { // False asserts that the specified value is false. // -// assert.False(t, myBool) +// assert.False(t, myBool) func False(t TestingT, value bool, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -463,7 +559,7 @@ func False(t TestingT, value bool, msgAndArgs ...interface{}) { // Falsef asserts that the specified value is false. // -// assert.Falsef(t, myBool, "error message %s", "formatted") +// assert.Falsef(t, myBool, "error message %s", "formatted") func Falsef(t TestingT, value bool, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -500,9 +596,9 @@ func FileExistsf(t TestingT, path string, msg string, args ...interface{}) { // Greater asserts that the first element is greater than the second // -// assert.Greater(t, 2, 1) -// assert.Greater(t, float64(2), float64(1)) -// assert.Greater(t, "b", "a") +// assert.Greater(t, 2, 1) +// assert.Greater(t, float64(2), float64(1)) +// assert.Greater(t, "b", "a") func Greater(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -515,10 +611,10 @@ func Greater(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface // GreaterOrEqual asserts that the first element is greater than or equal to the second // -// assert.GreaterOrEqual(t, 2, 1) -// assert.GreaterOrEqual(t, 2, 2) -// assert.GreaterOrEqual(t, "b", "a") -// assert.GreaterOrEqual(t, "b", "b") +// assert.GreaterOrEqual(t, 2, 1) +// assert.GreaterOrEqual(t, 2, 2) +// assert.GreaterOrEqual(t, "b", "a") +// assert.GreaterOrEqual(t, "b", "b") func GreaterOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -531,10 +627,10 @@ func GreaterOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...in // GreaterOrEqualf asserts that the first element is greater than or equal to the second // -// assert.GreaterOrEqualf(t, 2, 1, "error message %s", "formatted") -// assert.GreaterOrEqualf(t, 2, 2, "error message %s", "formatted") -// assert.GreaterOrEqualf(t, "b", "a", "error message %s", "formatted") -// assert.GreaterOrEqualf(t, "b", "b", "error message %s", "formatted") +// assert.GreaterOrEqualf(t, 2, 1, "error message %s", "formatted") +// assert.GreaterOrEqualf(t, 2, 2, "error message %s", "formatted") +// assert.GreaterOrEqualf(t, "b", "a", "error message %s", "formatted") +// assert.GreaterOrEqualf(t, "b", "b", "error message %s", "formatted") func GreaterOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -547,9 +643,9 @@ func GreaterOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, arg // Greaterf asserts that the first element is greater than the second // -// assert.Greaterf(t, 2, 1, "error message %s", "formatted") -// assert.Greaterf(t, float64(2), float64(1), "error message %s", "formatted") -// assert.Greaterf(t, "b", "a", "error message %s", "formatted") +// assert.Greaterf(t, 2, 1, "error message %s", "formatted") +// assert.Greaterf(t, float64(2), float64(1), "error message %s", "formatted") +// assert.Greaterf(t, "b", "a", "error message %s", "formatted") func Greaterf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -563,7 +659,7 @@ func Greaterf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...in // HTTPBodyContains asserts that a specified handler returns a // body that contains a string. // -// assert.HTTPBodyContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") +// assert.HTTPBodyContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) { @@ -579,7 +675,7 @@ func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method string, url s // HTTPBodyContainsf asserts that a specified handler returns a // body that contains a string. // -// assert.HTTPBodyContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// assert.HTTPBodyContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) { @@ -595,7 +691,7 @@ func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url // HTTPBodyNotContains asserts that a specified handler returns a // body that does not contain a string. // -// assert.HTTPBodyNotContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") +// assert.HTTPBodyNotContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) { @@ -611,7 +707,7 @@ func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method string, ur // HTTPBodyNotContainsf asserts that a specified handler returns a // body that does not contain a string. // -// assert.HTTPBodyNotContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// assert.HTTPBodyNotContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) { @@ -626,7 +722,7 @@ func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, u // HTTPError asserts that a specified handler returns an error status code. // -// assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPError(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { @@ -641,7 +737,7 @@ func HTTPError(t TestingT, handler http.HandlerFunc, method string, url string, // HTTPErrorf asserts that a specified handler returns an error status code. // -// assert.HTTPErrorf(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// assert.HTTPErrorf(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { @@ -656,7 +752,7 @@ func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, // HTTPRedirect asserts that a specified handler returns a redirect status code. // -// assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPRedirect(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { @@ -671,7 +767,7 @@ func HTTPRedirect(t TestingT, handler http.HandlerFunc, method string, url strin // HTTPRedirectf asserts that a specified handler returns a redirect status code. // -// assert.HTTPRedirectf(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// assert.HTTPRedirectf(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { @@ -686,7 +782,7 @@ func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url stri // HTTPStatusCode asserts that a specified handler returns a specified status code. // -// assert.HTTPStatusCode(t, myHandler, "GET", "/notImplemented", nil, 501) +// assert.HTTPStatusCode(t, myHandler, "GET", "/notImplemented", nil, 501) // // Returns whether the assertion was successful (true) or not (false). func HTTPStatusCode(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msgAndArgs ...interface{}) { @@ -701,7 +797,7 @@ func HTTPStatusCode(t TestingT, handler http.HandlerFunc, method string, url str // HTTPStatusCodef asserts that a specified handler returns a specified status code. // -// assert.HTTPStatusCodef(t, myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted") +// assert.HTTPStatusCodef(t, myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPStatusCodef(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msg string, args ...interface{}) { @@ -716,7 +812,7 @@ func HTTPStatusCodef(t TestingT, handler http.HandlerFunc, method string, url st // HTTPSuccess asserts that a specified handler returns a success status code. // -// assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) +// assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) // // Returns whether the assertion was successful (true) or not (false). func HTTPSuccess(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { @@ -731,7 +827,7 @@ func HTTPSuccess(t TestingT, handler http.HandlerFunc, method string, url string // HTTPSuccessf asserts that a specified handler returns a success status code. // -// assert.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") +// assert.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { @@ -746,7 +842,7 @@ func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url strin // Implements asserts that an object is implemented by the specified interface. // -// assert.Implements(t, (*MyInterface)(nil), new(MyObject)) +// assert.Implements(t, (*MyInterface)(nil), new(MyObject)) func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -759,7 +855,7 @@ func Implements(t TestingT, interfaceObject interface{}, object interface{}, msg // Implementsf asserts that an object is implemented by the specified interface. // -// assert.Implementsf(t, (*MyInterface)(nil), new(MyObject), "error message %s", "formatted") +// assert.Implementsf(t, (*MyInterface)(nil), new(MyObject), "error message %s", "formatted") func Implementsf(t TestingT, interfaceObject interface{}, object interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -772,7 +868,7 @@ func Implementsf(t TestingT, interfaceObject interface{}, object interface{}, ms // InDelta asserts that the two numerals are within delta of each other. // -// assert.InDelta(t, math.Pi, 22/7.0, 0.01) +// assert.InDelta(t, math.Pi, 22/7.0, 0.01) func InDelta(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -829,7 +925,7 @@ func InDeltaSlicef(t TestingT, expected interface{}, actual interface{}, delta f // InDeltaf asserts that the two numerals are within delta of each other. // -// assert.InDeltaf(t, math.Pi, 22/7.0, 0.01, "error message %s", "formatted") +// assert.InDeltaf(t, math.Pi, 22/7.0, 0.01, "error message %s", "formatted") func InDeltaf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -886,9 +982,9 @@ func InEpsilonf(t TestingT, expected interface{}, actual interface{}, epsilon fl // IsDecreasing asserts that the collection is decreasing // -// assert.IsDecreasing(t, []int{2, 1, 0}) -// assert.IsDecreasing(t, []float{2, 1}) -// assert.IsDecreasing(t, []string{"b", "a"}) +// assert.IsDecreasing(t, []int{2, 1, 0}) +// assert.IsDecreasing(t, []float{2, 1}) +// assert.IsDecreasing(t, []string{"b", "a"}) func IsDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -901,9 +997,9 @@ func IsDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) { // IsDecreasingf asserts that the collection is decreasing // -// assert.IsDecreasingf(t, []int{2, 1, 0}, "error message %s", "formatted") -// assert.IsDecreasingf(t, []float{2, 1}, "error message %s", "formatted") -// assert.IsDecreasingf(t, []string{"b", "a"}, "error message %s", "formatted") +// assert.IsDecreasingf(t, []int{2, 1, 0}, "error message %s", "formatted") +// assert.IsDecreasingf(t, []float{2, 1}, "error message %s", "formatted") +// assert.IsDecreasingf(t, []string{"b", "a"}, "error message %s", "formatted") func IsDecreasingf(t TestingT, object interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -916,9 +1012,9 @@ func IsDecreasingf(t TestingT, object interface{}, msg string, args ...interface // IsIncreasing asserts that the collection is increasing // -// assert.IsIncreasing(t, []int{1, 2, 3}) -// assert.IsIncreasing(t, []float{1, 2}) -// assert.IsIncreasing(t, []string{"a", "b"}) +// assert.IsIncreasing(t, []int{1, 2, 3}) +// assert.IsIncreasing(t, []float{1, 2}) +// assert.IsIncreasing(t, []string{"a", "b"}) func IsIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -931,9 +1027,9 @@ func IsIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) { // IsIncreasingf asserts that the collection is increasing // -// assert.IsIncreasingf(t, []int{1, 2, 3}, "error message %s", "formatted") -// assert.IsIncreasingf(t, []float{1, 2}, "error message %s", "formatted") -// assert.IsIncreasingf(t, []string{"a", "b"}, "error message %s", "formatted") +// assert.IsIncreasingf(t, []int{1, 2, 3}, "error message %s", "formatted") +// assert.IsIncreasingf(t, []float{1, 2}, "error message %s", "formatted") +// assert.IsIncreasingf(t, []string{"a", "b"}, "error message %s", "formatted") func IsIncreasingf(t TestingT, object interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -946,9 +1042,9 @@ func IsIncreasingf(t TestingT, object interface{}, msg string, args ...interface // IsNonDecreasing asserts that the collection is not decreasing // -// assert.IsNonDecreasing(t, []int{1, 1, 2}) -// assert.IsNonDecreasing(t, []float{1, 2}) -// assert.IsNonDecreasing(t, []string{"a", "b"}) +// assert.IsNonDecreasing(t, []int{1, 1, 2}) +// assert.IsNonDecreasing(t, []float{1, 2}) +// assert.IsNonDecreasing(t, []string{"a", "b"}) func IsNonDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -961,9 +1057,9 @@ func IsNonDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) // IsNonDecreasingf asserts that the collection is not decreasing // -// assert.IsNonDecreasingf(t, []int{1, 1, 2}, "error message %s", "formatted") -// assert.IsNonDecreasingf(t, []float{1, 2}, "error message %s", "formatted") -// assert.IsNonDecreasingf(t, []string{"a", "b"}, "error message %s", "formatted") +// assert.IsNonDecreasingf(t, []int{1, 1, 2}, "error message %s", "formatted") +// assert.IsNonDecreasingf(t, []float{1, 2}, "error message %s", "formatted") +// assert.IsNonDecreasingf(t, []string{"a", "b"}, "error message %s", "formatted") func IsNonDecreasingf(t TestingT, object interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -976,9 +1072,9 @@ func IsNonDecreasingf(t TestingT, object interface{}, msg string, args ...interf // IsNonIncreasing asserts that the collection is not increasing // -// assert.IsNonIncreasing(t, []int{2, 1, 1}) -// assert.IsNonIncreasing(t, []float{2, 1}) -// assert.IsNonIncreasing(t, []string{"b", "a"}) +// assert.IsNonIncreasing(t, []int{2, 1, 1}) +// assert.IsNonIncreasing(t, []float{2, 1}) +// assert.IsNonIncreasing(t, []string{"b", "a"}) func IsNonIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -991,9 +1087,9 @@ func IsNonIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) // IsNonIncreasingf asserts that the collection is not increasing // -// assert.IsNonIncreasingf(t, []int{2, 1, 1}, "error message %s", "formatted") -// assert.IsNonIncreasingf(t, []float{2, 1}, "error message %s", "formatted") -// assert.IsNonIncreasingf(t, []string{"b", "a"}, "error message %s", "formatted") +// assert.IsNonIncreasingf(t, []int{2, 1, 1}, "error message %s", "formatted") +// assert.IsNonIncreasingf(t, []float{2, 1}, "error message %s", "formatted") +// assert.IsNonIncreasingf(t, []string{"b", "a"}, "error message %s", "formatted") func IsNonIncreasingf(t TestingT, object interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1028,7 +1124,7 @@ func IsTypef(t TestingT, expectedType interface{}, object interface{}, msg strin // JSONEq asserts that two JSON strings are equivalent. // -// assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) +// assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1041,7 +1137,7 @@ func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{ // JSONEqf asserts that two JSON strings are equivalent. // -// assert.JSONEqf(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") +// assert.JSONEqf(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") func JSONEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1055,7 +1151,7 @@ func JSONEqf(t TestingT, expected string, actual string, msg string, args ...int // Len asserts that the specified object has specific length. // Len also fails if the object has a type that len() not accept. // -// assert.Len(t, mySlice, 3) +// assert.Len(t, mySlice, 3) func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1069,7 +1165,7 @@ func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) // Lenf asserts that the specified object has specific length. // Lenf also fails if the object has a type that len() not accept. // -// assert.Lenf(t, mySlice, 3, "error message %s", "formatted") +// assert.Lenf(t, mySlice, 3, "error message %s", "formatted") func Lenf(t TestingT, object interface{}, length int, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1082,9 +1178,9 @@ func Lenf(t TestingT, object interface{}, length int, msg string, args ...interf // Less asserts that the first element is less than the second // -// assert.Less(t, 1, 2) -// assert.Less(t, float64(1), float64(2)) -// assert.Less(t, "a", "b") +// assert.Less(t, 1, 2) +// assert.Less(t, float64(1), float64(2)) +// assert.Less(t, "a", "b") func Less(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1097,10 +1193,10 @@ func Less(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) // LessOrEqual asserts that the first element is less than or equal to the second // -// assert.LessOrEqual(t, 1, 2) -// assert.LessOrEqual(t, 2, 2) -// assert.LessOrEqual(t, "a", "b") -// assert.LessOrEqual(t, "b", "b") +// assert.LessOrEqual(t, 1, 2) +// assert.LessOrEqual(t, 2, 2) +// assert.LessOrEqual(t, "a", "b") +// assert.LessOrEqual(t, "b", "b") func LessOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1113,10 +1209,10 @@ func LessOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...inter // LessOrEqualf asserts that the first element is less than or equal to the second // -// assert.LessOrEqualf(t, 1, 2, "error message %s", "formatted") -// assert.LessOrEqualf(t, 2, 2, "error message %s", "formatted") -// assert.LessOrEqualf(t, "a", "b", "error message %s", "formatted") -// assert.LessOrEqualf(t, "b", "b", "error message %s", "formatted") +// assert.LessOrEqualf(t, 1, 2, "error message %s", "formatted") +// assert.LessOrEqualf(t, 2, 2, "error message %s", "formatted") +// assert.LessOrEqualf(t, "a", "b", "error message %s", "formatted") +// assert.LessOrEqualf(t, "b", "b", "error message %s", "formatted") func LessOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1129,9 +1225,9 @@ func LessOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, args . // Lessf asserts that the first element is less than the second // -// assert.Lessf(t, 1, 2, "error message %s", "formatted") -// assert.Lessf(t, float64(1), float64(2), "error message %s", "formatted") -// assert.Lessf(t, "a", "b", "error message %s", "formatted") +// assert.Lessf(t, 1, 2, "error message %s", "formatted") +// assert.Lessf(t, float64(1), float64(2), "error message %s", "formatted") +// assert.Lessf(t, "a", "b", "error message %s", "formatted") func Lessf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1144,8 +1240,8 @@ func Lessf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...inter // Negative asserts that the specified element is negative // -// assert.Negative(t, -1) -// assert.Negative(t, -1.23) +// assert.Negative(t, -1) +// assert.Negative(t, -1.23) func Negative(t TestingT, e interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1158,8 +1254,8 @@ func Negative(t TestingT, e interface{}, msgAndArgs ...interface{}) { // Negativef asserts that the specified element is negative // -// assert.Negativef(t, -1, "error message %s", "formatted") -// assert.Negativef(t, -1.23, "error message %s", "formatted") +// assert.Negativef(t, -1, "error message %s", "formatted") +// assert.Negativef(t, -1.23, "error message %s", "formatted") func Negativef(t TestingT, e interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1173,7 +1269,7 @@ func Negativef(t TestingT, e interface{}, msg string, args ...interface{}) { // Never asserts that the given condition doesn't satisfy in waitFor time, // periodically checking the target function each tick. // -// assert.Never(t, func() bool { return false; }, time.Second, 10*time.Millisecond) +// assert.Never(t, func() bool { return false; }, time.Second, 10*time.Millisecond) func Never(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1187,7 +1283,7 @@ func Never(t TestingT, condition func() bool, waitFor time.Duration, tick time.D // Neverf asserts that the given condition doesn't satisfy in waitFor time, // periodically checking the target function each tick. // -// assert.Neverf(t, func() bool { return false; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") +// assert.Neverf(t, func() bool { return false; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") func Neverf(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1200,7 +1296,7 @@ func Neverf(t TestingT, condition func() bool, waitFor time.Duration, tick time. // Nil asserts that the specified object is nil. // -// assert.Nil(t, err) +// assert.Nil(t, err) func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1213,7 +1309,7 @@ func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) { // Nilf asserts that the specified object is nil. // -// assert.Nilf(t, err, "error message %s", "formatted") +// assert.Nilf(t, err, "error message %s", "formatted") func Nilf(t TestingT, object interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1250,10 +1346,10 @@ func NoDirExistsf(t TestingT, path string, msg string, args ...interface{}) { // NoError asserts that a function returned no error (i.e. `nil`). // -// actualObj, err := SomeFunction() -// if assert.NoError(t, err) { -// assert.Equal(t, expectedObj, actualObj) -// } +// actualObj, err := SomeFunction() +// if assert.NoError(t, err) { +// assert.Equal(t, expectedObj, actualObj) +// } func NoError(t TestingT, err error, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1266,10 +1362,10 @@ func NoError(t TestingT, err error, msgAndArgs ...interface{}) { // NoErrorf asserts that a function returned no error (i.e. `nil`). // -// actualObj, err := SomeFunction() -// if assert.NoErrorf(t, err, "error message %s", "formatted") { -// assert.Equal(t, expectedObj, actualObj) -// } +// actualObj, err := SomeFunction() +// if assert.NoErrorf(t, err, "error message %s", "formatted") { +// assert.Equal(t, expectedObj, actualObj) +// } func NoErrorf(t TestingT, err error, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1307,9 +1403,9 @@ func NoFileExistsf(t TestingT, path string, msg string, args ...interface{}) { // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // -// assert.NotContains(t, "Hello World", "Earth") -// assert.NotContains(t, ["Hello", "World"], "Earth") -// assert.NotContains(t, {"Hello": "World"}, "Earth") +// assert.NotContains(t, "Hello World", "Earth") +// assert.NotContains(t, ["Hello", "World"], "Earth") +// assert.NotContains(t, {"Hello": "World"}, "Earth") func NotContains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1323,9 +1419,9 @@ func NotContains(t TestingT, s interface{}, contains interface{}, msgAndArgs ... // NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // -// assert.NotContainsf(t, "Hello World", "Earth", "error message %s", "formatted") -// assert.NotContainsf(t, ["Hello", "World"], "Earth", "error message %s", "formatted") -// assert.NotContainsf(t, {"Hello": "World"}, "Earth", "error message %s", "formatted") +// assert.NotContainsf(t, "Hello World", "Earth", "error message %s", "formatted") +// assert.NotContainsf(t, ["Hello", "World"], "Earth", "error message %s", "formatted") +// assert.NotContainsf(t, {"Hello": "World"}, "Earth", "error message %s", "formatted") func NotContainsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1339,9 +1435,9 @@ func NotContainsf(t TestingT, s interface{}, contains interface{}, msg string, a // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // -// if assert.NotEmpty(t, obj) { -// assert.Equal(t, "two", obj[1]) -// } +// if assert.NotEmpty(t, obj) { +// assert.Equal(t, "two", obj[1]) +// } func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1355,9 +1451,9 @@ func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) { // NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // -// if assert.NotEmptyf(t, obj, "error message %s", "formatted") { -// assert.Equal(t, "two", obj[1]) -// } +// if assert.NotEmptyf(t, obj, "error message %s", "formatted") { +// assert.Equal(t, "two", obj[1]) +// } func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1370,7 +1466,7 @@ func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{}) // NotEqual asserts that the specified values are NOT equal. // -// assert.NotEqual(t, obj1, obj2) +// assert.NotEqual(t, obj1, obj2) // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). @@ -1386,7 +1482,7 @@ func NotEqual(t TestingT, expected interface{}, actual interface{}, msgAndArgs . // NotEqualValues asserts that two objects are not equal even when converted to the same type // -// assert.NotEqualValues(t, obj1, obj2) +// assert.NotEqualValues(t, obj1, obj2) func NotEqualValues(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1399,7 +1495,7 @@ func NotEqualValues(t TestingT, expected interface{}, actual interface{}, msgAnd // NotEqualValuesf asserts that two objects are not equal even when converted to the same type // -// assert.NotEqualValuesf(t, obj1, obj2, "error message %s", "formatted") +// assert.NotEqualValuesf(t, obj1, obj2, "error message %s", "formatted") func NotEqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1412,7 +1508,7 @@ func NotEqualValuesf(t TestingT, expected interface{}, actual interface{}, msg s // NotEqualf asserts that the specified values are NOT equal. // -// assert.NotEqualf(t, obj1, obj2, "error message %s", "formatted") +// assert.NotEqualf(t, obj1, obj2, "error message %s", "formatted") // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). @@ -1452,7 +1548,7 @@ func NotErrorIsf(t TestingT, err error, target error, msg string, args ...interf // NotNil asserts that the specified object is not nil. // -// assert.NotNil(t, err) +// assert.NotNil(t, err) func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1465,7 +1561,7 @@ func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) { // NotNilf asserts that the specified object is not nil. // -// assert.NotNilf(t, err, "error message %s", "formatted") +// assert.NotNilf(t, err, "error message %s", "formatted") func NotNilf(t TestingT, object interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1478,7 +1574,7 @@ func NotNilf(t TestingT, object interface{}, msg string, args ...interface{}) { // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. // -// assert.NotPanics(t, func(){ RemainCalm() }) +// assert.NotPanics(t, func(){ RemainCalm() }) func NotPanics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1491,7 +1587,7 @@ func NotPanics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { // NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. // -// assert.NotPanicsf(t, func(){ RemainCalm() }, "error message %s", "formatted") +// assert.NotPanicsf(t, func(){ RemainCalm() }, "error message %s", "formatted") func NotPanicsf(t TestingT, f assert.PanicTestFunc, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1504,8 +1600,8 @@ func NotPanicsf(t TestingT, f assert.PanicTestFunc, msg string, args ...interfac // NotRegexp asserts that a specified regexp does not match a string. // -// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") -// assert.NotRegexp(t, "^start", "it's not starting") +// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") +// assert.NotRegexp(t, "^start", "it's not starting") func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1518,8 +1614,8 @@ func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interf // NotRegexpf asserts that a specified regexp does not match a string. // -// assert.NotRegexpf(t, regexp.MustCompile("starts"), "it's starting", "error message %s", "formatted") -// assert.NotRegexpf(t, "^start", "it's not starting", "error message %s", "formatted") +// assert.NotRegexpf(t, regexp.MustCompile("starts"), "it's starting", "error message %s", "formatted") +// assert.NotRegexpf(t, "^start", "it's not starting", "error message %s", "formatted") func NotRegexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1532,7 +1628,7 @@ func NotRegexpf(t TestingT, rx interface{}, str interface{}, msg string, args .. // NotSame asserts that two pointers do not reference the same object. // -// assert.NotSame(t, ptr1, ptr2) +// assert.NotSame(t, ptr1, ptr2) // // Both arguments must be pointer variables. Pointer variable sameness is // determined based on the equality of both type and value. @@ -1548,7 +1644,7 @@ func NotSame(t TestingT, expected interface{}, actual interface{}, msgAndArgs .. // NotSamef asserts that two pointers do not reference the same object. // -// assert.NotSamef(t, ptr1, ptr2, "error message %s", "formatted") +// assert.NotSamef(t, ptr1, ptr2, "error message %s", "formatted") // // Both arguments must be pointer variables. Pointer variable sameness is // determined based on the equality of both type and value. @@ -1565,7 +1661,7 @@ func NotSamef(t TestingT, expected interface{}, actual interface{}, msg string, // NotSubset asserts that the specified list(array, slice...) contains not all // elements given in the specified subset(array, slice...). // -// assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") +// assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") func NotSubset(t TestingT, list interface{}, subset interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1579,7 +1675,7 @@ func NotSubset(t TestingT, list interface{}, subset interface{}, msgAndArgs ...i // NotSubsetf asserts that the specified list(array, slice...) contains not all // elements given in the specified subset(array, slice...). // -// assert.NotSubsetf(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") +// assert.NotSubsetf(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") func NotSubsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1614,7 +1710,7 @@ func NotZerof(t TestingT, i interface{}, msg string, args ...interface{}) { // Panics asserts that the code inside the specified PanicTestFunc panics. // -// assert.Panics(t, func(){ GoCrazy() }) +// assert.Panics(t, func(){ GoCrazy() }) func Panics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1629,7 +1725,7 @@ func Panics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { // panics, and that the recovered panic value is an error that satisfies the // EqualError comparison. // -// assert.PanicsWithError(t, "crazy error", func(){ GoCrazy() }) +// assert.PanicsWithError(t, "crazy error", func(){ GoCrazy() }) func PanicsWithError(t TestingT, errString string, f assert.PanicTestFunc, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1644,7 +1740,7 @@ func PanicsWithError(t TestingT, errString string, f assert.PanicTestFunc, msgAn // panics, and that the recovered panic value is an error that satisfies the // EqualError comparison. // -// assert.PanicsWithErrorf(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") +// assert.PanicsWithErrorf(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") func PanicsWithErrorf(t TestingT, errString string, f assert.PanicTestFunc, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1658,7 +1754,7 @@ func PanicsWithErrorf(t TestingT, errString string, f assert.PanicTestFunc, msg // PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // -// assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() }) +// assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() }) func PanicsWithValue(t TestingT, expected interface{}, f assert.PanicTestFunc, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1672,7 +1768,7 @@ func PanicsWithValue(t TestingT, expected interface{}, f assert.PanicTestFunc, m // PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // -// assert.PanicsWithValuef(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") +// assert.PanicsWithValuef(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") func PanicsWithValuef(t TestingT, expected interface{}, f assert.PanicTestFunc, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1685,7 +1781,7 @@ func PanicsWithValuef(t TestingT, expected interface{}, f assert.PanicTestFunc, // Panicsf asserts that the code inside the specified PanicTestFunc panics. // -// assert.Panicsf(t, func(){ GoCrazy() }, "error message %s", "formatted") +// assert.Panicsf(t, func(){ GoCrazy() }, "error message %s", "formatted") func Panicsf(t TestingT, f assert.PanicTestFunc, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1698,8 +1794,8 @@ func Panicsf(t TestingT, f assert.PanicTestFunc, msg string, args ...interface{} // Positive asserts that the specified element is positive // -// assert.Positive(t, 1) -// assert.Positive(t, 1.23) +// assert.Positive(t, 1) +// assert.Positive(t, 1.23) func Positive(t TestingT, e interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1712,8 +1808,8 @@ func Positive(t TestingT, e interface{}, msgAndArgs ...interface{}) { // Positivef asserts that the specified element is positive // -// assert.Positivef(t, 1, "error message %s", "formatted") -// assert.Positivef(t, 1.23, "error message %s", "formatted") +// assert.Positivef(t, 1, "error message %s", "formatted") +// assert.Positivef(t, 1.23, "error message %s", "formatted") func Positivef(t TestingT, e interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1726,8 +1822,8 @@ func Positivef(t TestingT, e interface{}, msg string, args ...interface{}) { // Regexp asserts that a specified regexp matches a string. // -// assert.Regexp(t, regexp.MustCompile("start"), "it's starting") -// assert.Regexp(t, "start...$", "it's not starting") +// assert.Regexp(t, regexp.MustCompile("start"), "it's starting") +// assert.Regexp(t, "start...$", "it's not starting") func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1740,8 +1836,8 @@ func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface // Regexpf asserts that a specified regexp matches a string. // -// assert.Regexpf(t, regexp.MustCompile("start"), "it's starting", "error message %s", "formatted") -// assert.Regexpf(t, "start...$", "it's not starting", "error message %s", "formatted") +// assert.Regexpf(t, regexp.MustCompile("start"), "it's starting", "error message %s", "formatted") +// assert.Regexpf(t, "start...$", "it's not starting", "error message %s", "formatted") func Regexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1754,7 +1850,7 @@ func Regexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...in // Same asserts that two pointers reference the same object. // -// assert.Same(t, ptr1, ptr2) +// assert.Same(t, ptr1, ptr2) // // Both arguments must be pointer variables. Pointer variable sameness is // determined based on the equality of both type and value. @@ -1770,7 +1866,7 @@ func Same(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...in // Samef asserts that two pointers reference the same object. // -// assert.Samef(t, ptr1, ptr2, "error message %s", "formatted") +// assert.Samef(t, ptr1, ptr2, "error message %s", "formatted") // // Both arguments must be pointer variables. Pointer variable sameness is // determined based on the equality of both type and value. @@ -1787,7 +1883,7 @@ func Samef(t TestingT, expected interface{}, actual interface{}, msg string, arg // Subset asserts that the specified list(array, slice...) contains all // elements given in the specified subset(array, slice...). // -// assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") +// assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") func Subset(t TestingT, list interface{}, subset interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1801,7 +1897,7 @@ func Subset(t TestingT, list interface{}, subset interface{}, msgAndArgs ...inte // Subsetf asserts that the specified list(array, slice...) contains all // elements given in the specified subset(array, slice...). // -// assert.Subsetf(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") +// assert.Subsetf(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1814,7 +1910,7 @@ func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args // True asserts that the specified value is true. // -// assert.True(t, myBool) +// assert.True(t, myBool) func True(t TestingT, value bool, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1827,7 +1923,7 @@ func True(t TestingT, value bool, msgAndArgs ...interface{}) { // Truef asserts that the specified value is true. // -// assert.Truef(t, myBool, "error message %s", "formatted") +// assert.Truef(t, myBool, "error message %s", "formatted") func Truef(t TestingT, value bool, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1840,7 +1936,7 @@ func Truef(t TestingT, value bool, msg string, args ...interface{}) { // WithinDuration asserts that the two times are within duration delta of each other. // -// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second) +// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second) func WithinDuration(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1853,7 +1949,7 @@ func WithinDuration(t TestingT, expected time.Time, actual time.Time, delta time // WithinDurationf asserts that the two times are within duration delta of each other. // -// assert.WithinDurationf(t, time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") +// assert.WithinDurationf(t, time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1866,7 +1962,7 @@ func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta tim // WithinRange asserts that a time is within a time range (inclusive). // -// assert.WithinRange(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second)) +// assert.WithinRange(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second)) func WithinRange(t TestingT, actual time.Time, start time.Time, end time.Time, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() @@ -1879,7 +1975,7 @@ func WithinRange(t TestingT, actual time.Time, start time.Time, end time.Time, m // WithinRangef asserts that a time is within a time range (inclusive). // -// assert.WithinRangef(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second), "error message %s", "formatted") +// assert.WithinRangef(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second), "error message %s", "formatted") func WithinRangef(t TestingT, actual time.Time, start time.Time, end time.Time, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() diff --git a/vendor/github.com/stretchr/testify/require/require_forward.go b/vendor/github.com/stretchr/testify/require/require_forward.go index 960bf6f2cab..3b5b09330a4 100644 --- a/vendor/github.com/stretchr/testify/require/require_forward.go +++ b/vendor/github.com/stretchr/testify/require/require_forward.go @@ -31,9 +31,9 @@ func (a *Assertions) Conditionf(comp assert.Comparison, msg string, args ...inte // Contains asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // -// a.Contains("Hello World", "World") -// a.Contains(["Hello", "World"], "World") -// a.Contains({"Hello": "World"}, "Hello") +// a.Contains("Hello World", "World") +// a.Contains(["Hello", "World"], "World") +// a.Contains({"Hello": "World"}, "Hello") func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -44,9 +44,9 @@ func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs .. // Containsf asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // -// a.Containsf("Hello World", "World", "error message %s", "formatted") -// a.Containsf(["Hello", "World"], "World", "error message %s", "formatted") -// a.Containsf({"Hello": "World"}, "Hello", "error message %s", "formatted") +// a.Containsf("Hello World", "World", "error message %s", "formatted") +// a.Containsf(["Hello", "World"], "World", "error message %s", "formatted") +// a.Containsf({"Hello": "World"}, "Hello", "error message %s", "formatted") func (a *Assertions) Containsf(s interface{}, contains interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -99,7 +99,7 @@ func (a *Assertions) ElementsMatchf(listA interface{}, listB interface{}, msg st // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // -// a.Empty(obj) +// a.Empty(obj) func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -110,7 +110,7 @@ func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) { // Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // -// a.Emptyf(obj, "error message %s", "formatted") +// a.Emptyf(obj, "error message %s", "formatted") func (a *Assertions) Emptyf(object interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -120,7 +120,7 @@ func (a *Assertions) Emptyf(object interface{}, msg string, args ...interface{}) // Equal asserts that two objects are equal. // -// a.Equal(123, 123) +// a.Equal(123, 123) // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality @@ -135,8 +135,8 @@ func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs // EqualError asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // -// actualObj, err := SomeFunction() -// a.EqualError(err, expectedErrorString) +// actualObj, err := SomeFunction() +// a.EqualError(err, expectedErrorString) func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -147,8 +147,8 @@ func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ... // EqualErrorf asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // -// actualObj, err := SomeFunction() -// a.EqualErrorf(err, expectedErrorString, "error message %s", "formatted") +// actualObj, err := SomeFunction() +// a.EqualErrorf(err, expectedErrorString, "error message %s", "formatted") func (a *Assertions) EqualErrorf(theError error, errString string, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -156,10 +156,44 @@ func (a *Assertions) EqualErrorf(theError error, errString string, msg string, a EqualErrorf(a.t, theError, errString, msg, args...) } +// EqualExportedValues asserts that the types of two objects are equal and their public +// fields are also equal. This is useful for comparing structs that have private fields +// that could potentially differ. +// +// type S struct { +// Exported int +// notExported int +// } +// a.EqualExportedValues(S{1, 2}, S{1, 3}) => true +// a.EqualExportedValues(S{1, 2}, S{2, 3}) => false +func (a *Assertions) EqualExportedValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + EqualExportedValues(a.t, expected, actual, msgAndArgs...) +} + +// EqualExportedValuesf asserts that the types of two objects are equal and their public +// fields are also equal. This is useful for comparing structs that have private fields +// that could potentially differ. +// +// type S struct { +// Exported int +// notExported int +// } +// a.EqualExportedValuesf(S{1, 2}, S{1, 3}, "error message %s", "formatted") => true +// a.EqualExportedValuesf(S{1, 2}, S{2, 3}, "error message %s", "formatted") => false +func (a *Assertions) EqualExportedValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + EqualExportedValuesf(a.t, expected, actual, msg, args...) +} + // EqualValues asserts that two objects are equal or convertable to the same types // and equal. // -// a.EqualValues(uint32(123), int32(123)) +// a.EqualValues(uint32(123), int32(123)) func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -170,7 +204,7 @@ func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAn // EqualValuesf asserts that two objects are equal or convertable to the same types // and equal. // -// a.EqualValuesf(uint32(123), int32(123), "error message %s", "formatted") +// a.EqualValuesf(uint32(123), int32(123), "error message %s", "formatted") func (a *Assertions) EqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -180,7 +214,7 @@ func (a *Assertions) EqualValuesf(expected interface{}, actual interface{}, msg // Equalf asserts that two objects are equal. // -// a.Equalf(123, 123, "error message %s", "formatted") +// a.Equalf(123, 123, "error message %s", "formatted") // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality @@ -194,10 +228,10 @@ func (a *Assertions) Equalf(expected interface{}, actual interface{}, msg string // Error asserts that a function returned an error (i.e. not `nil`). // -// actualObj, err := SomeFunction() -// if a.Error(err) { -// assert.Equal(t, expectedError, err) -// } +// actualObj, err := SomeFunction() +// if a.Error(err) { +// assert.Equal(t, expectedError, err) +// } func (a *Assertions) Error(err error, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -226,8 +260,8 @@ func (a *Assertions) ErrorAsf(err error, target interface{}, msg string, args .. // ErrorContains asserts that a function returned an error (i.e. not `nil`) // and that the error contains the specified substring. // -// actualObj, err := SomeFunction() -// a.ErrorContains(err, expectedErrorSubString) +// actualObj, err := SomeFunction() +// a.ErrorContains(err, expectedErrorSubString) func (a *Assertions) ErrorContains(theError error, contains string, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -238,8 +272,8 @@ func (a *Assertions) ErrorContains(theError error, contains string, msgAndArgs . // ErrorContainsf asserts that a function returned an error (i.e. not `nil`) // and that the error contains the specified substring. // -// actualObj, err := SomeFunction() -// a.ErrorContainsf(err, expectedErrorSubString, "error message %s", "formatted") +// actualObj, err := SomeFunction() +// a.ErrorContainsf(err, expectedErrorSubString, "error message %s", "formatted") func (a *Assertions) ErrorContainsf(theError error, contains string, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -267,10 +301,10 @@ func (a *Assertions) ErrorIsf(err error, target error, msg string, args ...inter // Errorf asserts that a function returned an error (i.e. not `nil`). // -// actualObj, err := SomeFunction() -// if a.Errorf(err, "error message %s", "formatted") { -// assert.Equal(t, expectedErrorf, err) -// } +// actualObj, err := SomeFunction() +// if a.Errorf(err, "error message %s", "formatted") { +// assert.Equal(t, expectedErrorf, err) +// } func (a *Assertions) Errorf(err error, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -281,7 +315,7 @@ func (a *Assertions) Errorf(err error, msg string, args ...interface{}) { // Eventually asserts that given condition will be met in waitFor time, // periodically checking target function each tick. // -// a.Eventually(func() bool { return true; }, time.Second, 10*time.Millisecond) +// a.Eventually(func() bool { return true; }, time.Second, 10*time.Millisecond) func (a *Assertions) Eventually(condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -289,10 +323,60 @@ func (a *Assertions) Eventually(condition func() bool, waitFor time.Duration, ti Eventually(a.t, condition, waitFor, tick, msgAndArgs...) } +// EventuallyWithT asserts that given condition will be met in waitFor time, +// periodically checking target function each tick. In contrast to Eventually, +// it supplies a CollectT to the condition function, so that the condition +// function can use the CollectT to call other assertions. +// The condition is considered "met" if no errors are raised in a tick. +// The supplied CollectT collects all errors from one tick (if there are any). +// If the condition is not met before waitFor, the collected errors of +// the last tick are copied to t. +// +// externalValue := false +// go func() { +// time.Sleep(8*time.Second) +// externalValue = true +// }() +// a.EventuallyWithT(func(c *assert.CollectT) { +// // add assertions as needed; any assertion failure will fail the current tick +// assert.True(c, externalValue, "expected 'externalValue' to be true") +// }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false") +func (a *Assertions) EventuallyWithT(condition func(collect *assert.CollectT), waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + EventuallyWithT(a.t, condition, waitFor, tick, msgAndArgs...) +} + +// EventuallyWithTf asserts that given condition will be met in waitFor time, +// periodically checking target function each tick. In contrast to Eventually, +// it supplies a CollectT to the condition function, so that the condition +// function can use the CollectT to call other assertions. +// The condition is considered "met" if no errors are raised in a tick. +// The supplied CollectT collects all errors from one tick (if there are any). +// If the condition is not met before waitFor, the collected errors of +// the last tick are copied to t. +// +// externalValue := false +// go func() { +// time.Sleep(8*time.Second) +// externalValue = true +// }() +// a.EventuallyWithTf(func(c *assert.CollectT, "error message %s", "formatted") { +// // add assertions as needed; any assertion failure will fail the current tick +// assert.True(c, externalValue, "expected 'externalValue' to be true") +// }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false") +func (a *Assertions) EventuallyWithTf(condition func(collect *assert.CollectT), waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) { + if h, ok := a.t.(tHelper); ok { + h.Helper() + } + EventuallyWithTf(a.t, condition, waitFor, tick, msg, args...) +} + // Eventuallyf asserts that given condition will be met in waitFor time, // periodically checking target function each tick. // -// a.Eventuallyf(func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") +// a.Eventuallyf(func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") func (a *Assertions) Eventuallyf(condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -302,7 +386,7 @@ func (a *Assertions) Eventuallyf(condition func() bool, waitFor time.Duration, t // Exactly asserts that two objects are equal in value and type. // -// a.Exactly(int32(123), int64(123)) +// a.Exactly(int32(123), int64(123)) func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -312,7 +396,7 @@ func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArg // Exactlyf asserts that two objects are equal in value and type. // -// a.Exactlyf(int32(123), int64(123), "error message %s", "formatted") +// a.Exactlyf(int32(123), int64(123), "error message %s", "formatted") func (a *Assertions) Exactlyf(expected interface{}, actual interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -354,7 +438,7 @@ func (a *Assertions) Failf(failureMessage string, msg string, args ...interface{ // False asserts that the specified value is false. // -// a.False(myBool) +// a.False(myBool) func (a *Assertions) False(value bool, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -364,7 +448,7 @@ func (a *Assertions) False(value bool, msgAndArgs ...interface{}) { // Falsef asserts that the specified value is false. // -// a.Falsef(myBool, "error message %s", "formatted") +// a.Falsef(myBool, "error message %s", "formatted") func (a *Assertions) Falsef(value bool, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -392,9 +476,9 @@ func (a *Assertions) FileExistsf(path string, msg string, args ...interface{}) { // Greater asserts that the first element is greater than the second // -// a.Greater(2, 1) -// a.Greater(float64(2), float64(1)) -// a.Greater("b", "a") +// a.Greater(2, 1) +// a.Greater(float64(2), float64(1)) +// a.Greater("b", "a") func (a *Assertions) Greater(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -404,10 +488,10 @@ func (a *Assertions) Greater(e1 interface{}, e2 interface{}, msgAndArgs ...inter // GreaterOrEqual asserts that the first element is greater than or equal to the second // -// a.GreaterOrEqual(2, 1) -// a.GreaterOrEqual(2, 2) -// a.GreaterOrEqual("b", "a") -// a.GreaterOrEqual("b", "b") +// a.GreaterOrEqual(2, 1) +// a.GreaterOrEqual(2, 2) +// a.GreaterOrEqual("b", "a") +// a.GreaterOrEqual("b", "b") func (a *Assertions) GreaterOrEqual(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -417,10 +501,10 @@ func (a *Assertions) GreaterOrEqual(e1 interface{}, e2 interface{}, msgAndArgs . // GreaterOrEqualf asserts that the first element is greater than or equal to the second // -// a.GreaterOrEqualf(2, 1, "error message %s", "formatted") -// a.GreaterOrEqualf(2, 2, "error message %s", "formatted") -// a.GreaterOrEqualf("b", "a", "error message %s", "formatted") -// a.GreaterOrEqualf("b", "b", "error message %s", "formatted") +// a.GreaterOrEqualf(2, 1, "error message %s", "formatted") +// a.GreaterOrEqualf(2, 2, "error message %s", "formatted") +// a.GreaterOrEqualf("b", "a", "error message %s", "formatted") +// a.GreaterOrEqualf("b", "b", "error message %s", "formatted") func (a *Assertions) GreaterOrEqualf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -430,9 +514,9 @@ func (a *Assertions) GreaterOrEqualf(e1 interface{}, e2 interface{}, msg string, // Greaterf asserts that the first element is greater than the second // -// a.Greaterf(2, 1, "error message %s", "formatted") -// a.Greaterf(float64(2), float64(1), "error message %s", "formatted") -// a.Greaterf("b", "a", "error message %s", "formatted") +// a.Greaterf(2, 1, "error message %s", "formatted") +// a.Greaterf(float64(2), float64(1), "error message %s", "formatted") +// a.Greaterf("b", "a", "error message %s", "formatted") func (a *Assertions) Greaterf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -443,7 +527,7 @@ func (a *Assertions) Greaterf(e1 interface{}, e2 interface{}, msg string, args . // HTTPBodyContains asserts that a specified handler returns a // body that contains a string. // -// a.HTTPBodyContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") +// a.HTTPBodyContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) { @@ -456,7 +540,7 @@ func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, u // HTTPBodyContainsf asserts that a specified handler returns a // body that contains a string. // -// a.HTTPBodyContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// a.HTTPBodyContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) { @@ -469,7 +553,7 @@ func (a *Assertions) HTTPBodyContainsf(handler http.HandlerFunc, method string, // HTTPBodyNotContains asserts that a specified handler returns a // body that does not contain a string. // -// a.HTTPBodyNotContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") +// a.HTTPBodyNotContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) { @@ -482,7 +566,7 @@ func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string // HTTPBodyNotContainsf asserts that a specified handler returns a // body that does not contain a string. // -// a.HTTPBodyNotContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") +// a.HTTPBodyNotContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyNotContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) { @@ -494,7 +578,7 @@ func (a *Assertions) HTTPBodyNotContainsf(handler http.HandlerFunc, method strin // HTTPError asserts that a specified handler returns an error status code. // -// a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { @@ -506,7 +590,7 @@ func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url stri // HTTPErrorf asserts that a specified handler returns an error status code. // -// a.HTTPErrorf(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// a.HTTPErrorf(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPErrorf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { @@ -518,7 +602,7 @@ func (a *Assertions) HTTPErrorf(handler http.HandlerFunc, method string, url str // HTTPRedirect asserts that a specified handler returns a redirect status code. // -// a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { @@ -530,7 +614,7 @@ func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url s // HTTPRedirectf asserts that a specified handler returns a redirect status code. // -// a.HTTPRedirectf(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} +// a.HTTPRedirectf(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPRedirectf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { @@ -542,7 +626,7 @@ func (a *Assertions) HTTPRedirectf(handler http.HandlerFunc, method string, url // HTTPStatusCode asserts that a specified handler returns a specified status code. // -// a.HTTPStatusCode(myHandler, "GET", "/notImplemented", nil, 501) +// a.HTTPStatusCode(myHandler, "GET", "/notImplemented", nil, 501) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPStatusCode(handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msgAndArgs ...interface{}) { @@ -554,7 +638,7 @@ func (a *Assertions) HTTPStatusCode(handler http.HandlerFunc, method string, url // HTTPStatusCodef asserts that a specified handler returns a specified status code. // -// a.HTTPStatusCodef(myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted") +// a.HTTPStatusCodef(myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPStatusCodef(handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msg string, args ...interface{}) { @@ -566,7 +650,7 @@ func (a *Assertions) HTTPStatusCodef(handler http.HandlerFunc, method string, ur // HTTPSuccess asserts that a specified handler returns a success status code. // -// a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) +// a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { @@ -578,7 +662,7 @@ func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url st // HTTPSuccessf asserts that a specified handler returns a success status code. // -// a.HTTPSuccessf(myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") +// a.HTTPSuccessf(myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPSuccessf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { @@ -590,7 +674,7 @@ func (a *Assertions) HTTPSuccessf(handler http.HandlerFunc, method string, url s // Implements asserts that an object is implemented by the specified interface. // -// a.Implements((*MyInterface)(nil), new(MyObject)) +// a.Implements((*MyInterface)(nil), new(MyObject)) func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -600,7 +684,7 @@ func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, // Implementsf asserts that an object is implemented by the specified interface. // -// a.Implementsf((*MyInterface)(nil), new(MyObject), "error message %s", "formatted") +// a.Implementsf((*MyInterface)(nil), new(MyObject), "error message %s", "formatted") func (a *Assertions) Implementsf(interfaceObject interface{}, object interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -610,7 +694,7 @@ func (a *Assertions) Implementsf(interfaceObject interface{}, object interface{} // InDelta asserts that the two numerals are within delta of each other. // -// a.InDelta(math.Pi, 22/7.0, 0.01) +// a.InDelta(math.Pi, 22/7.0, 0.01) func (a *Assertions) InDelta(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -652,7 +736,7 @@ func (a *Assertions) InDeltaSlicef(expected interface{}, actual interface{}, del // InDeltaf asserts that the two numerals are within delta of each other. // -// a.InDeltaf(math.Pi, 22/7.0, 0.01, "error message %s", "formatted") +// a.InDeltaf(math.Pi, 22/7.0, 0.01, "error message %s", "formatted") func (a *Assertions) InDeltaf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -694,9 +778,9 @@ func (a *Assertions) InEpsilonf(expected interface{}, actual interface{}, epsilo // IsDecreasing asserts that the collection is decreasing // -// a.IsDecreasing([]int{2, 1, 0}) -// a.IsDecreasing([]float{2, 1}) -// a.IsDecreasing([]string{"b", "a"}) +// a.IsDecreasing([]int{2, 1, 0}) +// a.IsDecreasing([]float{2, 1}) +// a.IsDecreasing([]string{"b", "a"}) func (a *Assertions) IsDecreasing(object interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -706,9 +790,9 @@ func (a *Assertions) IsDecreasing(object interface{}, msgAndArgs ...interface{}) // IsDecreasingf asserts that the collection is decreasing // -// a.IsDecreasingf([]int{2, 1, 0}, "error message %s", "formatted") -// a.IsDecreasingf([]float{2, 1}, "error message %s", "formatted") -// a.IsDecreasingf([]string{"b", "a"}, "error message %s", "formatted") +// a.IsDecreasingf([]int{2, 1, 0}, "error message %s", "formatted") +// a.IsDecreasingf([]float{2, 1}, "error message %s", "formatted") +// a.IsDecreasingf([]string{"b", "a"}, "error message %s", "formatted") func (a *Assertions) IsDecreasingf(object interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -718,9 +802,9 @@ func (a *Assertions) IsDecreasingf(object interface{}, msg string, args ...inter // IsIncreasing asserts that the collection is increasing // -// a.IsIncreasing([]int{1, 2, 3}) -// a.IsIncreasing([]float{1, 2}) -// a.IsIncreasing([]string{"a", "b"}) +// a.IsIncreasing([]int{1, 2, 3}) +// a.IsIncreasing([]float{1, 2}) +// a.IsIncreasing([]string{"a", "b"}) func (a *Assertions) IsIncreasing(object interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -730,9 +814,9 @@ func (a *Assertions) IsIncreasing(object interface{}, msgAndArgs ...interface{}) // IsIncreasingf asserts that the collection is increasing // -// a.IsIncreasingf([]int{1, 2, 3}, "error message %s", "formatted") -// a.IsIncreasingf([]float{1, 2}, "error message %s", "formatted") -// a.IsIncreasingf([]string{"a", "b"}, "error message %s", "formatted") +// a.IsIncreasingf([]int{1, 2, 3}, "error message %s", "formatted") +// a.IsIncreasingf([]float{1, 2}, "error message %s", "formatted") +// a.IsIncreasingf([]string{"a", "b"}, "error message %s", "formatted") func (a *Assertions) IsIncreasingf(object interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -742,9 +826,9 @@ func (a *Assertions) IsIncreasingf(object interface{}, msg string, args ...inter // IsNonDecreasing asserts that the collection is not decreasing // -// a.IsNonDecreasing([]int{1, 1, 2}) -// a.IsNonDecreasing([]float{1, 2}) -// a.IsNonDecreasing([]string{"a", "b"}) +// a.IsNonDecreasing([]int{1, 1, 2}) +// a.IsNonDecreasing([]float{1, 2}) +// a.IsNonDecreasing([]string{"a", "b"}) func (a *Assertions) IsNonDecreasing(object interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -754,9 +838,9 @@ func (a *Assertions) IsNonDecreasing(object interface{}, msgAndArgs ...interface // IsNonDecreasingf asserts that the collection is not decreasing // -// a.IsNonDecreasingf([]int{1, 1, 2}, "error message %s", "formatted") -// a.IsNonDecreasingf([]float{1, 2}, "error message %s", "formatted") -// a.IsNonDecreasingf([]string{"a", "b"}, "error message %s", "formatted") +// a.IsNonDecreasingf([]int{1, 1, 2}, "error message %s", "formatted") +// a.IsNonDecreasingf([]float{1, 2}, "error message %s", "formatted") +// a.IsNonDecreasingf([]string{"a", "b"}, "error message %s", "formatted") func (a *Assertions) IsNonDecreasingf(object interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -766,9 +850,9 @@ func (a *Assertions) IsNonDecreasingf(object interface{}, msg string, args ...in // IsNonIncreasing asserts that the collection is not increasing // -// a.IsNonIncreasing([]int{2, 1, 1}) -// a.IsNonIncreasing([]float{2, 1}) -// a.IsNonIncreasing([]string{"b", "a"}) +// a.IsNonIncreasing([]int{2, 1, 1}) +// a.IsNonIncreasing([]float{2, 1}) +// a.IsNonIncreasing([]string{"b", "a"}) func (a *Assertions) IsNonIncreasing(object interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -778,9 +862,9 @@ func (a *Assertions) IsNonIncreasing(object interface{}, msgAndArgs ...interface // IsNonIncreasingf asserts that the collection is not increasing // -// a.IsNonIncreasingf([]int{2, 1, 1}, "error message %s", "formatted") -// a.IsNonIncreasingf([]float{2, 1}, "error message %s", "formatted") -// a.IsNonIncreasingf([]string{"b", "a"}, "error message %s", "formatted") +// a.IsNonIncreasingf([]int{2, 1, 1}, "error message %s", "formatted") +// a.IsNonIncreasingf([]float{2, 1}, "error message %s", "formatted") +// a.IsNonIncreasingf([]string{"b", "a"}, "error message %s", "formatted") func (a *Assertions) IsNonIncreasingf(object interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -806,7 +890,7 @@ func (a *Assertions) IsTypef(expectedType interface{}, object interface{}, msg s // JSONEq asserts that two JSON strings are equivalent. // -// a.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) +// a.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -816,7 +900,7 @@ func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interf // JSONEqf asserts that two JSON strings are equivalent. // -// a.JSONEqf(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") +// a.JSONEqf(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") func (a *Assertions) JSONEqf(expected string, actual string, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -827,7 +911,7 @@ func (a *Assertions) JSONEqf(expected string, actual string, msg string, args .. // Len asserts that the specified object has specific length. // Len also fails if the object has a type that len() not accept. // -// a.Len(mySlice, 3) +// a.Len(mySlice, 3) func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -838,7 +922,7 @@ func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface // Lenf asserts that the specified object has specific length. // Lenf also fails if the object has a type that len() not accept. // -// a.Lenf(mySlice, 3, "error message %s", "formatted") +// a.Lenf(mySlice, 3, "error message %s", "formatted") func (a *Assertions) Lenf(object interface{}, length int, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -848,9 +932,9 @@ func (a *Assertions) Lenf(object interface{}, length int, msg string, args ...in // Less asserts that the first element is less than the second // -// a.Less(1, 2) -// a.Less(float64(1), float64(2)) -// a.Less("a", "b") +// a.Less(1, 2) +// a.Less(float64(1), float64(2)) +// a.Less("a", "b") func (a *Assertions) Less(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -860,10 +944,10 @@ func (a *Assertions) Less(e1 interface{}, e2 interface{}, msgAndArgs ...interfac // LessOrEqual asserts that the first element is less than or equal to the second // -// a.LessOrEqual(1, 2) -// a.LessOrEqual(2, 2) -// a.LessOrEqual("a", "b") -// a.LessOrEqual("b", "b") +// a.LessOrEqual(1, 2) +// a.LessOrEqual(2, 2) +// a.LessOrEqual("a", "b") +// a.LessOrEqual("b", "b") func (a *Assertions) LessOrEqual(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -873,10 +957,10 @@ func (a *Assertions) LessOrEqual(e1 interface{}, e2 interface{}, msgAndArgs ...i // LessOrEqualf asserts that the first element is less than or equal to the second // -// a.LessOrEqualf(1, 2, "error message %s", "formatted") -// a.LessOrEqualf(2, 2, "error message %s", "formatted") -// a.LessOrEqualf("a", "b", "error message %s", "formatted") -// a.LessOrEqualf("b", "b", "error message %s", "formatted") +// a.LessOrEqualf(1, 2, "error message %s", "formatted") +// a.LessOrEqualf(2, 2, "error message %s", "formatted") +// a.LessOrEqualf("a", "b", "error message %s", "formatted") +// a.LessOrEqualf("b", "b", "error message %s", "formatted") func (a *Assertions) LessOrEqualf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -886,9 +970,9 @@ func (a *Assertions) LessOrEqualf(e1 interface{}, e2 interface{}, msg string, ar // Lessf asserts that the first element is less than the second // -// a.Lessf(1, 2, "error message %s", "formatted") -// a.Lessf(float64(1), float64(2), "error message %s", "formatted") -// a.Lessf("a", "b", "error message %s", "formatted") +// a.Lessf(1, 2, "error message %s", "formatted") +// a.Lessf(float64(1), float64(2), "error message %s", "formatted") +// a.Lessf("a", "b", "error message %s", "formatted") func (a *Assertions) Lessf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -898,8 +982,8 @@ func (a *Assertions) Lessf(e1 interface{}, e2 interface{}, msg string, args ...i // Negative asserts that the specified element is negative // -// a.Negative(-1) -// a.Negative(-1.23) +// a.Negative(-1) +// a.Negative(-1.23) func (a *Assertions) Negative(e interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -909,8 +993,8 @@ func (a *Assertions) Negative(e interface{}, msgAndArgs ...interface{}) { // Negativef asserts that the specified element is negative // -// a.Negativef(-1, "error message %s", "formatted") -// a.Negativef(-1.23, "error message %s", "formatted") +// a.Negativef(-1, "error message %s", "formatted") +// a.Negativef(-1.23, "error message %s", "formatted") func (a *Assertions) Negativef(e interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -921,7 +1005,7 @@ func (a *Assertions) Negativef(e interface{}, msg string, args ...interface{}) { // Never asserts that the given condition doesn't satisfy in waitFor time, // periodically checking the target function each tick. // -// a.Never(func() bool { return false; }, time.Second, 10*time.Millisecond) +// a.Never(func() bool { return false; }, time.Second, 10*time.Millisecond) func (a *Assertions) Never(condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -932,7 +1016,7 @@ func (a *Assertions) Never(condition func() bool, waitFor time.Duration, tick ti // Neverf asserts that the given condition doesn't satisfy in waitFor time, // periodically checking the target function each tick. // -// a.Neverf(func() bool { return false; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") +// a.Neverf(func() bool { return false; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") func (a *Assertions) Neverf(condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -942,7 +1026,7 @@ func (a *Assertions) Neverf(condition func() bool, waitFor time.Duration, tick t // Nil asserts that the specified object is nil. // -// a.Nil(err) +// a.Nil(err) func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -952,7 +1036,7 @@ func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) { // Nilf asserts that the specified object is nil. // -// a.Nilf(err, "error message %s", "formatted") +// a.Nilf(err, "error message %s", "formatted") func (a *Assertions) Nilf(object interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -980,10 +1064,10 @@ func (a *Assertions) NoDirExistsf(path string, msg string, args ...interface{}) // NoError asserts that a function returned no error (i.e. `nil`). // -// actualObj, err := SomeFunction() -// if a.NoError(err) { -// assert.Equal(t, expectedObj, actualObj) -// } +// actualObj, err := SomeFunction() +// if a.NoError(err) { +// assert.Equal(t, expectedObj, actualObj) +// } func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -993,10 +1077,10 @@ func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) { // NoErrorf asserts that a function returned no error (i.e. `nil`). // -// actualObj, err := SomeFunction() -// if a.NoErrorf(err, "error message %s", "formatted") { -// assert.Equal(t, expectedObj, actualObj) -// } +// actualObj, err := SomeFunction() +// if a.NoErrorf(err, "error message %s", "formatted") { +// assert.Equal(t, expectedObj, actualObj) +// } func (a *Assertions) NoErrorf(err error, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1025,9 +1109,9 @@ func (a *Assertions) NoFileExistsf(path string, msg string, args ...interface{}) // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // -// a.NotContains("Hello World", "Earth") -// a.NotContains(["Hello", "World"], "Earth") -// a.NotContains({"Hello": "World"}, "Earth") +// a.NotContains("Hello World", "Earth") +// a.NotContains(["Hello", "World"], "Earth") +// a.NotContains({"Hello": "World"}, "Earth") func (a *Assertions) NotContains(s interface{}, contains interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1038,9 +1122,9 @@ func (a *Assertions) NotContains(s interface{}, contains interface{}, msgAndArgs // NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // -// a.NotContainsf("Hello World", "Earth", "error message %s", "formatted") -// a.NotContainsf(["Hello", "World"], "Earth", "error message %s", "formatted") -// a.NotContainsf({"Hello": "World"}, "Earth", "error message %s", "formatted") +// a.NotContainsf("Hello World", "Earth", "error message %s", "formatted") +// a.NotContainsf(["Hello", "World"], "Earth", "error message %s", "formatted") +// a.NotContainsf({"Hello": "World"}, "Earth", "error message %s", "formatted") func (a *Assertions) NotContainsf(s interface{}, contains interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1051,9 +1135,9 @@ func (a *Assertions) NotContainsf(s interface{}, contains interface{}, msg strin // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // -// if a.NotEmpty(obj) { -// assert.Equal(t, "two", obj[1]) -// } +// if a.NotEmpty(obj) { +// assert.Equal(t, "two", obj[1]) +// } func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1064,9 +1148,9 @@ func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) { // NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // -// if a.NotEmptyf(obj, "error message %s", "formatted") { -// assert.Equal(t, "two", obj[1]) -// } +// if a.NotEmptyf(obj, "error message %s", "formatted") { +// assert.Equal(t, "two", obj[1]) +// } func (a *Assertions) NotEmptyf(object interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1076,7 +1160,7 @@ func (a *Assertions) NotEmptyf(object interface{}, msg string, args ...interface // NotEqual asserts that the specified values are NOT equal. // -// a.NotEqual(obj1, obj2) +// a.NotEqual(obj1, obj2) // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). @@ -1089,7 +1173,7 @@ func (a *Assertions) NotEqual(expected interface{}, actual interface{}, msgAndAr // NotEqualValues asserts that two objects are not equal even when converted to the same type // -// a.NotEqualValues(obj1, obj2) +// a.NotEqualValues(obj1, obj2) func (a *Assertions) NotEqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1099,7 +1183,7 @@ func (a *Assertions) NotEqualValues(expected interface{}, actual interface{}, ms // NotEqualValuesf asserts that two objects are not equal even when converted to the same type // -// a.NotEqualValuesf(obj1, obj2, "error message %s", "formatted") +// a.NotEqualValuesf(obj1, obj2, "error message %s", "formatted") func (a *Assertions) NotEqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1109,7 +1193,7 @@ func (a *Assertions) NotEqualValuesf(expected interface{}, actual interface{}, m // NotEqualf asserts that the specified values are NOT equal. // -// a.NotEqualf(obj1, obj2, "error message %s", "formatted") +// a.NotEqualf(obj1, obj2, "error message %s", "formatted") // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). @@ -1140,7 +1224,7 @@ func (a *Assertions) NotErrorIsf(err error, target error, msg string, args ...in // NotNil asserts that the specified object is not nil. // -// a.NotNil(err) +// a.NotNil(err) func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1150,7 +1234,7 @@ func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) { // NotNilf asserts that the specified object is not nil. // -// a.NotNilf(err, "error message %s", "formatted") +// a.NotNilf(err, "error message %s", "formatted") func (a *Assertions) NotNilf(object interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1160,7 +1244,7 @@ func (a *Assertions) NotNilf(object interface{}, msg string, args ...interface{} // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. // -// a.NotPanics(func(){ RemainCalm() }) +// a.NotPanics(func(){ RemainCalm() }) func (a *Assertions) NotPanics(f assert.PanicTestFunc, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1170,7 +1254,7 @@ func (a *Assertions) NotPanics(f assert.PanicTestFunc, msgAndArgs ...interface{} // NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. // -// a.NotPanicsf(func(){ RemainCalm() }, "error message %s", "formatted") +// a.NotPanicsf(func(){ RemainCalm() }, "error message %s", "formatted") func (a *Assertions) NotPanicsf(f assert.PanicTestFunc, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1180,8 +1264,8 @@ func (a *Assertions) NotPanicsf(f assert.PanicTestFunc, msg string, args ...inte // NotRegexp asserts that a specified regexp does not match a string. // -// a.NotRegexp(regexp.MustCompile("starts"), "it's starting") -// a.NotRegexp("^start", "it's not starting") +// a.NotRegexp(regexp.MustCompile("starts"), "it's starting") +// a.NotRegexp("^start", "it's not starting") func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1191,8 +1275,8 @@ func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...in // NotRegexpf asserts that a specified regexp does not match a string. // -// a.NotRegexpf(regexp.MustCompile("starts"), "it's starting", "error message %s", "formatted") -// a.NotRegexpf("^start", "it's not starting", "error message %s", "formatted") +// a.NotRegexpf(regexp.MustCompile("starts"), "it's starting", "error message %s", "formatted") +// a.NotRegexpf("^start", "it's not starting", "error message %s", "formatted") func (a *Assertions) NotRegexpf(rx interface{}, str interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1202,7 +1286,7 @@ func (a *Assertions) NotRegexpf(rx interface{}, str interface{}, msg string, arg // NotSame asserts that two pointers do not reference the same object. // -// a.NotSame(ptr1, ptr2) +// a.NotSame(ptr1, ptr2) // // Both arguments must be pointer variables. Pointer variable sameness is // determined based on the equality of both type and value. @@ -1215,7 +1299,7 @@ func (a *Assertions) NotSame(expected interface{}, actual interface{}, msgAndArg // NotSamef asserts that two pointers do not reference the same object. // -// a.NotSamef(ptr1, ptr2, "error message %s", "formatted") +// a.NotSamef(ptr1, ptr2, "error message %s", "formatted") // // Both arguments must be pointer variables. Pointer variable sameness is // determined based on the equality of both type and value. @@ -1229,7 +1313,7 @@ func (a *Assertions) NotSamef(expected interface{}, actual interface{}, msg stri // NotSubset asserts that the specified list(array, slice...) contains not all // elements given in the specified subset(array, slice...). // -// a.NotSubset([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") +// a.NotSubset([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") func (a *Assertions) NotSubset(list interface{}, subset interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1240,7 +1324,7 @@ func (a *Assertions) NotSubset(list interface{}, subset interface{}, msgAndArgs // NotSubsetf asserts that the specified list(array, slice...) contains not all // elements given in the specified subset(array, slice...). // -// a.NotSubsetf([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") +// a.NotSubsetf([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") func (a *Assertions) NotSubsetf(list interface{}, subset interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1266,7 +1350,7 @@ func (a *Assertions) NotZerof(i interface{}, msg string, args ...interface{}) { // Panics asserts that the code inside the specified PanicTestFunc panics. // -// a.Panics(func(){ GoCrazy() }) +// a.Panics(func(){ GoCrazy() }) func (a *Assertions) Panics(f assert.PanicTestFunc, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1278,7 +1362,7 @@ func (a *Assertions) Panics(f assert.PanicTestFunc, msgAndArgs ...interface{}) { // panics, and that the recovered panic value is an error that satisfies the // EqualError comparison. // -// a.PanicsWithError("crazy error", func(){ GoCrazy() }) +// a.PanicsWithError("crazy error", func(){ GoCrazy() }) func (a *Assertions) PanicsWithError(errString string, f assert.PanicTestFunc, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1290,7 +1374,7 @@ func (a *Assertions) PanicsWithError(errString string, f assert.PanicTestFunc, m // panics, and that the recovered panic value is an error that satisfies the // EqualError comparison. // -// a.PanicsWithErrorf("crazy error", func(){ GoCrazy() }, "error message %s", "formatted") +// a.PanicsWithErrorf("crazy error", func(){ GoCrazy() }, "error message %s", "formatted") func (a *Assertions) PanicsWithErrorf(errString string, f assert.PanicTestFunc, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1301,7 +1385,7 @@ func (a *Assertions) PanicsWithErrorf(errString string, f assert.PanicTestFunc, // PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // -// a.PanicsWithValue("crazy error", func(){ GoCrazy() }) +// a.PanicsWithValue("crazy error", func(){ GoCrazy() }) func (a *Assertions) PanicsWithValue(expected interface{}, f assert.PanicTestFunc, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1312,7 +1396,7 @@ func (a *Assertions) PanicsWithValue(expected interface{}, f assert.PanicTestFun // PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // -// a.PanicsWithValuef("crazy error", func(){ GoCrazy() }, "error message %s", "formatted") +// a.PanicsWithValuef("crazy error", func(){ GoCrazy() }, "error message %s", "formatted") func (a *Assertions) PanicsWithValuef(expected interface{}, f assert.PanicTestFunc, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1322,7 +1406,7 @@ func (a *Assertions) PanicsWithValuef(expected interface{}, f assert.PanicTestFu // Panicsf asserts that the code inside the specified PanicTestFunc panics. // -// a.Panicsf(func(){ GoCrazy() }, "error message %s", "formatted") +// a.Panicsf(func(){ GoCrazy() }, "error message %s", "formatted") func (a *Assertions) Panicsf(f assert.PanicTestFunc, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1332,8 +1416,8 @@ func (a *Assertions) Panicsf(f assert.PanicTestFunc, msg string, args ...interfa // Positive asserts that the specified element is positive // -// a.Positive(1) -// a.Positive(1.23) +// a.Positive(1) +// a.Positive(1.23) func (a *Assertions) Positive(e interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1343,8 +1427,8 @@ func (a *Assertions) Positive(e interface{}, msgAndArgs ...interface{}) { // Positivef asserts that the specified element is positive // -// a.Positivef(1, "error message %s", "formatted") -// a.Positivef(1.23, "error message %s", "formatted") +// a.Positivef(1, "error message %s", "formatted") +// a.Positivef(1.23, "error message %s", "formatted") func (a *Assertions) Positivef(e interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1354,8 +1438,8 @@ func (a *Assertions) Positivef(e interface{}, msg string, args ...interface{}) { // Regexp asserts that a specified regexp matches a string. // -// a.Regexp(regexp.MustCompile("start"), "it's starting") -// a.Regexp("start...$", "it's not starting") +// a.Regexp(regexp.MustCompile("start"), "it's starting") +// a.Regexp("start...$", "it's not starting") func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1365,8 +1449,8 @@ func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...inter // Regexpf asserts that a specified regexp matches a string. // -// a.Regexpf(regexp.MustCompile("start"), "it's starting", "error message %s", "formatted") -// a.Regexpf("start...$", "it's not starting", "error message %s", "formatted") +// a.Regexpf(regexp.MustCompile("start"), "it's starting", "error message %s", "formatted") +// a.Regexpf("start...$", "it's not starting", "error message %s", "formatted") func (a *Assertions) Regexpf(rx interface{}, str interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1376,7 +1460,7 @@ func (a *Assertions) Regexpf(rx interface{}, str interface{}, msg string, args . // Same asserts that two pointers reference the same object. // -// a.Same(ptr1, ptr2) +// a.Same(ptr1, ptr2) // // Both arguments must be pointer variables. Pointer variable sameness is // determined based on the equality of both type and value. @@ -1389,7 +1473,7 @@ func (a *Assertions) Same(expected interface{}, actual interface{}, msgAndArgs . // Samef asserts that two pointers reference the same object. // -// a.Samef(ptr1, ptr2, "error message %s", "formatted") +// a.Samef(ptr1, ptr2, "error message %s", "formatted") // // Both arguments must be pointer variables. Pointer variable sameness is // determined based on the equality of both type and value. @@ -1403,7 +1487,7 @@ func (a *Assertions) Samef(expected interface{}, actual interface{}, msg string, // Subset asserts that the specified list(array, slice...) contains all // elements given in the specified subset(array, slice...). // -// a.Subset([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") +// a.Subset([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") func (a *Assertions) Subset(list interface{}, subset interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1414,7 +1498,7 @@ func (a *Assertions) Subset(list interface{}, subset interface{}, msgAndArgs ... // Subsetf asserts that the specified list(array, slice...) contains all // elements given in the specified subset(array, slice...). // -// a.Subsetf([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") +// a.Subsetf([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") func (a *Assertions) Subsetf(list interface{}, subset interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1424,7 +1508,7 @@ func (a *Assertions) Subsetf(list interface{}, subset interface{}, msg string, a // True asserts that the specified value is true. // -// a.True(myBool) +// a.True(myBool) func (a *Assertions) True(value bool, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1434,7 +1518,7 @@ func (a *Assertions) True(value bool, msgAndArgs ...interface{}) { // Truef asserts that the specified value is true. // -// a.Truef(myBool, "error message %s", "formatted") +// a.Truef(myBool, "error message %s", "formatted") func (a *Assertions) Truef(value bool, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1444,7 +1528,7 @@ func (a *Assertions) Truef(value bool, msg string, args ...interface{}) { // WithinDuration asserts that the two times are within duration delta of each other. // -// a.WithinDuration(time.Now(), time.Now(), 10*time.Second) +// a.WithinDuration(time.Now(), time.Now(), 10*time.Second) func (a *Assertions) WithinDuration(expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1454,7 +1538,7 @@ func (a *Assertions) WithinDuration(expected time.Time, actual time.Time, delta // WithinDurationf asserts that the two times are within duration delta of each other. // -// a.WithinDurationf(time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") +// a.WithinDurationf(time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") func (a *Assertions) WithinDurationf(expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1464,7 +1548,7 @@ func (a *Assertions) WithinDurationf(expected time.Time, actual time.Time, delta // WithinRange asserts that a time is within a time range (inclusive). // -// a.WithinRange(time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second)) +// a.WithinRange(time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second)) func (a *Assertions) WithinRange(actual time.Time, start time.Time, end time.Time, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() @@ -1474,7 +1558,7 @@ func (a *Assertions) WithinRange(actual time.Time, start time.Time, end time.Tim // WithinRangef asserts that a time is within a time range (inclusive). // -// a.WithinRangef(time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second), "error message %s", "formatted") +// a.WithinRangef(time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second), "error message %s", "formatted") func (a *Assertions) WithinRangef(actual time.Time, start time.Time, end time.Time, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() diff --git a/vendor/github.com/stretchr/testify/suite/doc.go b/vendor/github.com/stretchr/testify/suite/doc.go new file mode 100644 index 00000000000..8d55a3aa892 --- /dev/null +++ b/vendor/github.com/stretchr/testify/suite/doc.go @@ -0,0 +1,66 @@ +// Package suite contains logic for creating testing suite structs +// and running the methods on those structs as tests. The most useful +// piece of this package is that you can create setup/teardown methods +// on your testing suites, which will run before/after the whole suite +// or individual tests (depending on which interface(s) you +// implement). +// +// A testing suite is usually built by first extending the built-in +// suite functionality from suite.Suite in testify. Alternatively, +// you could reproduce that logic on your own if you wanted (you +// just need to implement the TestingSuite interface from +// suite/interfaces.go). +// +// After that, you can implement any of the interfaces in +// suite/interfaces.go to add setup/teardown functionality to your +// suite, and add any methods that start with "Test" to add tests. +// Methods that do not match any suite interfaces and do not begin +// with "Test" will not be run by testify, and can safely be used as +// helper methods. +// +// Once you've built your testing suite, you need to run the suite +// (using suite.Run from testify) inside any function that matches the +// identity that "go test" is already looking for (i.e. +// func(*testing.T)). +// +// Regular expression to select test suites specified command-line +// argument "-run". Regular expression to select the methods +// of test suites specified command-line argument "-m". +// Suite object has assertion methods. +// +// A crude example: +// +// // Basic imports +// import ( +// "testing" +// "github.com/stretchr/testify/assert" +// "github.com/stretchr/testify/suite" +// ) +// +// // Define the suite, and absorb the built-in basic suite +// // functionality from testify - including a T() method which +// // returns the current testing context +// type ExampleTestSuite struct { +// suite.Suite +// VariableThatShouldStartAtFive int +// } +// +// // Make sure that VariableThatShouldStartAtFive is set to five +// // before each test +// func (suite *ExampleTestSuite) SetupTest() { +// suite.VariableThatShouldStartAtFive = 5 +// } +// +// // All methods that begin with "Test" are run as tests within a +// // suite. +// func (suite *ExampleTestSuite) TestExample() { +// assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive) +// suite.Equal(5, suite.VariableThatShouldStartAtFive) +// } +// +// // In order for 'go test' to run this suite, we need to create +// // a normal test function and pass our suite to suite.Run +// func TestExampleTestSuite(t *testing.T) { +// suite.Run(t, new(ExampleTestSuite)) +// } +package suite diff --git a/vendor/github.com/stretchr/testify/suite/interfaces.go b/vendor/github.com/stretchr/testify/suite/interfaces.go new file mode 100644 index 00000000000..fed037d7f3e --- /dev/null +++ b/vendor/github.com/stretchr/testify/suite/interfaces.go @@ -0,0 +1,66 @@ +package suite + +import "testing" + +// TestingSuite can store and return the current *testing.T context +// generated by 'go test'. +type TestingSuite interface { + T() *testing.T + SetT(*testing.T) + SetS(suite TestingSuite) +} + +// SetupAllSuite has a SetupSuite method, which will run before the +// tests in the suite are run. +type SetupAllSuite interface { + SetupSuite() +} + +// SetupTestSuite has a SetupTest method, which will run before each +// test in the suite. +type SetupTestSuite interface { + SetupTest() +} + +// TearDownAllSuite has a TearDownSuite method, which will run after +// all the tests in the suite have been run. +type TearDownAllSuite interface { + TearDownSuite() +} + +// TearDownTestSuite has a TearDownTest method, which will run after +// each test in the suite. +type TearDownTestSuite interface { + TearDownTest() +} + +// BeforeTest has a function to be executed right before the test +// starts and receives the suite and test names as input +type BeforeTest interface { + BeforeTest(suiteName, testName string) +} + +// AfterTest has a function to be executed right after the test +// finishes and receives the suite and test names as input +type AfterTest interface { + AfterTest(suiteName, testName string) +} + +// WithStats implements HandleStats, a function that will be executed +// when a test suite is finished. The stats contain information about +// the execution of that suite and its tests. +type WithStats interface { + HandleStats(suiteName string, stats *SuiteInformation) +} + +// SetupSubTest has a SetupSubTest method, which will run before each +// subtest in the suite. +type SetupSubTest interface { + SetupSubTest() +} + +// TearDownSubTest has a TearDownSubTest method, which will run after +// each subtest in the suite have been run. +type TearDownSubTest interface { + TearDownSubTest() +} diff --git a/vendor/github.com/stretchr/testify/suite/stats.go b/vendor/github.com/stretchr/testify/suite/stats.go new file mode 100644 index 00000000000..261da37f78f --- /dev/null +++ b/vendor/github.com/stretchr/testify/suite/stats.go @@ -0,0 +1,46 @@ +package suite + +import "time" + +// SuiteInformation stats stores stats for the whole suite execution. +type SuiteInformation struct { + Start, End time.Time + TestStats map[string]*TestInformation +} + +// TestInformation stores information about the execution of each test. +type TestInformation struct { + TestName string + Start, End time.Time + Passed bool +} + +func newSuiteInformation() *SuiteInformation { + testStats := make(map[string]*TestInformation) + + return &SuiteInformation{ + TestStats: testStats, + } +} + +func (s SuiteInformation) start(testName string) { + s.TestStats[testName] = &TestInformation{ + TestName: testName, + Start: time.Now(), + } +} + +func (s SuiteInformation) end(testName string, passed bool) { + s.TestStats[testName].End = time.Now() + s.TestStats[testName].Passed = passed +} + +func (s SuiteInformation) Passed() bool { + for _, stats := range s.TestStats { + if !stats.Passed { + return false + } + } + + return true +} diff --git a/vendor/github.com/stretchr/testify/suite/suite.go b/vendor/github.com/stretchr/testify/suite/suite.go new file mode 100644 index 00000000000..8b4202d8906 --- /dev/null +++ b/vendor/github.com/stretchr/testify/suite/suite.go @@ -0,0 +1,248 @@ +package suite + +import ( + "flag" + "fmt" + "os" + "reflect" + "regexp" + "runtime/debug" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +var allTestsFilter = func(_, _ string) (bool, error) { return true, nil } +var matchMethod = flag.String("testify.m", "", "regular expression to select tests of the testify suite to run") + +// Suite is a basic testing suite with methods for storing and +// retrieving the current *testing.T context. +type Suite struct { + *assert.Assertions + + mu sync.RWMutex + require *require.Assertions + t *testing.T + + // Parent suite to have access to the implemented methods of parent struct + s TestingSuite +} + +// T retrieves the current *testing.T context. +func (suite *Suite) T() *testing.T { + suite.mu.RLock() + defer suite.mu.RUnlock() + return suite.t +} + +// SetT sets the current *testing.T context. +func (suite *Suite) SetT(t *testing.T) { + suite.mu.Lock() + defer suite.mu.Unlock() + suite.t = t + suite.Assertions = assert.New(t) + suite.require = require.New(t) +} + +// SetS needs to set the current test suite as parent +// to get access to the parent methods +func (suite *Suite) SetS(s TestingSuite) { + suite.s = s +} + +// Require returns a require context for suite. +func (suite *Suite) Require() *require.Assertions { + suite.mu.Lock() + defer suite.mu.Unlock() + if suite.require == nil { + suite.require = require.New(suite.T()) + } + return suite.require +} + +// Assert returns an assert context for suite. Normally, you can call +// `suite.NoError(expected, actual)`, but for situations where the embedded +// methods are overridden (for example, you might want to override +// assert.Assertions with require.Assertions), this method is provided so you +// can call `suite.Assert().NoError()`. +func (suite *Suite) Assert() *assert.Assertions { + suite.mu.Lock() + defer suite.mu.Unlock() + if suite.Assertions == nil { + suite.Assertions = assert.New(suite.T()) + } + return suite.Assertions +} + +func recoverAndFailOnPanic(t *testing.T) { + r := recover() + failOnPanic(t, r) +} + +func failOnPanic(t *testing.T, r interface{}) { + if r != nil { + t.Errorf("test panicked: %v\n%s", r, debug.Stack()) + t.FailNow() + } +} + +// Run provides suite functionality around golang subtests. It should be +// called in place of t.Run(name, func(t *testing.T)) in test suite code. +// The passed-in func will be executed as a subtest with a fresh instance of t. +// Provides compatibility with go test pkg -run TestSuite/TestName/SubTestName. +func (suite *Suite) Run(name string, subtest func()) bool { + oldT := suite.T() + + if setupSubTest, ok := suite.s.(SetupSubTest); ok { + setupSubTest.SetupSubTest() + } + + defer func() { + suite.SetT(oldT) + if tearDownSubTest, ok := suite.s.(TearDownSubTest); ok { + tearDownSubTest.TearDownSubTest() + } + }() + + return oldT.Run(name, func(t *testing.T) { + suite.SetT(t) + subtest() + }) +} + +// Run takes a testing suite and runs all of the tests attached +// to it. +func Run(t *testing.T, suite TestingSuite) { + defer recoverAndFailOnPanic(t) + + suite.SetT(t) + suite.SetS(suite) + + var suiteSetupDone bool + + var stats *SuiteInformation + if _, ok := suite.(WithStats); ok { + stats = newSuiteInformation() + } + + tests := []testing.InternalTest{} + methodFinder := reflect.TypeOf(suite) + suiteName := methodFinder.Elem().Name() + + for i := 0; i < methodFinder.NumMethod(); i++ { + method := methodFinder.Method(i) + + ok, err := methodFilter(method.Name) + if err != nil { + fmt.Fprintf(os.Stderr, "testify: invalid regexp for -m: %s\n", err) + os.Exit(1) + } + + if !ok { + continue + } + + if !suiteSetupDone { + if stats != nil { + stats.Start = time.Now() + } + + if setupAllSuite, ok := suite.(SetupAllSuite); ok { + setupAllSuite.SetupSuite() + } + + suiteSetupDone = true + } + + test := testing.InternalTest{ + Name: method.Name, + F: func(t *testing.T) { + parentT := suite.T() + suite.SetT(t) + defer recoverAndFailOnPanic(t) + defer func() { + r := recover() + + if stats != nil { + passed := !t.Failed() && r == nil + stats.end(method.Name, passed) + } + + if afterTestSuite, ok := suite.(AfterTest); ok { + afterTestSuite.AfterTest(suiteName, method.Name) + } + + if tearDownTestSuite, ok := suite.(TearDownTestSuite); ok { + tearDownTestSuite.TearDownTest() + } + + suite.SetT(parentT) + failOnPanic(t, r) + }() + + if setupTestSuite, ok := suite.(SetupTestSuite); ok { + setupTestSuite.SetupTest() + } + if beforeTestSuite, ok := suite.(BeforeTest); ok { + beforeTestSuite.BeforeTest(methodFinder.Elem().Name(), method.Name) + } + + if stats != nil { + stats.start(method.Name) + } + + method.Func.Call([]reflect.Value{reflect.ValueOf(suite)}) + }, + } + tests = append(tests, test) + } + if suiteSetupDone { + defer func() { + if tearDownAllSuite, ok := suite.(TearDownAllSuite); ok { + tearDownAllSuite.TearDownSuite() + } + + if suiteWithStats, measureStats := suite.(WithStats); measureStats { + stats.End = time.Now() + suiteWithStats.HandleStats(suiteName, stats) + } + }() + } + + runTests(t, tests) +} + +// Filtering method according to set regular expression +// specified command-line argument -m +func methodFilter(name string) (bool, error) { + if ok, _ := regexp.MatchString("^Test", name); !ok { + return false, nil + } + return regexp.MatchString(*matchMethod, name) +} + +func runTests(t testing.TB, tests []testing.InternalTest) { + if len(tests) == 0 { + t.Log("warning: no tests to run") + return + } + + r, ok := t.(runner) + if !ok { // backwards compatibility with Go 1.6 and below + if !testing.RunTests(allTestsFilter, tests) { + t.Fail() + } + return + } + + for _, test := range tests { + r.Run(test.Name, test.F) + } +} + +type runner interface { + Run(name string, f func(t *testing.T)) bool +} diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/common.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/common.go index 728be09d0e0..303e5505e41 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/common.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/common.go @@ -42,5 +42,5 @@ const ( type Filter func(*http.Request) bool func newTracer(tp trace.TracerProvider) trace.Tracer { - return tp.Tracer(instrumentationName, trace.WithInstrumentationVersion(SemVersion())) + return tp.Tracer(instrumentationName, trace.WithInstrumentationVersion(Version())) } diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/config.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/config.go index 0c3e48d5583..e4fa1b8d9d6 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/config.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/config.go @@ -21,7 +21,6 @@ import ( "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/metric" - "go.opentelemetry.io/otel/metric/global" "go.opentelemetry.io/otel/propagation" "go.opentelemetry.io/otel/trace" ) @@ -65,7 +64,7 @@ func (o optionFunc) apply(c *config) { func newConfig(opts ...Option) *config { c := &config{ Propagators: otel.GetTextMapPropagator(), - MeterProvider: global.MeterProvider(), + MeterProvider: otel.GetMeterProvider(), } for _, opt := range opts { opt.apply(c) @@ -78,7 +77,7 @@ func newConfig(opts ...Option) *config { c.Meter = c.MeterProvider.Meter( instrumentationName, - metric.WithInstrumentationVersion(SemVersion()), + metric.WithInstrumentationVersion(Version()), ) return c diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/handler.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/handler.go index d92aecc0a3d..f2f20e3b930 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/handler.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/handler.go @@ -24,7 +24,6 @@ import ( "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/metric" - "go.opentelemetry.io/otel/metric/instrument" "go.opentelemetry.io/otel/propagation" semconv "go.opentelemetry.io/otel/semconv/v1.17.0" "go.opentelemetry.io/otel/semconv/v1.17.0/httpconv" @@ -50,8 +49,8 @@ type Handler struct { writeEvent bool filters []Filter spanNameFormatter func(string, *http.Request) string - counters map[string]instrument.Int64Counter - valueRecorders map[string]instrument.Float64Histogram + counters map[string]metric.Int64Counter + valueRecorders map[string]metric.Float64Histogram publicEndpoint bool publicEndpointFn func(*http.Request) bool } @@ -101,8 +100,8 @@ func handleErr(err error) { } func (h *Handler) createMeasures() { - h.counters = make(map[string]instrument.Int64Counter) - h.valueRecorders = make(map[string]instrument.Float64Histogram) + h.counters = make(map[string]metric.Int64Counter) + h.valueRecorders = make(map[string]metric.Float64Histogram) requestBytesCounter, err := h.meter.Int64Counter(RequestContentLength) handleErr(err) @@ -219,13 +218,14 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if rww.statusCode > 0 { attributes = append(attributes, semconv.HTTPStatusCode(rww.statusCode)) } - h.counters[RequestContentLength].Add(ctx, bw.read, attributes...) - h.counters[ResponseContentLength].Add(ctx, rww.written, attributes...) + o := metric.WithAttributes(attributes...) + h.counters[RequestContentLength].Add(ctx, bw.read, o) + h.counters[ResponseContentLength].Add(ctx, rww.written, o) // Use floating point division here for higher precision (instead of Millisecond method). elapsedTime := float64(time.Since(requestStartTime)) / float64(time.Millisecond) - h.valueRecorders[ServerLatency].Record(ctx, elapsedTime, attributes...) + h.valueRecorders[ServerLatency].Record(ctx, elapsedTime, o) } func setAfterServeAttributes(span trace.Span, read, wrote int64, statusCode int, rerr, werr error) { diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/version.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/version.go index 8a55855b9c7..bbcbb741607 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/version.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/version.go @@ -16,11 +16,13 @@ package otelhttp // import "go.opentelemetry.io/contrib/instrumentation/net/http // Version is the current release version of the otelhttp instrumentation. func Version() string { - return "0.40.0" + return "0.42.0" // This string is updated by the pre_release.sh script during release } // SemVersion is the semantic version to be supplied to tracer/meter creation. +// +// Deprecated: Use [Version] instead. func SemVersion() string { - return "semver:" + Version() + return Version() } diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/wrap.go b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/wrap.go index da6468c4e59..11a35ed167f 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/wrap.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/wrap.go @@ -50,7 +50,7 @@ func (w *bodyWrapper) Close() error { var _ http.ResponseWriter = &respWriterWrapper{} // respWriterWrapper wraps a http.ResponseWriter in order to track the number of -// bytes written, the last error, and to catch the returned statusCode +// bytes written, the last error, and to catch the first written statusCode. // TODO: The wrapped http.ResponseWriter doesn't implement any of the optional // types (http.Hijacker, http.Pusher, http.CloseNotifier, http.Flusher, etc) // that may be useful when using it in real life situations. @@ -85,11 +85,15 @@ func (w *respWriterWrapper) Write(p []byte) (int, error) { return n, err } +// WriteHeader persists initial statusCode for span attribution. +// All calls to WriteHeader will be propagated to the underlying ResponseWriter +// and will persist the statusCode from the first call. +// Blocking consecutive calls to WriteHeader alters expected behavior and will +// remove warning logs from net/http where developers will notice incorrect handler implementations. func (w *respWriterWrapper) WriteHeader(statusCode int) { - if w.wroteHeader { - return + if !w.wroteHeader { + w.wroteHeader = true + w.statusCode = statusCode } - w.wroteHeader = true - w.statusCode = statusCode w.ResponseWriter.WriteHeader(statusCode) } diff --git a/vendor/go.opentelemetry.io/otel/.codespellignore b/vendor/go.opentelemetry.io/otel/.codespellignore new file mode 100644 index 00000000000..ae6a3bcf12c --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/.codespellignore @@ -0,0 +1,5 @@ +ot +fo +te +collison +consequentially diff --git a/vendor/go.opentelemetry.io/otel/.codespellrc b/vendor/go.opentelemetry.io/otel/.codespellrc new file mode 100644 index 00000000000..4afbb1fb3bd --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/.codespellrc @@ -0,0 +1,10 @@ +# https://github.com/codespell-project/codespell +[codespell] +builtin = clear,rare,informal +check-filenames = +check-hidden = +ignore-words = .codespellignore +interactive = 1 +skip = .git,go.mod,go.sum,semconv,venv,.tools +uri-ignore-words-list = * +write = diff --git a/vendor/go.opentelemetry.io/otel/.gitignore b/vendor/go.opentelemetry.io/otel/.gitignore index 0b605b3d67d..aa699376225 100644 --- a/vendor/go.opentelemetry.io/otel/.gitignore +++ b/vendor/go.opentelemetry.io/otel/.gitignore @@ -2,11 +2,14 @@ Thumbs.db .tools/ +venv/ .idea/ .vscode/ *.iml *.so coverage.* +go.work +go.work.sum gen/ diff --git a/vendor/go.opentelemetry.io/otel/.golangci.yml b/vendor/go.opentelemetry.io/otel/.golangci.yml index 0f099f57595..dbb6670b397 100644 --- a/vendor/go.opentelemetry.io/otel/.golangci.yml +++ b/vendor/go.opentelemetry.io/otel/.golangci.yml @@ -85,6 +85,8 @@ linters-settings: - "**/internal/matchers/*.go" godot: exclude: + # Exclude links. + - '^ *\[[^]]+\]:' # Exclude sentence fragments for lists. - '^[ ]*[-•]' # Exclude sentences prefixing a list. @@ -111,7 +113,7 @@ linters-settings: - name: constant-logical-expr disabled: false # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#context-as-argument - # TODO (#3372) reenable linter when it is compatible. https://github.com/golangci/golangci-lint/issues/3280 + # TODO (#3372) re-enable linter when it is compatible. https://github.com/golangci/golangci-lint/issues/3280 - name: context-as-argument disabled: true arguments: diff --git a/vendor/go.opentelemetry.io/otel/CHANGELOG.md b/vendor/go.opentelemetry.io/otel/CHANGELOG.md index 1d9726f60b6..d9f145f86d7 100644 --- a/vendor/go.opentelemetry.io/otel/CHANGELOG.md +++ b/vendor/go.opentelemetry.io/otel/CHANGELOG.md @@ -8,6 +8,196 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm ## [Unreleased] +## [1.16.0/0.39.0] 2023-05-18 + +This release contains the first stable release of the OpenTelemetry Go [metric API]. +Our project stability guarantees now apply to the `go.opentelemetry.io/otel/metric` package. +See our [versioning policy](VERSIONING.md) for more information about these stability guarantees. + +### Added + +- The `go.opentelemetry.io/otel/semconv/v1.19.0` package. + The package contains semantic conventions from the `v1.19.0` version of the OpenTelemetry specification. (#3848) +- The `go.opentelemetry.io/otel/semconv/v1.20.0` package. + The package contains semantic conventions from the `v1.20.0` version of the OpenTelemetry specification. (#4078) + +### Changed + +- Use `strings.Cut()` instead of `string.SplitN()` for better readability and memory use. (#4049) + +### Removed + +- The deprecated `go.opentelemetry.io/otel/metric/instrument` package is removed. + Use `go.opentelemetry.io/otel/metric` instead. (#4055) + +### Fixed + +- Fix build for BSD based systems in `go.opentelemetry.io/otel/sdk/resource`. (#4077) + +## [1.16.0-rc.1/0.39.0-rc.1] 2023-05-03 + +This is a release candidate for the v1.16.0/v0.39.0 release. +That release is expected to include the `v1` release of the OpenTelemetry Go metric API and will provide stability guarantees of that API. +See our [versioning policy](VERSIONING.md) for more information about these stability guarantees. + +### Added + +- Support global `MeterProvider` in `go.opentelemetry.io/otel`. (#4039) + - Use `Meter` for a `metric.Meter` from the global `metric.MeterProvider`. + - Use `GetMeterProivder` for a global `metric.MeterProvider`. + - Use `SetMeterProivder` to set the global `metric.MeterProvider`. + +### Changed + +- Move the `go.opentelemetry.io/otel/metric` module to the `stable-v1` module set. + This stages the metric API to be released as a stable module. (#4038) + +### Removed + +- The `go.opentelemetry.io/otel/metric/global` package is removed. + Use `go.opentelemetry.io/otel` instead. (#4039) + +## [1.15.1/0.38.1] 2023-05-02 + +### Fixed + +- Remove unused imports from `sdk/resource/host_id_bsd.go` which caused build failures. (#4040, #4041) + +## [1.15.0/0.38.0] 2023-04-27 + +### Added + +- The `go.opentelemetry.io/otel/metric/embedded` package. (#3916) +- The `Version` function to `go.opentelemetry.io/otel/sdk` to return the SDK version. (#3949) +- Add a `WithNamespace` option to `go.opentelemetry.io/otel/exporters/prometheus` to allow users to prefix metrics with a namespace. (#3970) +- The following configuration types were added to `go.opentelemetry.io/otel/metric/instrument` to be used in the configuration of measurement methods. (#3971) + - The `AddConfig` used to hold configuration for addition measurements + - `NewAddConfig` used to create a new `AddConfig` + - `AddOption` used to configure an `AddConfig` + - The `RecordConfig` used to hold configuration for recorded measurements + - `NewRecordConfig` used to create a new `RecordConfig` + - `RecordOption` used to configure a `RecordConfig` + - The `ObserveConfig` used to hold configuration for observed measurements + - `NewObserveConfig` used to create a new `ObserveConfig` + - `ObserveOption` used to configure an `ObserveConfig` +- `WithAttributeSet` and `WithAttributes` are added to `go.opentelemetry.io/otel/metric/instrument`. + They return an option used during a measurement that defines the attribute Set associated with the measurement. (#3971) +- The `Version` function to `go.opentelemetry.io/otel/exporters/otlp/otlpmetric` to return the OTLP metrics client version. (#3956) +- The `Version` function to `go.opentelemetry.io/otel/exporters/otlp/otlptrace` to return the OTLP trace client version. (#3956) + +### Changed + +- The `Extrema` in `go.opentelemetry.io/otel/sdk/metric/metricdata` is redefined with a generic argument of `[N int64 | float64]`. (#3870) +- Update all exported interfaces from `go.opentelemetry.io/otel/metric` to embed their corresponding interface from `go.opentelemetry.io/otel/metric/embedded`. + This adds an implementation requirement to set the interface default behavior for unimplemented methods. (#3916) +- Move No-Op implementation from `go.opentelemetry.io/otel/metric` into its own package `go.opentelemetry.io/otel/metric/noop`. (#3941) + - `metric.NewNoopMeterProvider` is replaced with `noop.NewMeterProvider` +- Add all the methods from `"go.opentelemetry.io/otel/trace".SpanContext` to `bridgeSpanContext` by embedding `otel.SpanContext` in `bridgeSpanContext`. (#3966) +- Wrap `UploadMetrics` error in `go.opentelemetry.io/otel/exporters/otlp/otlpmetric/` to improve error message when encountering generic grpc errors. (#3974) +- The measurement methods for all instruments in `go.opentelemetry.io/otel/metric/instrument` accept an option instead of the variadic `"go.opentelemetry.io/otel/attribute".KeyValue`. (#3971) + - The `Int64Counter.Add` method now accepts `...AddOption` + - The `Float64Counter.Add` method now accepts `...AddOption` + - The `Int64UpDownCounter.Add` method now accepts `...AddOption` + - The `Float64UpDownCounter.Add` method now accepts `...AddOption` + - The `Int64Histogram.Record` method now accepts `...RecordOption` + - The `Float64Histogram.Record` method now accepts `...RecordOption` + - The `Int64Observer.Observe` method now accepts `...ObserveOption` + - The `Float64Observer.Observe` method now accepts `...ObserveOption` +- The `Observer` methods in `go.opentelemetry.io/otel/metric` accept an option instead of the variadic `"go.opentelemetry.io/otel/attribute".KeyValue`. (#3971) + - The `Observer.ObserveInt64` method now accepts `...ObserveOption` + - The `Observer.ObserveFloat64` method now accepts `...ObserveOption` +- Move global metric back to `go.opentelemetry.io/otel/metric/global` from `go.opentelemetry.io/otel`. (#3986) + +### Fixed + +- `TracerProvider` allows calling `Tracer()` while it's shutting down. + It used to deadlock. (#3924) +- Use the SDK version for the Telemetry SDK resource detector in `go.opentelemetry.io/otel/sdk/resource`. (#3949) +- Fix a data race in `SpanProcessor` returned by `NewSimpleSpanProcessor` in `go.opentelemetry.io/otel/sdk/trace`. (#3951) +- Automatically figure out the default aggregation with `aggregation.Default`. (#3967) + +### Deprecated + +- The `go.opentelemetry.io/otel/metric/instrument` package is deprecated. + Use the equivalent types added to `go.opentelemetry.io/otel/metric` instead. (#4018) + +## [1.15.0-rc.2/0.38.0-rc.2] 2023-03-23 + +This is a release candidate for the v1.15.0/v0.38.0 release. +That release will include the `v1` release of the OpenTelemetry Go metric API and will provide stability guarantees of that API. +See our [versioning policy](VERSIONING.md) for more information about these stability guarantees. + +### Added + +- The `WithHostID` option to `go.opentelemetry.io/otel/sdk/resource`. (#3812) +- The `WithoutTimestamps` option to `go.opentelemetry.io/otel/exporters/stdout/stdoutmetric` to sets all timestamps to zero. (#3828) +- The new `Exemplar` type is added to `go.opentelemetry.io/otel/sdk/metric/metricdata`. + Both the `DataPoint` and `HistogramDataPoint` types from that package have a new field of `Exemplars` containing the sampled exemplars for their timeseries. (#3849) +- Configuration for each metric instrument in `go.opentelemetry.io/otel/sdk/metric/instrument`. (#3895) +- The internal logging introduces a warning level verbosity equal to `V(1)`. (#3900) +- Added a log message warning about usage of `SimpleSpanProcessor` in production environments. (#3854) + +### Changed + +- Optimize memory allocation when creation a new `Set` using `NewSet` or `NewSetWithFiltered` in `go.opentelemetry.io/otel/attribute`. (#3832) +- Optimize memory allocation when creation new metric instruments in `go.opentelemetry.io/otel/sdk/metric`. (#3832) +- Avoid creating new objects on all calls to `WithDeferredSetup` and `SkipContextSetup` in OpenTracing bridge. (#3833) +- The `New` and `Detect` functions from `go.opentelemetry.io/otel/sdk/resource` return errors that wrap underlying errors instead of just containing the underlying error strings. (#3844) +- Both the `Histogram` and `HistogramDataPoint` are redefined with a generic argument of `[N int64 | float64]` in `go.opentelemetry.io/otel/sdk/metric/metricdata`. (#3849) +- The metric `Export` interface from `go.opentelemetry.io/otel/sdk/metric` accepts a `*ResourceMetrics` instead of `ResourceMetrics`. (#3853) +- Rename `Asynchronous` to `Observable` in `go.opentelemetry.io/otel/metric/instrument`. (#3892) +- Rename `Int64ObserverOption` to `Int64ObservableOption` in `go.opentelemetry.io/otel/metric/instrument`. (#3895) +- Rename `Float64ObserverOption` to `Float64ObservableOption` in `go.opentelemetry.io/otel/metric/instrument`. (#3895) +- The internal logging changes the verbosity level of info to `V(4)`, the verbosity level of debug to `V(8)`. (#3900) + +### Fixed + +- `TracerProvider` consistently doesn't allow to register a `SpanProcessor` after shutdown. (#3845) + +### Removed + +- The deprecated `go.opentelemetry.io/otel/metric/global` package is removed. (#3829) +- The unneeded `Synchronous` interface in `go.opentelemetry.io/otel/metric/instrument` was removed. (#3892) +- The `Float64ObserverConfig` and `NewFloat64ObserverConfig` in `go.opentelemetry.io/otel/sdk/metric/instrument`. + Use the added `float64` instrument configuration instead. (#3895) +- The `Int64ObserverConfig` and `NewInt64ObserverConfig` in `go.opentelemetry.io/otel/sdk/metric/instrument`. + Use the added `int64` instrument configuration instead. (#3895) +- The `NewNoopMeter` function in `go.opentelemetry.io/otel/metric`, use `NewMeterProvider().Meter("")` instead. (#3893) + +## [1.15.0-rc.1/0.38.0-rc.1] 2023-03-01 + +This is a release candidate for the v1.15.0/v0.38.0 release. +That release will include the `v1` release of the OpenTelemetry Go metric API and will provide stability guarantees of that API. +See our [versioning policy](VERSIONING.md) for more information about these stability guarantees. + +This release drops the compatibility guarantee of [Go 1.18]. + +### Added + +- Support global `MeterProvider` in `go.opentelemetry.io/otel`. (#3818) + - Use `Meter` for a `metric.Meter` from the global `metric.MeterProvider`. + - Use `GetMeterProivder` for a global `metric.MeterProvider`. + - Use `SetMeterProivder` to set the global `metric.MeterProvider`. + +### Changed + +- Dropped compatibility testing for [Go 1.18]. + The project no longer guarantees support for this version of Go. (#3813) + +### Fixed + +- Handle empty environment variable as it they were not set. (#3764) +- Clarify the `httpconv` and `netconv` packages in `go.opentelemetry.io/otel/semconv/*` provide tracing semantic conventions. (#3823) + +### Deprecated + +- The `go.opentelemetry.io/otel/metric/global` package is deprecated. + Use `go.opentelemetry.io/otel` instead. (#3818) + +### Removed + +- The deprecated `go.opentelemetry.io/otel/metric/unit` package is removed. (#3814) + ## [1.14.0/0.37.0/0.0.4] 2023-02-27 This release is the last to support [Go 1.18]. @@ -121,7 +311,7 @@ The next release will require at least [Go 1.19]. - The `go.opentelemetry.io/otel/semconv/v1.16.0` package. The package contains semantic conventions from the `v1.16.0` version of the OpenTelemetry specification. (#3579) - Metric instruments to `go.opentelemetry.io/otel/metric/instrument`. - These instruments are use as replacements of the depreacted `go.opentelemetry.io/otel/metric/instrument/{asyncfloat64,asyncint64,syncfloat64,syncint64}` packages.(#3575, #3586) + These instruments are use as replacements of the deprecated `go.opentelemetry.io/otel/metric/instrument/{asyncfloat64,asyncint64,syncfloat64,syncint64}` packages.(#3575, #3586) - `Float64ObservableCounter` replaces the `asyncfloat64.Counter` - `Float64ObservableUpDownCounter` replaces the `asyncfloat64.UpDownCounter` - `Float64ObservableGauge` replaces the `asyncfloat64.Gauge` @@ -144,7 +334,7 @@ The next release will require at least [Go 1.19]. ### Changed - Jaeger and Zipkin exporter use `github.com/go-logr/logr` as the logging interface, and add the `WithLogr` option. (#3497, #3500) -- Instrument configuration in `go.opentelemetry.io/otel/metric/instrument` is split into specific options and confguration based on the instrument type. (#3507) +- Instrument configuration in `go.opentelemetry.io/otel/metric/instrument` is split into specific options and configuration based on the instrument type. (#3507) - Use the added `Int64Option` type to configure instruments from `go.opentelemetry.io/otel/metric/instrument/syncint64`. - Use the added `Float64Option` type to configure instruments from `go.opentelemetry.io/otel/metric/instrument/syncfloat64`. - Use the added `Int64ObserverOption` type to configure instruments from `go.opentelemetry.io/otel/metric/instrument/asyncint64`. @@ -157,7 +347,7 @@ The next release will require at least [Go 1.19]. - The `Shutdown` method of the `"go.opentelemetry.io/otel/sdk/trace".TracerProvider` releases all computational resources when called the first time. (#3551) - The `Sampler` returned from `TraceIDRatioBased` `go.opentelemetry.io/otel/sdk/trace` now uses the rightmost bits for sampling decisions. This fixes random sampling when using ID generators like `xray.IDGenerator` and increasing parity with other language implementations. (#3557) -- Errors from `go.opentelemetry.io/otel/exporters/otlp/otlptrace` exporters are wrapped in erros identifying their signal name. +- Errors from `go.opentelemetry.io/otel/exporters/otlp/otlptrace` exporters are wrapped in errors identifying their signal name. Existing users of the exporters attempting to identify specific errors will need to use `errors.Unwrap()` to get the underlying error. (#3516) - Exporters from `go.opentelemetry.io/otel/exporters/otlp` will print the final retryable error message when attempts to retry time out. (#3514) - The instrument kind names in `go.opentelemetry.io/otel/sdk/metric` are updated to match the API. (#3562) @@ -266,7 +456,7 @@ The next release will require at least [Go 1.19]. - Asynchronous counters (`Counter` and `UpDownCounter`) from the metric SDK now produce delta sums when configured with delta temporality. (#3398) - Exported `Status` codes in the `go.opentelemetry.io/otel/exporters/zipkin` exporter are now exported as all upper case values. (#3340) - `Aggregation`s from `go.opentelemetry.io/otel/sdk/metric` with no data are not exported. (#3394, #3436) -- Reenabled Attribute Filters in the Metric SDK. (#3396) +- Re-enabled Attribute Filters in the Metric SDK. (#3396) - Asynchronous callbacks are only called if they are registered with at least one instrument that does not use drop aggragation. (#3408) - Do not report empty partial-success responses in the `go.opentelemetry.io/otel/exporters/otlp` exporters. (#3438, #3432) - Handle partial success responses in `go.opentelemetry.io/otel/exporters/otlp/otlpmetric` exporters. (#3162, #3440) @@ -847,7 +1037,7 @@ This release includes an API and SDK for the tracing signal that will comply wit - Setting the global `ErrorHandler` with `"go.opentelemetry.io/otel".SetErrorHandler` multiple times is now supported. (#2160, #2140) - The `"go.opentelemetry.io/otel/attribute".Any` function now supports `int32` values. (#2169) - Multiple calls to `"go.opentelemetry.io/otel/sdk/metric/controller/basic".WithResource()` are handled correctly, and when no resources are provided `"go.opentelemetry.io/otel/sdk/resource".Default()` is used. (#2120) -- The `WithoutTimestamps` option for the `go.opentelemetry.io/otel/exporters/stdout/stdouttrace` exporter causes the exporter to correctly ommit timestamps. (#2195) +- The `WithoutTimestamps` option for the `go.opentelemetry.io/otel/exporters/stdout/stdouttrace` exporter causes the exporter to correctly omit timestamps. (#2195) - Fixed typos in resources.go. (#2201) ## [1.0.0-RC2] - 2021-07-26 @@ -1293,7 +1483,7 @@ with major version 0. - `NewGRPCDriver` function returns a `ProtocolDriver` that maintains a single gRPC connection to the collector. (#1369) - Added documentation about the project's versioning policy. (#1388) - Added `NewSplitDriver` for OTLP exporter that allows sending traces and metrics to different endpoints. (#1418) -- Added codeql worfklow to GitHub Actions (#1428) +- Added codeql workflow to GitHub Actions (#1428) - Added Gosec workflow to GitHub Actions (#1429) - Add new HTTP driver for OTLP exporter in `exporters/otlp/otlphttp`. Currently it only supports the binary protobuf payloads. (#1420) - Add an OpenCensus exporter bridge. (#1444) @@ -2136,7 +2326,7 @@ There is still a possibility of breaking changes. ### Fixed -- Use stateful batcher on Prometheus exporter fixing regresion introduced in #395. (#428) +- Use stateful batcher on Prometheus exporter fixing regression introduced in #395. (#428) ## [0.2.1] - 2020-01-08 @@ -2302,7 +2492,13 @@ It contains api and sdk for trace and meter. - CircleCI build CI manifest files. - CODEOWNERS file to track owners of this project. -[Unreleased]: https://github.com/open-telemetry/opentelemetry-go/compare/v1.14.0...HEAD +[Unreleased]: https://github.com/open-telemetry/opentelemetry-go/compare/v1.16.0...HEAD +[1.16.0/0.39.0]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.16.0 +[1.16.0-rc.1/0.39.0-rc.1]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.16.0-rc.1 +[1.15.1/0.38.1]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.15.1 +[1.15.0/0.38.0]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.15.0 +[1.15.0-rc.2/0.38.0-rc.2]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.15.0-rc.2 +[1.15.0-rc.1/0.38.0-rc.1]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.15.0-rc.1 [1.14.0/0.37.0/0.0.4]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.14.0 [1.13.0/0.36.0]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.13.0 [1.12.0/0.35.0]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.12.0 @@ -2367,3 +2563,5 @@ It contains api and sdk for trace and meter. [Go 1.20]: https://go.dev/doc/go1.20 [Go 1.19]: https://go.dev/doc/go1.19 [Go 1.18]: https://go.dev/doc/go1.18 + +[metric API]:https://pkg.go.dev/go.opentelemetry.io/otel/metric diff --git a/vendor/go.opentelemetry.io/otel/CODEOWNERS b/vendor/go.opentelemetry.io/otel/CODEOWNERS index c4012ed6ca1..f6f6a313b5b 100644 --- a/vendor/go.opentelemetry.io/otel/CODEOWNERS +++ b/vendor/go.opentelemetry.io/otel/CODEOWNERS @@ -12,6 +12,6 @@ # https://help.github.com/en/articles/about-code-owners # -* @jmacd @MrAlias @Aneurysm9 @evantorrie @XSAM @dashpole @MadVikingGod @pellared @hanyuancheung @dmathieu +* @MrAlias @Aneurysm9 @evantorrie @XSAM @dashpole @MadVikingGod @pellared @hanyuancheung @dmathieu CODEOWNERS @MrAlias @Aneurysm9 @MadVikingGod diff --git a/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md b/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md index a6928bfdff8..b2df5de34a6 100644 --- a/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md +++ b/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md @@ -6,7 +6,7 @@ OpenTelemetry repo for information on this and other language SIGs. See the [public meeting -notes](https://docs.google.com/document/d/1A63zSWX0x2CyCK_LoNhmQC4rqhLpYXJzXbEPDUQ2n6w/edit#heading=h.9tngw7jdwd6b) +notes](https://docs.google.com/document/d/1E5e7Ld0NuU1iVvf-42tOBpu2VBBLYnh73GJuITGJTTU/edit) for a summary description of past meetings. To request edit access, join the meeting or get in touch on [Slack](https://cloud-native.slack.com/archives/C01NPAXACKT). @@ -28,6 +28,11 @@ precommit` - the `precommit` target is the default). The `precommit` target also fixes the formatting of the code and checks the status of the go module files. +Additionally, there is a `codespell` target that checks for common +typos in the code. It is not run by default, but you can run it +manually with `make codespell`. It will set up a virtual environment +in `venv` and install `codespell` there. + If after running `make precommit` the output of `git status` contains `nothing to commit, working tree clean` then it means that everything is up-to-date and properly formatted. @@ -94,38 +99,66 @@ request ID to the entry you added to `CHANGELOG.md`. ### How to Get PRs Merged -A PR is considered to be **ready to merge** when: - -* It has received two approvals from Collaborators/Maintainers (at - different companies). This is not enforced through technical means - and a PR may be **ready to merge** with a single approval if the change - and its approach have been discussed and consensus reached. -* Feedback has been addressed. -* Any substantive changes to your PR will require that you clear any prior - Approval reviews, this includes changes resulting from other feedback. Unless - the approver explicitly stated that their approval will persist across - changes it should be assumed that the PR needs their review again. Other - project members (e.g. approvers, maintainers) can help with this if there are - any questions or if you forget to clear reviews. -* It has been open for review for at least one working day. This gives - people reasonable time to review. -* Trivial changes (typo, cosmetic, doc, etc.) do not have to wait for - one day and may be merged with a single Maintainer's approval. -* `CHANGELOG.md` has been updated to reflect what has been - added, changed, removed, or fixed. -* `README.md` has been updated if necessary. -* Urgent fix can take exception as long as it has been actively - communicated. - -Any Maintainer can merge the PR once it is **ready to merge**. +A PR is considered **ready to merge** when: + +* It has received two qualified approvals[^1]. + + This is not enforced through automation, but needs to be validated by the + maintainer merging. + * The qualified approvals need to be from [Approver]s/[Maintainer]s + affiliated with different companies. Two qualified approvals from + [Approver]s or [Maintainer]s affiliated with the same company counts as a + single qualified approval. + * PRs introducing changes that have already been discussed and consensus + reached only need one qualified approval. The discussion and resolution + needs to be linked to the PR. + * Trivial changes[^2] only need one qualified approval. + +* All feedback has been addressed. + * All PR comments and suggestions are resolved. + * All GitHub Pull Request reviews with a status of "Request changes" have + been addressed. Another review by the objecting reviewer with a different + status can be submitted to clear the original review, or the review can be + dismissed by a [Maintainer] when the issues from the original review have + been addressed. + * Any comments or reviews that cannot be resolved between the PR author and + reviewers can be submitted to the community [Approver]s and [Maintainer]s + during the weekly SIG meeting. If consensus is reached among the + [Approver]s and [Maintainer]s during the SIG meeting the objections to the + PR may be dismissed or resolved or the PR closed by a [Maintainer]. + * Any substantive changes to the PR require existing Approval reviews be + cleared unless the approver explicitly states that their approval persists + across changes. This includes changes resulting from other feedback. + [Approver]s and [Maintainer]s can help in clearing reviews and they should + be consulted if there are any questions. + +* The PR branch is up to date with the base branch it is merging into. + * To ensure this does not block the PR, it should be configured to allow + maintainers to update it. + +* It has been open for review for at least one working day. This gives people + reasonable time to review. + * Trivial changes[^2] do not have to wait for one day and may be merged with + a single [Maintainer]'s approval. + +* All required GitHub workflows have succeeded. +* Urgent fix can take exception as long as it has been actively communicated + among [Maintainer]s. + +Any [Maintainer] can merge the PR once the above criteria have been met. + +[^1]: A qualified approval is a GitHub Pull Request review with "Approve" + status from an OpenTelemetry Go [Approver] or [Maintainer]. +[^2]: Trivial changes include: typo corrections, cosmetic non-substantive + changes, documentation corrections or updates, dependency updates, etc. ## Design Choices As with other OpenTelemetry clients, opentelemetry-go follows the -[opentelemetry-specification](https://github.com/open-telemetry/opentelemetry-specification). +[OpenTelemetry Specification](https://opentelemetry.io/docs/specs/otel). It's especially valuable to read through the [library -guidelines](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/library-guidelines.md). +guidelines](https://opentelemetry.io/docs/specs/otel/library-guidelines). ### Focus on Capabilities, Not Structure Compliance @@ -216,7 +249,7 @@ Meaning a `config` from one package should not be directly used by another. The one exception is the API packages. The configs from the base API, eg. `go.opentelemetry.io/otel/trace.TracerConfig` and `go.opentelemetry.io/otel/metric.InstrumentConfig`, are intended to be consumed -by the SDK therefor it is expected that these are exported. +by the SDK therefore it is expected that these are exported. When a config is exported we want to maintain forward and backward compatibility, to achieve this no fields should be exported but should @@ -234,12 +267,12 @@ func newConfig(options ...Option) config { for _, option := range options { config = option.apply(config) } - // Preform any validation here. + // Perform any validation here. return config } ``` -If validation of the `config` options is also preformed this can return an +If validation of the `config` options is also performed this can return an error as well that is expected to be handled by the instantiation function or propagated to the user. @@ -438,7 +471,7 @@ their parameters appropriately named. #### Interface Stability All exported stable interfaces that include the following warning in their -doumentation are allowed to be extended with additional methods. +documentation are allowed to be extended with additional methods. > Warning: methods may be added to this interface in minor releases. @@ -500,27 +533,30 @@ interface that defines the specific functionality should be preferred. ## Approvers and Maintainers -Approvers: +### Approvers - [Evan Torrie](https://github.com/evantorrie), Verizon Media -- [Josh MacDonald](https://github.com/jmacd), LightStep - [Sam Xie](https://github.com/XSAM), Cisco/AppDynamics - [David Ashpole](https://github.com/dashpole), Google - [Robert Pająk](https://github.com/pellared), Splunk - [Chester Cheung](https://github.com/hanyuancheung), Tencent - [Damien Mathieu](https://github.com/dmathieu), Elastic -Maintainers: +### Maintainers - [Aaron Clawson](https://github.com/MadVikingGod), LightStep - [Anthony Mirabella](https://github.com/Aneurysm9), AWS - [Tyler Yahn](https://github.com/MrAlias), Splunk -Emeritus: +### Emeritus - [Gustavo Silva Paiva](https://github.com/paivagustavo), LightStep +- [Josh MacDonald](https://github.com/jmacd), LightStep ### Become an Approver or a Maintainer See the [community membership document in OpenTelemetry community repo](https://github.com/open-telemetry/community/blob/main/community-membership.md). + +[Approver]: #approvers +[Maintainer]: #maintainers diff --git a/vendor/go.opentelemetry.io/otel/Makefile b/vendor/go.opentelemetry.io/otel/Makefile index 0e6ffa284e1..26e4bed226f 100644 --- a/vendor/go.opentelemetry.io/otel/Makefile +++ b/vendor/go.opentelemetry.io/otel/Makefile @@ -25,8 +25,8 @@ TIMEOUT = 60 .DEFAULT_GOAL := precommit .PHONY: precommit ci -precommit: dependabot-generate license-check vanity-import-fix misspell go-mod-tidy golangci-lint-fix test-default -ci: dependabot-check license-check lint vanity-import-check build test-default check-clean-work-tree test-coverage +precommit: generate dependabot-generate license-check vanity-import-fix misspell go-mod-tidy golangci-lint-fix test-default +ci: generate dependabot-check license-check lint vanity-import-check build test-default check-clean-work-tree test-coverage # Tools @@ -74,9 +74,42 @@ $(TOOLS)/gojq: PACKAGE=github.com/itchyny/gojq/cmd/gojq .PHONY: tools tools: $(CROSSLINK) $(DBOTCONF) $(GOLANGCI_LINT) $(MISSPELL) $(GOCOVMERGE) $(STRINGER) $(PORTO) $(GOJQ) $(SEMCONVGEN) $(MULTIMOD) $(SEMCONVKIT) -# Build +# Virtualized python tools via docker + +# The directory where the virtual environment is created. +VENVDIR := venv + +# The directory where the python tools are installed. +PYTOOLS := $(VENVDIR)/bin + +# The pip executable in the virtual environment. +PIP := $(PYTOOLS)/pip + +# The directory in the docker image where the current directory is mounted. +WORKDIR := /workdir + +# The python image to use for the virtual environment. +PYTHONIMAGE := python:3.11.3-slim-bullseye + +# Run the python image with the current directory mounted. +DOCKERPY := docker run --rm -v "$(CURDIR):$(WORKDIR)" -w $(WORKDIR) $(PYTHONIMAGE) + +# Create a virtual environment for Python tools. +$(PYTOOLS): +# The `--upgrade` flag is needed to ensure that the virtual environment is +# created with the latest pip version. + @$(DOCKERPY) bash -c "python3 -m venv $(VENVDIR) && $(PIP) install --upgrade pip" -.PHONY: generate build +# Install python packages into the virtual environment. +$(PYTOOLS)/%: | $(PYTOOLS) + @$(DOCKERPY) $(PIP) install -r requirements.txt + +CODESPELL = $(PYTOOLS)/codespell +$(CODESPELL): PACKAGE=codespell + +# Generate + +.PHONY: generate generate: $(OTEL_GO_MOD_DIRS:%=generate/%) generate/%: DIR=$* @@ -85,7 +118,11 @@ generate/%: | $(STRINGER) $(PORTO) && cd $(DIR) \ && PATH="$(TOOLS):$${PATH}" $(GO) generate ./... && $(PORTO) -w . -build: generate $(OTEL_GO_MOD_DIRS:%=build/%) $(OTEL_GO_MOD_DIRS:%=build-tests/%) +# Build + +.PHONY: build + +build: $(OTEL_GO_MOD_DIRS:%=build/%) $(OTEL_GO_MOD_DIRS:%=build-tests/%) build/%: DIR=$* build/%: @echo "$(GO) build $(DIR)/..." \ @@ -156,7 +193,7 @@ go-mod-tidy/%: DIR=$* go-mod-tidy/%: | crosslink @echo "$(GO) mod tidy in $(DIR)" \ && cd $(DIR) \ - && $(GO) mod tidy -compat=1.18 + && $(GO) mod tidy -compat=1.19 .PHONY: lint-modules lint-modules: go-mod-tidy @@ -176,6 +213,10 @@ vanity-import-fix: | $(PORTO) misspell: | $(MISSPELL) @$(MISSPELL) -w $(ALL_DOCS) +.PHONY: codespell +codespell: | $(CODESPELL) + @$(DOCKERPY) $(CODESPELL) + .PHONY: license-check license-check: @licRes=$$(for f in $$(find . -type f \( -iname '*.go' -o -iname '*.sh' \) ! -path '**/third_party/*' ! -path './.git/*' ) ; do \ @@ -211,6 +252,7 @@ semconv-generate: | $(SEMCONVGEN) $(SEMCONVKIT) [ "$(TAG)" ] || ( echo "TAG unset: missing opentelemetry specification tag"; exit 1 ) [ "$(OTEL_SPEC_REPO)" ] || ( echo "OTEL_SPEC_REPO unset: missing path to opentelemetry specification repo"; exit 1 ) $(SEMCONVGEN) -i "$(OTEL_SPEC_REPO)/semantic_conventions/." --only=span -p conventionType=trace -f trace.go -t "$(SEMCONVPKG)/template.j2" -s "$(TAG)" + $(SEMCONVGEN) -i "$(OTEL_SPEC_REPO)/semantic_conventions/." --only=attribute_group -p conventionType=trace -f attribute_group.go -t "$(SEMCONVPKG)/template.j2" -s "$(TAG)" $(SEMCONVGEN) -i "$(OTEL_SPEC_REPO)/semantic_conventions/." --only=event -p conventionType=event -f event.go -t "$(SEMCONVPKG)/template.j2" -s "$(TAG)" $(SEMCONVGEN) -i "$(OTEL_SPEC_REPO)/semantic_conventions/." --only=resource -p conventionType=resource -f resource.go -t "$(SEMCONVPKG)/template.j2" -s "$(TAG)" $(SEMCONVKIT) -output "$(SEMCONVPKG)/$(TAG)" -tag "$(TAG)" diff --git a/vendor/go.opentelemetry.io/otel/README.md b/vendor/go.opentelemetry.io/otel/README.md index 878d87e58b9..e138a8a07f4 100644 --- a/vendor/go.opentelemetry.io/otel/README.md +++ b/vendor/go.opentelemetry.io/otel/README.md @@ -14,7 +14,7 @@ It provides a set of APIs to directly measure performance and behavior of your s | Signal | Status | Project | | ------- | ---------- | ------- | | Traces | Stable | N/A | -| Metrics | Alpha | N/A | +| Metrics | Beta | N/A | | Logs | Frozen [1] | N/A | - [1]: The Logs signal development is halted for this project while we develop both Traces and Metrics. @@ -52,19 +52,14 @@ Currently, this project supports the following environments. | ------- | ---------- | ------------ | | Ubuntu | 1.20 | amd64 | | Ubuntu | 1.19 | amd64 | -| Ubuntu | 1.18 | amd64 | | Ubuntu | 1.20 | 386 | | Ubuntu | 1.19 | 386 | -| Ubuntu | 1.18 | 386 | | MacOS | 1.20 | amd64 | | MacOS | 1.19 | amd64 | -| MacOS | 1.18 | amd64 | | Windows | 1.20 | amd64 | | Windows | 1.19 | amd64 | -| Windows | 1.18 | amd64 | | Windows | 1.20 | 386 | | Windows | 1.19 | 386 | -| Windows | 1.18 | 386 | While this project should work for other systems, no compatibility guarantees are made for those systems currently. diff --git a/vendor/go.opentelemetry.io/otel/RELEASING.md b/vendor/go.opentelemetry.io/otel/RELEASING.md index 77d56c93651..5e6daf6c48e 100644 --- a/vendor/go.opentelemetry.io/otel/RELEASING.md +++ b/vendor/go.opentelemetry.io/otel/RELEASING.md @@ -2,10 +2,10 @@ ## Semantic Convention Generation -New versions of the [OpenTelemetry specification] mean new versions of the `semconv` package need to be generated. +New versions of the [OpenTelemetry Specification] mean new versions of the `semconv` package need to be generated. The `semconv-generate` make target is used for this. -1. Checkout a local copy of the [OpenTelemetry specification] to the desired release tag. +1. Checkout a local copy of the [OpenTelemetry Specification] to the desired release tag. 2. Pull the latest `otel/semconvgen` image: `docker pull otel/semconvgen:latest` 3. Run the `make semconv-generate ...` target from this repository. @@ -14,7 +14,6 @@ For example, ```sh export TAG="v1.13.0" # Change to the release version you are generating. export OTEL_SPEC_REPO="/absolute/path/to/opentelemetry-specification" -git -C "$OTEL_SPEC_REPO" checkout "tags/$TAG" -b "$TAG" docker pull otel/semconvgen:latest make semconv-generate # Uses the exported TAG and OTEL_SPEC_REPO. ``` @@ -124,4 +123,4 @@ Once verified be sure to [make a release for the `contrib` repository](https://g Update [the documentation](./website_docs) for [the OpenTelemetry website](https://opentelemetry.io/docs/go/). Importantly, bump any package versions referenced to be the latest one you just released and ensure all code examples still compile and are accurate. -[OpenTelemetry specification]: https://github.com/open-telemetry/opentelemetry-specification +[OpenTelemetry Specification]: https://github.com/open-telemetry/opentelemetry-specification diff --git a/vendor/go.opentelemetry.io/otel/attribute/set.go b/vendor/go.opentelemetry.io/otel/attribute/set.go index 26be5983223..b976367e46d 100644 --- a/vendor/go.opentelemetry.io/otel/attribute/set.go +++ b/vendor/go.opentelemetry.io/otel/attribute/set.go @@ -18,6 +18,7 @@ import ( "encoding/json" "reflect" "sort" + "sync" ) type ( @@ -62,6 +63,12 @@ var ( iface: [0]KeyValue{}, }, } + + // sortables is a pool of Sortables used to create Sets with a user does + // not provide one. + sortables = sync.Pool{ + New: func() interface{} { return new(Sortable) }, + } ) // EmptySet returns a reference to a Set with no elements. @@ -91,7 +98,7 @@ func (l *Set) Len() int { // Get returns the KeyValue at ordered position idx in this set. func (l *Set) Get(idx int) (KeyValue, bool) { - if l == nil { + if l == nil || !l.equivalent.Valid() { return KeyValue{}, false } value := l.equivalent.reflectValue() @@ -107,7 +114,7 @@ func (l *Set) Get(idx int) (KeyValue, bool) { // Value returns the value of a specified key in this set. func (l *Set) Value(k Key) (Value, bool) { - if l == nil { + if l == nil || !l.equivalent.Valid() { return Value{}, false } rValue := l.equivalent.reflectValue() @@ -191,7 +198,9 @@ func NewSet(kvs ...KeyValue) Set { if len(kvs) == 0 { return empty() } - s, _ := NewSetWithSortableFiltered(kvs, new(Sortable), nil) + srt := sortables.Get().(*Sortable) + s, _ := NewSetWithSortableFiltered(kvs, srt, nil) + sortables.Put(srt) return s } @@ -218,7 +227,10 @@ func NewSetWithFiltered(kvs []KeyValue, filter Filter) (Set, []KeyValue) { if len(kvs) == 0 { return empty(), nil } - return NewSetWithSortableFiltered(kvs, new(Sortable), filter) + srt := sortables.Get().(*Sortable) + s, filtered := NewSetWithSortableFiltered(kvs, srt, filter) + sortables.Put(srt) + return s, filtered } // NewSetWithSortableFiltered returns a new Set. diff --git a/vendor/go.opentelemetry.io/otel/baggage/baggage.go b/vendor/go.opentelemetry.io/otel/baggage/baggage.go index a36db8f8d85..46e523a80e4 100644 --- a/vendor/go.opentelemetry.io/otel/baggage/baggage.go +++ b/vendor/go.opentelemetry.io/otel/baggage/baggage.go @@ -289,45 +289,37 @@ func parseMember(member string) (Member, error) { props properties ) - parts := strings.SplitN(member, propertyDelimiter, 2) - switch len(parts) { - case 2: + keyValue, properties, found := strings.Cut(member, propertyDelimiter) + if found { // Parse the member properties. - for _, pStr := range strings.Split(parts[1], propertyDelimiter) { + for _, pStr := range strings.Split(properties, propertyDelimiter) { p, err := parseProperty(pStr) if err != nil { return newInvalidMember(), err } props = append(props, p) } - fallthrough - case 1: - // Parse the member key/value pair. - - // Take into account a value can contain equal signs (=). - kv := strings.SplitN(parts[0], keyValueDelimiter, 2) - if len(kv) != 2 { - return newInvalidMember(), fmt.Errorf("%w: %q", errInvalidMember, member) - } - // "Leading and trailing whitespaces are allowed but MUST be trimmed - // when converting the header into a data structure." - key = strings.TrimSpace(kv[0]) - var err error - value, err = url.QueryUnescape(strings.TrimSpace(kv[1])) - if err != nil { - return newInvalidMember(), fmt.Errorf("%w: %q", err, value) - } - if !keyRe.MatchString(key) { - return newInvalidMember(), fmt.Errorf("%w: %q", errInvalidKey, key) - } - if !valueRe.MatchString(value) { - return newInvalidMember(), fmt.Errorf("%w: %q", errInvalidValue, value) - } - default: - // This should never happen unless a developer has changed the string - // splitting somehow. Panic instead of failing silently and allowing - // the bug to slip past the CI checks. - panic("failed to parse baggage member") + } + // Parse the member key/value pair. + + // Take into account a value can contain equal signs (=). + k, v, found := strings.Cut(keyValue, keyValueDelimiter) + if !found { + return newInvalidMember(), fmt.Errorf("%w: %q", errInvalidMember, member) + } + // "Leading and trailing whitespaces are allowed but MUST be trimmed + // when converting the header into a data structure." + key = strings.TrimSpace(k) + var err error + value, err = url.QueryUnescape(strings.TrimSpace(v)) + if err != nil { + return newInvalidMember(), fmt.Errorf("%w: %q", err, value) + } + if !keyRe.MatchString(key) { + return newInvalidMember(), fmt.Errorf("%w: %q", errInvalidKey, key) + } + if !valueRe.MatchString(value) { + return newInvalidMember(), fmt.Errorf("%w: %q", errInvalidValue, value) } return Member{key: key, value: value, properties: props, hasData: true}, nil diff --git a/vendor/go.opentelemetry.io/otel/codes/doc.go b/vendor/go.opentelemetry.io/otel/codes/doc.go index df3e0f1b621..4e328fbb4b3 100644 --- a/vendor/go.opentelemetry.io/otel/codes/doc.go +++ b/vendor/go.opentelemetry.io/otel/codes/doc.go @@ -16,6 +16,6 @@ Package codes defines the canonical error codes used by OpenTelemetry. It conforms to [the OpenTelemetry -specification](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/api.md#statuscanonicalcode). +specification](https://github.com/open-telemetry/opentelemetry-specification/blob/v1.20.0/specification/trace/api.md#set-status). */ package codes // import "go.opentelemetry.io/otel/codes" diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/internal/envconfig/envconfig.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/internal/envconfig/envconfig.go index 53ff3126b6e..444eefbb388 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/internal/envconfig/envconfig.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/internal/envconfig/envconfig.go @@ -166,20 +166,20 @@ func stringToHeader(value string) map[string]string { headers := make(map[string]string) for _, header := range headersPairs { - nameValue := strings.SplitN(header, "=", 2) - if len(nameValue) < 2 { - global.Error(errors.New("missing '="), "parse headers", "input", nameValue) + n, v, found := strings.Cut(header, "=") + if !found { + global.Error(errors.New("missing '="), "parse headers", "input", header) continue } - name, err := url.QueryUnescape(nameValue[0]) + name, err := url.QueryUnescape(n) if err != nil { - global.Error(err, "escape header key", "key", nameValue[0]) + global.Error(err, "escape header key", "key", n) continue } trimmedName := strings.TrimSpace(name) - value, err := url.QueryUnescape(nameValue[1]) + value, err := url.QueryUnescape(v) if err != nil { - global.Error(err, "escape header value", "value", nameValue[1]) + global.Error(err, "escape header value", "value", v) continue } trimmedValue := strings.TrimSpace(value) diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/README.md b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/README.md index 6e9cc0366ba..50295223182 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/README.md +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/README.md @@ -2,7 +2,7 @@ [![Go Reference](https://pkg.go.dev/badge/go.opentelemetry.io/otel/exporters/otlp/otlptrace.svg)](https://pkg.go.dev/go.opentelemetry.io/otel/exporters/otlp/otlptrace) -[OpenTelemetry Protocol Exporter](https://github.com/open-telemetry/opentelemetry-specification/blob/v1.5.0/specification/protocol/exporter.md) implementation. +[OpenTelemetry Protocol Exporter](https://github.com/open-telemetry/opentelemetry-specification/blob/v1.20.0/specification/protocol/exporter.md) implementation. ## Installation @@ -36,7 +36,7 @@ The `otlptracehttp` package implements a client for the span exporter that sends The following environment variables can be used (instead of options objects) to override the default configuration. For more information about how each of these environment variables is interpreted, see [the OpenTelemetry -specification](https://github.com/open-telemetry/opentelemetry-specification/blob/v1.8.0/specification/protocol/exporter.md). +specification](https://github.com/open-telemetry/opentelemetry-specification/blob/v1.20.0/specification/protocol/exporter.md). | Environment variable | Option | Default value | | ------------------------------------------------------------------------ |------------------------------ | -------------------------------------------------------- | diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/internal/header.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/header.go similarity index 70% rename from vendor/go.opentelemetry.io/otel/exporters/otlp/internal/header.go rename to vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/header.go index 9aa62ed9e8e..36d3ca8e1c2 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/internal/header.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/header.go @@ -12,13 +12,14 @@ // See the License for the specific language governing permissions and // limitations under the License. -// Package internal contains common functionality for all OTLP exporters. -package internal // import "go.opentelemetry.io/otel/exporters/otlp/internal" +package internal // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal" -import "go.opentelemetry.io/otel" +import ( + "go.opentelemetry.io/otel/exporters/otlp/otlptrace" +) -// GetUserAgentHeader return an OTLP header value form "OTel OTLP Exporter Go/{{ .Version }}" -// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#user-agent +// GetUserAgentHeader returns an OTLP header value form "OTel OTLP Exporter Go/{{ .Version }}" +// https://github.com/open-telemetry/opentelemetry-specification/blob/v1.20.0/specification/protocol/exporter.md#user-agent func GetUserAgentHeader() string { - return "OTel OTLP Exporter Go/" + otel.Version() + return "OTel OTLP Exporter Go/" + otlptrace.Version() } diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/otlpconfig/options.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/otlpconfig/options.go index c48ffd53081..1a6bb423b30 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/otlpconfig/options.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/otlpconfig/options.go @@ -27,6 +27,7 @@ import ( "go.opentelemetry.io/otel/exporters/otlp/internal" "go.opentelemetry.io/otel/exporters/otlp/internal/retry" + otinternal "go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal" ) const ( @@ -97,7 +98,7 @@ func NewGRPCConfig(opts ...GRPCOption) Config { Timeout: DefaultTimeout, }, RetryConfig: retry.DefaultConfig, - DialOptions: []grpc.DialOption{grpc.WithUserAgent(internal.GetUserAgentHeader())}, + DialOptions: []grpc.DialOption{grpc.WithUserAgent(otinternal.GetUserAgentHeader())}, } cfg = ApplyGRPCEnvConfigs(cfg) for _, opt := range opts { diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/client.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/client.go index fe23f8e3766..2ab2a6e1484 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/client.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/client.go @@ -130,13 +130,16 @@ var errAlreadyStopped = errors.New("the client is already stopped") // If the client has already stopped, an error will be returned describing // this. func (c *client) Stop(ctx context.Context) error { + // Make sure to return context error if the context is done when calling this method. + err := ctx.Err() + // Acquire the c.tscMu lock within the ctx lifetime. acquired := make(chan struct{}) go func() { c.tscMu.Lock() close(acquired) }() - var err error + select { case <-ctx.Done(): // The Stop timeout is reached. Kill any remaining exports to force diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/client.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/client.go index 9fbe861717d..be21724212b 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/client.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/client.go @@ -33,6 +33,7 @@ import ( "go.opentelemetry.io/otel/exporters/otlp/internal" "go.opentelemetry.io/otel/exporters/otlp/internal/retry" "go.opentelemetry.io/otel/exporters/otlp/otlptrace" + otinternal "go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/otlpconfig" coltracepb "go.opentelemetry.io/proto/otlp/collector/trace/v1" tracepb "go.opentelemetry.io/proto/otlp/trace/v1" @@ -209,7 +210,7 @@ func (d *client) newRequest(body []byte) (request, error) { return request{Request: r}, err } - r.Header.Set("User-Agent", internal.GetUserAgentHeader()) + r.Header.Set("User-Agent", otinternal.GetUserAgentHeader()) for k, v := range d.cfg.Headers { r.Header.Set(k, v) diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/version.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/version.go new file mode 100644 index 00000000000..db70dc53143 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/version.go @@ -0,0 +1,20 @@ +// Copyright The OpenTelemetry Authors +// +// 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 otlptrace // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace" + +// Version is the current release version of the OpenTelemetry OTLP trace exporter in use. +func Version() string { + return "1.16.0" +} diff --git a/vendor/go.opentelemetry.io/otel/handler.go b/vendor/go.opentelemetry.io/otel/handler.go index ecd363ab516..4115fe3bbb5 100644 --- a/vendor/go.opentelemetry.io/otel/handler.go +++ b/vendor/go.opentelemetry.io/otel/handler.go @@ -15,58 +15,16 @@ package otel // import "go.opentelemetry.io/otel" import ( - "log" - "os" - "sync/atomic" - "unsafe" + "go.opentelemetry.io/otel/internal/global" ) var ( - // globalErrorHandler provides an ErrorHandler that can be used - // throughout an OpenTelemetry instrumented project. When a user - // specified ErrorHandler is registered (`SetErrorHandler`) all calls to - // `Handle` and will be delegated to the registered ErrorHandler. - globalErrorHandler = defaultErrorHandler() - - // Compile-time check that delegator implements ErrorHandler. - _ ErrorHandler = (*delegator)(nil) - // Compile-time check that errLogger implements ErrorHandler. - _ ErrorHandler = (*errLogger)(nil) + // Compile-time check global.ErrDelegator implements ErrorHandler. + _ ErrorHandler = (*global.ErrDelegator)(nil) + // Compile-time check global.ErrLogger implements ErrorHandler. + _ ErrorHandler = (*global.ErrLogger)(nil) ) -type delegator struct { - delegate unsafe.Pointer -} - -func (d *delegator) Handle(err error) { - d.getDelegate().Handle(err) -} - -func (d *delegator) getDelegate() ErrorHandler { - return *(*ErrorHandler)(atomic.LoadPointer(&d.delegate)) -} - -// setDelegate sets the ErrorHandler delegate. -func (d *delegator) setDelegate(eh ErrorHandler) { - atomic.StorePointer(&d.delegate, unsafe.Pointer(&eh)) -} - -func defaultErrorHandler() *delegator { - d := &delegator{} - d.setDelegate(&errLogger{l: log.New(os.Stderr, "", log.LstdFlags)}) - return d -} - -// errLogger logs errors if no delegate is set, otherwise they are delegated. -type errLogger struct { - l *log.Logger -} - -// Handle logs err if no delegate is set, otherwise it is delegated. -func (h *errLogger) Handle(err error) { - h.l.Print(err) -} - // GetErrorHandler returns the global ErrorHandler instance. // // The default ErrorHandler instance returned will log all errors to STDERR @@ -76,9 +34,7 @@ func (h *errLogger) Handle(err error) { // // Subsequent calls to SetErrorHandler after the first will not forward errors // to the new ErrorHandler for prior returned instances. -func GetErrorHandler() ErrorHandler { - return globalErrorHandler -} +func GetErrorHandler() ErrorHandler { return global.GetErrorHandler() } // SetErrorHandler sets the global ErrorHandler to h. // @@ -86,11 +42,7 @@ func GetErrorHandler() ErrorHandler { // GetErrorHandler will send errors to h instead of the default logging // ErrorHandler. Subsequent calls will set the global ErrorHandler, but not // delegate errors to h. -func SetErrorHandler(h ErrorHandler) { - globalErrorHandler.setDelegate(h) -} +func SetErrorHandler(h ErrorHandler) { global.SetErrorHandler(h) } // Handle is a convenience function for ErrorHandler().Handle(err). -func Handle(err error) { - GetErrorHandler().Handle(err) -} +func Handle(err error) { global.Handle(err) } diff --git a/vendor/go.opentelemetry.io/otel/internal/global/handler.go b/vendor/go.opentelemetry.io/otel/internal/global/handler.go new file mode 100644 index 00000000000..3dcd1caae69 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/internal/global/handler.go @@ -0,0 +1,103 @@ +// Copyright The OpenTelemetry Authors +// +// 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 global // import "go.opentelemetry.io/otel/internal/global" + +import ( + "log" + "os" + "sync/atomic" + "unsafe" +) + +var ( + // GlobalErrorHandler provides an ErrorHandler that can be used + // throughout an OpenTelemetry instrumented project. When a user + // specified ErrorHandler is registered (`SetErrorHandler`) all calls to + // `Handle` and will be delegated to the registered ErrorHandler. + GlobalErrorHandler = defaultErrorHandler() + + // Compile-time check that delegator implements ErrorHandler. + _ ErrorHandler = (*ErrDelegator)(nil) + // Compile-time check that errLogger implements ErrorHandler. + _ ErrorHandler = (*ErrLogger)(nil) +) + +// ErrorHandler handles irremediable events. +type ErrorHandler interface { + // Handle handles any error deemed irremediable by an OpenTelemetry + // component. + Handle(error) +} + +type ErrDelegator struct { + delegate unsafe.Pointer +} + +func (d *ErrDelegator) Handle(err error) { + d.getDelegate().Handle(err) +} + +func (d *ErrDelegator) getDelegate() ErrorHandler { + return *(*ErrorHandler)(atomic.LoadPointer(&d.delegate)) +} + +// setDelegate sets the ErrorHandler delegate. +func (d *ErrDelegator) setDelegate(eh ErrorHandler) { + atomic.StorePointer(&d.delegate, unsafe.Pointer(&eh)) +} + +func defaultErrorHandler() *ErrDelegator { + d := &ErrDelegator{} + d.setDelegate(&ErrLogger{l: log.New(os.Stderr, "", log.LstdFlags)}) + return d +} + +// ErrLogger logs errors if no delegate is set, otherwise they are delegated. +type ErrLogger struct { + l *log.Logger +} + +// Handle logs err if no delegate is set, otherwise it is delegated. +func (h *ErrLogger) Handle(err error) { + h.l.Print(err) +} + +// GetErrorHandler returns the global ErrorHandler instance. +// +// The default ErrorHandler instance returned will log all errors to STDERR +// until an override ErrorHandler is set with SetErrorHandler. All +// ErrorHandler returned prior to this will automatically forward errors to +// the set instance instead of logging. +// +// Subsequent calls to SetErrorHandler after the first will not forward errors +// to the new ErrorHandler for prior returned instances. +func GetErrorHandler() ErrorHandler { + return GlobalErrorHandler +} + +// SetErrorHandler sets the global ErrorHandler to h. +// +// The first time this is called all ErrorHandler previously returned from +// GetErrorHandler will send errors to h instead of the default logging +// ErrorHandler. Subsequent calls will set the global ErrorHandler, but not +// delegate errors to h. +func SetErrorHandler(h ErrorHandler) { + GlobalErrorHandler.setDelegate(h) +} + +// Handle is a convenience function for ErrorHandler().Handle(err). +func Handle(err error) { + GetErrorHandler().Handle(err) +} diff --git a/vendor/go.opentelemetry.io/otel/internal/global/instruments.go b/vendor/go.opentelemetry.io/otel/internal/global/instruments.go new file mode 100644 index 00000000000..a33eded872a --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/internal/global/instruments.go @@ -0,0 +1,359 @@ +// Copyright The OpenTelemetry Authors +// +// 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 global // import "go.opentelemetry.io/otel/internal/global" + +import ( + "context" + "sync/atomic" + + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/embedded" +) + +// unwrapper unwraps to return the underlying instrument implementation. +type unwrapper interface { + Unwrap() metric.Observable +} + +type afCounter struct { + embedded.Float64ObservableCounter + metric.Float64Observable + + name string + opts []metric.Float64ObservableCounterOption + + delegate atomic.Value //metric.Float64ObservableCounter +} + +var _ unwrapper = (*afCounter)(nil) +var _ metric.Float64ObservableCounter = (*afCounter)(nil) + +func (i *afCounter) setDelegate(m metric.Meter) { + ctr, err := m.Float64ObservableCounter(i.name, i.opts...) + if err != nil { + GetErrorHandler().Handle(err) + return + } + i.delegate.Store(ctr) +} + +func (i *afCounter) Unwrap() metric.Observable { + if ctr := i.delegate.Load(); ctr != nil { + return ctr.(metric.Float64ObservableCounter) + } + return nil +} + +type afUpDownCounter struct { + embedded.Float64ObservableUpDownCounter + metric.Float64Observable + + name string + opts []metric.Float64ObservableUpDownCounterOption + + delegate atomic.Value //metric.Float64ObservableUpDownCounter +} + +var _ unwrapper = (*afUpDownCounter)(nil) +var _ metric.Float64ObservableUpDownCounter = (*afUpDownCounter)(nil) + +func (i *afUpDownCounter) setDelegate(m metric.Meter) { + ctr, err := m.Float64ObservableUpDownCounter(i.name, i.opts...) + if err != nil { + GetErrorHandler().Handle(err) + return + } + i.delegate.Store(ctr) +} + +func (i *afUpDownCounter) Unwrap() metric.Observable { + if ctr := i.delegate.Load(); ctr != nil { + return ctr.(metric.Float64ObservableUpDownCounter) + } + return nil +} + +type afGauge struct { + embedded.Float64ObservableGauge + metric.Float64Observable + + name string + opts []metric.Float64ObservableGaugeOption + + delegate atomic.Value //metric.Float64ObservableGauge +} + +var _ unwrapper = (*afGauge)(nil) +var _ metric.Float64ObservableGauge = (*afGauge)(nil) + +func (i *afGauge) setDelegate(m metric.Meter) { + ctr, err := m.Float64ObservableGauge(i.name, i.opts...) + if err != nil { + GetErrorHandler().Handle(err) + return + } + i.delegate.Store(ctr) +} + +func (i *afGauge) Unwrap() metric.Observable { + if ctr := i.delegate.Load(); ctr != nil { + return ctr.(metric.Float64ObservableGauge) + } + return nil +} + +type aiCounter struct { + embedded.Int64ObservableCounter + metric.Int64Observable + + name string + opts []metric.Int64ObservableCounterOption + + delegate atomic.Value //metric.Int64ObservableCounter +} + +var _ unwrapper = (*aiCounter)(nil) +var _ metric.Int64ObservableCounter = (*aiCounter)(nil) + +func (i *aiCounter) setDelegate(m metric.Meter) { + ctr, err := m.Int64ObservableCounter(i.name, i.opts...) + if err != nil { + GetErrorHandler().Handle(err) + return + } + i.delegate.Store(ctr) +} + +func (i *aiCounter) Unwrap() metric.Observable { + if ctr := i.delegate.Load(); ctr != nil { + return ctr.(metric.Int64ObservableCounter) + } + return nil +} + +type aiUpDownCounter struct { + embedded.Int64ObservableUpDownCounter + metric.Int64Observable + + name string + opts []metric.Int64ObservableUpDownCounterOption + + delegate atomic.Value //metric.Int64ObservableUpDownCounter +} + +var _ unwrapper = (*aiUpDownCounter)(nil) +var _ metric.Int64ObservableUpDownCounter = (*aiUpDownCounter)(nil) + +func (i *aiUpDownCounter) setDelegate(m metric.Meter) { + ctr, err := m.Int64ObservableUpDownCounter(i.name, i.opts...) + if err != nil { + GetErrorHandler().Handle(err) + return + } + i.delegate.Store(ctr) +} + +func (i *aiUpDownCounter) Unwrap() metric.Observable { + if ctr := i.delegate.Load(); ctr != nil { + return ctr.(metric.Int64ObservableUpDownCounter) + } + return nil +} + +type aiGauge struct { + embedded.Int64ObservableGauge + metric.Int64Observable + + name string + opts []metric.Int64ObservableGaugeOption + + delegate atomic.Value //metric.Int64ObservableGauge +} + +var _ unwrapper = (*aiGauge)(nil) +var _ metric.Int64ObservableGauge = (*aiGauge)(nil) + +func (i *aiGauge) setDelegate(m metric.Meter) { + ctr, err := m.Int64ObservableGauge(i.name, i.opts...) + if err != nil { + GetErrorHandler().Handle(err) + return + } + i.delegate.Store(ctr) +} + +func (i *aiGauge) Unwrap() metric.Observable { + if ctr := i.delegate.Load(); ctr != nil { + return ctr.(metric.Int64ObservableGauge) + } + return nil +} + +// Sync Instruments. +type sfCounter struct { + embedded.Float64Counter + + name string + opts []metric.Float64CounterOption + + delegate atomic.Value //metric.Float64Counter +} + +var _ metric.Float64Counter = (*sfCounter)(nil) + +func (i *sfCounter) setDelegate(m metric.Meter) { + ctr, err := m.Float64Counter(i.name, i.opts...) + if err != nil { + GetErrorHandler().Handle(err) + return + } + i.delegate.Store(ctr) +} + +func (i *sfCounter) Add(ctx context.Context, incr float64, opts ...metric.AddOption) { + if ctr := i.delegate.Load(); ctr != nil { + ctr.(metric.Float64Counter).Add(ctx, incr, opts...) + } +} + +type sfUpDownCounter struct { + embedded.Float64UpDownCounter + + name string + opts []metric.Float64UpDownCounterOption + + delegate atomic.Value //metric.Float64UpDownCounter +} + +var _ metric.Float64UpDownCounter = (*sfUpDownCounter)(nil) + +func (i *sfUpDownCounter) setDelegate(m metric.Meter) { + ctr, err := m.Float64UpDownCounter(i.name, i.opts...) + if err != nil { + GetErrorHandler().Handle(err) + return + } + i.delegate.Store(ctr) +} + +func (i *sfUpDownCounter) Add(ctx context.Context, incr float64, opts ...metric.AddOption) { + if ctr := i.delegate.Load(); ctr != nil { + ctr.(metric.Float64UpDownCounter).Add(ctx, incr, opts...) + } +} + +type sfHistogram struct { + embedded.Float64Histogram + + name string + opts []metric.Float64HistogramOption + + delegate atomic.Value //metric.Float64Histogram +} + +var _ metric.Float64Histogram = (*sfHistogram)(nil) + +func (i *sfHistogram) setDelegate(m metric.Meter) { + ctr, err := m.Float64Histogram(i.name, i.opts...) + if err != nil { + GetErrorHandler().Handle(err) + return + } + i.delegate.Store(ctr) +} + +func (i *sfHistogram) Record(ctx context.Context, x float64, opts ...metric.RecordOption) { + if ctr := i.delegate.Load(); ctr != nil { + ctr.(metric.Float64Histogram).Record(ctx, x, opts...) + } +} + +type siCounter struct { + embedded.Int64Counter + + name string + opts []metric.Int64CounterOption + + delegate atomic.Value //metric.Int64Counter +} + +var _ metric.Int64Counter = (*siCounter)(nil) + +func (i *siCounter) setDelegate(m metric.Meter) { + ctr, err := m.Int64Counter(i.name, i.opts...) + if err != nil { + GetErrorHandler().Handle(err) + return + } + i.delegate.Store(ctr) +} + +func (i *siCounter) Add(ctx context.Context, x int64, opts ...metric.AddOption) { + if ctr := i.delegate.Load(); ctr != nil { + ctr.(metric.Int64Counter).Add(ctx, x, opts...) + } +} + +type siUpDownCounter struct { + embedded.Int64UpDownCounter + + name string + opts []metric.Int64UpDownCounterOption + + delegate atomic.Value //metric.Int64UpDownCounter +} + +var _ metric.Int64UpDownCounter = (*siUpDownCounter)(nil) + +func (i *siUpDownCounter) setDelegate(m metric.Meter) { + ctr, err := m.Int64UpDownCounter(i.name, i.opts...) + if err != nil { + GetErrorHandler().Handle(err) + return + } + i.delegate.Store(ctr) +} + +func (i *siUpDownCounter) Add(ctx context.Context, x int64, opts ...metric.AddOption) { + if ctr := i.delegate.Load(); ctr != nil { + ctr.(metric.Int64UpDownCounter).Add(ctx, x, opts...) + } +} + +type siHistogram struct { + embedded.Int64Histogram + + name string + opts []metric.Int64HistogramOption + + delegate atomic.Value //metric.Int64Histogram +} + +var _ metric.Int64Histogram = (*siHistogram)(nil) + +func (i *siHistogram) setDelegate(m metric.Meter) { + ctr, err := m.Int64Histogram(i.name, i.opts...) + if err != nil { + GetErrorHandler().Handle(err) + return + } + i.delegate.Store(ctr) +} + +func (i *siHistogram) Record(ctx context.Context, x int64, opts ...metric.RecordOption) { + if ctr := i.delegate.Load(); ctr != nil { + ctr.(metric.Int64Histogram).Record(ctx, x, opts...) + } +} diff --git a/vendor/go.opentelemetry.io/otel/internal/global/internal_logging.go b/vendor/go.opentelemetry.io/otel/internal/global/internal_logging.go index 293c08961fb..5951fd06d4c 100644 --- a/vendor/go.opentelemetry.io/otel/internal/global/internal_logging.go +++ b/vendor/go.opentelemetry.io/otel/internal/global/internal_logging.go @@ -24,7 +24,7 @@ import ( "github.com/go-logr/stdr" ) -// globalLogger is the logging interface used within the otel api and sdk provide deatails of the internals. +// globalLogger is the logging interface used within the otel api and sdk provide details of the internals. // // The default logger uses stdr which is backed by the standard `log.Logger` // interface. This logger will only show messages at the Error Level. @@ -36,8 +36,9 @@ func init() { // SetLogger overrides the globalLogger with l. // -// To see Info messages use a logger with `l.V(1).Enabled() == true` -// To see Debug messages use a logger with `l.V(5).Enabled() == true`. +// To see Warn messages use a logger with `l.V(1).Enabled() == true` +// To see Info messages use a logger with `l.V(4).Enabled() == true` +// To see Debug messages use a logger with `l.V(8).Enabled() == true`. func SetLogger(l logr.Logger) { atomic.StorePointer(&globalLogger, unsafe.Pointer(&l)) } @@ -47,9 +48,9 @@ func getLogger() logr.Logger { } // Info prints messages about the general state of the API or SDK. -// This should usually be less then 5 messages a minute. +// This should usually be less than 5 messages a minute. func Info(msg string, keysAndValues ...interface{}) { - getLogger().V(1).Info(msg, keysAndValues...) + getLogger().V(4).Info(msg, keysAndValues...) } // Error prints messages about exceptional states of the API or SDK. @@ -59,5 +60,11 @@ func Error(err error, msg string, keysAndValues ...interface{}) { // Debug prints messages about all internal changes in the API or SDK. func Debug(msg string, keysAndValues ...interface{}) { - getLogger().V(5).Info(msg, keysAndValues...) + getLogger().V(8).Info(msg, keysAndValues...) +} + +// Warn prints messages about warnings in the API or SDK. +// Not an error but is likely more important than an informational event. +func Warn(msg string, keysAndValues ...interface{}) { + getLogger().V(1).Info(msg, keysAndValues...) } diff --git a/vendor/go.opentelemetry.io/otel/metric/internal/global/meter.go b/vendor/go.opentelemetry.io/otel/internal/global/meter.go similarity index 79% rename from vendor/go.opentelemetry.io/otel/metric/internal/global/meter.go rename to vendor/go.opentelemetry.io/otel/internal/global/meter.go index 8acf632863c..0097db478c6 100644 --- a/vendor/go.opentelemetry.io/otel/metric/internal/global/meter.go +++ b/vendor/go.opentelemetry.io/otel/internal/global/meter.go @@ -12,16 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. -package global // import "go.opentelemetry.io/otel/metric/internal/global" +package global // import "go.opentelemetry.io/otel/internal/global" import ( "container/list" "sync" "sync/atomic" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/metric" - "go.opentelemetry.io/otel/metric/instrument" + "go.opentelemetry.io/otel/metric/embedded" ) // meterProvider is a placeholder for a configured SDK MeterProvider. @@ -29,17 +28,14 @@ import ( // All MeterProvider functionality is forwarded to a delegate once // configured. type meterProvider struct { + embedded.MeterProvider + mtx sync.Mutex meters map[il]*meter delegate metric.MeterProvider } -type il struct { - name string - version string -} - // setDelegate configures p to delegate all MeterProvider functionality to // provider. // @@ -100,6 +96,8 @@ func (p *meterProvider) Meter(name string, opts ...metric.MeterOption) metric.Me // All Meter functionality is forwarded to a delegate once configured. // Otherwise, all functionality is forwarded to a NoopMeter. type meter struct { + embedded.Meter + name string opts []metric.MeterOption @@ -142,7 +140,7 @@ func (m *meter) setDelegate(provider metric.MeterProvider) { m.registry.Init() } -func (m *meter) Int64Counter(name string, options ...instrument.Int64Option) (instrument.Int64Counter, error) { +func (m *meter) Int64Counter(name string, options ...metric.Int64CounterOption) (metric.Int64Counter, error) { if del, ok := m.delegate.Load().(metric.Meter); ok { return del.Int64Counter(name, options...) } @@ -153,7 +151,7 @@ func (m *meter) Int64Counter(name string, options ...instrument.Int64Option) (in return i, nil } -func (m *meter) Int64UpDownCounter(name string, options ...instrument.Int64Option) (instrument.Int64UpDownCounter, error) { +func (m *meter) Int64UpDownCounter(name string, options ...metric.Int64UpDownCounterOption) (metric.Int64UpDownCounter, error) { if del, ok := m.delegate.Load().(metric.Meter); ok { return del.Int64UpDownCounter(name, options...) } @@ -164,7 +162,7 @@ func (m *meter) Int64UpDownCounter(name string, options ...instrument.Int64Optio return i, nil } -func (m *meter) Int64Histogram(name string, options ...instrument.Int64Option) (instrument.Int64Histogram, error) { +func (m *meter) Int64Histogram(name string, options ...metric.Int64HistogramOption) (metric.Int64Histogram, error) { if del, ok := m.delegate.Load().(metric.Meter); ok { return del.Int64Histogram(name, options...) } @@ -175,7 +173,7 @@ func (m *meter) Int64Histogram(name string, options ...instrument.Int64Option) ( return i, nil } -func (m *meter) Int64ObservableCounter(name string, options ...instrument.Int64ObserverOption) (instrument.Int64ObservableCounter, error) { +func (m *meter) Int64ObservableCounter(name string, options ...metric.Int64ObservableCounterOption) (metric.Int64ObservableCounter, error) { if del, ok := m.delegate.Load().(metric.Meter); ok { return del.Int64ObservableCounter(name, options...) } @@ -186,7 +184,7 @@ func (m *meter) Int64ObservableCounter(name string, options ...instrument.Int64O return i, nil } -func (m *meter) Int64ObservableUpDownCounter(name string, options ...instrument.Int64ObserverOption) (instrument.Int64ObservableUpDownCounter, error) { +func (m *meter) Int64ObservableUpDownCounter(name string, options ...metric.Int64ObservableUpDownCounterOption) (metric.Int64ObservableUpDownCounter, error) { if del, ok := m.delegate.Load().(metric.Meter); ok { return del.Int64ObservableUpDownCounter(name, options...) } @@ -197,7 +195,7 @@ func (m *meter) Int64ObservableUpDownCounter(name string, options ...instrument. return i, nil } -func (m *meter) Int64ObservableGauge(name string, options ...instrument.Int64ObserverOption) (instrument.Int64ObservableGauge, error) { +func (m *meter) Int64ObservableGauge(name string, options ...metric.Int64ObservableGaugeOption) (metric.Int64ObservableGauge, error) { if del, ok := m.delegate.Load().(metric.Meter); ok { return del.Int64ObservableGauge(name, options...) } @@ -208,7 +206,7 @@ func (m *meter) Int64ObservableGauge(name string, options ...instrument.Int64Obs return i, nil } -func (m *meter) Float64Counter(name string, options ...instrument.Float64Option) (instrument.Float64Counter, error) { +func (m *meter) Float64Counter(name string, options ...metric.Float64CounterOption) (metric.Float64Counter, error) { if del, ok := m.delegate.Load().(metric.Meter); ok { return del.Float64Counter(name, options...) } @@ -219,7 +217,7 @@ func (m *meter) Float64Counter(name string, options ...instrument.Float64Option) return i, nil } -func (m *meter) Float64UpDownCounter(name string, options ...instrument.Float64Option) (instrument.Float64UpDownCounter, error) { +func (m *meter) Float64UpDownCounter(name string, options ...metric.Float64UpDownCounterOption) (metric.Float64UpDownCounter, error) { if del, ok := m.delegate.Load().(metric.Meter); ok { return del.Float64UpDownCounter(name, options...) } @@ -230,7 +228,7 @@ func (m *meter) Float64UpDownCounter(name string, options ...instrument.Float64O return i, nil } -func (m *meter) Float64Histogram(name string, options ...instrument.Float64Option) (instrument.Float64Histogram, error) { +func (m *meter) Float64Histogram(name string, options ...metric.Float64HistogramOption) (metric.Float64Histogram, error) { if del, ok := m.delegate.Load().(metric.Meter); ok { return del.Float64Histogram(name, options...) } @@ -241,7 +239,7 @@ func (m *meter) Float64Histogram(name string, options ...instrument.Float64Optio return i, nil } -func (m *meter) Float64ObservableCounter(name string, options ...instrument.Float64ObserverOption) (instrument.Float64ObservableCounter, error) { +func (m *meter) Float64ObservableCounter(name string, options ...metric.Float64ObservableCounterOption) (metric.Float64ObservableCounter, error) { if del, ok := m.delegate.Load().(metric.Meter); ok { return del.Float64ObservableCounter(name, options...) } @@ -252,7 +250,7 @@ func (m *meter) Float64ObservableCounter(name string, options ...instrument.Floa return i, nil } -func (m *meter) Float64ObservableUpDownCounter(name string, options ...instrument.Float64ObserverOption) (instrument.Float64ObservableUpDownCounter, error) { +func (m *meter) Float64ObservableUpDownCounter(name string, options ...metric.Float64ObservableUpDownCounterOption) (metric.Float64ObservableUpDownCounter, error) { if del, ok := m.delegate.Load().(metric.Meter); ok { return del.Float64ObservableUpDownCounter(name, options...) } @@ -263,7 +261,7 @@ func (m *meter) Float64ObservableUpDownCounter(name string, options ...instrumen return i, nil } -func (m *meter) Float64ObservableGauge(name string, options ...instrument.Float64ObserverOption) (instrument.Float64ObservableGauge, error) { +func (m *meter) Float64ObservableGauge(name string, options ...metric.Float64ObservableGaugeOption) (metric.Float64ObservableGauge, error) { if del, ok := m.delegate.Load().(metric.Meter); ok { return del.Float64ObservableGauge(name, options...) } @@ -275,7 +273,7 @@ func (m *meter) Float64ObservableGauge(name string, options ...instrument.Float6 } // RegisterCallback captures the function that will be called during Collect. -func (m *meter) RegisterCallback(f metric.Callback, insts ...instrument.Asynchronous) (metric.Registration, error) { +func (m *meter) RegisterCallback(f metric.Callback, insts ...metric.Observable) (metric.Registration, error) { if del, ok := m.delegate.Load().(metric.Meter); ok { insts = unwrapInstruments(insts) return del.RegisterCallback(f, insts...) @@ -296,11 +294,11 @@ func (m *meter) RegisterCallback(f metric.Callback, insts ...instrument.Asynchro } type wrapped interface { - unwrap() instrument.Asynchronous + unwrap() metric.Observable } -func unwrapInstruments(instruments []instrument.Asynchronous) []instrument.Asynchronous { - out := make([]instrument.Asynchronous, 0, len(instruments)) +func unwrapInstruments(instruments []metric.Observable) []metric.Observable { + out := make([]metric.Observable, 0, len(instruments)) for _, inst := range instruments { if in, ok := inst.(wrapped); ok { @@ -314,7 +312,9 @@ func unwrapInstruments(instruments []instrument.Asynchronous) []instrument.Async } type registration struct { - instruments []instrument.Asynchronous + embedded.Registration + + instruments []metric.Observable function metric.Callback unreg func() error @@ -334,7 +334,7 @@ func (c *registration) setDelegate(m metric.Meter) { reg, err := m.RegisterCallback(c.function, insts...) if err != nil { - otel.Handle(err) + GetErrorHandler().Handle(err) } c.unreg = reg.Unregister diff --git a/vendor/go.opentelemetry.io/otel/internal/global/state.go b/vendor/go.opentelemetry.io/otel/internal/global/state.go index 1ad38f828ec..7985005bcb6 100644 --- a/vendor/go.opentelemetry.io/otel/internal/global/state.go +++ b/vendor/go.opentelemetry.io/otel/internal/global/state.go @@ -19,6 +19,7 @@ import ( "sync" "sync/atomic" + "go.opentelemetry.io/otel/metric" "go.opentelemetry.io/otel/propagation" "go.opentelemetry.io/otel/trace" ) @@ -31,14 +32,20 @@ type ( propagatorsHolder struct { tm propagation.TextMapPropagator } + + meterProviderHolder struct { + mp metric.MeterProvider + } ) var ( - globalTracer = defaultTracerValue() - globalPropagators = defaultPropagatorsValue() + globalTracer = defaultTracerValue() + globalPropagators = defaultPropagatorsValue() + globalMeterProvider = defaultMeterProvider() delegateTraceOnce sync.Once delegateTextMapPropagatorOnce sync.Once + delegateMeterOnce sync.Once ) // TracerProvider is the internal implementation for global.TracerProvider. @@ -102,6 +109,34 @@ func SetTextMapPropagator(p propagation.TextMapPropagator) { globalPropagators.Store(propagatorsHolder{tm: p}) } +// MeterProvider is the internal implementation for global.MeterProvider. +func MeterProvider() metric.MeterProvider { + return globalMeterProvider.Load().(meterProviderHolder).mp +} + +// SetMeterProvider is the internal implementation for global.SetMeterProvider. +func SetMeterProvider(mp metric.MeterProvider) { + current := MeterProvider() + if _, cOk := current.(*meterProvider); cOk { + if _, mpOk := mp.(*meterProvider); mpOk && current == mp { + // Do not assign the default delegating MeterProvider to delegate + // to itself. + Error( + errors.New("no delegate configured in meter provider"), + "Setting meter provider to it's current value. No delegate will be configured", + ) + return + } + } + + delegateMeterOnce.Do(func() { + if def, ok := current.(*meterProvider); ok { + def.setDelegate(mp) + } + }) + globalMeterProvider.Store(meterProviderHolder{mp: mp}) +} + func defaultTracerValue() *atomic.Value { v := &atomic.Value{} v.Store(tracerProviderHolder{tp: &tracerProvider{}}) @@ -113,3 +148,9 @@ func defaultPropagatorsValue() *atomic.Value { v.Store(propagatorsHolder{tm: newTextMapPropagator()}) return v } + +func defaultMeterProvider() *atomic.Value { + v := &atomic.Value{} + v.Store(meterProviderHolder{mp: &meterProvider{}}) + return v +} diff --git a/vendor/go.opentelemetry.io/otel/metric.go b/vendor/go.opentelemetry.io/otel/metric.go new file mode 100644 index 00000000000..f955171951f --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/metric.go @@ -0,0 +1,53 @@ +// Copyright The OpenTelemetry Authors +// +// 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 otel // import "go.opentelemetry.io/otel" + +import ( + "go.opentelemetry.io/otel/internal/global" + "go.opentelemetry.io/otel/metric" +) + +// Meter returns a Meter from the global MeterProvider. The name must be the +// name of the library providing instrumentation. This name may be the same as +// the instrumented code only if that code provides built-in instrumentation. +// If the name is empty, then a implementation defined default name will be +// used instead. +// +// If this is called before a global MeterProvider is registered the returned +// Meter will be a No-op implementation of a Meter. When a global MeterProvider +// is registered for the first time, the returned Meter, and all the +// instruments it has created or will create, are recreated automatically from +// the new MeterProvider. +// +// This is short for GetMeterProvider().Meter(name). +func Meter(name string, opts ...metric.MeterOption) metric.Meter { + return GetMeterProvider().Meter(name, opts...) +} + +// GetMeterProvider returns the registered global meter provider. +// +// If no global GetMeterProvider has been registered, a No-op GetMeterProvider +// implementation is returned. When a global GetMeterProvider is registered for +// the first time, the returned GetMeterProvider, and all the Meters it has +// created or will create, are recreated automatically from the new +// GetMeterProvider. +func GetMeterProvider() metric.MeterProvider { + return global.MeterProvider() +} + +// SetMeterProvider registers mp as the global MeterProvider. +func SetMeterProvider(mp metric.MeterProvider) { + global.SetMeterProvider(mp) +} diff --git a/vendor/go.opentelemetry.io/otel/metric/asyncfloat64.go b/vendor/go.opentelemetry.io/otel/metric/asyncfloat64.go new file mode 100644 index 00000000000..072baa8e8d0 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/metric/asyncfloat64.go @@ -0,0 +1,271 @@ +// Copyright The OpenTelemetry Authors +// +// 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 metric // import "go.opentelemetry.io/otel/metric" + +import ( + "context" + + "go.opentelemetry.io/otel/metric/embedded" +) + +// Float64Observable describes a set of instruments used asynchronously to +// record float64 measurements once per collection cycle. Observations of +// these instruments are only made within a callback. +// +// Warning: Methods may be added to this interface in minor releases. +type Float64Observable interface { + Observable + + float64Observable() +} + +// Float64ObservableCounter is an instrument used to asynchronously record +// increasing float64 measurements once per collection cycle. Observations are +// only made within a callback for this instrument. The value observed is +// assumed the to be the cumulative sum of the count. +// +// Warning: Methods may be added to this interface in minor releases. See +// package documentation on API implementation for information on how to set +// default behavior for +// unimplemented methods. +type Float64ObservableCounter interface { + // Users of the interface can ignore this. This embedded type is only used + // by implementations of this interface. See the "API Implementations" + // section of the package documentation for more information. + embedded.Float64ObservableCounter + + Float64Observable +} + +// Float64ObservableCounterConfig contains options for asynchronous counter +// instruments that record int64 values. +type Float64ObservableCounterConfig struct { + description string + unit string + callbacks []Float64Callback +} + +// NewFloat64ObservableCounterConfig returns a new +// [Float64ObservableCounterConfig] with all opts applied. +func NewFloat64ObservableCounterConfig(opts ...Float64ObservableCounterOption) Float64ObservableCounterConfig { + var config Float64ObservableCounterConfig + for _, o := range opts { + config = o.applyFloat64ObservableCounter(config) + } + return config +} + +// Description returns the configured description. +func (c Float64ObservableCounterConfig) Description() string { + return c.description +} + +// Unit returns the configured unit. +func (c Float64ObservableCounterConfig) Unit() string { + return c.unit +} + +// Callbacks returns the configured callbacks. +func (c Float64ObservableCounterConfig) Callbacks() []Float64Callback { + return c.callbacks +} + +// Float64ObservableCounterOption applies options to a +// [Float64ObservableCounterConfig]. See [Float64ObservableOption] and +// [InstrumentOption] for other options that can be used as a +// Float64ObservableCounterOption. +type Float64ObservableCounterOption interface { + applyFloat64ObservableCounter(Float64ObservableCounterConfig) Float64ObservableCounterConfig +} + +// Float64ObservableUpDownCounter is an instrument used to asynchronously +// record float64 measurements once per collection cycle. Observations are only +// made within a callback for this instrument. The value observed is assumed +// the to be the cumulative sum of the count. +// +// Warning: Methods may be added to this interface in minor releases. See +// package documentation on API implementation for information on how to set +// default behavior for unimplemented methods. +type Float64ObservableUpDownCounter interface { + // Users of the interface can ignore this. This embedded type is only used + // by implementations of this interface. See the "API Implementations" + // section of the package documentation for more information. + embedded.Float64ObservableUpDownCounter + + Float64Observable +} + +// Float64ObservableUpDownCounterConfig contains options for asynchronous +// counter instruments that record int64 values. +type Float64ObservableUpDownCounterConfig struct { + description string + unit string + callbacks []Float64Callback +} + +// NewFloat64ObservableUpDownCounterConfig returns a new +// [Float64ObservableUpDownCounterConfig] with all opts applied. +func NewFloat64ObservableUpDownCounterConfig(opts ...Float64ObservableUpDownCounterOption) Float64ObservableUpDownCounterConfig { + var config Float64ObservableUpDownCounterConfig + for _, o := range opts { + config = o.applyFloat64ObservableUpDownCounter(config) + } + return config +} + +// Description returns the configured description. +func (c Float64ObservableUpDownCounterConfig) Description() string { + return c.description +} + +// Unit returns the configured unit. +func (c Float64ObservableUpDownCounterConfig) Unit() string { + return c.unit +} + +// Callbacks returns the configured callbacks. +func (c Float64ObservableUpDownCounterConfig) Callbacks() []Float64Callback { + return c.callbacks +} + +// Float64ObservableUpDownCounterOption applies options to a +// [Float64ObservableUpDownCounterConfig]. See [Float64ObservableOption] and +// [InstrumentOption] for other options that can be used as a +// Float64ObservableUpDownCounterOption. +type Float64ObservableUpDownCounterOption interface { + applyFloat64ObservableUpDownCounter(Float64ObservableUpDownCounterConfig) Float64ObservableUpDownCounterConfig +} + +// Float64ObservableGauge is an instrument used to asynchronously record +// instantaneous float64 measurements once per collection cycle. Observations +// are only made within a callback for this instrument. +// +// Warning: Methods may be added to this interface in minor releases. See +// package documentation on API implementation for information on how to set +// default behavior for unimplemented methods. +type Float64ObservableGauge interface { + // Users of the interface can ignore this. This embedded type is only used + // by implementations of this interface. See the "API Implementations" + // section of the package documentation for more information. + embedded.Float64ObservableGauge + + Float64Observable +} + +// Float64ObservableGaugeConfig contains options for asynchronous counter +// instruments that record int64 values. +type Float64ObservableGaugeConfig struct { + description string + unit string + callbacks []Float64Callback +} + +// NewFloat64ObservableGaugeConfig returns a new [Float64ObservableGaugeConfig] +// with all opts applied. +func NewFloat64ObservableGaugeConfig(opts ...Float64ObservableGaugeOption) Float64ObservableGaugeConfig { + var config Float64ObservableGaugeConfig + for _, o := range opts { + config = o.applyFloat64ObservableGauge(config) + } + return config +} + +// Description returns the configured description. +func (c Float64ObservableGaugeConfig) Description() string { + return c.description +} + +// Unit returns the configured unit. +func (c Float64ObservableGaugeConfig) Unit() string { + return c.unit +} + +// Callbacks returns the configured callbacks. +func (c Float64ObservableGaugeConfig) Callbacks() []Float64Callback { + return c.callbacks +} + +// Float64ObservableGaugeOption applies options to a +// [Float64ObservableGaugeConfig]. See [Float64ObservableOption] and +// [InstrumentOption] for other options that can be used as a +// Float64ObservableGaugeOption. +type Float64ObservableGaugeOption interface { + applyFloat64ObservableGauge(Float64ObservableGaugeConfig) Float64ObservableGaugeConfig +} + +// Float64Observer is a recorder of float64 measurements. +// +// Warning: Methods may be added to this interface in minor releases. See +// package documentation on API implementation for information on how to set +// default behavior for unimplemented methods. +type Float64Observer interface { + // Users of the interface can ignore this. This embedded type is only used + // by implementations of this interface. See the "API Implementations" + // section of the package documentation for more information. + embedded.Float64Observer + + // Observe records the float64 value. + // + // Use the WithAttributeSet (or, if performance is not a concern, + // the WithAttributes) option to include measurement attributes. + Observe(value float64, options ...ObserveOption) +} + +// Float64Callback is a function registered with a Meter that makes +// observations for a Float64Observerable instrument it is registered with. +// Calls to the Float64Observer record measurement values for the +// Float64Observable. +// +// The function needs to complete in a finite amount of time and the deadline +// of the passed context is expected to be honored. +// +// The function needs to make unique observations across all registered +// Float64Callbacks. Meaning, it should not report measurements with the same +// attributes as another Float64Callbacks also registered for the same +// instrument. +// +// The function needs to be concurrent safe. +type Float64Callback func(context.Context, Float64Observer) error + +// Float64ObservableOption applies options to float64 Observer instruments. +type Float64ObservableOption interface { + Float64ObservableCounterOption + Float64ObservableUpDownCounterOption + Float64ObservableGaugeOption +} + +type float64CallbackOpt struct { + cback Float64Callback +} + +func (o float64CallbackOpt) applyFloat64ObservableCounter(cfg Float64ObservableCounterConfig) Float64ObservableCounterConfig { + cfg.callbacks = append(cfg.callbacks, o.cback) + return cfg +} + +func (o float64CallbackOpt) applyFloat64ObservableUpDownCounter(cfg Float64ObservableUpDownCounterConfig) Float64ObservableUpDownCounterConfig { + cfg.callbacks = append(cfg.callbacks, o.cback) + return cfg +} + +func (o float64CallbackOpt) applyFloat64ObservableGauge(cfg Float64ObservableGaugeConfig) Float64ObservableGaugeConfig { + cfg.callbacks = append(cfg.callbacks, o.cback) + return cfg +} + +// WithFloat64Callback adds callback to be called for an instrument. +func WithFloat64Callback(callback Float64Callback) Float64ObservableOption { + return float64CallbackOpt{callback} +} diff --git a/vendor/go.opentelemetry.io/otel/metric/asyncint64.go b/vendor/go.opentelemetry.io/otel/metric/asyncint64.go new file mode 100644 index 00000000000..9bd6ebf0205 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/metric/asyncint64.go @@ -0,0 +1,269 @@ +// Copyright The OpenTelemetry Authors +// +// 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 metric // import "go.opentelemetry.io/otel/metric" + +import ( + "context" + + "go.opentelemetry.io/otel/metric/embedded" +) + +// Int64Observable describes a set of instruments used asynchronously to record +// int64 measurements once per collection cycle. Observations of these +// instruments are only made within a callback. +// +// Warning: Methods may be added to this interface in minor releases. +type Int64Observable interface { + Observable + + int64Observable() +} + +// Int64ObservableCounter is an instrument used to asynchronously record +// increasing int64 measurements once per collection cycle. Observations are +// only made within a callback for this instrument. The value observed is +// assumed the to be the cumulative sum of the count. +// +// Warning: Methods may be added to this interface in minor releases. See +// package documentation on API implementation for information on how to set +// default behavior for unimplemented methods. +type Int64ObservableCounter interface { + // Users of the interface can ignore this. This embedded type is only used + // by implementations of this interface. See the "API Implementations" + // section of the package documentation for more information. + embedded.Int64ObservableCounter + + Int64Observable +} + +// Int64ObservableCounterConfig contains options for asynchronous counter +// instruments that record int64 values. +type Int64ObservableCounterConfig struct { + description string + unit string + callbacks []Int64Callback +} + +// NewInt64ObservableCounterConfig returns a new [Int64ObservableCounterConfig] +// with all opts applied. +func NewInt64ObservableCounterConfig(opts ...Int64ObservableCounterOption) Int64ObservableCounterConfig { + var config Int64ObservableCounterConfig + for _, o := range opts { + config = o.applyInt64ObservableCounter(config) + } + return config +} + +// Description returns the configured description. +func (c Int64ObservableCounterConfig) Description() string { + return c.description +} + +// Unit returns the configured unit. +func (c Int64ObservableCounterConfig) Unit() string { + return c.unit +} + +// Callbacks returns the configured callbacks. +func (c Int64ObservableCounterConfig) Callbacks() []Int64Callback { + return c.callbacks +} + +// Int64ObservableCounterOption applies options to a +// [Int64ObservableCounterConfig]. See [Int64ObservableOption] and +// [InstrumentOption] for other options that can be used as an +// Int64ObservableCounterOption. +type Int64ObservableCounterOption interface { + applyInt64ObservableCounter(Int64ObservableCounterConfig) Int64ObservableCounterConfig +} + +// Int64ObservableUpDownCounter is an instrument used to asynchronously record +// int64 measurements once per collection cycle. Observations are only made +// within a callback for this instrument. The value observed is assumed the to +// be the cumulative sum of the count. +// +// Warning: Methods may be added to this interface in minor releases. See +// package documentation on API implementation for information on how to set +// default behavior for unimplemented methods. +type Int64ObservableUpDownCounter interface { + // Users of the interface can ignore this. This embedded type is only used + // by implementations of this interface. See the "API Implementations" + // section of the package documentation for more information. + embedded.Int64ObservableUpDownCounter + + Int64Observable +} + +// Int64ObservableUpDownCounterConfig contains options for asynchronous counter +// instruments that record int64 values. +type Int64ObservableUpDownCounterConfig struct { + description string + unit string + callbacks []Int64Callback +} + +// NewInt64ObservableUpDownCounterConfig returns a new +// [Int64ObservableUpDownCounterConfig] with all opts applied. +func NewInt64ObservableUpDownCounterConfig(opts ...Int64ObservableUpDownCounterOption) Int64ObservableUpDownCounterConfig { + var config Int64ObservableUpDownCounterConfig + for _, o := range opts { + config = o.applyInt64ObservableUpDownCounter(config) + } + return config +} + +// Description returns the configured description. +func (c Int64ObservableUpDownCounterConfig) Description() string { + return c.description +} + +// Unit returns the configured unit. +func (c Int64ObservableUpDownCounterConfig) Unit() string { + return c.unit +} + +// Callbacks returns the configured callbacks. +func (c Int64ObservableUpDownCounterConfig) Callbacks() []Int64Callback { + return c.callbacks +} + +// Int64ObservableUpDownCounterOption applies options to a +// [Int64ObservableUpDownCounterConfig]. See [Int64ObservableOption] and +// [InstrumentOption] for other options that can be used as an +// Int64ObservableUpDownCounterOption. +type Int64ObservableUpDownCounterOption interface { + applyInt64ObservableUpDownCounter(Int64ObservableUpDownCounterConfig) Int64ObservableUpDownCounterConfig +} + +// Int64ObservableGauge is an instrument used to asynchronously record +// instantaneous int64 measurements once per collection cycle. Observations are +// only made within a callback for this instrument. +// +// Warning: Methods may be added to this interface in minor releases. See +// package documentation on API implementation for information on how to set +// default behavior for unimplemented methods. +type Int64ObservableGauge interface { + // Users of the interface can ignore this. This embedded type is only used + // by implementations of this interface. See the "API Implementations" + // section of the package documentation for more information. + embedded.Int64ObservableGauge + + Int64Observable +} + +// Int64ObservableGaugeConfig contains options for asynchronous counter +// instruments that record int64 values. +type Int64ObservableGaugeConfig struct { + description string + unit string + callbacks []Int64Callback +} + +// NewInt64ObservableGaugeConfig returns a new [Int64ObservableGaugeConfig] +// with all opts applied. +func NewInt64ObservableGaugeConfig(opts ...Int64ObservableGaugeOption) Int64ObservableGaugeConfig { + var config Int64ObservableGaugeConfig + for _, o := range opts { + config = o.applyInt64ObservableGauge(config) + } + return config +} + +// Description returns the configured description. +func (c Int64ObservableGaugeConfig) Description() string { + return c.description +} + +// Unit returns the configured unit. +func (c Int64ObservableGaugeConfig) Unit() string { + return c.unit +} + +// Callbacks returns the configured callbacks. +func (c Int64ObservableGaugeConfig) Callbacks() []Int64Callback { + return c.callbacks +} + +// Int64ObservableGaugeOption applies options to a +// [Int64ObservableGaugeConfig]. See [Int64ObservableOption] and +// [InstrumentOption] for other options that can be used as an +// Int64ObservableGaugeOption. +type Int64ObservableGaugeOption interface { + applyInt64ObservableGauge(Int64ObservableGaugeConfig) Int64ObservableGaugeConfig +} + +// Int64Observer is a recorder of int64 measurements. +// +// Warning: Methods may be added to this interface in minor releases. See +// package documentation on API implementation for information on how to set +// default behavior for unimplemented methods. +type Int64Observer interface { + // Users of the interface can ignore this. This embedded type is only used + // by implementations of this interface. See the "API Implementations" + // section of the package documentation for more information. + embedded.Int64Observer + + // Observe records the int64 value. + // + // Use the WithAttributeSet (or, if performance is not a concern, + // the WithAttributes) option to include measurement attributes. + Observe(value int64, options ...ObserveOption) +} + +// Int64Callback is a function registered with a Meter that makes observations +// for an Int64Observerable instrument it is registered with. Calls to the +// Int64Observer record measurement values for the Int64Observable. +// +// The function needs to complete in a finite amount of time and the deadline +// of the passed context is expected to be honored. +// +// The function needs to make unique observations across all registered +// Int64Callbacks. Meaning, it should not report measurements with the same +// attributes as another Int64Callbacks also registered for the same +// instrument. +// +// The function needs to be concurrent safe. +type Int64Callback func(context.Context, Int64Observer) error + +// Int64ObservableOption applies options to int64 Observer instruments. +type Int64ObservableOption interface { + Int64ObservableCounterOption + Int64ObservableUpDownCounterOption + Int64ObservableGaugeOption +} + +type int64CallbackOpt struct { + cback Int64Callback +} + +func (o int64CallbackOpt) applyInt64ObservableCounter(cfg Int64ObservableCounterConfig) Int64ObservableCounterConfig { + cfg.callbacks = append(cfg.callbacks, o.cback) + return cfg +} + +func (o int64CallbackOpt) applyInt64ObservableUpDownCounter(cfg Int64ObservableUpDownCounterConfig) Int64ObservableUpDownCounterConfig { + cfg.callbacks = append(cfg.callbacks, o.cback) + return cfg +} + +func (o int64CallbackOpt) applyInt64ObservableGauge(cfg Int64ObservableGaugeConfig) Int64ObservableGaugeConfig { + cfg.callbacks = append(cfg.callbacks, o.cback) + return cfg +} + +// WithInt64Callback adds callback to be called for an instrument. +func WithInt64Callback(callback Int64Callback) Int64ObservableOption { + return int64CallbackOpt{callback} +} diff --git a/vendor/go.opentelemetry.io/otel/metric/doc.go b/vendor/go.opentelemetry.io/otel/metric/doc.go index bd6f4343720..ae24e448d91 100644 --- a/vendor/go.opentelemetry.io/otel/metric/doc.go +++ b/vendor/go.opentelemetry.io/otel/metric/doc.go @@ -13,11 +13,158 @@ // limitations under the License. /* -Package metric provides an implementation of the metrics part of the -OpenTelemetry API. +Package metric provides the OpenTelemetry API used to measure metrics about +source code operation. -This package is currently in a pre-GA phase. Backwards incompatible changes -may be introduced in subsequent minor version releases as we work to track the -evolving OpenTelemetry specification and user feedback. +This API is separate from its implementation so the instrumentation built from +it is reusable. See [go.opentelemetry.io/otel/sdk/metric] for the official +OpenTelemetry implementation of this API. + +All measurements made with this package are made via instruments. These +instruments are created by a [Meter] which itself is created by a +[MeterProvider]. Applications need to accept a [MeterProvider] implementation +as a starting point when instrumenting. This can be done directly, or by using +the OpenTelemetry global MeterProvider via [GetMeterProvider]. Using an +appropriately named [Meter] from the accepted [MeterProvider], instrumentation +can then be built from the [Meter]'s instruments. + +# Instruments + +Each instrument is designed to make measurements of a particular type. Broadly, +all instruments fall into two overlapping logical categories: asynchronous or +synchronous, and int64 or float64. + +All synchronous instruments ([Int64Counter], [Int64UpDownCounter], +[Int64Histogram], [Float64Counter], [Float64UpDownCounter], and +[Float64Histogram]) are used to measure the operation and performance of source +code during the source code execution. These instruments only make measurements +when the source code they instrument is run. + +All asynchronous instruments ([Int64ObservableCounter], +[Int64ObservableUpDownCounter], [Int64ObservableGauge], +[Float64ObservableCounter], [Float64ObservableUpDownCounter], and +[Float64ObservableGauge]) are used to measure metrics outside of the execution +of source code. They are said to make "observations" via a callback function +called once every measurement collection cycle. + +Each instrument is also grouped by the value type it measures. Either int64 or +float64. The value being measured will dictate which instrument in these +categories to use. + +Outside of these two broad categories, instruments are described by the +function they are designed to serve. All Counters ([Int64Counter], +[Float64Counter], [Int64ObservableCounter], and [Float64ObservableCounter]) are +designed to measure values that never decrease in value, but instead only +incrementally increase in value. UpDownCounters ([Int64UpDownCounter], +[Float64UpDownCounter], [Int64ObservableUpDownCounter], and +[Float64ObservableUpDownCounter]) on the other hand, are designed to measure +values that can increase and decrease. When more information needs to be +conveyed about all the synchronous measurements made during a collection cycle, +a Histogram ([Int64Histogram] and [Float64Histogram]) should be used. Finally, +when just the most recent measurement needs to be conveyed about an +asynchronous measurement, a Gauge ([Int64ObservableGauge] and +[Float64ObservableGauge]) should be used. + +See the [OpenTelemetry documentation] for more information about instruments +and their intended use. + +# Measurements + +Measurements are made by recording values and information about the values with +an instrument. How these measurements are recorded depends on the instrument. + +Measurements for synchronous instruments ([Int64Counter], [Int64UpDownCounter], +[Int64Histogram], [Float64Counter], [Float64UpDownCounter], and +[Float64Histogram]) are recorded using the instrument methods directly. All +counter instruments have an Add method that is used to measure an increment +value, and all histogram instruments have a Record method to measure a data +point. + +Asynchronous instruments ([Int64ObservableCounter], +[Int64ObservableUpDownCounter], [Int64ObservableGauge], +[Float64ObservableCounter], [Float64ObservableUpDownCounter], and +[Float64ObservableGauge]) record measurements within a callback function. The +callback is registered with the Meter which ensures the callback is called once +per collection cycle. A callback can be registered two ways: during the +instrument's creation using an option, or later using the RegisterCallback +method of the [Meter] that created the instrument. + +If the following criteria are met, an option ([WithInt64Callback] or +[WithFloat64Callback]) can be used during the asynchronous instrument's +creation to register a callback ([Int64Callback] or [Float64Callback], +respectively): + + - The measurement process is known when the instrument is created + - Only that instrument will make a measurement within the callback + - The callback never needs to be unregistered + +If the criteria are not met, use the RegisterCallback method of the [Meter] that +created the instrument to register a [Callback]. + +# API Implementations + +This package does not conform to the standard Go versioning policy, all of its +interfaces may have methods added to them without a package major version bump. +This non-standard API evolution could surprise an uninformed implementation +author. They could unknowingly build their implementation in a way that would +result in a runtime panic for their users that update to the new API. + +The API is designed to help inform an instrumentation author about this +non-standard API evolution. It requires them to choose a default behavior for +unimplemented interface methods. There are three behavior choices they can +make: + + - Compilation failure + - Panic + - Default to another implementation + +All interfaces in this API embed a corresponding interface from +[go.opentelemetry.io/otel/metric/embedded]. If an author wants the default +behavior of their implementations to be a compilation failure, signaling to +their users they need to update to the latest version of that implementation, +they need to embed the corresponding interface from +[go.opentelemetry.io/otel/metric/embedded] in their implementation. For +example, + + import "go.opentelemetry.io/otel/metric/embedded" + + type MeterProvider struct { + embedded.MeterProvider + // ... + } + +If an author wants the default behavior of their implementations to a panic, +they need to embed the API interface directly. + + import "go.opentelemetry.io/otel/metric" + + type MeterProvider struct { + metric.MeterProvider + // ... + } + +This is not a recommended behavior as it could lead to publishing packages that +contain runtime panics when users update other package that use newer versions +of [go.opentelemetry.io/otel/metric]. + +Finally, an author can embed another implementation in theirs. The embedded +implementation will be used for methods not defined by the author. For example, +an author who want to default to silently dropping the call can use +[go.opentelemetry.io/otel/metric/noop]: + + import "go.opentelemetry.io/otel/metric/noop" + + type MeterProvider struct { + noop.MeterProvider + // ... + } + +It is strongly recommended that authors only embed +[go.opentelemetry.io/otel/metric/noop] if they choose this default behavior. +That implementation is the only one OpenTelemetry authors can guarantee will +fully implement all the API interfaces when a user updates their API. + +[OpenTelemetry documentation]: https://opentelemetry.io/docs/concepts/signals/metrics/ +[GetMeterProvider]: https://pkg.go.dev/go.opentelemetry.io/otel#GetMeterProvider */ package metric // import "go.opentelemetry.io/otel/metric" diff --git a/vendor/go.opentelemetry.io/otel/metric/embedded/embedded.go b/vendor/go.opentelemetry.io/otel/metric/embedded/embedded.go new file mode 100644 index 00000000000..ae0bdbd2e64 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/metric/embedded/embedded.go @@ -0,0 +1,234 @@ +// Copyright The OpenTelemetry Authors +// +// 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 embedded provides interfaces embedded within the [OpenTelemetry +// metric API]. +// +// Implementers of the [OpenTelemetry metric API] can embed the relevant type +// from this package into their implementation directly. Doing so will result +// in a compilation error for users when the [OpenTelemetry metric API] is +// extended (which is something that can happen without a major version bump of +// the API package). +// +// [OpenTelemetry metric API]: https://pkg.go.dev/go.opentelemetry.io/otel/metric +package embedded // import "go.opentelemetry.io/otel/metric/embedded" + +// MeterProvider is embedded in +// [go.opentelemetry.io/otel/metric.MeterProvider]. +// +// Embed this interface in your implementation of the +// [go.opentelemetry.io/otel/metric.MeterProvider] if you want users to +// experience a compilation error, signaling they need to update to your latest +// implementation, when the [go.opentelemetry.io/otel/metric.MeterProvider] +// interface is extended (which is something that can happen without a major +// version bump of the API package). +type MeterProvider interface{ meterProvider() } + +// Meter is embedded in [go.opentelemetry.io/otel/metric.Meter]. +// +// Embed this interface in your implementation of the +// [go.opentelemetry.io/otel/metric.Meter] if you want users to experience a +// compilation error, signaling they need to update to your latest +// implementation, when the [go.opentelemetry.io/otel/metric.Meter] interface +// is extended (which is something that can happen without a major version bump +// of the API package). +type Meter interface{ meter() } + +// Float64Observer is embedded in +// [go.opentelemetry.io/otel/metric.Float64Observer]. +// +// Embed this interface in your implementation of the +// [go.opentelemetry.io/otel/metric.Float64Observer] if you want +// users to experience a compilation error, signaling they need to update to +// your latest implementation, when the +// [go.opentelemetry.io/otel/metric.Float64Observer] interface is +// extended (which is something that can happen without a major version bump of +// the API package). +type Float64Observer interface{ float64Observer() } + +// Int64Observer is embedded in +// [go.opentelemetry.io/otel/metric.Int64Observer]. +// +// Embed this interface in your implementation of the +// [go.opentelemetry.io/otel/metric.Int64Observer] if you want users +// to experience a compilation error, signaling they need to update to your +// latest implementation, when the +// [go.opentelemetry.io/otel/metric.Int64Observer] interface is +// extended (which is something that can happen without a major version bump of +// the API package). +type Int64Observer interface{ int64Observer() } + +// Observer is embedded in [go.opentelemetry.io/otel/metric.Observer]. +// +// Embed this interface in your implementation of the +// [go.opentelemetry.io/otel/metric.Observer] if you want users to experience a +// compilation error, signaling they need to update to your latest +// implementation, when the [go.opentelemetry.io/otel/metric.Observer] +// interface is extended (which is something that can happen without a major +// version bump of the API package). +type Observer interface{ observer() } + +// Registration is embedded in [go.opentelemetry.io/otel/metric.Registration]. +// +// Embed this interface in your implementation of the +// [go.opentelemetry.io/otel/metric.Registration] if you want users to +// experience a compilation error, signaling they need to update to your latest +// implementation, when the [go.opentelemetry.io/otel/metric.Registration] +// interface is extended (which is something that can happen without a major +// version bump of the API package). +type Registration interface{ registration() } + +// Float64Counter is embedded in +// [go.opentelemetry.io/otel/metric.Float64Counter]. +// +// Embed this interface in your implementation of the +// [go.opentelemetry.io/otel/metric.Float64Counter] if you want +// users to experience a compilation error, signaling they need to update to +// your latest implementation, when the +// [go.opentelemetry.io/otel/metric.Float64Counter] interface is +// extended (which is something that can happen without a major version bump of +// the API package). +type Float64Counter interface{ float64Counter() } + +// Float64Histogram is embedded in +// [go.opentelemetry.io/otel/metric.Float64Histogram]. +// +// Embed this interface in your implementation of the +// [go.opentelemetry.io/otel/metric.Float64Histogram] if you want +// users to experience a compilation error, signaling they need to update to +// your latest implementation, when the +// [go.opentelemetry.io/otel/metric.Float64Histogram] interface is +// extended (which is something that can happen without a major version bump of +// the API package). +type Float64Histogram interface{ float64Histogram() } + +// Float64ObservableCounter is embedded in +// [go.opentelemetry.io/otel/metric.Float64ObservableCounter]. +// +// Embed this interface in your implementation of the +// [go.opentelemetry.io/otel/metric.Float64ObservableCounter] if you +// want users to experience a compilation error, signaling they need to update +// to your latest implementation, when the +// [go.opentelemetry.io/otel/metric.Float64ObservableCounter] +// interface is extended (which is something that can happen without a major +// version bump of the API package). +type Float64ObservableCounter interface{ float64ObservableCounter() } + +// Float64ObservableGauge is embedded in +// [go.opentelemetry.io/otel/metric.Float64ObservableGauge]. +// +// Embed this interface in your implementation of the +// [go.opentelemetry.io/otel/metric.Float64ObservableGauge] if you +// want users to experience a compilation error, signaling they need to update +// to your latest implementation, when the +// [go.opentelemetry.io/otel/metric.Float64ObservableGauge] +// interface is extended (which is something that can happen without a major +// version bump of the API package). +type Float64ObservableGauge interface{ float64ObservableGauge() } + +// Float64ObservableUpDownCounter is embedded in +// [go.opentelemetry.io/otel/metric.Float64ObservableUpDownCounter]. +// +// Embed this interface in your implementation of the +// [go.opentelemetry.io/otel/metric.Float64ObservableUpDownCounter] +// if you want users to experience a compilation error, signaling they need to +// update to your latest implementation, when the +// [go.opentelemetry.io/otel/metric.Float64ObservableUpDownCounter] +// interface is extended (which is something that can happen without a major +// version bump of the API package). +type Float64ObservableUpDownCounter interface{ float64ObservableUpDownCounter() } + +// Float64UpDownCounter is embedded in +// [go.opentelemetry.io/otel/metric.Float64UpDownCounter]. +// +// Embed this interface in your implementation of the +// [go.opentelemetry.io/otel/metric.Float64UpDownCounter] if you +// want users to experience a compilation error, signaling they need to update +// to your latest implementation, when the +// [go.opentelemetry.io/otel/metric.Float64UpDownCounter] interface +// is extended (which is something that can happen without a major version bump +// of the API package). +type Float64UpDownCounter interface{ float64UpDownCounter() } + +// Int64Counter is embedded in +// [go.opentelemetry.io/otel/metric.Int64Counter]. +// +// Embed this interface in your implementation of the +// [go.opentelemetry.io/otel/metric.Int64Counter] if you want users +// to experience a compilation error, signaling they need to update to your +// latest implementation, when the +// [go.opentelemetry.io/otel/metric.Int64Counter] interface is +// extended (which is something that can happen without a major version bump of +// the API package). +type Int64Counter interface{ int64Counter() } + +// Int64Histogram is embedded in +// [go.opentelemetry.io/otel/metric.Int64Histogram]. +// +// Embed this interface in your implementation of the +// [go.opentelemetry.io/otel/metric.Int64Histogram] if you want +// users to experience a compilation error, signaling they need to update to +// your latest implementation, when the +// [go.opentelemetry.io/otel/metric.Int64Histogram] interface is +// extended (which is something that can happen without a major version bump of +// the API package). +type Int64Histogram interface{ int64Histogram() } + +// Int64ObservableCounter is embedded in +// [go.opentelemetry.io/otel/metric.Int64ObservableCounter]. +// +// Embed this interface in your implementation of the +// [go.opentelemetry.io/otel/metric.Int64ObservableCounter] if you +// want users to experience a compilation error, signaling they need to update +// to your latest implementation, when the +// [go.opentelemetry.io/otel/metric.Int64ObservableCounter] +// interface is extended (which is something that can happen without a major +// version bump of the API package). +type Int64ObservableCounter interface{ int64ObservableCounter() } + +// Int64ObservableGauge is embedded in +// [go.opentelemetry.io/otel/metric.Int64ObservableGauge]. +// +// Embed this interface in your implementation of the +// [go.opentelemetry.io/otel/metric.Int64ObservableGauge] if you +// want users to experience a compilation error, signaling they need to update +// to your latest implementation, when the +// [go.opentelemetry.io/otel/metric.Int64ObservableGauge] interface +// is extended (which is something that can happen without a major version bump +// of the API package). +type Int64ObservableGauge interface{ int64ObservableGauge() } + +// Int64ObservableUpDownCounter is embedded in +// [go.opentelemetry.io/otel/metric.Int64ObservableUpDownCounter]. +// +// Embed this interface in your implementation of the +// [go.opentelemetry.io/otel/metric.Int64ObservableUpDownCounter] if +// you want users to experience a compilation error, signaling they need to +// update to your latest implementation, when the +// [go.opentelemetry.io/otel/metric.Int64ObservableUpDownCounter] +// interface is extended (which is something that can happen without a major +// version bump of the API package). +type Int64ObservableUpDownCounter interface{ int64ObservableUpDownCounter() } + +// Int64UpDownCounter is embedded in +// [go.opentelemetry.io/otel/metric.Int64UpDownCounter]. +// +// Embed this interface in your implementation of the +// [go.opentelemetry.io/otel/metric.Int64UpDownCounter] if you want +// users to experience a compilation error, signaling they need to update to +// your latest implementation, when the +// [go.opentelemetry.io/otel/metric.Int64UpDownCounter] interface is +// extended (which is something that can happen without a major version bump of +// the API package). +type Int64UpDownCounter interface{ int64UpDownCounter() } diff --git a/vendor/go.opentelemetry.io/otel/metric/global/global.go b/vendor/go.opentelemetry.io/otel/metric/global/global.go deleted file mode 100644 index cb0896d38ac..00000000000 --- a/vendor/go.opentelemetry.io/otel/metric/global/global.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright The OpenTelemetry Authors -// -// 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 global // import "go.opentelemetry.io/otel/metric/global" - -import ( - "go.opentelemetry.io/otel/metric" - "go.opentelemetry.io/otel/metric/internal/global" -) - -// Meter returns a Meter from the global MeterProvider. The -// instrumentationName must be the name of the library providing -// instrumentation. This name may be the same as the instrumented code only if -// that code provides built-in instrumentation. If the instrumentationName is -// empty, then a implementation defined default name will be used instead. -// -// This is short for MeterProvider().Meter(name). -func Meter(instrumentationName string, opts ...metric.MeterOption) metric.Meter { - return MeterProvider().Meter(instrumentationName, opts...) -} - -// MeterProvider returns the registered global meter provider. -// If none is registered then a No-op MeterProvider is returned. -func MeterProvider() metric.MeterProvider { - return global.MeterProvider() -} - -// SetMeterProvider registers `mp` as the global meter provider. -func SetMeterProvider(mp metric.MeterProvider) { - global.SetMeterProvider(mp) -} diff --git a/vendor/go.opentelemetry.io/otel/metric/instrument.go b/vendor/go.opentelemetry.io/otel/metric/instrument.go new file mode 100644 index 00000000000..0033c1e12d5 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/metric/instrument.go @@ -0,0 +1,332 @@ +// Copyright The OpenTelemetry Authors +// +// 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 metric // import "go.opentelemetry.io/otel/metric" + +import "go.opentelemetry.io/otel/attribute" + +// Observable is used as a grouping mechanism for all instruments that are +// updated within a Callback. +type Observable interface { + observable() +} + +// InstrumentOption applies options to all instruments. +type InstrumentOption interface { + Int64CounterOption + Int64UpDownCounterOption + Int64HistogramOption + Int64ObservableCounterOption + Int64ObservableUpDownCounterOption + Int64ObservableGaugeOption + + Float64CounterOption + Float64UpDownCounterOption + Float64HistogramOption + Float64ObservableCounterOption + Float64ObservableUpDownCounterOption + Float64ObservableGaugeOption +} + +type descOpt string + +func (o descOpt) applyFloat64Counter(c Float64CounterConfig) Float64CounterConfig { + c.description = string(o) + return c +} + +func (o descOpt) applyFloat64UpDownCounter(c Float64UpDownCounterConfig) Float64UpDownCounterConfig { + c.description = string(o) + return c +} + +func (o descOpt) applyFloat64Histogram(c Float64HistogramConfig) Float64HistogramConfig { + c.description = string(o) + return c +} + +func (o descOpt) applyFloat64ObservableCounter(c Float64ObservableCounterConfig) Float64ObservableCounterConfig { + c.description = string(o) + return c +} + +func (o descOpt) applyFloat64ObservableUpDownCounter(c Float64ObservableUpDownCounterConfig) Float64ObservableUpDownCounterConfig { + c.description = string(o) + return c +} + +func (o descOpt) applyFloat64ObservableGauge(c Float64ObservableGaugeConfig) Float64ObservableGaugeConfig { + c.description = string(o) + return c +} + +func (o descOpt) applyInt64Counter(c Int64CounterConfig) Int64CounterConfig { + c.description = string(o) + return c +} + +func (o descOpt) applyInt64UpDownCounter(c Int64UpDownCounterConfig) Int64UpDownCounterConfig { + c.description = string(o) + return c +} + +func (o descOpt) applyInt64Histogram(c Int64HistogramConfig) Int64HistogramConfig { + c.description = string(o) + return c +} + +func (o descOpt) applyInt64ObservableCounter(c Int64ObservableCounterConfig) Int64ObservableCounterConfig { + c.description = string(o) + return c +} + +func (o descOpt) applyInt64ObservableUpDownCounter(c Int64ObservableUpDownCounterConfig) Int64ObservableUpDownCounterConfig { + c.description = string(o) + return c +} + +func (o descOpt) applyInt64ObservableGauge(c Int64ObservableGaugeConfig) Int64ObservableGaugeConfig { + c.description = string(o) + return c +} + +// WithDescription sets the instrument description. +func WithDescription(desc string) InstrumentOption { return descOpt(desc) } + +type unitOpt string + +func (o unitOpt) applyFloat64Counter(c Float64CounterConfig) Float64CounterConfig { + c.unit = string(o) + return c +} + +func (o unitOpt) applyFloat64UpDownCounter(c Float64UpDownCounterConfig) Float64UpDownCounterConfig { + c.unit = string(o) + return c +} + +func (o unitOpt) applyFloat64Histogram(c Float64HistogramConfig) Float64HistogramConfig { + c.unit = string(o) + return c +} + +func (o unitOpt) applyFloat64ObservableCounter(c Float64ObservableCounterConfig) Float64ObservableCounterConfig { + c.unit = string(o) + return c +} + +func (o unitOpt) applyFloat64ObservableUpDownCounter(c Float64ObservableUpDownCounterConfig) Float64ObservableUpDownCounterConfig { + c.unit = string(o) + return c +} + +func (o unitOpt) applyFloat64ObservableGauge(c Float64ObservableGaugeConfig) Float64ObservableGaugeConfig { + c.unit = string(o) + return c +} + +func (o unitOpt) applyInt64Counter(c Int64CounterConfig) Int64CounterConfig { + c.unit = string(o) + return c +} + +func (o unitOpt) applyInt64UpDownCounter(c Int64UpDownCounterConfig) Int64UpDownCounterConfig { + c.unit = string(o) + return c +} + +func (o unitOpt) applyInt64Histogram(c Int64HistogramConfig) Int64HistogramConfig { + c.unit = string(o) + return c +} + +func (o unitOpt) applyInt64ObservableCounter(c Int64ObservableCounterConfig) Int64ObservableCounterConfig { + c.unit = string(o) + return c +} + +func (o unitOpt) applyInt64ObservableUpDownCounter(c Int64ObservableUpDownCounterConfig) Int64ObservableUpDownCounterConfig { + c.unit = string(o) + return c +} + +func (o unitOpt) applyInt64ObservableGauge(c Int64ObservableGaugeConfig) Int64ObservableGaugeConfig { + c.unit = string(o) + return c +} + +// WithUnit sets the instrument unit. +func WithUnit(u string) InstrumentOption { return unitOpt(u) } + +// AddOption applies options to an addition measurement. See +// [MeasurementOption] for other options that can be used as an AddOption. +type AddOption interface { + applyAdd(AddConfig) AddConfig +} + +// AddConfig contains options for an addition measurement. +type AddConfig struct { + attrs attribute.Set +} + +// NewAddConfig returns a new [AddConfig] with all opts applied. +func NewAddConfig(opts []AddOption) AddConfig { + config := AddConfig{attrs: *attribute.EmptySet()} + for _, o := range opts { + config = o.applyAdd(config) + } + return config +} + +// Attributes returns the configured attribute set. +func (c AddConfig) Attributes() attribute.Set { + return c.attrs +} + +// RecordOption applies options to an addition measurement. See +// [MeasurementOption] for other options that can be used as a RecordOption. +type RecordOption interface { + applyRecord(RecordConfig) RecordConfig +} + +// RecordConfig contains options for a recorded measurement. +type RecordConfig struct { + attrs attribute.Set +} + +// NewRecordConfig returns a new [RecordConfig] with all opts applied. +func NewRecordConfig(opts []RecordOption) RecordConfig { + config := RecordConfig{attrs: *attribute.EmptySet()} + for _, o := range opts { + config = o.applyRecord(config) + } + return config +} + +// Attributes returns the configured attribute set. +func (c RecordConfig) Attributes() attribute.Set { + return c.attrs +} + +// ObserveOption applies options to an addition measurement. See +// [MeasurementOption] for other options that can be used as a ObserveOption. +type ObserveOption interface { + applyObserve(ObserveConfig) ObserveConfig +} + +// ObserveConfig contains options for an observed measurement. +type ObserveConfig struct { + attrs attribute.Set +} + +// NewObserveConfig returns a new [ObserveConfig] with all opts applied. +func NewObserveConfig(opts []ObserveOption) ObserveConfig { + config := ObserveConfig{attrs: *attribute.EmptySet()} + for _, o := range opts { + config = o.applyObserve(config) + } + return config +} + +// Attributes returns the configured attribute set. +func (c ObserveConfig) Attributes() attribute.Set { + return c.attrs +} + +// MeasurementOption applies options to all instrument measurement. +type MeasurementOption interface { + AddOption + RecordOption + ObserveOption +} + +type attrOpt struct { + set attribute.Set +} + +// mergeSets returns the union of keys between a and b. Any duplicate keys will +// use the value associated with b. +func mergeSets(a, b attribute.Set) attribute.Set { + // NewMergeIterator uses the first value for any duplicates. + iter := attribute.NewMergeIterator(&b, &a) + merged := make([]attribute.KeyValue, 0, a.Len()+b.Len()) + for iter.Next() { + merged = append(merged, iter.Attribute()) + } + return attribute.NewSet(merged...) +} + +func (o attrOpt) applyAdd(c AddConfig) AddConfig { + switch { + case o.set.Len() == 0: + case c.attrs.Len() == 0: + c.attrs = o.set + default: + c.attrs = mergeSets(c.attrs, o.set) + } + return c +} + +func (o attrOpt) applyRecord(c RecordConfig) RecordConfig { + switch { + case o.set.Len() == 0: + case c.attrs.Len() == 0: + c.attrs = o.set + default: + c.attrs = mergeSets(c.attrs, o.set) + } + return c +} + +func (o attrOpt) applyObserve(c ObserveConfig) ObserveConfig { + switch { + case o.set.Len() == 0: + case c.attrs.Len() == 0: + c.attrs = o.set + default: + c.attrs = mergeSets(c.attrs, o.set) + } + return c +} + +// WithAttributeSet sets the attribute Set associated with a measurement is +// made with. +// +// If multiple WithAttributeSet or WithAttributes options are passed the +// attributes will be merged together in the order they are passed. Attributes +// with duplicate keys will use the last value passed. +func WithAttributeSet(attributes attribute.Set) MeasurementOption { + return attrOpt{set: attributes} +} + +// WithAttributes converts attributes into an attribute Set and sets the Set to +// be associated with a measurement. This is shorthand for: +// +// cp := make([]attribute.KeyValue, len(attributes)) +// copy(cp, attributes) +// WithAttributes(attribute.NewSet(cp...)) +// +// [attribute.NewSet] may modify the passed attributes so this will make a copy +// of attributes before creating a set in order to ensure this function is +// concurrent safe. This makes this option function less optimized in +// comparison to [WithAttributeSet]. Therefore, [WithAttributeSet] should be +// preferred for performance sensitive code. +// +// See [WithAttributeSet] for information about how multiple WithAttributes are +// merged. +func WithAttributes(attributes ...attribute.KeyValue) MeasurementOption { + cp := make([]attribute.KeyValue, len(attributes)) + copy(cp, attributes) + return attrOpt{set: attribute.NewSet(cp...)} +} diff --git a/vendor/go.opentelemetry.io/otel/metric/instrument/asyncfloat64.go b/vendor/go.opentelemetry.io/otel/metric/instrument/asyncfloat64.go deleted file mode 100644 index 0b5d5a99c0f..00000000000 --- a/vendor/go.opentelemetry.io/otel/metric/instrument/asyncfloat64.go +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright The OpenTelemetry Authors -// -// 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 instrument // import "go.opentelemetry.io/otel/metric/instrument" - -import ( - "context" - - "go.opentelemetry.io/otel/attribute" -) - -// Float64Observable describes a set of instruments used asynchronously to -// record float64 measurements once per collection cycle. Observations of -// these instruments are only made within a callback. -// -// Warning: methods may be added to this interface in minor releases. -type Float64Observable interface { - Asynchronous - - float64Observable() -} - -// Float64ObservableCounter is an instrument used to asynchronously record -// increasing float64 measurements once per collection cycle. Observations are -// only made within a callback for this instrument. The value observed is -// assumed the to be the cumulative sum of the count. -// -// Warning: methods may be added to this interface in minor releases. -type Float64ObservableCounter interface{ Float64Observable } - -// Float64ObservableUpDownCounter is an instrument used to asynchronously -// record float64 measurements once per collection cycle. Observations are only -// made within a callback for this instrument. The value observed is assumed -// the to be the cumulative sum of the count. -// -// Warning: methods may be added to this interface in minor releases. -type Float64ObservableUpDownCounter interface{ Float64Observable } - -// Float64ObservableGauge is an instrument used to asynchronously record -// instantaneous float64 measurements once per collection cycle. Observations -// are only made within a callback for this instrument. -// -// Warning: methods may be added to this interface in minor releases. -type Float64ObservableGauge interface{ Float64Observable } - -// Float64Observer is a recorder of float64 measurements. -// -// Warning: methods may be added to this interface in minor releases. -type Float64Observer interface { - Observe(value float64, attributes ...attribute.KeyValue) -} - -// Float64Callback is a function registered with a Meter that makes -// observations for a Float64Observerable instrument it is registered with. -// Calls to the Float64Observer record measurement values for the -// Float64Observable. -// -// The function needs to complete in a finite amount of time and the deadline -// of the passed context is expected to be honored. -// -// The function needs to make unique observations across all registered -// Float64Callbacks. Meaning, it should not report measurements with the same -// attributes as another Float64Callbacks also registered for the same -// instrument. -// -// The function needs to be concurrent safe. -type Float64Callback func(context.Context, Float64Observer) error - -// Float64ObserverConfig contains options for Asynchronous instruments that -// observe float64 values. -type Float64ObserverConfig struct { - description string - unit string - callbacks []Float64Callback -} - -// NewFloat64ObserverConfig returns a new Float64ObserverConfig with all opts -// applied. -func NewFloat64ObserverConfig(opts ...Float64ObserverOption) Float64ObserverConfig { - var config Float64ObserverConfig - for _, o := range opts { - config = o.applyFloat64Observer(config) - } - return config -} - -// Description returns the Config description. -func (c Float64ObserverConfig) Description() string { - return c.description -} - -// Unit returns the Config unit. -func (c Float64ObserverConfig) Unit() string { - return c.unit -} - -// Callbacks returns the Config callbacks. -func (c Float64ObserverConfig) Callbacks() []Float64Callback { - return c.callbacks -} - -// Float64ObserverOption applies options to float64 Observer instruments. -type Float64ObserverOption interface { - applyFloat64Observer(Float64ObserverConfig) Float64ObserverConfig -} - -type float64ObserverOptionFunc func(Float64ObserverConfig) Float64ObserverConfig - -func (fn float64ObserverOptionFunc) applyFloat64Observer(cfg Float64ObserverConfig) Float64ObserverConfig { - return fn(cfg) -} - -// WithFloat64Callback adds callback to be called for an instrument. -func WithFloat64Callback(callback Float64Callback) Float64ObserverOption { - return float64ObserverOptionFunc(func(cfg Float64ObserverConfig) Float64ObserverConfig { - cfg.callbacks = append(cfg.callbacks, callback) - return cfg - }) -} diff --git a/vendor/go.opentelemetry.io/otel/metric/instrument/asyncint64.go b/vendor/go.opentelemetry.io/otel/metric/instrument/asyncint64.go deleted file mode 100644 index 05feeacb053..00000000000 --- a/vendor/go.opentelemetry.io/otel/metric/instrument/asyncint64.go +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright The OpenTelemetry Authors -// -// 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 instrument // import "go.opentelemetry.io/otel/metric/instrument" - -import ( - "context" - - "go.opentelemetry.io/otel/attribute" -) - -// Int64Observable describes a set of instruments used asynchronously to record -// int64 measurements once per collection cycle. Observations of these -// instruments are only made within a callback. -// -// Warning: methods may be added to this interface in minor releases. -type Int64Observable interface { - Asynchronous - - int64Observable() -} - -// Int64ObservableCounter is an instrument used to asynchronously record -// increasing int64 measurements once per collection cycle. Observations are -// only made within a callback for this instrument. The value observed is -// assumed the to be the cumulative sum of the count. -// -// Warning: methods may be added to this interface in minor releases. -type Int64ObservableCounter interface{ Int64Observable } - -// Int64ObservableUpDownCounter is an instrument used to asynchronously record -// int64 measurements once per collection cycle. Observations are only made -// within a callback for this instrument. The value observed is assumed the to -// be the cumulative sum of the count. -// -// Warning: methods may be added to this interface in minor releases. -type Int64ObservableUpDownCounter interface{ Int64Observable } - -// Int64ObservableGauge is an instrument used to asynchronously record -// instantaneous int64 measurements once per collection cycle. Observations are -// only made within a callback for this instrument. -// -// Warning: methods may be added to this interface in minor releases. -type Int64ObservableGauge interface{ Int64Observable } - -// Int64Observer is a recorder of int64 measurements. -// -// Warning: methods may be added to this interface in minor releases. -type Int64Observer interface { - Observe(value int64, attributes ...attribute.KeyValue) -} - -// Int64Callback is a function registered with a Meter that makes -// observations for a Int64Observerable instrument it is registered with. -// Calls to the Int64Observer record measurement values for the -// Int64Observable. -// -// The function needs to complete in a finite amount of time and the deadline -// of the passed context is expected to be honored. -// -// The function needs to make unique observations across all registered -// Int64Callback. Meaning, it should not report measurements with the same -// attributes as another Int64Callbacks also registered for the same -// instrument. -// -// The function needs to be concurrent safe. -type Int64Callback func(context.Context, Int64Observer) error - -// Int64ObserverConfig contains options for Asynchronous instruments that -// observe int64 values. -type Int64ObserverConfig struct { - description string - unit string - callbacks []Int64Callback -} - -// NewInt64ObserverConfig returns a new Int64ObserverConfig with all opts -// applied. -func NewInt64ObserverConfig(opts ...Int64ObserverOption) Int64ObserverConfig { - var config Int64ObserverConfig - for _, o := range opts { - config = o.applyInt64Observer(config) - } - return config -} - -// Description returns the Config description. -func (c Int64ObserverConfig) Description() string { - return c.description -} - -// Unit returns the Config unit. -func (c Int64ObserverConfig) Unit() string { - return c.unit -} - -// Callbacks returns the Config callbacks. -func (c Int64ObserverConfig) Callbacks() []Int64Callback { - return c.callbacks -} - -// Int64ObserverOption applies options to int64 Observer instruments. -type Int64ObserverOption interface { - applyInt64Observer(Int64ObserverConfig) Int64ObserverConfig -} - -type int64ObserverOptionFunc func(Int64ObserverConfig) Int64ObserverConfig - -func (fn int64ObserverOptionFunc) applyInt64Observer(cfg Int64ObserverConfig) Int64ObserverConfig { - return fn(cfg) -} - -// WithInt64Callback adds callback to be called for an instrument. -func WithInt64Callback(callback Int64Callback) Int64ObserverOption { - return int64ObserverOptionFunc(func(cfg Int64ObserverConfig) Int64ObserverConfig { - cfg.callbacks = append(cfg.callbacks, callback) - return cfg - }) -} diff --git a/vendor/go.opentelemetry.io/otel/metric/instrument/instrument.go b/vendor/go.opentelemetry.io/otel/metric/instrument/instrument.go deleted file mode 100644 index f6dd9e890f4..00000000000 --- a/vendor/go.opentelemetry.io/otel/metric/instrument/instrument.go +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright The OpenTelemetry Authors -// -// 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 instrument // import "go.opentelemetry.io/otel/metric/instrument" - -// Asynchronous instruments are instruments that are updated within a Callback. -// If an instrument is observed outside of it's callback it should be an error. -// -// This interface is used as a grouping mechanism. -type Asynchronous interface { - asynchronous() -} - -// Synchronous instruments are updated in line with application code. -// -// This interface is used as a grouping mechanism. -type Synchronous interface { - synchronous() -} - -// Option applies options to all instruments. -type Option interface { - Float64ObserverOption - Int64ObserverOption - Float64Option - Int64Option -} - -type descOpt string - -func (o descOpt) applyFloat64(c Float64Config) Float64Config { - c.description = string(o) - return c -} - -func (o descOpt) applyInt64(c Int64Config) Int64Config { - c.description = string(o) - return c -} - -func (o descOpt) applyFloat64Observer(c Float64ObserverConfig) Float64ObserverConfig { - c.description = string(o) - return c -} - -func (o descOpt) applyInt64Observer(c Int64ObserverConfig) Int64ObserverConfig { - c.description = string(o) - return c -} - -// WithDescription sets the instrument description. -func WithDescription(desc string) Option { return descOpt(desc) } - -type unitOpt string - -func (o unitOpt) applyFloat64(c Float64Config) Float64Config { - c.unit = string(o) - return c -} - -func (o unitOpt) applyInt64(c Int64Config) Int64Config { - c.unit = string(o) - return c -} - -func (o unitOpt) applyFloat64Observer(c Float64ObserverConfig) Float64ObserverConfig { - c.unit = string(o) - return c -} - -func (o unitOpt) applyInt64Observer(c Int64ObserverConfig) Int64ObserverConfig { - c.unit = string(o) - return c -} - -// WithUnit sets the instrument unit. -func WithUnit(u string) Option { return unitOpt(u) } diff --git a/vendor/go.opentelemetry.io/otel/metric/instrument/syncfloat64.go b/vendor/go.opentelemetry.io/otel/metric/instrument/syncfloat64.go deleted file mode 100644 index 2cdfeb2691a..00000000000 --- a/vendor/go.opentelemetry.io/otel/metric/instrument/syncfloat64.go +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright The OpenTelemetry Authors -// -// 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 instrument // import "go.opentelemetry.io/otel/metric/instrument" - -import ( - "context" - - "go.opentelemetry.io/otel/attribute" -) - -// Float64Counter is an instrument that records increasing float64 values. -// -// Warning: methods may be added to this interface in minor releases. -type Float64Counter interface { - // Add records a change to the counter. - Add(ctx context.Context, incr float64, attrs ...attribute.KeyValue) - - Synchronous -} - -// Float64UpDownCounter is an instrument that records increasing or decreasing -// float64 values. -// -// Warning: methods may be added to this interface in minor releases. -type Float64UpDownCounter interface { - // Add records a change to the counter. - Add(ctx context.Context, incr float64, attrs ...attribute.KeyValue) - - Synchronous -} - -// Float64Histogram is an instrument that records a distribution of float64 -// values. -// -// Warning: methods may be added to this interface in minor releases. -type Float64Histogram interface { - // Record adds an additional value to the distribution. - Record(ctx context.Context, incr float64, attrs ...attribute.KeyValue) - - Synchronous -} - -// Float64Config contains options for Asynchronous instruments that -// observe float64 values. -type Float64Config struct { - description string - unit string -} - -// Float64Config contains options for Synchronous instruments that record -// float64 values. -func NewFloat64Config(opts ...Float64Option) Float64Config { - var config Float64Config - for _, o := range opts { - config = o.applyFloat64(config) - } - return config -} - -// Description returns the Config description. -func (c Float64Config) Description() string { - return c.description -} - -// Unit returns the Config unit. -func (c Float64Config) Unit() string { - return c.unit -} - -// Float64Option applies options to synchronous float64 instruments. -type Float64Option interface { - applyFloat64(Float64Config) Float64Config -} diff --git a/vendor/go.opentelemetry.io/otel/metric/instrument/syncint64.go b/vendor/go.opentelemetry.io/otel/metric/instrument/syncint64.go deleted file mode 100644 index e212c6d695f..00000000000 --- a/vendor/go.opentelemetry.io/otel/metric/instrument/syncint64.go +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright The OpenTelemetry Authors -// -// 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 instrument // import "go.opentelemetry.io/otel/metric/instrument" - -import ( - "context" - - "go.opentelemetry.io/otel/attribute" -) - -// Int64Counter is an instrument that records increasing int64 values. -// -// Warning: methods may be added to this interface in minor releases. -type Int64Counter interface { - // Add records a change to the counter. - Add(ctx context.Context, incr int64, attrs ...attribute.KeyValue) - - Synchronous -} - -// Int64UpDownCounter is an instrument that records increasing or decreasing -// int64 values. -// -// Warning: methods may be added to this interface in minor releases. -type Int64UpDownCounter interface { - // Add records a change to the counter. - Add(ctx context.Context, incr int64, attrs ...attribute.KeyValue) - - Synchronous -} - -// Int64Histogram is an instrument that records a distribution of int64 -// values. -// -// Warning: methods may be added to this interface in minor releases. -type Int64Histogram interface { - // Record adds an additional value to the distribution. - Record(ctx context.Context, incr int64, attrs ...attribute.KeyValue) - - Synchronous -} - -// Int64Config contains options for Synchronous instruments that record int64 -// values. -type Int64Config struct { - description string - unit string -} - -// NewInt64Config returns a new Int64Config with all opts -// applied. -func NewInt64Config(opts ...Int64Option) Int64Config { - var config Int64Config - for _, o := range opts { - config = o.applyInt64(config) - } - return config -} - -// Description returns the Config description. -func (c Int64Config) Description() string { - return c.description -} - -// Unit returns the Config unit. -func (c Int64Config) Unit() string { - return c.unit -} - -// Int64Option applies options to synchronous int64 instruments. -type Int64Option interface { - applyInt64(Int64Config) Int64Config -} diff --git a/vendor/go.opentelemetry.io/otel/metric/internal/global/instruments.go b/vendor/go.opentelemetry.io/otel/metric/internal/global/instruments.go deleted file mode 100644 index d1480fa5f3e..00000000000 --- a/vendor/go.opentelemetry.io/otel/metric/internal/global/instruments.go +++ /dev/null @@ -1,355 +0,0 @@ -// Copyright The OpenTelemetry Authors -// -// 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 global // import "go.opentelemetry.io/otel/metric/internal/global" - -import ( - "context" - "sync/atomic" - - "go.opentelemetry.io/otel" - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/metric" - "go.opentelemetry.io/otel/metric/instrument" -) - -// unwrapper unwraps to return the underlying instrument implementation. -type unwrapper interface { - Unwrap() instrument.Asynchronous -} - -type afCounter struct { - instrument.Float64Observable - - name string - opts []instrument.Float64ObserverOption - - delegate atomic.Value //instrument.Float64ObservableCounter -} - -var _ unwrapper = (*afCounter)(nil) -var _ instrument.Float64ObservableCounter = (*afCounter)(nil) - -func (i *afCounter) setDelegate(m metric.Meter) { - ctr, err := m.Float64ObservableCounter(i.name, i.opts...) - if err != nil { - otel.Handle(err) - return - } - i.delegate.Store(ctr) -} - -func (i *afCounter) Unwrap() instrument.Asynchronous { - if ctr := i.delegate.Load(); ctr != nil { - return ctr.(instrument.Float64ObservableCounter) - } - return nil -} - -type afUpDownCounter struct { - instrument.Float64Observable - - name string - opts []instrument.Float64ObserverOption - - delegate atomic.Value //instrument.Float64ObservableUpDownCounter -} - -var _ unwrapper = (*afUpDownCounter)(nil) -var _ instrument.Float64ObservableUpDownCounter = (*afUpDownCounter)(nil) - -func (i *afUpDownCounter) setDelegate(m metric.Meter) { - ctr, err := m.Float64ObservableUpDownCounter(i.name, i.opts...) - if err != nil { - otel.Handle(err) - return - } - i.delegate.Store(ctr) -} - -func (i *afUpDownCounter) Unwrap() instrument.Asynchronous { - if ctr := i.delegate.Load(); ctr != nil { - return ctr.(instrument.Float64ObservableUpDownCounter) - } - return nil -} - -type afGauge struct { - instrument.Float64Observable - - name string - opts []instrument.Float64ObserverOption - - delegate atomic.Value //instrument.Float64ObservableGauge -} - -var _ unwrapper = (*afGauge)(nil) -var _ instrument.Float64ObservableGauge = (*afGauge)(nil) - -func (i *afGauge) setDelegate(m metric.Meter) { - ctr, err := m.Float64ObservableGauge(i.name, i.opts...) - if err != nil { - otel.Handle(err) - return - } - i.delegate.Store(ctr) -} - -func (i *afGauge) Unwrap() instrument.Asynchronous { - if ctr := i.delegate.Load(); ctr != nil { - return ctr.(instrument.Float64ObservableGauge) - } - return nil -} - -type aiCounter struct { - instrument.Int64Observable - - name string - opts []instrument.Int64ObserverOption - - delegate atomic.Value //instrument.Int64ObservableCounter -} - -var _ unwrapper = (*aiCounter)(nil) -var _ instrument.Int64ObservableCounter = (*aiCounter)(nil) - -func (i *aiCounter) setDelegate(m metric.Meter) { - ctr, err := m.Int64ObservableCounter(i.name, i.opts...) - if err != nil { - otel.Handle(err) - return - } - i.delegate.Store(ctr) -} - -func (i *aiCounter) Unwrap() instrument.Asynchronous { - if ctr := i.delegate.Load(); ctr != nil { - return ctr.(instrument.Int64ObservableCounter) - } - return nil -} - -type aiUpDownCounter struct { - instrument.Int64Observable - - name string - opts []instrument.Int64ObserverOption - - delegate atomic.Value //instrument.Int64ObservableUpDownCounter -} - -var _ unwrapper = (*aiUpDownCounter)(nil) -var _ instrument.Int64ObservableUpDownCounter = (*aiUpDownCounter)(nil) - -func (i *aiUpDownCounter) setDelegate(m metric.Meter) { - ctr, err := m.Int64ObservableUpDownCounter(i.name, i.opts...) - if err != nil { - otel.Handle(err) - return - } - i.delegate.Store(ctr) -} - -func (i *aiUpDownCounter) Unwrap() instrument.Asynchronous { - if ctr := i.delegate.Load(); ctr != nil { - return ctr.(instrument.Int64ObservableUpDownCounter) - } - return nil -} - -type aiGauge struct { - instrument.Int64Observable - - name string - opts []instrument.Int64ObserverOption - - delegate atomic.Value //instrument.Int64ObservableGauge -} - -var _ unwrapper = (*aiGauge)(nil) -var _ instrument.Int64ObservableGauge = (*aiGauge)(nil) - -func (i *aiGauge) setDelegate(m metric.Meter) { - ctr, err := m.Int64ObservableGauge(i.name, i.opts...) - if err != nil { - otel.Handle(err) - return - } - i.delegate.Store(ctr) -} - -func (i *aiGauge) Unwrap() instrument.Asynchronous { - if ctr := i.delegate.Load(); ctr != nil { - return ctr.(instrument.Int64ObservableGauge) - } - return nil -} - -// Sync Instruments. -type sfCounter struct { - name string - opts []instrument.Float64Option - - delegate atomic.Value //instrument.Float64Counter - - instrument.Synchronous -} - -var _ instrument.Float64Counter = (*sfCounter)(nil) - -func (i *sfCounter) setDelegate(m metric.Meter) { - ctr, err := m.Float64Counter(i.name, i.opts...) - if err != nil { - otel.Handle(err) - return - } - i.delegate.Store(ctr) -} - -func (i *sfCounter) Add(ctx context.Context, incr float64, attrs ...attribute.KeyValue) { - if ctr := i.delegate.Load(); ctr != nil { - ctr.(instrument.Float64Counter).Add(ctx, incr, attrs...) - } -} - -type sfUpDownCounter struct { - name string - opts []instrument.Float64Option - - delegate atomic.Value //instrument.Float64UpDownCounter - - instrument.Synchronous -} - -var _ instrument.Float64UpDownCounter = (*sfUpDownCounter)(nil) - -func (i *sfUpDownCounter) setDelegate(m metric.Meter) { - ctr, err := m.Float64UpDownCounter(i.name, i.opts...) - if err != nil { - otel.Handle(err) - return - } - i.delegate.Store(ctr) -} - -func (i *sfUpDownCounter) Add(ctx context.Context, incr float64, attrs ...attribute.KeyValue) { - if ctr := i.delegate.Load(); ctr != nil { - ctr.(instrument.Float64UpDownCounter).Add(ctx, incr, attrs...) - } -} - -type sfHistogram struct { - name string - opts []instrument.Float64Option - - delegate atomic.Value //instrument.Float64Histogram - - instrument.Synchronous -} - -var _ instrument.Float64Histogram = (*sfHistogram)(nil) - -func (i *sfHistogram) setDelegate(m metric.Meter) { - ctr, err := m.Float64Histogram(i.name, i.opts...) - if err != nil { - otel.Handle(err) - return - } - i.delegate.Store(ctr) -} - -func (i *sfHistogram) Record(ctx context.Context, x float64, attrs ...attribute.KeyValue) { - if ctr := i.delegate.Load(); ctr != nil { - ctr.(instrument.Float64Histogram).Record(ctx, x, attrs...) - } -} - -type siCounter struct { - name string - opts []instrument.Int64Option - - delegate atomic.Value //instrument.Int64Counter - - instrument.Synchronous -} - -var _ instrument.Int64Counter = (*siCounter)(nil) - -func (i *siCounter) setDelegate(m metric.Meter) { - ctr, err := m.Int64Counter(i.name, i.opts...) - if err != nil { - otel.Handle(err) - return - } - i.delegate.Store(ctr) -} - -func (i *siCounter) Add(ctx context.Context, x int64, attrs ...attribute.KeyValue) { - if ctr := i.delegate.Load(); ctr != nil { - ctr.(instrument.Int64Counter).Add(ctx, x, attrs...) - } -} - -type siUpDownCounter struct { - name string - opts []instrument.Int64Option - - delegate atomic.Value //instrument.Int64UpDownCounter - - instrument.Synchronous -} - -var _ instrument.Int64UpDownCounter = (*siUpDownCounter)(nil) - -func (i *siUpDownCounter) setDelegate(m metric.Meter) { - ctr, err := m.Int64UpDownCounter(i.name, i.opts...) - if err != nil { - otel.Handle(err) - return - } - i.delegate.Store(ctr) -} - -func (i *siUpDownCounter) Add(ctx context.Context, x int64, attrs ...attribute.KeyValue) { - if ctr := i.delegate.Load(); ctr != nil { - ctr.(instrument.Int64UpDownCounter).Add(ctx, x, attrs...) - } -} - -type siHistogram struct { - name string - opts []instrument.Int64Option - - delegate atomic.Value //instrument.Int64Histogram - - instrument.Synchronous -} - -var _ instrument.Int64Histogram = (*siHistogram)(nil) - -func (i *siHistogram) setDelegate(m metric.Meter) { - ctr, err := m.Int64Histogram(i.name, i.opts...) - if err != nil { - otel.Handle(err) - return - } - i.delegate.Store(ctr) -} - -func (i *siHistogram) Record(ctx context.Context, x int64, attrs ...attribute.KeyValue) { - if ctr := i.delegate.Load(); ctr != nil { - ctr.(instrument.Int64Histogram).Record(ctx, x, attrs...) - } -} diff --git a/vendor/go.opentelemetry.io/otel/metric/internal/global/state.go b/vendor/go.opentelemetry.io/otel/metric/internal/global/state.go deleted file mode 100644 index 47c0d787d8a..00000000000 --- a/vendor/go.opentelemetry.io/otel/metric/internal/global/state.go +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright The OpenTelemetry Authors -// -// 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 -// -// htmp://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package global // import "go.opentelemetry.io/otel/metric/internal/global" - -import ( - "errors" - "sync" - "sync/atomic" - - "go.opentelemetry.io/otel/internal/global" - "go.opentelemetry.io/otel/metric" -) - -var ( - globalMeterProvider = defaultMeterProvider() - - delegateMeterOnce sync.Once -) - -type meterProviderHolder struct { - mp metric.MeterProvider -} - -// MeterProvider is the internal implementation for global.MeterProvider. -func MeterProvider() metric.MeterProvider { - return globalMeterProvider.Load().(meterProviderHolder).mp -} - -// SetMeterProvider is the internal implementation for global.SetMeterProvider. -func SetMeterProvider(mp metric.MeterProvider) { - current := MeterProvider() - if _, cOk := current.(*meterProvider); cOk { - if _, mpOk := mp.(*meterProvider); mpOk && current == mp { - // Do not assign the default delegating MeterProvider to delegate - // to itself. - global.Error( - errors.New("no delegate configured in meter provider"), - "Setting meter provider to it's current value. No delegate will be configured", - ) - return - } - } - - delegateMeterOnce.Do(func() { - if def, ok := current.(*meterProvider); ok { - def.setDelegate(mp) - } - }) - globalMeterProvider.Store(meterProviderHolder{mp: mp}) -} - -func defaultMeterProvider() *atomic.Value { - v := &atomic.Value{} - v.Store(meterProviderHolder{mp: &meterProvider{}}) - return v -} diff --git a/vendor/go.opentelemetry.io/otel/metric/meter.go b/vendor/go.opentelemetry.io/otel/metric/meter.go index 2f69d2ae54f..8e1917c3214 100644 --- a/vendor/go.opentelemetry.io/otel/metric/meter.go +++ b/vendor/go.opentelemetry.io/otel/metric/meter.go @@ -17,80 +17,134 @@ package metric // import "go.opentelemetry.io/otel/metric" import ( "context" - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/metric/instrument" + "go.opentelemetry.io/otel/metric/embedded" ) // MeterProvider provides access to named Meter instances, for instrumenting -// an application or library. +// an application or package. // -// Warning: methods may be added to this interface in minor releases. +// Warning: Methods may be added to this interface in minor releases. See +// package documentation on API implementation for information on how to set +// default behavior for unimplemented methods. type MeterProvider interface { - // Meter creates an instance of a `Meter` interface. The name must be the - // name of the library providing instrumentation. This name may be the same - // as the instrumented code only if that code provides built-in - // instrumentation. If the name is empty, then a implementation defined - // default name will be used instead. + // Users of the interface can ignore this. This embedded type is only used + // by implementations of this interface. See the "API Implementations" + // section of the package documentation for more information. + embedded.MeterProvider + + // Meter returns a new Meter with the provided name and configuration. + // + // A Meter should be scoped at most to a single package. The name needs to + // be unique so it does not collide with other names used by + // an application, nor other applications. To achieve this, the import path + // of the instrumentation package is recommended to be used as name. + // + // If the name is empty, then an implementation defined default name will + // be used instead. Meter(name string, opts ...MeterOption) Meter } // Meter provides access to instrument instances for recording metrics. // -// Warning: methods may be added to this interface in minor releases. +// Warning: Methods may be added to this interface in minor releases. See +// package documentation on API implementation for information on how to set +// default behavior for unimplemented methods. type Meter interface { - // Int64Counter returns a new instrument identified by name and configured - // with options. The instrument is used to synchronously record increasing - // int64 measurements during a computational operation. - Int64Counter(name string, options ...instrument.Int64Option) (instrument.Int64Counter, error) - // Int64UpDownCounter returns a new instrument identified by name and - // configured with options. The instrument is used to synchronously record - // int64 measurements during a computational operation. - Int64UpDownCounter(name string, options ...instrument.Int64Option) (instrument.Int64UpDownCounter, error) - // Int64Histogram returns a new instrument identified by name and - // configured with options. The instrument is used to synchronously record - // the distribution of int64 measurements during a computational operation. - Int64Histogram(name string, options ...instrument.Int64Option) (instrument.Int64Histogram, error) - // Int64ObservableCounter returns a new instrument identified by name and - // configured with options. The instrument is used to asynchronously record - // increasing int64 measurements once per a measurement collection cycle. - Int64ObservableCounter(name string, options ...instrument.Int64ObserverOption) (instrument.Int64ObservableCounter, error) - // Int64ObservableUpDownCounter returns a new instrument identified by name - // and configured with options. The instrument is used to asynchronously - // record int64 measurements once per a measurement collection cycle. - Int64ObservableUpDownCounter(name string, options ...instrument.Int64ObserverOption) (instrument.Int64ObservableUpDownCounter, error) - // Int64ObservableGauge returns a new instrument identified by name and - // configured with options. The instrument is used to asynchronously record - // instantaneous int64 measurements once per a measurement collection - // cycle. - Int64ObservableGauge(name string, options ...instrument.Int64ObserverOption) (instrument.Int64ObservableGauge, error) + // Users of the interface can ignore this. This embedded type is only used + // by implementations of this interface. See the "API Implementations" + // section of the package documentation for more information. + embedded.Meter - // Float64Counter returns a new instrument identified by name and - // configured with options. The instrument is used to synchronously record - // increasing float64 measurements during a computational operation. - Float64Counter(name string, options ...instrument.Float64Option) (instrument.Float64Counter, error) - // Float64UpDownCounter returns a new instrument identified by name and - // configured with options. The instrument is used to synchronously record - // float64 measurements during a computational operation. - Float64UpDownCounter(name string, options ...instrument.Float64Option) (instrument.Float64UpDownCounter, error) - // Float64Histogram returns a new instrument identified by name and - // configured with options. The instrument is used to synchronously record - // the distribution of float64 measurements during a computational + // Int64Counter returns a new Int64Counter instrument identified by name + // and configured with options. The instrument is used to synchronously + // record increasing int64 measurements during a computational operation. + Int64Counter(name string, options ...Int64CounterOption) (Int64Counter, error) + // Int64UpDownCounter returns a new Int64UpDownCounter instrument + // identified by name and configured with options. The instrument is used + // to synchronously record int64 measurements during a computational // operation. - Float64Histogram(name string, options ...instrument.Float64Option) (instrument.Float64Histogram, error) - // Float64ObservableCounter returns a new instrument identified by name and - // configured with options. The instrument is used to asynchronously record - // increasing float64 measurements once per a measurement collection cycle. - Float64ObservableCounter(name string, options ...instrument.Float64ObserverOption) (instrument.Float64ObservableCounter, error) - // Float64ObservableUpDownCounter returns a new instrument identified by + Int64UpDownCounter(name string, options ...Int64UpDownCounterOption) (Int64UpDownCounter, error) + // Int64Histogram returns a new Int64Histogram instrument identified by + // name and configured with options. The instrument is used to + // synchronously record the distribution of int64 measurements during a + // computational operation. + Int64Histogram(name string, options ...Int64HistogramOption) (Int64Histogram, error) + // Int64ObservableCounter returns a new Int64ObservableCounter identified + // by name and configured with options. The instrument is used to + // asynchronously record increasing int64 measurements once per a + // measurement collection cycle. + // + // Measurements for the returned instrument are made via a callback. Use + // the WithInt64Callback option to register the callback here, or use the + // RegisterCallback method of this Meter to register one later. See the + // Measurements section of the package documentation for more information. + Int64ObservableCounter(name string, options ...Int64ObservableCounterOption) (Int64ObservableCounter, error) + // Int64ObservableUpDownCounter returns a new Int64ObservableUpDownCounter + // instrument identified by name and configured with options. The + // instrument is used to asynchronously record int64 measurements once per + // a measurement collection cycle. + // + // Measurements for the returned instrument are made via a callback. Use + // the WithInt64Callback option to register the callback here, or use the + // RegisterCallback method of this Meter to register one later. See the + // Measurements section of the package documentation for more information. + Int64ObservableUpDownCounter(name string, options ...Int64ObservableUpDownCounterOption) (Int64ObservableUpDownCounter, error) + // Int64ObservableGauge returns a new Int64ObservableGauge instrument + // identified by name and configured with options. The instrument is used + // to asynchronously record instantaneous int64 measurements once per a + // measurement collection cycle. + // + // Measurements for the returned instrument are made via a callback. Use + // the WithInt64Callback option to register the callback here, or use the + // RegisterCallback method of this Meter to register one later. See the + // Measurements section of the package documentation for more information. + Int64ObservableGauge(name string, options ...Int64ObservableGaugeOption) (Int64ObservableGauge, error) + + // Float64Counter returns a new Float64Counter instrument identified by + // name and configured with options. The instrument is used to + // synchronously record increasing float64 measurements during a + // computational operation. + Float64Counter(name string, options ...Float64CounterOption) (Float64Counter, error) + // Float64UpDownCounter returns a new Float64UpDownCounter instrument + // identified by name and configured with options. The instrument is used + // to synchronously record float64 measurements during a computational + // operation. + Float64UpDownCounter(name string, options ...Float64UpDownCounterOption) (Float64UpDownCounter, error) + // Float64Histogram returns a new Float64Histogram instrument identified by // name and configured with options. The instrument is used to - // asynchronously record float64 measurements once per a measurement - // collection cycle. - Float64ObservableUpDownCounter(name string, options ...instrument.Float64ObserverOption) (instrument.Float64ObservableUpDownCounter, error) - // Float64ObservableGauge returns a new instrument identified by name and + // synchronously record the distribution of float64 measurements during a + // computational operation. + Float64Histogram(name string, options ...Float64HistogramOption) (Float64Histogram, error) + // Float64ObservableCounter returns a new Float64ObservableCounter + // instrument identified by name and configured with options. The + // instrument is used to asynchronously record increasing float64 + // measurements once per a measurement collection cycle. + // + // Measurements for the returned instrument are made via a callback. Use + // the WithFloat64Callback option to register the callback here, or use the + // RegisterCallback method of this Meter to register one later. See the + // Measurements section of the package documentation for more information. + Float64ObservableCounter(name string, options ...Float64ObservableCounterOption) (Float64ObservableCounter, error) + // Float64ObservableUpDownCounter returns a new + // Float64ObservableUpDownCounter instrument identified by name and // configured with options. The instrument is used to asynchronously record - // instantaneous float64 measurements once per a measurement collection - // cycle. - Float64ObservableGauge(name string, options ...instrument.Float64ObserverOption) (instrument.Float64ObservableGauge, error) + // float64 measurements once per a measurement collection cycle. + // + // Measurements for the returned instrument are made via a callback. Use + // the WithFloat64Callback option to register the callback here, or use the + // RegisterCallback method of this Meter to register one later. See the + // Measurements section of the package documentation for more information. + Float64ObservableUpDownCounter(name string, options ...Float64ObservableUpDownCounterOption) (Float64ObservableUpDownCounter, error) + // Float64ObservableGauge returns a new Float64ObservableGauge instrument + // identified by name and configured with options. The instrument is used + // to asynchronously record instantaneous float64 measurements once per a + // measurement collection cycle. + // + // Measurements for the returned instrument are made via a callback. Use + // the WithFloat64Callback option to register the callback here, or use the + // RegisterCallback method of this Meter to register one later. See the + // Measurements section of the package documentation for more information. + Float64ObservableGauge(name string, options ...Float64ObservableGaugeOption) (Float64ObservableGauge, error) // RegisterCallback registers f to be called during the collection of a // measurement cycle. @@ -103,12 +157,12 @@ type Meter interface { // // If no instruments are passed, f should not be registered nor called // during collection. - RegisterCallback(f Callback, instruments ...instrument.Asynchronous) (Registration, error) + RegisterCallback(f Callback, instruments ...Observable) (Registration, error) } // Callback is a function registered with a Meter that makes observations for // the set of instruments it is registered with. The Observer parameter is used -// to record measurment observations for these instruments. +// to record measurement observations for these instruments. // // The function needs to complete in a finite amount of time and the deadline // of the passed context is expected to be honored. @@ -121,16 +175,34 @@ type Meter interface { type Callback func(context.Context, Observer) error // Observer records measurements for multiple instruments in a Callback. +// +// Warning: Methods may be added to this interface in minor releases. See +// package documentation on API implementation for information on how to set +// default behavior for unimplemented methods. type Observer interface { - // ObserveFloat64 records the float64 value with attributes for obsrv. - ObserveFloat64(obsrv instrument.Float64Observable, value float64, attributes ...attribute.KeyValue) - // ObserveInt64 records the int64 value with attributes for obsrv. - ObserveInt64(obsrv instrument.Int64Observable, value int64, attributes ...attribute.KeyValue) + // Users of the interface can ignore this. This embedded type is only used + // by implementations of this interface. See the "API Implementations" + // section of the package documentation for more information. + embedded.Observer + + // ObserveFloat64 records the float64 value for obsrv. + ObserveFloat64(obsrv Float64Observable, value float64, opts ...ObserveOption) + // ObserveInt64 records the int64 value for obsrv. + ObserveInt64(obsrv Int64Observable, value int64, opts ...ObserveOption) } // Registration is an token representing the unique registration of a callback // for a set of instruments with a Meter. +// +// Warning: Methods may be added to this interface in minor releases. See +// package documentation on API implementation for information on how to set +// default behavior for unimplemented methods. type Registration interface { + // Users of the interface can ignore this. This embedded type is only used + // by implementations of this interface. See the "API Implementations" + // section of the package documentation for more information. + embedded.Registration + // Unregister removes the callback registration from a Meter. // // This method needs to be idempotent and concurrent safe. diff --git a/vendor/go.opentelemetry.io/otel/metric/noop.go b/vendor/go.opentelemetry.io/otel/metric/noop.go deleted file mode 100644 index f38619e39ab..00000000000 --- a/vendor/go.opentelemetry.io/otel/metric/noop.go +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright The OpenTelemetry Authors -// -// 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 metric // import "go.opentelemetry.io/otel/metric" - -import ( - "context" - - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/metric/instrument" -) - -// NewNoopMeterProvider creates a MeterProvider that does not record any metrics. -func NewNoopMeterProvider() MeterProvider { - return noopMeterProvider{} -} - -type noopMeterProvider struct{} - -func (noopMeterProvider) Meter(string, ...MeterOption) Meter { - return noopMeter{} -} - -// NewNoopMeter creates a Meter that does not record any metrics. -func NewNoopMeter() Meter { - return noopMeter{} -} - -type noopMeter struct{} - -func (noopMeter) Int64Counter(string, ...instrument.Int64Option) (instrument.Int64Counter, error) { - return nonrecordingSyncInt64Instrument{}, nil -} - -func (noopMeter) Int64UpDownCounter(string, ...instrument.Int64Option) (instrument.Int64UpDownCounter, error) { - return nonrecordingSyncInt64Instrument{}, nil -} - -func (noopMeter) Int64Histogram(string, ...instrument.Int64Option) (instrument.Int64Histogram, error) { - return nonrecordingSyncInt64Instrument{}, nil -} - -func (noopMeter) Int64ObservableCounter(string, ...instrument.Int64ObserverOption) (instrument.Int64ObservableCounter, error) { - return nonrecordingAsyncInt64Instrument{}, nil -} - -func (noopMeter) Int64ObservableUpDownCounter(string, ...instrument.Int64ObserverOption) (instrument.Int64ObservableUpDownCounter, error) { - return nonrecordingAsyncInt64Instrument{}, nil -} - -func (noopMeter) Int64ObservableGauge(string, ...instrument.Int64ObserverOption) (instrument.Int64ObservableGauge, error) { - return nonrecordingAsyncInt64Instrument{}, nil -} - -func (noopMeter) Float64Counter(string, ...instrument.Float64Option) (instrument.Float64Counter, error) { - return nonrecordingSyncFloat64Instrument{}, nil -} - -func (noopMeter) Float64UpDownCounter(string, ...instrument.Float64Option) (instrument.Float64UpDownCounter, error) { - return nonrecordingSyncFloat64Instrument{}, nil -} - -func (noopMeter) Float64Histogram(string, ...instrument.Float64Option) (instrument.Float64Histogram, error) { - return nonrecordingSyncFloat64Instrument{}, nil -} - -func (noopMeter) Float64ObservableCounter(string, ...instrument.Float64ObserverOption) (instrument.Float64ObservableCounter, error) { - return nonrecordingAsyncFloat64Instrument{}, nil -} - -func (noopMeter) Float64ObservableUpDownCounter(string, ...instrument.Float64ObserverOption) (instrument.Float64ObservableUpDownCounter, error) { - return nonrecordingAsyncFloat64Instrument{}, nil -} - -func (noopMeter) Float64ObservableGauge(string, ...instrument.Float64ObserverOption) (instrument.Float64ObservableGauge, error) { - return nonrecordingAsyncFloat64Instrument{}, nil -} - -// RegisterCallback creates a register callback that does not record any metrics. -func (noopMeter) RegisterCallback(Callback, ...instrument.Asynchronous) (Registration, error) { - return noopReg{}, nil -} - -type noopReg struct{} - -func (noopReg) Unregister() error { return nil } - -type nonrecordingAsyncFloat64Instrument struct { - instrument.Float64Observable -} - -var ( - _ instrument.Float64ObservableCounter = nonrecordingAsyncFloat64Instrument{} - _ instrument.Float64ObservableUpDownCounter = nonrecordingAsyncFloat64Instrument{} - _ instrument.Float64ObservableGauge = nonrecordingAsyncFloat64Instrument{} -) - -type nonrecordingAsyncInt64Instrument struct { - instrument.Int64Observable -} - -var ( - _ instrument.Int64ObservableCounter = nonrecordingAsyncInt64Instrument{} - _ instrument.Int64ObservableUpDownCounter = nonrecordingAsyncInt64Instrument{} - _ instrument.Int64ObservableGauge = nonrecordingAsyncInt64Instrument{} -) - -type nonrecordingSyncFloat64Instrument struct { - instrument.Synchronous -} - -var ( - _ instrument.Float64Counter = nonrecordingSyncFloat64Instrument{} - _ instrument.Float64UpDownCounter = nonrecordingSyncFloat64Instrument{} - _ instrument.Float64Histogram = nonrecordingSyncFloat64Instrument{} -) - -func (nonrecordingSyncFloat64Instrument) Add(context.Context, float64, ...attribute.KeyValue) {} -func (nonrecordingSyncFloat64Instrument) Record(context.Context, float64, ...attribute.KeyValue) {} - -type nonrecordingSyncInt64Instrument struct { - instrument.Synchronous -} - -var ( - _ instrument.Int64Counter = nonrecordingSyncInt64Instrument{} - _ instrument.Int64UpDownCounter = nonrecordingSyncInt64Instrument{} - _ instrument.Int64Histogram = nonrecordingSyncInt64Instrument{} -) - -func (nonrecordingSyncInt64Instrument) Add(context.Context, int64, ...attribute.KeyValue) {} -func (nonrecordingSyncInt64Instrument) Record(context.Context, int64, ...attribute.KeyValue) {} diff --git a/vendor/go.opentelemetry.io/otel/metric/syncfloat64.go b/vendor/go.opentelemetry.io/otel/metric/syncfloat64.go new file mode 100644 index 00000000000..f0b063721d8 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/metric/syncfloat64.go @@ -0,0 +1,179 @@ +// Copyright The OpenTelemetry Authors +// +// 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 metric // import "go.opentelemetry.io/otel/metric" + +import ( + "context" + + "go.opentelemetry.io/otel/metric/embedded" +) + +// Float64Counter is an instrument that records increasing float64 values. +// +// Warning: Methods may be added to this interface in minor releases. See +// package documentation on API implementation for information on how to set +// default behavior for unimplemented methods. +type Float64Counter interface { + // Users of the interface can ignore this. This embedded type is only used + // by implementations of this interface. See the "API Implementations" + // section of the package documentation for more information. + embedded.Float64Counter + + // Add records a change to the counter. + // + // Use the WithAttributeSet (or, if performance is not a concern, + // the WithAttributes) option to include measurement attributes. + Add(ctx context.Context, incr float64, options ...AddOption) +} + +// Float64CounterConfig contains options for synchronous counter instruments that +// record int64 values. +type Float64CounterConfig struct { + description string + unit string +} + +// NewFloat64CounterConfig returns a new [Float64CounterConfig] with all opts +// applied. +func NewFloat64CounterConfig(opts ...Float64CounterOption) Float64CounterConfig { + var config Float64CounterConfig + for _, o := range opts { + config = o.applyFloat64Counter(config) + } + return config +} + +// Description returns the configured description. +func (c Float64CounterConfig) Description() string { + return c.description +} + +// Unit returns the configured unit. +func (c Float64CounterConfig) Unit() string { + return c.unit +} + +// Float64CounterOption applies options to a [Float64CounterConfig]. See +// [InstrumentOption] for other options that can be used as a +// Float64CounterOption. +type Float64CounterOption interface { + applyFloat64Counter(Float64CounterConfig) Float64CounterConfig +} + +// Float64UpDownCounter is an instrument that records increasing or decreasing +// float64 values. +// +// Warning: Methods may be added to this interface in minor releases. See +// package documentation on API implementation for information on how to set +// default behavior for unimplemented methods. +type Float64UpDownCounter interface { + // Users of the interface can ignore this. This embedded type is only used + // by implementations of this interface. See the "API Implementations" + // section of the package documentation for more information. + embedded.Float64UpDownCounter + + // Add records a change to the counter. + // + // Use the WithAttributeSet (or, if performance is not a concern, + // the WithAttributes) option to include measurement attributes. + Add(ctx context.Context, incr float64, options ...AddOption) +} + +// Float64UpDownCounterConfig contains options for synchronous counter +// instruments that record int64 values. +type Float64UpDownCounterConfig struct { + description string + unit string +} + +// NewFloat64UpDownCounterConfig returns a new [Float64UpDownCounterConfig] +// with all opts applied. +func NewFloat64UpDownCounterConfig(opts ...Float64UpDownCounterOption) Float64UpDownCounterConfig { + var config Float64UpDownCounterConfig + for _, o := range opts { + config = o.applyFloat64UpDownCounter(config) + } + return config +} + +// Description returns the configured description. +func (c Float64UpDownCounterConfig) Description() string { + return c.description +} + +// Unit returns the configured unit. +func (c Float64UpDownCounterConfig) Unit() string { + return c.unit +} + +// Float64UpDownCounterOption applies options to a +// [Float64UpDownCounterConfig]. See [InstrumentOption] for other options that +// can be used as a Float64UpDownCounterOption. +type Float64UpDownCounterOption interface { + applyFloat64UpDownCounter(Float64UpDownCounterConfig) Float64UpDownCounterConfig +} + +// Float64Histogram is an instrument that records a distribution of float64 +// values. +// +// Warning: Methods may be added to this interface in minor releases. See +// package documentation on API implementation for information on how to set +// default behavior for unimplemented methods. +type Float64Histogram interface { + // Users of the interface can ignore this. This embedded type is only used + // by implementations of this interface. See the "API Implementations" + // section of the package documentation for more information. + embedded.Float64Histogram + + // Record adds an additional value to the distribution. + // + // Use the WithAttributeSet (or, if performance is not a concern, + // the WithAttributes) option to include measurement attributes. + Record(ctx context.Context, incr float64, options ...RecordOption) +} + +// Float64HistogramConfig contains options for synchronous counter instruments +// that record int64 values. +type Float64HistogramConfig struct { + description string + unit string +} + +// NewFloat64HistogramConfig returns a new [Float64HistogramConfig] with all +// opts applied. +func NewFloat64HistogramConfig(opts ...Float64HistogramOption) Float64HistogramConfig { + var config Float64HistogramConfig + for _, o := range opts { + config = o.applyFloat64Histogram(config) + } + return config +} + +// Description returns the configured description. +func (c Float64HistogramConfig) Description() string { + return c.description +} + +// Unit returns the configured unit. +func (c Float64HistogramConfig) Unit() string { + return c.unit +} + +// Float64HistogramOption applies options to a [Float64HistogramConfig]. See +// [InstrumentOption] for other options that can be used as a +// Float64HistogramOption. +type Float64HistogramOption interface { + applyFloat64Histogram(Float64HistogramConfig) Float64HistogramConfig +} diff --git a/vendor/go.opentelemetry.io/otel/metric/syncint64.go b/vendor/go.opentelemetry.io/otel/metric/syncint64.go new file mode 100644 index 00000000000..6f508eb66d4 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/metric/syncint64.go @@ -0,0 +1,179 @@ +// Copyright The OpenTelemetry Authors +// +// 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 metric // import "go.opentelemetry.io/otel/metric" + +import ( + "context" + + "go.opentelemetry.io/otel/metric/embedded" +) + +// Int64Counter is an instrument that records increasing int64 values. +// +// Warning: Methods may be added to this interface in minor releases. See +// package documentation on API implementation for information on how to set +// default behavior for unimplemented methods. +type Int64Counter interface { + // Users of the interface can ignore this. This embedded type is only used + // by implementations of this interface. See the "API Implementations" + // section of the package documentation for more information. + embedded.Int64Counter + + // Add records a change to the counter. + // + // Use the WithAttributeSet (or, if performance is not a concern, + // the WithAttributes) option to include measurement attributes. + Add(ctx context.Context, incr int64, options ...AddOption) +} + +// Int64CounterConfig contains options for synchronous counter instruments that +// record int64 values. +type Int64CounterConfig struct { + description string + unit string +} + +// NewInt64CounterConfig returns a new [Int64CounterConfig] with all opts +// applied. +func NewInt64CounterConfig(opts ...Int64CounterOption) Int64CounterConfig { + var config Int64CounterConfig + for _, o := range opts { + config = o.applyInt64Counter(config) + } + return config +} + +// Description returns the configured description. +func (c Int64CounterConfig) Description() string { + return c.description +} + +// Unit returns the configured unit. +func (c Int64CounterConfig) Unit() string { + return c.unit +} + +// Int64CounterOption applies options to a [Int64CounterConfig]. See +// [InstrumentOption] for other options that can be used as an +// Int64CounterOption. +type Int64CounterOption interface { + applyInt64Counter(Int64CounterConfig) Int64CounterConfig +} + +// Int64UpDownCounter is an instrument that records increasing or decreasing +// int64 values. +// +// Warning: Methods may be added to this interface in minor releases. See +// package documentation on API implementation for information on how to set +// default behavior for unimplemented methods. +type Int64UpDownCounter interface { + // Users of the interface can ignore this. This embedded type is only used + // by implementations of this interface. See the "API Implementations" + // section of the package documentation for more information. + embedded.Int64UpDownCounter + + // Add records a change to the counter. + // + // Use the WithAttributeSet (or, if performance is not a concern, + // the WithAttributes) option to include measurement attributes. + Add(ctx context.Context, incr int64, options ...AddOption) +} + +// Int64UpDownCounterConfig contains options for synchronous counter +// instruments that record int64 values. +type Int64UpDownCounterConfig struct { + description string + unit string +} + +// NewInt64UpDownCounterConfig returns a new [Int64UpDownCounterConfig] with +// all opts applied. +func NewInt64UpDownCounterConfig(opts ...Int64UpDownCounterOption) Int64UpDownCounterConfig { + var config Int64UpDownCounterConfig + for _, o := range opts { + config = o.applyInt64UpDownCounter(config) + } + return config +} + +// Description returns the configured description. +func (c Int64UpDownCounterConfig) Description() string { + return c.description +} + +// Unit returns the configured unit. +func (c Int64UpDownCounterConfig) Unit() string { + return c.unit +} + +// Int64UpDownCounterOption applies options to a [Int64UpDownCounterConfig]. +// See [InstrumentOption] for other options that can be used as an +// Int64UpDownCounterOption. +type Int64UpDownCounterOption interface { + applyInt64UpDownCounter(Int64UpDownCounterConfig) Int64UpDownCounterConfig +} + +// Int64Histogram is an instrument that records a distribution of int64 +// values. +// +// Warning: Methods may be added to this interface in minor releases. See +// package documentation on API implementation for information on how to set +// default behavior for unimplemented methods. +type Int64Histogram interface { + // Users of the interface can ignore this. This embedded type is only used + // by implementations of this interface. See the "API Implementations" + // section of the package documentation for more information. + embedded.Int64Histogram + + // Record adds an additional value to the distribution. + // + // Use the WithAttributeSet (or, if performance is not a concern, + // the WithAttributes) option to include measurement attributes. + Record(ctx context.Context, incr int64, options ...RecordOption) +} + +// Int64HistogramConfig contains options for synchronous counter instruments +// that record int64 values. +type Int64HistogramConfig struct { + description string + unit string +} + +// NewInt64HistogramConfig returns a new [Int64HistogramConfig] with all opts +// applied. +func NewInt64HistogramConfig(opts ...Int64HistogramOption) Int64HistogramConfig { + var config Int64HistogramConfig + for _, o := range opts { + config = o.applyInt64Histogram(config) + } + return config +} + +// Description returns the configured description. +func (c Int64HistogramConfig) Description() string { + return c.description +} + +// Unit returns the configured unit. +func (c Int64HistogramConfig) Unit() string { + return c.unit +} + +// Int64HistogramOption applies options to a [Int64HistogramConfig]. See +// [InstrumentOption] for other options that can be used as an +// Int64HistogramOption. +type Int64HistogramOption interface { + applyInt64Histogram(Int64HistogramConfig) Int64HistogramConfig +} diff --git a/vendor/go.opentelemetry.io/otel/requirements.txt b/vendor/go.opentelemetry.io/otel/requirements.txt new file mode 100644 index 00000000000..407f17489c6 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/requirements.txt @@ -0,0 +1 @@ +codespell==2.2.4 diff --git a/vendor/go.opentelemetry.io/otel/sdk/internal/env/env.go b/vendor/go.opentelemetry.io/otel/sdk/internal/env/env.go index 5e94b8ae521..59dcfab2501 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/internal/env/env.go +++ b/vendor/go.opentelemetry.io/otel/sdk/internal/env/env.go @@ -70,8 +70,8 @@ const ( // returned. func firstInt(defaultValue int, keys ...string) int { for _, key := range keys { - value, ok := os.LookupEnv(key) - if !ok { + value := os.Getenv(key) + if value == "" { continue } @@ -88,10 +88,10 @@ func firstInt(defaultValue int, keys ...string) int { } // IntEnvOr returns the int value of the environment variable with name key if -// it exists and the value is an int. Otherwise, defaultValue is returned. +// it exists, it is not empty, and the value is an int. Otherwise, defaultValue is returned. func IntEnvOr(key string, defaultValue int) int { - value, ok := os.LookupEnv(key) - if !ok { + value := os.Getenv(key) + if value == "" { return defaultValue } diff --git a/vendor/go.opentelemetry.io/otel/sdk/internal/internal.go b/vendor/go.opentelemetry.io/otel/sdk/internal/internal.go index 84a02306e64..dfeaaa8ca04 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/internal/internal.go +++ b/vendor/go.opentelemetry.io/otel/sdk/internal/internal.go @@ -14,16 +14,7 @@ package internal // import "go.opentelemetry.io/otel/sdk/internal" -import ( - "fmt" - "time" - - "go.opentelemetry.io/otel" -) - -// UserAgent is the user agent to be added to the outgoing -// requests from the exporters. -var UserAgent = fmt.Sprintf("opentelemetry-go/%s", otel.Version()) +import "time" // MonotonicEndTime returns the end time at present // but offset from start, monotonically. diff --git a/vendor/go.opentelemetry.io/otel/sdk/resource/auto.go b/vendor/go.opentelemetry.io/otel/sdk/resource/auto.go index c1d220408ae..324dd4baf24 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/resource/auto.go +++ b/vendor/go.opentelemetry.io/otel/sdk/resource/auto.go @@ -18,6 +18,7 @@ import ( "context" "errors" "fmt" + "strings" ) var ( @@ -45,28 +46,65 @@ type Detector interface { // Detect calls all input detectors sequentially and merges each result with the previous one. // It returns the merged error too. func Detect(ctx context.Context, detectors ...Detector) (*Resource, error) { - var autoDetectedRes *Resource - var errInfo []string + r := new(Resource) + return r, detect(ctx, r, detectors) +} + +// detect runs all detectors using ctx and merges the result into res. This +// assumes res is allocated and not nil, it will panic otherwise. +func detect(ctx context.Context, res *Resource, detectors []Detector) error { + var ( + r *Resource + errs detectErrs + err error + ) + for _, detector := range detectors { if detector == nil { continue } - res, err := detector.Detect(ctx) + r, err = detector.Detect(ctx) if err != nil { - errInfo = append(errInfo, err.Error()) + errs = append(errs, err) if !errors.Is(err, ErrPartialResource) { continue } } - autoDetectedRes, err = Merge(autoDetectedRes, res) + r, err = Merge(res, r) if err != nil { - errInfo = append(errInfo, err.Error()) + errs = append(errs, err) } + *res = *r } - var aggregatedError error - if len(errInfo) > 0 { - aggregatedError = fmt.Errorf("detecting resources: %s", errInfo) + if len(errs) == 0 { + return nil + } + return errs +} + +type detectErrs []error + +func (e detectErrs) Error() string { + errStr := make([]string, len(e)) + for i, err := range e { + errStr[i] = fmt.Sprintf("* %s", err) } - return autoDetectedRes, aggregatedError + + format := "%d errors occurred detecting resource:\n\t%s" + return fmt.Sprintf(format, len(e), strings.Join(errStr, "\n\t")) +} + +func (e detectErrs) Unwrap() error { + switch len(e) { + case 0: + return nil + case 1: + return e[0] + } + return e[1:] +} + +func (e detectErrs) Is(target error) bool { + return len(e) != 0 && errors.Is(e[0], target) } diff --git a/vendor/go.opentelemetry.io/otel/sdk/resource/builtin.go b/vendor/go.opentelemetry.io/otel/sdk/resource/builtin.go index aa0f942f490..72320ca51f9 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/resource/builtin.go +++ b/vendor/go.opentelemetry.io/otel/sdk/resource/builtin.go @@ -20,8 +20,8 @@ import ( "os" "path/filepath" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/sdk" semconv "go.opentelemetry.io/otel/semconv/v1.17.0" ) @@ -62,7 +62,7 @@ func (telemetrySDK) Detect(context.Context) (*Resource, error) { semconv.SchemaURL, semconv.TelemetrySDKName("opentelemetry"), semconv.TelemetrySDKLanguageGo, - semconv.TelemetrySDKVersion(otel.Version()), + semconv.TelemetrySDKVersion(sdk.Version()), ), nil } diff --git a/vendor/go.opentelemetry.io/otel/sdk/resource/config.go b/vendor/go.opentelemetry.io/otel/sdk/resource/config.go index f9a2a299907..f263919f6ec 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/resource/config.go +++ b/vendor/go.opentelemetry.io/otel/sdk/resource/config.go @@ -71,6 +71,11 @@ func WithHost() Option { return WithDetectors(host{}) } +// WithHostID adds host ID information to the configured resource. +func WithHostID() Option { + return WithDetectors(hostIDDetector{}) +} + // WithTelemetrySDK adds TelemetrySDK version info to the configured resource. func WithTelemetrySDK() Option { return WithDetectors(telemetrySDK{}) diff --git a/vendor/go.opentelemetry.io/otel/sdk/resource/doc.go b/vendor/go.opentelemetry.io/otel/sdk/resource/doc.go index 9aab3d83934..d55a50b0dc2 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/resource/doc.go +++ b/vendor/go.opentelemetry.io/otel/sdk/resource/doc.go @@ -25,4 +25,7 @@ // OTEL_RESOURCE_ATTRIBUTES the FromEnv Detector can be used. It will interpret // the value as a list of comma delimited key/value pairs // (e.g. `=,=,...`). +// +// While this package provides a stable API, +// the attributes added by resource detectors may change. package resource // import "go.opentelemetry.io/otel/sdk/resource" diff --git a/vendor/go.opentelemetry.io/otel/sdk/resource/env.go b/vendor/go.opentelemetry.io/otel/sdk/resource/env.go index e32843cad14..f09a7819067 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/resource/env.go +++ b/vendor/go.opentelemetry.io/otel/sdk/resource/env.go @@ -82,23 +82,23 @@ func constructOTResources(s string) (*Resource, error) { return Empty(), nil } pairs := strings.Split(s, ",") - attrs := []attribute.KeyValue{} + var attrs []attribute.KeyValue var invalid []string for _, p := range pairs { - field := strings.SplitN(p, "=", 2) - if len(field) != 2 { + k, v, found := strings.Cut(p, "=") + if !found { invalid = append(invalid, p) continue } - k := strings.TrimSpace(field[0]) - v, err := url.QueryUnescape(strings.TrimSpace(field[1])) + key := strings.TrimSpace(k) + val, err := url.QueryUnescape(strings.TrimSpace(v)) if err != nil { // Retain original value if decoding fails, otherwise it will be // an empty string. - v = field[1] + val = v otel.Handle(err) } - attrs = append(attrs, attribute.String(k, v)) + attrs = append(attrs, attribute.String(key, val)) } var err error if len(invalid) > 0 { diff --git a/vendor/go.opentelemetry.io/otel/sdk/resource/host_id.go b/vendor/go.opentelemetry.io/otel/sdk/resource/host_id.go new file mode 100644 index 00000000000..b8e934d4f8a --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/sdk/resource/host_id.go @@ -0,0 +1,120 @@ +// Copyright The OpenTelemetry Authors +// +// 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 resource // import "go.opentelemetry.io/otel/sdk/resource" + +import ( + "context" + "errors" + "strings" + + semconv "go.opentelemetry.io/otel/semconv/v1.17.0" +) + +type hostIDProvider func() (string, error) + +var defaultHostIDProvider hostIDProvider = platformHostIDReader.read + +var hostID = defaultHostIDProvider + +type hostIDReader interface { + read() (string, error) +} + +type fileReader func(string) (string, error) + +type commandExecutor func(string, ...string) (string, error) + +// hostIDReaderBSD implements hostIDReader. +type hostIDReaderBSD struct { + execCommand commandExecutor + readFile fileReader +} + +// read attempts to read the machine-id from /etc/hostid. If not found it will +// execute `kenv -q smbios.system.uuid`. If neither location yields an id an +// error will be returned. +func (r *hostIDReaderBSD) read() (string, error) { + if result, err := r.readFile("/etc/hostid"); err == nil { + return strings.TrimSpace(result), nil + } + + if result, err := r.execCommand("kenv", "-q", "smbios.system.uuid"); err == nil { + return strings.TrimSpace(result), nil + } + + return "", errors.New("host id not found in: /etc/hostid or kenv") +} + +// hostIDReaderDarwin implements hostIDReader. +type hostIDReaderDarwin struct { + execCommand commandExecutor +} + +// read executes `ioreg -rd1 -c "IOPlatformExpertDevice"` and parses host id +// from the IOPlatformUUID line. If the command fails or the uuid cannot be +// parsed an error will be returned. +func (r *hostIDReaderDarwin) read() (string, error) { + result, err := r.execCommand("ioreg", "-rd1", "-c", "IOPlatformExpertDevice") + if err != nil { + return "", err + } + + lines := strings.Split(result, "\n") + for _, line := range lines { + if strings.Contains(line, "IOPlatformUUID") { + parts := strings.Split(line, " = ") + if len(parts) == 2 { + return strings.Trim(parts[1], "\""), nil + } + break + } + } + + return "", errors.New("could not parse IOPlatformUUID") +} + +type hostIDReaderLinux struct { + readFile fileReader +} + +// read attempts to read the machine-id from /etc/machine-id followed by +// /var/lib/dbus/machine-id. If neither location yields an ID an error will +// be returned. +func (r *hostIDReaderLinux) read() (string, error) { + if result, err := r.readFile("/etc/machine-id"); err == nil { + return strings.TrimSpace(result), nil + } + + if result, err := r.readFile("/var/lib/dbus/machine-id"); err == nil { + return strings.TrimSpace(result), nil + } + + return "", errors.New("host id not found in: /etc/machine-id or /var/lib/dbus/machine-id") +} + +type hostIDDetector struct{} + +// Detect returns a *Resource containing the platform specific host id. +func (hostIDDetector) Detect(ctx context.Context) (*Resource, error) { + hostID, err := hostID() + if err != nil { + return nil, err + } + + return NewWithAttributes( + semconv.SchemaURL, + semconv.HostID(hostID), + ), nil +} diff --git a/vendor/go.opentelemetry.io/otel/sdk/resource/host_id_bsd.go b/vendor/go.opentelemetry.io/otel/sdk/resource/host_id_bsd.go new file mode 100644 index 00000000000..1778bbacf05 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/sdk/resource/host_id_bsd.go @@ -0,0 +1,23 @@ +// Copyright The OpenTelemetry Authors +// +// 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 dragonfly || freebsd || netbsd || openbsd || solaris +// +build dragonfly freebsd netbsd openbsd solaris + +package resource // import "go.opentelemetry.io/otel/sdk/resource" + +var platformHostIDReader hostIDReader = &hostIDReaderBSD{ + execCommand: execCommand, + readFile: readFile, +} diff --git a/vendor/go.opentelemetry.io/otel/sdk/resource/host_id_darwin.go b/vendor/go.opentelemetry.io/otel/sdk/resource/host_id_darwin.go new file mode 100644 index 00000000000..ba41409b23c --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/sdk/resource/host_id_darwin.go @@ -0,0 +1,19 @@ +// Copyright The OpenTelemetry Authors +// +// 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 resource // import "go.opentelemetry.io/otel/sdk/resource" + +var platformHostIDReader hostIDReader = &hostIDReaderDarwin{ + execCommand: execCommand, +} diff --git a/vendor/go.opentelemetry.io/otel/sdk/resource/host_id_exec.go b/vendor/go.opentelemetry.io/otel/sdk/resource/host_id_exec.go new file mode 100644 index 00000000000..207acb0ed3a --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/sdk/resource/host_id_exec.go @@ -0,0 +1,29 @@ +// Copyright The OpenTelemetry Authors +// +// 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 darwin || dragonfly || freebsd || netbsd || openbsd || solaris + +package resource // import "go.opentelemetry.io/otel/sdk/resource" + +import "os/exec" + +func execCommand(name string, arg ...string) (string, error) { + cmd := exec.Command(name, arg...) + b, err := cmd.Output() + if err != nil { + return "", err + } + + return string(b), nil +} diff --git a/vendor/go.opentelemetry.io/otel/sdk/resource/host_id_linux.go b/vendor/go.opentelemetry.io/otel/sdk/resource/host_id_linux.go new file mode 100644 index 00000000000..410579b8fc9 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/sdk/resource/host_id_linux.go @@ -0,0 +1,22 @@ +// Copyright The OpenTelemetry Authors +// +// 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 linux +// +build linux + +package resource // import "go.opentelemetry.io/otel/sdk/resource" + +var platformHostIDReader hostIDReader = &hostIDReaderLinux{ + readFile: readFile, +} diff --git a/vendor/go.opentelemetry.io/otel/sdk/resource/host_id_readfile.go b/vendor/go.opentelemetry.io/otel/sdk/resource/host_id_readfile.go new file mode 100644 index 00000000000..f92c6dad0f9 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/sdk/resource/host_id_readfile.go @@ -0,0 +1,28 @@ +// Copyright The OpenTelemetry Authors +// +// 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 linux || dragonfly || freebsd || netbsd || openbsd || solaris + +package resource // import "go.opentelemetry.io/otel/sdk/resource" + +import "os" + +func readFile(filename string) (string, error) { + b, err := os.ReadFile(filename) + if err != nil { + return "", nil + } + + return string(b), nil +} diff --git a/vendor/go.opentelemetry.io/otel/sdk/resource/host_id_unsupported.go b/vendor/go.opentelemetry.io/otel/sdk/resource/host_id_unsupported.go new file mode 100644 index 00000000000..89df9d6882e --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/sdk/resource/host_id_unsupported.go @@ -0,0 +1,36 @@ +// Copyright The OpenTelemetry Authors +// +// 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. + +// +build !darwin +// +build !dragonfly +// +build !freebsd +// +build !linux +// +build !netbsd +// +build !openbsd +// +build !solaris +// +build !windows + +package resource // import "go.opentelemetry.io/otel/sdk/resource" + +// hostIDReaderUnsupported is a placeholder implementation for operating systems +// for which this project currently doesn't support host.id +// attribute detection. See build tags declaration early on this file +// for a list of unsupported OSes. +type hostIDReaderUnsupported struct{} + +func (*hostIDReaderUnsupported) read() (string, error) { + return "", nil +} + +var platformHostIDReader hostIDReader = &hostIDReaderUnsupported{} diff --git a/vendor/go.opentelemetry.io/otel/sdk/resource/host_id_windows.go b/vendor/go.opentelemetry.io/otel/sdk/resource/host_id_windows.go new file mode 100644 index 00000000000..5b431c6ee6e --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/sdk/resource/host_id_windows.go @@ -0,0 +1,48 @@ +// Copyright The OpenTelemetry Authors +// +// 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 windows +// +build windows + +package resource // import "go.opentelemetry.io/otel/sdk/resource" + +import ( + "golang.org/x/sys/windows/registry" +) + +// implements hostIDReader +type hostIDReaderWindows struct{} + +// read reads MachineGuid from the windows registry key: +// SOFTWARE\Microsoft\Cryptography +func (*hostIDReaderWindows) read() (string, error) { + k, err := registry.OpenKey( + registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Cryptography`, + registry.QUERY_VALUE|registry.WOW64_64KEY, + ) + + if err != nil { + return "", err + } + defer k.Close() + + guid, _, err := k.GetStringValue("MachineGuid") + if err != nil { + return "", err + } + + return guid, nil +} + +var platformHostIDReader hostIDReader = &hostIDReaderWindows{} diff --git a/vendor/go.opentelemetry.io/otel/sdk/resource/os_release_unix.go b/vendor/go.opentelemetry.io/otel/sdk/resource/os_release_unix.go index fba6790e445..c771942deec 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/resource/os_release_unix.go +++ b/vendor/go.opentelemetry.io/otel/sdk/resource/os_release_unix.go @@ -85,14 +85,14 @@ func skip(line string) bool { // parse attempts to split the provided line on the first '=' character, and then // sanitize each side of the split before returning them as a key-value pair. func parse(line string) (string, string, bool) { - parts := strings.SplitN(line, "=", 2) + k, v, found := strings.Cut(line, "=") - if len(parts) != 2 || len(parts[0]) == 0 { + if !found || len(k) == 0 { return "", "", false } - key := strings.TrimSpace(parts[0]) - value := unescape(unquote(strings.TrimSpace(parts[1]))) + key := strings.TrimSpace(k) + value := unescape(unquote(strings.TrimSpace(v))) return key, value, true } diff --git a/vendor/go.opentelemetry.io/otel/sdk/resource/resource.go b/vendor/go.opentelemetry.io/otel/sdk/resource/resource.go index c425ff05db5..139dc7e8f92 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/resource/resource.go +++ b/vendor/go.opentelemetry.io/otel/sdk/resource/resource.go @@ -17,7 +17,6 @@ package resource // import "go.opentelemetry.io/otel/sdk/resource" import ( "context" "errors" - "fmt" "sync" "go.opentelemetry.io/otel" @@ -51,17 +50,8 @@ func New(ctx context.Context, opts ...Option) (*Resource, error) { cfg = opt.apply(cfg) } - resource, err := Detect(ctx, cfg.detectors...) - - var err2 error - resource, err2 = Merge(resource, &Resource{schemaURL: cfg.schemaURL}) - if err == nil { - err = err2 - } else if err2 != nil { - err = fmt.Errorf("detecting resources: %s", []string{err.Error(), err2.Error()}) - } - - return resource, err + r := &Resource{schemaURL: cfg.schemaURL} + return r, detect(ctx, r, cfg.detectors) } // NewWithAttributes creates a resource from attrs and associates the resource with a @@ -84,7 +74,7 @@ func NewSchemaless(attrs ...attribute.KeyValue) *Resource { } // Ensure attributes comply with the specification: - // https://github.com/open-telemetry/opentelemetry-specification/blob/v1.0.1/specification/common/common.md#attributes + // https://github.com/open-telemetry/opentelemetry-specification/blob/v1.20.0/specification/common/README.md#attribute s, _ := attribute.NewSetWithFiltered(attrs, func(kv attribute.KeyValue) bool { return kv.Valid() }) @@ -164,7 +154,7 @@ func (r *Resource) Equal(eq *Resource) bool { // if resource b's value is empty. // // The SchemaURL of the resources will be merged according to the spec rules: -// https://github.com/open-telemetry/opentelemetry-specification/blob/bad49c714a62da5493f2d1d9bafd7ebe8c8ce7eb/specification/resource/sdk.md#merge +// https://github.com/open-telemetry/opentelemetry-specification/blob/v1.20.0/specification/resource/sdk.md#merge // If the resources have different non-empty schemaURL an empty resource and an error // will be returned. func Merge(a, b *Resource) (*Resource, error) { diff --git a/vendor/go.opentelemetry.io/otel/sdk/trace/batch_span_processor.go b/vendor/go.opentelemetry.io/otel/sdk/trace/batch_span_processor.go index a2d7db49001..43d5b042303 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/trace/batch_span_processor.go +++ b/vendor/go.opentelemetry.io/otel/sdk/trace/batch_span_processor.go @@ -91,7 +91,7 @@ var _ SpanProcessor = (*batchSpanProcessor)(nil) // NewBatchSpanProcessor creates a new SpanProcessor that will send completed // span batches to the exporter with the supplied options. // -// If the exporter is nil, the span processor will preform no action. +// If the exporter is nil, the span processor will perform no action. func NewBatchSpanProcessor(exporter SpanExporter, options ...BatchSpanProcessorOption) SpanProcessor { maxQueueSize := env.BatchSpanProcessorMaxQueueSize(DefaultMaxQueueSize) maxExportBatchSize := env.BatchSpanProcessorMaxExportBatchSize(DefaultMaxExportBatchSize) diff --git a/vendor/go.opentelemetry.io/otel/sdk/trace/provider.go b/vendor/go.opentelemetry.io/otel/sdk/trace/provider.go index 201c1781700..0a018c14ded 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/trace/provider.go +++ b/vendor/go.opentelemetry.io/otel/sdk/trace/provider.go @@ -75,8 +75,9 @@ func (cfg tracerProviderConfig) MarshalLog() interface{} { type TracerProvider struct { mu sync.Mutex namedTracer map[instrumentation.Scope]*tracer - spanProcessors atomic.Value - isShutdown bool + spanProcessors atomic.Pointer[spanProcessorStates] + + isShutdown atomic.Bool // These fields are not protected by the lock mu. They are assumed to be // immutable after creation of the TracerProvider. @@ -119,11 +120,11 @@ func NewTracerProvider(opts ...TracerProviderOption) *TracerProvider { } global.Info("TracerProvider created", "config", o) - spss := spanProcessorStates{} + spss := make(spanProcessorStates, 0, len(o.processors)) for _, sp := range o.processors { spss = append(spss, newSpanProcessorState(sp)) } - tp.spanProcessors.Store(spss) + tp.spanProcessors.Store(&spss) return tp } @@ -136,10 +137,11 @@ func NewTracerProvider(opts ...TracerProviderOption) *TracerProvider { // // This method is safe to be called concurrently. func (p *TracerProvider) Tracer(name string, opts ...trace.TracerOption) trace.Tracer { + // This check happens before the mutex is acquired to avoid deadlocking if Tracer() is called from within Shutdown(). + if p.isShutdown.Load() { + return trace.NewNoopTracerProvider().Tracer(name, opts...) + } c := trace.NewTracerConfig(opts...) - - p.mu.Lock() - defer p.mu.Unlock() if name == "" { name = defaultTracerName } @@ -148,44 +150,74 @@ func (p *TracerProvider) Tracer(name string, opts ...trace.TracerOption) trace.T Version: c.InstrumentationVersion(), SchemaURL: c.SchemaURL(), } - t, ok := p.namedTracer[is] - if !ok { - t = &tracer{ - provider: p, - instrumentationScope: is, + + t, ok := func() (trace.Tracer, bool) { + p.mu.Lock() + defer p.mu.Unlock() + // Must check the flag after acquiring the mutex to avoid returning a valid tracer if Shutdown() ran + // after the first check above but before we acquired the mutex. + if p.isShutdown.Load() { + return trace.NewNoopTracerProvider().Tracer(name, opts...), true + } + t, ok := p.namedTracer[is] + if !ok { + t = &tracer{ + provider: p, + instrumentationScope: is, + } + p.namedTracer[is] = t } - p.namedTracer[is] = t - global.Info("Tracer created", "name", name, "version", c.InstrumentationVersion(), "schemaURL", c.SchemaURL()) + return t, ok + }() + if !ok { + // This code is outside the mutex to not hold the lock while calling third party logging code: + // - That code may do slow things like I/O, which would prolong the duration the lock is held, + // slowing down all tracing consumers. + // - Logging code may be instrumented with tracing and deadlock because it could try + // acquiring the same non-reentrant mutex. + global.Info("Tracer created", "name", name, "version", is.Version, "schemaURL", is.SchemaURL) } return t } // RegisterSpanProcessor adds the given SpanProcessor to the list of SpanProcessors. func (p *TracerProvider) RegisterSpanProcessor(sp SpanProcessor) { + // This check prevents calls during a shutdown. + if p.isShutdown.Load() { + return + } p.mu.Lock() defer p.mu.Unlock() - if p.isShutdown { + // This check prevents calls after a shutdown. + if p.isShutdown.Load() { return } - newSPS := spanProcessorStates{} - newSPS = append(newSPS, p.spanProcessors.Load().(spanProcessorStates)...) + + current := p.getSpanProcessors() + newSPS := make(spanProcessorStates, 0, len(current)+1) + newSPS = append(newSPS, current...) newSPS = append(newSPS, newSpanProcessorState(sp)) - p.spanProcessors.Store(newSPS) + p.spanProcessors.Store(&newSPS) } // UnregisterSpanProcessor removes the given SpanProcessor from the list of SpanProcessors. func (p *TracerProvider) UnregisterSpanProcessor(sp SpanProcessor) { + // This check prevents calls during a shutdown. + if p.isShutdown.Load() { + return + } p.mu.Lock() defer p.mu.Unlock() - if p.isShutdown { + // This check prevents calls after a shutdown. + if p.isShutdown.Load() { return } - old := p.spanProcessors.Load().(spanProcessorStates) + old := p.getSpanProcessors() if len(old) == 0 { return } - spss := spanProcessorStates{} - spss = append(spss, old...) + spss := make(spanProcessorStates, len(old)) + copy(spss, old) // stop the span processor if it is started and remove it from the list var stopOnce *spanProcessorState @@ -209,13 +241,13 @@ func (p *TracerProvider) UnregisterSpanProcessor(sp SpanProcessor) { spss[len(spss)-1] = nil spss = spss[:len(spss)-1] - p.spanProcessors.Store(spss) + p.spanProcessors.Store(&spss) } // ForceFlush immediately exports all spans that have not yet been exported for // all the registered span processors. func (p *TracerProvider) ForceFlush(ctx context.Context) error { - spss := p.spanProcessors.Load().(spanProcessorStates) + spss := p.getSpanProcessors() if len(spss) == 0 { return nil } @@ -236,18 +268,21 @@ func (p *TracerProvider) ForceFlush(ctx context.Context) error { // Shutdown shuts down TracerProvider. All registered span processors are shut down // in the order they were registered and any held computational resources are released. +// After Shutdown is called, all methods are no-ops. func (p *TracerProvider) Shutdown(ctx context.Context) error { - spss := p.spanProcessors.Load().(spanProcessorStates) - if len(spss) == 0 { + // This check prevents deadlocks in case of recursive shutdown. + if p.isShutdown.Load() { return nil } - p.mu.Lock() defer p.mu.Unlock() - p.isShutdown = true + // This check prevents calls after a shutdown has already been done concurrently. + if !p.isShutdown.CompareAndSwap(false, true) { // did toggle? + return nil + } var retErr error - for _, sps := range spss { + for _, sps := range p.getSpanProcessors() { select { case <-ctx.Done(): return ctx.Err() @@ -267,10 +302,14 @@ func (p *TracerProvider) Shutdown(ctx context.Context) error { } } } - p.spanProcessors.Store(spanProcessorStates{}) + p.spanProcessors.Store(&spanProcessorStates{}) return retErr } +func (p *TracerProvider) getSpanProcessors() spanProcessorStates { + return *(p.spanProcessors.Load()) +} + // TracerProviderOption configures a TracerProvider. type TracerProviderOption interface { apply(tracerProviderConfig) tracerProviderConfig diff --git a/vendor/go.opentelemetry.io/otel/sdk/trace/simple_span_processor.go b/vendor/go.opentelemetry.io/otel/sdk/trace/simple_span_processor.go index e8530a95932..f8770fff79b 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/trace/simple_span_processor.go +++ b/vendor/go.opentelemetry.io/otel/sdk/trace/simple_span_processor.go @@ -19,12 +19,13 @@ import ( "sync" "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/internal/global" ) // simpleSpanProcessor is a SpanProcessor that synchronously sends all // completed Spans to a trace.Exporter immediately. type simpleSpanProcessor struct { - exporterMu sync.RWMutex + exporterMu sync.Mutex exporter SpanExporter stopOnce sync.Once } @@ -43,6 +44,8 @@ func NewSimpleSpanProcessor(exporter SpanExporter) SpanProcessor { ssp := &simpleSpanProcessor{ exporter: exporter, } + global.Warn("SimpleSpanProcessor is not recommended for production use, consider using BatchSpanProcessor instead.") + return ssp } @@ -51,8 +54,8 @@ func (ssp *simpleSpanProcessor) OnStart(context.Context, ReadWriteSpan) {} // OnEnd immediately exports a ReadOnlySpan. func (ssp *simpleSpanProcessor) OnEnd(s ReadOnlySpan) { - ssp.exporterMu.RLock() - defer ssp.exporterMu.RUnlock() + ssp.exporterMu.Lock() + defer ssp.exporterMu.Unlock() if ssp.exporter != nil && s.SpanContext().TraceFlags().IsSampled() { if err := ssp.exporter.ExportSpans(context.Background(), []ReadOnlySpan{s}); err != nil { diff --git a/vendor/go.opentelemetry.io/otel/sdk/trace/span.go b/vendor/go.opentelemetry.io/otel/sdk/trace/span.go index 9fb483a99fe..4fcca26e088 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/trace/span.go +++ b/vendor/go.opentelemetry.io/otel/sdk/trace/span.go @@ -302,7 +302,7 @@ func (s *recordingSpan) addOverCapAttrs(limit int, attrs []attribute.KeyValue) { // most a length of limit. Each string slice value is truncated in this fashion // (the slice length itself is unaffected). // -// No truncation is perfromed for a negative limit. +// No truncation is performed for a negative limit. func truncateAttr(limit int, attr attribute.KeyValue) attribute.KeyValue { if limit < 0 { return attr @@ -410,7 +410,7 @@ func (s *recordingSpan) End(options ...trace.SpanEndOption) { } s.mu.Unlock() - sps := s.tracer.provider.spanProcessors.Load().(spanProcessorStates) + sps := s.tracer.provider.getSpanProcessors() if len(sps) == 0 { return } diff --git a/vendor/go.opentelemetry.io/otel/sdk/trace/span_exporter.go b/vendor/go.opentelemetry.io/otel/sdk/trace/span_exporter.go index 9fb3d6eac3b..c9bd52f7ad4 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/trace/span_exporter.go +++ b/vendor/go.opentelemetry.io/otel/sdk/trace/span_exporter.go @@ -38,7 +38,7 @@ type SpanExporter interface { // must never be done outside of a new major release. // Shutdown notifies the exporter of a pending halt to operations. The - // exporter is expected to preform any cleanup or synchronization it + // exporter is expected to perform any cleanup or synchronization it // requires while honoring all timeouts and cancellations contained in // the passed context. Shutdown(ctx context.Context) error diff --git a/vendor/go.opentelemetry.io/otel/sdk/trace/span_processor.go b/vendor/go.opentelemetry.io/otel/sdk/trace/span_processor.go index e6ae1935219..9c53657a719 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/trace/span_processor.go +++ b/vendor/go.opentelemetry.io/otel/sdk/trace/span_processor.go @@ -62,11 +62,11 @@ type SpanProcessor interface { type spanProcessorState struct { sp SpanProcessor - state *sync.Once + state sync.Once } func newSpanProcessorState(sp SpanProcessor) *spanProcessorState { - return &spanProcessorState{sp: sp, state: &sync.Once{}} + return &spanProcessorState{sp: sp} } type spanProcessorStates []*spanProcessorState diff --git a/vendor/go.opentelemetry.io/otel/sdk/trace/tracer.go b/vendor/go.opentelemetry.io/otel/sdk/trace/tracer.go index f17d924b89e..85a71227f3f 100644 --- a/vendor/go.opentelemetry.io/otel/sdk/trace/tracer.go +++ b/vendor/go.opentelemetry.io/otel/sdk/trace/tracer.go @@ -51,7 +51,7 @@ func (tr *tracer) Start(ctx context.Context, name string, options ...trace.SpanS s := tr.newSpan(ctx, name, &config) if rw, ok := s.(ReadWriteSpan); ok && s.IsRecording() { - sps := tr.provider.spanProcessors.Load().(spanProcessorStates) + sps := tr.provider.getSpanProcessors() for _, sp := range sps { sp.sp.OnStart(ctx, rw) } diff --git a/vendor/go.opentelemetry.io/otel/sdk/trace/version.go b/vendor/go.opentelemetry.io/otel/sdk/trace/version.go new file mode 100644 index 00000000000..d3457ed1355 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/sdk/trace/version.go @@ -0,0 +1,20 @@ +// Copyright The OpenTelemetry Authors +// +// 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 trace // import "go.opentelemetry.io/otel/sdk/trace" + +// version is the current release version of the metric SDK in use. +func version() string { + return "1.16.0-rc.1" +} diff --git a/vendor/go.opentelemetry.io/otel/sdk/version.go b/vendor/go.opentelemetry.io/otel/sdk/version.go new file mode 100644 index 00000000000..dbef90b0df1 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/sdk/version.go @@ -0,0 +1,20 @@ +// Copyright The OpenTelemetry Authors +// +// 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 sdk // import "go.opentelemetry.io/otel/sdk" + +// Version is the current release version of the OpenTelemetry SDK in use. +func Version() string { + return "1.16.0" +} diff --git a/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/httpconv/http.go b/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/httpconv/http.go index c60b2a6bb68..fc43808fe44 100644 --- a/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/httpconv/http.go +++ b/vendor/go.opentelemetry.io/otel/semconv/v1.17.0/httpconv/http.go @@ -12,8 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -// Package httpconv provides OpenTelemetry semantic convetions for the net/http -// package from the standard library. +// Package httpconv provides OpenTelemetry HTTP semantic conventions for +// tracing telemetry. package httpconv // import "go.opentelemetry.io/otel/semconv/v1.17.0/httpconv" import ( @@ -58,9 +58,10 @@ var ( } ) -// ClientResponse returns attributes for an HTTP response received by a client -// from a server. It will return the following attributes if the related values -// are defined in resp: "http.status.code", "http.response_content_length". +// ClientResponse returns trace attributes for an HTTP response received by a +// client from a server. It will return the following attributes if the related +// values are defined in resp: "http.status.code", +// "http.response_content_length". // // This does not add all OpenTelemetry required attributes for an HTTP event, // it assumes ClientRequest was used to create the span with a complete set of @@ -72,8 +73,8 @@ func ClientResponse(resp *http.Response) []attribute.KeyValue { return hc.ClientResponse(resp) } -// ClientRequest returns attributes for an HTTP request made by a client. The -// following attributes are always returned: "http.url", "http.flavor", +// ClientRequest returns trace attributes for an HTTP request made by a client. +// The following attributes are always returned: "http.url", "http.flavor", // "http.method", "net.peer.name". The following attributes are returned if the // related values are defined in req: "net.peer.port", "http.user_agent", // "http.request_content_length", "enduser.id". @@ -87,7 +88,8 @@ func ClientStatus(code int) (codes.Code, string) { return hc.ClientStatus(code) } -// ServerRequest returns attributes for an HTTP request received by a server. +// ServerRequest returns trace attributes for an HTTP request received by a +// server. // // The server must be the primary server name if it is known. For example this // would be the ServerName directive diff --git a/vendor/go.opentelemetry.io/otel/trace/noop.go b/vendor/go.opentelemetry.io/otel/trace/noop.go index 73950f20778..7cf6c7f3ef9 100644 --- a/vendor/go.opentelemetry.io/otel/trace/noop.go +++ b/vendor/go.opentelemetry.io/otel/trace/noop.go @@ -37,7 +37,7 @@ func (p noopTracerProvider) Tracer(string, ...TracerOption) Tracer { return noopTracer{} } -// noopTracer is an implementation of Tracer that preforms no operations. +// noopTracer is an implementation of Tracer that performs no operations. type noopTracer struct{} var _ Tracer = noopTracer{} @@ -53,7 +53,7 @@ func (t noopTracer) Start(ctx context.Context, name string, _ ...SpanStartOption return ContextWithSpan(ctx, span), span } -// noopSpan is an implementation of Span that preforms no operations. +// noopSpan is an implementation of Span that performs no operations. type noopSpan struct{} var _ Span = noopSpan{} diff --git a/vendor/go.opentelemetry.io/otel/version.go b/vendor/go.opentelemetry.io/otel/version.go index 0e8e5e02329..c2217a28d68 100644 --- a/vendor/go.opentelemetry.io/otel/version.go +++ b/vendor/go.opentelemetry.io/otel/version.go @@ -16,5 +16,5 @@ package otel // import "go.opentelemetry.io/otel" // Version is the current release version of OpenTelemetry in use. func Version() string { - return "1.14.0" + return "1.16.0" } diff --git a/vendor/go.opentelemetry.io/otel/versions.yaml b/vendor/go.opentelemetry.io/otel/versions.yaml index 40df1fae417..9dc47532bc2 100644 --- a/vendor/go.opentelemetry.io/otel/versions.yaml +++ b/vendor/go.opentelemetry.io/otel/versions.yaml @@ -14,7 +14,7 @@ module-sets: stable-v1: - version: v1.14.0 + version: v1.16.0 modules: - go.opentelemetry.io/otel - go.opentelemetry.io/otel/bridge/opentracing @@ -26,16 +26,17 @@ module-sets: - go.opentelemetry.io/otel/example/passthrough - go.opentelemetry.io/otel/example/zipkin - go.opentelemetry.io/otel/exporters/jaeger - - go.opentelemetry.io/otel/exporters/zipkin + - go.opentelemetry.io/otel/exporters/otlp/internal/retry - go.opentelemetry.io/otel/exporters/otlp/otlptrace - go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc - go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp - - go.opentelemetry.io/otel/exporters/otlp/internal/retry - go.opentelemetry.io/otel/exporters/stdout/stdouttrace - - go.opentelemetry.io/otel/trace + - go.opentelemetry.io/otel/exporters/zipkin + - go.opentelemetry.io/otel/metric - go.opentelemetry.io/otel/sdk + - go.opentelemetry.io/otel/trace experimental-metrics: - version: v0.37.0 + version: v0.39.0 modules: - go.opentelemetry.io/otel/example/opencensus - go.opentelemetry.io/otel/example/prometheus @@ -44,7 +45,6 @@ module-sets: - go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp - go.opentelemetry.io/otel/exporters/prometheus - go.opentelemetry.io/otel/exporters/stdout/stdoutmetric - - go.opentelemetry.io/otel/metric - go.opentelemetry.io/otel/sdk/metric - go.opentelemetry.io/otel/bridge/opencensus - go.opentelemetry.io/otel/bridge/opencensus/test diff --git a/vendor/go.uber.org/atomic/CHANGELOG.md b/vendor/go.uber.org/atomic/CHANGELOG.md index 5fe03f21bd3..6f87f33fa95 100644 --- a/vendor/go.uber.org/atomic/CHANGELOG.md +++ b/vendor/go.uber.org/atomic/CHANGELOG.md @@ -4,6 +4,16 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [1.11.0] - 2023-05-02 +### Fixed +- Fix initialization of `Value` wrappers. + +### Added +- Add `String` method to `atomic.Pointer[T]` type allowing users to safely print +underlying values of pointers. + +[1.11.0]: https://github.com/uber-go/atomic/compare/v1.10.0...v1.11.0 + ## [1.10.0] - 2022-08-11 ### Added - Add `atomic.Float32` type for atomic operations on `float32`. diff --git a/vendor/go.uber.org/atomic/bool.go b/vendor/go.uber.org/atomic/bool.go index dfa2085f491..f0a2ddd148c 100644 --- a/vendor/go.uber.org/atomic/bool.go +++ b/vendor/go.uber.org/atomic/bool.go @@ -1,6 +1,6 @@ // @generated Code generated by gen-atomicwrapper. -// Copyright (c) 2020-2022 Uber Technologies, Inc. +// Copyright (c) 2020-2023 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/vendor/go.uber.org/atomic/duration.go b/vendor/go.uber.org/atomic/duration.go index 6f4157445cf..7c23868fc87 100644 --- a/vendor/go.uber.org/atomic/duration.go +++ b/vendor/go.uber.org/atomic/duration.go @@ -1,6 +1,6 @@ // @generated Code generated by gen-atomicwrapper. -// Copyright (c) 2020-2022 Uber Technologies, Inc. +// Copyright (c) 2020-2023 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/vendor/go.uber.org/atomic/error.go b/vendor/go.uber.org/atomic/error.go index 27b23ea1628..b7e3f1291a3 100644 --- a/vendor/go.uber.org/atomic/error.go +++ b/vendor/go.uber.org/atomic/error.go @@ -1,6 +1,6 @@ // @generated Code generated by gen-atomicwrapper. -// Copyright (c) 2020-2022 Uber Technologies, Inc. +// Copyright (c) 2020-2023 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -52,7 +52,17 @@ func (x *Error) Store(val error) { // CompareAndSwap is an atomic compare-and-swap for error values. func (x *Error) CompareAndSwap(old, new error) (swapped bool) { - return x.v.CompareAndSwap(packError(old), packError(new)) + if x.v.CompareAndSwap(packError(old), packError(new)) { + return true + } + + if old == _zeroError { + // If the old value is the empty value, then it's possible the + // underlying Value hasn't been set and is nil, so retry with nil. + return x.v.CompareAndSwap(nil, packError(new)) + } + + return false } // Swap atomically stores the given error and returns the old diff --git a/vendor/go.uber.org/atomic/float32.go b/vendor/go.uber.org/atomic/float32.go index 5d535a6d2ac..62c36334fd5 100644 --- a/vendor/go.uber.org/atomic/float32.go +++ b/vendor/go.uber.org/atomic/float32.go @@ -1,6 +1,6 @@ // @generated Code generated by gen-atomicwrapper. -// Copyright (c) 2020-2022 Uber Technologies, Inc. +// Copyright (c) 2020-2023 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/vendor/go.uber.org/atomic/float64.go b/vendor/go.uber.org/atomic/float64.go index 11d5189a5f2..5bc11caabe2 100644 --- a/vendor/go.uber.org/atomic/float64.go +++ b/vendor/go.uber.org/atomic/float64.go @@ -1,6 +1,6 @@ // @generated Code generated by gen-atomicwrapper. -// Copyright (c) 2020-2022 Uber Technologies, Inc. +// Copyright (c) 2020-2023 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/vendor/go.uber.org/atomic/int32.go b/vendor/go.uber.org/atomic/int32.go index b9a68f42ca8..5320eac10f1 100644 --- a/vendor/go.uber.org/atomic/int32.go +++ b/vendor/go.uber.org/atomic/int32.go @@ -1,6 +1,6 @@ // @generated Code generated by gen-atomicint. -// Copyright (c) 2020-2022 Uber Technologies, Inc. +// Copyright (c) 2020-2023 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/vendor/go.uber.org/atomic/int64.go b/vendor/go.uber.org/atomic/int64.go index 78d260976fc..460821d009d 100644 --- a/vendor/go.uber.org/atomic/int64.go +++ b/vendor/go.uber.org/atomic/int64.go @@ -1,6 +1,6 @@ // @generated Code generated by gen-atomicint. -// Copyright (c) 2020-2022 Uber Technologies, Inc. +// Copyright (c) 2020-2023 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/vendor/go.uber.org/atomic/pointer_go118.go b/vendor/go.uber.org/atomic/pointer_go118.go index e0f47dba468..1fb6c03b261 100644 --- a/vendor/go.uber.org/atomic/pointer_go118.go +++ b/vendor/go.uber.org/atomic/pointer_go118.go @@ -18,43 +18,14 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -//go:build go1.18 && !go1.19 -// +build go1.18,!go1.19 +//go:build go1.18 +// +build go1.18 package atomic -import "unsafe" +import "fmt" -type Pointer[T any] struct { - _ nocmp // disallow non-atomic comparison - p UnsafePointer -} - -// NewPointer creates a new Pointer. -func NewPointer[T any](v *T) *Pointer[T] { - var p Pointer[T] - if v != nil { - p.p.Store(unsafe.Pointer(v)) - } - return &p -} - -// Load atomically loads the wrapped value. -func (p *Pointer[T]) Load() *T { - return (*T)(p.p.Load()) -} - -// Store atomically stores the passed value. -func (p *Pointer[T]) Store(val *T) { - p.p.Store(unsafe.Pointer(val)) -} - -// Swap atomically swaps the wrapped pointer and returns the old value. -func (p *Pointer[T]) Swap(val *T) (old *T) { - return (*T)(p.p.Swap(unsafe.Pointer(val))) -} - -// CompareAndSwap is an atomic compare-and-swap. -func (p *Pointer[T]) CompareAndSwap(old, new *T) (swapped bool) { - return p.p.CompareAndSwap(unsafe.Pointer(old), unsafe.Pointer(new)) +// String returns a human readable representation of a Pointer's underlying value. +func (p *Pointer[T]) String() string { + return fmt.Sprint(p.Load()) } diff --git a/vendor/go.uber.org/atomic/pointer_go118_pre119.go b/vendor/go.uber.org/atomic/pointer_go118_pre119.go new file mode 100644 index 00000000000..e0f47dba468 --- /dev/null +++ b/vendor/go.uber.org/atomic/pointer_go118_pre119.go @@ -0,0 +1,60 @@ +// Copyright (c) 2022 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +//go:build go1.18 && !go1.19 +// +build go1.18,!go1.19 + +package atomic + +import "unsafe" + +type Pointer[T any] struct { + _ nocmp // disallow non-atomic comparison + p UnsafePointer +} + +// NewPointer creates a new Pointer. +func NewPointer[T any](v *T) *Pointer[T] { + var p Pointer[T] + if v != nil { + p.p.Store(unsafe.Pointer(v)) + } + return &p +} + +// Load atomically loads the wrapped value. +func (p *Pointer[T]) Load() *T { + return (*T)(p.p.Load()) +} + +// Store atomically stores the passed value. +func (p *Pointer[T]) Store(val *T) { + p.p.Store(unsafe.Pointer(val)) +} + +// Swap atomically swaps the wrapped pointer and returns the old value. +func (p *Pointer[T]) Swap(val *T) (old *T) { + return (*T)(p.p.Swap(unsafe.Pointer(val))) +} + +// CompareAndSwap is an atomic compare-and-swap. +func (p *Pointer[T]) CompareAndSwap(old, new *T) (swapped bool) { + return p.p.CompareAndSwap(unsafe.Pointer(old), unsafe.Pointer(new)) +} diff --git a/vendor/go.uber.org/atomic/string.go b/vendor/go.uber.org/atomic/string.go index c4bea70f4dd..061466c5bde 100644 --- a/vendor/go.uber.org/atomic/string.go +++ b/vendor/go.uber.org/atomic/string.go @@ -1,6 +1,6 @@ // @generated Code generated by gen-atomicwrapper. -// Copyright (c) 2020-2022 Uber Technologies, Inc. +// Copyright (c) 2020-2023 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -42,24 +42,31 @@ func NewString(val string) *String { // Load atomically loads the wrapped string. func (x *String) Load() string { - if v := x.v.Load(); v != nil { - return v.(string) - } - return _zeroString + return unpackString(x.v.Load()) } // Store atomically stores the passed string. func (x *String) Store(val string) { - x.v.Store(val) + x.v.Store(packString(val)) } // CompareAndSwap is an atomic compare-and-swap for string values. func (x *String) CompareAndSwap(old, new string) (swapped bool) { - return x.v.CompareAndSwap(old, new) + if x.v.CompareAndSwap(packString(old), packString(new)) { + return true + } + + if old == _zeroString { + // If the old value is the empty value, then it's possible the + // underlying Value hasn't been set and is nil, so retry with nil. + return x.v.CompareAndSwap(nil, packString(new)) + } + + return false } // Swap atomically stores the given string and returns the old // value. func (x *String) Swap(val string) (old string) { - return x.v.Swap(val).(string) + return unpackString(x.v.Swap(packString(val))) } diff --git a/vendor/go.uber.org/atomic/string_ext.go b/vendor/go.uber.org/atomic/string_ext.go index 1f63dfd5b97..019109c86ba 100644 --- a/vendor/go.uber.org/atomic/string_ext.go +++ b/vendor/go.uber.org/atomic/string_ext.go @@ -1,4 +1,4 @@ -// Copyright (c) 2020-2022 Uber Technologies, Inc. +// Copyright (c) 2020-2023 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -20,7 +20,18 @@ package atomic -//go:generate bin/gen-atomicwrapper -name=String -type=string -wrapped=Value -compareandswap -swap -file=string.go +//go:generate bin/gen-atomicwrapper -name=String -type=string -wrapped Value -pack packString -unpack unpackString -compareandswap -swap -file=string.go + +func packString(s string) interface{} { + return s +} + +func unpackString(v interface{}) string { + if s, ok := v.(string); ok { + return s + } + return "" +} // String returns the wrapped value. func (s *String) String() string { diff --git a/vendor/go.uber.org/atomic/time.go b/vendor/go.uber.org/atomic/time.go index 1660feb1426..cc2a230c001 100644 --- a/vendor/go.uber.org/atomic/time.go +++ b/vendor/go.uber.org/atomic/time.go @@ -1,6 +1,6 @@ // @generated Code generated by gen-atomicwrapper. -// Copyright (c) 2020-2022 Uber Technologies, Inc. +// Copyright (c) 2020-2023 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/vendor/go.uber.org/atomic/uint32.go b/vendor/go.uber.org/atomic/uint32.go index d6f04a96dc3..4adc294ac2a 100644 --- a/vendor/go.uber.org/atomic/uint32.go +++ b/vendor/go.uber.org/atomic/uint32.go @@ -1,6 +1,6 @@ // @generated Code generated by gen-atomicint. -// Copyright (c) 2020-2022 Uber Technologies, Inc. +// Copyright (c) 2020-2023 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/vendor/go.uber.org/atomic/uint64.go b/vendor/go.uber.org/atomic/uint64.go index 2574bdd5ec4..0e2eddb3038 100644 --- a/vendor/go.uber.org/atomic/uint64.go +++ b/vendor/go.uber.org/atomic/uint64.go @@ -1,6 +1,6 @@ // @generated Code generated by gen-atomicint. -// Copyright (c) 2020-2022 Uber Technologies, Inc. +// Copyright (c) 2020-2023 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/vendor/go.uber.org/atomic/uintptr.go b/vendor/go.uber.org/atomic/uintptr.go index 81b275a7ad5..7d5b000d610 100644 --- a/vendor/go.uber.org/atomic/uintptr.go +++ b/vendor/go.uber.org/atomic/uintptr.go @@ -1,6 +1,6 @@ // @generated Code generated by gen-atomicint. -// Copyright (c) 2020-2022 Uber Technologies, Inc. +// Copyright (c) 2020-2023 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal diff --git a/vendor/golang.org/x/exp/slices/slices.go b/vendor/golang.org/x/exp/slices/slices.go index cff0cd49ecf..2540bd68255 100644 --- a/vendor/golang.org/x/exp/slices/slices.go +++ b/vendor/golang.org/x/exp/slices/slices.go @@ -104,8 +104,8 @@ func CompareFunc[E1, E2 any](s1 []E1, s2 []E2, cmp func(E1, E2) int) int { // Index returns the index of the first occurrence of v in s, // or -1 if not present. func Index[E comparable](s []E, v E) int { - for i, vs := range s { - if v == vs { + for i := range s { + if v == s[i] { return i } } @@ -115,8 +115,8 @@ func Index[E comparable](s []E, v E) int { // IndexFunc returns the first index i satisfying f(s[i]), // or -1 if none do. func IndexFunc[E any](s []E, f func(E) bool) int { - for i, v := range s { - if f(v) { + for i := range s { + if f(s[i]) { return i } } @@ -207,12 +207,12 @@ func Compact[S ~[]E, E comparable](s S) S { return s } i := 1 - last := s[0] - for _, v := range s[1:] { - if v != last { - s[i] = v + for k := 1; k < len(s); k++ { + if s[k] != s[k-1] { + if i != k { + s[i] = s[k] + } i++ - last = v } } return s[:i] @@ -224,12 +224,12 @@ func CompactFunc[S ~[]E, E any](s S, eq func(E, E) bool) S { return s } i := 1 - last := s[0] - for _, v := range s[1:] { - if !eq(v, last) { - s[i] = v + for k := 1; k < len(s); k++ { + if !eq(s[k], s[k-1]) { + if i != k { + s[i] = s[k] + } i++ - last = v } } return s[:i] diff --git a/vendor/golang.org/x/exp/slices/sort.go b/vendor/golang.org/x/exp/slices/sort.go index f14f40da712..231b6448acd 100644 --- a/vendor/golang.org/x/exp/slices/sort.go +++ b/vendor/golang.org/x/exp/slices/sort.go @@ -81,10 +81,12 @@ func BinarySearch[E constraints.Ordered](x []E, target E) (int, bool) { } // BinarySearchFunc works like BinarySearch, but uses a custom comparison -// function. The slice must be sorted in increasing order, where "increasing" is -// defined by cmp. cmp(a, b) is expected to return an integer comparing the two -// parameters: 0 if a == b, a negative number if a < b and a positive number if -// a > b. +// function. The slice must be sorted in increasing order, where "increasing" +// is defined by cmp. cmp should return 0 if the slice element matches +// the target, a negative number if the slice element precedes the target, +// or a positive number if the slice element follows the target. +// cmp must implement the same ordering as the slice, such that if +// cmp(a, t) < 0 and cmp(b, t) >= 0, then a must precede b in the slice. func BinarySearchFunc[E, T any](x []E, target T, cmp func(E, T) int) (int, bool) { n := len(x) // Define cmp(x[-1], target) < 0 and cmp(x[n], target) >= 0 . diff --git a/vendor/golang.org/x/net/http2/transport.go b/vendor/golang.org/x/net/http2/transport.go index f965579f7d5..ac90a2631c9 100644 --- a/vendor/golang.org/x/net/http2/transport.go +++ b/vendor/golang.org/x/net/http2/transport.go @@ -1266,6 +1266,27 @@ func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) { return res, nil } + cancelRequest := func(cs *clientStream, err error) error { + cs.cc.mu.Lock() + defer cs.cc.mu.Unlock() + cs.abortStreamLocked(err) + if cs.ID != 0 { + // This request may have failed because of a problem with the connection, + // or for some unrelated reason. (For example, the user might have canceled + // the request without waiting for a response.) Mark the connection as + // not reusable, since trying to reuse a dead connection is worse than + // unnecessarily creating a new one. + // + // If cs.ID is 0, then the request was never allocated a stream ID and + // whatever went wrong was unrelated to the connection. We might have + // timed out waiting for a stream slot when StrictMaxConcurrentStreams + // is set, for example, in which case retrying on a different connection + // will not help. + cs.cc.doNotReuse = true + } + return err + } + for { select { case <-cs.respHeaderRecv: @@ -1280,15 +1301,12 @@ func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) { return handleResponseHeaders() default: waitDone() - return nil, cs.abortErr + return nil, cancelRequest(cs, cs.abortErr) } case <-ctx.Done(): - err := ctx.Err() - cs.abortStream(err) - return nil, err + return nil, cancelRequest(cs, ctx.Err()) case <-cs.reqCancel: - cs.abortStream(errRequestCanceled) - return nil, errRequestCanceled + return nil, cancelRequest(cs, errRequestCanceled) } } } diff --git a/vendor/golang.org/x/net/internal/socks/socks.go b/vendor/golang.org/x/net/internal/socks/socks.go index 97db2340ec9..84fcc32b634 100644 --- a/vendor/golang.org/x/net/internal/socks/socks.go +++ b/vendor/golang.org/x/net/internal/socks/socks.go @@ -289,7 +289,7 @@ func (up *UsernamePassword) Authenticate(ctx context.Context, rw io.ReadWriter, case AuthMethodNotRequired: return nil case AuthMethodUsernamePassword: - if len(up.Username) == 0 || len(up.Username) > 255 || len(up.Password) == 0 || len(up.Password) > 255 { + if len(up.Username) == 0 || len(up.Username) > 255 || len(up.Password) > 255 { return errors.New("invalid username/password") } b := []byte{authUsernamePasswordVersion} diff --git a/vendor/golang.org/x/oauth2/google/default.go b/vendor/golang.org/x/oauth2/google/default.go index b3e8783cc59..2cf71f0f93f 100644 --- a/vendor/golang.org/x/oauth2/google/default.go +++ b/vendor/golang.org/x/oauth2/google/default.go @@ -8,7 +8,6 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" "net/http" "os" "path/filepath" @@ -142,10 +141,8 @@ func FindDefaultCredentialsWithParams(ctx context.Context, params CredentialsPar // Second, try a well-known file. filename := wellKnownFile() - if creds, err := readCredentialsFile(ctx, filename, params); err == nil { - return creds, nil - } else if !os.IsNotExist(err) { - return nil, fmt.Errorf("google: error getting credentials using well-known file (%v): %v", filename, err) + if b, err := os.ReadFile(filename); err == nil { + return CredentialsFromJSONWithParams(ctx, b, params) } // Third, if we're on a Google App Engine standard first generation runtime (<= Go 1.9) @@ -231,7 +228,7 @@ func wellKnownFile() string { } func readCredentialsFile(ctx context.Context, filename string, params CredentialsParams) (*Credentials, error) { - b, err := ioutil.ReadFile(filename) + b, err := os.ReadFile(filename) if err != nil { return nil, err } diff --git a/vendor/golang.org/x/oauth2/internal/oauth2.go b/vendor/golang.org/x/oauth2/internal/oauth2.go index c0ab196cf46..14989beaf49 100644 --- a/vendor/golang.org/x/oauth2/internal/oauth2.go +++ b/vendor/golang.org/x/oauth2/internal/oauth2.go @@ -14,7 +14,7 @@ import ( // ParseKey converts the binary contents of a private key file // to an *rsa.PrivateKey. It detects whether the private key is in a -// PEM container or not. If so, it extracts the the private key +// PEM container or not. If so, it extracts the private key // from PEM container before conversion. It only supports PEM // containers with no passphrase. func ParseKey(key []byte) (*rsa.PrivateKey, error) { diff --git a/vendor/golang.org/x/oauth2/internal/token.go b/vendor/golang.org/x/oauth2/internal/token.go index b4723fcacea..58901bda53e 100644 --- a/vendor/golang.org/x/oauth2/internal/token.go +++ b/vendor/golang.org/x/oauth2/internal/token.go @@ -55,12 +55,18 @@ type Token struct { } // tokenJSON is the struct representing the HTTP response from OAuth2 -// providers returning a token in JSON form. +// providers returning a token or error in JSON form. +// https://datatracker.ietf.org/doc/html/rfc6749#section-5.1 type tokenJSON struct { AccessToken string `json:"access_token"` TokenType string `json:"token_type"` RefreshToken string `json:"refresh_token"` ExpiresIn expirationTime `json:"expires_in"` // at least PayPal returns string, while most return number + // error fields + // https://datatracker.ietf.org/doc/html/rfc6749#section-5.2 + ErrorCode string `json:"error"` + ErrorDescription string `json:"error_description"` + ErrorURI string `json:"error_uri"` } func (e *tokenJSON) expiry() (t time.Time) { @@ -236,21 +242,29 @@ func doTokenRoundTrip(ctx context.Context, req *http.Request) (*Token, error) { if err != nil { return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err) } - if code := r.StatusCode; code < 200 || code > 299 { - return nil, &RetrieveError{ - Response: r, - Body: body, - } + + failureStatus := r.StatusCode < 200 || r.StatusCode > 299 + retrieveError := &RetrieveError{ + Response: r, + Body: body, + // attempt to populate error detail below } var token *Token content, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type")) switch content { case "application/x-www-form-urlencoded", "text/plain": + // some endpoints return a query string vals, err := url.ParseQuery(string(body)) if err != nil { - return nil, err + if failureStatus { + return nil, retrieveError + } + return nil, fmt.Errorf("oauth2: cannot parse response: %v", err) } + retrieveError.ErrorCode = vals.Get("error") + retrieveError.ErrorDescription = vals.Get("error_description") + retrieveError.ErrorURI = vals.Get("error_uri") token = &Token{ AccessToken: vals.Get("access_token"), TokenType: vals.Get("token_type"), @@ -265,8 +279,14 @@ func doTokenRoundTrip(ctx context.Context, req *http.Request) (*Token, error) { default: var tj tokenJSON if err = json.Unmarshal(body, &tj); err != nil { - return nil, err + if failureStatus { + return nil, retrieveError + } + return nil, fmt.Errorf("oauth2: cannot parse json: %v", err) } + retrieveError.ErrorCode = tj.ErrorCode + retrieveError.ErrorDescription = tj.ErrorDescription + retrieveError.ErrorURI = tj.ErrorURI token = &Token{ AccessToken: tj.AccessToken, TokenType: tj.TokenType, @@ -276,17 +296,37 @@ func doTokenRoundTrip(ctx context.Context, req *http.Request) (*Token, error) { } json.Unmarshal(body, &token.Raw) // no error checks for optional fields } + // according to spec, servers should respond status 400 in error case + // https://www.rfc-editor.org/rfc/rfc6749#section-5.2 + // but some unorthodox servers respond 200 in error case + if failureStatus || retrieveError.ErrorCode != "" { + return nil, retrieveError + } if token.AccessToken == "" { return nil, errors.New("oauth2: server response missing access_token") } return token, nil } +// mirrors oauth2.RetrieveError type RetrieveError struct { - Response *http.Response - Body []byte + Response *http.Response + Body []byte + ErrorCode string + ErrorDescription string + ErrorURI string } func (r *RetrieveError) Error() string { + if r.ErrorCode != "" { + s := fmt.Sprintf("oauth2: %q", r.ErrorCode) + if r.ErrorDescription != "" { + s += fmt.Sprintf(" %q", r.ErrorDescription) + } + if r.ErrorURI != "" { + s += fmt.Sprintf(" %q", r.ErrorURI) + } + return s + } return fmt.Sprintf("oauth2: cannot fetch token: %v\nResponse: %s", r.Response.Status, r.Body) } diff --git a/vendor/golang.org/x/oauth2/token.go b/vendor/golang.org/x/oauth2/token.go index 7c64006de69..5ffce9764be 100644 --- a/vendor/golang.org/x/oauth2/token.go +++ b/vendor/golang.org/x/oauth2/token.go @@ -175,14 +175,31 @@ func retrieveToken(ctx context.Context, c *Config, v url.Values) (*Token, error) } // RetrieveError is the error returned when the token endpoint returns a -// non-2XX HTTP status code. +// non-2XX HTTP status code or populates RFC 6749's 'error' parameter. +// https://datatracker.ietf.org/doc/html/rfc6749#section-5.2 type RetrieveError struct { Response *http.Response // Body is the body that was consumed by reading Response.Body. // It may be truncated. Body []byte + // ErrorCode is RFC 6749's 'error' parameter. + ErrorCode string + // ErrorDescription is RFC 6749's 'error_description' parameter. + ErrorDescription string + // ErrorURI is RFC 6749's 'error_uri' parameter. + ErrorURI string } func (r *RetrieveError) Error() string { + if r.ErrorCode != "" { + s := fmt.Sprintf("oauth2: %q", r.ErrorCode) + if r.ErrorDescription != "" { + s += fmt.Sprintf(" %q", r.ErrorDescription) + } + if r.ErrorURI != "" { + s += fmt.Sprintf(" %q", r.ErrorURI) + } + return s + } return fmt.Sprintf("oauth2: cannot fetch token: %v\nResponse: %s", r.Response.Status, r.Body) } diff --git a/vendor/golang.org/x/sys/unix/mkerrors.sh b/vendor/golang.org/x/sys/unix/mkerrors.sh index 2045d3dadb8..be0423e6856 100644 --- a/vendor/golang.org/x/sys/unix/mkerrors.sh +++ b/vendor/golang.org/x/sys/unix/mkerrors.sh @@ -204,6 +204,7 @@ struct ltchars { #include #include #include +#include #include #include #include @@ -518,7 +519,7 @@ ccflags="$@" $2 ~ /^LOCK_(SH|EX|NB|UN)$/ || $2 ~ /^LO_(KEY|NAME)_SIZE$/ || $2 ~ /^LOOP_(CLR|CTL|GET|SET)_/ || - $2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|TCP|MCAST|EVFILT|NOTE|SHUT|PROT|MAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR|LOCAL|TCPOPT)_/ || + $2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|TCP|MCAST|EVFILT|NOTE|SHUT|PROT|MAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR|LOCAL|TCPOPT|UDP)_/ || $2 ~ /^NFC_(GENL|PROTO|COMM|RF|SE|DIRECTION|LLCP|SOCKPROTO)_/ || $2 ~ /^NFC_.*_(MAX)?SIZE$/ || $2 ~ /^RAW_PAYLOAD_/ || diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux.go b/vendor/golang.org/x/sys/unix/zerrors_linux.go index 398c37e52d6..de936b677b6 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux.go @@ -2967,6 +2967,7 @@ const ( SOL_TCP = 0x6 SOL_TIPC = 0x10f SOL_TLS = 0x11a + SOL_UDP = 0x11 SOL_X25 = 0x106 SOL_XDP = 0x11b SOMAXCONN = 0x1000 @@ -3251,6 +3252,19 @@ const ( TRACEFS_MAGIC = 0x74726163 TS_COMM_LEN = 0x20 UDF_SUPER_MAGIC = 0x15013346 + UDP_CORK = 0x1 + UDP_ENCAP = 0x64 + UDP_ENCAP_ESPINUDP = 0x2 + UDP_ENCAP_ESPINUDP_NON_IKE = 0x1 + UDP_ENCAP_GTP0 = 0x4 + UDP_ENCAP_GTP1U = 0x5 + UDP_ENCAP_L2TPINUDP = 0x3 + UDP_GRO = 0x68 + UDP_NO_CHECK6_RX = 0x66 + UDP_NO_CHECK6_TX = 0x65 + UDP_SEGMENT = 0x67 + UDP_V4_FLOW = 0x2 + UDP_V6_FLOW = 0x6 UMOUNT_NOFOLLOW = 0x8 USBDEVICE_SUPER_MAGIC = 0x9fa2 UTIME_NOW = 0x3fffffff diff --git a/vendor/golang.org/x/sys/windows/env_windows.go b/vendor/golang.org/x/sys/windows/env_windows.go index 92ac05ff4ea..b8ad1925068 100644 --- a/vendor/golang.org/x/sys/windows/env_windows.go +++ b/vendor/golang.org/x/sys/windows/env_windows.go @@ -37,14 +37,14 @@ func (token Token) Environ(inheritExisting bool) (env []string, err error) { return nil, err } defer DestroyEnvironmentBlock(block) - blockp := uintptr(unsafe.Pointer(block)) + blockp := unsafe.Pointer(block) for { - entry := UTF16PtrToString((*uint16)(unsafe.Pointer(blockp))) + entry := UTF16PtrToString((*uint16)(blockp)) if len(entry) == 0 { break } env = append(env, entry) - blockp += 2 * (uintptr(len(entry)) + 1) + blockp = unsafe.Add(blockp, 2*(len(entry)+1)) } return env, nil } diff --git a/vendor/golang.org/x/sys/windows/exec_windows.go b/vendor/golang.org/x/sys/windows/exec_windows.go index 75980fd44ad..a52e0331d8b 100644 --- a/vendor/golang.org/x/sys/windows/exec_windows.go +++ b/vendor/golang.org/x/sys/windows/exec_windows.go @@ -95,12 +95,17 @@ func ComposeCommandLine(args []string) string { // DecomposeCommandLine breaks apart its argument command line into unescaped parts using CommandLineToArgv, // as gathered from GetCommandLine, QUERY_SERVICE_CONFIG's BinaryPathName argument, or elsewhere that // command lines are passed around. +// DecomposeCommandLine returns error if commandLine contains NUL. func DecomposeCommandLine(commandLine string) ([]string, error) { if len(commandLine) == 0 { return []string{}, nil } + utf16CommandLine, err := UTF16FromString(commandLine) + if err != nil { + return nil, errorspkg.New("string with NUL passed to DecomposeCommandLine") + } var argc int32 - argv, err := CommandLineToArgv(StringToUTF16Ptr(commandLine), &argc) + argv, err := CommandLineToArgv(&utf16CommandLine[0], &argc) if err != nil { return nil, err } diff --git a/vendor/golang.org/x/sys/windows/service.go b/vendor/golang.org/x/sys/windows/service.go index f8deca8397a..c964b6848d4 100644 --- a/vendor/golang.org/x/sys/windows/service.go +++ b/vendor/golang.org/x/sys/windows/service.go @@ -141,6 +141,12 @@ const ( SERVICE_DYNAMIC_INFORMATION_LEVEL_START_REASON = 1 ) +type ENUM_SERVICE_STATUS struct { + ServiceName *uint16 + DisplayName *uint16 + ServiceStatus SERVICE_STATUS +} + type SERVICE_STATUS struct { ServiceType uint32 CurrentState uint32 @@ -245,3 +251,4 @@ type QUERY_SERVICE_LOCK_STATUS struct { //sys UnsubscribeServiceChangeNotifications(subscription uintptr) = sechost.UnsubscribeServiceChangeNotifications? //sys RegisterServiceCtrlHandlerEx(serviceName *uint16, handlerProc uintptr, context uintptr) (handle Handle, err error) = advapi32.RegisterServiceCtrlHandlerExW //sys QueryServiceDynamicInformation(service Handle, infoLevel uint32, dynamicInfo unsafe.Pointer) (err error) = advapi32.QueryServiceDynamicInformation? +//sys EnumDependentServices(service Handle, activityState uint32, services *ENUM_SERVICE_STATUS, buffSize uint32, bytesNeeded *uint32, servicesReturned *uint32) (err error) = advapi32.EnumDependentServicesW diff --git a/vendor/golang.org/x/sys/windows/types_windows.go b/vendor/golang.org/x/sys/windows/types_windows.go index 0dbb2084117..88e62a63851 100644 --- a/vendor/golang.org/x/sys/windows/types_windows.go +++ b/vendor/golang.org/x/sys/windows/types_windows.go @@ -2220,15 +2220,19 @@ type JOBOBJECT_BASIC_UI_RESTRICTIONS struct { } const ( - // JobObjectInformationClass + // JobObjectInformationClass for QueryInformationJobObject and SetInformationJobObject JobObjectAssociateCompletionPortInformation = 7 + JobObjectBasicAccountingInformation = 1 + JobObjectBasicAndIoAccountingInformation = 8 JobObjectBasicLimitInformation = 2 + JobObjectBasicProcessIdList = 3 JobObjectBasicUIRestrictions = 4 JobObjectCpuRateControlInformation = 15 JobObjectEndOfJobTimeInformation = 6 JobObjectExtendedLimitInformation = 9 JobObjectGroupInformation = 11 JobObjectGroupInformationEx = 14 + JobObjectLimitViolationInformation = 13 JobObjectLimitViolationInformation2 = 34 JobObjectNetRateControlInformation = 32 JobObjectNotificationLimitInformation = 12 diff --git a/vendor/golang.org/x/sys/windows/zsyscall_windows.go b/vendor/golang.org/x/sys/windows/zsyscall_windows.go index 6d2a268534d..a81ea2c7001 100644 --- a/vendor/golang.org/x/sys/windows/zsyscall_windows.go +++ b/vendor/golang.org/x/sys/windows/zsyscall_windows.go @@ -86,6 +86,7 @@ var ( procDeleteService = modadvapi32.NewProc("DeleteService") procDeregisterEventSource = modadvapi32.NewProc("DeregisterEventSource") procDuplicateTokenEx = modadvapi32.NewProc("DuplicateTokenEx") + procEnumDependentServicesW = modadvapi32.NewProc("EnumDependentServicesW") procEnumServicesStatusExW = modadvapi32.NewProc("EnumServicesStatusExW") procEqualSid = modadvapi32.NewProc("EqualSid") procFreeSid = modadvapi32.NewProc("FreeSid") @@ -734,6 +735,14 @@ func DuplicateTokenEx(existingToken Token, desiredAccess uint32, tokenAttributes return } +func EnumDependentServices(service Handle, activityState uint32, services *ENUM_SERVICE_STATUS, buffSize uint32, bytesNeeded *uint32, servicesReturned *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procEnumDependentServicesW.Addr(), 6, uintptr(service), uintptr(activityState), uintptr(unsafe.Pointer(services)), uintptr(buffSize), uintptr(unsafe.Pointer(bytesNeeded)), uintptr(unsafe.Pointer(servicesReturned))) + if r1 == 0 { + err = errnoErr(e1) + } + return +} + func EnumServicesStatusEx(mgr Handle, infoLevel uint32, serviceType uint32, serviceState uint32, services *byte, bufSize uint32, bytesNeeded *uint32, servicesReturned *uint32, resumeHandle *uint32, groupName *uint16) (err error) { r1, _, e1 := syscall.Syscall12(procEnumServicesStatusExW.Addr(), 10, uintptr(mgr), uintptr(infoLevel), uintptr(serviceType), uintptr(serviceState), uintptr(unsafe.Pointer(services)), uintptr(bufSize), uintptr(unsafe.Pointer(bytesNeeded)), uintptr(unsafe.Pointer(servicesReturned)), uintptr(unsafe.Pointer(resumeHandle)), uintptr(unsafe.Pointer(groupName)), 0, 0) if r1 == 0 { diff --git a/vendor/golang.org/x/tools/go/gcexportdata/gcexportdata.go b/vendor/golang.org/x/tools/go/gcexportdata/gcexportdata.go index 165ede0f8f3..03543bd4bb8 100644 --- a/vendor/golang.org/x/tools/go/gcexportdata/gcexportdata.go +++ b/vendor/golang.org/x/tools/go/gcexportdata/gcexportdata.go @@ -128,15 +128,14 @@ func Read(in io.Reader, fset *token.FileSet, imports map[string]*types.Package, // (from "version"). Select appropriate importer. if len(data) > 0 { switch data[0] { - case 'i': - _, pkg, err := gcimporter.IImportData(fset, imports, data[1:], path) - return pkg, err + case 'v', 'c', 'd': // binary, till go1.10 + return nil, fmt.Errorf("binary (%c) import format is no longer supported", data[0]) - case 'v', 'c', 'd': - _, pkg, err := gcimporter.BImportData(fset, imports, data, path) + case 'i': // indexed, till go1.19 + _, pkg, err := gcimporter.IImportData(fset, imports, data[1:], path) return pkg, err - case 'u': + case 'u': // unified, from go1.20 _, pkg, err := gcimporter.UImportData(fset, imports, data[1:], path) return pkg, err diff --git a/vendor/golang.org/x/tools/go/packages/golist.go b/vendor/golang.org/x/tools/go/packages/golist.go index 6bb7168d2e3..e84f19dfa98 100644 --- a/vendor/golang.org/x/tools/go/packages/golist.go +++ b/vendor/golang.org/x/tools/go/packages/golist.go @@ -625,7 +625,12 @@ func (state *golistState) createDriverResponse(words ...string) (*driverResponse } if pkg.PkgPath == "unsafe" { - pkg.GoFiles = nil // ignore fake unsafe.go file + pkg.CompiledGoFiles = nil // ignore fake unsafe.go file (#59929) + } else if len(pkg.CompiledGoFiles) == 0 { + // Work around for pre-go.1.11 versions of go list. + // TODO(matloob): they should be handled by the fallback. + // Can we delete this? + pkg.CompiledGoFiles = pkg.GoFiles } // Assume go list emits only absolute paths for Dir. @@ -663,13 +668,6 @@ func (state *golistState) createDriverResponse(words ...string) (*driverResponse response.Roots = append(response.Roots, pkg.ID) } - // Work around for pre-go.1.11 versions of go list. - // TODO(matloob): they should be handled by the fallback. - // Can we delete this? - if len(pkg.CompiledGoFiles) == 0 { - pkg.CompiledGoFiles = pkg.GoFiles - } - // Temporary work-around for golang/go#39986. Parse filenames out of // error messages. This happens if there are unrecoverable syntax // errors in the source, so we can't match on a specific error message. @@ -891,6 +889,15 @@ func golistargs(cfg *Config, words []string, goVersion int) []string { // probably because you'd just get the TestMain. fmt.Sprintf("-find=%t", !cfg.Tests && cfg.Mode&findFlags == 0 && !usesExportData(cfg)), } + + // golang/go#60456: with go1.21 and later, go list serves pgo variants, which + // can be costly to compute and may result in redundant processing for the + // caller. Disable these variants. If someone wants to add e.g. a NeedPGO + // mode flag, that should be a separate proposal. + if goVersion >= 21 { + fullargs = append(fullargs, "-pgo=off") + } + fullargs = append(fullargs, cfg.BuildFlags...) fullargs = append(fullargs, "--") fullargs = append(fullargs, words...) diff --git a/vendor/golang.org/x/tools/go/packages/packages.go b/vendor/golang.org/x/tools/go/packages/packages.go index 0f1505b808a..632be722a2b 100644 --- a/vendor/golang.org/x/tools/go/packages/packages.go +++ b/vendor/golang.org/x/tools/go/packages/packages.go @@ -308,6 +308,9 @@ type Package struct { TypeErrors []types.Error // GoFiles lists the absolute file paths of the package's Go source files. + // It may include files that should not be compiled, for example because + // they contain non-matching build tags, are documentary pseudo-files such as + // unsafe/unsafe.go or builtin/builtin.go, or are subject to cgo preprocessing. GoFiles []string // CompiledGoFiles lists the absolute file paths of the package's source diff --git a/vendor/golang.org/x/tools/go/types/objectpath/objectpath.go b/vendor/golang.org/x/tools/go/types/objectpath/objectpath.go deleted file mode 100644 index be8f5a867e6..00000000000 --- a/vendor/golang.org/x/tools/go/types/objectpath/objectpath.go +++ /dev/null @@ -1,762 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package objectpath defines a naming scheme for types.Objects -// (that is, named entities in Go programs) relative to their enclosing -// package. -// -// Type-checker objects are canonical, so they are usually identified by -// their address in memory (a pointer), but a pointer has meaning only -// within one address space. By contrast, objectpath names allow the -// identity of an object to be sent from one program to another, -// establishing a correspondence between types.Object variables that are -// distinct but logically equivalent. -// -// A single object may have multiple paths. In this example, -// -// type A struct{ X int } -// type B A -// -// the field X has two paths due to its membership of both A and B. -// The For(obj) function always returns one of these paths, arbitrarily -// but consistently. -package objectpath - -import ( - "fmt" - "go/types" - "sort" - "strconv" - "strings" - - "golang.org/x/tools/internal/typeparams" - - _ "unsafe" // for go:linkname -) - -// A Path is an opaque name that identifies a types.Object -// relative to its package. Conceptually, the name consists of a -// sequence of destructuring operations applied to the package scope -// to obtain the original object. -// The name does not include the package itself. -type Path string - -// Encoding -// -// An object path is a textual and (with training) human-readable encoding -// of a sequence of destructuring operators, starting from a types.Package. -// The sequences represent a path through the package/object/type graph. -// We classify these operators by their type: -// -// PO package->object Package.Scope.Lookup -// OT object->type Object.Type -// TT type->type Type.{Elem,Key,Params,Results,Underlying} [EKPRU] -// TO type->object Type.{At,Field,Method,Obj} [AFMO] -// -// All valid paths start with a package and end at an object -// and thus may be defined by the regular language: -// -// objectpath = PO (OT TT* TO)* -// -// The concrete encoding follows directly: -// - The only PO operator is Package.Scope.Lookup, which requires an identifier. -// - The only OT operator is Object.Type, -// which we encode as '.' because dot cannot appear in an identifier. -// - The TT operators are encoded as [EKPRUTC]; -// one of these (TypeParam) requires an integer operand, -// which is encoded as a string of decimal digits. -// - The TO operators are encoded as [AFMO]; -// three of these (At,Field,Method) require an integer operand, -// which is encoded as a string of decimal digits. -// These indices are stable across different representations -// of the same package, even source and export data. -// The indices used are implementation specific and may not correspond to -// the argument to the go/types function. -// -// In the example below, -// -// package p -// -// type T interface { -// f() (a string, b struct{ X int }) -// } -// -// field X has the path "T.UM0.RA1.F0", -// representing the following sequence of operations: -// -// p.Lookup("T") T -// .Type().Underlying().Method(0). f -// .Type().Results().At(1) b -// .Type().Field(0) X -// -// The encoding is not maximally compact---every R or P is -// followed by an A, for example---but this simplifies the -// encoder and decoder. -const ( - // object->type operators - opType = '.' // .Type() (Object) - - // type->type operators - opElem = 'E' // .Elem() (Pointer, Slice, Array, Chan, Map) - opKey = 'K' // .Key() (Map) - opParams = 'P' // .Params() (Signature) - opResults = 'R' // .Results() (Signature) - opUnderlying = 'U' // .Underlying() (Named) - opTypeParam = 'T' // .TypeParams.At(i) (Named, Signature) - opConstraint = 'C' // .Constraint() (TypeParam) - - // type->object operators - opAt = 'A' // .At(i) (Tuple) - opField = 'F' // .Field(i) (Struct) - opMethod = 'M' // .Method(i) (Named or Interface; not Struct: "promoted" names are ignored) - opObj = 'O' // .Obj() (Named, TypeParam) -) - -// For returns the path to an object relative to its package, -// or an error if the object is not accessible from the package's Scope. -// -// The For function guarantees to return a path only for the following objects: -// - package-level types -// - exported package-level non-types -// - methods -// - parameter and result variables -// - struct fields -// These objects are sufficient to define the API of their package. -// The objects described by a package's export data are drawn from this set. -// -// For does not return a path for predeclared names, imported package -// names, local names, and unexported package-level names (except -// types). -// -// Example: given this definition, -// -// package p -// -// type T interface { -// f() (a string, b struct{ X int }) -// } -// -// For(X) would return a path that denotes the following sequence of operations: -// -// p.Scope().Lookup("T") (TypeName T) -// .Type().Underlying().Method(0). (method Func f) -// .Type().Results().At(1) (field Var b) -// .Type().Field(0) (field Var X) -// -// where p is the package (*types.Package) to which X belongs. -func For(obj types.Object) (Path, error) { - return newEncoderFor()(obj) -} - -// An encoder amortizes the cost of encoding the paths of multiple objects. -// Nonexported pending approval of proposal 58668. -type encoder struct { - scopeNamesMemo map[*types.Scope][]string // memoization of Scope.Names() - namedMethodsMemo map[*types.Named][]*types.Func // memoization of namedMethods() -} - -// Exposed to gopls via golang.org/x/tools/internal/typesinternal -// pending approval of proposal 58668. -// -//go:linkname newEncoderFor -func newEncoderFor() func(types.Object) (Path, error) { return new(encoder).For } - -func (enc *encoder) For(obj types.Object) (Path, error) { - pkg := obj.Pkg() - - // This table lists the cases of interest. - // - // Object Action - // ------ ------ - // nil reject - // builtin reject - // pkgname reject - // label reject - // var - // package-level accept - // func param/result accept - // local reject - // struct field accept - // const - // package-level accept - // local reject - // func - // package-level accept - // init functions reject - // concrete method accept - // interface method accept - // type - // package-level accept - // local reject - // - // The only accessible package-level objects are members of pkg itself. - // - // The cases are handled in four steps: - // - // 1. reject nil and builtin - // 2. accept package-level objects - // 3. reject obviously invalid objects - // 4. search the API for the path to the param/result/field/method. - - // 1. reference to nil or builtin? - if pkg == nil { - return "", fmt.Errorf("predeclared %s has no path", obj) - } - scope := pkg.Scope() - - // 2. package-level object? - if scope.Lookup(obj.Name()) == obj { - // Only exported objects (and non-exported types) have a path. - // Non-exported types may be referenced by other objects. - if _, ok := obj.(*types.TypeName); !ok && !obj.Exported() { - return "", fmt.Errorf("no path for non-exported %v", obj) - } - return Path(obj.Name()), nil - } - - // 3. Not a package-level object. - // Reject obviously non-viable cases. - switch obj := obj.(type) { - case *types.TypeName: - if _, ok := obj.Type().(*typeparams.TypeParam); !ok { - // With the exception of type parameters, only package-level type names - // have a path. - return "", fmt.Errorf("no path for %v", obj) - } - case *types.Const, // Only package-level constants have a path. - *types.Label, // Labels are function-local. - *types.PkgName: // PkgNames are file-local. - return "", fmt.Errorf("no path for %v", obj) - - case *types.Var: - // Could be: - // - a field (obj.IsField()) - // - a func parameter or result - // - a local var. - // Sadly there is no way to distinguish - // a param/result from a local - // so we must proceed to the find. - - case *types.Func: - // A func, if not package-level, must be a method. - if recv := obj.Type().(*types.Signature).Recv(); recv == nil { - return "", fmt.Errorf("func is not a method: %v", obj) - } - - if path, ok := enc.concreteMethod(obj); ok { - // Fast path for concrete methods that avoids looping over scope. - return path, nil - } - - default: - panic(obj) - } - - // 4. Search the API for the path to the var (field/param/result) or method. - - // First inspect package-level named types. - // In the presence of path aliases, these give - // the best paths because non-types may - // refer to types, but not the reverse. - empty := make([]byte, 0, 48) // initial space - names := enc.scopeNames(scope) - for _, name := range names { - o := scope.Lookup(name) - tname, ok := o.(*types.TypeName) - if !ok { - continue // handle non-types in second pass - } - - path := append(empty, name...) - path = append(path, opType) - - T := o.Type() - - if tname.IsAlias() { - // type alias - if r := find(obj, T, path, nil); r != nil { - return Path(r), nil - } - } else { - if named, _ := T.(*types.Named); named != nil { - if r := findTypeParam(obj, typeparams.ForNamed(named), path, nil); r != nil { - // generic named type - return Path(r), nil - } - } - // defined (named) type - if r := find(obj, T.Underlying(), append(path, opUnderlying), nil); r != nil { - return Path(r), nil - } - } - } - - // Then inspect everything else: - // non-types, and declared methods of defined types. - for _, name := range names { - o := scope.Lookup(name) - path := append(empty, name...) - if _, ok := o.(*types.TypeName); !ok { - if o.Exported() { - // exported non-type (const, var, func) - if r := find(obj, o.Type(), append(path, opType), nil); r != nil { - return Path(r), nil - } - } - continue - } - - // Inspect declared methods of defined types. - if T, ok := o.Type().(*types.Named); ok { - path = append(path, opType) - // Note that method index here is always with respect - // to canonical ordering of methods, regardless of how - // they appear in the underlying type. - for i, m := range enc.namedMethods(T) { - path2 := appendOpArg(path, opMethod, i) - if m == obj { - return Path(path2), nil // found declared method - } - if r := find(obj, m.Type(), append(path2, opType), nil); r != nil { - return Path(r), nil - } - } - } - } - - return "", fmt.Errorf("can't find path for %v in %s", obj, pkg.Path()) -} - -func appendOpArg(path []byte, op byte, arg int) []byte { - path = append(path, op) - path = strconv.AppendInt(path, int64(arg), 10) - return path -} - -// concreteMethod returns the path for meth, which must have a non-nil receiver. -// The second return value indicates success and may be false if the method is -// an interface method or if it is an instantiated method. -// -// This function is just an optimization that avoids the general scope walking -// approach. You are expected to fall back to the general approach if this -// function fails. -func (enc *encoder) concreteMethod(meth *types.Func) (Path, bool) { - // Concrete methods can only be declared on package-scoped named types. For - // that reason we can skip the expensive walk over the package scope: the - // path will always be package -> named type -> method. We can trivially get - // the type name from the receiver, and only have to look over the type's - // methods to find the method index. - // - // Methods on generic types require special consideration, however. Consider - // the following package: - // - // L1: type S[T any] struct{} - // L2: func (recv S[A]) Foo() { recv.Bar() } - // L3: func (recv S[B]) Bar() { } - // L4: type Alias = S[int] - // L5: func _[T any]() { var s S[int]; s.Foo() } - // - // The receivers of methods on generic types are instantiations. L2 and L3 - // instantiate S with the type-parameters A and B, which are scoped to the - // respective methods. L4 and L5 each instantiate S with int. Each of these - // instantiations has its own method set, full of methods (and thus objects) - // with receivers whose types are the respective instantiations. In other - // words, we have - // - // S[A].Foo, S[A].Bar - // S[B].Foo, S[B].Bar - // S[int].Foo, S[int].Bar - // - // We may thus be trying to produce object paths for any of these objects. - // - // S[A].Foo and S[B].Bar are the origin methods, and their paths are S.Foo - // and S.Bar, which are the paths that this function naturally produces. - // - // S[A].Bar, S[B].Foo, and both methods on S[int] are instantiations that - // don't correspond to the origin methods. For S[int], this is significant. - // The most precise object path for S[int].Foo, for example, is Alias.Foo, - // not S.Foo. Our function, however, would produce S.Foo, which would - // resolve to a different object. - // - // For S[A].Bar and S[B].Foo it could be argued that S.Bar and S.Foo are - // still the correct paths, since only the origin methods have meaningful - // paths. But this is likely only true for trivial cases and has edge cases. - // Since this function is only an optimization, we err on the side of giving - // up, deferring to the slower but definitely correct algorithm. Most users - // of objectpath will only be giving us origin methods, anyway, as referring - // to instantiated methods is usually not useful. - - if typeparams.OriginMethod(meth) != meth { - return "", false - } - - recvT := meth.Type().(*types.Signature).Recv().Type() - if ptr, ok := recvT.(*types.Pointer); ok { - recvT = ptr.Elem() - } - - named, ok := recvT.(*types.Named) - if !ok { - return "", false - } - - if types.IsInterface(named) { - // Named interfaces don't have to be package-scoped - // - // TODO(dominikh): opt: if scope.Lookup(name) == named, then we can apply this optimization to interface - // methods, too, I think. - return "", false - } - - // Preallocate space for the name, opType, opMethod, and some digits. - name := named.Obj().Name() - path := make([]byte, 0, len(name)+8) - path = append(path, name...) - path = append(path, opType) - for i, m := range enc.namedMethods(named) { - if m == meth { - path = appendOpArg(path, opMethod, i) - return Path(path), true - } - } - - panic(fmt.Sprintf("couldn't find method %s on type %s", meth, named)) -} - -// find finds obj within type T, returning the path to it, or nil if not found. -// -// The seen map is used to short circuit cycles through type parameters. If -// nil, it will be allocated as necessary. -func find(obj types.Object, T types.Type, path []byte, seen map[*types.TypeName]bool) []byte { - switch T := T.(type) { - case *types.Basic, *types.Named: - // Named types belonging to pkg were handled already, - // so T must belong to another package. No path. - return nil - case *types.Pointer: - return find(obj, T.Elem(), append(path, opElem), seen) - case *types.Slice: - return find(obj, T.Elem(), append(path, opElem), seen) - case *types.Array: - return find(obj, T.Elem(), append(path, opElem), seen) - case *types.Chan: - return find(obj, T.Elem(), append(path, opElem), seen) - case *types.Map: - if r := find(obj, T.Key(), append(path, opKey), seen); r != nil { - return r - } - return find(obj, T.Elem(), append(path, opElem), seen) - case *types.Signature: - if r := findTypeParam(obj, typeparams.ForSignature(T), path, seen); r != nil { - return r - } - if r := find(obj, T.Params(), append(path, opParams), seen); r != nil { - return r - } - return find(obj, T.Results(), append(path, opResults), seen) - case *types.Struct: - for i := 0; i < T.NumFields(); i++ { - fld := T.Field(i) - path2 := appendOpArg(path, opField, i) - if fld == obj { - return path2 // found field var - } - if r := find(obj, fld.Type(), append(path2, opType), seen); r != nil { - return r - } - } - return nil - case *types.Tuple: - for i := 0; i < T.Len(); i++ { - v := T.At(i) - path2 := appendOpArg(path, opAt, i) - if v == obj { - return path2 // found param/result var - } - if r := find(obj, v.Type(), append(path2, opType), seen); r != nil { - return r - } - } - return nil - case *types.Interface: - for i := 0; i < T.NumMethods(); i++ { - m := T.Method(i) - path2 := appendOpArg(path, opMethod, i) - if m == obj { - return path2 // found interface method - } - if r := find(obj, m.Type(), append(path2, opType), seen); r != nil { - return r - } - } - return nil - case *typeparams.TypeParam: - name := T.Obj() - if name == obj { - return append(path, opObj) - } - if seen[name] { - return nil - } - if seen == nil { - seen = make(map[*types.TypeName]bool) - } - seen[name] = true - if r := find(obj, T.Constraint(), append(path, opConstraint), seen); r != nil { - return r - } - return nil - } - panic(T) -} - -func findTypeParam(obj types.Object, list *typeparams.TypeParamList, path []byte, seen map[*types.TypeName]bool) []byte { - for i := 0; i < list.Len(); i++ { - tparam := list.At(i) - path2 := appendOpArg(path, opTypeParam, i) - if r := find(obj, tparam, path2, seen); r != nil { - return r - } - } - return nil -} - -// Object returns the object denoted by path p within the package pkg. -func Object(pkg *types.Package, p Path) (types.Object, error) { - if p == "" { - return nil, fmt.Errorf("empty path") - } - - pathstr := string(p) - var pkgobj, suffix string - if dot := strings.IndexByte(pathstr, opType); dot < 0 { - pkgobj = pathstr - } else { - pkgobj = pathstr[:dot] - suffix = pathstr[dot:] // suffix starts with "." - } - - obj := pkg.Scope().Lookup(pkgobj) - if obj == nil { - return nil, fmt.Errorf("package %s does not contain %q", pkg.Path(), pkgobj) - } - - // abstraction of *types.{Pointer,Slice,Array,Chan,Map} - type hasElem interface { - Elem() types.Type - } - // abstraction of *types.{Named,Signature} - type hasTypeParams interface { - TypeParams() *typeparams.TypeParamList - } - // abstraction of *types.{Named,TypeParam} - type hasObj interface { - Obj() *types.TypeName - } - - // The loop state is the pair (t, obj), - // exactly one of which is non-nil, initially obj. - // All suffixes start with '.' (the only object->type operation), - // followed by optional type->type operations, - // then a type->object operation. - // The cycle then repeats. - var t types.Type - for suffix != "" { - code := suffix[0] - suffix = suffix[1:] - - // Codes [AFM] have an integer operand. - var index int - switch code { - case opAt, opField, opMethod, opTypeParam: - rest := strings.TrimLeft(suffix, "0123456789") - numerals := suffix[:len(suffix)-len(rest)] - suffix = rest - i, err := strconv.Atoi(numerals) - if err != nil { - return nil, fmt.Errorf("invalid path: bad numeric operand %q for code %q", numerals, code) - } - index = int(i) - case opObj: - // no operand - default: - // The suffix must end with a type->object operation. - if suffix == "" { - return nil, fmt.Errorf("invalid path: ends with %q, want [AFMO]", code) - } - } - - if code == opType { - if t != nil { - return nil, fmt.Errorf("invalid path: unexpected %q in type context", opType) - } - t = obj.Type() - obj = nil - continue - } - - if t == nil { - return nil, fmt.Errorf("invalid path: code %q in object context", code) - } - - // Inv: t != nil, obj == nil - - switch code { - case opElem: - hasElem, ok := t.(hasElem) // Pointer, Slice, Array, Chan, Map - if !ok { - return nil, fmt.Errorf("cannot apply %q to %s (got %T, want pointer, slice, array, chan or map)", code, t, t) - } - t = hasElem.Elem() - - case opKey: - mapType, ok := t.(*types.Map) - if !ok { - return nil, fmt.Errorf("cannot apply %q to %s (got %T, want map)", code, t, t) - } - t = mapType.Key() - - case opParams: - sig, ok := t.(*types.Signature) - if !ok { - return nil, fmt.Errorf("cannot apply %q to %s (got %T, want signature)", code, t, t) - } - t = sig.Params() - - case opResults: - sig, ok := t.(*types.Signature) - if !ok { - return nil, fmt.Errorf("cannot apply %q to %s (got %T, want signature)", code, t, t) - } - t = sig.Results() - - case opUnderlying: - named, ok := t.(*types.Named) - if !ok { - return nil, fmt.Errorf("cannot apply %q to %s (got %T, want named)", code, t, t) - } - t = named.Underlying() - - case opTypeParam: - hasTypeParams, ok := t.(hasTypeParams) // Named, Signature - if !ok { - return nil, fmt.Errorf("cannot apply %q to %s (got %T, want named or signature)", code, t, t) - } - tparams := hasTypeParams.TypeParams() - if n := tparams.Len(); index >= n { - return nil, fmt.Errorf("tuple index %d out of range [0-%d)", index, n) - } - t = tparams.At(index) - - case opConstraint: - tparam, ok := t.(*typeparams.TypeParam) - if !ok { - return nil, fmt.Errorf("cannot apply %q to %s (got %T, want type parameter)", code, t, t) - } - t = tparam.Constraint() - - case opAt: - tuple, ok := t.(*types.Tuple) - if !ok { - return nil, fmt.Errorf("cannot apply %q to %s (got %T, want tuple)", code, t, t) - } - if n := tuple.Len(); index >= n { - return nil, fmt.Errorf("tuple index %d out of range [0-%d)", index, n) - } - obj = tuple.At(index) - t = nil - - case opField: - structType, ok := t.(*types.Struct) - if !ok { - return nil, fmt.Errorf("cannot apply %q to %s (got %T, want struct)", code, t, t) - } - if n := structType.NumFields(); index >= n { - return nil, fmt.Errorf("field index %d out of range [0-%d)", index, n) - } - obj = structType.Field(index) - t = nil - - case opMethod: - switch t := t.(type) { - case *types.Interface: - if index >= t.NumMethods() { - return nil, fmt.Errorf("method index %d out of range [0-%d)", index, t.NumMethods()) - } - obj = t.Method(index) // Id-ordered - - case *types.Named: - methods := namedMethods(t) // (unmemoized) - if index >= len(methods) { - return nil, fmt.Errorf("method index %d out of range [0-%d)", index, len(methods)) - } - obj = methods[index] // Id-ordered - - default: - return nil, fmt.Errorf("cannot apply %q to %s (got %T, want interface or named)", code, t, t) - } - t = nil - - case opObj: - hasObj, ok := t.(hasObj) - if !ok { - return nil, fmt.Errorf("cannot apply %q to %s (got %T, want named or type param)", code, t, t) - } - obj = hasObj.Obj() - t = nil - - default: - return nil, fmt.Errorf("invalid path: unknown code %q", code) - } - } - - if obj.Pkg() != pkg { - return nil, fmt.Errorf("path denotes %s, which belongs to a different package", obj) - } - - return obj, nil // success -} - -// namedMethods returns the methods of a Named type in ascending Id order. -func namedMethods(named *types.Named) []*types.Func { - methods := make([]*types.Func, named.NumMethods()) - for i := range methods { - methods[i] = named.Method(i) - } - sort.Slice(methods, func(i, j int) bool { - return methods[i].Id() < methods[j].Id() - }) - return methods -} - -// scopeNames is a memoization of scope.Names. Callers must not modify the result. -func (enc *encoder) scopeNames(scope *types.Scope) []string { - m := enc.scopeNamesMemo - if m == nil { - m = make(map[*types.Scope][]string) - enc.scopeNamesMemo = m - } - names, ok := m[scope] - if !ok { - names = scope.Names() // allocates and sorts - m[scope] = names - } - return names -} - -// namedMethods is a memoization of the namedMethods function. Callers must not modify the result. -func (enc *encoder) namedMethods(named *types.Named) []*types.Func { - m := enc.namedMethodsMemo - if m == nil { - m = make(map[*types.Named][]*types.Func) - enc.namedMethodsMemo = m - } - methods, ok := m[named] - if !ok { - methods = namedMethods(named) // allocates and sorts - m[named] = methods - } - return methods - -} diff --git a/vendor/golang.org/x/tools/internal/event/tag/tag.go b/vendor/golang.org/x/tools/internal/event/tag/tag.go new file mode 100644 index 00000000000..ff2f2ecd38d --- /dev/null +++ b/vendor/golang.org/x/tools/internal/event/tag/tag.go @@ -0,0 +1,59 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package tag provides the labels used for telemetry throughout gopls. +package tag + +import ( + "golang.org/x/tools/internal/event/keys" +) + +var ( + // create the label keys we use + Method = keys.NewString("method", "") + StatusCode = keys.NewString("status.code", "") + StatusMessage = keys.NewString("status.message", "") + RPCID = keys.NewString("id", "") + RPCDirection = keys.NewString("direction", "") + File = keys.NewString("file", "") + Directory = keys.New("directory", "") + URI = keys.New("URI", "") + Package = keys.NewString("package", "") // Package ID + PackagePath = keys.NewString("package_path", "") + Query = keys.New("query", "") + Snapshot = keys.NewUInt64("snapshot", "") + Operation = keys.NewString("operation", "") + + Position = keys.New("position", "") + Category = keys.NewString("category", "") + PackageCount = keys.NewInt("packages", "") + Files = keys.New("files", "") + Port = keys.NewInt("port", "") + Type = keys.New("type", "") + HoverKind = keys.NewString("hoverkind", "") + + NewServer = keys.NewString("new_server", "A new server was added") + EndServer = keys.NewString("end_server", "A server was shut down") + + ServerID = keys.NewString("server", "The server ID an event is related to") + Logfile = keys.NewString("logfile", "") + DebugAddress = keys.NewString("debug_address", "") + GoplsPath = keys.NewString("gopls_path", "") + ClientID = keys.NewString("client_id", "") + + Level = keys.NewInt("level", "The logging level") +) + +var ( + // create the stats we measure + Started = keys.NewInt64("started", "Count of started RPCs.") + ReceivedBytes = keys.NewInt64("received_bytes", "Bytes received.") //, unit.Bytes) + SentBytes = keys.NewInt64("sent_bytes", "Bytes sent.") //, unit.Bytes) + Latency = keys.NewFloat64("latency_ms", "Elapsed time in milliseconds") //, unit.Milliseconds) +) + +const ( + Inbound = "in" + Outbound = "out" +) diff --git a/vendor/golang.org/x/tools/internal/gcimporter/bexport.go b/vendor/golang.org/x/tools/internal/gcimporter/bexport.go deleted file mode 100644 index 30582ed6d3d..00000000000 --- a/vendor/golang.org/x/tools/internal/gcimporter/bexport.go +++ /dev/null @@ -1,852 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Binary package export. -// This file was derived from $GOROOT/src/cmd/compile/internal/gc/bexport.go; -// see that file for specification of the format. - -package gcimporter - -import ( - "bytes" - "encoding/binary" - "fmt" - "go/constant" - "go/token" - "go/types" - "math" - "math/big" - "sort" - "strings" -) - -// If debugFormat is set, each integer and string value is preceded by a marker -// and position information in the encoding. This mechanism permits an importer -// to recognize immediately when it is out of sync. The importer recognizes this -// mode automatically (i.e., it can import export data produced with debugging -// support even if debugFormat is not set at the time of import). This mode will -// lead to massively larger export data (by a factor of 2 to 3) and should only -// be enabled during development and debugging. -// -// NOTE: This flag is the first flag to enable if importing dies because of -// (suspected) format errors, and whenever a change is made to the format. -const debugFormat = false // default: false - -// Current export format version. Increase with each format change. -// -// Note: The latest binary (non-indexed) export format is at version 6. -// This exporter is still at level 4, but it doesn't matter since -// the binary importer can handle older versions just fine. -// -// 6: package height (CL 105038) -- NOT IMPLEMENTED HERE -// 5: improved position encoding efficiency (issue 20080, CL 41619) -- NOT IMPLEMENTED HERE -// 4: type name objects support type aliases, uses aliasTag -// 3: Go1.8 encoding (same as version 2, aliasTag defined but never used) -// 2: removed unused bool in ODCL export (compiler only) -// 1: header format change (more regular), export package for _ struct fields -// 0: Go1.7 encoding -const exportVersion = 4 - -// trackAllTypes enables cycle tracking for all types, not just named -// types. The existing compiler invariants assume that unnamed types -// that are not completely set up are not used, or else there are spurious -// errors. -// If disabled, only named types are tracked, possibly leading to slightly -// less efficient encoding in rare cases. It also prevents the export of -// some corner-case type declarations (but those are not handled correctly -// with with the textual export format either). -// TODO(gri) enable and remove once issues caused by it are fixed -const trackAllTypes = false - -type exporter struct { - fset *token.FileSet - out bytes.Buffer - - // object -> index maps, indexed in order of serialization - strIndex map[string]int - pkgIndex map[*types.Package]int - typIndex map[types.Type]int - - // position encoding - posInfoFormat bool - prevFile string - prevLine int - - // debugging support - written int // bytes written - indent int // for trace -} - -// internalError represents an error generated inside this package. -type internalError string - -func (e internalError) Error() string { return "gcimporter: " + string(e) } - -func internalErrorf(format string, args ...interface{}) error { - return internalError(fmt.Sprintf(format, args...)) -} - -// BExportData returns binary export data for pkg. -// If no file set is provided, position info will be missing. -func BExportData(fset *token.FileSet, pkg *types.Package) (b []byte, err error) { - if !debug { - defer func() { - if e := recover(); e != nil { - if ierr, ok := e.(internalError); ok { - err = ierr - return - } - // Not an internal error; panic again. - panic(e) - } - }() - } - - p := exporter{ - fset: fset, - strIndex: map[string]int{"": 0}, // empty string is mapped to 0 - pkgIndex: make(map[*types.Package]int), - typIndex: make(map[types.Type]int), - posInfoFormat: true, // TODO(gri) might become a flag, eventually - } - - // write version info - // The version string must start with "version %d" where %d is the version - // number. Additional debugging information may follow after a blank; that - // text is ignored by the importer. - p.rawStringln(fmt.Sprintf("version %d", exportVersion)) - var debug string - if debugFormat { - debug = "debug" - } - p.rawStringln(debug) // cannot use p.bool since it's affected by debugFormat; also want to see this clearly - p.bool(trackAllTypes) - p.bool(p.posInfoFormat) - - // --- generic export data --- - - // populate type map with predeclared "known" types - for index, typ := range predeclared() { - p.typIndex[typ] = index - } - if len(p.typIndex) != len(predeclared()) { - return nil, internalError("duplicate entries in type map?") - } - - // write package data - p.pkg(pkg, true) - if trace { - p.tracef("\n") - } - - // write objects - objcount := 0 - scope := pkg.Scope() - for _, name := range scope.Names() { - if !token.IsExported(name) { - continue - } - if trace { - p.tracef("\n") - } - p.obj(scope.Lookup(name)) - objcount++ - } - - // indicate end of list - if trace { - p.tracef("\n") - } - p.tag(endTag) - - // for self-verification only (redundant) - p.int(objcount) - - if trace { - p.tracef("\n") - } - - // --- end of export data --- - - return p.out.Bytes(), nil -} - -func (p *exporter) pkg(pkg *types.Package, emptypath bool) { - if pkg == nil { - panic(internalError("unexpected nil pkg")) - } - - // if we saw the package before, write its index (>= 0) - if i, ok := p.pkgIndex[pkg]; ok { - p.index('P', i) - return - } - - // otherwise, remember the package, write the package tag (< 0) and package data - if trace { - p.tracef("P%d = { ", len(p.pkgIndex)) - defer p.tracef("} ") - } - p.pkgIndex[pkg] = len(p.pkgIndex) - - p.tag(packageTag) - p.string(pkg.Name()) - if emptypath { - p.string("") - } else { - p.string(pkg.Path()) - } -} - -func (p *exporter) obj(obj types.Object) { - switch obj := obj.(type) { - case *types.Const: - p.tag(constTag) - p.pos(obj) - p.qualifiedName(obj) - p.typ(obj.Type()) - p.value(obj.Val()) - - case *types.TypeName: - if obj.IsAlias() { - p.tag(aliasTag) - p.pos(obj) - p.qualifiedName(obj) - } else { - p.tag(typeTag) - } - p.typ(obj.Type()) - - case *types.Var: - p.tag(varTag) - p.pos(obj) - p.qualifiedName(obj) - p.typ(obj.Type()) - - case *types.Func: - p.tag(funcTag) - p.pos(obj) - p.qualifiedName(obj) - sig := obj.Type().(*types.Signature) - p.paramList(sig.Params(), sig.Variadic()) - p.paramList(sig.Results(), false) - - default: - panic(internalErrorf("unexpected object %v (%T)", obj, obj)) - } -} - -func (p *exporter) pos(obj types.Object) { - if !p.posInfoFormat { - return - } - - file, line := p.fileLine(obj) - if file == p.prevFile { - // common case: write line delta - // delta == 0 means different file or no line change - delta := line - p.prevLine - p.int(delta) - if delta == 0 { - p.int(-1) // -1 means no file change - } - } else { - // different file - p.int(0) - // Encode filename as length of common prefix with previous - // filename, followed by (possibly empty) suffix. Filenames - // frequently share path prefixes, so this can save a lot - // of space and make export data size less dependent on file - // path length. The suffix is unlikely to be empty because - // file names tend to end in ".go". - n := commonPrefixLen(p.prevFile, file) - p.int(n) // n >= 0 - p.string(file[n:]) // write suffix only - p.prevFile = file - p.int(line) - } - p.prevLine = line -} - -func (p *exporter) fileLine(obj types.Object) (file string, line int) { - if p.fset != nil { - pos := p.fset.Position(obj.Pos()) - file = pos.Filename - line = pos.Line - } - return -} - -func commonPrefixLen(a, b string) int { - if len(a) > len(b) { - a, b = b, a - } - // len(a) <= len(b) - i := 0 - for i < len(a) && a[i] == b[i] { - i++ - } - return i -} - -func (p *exporter) qualifiedName(obj types.Object) { - p.string(obj.Name()) - p.pkg(obj.Pkg(), false) -} - -func (p *exporter) typ(t types.Type) { - if t == nil { - panic(internalError("nil type")) - } - - // Possible optimization: Anonymous pointer types *T where - // T is a named type are common. We could canonicalize all - // such types *T to a single type PT = *T. This would lead - // to at most one *T entry in typIndex, and all future *T's - // would be encoded as the respective index directly. Would - // save 1 byte (pointerTag) per *T and reduce the typIndex - // size (at the cost of a canonicalization map). We can do - // this later, without encoding format change. - - // if we saw the type before, write its index (>= 0) - if i, ok := p.typIndex[t]; ok { - p.index('T', i) - return - } - - // otherwise, remember the type, write the type tag (< 0) and type data - if trackAllTypes { - if trace { - p.tracef("T%d = {>\n", len(p.typIndex)) - defer p.tracef("<\n} ") - } - p.typIndex[t] = len(p.typIndex) - } - - switch t := t.(type) { - case *types.Named: - if !trackAllTypes { - // if we don't track all types, track named types now - p.typIndex[t] = len(p.typIndex) - } - - p.tag(namedTag) - p.pos(t.Obj()) - p.qualifiedName(t.Obj()) - p.typ(t.Underlying()) - if !types.IsInterface(t) { - p.assocMethods(t) - } - - case *types.Array: - p.tag(arrayTag) - p.int64(t.Len()) - p.typ(t.Elem()) - - case *types.Slice: - p.tag(sliceTag) - p.typ(t.Elem()) - - case *dddSlice: - p.tag(dddTag) - p.typ(t.elem) - - case *types.Struct: - p.tag(structTag) - p.fieldList(t) - - case *types.Pointer: - p.tag(pointerTag) - p.typ(t.Elem()) - - case *types.Signature: - p.tag(signatureTag) - p.paramList(t.Params(), t.Variadic()) - p.paramList(t.Results(), false) - - case *types.Interface: - p.tag(interfaceTag) - p.iface(t) - - case *types.Map: - p.tag(mapTag) - p.typ(t.Key()) - p.typ(t.Elem()) - - case *types.Chan: - p.tag(chanTag) - p.int(int(3 - t.Dir())) // hack - p.typ(t.Elem()) - - default: - panic(internalErrorf("unexpected type %T: %s", t, t)) - } -} - -func (p *exporter) assocMethods(named *types.Named) { - // Sort methods (for determinism). - var methods []*types.Func - for i := 0; i < named.NumMethods(); i++ { - methods = append(methods, named.Method(i)) - } - sort.Sort(methodsByName(methods)) - - p.int(len(methods)) - - if trace && methods != nil { - p.tracef("associated methods {>\n") - } - - for i, m := range methods { - if trace && i > 0 { - p.tracef("\n") - } - - p.pos(m) - name := m.Name() - p.string(name) - if !exported(name) { - p.pkg(m.Pkg(), false) - } - - sig := m.Type().(*types.Signature) - p.paramList(types.NewTuple(sig.Recv()), false) - p.paramList(sig.Params(), sig.Variadic()) - p.paramList(sig.Results(), false) - p.int(0) // dummy value for go:nointerface pragma - ignored by importer - } - - if trace && methods != nil { - p.tracef("<\n} ") - } -} - -type methodsByName []*types.Func - -func (x methodsByName) Len() int { return len(x) } -func (x methodsByName) Swap(i, j int) { x[i], x[j] = x[j], x[i] } -func (x methodsByName) Less(i, j int) bool { return x[i].Name() < x[j].Name() } - -func (p *exporter) fieldList(t *types.Struct) { - if trace && t.NumFields() > 0 { - p.tracef("fields {>\n") - defer p.tracef("<\n} ") - } - - p.int(t.NumFields()) - for i := 0; i < t.NumFields(); i++ { - if trace && i > 0 { - p.tracef("\n") - } - p.field(t.Field(i)) - p.string(t.Tag(i)) - } -} - -func (p *exporter) field(f *types.Var) { - if !f.IsField() { - panic(internalError("field expected")) - } - - p.pos(f) - p.fieldName(f) - p.typ(f.Type()) -} - -func (p *exporter) iface(t *types.Interface) { - // TODO(gri): enable importer to load embedded interfaces, - // then emit Embeddeds and ExplicitMethods separately here. - p.int(0) - - n := t.NumMethods() - if trace && n > 0 { - p.tracef("methods {>\n") - defer p.tracef("<\n} ") - } - p.int(n) - for i := 0; i < n; i++ { - if trace && i > 0 { - p.tracef("\n") - } - p.method(t.Method(i)) - } -} - -func (p *exporter) method(m *types.Func) { - sig := m.Type().(*types.Signature) - if sig.Recv() == nil { - panic(internalError("method expected")) - } - - p.pos(m) - p.string(m.Name()) - if m.Name() != "_" && !token.IsExported(m.Name()) { - p.pkg(m.Pkg(), false) - } - - // interface method; no need to encode receiver. - p.paramList(sig.Params(), sig.Variadic()) - p.paramList(sig.Results(), false) -} - -func (p *exporter) fieldName(f *types.Var) { - name := f.Name() - - if f.Anonymous() { - // anonymous field - we distinguish between 3 cases: - // 1) field name matches base type name and is exported - // 2) field name matches base type name and is not exported - // 3) field name doesn't match base type name (alias name) - bname := basetypeName(f.Type()) - if name == bname { - if token.IsExported(name) { - name = "" // 1) we don't need to know the field name or package - } else { - name = "?" // 2) use unexported name "?" to force package export - } - } else { - // 3) indicate alias and export name as is - // (this requires an extra "@" but this is a rare case) - p.string("@") - } - } - - p.string(name) - if name != "" && !token.IsExported(name) { - p.pkg(f.Pkg(), false) - } -} - -func basetypeName(typ types.Type) string { - switch typ := deref(typ).(type) { - case *types.Basic: - return typ.Name() - case *types.Named: - return typ.Obj().Name() - default: - return "" // unnamed type - } -} - -func (p *exporter) paramList(params *types.Tuple, variadic bool) { - // use negative length to indicate unnamed parameters - // (look at the first parameter only since either all - // names are present or all are absent) - n := params.Len() - if n > 0 && params.At(0).Name() == "" { - n = -n - } - p.int(n) - for i := 0; i < params.Len(); i++ { - q := params.At(i) - t := q.Type() - if variadic && i == params.Len()-1 { - t = &dddSlice{t.(*types.Slice).Elem()} - } - p.typ(t) - if n > 0 { - name := q.Name() - p.string(name) - if name != "_" { - p.pkg(q.Pkg(), false) - } - } - p.string("") // no compiler-specific info - } -} - -func (p *exporter) value(x constant.Value) { - if trace { - p.tracef("= ") - } - - switch x.Kind() { - case constant.Bool: - tag := falseTag - if constant.BoolVal(x) { - tag = trueTag - } - p.tag(tag) - - case constant.Int: - if v, exact := constant.Int64Val(x); exact { - // common case: x fits into an int64 - use compact encoding - p.tag(int64Tag) - p.int64(v) - return - } - // uncommon case: large x - use float encoding - // (powers of 2 will be encoded efficiently with exponent) - p.tag(floatTag) - p.float(constant.ToFloat(x)) - - case constant.Float: - p.tag(floatTag) - p.float(x) - - case constant.Complex: - p.tag(complexTag) - p.float(constant.Real(x)) - p.float(constant.Imag(x)) - - case constant.String: - p.tag(stringTag) - p.string(constant.StringVal(x)) - - case constant.Unknown: - // package contains type errors - p.tag(unknownTag) - - default: - panic(internalErrorf("unexpected value %v (%T)", x, x)) - } -} - -func (p *exporter) float(x constant.Value) { - if x.Kind() != constant.Float { - panic(internalErrorf("unexpected constant %v, want float", x)) - } - // extract sign (there is no -0) - sign := constant.Sign(x) - if sign == 0 { - // x == 0 - p.int(0) - return - } - // x != 0 - - var f big.Float - if v, exact := constant.Float64Val(x); exact { - // float64 - f.SetFloat64(v) - } else if num, denom := constant.Num(x), constant.Denom(x); num.Kind() == constant.Int { - // TODO(gri): add big.Rat accessor to constant.Value. - r := valueToRat(num) - f.SetRat(r.Quo(r, valueToRat(denom))) - } else { - // Value too large to represent as a fraction => inaccessible. - // TODO(gri): add big.Float accessor to constant.Value. - f.SetFloat64(math.MaxFloat64) // FIXME - } - - // extract exponent such that 0.5 <= m < 1.0 - var m big.Float - exp := f.MantExp(&m) - - // extract mantissa as *big.Int - // - set exponent large enough so mant satisfies mant.IsInt() - // - get *big.Int from mant - m.SetMantExp(&m, int(m.MinPrec())) - mant, acc := m.Int(nil) - if acc != big.Exact { - panic(internalError("internal error")) - } - - p.int(sign) - p.int(exp) - p.string(string(mant.Bytes())) -} - -func valueToRat(x constant.Value) *big.Rat { - // Convert little-endian to big-endian. - // I can't believe this is necessary. - bytes := constant.Bytes(x) - for i := 0; i < len(bytes)/2; i++ { - bytes[i], bytes[len(bytes)-1-i] = bytes[len(bytes)-1-i], bytes[i] - } - return new(big.Rat).SetInt(new(big.Int).SetBytes(bytes)) -} - -func (p *exporter) bool(b bool) bool { - if trace { - p.tracef("[") - defer p.tracef("= %v] ", b) - } - - x := 0 - if b { - x = 1 - } - p.int(x) - return b -} - -// ---------------------------------------------------------------------------- -// Low-level encoders - -func (p *exporter) index(marker byte, index int) { - if index < 0 { - panic(internalError("invalid index < 0")) - } - if debugFormat { - p.marker('t') - } - if trace { - p.tracef("%c%d ", marker, index) - } - p.rawInt64(int64(index)) -} - -func (p *exporter) tag(tag int) { - if tag >= 0 { - panic(internalError("invalid tag >= 0")) - } - if debugFormat { - p.marker('t') - } - if trace { - p.tracef("%s ", tagString[-tag]) - } - p.rawInt64(int64(tag)) -} - -func (p *exporter) int(x int) { - p.int64(int64(x)) -} - -func (p *exporter) int64(x int64) { - if debugFormat { - p.marker('i') - } - if trace { - p.tracef("%d ", x) - } - p.rawInt64(x) -} - -func (p *exporter) string(s string) { - if debugFormat { - p.marker('s') - } - if trace { - p.tracef("%q ", s) - } - // if we saw the string before, write its index (>= 0) - // (the empty string is mapped to 0) - if i, ok := p.strIndex[s]; ok { - p.rawInt64(int64(i)) - return - } - // otherwise, remember string and write its negative length and bytes - p.strIndex[s] = len(p.strIndex) - p.rawInt64(-int64(len(s))) - for i := 0; i < len(s); i++ { - p.rawByte(s[i]) - } -} - -// marker emits a marker byte and position information which makes -// it easy for a reader to detect if it is "out of sync". Used for -// debugFormat format only. -func (p *exporter) marker(m byte) { - p.rawByte(m) - // Enable this for help tracking down the location - // of an incorrect marker when running in debugFormat. - if false && trace { - p.tracef("#%d ", p.written) - } - p.rawInt64(int64(p.written)) -} - -// rawInt64 should only be used by low-level encoders. -func (p *exporter) rawInt64(x int64) { - var tmp [binary.MaxVarintLen64]byte - n := binary.PutVarint(tmp[:], x) - for i := 0; i < n; i++ { - p.rawByte(tmp[i]) - } -} - -// rawStringln should only be used to emit the initial version string. -func (p *exporter) rawStringln(s string) { - for i := 0; i < len(s); i++ { - p.rawByte(s[i]) - } - p.rawByte('\n') -} - -// rawByte is the bottleneck interface to write to p.out. -// rawByte escapes b as follows (any encoding does that -// hides '$'): -// -// '$' => '|' 'S' -// '|' => '|' '|' -// -// Necessary so other tools can find the end of the -// export data by searching for "$$". -// rawByte should only be used by low-level encoders. -func (p *exporter) rawByte(b byte) { - switch b { - case '$': - // write '$' as '|' 'S' - b = 'S' - fallthrough - case '|': - // write '|' as '|' '|' - p.out.WriteByte('|') - p.written++ - } - p.out.WriteByte(b) - p.written++ -} - -// tracef is like fmt.Printf but it rewrites the format string -// to take care of indentation. -func (p *exporter) tracef(format string, args ...interface{}) { - if strings.ContainsAny(format, "<>\n") { - var buf bytes.Buffer - for i := 0; i < len(format); i++ { - // no need to deal with runes - ch := format[i] - switch ch { - case '>': - p.indent++ - continue - case '<': - p.indent-- - continue - } - buf.WriteByte(ch) - if ch == '\n' { - for j := p.indent; j > 0; j-- { - buf.WriteString(". ") - } - } - } - format = buf.String() - } - fmt.Printf(format, args...) -} - -// Debugging support. -// (tagString is only used when tracing is enabled) -var tagString = [...]string{ - // Packages - -packageTag: "package", - - // Types - -namedTag: "named type", - -arrayTag: "array", - -sliceTag: "slice", - -dddTag: "ddd", - -structTag: "struct", - -pointerTag: "pointer", - -signatureTag: "signature", - -interfaceTag: "interface", - -mapTag: "map", - -chanTag: "chan", - - // Values - -falseTag: "false", - -trueTag: "true", - -int64Tag: "int64", - -floatTag: "float", - -fractionTag: "fraction", - -complexTag: "complex", - -stringTag: "string", - -unknownTag: "unknown", - - // Type aliases - -aliasTag: "alias", -} diff --git a/vendor/golang.org/x/tools/internal/gcimporter/bimport.go b/vendor/golang.org/x/tools/internal/gcimporter/bimport.go index b85de014700..d98b0db2a9a 100644 --- a/vendor/golang.org/x/tools/internal/gcimporter/bimport.go +++ b/vendor/golang.org/x/tools/internal/gcimporter/bimport.go @@ -2,340 +2,24 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// This file is a copy of $GOROOT/src/go/internal/gcimporter/bimport.go. +// This file contains the remaining vestiges of +// $GOROOT/src/go/internal/gcimporter/bimport.go. package gcimporter import ( - "encoding/binary" "fmt" - "go/constant" "go/token" "go/types" - "sort" - "strconv" - "strings" "sync" - "unicode" - "unicode/utf8" ) -type importer struct { - imports map[string]*types.Package - data []byte - importpath string - buf []byte // for reading strings - version int // export format version - - // object lists - strList []string // in order of appearance - pathList []string // in order of appearance - pkgList []*types.Package // in order of appearance - typList []types.Type // in order of appearance - interfaceList []*types.Interface // for delayed completion only - trackAllTypes bool - - // position encoding - posInfoFormat bool - prevFile string - prevLine int - fake fakeFileSet - - // debugging support - debugFormat bool - read int // bytes read -} - -// BImportData imports a package from the serialized package data -// and returns the number of bytes consumed and a reference to the package. -// If the export data version is not recognized or the format is otherwise -// compromised, an error is returned. -func BImportData(fset *token.FileSet, imports map[string]*types.Package, data []byte, path string) (_ int, pkg *types.Package, err error) { - // catch panics and return them as errors - const currentVersion = 6 - version := -1 // unknown version - defer func() { - if e := recover(); e != nil { - // Return a (possibly nil or incomplete) package unchanged (see #16088). - if version > currentVersion { - err = fmt.Errorf("cannot import %q (%v), export data is newer version - update tool", path, e) - } else { - err = fmt.Errorf("cannot import %q (%v), possibly version skew - reinstall package", path, e) - } - } - }() - - p := importer{ - imports: imports, - data: data, - importpath: path, - version: version, - strList: []string{""}, // empty string is mapped to 0 - pathList: []string{""}, // empty string is mapped to 0 - fake: fakeFileSet{ - fset: fset, - files: make(map[string]*fileInfo), - }, - } - defer p.fake.setLines() // set lines for files in fset - - // read version info - var versionstr string - if b := p.rawByte(); b == 'c' || b == 'd' { - // Go1.7 encoding; first byte encodes low-level - // encoding format (compact vs debug). - // For backward-compatibility only (avoid problems with - // old installed packages). Newly compiled packages use - // the extensible format string. - // TODO(gri) Remove this support eventually; after Go1.8. - if b == 'd' { - p.debugFormat = true - } - p.trackAllTypes = p.rawByte() == 'a' - p.posInfoFormat = p.int() != 0 - versionstr = p.string() - if versionstr == "v1" { - version = 0 - } - } else { - // Go1.8 extensible encoding - // read version string and extract version number (ignore anything after the version number) - versionstr = p.rawStringln(b) - if s := strings.SplitN(versionstr, " ", 3); len(s) >= 2 && s[0] == "version" { - if v, err := strconv.Atoi(s[1]); err == nil && v > 0 { - version = v - } - } - } - p.version = version - - // read version specific flags - extend as necessary - switch p.version { - // case currentVersion: - // ... - // fallthrough - case currentVersion, 5, 4, 3, 2, 1: - p.debugFormat = p.rawStringln(p.rawByte()) == "debug" - p.trackAllTypes = p.int() != 0 - p.posInfoFormat = p.int() != 0 - case 0: - // Go1.7 encoding format - nothing to do here - default: - errorf("unknown bexport format version %d (%q)", p.version, versionstr) - } - - // --- generic export data --- - - // populate typList with predeclared "known" types - p.typList = append(p.typList, predeclared()...) - - // read package data - pkg = p.pkg() - - // read objects of phase 1 only (see cmd/compile/internal/gc/bexport.go) - objcount := 0 - for { - tag := p.tagOrIndex() - if tag == endTag { - break - } - p.obj(tag) - objcount++ - } - - // self-verification - if count := p.int(); count != objcount { - errorf("got %d objects; want %d", objcount, count) - } - - // ignore compiler-specific import data - - // complete interfaces - // TODO(gri) re-investigate if we still need to do this in a delayed fashion - for _, typ := range p.interfaceList { - typ.Complete() - } - - // record all referenced packages as imports - list := append(([]*types.Package)(nil), p.pkgList[1:]...) - sort.Sort(byPath(list)) - pkg.SetImports(list) - - // package was imported completely and without errors - pkg.MarkComplete() - - return p.read, pkg, nil -} - func errorf(format string, args ...interface{}) { panic(fmt.Sprintf(format, args...)) } -func (p *importer) pkg() *types.Package { - // if the package was seen before, i is its index (>= 0) - i := p.tagOrIndex() - if i >= 0 { - return p.pkgList[i] - } - - // otherwise, i is the package tag (< 0) - if i != packageTag { - errorf("unexpected package tag %d version %d", i, p.version) - } - - // read package data - name := p.string() - var path string - if p.version >= 5 { - path = p.path() - } else { - path = p.string() - } - if p.version >= 6 { - p.int() // package height; unused by go/types - } - - // we should never see an empty package name - if name == "" { - errorf("empty package name in import") - } - - // an empty path denotes the package we are currently importing; - // it must be the first package we see - if (path == "") != (len(p.pkgList) == 0) { - errorf("package path %q for pkg index %d", path, len(p.pkgList)) - } - - // if the package was imported before, use that one; otherwise create a new one - if path == "" { - path = p.importpath - } - pkg := p.imports[path] - if pkg == nil { - pkg = types.NewPackage(path, name) - p.imports[path] = pkg - } else if pkg.Name() != name { - errorf("conflicting names %s and %s for package %q", pkg.Name(), name, path) - } - p.pkgList = append(p.pkgList, pkg) - - return pkg -} - -// objTag returns the tag value for each object kind. -func objTag(obj types.Object) int { - switch obj.(type) { - case *types.Const: - return constTag - case *types.TypeName: - return typeTag - case *types.Var: - return varTag - case *types.Func: - return funcTag - default: - errorf("unexpected object: %v (%T)", obj, obj) // panics - panic("unreachable") - } -} - -func sameObj(a, b types.Object) bool { - // Because unnamed types are not canonicalized, we cannot simply compare types for - // (pointer) identity. - // Ideally we'd check equality of constant values as well, but this is good enough. - return objTag(a) == objTag(b) && types.Identical(a.Type(), b.Type()) -} - -func (p *importer) declare(obj types.Object) { - pkg := obj.Pkg() - if alt := pkg.Scope().Insert(obj); alt != nil { - // This can only trigger if we import a (non-type) object a second time. - // Excluding type aliases, this cannot happen because 1) we only import a package - // once; and b) we ignore compiler-specific export data which may contain - // functions whose inlined function bodies refer to other functions that - // were already imported. - // However, type aliases require reexporting the original type, so we need - // to allow it (see also the comment in cmd/compile/internal/gc/bimport.go, - // method importer.obj, switch case importing functions). - // TODO(gri) review/update this comment once the gc compiler handles type aliases. - if !sameObj(obj, alt) { - errorf("inconsistent import:\n\t%v\npreviously imported as:\n\t%v\n", obj, alt) - } - } -} - -func (p *importer) obj(tag int) { - switch tag { - case constTag: - pos := p.pos() - pkg, name := p.qualifiedName() - typ := p.typ(nil, nil) - val := p.value() - p.declare(types.NewConst(pos, pkg, name, typ, val)) - - case aliasTag: - // TODO(gri) verify type alias hookup is correct - pos := p.pos() - pkg, name := p.qualifiedName() - typ := p.typ(nil, nil) - p.declare(types.NewTypeName(pos, pkg, name, typ)) - - case typeTag: - p.typ(nil, nil) - - case varTag: - pos := p.pos() - pkg, name := p.qualifiedName() - typ := p.typ(nil, nil) - p.declare(types.NewVar(pos, pkg, name, typ)) - - case funcTag: - pos := p.pos() - pkg, name := p.qualifiedName() - params, isddd := p.paramList() - result, _ := p.paramList() - sig := types.NewSignature(nil, params, result, isddd) - p.declare(types.NewFunc(pos, pkg, name, sig)) - - default: - errorf("unexpected object tag %d", tag) - } -} - const deltaNewFile = -64 // see cmd/compile/internal/gc/bexport.go -func (p *importer) pos() token.Pos { - if !p.posInfoFormat { - return token.NoPos - } - - file := p.prevFile - line := p.prevLine - delta := p.int() - line += delta - if p.version >= 5 { - if delta == deltaNewFile { - if n := p.int(); n >= 0 { - // file changed - file = p.path() - line = n - } - } - } else { - if delta == 0 { - if n := p.int(); n >= 0 { - // file changed - file = p.prevFile[:n] + p.string() - line = p.int() - } - } - } - p.prevFile = file - p.prevLine = line - - return p.fake.pos(file, line, 0) -} - // Synthesize a token.Pos type fakeFileSet struct { fset *token.FileSet @@ -389,205 +73,6 @@ var ( fakeLinesOnce sync.Once ) -func (p *importer) qualifiedName() (pkg *types.Package, name string) { - name = p.string() - pkg = p.pkg() - return -} - -func (p *importer) record(t types.Type) { - p.typList = append(p.typList, t) -} - -// A dddSlice is a types.Type representing ...T parameters. -// It only appears for parameter types and does not escape -// the importer. -type dddSlice struct { - elem types.Type -} - -func (t *dddSlice) Underlying() types.Type { return t } -func (t *dddSlice) String() string { return "..." + t.elem.String() } - -// parent is the package which declared the type; parent == nil means -// the package currently imported. The parent package is needed for -// exported struct fields and interface methods which don't contain -// explicit package information in the export data. -// -// A non-nil tname is used as the "owner" of the result type; i.e., -// the result type is the underlying type of tname. tname is used -// to give interface methods a named receiver type where possible. -func (p *importer) typ(parent *types.Package, tname *types.Named) types.Type { - // if the type was seen before, i is its index (>= 0) - i := p.tagOrIndex() - if i >= 0 { - return p.typList[i] - } - - // otherwise, i is the type tag (< 0) - switch i { - case namedTag: - // read type object - pos := p.pos() - parent, name := p.qualifiedName() - scope := parent.Scope() - obj := scope.Lookup(name) - - // if the object doesn't exist yet, create and insert it - if obj == nil { - obj = types.NewTypeName(pos, parent, name, nil) - scope.Insert(obj) - } - - if _, ok := obj.(*types.TypeName); !ok { - errorf("pkg = %s, name = %s => %s", parent, name, obj) - } - - // associate new named type with obj if it doesn't exist yet - t0 := types.NewNamed(obj.(*types.TypeName), nil, nil) - - // but record the existing type, if any - tname := obj.Type().(*types.Named) // tname is either t0 or the existing type - p.record(tname) - - // read underlying type - t0.SetUnderlying(p.typ(parent, t0)) - - // interfaces don't have associated methods - if types.IsInterface(t0) { - return tname - } - - // read associated methods - for i := p.int(); i > 0; i-- { - // TODO(gri) replace this with something closer to fieldName - pos := p.pos() - name := p.string() - if !exported(name) { - p.pkg() - } - - recv, _ := p.paramList() // TODO(gri) do we need a full param list for the receiver? - params, isddd := p.paramList() - result, _ := p.paramList() - p.int() // go:nointerface pragma - discarded - - sig := types.NewSignature(recv.At(0), params, result, isddd) - t0.AddMethod(types.NewFunc(pos, parent, name, sig)) - } - - return tname - - case arrayTag: - t := new(types.Array) - if p.trackAllTypes { - p.record(t) - } - - n := p.int64() - *t = *types.NewArray(p.typ(parent, nil), n) - return t - - case sliceTag: - t := new(types.Slice) - if p.trackAllTypes { - p.record(t) - } - - *t = *types.NewSlice(p.typ(parent, nil)) - return t - - case dddTag: - t := new(dddSlice) - if p.trackAllTypes { - p.record(t) - } - - t.elem = p.typ(parent, nil) - return t - - case structTag: - t := new(types.Struct) - if p.trackAllTypes { - p.record(t) - } - - *t = *types.NewStruct(p.fieldList(parent)) - return t - - case pointerTag: - t := new(types.Pointer) - if p.trackAllTypes { - p.record(t) - } - - *t = *types.NewPointer(p.typ(parent, nil)) - return t - - case signatureTag: - t := new(types.Signature) - if p.trackAllTypes { - p.record(t) - } - - params, isddd := p.paramList() - result, _ := p.paramList() - *t = *types.NewSignature(nil, params, result, isddd) - return t - - case interfaceTag: - // Create a dummy entry in the type list. This is safe because we - // cannot expect the interface type to appear in a cycle, as any - // such cycle must contain a named type which would have been - // first defined earlier. - // TODO(gri) Is this still true now that we have type aliases? - // See issue #23225. - n := len(p.typList) - if p.trackAllTypes { - p.record(nil) - } - - var embeddeds []types.Type - for n := p.int(); n > 0; n-- { - p.pos() - embeddeds = append(embeddeds, p.typ(parent, nil)) - } - - t := newInterface(p.methodList(parent, tname), embeddeds) - p.interfaceList = append(p.interfaceList, t) - if p.trackAllTypes { - p.typList[n] = t - } - return t - - case mapTag: - t := new(types.Map) - if p.trackAllTypes { - p.record(t) - } - - key := p.typ(parent, nil) - val := p.typ(parent, nil) - *t = *types.NewMap(key, val) - return t - - case chanTag: - t := new(types.Chan) - if p.trackAllTypes { - p.record(t) - } - - dir := chanDir(p.int()) - val := p.typ(parent, nil) - *t = *types.NewChan(dir, val) - return t - - default: - errorf("unexpected type tag %d", i) // panics - panic("unreachable") - } -} - func chanDir(d int) types.ChanDir { // tag values must match the constants in cmd/compile/internal/gc/go.go switch d { @@ -603,394 +88,6 @@ func chanDir(d int) types.ChanDir { } } -func (p *importer) fieldList(parent *types.Package) (fields []*types.Var, tags []string) { - if n := p.int(); n > 0 { - fields = make([]*types.Var, n) - tags = make([]string, n) - for i := range fields { - fields[i], tags[i] = p.field(parent) - } - } - return -} - -func (p *importer) field(parent *types.Package) (*types.Var, string) { - pos := p.pos() - pkg, name, alias := p.fieldName(parent) - typ := p.typ(parent, nil) - tag := p.string() - - anonymous := false - if name == "" { - // anonymous field - typ must be T or *T and T must be a type name - switch typ := deref(typ).(type) { - case *types.Basic: // basic types are named types - pkg = nil // // objects defined in Universe scope have no package - name = typ.Name() - case *types.Named: - name = typ.Obj().Name() - default: - errorf("named base type expected") - } - anonymous = true - } else if alias { - // anonymous field: we have an explicit name because it's an alias - anonymous = true - } - - return types.NewField(pos, pkg, name, typ, anonymous), tag -} - -func (p *importer) methodList(parent *types.Package, baseType *types.Named) (methods []*types.Func) { - if n := p.int(); n > 0 { - methods = make([]*types.Func, n) - for i := range methods { - methods[i] = p.method(parent, baseType) - } - } - return -} - -func (p *importer) method(parent *types.Package, baseType *types.Named) *types.Func { - pos := p.pos() - pkg, name, _ := p.fieldName(parent) - // If we don't have a baseType, use a nil receiver. - // A receiver using the actual interface type (which - // we don't know yet) will be filled in when we call - // types.Interface.Complete. - var recv *types.Var - if baseType != nil { - recv = types.NewVar(token.NoPos, parent, "", baseType) - } - params, isddd := p.paramList() - result, _ := p.paramList() - sig := types.NewSignature(recv, params, result, isddd) - return types.NewFunc(pos, pkg, name, sig) -} - -func (p *importer) fieldName(parent *types.Package) (pkg *types.Package, name string, alias bool) { - name = p.string() - pkg = parent - if pkg == nil { - // use the imported package instead - pkg = p.pkgList[0] - } - if p.version == 0 && name == "_" { - // version 0 didn't export a package for _ fields - return - } - switch name { - case "": - // 1) field name matches base type name and is exported: nothing to do - case "?": - // 2) field name matches base type name and is not exported: need package - name = "" - pkg = p.pkg() - case "@": - // 3) field name doesn't match type name (alias) - name = p.string() - alias = true - fallthrough - default: - if !exported(name) { - pkg = p.pkg() - } - } - return -} - -func (p *importer) paramList() (*types.Tuple, bool) { - n := p.int() - if n == 0 { - return nil, false - } - // negative length indicates unnamed parameters - named := true - if n < 0 { - n = -n - named = false - } - // n > 0 - params := make([]*types.Var, n) - isddd := false - for i := range params { - params[i], isddd = p.param(named) - } - return types.NewTuple(params...), isddd -} - -func (p *importer) param(named bool) (*types.Var, bool) { - t := p.typ(nil, nil) - td, isddd := t.(*dddSlice) - if isddd { - t = types.NewSlice(td.elem) - } - - var pkg *types.Package - var name string - if named { - name = p.string() - if name == "" { - errorf("expected named parameter") - } - if name != "_" { - pkg = p.pkg() - } - if i := strings.Index(name, "·"); i > 0 { - name = name[:i] // cut off gc-specific parameter numbering - } - } - - // read and discard compiler-specific info - p.string() - - return types.NewVar(token.NoPos, pkg, name, t), isddd -} - -func exported(name string) bool { - ch, _ := utf8.DecodeRuneInString(name) - return unicode.IsUpper(ch) -} - -func (p *importer) value() constant.Value { - switch tag := p.tagOrIndex(); tag { - case falseTag: - return constant.MakeBool(false) - case trueTag: - return constant.MakeBool(true) - case int64Tag: - return constant.MakeInt64(p.int64()) - case floatTag: - return p.float() - case complexTag: - re := p.float() - im := p.float() - return constant.BinaryOp(re, token.ADD, constant.MakeImag(im)) - case stringTag: - return constant.MakeString(p.string()) - case unknownTag: - return constant.MakeUnknown() - default: - errorf("unexpected value tag %d", tag) // panics - panic("unreachable") - } -} - -func (p *importer) float() constant.Value { - sign := p.int() - if sign == 0 { - return constant.MakeInt64(0) - } - - exp := p.int() - mant := []byte(p.string()) // big endian - - // remove leading 0's if any - for len(mant) > 0 && mant[0] == 0 { - mant = mant[1:] - } - - // convert to little endian - // TODO(gri) go/constant should have a more direct conversion function - // (e.g., once it supports a big.Float based implementation) - for i, j := 0, len(mant)-1; i < j; i, j = i+1, j-1 { - mant[i], mant[j] = mant[j], mant[i] - } - - // adjust exponent (constant.MakeFromBytes creates an integer value, - // but mant represents the mantissa bits such that 0.5 <= mant < 1.0) - exp -= len(mant) << 3 - if len(mant) > 0 { - for msd := mant[len(mant)-1]; msd&0x80 == 0; msd <<= 1 { - exp++ - } - } - - x := constant.MakeFromBytes(mant) - switch { - case exp < 0: - d := constant.Shift(constant.MakeInt64(1), token.SHL, uint(-exp)) - x = constant.BinaryOp(x, token.QUO, d) - case exp > 0: - x = constant.Shift(x, token.SHL, uint(exp)) - } - - if sign < 0 { - x = constant.UnaryOp(token.SUB, x, 0) - } - return x -} - -// ---------------------------------------------------------------------------- -// Low-level decoders - -func (p *importer) tagOrIndex() int { - if p.debugFormat { - p.marker('t') - } - - return int(p.rawInt64()) -} - -func (p *importer) int() int { - x := p.int64() - if int64(int(x)) != x { - errorf("exported integer too large") - } - return int(x) -} - -func (p *importer) int64() int64 { - if p.debugFormat { - p.marker('i') - } - - return p.rawInt64() -} - -func (p *importer) path() string { - if p.debugFormat { - p.marker('p') - } - // if the path was seen before, i is its index (>= 0) - // (the empty string is at index 0) - i := p.rawInt64() - if i >= 0 { - return p.pathList[i] - } - // otherwise, i is the negative path length (< 0) - a := make([]string, -i) - for n := range a { - a[n] = p.string() - } - s := strings.Join(a, "/") - p.pathList = append(p.pathList, s) - return s -} - -func (p *importer) string() string { - if p.debugFormat { - p.marker('s') - } - // if the string was seen before, i is its index (>= 0) - // (the empty string is at index 0) - i := p.rawInt64() - if i >= 0 { - return p.strList[i] - } - // otherwise, i is the negative string length (< 0) - if n := int(-i); n <= cap(p.buf) { - p.buf = p.buf[:n] - } else { - p.buf = make([]byte, n) - } - for i := range p.buf { - p.buf[i] = p.rawByte() - } - s := string(p.buf) - p.strList = append(p.strList, s) - return s -} - -func (p *importer) marker(want byte) { - if got := p.rawByte(); got != want { - errorf("incorrect marker: got %c; want %c (pos = %d)", got, want, p.read) - } - - pos := p.read - if n := int(p.rawInt64()); n != pos { - errorf("incorrect position: got %d; want %d", n, pos) - } -} - -// rawInt64 should only be used by low-level decoders. -func (p *importer) rawInt64() int64 { - i, err := binary.ReadVarint(p) - if err != nil { - errorf("read error: %v", err) - } - return i -} - -// rawStringln should only be used to read the initial version string. -func (p *importer) rawStringln(b byte) string { - p.buf = p.buf[:0] - for b != '\n' { - p.buf = append(p.buf, b) - b = p.rawByte() - } - return string(p.buf) -} - -// needed for binary.ReadVarint in rawInt64 -func (p *importer) ReadByte() (byte, error) { - return p.rawByte(), nil -} - -// byte is the bottleneck interface for reading p.data. -// It unescapes '|' 'S' to '$' and '|' '|' to '|'. -// rawByte should only be used by low-level decoders. -func (p *importer) rawByte() byte { - b := p.data[0] - r := 1 - if b == '|' { - b = p.data[1] - r = 2 - switch b { - case 'S': - b = '$' - case '|': - // nothing to do - default: - errorf("unexpected escape sequence in export data") - } - } - p.data = p.data[r:] - p.read += r - return b - -} - -// ---------------------------------------------------------------------------- -// Export format - -// Tags. Must be < 0. -const ( - // Objects - packageTag = -(iota + 1) - constTag - typeTag - varTag - funcTag - endTag - - // Types - namedTag - arrayTag - sliceTag - dddTag - structTag - pointerTag - signatureTag - interfaceTag - mapTag - chanTag - - // Values - falseTag - trueTag - int64Tag - floatTag - fractionTag // not used by gc - complexTag - stringTag - nilTag // only used by gc (appears in exported inlined function bodies) - unknownTag // not used by gc (only appears in packages with errors) - - // Type aliases - aliasTag -) - var predeclOnce sync.Once var predecl []types.Type // initialized lazily diff --git a/vendor/golang.org/x/tools/internal/gcimporter/gcimporter.go b/vendor/golang.org/x/tools/internal/gcimporter/gcimporter.go index a973dece936..b1223713b94 100644 --- a/vendor/golang.org/x/tools/internal/gcimporter/gcimporter.go +++ b/vendor/golang.org/x/tools/internal/gcimporter/gcimporter.go @@ -230,20 +230,17 @@ func Import(packages map[string]*types.Package, path, srcDir string, lookup func // Or, define a new standard go/types/gcexportdata package. fset := token.NewFileSet() - // The indexed export format starts with an 'i'; the older - // binary export format starts with a 'c', 'd', or 'v' - // (from "version"). Select appropriate importer. + // Select appropriate importer. if len(data) > 0 { switch data[0] { - case 'i': - _, pkg, err := IImportData(fset, packages, data[1:], id) - return pkg, err + case 'v', 'c', 'd': // binary, till go1.10 + return nil, fmt.Errorf("binary (%c) import format is no longer supported", data[0]) - case 'v', 'c', 'd': - _, pkg, err := BImportData(fset, packages, data, id) + case 'i': // indexed, till go1.19 + _, pkg, err := IImportData(fset, packages, data[1:], id) return pkg, err - case 'u': + case 'u': // unified, from go1.20 _, pkg, err := UImportData(fset, packages, data[1:size], id) return pkg, err diff --git a/vendor/golang.org/x/tools/internal/gcimporter/iexport.go b/vendor/golang.org/x/tools/internal/gcimporter/iexport.go index a0dc0b5e27d..9930d8c36a7 100644 --- a/vendor/golang.org/x/tools/internal/gcimporter/iexport.go +++ b/vendor/golang.org/x/tools/internal/gcimporter/iexport.go @@ -969,6 +969,16 @@ func constantToFloat(x constant.Value) *big.Float { return &f } +func valueToRat(x constant.Value) *big.Rat { + // Convert little-endian to big-endian. + // I can't believe this is necessary. + bytes := constant.Bytes(x) + for i := 0; i < len(bytes)/2; i++ { + bytes[i], bytes[len(bytes)-1-i] = bytes[len(bytes)-1-i], bytes[i] + } + return new(big.Rat).SetInt(new(big.Int).SetBytes(bytes)) +} + // mpint exports a multi-precision integer. // // For unsigned types, small values are written out as a single @@ -1178,3 +1188,12 @@ func (q *objQueue) popHead() types.Object { q.head++ return obj } + +// internalError represents an error generated inside this package. +type internalError string + +func (e internalError) Error() string { return "gcimporter: " + string(e) } + +func internalErrorf(format string, args ...interface{}) error { + return internalError(fmt.Sprintf(format, args...)) +} diff --git a/vendor/golang.org/x/tools/internal/gcimporter/iimport.go b/vendor/golang.org/x/tools/internal/gcimporter/iimport.go index be6dace1534..94a5eba333f 100644 --- a/vendor/golang.org/x/tools/internal/gcimporter/iimport.go +++ b/vendor/golang.org/x/tools/internal/gcimporter/iimport.go @@ -131,7 +131,7 @@ func iimportCommon(fset *token.FileSet, getPackage GetPackageFunc, data []byte, } else if version > currentVersion { err = fmt.Errorf("cannot import %q (%v), export data is newer version - update tool", path, e) } else { - err = fmt.Errorf("cannot import %q (%v), possibly version skew - reinstall package", path, e) + err = fmt.Errorf("internal error while importing %q (%v); please report an issue", path, e) } } }() @@ -140,11 +140,8 @@ func iimportCommon(fset *token.FileSet, getPackage GetPackageFunc, data []byte, r := &intReader{bytes.NewReader(data), path} if bundle { - bundleVersion := r.uint64() - switch bundleVersion { - case bundleVersion: - default: - errorf("unknown bundle format version %d", bundleVersion) + if v := r.uint64(); v != bundleVersion { + errorf("unknown bundle format version %d", v) } } diff --git a/vendor/golang.org/x/tools/internal/gcimporter/ureader_yes.go b/vendor/golang.org/x/tools/internal/gcimporter/ureader_yes.go index 34fc783f82b..b977435f626 100644 --- a/vendor/golang.org/x/tools/internal/gcimporter/ureader_yes.go +++ b/vendor/golang.org/x/tools/internal/gcimporter/ureader_yes.go @@ -10,6 +10,7 @@ package gcimporter import ( + "fmt" "go/token" "go/types" "sort" @@ -63,6 +64,14 @@ type typeInfo struct { } func UImportData(fset *token.FileSet, imports map[string]*types.Package, data []byte, path string) (_ int, pkg *types.Package, err error) { + if !debug { + defer func() { + if x := recover(); x != nil { + err = fmt.Errorf("internal error in importing %q (%v); please report an issue", path, x) + } + }() + } + s := string(data) s = s[:strings.LastIndex(s, "\n$$\n")] input := pkgbits.NewPkgDecoder(path, s) diff --git a/vendor/golang.org/x/tools/internal/gocommand/invoke.go b/vendor/golang.org/x/tools/internal/gocommand/invoke.go index d50551693f3..8d9fc98d8f5 100644 --- a/vendor/golang.org/x/tools/internal/gocommand/invoke.go +++ b/vendor/golang.org/x/tools/internal/gocommand/invoke.go @@ -8,10 +8,12 @@ package gocommand import ( "bytes" "context" + "errors" "fmt" "io" "log" "os" + "reflect" "regexp" "runtime" "strconv" @@ -22,6 +24,9 @@ import ( exec "golang.org/x/sys/execabs" "golang.org/x/tools/internal/event" + "golang.org/x/tools/internal/event/keys" + "golang.org/x/tools/internal/event/label" + "golang.org/x/tools/internal/event/tag" ) // An Runner will run go command invocations and serialize @@ -51,9 +56,19 @@ func (runner *Runner) initialize() { // 1.14: go: updating go.mod: existing contents have changed since last read var modConcurrencyError = regexp.MustCompile(`go:.*go.mod.*contents have changed`) +// verb is an event label for the go command verb. +var verb = keys.NewString("verb", "go command verb") + +func invLabels(inv Invocation) []label.Label { + return []label.Label{verb.Of(inv.Verb), tag.Directory.Of(inv.WorkingDir)} +} + // Run is a convenience wrapper around RunRaw. // It returns only stdout and a "friendly" error. func (runner *Runner) Run(ctx context.Context, inv Invocation) (*bytes.Buffer, error) { + ctx, done := event.Start(ctx, "gocommand.Runner.Run", invLabels(inv)...) + defer done() + stdout, _, friendly, _ := runner.RunRaw(ctx, inv) return stdout, friendly } @@ -61,6 +76,9 @@ func (runner *Runner) Run(ctx context.Context, inv Invocation) (*bytes.Buffer, e // RunPiped runs the invocation serially, always waiting for any concurrent // invocations to complete first. func (runner *Runner) RunPiped(ctx context.Context, inv Invocation, stdout, stderr io.Writer) error { + ctx, done := event.Start(ctx, "gocommand.Runner.RunPiped", invLabels(inv)...) + defer done() + _, err := runner.runPiped(ctx, inv, stdout, stderr) return err } @@ -68,6 +86,8 @@ func (runner *Runner) RunPiped(ctx context.Context, inv Invocation, stdout, stde // RunRaw runs the invocation, serializing requests only if they fight over // go.mod changes. func (runner *Runner) RunRaw(ctx context.Context, inv Invocation) (*bytes.Buffer, *bytes.Buffer, error, error) { + ctx, done := event.Start(ctx, "gocommand.Runner.RunRaw", invLabels(inv)...) + defer done() // Make sure the runner is always initialized. runner.initialize() @@ -215,6 +235,18 @@ func (i *Invocation) run(ctx context.Context, stdout, stderr io.Writer) error { cmd := exec.Command("go", goArgs...) cmd.Stdout = stdout cmd.Stderr = stderr + + // cmd.WaitDelay was added only in go1.20 (see #50436). + if waitDelay := reflect.ValueOf(cmd).Elem().FieldByName("WaitDelay"); waitDelay.IsValid() { + // https://go.dev/issue/59541: don't wait forever copying stderr + // after the command has exited. + // After CL 484741 we copy stdout manually, so we we'll stop reading that as + // soon as ctx is done. However, we also don't want to wait around forever + // for stderr. Give a much-longer-than-reasonable delay and then assume that + // something has wedged in the kernel or runtime. + waitDelay.Set(reflect.ValueOf(30 * time.Second)) + } + // On darwin the cwd gets resolved to the real path, which breaks anything that // expects the working directory to keep the original path, including the // go command when dealing with modules. @@ -229,6 +261,7 @@ func (i *Invocation) run(ctx context.Context, stdout, stderr io.Writer) error { cmd.Env = append(cmd.Env, "PWD="+i.WorkingDir) cmd.Dir = i.WorkingDir } + defer func(start time.Time) { log("%s for %v", time.Since(start), cmdDebugStr(cmd)) }(time.Now()) return runCmdContext(ctx, cmd) @@ -242,10 +275,85 @@ var DebugHangingGoCommands = false // runCmdContext is like exec.CommandContext except it sends os.Interrupt // before os.Kill. -func runCmdContext(ctx context.Context, cmd *exec.Cmd) error { - if err := cmd.Start(); err != nil { +func runCmdContext(ctx context.Context, cmd *exec.Cmd) (err error) { + // If cmd.Stdout is not an *os.File, the exec package will create a pipe and + // copy it to the Writer in a goroutine until the process has finished and + // either the pipe reaches EOF or command's WaitDelay expires. + // + // However, the output from 'go list' can be quite large, and we don't want to + // keep reading (and allocating buffers) if we've already decided we don't + // care about the output. We don't want to wait for the process to finish, and + // we don't wait to wait for the WaitDelay to expire either. + // + // Instead, if cmd.Stdout requires a copying goroutine we explicitly replace + // it with a pipe (which is an *os.File), which we can close in order to stop + // copying output as soon as we realize we don't care about it. + var stdoutW *os.File + if cmd.Stdout != nil { + if _, ok := cmd.Stdout.(*os.File); !ok { + var stdoutR *os.File + stdoutR, stdoutW, err = os.Pipe() + if err != nil { + return err + } + prevStdout := cmd.Stdout + cmd.Stdout = stdoutW + + stdoutErr := make(chan error, 1) + go func() { + _, err := io.Copy(prevStdout, stdoutR) + if err != nil { + err = fmt.Errorf("copying stdout: %w", err) + } + stdoutErr <- err + }() + defer func() { + // We started a goroutine to copy a stdout pipe. + // Wait for it to finish, or terminate it if need be. + var err2 error + select { + case err2 = <-stdoutErr: + stdoutR.Close() + case <-ctx.Done(): + stdoutR.Close() + // Per https://pkg.go.dev/os#File.Close, the call to stdoutR.Close + // should cause the Read call in io.Copy to unblock and return + // immediately, but we still need to receive from stdoutErr to confirm + // that that has happened. + <-stdoutErr + err2 = ctx.Err() + } + if err == nil { + err = err2 + } + }() + + // Per https://pkg.go.dev/os/exec#Cmd, “If Stdout and Stderr are the + // same writer, and have a type that can be compared with ==, at most + // one goroutine at a time will call Write.” + // + // Since we're starting a goroutine that writes to cmd.Stdout, we must + // also update cmd.Stderr so that that still holds. + func() { + defer func() { recover() }() + if cmd.Stderr == prevStdout { + cmd.Stderr = cmd.Stdout + } + }() + } + } + + err = cmd.Start() + if stdoutW != nil { + // The child process has inherited the pipe file, + // so close the copy held in this process. + stdoutW.Close() + stdoutW = nil + } + if err != nil { return err } + resChan := make(chan error, 1) go func() { resChan <- cmd.Wait() @@ -253,11 +361,14 @@ func runCmdContext(ctx context.Context, cmd *exec.Cmd) error { // If we're interested in debugging hanging Go commands, stop waiting after a // minute and panic with interesting information. - if DebugHangingGoCommands { + debug := DebugHangingGoCommands + if debug { + timer := time.NewTimer(1 * time.Minute) + defer timer.Stop() select { case err := <-resChan: return err - case <-time.After(1 * time.Minute): + case <-timer.C: HandleHangingGoCommand(cmd.Process) case <-ctx.Done(): } @@ -270,30 +381,25 @@ func runCmdContext(ctx context.Context, cmd *exec.Cmd) error { } // Cancelled. Interrupt and see if it ends voluntarily. - cmd.Process.Signal(os.Interrupt) - select { - case err := <-resChan: - return err - case <-time.After(time.Second): + if err := cmd.Process.Signal(os.Interrupt); err == nil { + // (We used to wait only 1s but this proved + // fragile on loaded builder machines.) + timer := time.NewTimer(5 * time.Second) + defer timer.Stop() + select { + case err := <-resChan: + return err + case <-timer.C: + } } // Didn't shut down in response to interrupt. Kill it hard. // TODO(rfindley): per advice from bcmills@, it may be better to send SIGQUIT // on certain platforms, such as unix. - if err := cmd.Process.Kill(); err != nil && DebugHangingGoCommands { - // Don't panic here as this reliably fails on windows with EINVAL. + if err := cmd.Process.Kill(); err != nil && !errors.Is(err, os.ErrProcessDone) && debug { log.Printf("error killing the Go command: %v", err) } - // See above: don't wait indefinitely if we're debugging hanging Go commands. - if DebugHangingGoCommands { - select { - case err := <-resChan: - return err - case <-time.After(10 * time.Second): // a shorter wait as resChan should return quickly following Kill - HandleHangingGoCommand(cmd.Process) - } - } return <-resChan } diff --git a/vendor/golang.org/x/tools/internal/gocommand/version.go b/vendor/golang.org/x/tools/internal/gocommand/version.go index 307a76d474a..446c5846a60 100644 --- a/vendor/golang.org/x/tools/internal/gocommand/version.go +++ b/vendor/golang.org/x/tools/internal/gocommand/version.go @@ -23,21 +23,11 @@ import ( func GoVersion(ctx context.Context, inv Invocation, r *Runner) (int, error) { inv.Verb = "list" inv.Args = []string{"-e", "-f", `{{context.ReleaseTags}}`, `--`, `unsafe`} - inv.Env = append(append([]string{}, inv.Env...), "GO111MODULE=off") - // Unset any unneeded flags, and remove them from BuildFlags, if they're - // present. - inv.ModFile = "" + inv.BuildFlags = nil // This is not a build command. inv.ModFlag = "" - var buildFlags []string - for _, flag := range inv.BuildFlags { - // Flags can be prefixed by one or two dashes. - f := strings.TrimPrefix(strings.TrimPrefix(flag, "-"), "-") - if strings.HasPrefix(f, "mod=") || strings.HasPrefix(f, "modfile=") { - continue - } - buildFlags = append(buildFlags, flag) - } - inv.BuildFlags = buildFlags + inv.ModFile = "" + inv.Env = append(inv.Env[:len(inv.Env):len(inv.Env)], "GO111MODULE=off") + stdoutBytes, err := r.Run(ctx, inv) if err != nil { return 0, err diff --git a/vendor/golang.org/x/tools/internal/imports/fix.go b/vendor/golang.org/x/tools/internal/imports/fix.go index 642a5ac2d75..d4f1b4e8a0f 100644 --- a/vendor/golang.org/x/tools/internal/imports/fix.go +++ b/vendor/golang.org/x/tools/internal/imports/fix.go @@ -26,6 +26,7 @@ import ( "unicode/utf8" "golang.org/x/tools/go/ast/astutil" + "golang.org/x/tools/internal/event" "golang.org/x/tools/internal/gocommand" "golang.org/x/tools/internal/gopathwalk" ) @@ -414,9 +415,16 @@ func (p *pass) fix() ([]*ImportFix, bool) { }) } } + // Collecting fixes involved map iteration, so sort for stability. See + // golang/go#59976. + sortFixes(fixes) + // collect selected fixes in a separate slice, so that it can be sorted + // separately. Note that these fixes must occur after fixes to existing + // imports. TODO(rfindley): figure out why. + var selectedFixes []*ImportFix for _, imp := range selected { - fixes = append(fixes, &ImportFix{ + selectedFixes = append(selectedFixes, &ImportFix{ StmtInfo: ImportInfo{ Name: p.importSpecName(imp), ImportPath: imp.ImportPath, @@ -425,8 +433,25 @@ func (p *pass) fix() ([]*ImportFix, bool) { FixType: AddImport, }) } + sortFixes(selectedFixes) - return fixes, true + return append(fixes, selectedFixes...), true +} + +func sortFixes(fixes []*ImportFix) { + sort.Slice(fixes, func(i, j int) bool { + fi, fj := fixes[i], fixes[j] + if fi.StmtInfo.ImportPath != fj.StmtInfo.ImportPath { + return fi.StmtInfo.ImportPath < fj.StmtInfo.ImportPath + } + if fi.StmtInfo.Name != fj.StmtInfo.Name { + return fi.StmtInfo.Name < fj.StmtInfo.Name + } + if fi.IdentName != fj.IdentName { + return fi.IdentName < fj.IdentName + } + return fi.FixType < fj.FixType + }) } // importSpecName gets the import name of imp in the import spec. @@ -519,7 +544,7 @@ func (p *pass) addCandidate(imp *ImportInfo, pkg *packageInfo) { var fixImports = fixImportsDefault func fixImportsDefault(fset *token.FileSet, f *ast.File, filename string, env *ProcessEnv) error { - fixes, err := getFixes(fset, f, filename, env) + fixes, err := getFixes(context.Background(), fset, f, filename, env) if err != nil { return err } @@ -529,7 +554,7 @@ func fixImportsDefault(fset *token.FileSet, f *ast.File, filename string, env *P // getFixes gets the import fixes that need to be made to f in order to fix the imports. // It does not modify the ast. -func getFixes(fset *token.FileSet, f *ast.File, filename string, env *ProcessEnv) ([]*ImportFix, error) { +func getFixes(ctx context.Context, fset *token.FileSet, f *ast.File, filename string, env *ProcessEnv) ([]*ImportFix, error) { abs, err := filepath.Abs(filename) if err != nil { return nil, err @@ -583,7 +608,7 @@ func getFixes(fset *token.FileSet, f *ast.File, filename string, env *ProcessEnv // Go look for candidates in $GOPATH, etc. We don't necessarily load // the real exports of sibling imports, so keep assuming their contents. - if err := addExternalCandidates(p, p.missingRefs, filename); err != nil { + if err := addExternalCandidates(ctx, p, p.missingRefs, filename); err != nil { return nil, err } @@ -1031,7 +1056,10 @@ type scanCallback struct { exportsLoaded func(pkg *pkg, exports []string) } -func addExternalCandidates(pass *pass, refs references, filename string) error { +func addExternalCandidates(ctx context.Context, pass *pass, refs references, filename string) error { + ctx, done := event.Start(ctx, "imports.addExternalCandidates") + defer done() + var mu sync.Mutex found := make(map[string][]pkgDistance) callback := &scanCallback{ diff --git a/vendor/golang.org/x/tools/internal/imports/imports.go b/vendor/golang.org/x/tools/internal/imports/imports.go index 95a88383a79..58e637b90f2 100644 --- a/vendor/golang.org/x/tools/internal/imports/imports.go +++ b/vendor/golang.org/x/tools/internal/imports/imports.go @@ -11,6 +11,7 @@ package imports import ( "bufio" "bytes" + "context" "fmt" "go/ast" "go/format" @@ -23,6 +24,7 @@ import ( "strings" "golang.org/x/tools/go/ast/astutil" + "golang.org/x/tools/internal/event" ) // Options is golang.org/x/tools/imports.Options with extra internal-only options. @@ -66,14 +68,17 @@ func Process(filename string, src []byte, opt *Options) (formatted []byte, err e // // Note that filename's directory influences which imports can be chosen, // so it is important that filename be accurate. -func FixImports(filename string, src []byte, opt *Options) (fixes []*ImportFix, err error) { +func FixImports(ctx context.Context, filename string, src []byte, opt *Options) (fixes []*ImportFix, err error) { + ctx, done := event.Start(ctx, "imports.FixImports") + defer done() + fileSet := token.NewFileSet() file, _, err := parse(fileSet, filename, src, opt) if err != nil { return nil, err } - return getFixes(fileSet, file, filename, opt.Env) + return getFixes(ctx, fileSet, file, filename, opt.Env) } // ApplyFixes applies all of the fixes to the file and formats it. extraMode diff --git a/vendor/golang.org/x/tools/internal/imports/mod.go b/vendor/golang.org/x/tools/internal/imports/mod.go index 7d99d04ca8a..1389d38b213 100644 --- a/vendor/golang.org/x/tools/internal/imports/mod.go +++ b/vendor/golang.org/x/tools/internal/imports/mod.go @@ -19,6 +19,7 @@ import ( "strings" "golang.org/x/mod/module" + "golang.org/x/tools/internal/event" "golang.org/x/tools/internal/gocommand" "golang.org/x/tools/internal/gopathwalk" ) @@ -424,6 +425,9 @@ func (r *ModuleResolver) loadPackageNames(importPaths []string, srcDir string) ( } func (r *ModuleResolver) scan(ctx context.Context, callback *scanCallback) error { + ctx, done := event.Start(ctx, "imports.ModuleResolver.scan") + defer done() + if err := r.init(); err != nil { return err } diff --git a/vendor/golang.org/x/tools/internal/typesinternal/types.go b/vendor/golang.org/x/tools/internal/typesinternal/types.go index 3c53fbc63b9..ce7d4351b22 100644 --- a/vendor/golang.org/x/tools/internal/typesinternal/types.go +++ b/vendor/golang.org/x/tools/internal/typesinternal/types.go @@ -11,8 +11,6 @@ import ( "go/types" "reflect" "unsafe" - - "golang.org/x/tools/go/types/objectpath" ) func SetUsesCgo(conf *types.Config) bool { @@ -52,10 +50,3 @@ func ReadGo116ErrorData(err types.Error) (code ErrorCode, start, end token.Pos, } var SetGoVersion = func(conf *types.Config, version string) bool { return false } - -// NewObjectpathEncoder returns a function closure equivalent to -// objectpath.For but amortized for multiple (sequential) calls. -// It is a temporary workaround, pending the approval of proposal 58668. -// -//go:linkname NewObjectpathFunc golang.org/x/tools/go/types/objectpath.newEncoderFor -func NewObjectpathFunc() func(types.Object) (objectpath.Path, error) diff --git a/vendor/google.golang.org/genproto/googleapis/api/annotations/client.pb.go b/vendor/google.golang.org/genproto/googleapis/api/annotations/client.pb.go index 4c91534d5a9..c2ddc8e90a9 100644 --- a/vendor/google.golang.org/genproto/googleapis/api/annotations/client.pb.go +++ b/vendor/google.golang.org/genproto/googleapis/api/annotations/client.pb.go @@ -1,4 +1,4 @@ -// Copyright 2018 Google LLC +// Copyright 2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -223,7 +223,9 @@ type ClientLibrarySettings struct { sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - // Version of the API to apply these settings to. + // Version of the API to apply these settings to. This is the full protobuf + // package for the API, ending in the version element. + // Examples: "google.cloud.speech.v1" and "google.spanner.admin.database.v1". Version string `protobuf:"bytes,1,opt,name=version,proto3" json:"version,omitempty"` // Launch stage of this version of the API. LaunchStage api.LaunchStage `protobuf:"varint,2,opt,name=launch_stage,json=launchStage,proto3,enum=google.api.LaunchStage" json:"launch_stage,omitempty"` @@ -392,6 +394,9 @@ type Publishing struct { // times in this list, then the last one wins. Settings from earlier // settings with the same version string are discarded. LibrarySettings []*ClientLibrarySettings `protobuf:"bytes,109,rep,name=library_settings,json=librarySettings,proto3" json:"library_settings,omitempty"` + // Optional link to proto reference documentation. Example: + // https://cloud.google.com/pubsub/lite/docs/reference/rpc + ProtoReferenceDocumentationUri string `protobuf:"bytes,110,opt,name=proto_reference_documentation_uri,json=protoReferenceDocumentationUri,proto3" json:"proto_reference_documentation_uri,omitempty"` } func (x *Publishing) Reset() { @@ -489,6 +494,13 @@ func (x *Publishing) GetLibrarySettings() []*ClientLibrarySettings { return nil } +func (x *Publishing) GetProtoReferenceDocumentationUri() string { + if x != nil { + return x.ProtoReferenceDocumentationUri + } + return "" +} + // Settings for Java client libraries. type JavaSettings struct { state protoimpl.MessageState @@ -938,8 +950,8 @@ type MethodSettings struct { // Example of a YAML configuration:: // // publishing: - // method_behavior: - // - selector: CreateAdDomain + // method_settings: + // - selector: google.cloud.speech.v2.Speech.BatchRecognize // long_running: // initial_poll_delay: // seconds: 60 # 1 minute @@ -1252,7 +1264,7 @@ var file_google_api_client_proto_rawDesc = []byte{ 0x5f, 0x73, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x18, 0x1c, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x47, 0x6f, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, 0x0a, 0x67, 0x6f, 0x53, 0x65, 0x74, 0x74, 0x69, - 0x6e, 0x67, 0x73, 0x22, 0xe0, 0x03, 0x0a, 0x0a, 0x50, 0x75, 0x62, 0x6c, 0x69, 0x73, 0x68, 0x69, + 0x6e, 0x67, 0x73, 0x22, 0xab, 0x04, 0x0a, 0x0a, 0x50, 0x75, 0x62, 0x6c, 0x69, 0x73, 0x68, 0x69, 0x6e, 0x67, 0x12, 0x43, 0x0a, 0x0f, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x5f, 0x73, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x53, @@ -1282,118 +1294,122 @@ var file_google_api_client_proto_rawDesc = []byte{ 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x4c, 0x69, 0x62, 0x72, 0x61, 0x72, 0x79, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, 0x0f, 0x6c, 0x69, 0x62, 0x72, 0x61, 0x72, 0x79, 0x53, 0x65, - 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x22, 0x9a, 0x02, 0x0a, 0x0c, 0x4a, 0x61, 0x76, 0x61, 0x53, - 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x12, 0x27, 0x0a, 0x0f, 0x6c, 0x69, 0x62, 0x72, 0x61, - 0x72, 0x79, 0x5f, 0x70, 0x61, 0x63, 0x6b, 0x61, 0x67, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, - 0x52, 0x0e, 0x6c, 0x69, 0x62, 0x72, 0x61, 0x72, 0x79, 0x50, 0x61, 0x63, 0x6b, 0x61, 0x67, 0x65, - 0x12, 0x5f, 0x0a, 0x13, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x5f, 0x63, 0x6c, 0x61, 0x73, - 0x73, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2f, 0x2e, - 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x4a, 0x61, 0x76, 0x61, 0x53, - 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x2e, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x43, - 0x6c, 0x61, 0x73, 0x73, 0x4e, 0x61, 0x6d, 0x65, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x11, - 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x43, 0x6c, 0x61, 0x73, 0x73, 0x4e, 0x61, 0x6d, 0x65, - 0x73, 0x12, 0x3a, 0x0a, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x22, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, - 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x4c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x53, 0x65, 0x74, - 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x1a, 0x44, 0x0a, - 0x16, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x43, 0x6c, 0x61, 0x73, 0x73, 0x4e, 0x61, 0x6d, - 0x65, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, - 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, - 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, - 0x02, 0x38, 0x01, 0x22, 0x49, 0x0a, 0x0b, 0x43, 0x70, 0x70, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, - 0x67, 0x73, 0x12, 0x3a, 0x0a, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, - 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, - 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x4c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x53, 0x65, - 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x22, 0x49, - 0x0a, 0x0b, 0x50, 0x68, 0x70, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x12, 0x3a, 0x0a, + 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x12, 0x49, 0x0a, 0x21, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x5f, + 0x72, 0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65, 0x5f, 0x64, 0x6f, 0x63, 0x75, 0x6d, 0x65, + 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x75, 0x72, 0x69, 0x18, 0x6e, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x1e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x52, 0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, + 0x65, 0x44, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x55, 0x72, + 0x69, 0x22, 0x9a, 0x02, 0x0a, 0x0c, 0x4a, 0x61, 0x76, 0x61, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, + 0x67, 0x73, 0x12, 0x27, 0x0a, 0x0f, 0x6c, 0x69, 0x62, 0x72, 0x61, 0x72, 0x79, 0x5f, 0x70, 0x61, + 0x63, 0x6b, 0x61, 0x67, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x6c, 0x69, 0x62, + 0x72, 0x61, 0x72, 0x79, 0x50, 0x61, 0x63, 0x6b, 0x61, 0x67, 0x65, 0x12, 0x5f, 0x0a, 0x13, 0x73, + 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x5f, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x5f, 0x6e, 0x61, 0x6d, + 0x65, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x4a, 0x61, 0x76, 0x61, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, + 0x67, 0x73, 0x2e, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x43, 0x6c, 0x61, 0x73, 0x73, 0x4e, + 0x61, 0x6d, 0x65, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x11, 0x73, 0x65, 0x72, 0x76, 0x69, + 0x63, 0x65, 0x43, 0x6c, 0x61, 0x73, 0x73, 0x4e, 0x61, 0x6d, 0x65, 0x73, 0x12, 0x3a, 0x0a, 0x06, + 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, + 0x4c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, + 0x52, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x1a, 0x44, 0x0a, 0x16, 0x53, 0x65, 0x72, 0x76, + 0x69, 0x63, 0x65, 0x43, 0x6c, 0x61, 0x73, 0x73, 0x4e, 0x61, 0x6d, 0x65, 0x73, 0x45, 0x6e, 0x74, + 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0x49, + 0x0a, 0x0b, 0x43, 0x70, 0x70, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x12, 0x3a, 0x0a, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x4c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, - 0x73, 0x52, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x22, 0x4c, 0x0a, 0x0e, 0x50, 0x79, 0x74, - 0x68, 0x6f, 0x6e, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x12, 0x3a, 0x0a, 0x06, 0x63, - 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x67, 0x6f, - 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x4c, - 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, - 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x22, 0x4a, 0x0a, 0x0c, 0x4e, 0x6f, 0x64, 0x65, 0x53, - 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x12, 0x3a, 0x0a, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, - 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, - 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x4c, 0x61, 0x6e, 0x67, 0x75, - 0x61, 0x67, 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, 0x06, 0x63, 0x6f, 0x6d, - 0x6d, 0x6f, 0x6e, 0x22, 0x4c, 0x0a, 0x0e, 0x44, 0x6f, 0x74, 0x6e, 0x65, 0x74, 0x53, 0x65, 0x74, - 0x74, 0x69, 0x6e, 0x67, 0x73, 0x12, 0x3a, 0x0a, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x18, - 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, - 0x70, 0x69, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x4c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, - 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, - 0x6e, 0x22, 0x4a, 0x0a, 0x0c, 0x52, 0x75, 0x62, 0x79, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, - 0x73, 0x12, 0x3a, 0x0a, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x22, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, - 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x4c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x53, 0x65, 0x74, - 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x22, 0x48, 0x0a, - 0x0a, 0x47, 0x6f, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x12, 0x3a, 0x0a, 0x06, 0x63, - 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x67, 0x6f, - 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x4c, - 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, - 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x22, 0x8e, 0x03, 0x0a, 0x0e, 0x4d, 0x65, 0x74, 0x68, - 0x6f, 0x64, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x12, 0x1a, 0x0a, 0x08, 0x73, 0x65, - 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x73, 0x65, - 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x12, 0x49, 0x0a, 0x0c, 0x6c, 0x6f, 0x6e, 0x67, 0x5f, 0x72, - 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, - 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x2e, 0x4c, 0x6f, 0x6e, 0x67, 0x52, 0x75, 0x6e, - 0x6e, 0x69, 0x6e, 0x67, 0x52, 0x0b, 0x6c, 0x6f, 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, - 0x67, 0x1a, 0x94, 0x02, 0x0a, 0x0b, 0x4c, 0x6f, 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, - 0x67, 0x12, 0x47, 0x0a, 0x12, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x70, 0x6f, 0x6c, - 0x6c, 0x5f, 0x64, 0x65, 0x6c, 0x61, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, - 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, - 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x10, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, - 0x6c, 0x50, 0x6f, 0x6c, 0x6c, 0x44, 0x65, 0x6c, 0x61, 0x79, 0x12, 0x32, 0x0a, 0x15, 0x70, 0x6f, - 0x6c, 0x6c, 0x5f, 0x64, 0x65, 0x6c, 0x61, 0x79, 0x5f, 0x6d, 0x75, 0x6c, 0x74, 0x69, 0x70, 0x6c, - 0x69, 0x65, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x02, 0x52, 0x13, 0x70, 0x6f, 0x6c, 0x6c, 0x44, - 0x65, 0x6c, 0x61, 0x79, 0x4d, 0x75, 0x6c, 0x74, 0x69, 0x70, 0x6c, 0x69, 0x65, 0x72, 0x12, 0x3f, - 0x0a, 0x0e, 0x6d, 0x61, 0x78, 0x5f, 0x70, 0x6f, 0x6c, 0x6c, 0x5f, 0x64, 0x65, 0x6c, 0x61, 0x79, - 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x73, 0x52, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x22, 0x49, 0x0a, 0x0b, 0x50, 0x68, 0x70, + 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x12, 0x3a, 0x0a, 0x06, 0x63, 0x6f, 0x6d, 0x6d, + 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x4c, 0x61, 0x6e, 0x67, + 0x75, 0x61, 0x67, 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, 0x06, 0x63, 0x6f, + 0x6d, 0x6d, 0x6f, 0x6e, 0x22, 0x4c, 0x0a, 0x0e, 0x50, 0x79, 0x74, 0x68, 0x6f, 0x6e, 0x53, 0x65, + 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x12, 0x3a, 0x0a, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x61, 0x70, 0x69, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x4c, 0x61, 0x6e, 0x67, 0x75, 0x61, + 0x67, 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, 0x06, 0x63, 0x6f, 0x6d, 0x6d, + 0x6f, 0x6e, 0x22, 0x4a, 0x0a, 0x0c, 0x4e, 0x6f, 0x64, 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, + 0x67, 0x73, 0x12, 0x3a, 0x0a, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, + 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, + 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x4c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x53, 0x65, + 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x22, 0x4c, + 0x0a, 0x0e, 0x44, 0x6f, 0x74, 0x6e, 0x65, 0x74, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, + 0x12, 0x3a, 0x0a, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, + 0x32, 0x22, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, 0x6f, + 0x6d, 0x6d, 0x6f, 0x6e, 0x4c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x53, 0x65, 0x74, 0x74, + 0x69, 0x6e, 0x67, 0x73, 0x52, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x22, 0x4a, 0x0a, 0x0c, + 0x52, 0x75, 0x62, 0x79, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x12, 0x3a, 0x0a, 0x06, + 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, + 0x4c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, + 0x52, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x22, 0x48, 0x0a, 0x0a, 0x47, 0x6f, 0x53, 0x65, + 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x12, 0x3a, 0x0a, 0x06, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x61, 0x70, 0x69, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x4c, 0x61, 0x6e, 0x67, 0x75, 0x61, + 0x67, 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, 0x06, 0x63, 0x6f, 0x6d, 0x6d, + 0x6f, 0x6e, 0x22, 0x8e, 0x03, 0x0a, 0x0e, 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x53, 0x65, 0x74, + 0x74, 0x69, 0x6e, 0x67, 0x73, 0x12, 0x1a, 0x0a, 0x08, 0x73, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x6f, + 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x73, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x6f, + 0x72, 0x12, 0x49, 0x0a, 0x0c, 0x6c, 0x6f, 0x6e, 0x67, 0x5f, 0x72, 0x75, 0x6e, 0x6e, 0x69, 0x6e, + 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x53, 0x65, 0x74, 0x74, 0x69, + 0x6e, 0x67, 0x73, 0x2e, 0x4c, 0x6f, 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x52, + 0x0b, 0x6c, 0x6f, 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x1a, 0x94, 0x02, 0x0a, + 0x0b, 0x4c, 0x6f, 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x12, 0x47, 0x0a, 0x12, + 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x70, 0x6f, 0x6c, 0x6c, 0x5f, 0x64, 0x65, 0x6c, + 0x61, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, + 0x69, 0x6f, 0x6e, 0x52, 0x10, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x50, 0x6f, 0x6c, 0x6c, + 0x44, 0x65, 0x6c, 0x61, 0x79, 0x12, 0x32, 0x0a, 0x15, 0x70, 0x6f, 0x6c, 0x6c, 0x5f, 0x64, 0x65, + 0x6c, 0x61, 0x79, 0x5f, 0x6d, 0x75, 0x6c, 0x74, 0x69, 0x70, 0x6c, 0x69, 0x65, 0x72, 0x18, 0x02, + 0x20, 0x01, 0x28, 0x02, 0x52, 0x13, 0x70, 0x6f, 0x6c, 0x6c, 0x44, 0x65, 0x6c, 0x61, 0x79, 0x4d, + 0x75, 0x6c, 0x74, 0x69, 0x70, 0x6c, 0x69, 0x65, 0x72, 0x12, 0x3f, 0x0a, 0x0e, 0x6d, 0x61, 0x78, + 0x5f, 0x70, 0x6f, 0x6c, 0x6c, 0x5f, 0x64, 0x65, 0x6c, 0x61, 0x79, 0x18, 0x03, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0c, 0x6d, 0x61, + 0x78, 0x50, 0x6f, 0x6c, 0x6c, 0x44, 0x65, 0x6c, 0x61, 0x79, 0x12, 0x47, 0x0a, 0x12, 0x74, 0x6f, + 0x74, 0x61, 0x6c, 0x5f, 0x70, 0x6f, 0x6c, 0x6c, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, + 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, - 0x6e, 0x52, 0x0c, 0x6d, 0x61, 0x78, 0x50, 0x6f, 0x6c, 0x6c, 0x44, 0x65, 0x6c, 0x61, 0x79, 0x12, - 0x47, 0x0a, 0x12, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x5f, 0x70, 0x6f, 0x6c, 0x6c, 0x5f, 0x74, 0x69, - 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, - 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, - 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x10, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x50, 0x6f, 0x6c, - 0x6c, 0x54, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x2a, 0x79, 0x0a, 0x19, 0x43, 0x6c, 0x69, 0x65, - 0x6e, 0x74, 0x4c, 0x69, 0x62, 0x72, 0x61, 0x72, 0x79, 0x4f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, - 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x2b, 0x0a, 0x27, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, - 0x4c, 0x49, 0x42, 0x52, 0x41, 0x52, 0x59, 0x5f, 0x4f, 0x52, 0x47, 0x41, 0x4e, 0x49, 0x5a, 0x41, - 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, - 0x10, 0x00, 0x12, 0x09, 0x0a, 0x05, 0x43, 0x4c, 0x4f, 0x55, 0x44, 0x10, 0x01, 0x12, 0x07, 0x0a, - 0x03, 0x41, 0x44, 0x53, 0x10, 0x02, 0x12, 0x0a, 0x0a, 0x06, 0x50, 0x48, 0x4f, 0x54, 0x4f, 0x53, - 0x10, 0x03, 0x12, 0x0f, 0x0a, 0x0b, 0x53, 0x54, 0x52, 0x45, 0x45, 0x54, 0x5f, 0x56, 0x49, 0x45, - 0x57, 0x10, 0x04, 0x2a, 0x67, 0x0a, 0x18, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x4c, 0x69, 0x62, - 0x72, 0x61, 0x72, 0x79, 0x44, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, - 0x2a, 0x0a, 0x26, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x4c, 0x49, 0x42, 0x52, 0x41, 0x52, - 0x59, 0x5f, 0x44, 0x45, 0x53, 0x54, 0x49, 0x4e, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x55, 0x4e, - 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x0a, 0x0a, 0x06, 0x47, - 0x49, 0x54, 0x48, 0x55, 0x42, 0x10, 0x0a, 0x12, 0x13, 0x0a, 0x0f, 0x50, 0x41, 0x43, 0x4b, 0x41, - 0x47, 0x45, 0x5f, 0x4d, 0x41, 0x4e, 0x41, 0x47, 0x45, 0x52, 0x10, 0x14, 0x3a, 0x4a, 0x0a, 0x10, - 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x5f, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, - 0x12, 0x1e, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, - 0x75, 0x66, 0x2e, 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, - 0x18, 0x9b, 0x08, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0f, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x53, - 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x3a, 0x43, 0x0a, 0x0c, 0x64, 0x65, 0x66, 0x61, - 0x75, 0x6c, 0x74, 0x5f, 0x68, 0x6f, 0x73, 0x74, 0x12, 0x1f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x6e, 0x52, 0x10, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x50, 0x6f, 0x6c, 0x6c, 0x54, 0x69, 0x6d, 0x65, + 0x6f, 0x75, 0x74, 0x2a, 0x79, 0x0a, 0x19, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x4c, 0x69, 0x62, + 0x72, 0x61, 0x72, 0x79, 0x4f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, + 0x12, 0x2b, 0x0a, 0x27, 0x43, 0x4c, 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x4c, 0x49, 0x42, 0x52, 0x41, + 0x52, 0x59, 0x5f, 0x4f, 0x52, 0x47, 0x41, 0x4e, 0x49, 0x5a, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x5f, + 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x09, 0x0a, + 0x05, 0x43, 0x4c, 0x4f, 0x55, 0x44, 0x10, 0x01, 0x12, 0x07, 0x0a, 0x03, 0x41, 0x44, 0x53, 0x10, + 0x02, 0x12, 0x0a, 0x0a, 0x06, 0x50, 0x48, 0x4f, 0x54, 0x4f, 0x53, 0x10, 0x03, 0x12, 0x0f, 0x0a, + 0x0b, 0x53, 0x54, 0x52, 0x45, 0x45, 0x54, 0x5f, 0x56, 0x49, 0x45, 0x57, 0x10, 0x04, 0x2a, 0x67, + 0x0a, 0x18, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x4c, 0x69, 0x62, 0x72, 0x61, 0x72, 0x79, 0x44, + 0x65, 0x73, 0x74, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x2a, 0x0a, 0x26, 0x43, 0x4c, + 0x49, 0x45, 0x4e, 0x54, 0x5f, 0x4c, 0x49, 0x42, 0x52, 0x41, 0x52, 0x59, 0x5f, 0x44, 0x45, 0x53, + 0x54, 0x49, 0x4e, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, + 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x0a, 0x0a, 0x06, 0x47, 0x49, 0x54, 0x48, 0x55, 0x42, + 0x10, 0x0a, 0x12, 0x13, 0x0a, 0x0f, 0x50, 0x41, 0x43, 0x4b, 0x41, 0x47, 0x45, 0x5f, 0x4d, 0x41, + 0x4e, 0x41, 0x47, 0x45, 0x52, 0x10, 0x14, 0x3a, 0x4a, 0x0a, 0x10, 0x6d, 0x65, 0x74, 0x68, 0x6f, + 0x64, 0x5f, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x12, 0x1e, 0x2e, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x4d, 0x65, + 0x74, 0x68, 0x6f, 0x64, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x9b, 0x08, 0x20, 0x03, + 0x28, 0x09, 0x52, 0x0f, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x74, + 0x75, 0x72, 0x65, 0x3a, 0x43, 0x0a, 0x0c, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x5f, 0x68, + 0x6f, 0x73, 0x74, 0x12, 0x1f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x4f, 0x70, 0x74, + 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x99, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x65, 0x66, + 0x61, 0x75, 0x6c, 0x74, 0x48, 0x6f, 0x73, 0x74, 0x3a, 0x43, 0x0a, 0x0c, 0x6f, 0x61, 0x75, 0x74, + 0x68, 0x5f, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x73, 0x12, 0x1f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x65, 0x72, 0x76, 0x69, - 0x63, 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x99, 0x08, 0x20, 0x01, 0x28, 0x09, - 0x52, 0x0b, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x48, 0x6f, 0x73, 0x74, 0x3a, 0x43, 0x0a, - 0x0c, 0x6f, 0x61, 0x75, 0x74, 0x68, 0x5f, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x73, 0x12, 0x1f, 0x2e, - 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, - 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x9a, - 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x6f, 0x61, 0x75, 0x74, 0x68, 0x53, 0x63, 0x6f, 0x70, - 0x65, 0x73, 0x42, 0x69, 0x0a, 0x0e, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, - 0x2e, 0x61, 0x70, 0x69, 0x42, 0x0b, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x50, 0x72, 0x6f, 0x74, - 0x6f, 0x50, 0x01, 0x5a, 0x41, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, - 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, - 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x61, - 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x3b, 0x61, 0x6e, 0x6e, 0x6f, 0x74, - 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0xa2, 0x02, 0x04, 0x47, 0x41, 0x50, 0x49, 0x62, 0x06, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x63, 0x65, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x9a, 0x08, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x0b, 0x6f, 0x61, 0x75, 0x74, 0x68, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x73, 0x42, 0x69, 0x0a, + 0x0e, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x42, + 0x0b, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x41, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, + 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, + 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x3b, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, + 0x73, 0xa2, 0x02, 0x04, 0x47, 0x41, 0x50, 0x49, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/vendor/google.golang.org/genproto/googleapis/api/annotations/field_behavior.pb.go b/vendor/google.golang.org/genproto/googleapis/api/annotations/field_behavior.pb.go index 164e0df0bf5..dbe2e2d0c65 100644 --- a/vendor/google.golang.org/genproto/googleapis/api/annotations/field_behavior.pb.go +++ b/vendor/google.golang.org/genproto/googleapis/api/annotations/field_behavior.pb.go @@ -1,4 +1,4 @@ -// Copyright 2018 Google LLC +// Copyright 2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.27.1 -// protoc v3.12.2 +// protoc-gen-go v1.26.0 +// protoc v3.21.9 // source: google/api/field_behavior.proto package annotations @@ -149,13 +149,13 @@ var ( // // Examples: // - // string name = 1 [(google.api.field_behavior) = REQUIRED]; - // State state = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; - // google.protobuf.Duration ttl = 1 - // [(google.api.field_behavior) = INPUT_ONLY]; - // google.protobuf.Timestamp expire_time = 1 - // [(google.api.field_behavior) = OUTPUT_ONLY, - // (google.api.field_behavior) = IMMUTABLE]; + // string name = 1 [(google.api.field_behavior) = REQUIRED]; + // State state = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; + // google.protobuf.Duration ttl = 1 + // [(google.api.field_behavior) = INPUT_ONLY]; + // google.protobuf.Timestamp expire_time = 1 + // [(google.api.field_behavior) = OUTPUT_ONLY, + // (google.api.field_behavior) = IMMUTABLE]; // // repeated google.api.FieldBehavior field_behavior = 1052; E_FieldBehavior = &file_google_api_field_behavior_proto_extTypes[0] diff --git a/vendor/google.golang.org/genproto/googleapis/api/annotations/http.pb.go b/vendor/google.golang.org/genproto/googleapis/api/annotations/http.pb.go index 6f11b7c500f..8a0e1c345b9 100644 --- a/vendor/google.golang.org/genproto/googleapis/api/annotations/http.pb.go +++ b/vendor/google.golang.org/genproto/googleapis/api/annotations/http.pb.go @@ -1,4 +1,4 @@ -// Copyright 2015 Google LLC +// Copyright 2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,7 +15,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.26.0 -// protoc v3.12.2 +// protoc v3.21.9 // source: google/api/http.proto package annotations @@ -270,15 +270,18 @@ func (x *Http) GetFullyDecodeReservedExpansion() bool { // 1. Leaf request fields (recursive expansion nested messages in the request // message) are classified into three categories: // - Fields referred by the path template. They are passed via the URL path. -// - Fields referred by the [HttpRule.body][google.api.HttpRule.body]. They are passed via the HTTP +// - Fields referred by the [HttpRule.body][google.api.HttpRule.body]. They +// are passed via the HTTP // request body. // - All other fields are passed via the URL query parameters, and the // parameter name is the field path in the request message. A repeated // field can be represented as multiple query parameters under the same // name. -// 2. If [HttpRule.body][google.api.HttpRule.body] is "*", there is no URL query parameter, all fields +// 2. If [HttpRule.body][google.api.HttpRule.body] is "*", there is no URL +// query parameter, all fields // are passed via URL path and HTTP request body. -// 3. If [HttpRule.body][google.api.HttpRule.body] is omitted, there is no HTTP request body, all +// 3. If [HttpRule.body][google.api.HttpRule.body] is omitted, there is no HTTP +// request body, all // fields are passed via URL path and URL query parameters. // // ### Path template syntax @@ -377,13 +380,15 @@ type HttpRule struct { // Selects a method to which this rule applies. // - // Refer to [selector][google.api.DocumentationRule.selector] for syntax details. + // Refer to [selector][google.api.DocumentationRule.selector] for syntax + // details. Selector string `protobuf:"bytes,1,opt,name=selector,proto3" json:"selector,omitempty"` // Determines the URL pattern is matched by this rules. This pattern can be // used with any of the {get|put|post|delete|patch} methods. A custom method // can be defined using the 'custom' field. // // Types that are assignable to Pattern: + // // *HttpRule_Get // *HttpRule_Put // *HttpRule_Post diff --git a/vendor/google.golang.org/genproto/googleapis/api/annotations/resource.pb.go b/vendor/google.golang.org/genproto/googleapis/api/annotations/resource.pb.go index 13ea54b2940..bbcc12d29c8 100644 --- a/vendor/google.golang.org/genproto/googleapis/api/annotations/resource.pb.go +++ b/vendor/google.golang.org/genproto/googleapis/api/annotations/resource.pb.go @@ -1,4 +1,4 @@ -// Copyright 2018 Google LLC +// Copyright 2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,7 +15,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.26.0 -// protoc v3.12.2 +// protoc v3.21.9 // source: google/api/resource.proto package annotations @@ -218,14 +218,14 @@ type ResourceDescriptor struct { // The path pattern must follow the syntax, which aligns with HTTP binding // syntax: // - // Template = Segment { "/" Segment } ; - // Segment = LITERAL | Variable ; - // Variable = "{" LITERAL "}" ; + // Template = Segment { "/" Segment } ; + // Segment = LITERAL | Variable ; + // Variable = "{" LITERAL "}" ; // // Examples: // - // - "projects/{project}/topics/{topic}" - // - "projects/{project}/knowledgeBases/{knowledge_base}" + // - "projects/{project}/topics/{topic}" + // - "projects/{project}/knowledgeBases/{knowledge_base}" // // The components in braces correspond to the IDs for each resource in the // hierarchy. It is expected that, if multiple patterns are provided, @@ -239,17 +239,17 @@ type ResourceDescriptor struct { // // Example: // - // // The InspectTemplate message originally only supported resource - // // names with organization, and project was added later. - // message InspectTemplate { - // option (google.api.resource) = { - // type: "dlp.googleapis.com/InspectTemplate" - // pattern: - // "organizations/{organization}/inspectTemplates/{inspect_template}" - // pattern: "projects/{project}/inspectTemplates/{inspect_template}" - // history: ORIGINALLY_SINGLE_PATTERN - // }; - // } + // // The InspectTemplate message originally only supported resource + // // names with organization, and project was added later. + // message InspectTemplate { + // option (google.api.resource) = { + // type: "dlp.googleapis.com/InspectTemplate" + // pattern: + // "organizations/{organization}/inspectTemplates/{inspect_template}" + // pattern: "projects/{project}/inspectTemplates/{inspect_template}" + // history: ORIGINALLY_SINGLE_PATTERN + // }; + // } History ResourceDescriptor_History `protobuf:"varint,4,opt,name=history,proto3,enum=google.api.ResourceDescriptor_History" json:"history,omitempty"` // The plural name used in the resource name and permission names, such as // 'projects' for the resource name of 'projects/{project}' and the permission @@ -362,22 +362,22 @@ type ResourceReference struct { // // Example: // - // message Subscription { - // string topic = 2 [(google.api.resource_reference) = { - // type: "pubsub.googleapis.com/Topic" - // }]; - // } + // message Subscription { + // string topic = 2 [(google.api.resource_reference) = { + // type: "pubsub.googleapis.com/Topic" + // }]; + // } // // Occasionally, a field may reference an arbitrary resource. In this case, // APIs use the special value * in their resource reference. // // Example: // - // message GetIamPolicyRequest { - // string resource = 2 [(google.api.resource_reference) = { - // type: "*" - // }]; - // } + // message GetIamPolicyRequest { + // string resource = 2 [(google.api.resource_reference) = { + // type: "*" + // }]; + // } Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"` // The resource type of a child collection that the annotated field // references. This is useful for annotating the `parent` field that @@ -385,11 +385,11 @@ type ResourceReference struct { // // Example: // - // message ListLogEntriesRequest { - // string parent = 1 [(google.api.resource_reference) = { - // child_type: "logging.googleapis.com/LogEntry" - // }; - // } + // message ListLogEntriesRequest { + // string parent = 1 [(google.api.resource_reference) = { + // child_type: "logging.googleapis.com/LogEntry" + // }; + // } ChildType string `protobuf:"bytes,2,opt,name=child_type,json=childType,proto3" json:"child_type,omitempty"` } diff --git a/vendor/google.golang.org/genproto/googleapis/api/annotations/routing.pb.go b/vendor/google.golang.org/genproto/googleapis/api/annotations/routing.pb.go index 6707a7b1c1d..9a9ae04c29a 100644 --- a/vendor/google.golang.org/genproto/googleapis/api/annotations/routing.pb.go +++ b/vendor/google.golang.org/genproto/googleapis/api/annotations/routing.pb.go @@ -1,4 +1,4 @@ -// Copyright 2021 Google LLC +// Copyright 2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,7 +15,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.26.0 -// protoc v3.12.2 +// protoc v3.21.9 // source: google/api/routing.proto package annotations @@ -468,46 +468,46 @@ type RoutingParameter struct { // // Example: // - // -- This is a field in the request message - // | that the header value will be extracted from. - // | - // | -- This is the key name in the - // | | routing header. - // V | - // field: "table_name" v - // path_template: "projects/*/{table_location=instances/*}/tables/*" - // ^ ^ - // | | - // In the {} brackets is the pattern that -- | - // specifies what to extract from the | - // field as a value to be sent. | - // | - // The string in the field must match the whole pattern -- - // before brackets, inside brackets, after brackets. + // -- This is a field in the request message + // | that the header value will be extracted from. + // | + // | -- This is the key name in the + // | | routing header. + // V | + // field: "table_name" v + // path_template: "projects/*/{table_location=instances/*}/tables/*" + // ^ ^ + // | | + // In the {} brackets is the pattern that -- | + // specifies what to extract from the | + // field as a value to be sent. | + // | + // The string in the field must match the whole pattern -- + // before brackets, inside brackets, after brackets. // // When looking at this specific example, we can see that: - // - A key-value pair with the key `table_location` - // and the value matching `instances/*` should be added - // to the x-goog-request-params routing header. - // - The value is extracted from the request message's `table_name` field - // if it matches the full pattern specified: - // `projects/*/instances/*/tables/*`. + // - A key-value pair with the key `table_location` + // and the value matching `instances/*` should be added + // to the x-goog-request-params routing header. + // - The value is extracted from the request message's `table_name` field + // if it matches the full pattern specified: + // `projects/*/instances/*/tables/*`. // // **NB:** If the `path_template` field is not provided, the key name is // equal to the field name, and the whole field should be sent as a value. // This makes the pattern for the field and the value functionally equivalent // to `**`, and the configuration // - // { - // field: "table_name" - // } + // { + // field: "table_name" + // } // // is a functionally equivalent shorthand to: // - // { - // field: "table_name" - // path_template: "{table_name=**}" - // } + // { + // field: "table_name" + // path_template: "{table_name=**}" + // } // // See Example 1 for more details. PathTemplate string `protobuf:"bytes,2,opt,name=path_template,json=pathTemplate,proto3" json:"path_template,omitempty"` diff --git a/vendor/google.golang.org/genproto/googleapis/api/httpbody/httpbody.pb.go b/vendor/google.golang.org/genproto/googleapis/api/httpbody/httpbody.pb.go index af72196c809..3543268f84e 100644 --- a/vendor/google.golang.org/genproto/googleapis/api/httpbody/httpbody.pb.go +++ b/vendor/google.golang.org/genproto/googleapis/api/httpbody/httpbody.pb.go @@ -1,4 +1,4 @@ -// Copyright 2015 Google LLC +// Copyright 2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,7 +15,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.26.0 -// protoc v3.12.2 +// protoc v3.21.9 // source: google/api/httpbody.proto package httpbody diff --git a/vendor/google.golang.org/genproto/googleapis/api/launch_stage.pb.go b/vendor/google.golang.org/genproto/googleapis/api/launch_stage.pb.go index 71075313773..454948669dc 100644 --- a/vendor/google.golang.org/genproto/googleapis/api/launch_stage.pb.go +++ b/vendor/google.golang.org/genproto/googleapis/api/launch_stage.pb.go @@ -1,4 +1,4 @@ -// Copyright 2015 Google LLC +// Copyright 2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,7 +15,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.26.0 -// protoc v3.18.1 +// protoc v3.21.9 // source: google/api/launch_stage.proto package api diff --git a/vendor/google.golang.org/grpc/CONTRIBUTING.md b/vendor/google.golang.org/grpc/CONTRIBUTING.md index 52338d004ce..608aa6e1ac5 100644 --- a/vendor/google.golang.org/grpc/CONTRIBUTING.md +++ b/vendor/google.golang.org/grpc/CONTRIBUTING.md @@ -20,6 +20,15 @@ How to get your contributions merged smoothly and quickly. both author's & review's time is wasted. Create more PRs to address different concerns and everyone will be happy. +- If you are searching for features to work on, issues labeled [Status: Help + Wanted](https://github.com/grpc/grpc-go/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22Status%3A+Help+Wanted%22) + is a great place to start. These issues are well-documented and usually can be + resolved with a single pull request. + +- If you are adding a new file, make sure it has the copyright message template + at the top as a comment. You can copy over the message from an existing file + and update the year. + - The grpc package should only depend on standard Go packages and a small number of exceptions. If your contribution introduces new dependencies which are NOT in the [list](https://godoc.org/google.golang.org/grpc?imports), you need a @@ -32,14 +41,18 @@ How to get your contributions merged smoothly and quickly. - Provide a good **PR description** as a record of **what** change is being made and **why** it was made. Link to a github issue if it exists. -- Don't fix code style and formatting unless you are already changing that line - to address an issue. PRs with irrelevant changes won't be merged. If you do - want to fix formatting or style, do that in a separate PR. +- If you want to fix formatting or style, consider whether your changes are an + obvious improvement or might be considered a personal preference. If a style + change is based on preference, it likely will not be accepted. If it corrects + widely agreed-upon anti-patterns, then please do create a PR and explain the + benefits of the change. - Unless your PR is trivial, you should expect there will be reviewer comments - that you'll need to address before merging. We expect you to be reasonably - responsive to those comments, otherwise the PR will be closed after 2-3 weeks - of inactivity. + that you'll need to address before merging. We'll mark it as `Status: Requires + Reporter Clarification` if we expect you to respond to these comments in a + timely manner. If the PR remains inactive for 6 days, it will be marked as + `stale` and automatically close 7 days after that if we don't hear back from + you. - Maintain **clean commit history** and use **meaningful commit messages**. PRs with messy commit history are difficult to review and won't be merged. Use diff --git a/vendor/google.golang.org/grpc/binarylog/grpc_binarylog_v1/binarylog.pb.go b/vendor/google.golang.org/grpc/binarylog/grpc_binarylog_v1/binarylog.pb.go index 66d141fce70..ec2c2fa14dd 100644 --- a/vendor/google.golang.org/grpc/binarylog/grpc_binarylog_v1/binarylog.pb.go +++ b/vendor/google.golang.org/grpc/binarylog/grpc_binarylog_v1/binarylog.pb.go @@ -18,8 +18,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.14.0 +// protoc-gen-go v1.30.0 +// protoc v4.22.0 // source: grpc/binlog/v1/binarylog.proto package grpc_binarylog_v1 diff --git a/vendor/google.golang.org/grpc/clientconn.go b/vendor/google.golang.org/grpc/clientconn.go index d607d4e9e24..3a76142424d 100644 --- a/vendor/google.golang.org/grpc/clientconn.go +++ b/vendor/google.golang.org/grpc/clientconn.go @@ -146,8 +146,18 @@ func DialContext(ctx context.Context, target string, opts ...DialOption) (conn * cc.safeConfigSelector.UpdateConfigSelector(&defaultConfigSelector{nil}) cc.ctx, cc.cancel = context.WithCancel(context.Background()) - for _, opt := range extraDialOptions { - opt.apply(&cc.dopts) + disableGlobalOpts := false + for _, opt := range opts { + if _, ok := opt.(*disableGlobalDialOptions); ok { + disableGlobalOpts = true + break + } + } + + if !disableGlobalOpts { + for _, opt := range globalDialOptions { + opt.apply(&cc.dopts) + } } for _, opt := range opts { @@ -234,19 +244,6 @@ func DialContext(ctx context.Context, target string, opts ...DialOption) (conn * } }() - scSet := false - if cc.dopts.scChan != nil { - // Try to get an initial service config. - select { - case sc, ok := <-cc.dopts.scChan: - if ok { - cc.sc = &sc - cc.safeConfigSelector.UpdateConfigSelector(&defaultConfigSelector{&sc}) - scSet = true - } - default: - } - } if cc.dopts.bs == nil { cc.dopts.bs = backoff.DefaultExponential } @@ -262,7 +259,7 @@ func DialContext(ctx context.Context, target string, opts ...DialOption) (conn * } channelz.Infof(logger, cc.channelzID, "Channel authority set to %q", cc.authority) - if cc.dopts.scChan != nil && !scSet { + if cc.dopts.scChan != nil { // Blocking wait for the initial service config. select { case sc, ok := <-cc.dopts.scChan: @@ -1103,7 +1100,11 @@ func (ac *addrConn) updateConnectivityState(s connectivity.State, lastErr error) return } ac.state = s - channelz.Infof(logger, ac.channelzID, "Subchannel Connectivity change to %v", s) + if lastErr == nil { + channelz.Infof(logger, ac.channelzID, "Subchannel Connectivity change to %v", s) + } else { + channelz.Infof(logger, ac.channelzID, "Subchannel Connectivity change to %v, last error: %s", s, lastErr) + } ac.cc.handleSubConnStateChange(ac.acbw, s, lastErr) } @@ -1527,6 +1528,9 @@ func (c *channelzChannel) ChannelzMetric() *channelz.ChannelInternalMetric { // referenced by users. var ErrClientConnTimeout = errors.New("grpc: timed out when dialing") +// getResolver finds the scheme in the cc's resolvers or the global registry. +// scheme should always be lowercase (typically by virtue of url.Parse() +// performing proper RFC3986 behavior). func (cc *ClientConn) getResolver(scheme string) resolver.Builder { for _, rb := range cc.dopts.resolvers { if scheme == rb.Scheme() { diff --git a/vendor/google.golang.org/grpc/codes/code_string.go b/vendor/google.golang.org/grpc/codes/code_string.go index 0b206a57822..934fac2b090 100644 --- a/vendor/google.golang.org/grpc/codes/code_string.go +++ b/vendor/google.golang.org/grpc/codes/code_string.go @@ -18,7 +18,15 @@ package codes -import "strconv" +import ( + "strconv" + + "google.golang.org/grpc/internal" +) + +func init() { + internal.CanonicalString = canonicalString +} func (c Code) String() string { switch c { @@ -60,3 +68,44 @@ func (c Code) String() string { return "Code(" + strconv.FormatInt(int64(c), 10) + ")" } } + +func canonicalString(c Code) string { + switch c { + case OK: + return "OK" + case Canceled: + return "CANCELLED" + case Unknown: + return "UNKNOWN" + case InvalidArgument: + return "INVALID_ARGUMENT" + case DeadlineExceeded: + return "DEADLINE_EXCEEDED" + case NotFound: + return "NOT_FOUND" + case AlreadyExists: + return "ALREADY_EXISTS" + case PermissionDenied: + return "PERMISSION_DENIED" + case ResourceExhausted: + return "RESOURCE_EXHAUSTED" + case FailedPrecondition: + return "FAILED_PRECONDITION" + case Aborted: + return "ABORTED" + case OutOfRange: + return "OUT_OF_RANGE" + case Unimplemented: + return "UNIMPLEMENTED" + case Internal: + return "INTERNAL" + case Unavailable: + return "UNAVAILABLE" + case DataLoss: + return "DATA_LOSS" + case Unauthenticated: + return "UNAUTHENTICATED" + default: + return "CODE(" + strconv.FormatInt(int64(c), 10) + ")" + } +} diff --git a/vendor/google.golang.org/grpc/dialoptions.go b/vendor/google.golang.org/grpc/dialoptions.go index 4866da101c6..cdc8263bda6 100644 --- a/vendor/google.golang.org/grpc/dialoptions.go +++ b/vendor/google.golang.org/grpc/dialoptions.go @@ -38,13 +38,14 @@ import ( func init() { internal.AddGlobalDialOptions = func(opt ...DialOption) { - extraDialOptions = append(extraDialOptions, opt...) + globalDialOptions = append(globalDialOptions, opt...) } internal.ClearGlobalDialOptions = func() { - extraDialOptions = nil + globalDialOptions = nil } internal.WithBinaryLogger = withBinaryLogger internal.JoinDialOptions = newJoinDialOption + internal.DisableGlobalDialOptions = newDisableGlobalDialOptions } // dialOptions configure a Dial call. dialOptions are set by the DialOption @@ -83,7 +84,7 @@ type DialOption interface { apply(*dialOptions) } -var extraDialOptions []DialOption +var globalDialOptions []DialOption // EmptyDialOption does not alter the dial configuration. It can be embedded in // another structure to build custom dial options. @@ -96,6 +97,16 @@ type EmptyDialOption struct{} func (EmptyDialOption) apply(*dialOptions) {} +type disableGlobalDialOptions struct{} + +func (disableGlobalDialOptions) apply(*dialOptions) {} + +// newDisableGlobalDialOptions returns a DialOption that prevents the ClientConn +// from applying the global DialOptions (set via AddGlobalDialOptions). +func newDisableGlobalDialOptions() DialOption { + return &disableGlobalDialOptions{} +} + // funcDialOption wraps a function that modifies dialOptions into an // implementation of the DialOption interface. type funcDialOption struct { @@ -284,6 +295,9 @@ func withBackoff(bs internalbackoff.Strategy) DialOption { // WithBlock returns a DialOption which makes callers of Dial block until the // underlying connection is up. Without this, Dial returns immediately and // connecting the server happens in background. +// +// Use of this feature is not recommended. For more information, please see: +// https://github.com/grpc/grpc-go/blob/master/Documentation/anti-patterns.md func WithBlock() DialOption { return newFuncDialOption(func(o *dialOptions) { o.block = true @@ -295,6 +309,9 @@ func WithBlock() DialOption { // the context.DeadlineExceeded error. // Implies WithBlock() // +// Use of this feature is not recommended. For more information, please see: +// https://github.com/grpc/grpc-go/blob/master/Documentation/anti-patterns.md +// // # Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a @@ -437,6 +454,9 @@ func withBinaryLogger(bl binarylog.Logger) DialOption { // FailOnNonTempDialError only affects the initial dial, and does not do // anything useful unless you are also using WithBlock(). // +// Use of this feature is not recommended. For more information, please see: +// https://github.com/grpc/grpc-go/blob/master/Documentation/anti-patterns.md +// // # Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a diff --git a/vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go b/vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go index 8e29a62f164..142d35f753e 100644 --- a/vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go +++ b/vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go @@ -17,8 +17,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 -// protoc v3.14.0 +// protoc-gen-go v1.30.0 +// protoc v4.22.0 // source: grpc/health/v1/health.proto package grpc_health_v1 diff --git a/vendor/google.golang.org/grpc/health/grpc_health_v1/health_grpc.pb.go b/vendor/google.golang.org/grpc/health/grpc_health_v1/health_grpc.pb.go index a332dfd7b54..a01a1b4d54b 100644 --- a/vendor/google.golang.org/grpc/health/grpc_health_v1/health_grpc.pb.go +++ b/vendor/google.golang.org/grpc/health/grpc_health_v1/health_grpc.pb.go @@ -17,8 +17,8 @@ // Code generated by protoc-gen-go-grpc. DO NOT EDIT. // versions: -// - protoc-gen-go-grpc v1.2.0 -// - protoc v3.14.0 +// - protoc-gen-go-grpc v1.3.0 +// - protoc v4.22.0 // source: grpc/health/v1/health.proto package grpc_health_v1 @@ -35,6 +35,11 @@ import ( // Requires gRPC-Go v1.32.0 or later. const _ = grpc.SupportPackageIsVersion7 +const ( + Health_Check_FullMethodName = "/grpc.health.v1.Health/Check" + Health_Watch_FullMethodName = "/grpc.health.v1.Health/Watch" +) + // HealthClient is the client API for Health service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. @@ -70,7 +75,7 @@ func NewHealthClient(cc grpc.ClientConnInterface) HealthClient { func (c *healthClient) Check(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (*HealthCheckResponse, error) { out := new(HealthCheckResponse) - err := c.cc.Invoke(ctx, "/grpc.health.v1.Health/Check", in, out, opts...) + err := c.cc.Invoke(ctx, Health_Check_FullMethodName, in, out, opts...) if err != nil { return nil, err } @@ -78,7 +83,7 @@ func (c *healthClient) Check(ctx context.Context, in *HealthCheckRequest, opts . } func (c *healthClient) Watch(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (Health_WatchClient, error) { - stream, err := c.cc.NewStream(ctx, &Health_ServiceDesc.Streams[0], "/grpc.health.v1.Health/Watch", opts...) + stream, err := c.cc.NewStream(ctx, &Health_ServiceDesc.Streams[0], Health_Watch_FullMethodName, opts...) if err != nil { return nil, err } @@ -166,7 +171,7 @@ func _Health_Check_Handler(srv interface{}, ctx context.Context, dec func(interf } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/grpc.health.v1.Health/Check", + FullMethod: Health_Check_FullMethodName, } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(HealthServer).Check(ctx, req.(*HealthCheckRequest)) diff --git a/vendor/google.golang.org/grpc/internal/binarylog/binarylog.go b/vendor/google.golang.org/grpc/internal/binarylog/binarylog.go index 809d73ccafb..af03a40d990 100644 --- a/vendor/google.golang.org/grpc/internal/binarylog/binarylog.go +++ b/vendor/google.golang.org/grpc/internal/binarylog/binarylog.go @@ -28,8 +28,10 @@ import ( "google.golang.org/grpc/internal/grpcutil" ) -// Logger is the global binary logger. It can be used to get binary logger for -// each method. +var grpclogLogger = grpclog.Component("binarylog") + +// Logger specifies MethodLoggers for method names with a Log call that +// takes a context. type Logger interface { GetMethodLogger(methodName string) MethodLogger } @@ -40,8 +42,6 @@ type Logger interface { // It is used to get a MethodLogger for each individual method. var binLogger Logger -var grpclogLogger = grpclog.Component("binarylog") - // SetLogger sets the binary logger. // // Only call this at init time. diff --git a/vendor/google.golang.org/grpc/internal/binarylog/method_logger.go b/vendor/google.golang.org/grpc/internal/binarylog/method_logger.go index d71e441778f..56fcf008d3d 100644 --- a/vendor/google.golang.org/grpc/internal/binarylog/method_logger.go +++ b/vendor/google.golang.org/grpc/internal/binarylog/method_logger.go @@ -19,6 +19,7 @@ package binarylog import ( + "context" "net" "strings" "sync/atomic" @@ -49,7 +50,7 @@ var idGen callIDGenerator // MethodLogger is the sub-logger for each method. type MethodLogger interface { - Log(LogEntryConfig) + Log(context.Context, LogEntryConfig) } // TruncatingMethodLogger is a method logger that truncates headers and messages @@ -98,7 +99,7 @@ func (ml *TruncatingMethodLogger) Build(c LogEntryConfig) *binlogpb.GrpcLogEntry } // Log creates a proto binary log entry, and logs it to the sink. -func (ml *TruncatingMethodLogger) Log(c LogEntryConfig) { +func (ml *TruncatingMethodLogger) Log(ctx context.Context, c LogEntryConfig) { ml.sink.Write(ml.Build(c)) } diff --git a/vendor/google.golang.org/grpc/internal/envconfig/xds.go b/vendor/google.golang.org/grpc/internal/envconfig/xds.go index 04136882c7b..3b17705ba09 100644 --- a/vendor/google.golang.org/grpc/internal/envconfig/xds.go +++ b/vendor/google.golang.org/grpc/internal/envconfig/xds.go @@ -79,7 +79,7 @@ var ( // XDSFederation indicates whether federation support is enabled, which can // be enabled by setting the environment variable // "GRPC_EXPERIMENTAL_XDS_FEDERATION" to "true". - XDSFederation = boolFromEnv("GRPC_EXPERIMENTAL_XDS_FEDERATION", false) + XDSFederation = boolFromEnv("GRPC_EXPERIMENTAL_XDS_FEDERATION", true) // XDSRLS indicates whether processing of Cluster Specifier plugins and // support for the RLS CLuster Specifier is enabled, which can be enabled by diff --git a/vendor/google.golang.org/grpc/internal/grpclog/prefixLogger.go b/vendor/google.golang.org/grpc/internal/grpclog/prefixLogger.go index 82af70e96f1..02224b42ca8 100644 --- a/vendor/google.golang.org/grpc/internal/grpclog/prefixLogger.go +++ b/vendor/google.golang.org/grpc/internal/grpclog/prefixLogger.go @@ -63,6 +63,9 @@ func (pl *PrefixLogger) Errorf(format string, args ...interface{}) { // Debugf does info logging at verbose level 2. func (pl *PrefixLogger) Debugf(format string, args ...interface{}) { + // TODO(6044): Refactor interfaces LoggerV2 and DepthLogger, and maybe + // rewrite PrefixLogger a little to ensure that we don't use the global + // `Logger` here, and instead use the `logger` field. if !Logger.V(2) { return } @@ -73,6 +76,15 @@ func (pl *PrefixLogger) Debugf(format string, args ...interface{}) { return } InfoDepth(1, fmt.Sprintf(format, args...)) + +} + +// V reports whether verbosity level l is at least the requested verbose level. +func (pl *PrefixLogger) V(l int) bool { + // TODO(6044): Refactor interfaces LoggerV2 and DepthLogger, and maybe + // rewrite PrefixLogger a little to ensure that we don't use the global + // `Logger` here, and instead use the `logger` field. + return Logger.V(l) } // NewPrefixLogger creates a prefix logger with the given prefix. diff --git a/vendor/google.golang.org/grpc/internal/grpcsync/callback_serializer.go b/vendor/google.golang.org/grpc/internal/grpcsync/callback_serializer.go new file mode 100644 index 00000000000..79993d34375 --- /dev/null +++ b/vendor/google.golang.org/grpc/internal/grpcsync/callback_serializer.go @@ -0,0 +1,65 @@ +/* + * + * Copyright 2022 gRPC authors. + * + * 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 grpcsync + +import ( + "context" + + "google.golang.org/grpc/internal/buffer" +) + +// CallbackSerializer provides a mechanism to schedule callbacks in a +// synchronized manner. It provides a FIFO guarantee on the order of execution +// of scheduled callbacks. New callbacks can be scheduled by invoking the +// Schedule() method. +// +// This type is safe for concurrent access. +type CallbackSerializer struct { + callbacks *buffer.Unbounded +} + +// NewCallbackSerializer returns a new CallbackSerializer instance. The provided +// context will be passed to the scheduled callbacks. Users should cancel the +// provided context to shutdown the CallbackSerializer. It is guaranteed that no +// callbacks will be executed once this context is canceled. +func NewCallbackSerializer(ctx context.Context) *CallbackSerializer { + t := &CallbackSerializer{callbacks: buffer.NewUnbounded()} + go t.run(ctx) + return t +} + +// Schedule adds a callback to be scheduled after existing callbacks are run. +// +// Callbacks are expected to honor the context when performing any blocking +// operations, and should return early when the context is canceled. +func (t *CallbackSerializer) Schedule(f func(ctx context.Context)) { + t.callbacks.Put(f) +} + +func (t *CallbackSerializer) run(ctx context.Context) { + for ctx.Err() == nil { + select { + case <-ctx.Done(): + return + case callback := <-t.callbacks.Get(): + t.callbacks.Load() + callback.(func(ctx context.Context))(ctx) + } + } +} diff --git a/vendor/google.golang.org/grpc/internal/internal.go b/vendor/google.golang.org/grpc/internal/internal.go index 0a76d9de6e0..836b6a3b3e7 100644 --- a/vendor/google.golang.org/grpc/internal/internal.go +++ b/vendor/google.golang.org/grpc/internal/internal.go @@ -58,6 +58,9 @@ var ( // gRPC server. An xDS-enabled server needs to know what type of credentials // is configured on the underlying gRPC server. This is set by server.go. GetServerCredentials interface{} // func (*grpc.Server) credentials.TransportCredentials + // CanonicalString returns the canonical string of the code defined here: + // https://github.com/grpc/grpc/blob/master/doc/statuscodes.md. + CanonicalString interface{} // func (codes.Code) string // DrainServerTransports initiates a graceful close of existing connections // on a gRPC server accepted on the provided listener address. An // xDS-enabled server invokes this method on a grpc.Server when a particular @@ -74,6 +77,10 @@ var ( // globally for newly created client channels. The priority will be: 1. // user-provided; 2. this method; 3. default values. AddGlobalDialOptions interface{} // func(opt ...DialOption) + // DisableGlobalDialOptions returns a DialOption that prevents the + // ClientConn from applying the global DialOptions (set via + // AddGlobalDialOptions). + DisableGlobalDialOptions interface{} // func() grpc.DialOption // ClearGlobalDialOptions clears the array of extra DialOption. This // method is useful in testing and benchmarking. ClearGlobalDialOptions func() @@ -130,6 +137,9 @@ var ( // // TODO: Remove this function once the RBAC env var is removed. UnregisterRBACHTTPFilterForTesting func() + + // ORCAAllowAnyMinReportingInterval is for examples/orca use ONLY. + ORCAAllowAnyMinReportingInterval interface{} // func(so *orca.ServiceOptions) ) // HealthChecker defines the signature of the client-side LB channel health checking function. diff --git a/vendor/google.golang.org/grpc/internal/metadata/metadata.go b/vendor/google.golang.org/grpc/internal/metadata/metadata.go index b2980f8ac44..c82e608e077 100644 --- a/vendor/google.golang.org/grpc/internal/metadata/metadata.go +++ b/vendor/google.golang.org/grpc/internal/metadata/metadata.go @@ -76,33 +76,11 @@ func Set(addr resolver.Address, md metadata.MD) resolver.Address { return addr } -// Validate returns an error if the input md contains invalid keys or values. -// -// If the header is not a pseudo-header, the following items are checked: -// - header names must contain one or more characters from this set [0-9 a-z _ - .]. -// - if the header-name ends with a "-bin" suffix, no validation of the header value is performed. -// - otherwise, the header value must contain one or more characters from the set [%x20-%x7E]. +// Validate validates every pair in md with ValidatePair. func Validate(md metadata.MD) error { for k, vals := range md { - // pseudo-header will be ignored - if k[0] == ':' { - continue - } - // check key, for i that saving a conversion if not using for range - for i := 0; i < len(k); i++ { - r := k[i] - if !(r >= 'a' && r <= 'z') && !(r >= '0' && r <= '9') && r != '.' && r != '-' && r != '_' { - return fmt.Errorf("header key %q contains illegal characters not in [0-9a-z-_.]", k) - } - } - if strings.HasSuffix(k, "-bin") { - continue - } - // check value - for _, val := range vals { - if hasNotPrintable(val) { - return fmt.Errorf("header key %q contains value with non-printable ASCII characters", k) - } + if err := ValidatePair(k, vals...); err != nil { + return err } } return nil @@ -118,3 +96,37 @@ func hasNotPrintable(msg string) bool { } return false } + +// ValidatePair validate a key-value pair with the following rules (the pseudo-header will be skipped) : +// +// - key must contain one or more characters. +// - the characters in the key must be contained in [0-9 a-z _ - .]. +// - if the key ends with a "-bin" suffix, no validation of the corresponding value is performed. +// - the characters in the every value must be printable (in [%x20-%x7E]). +func ValidatePair(key string, vals ...string) error { + // key should not be empty + if key == "" { + return fmt.Errorf("there is an empty key in the header") + } + // pseudo-header will be ignored + if key[0] == ':' { + return nil + } + // check key, for i that saving a conversion if not using for range + for i := 0; i < len(key); i++ { + r := key[i] + if !(r >= 'a' && r <= 'z') && !(r >= '0' && r <= '9') && r != '.' && r != '-' && r != '_' { + return fmt.Errorf("header key %q contains illegal characters not in [0-9a-z-_.]", key) + } + } + if strings.HasSuffix(key, "-bin") { + return nil + } + // check value + for _, val := range vals { + if hasNotPrintable(val) { + return fmt.Errorf("header key %q contains value with non-printable ASCII characters", key) + } + } + return nil +} diff --git a/vendor/google.golang.org/grpc/internal/transport/controlbuf.go b/vendor/google.golang.org/grpc/internal/transport/controlbuf.go index 9097385e1a6..be5a9c81eb9 100644 --- a/vendor/google.golang.org/grpc/internal/transport/controlbuf.go +++ b/vendor/google.golang.org/grpc/internal/transport/controlbuf.go @@ -22,6 +22,7 @@ import ( "bytes" "errors" "fmt" + "net" "runtime" "strconv" "sync" @@ -29,6 +30,7 @@ import ( "golang.org/x/net/http2" "golang.org/x/net/http2/hpack" + "google.golang.org/grpc/internal/grpclog" "google.golang.org/grpc/internal/grpcutil" "google.golang.org/grpc/status" ) @@ -486,12 +488,14 @@ type loopyWriter struct { hEnc *hpack.Encoder // HPACK encoder. bdpEst *bdpEstimator draining bool + conn net.Conn + logger *grpclog.PrefixLogger // Side-specific handlers ssGoAwayHandler func(*goAway) (bool, error) } -func newLoopyWriter(s side, fr *framer, cbuf *controlBuffer, bdpEst *bdpEstimator) *loopyWriter { +func newLoopyWriter(s side, fr *framer, cbuf *controlBuffer, bdpEst *bdpEstimator, conn net.Conn, logger *grpclog.PrefixLogger) *loopyWriter { var buf bytes.Buffer l := &loopyWriter{ side: s, @@ -504,6 +508,8 @@ func newLoopyWriter(s side, fr *framer, cbuf *controlBuffer, bdpEst *bdpEstimato hBuf: &buf, hEnc: hpack.NewEncoder(&buf), bdpEst: bdpEst, + conn: conn, + logger: logger, } return l } @@ -521,15 +527,27 @@ const minBatchSize = 1000 // 2. Stream level flow control quota available. // // In each iteration of run loop, other than processing the incoming control -// frame, loopy calls processData, which processes one node from the activeStreams linked-list. -// This results in writing of HTTP2 frames into an underlying write buffer. -// When there's no more control frames to read from controlBuf, loopy flushes the write buffer. -// As an optimization, to increase the batch size for each flush, loopy yields the processor, once -// if the batch size is too low to give stream goroutines a chance to fill it up. +// frame, loopy calls processData, which processes one node from the +// activeStreams linked-list. This results in writing of HTTP2 frames into an +// underlying write buffer. When there's no more control frames to read from +// controlBuf, loopy flushes the write buffer. As an optimization, to increase +// the batch size for each flush, loopy yields the processor, once if the batch +// size is too low to give stream goroutines a chance to fill it up. +// +// Upon exiting, if the error causing the exit is not an I/O error, run() +// flushes and closes the underlying connection. Otherwise, the connection is +// left open to allow the I/O error to be encountered by the reader instead. func (l *loopyWriter) run() (err error) { - // Always flush the writer before exiting in case there are pending frames - // to be sent. - defer l.framer.writer.Flush() + defer func() { + if l.logger.V(logLevel) { + l.logger.Infof("loopyWriter exiting with error: %v", err) + } + if !isIOError(err) { + l.framer.writer.Flush() + l.conn.Close() + } + l.cbuf.finish() + }() for { it, err := l.cbuf.get(true) if err != nil { @@ -581,11 +599,11 @@ func (l *loopyWriter) outgoingWindowUpdateHandler(w *outgoingWindowUpdate) error return l.framer.fr.WriteWindowUpdate(w.streamID, w.increment) } -func (l *loopyWriter) incomingWindowUpdateHandler(w *incomingWindowUpdate) error { +func (l *loopyWriter) incomingWindowUpdateHandler(w *incomingWindowUpdate) { // Otherwise update the quota. if w.streamID == 0 { l.sendQuota += w.increment - return nil + return } // Find the stream and update it. if str, ok := l.estdStreams[w.streamID]; ok { @@ -593,10 +611,9 @@ func (l *loopyWriter) incomingWindowUpdateHandler(w *incomingWindowUpdate) error if strQuota := int(l.oiws) - str.bytesOutStanding; strQuota > 0 && str.state == waitingOnStreamQuota { str.state = active l.activeStreams.enqueue(str) - return nil + return } } - return nil } func (l *loopyWriter) outgoingSettingsHandler(s *outgoingSettings) error { @@ -604,13 +621,11 @@ func (l *loopyWriter) outgoingSettingsHandler(s *outgoingSettings) error { } func (l *loopyWriter) incomingSettingsHandler(s *incomingSettings) error { - if err := l.applySettings(s.ss); err != nil { - return err - } + l.applySettings(s.ss) return l.framer.fr.WriteSettingsAck() } -func (l *loopyWriter) registerStreamHandler(h *registerStream) error { +func (l *loopyWriter) registerStreamHandler(h *registerStream) { str := &outStream{ id: h.streamID, state: empty, @@ -618,15 +633,14 @@ func (l *loopyWriter) registerStreamHandler(h *registerStream) error { wq: h.wq, } l.estdStreams[h.streamID] = str - return nil } func (l *loopyWriter) headerHandler(h *headerFrame) error { if l.side == serverSide { str, ok := l.estdStreams[h.streamID] if !ok { - if logger.V(logLevel) { - logger.Warningf("transport: loopy doesn't recognize the stream: %d", h.streamID) + if l.logger.V(logLevel) { + l.logger.Infof("Unrecognized streamID %d in loopyWriter", h.streamID) } return nil } @@ -681,8 +695,8 @@ func (l *loopyWriter) writeHeader(streamID uint32, endStream bool, hf []hpack.He l.hBuf.Reset() for _, f := range hf { if err := l.hEnc.WriteField(f); err != nil { - if logger.V(logLevel) { - logger.Warningf("transport: loopyWriter.writeHeader encountered error while encoding headers: %v", err) + if l.logger.V(logLevel) { + l.logger.Warningf("Encountered error while encoding headers: %v", err) } } } @@ -720,10 +734,10 @@ func (l *loopyWriter) writeHeader(streamID uint32, endStream bool, hf []hpack.He return nil } -func (l *loopyWriter) preprocessData(df *dataFrame) error { +func (l *loopyWriter) preprocessData(df *dataFrame) { str, ok := l.estdStreams[df.streamID] if !ok { - return nil + return } // If we got data for a stream it means that // stream was originated and the headers were sent out. @@ -732,7 +746,6 @@ func (l *loopyWriter) preprocessData(df *dataFrame) error { str.state = active l.activeStreams.enqueue(str) } - return nil } func (l *loopyWriter) pingHandler(p *ping) error { @@ -743,9 +756,8 @@ func (l *loopyWriter) pingHandler(p *ping) error { } -func (l *loopyWriter) outFlowControlSizeRequestHandler(o *outFlowControlSizeRequest) error { +func (l *loopyWriter) outFlowControlSizeRequestHandler(o *outFlowControlSizeRequest) { o.resp <- l.sendQuota - return nil } func (l *loopyWriter) cleanupStreamHandler(c *cleanupStream) error { @@ -763,6 +775,7 @@ func (l *loopyWriter) cleanupStreamHandler(c *cleanupStream) error { } } if l.draining && len(l.estdStreams) == 0 { + // Flush and close the connection; we are done with it. return errors.New("finished processing active streams while in draining mode") } return nil @@ -798,6 +811,7 @@ func (l *loopyWriter) incomingGoAwayHandler(*incomingGoAway) error { if l.side == clientSide { l.draining = true if len(l.estdStreams) == 0 { + // Flush and close the connection; we are done with it. return errors.New("received GOAWAY with no active streams") } } @@ -816,17 +830,10 @@ func (l *loopyWriter) goAwayHandler(g *goAway) error { return nil } -func (l *loopyWriter) closeConnectionHandler() error { - // Exit loopyWriter entirely by returning an error here. This will lead to - // the transport closing the connection, and, ultimately, transport - // closure. - return ErrConnClosing -} - func (l *loopyWriter) handle(i interface{}) error { switch i := i.(type) { case *incomingWindowUpdate: - return l.incomingWindowUpdateHandler(i) + l.incomingWindowUpdateHandler(i) case *outgoingWindowUpdate: return l.outgoingWindowUpdateHandler(i) case *incomingSettings: @@ -836,7 +843,7 @@ func (l *loopyWriter) handle(i interface{}) error { case *headerFrame: return l.headerHandler(i) case *registerStream: - return l.registerStreamHandler(i) + l.registerStreamHandler(i) case *cleanupStream: return l.cleanupStreamHandler(i) case *earlyAbortStream: @@ -844,21 +851,24 @@ func (l *loopyWriter) handle(i interface{}) error { case *incomingGoAway: return l.incomingGoAwayHandler(i) case *dataFrame: - return l.preprocessData(i) + l.preprocessData(i) case *ping: return l.pingHandler(i) case *goAway: return l.goAwayHandler(i) case *outFlowControlSizeRequest: - return l.outFlowControlSizeRequestHandler(i) + l.outFlowControlSizeRequestHandler(i) case closeConnection: - return l.closeConnectionHandler() + // Just return a non-I/O error and run() will flush and close the + // connection. + return ErrConnClosing default: return fmt.Errorf("transport: unknown control message type %T", i) } + return nil } -func (l *loopyWriter) applySettings(ss []http2.Setting) error { +func (l *loopyWriter) applySettings(ss []http2.Setting) { for _, s := range ss { switch s.ID { case http2.SettingInitialWindowSize: @@ -877,7 +887,6 @@ func (l *loopyWriter) applySettings(ss []http2.Setting) error { updateHeaderTblSize(l.hEnc, s.Val) } } - return nil } // processData removes the first stream from active streams, writes out at most 16KB @@ -911,7 +920,7 @@ func (l *loopyWriter) processData() (bool, error) { return false, err } if err := l.cleanupStreamHandler(trailer.cleanup); err != nil { - return false, nil + return false, err } } else { l.activeStreams.enqueue(str) diff --git a/vendor/google.golang.org/grpc/internal/transport/handler_server.go b/vendor/google.golang.org/grpc/internal/transport/handler_server.go index e6626bf96e7..fbee581b866 100644 --- a/vendor/google.golang.org/grpc/internal/transport/handler_server.go +++ b/vendor/google.golang.org/grpc/internal/transport/handler_server.go @@ -39,6 +39,7 @@ import ( "golang.org/x/net/http2" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" + "google.golang.org/grpc/internal/grpclog" "google.golang.org/grpc/internal/grpcutil" "google.golang.org/grpc/metadata" "google.golang.org/grpc/peer" @@ -83,6 +84,7 @@ func NewServerHandlerTransport(w http.ResponseWriter, r *http.Request, stats []s contentSubtype: contentSubtype, stats: stats, } + st.logger = prefixLoggerForServerHandlerTransport(st) if v := r.Header.Get("grpc-timeout"); v != "" { to, err := decodeTimeout(v) @@ -150,13 +152,14 @@ type serverHandlerTransport struct { // TODO make sure this is consistent across handler_server and http2_server contentSubtype string - stats []stats.Handler + stats []stats.Handler + logger *grpclog.PrefixLogger } func (ht *serverHandlerTransport) Close(err error) { ht.closeOnce.Do(func() { - if logger.V(logLevel) { - logger.Infof("Closing serverHandlerTransport: %v", err) + if ht.logger.V(logLevel) { + ht.logger.Infof("Closing: %v", err) } close(ht.closedCh) }) diff --git a/vendor/google.golang.org/grpc/internal/transport/http2_client.go b/vendor/google.golang.org/grpc/internal/transport/http2_client.go index 79ee8aea0a2..5216998a88b 100644 --- a/vendor/google.golang.org/grpc/internal/transport/http2_client.go +++ b/vendor/google.golang.org/grpc/internal/transport/http2_client.go @@ -38,6 +38,7 @@ import ( "google.golang.org/grpc/credentials" "google.golang.org/grpc/internal/channelz" icredentials "google.golang.org/grpc/internal/credentials" + "google.golang.org/grpc/internal/grpclog" "google.golang.org/grpc/internal/grpcsync" "google.golang.org/grpc/internal/grpcutil" imetadata "google.golang.org/grpc/internal/metadata" @@ -145,6 +146,7 @@ type http2Client struct { bufferPool *bufferPool connectionID uint64 + logger *grpclog.PrefixLogger } func dial(ctx context.Context, fn func(context.Context, string) (net.Conn, error), addr resolver.Address, useProxy bool, grpcUA string) (net.Conn, error) { @@ -244,7 +246,7 @@ func newHTTP2Client(connectCtx, ctx context.Context, addr resolver.Address, opts if err := connectCtx.Err(); err != nil { // connectCtx expired before exiting the function. Hard close the connection. if logger.V(logLevel) { - logger.Infof("newClientTransport: aborting due to connectCtx: %v", err) + logger.Infof("Aborting due to connect deadline expiring: %v", err) } conn.Close() } @@ -346,6 +348,7 @@ func newHTTP2Client(connectCtx, ctx context.Context, addr resolver.Address, opts bufferPool: newBufferPool(), onClose: onClose, } + t.logger = prefixLoggerForClientTransport(t) // Add peer information to the http2client context. t.ctx = peer.NewContext(t.ctx, t.getPeer()) @@ -444,15 +447,8 @@ func newHTTP2Client(connectCtx, ctx context.Context, addr resolver.Address, opts return nil, err } go func() { - t.loopy = newLoopyWriter(clientSide, t.framer, t.controlBuf, t.bdpEst) - err := t.loopy.run() - if logger.V(logLevel) { - logger.Infof("transport: loopyWriter exited. Closing connection. Err: %v", err) - } - // Do not close the transport. Let reader goroutine handle it since - // there might be data in the buffers. - t.conn.Close() - t.controlBuf.finish() + t.loopy = newLoopyWriter(clientSide, t.framer, t.controlBuf, t.bdpEst, t.conn, t.logger) + t.loopy.run() close(t.writerDone) }() return t, nil @@ -789,7 +785,7 @@ func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (*Stream, s.id = h.streamID s.fc = &inFlow{limit: uint32(t.initialWindowSize)} t.mu.Lock() - if t.activeStreams == nil { // Can be niled from Close(). + if t.state == draining || t.activeStreams == nil { // Can be niled from Close(). t.mu.Unlock() return false // Don't create a stream if the transport is already closed. } @@ -866,8 +862,8 @@ func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (*Stream, } } if transportDrainRequired { - if logger.V(logLevel) { - logger.Infof("transport: t.nextID > MaxStreamID. Draining") + if t.logger.V(logLevel) { + t.logger.Infof("Draining transport: t.nextID > MaxStreamID") } t.GracefulClose() } @@ -959,8 +955,8 @@ func (t *http2Client) Close(err error) { t.mu.Unlock() return } - if logger.V(logLevel) { - logger.Infof("transport: closing: %v", err) + if t.logger.V(logLevel) { + t.logger.Infof("Closing: %v", err) } // Call t.onClose ASAP to prevent the client from attempting to create new // streams. @@ -1016,8 +1012,8 @@ func (t *http2Client) GracefulClose() { t.mu.Unlock() return } - if logger.V(logLevel) { - logger.Infof("transport: GracefulClose called") + if t.logger.V(logLevel) { + t.logger.Infof("GracefulClose called") } t.onClose(GoAwayInvalid) t.state = draining @@ -1181,8 +1177,8 @@ func (t *http2Client) handleRSTStream(f *http2.RSTStreamFrame) { } statusCode, ok := http2ErrConvTab[f.ErrCode] if !ok { - if logger.V(logLevel) { - logger.Warningf("transport: http2Client.handleRSTStream found no mapped gRPC status for the received http2 error: %v", f.ErrCode) + if t.logger.V(logLevel) { + t.logger.Infof("Received a RST_STREAM frame with code %q, but found no mapped gRPC status", f.ErrCode) } statusCode = codes.Unknown } @@ -1264,10 +1260,12 @@ func (t *http2Client) handleGoAway(f *http2.GoAwayFrame) { t.mu.Unlock() return } - if f.ErrCode == http2.ErrCodeEnhanceYourCalm { - if logger.V(logLevel) { - logger.Infof("Client received GoAway with http2.ErrCodeEnhanceYourCalm.") - } + if f.ErrCode == http2.ErrCodeEnhanceYourCalm && string(f.DebugData()) == "too_many_pings" { + // When a client receives a GOAWAY with error code ENHANCE_YOUR_CALM and debug + // data equal to ASCII "too_many_pings", it should log the occurrence at a log level that is + // enabled by default and double the configure KEEPALIVE_TIME used for new connections + // on that channel. + logger.Errorf("Client received GoAway with error code ENHANCE_YOUR_CALM and debug data equal to ASCII \"too_many_pings\".") } id := f.LastStreamID if id > 0 && id%2 == 0 { diff --git a/vendor/google.golang.org/grpc/internal/transport/http2_server.go b/vendor/google.golang.org/grpc/internal/transport/http2_server.go index bc3da706726..4b406b8cb01 100644 --- a/vendor/google.golang.org/grpc/internal/transport/http2_server.go +++ b/vendor/google.golang.org/grpc/internal/transport/http2_server.go @@ -35,7 +35,9 @@ import ( "github.com/golang/protobuf/proto" "golang.org/x/net/http2" "golang.org/x/net/http2/hpack" + "google.golang.org/grpc/internal/grpclog" "google.golang.org/grpc/internal/grpcutil" + "google.golang.org/grpc/internal/pretty" "google.golang.org/grpc/internal/syscall" "google.golang.org/grpc/codes" @@ -129,6 +131,8 @@ type http2Server struct { // This lock may not be taken if mu is already held. maxStreamMu sync.Mutex maxStreamID uint32 // max stream ID ever seen + + logger *grpclog.PrefixLogger } // NewServerTransport creates a http2 transport with conn and configuration @@ -267,6 +271,7 @@ func NewServerTransport(conn net.Conn, config *ServerConfig) (_ ServerTransport, czData: new(channelzData), bufferPool: newBufferPool(), } + t.logger = prefixLoggerForServerTransport(t) // Add peer information to the http2server context. t.ctx = peer.NewContext(t.ctx, t.getPeer()) @@ -331,14 +336,9 @@ func NewServerTransport(conn net.Conn, config *ServerConfig) (_ ServerTransport, t.handleSettings(sf) go func() { - t.loopy = newLoopyWriter(serverSide, t.framer, t.controlBuf, t.bdpEst) + t.loopy = newLoopyWriter(serverSide, t.framer, t.controlBuf, t.bdpEst, t.conn, t.logger) t.loopy.ssGoAwayHandler = t.outgoingGoAwayHandler - err := t.loopy.run() - if logger.V(logLevel) { - logger.Infof("transport: loopyWriter exited. Closing connection. Err: %v", err) - } - t.conn.Close() - t.controlBuf.finish() + t.loopy.run() close(t.writerDone) }() go t.keepalive() @@ -383,7 +383,7 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( // if false, content-type was missing or invalid isGRPC = false contentType = "" - mdata = make(map[string][]string) + mdata = make(metadata.MD, len(frame.Fields)) httpMethod string // these are set if an error is encountered while parsing the headers protocolError bool @@ -404,6 +404,17 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( mdata[hf.Name] = append(mdata[hf.Name], hf.Value) s.contentSubtype = contentSubtype isGRPC = true + + case "grpc-accept-encoding": + mdata[hf.Name] = append(mdata[hf.Name], hf.Value) + if hf.Value == "" { + continue + } + compressors := hf.Value + if s.clientAdvertisedCompressors != "" { + compressors = s.clientAdvertisedCompressors + "," + compressors + } + s.clientAdvertisedCompressors = compressors case "grpc-encoding": s.recvCompress = hf.Value case ":method": @@ -419,8 +430,8 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( // "Transports must consider requests containing the Connection header // as malformed." - A41 case "connection": - if logger.V(logLevel) { - logger.Errorf("transport: http2Server.operateHeaders parsed a :connection header which makes a request malformed as per the HTTP/2 spec") + if t.logger.V(logLevel) { + t.logger.Infof("Received a HEADERS frame with a :connection header which makes the request malformed, as per the HTTP/2 spec") } protocolError = true default: @@ -430,7 +441,7 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( v, err := decodeMetadataHeader(hf.Name, hf.Value) if err != nil { headerError = status.Newf(codes.Internal, "malformed binary metadata %q in header %q: %v", hf.Value, hf.Name, err) - logger.Warningf("Failed to decode metadata header (%q, %q): %v", hf.Name, hf.Value, err) + t.logger.Warningf("Failed to decode metadata header (%q, %q): %v", hf.Name, hf.Value, err) break } mdata[hf.Name] = append(mdata[hf.Name], v) @@ -444,8 +455,8 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( // error, this takes precedence over a client not speaking gRPC. if len(mdata[":authority"]) > 1 || len(mdata["host"]) > 1 { errMsg := fmt.Sprintf("num values of :authority: %v, num values of host: %v, both must only have 1 value as per HTTP/2 spec", len(mdata[":authority"]), len(mdata["host"])) - if logger.V(logLevel) { - logger.Errorf("transport: %v", errMsg) + if t.logger.V(logLevel) { + t.logger.Infof("Aborting the stream early: %v", errMsg) } t.controlBuf.put(&earlyAbortStream{ httpStatus: http.StatusBadRequest, @@ -539,9 +550,9 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( } if httpMethod != http.MethodPost { t.mu.Unlock() - errMsg := fmt.Sprintf("http2Server.operateHeaders parsed a :method field: %v which should be POST", httpMethod) - if logger.V(logLevel) { - logger.Infof("transport: %v", errMsg) + errMsg := fmt.Sprintf("Received a HEADERS frame with :method %q which should be POST", httpMethod) + if t.logger.V(logLevel) { + t.logger.Infof("Aborting the stream early: %v", errMsg) } t.controlBuf.put(&earlyAbortStream{ httpStatus: 405, @@ -557,8 +568,8 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( var err error if s.ctx, err = t.inTapHandle(s.ctx, &tap.Info{FullMethodName: s.method}); err != nil { t.mu.Unlock() - if logger.V(logLevel) { - logger.Infof("transport: http2Server.operateHeaders got an error from InTapHandle: %v", err) + if t.logger.V(logLevel) { + t.logger.Infof("Aborting the stream early due to InTapHandle failure: %v", err) } stat, ok := status.FromError(err) if !ok { @@ -595,7 +606,7 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( LocalAddr: t.localAddr, Compression: s.recvCompress, WireLength: int(frame.Header().Length), - Header: metadata.MD(mdata).Copy(), + Header: mdata.Copy(), } sh.HandleRPC(s.ctx, inHeader) } @@ -632,8 +643,8 @@ func (t *http2Server) HandleStreams(handle func(*Stream), traceCtx func(context. atomic.StoreInt64(&t.lastRead, time.Now().UnixNano()) if err != nil { if se, ok := err.(http2.StreamError); ok { - if logger.V(logLevel) { - logger.Warningf("transport: http2Server.HandleStreams encountered http2.StreamError: %v", se) + if t.logger.V(logLevel) { + t.logger.Warningf("Encountered http2.StreamError: %v", se) } t.mu.Lock() s := t.activeStreams[se.StreamID] @@ -676,8 +687,8 @@ func (t *http2Server) HandleStreams(handle func(*Stream), traceCtx func(context. case *http2.GoAwayFrame: // TODO: Handle GoAway from the client appropriately. default: - if logger.V(logLevel) { - logger.Errorf("transport: http2Server.HandleStreams found unhandled frame type %v.", frame) + if t.logger.V(logLevel) { + t.logger.Infof("Received unsupported frame type %T", frame) } } } @@ -936,8 +947,8 @@ func (t *http2Server) checkForHeaderListSize(it interface{}) bool { var sz int64 for _, f := range hdrFrame.hf { if sz += int64(f.Size()); sz > int64(*t.maxSendHeaderListSize) { - if logger.V(logLevel) { - logger.Errorf("header list size to send violates the maximum size (%d bytes) set by client", *t.maxSendHeaderListSize) + if t.logger.V(logLevel) { + t.logger.Infof("Header list size to send violates the maximum size (%d bytes) set by client", *t.maxSendHeaderListSize) } return false } @@ -1050,7 +1061,7 @@ func (t *http2Server) WriteStatus(s *Stream, st *status.Status) error { stBytes, err := proto.Marshal(p) if err != nil { // TODO: return error instead, when callers are able to handle it. - logger.Errorf("transport: failed to marshal rpc status: %v, error: %v", p, err) + t.logger.Errorf("Failed to marshal rpc status: %s, error: %v", pretty.ToJSON(p), err) } else { headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-status-details-bin", Value: encodeBinHeader(stBytes)}) } @@ -1165,8 +1176,8 @@ func (t *http2Server) keepalive() { select { case <-ageTimer.C: // Close the connection after grace period. - if logger.V(logLevel) { - logger.Infof("transport: closing server transport due to maximum connection age.") + if t.logger.V(logLevel) { + t.logger.Infof("Closing server transport due to maximum connection age") } t.controlBuf.put(closeConnection{}) case <-t.done: @@ -1217,8 +1228,8 @@ func (t *http2Server) Close(err error) { t.mu.Unlock() return } - if logger.V(logLevel) { - logger.Infof("transport: closing: %v", err) + if t.logger.V(logLevel) { + t.logger.Infof("Closing: %v", err) } t.state = closing streams := t.activeStreams @@ -1226,8 +1237,8 @@ func (t *http2Server) Close(err error) { t.mu.Unlock() t.controlBuf.finish() close(t.done) - if err := t.conn.Close(); err != nil && logger.V(logLevel) { - logger.Infof("transport: error closing conn during Close: %v", err) + if err := t.conn.Close(); err != nil && t.logger.V(logLevel) { + t.logger.Infof("Error closing underlying net.Conn during Close: %v", err) } channelz.RemoveEntry(t.channelzID) // Cancel all active streams. @@ -1344,9 +1355,6 @@ func (t *http2Server) outgoingGoAwayHandler(g *goAway) (bool, error) { return false, err } if retErr != nil { - // Abruptly close the connection following the GoAway (via - // loopywriter). But flush out what's inside the buffer first. - t.framer.writer.Flush() return false, retErr } return true, nil diff --git a/vendor/google.golang.org/grpc/internal/transport/http_util.go b/vendor/google.golang.org/grpc/internal/transport/http_util.go index 2c601a864d9..19cbb18f5ab 100644 --- a/vendor/google.golang.org/grpc/internal/transport/http_util.go +++ b/vendor/google.golang.org/grpc/internal/transport/http_util.go @@ -21,6 +21,7 @@ package transport import ( "bufio" "encoding/base64" + "errors" "fmt" "io" "math" @@ -37,7 +38,6 @@ import ( "golang.org/x/net/http2/hpack" spb "google.golang.org/genproto/googleapis/rpc/status" "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" "google.golang.org/grpc/status" ) @@ -85,7 +85,6 @@ var ( // 504 Gateway timeout - UNAVAILABLE. http.StatusGatewayTimeout: codes.Unavailable, } - logger = grpclog.Component("transport") ) // isReservedHeader checks whether hdr belongs to HTTP2 headers @@ -330,7 +329,8 @@ func (w *bufWriter) Write(b []byte) (n int, err error) { return 0, w.err } if w.batchSize == 0 { // Buffer has been disabled. - return w.conn.Write(b) + n, err = w.conn.Write(b) + return n, toIOError(err) } for len(b) > 0 { nn := copy(w.buf[w.offset:], b) @@ -352,10 +352,30 @@ func (w *bufWriter) Flush() error { return nil } _, w.err = w.conn.Write(w.buf[:w.offset]) + w.err = toIOError(w.err) w.offset = 0 return w.err } +type ioError struct { + error +} + +func (i ioError) Unwrap() error { + return i.error +} + +func isIOError(err error) bool { + return errors.As(err, &ioError{}) +} + +func toIOError(err error) error { + if err == nil { + return nil + } + return ioError{error: err} +} + type framer struct { writer *bufWriter fr *http2.Framer diff --git a/vendor/google.golang.org/grpc/internal/transport/logging.go b/vendor/google.golang.org/grpc/internal/transport/logging.go new file mode 100644 index 00000000000..42ed2b07af6 --- /dev/null +++ b/vendor/google.golang.org/grpc/internal/transport/logging.go @@ -0,0 +1,40 @@ +/* + * + * Copyright 2023 gRPC authors. + * + * 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 transport + +import ( + "fmt" + + "google.golang.org/grpc/grpclog" + internalgrpclog "google.golang.org/grpc/internal/grpclog" +) + +var logger = grpclog.Component("transport") + +func prefixLoggerForServerTransport(p *http2Server) *internalgrpclog.PrefixLogger { + return internalgrpclog.NewPrefixLogger(logger, fmt.Sprintf("[server-transport %p] ", p)) +} + +func prefixLoggerForServerHandlerTransport(p *serverHandlerTransport) *internalgrpclog.PrefixLogger { + return internalgrpclog.NewPrefixLogger(logger, fmt.Sprintf("[server-handler-transport %p] ", p)) +} + +func prefixLoggerForClientTransport(p *http2Client) *internalgrpclog.PrefixLogger { + return internalgrpclog.NewPrefixLogger(logger, fmt.Sprintf("[client-transport %p] ", p)) +} diff --git a/vendor/google.golang.org/grpc/internal/transport/transport.go b/vendor/google.golang.org/grpc/internal/transport/transport.go index 0ac77ea4f8c..1b7d7fabc51 100644 --- a/vendor/google.golang.org/grpc/internal/transport/transport.go +++ b/vendor/google.golang.org/grpc/internal/transport/transport.go @@ -257,6 +257,9 @@ type Stream struct { fc *inFlow wq *writeQuota + // Holds compressor names passed in grpc-accept-encoding metadata from the + // client. This is empty for the client side stream. + clientAdvertisedCompressors string // Callback to state application's intentions to read data. This // is used to adjust flow control, if needed. requestRead func(int) @@ -345,8 +348,24 @@ func (s *Stream) RecvCompress() string { } // SetSendCompress sets the compression algorithm to the stream. -func (s *Stream) SetSendCompress(str string) { - s.sendCompress = str +func (s *Stream) SetSendCompress(name string) error { + if s.isHeaderSent() || s.getState() == streamDone { + return errors.New("transport: set send compressor called after headers sent or stream done") + } + + s.sendCompress = name + return nil +} + +// SendCompress returns the send compressor name. +func (s *Stream) SendCompress() string { + return s.sendCompress +} + +// ClientAdvertisedCompressors returns the compressor names advertised by the +// client via grpc-accept-encoding header. +func (s *Stream) ClientAdvertisedCompressors() string { + return s.clientAdvertisedCompressors } // Done returns a channel which is closed when it receives the final status diff --git a/vendor/google.golang.org/grpc/metadata/metadata.go b/vendor/google.golang.org/grpc/metadata/metadata.go index fb4a88f59bd..a2cdcaf12a8 100644 --- a/vendor/google.golang.org/grpc/metadata/metadata.go +++ b/vendor/google.golang.org/grpc/metadata/metadata.go @@ -91,7 +91,11 @@ func (md MD) Len() int { // Copy returns a copy of md. func (md MD) Copy() MD { - return Join(md) + out := make(MD, len(md)) + for k, v := range md { + out[k] = copyOf(v) + } + return out } // Get obtains the values for a given key. @@ -171,8 +175,11 @@ func AppendToOutgoingContext(ctx context.Context, kv ...string) context.Context md, _ := ctx.Value(mdOutgoingKey{}).(rawMD) added := make([][]string, len(md.added)+1) copy(added, md.added) - added[len(added)-1] = make([]string, len(kv)) - copy(added[len(added)-1], kv) + kvCopy := make([]string, 0, len(kv)) + for i := 0; i < len(kv); i += 2 { + kvCopy = append(kvCopy, strings.ToLower(kv[i]), kv[i+1]) + } + added[len(added)-1] = kvCopy return context.WithValue(ctx, mdOutgoingKey{}, rawMD{md: md.md, added: added}) } diff --git a/vendor/google.golang.org/grpc/resolver/resolver.go b/vendor/google.golang.org/grpc/resolver/resolver.go index 654e9ce69f4..6215e5ef2b0 100644 --- a/vendor/google.golang.org/grpc/resolver/resolver.go +++ b/vendor/google.golang.org/grpc/resolver/resolver.go @@ -41,8 +41,9 @@ var ( // TODO(bar) install dns resolver in init(){}. -// Register registers the resolver builder to the resolver map. b.Scheme will be -// used as the scheme registered with this builder. +// Register registers the resolver builder to the resolver map. b.Scheme will +// be used as the scheme registered with this builder. The registry is case +// sensitive, and schemes should not contain any uppercase characters. // // NOTE: this function must only be called during initialization time (i.e. in // an init() function), and is not thread-safe. If multiple Resolvers are @@ -203,6 +204,15 @@ type State struct { // gRPC to add new methods to this interface. type ClientConn interface { // UpdateState updates the state of the ClientConn appropriately. + // + // If an error is returned, the resolver should try to resolve the + // target again. The resolver should use a backoff timer to prevent + // overloading the server with requests. If a resolver is certain that + // reresolving will not change the result, e.g. because it is + // a watch-based resolver, returned errors can be ignored. + // + // If the resolved State is the same as the last reported one, calling + // UpdateState can be omitted. UpdateState(State) error // ReportError notifies the ClientConn that the Resolver encountered an // error. The ClientConn will notify the load balancer and begin calling @@ -280,8 +290,10 @@ type Builder interface { // gRPC dial calls Build synchronously, and fails if the returned error is // not nil. Build(target Target, cc ClientConn, opts BuildOptions) (Resolver, error) - // Scheme returns the scheme supported by this resolver. - // Scheme is defined at https://github.com/grpc/grpc/blob/master/doc/naming.md. + // Scheme returns the scheme supported by this resolver. Scheme is defined + // at https://github.com/grpc/grpc/blob/master/doc/naming.md. The returned + // string should not contain uppercase characters, as they will not match + // the parsed target's scheme as defined in RFC 3986. Scheme() string } diff --git a/vendor/google.golang.org/grpc/rpc_util.go b/vendor/google.golang.org/grpc/rpc_util.go index cb7020ebecd..2030736a306 100644 --- a/vendor/google.golang.org/grpc/rpc_util.go +++ b/vendor/google.golang.org/grpc/rpc_util.go @@ -159,6 +159,7 @@ type callInfo struct { contentSubtype string codec baseCodec maxRetryRPCBufferSize int + onFinish []func(err error) } func defaultCallInfo() *callInfo { @@ -295,6 +296,41 @@ func (o FailFastCallOption) before(c *callInfo) error { } func (o FailFastCallOption) after(c *callInfo, attempt *csAttempt) {} +// OnFinish returns a CallOption that configures a callback to be called when +// the call completes. The error passed to the callback is the status of the +// RPC, and may be nil. The onFinish callback provided will only be called once +// by gRPC. This is mainly used to be used by streaming interceptors, to be +// notified when the RPC completes along with information about the status of +// the RPC. +// +// # Experimental +// +// Notice: This API is EXPERIMENTAL and may be changed or removed in a +// later release. +func OnFinish(onFinish func(err error)) CallOption { + return OnFinishCallOption{ + OnFinish: onFinish, + } +} + +// OnFinishCallOption is CallOption that indicates a callback to be called when +// the call completes. +// +// # Experimental +// +// Notice: This type is EXPERIMENTAL and may be changed or removed in a +// later release. +type OnFinishCallOption struct { + OnFinish func(error) +} + +func (o OnFinishCallOption) before(c *callInfo) error { + c.onFinish = append(c.onFinish, o.OnFinish) + return nil +} + +func (o OnFinishCallOption) after(c *callInfo, attempt *csAttempt) {} + // MaxCallRecvMsgSize returns a CallOption which sets the maximum message size // in bytes the client can receive. If this is not set, gRPC uses the default // 4MB. @@ -658,12 +694,13 @@ func msgHeader(data, compData []byte) (hdr []byte, payload []byte) { func outPayload(client bool, msg interface{}, data, payload []byte, t time.Time) *stats.OutPayload { return &stats.OutPayload{ - Client: client, - Payload: msg, - Data: data, - Length: len(data), - WireLength: len(payload) + headerLen, - SentTime: t, + Client: client, + Payload: msg, + Data: data, + Length: len(data), + WireLength: len(payload) + headerLen, + CompressedLength: len(payload), + SentTime: t, } } @@ -684,7 +721,7 @@ func checkRecvPayload(pf payloadFormat, recvCompress string, haveCompressor bool } type payloadInfo struct { - wireLength int // The compressed length got from wire. + compressedLength int // The compressed length got from wire. uncompressedBytes []byte } @@ -694,7 +731,7 @@ func recvAndDecompress(p *parser, s *transport.Stream, dc Decompressor, maxRecei return nil, err } if payInfo != nil { - payInfo.wireLength = len(d) + payInfo.compressedLength = len(d) } if st := checkRecvPayload(pf, s.RecvCompress(), compressor != nil || dc != nil); st != nil { diff --git a/vendor/google.golang.org/grpc/server.go b/vendor/google.golang.org/grpc/server.go index d5a6e78be44..76d152a69c8 100644 --- a/vendor/google.golang.org/grpc/server.go +++ b/vendor/google.golang.org/grpc/server.go @@ -43,8 +43,8 @@ import ( "google.golang.org/grpc/internal" "google.golang.org/grpc/internal/binarylog" "google.golang.org/grpc/internal/channelz" - "google.golang.org/grpc/internal/grpcrand" "google.golang.org/grpc/internal/grpcsync" + "google.golang.org/grpc/internal/grpcutil" "google.golang.org/grpc/internal/transport" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/metadata" @@ -74,10 +74,10 @@ func init() { srv.drainServerTransports(addr) } internal.AddGlobalServerOptions = func(opt ...ServerOption) { - extraServerOptions = append(extraServerOptions, opt...) + globalServerOptions = append(globalServerOptions, opt...) } internal.ClearGlobalServerOptions = func() { - extraServerOptions = nil + globalServerOptions = nil } internal.BinaryLogger = binaryLogger internal.JoinServerOptions = newJoinServerOption @@ -145,7 +145,7 @@ type Server struct { channelzID *channelz.Identifier czData *channelzData - serverWorkerChannels []chan *serverWorkerData + serverWorkerChannel chan *serverWorkerData } type serverOptions struct { @@ -183,7 +183,7 @@ var defaultServerOptions = serverOptions{ writeBufferSize: defaultWriteBufSize, readBufferSize: defaultReadBufSize, } -var extraServerOptions []ServerOption +var globalServerOptions []ServerOption // A ServerOption sets options such as credentials, codec and keepalive parameters, etc. type ServerOption interface { @@ -560,47 +560,45 @@ func NumStreamWorkers(numServerWorkers uint32) ServerOption { const serverWorkerResetThreshold = 1 << 16 // serverWorkers blocks on a *transport.Stream channel forever and waits for -// data to be fed by serveStreams. This allows different requests to be +// data to be fed by serveStreams. This allows multiple requests to be // processed by the same goroutine, removing the need for expensive stack // re-allocations (see the runtime.morestack problem [1]). // // [1] https://github.com/golang/go/issues/18138 -func (s *Server) serverWorker(ch chan *serverWorkerData) { - // To make sure all server workers don't reset at the same time, choose a - // random number of iterations before resetting. - threshold := serverWorkerResetThreshold + grpcrand.Intn(serverWorkerResetThreshold) - for completed := 0; completed < threshold; completed++ { - data, ok := <-ch +func (s *Server) serverWorker() { + for completed := 0; completed < serverWorkerResetThreshold; completed++ { + data, ok := <-s.serverWorkerChannel if !ok { return } - s.handleStream(data.st, data.stream, s.traceInfo(data.st, data.stream)) - data.wg.Done() + s.handleSingleStream(data) } - go s.serverWorker(ch) + go s.serverWorker() } -// initServerWorkers creates worker goroutines and channels to process incoming +func (s *Server) handleSingleStream(data *serverWorkerData) { + defer data.wg.Done() + s.handleStream(data.st, data.stream, s.traceInfo(data.st, data.stream)) +} + +// initServerWorkers creates worker goroutines and a channel to process incoming // connections to reduce the time spent overall on runtime.morestack. func (s *Server) initServerWorkers() { - s.serverWorkerChannels = make([]chan *serverWorkerData, s.opts.numServerWorkers) + s.serverWorkerChannel = make(chan *serverWorkerData) for i := uint32(0); i < s.opts.numServerWorkers; i++ { - s.serverWorkerChannels[i] = make(chan *serverWorkerData) - go s.serverWorker(s.serverWorkerChannels[i]) + go s.serverWorker() } } func (s *Server) stopServerWorkers() { - for i := uint32(0); i < s.opts.numServerWorkers; i++ { - close(s.serverWorkerChannels[i]) - } + close(s.serverWorkerChannel) } // NewServer creates a gRPC server which has no service registered and has not // started to accept requests yet. func NewServer(opt ...ServerOption) *Server { opts := defaultServerOptions - for _, o := range extraServerOptions { + for _, o := range globalServerOptions { o.apply(&opts) } for _, o := range opt { @@ -945,26 +943,21 @@ func (s *Server) serveStreams(st transport.ServerTransport) { defer st.Close(errors.New("finished serving streams for the server transport")) var wg sync.WaitGroup - var roundRobinCounter uint32 st.HandleStreams(func(stream *transport.Stream) { wg.Add(1) if s.opts.numServerWorkers > 0 { data := &serverWorkerData{st: st, wg: &wg, stream: stream} select { - case s.serverWorkerChannels[atomic.AddUint32(&roundRobinCounter, 1)%s.opts.numServerWorkers] <- data: + case s.serverWorkerChannel <- data: + return default: // If all stream workers are busy, fallback to the default code path. - go func() { - s.handleStream(st, stream, s.traceInfo(st, stream)) - wg.Done() - }() } - } else { - go func() { - defer wg.Done() - s.handleStream(st, stream, s.traceInfo(st, stream)) - }() } + go func() { + defer wg.Done() + s.handleStream(st, stream, s.traceInfo(st, stream)) + }() }, func(ctx context.Context, method string) context.Context { if !EnableTracing { return ctx @@ -1252,7 +1245,7 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. logEntry.PeerAddr = peer.Addr } for _, binlog := range binlogs { - binlog.Log(logEntry) + binlog.Log(ctx, logEntry) } } @@ -1263,6 +1256,7 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. var comp, decomp encoding.Compressor var cp Compressor var dc Decompressor + var sendCompressorName string // If dc is set and matches the stream's compression, use it. Otherwise, try // to find a matching registered compressor for decomp. @@ -1283,12 +1277,18 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. // NOTE: this needs to be ahead of all handling, https://github.com/grpc/grpc-go/issues/686. if s.opts.cp != nil { cp = s.opts.cp - stream.SetSendCompress(cp.Type()) + sendCompressorName = cp.Type() } else if rc := stream.RecvCompress(); rc != "" && rc != encoding.Identity { // Legacy compressor not specified; attempt to respond with same encoding. comp = encoding.GetCompressor(rc) if comp != nil { - stream.SetSendCompress(rc) + sendCompressorName = comp.Name() + } + } + + if sendCompressorName != "" { + if err := stream.SetSendCompress(sendCompressorName); err != nil { + return status.Errorf(codes.Internal, "grpc: failed to set send compressor: %v", err) } } @@ -1312,11 +1312,12 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. } for _, sh := range shs { sh.HandleRPC(stream.Context(), &stats.InPayload{ - RecvTime: time.Now(), - Payload: v, - WireLength: payInfo.wireLength + headerLen, - Data: d, - Length: len(d), + RecvTime: time.Now(), + Payload: v, + Length: len(d), + WireLength: payInfo.compressedLength + headerLen, + CompressedLength: payInfo.compressedLength, + Data: d, }) } if len(binlogs) != 0 { @@ -1324,7 +1325,7 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. Message: d, } for _, binlog := range binlogs { - binlog.Log(cm) + binlog.Log(stream.Context(), cm) } } if trInfo != nil { @@ -1357,7 +1358,7 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. Header: h, } for _, binlog := range binlogs { - binlog.Log(sh) + binlog.Log(stream.Context(), sh) } } st := &binarylog.ServerTrailer{ @@ -1365,7 +1366,7 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. Err: appErr, } for _, binlog := range binlogs { - binlog.Log(st) + binlog.Log(stream.Context(), st) } } return appErr @@ -1375,6 +1376,11 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. } opts := &transport.Options{Last: true} + // Server handler could have set new compressor by calling SetSendCompressor. + // In case it is set, we need to use it for compressing outbound message. + if stream.SendCompress() != sendCompressorName { + comp = encoding.GetCompressor(stream.SendCompress()) + } if err := s.sendResponse(t, stream, reply, cp, opts, comp); err != nil { if err == io.EOF { // The entire stream is done (for unary RPC only). @@ -1402,8 +1408,8 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. Err: appErr, } for _, binlog := range binlogs { - binlog.Log(sh) - binlog.Log(st) + binlog.Log(stream.Context(), sh) + binlog.Log(stream.Context(), st) } } return err @@ -1417,8 +1423,8 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. Message: reply, } for _, binlog := range binlogs { - binlog.Log(sh) - binlog.Log(sm) + binlog.Log(stream.Context(), sh) + binlog.Log(stream.Context(), sm) } } if channelz.IsOn() { @@ -1430,17 +1436,16 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. // TODO: Should we be logging if writing status failed here, like above? // Should the logging be in WriteStatus? Should we ignore the WriteStatus // error or allow the stats handler to see it? - err = t.WriteStatus(stream, statusOK) if len(binlogs) != 0 { st := &binarylog.ServerTrailer{ Trailer: stream.Trailer(), Err: appErr, } for _, binlog := range binlogs { - binlog.Log(st) + binlog.Log(stream.Context(), st) } } - return err + return t.WriteStatus(stream, statusOK) } // chainStreamServerInterceptors chains all stream server interceptors into one. @@ -1574,7 +1579,7 @@ func (s *Server) processStreamingRPC(t transport.ServerTransport, stream *transp logEntry.PeerAddr = peer.Addr } for _, binlog := range ss.binlogs { - binlog.Log(logEntry) + binlog.Log(stream.Context(), logEntry) } } @@ -1597,12 +1602,18 @@ func (s *Server) processStreamingRPC(t transport.ServerTransport, stream *transp // NOTE: this needs to be ahead of all handling, https://github.com/grpc/grpc-go/issues/686. if s.opts.cp != nil { ss.cp = s.opts.cp - stream.SetSendCompress(s.opts.cp.Type()) + ss.sendCompressorName = s.opts.cp.Type() } else if rc := stream.RecvCompress(); rc != "" && rc != encoding.Identity { // Legacy compressor not specified; attempt to respond with same encoding. ss.comp = encoding.GetCompressor(rc) if ss.comp != nil { - stream.SetSendCompress(rc) + ss.sendCompressorName = rc + } + } + + if ss.sendCompressorName != "" { + if err := stream.SetSendCompress(ss.sendCompressorName); err != nil { + return status.Errorf(codes.Internal, "grpc: failed to set send compressor: %v", err) } } @@ -1640,16 +1651,16 @@ func (s *Server) processStreamingRPC(t transport.ServerTransport, stream *transp ss.trInfo.tr.SetError() ss.mu.Unlock() } - t.WriteStatus(ss.s, appStatus) if len(ss.binlogs) != 0 { st := &binarylog.ServerTrailer{ Trailer: ss.s.Trailer(), Err: appErr, } for _, binlog := range ss.binlogs { - binlog.Log(st) + binlog.Log(stream.Context(), st) } } + t.WriteStatus(ss.s, appStatus) // TODO: Should we log an error from WriteStatus here and below? return appErr } @@ -1658,17 +1669,16 @@ func (s *Server) processStreamingRPC(t transport.ServerTransport, stream *transp ss.trInfo.tr.LazyLog(stringer("OK"), false) ss.mu.Unlock() } - err = t.WriteStatus(ss.s, statusOK) if len(ss.binlogs) != 0 { st := &binarylog.ServerTrailer{ Trailer: ss.s.Trailer(), Err: appErr, } for _, binlog := range ss.binlogs { - binlog.Log(st) + binlog.Log(stream.Context(), st) } } - return err + return t.WriteStatus(ss.s, statusOK) } func (s *Server) handleStream(t transport.ServerTransport, stream *transport.Stream, trInfo *traceInfo) { @@ -1935,6 +1945,60 @@ func SendHeader(ctx context.Context, md metadata.MD) error { return nil } +// SetSendCompressor sets a compressor for outbound messages from the server. +// It must not be called after any event that causes headers to be sent +// (see ServerStream.SetHeader for the complete list). Provided compressor is +// used when below conditions are met: +// +// - compressor is registered via encoding.RegisterCompressor +// - compressor name must exist in the client advertised compressor names +// sent in grpc-accept-encoding header. Use ClientSupportedCompressors to +// get client supported compressor names. +// +// The context provided must be the context passed to the server's handler. +// It must be noted that compressor name encoding.Identity disables the +// outbound compression. +// By default, server messages will be sent using the same compressor with +// which request messages were sent. +// +// It is not safe to call SetSendCompressor concurrently with SendHeader and +// SendMsg. +// +// # Experimental +// +// Notice: This function is EXPERIMENTAL and may be changed or removed in a +// later release. +func SetSendCompressor(ctx context.Context, name string) error { + stream, ok := ServerTransportStreamFromContext(ctx).(*transport.Stream) + if !ok || stream == nil { + return fmt.Errorf("failed to fetch the stream from the given context") + } + + if err := validateSendCompressor(name, stream.ClientAdvertisedCompressors()); err != nil { + return fmt.Errorf("unable to set send compressor: %w", err) + } + + return stream.SetSendCompress(name) +} + +// ClientSupportedCompressors returns compressor names advertised by the client +// via grpc-accept-encoding header. +// +// The context provided must be the context passed to the server's handler. +// +// # Experimental +// +// Notice: This function is EXPERIMENTAL and may be changed or removed in a +// later release. +func ClientSupportedCompressors(ctx context.Context) ([]string, error) { + stream, ok := ServerTransportStreamFromContext(ctx).(*transport.Stream) + if !ok || stream == nil { + return nil, fmt.Errorf("failed to fetch the stream from the given context %v", ctx) + } + + return strings.Split(stream.ClientAdvertisedCompressors(), ","), nil +} + // SetTrailer sets the trailer metadata that will be sent when an RPC returns. // When called more than once, all the provided metadata will be merged. // @@ -1969,3 +2033,22 @@ type channelzServer struct { func (c *channelzServer) ChannelzMetric() *channelz.ServerInternalMetric { return c.s.channelzMetric() } + +// validateSendCompressor returns an error when given compressor name cannot be +// handled by the server or the client based on the advertised compressors. +func validateSendCompressor(name, clientCompressors string) error { + if name == encoding.Identity { + return nil + } + + if !grpcutil.IsCompressorNameRegistered(name) { + return fmt.Errorf("compressor not registered %q", name) + } + + for _, c := range strings.Split(clientCompressors, ",") { + if c == name { + return nil // found match + } + } + return fmt.Errorf("client does not support compressor %q", name) +} diff --git a/vendor/google.golang.org/grpc/stats/stats.go b/vendor/google.golang.org/grpc/stats/stats.go index 0285dcc6a26..7a552a9b787 100644 --- a/vendor/google.golang.org/grpc/stats/stats.go +++ b/vendor/google.golang.org/grpc/stats/stats.go @@ -67,10 +67,18 @@ type InPayload struct { Payload interface{} // Data is the serialized message payload. Data []byte - // Length is the length of uncompressed data. + + // Length is the size of the uncompressed payload data. Does not include any + // framing (gRPC or HTTP/2). Length int - // WireLength is the length of data on wire (compressed, signed, encrypted). + // CompressedLength is the size of the compressed payload data. Does not + // include any framing (gRPC or HTTP/2). Same as Length if compression not + // enabled. + CompressedLength int + // WireLength is the size of the compressed payload data plus gRPC framing. + // Does not include HTTP/2 framing. WireLength int + // RecvTime is the time when the payload is received. RecvTime time.Time } @@ -129,9 +137,15 @@ type OutPayload struct { Payload interface{} // Data is the serialized message payload. Data []byte - // Length is the length of uncompressed data. + // Length is the size of the uncompressed payload data. Does not include any + // framing (gRPC or HTTP/2). Length int - // WireLength is the length of data on wire (compressed, signed, encrypted). + // CompressedLength is the size of the compressed payload data. Does not + // include any framing (gRPC or HTTP/2). Same as Length if compression not + // enabled. + CompressedLength int + // WireLength is the size of the compressed payload data plus gRPC framing. + // Does not include HTTP/2 framing. WireLength int // SentTime is the time when the payload is sent. SentTime time.Time diff --git a/vendor/google.golang.org/grpc/status/status.go b/vendor/google.golang.org/grpc/status/status.go index 623be39f26b..53910fb7c90 100644 --- a/vendor/google.golang.org/grpc/status/status.go +++ b/vendor/google.golang.org/grpc/status/status.go @@ -77,7 +77,9 @@ func FromProto(s *spb.Status) *Status { // FromError returns a Status representation of err. // // - If err was produced by this package or implements the method `GRPCStatus() -// *Status`, the appropriate Status is returned. +// *Status`, or if err wraps a type satisfying this, the appropriate Status is +// returned. For wrapped errors, the message returned contains the entire +// err.Error() text and not just the wrapped status. // // - If err is nil, a Status is returned with codes.OK and no message. // @@ -88,10 +90,15 @@ func FromError(err error) (s *Status, ok bool) { if err == nil { return nil, true } - if se, ok := err.(interface { - GRPCStatus() *Status - }); ok { - return se.GRPCStatus(), true + type grpcstatus interface{ GRPCStatus() *Status } + if gs, ok := err.(grpcstatus); ok { + return gs.GRPCStatus(), true + } + var gs grpcstatus + if errors.As(err, &gs) { + p := gs.GRPCStatus().Proto() + p.Message = err.Error() + return status.FromProto(p), true } return New(codes.Unknown, err.Error()), false } @@ -103,19 +110,16 @@ func Convert(err error) *Status { return s } -// Code returns the Code of the error if it is a Status error, codes.OK if err -// is nil, or codes.Unknown otherwise. +// Code returns the Code of the error if it is a Status error or if it wraps a +// Status error. If that is not the case, it returns codes.OK if err is nil, or +// codes.Unknown otherwise. func Code(err error) codes.Code { // Don't use FromError to avoid allocation of OK status. if err == nil { return codes.OK } - if se, ok := err.(interface { - GRPCStatus() *Status - }); ok { - return se.GRPCStatus().Code() - } - return codes.Unknown + + return Convert(err).Code() } // FromContextError converts a context error or wrapped context error into a diff --git a/vendor/google.golang.org/grpc/stream.go b/vendor/google.golang.org/grpc/stream.go index 93231af2ac5..d1226a4120f 100644 --- a/vendor/google.golang.org/grpc/stream.go +++ b/vendor/google.golang.org/grpc/stream.go @@ -168,10 +168,19 @@ func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, meth } func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error) { - if md, _, ok := metadata.FromOutgoingContextRaw(ctx); ok { + if md, added, ok := metadata.FromOutgoingContextRaw(ctx); ok { + // validate md if err := imetadata.Validate(md); err != nil { return nil, status.Error(codes.Internal, err.Error()) } + // validate added + for _, kvs := range added { + for i := 0; i < len(kvs); i += 2 { + if err := imetadata.ValidatePair(kvs[i], kvs[i+1]); err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } + } + } } if channelz.IsOn() { cc.incrCallsStarted() @@ -352,7 +361,7 @@ func newClientStreamWithParams(ctx context.Context, desc *StreamDesc, cc *Client } } for _, binlog := range cs.binlogs { - binlog.Log(logEntry) + binlog.Log(cs.ctx, logEntry) } } @@ -800,7 +809,7 @@ func (cs *clientStream) Header() (metadata.MD, error) { } cs.serverHeaderBinlogged = true for _, binlog := range cs.binlogs { - binlog.Log(logEntry) + binlog.Log(cs.ctx, logEntry) } } return m, nil @@ -881,7 +890,7 @@ func (cs *clientStream) SendMsg(m interface{}) (err error) { Message: data, } for _, binlog := range cs.binlogs { - binlog.Log(cm) + binlog.Log(cs.ctx, cm) } } return err @@ -905,7 +914,7 @@ func (cs *clientStream) RecvMsg(m interface{}) error { Message: recvInfo.uncompressedBytes, } for _, binlog := range cs.binlogs { - binlog.Log(sm) + binlog.Log(cs.ctx, sm) } } if err != nil || !cs.desc.ServerStreams { @@ -926,7 +935,7 @@ func (cs *clientStream) RecvMsg(m interface{}) error { logEntry.PeerAddr = peer.Addr } for _, binlog := range cs.binlogs { - binlog.Log(logEntry) + binlog.Log(cs.ctx, logEntry) } } } @@ -953,7 +962,7 @@ func (cs *clientStream) CloseSend() error { OnClientSide: true, } for _, binlog := range cs.binlogs { - binlog.Log(chc) + binlog.Log(cs.ctx, chc) } } // We never returned an error here for reasons. @@ -971,6 +980,9 @@ func (cs *clientStream) finish(err error) { return } cs.finished = true + for _, onFinish := range cs.callInfo.onFinish { + onFinish(err) + } cs.commitAttemptLocked() if cs.attempt != nil { cs.attempt.finish(err) @@ -992,7 +1004,7 @@ func (cs *clientStream) finish(err error) { OnClientSide: true, } for _, binlog := range cs.binlogs { - binlog.Log(c) + binlog.Log(cs.ctx, c) } } if err == nil { @@ -1081,9 +1093,10 @@ func (a *csAttempt) recvMsg(m interface{}, payInfo *payloadInfo) (err error) { RecvTime: time.Now(), Payload: m, // TODO truncate large payload. - Data: payInfo.uncompressedBytes, - WireLength: payInfo.wireLength + headerLen, - Length: len(payInfo.uncompressedBytes), + Data: payInfo.uncompressedBytes, + WireLength: payInfo.compressedLength + headerLen, + CompressedLength: payInfo.compressedLength, + Length: len(payInfo.uncompressedBytes), }) } if channelz.IsOn() { @@ -1511,6 +1524,8 @@ type serverStream struct { comp encoding.Compressor decomp encoding.Compressor + sendCompressorName string + maxReceiveMessageSize int maxSendMessageSize int trInfo *traceInfo @@ -1558,7 +1573,7 @@ func (ss *serverStream) SendHeader(md metadata.MD) error { } ss.serverHeaderBinlogged = true for _, binlog := range ss.binlogs { - binlog.Log(sh) + binlog.Log(ss.ctx, sh) } } return err @@ -1603,6 +1618,13 @@ func (ss *serverStream) SendMsg(m interface{}) (err error) { } }() + // Server handler could have set new compressor by calling SetSendCompressor. + // In case it is set, we need to use it for compressing outbound message. + if sendCompressorsName := ss.s.SendCompress(); sendCompressorsName != ss.sendCompressorName { + ss.comp = encoding.GetCompressor(sendCompressorsName) + ss.sendCompressorName = sendCompressorsName + } + // load hdr, payload, data hdr, payload, data, err := prepareMsg(m, ss.codec, ss.cp, ss.comp) if err != nil { @@ -1624,14 +1646,14 @@ func (ss *serverStream) SendMsg(m interface{}) (err error) { } ss.serverHeaderBinlogged = true for _, binlog := range ss.binlogs { - binlog.Log(sh) + binlog.Log(ss.ctx, sh) } } sm := &binarylog.ServerMessage{ Message: data, } for _, binlog := range ss.binlogs { - binlog.Log(sm) + binlog.Log(ss.ctx, sm) } } if len(ss.statsHandler) != 0 { @@ -1679,7 +1701,7 @@ func (ss *serverStream) RecvMsg(m interface{}) (err error) { if len(ss.binlogs) != 0 { chc := &binarylog.ClientHalfClose{} for _, binlog := range ss.binlogs { - binlog.Log(chc) + binlog.Log(ss.ctx, chc) } } return err @@ -1695,9 +1717,10 @@ func (ss *serverStream) RecvMsg(m interface{}) (err error) { RecvTime: time.Now(), Payload: m, // TODO truncate large payload. - Data: payInfo.uncompressedBytes, - WireLength: payInfo.wireLength + headerLen, - Length: len(payInfo.uncompressedBytes), + Data: payInfo.uncompressedBytes, + Length: len(payInfo.uncompressedBytes), + WireLength: payInfo.compressedLength + headerLen, + CompressedLength: payInfo.compressedLength, }) } } @@ -1706,7 +1729,7 @@ func (ss *serverStream) RecvMsg(m interface{}) (err error) { Message: payInfo.uncompressedBytes, } for _, binlog := range ss.binlogs { - binlog.Log(cm) + binlog.Log(ss.ctx, cm) } } return nil diff --git a/vendor/google.golang.org/grpc/version.go b/vendor/google.golang.org/grpc/version.go index fe552c315be..853ce0e30fc 100644 --- a/vendor/google.golang.org/grpc/version.go +++ b/vendor/google.golang.org/grpc/version.go @@ -19,4 +19,4 @@ package grpc // Version is the current grpc version. -const Version = "1.53.0" +const Version = "1.55.0" diff --git a/vendor/google.golang.org/grpc/vet.sh b/vendor/google.golang.org/grpc/vet.sh index 3728aed04fc..a8e4732b3d2 100644 --- a/vendor/google.golang.org/grpc/vet.sh +++ b/vendor/google.golang.org/grpc/vet.sh @@ -41,16 +41,8 @@ if [[ "$1" = "-install" ]]; then github.com/client9/misspell/cmd/misspell popd if [[ -z "${VET_SKIP_PROTO}" ]]; then - if [[ "${TRAVIS}" = "true" ]]; then - PROTOBUF_VERSION=3.14.0 - PROTOC_FILENAME=protoc-${PROTOBUF_VERSION}-linux-x86_64.zip - pushd /home/travis - wget https://github.com/google/protobuf/releases/download/v${PROTOBUF_VERSION}/${PROTOC_FILENAME} - unzip ${PROTOC_FILENAME} - bin/protoc --version - popd - elif [[ "${GITHUB_ACTIONS}" = "true" ]]; then - PROTOBUF_VERSION=3.14.0 + if [[ "${GITHUB_ACTIONS}" = "true" ]]; then + PROTOBUF_VERSION=22.0 # a.k.a v4.22.0 in pb.go files. PROTOC_FILENAME=protoc-${PROTOBUF_VERSION}-linux-x86_64.zip pushd /home/runner/go wget https://github.com/google/protobuf/releases/download/v${PROTOBUF_VERSION}/${PROTOC_FILENAME} @@ -68,8 +60,7 @@ fi # - Check that generated proto files are up to date. if [[ -z "${VET_SKIP_PROTO}" ]]; then - PATH="/home/travis/bin:${PATH}" make proto && \ - git status --porcelain 2>&1 | fail_on_output || \ + make proto && git status --porcelain 2>&1 | fail_on_output || \ (git status; git --no-pager diff; exit 1) fi diff --git a/vendor/k8s.io/kube-openapi/pkg/cached/cache.go b/vendor/k8s.io/kube-openapi/pkg/cached/cache.go new file mode 100644 index 00000000000..16e34853af7 --- /dev/null +++ b/vendor/k8s.io/kube-openapi/pkg/cached/cache.go @@ -0,0 +1,264 @@ +/* +Copyright 2022 The Kubernetes Authors. + +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 cache provides a cache mechanism based on etags to lazily +// build, and/or cache results from expensive operation such that those +// operations are not repeated unnecessarily. The operations can be +// created as a tree, and replaced dynamically as needed. +// +// # Dependencies and types of caches +// +// This package uses a source/transform/sink model of caches to build +// the dependency tree, and can be used as follows: +// - [NewSource]: A source cache that recomputes the content every time. +// - [NewStaticSource]: A source cache that always produces the +// same content, it is only called once. +// - [NewTransformer]: A cache that transforms data from one format to +// another. It's only refreshed when the source changes. +// - [NewMerger]: A cache that aggregates multiple caches into one. +// It's only refreshed when the source changes. +// - [Replaceable]: A cache adapter that can be atomically +// replaced with a new one, and saves the previous results in case an +// error pops-up. +// +// # Atomicity +// +// Most of the operations are not atomic/thread-safe, except for +// [Replaceable.Replace] which can be performed while the objects +// are being read. +// +// # Etags +// +// Etags in this library is a cache version identifier. It doesn't +// necessarily strictly match to the semantics of http `etags`, but are +// somewhat inspired from it and function with the same principles. +// Hashing the content is a good way to guarantee that your function is +// never going to be called spuriously. In Kubernetes world, this could +// be a `resourceVersion`, this can be an actual etag, a hash, a UUID +// (if the cache always changes), or even a made-up string when the +// content of the cache never changes. +package cached + +import ( + "fmt" + "sync/atomic" +) + +// Result is the content returned from a call to a cache. It can either +// be created with [NewResultOK] if the call was a success, or +// [NewResultErr] if the call resulted in an error. +type Result[T any] struct { + Data T + Etag string + Err error +} + +// NewResultOK creates a new [Result] for a successful operation. +func NewResultOK[T any](data T, etag string) Result[T] { + return Result[T]{ + Data: data, + Etag: etag, + } +} + +// NewResultErr creates a new [Result] when an error has happened. +func NewResultErr[T any](err error) Result[T] { + return Result[T]{ + Err: err, + } +} + +// Result can be treated as a [Data] if necessary. +func (r Result[T]) Get() Result[T] { + return r +} + +// Data is a cache that performs an action whose result data will be +// cached. It also returns an "etag" identifier to version the cache, so +// that the caller can know if they have the most recent version of the +// cache (and can decide to cache some operation based on that). +// +// The [NewMerger] and [NewTransformer] automatically handle +// that for you by checking if the etag is updated before calling the +// merging or transforming function. +type Data[T any] interface { + // Returns the cached data, as well as an "etag" to identify the + // version of the cache, or an error if something happened. + Get() Result[T] +} + +// T is the source type, V is the destination type. +type merger[K comparable, T, V any] struct { + mergeFn func(map[K]Result[T]) Result[V] + caches map[K]Data[T] + cacheResults map[K]Result[T] + result Result[V] +} + +// NewMerger creates a new merge cache, a cache that merges the result +// of other caches. The function only gets called if any of the +// dependency has changed. +// +// If any of the dependency returned an error before, or any of the +// dependency returned an error this time, or if the mergeFn failed +// before, then the function is reran. +// +// The caches and results are mapped by K so that associated data can be +// retrieved. The map of dependencies can not be modified after +// creation, and a new merger should be created (and probably replaced +// using a [Replaceable]). +// +// Note that this assumes there is no "partial" merge, the merge +// function will remerge all the dependencies together everytime. Since +// the list of dependencies is constant, there is no way to save some +// partial merge information either. +func NewMerger[K comparable, T, V any](mergeFn func(results map[K]Result[T]) Result[V], caches map[K]Data[T]) Data[V] { + return &merger[K, T, V]{ + mergeFn: mergeFn, + caches: caches, + } +} + +func (c *merger[K, T, V]) prepareResults() map[K]Result[T] { + cacheResults := make(map[K]Result[T], len(c.caches)) + for key, cache := range c.caches { + cacheResults[key] = cache.Get() + } + return cacheResults +} + +// Rerun if: +// - The last run resulted in an error +// - Any of the dependency previously returned an error +// - Any of the dependency just returned an error +// - Any of the dependency's etag changed +func (c *merger[K, T, V]) needsRunning(results map[K]Result[T]) bool { + if c.cacheResults == nil { + return true + } + if c.result.Err != nil { + return true + } + if len(results) != len(c.cacheResults) { + panic(fmt.Errorf("invalid number of results: %v (expected %v)", len(results), len(c.cacheResults))) + } + for key, oldResult := range c.cacheResults { + newResult, ok := results[key] + if !ok { + panic(fmt.Errorf("unknown cache entry: %v", key)) + } + + if newResult.Etag != oldResult.Etag || newResult.Err != nil || oldResult.Err != nil { + return true + } + } + return false +} + +func (c *merger[K, T, V]) Get() Result[V] { + cacheResults := c.prepareResults() + if c.needsRunning(cacheResults) { + c.cacheResults = cacheResults + c.result = c.mergeFn(c.cacheResults) + } + return c.result +} + +type transformerCacheKeyType struct{} + +// NewTransformer creates a new cache that transforms the result of +// another cache. The transformFn will only be called if the source +// cache has updated the output, otherwise, the cached result will be +// returned. +// +// If the dependency returned an error before, or it returns an error +// this time, or if the transformerFn failed before, the function is +// reran. +func NewTransformer[T, V any](transformerFn func(Result[T]) Result[V], source Data[T]) Data[V] { + return NewMerger(func(caches map[transformerCacheKeyType]Result[T]) Result[V] { + cache, ok := caches[transformerCacheKeyType{}] + if len(caches) != 1 || !ok { + panic(fmt.Errorf("invalid cache for transformer cache: %v", caches)) + } + return transformerFn(cache) + }, map[transformerCacheKeyType]Data[T]{ + {}: source, + }) +} + +// NewSource creates a new cache that generates some data. This +// will always be called since we don't know the origin of the data and +// if it needs to be updated or not. +func NewSource[T any](sourceFn func() Result[T]) Data[T] { + c := source[T](sourceFn) + return &c +} + +type source[T any] func() Result[T] + +func (c *source[T]) Get() Result[T] { + return (*c)() +} + +// NewStaticSource creates a new cache that always generates the +// same data. This will only be called once (lazily). +func NewStaticSource[T any](staticFn func() Result[T]) Data[T] { + return &static[T]{ + fn: staticFn, + } +} + +type static[T any] struct { + fn func() Result[T] + result *Result[T] +} + +func (c *static[T]) Get() Result[T] { + if c.result == nil { + result := c.fn() + c.result = &result + } + return *c.result +} + +// Replaceable is a cache that carries the result even when the +// cache is replaced. The cache can be replaced atomically (without any +// lock held). This is the type that should typically be stored in +// structs. +type Replaceable[T any] struct { + cache atomic.Pointer[Data[T]] + result *Result[T] +} + +// Get retrieves the data from the underlying source. [Replaceable] +// implements the [Data] interface itself. This is a pass-through +// that calls the most recent underlying cache. If the cache fails but +// previously had returned a success, that success will be returned +// instead. If the cache fails but we never returned a success, that +// failure is returned. +func (c *Replaceable[T]) Get() Result[T] { + result := (*c.cache.Load()).Get() + if result.Err != nil && c.result != nil && c.result.Err == nil { + return *c.result + } + c.result = &result + return *c.result +} + +// Replace changes the cache in a thread-safe way. +func (c *Replaceable[T]) Replace(cache Data[T]) { + c.cache.Swap(&cache) +} diff --git a/vendor/k8s.io/kube-openapi/pkg/handler3/handler.go b/vendor/k8s.io/kube-openapi/pkg/handler3/handler.go index 2c730f1bf8e..66b7a68da67 100644 --- a/vendor/k8s.io/kube-openapi/pkg/handler3/handler.go +++ b/vendor/k8s.io/kube-openapi/pkg/handler3/handler.go @@ -24,7 +24,6 @@ import ( "net/http" "net/url" "path" - "sort" "strconv" "strings" "sync" @@ -32,11 +31,12 @@ import ( "github.com/golang/protobuf/proto" openapi_v3 "github.com/google/gnostic/openapiv3" + "github.com/google/uuid" "github.com/munnerz/goautoneg" + "k8s.io/klog/v2" + "k8s.io/kube-openapi/pkg/cached" "k8s.io/kube-openapi/pkg/common" - "k8s.io/kube-openapi/pkg/internal/handler" "k8s.io/kube-openapi/pkg/spec3" - "k8s.io/kube-openapi/pkg/validation/spec" ) const ( @@ -58,23 +58,63 @@ type OpenAPIV3DiscoveryGroupVersion struct { ServerRelativeURL string `json:"serverRelativeURL"` } -// OpenAPIService is the service responsible for serving OpenAPI spec. It has -// the ability to safely change the spec while serving it. -type OpenAPIService struct { - // rwMutex protects All members of this service. - rwMutex sync.RWMutex +func ToV3ProtoBinary(json []byte) ([]byte, error) { + document, err := openapi_v3.ParseDocument(json) + if err != nil { + return nil, err + } + return proto.Marshal(document) +} + +type timedSpec struct { + spec []byte lastModified time.Time - v3Schema map[string]*OpenAPIV3Group } -type OpenAPIV3Group struct { - rwMutex sync.RWMutex +// This type is protected by the lock on OpenAPIService. +type openAPIV3Group struct { + specCache cached.Replaceable[*spec3.OpenAPI] + pbCache cached.Data[timedSpec] + jsonCache cached.Data[timedSpec] +} - lastModified time.Time +func newOpenAPIV3Group() *openAPIV3Group { + o := &openAPIV3Group{} + o.jsonCache = cached.NewTransformer[*spec3.OpenAPI](func(result cached.Result[*spec3.OpenAPI]) cached.Result[timedSpec] { + if result.Err != nil { + return cached.NewResultErr[timedSpec](result.Err) + } + json, err := json.Marshal(result.Data) + if err != nil { + return cached.NewResultErr[timedSpec](err) + } + return cached.NewResultOK(timedSpec{spec: json, lastModified: time.Now()}, computeETag(json)) + }, &o.specCache) + o.pbCache = cached.NewTransformer(func(result cached.Result[timedSpec]) cached.Result[timedSpec] { + if result.Err != nil { + return cached.NewResultErr[timedSpec](result.Err) + } + proto, err := ToV3ProtoBinary(result.Data.spec) + if err != nil { + return cached.NewResultErr[timedSpec](err) + } + return cached.NewResultOK(timedSpec{spec: proto, lastModified: result.Data.lastModified}, result.Etag) + }, o.jsonCache) + return o +} - pbCache handler.HandlerCache - jsonCache handler.HandlerCache - etagCache handler.HandlerCache +func (o *openAPIV3Group) UpdateSpec(openapi cached.Data[*spec3.OpenAPI]) { + o.specCache.Replace(openapi) +} + +// OpenAPIService is the service responsible for serving OpenAPI spec. It has +// the ability to safely change the spec while serving it. +type OpenAPIService struct { + // Mutex protects the schema map. + mutex sync.Mutex + v3Schema map[string]*openAPIV3Group + + discoveryCache cached.Replaceable[timedSpec] } func computeETag(data []byte) string { @@ -93,94 +133,90 @@ func constructServerRelativeURL(gvString, etag string) string { } // NewOpenAPIService builds an OpenAPIService starting with the given spec. -func NewOpenAPIService(spec *spec.Swagger) (*OpenAPIService, error) { +func NewOpenAPIService() *OpenAPIService { o := &OpenAPIService{} - o.v3Schema = make(map[string]*OpenAPIV3Group) - return o, nil + o.v3Schema = make(map[string]*openAPIV3Group) + // We're not locked because we haven't shared the structure yet. + o.discoveryCache.Replace(o.buildDiscoveryCacheLocked()) + return o } -func (o *OpenAPIService) getGroupBytes() ([]byte, error) { - o.rwMutex.RLock() - defer o.rwMutex.RUnlock() - keys := make([]string, len(o.v3Schema)) - i := 0 - for k := range o.v3Schema { - keys[i] = k - i++ +func (o *OpenAPIService) buildDiscoveryCacheLocked() cached.Data[timedSpec] { + caches := make(map[string]cached.Data[timedSpec], len(o.v3Schema)) + for gvName, group := range o.v3Schema { + caches[gvName] = group.jsonCache } - - sort.Strings(keys) - discovery := &OpenAPIV3Discovery{Paths: make(map[string]OpenAPIV3DiscoveryGroupVersion)} - for gvString, groupVersion := range o.v3Schema { - etagBytes, err := groupVersion.etagCache.Get() - if err != nil { - return nil, err + return cached.NewMerger(func(results map[string]cached.Result[timedSpec]) cached.Result[timedSpec] { + discovery := &OpenAPIV3Discovery{Paths: make(map[string]OpenAPIV3DiscoveryGroupVersion)} + for gvName, result := range results { + if result.Err != nil { + return cached.NewResultErr[timedSpec](result.Err) + } + discovery.Paths[gvName] = OpenAPIV3DiscoveryGroupVersion{ + ServerRelativeURL: constructServerRelativeURL(gvName, result.Etag), + } } - discovery.Paths[gvString] = OpenAPIV3DiscoveryGroupVersion{ - ServerRelativeURL: constructServerRelativeURL(gvString, string(etagBytes)), + j, err := json.Marshal(discovery) + if err != nil { + return cached.NewResultErr[timedSpec](err) } - } - j, err := json.Marshal(discovery) - if err != nil { - return nil, err - } - return j, nil + return cached.NewResultOK(timedSpec{spec: j, lastModified: time.Now()}, computeETag(j)) + }, caches) } func (o *OpenAPIService) getSingleGroupBytes(getType string, group string) ([]byte, string, time.Time, error) { - o.rwMutex.RLock() - defer o.rwMutex.RUnlock() + o.mutex.Lock() + defer o.mutex.Unlock() v, ok := o.v3Schema[group] if !ok { return nil, "", time.Now(), fmt.Errorf("Cannot find CRD group %s", group) } - if getType == subTypeJSON { - specBytes, err := v.jsonCache.Get() - if err != nil { - return nil, "", v.lastModified, err - } - etagBytes, err := v.etagCache.Get() - return specBytes, string(etagBytes), v.lastModified, err - } else if getType == subTypeProtobuf || getType == subTypeProtobufDeprecated { - specPb, err := v.pbCache.Get() - if err != nil { - return nil, "", v.lastModified, err - } - etagBytes, err := v.etagCache.Get() - return specPb, string(etagBytes), v.lastModified, err + result := cached.Result[timedSpec]{} + switch getType { + case subTypeJSON: + result = v.jsonCache.Get() + case subTypeProtobuf, subTypeProtobufDeprecated: + result = v.pbCache.Get() + default: + return nil, "", time.Now(), fmt.Errorf("Invalid accept clause %s", getType) } - return nil, "", time.Now(), fmt.Errorf("Invalid accept clause %s", getType) + return result.Data.spec, result.Etag, result.Data.lastModified, result.Err } -func (o *OpenAPIService) UpdateGroupVersion(group string, openapi *spec3.OpenAPI) (err error) { - o.rwMutex.Lock() - defer o.rwMutex.Unlock() - +// UpdateGroupVersionLazy adds or updates an existing group with the new cached. +func (o *OpenAPIService) UpdateGroupVersionLazy(group string, openapi cached.Data[*spec3.OpenAPI]) { + o.mutex.Lock() + defer o.mutex.Unlock() if _, ok := o.v3Schema[group]; !ok { - o.v3Schema[group] = &OpenAPIV3Group{} + o.v3Schema[group] = newOpenAPIV3Group() + // Since there is a new item, we need to re-build the cache map. + o.discoveryCache.Replace(o.buildDiscoveryCacheLocked()) } - return o.v3Schema[group].UpdateSpec(openapi) + o.v3Schema[group].UpdateSpec(openapi) } -func (o *OpenAPIService) DeleteGroupVersion(group string) { - o.rwMutex.Lock() - defer o.rwMutex.Unlock() - delete(o.v3Schema, group) +func (o *OpenAPIService) UpdateGroupVersion(group string, openapi *spec3.OpenAPI) { + o.UpdateGroupVersionLazy(group, cached.NewResultOK(openapi, uuid.New().String())) } -func ToV3ProtoBinary(json []byte) ([]byte, error) { - document, err := openapi_v3.ParseDocument(json) - if err != nil { - return nil, err - } - return proto.Marshal(document) +func (o *OpenAPIService) DeleteGroupVersion(group string) { + o.mutex.Lock() + defer o.mutex.Unlock() + delete(o.v3Schema, group) + // Rebuild the merge cache map since the items have changed. + o.discoveryCache.Replace(o.buildDiscoveryCacheLocked()) } func (o *OpenAPIService) HandleDiscovery(w http.ResponseWriter, r *http.Request) { - data, _ := o.getGroupBytes() - w.Header().Set("Etag", strconv.Quote(computeETag(data))) + result := o.discoveryCache.Get() + if result.Err != nil { + klog.Errorf("Error serving discovery: %s", result.Err) + w.WriteHeader(http.StatusInternalServerError) + return + } + w.Header().Set("Etag", strconv.Quote(result.Etag)) w.Header().Set("Content-Type", "application/json") - http.ServeContent(w, r, "/openapi/v3", time.Now(), bytes.NewReader(data)) + http.ServeContent(w, r, "/openapi/v3", result.Data.lastModified, bytes.NewReader(result.Data.spec)) } func (o *OpenAPIService) HandleGroupVersion(w http.ResponseWriter, r *http.Request) { @@ -256,30 +292,3 @@ func (o *OpenAPIService) RegisterOpenAPIV3VersionedService(servePath string, han handler.HandlePrefix(servePath+"/", http.HandlerFunc(o.HandleGroupVersion)) return nil } - -func (o *OpenAPIV3Group) UpdateSpec(openapi *spec3.OpenAPI) (err error) { - o.rwMutex.Lock() - defer o.rwMutex.Unlock() - - o.jsonCache = o.jsonCache.New(func() ([]byte, error) { - return json.Marshal(openapi) - }) - o.pbCache = o.pbCache.New(func() ([]byte, error) { - json, err := o.jsonCache.Get() - if err != nil { - return nil, err - } - return ToV3ProtoBinary(json) - }) - // TODO: This forces a json marshal of corresponding group-versions. - // We should look to replace this with a faster hashing mechanism. - o.etagCache = o.etagCache.New(func() ([]byte, error) { - json, err := o.jsonCache.Get() - if err != nil { - return nil, err - } - return []byte(computeETag(json)), nil - }) - o.lastModified = time.Now() - return nil -} diff --git a/vendor/k8s.io/kube-openapi/pkg/internal/handler/handler_cache.go b/vendor/k8s.io/kube-openapi/pkg/internal/handler/handler_cache.go deleted file mode 100644 index e128c26ebee..00000000000 --- a/vendor/k8s.io/kube-openapi/pkg/internal/handler/handler_cache.go +++ /dev/null @@ -1,57 +0,0 @@ -/* -Copyright 2021 The Kubernetes Authors. - -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 handler - -import ( - "sync" -) - -// HandlerCache represents a lazy cache for generating a byte array -// It is used to lazily marshal OpenAPI v2/v3 and lazily generate the ETag -type HandlerCache struct { - BuildCache func() ([]byte, error) - once sync.Once - bytes []byte - err error -} - -// Get either returns the cached value or calls BuildCache() once before caching and returning -// its results. If BuildCache returns an error, the last valid value for the cache (from prior -// calls to New()) is used instead if possible. -func (c *HandlerCache) Get() ([]byte, error) { - c.once.Do(func() { - bytes, err := c.BuildCache() - // if there is an error updating the cache, there can be situations where - // c.bytes contains a valid value (carried over from the previous update) - // but c.err is also not nil; the cache user is expected to check for this - c.err = err - if c.err == nil { - // don't override previous spec if we had an error - c.bytes = bytes - } - }) - return c.bytes, c.err -} - -// New creates a new HandlerCache for situations where a cache refresh is needed. -// This function is not thread-safe and should not be called at the same time as Get(). -func (c *HandlerCache) New(cacheBuilder func() ([]byte, error)) HandlerCache { - return HandlerCache{ - bytes: c.bytes, - BuildCache: cacheBuilder, - } -} diff --git a/vendor/modules.txt b/vendor/modules.txt index 7be4342efcf..a3b9f812f99 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,4 +1,4 @@ -# cloud.google.com/go/compute v1.18.0 +# cloud.google.com/go/compute v1.19.0 ## explicit; go 1.19 cloud.google.com/go/compute/internal # cloud.google.com/go/compute/metadata v0.2.3 @@ -9,10 +9,37 @@ cloud.google.com/go/compute/metadata github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-10-01/compute github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-10-01/network github.com/Azure/azure-sdk-for-go/version +# github.com/Azure/azure-sdk-for-go/sdk/azcore v1.3.1 +## explicit; go 1.18 +github.com/Azure/azure-sdk-for-go/sdk/azcore +github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud +github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/exported +github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/log +github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers +github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/async +github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/body +github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/loc +github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/pollers/op +github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared +github.com/Azure/azure-sdk-for-go/sdk/azcore/log +github.com/Azure/azure-sdk-for-go/sdk/azcore/policy +github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime +github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming +github.com/Azure/azure-sdk-for-go/sdk/azcore/tracing +# github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.2.1 +## explicit; go 1.18 +github.com/Azure/azure-sdk-for-go/sdk/azidentity +# github.com/Azure/azure-sdk-for-go/sdk/internal v1.3.0 +## explicit; go 1.18 +github.com/Azure/azure-sdk-for-go/sdk/internal/diag +github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo +github.com/Azure/azure-sdk-for-go/sdk/internal/log +github.com/Azure/azure-sdk-for-go/sdk/internal/temporal +github.com/Azure/azure-sdk-for-go/sdk/internal/uuid # github.com/Azure/go-autorest v14.2.0+incompatible ## explicit github.com/Azure/go-autorest -# github.com/Azure/go-autorest/autorest v0.11.28 +# github.com/Azure/go-autorest/autorest v0.11.29 ## explicit; go 1.15 github.com/Azure/go-autorest/autorest github.com/Azure/go-autorest/autorest/azure @@ -34,6 +61,29 @@ github.com/Azure/go-autorest/logger # github.com/Azure/go-autorest/tracing v0.6.0 ## explicit; go 1.12 github.com/Azure/go-autorest/tracing +# github.com/AzureAD/microsoft-authentication-library-for-go v0.8.1 +## explicit; go 1.18 +github.com/AzureAD/microsoft-authentication-library-for-go/apps/cache +github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential +github.com/AzureAD/microsoft-authentication-library-for-go/apps/errors +github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base +github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base/internal/storage +github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/exported +github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json +github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/json/types/time +github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/local +github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth +github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops +github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens +github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority +github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/comm +github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/internal/grant +github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust +github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/wstrust/defs +github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/options +github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/shared +github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/version +github.com/AzureAD/microsoft-authentication-library-for-go/apps/public # github.com/Microsoft/go-winio v0.6.0 ## explicit; go 1.17 github.com/Microsoft/go-winio @@ -51,7 +101,7 @@ github.com/armon/go-metrics # github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 ## explicit; go 1.13 github.com/asaskevich/govalidator -# github.com/aws/aws-sdk-go v1.44.245 +# github.com/aws/aws-sdk-go v1.44.276 ## explicit; go 1.11 github.com/aws/aws-sdk-go/aws github.com/aws/aws-sdk-go/aws/awserr @@ -99,13 +149,13 @@ github.com/aws/aws-sdk-go/service/sts/stsiface # github.com/beorn7/perks v1.0.1 ## explicit; go 1.11 github.com/beorn7/perks/quantile -# github.com/cenkalti/backoff/v4 v4.2.0 +# github.com/cenkalti/backoff/v4 v4.2.1 ## explicit; go 1.18 github.com/cenkalti/backoff/v4 # github.com/cespare/xxhash/v2 v2.2.0 ## explicit; go 1.11 github.com/cespare/xxhash/v2 -# github.com/cncf/xds/go v0.0.0-20230112175826-46e39c7b9b43 +# github.com/cncf/xds/go v0.0.0-20230428030218-4003588d1b74 ## explicit; go 1.11 github.com/cncf/xds/go/udpa/annotations github.com/cncf/xds/go/xds/annotations/v3 @@ -119,7 +169,7 @@ github.com/davecgh/go-spew/spew # github.com/dennwc/varint v1.0.0 ## explicit; go 1.12 github.com/dennwc/varint -# github.com/digitalocean/godo v1.98.0 +# github.com/digitalocean/godo v1.99.0 ## explicit; go 1.18 github.com/digitalocean/godo github.com/digitalocean/godo/metrics @@ -127,7 +177,7 @@ github.com/digitalocean/godo/metrics ## explicit github.com/docker/distribution/digestset github.com/docker/distribution/reference -# github.com/docker/docker v23.0.4+incompatible +# github.com/docker/docker v24.0.2+incompatible ## explicit github.com/docker/docker/api github.com/docker/docker/api/types @@ -169,7 +219,7 @@ github.com/envoyproxy/go-control-plane/envoy/config/core/v3 github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3 github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3 github.com/envoyproxy/go-control-plane/envoy/type/v3 -# github.com/envoyproxy/protoc-gen-validate v0.10.1 +# github.com/envoyproxy/protoc-gen-validate v1.0.1 ## explicit; go 1.19 github.com/envoyproxy/protoc-gen-validate/validate # github.com/evanphx/json-patch v4.12.0+incompatible @@ -198,7 +248,7 @@ github.com/go-kit/log/level # github.com/go-logfmt/logfmt v0.6.0 ## explicit; go 1.17 github.com/go-logfmt/logfmt -# github.com/go-logr/logr v1.2.3 +# github.com/go-logr/logr v1.2.4 ## explicit; go 1.16 github.com/go-logr/logr github.com/go-logr/logr/funcr @@ -278,9 +328,11 @@ github.com/gogo/protobuf/vanity/command # github.com/golang-jwt/jwt/v4 v4.5.0 ## explicit; go 1.16 github.com/golang-jwt/jwt/v4 -# github.com/golang/glog v1.0.0 -## explicit; go 1.11 +# github.com/golang/glog v1.1.0 +## explicit; go 1.18 github.com/golang/glog +github.com/golang/glog/internal/logsink +github.com/golang/glog/internal/stackdump # github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da ## explicit github.com/golang/groupcache/lru @@ -321,7 +373,7 @@ github.com/google/go-querystring/query ## explicit; go 1.12 github.com/google/gofuzz github.com/google/gofuzz/bytesource -# github.com/google/pprof v0.0.0-20230406165453-00490a63f317 +# github.com/google/pprof v0.0.0-20230602150820-91b7bce49751 ## explicit; go 1.19 github.com/google/pprof/profile # github.com/google/uuid v1.3.0 @@ -337,7 +389,7 @@ github.com/googleapis/gax-go/v2 github.com/googleapis/gax-go/v2/apierror github.com/googleapis/gax-go/v2/apierror/internal/proto github.com/googleapis/gax-go/v2/internal -# github.com/gophercloud/gophercloud v1.3.0 +# github.com/gophercloud/gophercloud v1.4.0 ## explicit; go 1.14 github.com/gophercloud/gophercloud github.com/gophercloud/gophercloud/openstack @@ -372,12 +424,12 @@ github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options github.com/grpc-ecosystem/grpc-gateway/utilities -# github.com/grpc-ecosystem/grpc-gateway/v2 v2.15.2 +# github.com/grpc-ecosystem/grpc-gateway/v2 v2.15.0 ## explicit; go 1.17 github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule github.com/grpc-ecosystem/grpc-gateway/v2/runtime github.com/grpc-ecosystem/grpc-gateway/v2/utilities -# github.com/hashicorp/consul/api v1.20.0 +# github.com/hashicorp/consul/api v1.21.0 ## explicit; go 1.19 github.com/hashicorp/consul/api # github.com/hashicorp/cronexpr v1.1.1 @@ -407,14 +459,14 @@ github.com/hashicorp/go-rootcerts # github.com/hashicorp/golang-lru v0.6.0 ## explicit; go 1.12 github.com/hashicorp/golang-lru/simplelru -# github.com/hashicorp/nomad/api v0.0.0-20230418003350-3067191c5197 -## explicit; go 1.19 +# github.com/hashicorp/nomad/api v0.0.0-20230605233119-67e39d5d248f +## explicit; go 1.20 github.com/hashicorp/nomad/api github.com/hashicorp/nomad/api/contexts # github.com/hashicorp/serf v0.10.1 ## explicit; go 1.12 github.com/hashicorp/serf/coordinate -# github.com/hetznercloud/hcloud-go v1.42.0 +# github.com/hetznercloud/hcloud-go v1.45.1 ## explicit; go 1.19 github.com/hetznercloud/hcloud-go/hcloud github.com/hetznercloud/hcloud-go/hcloud/internal/instrumentation @@ -422,7 +474,7 @@ github.com/hetznercloud/hcloud-go/hcloud/schema # github.com/imdario/mergo v0.3.13 ## explicit; go 1.13 github.com/imdario/mergo -# github.com/ionos-cloud/sdk-go/v6 v6.1.6 +# github.com/ionos-cloud/sdk-go/v6 v6.1.7 ## explicit; go 1.19 github.com/ionos-cloud/sdk-go/v6 # github.com/jmespath/go-jmespath v0.4.0 @@ -443,7 +495,11 @@ github.com/julienschmidt/httprouter # github.com/kolo/xmlrpc v0.0.0-20220921171641-a4b6fa1dd06b ## explicit; go 1.14 github.com/kolo/xmlrpc -# github.com/linode/linodego v1.16.1 +# github.com/kylelemons/godebug v1.1.0 +## explicit; go 1.11 +github.com/kylelemons/godebug/diff +github.com/kylelemons/godebug/pretty +# github.com/linode/linodego v1.17.0 ## explicit; go 1.18 github.com/linode/linodego github.com/linode/linodego/internal/duration @@ -462,7 +518,7 @@ github.com/mattn/go-isatty # github.com/matttproud/golang_protobuf_extensions v1.0.4 ## explicit; go 1.9 github.com/matttproud/golang_protobuf_extensions/pbutil -# github.com/miekg/dns v1.1.53 +# github.com/miekg/dns v1.1.54 ## explicit; go 1.19 github.com/miekg/dns # github.com/mitchellh/go-homedir v1.1.0 @@ -503,6 +559,9 @@ github.com/opencontainers/image-spec/specs-go/v1 # github.com/ovh/go-ovh v1.4.1 ## explicit; go 1.18 github.com/ovh/go-ovh/ovh +# github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 +## explicit; go 1.14 +github.com/pkg/browser # github.com/pkg/errors v0.9.1 ## explicit github.com/pkg/errors @@ -512,7 +571,7 @@ github.com/pmezard/go-difflib/difflib # github.com/prometheus/alertmanager v0.25.0 ## explicit; go 1.18 github.com/prometheus/alertmanager/api/v2/models -# github.com/prometheus/client_golang v1.15.0 +# github.com/prometheus/client_golang v1.15.1 ## explicit; go 1.17 github.com/prometheus/client_golang/api github.com/prometheus/client_golang/api/prometheus/v1 @@ -522,10 +581,10 @@ github.com/prometheus/client_golang/prometheus/promauto github.com/prometheus/client_golang/prometheus/promhttp github.com/prometheus/client_golang/prometheus/testutil github.com/prometheus/client_golang/prometheus/testutil/promlint -# github.com/prometheus/client_model v0.3.0 -## explicit; go 1.9 +# github.com/prometheus/client_model v0.4.0 +## explicit; go 1.18 github.com/prometheus/client_model/go -# github.com/prometheus/common v0.42.0 +# github.com/prometheus/common v0.44.0 ## explicit; go 1.18 github.com/prometheus/common/config github.com/prometheus/common/expfmt @@ -542,7 +601,7 @@ github.com/prometheus/common/assets # github.com/prometheus/common/sigv4 v0.1.0 ## explicit; go 1.15 github.com/prometheus/common/sigv4 -# github.com/prometheus/exporter-toolkit v0.9.1 +# github.com/prometheus/exporter-toolkit v0.10.0 ## explicit; go 1.18 github.com/prometheus/exporter-toolkit/web # github.com/prometheus/procfs v0.9.0 @@ -550,9 +609,7 @@ github.com/prometheus/exporter-toolkit/web github.com/prometheus/procfs github.com/prometheus/procfs/internal/fs github.com/prometheus/procfs/internal/util -# github.com/rogpeppe/go-internal v1.10.0 -## explicit; go 1.19 -# github.com/scaleway/scaleway-sdk-go v1.0.0-beta.15 +# github.com/scaleway/scaleway-sdk-go v1.0.0-beta.17 ## explicit; go 1.17 github.com/scaleway/scaleway-sdk-go/api/baremetal/v1 github.com/scaleway/scaleway-sdk-go/api/instance/v1 @@ -574,10 +631,15 @@ github.com/shurcooL/httpfs/union # github.com/spf13/pflag v1.0.5 ## explicit; go 1.12 github.com/spf13/pflag -# github.com/stretchr/testify v1.8.2 -## explicit; go 1.13 +# github.com/stretchr/objx v0.5.0 +## explicit; go 1.12 +github.com/stretchr/objx +# github.com/stretchr/testify v1.8.4 +## explicit; go 1.20 github.com/stretchr/testify/assert +github.com/stretchr/testify/mock github.com/stretchr/testify/require +github.com/stretchr/testify/suite # github.com/vultr/govultr/v2 v2.17.2 ## explicit; go 1.17 github.com/vultr/govultr/v2 @@ -611,11 +673,11 @@ go.opencensus.io/trace go.opencensus.io/trace/internal go.opencensus.io/trace/propagation go.opencensus.io/trace/tracestate -# go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.40.0 -## explicit; go 1.18 +# go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.42.0 +## explicit; go 1.19 go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp -# go.opentelemetry.io/otel v1.14.0 -## explicit; go 1.18 +# go.opentelemetry.io/otel v1.16.0 +## explicit; go 1.19 go.opentelemetry.io/otel go.opentelemetry.io/otel/attribute go.opentelemetry.io/otel/baggage @@ -630,35 +692,35 @@ go.opentelemetry.io/otel/propagation go.opentelemetry.io/otel/semconv/internal/v2 go.opentelemetry.io/otel/semconv/v1.17.0 go.opentelemetry.io/otel/semconv/v1.17.0/httpconv -# go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.14.0 -## explicit; go 1.18 +# go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.16.0 +## explicit; go 1.19 go.opentelemetry.io/otel/exporters/otlp/internal/retry -# go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.14.0 -## explicit; go 1.18 +# go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.16.0 +## explicit; go 1.19 go.opentelemetry.io/otel/exporters/otlp/otlptrace +go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/otlpconfig go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform -# go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.14.0 -## explicit; go 1.18 +# go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.16.0 +## explicit; go 1.19 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc -# go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.14.0 -## explicit; go 1.18 +# go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.16.0 +## explicit; go 1.19 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp -# go.opentelemetry.io/otel/metric v0.37.0 -## explicit; go 1.18 +# go.opentelemetry.io/otel/metric v1.16.0 +## explicit; go 1.19 go.opentelemetry.io/otel/metric -go.opentelemetry.io/otel/metric/global -go.opentelemetry.io/otel/metric/instrument -go.opentelemetry.io/otel/metric/internal/global -# go.opentelemetry.io/otel/sdk v1.14.0 -## explicit; go 1.18 +go.opentelemetry.io/otel/metric/embedded +# go.opentelemetry.io/otel/sdk v1.16.0 +## explicit; go 1.19 +go.opentelemetry.io/otel/sdk go.opentelemetry.io/otel/sdk/instrumentation go.opentelemetry.io/otel/sdk/internal go.opentelemetry.io/otel/sdk/internal/env go.opentelemetry.io/otel/sdk/resource go.opentelemetry.io/otel/sdk/trace -# go.opentelemetry.io/otel/trace v1.14.0 -## explicit; go 1.18 +# go.opentelemetry.io/otel/trace v1.16.0 +## explicit; go 1.19 go.opentelemetry.io/otel/trace # go.opentelemetry.io/proto/otlp v0.19.0 ## explicit; go 1.14 @@ -666,7 +728,7 @@ go.opentelemetry.io/proto/otlp/collector/trace/v1 go.opentelemetry.io/proto/otlp/common/v1 go.opentelemetry.io/proto/otlp/resource/v1 go.opentelemetry.io/proto/otlp/trace/v1 -# go.uber.org/atomic v1.10.0 +# go.uber.org/atomic v1.11.0 ## explicit; go 1.18 go.uber.org/atomic # go.uber.org/automaxprocs v1.5.2 @@ -678,14 +740,14 @@ go.uber.org/automaxprocs/maxprocs ## explicit; go 1.18 go.uber.org/goleak go.uber.org/goleak/internal/stack -# golang.org/x/crypto v0.7.0 +# golang.org/x/crypto v0.8.0 ## explicit; go 1.17 golang.org/x/crypto/bcrypt golang.org/x/crypto/blowfish golang.org/x/crypto/pkcs12 golang.org/x/crypto/pkcs12/internal/rc2 -# golang.org/x/exp v0.0.0-20230321023759-10a507213a29 -## explicit; go 1.18 +# golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1 +## explicit; go 1.20 golang.org/x/exp/constraints golang.org/x/exp/maps golang.org/x/exp/slices @@ -694,7 +756,7 @@ golang.org/x/exp/slices golang.org/x/mod/internal/lazyregexp golang.org/x/mod/module golang.org/x/mod/semver -# golang.org/x/net v0.9.0 +# golang.org/x/net v0.10.0 ## explicit; go 1.17 golang.org/x/net/bpf golang.org/x/net/context @@ -713,7 +775,7 @@ golang.org/x/net/netutil golang.org/x/net/proxy golang.org/x/net/publicsuffix golang.org/x/net/trace -# golang.org/x/oauth2 v0.7.0 +# golang.org/x/oauth2 v0.8.0 ## explicit; go 1.17 golang.org/x/oauth2 golang.org/x/oauth2/authhandler @@ -723,10 +785,10 @@ golang.org/x/oauth2/google/internal/externalaccount golang.org/x/oauth2/internal golang.org/x/oauth2/jws golang.org/x/oauth2/jwt -# golang.org/x/sync v0.1.0 +# golang.org/x/sync v0.2.0 ## explicit golang.org/x/sync/errgroup -# golang.org/x/sys v0.7.0 +# golang.org/x/sys v0.8.0 ## explicit; go 1.17 golang.org/x/sys/execabs golang.org/x/sys/internal/unsafeheader @@ -734,7 +796,7 @@ golang.org/x/sys/plan9 golang.org/x/sys/unix golang.org/x/sys/windows golang.org/x/sys/windows/registry -# golang.org/x/term v0.7.0 +# golang.org/x/term v0.8.0 ## explicit; go 1.17 golang.org/x/term # golang.org/x/text v0.9.0 @@ -746,7 +808,7 @@ golang.org/x/text/unicode/norm # golang.org/x/time v0.3.0 ## explicit golang.org/x/time/rate -# golang.org/x/tools v0.8.0 +# golang.org/x/tools v0.9.3 ## explicit; go 1.18 golang.org/x/tools/cmd/goimports golang.org/x/tools/cmd/stringer @@ -754,11 +816,11 @@ golang.org/x/tools/go/ast/astutil golang.org/x/tools/go/gcexportdata golang.org/x/tools/go/internal/packagesdriver golang.org/x/tools/go/packages -golang.org/x/tools/go/types/objectpath golang.org/x/tools/internal/event golang.org/x/tools/internal/event/core golang.org/x/tools/internal/event/keys golang.org/x/tools/internal/event/label +golang.org/x/tools/internal/event/tag golang.org/x/tools/internal/fastwalk golang.org/x/tools/internal/gcimporter golang.org/x/tools/internal/gocommand @@ -795,7 +857,7 @@ google.golang.org/appengine/internal/modules google.golang.org/appengine/internal/remote_api google.golang.org/appengine/internal/urlfetch google.golang.org/appengine/urlfetch -# google.golang.org/genproto v0.0.0-20230306155012-7f2fa6fef1f4 +# google.golang.org/genproto v0.0.0-20230320184635-7606e756e683 ## explicit; go 1.19 google.golang.org/genproto/googleapis/api google.golang.org/genproto/googleapis/api/annotations @@ -804,7 +866,7 @@ google.golang.org/genproto/googleapis/rpc/code google.golang.org/genproto/googleapis/rpc/errdetails google.golang.org/genproto/googleapis/rpc/status google.golang.org/genproto/protobuf/field_mask -# google.golang.org/grpc v1.53.0 +# google.golang.org/grpc v1.55.0 ## explicit; go 1.17 google.golang.org/grpc google.golang.org/grpc/attributes @@ -1192,16 +1254,16 @@ k8s.io/client-go/util/workqueue # k8s.io/klog v1.0.0 => github.com/simonpasquier/klog-gokit v0.3.0 ## explicit; go 1.12 k8s.io/klog -# k8s.io/klog/v2 v2.90.1 => github.com/simonpasquier/klog-gokit/v3 v3.0.0 +# k8s.io/klog/v2 v2.100.1 => github.com/simonpasquier/klog-gokit/v3 v3.0.0 ## explicit; go 1.12 k8s.io/klog/v2 -# k8s.io/kube-openapi v0.0.0-20230303024457-afdc3dddf62d -## explicit; go 1.18 +# k8s.io/kube-openapi v0.0.0-20230501164219-8b0f38b5fd1f +## explicit; go 1.19 k8s.io/kube-openapi/pkg/builder3/util +k8s.io/kube-openapi/pkg/cached k8s.io/kube-openapi/pkg/common k8s.io/kube-openapi/pkg/handler3 k8s.io/kube-openapi/pkg/internal -k8s.io/kube-openapi/pkg/internal/handler k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json k8s.io/kube-openapi/pkg/openapiconv k8s.io/kube-openapi/pkg/schemaconv diff --git a/web/api/v1/api.go b/web/api/v1/api.go index e1168e1a660..e9b0081b365 100644 --- a/web/api/v1/api.go +++ b/web/api/v1/api.go @@ -171,7 +171,7 @@ type TSDBAdminStats interface { CleanTombstones() error Delete(mint, maxt int64, ms ...*labels.Matcher) error Snapshot(dir string, withHead bool) error - Stats(statsByLabelName string) (*tsdb.Stats, error) + Stats(statsByLabelName string, limit int) (*tsdb.Stats, error) WALReplayStatus() (tsdb.WALReplayStatus, error) } @@ -1472,8 +1472,15 @@ func TSDBStatsFromIndexStats(stats []index.Stat) []TSDBStat { return result } -func (api *API) serveTSDBStatus(*http.Request) apiFuncResult { - s, err := api.db.Stats(labels.MetricName) +func (api *API) serveTSDBStatus(r *http.Request) apiFuncResult { + limit := 10 + if s := r.FormValue("limit"); s != "" { + var err error + if limit, err = strconv.Atoi(s); err != nil || limit < 1 { + return apiFuncResult{nil, &apiError{errorBadData, errors.New("limit must be a positive number")}, nil, nil} + } + } + s, err := api.db.Stats(labels.MetricName, limit) if err != nil { return apiFuncResult{nil, &apiError{errorInternal, err}, nil, nil} } @@ -1484,7 +1491,7 @@ func (api *API) serveTSDBStatus(*http.Request) apiFuncResult { chunkCount := int64(math.NaN()) for _, mF := range metrics { if *mF.Name == "prometheus_tsdb_head_chunks" { - m := *mF.Metric[0] + m := mF.Metric[0] if m.Gauge != nil { chunkCount = int64(m.Gauge.GetValue()) break diff --git a/web/api/v1/api_test.go b/web/api/v1/api_test.go index 620acd8629d..baee2189ef5 100644 --- a/web/api/v1/api_test.go +++ b/web/api/v1/api_test.go @@ -2622,7 +2622,7 @@ type fakeDB struct { func (f *fakeDB) CleanTombstones() error { return f.err } func (f *fakeDB) Delete(int64, int64, ...*labels.Matcher) error { return f.err } func (f *fakeDB) Snapshot(string, bool) error { return f.err } -func (f *fakeDB) Stats(statsByLabelName string) (_ *tsdb.Stats, retErr error) { +func (f *fakeDB) Stats(statsByLabelName string, limit int) (_ *tsdb.Stats, retErr error) { dbDir, err := os.MkdirTemp("", "tsdb-api-ready") if err != nil { return nil, err @@ -2636,7 +2636,7 @@ func (f *fakeDB) Stats(statsByLabelName string) (_ *tsdb.Stats, retErr error) { opts := tsdb.DefaultHeadOptions() opts.ChunkRange = 1000 h, _ := tsdb.NewHead(nil, nil, nil, nil, opts, nil) - return h.Stats(statsByLabelName), nil + return h.Stats(statsByLabelName, limit), nil } func (f *fakeDB) WALReplayStatus() (tsdb.WALReplayStatus, error) { @@ -3283,8 +3283,19 @@ func TestTSDBStatus(t *testing.T) { { db: tsdb, endpoint: tsdbStatusAPI, - - errType: errorNone, + errType: errorNone, + }, + { + db: tsdb, + endpoint: tsdbStatusAPI, + values: map[string][]string{"limit": {"20"}}, + errType: errorNone, + }, + { + db: tsdb, + endpoint: tsdbStatusAPI, + values: map[string][]string{"limit": {"0"}}, + errType: errorBadData, }, } { tc := tc diff --git a/web/federate_test.go b/web/federate_test.go index 61ef62f46de..6bc0ae212a8 100644 --- a/web/federate_test.go +++ b/web/federate_test.go @@ -251,7 +251,7 @@ func (notReadyReadStorage) StartTime() (int64, error) { return 0, errors.Wrap(tsdb.ErrNotReady, "wrap") } -func (notReadyReadStorage) Stats(string) (*tsdb.Stats, error) { +func (notReadyReadStorage) Stats(string, int) (*tsdb.Stats, error) { return nil, errors.Wrap(tsdb.ErrNotReady, "wrap") } @@ -378,7 +378,7 @@ func TestFederationWithNativeHistograms(t *testing.T) { body, err := io.ReadAll(res.Body) require.NoError(t, err) - p := textparse.NewProtobufParser(body) + p := textparse.NewProtobufParser(body, false) var actVec promql.Vector metricFamilies := 0 l := labels.Labels{} diff --git a/web/ui/embed.go b/web/ui/embed.go index b1c3c814bea..3d2fb492336 100644 --- a/web/ui/embed.go +++ b/web/ui/embed.go @@ -18,5 +18,5 @@ package ui import "embed" -//go:embed static/vendor/bootstrap4-glyphicons/css/bootstrap-glyphicons.min.css.gz static/vendor/bootstrap4-glyphicons/css/bootstrap-glyphicons.css.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.woff2.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.eot.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.eot.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.eot.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.svg.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.svg.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.woff2.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.woff.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.ttf.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.svg.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.ttf.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.woff.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.woff2.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.woff.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.ttf.gz static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.ttf.gz static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.woff.gz static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.woff2.gz static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.svg.gz static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.eot.gz static/vendor/bootstrap4-glyphicons/maps/glyphicons-fontawesome.min.css.gz static/vendor/bootstrap4-glyphicons/maps/glyphicons-fontawesome.less.gz static/vendor/bootstrap4-glyphicons/maps/glyphicons-fontawesome.css.gz static/vendor/bootstrap-4.5.2/css/bootstrap-grid.min.css.map.gz static/vendor/bootstrap-4.5.2/css/bootstrap.css.map.gz static/vendor/bootstrap-4.5.2/css/bootstrap-reboot.min.css.map.gz static/vendor/bootstrap-4.5.2/css/bootstrap-grid.css.gz static/vendor/bootstrap-4.5.2/css/bootstrap-grid.min.css.gz static/vendor/bootstrap-4.5.2/css/bootstrap-grid.css.map.gz static/vendor/bootstrap-4.5.2/css/bootstrap.css.gz static/vendor/bootstrap-4.5.2/css/bootstrap-reboot.min.css.gz static/vendor/bootstrap-4.5.2/css/bootstrap.min.css.gz static/vendor/bootstrap-4.5.2/css/bootstrap-reboot.css.gz static/vendor/bootstrap-4.5.2/css/bootstrap-reboot.css.map.gz static/vendor/bootstrap-4.5.2/css/bootstrap.min.css.map.gz static/vendor/bootstrap-4.5.2/js/bootstrap.bundle.min.js.map.gz static/vendor/bootstrap-4.5.2/js/bootstrap.bundle.js.map.gz static/vendor/bootstrap-4.5.2/js/bootstrap.min.js.map.gz static/vendor/bootstrap-4.5.2/js/bootstrap.min.js.gz static/vendor/bootstrap-4.5.2/js/bootstrap.bundle.min.js.gz static/vendor/bootstrap-4.5.2/js/bootstrap.js.map.gz static/vendor/bootstrap-4.5.2/js/bootstrap.js.gz static/vendor/bootstrap-4.5.2/js/bootstrap.bundle.js.gz static/vendor/js/jquery.hotkeys.js.gz static/vendor/js/jquery.selection.js.gz static/vendor/js/jquery-3.5.1.min.js.gz static/vendor/js/popper.min.js.gz static/vendor/rickshaw/rickshaw.min.css.gz static/vendor/rickshaw/vendor/d3.layout.min.js.gz static/vendor/rickshaw/vendor/d3.v3.js.gz static/vendor/rickshaw/rickshaw.min.js.gz static/css/prom_console.css.gz static/react/index.html.gz static/react/manifest.json.gz static/react/asset-manifest.json.gz static/react/static/css/main.4858e794.css.gz static/react/static/media/index.cd351d7c31d0d3fccf96.cjs.gz static/react/static/media/prometheus_logo_grey.3cf697e5443028ca5e5255b93c7906c5.svg.gz static/react/static/media/codicon.b3726f0165bf67ac6849.ttf.gz static/react/static/js/main.1542d2ea.js.LICENSE.txt.gz static/react/static/js/main.1542d2ea.js.gz static/react/favicon.ico.gz static/js/prom_console.js.gz +//go:embed static/js/prom_console.js.gz static/react/manifest.json.gz static/react/static/js/main.aed3c73f.js.gz static/react/static/js/main.aed3c73f.js.LICENSE.txt.gz static/react/static/media/prometheus_logo_grey.3cf697e5443028ca5e5255b93c7906c5.svg.gz static/react/static/media/codicon.b3726f0165bf67ac6849.ttf.gz static/react/static/media/index.cd351d7c31d0d3fccf96.cjs.gz static/react/static/css/main.4858e794.css.gz static/react/asset-manifest.json.gz static/react/favicon.ico.gz static/react/index.html.gz static/vendor/js/jquery.hotkeys.js.gz static/vendor/js/jquery-3.5.1.min.js.gz static/vendor/js/popper.min.js.gz static/vendor/js/jquery.selection.js.gz static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.eot.gz static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.ttf.gz static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.woff.gz static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.woff2.gz static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.svg.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.svg.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.eot.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.ttf.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.ttf.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.svg.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.ttf.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.woff.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.woff2.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.eot.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.svg.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.eot.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.woff.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.woff.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.woff2.gz static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.woff2.gz static/vendor/bootstrap4-glyphicons/maps/glyphicons-fontawesome.less.gz static/vendor/bootstrap4-glyphicons/maps/glyphicons-fontawesome.css.gz static/vendor/bootstrap4-glyphicons/maps/glyphicons-fontawesome.min.css.gz static/vendor/bootstrap4-glyphicons/css/bootstrap-glyphicons.css.gz static/vendor/bootstrap4-glyphicons/css/bootstrap-glyphicons.min.css.gz static/vendor/bootstrap-4.5.2/js/bootstrap.bundle.js.map.gz static/vendor/bootstrap-4.5.2/js/bootstrap.js.gz static/vendor/bootstrap-4.5.2/js/bootstrap.min.js.map.gz static/vendor/bootstrap-4.5.2/js/bootstrap.js.map.gz static/vendor/bootstrap-4.5.2/js/bootstrap.bundle.min.js.gz static/vendor/bootstrap-4.5.2/js/bootstrap.bundle.js.gz static/vendor/bootstrap-4.5.2/js/bootstrap.bundle.min.js.map.gz static/vendor/bootstrap-4.5.2/js/bootstrap.min.js.gz static/vendor/bootstrap-4.5.2/css/bootstrap-grid.min.css.map.gz static/vendor/bootstrap-4.5.2/css/bootstrap.css.map.gz static/vendor/bootstrap-4.5.2/css/bootstrap-grid.min.css.gz static/vendor/bootstrap-4.5.2/css/bootstrap-grid.css.gz static/vendor/bootstrap-4.5.2/css/bootstrap-grid.css.map.gz static/vendor/bootstrap-4.5.2/css/bootstrap-reboot.css.map.gz static/vendor/bootstrap-4.5.2/css/bootstrap-reboot.css.gz static/vendor/bootstrap-4.5.2/css/bootstrap-reboot.min.css.gz static/vendor/bootstrap-4.5.2/css/bootstrap-reboot.min.css.map.gz static/vendor/bootstrap-4.5.2/css/bootstrap.css.gz static/vendor/bootstrap-4.5.2/css/bootstrap.min.css.gz static/vendor/bootstrap-4.5.2/css/bootstrap.min.css.map.gz static/vendor/rickshaw/rickshaw.min.css.gz static/vendor/rickshaw/rickshaw.min.js.gz static/vendor/rickshaw/vendor/d3.layout.min.js.gz static/vendor/rickshaw/vendor/d3.v3.js.gz static/css/prom_console.css.gz var EmbedFS embed.FS diff --git a/web/ui/module/codemirror-promql/README.md b/web/ui/module/codemirror-promql/README.md index 441a81315b7..627e4fe15ad 100644 --- a/web/ui/module/codemirror-promql/README.md +++ b/web/ui/module/codemirror-promql/README.md @@ -1,7 +1,7 @@ CodeMirror-promql ================= -This project provides a mode for [CodeMirror Next](https://codemirror.net/6) that handles syntax highlighting, linting +This project provides a mode for [CodeMirror](https://codemirror.net/6/) that handles syntax highlighting, linting and autocompletion for PromQL ([Prometheus Query Language](https://prometheus.io/docs/introduction/overview/)). ![preview](https://user-images.githubusercontent.com/4548045/95660829-d5e4b680-0b2a-11eb-9ecb-41dca6396273.gif) @@ -15,7 +15,7 @@ npm install --save @prometheus-io/codemirror-promql ``` **Note:** You will have to manually install different packages that are part -of [CodeMirror Next](https://codemirror.net/6), as they are a peer dependency to this package. Here are the different +of [CodeMirror](https://codemirror.net/6/), as they are a peer dependency to this package. Here are the different packages you need to install: * **@codemirror/autocomplete** diff --git a/web/ui/module/codemirror-promql/package.json b/web/ui/module/codemirror-promql/package.json index e819319ee68..c7fafb13378 100644 --- a/web/ui/module/codemirror-promql/package.json +++ b/web/ui/module/codemirror-promql/package.json @@ -1,6 +1,6 @@ { "name": "@prometheus-io/codemirror-promql", - "version": "0.44.0", + "version": "0.45.0", "description": "a CodeMirror mode for the PromQL language", "types": "dist/esm/index.d.ts", "module": "dist/esm/index.js", @@ -29,21 +29,21 @@ }, "homepage": "https://github.com/prometheus/prometheus/blob/main/web/ui/module/codemirror-promql/README.md", "dependencies": { - "@prometheus-io/lezer-promql": "0.44.0", + "@prometheus-io/lezer-promql": "0.45.0", "lru-cache": "^6.0.0" }, "devDependencies": { - "@codemirror/autocomplete": "^6.4.0", - "@codemirror/language": "^6.4.0", - "@codemirror/lint": "^6.1.0", - "@codemirror/state": "^6.2.0", - "@codemirror/view": "^6.7.3", - "@lezer/common": "^1.0.2", - "@lezer/lr": "^1.3.1", - "@lezer/highlight": "^1.1.3", + "@codemirror/autocomplete": "^6.7.1", + "@codemirror/language": "^6.7.0", + "@codemirror/lint": "^6.2.2", + "@codemirror/state": "^6.2.1", + "@codemirror/view": "^6.13.0", + "@lezer/common": "^1.0.3", + "@lezer/lr": "^1.3.6", + "@lezer/highlight": "^1.1.6", "@types/lru-cache": "^5.1.1", "isomorphic-fetch": "^3.0.0", - "nock": "^13.3.0" + "nock": "^13.3.1" }, "peerDependencies": { "@codemirror/autocomplete": "^6.4.0", diff --git a/web/ui/module/lezer-promql/package.json b/web/ui/module/lezer-promql/package.json index 7daa567388c..847a9610e3c 100644 --- a/web/ui/module/lezer-promql/package.json +++ b/web/ui/module/lezer-promql/package.json @@ -1,6 +1,6 @@ { "name": "@prometheus-io/lezer-promql", - "version": "0.44.0", + "version": "0.45.0", "description": "lezer-based PromQL grammar", "main": "dist/index.cjs", "type": "module", @@ -30,9 +30,9 @@ "test": "NODE_OPTIONS=--experimental-vm-modules jest" }, "devDependencies": { - "@lezer/generator": "^1.2.2", - "@lezer/lr": "^1.3.1", - "@lezer/highlight": "^1.1.3" + "@lezer/generator": "^1.2.3", + "@lezer/lr": "^1.3.6", + "@lezer/highlight": "^1.1.6" }, "peerDependencies": { "@lezer/lr": "^1.2.3", diff --git a/web/ui/package-lock.json b/web/ui/package-lock.json index 1d3d1d3e34d..ac365d0d090 100644 --- a/web/ui/package-lock.json +++ b/web/ui/package-lock.json @@ -10,17 +10,17 @@ "module/*" ], "devDependencies": { - "@types/jest": "^29.4.0", + "@types/jest": "^29.5.2", "@types/node": "^17.0.45", - "eslint-config-prettier": "^8.6.0", + "eslint-config-prettier": "^8.8.0", "eslint-config-react-app": "^7.0.1", "eslint-plugin-prettier": "^4.2.1", - "jest-canvas-mock": "^2.4.0", + "jest-canvas-mock": "^2.5.1", "jest-fetch-mock": "^3.0.3", - "prettier": "^2.8.3", + "prettier": "^2.8.8", "react-scripts": "^5.0.1", - "ts-jest": "^29.0.5", - "typescript": "^4.9.4" + "ts-jest": "^29.1.0", + "typescript": "^4.9.5" }, "engines": { "npm": ">=7.0.0" @@ -28,24 +28,24 @@ }, "module/codemirror-promql": { "name": "@prometheus-io/codemirror-promql", - "version": "0.44.0", + "version": "0.45.0", "license": "Apache-2.0", "dependencies": { - "@prometheus-io/lezer-promql": "0.44.0", + "@prometheus-io/lezer-promql": "0.45.0", "lru-cache": "^6.0.0" }, "devDependencies": { - "@codemirror/autocomplete": "^6.4.0", - "@codemirror/language": "^6.4.0", - "@codemirror/lint": "^6.1.0", - "@codemirror/state": "^6.2.0", - "@codemirror/view": "^6.7.3", - "@lezer/common": "^1.0.2", - "@lezer/highlight": "^1.1.3", - "@lezer/lr": "^1.3.1", + "@codemirror/autocomplete": "^6.7.1", + "@codemirror/language": "^6.7.0", + "@codemirror/lint": "^6.2.2", + "@codemirror/state": "^6.2.1", + "@codemirror/view": "^6.13.0", + "@lezer/common": "^1.0.3", + "@lezer/highlight": "^1.1.6", + "@lezer/lr": "^1.3.6", "@types/lru-cache": "^5.1.1", "isomorphic-fetch": "^3.0.0", - "nock": "^13.3.0" + "nock": "^13.3.1" }, "engines": { "node": ">=12.0.0" @@ -61,12 +61,12 @@ }, "module/lezer-promql": { "name": "@prometheus-io/lezer-promql", - "version": "0.44.0", + "version": "0.45.0", "license": "Apache-2.0", "devDependencies": { - "@lezer/generator": "^1.2.2", - "@lezer/highlight": "^1.1.3", - "@lezer/lr": "^1.3.1" + "@lezer/generator": "^1.2.3", + "@lezer/highlight": "^1.1.6", + "@lezer/lr": "^1.3.6" }, "peerDependencies": { "@lezer/highlight": "^1.1.2", @@ -2080,9 +2080,9 @@ "dev": true }, "node_modules/@codemirror/autocomplete": { - "version": "6.4.0", - "resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.4.0.tgz", - "integrity": "sha512-HLF2PnZAm1s4kGs30EiqKMgD7XsYaQ0XJnMR0rofEWQ5t5D60SfqpDIkIh1ze5tiEbyUWm8+VJ6W1/erVvBMIA==", + "version": "6.7.1", + "resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.7.1.tgz", + "integrity": "sha512-hSxf9S0uB+GV+gBsjY1FZNo53e1FFdzPceRfCfD1gWOnV6o21GfB5J5Wg9G/4h76XZMPrF0A6OCK/Rz5+V1egg==", "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", @@ -2097,9 +2097,9 @@ } }, "node_modules/@codemirror/commands": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.2.0.tgz", - "integrity": "sha512-+00smmZBradoGFEkRjliN7BjqPh/Hx0KCHWOEibUmflUqZz2RwBTU0MrVovEEHozhx3AUSGcO/rl3/5f9e9Biw==", + "version": "6.2.4", + "resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.2.4.tgz", + "integrity": "sha512-42lmDqVH0ttfilLShReLXsDfASKLXzfyC36bzwcqzox9PlHulMcsUOfHXNo2X2aFMVNUoQ7j+d4q5bnfseYoOA==", "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.2.0", @@ -2108,9 +2108,9 @@ } }, "node_modules/@codemirror/language": { - "version": "6.4.0", - "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.4.0.tgz", - "integrity": "sha512-Wzb7GnNj8vnEtbPWiOy9H0m1fBtE28kepQNGLXekU2EEZv43BF865VKITUn+NoV8OpW6gRtvm29YEhqm46927Q==", + "version": "6.7.0", + "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.7.0.tgz", + "integrity": "sha512-4SMwe6Fwn57klCUsVN0y4/h/iWT+XIXFEmop2lIHHuWO0ubjCrF3suqSZLyOQlznxkNnNbOOfKe5HQbQGCAmTg==", "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", @@ -2121,9 +2121,9 @@ } }, "node_modules/@codemirror/lint": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.1.0.tgz", - "integrity": "sha512-mdvDQrjRmYPvQ3WrzF6Ewaao+NWERYtpthJvoQ3tK3t/44Ynhk8ZGjTSL9jMEv8CgSMogmt75X8ceOZRDSXHtQ==", + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.2.2.tgz", + "integrity": "sha512-kHGuynBHjqinp1Bx25D2hgH8a6Fh1m9rSmZFzBVTqPIXDIcZ6j3VI67DY8USGYpGrjrJys9R52eLxtfERGNozg==", "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", @@ -2131,9 +2131,9 @@ } }, "node_modules/@codemirror/search": { - "version": "6.2.3", - "resolved": "https://registry.npmjs.org/@codemirror/search/-/search-6.2.3.tgz", - "integrity": "sha512-V9n9233lopQhB1dyjsBK2Wc1i+8hcCqxl1wQ46c5HWWLePoe4FluV3TGHoZ04rBRlGjNyz9DTmpJErig8UE4jw==", + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/@codemirror/search/-/search-6.5.0.tgz", + "integrity": "sha512-64/M40YeJPToKvGO6p3fijo2vwUEj4nACEAXElCaYQ50HrXSvRaK+NHEhSh73WFBGdvIdhrV+lL9PdJy2RfCYA==", "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", @@ -2141,14 +2141,14 @@ } }, "node_modules/@codemirror/state": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.2.0.tgz", - "integrity": "sha512-69QXtcrsc3RYtOtd+GsvczJ319udtBf1PTrr2KbLWM/e2CXUPnh0Nz9AUo8WfhSQ7GeL8dPVNUmhQVgpmuaNGA==" + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.2.1.tgz", + "integrity": "sha512-RupHSZ8+OjNT38zU9fKH2sv+Dnlr8Eb8sl4NOnnqz95mCFTZUaiRP8Xv5MeeaG0px2b8Bnfe7YGwCV3nsBhbuw==" }, "node_modules/@codemirror/view": { - "version": "6.7.3", - "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.7.3.tgz", - "integrity": "sha512-Lt+4POnhXrZFfHOdPzXEHxrzwdy7cjqYlMkOWvoFGi6/bAsjzlFfr0NY3B15B/PGx+cDFgM1hlc12wvYeZbGLw==", + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.13.0.tgz", + "integrity": "sha512-oXTfJzHJ5Tl7f6T8ZO0HKf981zubxgKohjddLobbntbNZHlOZGMRL+pPZGtclDWFaFJWtGBYRGyNdjQ6Xsx5yA==", "dependencies": { "@codemirror/state": "^6.1.4", "style-mod": "^4.0.0", @@ -2476,42 +2476,33 @@ } }, "node_modules/@fortawesome/fontawesome-common-types": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-common-types/-/fontawesome-common-types-6.2.1.tgz", - "integrity": "sha512-Sz07mnQrTekFWLz5BMjOzHl/+NooTdW8F8kDQxjWwbpOJcnoSg4vUDng8d/WR1wOxM0O+CY9Zw0nR054riNYtQ==", + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-common-types/-/fontawesome-common-types-6.4.0.tgz", + "integrity": "sha512-HNii132xfomg5QVZw0HwXXpN22s7VBHQBv9CeOu9tfJnhsWQNd2lmTNi8CSrnw5B+5YOmzu1UoPAyxaXsJ6RgQ==", "hasInstallScript": true, "engines": { "node": ">=6" } }, "node_modules/@fortawesome/fontawesome-svg-core": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-svg-core/-/fontawesome-svg-core-6.2.1.tgz", - "integrity": "sha512-HELwwbCz6C1XEcjzyT1Jugmz2NNklMrSPjZOWMlc+ZsHIVk+XOvOXLGGQtFBwSyqfJDNgRq4xBCwWOaZ/d9DEA==", + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-svg-core/-/fontawesome-svg-core-6.4.0.tgz", + "integrity": "sha512-Bertv8xOiVELz5raB2FlXDPKt+m94MQ3JgDfsVbrqNpLU9+UE2E18GKjLKw+d3XbeYPqg1pzyQKGsrzbw+pPaw==", "hasInstallScript": true, "dependencies": { - "@fortawesome/fontawesome-common-types": "6.2.1" + "@fortawesome/fontawesome-common-types": "6.4.0" }, "engines": { "node": ">=6" } }, - "node_modules/@fortawesome/fontawesome-svg-core/node_modules/@fortawesome/fontawesome-common-types": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-common-types/-/fontawesome-common-types-6.2.1.tgz", - "integrity": "sha512-Sz07mnQrTekFWLz5BMjOzHl/+NooTdW8F8kDQxjWwbpOJcnoSg4vUDng8d/WR1wOxM0O+CY9Zw0nR054riNYtQ==", - "hasInstallScript": true, - "engines": { - "node": ">=6" - } - }, "node_modules/@fortawesome/free-solid-svg-icons": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/@fortawesome/free-solid-svg-icons/-/free-solid-svg-icons-6.2.1.tgz", - "integrity": "sha512-oKuqrP5jbfEPJWTij4sM+/RvgX+RMFwx3QZCZcK9PrBDgxC35zuc7AOFsyMjMd/PIFPeB2JxyqDr5zs/DZFPPw==", + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/@fortawesome/free-solid-svg-icons/-/free-solid-svg-icons-6.4.0.tgz", + "integrity": "sha512-kutPeRGWm8V5dltFP1zGjQOEAzaLZj4StdQhWVZnfGFCvAPVvHh8qk5bRrU4KXnRRRNni5tKQI9PBAdI6MP8nQ==", "hasInstallScript": true, "dependencies": { - "@fortawesome/fontawesome-common-types": "6.2.1" + "@fortawesome/fontawesome-common-types": "6.4.0" }, "engines": { "node": ">=6" @@ -3510,14 +3501,14 @@ "dev": true }, "node_modules/@lezer/common": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.0.2.tgz", - "integrity": "sha512-SVgiGtMnMnW3ActR8SXgsDhw7a0w0ChHSYAyAUxxrOiJ1OqYWEKk/xJd84tTSPo1mo6DXLObAJALNnd0Hrv7Ng==" + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.0.3.tgz", + "integrity": "sha512-JH4wAXCgUOcCGNekQPLhVeUtIqjH0yPBs7vvUdSjyQama9618IOKFJwkv2kcqdhF0my8hQEgCTEJU0GIgnahvA==" }, "node_modules/@lezer/generator": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/@lezer/generator/-/generator-1.2.2.tgz", - "integrity": "sha512-O//eH9jTPM1GnbZruuD23xU68Pkuragonn1DEIom4Kt/eJN/QFt7Vzvp1YjV/XBmoUKC+2ySPgrA5fMF9FMM2g==", + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@lezer/generator/-/generator-1.2.3.tgz", + "integrity": "sha512-xRmNryYbJpWs7novjWtQLCGHOj71B4X1QHQ4SgJqwm11tl6COEVAGhuFTXKX16JMJUhumdXaX8We6hEMd4clDg==", "dev": true, "dependencies": { "@lezer/common": "^1.0.2", @@ -3528,17 +3519,17 @@ } }, "node_modules/@lezer/highlight": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.1.3.tgz", - "integrity": "sha512-3vLKLPThO4td43lYRBygmMY18JN3CPh9w+XS2j8WC30vR4yZeFG4z1iFe4jXE43NtGqe//zHW5q8ENLlHvz9gw==", + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.1.6.tgz", + "integrity": "sha512-cmSJYa2us+r3SePpRCjN5ymCqCPv+zyXmDl0ciWtVaNiORT/MxM7ZgOMQZADD0o51qOaOg24qc/zBViOIwAjJg==", "dependencies": { "@lezer/common": "^1.0.0" } }, "node_modules/@lezer/lr": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.3.1.tgz", - "integrity": "sha512-+GymJB/+3gThkk2zHwseaJTI5oa4AuOuj1I2LCslAVq1dFZLSX8SAe4ZlJq1TjezteDXtF/+d4qeWz9JvnrG9Q==", + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.3.6.tgz", + "integrity": "sha512-IDhcWjfxwWACnatUi0GzWBCbochfqxo3LZZlS27LbJh8RVYYXXyR5Ck9659IhkWkhSW/kZlaaiJpUO+YZTUK+Q==", "dependencies": { "@lezer/common": "^1.0.0" } @@ -4209,13 +4200,24 @@ } }, "node_modules/@types/enzyme": { - "version": "3.10.12", - "resolved": "https://registry.npmjs.org/@types/enzyme/-/enzyme-3.10.12.tgz", - "integrity": "sha512-xryQlOEIe1TduDWAOphR0ihfebKFSWOXpIsk+70JskCfRfW+xALdnJ0r1ZOTo85F9Qsjk6vtlU7edTYHbls9tA==", + "version": "3.10.13", + "resolved": "https://registry.npmjs.org/@types/enzyme/-/enzyme-3.10.13.tgz", + "integrity": "sha512-FCtoUhmFsud0Yx9fmZk179GkdZ4U9B0GFte64/Md+W/agx0L5SxsIIbhLBOxIb9y2UfBA4WQnaG1Od/UsUQs9Q==", "dev": true, "dependencies": { "@types/cheerio": "*", - "@types/react": "*" + "@types/react": "^16" + } + }, + "node_modules/@types/enzyme/node_modules/@types/react": { + "version": "16.14.42", + "resolved": "https://registry.npmjs.org/@types/react/-/react-16.14.42.tgz", + "integrity": "sha512-r6lbqQBJsQ5JJ0fp5I1+F3weosNhk7jOEcKeusIlCDYUK6kCpvIkYCamBNqGyS6WEztYlT8wmAVgblV0HxOFoA==", + "dev": true, + "dependencies": { + "@types/prop-types": "*", + "@types/scheduler": "*", + "csstype": "^3.0.2" } }, "node_modules/@types/eslint": { @@ -4330,9 +4332,9 @@ } }, "node_modules/@types/jest": { - "version": "29.4.0", - "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.4.0.tgz", - "integrity": "sha512-VaywcGQ9tPorCX/Jkkni7RWGFfI11whqzs8dvxF41P17Z+z872thvEvlIbznjPJ02kl1HMX3LmLOonsj2n7HeQ==", + "version": "29.5.2", + "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.5.2.tgz", + "integrity": "sha512-mSoZVJF5YzGVCk+FsDxzDuH7s+SCkzrgKZzf0Z0T2WudhBUPoF6ktoTPC4R0ZoCPCV5xUvuU6ias5NvxcBcMMg==", "dev": true, "dependencies": { "expect": "^29.0.0", @@ -4466,9 +4468,9 @@ } }, "node_modules/@types/react-dom": { - "version": "17.0.18", - "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-17.0.18.tgz", - "integrity": "sha512-rLVtIfbwyur2iFKykP2w0pl/1unw26b5td16d5xMgp7/yjTHomkyxPYChFoCr/FtEX1lN9wY6lFj1qvKdS5kDw==", + "version": "17.0.20", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-17.0.20.tgz", + "integrity": "sha512-4pzIjSxDueZZ90F52mU3aPoogkHIoSIDG+oQ+wQK7Cy2B9S+MvOqY0uEA/qawKz381qrEDkvpwyt8Bm31I8sbA==", "dev": true, "dependencies": { "@types/react": "^17" @@ -4520,9 +4522,9 @@ "dev": true }, "node_modules/@types/sanitize-html": { - "version": "2.8.0", - "resolved": "https://registry.npmjs.org/@types/sanitize-html/-/sanitize-html-2.8.0.tgz", - "integrity": "sha512-Uih6caOm3DsBYnVGOYn0A9NoTNe1c4aPStmHC/YA2JrpP9kx//jzaRcIklFvSpvVQEcpl/ZCr4DgISSf/YxTvg==", + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/@types/sanitize-html/-/sanitize-html-2.9.0.tgz", + "integrity": "sha512-4fP/kEcKNj2u39IzrxWYuf/FnCCwwQCpif6wwY6ROUS1EPRIfWJjGkY3HIowY1EX/VbX5e86yq8AAE7UPMgATg==", "dev": true, "dependencies": { "htmlparser2": "^8.0.0" @@ -4573,9 +4575,9 @@ } }, "node_modules/@types/sinon": { - "version": "10.0.13", - "resolved": "https://registry.npmjs.org/@types/sinon/-/sinon-10.0.13.tgz", - "integrity": "sha512-UVjDqJblVNQYvVNUsj0PuYYw0ELRmgt1Nt5Vk0pT5f16ROGfcKJY8o1HVuMOJOpD727RrGB9EGvoaTQE5tgxZQ==", + "version": "10.0.15", + "resolved": "https://registry.npmjs.org/@types/sinon/-/sinon-10.0.15.tgz", + "integrity": "sha512-3lrFNQG0Kr2LDzvjyjB6AMJk4ge+8iYhQfdnSwIwlG88FUOV43kPcQqDZkDa/h3WSZy6i8Fr0BSjfQtB1B3xuQ==", "dev": true, "dependencies": { "@types/sinonjs__fake-timers": "*" @@ -7557,9 +7559,9 @@ "dev": true }, "node_modules/downshift": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/downshift/-/downshift-7.2.0.tgz", - "integrity": "sha512-dEn1Sshe7iTelUhmdbmiJhtIiwIBxBV8p15PuvEBh0qZcHXZnEt0geuCIIkCL4+ooaKRuLE0Wc+Fz9SwWuBIyg==", + "version": "7.6.0", + "resolved": "https://registry.npmjs.org/downshift/-/downshift-7.6.0.tgz", + "integrity": "sha512-VSoTVynTAsabou/hbZ6HJHUVhtBiVOjQoBsCPcQq5eAROIGP+9XKMp9asAKQ3cEcUP4oe0fFdD2pziUjhFY33Q==", "dependencies": { "@babel/runtime": "^7.14.8", "compute-scroll-into-view": "^2.0.4", @@ -7984,9 +7986,9 @@ } }, "node_modules/eslint-config-prettier": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-8.6.0.tgz", - "integrity": "sha512-bAF0eLpLVqP5oEVUFKpMA+NnRFICwn9X8B5jrR9FcqnYBuPbqWEjTEspPWMj5ye6czoSLDweCzSo3Ko7gGrZaA==", + "version": "8.8.0", + "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-8.8.0.tgz", + "integrity": "sha512-wLbQiFre3tdGgpDv67NQKnJuTlcUVYHas3k+DZCc2U2BadthoEY4B7hLPvAxaqdyOGCzuLfii2fqGph10va7oA==", "dev": true, "bin": { "eslint-config-prettier": "bin/cli.js" @@ -10550,9 +10552,9 @@ } }, "node_modules/jest-canvas-mock": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/jest-canvas-mock/-/jest-canvas-mock-2.4.0.tgz", - "integrity": "sha512-mmMpZzpmLzn5vepIaHk5HoH3Ka4WykbSoLuG/EKoJd0x0ID/t+INo1l8ByfcUJuDM+RIsL4QDg/gDnBbrj2/IQ==", + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/jest-canvas-mock/-/jest-canvas-mock-2.5.1.tgz", + "integrity": "sha512-IVnRiz+v4EYn3ydM/pBo8GW/J+nU/Hg5gHBQQOUQhdRyNfvHnabB8ReqARLO0p+kvQghqr4V0tA92CF3JcUSRg==", "dev": true, "dependencies": { "cssfontparser": "^1.2.1", @@ -12836,9 +12838,9 @@ } }, "node_modules/jquery": { - "version": "3.6.3", - "resolved": "https://registry.npmjs.org/jquery/-/jquery-3.6.3.tgz", - "integrity": "sha512-bZ5Sy3YzKo9Fyc8wH2iIQK4JImJ6R0GWI9kL1/k7Z91ZBNgkRXE6U0JfHIizZbort8ZunhSI3jw9I6253ahKfg==" + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/jquery/-/jquery-3.7.0.tgz", + "integrity": "sha512-umpJ0/k8X0MvD1ds0P9SfowREz2LenHsQaxSohMZ5OMNEU2r0tf8pdeEFTHMFxWVxKNyU9rTtK3CWzUCTKJUeQ==" }, "node_modules/jquery.flot.tooltip": { "version": "0.9.0", @@ -13488,11 +13490,11 @@ } }, "node_modules/moment-timezone": { - "version": "0.5.40", - "resolved": "https://registry.npmjs.org/moment-timezone/-/moment-timezone-0.5.40.tgz", - "integrity": "sha512-tWfmNkRYmBkPJz5mr9GVDn9vRlVZOTe6yqY92rFxiOdWXbjaR0+9LwQnZGGuNR63X456NqmEkbskte8tWL5ePg==", + "version": "0.5.43", + "resolved": "https://registry.npmjs.org/moment-timezone/-/moment-timezone-0.5.43.tgz", + "integrity": "sha512-72j3aNyuIsDxdF1i7CEgV2FfxM1r6aaqJyLB2vwb33mXYyoyLly+F1zbWqhA3/bVIoJ4szlUoMbUnVdid32NUQ==", "dependencies": { - "moment": ">= 2.9.0" + "moment": "^2.29.4" }, "engines": { "node": "*" @@ -13640,9 +13642,9 @@ } }, "node_modules/nock": { - "version": "13.3.0", - "resolved": "https://registry.npmjs.org/nock/-/nock-13.3.0.tgz", - "integrity": "sha512-HHqYQ6mBeiMc+N038w8LkMpDCRquCHWeNmN3v6645P3NhN2+qXOBqvPqo7Rt1VyCMzKhJ733wZqw5B7cQVFNPg==", + "version": "13.3.1", + "resolved": "https://registry.npmjs.org/nock/-/nock-13.3.1.tgz", + "integrity": "sha512-vHnopocZuI93p2ccivFyGuUfzjq2fxNyNurp7816mlT5V5HF4SzXu8lvLrVzBbNqzs+ODooZ6OksuSUNM7Njkw==", "dev": true, "dependencies": { "debug": "^4.1.0", @@ -15708,9 +15710,9 @@ } }, "node_modules/prettier": { - "version": "2.8.3", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.3.tgz", - "integrity": "sha512-tJ/oJ4amDihPoufT5sM0Z1SKEuKay8LfVAMlbbhnnkvt6BUserZylqo2PN+p9KeljLr0OHa2rXHU1T8reeoTrw==", + "version": "2.8.8", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.8.tgz", + "integrity": "sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==", "dev": true, "bin": { "prettier": "bin-prettier.js" @@ -18022,9 +18024,9 @@ "dev": true }, "node_modules/sanitize-html": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/sanitize-html/-/sanitize-html-2.8.1.tgz", - "integrity": "sha512-qK5neD0SaMxGwVv5txOYv05huC3o6ZAA4h5+7nJJgWMNFUNRjcjLO6FpwAtKzfKCZ0jrG6xTk6eVFskbvOGblg==", + "version": "2.10.0", + "resolved": "https://registry.npmjs.org/sanitize-html/-/sanitize-html-2.10.0.tgz", + "integrity": "sha512-JqdovUd81dG4k87vZt6uA6YhDfWkUGruUu/aPmXLxXi45gZExnt9Bnw/qeQU8oGf82vPyaE0vO4aH0PbobB9JQ==", "dependencies": { "deepmerge": "^4.2.2", "escape-string-regexp": "^4.0.0", @@ -18059,9 +18061,9 @@ "dev": true }, "node_modules/sass": { - "version": "1.57.1", - "resolved": "https://registry.npmjs.org/sass/-/sass-1.57.1.tgz", - "integrity": "sha512-O2+LwLS79op7GI0xZ8fqzF7X2m/m8WFfI02dHOdsK5R2ECeS5F62zrwg/relM1rjSLy7Vd/DiMNIvPrQGsA0jw==", + "version": "1.62.1", + "resolved": "https://registry.npmjs.org/sass/-/sass-1.62.1.tgz", + "integrity": "sha512-NHpxIzN29MXvWiuswfc1W3I0N8SXBd8UR26WntmDlRYf0bSADnwnOjsyMZ3lMezSlArD33Vs3YFhp7dWvL770A==", "dependencies": { "chokidar": ">=3.0.0 <4.0.0", "immutable": "^4.0.0", @@ -18071,7 +18073,7 @@ "sass": "sass.js" }, "engines": { - "node": ">=12.0.0" + "node": ">=14.0.0" } }, "node_modules/sass-loader": { @@ -19378,9 +19380,9 @@ "dev": true }, "node_modules/ts-jest": { - "version": "29.0.5", - "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.0.5.tgz", - "integrity": "sha512-PL3UciSgIpQ7f6XjVOmbi96vmDHUqAyqDr8YxzopDqX3kfgYtX1cuNeBjP+L9sFXi6nzsGGA6R3fP3DDDJyrxA==", + "version": "29.1.0", + "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.1.0.tgz", + "integrity": "sha512-ZhNr7Z4PcYa+JjMl62ir+zPiNJfXJN6E8hSLnaUKhOgqcn8vb3e537cpkd0FuAfRK3sR1LSqM1MOhliXNgOFPA==", "dev": true, "dependencies": { "bs-logger": "0.x", @@ -19403,7 +19405,7 @@ "@jest/types": "^29.0.0", "babel-jest": "^29.0.0", "jest": "^29.0.0", - "typescript": ">=4.3" + "typescript": ">=4.3 <6" }, "peerDependenciesMeta": { "@babel/core": { @@ -19572,9 +19574,9 @@ } }, "node_modules/typescript": { - "version": "4.9.4", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.4.tgz", - "integrity": "sha512-Uz+dTXYzxXXbsFpM86Wh3dKCxrQqUcVMxwU54orwlJjOpO3ao8L7j5lH+dWfTwgCwIuM9GQ2kvVotzYJMXTBZg==", + "version": "4.9.5", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz", + "integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==", "dev": true, "bin": { "tsc": "bin/tsc", @@ -20763,33 +20765,33 @@ }, "react-app": { "name": "@prometheus-io/app", - "version": "0.44.0", - "dependencies": { - "@codemirror/autocomplete": "^6.4.0", - "@codemirror/commands": "^6.2.0", - "@codemirror/language": "^6.4.0", - "@codemirror/lint": "^6.1.0", - "@codemirror/search": "^6.2.3", - "@codemirror/state": "^6.2.0", - "@codemirror/view": "^6.7.3", + "version": "0.45.0", + "dependencies": { + "@codemirror/autocomplete": "^6.7.1", + "@codemirror/commands": "^6.2.4", + "@codemirror/language": "^6.7.0", + "@codemirror/lint": "^6.2.2", + "@codemirror/search": "^6.5.0", + "@codemirror/state": "^6.2.1", + "@codemirror/view": "^6.13.0", "@forevolve/bootstrap-dark": "^2.1.1", - "@fortawesome/fontawesome-svg-core": "6.2.1", - "@fortawesome/free-solid-svg-icons": "6.2.1", + "@fortawesome/fontawesome-svg-core": "6.4.0", + "@fortawesome/free-solid-svg-icons": "6.4.0", "@fortawesome/react-fontawesome": "0.2.0", - "@lezer/common": "^1.0.2", - "@lezer/highlight": "^1.1.3", - "@lezer/lr": "^1.3.1", + "@lezer/common": "^1.0.3", + "@lezer/highlight": "^1.1.6", + "@lezer/lr": "^1.3.6", "@nexucis/fuzzy": "^0.4.1", "@nexucis/kvsearch": "^0.8.1", - "@prometheus-io/codemirror-promql": "0.44.0", + "@prometheus-io/codemirror-promql": "0.45.0", "bootstrap": "^4.6.2", "css.escape": "^1.5.1", - "downshift": "^7.2.0", + "downshift": "^7.6.0", "http-proxy-middleware": "^2.0.6", - "jquery": "^3.6.3", + "jquery": "^3.7.0", "jquery.flot.tooltip": "^0.9.0", "moment": "^2.29.4", - "moment-timezone": "^0.5.40", + "moment-timezone": "^0.5.43", "popper.js": "^1.14.3", "react": "^17.0.2", "react-copy-to-clipboard": "^5.1.0", @@ -20799,22 +20801,22 @@ "react-router-dom": "^5.3.4", "react-test-renderer": "^17.0.2", "reactstrap": "^8.10.1", - "sanitize-html": "^2.8.1", - "sass": "1.57.1", + "sanitize-html": "^2.10.0", + "sass": "1.62.1", "tempusdominus-bootstrap-4": "^5.39.2", "tempusdominus-core": "^5.19.3" }, "devDependencies": { "@testing-library/react-hooks": "^7.0.2", - "@types/enzyme": "^3.10.12", + "@types/enzyme": "^3.10.13", "@types/flot": "0.0.32", "@types/jquery": "^3.5.16", - "@types/react": "^17.0.53", + "@types/react": "^17.0.60", "@types/react-copy-to-clipboard": "^5.0.4", - "@types/react-dom": "^17.0.18", + "@types/react-dom": "^17.0.20", "@types/react-router-dom": "^5.3.3", - "@types/sanitize-html": "^2.8.0", - "@types/sinon": "^10.0.13", + "@types/sanitize-html": "^2.9.0", + "@types/sinon": "^10.0.15", "@wojtekmaj/enzyme-adapter-react-17": "^0.8.0", "enzyme": "^3.11.0", "enzyme-to-json": "^3.6.2", @@ -20824,6 +20826,17 @@ "optionalDependencies": { "fsevents": "^2.3.2" } + }, + "react-app/node_modules/@types/react": { + "version": "17.0.60", + "resolved": "https://registry.npmjs.org/@types/react/-/react-17.0.60.tgz", + "integrity": "sha512-pCH7bqWIfzHs3D+PDs3O/COCQJka+Kcw3RnO9rFA2zalqoXg7cNjJDh6mZ7oRtY1wmY4LVwDdAbA1F7Z8tv3BQ==", + "dev": true, + "dependencies": { + "@types/prop-types": "*", + "@types/scheduler": "*", + "csstype": "^3.0.2" + } } }, "dependencies": { @@ -22224,9 +22237,9 @@ "dev": true }, "@codemirror/autocomplete": { - "version": "6.4.0", - "resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.4.0.tgz", - "integrity": "sha512-HLF2PnZAm1s4kGs30EiqKMgD7XsYaQ0XJnMR0rofEWQ5t5D60SfqpDIkIh1ze5tiEbyUWm8+VJ6W1/erVvBMIA==", + "version": "6.7.1", + "resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.7.1.tgz", + "integrity": "sha512-hSxf9S0uB+GV+gBsjY1FZNo53e1FFdzPceRfCfD1gWOnV6o21GfB5J5Wg9G/4h76XZMPrF0A6OCK/Rz5+V1egg==", "requires": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", @@ -22235,9 +22248,9 @@ } }, "@codemirror/commands": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.2.0.tgz", - "integrity": "sha512-+00smmZBradoGFEkRjliN7BjqPh/Hx0KCHWOEibUmflUqZz2RwBTU0MrVovEEHozhx3AUSGcO/rl3/5f9e9Biw==", + "version": "6.2.4", + "resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.2.4.tgz", + "integrity": "sha512-42lmDqVH0ttfilLShReLXsDfASKLXzfyC36bzwcqzox9PlHulMcsUOfHXNo2X2aFMVNUoQ7j+d4q5bnfseYoOA==", "requires": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.2.0", @@ -22246,9 +22259,9 @@ } }, "@codemirror/language": { - "version": "6.4.0", - "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.4.0.tgz", - "integrity": "sha512-Wzb7GnNj8vnEtbPWiOy9H0m1fBtE28kepQNGLXekU2EEZv43BF865VKITUn+NoV8OpW6gRtvm29YEhqm46927Q==", + "version": "6.7.0", + "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.7.0.tgz", + "integrity": "sha512-4SMwe6Fwn57klCUsVN0y4/h/iWT+XIXFEmop2lIHHuWO0ubjCrF3suqSZLyOQlznxkNnNbOOfKe5HQbQGCAmTg==", "requires": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", @@ -22259,9 +22272,9 @@ } }, "@codemirror/lint": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.1.0.tgz", - "integrity": "sha512-mdvDQrjRmYPvQ3WrzF6Ewaao+NWERYtpthJvoQ3tK3t/44Ynhk8ZGjTSL9jMEv8CgSMogmt75X8ceOZRDSXHtQ==", + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.2.2.tgz", + "integrity": "sha512-kHGuynBHjqinp1Bx25D2hgH8a6Fh1m9rSmZFzBVTqPIXDIcZ6j3VI67DY8USGYpGrjrJys9R52eLxtfERGNozg==", "requires": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", @@ -22269,9 +22282,9 @@ } }, "@codemirror/search": { - "version": "6.2.3", - "resolved": "https://registry.npmjs.org/@codemirror/search/-/search-6.2.3.tgz", - "integrity": "sha512-V9n9233lopQhB1dyjsBK2Wc1i+8hcCqxl1wQ46c5HWWLePoe4FluV3TGHoZ04rBRlGjNyz9DTmpJErig8UE4jw==", + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/@codemirror/search/-/search-6.5.0.tgz", + "integrity": "sha512-64/M40YeJPToKvGO6p3fijo2vwUEj4nACEAXElCaYQ50HrXSvRaK+NHEhSh73WFBGdvIdhrV+lL9PdJy2RfCYA==", "requires": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", @@ -22279,14 +22292,14 @@ } }, "@codemirror/state": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.2.0.tgz", - "integrity": "sha512-69QXtcrsc3RYtOtd+GsvczJ319udtBf1PTrr2KbLWM/e2CXUPnh0Nz9AUo8WfhSQ7GeL8dPVNUmhQVgpmuaNGA==" + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.2.1.tgz", + "integrity": "sha512-RupHSZ8+OjNT38zU9fKH2sv+Dnlr8Eb8sl4NOnnqz95mCFTZUaiRP8Xv5MeeaG0px2b8Bnfe7YGwCV3nsBhbuw==" }, "@codemirror/view": { - "version": "6.7.3", - "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.7.3.tgz", - "integrity": "sha512-Lt+4POnhXrZFfHOdPzXEHxrzwdy7cjqYlMkOWvoFGi6/bAsjzlFfr0NY3B15B/PGx+cDFgM1hlc12wvYeZbGLw==", + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.13.0.tgz", + "integrity": "sha512-oXTfJzHJ5Tl7f6T8ZO0HKf981zubxgKohjddLobbntbNZHlOZGMRL+pPZGtclDWFaFJWtGBYRGyNdjQ6Xsx5yA==", "requires": { "@codemirror/state": "^6.1.4", "style-mod": "^4.0.0", @@ -22463,31 +22476,24 @@ } }, "@fortawesome/fontawesome-common-types": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-common-types/-/fontawesome-common-types-6.2.1.tgz", - "integrity": "sha512-Sz07mnQrTekFWLz5BMjOzHl/+NooTdW8F8kDQxjWwbpOJcnoSg4vUDng8d/WR1wOxM0O+CY9Zw0nR054riNYtQ==" + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-common-types/-/fontawesome-common-types-6.4.0.tgz", + "integrity": "sha512-HNii132xfomg5QVZw0HwXXpN22s7VBHQBv9CeOu9tfJnhsWQNd2lmTNi8CSrnw5B+5YOmzu1UoPAyxaXsJ6RgQ==" }, "@fortawesome/fontawesome-svg-core": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-svg-core/-/fontawesome-svg-core-6.2.1.tgz", - "integrity": "sha512-HELwwbCz6C1XEcjzyT1Jugmz2NNklMrSPjZOWMlc+ZsHIVk+XOvOXLGGQtFBwSyqfJDNgRq4xBCwWOaZ/d9DEA==", + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-svg-core/-/fontawesome-svg-core-6.4.0.tgz", + "integrity": "sha512-Bertv8xOiVELz5raB2FlXDPKt+m94MQ3JgDfsVbrqNpLU9+UE2E18GKjLKw+d3XbeYPqg1pzyQKGsrzbw+pPaw==", "requires": { - "@fortawesome/fontawesome-common-types": "6.2.1" - }, - "dependencies": { - "@fortawesome/fontawesome-common-types": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-common-types/-/fontawesome-common-types-6.2.1.tgz", - "integrity": "sha512-Sz07mnQrTekFWLz5BMjOzHl/+NooTdW8F8kDQxjWwbpOJcnoSg4vUDng8d/WR1wOxM0O+CY9Zw0nR054riNYtQ==" - } + "@fortawesome/fontawesome-common-types": "6.4.0" } }, "@fortawesome/free-solid-svg-icons": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/@fortawesome/free-solid-svg-icons/-/free-solid-svg-icons-6.2.1.tgz", - "integrity": "sha512-oKuqrP5jbfEPJWTij4sM+/RvgX+RMFwx3QZCZcK9PrBDgxC35zuc7AOFsyMjMd/PIFPeB2JxyqDr5zs/DZFPPw==", + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/@fortawesome/free-solid-svg-icons/-/free-solid-svg-icons-6.4.0.tgz", + "integrity": "sha512-kutPeRGWm8V5dltFP1zGjQOEAzaLZj4StdQhWVZnfGFCvAPVvHh8qk5bRrU4KXnRRRNni5tKQI9PBAdI6MP8nQ==", "requires": { - "@fortawesome/fontawesome-common-types": "6.2.1" + "@fortawesome/fontawesome-common-types": "6.4.0" } }, "@fortawesome/react-fontawesome": { @@ -23277,14 +23283,14 @@ "dev": true }, "@lezer/common": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.0.2.tgz", - "integrity": "sha512-SVgiGtMnMnW3ActR8SXgsDhw7a0w0ChHSYAyAUxxrOiJ1OqYWEKk/xJd84tTSPo1mo6DXLObAJALNnd0Hrv7Ng==" + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.0.3.tgz", + "integrity": "sha512-JH4wAXCgUOcCGNekQPLhVeUtIqjH0yPBs7vvUdSjyQama9618IOKFJwkv2kcqdhF0my8hQEgCTEJU0GIgnahvA==" }, "@lezer/generator": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/@lezer/generator/-/generator-1.2.2.tgz", - "integrity": "sha512-O//eH9jTPM1GnbZruuD23xU68Pkuragonn1DEIom4Kt/eJN/QFt7Vzvp1YjV/XBmoUKC+2ySPgrA5fMF9FMM2g==", + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@lezer/generator/-/generator-1.2.3.tgz", + "integrity": "sha512-xRmNryYbJpWs7novjWtQLCGHOj71B4X1QHQ4SgJqwm11tl6COEVAGhuFTXKX16JMJUhumdXaX8We6hEMd4clDg==", "dev": true, "requires": { "@lezer/common": "^1.0.2", @@ -23292,17 +23298,17 @@ } }, "@lezer/highlight": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.1.3.tgz", - "integrity": "sha512-3vLKLPThO4td43lYRBygmMY18JN3CPh9w+XS2j8WC30vR4yZeFG4z1iFe4jXE43NtGqe//zHW5q8ENLlHvz9gw==", + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.1.6.tgz", + "integrity": "sha512-cmSJYa2us+r3SePpRCjN5ymCqCPv+zyXmDl0ciWtVaNiORT/MxM7ZgOMQZADD0o51qOaOg24qc/zBViOIwAjJg==", "requires": { "@lezer/common": "^1.0.0" } }, "@lezer/lr": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.3.1.tgz", - "integrity": "sha512-+GymJB/+3gThkk2zHwseaJTI5oa4AuOuj1I2LCslAVq1dFZLSX8SAe4ZlJq1TjezteDXtF/+d4qeWz9JvnrG9Q==", + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.3.6.tgz", + "integrity": "sha512-IDhcWjfxwWACnatUi0GzWBCbochfqxo3LZZlS27LbJh8RVYYXXyR5Ck9659IhkWkhSW/kZlaaiJpUO+YZTUK+Q==", "requires": { "@lezer/common": "^1.0.0" } @@ -23401,45 +23407,45 @@ "@prometheus-io/app": { "version": "file:react-app", "requires": { - "@codemirror/autocomplete": "^6.4.0", - "@codemirror/commands": "^6.2.0", - "@codemirror/language": "^6.4.0", - "@codemirror/lint": "^6.1.0", - "@codemirror/search": "^6.2.3", - "@codemirror/state": "^6.2.0", - "@codemirror/view": "^6.7.3", + "@codemirror/autocomplete": "^6.7.1", + "@codemirror/commands": "^6.2.4", + "@codemirror/language": "^6.7.0", + "@codemirror/lint": "^6.2.2", + "@codemirror/search": "^6.5.0", + "@codemirror/state": "^6.2.1", + "@codemirror/view": "^6.13.0", "@forevolve/bootstrap-dark": "^2.1.1", - "@fortawesome/fontawesome-svg-core": "6.2.1", - "@fortawesome/free-solid-svg-icons": "6.2.1", + "@fortawesome/fontawesome-svg-core": "6.4.0", + "@fortawesome/free-solid-svg-icons": "6.4.0", "@fortawesome/react-fontawesome": "0.2.0", - "@lezer/common": "^1.0.2", - "@lezer/highlight": "^1.1.3", - "@lezer/lr": "^1.3.1", + "@lezer/common": "^1.0.3", + "@lezer/highlight": "^1.1.6", + "@lezer/lr": "^1.3.6", "@nexucis/fuzzy": "^0.4.1", "@nexucis/kvsearch": "^0.8.1", - "@prometheus-io/codemirror-promql": "0.44.0", + "@prometheus-io/codemirror-promql": "0.45.0", "@testing-library/react-hooks": "^7.0.2", - "@types/enzyme": "^3.10.12", + "@types/enzyme": "^3.10.13", "@types/flot": "0.0.32", "@types/jquery": "^3.5.16", - "@types/react": "^17.0.53", + "@types/react": "^17.0.60", "@types/react-copy-to-clipboard": "^5.0.4", - "@types/react-dom": "^17.0.18", + "@types/react-dom": "^17.0.20", "@types/react-router-dom": "^5.3.3", - "@types/sanitize-html": "^2.8.0", - "@types/sinon": "^10.0.13", + "@types/sanitize-html": "^2.9.0", + "@types/sinon": "^10.0.15", "@wojtekmaj/enzyme-adapter-react-17": "^0.8.0", "bootstrap": "^4.6.2", "css.escape": "^1.5.1", - "downshift": "^7.2.0", + "downshift": "^7.6.0", "enzyme": "^3.11.0", "enzyme-to-json": "^3.6.2", "fsevents": "^2.3.2", "http-proxy-middleware": "^2.0.6", - "jquery": "^3.6.3", + "jquery": "^3.7.0", "jquery.flot.tooltip": "^0.9.0", "moment": "^2.29.4", - "moment-timezone": "^0.5.40", + "moment-timezone": "^0.5.43", "mutationobserver-shim": "^0.3.7", "popper.js": "^1.14.3", "react": "^17.0.2", @@ -23450,37 +23456,50 @@ "react-router-dom": "^5.3.4", "react-test-renderer": "^17.0.2", "reactstrap": "^8.10.1", - "sanitize-html": "^2.8.1", - "sass": "1.57.1", + "sanitize-html": "^2.10.0", + "sass": "1.62.1", "sinon": "^14.0.2", "tempusdominus-bootstrap-4": "^5.39.2", "tempusdominus-core": "^5.19.3" + }, + "dependencies": { + "@types/react": { + "version": "17.0.60", + "resolved": "https://registry.npmjs.org/@types/react/-/react-17.0.60.tgz", + "integrity": "sha512-pCH7bqWIfzHs3D+PDs3O/COCQJka+Kcw3RnO9rFA2zalqoXg7cNjJDh6mZ7oRtY1wmY4LVwDdAbA1F7Z8tv3BQ==", + "dev": true, + "requires": { + "@types/prop-types": "*", + "@types/scheduler": "*", + "csstype": "^3.0.2" + } + } } }, "@prometheus-io/codemirror-promql": { "version": "file:module/codemirror-promql", "requires": { - "@codemirror/autocomplete": "^6.4.0", - "@codemirror/language": "^6.4.0", - "@codemirror/lint": "^6.1.0", - "@codemirror/state": "^6.2.0", - "@codemirror/view": "^6.7.3", - "@lezer/common": "^1.0.2", - "@lezer/highlight": "^1.1.3", - "@lezer/lr": "^1.3.1", - "@prometheus-io/lezer-promql": "0.44.0", + "@codemirror/autocomplete": "^6.7.1", + "@codemirror/language": "^6.7.0", + "@codemirror/lint": "^6.2.2", + "@codemirror/state": "^6.2.1", + "@codemirror/view": "^6.13.0", + "@lezer/common": "^1.0.3", + "@lezer/highlight": "^1.1.6", + "@lezer/lr": "^1.3.6", + "@prometheus-io/lezer-promql": "0.45.0", "@types/lru-cache": "^5.1.1", "isomorphic-fetch": "^3.0.0", "lru-cache": "^6.0.0", - "nock": "^13.3.0" + "nock": "^13.3.1" } }, "@prometheus-io/lezer-promql": { "version": "file:module/lezer-promql", "requires": { - "@lezer/generator": "^1.2.2", - "@lezer/highlight": "^1.1.3", - "@lezer/lr": "^1.3.1" + "@lezer/generator": "^1.2.3", + "@lezer/highlight": "^1.1.6", + "@lezer/lr": "^1.3.6" } }, "@rollup/plugin-babel": { @@ -23851,13 +23870,26 @@ } }, "@types/enzyme": { - "version": "3.10.12", - "resolved": "https://registry.npmjs.org/@types/enzyme/-/enzyme-3.10.12.tgz", - "integrity": "sha512-xryQlOEIe1TduDWAOphR0ihfebKFSWOXpIsk+70JskCfRfW+xALdnJ0r1ZOTo85F9Qsjk6vtlU7edTYHbls9tA==", + "version": "3.10.13", + "resolved": "https://registry.npmjs.org/@types/enzyme/-/enzyme-3.10.13.tgz", + "integrity": "sha512-FCtoUhmFsud0Yx9fmZk179GkdZ4U9B0GFte64/Md+W/agx0L5SxsIIbhLBOxIb9y2UfBA4WQnaG1Od/UsUQs9Q==", "dev": true, "requires": { "@types/cheerio": "*", - "@types/react": "*" + "@types/react": "^16" + }, + "dependencies": { + "@types/react": { + "version": "16.14.42", + "resolved": "https://registry.npmjs.org/@types/react/-/react-16.14.42.tgz", + "integrity": "sha512-r6lbqQBJsQ5JJ0fp5I1+F3weosNhk7jOEcKeusIlCDYUK6kCpvIkYCamBNqGyS6WEztYlT8wmAVgblV0HxOFoA==", + "dev": true, + "requires": { + "@types/prop-types": "*", + "@types/scheduler": "*", + "csstype": "^3.0.2" + } + } } }, "@types/eslint": { @@ -23972,9 +24004,9 @@ } }, "@types/jest": { - "version": "29.4.0", - "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.4.0.tgz", - "integrity": "sha512-VaywcGQ9tPorCX/Jkkni7RWGFfI11whqzs8dvxF41P17Z+z872thvEvlIbznjPJ02kl1HMX3LmLOonsj2n7HeQ==", + "version": "29.5.2", + "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.5.2.tgz", + "integrity": "sha512-mSoZVJF5YzGVCk+FsDxzDuH7s+SCkzrgKZzf0Z0T2WudhBUPoF6ktoTPC4R0ZoCPCV5xUvuU6ias5NvxcBcMMg==", "dev": true, "requires": { "expect": "^29.0.0", @@ -24101,9 +24133,9 @@ } }, "@types/react-dom": { - "version": "17.0.18", - "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-17.0.18.tgz", - "integrity": "sha512-rLVtIfbwyur2iFKykP2w0pl/1unw26b5td16d5xMgp7/yjTHomkyxPYChFoCr/FtEX1lN9wY6lFj1qvKdS5kDw==", + "version": "17.0.20", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-17.0.20.tgz", + "integrity": "sha512-4pzIjSxDueZZ90F52mU3aPoogkHIoSIDG+oQ+wQK7Cy2B9S+MvOqY0uEA/qawKz381qrEDkvpwyt8Bm31I8sbA==", "dev": true, "requires": { "@types/react": "^17" @@ -24155,9 +24187,9 @@ "dev": true }, "@types/sanitize-html": { - "version": "2.8.0", - "resolved": "https://registry.npmjs.org/@types/sanitize-html/-/sanitize-html-2.8.0.tgz", - "integrity": "sha512-Uih6caOm3DsBYnVGOYn0A9NoTNe1c4aPStmHC/YA2JrpP9kx//jzaRcIklFvSpvVQEcpl/ZCr4DgISSf/YxTvg==", + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/@types/sanitize-html/-/sanitize-html-2.9.0.tgz", + "integrity": "sha512-4fP/kEcKNj2u39IzrxWYuf/FnCCwwQCpif6wwY6ROUS1EPRIfWJjGkY3HIowY1EX/VbX5e86yq8AAE7UPMgATg==", "dev": true, "requires": { "htmlparser2": "^8.0.0" @@ -24203,9 +24235,9 @@ } }, "@types/sinon": { - "version": "10.0.13", - "resolved": "https://registry.npmjs.org/@types/sinon/-/sinon-10.0.13.tgz", - "integrity": "sha512-UVjDqJblVNQYvVNUsj0PuYYw0ELRmgt1Nt5Vk0pT5f16ROGfcKJY8o1HVuMOJOpD727RrGB9EGvoaTQE5tgxZQ==", + "version": "10.0.15", + "resolved": "https://registry.npmjs.org/@types/sinon/-/sinon-10.0.15.tgz", + "integrity": "sha512-3lrFNQG0Kr2LDzvjyjB6AMJk4ge+8iYhQfdnSwIwlG88FUOV43kPcQqDZkDa/h3WSZy6i8Fr0BSjfQtB1B3xuQ==", "dev": true, "requires": { "@types/sinonjs__fake-timers": "*" @@ -26441,9 +26473,9 @@ "dev": true }, "downshift": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/downshift/-/downshift-7.2.0.tgz", - "integrity": "sha512-dEn1Sshe7iTelUhmdbmiJhtIiwIBxBV8p15PuvEBh0qZcHXZnEt0geuCIIkCL4+ooaKRuLE0Wc+Fz9SwWuBIyg==", + "version": "7.6.0", + "resolved": "https://registry.npmjs.org/downshift/-/downshift-7.6.0.tgz", + "integrity": "sha512-VSoTVynTAsabou/hbZ6HJHUVhtBiVOjQoBsCPcQq5eAROIGP+9XKMp9asAKQ3cEcUP4oe0fFdD2pziUjhFY33Q==", "requires": { "@babel/runtime": "^7.14.8", "compute-scroll-into-view": "^2.0.4", @@ -26779,9 +26811,9 @@ } }, "eslint-config-prettier": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-8.6.0.tgz", - "integrity": "sha512-bAF0eLpLVqP5oEVUFKpMA+NnRFICwn9X8B5jrR9FcqnYBuPbqWEjTEspPWMj5ye6czoSLDweCzSo3Ko7gGrZaA==", + "version": "8.8.0", + "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-8.8.0.tgz", + "integrity": "sha512-wLbQiFre3tdGgpDv67NQKnJuTlcUVYHas3k+DZCc2U2BadthoEY4B7hLPvAxaqdyOGCzuLfii2fqGph10va7oA==", "dev": true, "requires": {} }, @@ -28650,9 +28682,9 @@ } }, "jest-canvas-mock": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/jest-canvas-mock/-/jest-canvas-mock-2.4.0.tgz", - "integrity": "sha512-mmMpZzpmLzn5vepIaHk5HoH3Ka4WykbSoLuG/EKoJd0x0ID/t+INo1l8ByfcUJuDM+RIsL4QDg/gDnBbrj2/IQ==", + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/jest-canvas-mock/-/jest-canvas-mock-2.5.1.tgz", + "integrity": "sha512-IVnRiz+v4EYn3ydM/pBo8GW/J+nU/Hg5gHBQQOUQhdRyNfvHnabB8ReqARLO0p+kvQghqr4V0tA92CF3JcUSRg==", "dev": true, "requires": { "cssfontparser": "^1.2.1", @@ -30498,9 +30530,9 @@ } }, "jquery": { - "version": "3.6.3", - "resolved": "https://registry.npmjs.org/jquery/-/jquery-3.6.3.tgz", - "integrity": "sha512-bZ5Sy3YzKo9Fyc8wH2iIQK4JImJ6R0GWI9kL1/k7Z91ZBNgkRXE6U0JfHIizZbort8ZunhSI3jw9I6253ahKfg==" + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/jquery/-/jquery-3.7.0.tgz", + "integrity": "sha512-umpJ0/k8X0MvD1ds0P9SfowREz2LenHsQaxSohMZ5OMNEU2r0tf8pdeEFTHMFxWVxKNyU9rTtK3CWzUCTKJUeQ==" }, "jquery.flot.tooltip": { "version": "0.9.0", @@ -31015,11 +31047,11 @@ "integrity": "sha512-5LC9SOxjSc2HF6vO2CyuTDNivEdoz2IvyJJGj6X8DJ0eFyfszE0QiEd+iXmBvUP3WHxSjFH/vIsA0EN00cgr8w==" }, "moment-timezone": { - "version": "0.5.40", - "resolved": "https://registry.npmjs.org/moment-timezone/-/moment-timezone-0.5.40.tgz", - "integrity": "sha512-tWfmNkRYmBkPJz5mr9GVDn9vRlVZOTe6yqY92rFxiOdWXbjaR0+9LwQnZGGuNR63X456NqmEkbskte8tWL5ePg==", + "version": "0.5.43", + "resolved": "https://registry.npmjs.org/moment-timezone/-/moment-timezone-0.5.43.tgz", + "integrity": "sha512-72j3aNyuIsDxdF1i7CEgV2FfxM1r6aaqJyLB2vwb33mXYyoyLly+F1zbWqhA3/bVIoJ4szlUoMbUnVdid32NUQ==", "requires": { - "moment": ">= 2.9.0" + "moment": "^2.29.4" } }, "moo": { @@ -31146,9 +31178,9 @@ } }, "nock": { - "version": "13.3.0", - "resolved": "https://registry.npmjs.org/nock/-/nock-13.3.0.tgz", - "integrity": "sha512-HHqYQ6mBeiMc+N038w8LkMpDCRquCHWeNmN3v6645P3NhN2+qXOBqvPqo7Rt1VyCMzKhJ733wZqw5B7cQVFNPg==", + "version": "13.3.1", + "resolved": "https://registry.npmjs.org/nock/-/nock-13.3.1.tgz", + "integrity": "sha512-vHnopocZuI93p2ccivFyGuUfzjq2fxNyNurp7816mlT5V5HF4SzXu8lvLrVzBbNqzs+ODooZ6OksuSUNM7Njkw==", "dev": true, "requires": { "debug": "^4.1.0", @@ -32479,9 +32511,9 @@ "dev": true }, "prettier": { - "version": "2.8.3", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.3.tgz", - "integrity": "sha512-tJ/oJ4amDihPoufT5sM0Z1SKEuKay8LfVAMlbbhnnkvt6BUserZylqo2PN+p9KeljLr0OHa2rXHU1T8reeoTrw==", + "version": "2.8.8", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.8.tgz", + "integrity": "sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==", "dev": true }, "prettier-linter-helpers": { @@ -34265,9 +34297,9 @@ "dev": true }, "sanitize-html": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/sanitize-html/-/sanitize-html-2.8.1.tgz", - "integrity": "sha512-qK5neD0SaMxGwVv5txOYv05huC3o6ZAA4h5+7nJJgWMNFUNRjcjLO6FpwAtKzfKCZ0jrG6xTk6eVFskbvOGblg==", + "version": "2.10.0", + "resolved": "https://registry.npmjs.org/sanitize-html/-/sanitize-html-2.10.0.tgz", + "integrity": "sha512-JqdovUd81dG4k87vZt6uA6YhDfWkUGruUu/aPmXLxXi45gZExnt9Bnw/qeQU8oGf82vPyaE0vO4aH0PbobB9JQ==", "requires": { "deepmerge": "^4.2.2", "escape-string-regexp": "^4.0.0", @@ -34297,9 +34329,9 @@ "dev": true }, "sass": { - "version": "1.57.1", - "resolved": "https://registry.npmjs.org/sass/-/sass-1.57.1.tgz", - "integrity": "sha512-O2+LwLS79op7GI0xZ8fqzF7X2m/m8WFfI02dHOdsK5R2ECeS5F62zrwg/relM1rjSLy7Vd/DiMNIvPrQGsA0jw==", + "version": "1.62.1", + "resolved": "https://registry.npmjs.org/sass/-/sass-1.62.1.tgz", + "integrity": "sha512-NHpxIzN29MXvWiuswfc1W3I0N8SXBd8UR26WntmDlRYf0bSADnwnOjsyMZ3lMezSlArD33Vs3YFhp7dWvL770A==", "requires": { "chokidar": ">=3.0.0 <4.0.0", "immutable": "^4.0.0", @@ -35312,9 +35344,9 @@ "dev": true }, "ts-jest": { - "version": "29.0.5", - "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.0.5.tgz", - "integrity": "sha512-PL3UciSgIpQ7f6XjVOmbi96vmDHUqAyqDr8YxzopDqX3kfgYtX1cuNeBjP+L9sFXi6nzsGGA6R3fP3DDDJyrxA==", + "version": "29.1.0", + "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.1.0.tgz", + "integrity": "sha512-ZhNr7Z4PcYa+JjMl62ir+zPiNJfXJN6E8hSLnaUKhOgqcn8vb3e537cpkd0FuAfRK3sR1LSqM1MOhliXNgOFPA==", "dev": true, "requires": { "bs-logger": "0.x", @@ -35449,9 +35481,9 @@ } }, "typescript": { - "version": "4.9.4", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.4.tgz", - "integrity": "sha512-Uz+dTXYzxXXbsFpM86Wh3dKCxrQqUcVMxwU54orwlJjOpO3ao8L7j5lH+dWfTwgCwIuM9GQ2kvVotzYJMXTBZg==", + "version": "4.9.5", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz", + "integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==", "dev": true }, "unbox-primitive": { diff --git a/web/ui/package.json b/web/ui/package.json index 22f2615ff84..d5663ee75eb 100644 --- a/web/ui/package.json +++ b/web/ui/package.json @@ -16,16 +16,16 @@ "npm": ">=7.0.0" }, "devDependencies": { - "@types/jest": "^29.4.0", + "@types/jest": "^29.5.2", "@types/node": "^17.0.45", - "eslint-config-prettier": "^8.6.0", + "eslint-config-prettier": "^8.8.0", "eslint-config-react-app": "^7.0.1", "eslint-plugin-prettier": "^4.2.1", - "jest-canvas-mock": "^2.4.0", + "jest-canvas-mock": "^2.5.1", "jest-fetch-mock": "^3.0.3", "react-scripts": "^5.0.1", - "prettier": "^2.8.3", - "ts-jest": "^29.0.5", - "typescript": "^4.9.4" + "prettier": "^2.8.8", + "ts-jest": "^29.1.0", + "typescript": "^4.9.5" } } diff --git a/web/ui/react-app/package.json b/web/ui/react-app/package.json index fc0d1e5fc3e..81eba150a0a 100644 --- a/web/ui/react-app/package.json +++ b/web/ui/react-app/package.json @@ -1,33 +1,33 @@ { "name": "@prometheus-io/app", - "version": "0.44.0", + "version": "0.45.0", "private": true, "dependencies": { - "@codemirror/autocomplete": "^6.4.0", - "@codemirror/commands": "^6.2.0", - "@codemirror/language": "^6.4.0", - "@codemirror/lint": "^6.1.0", - "@codemirror/search": "^6.2.3", - "@codemirror/state": "^6.2.0", - "@codemirror/view": "^6.7.3", + "@codemirror/autocomplete": "^6.7.1", + "@codemirror/commands": "^6.2.4", + "@codemirror/language": "^6.7.0", + "@codemirror/lint": "^6.2.2", + "@codemirror/search": "^6.5.0", + "@codemirror/state": "^6.2.1", + "@codemirror/view": "^6.13.0", "@forevolve/bootstrap-dark": "^2.1.1", - "@fortawesome/fontawesome-svg-core": "6.2.1", - "@fortawesome/free-solid-svg-icons": "6.2.1", + "@fortawesome/fontawesome-svg-core": "6.4.0", + "@fortawesome/free-solid-svg-icons": "6.4.0", "@fortawesome/react-fontawesome": "0.2.0", - "@lezer/lr": "^1.3.1", - "@lezer/highlight": "^1.1.3", - "@lezer/common": "^1.0.2", + "@lezer/lr": "^1.3.6", + "@lezer/highlight": "^1.1.6", + "@lezer/common": "^1.0.3", "@nexucis/fuzzy": "^0.4.1", "@nexucis/kvsearch": "^0.8.1", - "@prometheus-io/codemirror-promql": "0.44.0", + "@prometheus-io/codemirror-promql": "0.45.0", "bootstrap": "^4.6.2", "css.escape": "^1.5.1", - "downshift": "^7.2.0", + "downshift": "^7.6.0", "http-proxy-middleware": "^2.0.6", - "jquery": "^3.6.3", + "jquery": "^3.7.0", "jquery.flot.tooltip": "^0.9.0", "moment": "^2.29.4", - "moment-timezone": "^0.5.40", + "moment-timezone": "^0.5.43", "popper.js": "^1.14.3", "react": "^17.0.2", "react-copy-to-clipboard": "^5.1.0", @@ -37,8 +37,8 @@ "react-router-dom": "^5.3.4", "react-test-renderer": "^17.0.2", "reactstrap": "^8.10.1", - "sanitize-html": "^2.8.1", - "sass": "1.57.1", + "sanitize-html": "^2.10.0", + "sass": "1.62.1", "tempusdominus-bootstrap-4": "^5.39.2", "tempusdominus-core": "^5.19.3" }, @@ -66,15 +66,15 @@ ], "devDependencies": { "@testing-library/react-hooks": "^7.0.2", - "@types/enzyme": "^3.10.12", + "@types/enzyme": "^3.10.13", "@types/flot": "0.0.32", "@types/jquery": "^3.5.16", - "@types/react": "^17.0.53", + "@types/react": "^17.0.60", "@types/react-copy-to-clipboard": "^5.0.4", - "@types/react-dom": "^17.0.18", + "@types/react-dom": "^17.0.20", "@types/react-router-dom": "^5.3.3", - "@types/sanitize-html": "^2.8.0", - "@types/sinon": "^10.0.13", + "@types/sanitize-html": "^2.9.0", + "@types/sinon": "^10.0.15", "@wojtekmaj/enzyme-adapter-react-17": "^0.8.0", "enzyme": "^3.11.0", "enzyme-to-json": "^3.6.2", diff --git a/web/ui/static/css/prom_console.css.gz b/web/ui/static/css/prom_console.css.gz index 407138aa243..1255bbc4941 100644 Binary files a/web/ui/static/css/prom_console.css.gz and b/web/ui/static/css/prom_console.css.gz differ diff --git a/web/ui/static/js/prom_console.js.gz b/web/ui/static/js/prom_console.js.gz index d2a41e336c9..27249717204 100644 Binary files a/web/ui/static/js/prom_console.js.gz and b/web/ui/static/js/prom_console.js.gz differ diff --git a/web/ui/static/react/asset-manifest.json.gz b/web/ui/static/react/asset-manifest.json.gz index 2f9108524ad..52ae0d49ecc 100644 Binary files a/web/ui/static/react/asset-manifest.json.gz and b/web/ui/static/react/asset-manifest.json.gz differ diff --git a/web/ui/static/react/favicon.ico.gz b/web/ui/static/react/favicon.ico.gz index 7f8586d67e1..0b8fbc90837 100755 Binary files a/web/ui/static/react/favicon.ico.gz and b/web/ui/static/react/favicon.ico.gz differ diff --git a/web/ui/static/react/index.html.gz b/web/ui/static/react/index.html.gz index c16cd8c7aa1..f9733d38efc 100644 Binary files a/web/ui/static/react/index.html.gz and b/web/ui/static/react/index.html.gz differ diff --git a/web/ui/static/react/manifest.json.gz b/web/ui/static/react/manifest.json.gz index 0e6ddf9e7cd..b3fa5128623 100755 Binary files a/web/ui/static/react/manifest.json.gz and b/web/ui/static/react/manifest.json.gz differ diff --git a/web/ui/static/react/static/css/main.4858e794.css.gz b/web/ui/static/react/static/css/main.4858e794.css.gz index 8df37de9570..f6912e09efd 100644 Binary files a/web/ui/static/react/static/css/main.4858e794.css.gz and b/web/ui/static/react/static/css/main.4858e794.css.gz differ diff --git a/web/ui/static/react/static/js/main.1542d2ea.js.LICENSE.txt.gz b/web/ui/static/react/static/js/main.1542d2ea.js.LICENSE.txt.gz deleted file mode 100644 index 46836f0f1a5..00000000000 Binary files a/web/ui/static/react/static/js/main.1542d2ea.js.LICENSE.txt.gz and /dev/null differ diff --git a/web/ui/static/react/static/js/main.1542d2ea.js.gz b/web/ui/static/react/static/js/main.1542d2ea.js.gz deleted file mode 100644 index 0311bb15c79..00000000000 Binary files a/web/ui/static/react/static/js/main.1542d2ea.js.gz and /dev/null differ diff --git a/web/ui/static/react/static/js/main.aed3c73f.js.LICENSE.txt.gz b/web/ui/static/react/static/js/main.aed3c73f.js.LICENSE.txt.gz new file mode 100644 index 00000000000..172a431f1f7 Binary files /dev/null and b/web/ui/static/react/static/js/main.aed3c73f.js.LICENSE.txt.gz differ diff --git a/web/ui/static/react/static/js/main.aed3c73f.js.gz b/web/ui/static/react/static/js/main.aed3c73f.js.gz new file mode 100644 index 00000000000..19434fd0714 Binary files /dev/null and b/web/ui/static/react/static/js/main.aed3c73f.js.gz differ diff --git a/web/ui/static/react/static/media/codicon.b3726f0165bf67ac6849.ttf.gz b/web/ui/static/react/static/media/codicon.b3726f0165bf67ac6849.ttf.gz index 28345a5c464..de5bfbf5f19 100644 Binary files a/web/ui/static/react/static/media/codicon.b3726f0165bf67ac6849.ttf.gz and b/web/ui/static/react/static/media/codicon.b3726f0165bf67ac6849.ttf.gz differ diff --git a/web/ui/static/react/static/media/index.cd351d7c31d0d3fccf96.cjs.gz b/web/ui/static/react/static/media/index.cd351d7c31d0d3fccf96.cjs.gz index 0c61401b260..5f572aeaee2 100644 Binary files a/web/ui/static/react/static/media/index.cd351d7c31d0d3fccf96.cjs.gz and b/web/ui/static/react/static/media/index.cd351d7c31d0d3fccf96.cjs.gz differ diff --git a/web/ui/static/react/static/media/prometheus_logo_grey.3cf697e5443028ca5e5255b93c7906c5.svg.gz b/web/ui/static/react/static/media/prometheus_logo_grey.3cf697e5443028ca5e5255b93c7906c5.svg.gz index 2fa360260f2..496cfc724c7 100644 Binary files a/web/ui/static/react/static/media/prometheus_logo_grey.3cf697e5443028ca5e5255b93c7906c5.svg.gz and b/web/ui/static/react/static/media/prometheus_logo_grey.3cf697e5443028ca5e5255b93c7906c5.svg.gz differ diff --git a/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-grid.css.gz b/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-grid.css.gz index 927407ee40d..e26f23b90e9 100644 Binary files a/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-grid.css.gz and b/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-grid.css.gz differ diff --git a/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-grid.css.map.gz b/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-grid.css.map.gz index 3f78b14ecbb..1e775bf5f58 100644 Binary files a/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-grid.css.map.gz and b/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-grid.css.map.gz differ diff --git a/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-grid.min.css.gz b/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-grid.min.css.gz index 312946574c3..d3d2463cc52 100644 Binary files a/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-grid.min.css.gz and b/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-grid.min.css.gz differ diff --git a/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-grid.min.css.map.gz b/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-grid.min.css.map.gz index ae03ba037b7..dc7e084dc4d 100644 Binary files a/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-grid.min.css.map.gz and b/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-grid.min.css.map.gz differ diff --git a/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-reboot.css.gz b/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-reboot.css.gz index fd645cf2af4..6961abf11c7 100644 Binary files a/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-reboot.css.gz and b/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-reboot.css.gz differ diff --git a/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-reboot.css.map.gz b/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-reboot.css.map.gz index 98548466db1..57825e73bef 100644 Binary files a/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-reboot.css.map.gz and b/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-reboot.css.map.gz differ diff --git a/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-reboot.min.css.gz b/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-reboot.min.css.gz index f7bae497f84..8fa8bdde085 100644 Binary files a/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-reboot.min.css.gz and b/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-reboot.min.css.gz differ diff --git a/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-reboot.min.css.map.gz b/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-reboot.min.css.map.gz index 1aab37ef033..3fb1b7eea39 100644 Binary files a/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-reboot.min.css.map.gz and b/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap-reboot.min.css.map.gz differ diff --git a/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap.css.gz b/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap.css.gz index e06a2ed6dfb..8910dcea54a 100644 Binary files a/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap.css.gz and b/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap.css.gz differ diff --git a/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap.css.map.gz b/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap.css.map.gz index 7240ba6c6dd..c946120689c 100644 Binary files a/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap.css.map.gz and b/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap.css.map.gz differ diff --git a/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap.min.css.gz b/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap.min.css.gz index ead329c9849..1a8768bb395 100644 Binary files a/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap.min.css.gz and b/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap.min.css.gz differ diff --git a/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap.min.css.map.gz b/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap.min.css.map.gz index 8542affba67..79a1c711832 100644 Binary files a/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap.min.css.map.gz and b/web/ui/static/vendor/bootstrap-4.5.2/css/bootstrap.min.css.map.gz differ diff --git a/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.bundle.js.gz b/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.bundle.js.gz index d50c34cbbf4..32275b371b4 100644 Binary files a/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.bundle.js.gz and b/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.bundle.js.gz differ diff --git a/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.bundle.js.map.gz b/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.bundle.js.map.gz index 0935260137b..ee865220a5f 100644 Binary files a/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.bundle.js.map.gz and b/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.bundle.js.map.gz differ diff --git a/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.bundle.min.js.gz b/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.bundle.min.js.gz index 18e115e1689..7cec28821bd 100644 Binary files a/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.bundle.min.js.gz and b/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.bundle.min.js.gz differ diff --git a/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.bundle.min.js.map.gz b/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.bundle.min.js.map.gz index ca6b8b54485..ff9edc50693 100644 Binary files a/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.bundle.min.js.map.gz and b/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.bundle.min.js.map.gz differ diff --git a/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.js.gz b/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.js.gz index 7e118a38e11..cc12864d819 100644 Binary files a/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.js.gz and b/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.js.gz differ diff --git a/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.js.map.gz b/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.js.map.gz index c9d1214cc8a..2837bd25c22 100644 Binary files a/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.js.map.gz and b/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.js.map.gz differ diff --git a/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.min.js.gz b/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.min.js.gz index 2a3a51d6fdc..624105bf7c4 100644 Binary files a/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.min.js.gz and b/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.min.js.gz differ diff --git a/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.min.js.map.gz b/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.min.js.map.gz index a9726165d2a..aed6926ffe4 100644 Binary files a/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.min.js.map.gz and b/web/ui/static/vendor/bootstrap-4.5.2/js/bootstrap.min.js.map.gz differ diff --git a/web/ui/static/vendor/bootstrap4-glyphicons/css/bootstrap-glyphicons.css.gz b/web/ui/static/vendor/bootstrap4-glyphicons/css/bootstrap-glyphicons.css.gz index 7b52ecb21a9..42be5b9fdce 100644 Binary files a/web/ui/static/vendor/bootstrap4-glyphicons/css/bootstrap-glyphicons.css.gz and b/web/ui/static/vendor/bootstrap4-glyphicons/css/bootstrap-glyphicons.css.gz differ diff --git a/web/ui/static/vendor/bootstrap4-glyphicons/css/bootstrap-glyphicons.min.css.gz b/web/ui/static/vendor/bootstrap4-glyphicons/css/bootstrap-glyphicons.min.css.gz index 53ba4639e17..22b0989bd85 100644 Binary files a/web/ui/static/vendor/bootstrap4-glyphicons/css/bootstrap-glyphicons.min.css.gz and b/web/ui/static/vendor/bootstrap4-glyphicons/css/bootstrap-glyphicons.min.css.gz differ diff --git a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.eot.gz b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.eot.gz index ab7d184cc14..2cfbe0d34f7 100644 Binary files a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.eot.gz and b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.eot.gz differ diff --git a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.svg.gz b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.svg.gz index 4d93a82ccd7..97d65ee722f 100644 Binary files a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.svg.gz and b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.svg.gz differ diff --git a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.ttf.gz b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.ttf.gz index d44b3111110..52353536018 100644 Binary files a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.ttf.gz and b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.ttf.gz differ diff --git a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.woff.gz b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.woff.gz index 94ac6252830..8c7537d4128 100644 Binary files a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.woff.gz and b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.woff.gz differ diff --git a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.woff2.gz b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.woff2.gz index c9a9a7811f7..fa9442b26f1 100644 Binary files a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.woff2.gz and b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-brands-400.woff2.gz differ diff --git a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.eot.gz b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.eot.gz index 72eaff04823..87e374d98f1 100644 Binary files a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.eot.gz and b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.eot.gz differ diff --git a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.svg.gz b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.svg.gz index d9cde8aaf9a..bbb9c34c6be 100644 Binary files a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.svg.gz and b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.svg.gz differ diff --git a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.ttf.gz b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.ttf.gz index dd3068dd822..54e887b2344 100644 Binary files a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.ttf.gz and b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.ttf.gz differ diff --git a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.woff.gz b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.woff.gz index 733c1b3a56d..0f61be234e1 100644 Binary files a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.woff.gz and b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.woff.gz differ diff --git a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.woff2.gz b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.woff2.gz index 6df48ba5bf6..946b6876309 100644 Binary files a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.woff2.gz and b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-regular-400.woff2.gz differ diff --git a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.eot.gz b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.eot.gz index 6a709d2d52e..561bd6c2e0a 100644 Binary files a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.eot.gz and b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.eot.gz differ diff --git a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.svg.gz b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.svg.gz index 9d96dbd355b..6596e1f1a92 100644 Binary files a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.svg.gz and b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.svg.gz differ diff --git a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.ttf.gz b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.ttf.gz index 3adeed62baa..f72929b266d 100644 Binary files a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.ttf.gz and b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.ttf.gz differ diff --git a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.woff.gz b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.woff.gz index e3d071d3ad0..02be12194a1 100644 Binary files a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.woff.gz and b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.woff.gz differ diff --git a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.woff2.gz b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.woff2.gz index 2be69782c1e..724a2030d44 100644 Binary files a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.woff2.gz and b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/fontawesome/fa-solid-900.woff2.gz differ diff --git a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.eot.gz b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.eot.gz index 07b40b59930..32325c728e4 100644 Binary files a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.eot.gz and b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.eot.gz differ diff --git a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.svg.gz b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.svg.gz index 1cf6d3fcd49..4f31b7a04d2 100644 Binary files a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.svg.gz and b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.svg.gz differ diff --git a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.ttf.gz b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.ttf.gz index 90b8c6a4f3b..468577b05c4 100644 Binary files a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.ttf.gz and b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.ttf.gz differ diff --git a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.woff.gz b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.woff.gz index 34e6fb9b5ed..7c6e560eb0b 100644 Binary files a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.woff.gz and b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.woff.gz differ diff --git a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.woff2.gz b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.woff2.gz index b7d44f11116..27d25f037f0 100644 Binary files a/web/ui/static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.woff2.gz and b/web/ui/static/vendor/bootstrap4-glyphicons/fonts/glyphicons/glyphicons-halflings-regular.woff2.gz differ diff --git a/web/ui/static/vendor/bootstrap4-glyphicons/maps/glyphicons-fontawesome.css.gz b/web/ui/static/vendor/bootstrap4-glyphicons/maps/glyphicons-fontawesome.css.gz index b13bb325536..306e76751df 100644 Binary files a/web/ui/static/vendor/bootstrap4-glyphicons/maps/glyphicons-fontawesome.css.gz and b/web/ui/static/vendor/bootstrap4-glyphicons/maps/glyphicons-fontawesome.css.gz differ diff --git a/web/ui/static/vendor/bootstrap4-glyphicons/maps/glyphicons-fontawesome.less.gz b/web/ui/static/vendor/bootstrap4-glyphicons/maps/glyphicons-fontawesome.less.gz index e922a2286d5..9d0b19a3667 100644 Binary files a/web/ui/static/vendor/bootstrap4-glyphicons/maps/glyphicons-fontawesome.less.gz and b/web/ui/static/vendor/bootstrap4-glyphicons/maps/glyphicons-fontawesome.less.gz differ diff --git a/web/ui/static/vendor/bootstrap4-glyphicons/maps/glyphicons-fontawesome.min.css.gz b/web/ui/static/vendor/bootstrap4-glyphicons/maps/glyphicons-fontawesome.min.css.gz index ed63c9bf613..db937d31006 100644 Binary files a/web/ui/static/vendor/bootstrap4-glyphicons/maps/glyphicons-fontawesome.min.css.gz and b/web/ui/static/vendor/bootstrap4-glyphicons/maps/glyphicons-fontawesome.min.css.gz differ diff --git a/web/ui/static/vendor/js/jquery-3.5.1.min.js.gz b/web/ui/static/vendor/js/jquery-3.5.1.min.js.gz index 440a98d2463..32a72c3c8c2 100644 Binary files a/web/ui/static/vendor/js/jquery-3.5.1.min.js.gz and b/web/ui/static/vendor/js/jquery-3.5.1.min.js.gz differ diff --git a/web/ui/static/vendor/js/jquery.hotkeys.js.gz b/web/ui/static/vendor/js/jquery.hotkeys.js.gz index 4aef3b7deda..310d0f8696a 100644 Binary files a/web/ui/static/vendor/js/jquery.hotkeys.js.gz and b/web/ui/static/vendor/js/jquery.hotkeys.js.gz differ diff --git a/web/ui/static/vendor/js/jquery.selection.js.gz b/web/ui/static/vendor/js/jquery.selection.js.gz index 01364d71b6f..ca573dc0a9d 100644 Binary files a/web/ui/static/vendor/js/jquery.selection.js.gz and b/web/ui/static/vendor/js/jquery.selection.js.gz differ diff --git a/web/ui/static/vendor/js/popper.min.js.gz b/web/ui/static/vendor/js/popper.min.js.gz index 95beb0f6f6b..bd0a93a7dcf 100644 Binary files a/web/ui/static/vendor/js/popper.min.js.gz and b/web/ui/static/vendor/js/popper.min.js.gz differ diff --git a/web/ui/static/vendor/rickshaw/rickshaw.min.css.gz b/web/ui/static/vendor/rickshaw/rickshaw.min.css.gz index 773a8b8a4bd..450bb463146 100644 Binary files a/web/ui/static/vendor/rickshaw/rickshaw.min.css.gz and b/web/ui/static/vendor/rickshaw/rickshaw.min.css.gz differ diff --git a/web/ui/static/vendor/rickshaw/rickshaw.min.js.gz b/web/ui/static/vendor/rickshaw/rickshaw.min.js.gz index 54ad2c42fd6..78d779c07db 100644 Binary files a/web/ui/static/vendor/rickshaw/rickshaw.min.js.gz and b/web/ui/static/vendor/rickshaw/rickshaw.min.js.gz differ diff --git a/web/ui/static/vendor/rickshaw/vendor/d3.layout.min.js.gz b/web/ui/static/vendor/rickshaw/vendor/d3.layout.min.js.gz index d58b4af00d2..9267aed54e9 100644 Binary files a/web/ui/static/vendor/rickshaw/vendor/d3.layout.min.js.gz and b/web/ui/static/vendor/rickshaw/vendor/d3.layout.min.js.gz differ diff --git a/web/ui/static/vendor/rickshaw/vendor/d3.v3.js.gz b/web/ui/static/vendor/rickshaw/vendor/d3.v3.js.gz index 69b6d68911f..8dc8a7b63a5 100644 Binary files a/web/ui/static/vendor/rickshaw/vendor/d3.v3.js.gz and b/web/ui/static/vendor/rickshaw/vendor/d3.v3.js.gz differ diff --git a/web/web.go b/web/web.go index 27378b3b819..b9af2819b75 100644 --- a/web/web.go +++ b/web/web.go @@ -744,7 +744,7 @@ func (h *Handler) runtimeInfo() (api_v1.RuntimeInfo, error) { } func toFloat64(f *io_prometheus_client.MetricFamily) float64 { - m := *f.Metric[0] + m := f.Metric[0] if m.Gauge != nil { return m.Gauge.GetValue() } diff --git a/web/web_test.go b/web/web_test.go index 7da06a30601..8832c28390c 100644 --- a/web/web_test.go +++ b/web/web_test.go @@ -52,8 +52,8 @@ type dbAdapter struct { *tsdb.DB } -func (a *dbAdapter) Stats(statsByLabelName string) (*tsdb.Stats, error) { - return a.Head().Stats(statsByLabelName), nil +func (a *dbAdapter) Stats(statsByLabelName string, limit int) (*tsdb.Stats, error) { + return a.Head().Stats(statsByLabelName, limit), nil } func (a *dbAdapter) WALReplayStatus() (tsdb.WALReplayStatus, error) {