feat: kubesphere 4.0 (#6115)

* feat: kubesphere 4.0

Signed-off-by: ci-bot <ci-bot@kubesphere.io>

* feat: kubesphere 4.0

Signed-off-by: ci-bot <ci-bot@kubesphere.io>

---------

Signed-off-by: ci-bot <ci-bot@kubesphere.io>
Co-authored-by: ks-ci-bot <ks-ci-bot@example.com>
Co-authored-by: joyceliu <joyceliu@yunify.com>
This commit is contained in:
KubeSphere CI Bot
2024-09-06 11:05:52 +08:00
committed by GitHub
parent b5015ec7b9
commit 447a51f08b
8557 changed files with 546695 additions and 1146174 deletions

View File

@@ -1,12 +0,0 @@
Copyright 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.

View File

@@ -1,201 +0,0 @@
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.

View File

@@ -1,18 +0,0 @@
Prometheus Alertmanager
Copyright 2013-2015 The Prometheus Authors
This product includes software developed at
SoundCloud Ltd. (http://soundcloud.com/).
The following components are included in this product:
Bootstrap
http://getbootstrap.com
Copyright 2011-2014 Twitter, Inc.
Licensed under the MIT License
bootstrap-datetimepicker.js
http://www.eyecon.ro/bootstrap-datepicker
Copyright 2012 Stefan Petre
Licensed under the Apache License, Version 2.0

View File

@@ -1,133 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package alert
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
)
// New creates a new alert API client.
func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService {
return &Client{transport: transport, formats: formats}
}
/*
Client for alert API
*/
type Client struct {
transport runtime.ClientTransport
formats strfmt.Registry
}
// ClientOption is the option for Client methods
type ClientOption func(*runtime.ClientOperation)
// ClientService is the interface for Client methods
type ClientService interface {
GetAlerts(params *GetAlertsParams, opts ...ClientOption) (*GetAlertsOK, error)
PostAlerts(params *PostAlertsParams, opts ...ClientOption) (*PostAlertsOK, error)
SetTransport(transport runtime.ClientTransport)
}
/*
GetAlerts Get a list of alerts
*/
func (a *Client) GetAlerts(params *GetAlertsParams, opts ...ClientOption) (*GetAlertsOK, error) {
// TODO: Validate the params before sending
if params == nil {
params = NewGetAlertsParams()
}
op := &runtime.ClientOperation{
ID: "getAlerts",
Method: "GET",
PathPattern: "/alerts",
ProducesMediaTypes: []string{"application/json"},
ConsumesMediaTypes: []string{"application/json"},
Schemes: []string{"http"},
Params: params,
Reader: &GetAlertsReader{formats: a.formats},
Context: params.Context,
Client: params.HTTPClient,
}
for _, opt := range opts {
opt(op)
}
result, err := a.transport.Submit(op)
if err != nil {
return nil, err
}
success, ok := result.(*GetAlertsOK)
if ok {
return success, nil
}
// unexpected success response
// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue
msg := fmt.Sprintf("unexpected success response for getAlerts: API contract not enforced by server. Client expected to get an error, but got: %T", result)
panic(msg)
}
/*
PostAlerts Create new Alerts
*/
func (a *Client) PostAlerts(params *PostAlertsParams, opts ...ClientOption) (*PostAlertsOK, error) {
// TODO: Validate the params before sending
if params == nil {
params = NewPostAlertsParams()
}
op := &runtime.ClientOperation{
ID: "postAlerts",
Method: "POST",
PathPattern: "/alerts",
ProducesMediaTypes: []string{"application/json"},
ConsumesMediaTypes: []string{"application/json"},
Schemes: []string{"http"},
Params: params,
Reader: &PostAlertsReader{formats: a.formats},
Context: params.Context,
Client: params.HTTPClient,
}
for _, opt := range opts {
opt(op)
}
result, err := a.transport.Submit(op)
if err != nil {
return nil, err
}
success, ok := result.(*PostAlertsOK)
if ok {
return success, nil
}
// unexpected success response
// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue
msg := fmt.Sprintf("unexpected success response for postAlerts: API contract not enforced by server. Client expected to get an error, but got: %T", result)
panic(msg)
}
// SetTransport changes the transport on the client
func (a *Client) SetTransport(transport runtime.ClientTransport) {
a.transport = transport
}

View File

@@ -1,387 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package alert
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"time"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
cr "github.com/go-openapi/runtime/client"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// NewGetAlertsParams creates a new GetAlertsParams object,
// with the default timeout for this client.
//
// Default values are not hydrated, since defaults are normally applied by the API server side.
//
// To enforce default values in parameter, use SetDefaults or WithDefaults.
func NewGetAlertsParams() *GetAlertsParams {
return &GetAlertsParams{
timeout: cr.DefaultTimeout,
}
}
// NewGetAlertsParamsWithTimeout creates a new GetAlertsParams object
// with the ability to set a timeout on a request.
func NewGetAlertsParamsWithTimeout(timeout time.Duration) *GetAlertsParams {
return &GetAlertsParams{
timeout: timeout,
}
}
// NewGetAlertsParamsWithContext creates a new GetAlertsParams object
// with the ability to set a context for a request.
func NewGetAlertsParamsWithContext(ctx context.Context) *GetAlertsParams {
return &GetAlertsParams{
Context: ctx,
}
}
// NewGetAlertsParamsWithHTTPClient creates a new GetAlertsParams object
// with the ability to set a custom HTTPClient for a request.
func NewGetAlertsParamsWithHTTPClient(client *http.Client) *GetAlertsParams {
return &GetAlertsParams{
HTTPClient: client,
}
}
/*
GetAlertsParams contains all the parameters to send to the API endpoint
for the get alerts operation.
Typically these are written to a http.Request.
*/
type GetAlertsParams struct {
/* Active.
Show active alerts
Default: true
*/
Active *bool
/* Filter.
A list of matchers to filter alerts by
*/
Filter []string
/* Inhibited.
Show inhibited alerts
Default: true
*/
Inhibited *bool
/* Receiver.
A regex matching receivers to filter alerts by
*/
Receiver *string
/* Silenced.
Show silenced alerts
Default: true
*/
Silenced *bool
/* Unprocessed.
Show unprocessed alerts
Default: true
*/
Unprocessed *bool
timeout time.Duration
Context context.Context
HTTPClient *http.Client
}
// WithDefaults hydrates default values in the get alerts params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *GetAlertsParams) WithDefaults() *GetAlertsParams {
o.SetDefaults()
return o
}
// SetDefaults hydrates default values in the get alerts params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *GetAlertsParams) SetDefaults() {
var (
activeDefault = bool(true)
inhibitedDefault = bool(true)
silencedDefault = bool(true)
unprocessedDefault = bool(true)
)
val := GetAlertsParams{
Active: &activeDefault,
Inhibited: &inhibitedDefault,
Silenced: &silencedDefault,
Unprocessed: &unprocessedDefault,
}
val.timeout = o.timeout
val.Context = o.Context
val.HTTPClient = o.HTTPClient
*o = val
}
// WithTimeout adds the timeout to the get alerts params
func (o *GetAlertsParams) WithTimeout(timeout time.Duration) *GetAlertsParams {
o.SetTimeout(timeout)
return o
}
// SetTimeout adds the timeout to the get alerts params
func (o *GetAlertsParams) SetTimeout(timeout time.Duration) {
o.timeout = timeout
}
// WithContext adds the context to the get alerts params
func (o *GetAlertsParams) WithContext(ctx context.Context) *GetAlertsParams {
o.SetContext(ctx)
return o
}
// SetContext adds the context to the get alerts params
func (o *GetAlertsParams) SetContext(ctx context.Context) {
o.Context = ctx
}
// WithHTTPClient adds the HTTPClient to the get alerts params
func (o *GetAlertsParams) WithHTTPClient(client *http.Client) *GetAlertsParams {
o.SetHTTPClient(client)
return o
}
// SetHTTPClient adds the HTTPClient to the get alerts params
func (o *GetAlertsParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithActive adds the active to the get alerts params
func (o *GetAlertsParams) WithActive(active *bool) *GetAlertsParams {
o.SetActive(active)
return o
}
// SetActive adds the active to the get alerts params
func (o *GetAlertsParams) SetActive(active *bool) {
o.Active = active
}
// WithFilter adds the filter to the get alerts params
func (o *GetAlertsParams) WithFilter(filter []string) *GetAlertsParams {
o.SetFilter(filter)
return o
}
// SetFilter adds the filter to the get alerts params
func (o *GetAlertsParams) SetFilter(filter []string) {
o.Filter = filter
}
// WithInhibited adds the inhibited to the get alerts params
func (o *GetAlertsParams) WithInhibited(inhibited *bool) *GetAlertsParams {
o.SetInhibited(inhibited)
return o
}
// SetInhibited adds the inhibited to the get alerts params
func (o *GetAlertsParams) SetInhibited(inhibited *bool) {
o.Inhibited = inhibited
}
// WithReceiver adds the receiver to the get alerts params
func (o *GetAlertsParams) WithReceiver(receiver *string) *GetAlertsParams {
o.SetReceiver(receiver)
return o
}
// SetReceiver adds the receiver to the get alerts params
func (o *GetAlertsParams) SetReceiver(receiver *string) {
o.Receiver = receiver
}
// WithSilenced adds the silenced to the get alerts params
func (o *GetAlertsParams) WithSilenced(silenced *bool) *GetAlertsParams {
o.SetSilenced(silenced)
return o
}
// SetSilenced adds the silenced to the get alerts params
func (o *GetAlertsParams) SetSilenced(silenced *bool) {
o.Silenced = silenced
}
// WithUnprocessed adds the unprocessed to the get alerts params
func (o *GetAlertsParams) WithUnprocessed(unprocessed *bool) *GetAlertsParams {
o.SetUnprocessed(unprocessed)
return o
}
// SetUnprocessed adds the unprocessed to the get alerts params
func (o *GetAlertsParams) SetUnprocessed(unprocessed *bool) {
o.Unprocessed = unprocessed
}
// WriteToRequest writes these params to a swagger request
func (o *GetAlertsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {
if err := r.SetTimeout(o.timeout); err != nil {
return err
}
var res []error
if o.Active != nil {
// query param active
var qrActive bool
if o.Active != nil {
qrActive = *o.Active
}
qActive := swag.FormatBool(qrActive)
if qActive != "" {
if err := r.SetQueryParam("active", qActive); err != nil {
return err
}
}
}
if o.Filter != nil {
// binding items for filter
joinedFilter := o.bindParamFilter(reg)
// query array param filter
if err := r.SetQueryParam("filter", joinedFilter...); err != nil {
return err
}
}
if o.Inhibited != nil {
// query param inhibited
var qrInhibited bool
if o.Inhibited != nil {
qrInhibited = *o.Inhibited
}
qInhibited := swag.FormatBool(qrInhibited)
if qInhibited != "" {
if err := r.SetQueryParam("inhibited", qInhibited); err != nil {
return err
}
}
}
if o.Receiver != nil {
// query param receiver
var qrReceiver string
if o.Receiver != nil {
qrReceiver = *o.Receiver
}
qReceiver := qrReceiver
if qReceiver != "" {
if err := r.SetQueryParam("receiver", qReceiver); err != nil {
return err
}
}
}
if o.Silenced != nil {
// query param silenced
var qrSilenced bool
if o.Silenced != nil {
qrSilenced = *o.Silenced
}
qSilenced := swag.FormatBool(qrSilenced)
if qSilenced != "" {
if err := r.SetQueryParam("silenced", qSilenced); err != nil {
return err
}
}
}
if o.Unprocessed != nil {
// query param unprocessed
var qrUnprocessed bool
if o.Unprocessed != nil {
qrUnprocessed = *o.Unprocessed
}
qUnprocessed := swag.FormatBool(qrUnprocessed)
if qUnprocessed != "" {
if err := r.SetQueryParam("unprocessed", qUnprocessed); err != nil {
return err
}
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
// bindParamGetAlerts binds the parameter filter
func (o *GetAlertsParams) bindParamFilter(formats strfmt.Registry) []string {
filterIR := o.Filter
var filterIC []string
for _, filterIIR := range filterIR { // explode []string
filterIIV := filterIIR // string as string
filterIC = append(filterIC, filterIIV)
}
// items.CollectionFormat: "multi"
filterIS := swag.JoinByFormat(filterIC, "multi")
return filterIS
}

View File

@@ -1,244 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package alert
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"io"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
"github.com/prometheus/alertmanager/api/v2/models"
)
// GetAlertsReader is a Reader for the GetAlerts structure.
type GetAlertsReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *GetAlertsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 200:
result := NewGetAlertsOK()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
case 400:
result := NewGetAlertsBadRequest()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
case 500:
result := NewGetAlertsInternalServerError()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
default:
return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code())
}
}
// NewGetAlertsOK creates a GetAlertsOK with default headers values
func NewGetAlertsOK() *GetAlertsOK {
return &GetAlertsOK{}
}
/*
GetAlertsOK describes a response with status code 200, with default header values.
Get alerts response
*/
type GetAlertsOK struct {
Payload models.GettableAlerts
}
// IsSuccess returns true when this get alerts o k response has a 2xx status code
func (o *GetAlertsOK) IsSuccess() bool {
return true
}
// IsRedirect returns true when this get alerts o k response has a 3xx status code
func (o *GetAlertsOK) IsRedirect() bool {
return false
}
// IsClientError returns true when this get alerts o k response has a 4xx status code
func (o *GetAlertsOK) IsClientError() bool {
return false
}
// IsServerError returns true when this get alerts o k response has a 5xx status code
func (o *GetAlertsOK) IsServerError() bool {
return false
}
// IsCode returns true when this get alerts o k response a status code equal to that given
func (o *GetAlertsOK) IsCode(code int) bool {
return code == 200
}
func (o *GetAlertsOK) Error() string {
return fmt.Sprintf("[GET /alerts][%d] getAlertsOK %+v", 200, o.Payload)
}
func (o *GetAlertsOK) String() string {
return fmt.Sprintf("[GET /alerts][%d] getAlertsOK %+v", 200, o.Payload)
}
func (o *GetAlertsOK) GetPayload() models.GettableAlerts {
return o.Payload
}
func (o *GetAlertsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
// response payload
if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
// NewGetAlertsBadRequest creates a GetAlertsBadRequest with default headers values
func NewGetAlertsBadRequest() *GetAlertsBadRequest {
return &GetAlertsBadRequest{}
}
/*
GetAlertsBadRequest describes a response with status code 400, with default header values.
Bad request
*/
type GetAlertsBadRequest struct {
Payload string
}
// IsSuccess returns true when this get alerts bad request response has a 2xx status code
func (o *GetAlertsBadRequest) IsSuccess() bool {
return false
}
// IsRedirect returns true when this get alerts bad request response has a 3xx status code
func (o *GetAlertsBadRequest) IsRedirect() bool {
return false
}
// IsClientError returns true when this get alerts bad request response has a 4xx status code
func (o *GetAlertsBadRequest) IsClientError() bool {
return true
}
// IsServerError returns true when this get alerts bad request response has a 5xx status code
func (o *GetAlertsBadRequest) IsServerError() bool {
return false
}
// IsCode returns true when this get alerts bad request response a status code equal to that given
func (o *GetAlertsBadRequest) IsCode(code int) bool {
return code == 400
}
func (o *GetAlertsBadRequest) Error() string {
return fmt.Sprintf("[GET /alerts][%d] getAlertsBadRequest %+v", 400, o.Payload)
}
func (o *GetAlertsBadRequest) String() string {
return fmt.Sprintf("[GET /alerts][%d] getAlertsBadRequest %+v", 400, o.Payload)
}
func (o *GetAlertsBadRequest) GetPayload() string {
return o.Payload
}
func (o *GetAlertsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
// response payload
if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
// NewGetAlertsInternalServerError creates a GetAlertsInternalServerError with default headers values
func NewGetAlertsInternalServerError() *GetAlertsInternalServerError {
return &GetAlertsInternalServerError{}
}
/*
GetAlertsInternalServerError describes a response with status code 500, with default header values.
Internal server error
*/
type GetAlertsInternalServerError struct {
Payload string
}
// IsSuccess returns true when this get alerts internal server error response has a 2xx status code
func (o *GetAlertsInternalServerError) IsSuccess() bool {
return false
}
// IsRedirect returns true when this get alerts internal server error response has a 3xx status code
func (o *GetAlertsInternalServerError) IsRedirect() bool {
return false
}
// IsClientError returns true when this get alerts internal server error response has a 4xx status code
func (o *GetAlertsInternalServerError) IsClientError() bool {
return false
}
// IsServerError returns true when this get alerts internal server error response has a 5xx status code
func (o *GetAlertsInternalServerError) IsServerError() bool {
return true
}
// IsCode returns true when this get alerts internal server error response a status code equal to that given
func (o *GetAlertsInternalServerError) IsCode(code int) bool {
return code == 500
}
func (o *GetAlertsInternalServerError) Error() string {
return fmt.Sprintf("[GET /alerts][%d] getAlertsInternalServerError %+v", 500, o.Payload)
}
func (o *GetAlertsInternalServerError) String() string {
return fmt.Sprintf("[GET /alerts][%d] getAlertsInternalServerError %+v", 500, o.Payload)
}
func (o *GetAlertsInternalServerError) GetPayload() string {
return o.Payload
}
func (o *GetAlertsInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
// response payload
if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}

View File

@@ -1,167 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package alert
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"time"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
cr "github.com/go-openapi/runtime/client"
"github.com/go-openapi/strfmt"
"github.com/prometheus/alertmanager/api/v2/models"
)
// NewPostAlertsParams creates a new PostAlertsParams object,
// with the default timeout for this client.
//
// Default values are not hydrated, since defaults are normally applied by the API server side.
//
// To enforce default values in parameter, use SetDefaults or WithDefaults.
func NewPostAlertsParams() *PostAlertsParams {
return &PostAlertsParams{
timeout: cr.DefaultTimeout,
}
}
// NewPostAlertsParamsWithTimeout creates a new PostAlertsParams object
// with the ability to set a timeout on a request.
func NewPostAlertsParamsWithTimeout(timeout time.Duration) *PostAlertsParams {
return &PostAlertsParams{
timeout: timeout,
}
}
// NewPostAlertsParamsWithContext creates a new PostAlertsParams object
// with the ability to set a context for a request.
func NewPostAlertsParamsWithContext(ctx context.Context) *PostAlertsParams {
return &PostAlertsParams{
Context: ctx,
}
}
// NewPostAlertsParamsWithHTTPClient creates a new PostAlertsParams object
// with the ability to set a custom HTTPClient for a request.
func NewPostAlertsParamsWithHTTPClient(client *http.Client) *PostAlertsParams {
return &PostAlertsParams{
HTTPClient: client,
}
}
/*
PostAlertsParams contains all the parameters to send to the API endpoint
for the post alerts operation.
Typically these are written to a http.Request.
*/
type PostAlertsParams struct {
/* Alerts.
The alerts to create
*/
Alerts models.PostableAlerts
timeout time.Duration
Context context.Context
HTTPClient *http.Client
}
// WithDefaults hydrates default values in the post alerts params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *PostAlertsParams) WithDefaults() *PostAlertsParams {
o.SetDefaults()
return o
}
// SetDefaults hydrates default values in the post alerts params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *PostAlertsParams) SetDefaults() {
// no default values defined for this parameter
}
// WithTimeout adds the timeout to the post alerts params
func (o *PostAlertsParams) WithTimeout(timeout time.Duration) *PostAlertsParams {
o.SetTimeout(timeout)
return o
}
// SetTimeout adds the timeout to the post alerts params
func (o *PostAlertsParams) SetTimeout(timeout time.Duration) {
o.timeout = timeout
}
// WithContext adds the context to the post alerts params
func (o *PostAlertsParams) WithContext(ctx context.Context) *PostAlertsParams {
o.SetContext(ctx)
return o
}
// SetContext adds the context to the post alerts params
func (o *PostAlertsParams) SetContext(ctx context.Context) {
o.Context = ctx
}
// WithHTTPClient adds the HTTPClient to the post alerts params
func (o *PostAlertsParams) WithHTTPClient(client *http.Client) *PostAlertsParams {
o.SetHTTPClient(client)
return o
}
// SetHTTPClient adds the HTTPClient to the post alerts params
func (o *PostAlertsParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithAlerts adds the alerts to the post alerts params
func (o *PostAlertsParams) WithAlerts(alerts models.PostableAlerts) *PostAlertsParams {
o.SetAlerts(alerts)
return o
}
// SetAlerts adds the alerts to the post alerts params
func (o *PostAlertsParams) SetAlerts(alerts models.PostableAlerts) {
o.Alerts = alerts
}
// WriteToRequest writes these params to a swagger request
func (o *PostAlertsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {
if err := r.SetTimeout(o.timeout); err != nil {
return err
}
var res []error
if o.Alerts != nil {
if err := r.SetBodyParam(o.Alerts); err != nil {
return err
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,232 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package alert
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"io"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
)
// PostAlertsReader is a Reader for the PostAlerts structure.
type PostAlertsReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *PostAlertsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 200:
result := NewPostAlertsOK()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
case 400:
result := NewPostAlertsBadRequest()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
case 500:
result := NewPostAlertsInternalServerError()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
default:
return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code())
}
}
// NewPostAlertsOK creates a PostAlertsOK with default headers values
func NewPostAlertsOK() *PostAlertsOK {
return &PostAlertsOK{}
}
/*
PostAlertsOK describes a response with status code 200, with default header values.
Create alerts response
*/
type PostAlertsOK struct {
}
// IsSuccess returns true when this post alerts o k response has a 2xx status code
func (o *PostAlertsOK) IsSuccess() bool {
return true
}
// IsRedirect returns true when this post alerts o k response has a 3xx status code
func (o *PostAlertsOK) IsRedirect() bool {
return false
}
// IsClientError returns true when this post alerts o k response has a 4xx status code
func (o *PostAlertsOK) IsClientError() bool {
return false
}
// IsServerError returns true when this post alerts o k response has a 5xx status code
func (o *PostAlertsOK) IsServerError() bool {
return false
}
// IsCode returns true when this post alerts o k response a status code equal to that given
func (o *PostAlertsOK) IsCode(code int) bool {
return code == 200
}
func (o *PostAlertsOK) Error() string {
return fmt.Sprintf("[POST /alerts][%d] postAlertsOK ", 200)
}
func (o *PostAlertsOK) String() string {
return fmt.Sprintf("[POST /alerts][%d] postAlertsOK ", 200)
}
func (o *PostAlertsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
return nil
}
// NewPostAlertsBadRequest creates a PostAlertsBadRequest with default headers values
func NewPostAlertsBadRequest() *PostAlertsBadRequest {
return &PostAlertsBadRequest{}
}
/*
PostAlertsBadRequest describes a response with status code 400, with default header values.
Bad request
*/
type PostAlertsBadRequest struct {
Payload string
}
// IsSuccess returns true when this post alerts bad request response has a 2xx status code
func (o *PostAlertsBadRequest) IsSuccess() bool {
return false
}
// IsRedirect returns true when this post alerts bad request response has a 3xx status code
func (o *PostAlertsBadRequest) IsRedirect() bool {
return false
}
// IsClientError returns true when this post alerts bad request response has a 4xx status code
func (o *PostAlertsBadRequest) IsClientError() bool {
return true
}
// IsServerError returns true when this post alerts bad request response has a 5xx status code
func (o *PostAlertsBadRequest) IsServerError() bool {
return false
}
// IsCode returns true when this post alerts bad request response a status code equal to that given
func (o *PostAlertsBadRequest) IsCode(code int) bool {
return code == 400
}
func (o *PostAlertsBadRequest) Error() string {
return fmt.Sprintf("[POST /alerts][%d] postAlertsBadRequest %+v", 400, o.Payload)
}
func (o *PostAlertsBadRequest) String() string {
return fmt.Sprintf("[POST /alerts][%d] postAlertsBadRequest %+v", 400, o.Payload)
}
func (o *PostAlertsBadRequest) GetPayload() string {
return o.Payload
}
func (o *PostAlertsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
// response payload
if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
// NewPostAlertsInternalServerError creates a PostAlertsInternalServerError with default headers values
func NewPostAlertsInternalServerError() *PostAlertsInternalServerError {
return &PostAlertsInternalServerError{}
}
/*
PostAlertsInternalServerError describes a response with status code 500, with default header values.
Internal server error
*/
type PostAlertsInternalServerError struct {
Payload string
}
// IsSuccess returns true when this post alerts internal server error response has a 2xx status code
func (o *PostAlertsInternalServerError) IsSuccess() bool {
return false
}
// IsRedirect returns true when this post alerts internal server error response has a 3xx status code
func (o *PostAlertsInternalServerError) IsRedirect() bool {
return false
}
// IsClientError returns true when this post alerts internal server error response has a 4xx status code
func (o *PostAlertsInternalServerError) IsClientError() bool {
return false
}
// IsServerError returns true when this post alerts internal server error response has a 5xx status code
func (o *PostAlertsInternalServerError) IsServerError() bool {
return true
}
// IsCode returns true when this post alerts internal server error response a status code equal to that given
func (o *PostAlertsInternalServerError) IsCode(code int) bool {
return code == 500
}
func (o *PostAlertsInternalServerError) Error() string {
return fmt.Sprintf("[POST /alerts][%d] postAlertsInternalServerError %+v", 500, o.Payload)
}
func (o *PostAlertsInternalServerError) String() string {
return fmt.Sprintf("[POST /alerts][%d] postAlertsInternalServerError %+v", 500, o.Payload)
}
func (o *PostAlertsInternalServerError) GetPayload() string {
return o.Payload
}
func (o *PostAlertsInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
// response payload
if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}

View File

@@ -1,93 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package alertgroup
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
)
// New creates a new alertgroup API client.
func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService {
return &Client{transport: transport, formats: formats}
}
/*
Client for alertgroup API
*/
type Client struct {
transport runtime.ClientTransport
formats strfmt.Registry
}
// ClientOption is the option for Client methods
type ClientOption func(*runtime.ClientOperation)
// ClientService is the interface for Client methods
type ClientService interface {
GetAlertGroups(params *GetAlertGroupsParams, opts ...ClientOption) (*GetAlertGroupsOK, error)
SetTransport(transport runtime.ClientTransport)
}
/*
GetAlertGroups Get a list of alert groups
*/
func (a *Client) GetAlertGroups(params *GetAlertGroupsParams, opts ...ClientOption) (*GetAlertGroupsOK, error) {
// TODO: Validate the params before sending
if params == nil {
params = NewGetAlertGroupsParams()
}
op := &runtime.ClientOperation{
ID: "getAlertGroups",
Method: "GET",
PathPattern: "/alerts/groups",
ProducesMediaTypes: []string{"application/json"},
ConsumesMediaTypes: []string{"application/json"},
Schemes: []string{"http"},
Params: params,
Reader: &GetAlertGroupsReader{formats: a.formats},
Context: params.Context,
Client: params.HTTPClient,
}
for _, opt := range opts {
opt(op)
}
result, err := a.transport.Submit(op)
if err != nil {
return nil, err
}
success, ok := result.(*GetAlertGroupsOK)
if ok {
return success, nil
}
// unexpected success response
// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue
msg := fmt.Sprintf("unexpected success response for getAlertGroups: API contract not enforced by server. Client expected to get an error, but got: %T", result)
panic(msg)
}
// SetTransport changes the transport on the client
func (a *Client) SetTransport(transport runtime.ClientTransport) {
a.transport = transport
}

View File

@@ -1,348 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package alertgroup
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"time"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
cr "github.com/go-openapi/runtime/client"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// NewGetAlertGroupsParams creates a new GetAlertGroupsParams object,
// with the default timeout for this client.
//
// Default values are not hydrated, since defaults are normally applied by the API server side.
//
// To enforce default values in parameter, use SetDefaults or WithDefaults.
func NewGetAlertGroupsParams() *GetAlertGroupsParams {
return &GetAlertGroupsParams{
timeout: cr.DefaultTimeout,
}
}
// NewGetAlertGroupsParamsWithTimeout creates a new GetAlertGroupsParams object
// with the ability to set a timeout on a request.
func NewGetAlertGroupsParamsWithTimeout(timeout time.Duration) *GetAlertGroupsParams {
return &GetAlertGroupsParams{
timeout: timeout,
}
}
// NewGetAlertGroupsParamsWithContext creates a new GetAlertGroupsParams object
// with the ability to set a context for a request.
func NewGetAlertGroupsParamsWithContext(ctx context.Context) *GetAlertGroupsParams {
return &GetAlertGroupsParams{
Context: ctx,
}
}
// NewGetAlertGroupsParamsWithHTTPClient creates a new GetAlertGroupsParams object
// with the ability to set a custom HTTPClient for a request.
func NewGetAlertGroupsParamsWithHTTPClient(client *http.Client) *GetAlertGroupsParams {
return &GetAlertGroupsParams{
HTTPClient: client,
}
}
/*
GetAlertGroupsParams contains all the parameters to send to the API endpoint
for the get alert groups operation.
Typically these are written to a http.Request.
*/
type GetAlertGroupsParams struct {
/* Active.
Show active alerts
Default: true
*/
Active *bool
/* Filter.
A list of matchers to filter alerts by
*/
Filter []string
/* Inhibited.
Show inhibited alerts
Default: true
*/
Inhibited *bool
/* Receiver.
A regex matching receivers to filter alerts by
*/
Receiver *string
/* Silenced.
Show silenced alerts
Default: true
*/
Silenced *bool
timeout time.Duration
Context context.Context
HTTPClient *http.Client
}
// WithDefaults hydrates default values in the get alert groups params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *GetAlertGroupsParams) WithDefaults() *GetAlertGroupsParams {
o.SetDefaults()
return o
}
// SetDefaults hydrates default values in the get alert groups params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *GetAlertGroupsParams) SetDefaults() {
var (
activeDefault = bool(true)
inhibitedDefault = bool(true)
silencedDefault = bool(true)
)
val := GetAlertGroupsParams{
Active: &activeDefault,
Inhibited: &inhibitedDefault,
Silenced: &silencedDefault,
}
val.timeout = o.timeout
val.Context = o.Context
val.HTTPClient = o.HTTPClient
*o = val
}
// WithTimeout adds the timeout to the get alert groups params
func (o *GetAlertGroupsParams) WithTimeout(timeout time.Duration) *GetAlertGroupsParams {
o.SetTimeout(timeout)
return o
}
// SetTimeout adds the timeout to the get alert groups params
func (o *GetAlertGroupsParams) SetTimeout(timeout time.Duration) {
o.timeout = timeout
}
// WithContext adds the context to the get alert groups params
func (o *GetAlertGroupsParams) WithContext(ctx context.Context) *GetAlertGroupsParams {
o.SetContext(ctx)
return o
}
// SetContext adds the context to the get alert groups params
func (o *GetAlertGroupsParams) SetContext(ctx context.Context) {
o.Context = ctx
}
// WithHTTPClient adds the HTTPClient to the get alert groups params
func (o *GetAlertGroupsParams) WithHTTPClient(client *http.Client) *GetAlertGroupsParams {
o.SetHTTPClient(client)
return o
}
// SetHTTPClient adds the HTTPClient to the get alert groups params
func (o *GetAlertGroupsParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithActive adds the active to the get alert groups params
func (o *GetAlertGroupsParams) WithActive(active *bool) *GetAlertGroupsParams {
o.SetActive(active)
return o
}
// SetActive adds the active to the get alert groups params
func (o *GetAlertGroupsParams) SetActive(active *bool) {
o.Active = active
}
// WithFilter adds the filter to the get alert groups params
func (o *GetAlertGroupsParams) WithFilter(filter []string) *GetAlertGroupsParams {
o.SetFilter(filter)
return o
}
// SetFilter adds the filter to the get alert groups params
func (o *GetAlertGroupsParams) SetFilter(filter []string) {
o.Filter = filter
}
// WithInhibited adds the inhibited to the get alert groups params
func (o *GetAlertGroupsParams) WithInhibited(inhibited *bool) *GetAlertGroupsParams {
o.SetInhibited(inhibited)
return o
}
// SetInhibited adds the inhibited to the get alert groups params
func (o *GetAlertGroupsParams) SetInhibited(inhibited *bool) {
o.Inhibited = inhibited
}
// WithReceiver adds the receiver to the get alert groups params
func (o *GetAlertGroupsParams) WithReceiver(receiver *string) *GetAlertGroupsParams {
o.SetReceiver(receiver)
return o
}
// SetReceiver adds the receiver to the get alert groups params
func (o *GetAlertGroupsParams) SetReceiver(receiver *string) {
o.Receiver = receiver
}
// WithSilenced adds the silenced to the get alert groups params
func (o *GetAlertGroupsParams) WithSilenced(silenced *bool) *GetAlertGroupsParams {
o.SetSilenced(silenced)
return o
}
// SetSilenced adds the silenced to the get alert groups params
func (o *GetAlertGroupsParams) SetSilenced(silenced *bool) {
o.Silenced = silenced
}
// WriteToRequest writes these params to a swagger request
func (o *GetAlertGroupsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {
if err := r.SetTimeout(o.timeout); err != nil {
return err
}
var res []error
if o.Active != nil {
// query param active
var qrActive bool
if o.Active != nil {
qrActive = *o.Active
}
qActive := swag.FormatBool(qrActive)
if qActive != "" {
if err := r.SetQueryParam("active", qActive); err != nil {
return err
}
}
}
if o.Filter != nil {
// binding items for filter
joinedFilter := o.bindParamFilter(reg)
// query array param filter
if err := r.SetQueryParam("filter", joinedFilter...); err != nil {
return err
}
}
if o.Inhibited != nil {
// query param inhibited
var qrInhibited bool
if o.Inhibited != nil {
qrInhibited = *o.Inhibited
}
qInhibited := swag.FormatBool(qrInhibited)
if qInhibited != "" {
if err := r.SetQueryParam("inhibited", qInhibited); err != nil {
return err
}
}
}
if o.Receiver != nil {
// query param receiver
var qrReceiver string
if o.Receiver != nil {
qrReceiver = *o.Receiver
}
qReceiver := qrReceiver
if qReceiver != "" {
if err := r.SetQueryParam("receiver", qReceiver); err != nil {
return err
}
}
}
if o.Silenced != nil {
// query param silenced
var qrSilenced bool
if o.Silenced != nil {
qrSilenced = *o.Silenced
}
qSilenced := swag.FormatBool(qrSilenced)
if qSilenced != "" {
if err := r.SetQueryParam("silenced", qSilenced); err != nil {
return err
}
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
// bindParamGetAlertGroups binds the parameter filter
func (o *GetAlertGroupsParams) bindParamFilter(formats strfmt.Registry) []string {
filterIR := o.Filter
var filterIC []string
for _, filterIIR := range filterIR { // explode []string
filterIIV := filterIIR // string as string
filterIC = append(filterIC, filterIIV)
}
// items.CollectionFormat: "multi"
filterIS := swag.JoinByFormat(filterIC, "multi")
return filterIS
}

View File

@@ -1,244 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package alertgroup
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"io"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
"github.com/prometheus/alertmanager/api/v2/models"
)
// GetAlertGroupsReader is a Reader for the GetAlertGroups structure.
type GetAlertGroupsReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *GetAlertGroupsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 200:
result := NewGetAlertGroupsOK()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
case 400:
result := NewGetAlertGroupsBadRequest()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
case 500:
result := NewGetAlertGroupsInternalServerError()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
default:
return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code())
}
}
// NewGetAlertGroupsOK creates a GetAlertGroupsOK with default headers values
func NewGetAlertGroupsOK() *GetAlertGroupsOK {
return &GetAlertGroupsOK{}
}
/*
GetAlertGroupsOK describes a response with status code 200, with default header values.
Get alert groups response
*/
type GetAlertGroupsOK struct {
Payload models.AlertGroups
}
// IsSuccess returns true when this get alert groups o k response has a 2xx status code
func (o *GetAlertGroupsOK) IsSuccess() bool {
return true
}
// IsRedirect returns true when this get alert groups o k response has a 3xx status code
func (o *GetAlertGroupsOK) IsRedirect() bool {
return false
}
// IsClientError returns true when this get alert groups o k response has a 4xx status code
func (o *GetAlertGroupsOK) IsClientError() bool {
return false
}
// IsServerError returns true when this get alert groups o k response has a 5xx status code
func (o *GetAlertGroupsOK) IsServerError() bool {
return false
}
// IsCode returns true when this get alert groups o k response a status code equal to that given
func (o *GetAlertGroupsOK) IsCode(code int) bool {
return code == 200
}
func (o *GetAlertGroupsOK) Error() string {
return fmt.Sprintf("[GET /alerts/groups][%d] getAlertGroupsOK %+v", 200, o.Payload)
}
func (o *GetAlertGroupsOK) String() string {
return fmt.Sprintf("[GET /alerts/groups][%d] getAlertGroupsOK %+v", 200, o.Payload)
}
func (o *GetAlertGroupsOK) GetPayload() models.AlertGroups {
return o.Payload
}
func (o *GetAlertGroupsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
// response payload
if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
// NewGetAlertGroupsBadRequest creates a GetAlertGroupsBadRequest with default headers values
func NewGetAlertGroupsBadRequest() *GetAlertGroupsBadRequest {
return &GetAlertGroupsBadRequest{}
}
/*
GetAlertGroupsBadRequest describes a response with status code 400, with default header values.
Bad request
*/
type GetAlertGroupsBadRequest struct {
Payload string
}
// IsSuccess returns true when this get alert groups bad request response has a 2xx status code
func (o *GetAlertGroupsBadRequest) IsSuccess() bool {
return false
}
// IsRedirect returns true when this get alert groups bad request response has a 3xx status code
func (o *GetAlertGroupsBadRequest) IsRedirect() bool {
return false
}
// IsClientError returns true when this get alert groups bad request response has a 4xx status code
func (o *GetAlertGroupsBadRequest) IsClientError() bool {
return true
}
// IsServerError returns true when this get alert groups bad request response has a 5xx status code
func (o *GetAlertGroupsBadRequest) IsServerError() bool {
return false
}
// IsCode returns true when this get alert groups bad request response a status code equal to that given
func (o *GetAlertGroupsBadRequest) IsCode(code int) bool {
return code == 400
}
func (o *GetAlertGroupsBadRequest) Error() string {
return fmt.Sprintf("[GET /alerts/groups][%d] getAlertGroupsBadRequest %+v", 400, o.Payload)
}
func (o *GetAlertGroupsBadRequest) String() string {
return fmt.Sprintf("[GET /alerts/groups][%d] getAlertGroupsBadRequest %+v", 400, o.Payload)
}
func (o *GetAlertGroupsBadRequest) GetPayload() string {
return o.Payload
}
func (o *GetAlertGroupsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
// response payload
if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
// NewGetAlertGroupsInternalServerError creates a GetAlertGroupsInternalServerError with default headers values
func NewGetAlertGroupsInternalServerError() *GetAlertGroupsInternalServerError {
return &GetAlertGroupsInternalServerError{}
}
/*
GetAlertGroupsInternalServerError describes a response with status code 500, with default header values.
Internal server error
*/
type GetAlertGroupsInternalServerError struct {
Payload string
}
// IsSuccess returns true when this get alert groups internal server error response has a 2xx status code
func (o *GetAlertGroupsInternalServerError) IsSuccess() bool {
return false
}
// IsRedirect returns true when this get alert groups internal server error response has a 3xx status code
func (o *GetAlertGroupsInternalServerError) IsRedirect() bool {
return false
}
// IsClientError returns true when this get alert groups internal server error response has a 4xx status code
func (o *GetAlertGroupsInternalServerError) IsClientError() bool {
return false
}
// IsServerError returns true when this get alert groups internal server error response has a 5xx status code
func (o *GetAlertGroupsInternalServerError) IsServerError() bool {
return true
}
// IsCode returns true when this get alert groups internal server error response a status code equal to that given
func (o *GetAlertGroupsInternalServerError) IsCode(code int) bool {
return code == 500
}
func (o *GetAlertGroupsInternalServerError) Error() string {
return fmt.Sprintf("[GET /alerts/groups][%d] getAlertGroupsInternalServerError %+v", 500, o.Payload)
}
func (o *GetAlertGroupsInternalServerError) String() string {
return fmt.Sprintf("[GET /alerts/groups][%d] getAlertGroupsInternalServerError %+v", 500, o.Payload)
}
func (o *GetAlertGroupsInternalServerError) GetPayload() string {
return o.Payload
}
func (o *GetAlertGroupsInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
// response payload
if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}

View File

@@ -1,146 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package client
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"github.com/go-openapi/runtime"
httptransport "github.com/go-openapi/runtime/client"
"github.com/go-openapi/strfmt"
"github.com/prometheus/alertmanager/api/v2/client/alert"
"github.com/prometheus/alertmanager/api/v2/client/alertgroup"
"github.com/prometheus/alertmanager/api/v2/client/general"
"github.com/prometheus/alertmanager/api/v2/client/receiver"
"github.com/prometheus/alertmanager/api/v2/client/silence"
)
// Default alertmanager API HTTP client.
var Default = NewHTTPClient(nil)
const (
// DefaultHost is the default Host
// found in Meta (info) section of spec file
DefaultHost string = "localhost"
// DefaultBasePath is the default BasePath
// found in Meta (info) section of spec file
DefaultBasePath string = "/api/v2/"
)
// DefaultSchemes are the default schemes found in Meta (info) section of spec file
var DefaultSchemes = []string{"http"}
// NewHTTPClient creates a new alertmanager API HTTP client.
func NewHTTPClient(formats strfmt.Registry) *AlertmanagerAPI {
return NewHTTPClientWithConfig(formats, nil)
}
// NewHTTPClientWithConfig creates a new alertmanager API HTTP client,
// using a customizable transport config.
func NewHTTPClientWithConfig(formats strfmt.Registry, cfg *TransportConfig) *AlertmanagerAPI {
// ensure nullable parameters have default
if cfg == nil {
cfg = DefaultTransportConfig()
}
// create transport and client
transport := httptransport.New(cfg.Host, cfg.BasePath, cfg.Schemes)
return New(transport, formats)
}
// New creates a new alertmanager API client
func New(transport runtime.ClientTransport, formats strfmt.Registry) *AlertmanagerAPI {
// ensure nullable parameters have default
if formats == nil {
formats = strfmt.Default
}
cli := new(AlertmanagerAPI)
cli.Transport = transport
cli.Alert = alert.New(transport, formats)
cli.Alertgroup = alertgroup.New(transport, formats)
cli.General = general.New(transport, formats)
cli.Receiver = receiver.New(transport, formats)
cli.Silence = silence.New(transport, formats)
return cli
}
// DefaultTransportConfig creates a TransportConfig with the
// default settings taken from the meta section of the spec file.
func DefaultTransportConfig() *TransportConfig {
return &TransportConfig{
Host: DefaultHost,
BasePath: DefaultBasePath,
Schemes: DefaultSchemes,
}
}
// TransportConfig contains the transport related info,
// found in the meta section of the spec file.
type TransportConfig struct {
Host string
BasePath string
Schemes []string
}
// WithHost overrides the default host,
// provided by the meta section of the spec file.
func (cfg *TransportConfig) WithHost(host string) *TransportConfig {
cfg.Host = host
return cfg
}
// WithBasePath overrides the default basePath,
// provided by the meta section of the spec file.
func (cfg *TransportConfig) WithBasePath(basePath string) *TransportConfig {
cfg.BasePath = basePath
return cfg
}
// WithSchemes overrides the default schemes,
// provided by the meta section of the spec file.
func (cfg *TransportConfig) WithSchemes(schemes []string) *TransportConfig {
cfg.Schemes = schemes
return cfg
}
// AlertmanagerAPI is a client for alertmanager API
type AlertmanagerAPI struct {
Alert alert.ClientService
Alertgroup alertgroup.ClientService
General general.ClientService
Receiver receiver.ClientService
Silence silence.ClientService
Transport runtime.ClientTransport
}
// SetTransport changes the transport on the client and all its subresources
func (c *AlertmanagerAPI) SetTransport(transport runtime.ClientTransport) {
c.Transport = transport
c.Alert.SetTransport(transport)
c.Alertgroup.SetTransport(transport)
c.General.SetTransport(transport)
c.Receiver.SetTransport(transport)
c.Silence.SetTransport(transport)
}

View File

@@ -1,93 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package general
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
)
// New creates a new general API client.
func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService {
return &Client{transport: transport, formats: formats}
}
/*
Client for general API
*/
type Client struct {
transport runtime.ClientTransport
formats strfmt.Registry
}
// ClientOption is the option for Client methods
type ClientOption func(*runtime.ClientOperation)
// ClientService is the interface for Client methods
type ClientService interface {
GetStatus(params *GetStatusParams, opts ...ClientOption) (*GetStatusOK, error)
SetTransport(transport runtime.ClientTransport)
}
/*
GetStatus Get current status of an Alertmanager instance and its cluster
*/
func (a *Client) GetStatus(params *GetStatusParams, opts ...ClientOption) (*GetStatusOK, error) {
// TODO: Validate the params before sending
if params == nil {
params = NewGetStatusParams()
}
op := &runtime.ClientOperation{
ID: "getStatus",
Method: "GET",
PathPattern: "/status",
ProducesMediaTypes: []string{"application/json"},
ConsumesMediaTypes: []string{"application/json"},
Schemes: []string{"http"},
Params: params,
Reader: &GetStatusReader{formats: a.formats},
Context: params.Context,
Client: params.HTTPClient,
}
for _, opt := range opts {
opt(op)
}
result, err := a.transport.Submit(op)
if err != nil {
return nil, err
}
success, ok := result.(*GetStatusOK)
if ok {
return success, nil
}
// unexpected success response
// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue
msg := fmt.Sprintf("unexpected success response for getStatus: API contract not enforced by server. Client expected to get an error, but got: %T", result)
panic(msg)
}
// SetTransport changes the transport on the client
func (a *Client) SetTransport(transport runtime.ClientTransport) {
a.transport = transport
}

View File

@@ -1,142 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package general
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"time"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
cr "github.com/go-openapi/runtime/client"
"github.com/go-openapi/strfmt"
)
// NewGetStatusParams creates a new GetStatusParams object,
// with the default timeout for this client.
//
// Default values are not hydrated, since defaults are normally applied by the API server side.
//
// To enforce default values in parameter, use SetDefaults or WithDefaults.
func NewGetStatusParams() *GetStatusParams {
return &GetStatusParams{
timeout: cr.DefaultTimeout,
}
}
// NewGetStatusParamsWithTimeout creates a new GetStatusParams object
// with the ability to set a timeout on a request.
func NewGetStatusParamsWithTimeout(timeout time.Duration) *GetStatusParams {
return &GetStatusParams{
timeout: timeout,
}
}
// NewGetStatusParamsWithContext creates a new GetStatusParams object
// with the ability to set a context for a request.
func NewGetStatusParamsWithContext(ctx context.Context) *GetStatusParams {
return &GetStatusParams{
Context: ctx,
}
}
// NewGetStatusParamsWithHTTPClient creates a new GetStatusParams object
// with the ability to set a custom HTTPClient for a request.
func NewGetStatusParamsWithHTTPClient(client *http.Client) *GetStatusParams {
return &GetStatusParams{
HTTPClient: client,
}
}
/*
GetStatusParams contains all the parameters to send to the API endpoint
for the get status operation.
Typically these are written to a http.Request.
*/
type GetStatusParams struct {
timeout time.Duration
Context context.Context
HTTPClient *http.Client
}
// WithDefaults hydrates default values in the get status params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *GetStatusParams) WithDefaults() *GetStatusParams {
o.SetDefaults()
return o
}
// SetDefaults hydrates default values in the get status params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *GetStatusParams) SetDefaults() {
// no default values defined for this parameter
}
// WithTimeout adds the timeout to the get status params
func (o *GetStatusParams) WithTimeout(timeout time.Duration) *GetStatusParams {
o.SetTimeout(timeout)
return o
}
// SetTimeout adds the timeout to the get status params
func (o *GetStatusParams) SetTimeout(timeout time.Duration) {
o.timeout = timeout
}
// WithContext adds the context to the get status params
func (o *GetStatusParams) WithContext(ctx context.Context) *GetStatusParams {
o.SetContext(ctx)
return o
}
// SetContext adds the context to the get status params
func (o *GetStatusParams) SetContext(ctx context.Context) {
o.Context = ctx
}
// WithHTTPClient adds the HTTPClient to the get status params
func (o *GetStatusParams) WithHTTPClient(client *http.Client) *GetStatusParams {
o.SetHTTPClient(client)
return o
}
// SetHTTPClient adds the HTTPClient to the get status params
func (o *GetStatusParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WriteToRequest writes these params to a swagger request
func (o *GetStatusParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {
if err := r.SetTimeout(o.timeout); err != nil {
return err
}
var res []error
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,112 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package general
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"io"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
"github.com/prometheus/alertmanager/api/v2/models"
)
// GetStatusReader is a Reader for the GetStatus structure.
type GetStatusReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *GetStatusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 200:
result := NewGetStatusOK()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
default:
return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code())
}
}
// NewGetStatusOK creates a GetStatusOK with default headers values
func NewGetStatusOK() *GetStatusOK {
return &GetStatusOK{}
}
/*
GetStatusOK describes a response with status code 200, with default header values.
Get status response
*/
type GetStatusOK struct {
Payload *models.AlertmanagerStatus
}
// IsSuccess returns true when this get status o k response has a 2xx status code
func (o *GetStatusOK) IsSuccess() bool {
return true
}
// IsRedirect returns true when this get status o k response has a 3xx status code
func (o *GetStatusOK) IsRedirect() bool {
return false
}
// IsClientError returns true when this get status o k response has a 4xx status code
func (o *GetStatusOK) IsClientError() bool {
return false
}
// IsServerError returns true when this get status o k response has a 5xx status code
func (o *GetStatusOK) IsServerError() bool {
return false
}
// IsCode returns true when this get status o k response a status code equal to that given
func (o *GetStatusOK) IsCode(code int) bool {
return code == 200
}
func (o *GetStatusOK) Error() string {
return fmt.Sprintf("[GET /status][%d] getStatusOK %+v", 200, o.Payload)
}
func (o *GetStatusOK) String() string {
return fmt.Sprintf("[GET /status][%d] getStatusOK %+v", 200, o.Payload)
}
func (o *GetStatusOK) GetPayload() *models.AlertmanagerStatus {
return o.Payload
}
func (o *GetStatusOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
o.Payload = new(models.AlertmanagerStatus)
// response payload
if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}

View File

@@ -1,142 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package receiver
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"time"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
cr "github.com/go-openapi/runtime/client"
"github.com/go-openapi/strfmt"
)
// NewGetReceiversParams creates a new GetReceiversParams object,
// with the default timeout for this client.
//
// Default values are not hydrated, since defaults are normally applied by the API server side.
//
// To enforce default values in parameter, use SetDefaults or WithDefaults.
func NewGetReceiversParams() *GetReceiversParams {
return &GetReceiversParams{
timeout: cr.DefaultTimeout,
}
}
// NewGetReceiversParamsWithTimeout creates a new GetReceiversParams object
// with the ability to set a timeout on a request.
func NewGetReceiversParamsWithTimeout(timeout time.Duration) *GetReceiversParams {
return &GetReceiversParams{
timeout: timeout,
}
}
// NewGetReceiversParamsWithContext creates a new GetReceiversParams object
// with the ability to set a context for a request.
func NewGetReceiversParamsWithContext(ctx context.Context) *GetReceiversParams {
return &GetReceiversParams{
Context: ctx,
}
}
// NewGetReceiversParamsWithHTTPClient creates a new GetReceiversParams object
// with the ability to set a custom HTTPClient for a request.
func NewGetReceiversParamsWithHTTPClient(client *http.Client) *GetReceiversParams {
return &GetReceiversParams{
HTTPClient: client,
}
}
/*
GetReceiversParams contains all the parameters to send to the API endpoint
for the get receivers operation.
Typically these are written to a http.Request.
*/
type GetReceiversParams struct {
timeout time.Duration
Context context.Context
HTTPClient *http.Client
}
// WithDefaults hydrates default values in the get receivers params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *GetReceiversParams) WithDefaults() *GetReceiversParams {
o.SetDefaults()
return o
}
// SetDefaults hydrates default values in the get receivers params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *GetReceiversParams) SetDefaults() {
// no default values defined for this parameter
}
// WithTimeout adds the timeout to the get receivers params
func (o *GetReceiversParams) WithTimeout(timeout time.Duration) *GetReceiversParams {
o.SetTimeout(timeout)
return o
}
// SetTimeout adds the timeout to the get receivers params
func (o *GetReceiversParams) SetTimeout(timeout time.Duration) {
o.timeout = timeout
}
// WithContext adds the context to the get receivers params
func (o *GetReceiversParams) WithContext(ctx context.Context) *GetReceiversParams {
o.SetContext(ctx)
return o
}
// SetContext adds the context to the get receivers params
func (o *GetReceiversParams) SetContext(ctx context.Context) {
o.Context = ctx
}
// WithHTTPClient adds the HTTPClient to the get receivers params
func (o *GetReceiversParams) WithHTTPClient(client *http.Client) *GetReceiversParams {
o.SetHTTPClient(client)
return o
}
// SetHTTPClient adds the HTTPClient to the get receivers params
func (o *GetReceiversParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WriteToRequest writes these params to a swagger request
func (o *GetReceiversParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {
if err := r.SetTimeout(o.timeout); err != nil {
return err
}
var res []error
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,110 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package receiver
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"io"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
"github.com/prometheus/alertmanager/api/v2/models"
)
// GetReceiversReader is a Reader for the GetReceivers structure.
type GetReceiversReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *GetReceiversReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 200:
result := NewGetReceiversOK()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
default:
return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code())
}
}
// NewGetReceiversOK creates a GetReceiversOK with default headers values
func NewGetReceiversOK() *GetReceiversOK {
return &GetReceiversOK{}
}
/*
GetReceiversOK describes a response with status code 200, with default header values.
Get receivers response
*/
type GetReceiversOK struct {
Payload []*models.Receiver
}
// IsSuccess returns true when this get receivers o k response has a 2xx status code
func (o *GetReceiversOK) IsSuccess() bool {
return true
}
// IsRedirect returns true when this get receivers o k response has a 3xx status code
func (o *GetReceiversOK) IsRedirect() bool {
return false
}
// IsClientError returns true when this get receivers o k response has a 4xx status code
func (o *GetReceiversOK) IsClientError() bool {
return false
}
// IsServerError returns true when this get receivers o k response has a 5xx status code
func (o *GetReceiversOK) IsServerError() bool {
return false
}
// IsCode returns true when this get receivers o k response a status code equal to that given
func (o *GetReceiversOK) IsCode(code int) bool {
return code == 200
}
func (o *GetReceiversOK) Error() string {
return fmt.Sprintf("[GET /receivers][%d] getReceiversOK %+v", 200, o.Payload)
}
func (o *GetReceiversOK) String() string {
return fmt.Sprintf("[GET /receivers][%d] getReceiversOK %+v", 200, o.Payload)
}
func (o *GetReceiversOK) GetPayload() []*models.Receiver {
return o.Payload
}
func (o *GetReceiversOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
// response payload
if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}

View File

@@ -1,93 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package receiver
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
)
// New creates a new receiver API client.
func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService {
return &Client{transport: transport, formats: formats}
}
/*
Client for receiver API
*/
type Client struct {
transport runtime.ClientTransport
formats strfmt.Registry
}
// ClientOption is the option for Client methods
type ClientOption func(*runtime.ClientOperation)
// ClientService is the interface for Client methods
type ClientService interface {
GetReceivers(params *GetReceiversParams, opts ...ClientOption) (*GetReceiversOK, error)
SetTransport(transport runtime.ClientTransport)
}
/*
GetReceivers Get list of all receivers (name of notification integrations)
*/
func (a *Client) GetReceivers(params *GetReceiversParams, opts ...ClientOption) (*GetReceiversOK, error) {
// TODO: Validate the params before sending
if params == nil {
params = NewGetReceiversParams()
}
op := &runtime.ClientOperation{
ID: "getReceivers",
Method: "GET",
PathPattern: "/receivers",
ProducesMediaTypes: []string{"application/json"},
ConsumesMediaTypes: []string{"application/json"},
Schemes: []string{"http"},
Params: params,
Reader: &GetReceiversReader{formats: a.formats},
Context: params.Context,
Client: params.HTTPClient,
}
for _, opt := range opts {
opt(op)
}
result, err := a.transport.Submit(op)
if err != nil {
return nil, err
}
success, ok := result.(*GetReceiversOK)
if ok {
return success, nil
}
// unexpected success response
// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue
msg := fmt.Sprintf("unexpected success response for getReceivers: API contract not enforced by server. Client expected to get an error, but got: %T", result)
panic(msg)
}
// SetTransport changes the transport on the client
func (a *Client) SetTransport(transport runtime.ClientTransport) {
a.transport = transport
}

View File

@@ -1,167 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package silence
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"time"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
cr "github.com/go-openapi/runtime/client"
"github.com/go-openapi/strfmt"
)
// NewDeleteSilenceParams creates a new DeleteSilenceParams object,
// with the default timeout for this client.
//
// Default values are not hydrated, since defaults are normally applied by the API server side.
//
// To enforce default values in parameter, use SetDefaults or WithDefaults.
func NewDeleteSilenceParams() *DeleteSilenceParams {
return &DeleteSilenceParams{
timeout: cr.DefaultTimeout,
}
}
// NewDeleteSilenceParamsWithTimeout creates a new DeleteSilenceParams object
// with the ability to set a timeout on a request.
func NewDeleteSilenceParamsWithTimeout(timeout time.Duration) *DeleteSilenceParams {
return &DeleteSilenceParams{
timeout: timeout,
}
}
// NewDeleteSilenceParamsWithContext creates a new DeleteSilenceParams object
// with the ability to set a context for a request.
func NewDeleteSilenceParamsWithContext(ctx context.Context) *DeleteSilenceParams {
return &DeleteSilenceParams{
Context: ctx,
}
}
// NewDeleteSilenceParamsWithHTTPClient creates a new DeleteSilenceParams object
// with the ability to set a custom HTTPClient for a request.
func NewDeleteSilenceParamsWithHTTPClient(client *http.Client) *DeleteSilenceParams {
return &DeleteSilenceParams{
HTTPClient: client,
}
}
/*
DeleteSilenceParams contains all the parameters to send to the API endpoint
for the delete silence operation.
Typically these are written to a http.Request.
*/
type DeleteSilenceParams struct {
/* SilenceID.
ID of the silence to get
Format: uuid
*/
SilenceID strfmt.UUID
timeout time.Duration
Context context.Context
HTTPClient *http.Client
}
// WithDefaults hydrates default values in the delete silence params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *DeleteSilenceParams) WithDefaults() *DeleteSilenceParams {
o.SetDefaults()
return o
}
// SetDefaults hydrates default values in the delete silence params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *DeleteSilenceParams) SetDefaults() {
// no default values defined for this parameter
}
// WithTimeout adds the timeout to the delete silence params
func (o *DeleteSilenceParams) WithTimeout(timeout time.Duration) *DeleteSilenceParams {
o.SetTimeout(timeout)
return o
}
// SetTimeout adds the timeout to the delete silence params
func (o *DeleteSilenceParams) SetTimeout(timeout time.Duration) {
o.timeout = timeout
}
// WithContext adds the context to the delete silence params
func (o *DeleteSilenceParams) WithContext(ctx context.Context) *DeleteSilenceParams {
o.SetContext(ctx)
return o
}
// SetContext adds the context to the delete silence params
func (o *DeleteSilenceParams) SetContext(ctx context.Context) {
o.Context = ctx
}
// WithHTTPClient adds the HTTPClient to the delete silence params
func (o *DeleteSilenceParams) WithHTTPClient(client *http.Client) *DeleteSilenceParams {
o.SetHTTPClient(client)
return o
}
// SetHTTPClient adds the HTTPClient to the delete silence params
func (o *DeleteSilenceParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithSilenceID adds the silenceID to the delete silence params
func (o *DeleteSilenceParams) WithSilenceID(silenceID strfmt.UUID) *DeleteSilenceParams {
o.SetSilenceID(silenceID)
return o
}
// SetSilenceID adds the silenceId to the delete silence params
func (o *DeleteSilenceParams) SetSilenceID(silenceID strfmt.UUID) {
o.SilenceID = silenceID
}
// WriteToRequest writes these params to a swagger request
func (o *DeleteSilenceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {
if err := r.SetTimeout(o.timeout); err != nil {
return err
}
var res []error
// path param silenceID
if err := r.SetPathParam("silenceID", o.SilenceID.String()); err != nil {
return err
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,165 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package silence
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"io"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
)
// DeleteSilenceReader is a Reader for the DeleteSilence structure.
type DeleteSilenceReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *DeleteSilenceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 200:
result := NewDeleteSilenceOK()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
case 500:
result := NewDeleteSilenceInternalServerError()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
default:
return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code())
}
}
// NewDeleteSilenceOK creates a DeleteSilenceOK with default headers values
func NewDeleteSilenceOK() *DeleteSilenceOK {
return &DeleteSilenceOK{}
}
/*
DeleteSilenceOK describes a response with status code 200, with default header values.
Delete silence response
*/
type DeleteSilenceOK struct {
}
// IsSuccess returns true when this delete silence o k response has a 2xx status code
func (o *DeleteSilenceOK) IsSuccess() bool {
return true
}
// IsRedirect returns true when this delete silence o k response has a 3xx status code
func (o *DeleteSilenceOK) IsRedirect() bool {
return false
}
// IsClientError returns true when this delete silence o k response has a 4xx status code
func (o *DeleteSilenceOK) IsClientError() bool {
return false
}
// IsServerError returns true when this delete silence o k response has a 5xx status code
func (o *DeleteSilenceOK) IsServerError() bool {
return false
}
// IsCode returns true when this delete silence o k response a status code equal to that given
func (o *DeleteSilenceOK) IsCode(code int) bool {
return code == 200
}
func (o *DeleteSilenceOK) Error() string {
return fmt.Sprintf("[DELETE /silence/{silenceID}][%d] deleteSilenceOK ", 200)
}
func (o *DeleteSilenceOK) String() string {
return fmt.Sprintf("[DELETE /silence/{silenceID}][%d] deleteSilenceOK ", 200)
}
func (o *DeleteSilenceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
return nil
}
// NewDeleteSilenceInternalServerError creates a DeleteSilenceInternalServerError with default headers values
func NewDeleteSilenceInternalServerError() *DeleteSilenceInternalServerError {
return &DeleteSilenceInternalServerError{}
}
/*
DeleteSilenceInternalServerError describes a response with status code 500, with default header values.
Internal server error
*/
type DeleteSilenceInternalServerError struct {
Payload string
}
// IsSuccess returns true when this delete silence internal server error response has a 2xx status code
func (o *DeleteSilenceInternalServerError) IsSuccess() bool {
return false
}
// IsRedirect returns true when this delete silence internal server error response has a 3xx status code
func (o *DeleteSilenceInternalServerError) IsRedirect() bool {
return false
}
// IsClientError returns true when this delete silence internal server error response has a 4xx status code
func (o *DeleteSilenceInternalServerError) IsClientError() bool {
return false
}
// IsServerError returns true when this delete silence internal server error response has a 5xx status code
func (o *DeleteSilenceInternalServerError) IsServerError() bool {
return true
}
// IsCode returns true when this delete silence internal server error response a status code equal to that given
func (o *DeleteSilenceInternalServerError) IsCode(code int) bool {
return code == 500
}
func (o *DeleteSilenceInternalServerError) Error() string {
return fmt.Sprintf("[DELETE /silence/{silenceID}][%d] deleteSilenceInternalServerError %+v", 500, o.Payload)
}
func (o *DeleteSilenceInternalServerError) String() string {
return fmt.Sprintf("[DELETE /silence/{silenceID}][%d] deleteSilenceInternalServerError %+v", 500, o.Payload)
}
func (o *DeleteSilenceInternalServerError) GetPayload() string {
return o.Payload
}
func (o *DeleteSilenceInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
// response payload
if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}

View File

@@ -1,167 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package silence
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"time"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
cr "github.com/go-openapi/runtime/client"
"github.com/go-openapi/strfmt"
)
// NewGetSilenceParams creates a new GetSilenceParams object,
// with the default timeout for this client.
//
// Default values are not hydrated, since defaults are normally applied by the API server side.
//
// To enforce default values in parameter, use SetDefaults or WithDefaults.
func NewGetSilenceParams() *GetSilenceParams {
return &GetSilenceParams{
timeout: cr.DefaultTimeout,
}
}
// NewGetSilenceParamsWithTimeout creates a new GetSilenceParams object
// with the ability to set a timeout on a request.
func NewGetSilenceParamsWithTimeout(timeout time.Duration) *GetSilenceParams {
return &GetSilenceParams{
timeout: timeout,
}
}
// NewGetSilenceParamsWithContext creates a new GetSilenceParams object
// with the ability to set a context for a request.
func NewGetSilenceParamsWithContext(ctx context.Context) *GetSilenceParams {
return &GetSilenceParams{
Context: ctx,
}
}
// NewGetSilenceParamsWithHTTPClient creates a new GetSilenceParams object
// with the ability to set a custom HTTPClient for a request.
func NewGetSilenceParamsWithHTTPClient(client *http.Client) *GetSilenceParams {
return &GetSilenceParams{
HTTPClient: client,
}
}
/*
GetSilenceParams contains all the parameters to send to the API endpoint
for the get silence operation.
Typically these are written to a http.Request.
*/
type GetSilenceParams struct {
/* SilenceID.
ID of the silence to get
Format: uuid
*/
SilenceID strfmt.UUID
timeout time.Duration
Context context.Context
HTTPClient *http.Client
}
// WithDefaults hydrates default values in the get silence params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *GetSilenceParams) WithDefaults() *GetSilenceParams {
o.SetDefaults()
return o
}
// SetDefaults hydrates default values in the get silence params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *GetSilenceParams) SetDefaults() {
// no default values defined for this parameter
}
// WithTimeout adds the timeout to the get silence params
func (o *GetSilenceParams) WithTimeout(timeout time.Duration) *GetSilenceParams {
o.SetTimeout(timeout)
return o
}
// SetTimeout adds the timeout to the get silence params
func (o *GetSilenceParams) SetTimeout(timeout time.Duration) {
o.timeout = timeout
}
// WithContext adds the context to the get silence params
func (o *GetSilenceParams) WithContext(ctx context.Context) *GetSilenceParams {
o.SetContext(ctx)
return o
}
// SetContext adds the context to the get silence params
func (o *GetSilenceParams) SetContext(ctx context.Context) {
o.Context = ctx
}
// WithHTTPClient adds the HTTPClient to the get silence params
func (o *GetSilenceParams) WithHTTPClient(client *http.Client) *GetSilenceParams {
o.SetHTTPClient(client)
return o
}
// SetHTTPClient adds the HTTPClient to the get silence params
func (o *GetSilenceParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithSilenceID adds the silenceID to the get silence params
func (o *GetSilenceParams) WithSilenceID(silenceID strfmt.UUID) *GetSilenceParams {
o.SetSilenceID(silenceID)
return o
}
// SetSilenceID adds the silenceId to the get silence params
func (o *GetSilenceParams) SetSilenceID(silenceID strfmt.UUID) {
o.SilenceID = silenceID
}
// WriteToRequest writes these params to a swagger request
func (o *GetSilenceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {
if err := r.SetTimeout(o.timeout); err != nil {
return err
}
var res []error
// path param silenceID
if err := r.SetPathParam("silenceID", o.SilenceID.String()); err != nil {
return err
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,236 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package silence
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"io"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
"github.com/prometheus/alertmanager/api/v2/models"
)
// GetSilenceReader is a Reader for the GetSilence structure.
type GetSilenceReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *GetSilenceReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 200:
result := NewGetSilenceOK()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
case 404:
result := NewGetSilenceNotFound()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
case 500:
result := NewGetSilenceInternalServerError()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
default:
return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code())
}
}
// NewGetSilenceOK creates a GetSilenceOK with default headers values
func NewGetSilenceOK() *GetSilenceOK {
return &GetSilenceOK{}
}
/*
GetSilenceOK describes a response with status code 200, with default header values.
Get silence response
*/
type GetSilenceOK struct {
Payload *models.GettableSilence
}
// IsSuccess returns true when this get silence o k response has a 2xx status code
func (o *GetSilenceOK) IsSuccess() bool {
return true
}
// IsRedirect returns true when this get silence o k response has a 3xx status code
func (o *GetSilenceOK) IsRedirect() bool {
return false
}
// IsClientError returns true when this get silence o k response has a 4xx status code
func (o *GetSilenceOK) IsClientError() bool {
return false
}
// IsServerError returns true when this get silence o k response has a 5xx status code
func (o *GetSilenceOK) IsServerError() bool {
return false
}
// IsCode returns true when this get silence o k response a status code equal to that given
func (o *GetSilenceOK) IsCode(code int) bool {
return code == 200
}
func (o *GetSilenceOK) Error() string {
return fmt.Sprintf("[GET /silence/{silenceID}][%d] getSilenceOK %+v", 200, o.Payload)
}
func (o *GetSilenceOK) String() string {
return fmt.Sprintf("[GET /silence/{silenceID}][%d] getSilenceOK %+v", 200, o.Payload)
}
func (o *GetSilenceOK) GetPayload() *models.GettableSilence {
return o.Payload
}
func (o *GetSilenceOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
o.Payload = new(models.GettableSilence)
// response payload
if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
// NewGetSilenceNotFound creates a GetSilenceNotFound with default headers values
func NewGetSilenceNotFound() *GetSilenceNotFound {
return &GetSilenceNotFound{}
}
/*
GetSilenceNotFound describes a response with status code 404, with default header values.
A silence with the specified ID was not found
*/
type GetSilenceNotFound struct {
}
// IsSuccess returns true when this get silence not found response has a 2xx status code
func (o *GetSilenceNotFound) IsSuccess() bool {
return false
}
// IsRedirect returns true when this get silence not found response has a 3xx status code
func (o *GetSilenceNotFound) IsRedirect() bool {
return false
}
// IsClientError returns true when this get silence not found response has a 4xx status code
func (o *GetSilenceNotFound) IsClientError() bool {
return true
}
// IsServerError returns true when this get silence not found response has a 5xx status code
func (o *GetSilenceNotFound) IsServerError() bool {
return false
}
// IsCode returns true when this get silence not found response a status code equal to that given
func (o *GetSilenceNotFound) IsCode(code int) bool {
return code == 404
}
func (o *GetSilenceNotFound) Error() string {
return fmt.Sprintf("[GET /silence/{silenceID}][%d] getSilenceNotFound ", 404)
}
func (o *GetSilenceNotFound) String() string {
return fmt.Sprintf("[GET /silence/{silenceID}][%d] getSilenceNotFound ", 404)
}
func (o *GetSilenceNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
return nil
}
// NewGetSilenceInternalServerError creates a GetSilenceInternalServerError with default headers values
func NewGetSilenceInternalServerError() *GetSilenceInternalServerError {
return &GetSilenceInternalServerError{}
}
/*
GetSilenceInternalServerError describes a response with status code 500, with default header values.
Internal server error
*/
type GetSilenceInternalServerError struct {
Payload string
}
// IsSuccess returns true when this get silence internal server error response has a 2xx status code
func (o *GetSilenceInternalServerError) IsSuccess() bool {
return false
}
// IsRedirect returns true when this get silence internal server error response has a 3xx status code
func (o *GetSilenceInternalServerError) IsRedirect() bool {
return false
}
// IsClientError returns true when this get silence internal server error response has a 4xx status code
func (o *GetSilenceInternalServerError) IsClientError() bool {
return false
}
// IsServerError returns true when this get silence internal server error response has a 5xx status code
func (o *GetSilenceInternalServerError) IsServerError() bool {
return true
}
// IsCode returns true when this get silence internal server error response a status code equal to that given
func (o *GetSilenceInternalServerError) IsCode(code int) bool {
return code == 500
}
func (o *GetSilenceInternalServerError) Error() string {
return fmt.Sprintf("[GET /silence/{silenceID}][%d] getSilenceInternalServerError %+v", 500, o.Payload)
}
func (o *GetSilenceInternalServerError) String() string {
return fmt.Sprintf("[GET /silence/{silenceID}][%d] getSilenceInternalServerError %+v", 500, o.Payload)
}
func (o *GetSilenceInternalServerError) GetPayload() string {
return o.Payload
}
func (o *GetSilenceInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
// response payload
if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}

View File

@@ -1,189 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package silence
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"time"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
cr "github.com/go-openapi/runtime/client"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// NewGetSilencesParams creates a new GetSilencesParams object,
// with the default timeout for this client.
//
// Default values are not hydrated, since defaults are normally applied by the API server side.
//
// To enforce default values in parameter, use SetDefaults or WithDefaults.
func NewGetSilencesParams() *GetSilencesParams {
return &GetSilencesParams{
timeout: cr.DefaultTimeout,
}
}
// NewGetSilencesParamsWithTimeout creates a new GetSilencesParams object
// with the ability to set a timeout on a request.
func NewGetSilencesParamsWithTimeout(timeout time.Duration) *GetSilencesParams {
return &GetSilencesParams{
timeout: timeout,
}
}
// NewGetSilencesParamsWithContext creates a new GetSilencesParams object
// with the ability to set a context for a request.
func NewGetSilencesParamsWithContext(ctx context.Context) *GetSilencesParams {
return &GetSilencesParams{
Context: ctx,
}
}
// NewGetSilencesParamsWithHTTPClient creates a new GetSilencesParams object
// with the ability to set a custom HTTPClient for a request.
func NewGetSilencesParamsWithHTTPClient(client *http.Client) *GetSilencesParams {
return &GetSilencesParams{
HTTPClient: client,
}
}
/*
GetSilencesParams contains all the parameters to send to the API endpoint
for the get silences operation.
Typically these are written to a http.Request.
*/
type GetSilencesParams struct {
/* Filter.
A list of matchers to filter silences by
*/
Filter []string
timeout time.Duration
Context context.Context
HTTPClient *http.Client
}
// WithDefaults hydrates default values in the get silences params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *GetSilencesParams) WithDefaults() *GetSilencesParams {
o.SetDefaults()
return o
}
// SetDefaults hydrates default values in the get silences params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *GetSilencesParams) SetDefaults() {
// no default values defined for this parameter
}
// WithTimeout adds the timeout to the get silences params
func (o *GetSilencesParams) WithTimeout(timeout time.Duration) *GetSilencesParams {
o.SetTimeout(timeout)
return o
}
// SetTimeout adds the timeout to the get silences params
func (o *GetSilencesParams) SetTimeout(timeout time.Duration) {
o.timeout = timeout
}
// WithContext adds the context to the get silences params
func (o *GetSilencesParams) WithContext(ctx context.Context) *GetSilencesParams {
o.SetContext(ctx)
return o
}
// SetContext adds the context to the get silences params
func (o *GetSilencesParams) SetContext(ctx context.Context) {
o.Context = ctx
}
// WithHTTPClient adds the HTTPClient to the get silences params
func (o *GetSilencesParams) WithHTTPClient(client *http.Client) *GetSilencesParams {
o.SetHTTPClient(client)
return o
}
// SetHTTPClient adds the HTTPClient to the get silences params
func (o *GetSilencesParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithFilter adds the filter to the get silences params
func (o *GetSilencesParams) WithFilter(filter []string) *GetSilencesParams {
o.SetFilter(filter)
return o
}
// SetFilter adds the filter to the get silences params
func (o *GetSilencesParams) SetFilter(filter []string) {
o.Filter = filter
}
// WriteToRequest writes these params to a swagger request
func (o *GetSilencesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {
if err := r.SetTimeout(o.timeout); err != nil {
return err
}
var res []error
if o.Filter != nil {
// binding items for filter
joinedFilter := o.bindParamFilter(reg)
// query array param filter
if err := r.SetQueryParam("filter", joinedFilter...); err != nil {
return err
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
// bindParamGetSilences binds the parameter filter
func (o *GetSilencesParams) bindParamFilter(formats strfmt.Registry) []string {
filterIR := o.Filter
var filterIC []string
for _, filterIIR := range filterIR { // explode []string
filterIIV := filterIIR // string as string
filterIC = append(filterIC, filterIIV)
}
// items.CollectionFormat: "multi"
filterIS := swag.JoinByFormat(filterIC, "multi")
return filterIS
}

View File

@@ -1,177 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package silence
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"io"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
"github.com/prometheus/alertmanager/api/v2/models"
)
// GetSilencesReader is a Reader for the GetSilences structure.
type GetSilencesReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *GetSilencesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 200:
result := NewGetSilencesOK()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
case 500:
result := NewGetSilencesInternalServerError()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
default:
return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code())
}
}
// NewGetSilencesOK creates a GetSilencesOK with default headers values
func NewGetSilencesOK() *GetSilencesOK {
return &GetSilencesOK{}
}
/*
GetSilencesOK describes a response with status code 200, with default header values.
Get silences response
*/
type GetSilencesOK struct {
Payload models.GettableSilences
}
// IsSuccess returns true when this get silences o k response has a 2xx status code
func (o *GetSilencesOK) IsSuccess() bool {
return true
}
// IsRedirect returns true when this get silences o k response has a 3xx status code
func (o *GetSilencesOK) IsRedirect() bool {
return false
}
// IsClientError returns true when this get silences o k response has a 4xx status code
func (o *GetSilencesOK) IsClientError() bool {
return false
}
// IsServerError returns true when this get silences o k response has a 5xx status code
func (o *GetSilencesOK) IsServerError() bool {
return false
}
// IsCode returns true when this get silences o k response a status code equal to that given
func (o *GetSilencesOK) IsCode(code int) bool {
return code == 200
}
func (o *GetSilencesOK) Error() string {
return fmt.Sprintf("[GET /silences][%d] getSilencesOK %+v", 200, o.Payload)
}
func (o *GetSilencesOK) String() string {
return fmt.Sprintf("[GET /silences][%d] getSilencesOK %+v", 200, o.Payload)
}
func (o *GetSilencesOK) GetPayload() models.GettableSilences {
return o.Payload
}
func (o *GetSilencesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
// response payload
if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
// NewGetSilencesInternalServerError creates a GetSilencesInternalServerError with default headers values
func NewGetSilencesInternalServerError() *GetSilencesInternalServerError {
return &GetSilencesInternalServerError{}
}
/*
GetSilencesInternalServerError describes a response with status code 500, with default header values.
Internal server error
*/
type GetSilencesInternalServerError struct {
Payload string
}
// IsSuccess returns true when this get silences internal server error response has a 2xx status code
func (o *GetSilencesInternalServerError) IsSuccess() bool {
return false
}
// IsRedirect returns true when this get silences internal server error response has a 3xx status code
func (o *GetSilencesInternalServerError) IsRedirect() bool {
return false
}
// IsClientError returns true when this get silences internal server error response has a 4xx status code
func (o *GetSilencesInternalServerError) IsClientError() bool {
return false
}
// IsServerError returns true when this get silences internal server error response has a 5xx status code
func (o *GetSilencesInternalServerError) IsServerError() bool {
return true
}
// IsCode returns true when this get silences internal server error response a status code equal to that given
func (o *GetSilencesInternalServerError) IsCode(code int) bool {
return code == 500
}
func (o *GetSilencesInternalServerError) Error() string {
return fmt.Sprintf("[GET /silences][%d] getSilencesInternalServerError %+v", 500, o.Payload)
}
func (o *GetSilencesInternalServerError) String() string {
return fmt.Sprintf("[GET /silences][%d] getSilencesInternalServerError %+v", 500, o.Payload)
}
func (o *GetSilencesInternalServerError) GetPayload() string {
return o.Payload
}
func (o *GetSilencesInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
// response payload
if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}

View File

@@ -1,167 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package silence
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"time"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
cr "github.com/go-openapi/runtime/client"
"github.com/go-openapi/strfmt"
"github.com/prometheus/alertmanager/api/v2/models"
)
// NewPostSilencesParams creates a new PostSilencesParams object,
// with the default timeout for this client.
//
// Default values are not hydrated, since defaults are normally applied by the API server side.
//
// To enforce default values in parameter, use SetDefaults or WithDefaults.
func NewPostSilencesParams() *PostSilencesParams {
return &PostSilencesParams{
timeout: cr.DefaultTimeout,
}
}
// NewPostSilencesParamsWithTimeout creates a new PostSilencesParams object
// with the ability to set a timeout on a request.
func NewPostSilencesParamsWithTimeout(timeout time.Duration) *PostSilencesParams {
return &PostSilencesParams{
timeout: timeout,
}
}
// NewPostSilencesParamsWithContext creates a new PostSilencesParams object
// with the ability to set a context for a request.
func NewPostSilencesParamsWithContext(ctx context.Context) *PostSilencesParams {
return &PostSilencesParams{
Context: ctx,
}
}
// NewPostSilencesParamsWithHTTPClient creates a new PostSilencesParams object
// with the ability to set a custom HTTPClient for a request.
func NewPostSilencesParamsWithHTTPClient(client *http.Client) *PostSilencesParams {
return &PostSilencesParams{
HTTPClient: client,
}
}
/*
PostSilencesParams contains all the parameters to send to the API endpoint
for the post silences operation.
Typically these are written to a http.Request.
*/
type PostSilencesParams struct {
/* Silence.
The silence to create
*/
Silence *models.PostableSilence
timeout time.Duration
Context context.Context
HTTPClient *http.Client
}
// WithDefaults hydrates default values in the post silences params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *PostSilencesParams) WithDefaults() *PostSilencesParams {
o.SetDefaults()
return o
}
// SetDefaults hydrates default values in the post silences params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *PostSilencesParams) SetDefaults() {
// no default values defined for this parameter
}
// WithTimeout adds the timeout to the post silences params
func (o *PostSilencesParams) WithTimeout(timeout time.Duration) *PostSilencesParams {
o.SetTimeout(timeout)
return o
}
// SetTimeout adds the timeout to the post silences params
func (o *PostSilencesParams) SetTimeout(timeout time.Duration) {
o.timeout = timeout
}
// WithContext adds the context to the post silences params
func (o *PostSilencesParams) WithContext(ctx context.Context) *PostSilencesParams {
o.SetContext(ctx)
return o
}
// SetContext adds the context to the post silences params
func (o *PostSilencesParams) SetContext(ctx context.Context) {
o.Context = ctx
}
// WithHTTPClient adds the HTTPClient to the post silences params
func (o *PostSilencesParams) WithHTTPClient(client *http.Client) *PostSilencesParams {
o.SetHTTPClient(client)
return o
}
// SetHTTPClient adds the HTTPClient to the post silences params
func (o *PostSilencesParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithSilence adds the silence to the post silences params
func (o *PostSilencesParams) WithSilence(silence *models.PostableSilence) *PostSilencesParams {
o.SetSilence(silence)
return o
}
// SetSilence adds the silence to the post silences params
func (o *PostSilencesParams) SetSilence(silence *models.PostableSilence) {
o.Silence = silence
}
// WriteToRequest writes these params to a swagger request
func (o *PostSilencesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {
if err := r.SetTimeout(o.timeout); err != nil {
return err
}
var res []error
if o.Silence != nil {
if err := r.SetBodyParam(o.Silence); err != nil {
return err
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,284 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package silence
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"fmt"
"io"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// PostSilencesReader is a Reader for the PostSilences structure.
type PostSilencesReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *PostSilencesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 200:
result := NewPostSilencesOK()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
case 400:
result := NewPostSilencesBadRequest()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
case 404:
result := NewPostSilencesNotFound()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
default:
return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code())
}
}
// NewPostSilencesOK creates a PostSilencesOK with default headers values
func NewPostSilencesOK() *PostSilencesOK {
return &PostSilencesOK{}
}
/*
PostSilencesOK describes a response with status code 200, with default header values.
Create / update silence response
*/
type PostSilencesOK struct {
Payload *PostSilencesOKBody
}
// IsSuccess returns true when this post silences o k response has a 2xx status code
func (o *PostSilencesOK) IsSuccess() bool {
return true
}
// IsRedirect returns true when this post silences o k response has a 3xx status code
func (o *PostSilencesOK) IsRedirect() bool {
return false
}
// IsClientError returns true when this post silences o k response has a 4xx status code
func (o *PostSilencesOK) IsClientError() bool {
return false
}
// IsServerError returns true when this post silences o k response has a 5xx status code
func (o *PostSilencesOK) IsServerError() bool {
return false
}
// IsCode returns true when this post silences o k response a status code equal to that given
func (o *PostSilencesOK) IsCode(code int) bool {
return code == 200
}
func (o *PostSilencesOK) Error() string {
return fmt.Sprintf("[POST /silences][%d] postSilencesOK %+v", 200, o.Payload)
}
func (o *PostSilencesOK) String() string {
return fmt.Sprintf("[POST /silences][%d] postSilencesOK %+v", 200, o.Payload)
}
func (o *PostSilencesOK) GetPayload() *PostSilencesOKBody {
return o.Payload
}
func (o *PostSilencesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
o.Payload = new(PostSilencesOKBody)
// response payload
if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
// NewPostSilencesBadRequest creates a PostSilencesBadRequest with default headers values
func NewPostSilencesBadRequest() *PostSilencesBadRequest {
return &PostSilencesBadRequest{}
}
/*
PostSilencesBadRequest describes a response with status code 400, with default header values.
Bad request
*/
type PostSilencesBadRequest struct {
Payload string
}
// IsSuccess returns true when this post silences bad request response has a 2xx status code
func (o *PostSilencesBadRequest) IsSuccess() bool {
return false
}
// IsRedirect returns true when this post silences bad request response has a 3xx status code
func (o *PostSilencesBadRequest) IsRedirect() bool {
return false
}
// IsClientError returns true when this post silences bad request response has a 4xx status code
func (o *PostSilencesBadRequest) IsClientError() bool {
return true
}
// IsServerError returns true when this post silences bad request response has a 5xx status code
func (o *PostSilencesBadRequest) IsServerError() bool {
return false
}
// IsCode returns true when this post silences bad request response a status code equal to that given
func (o *PostSilencesBadRequest) IsCode(code int) bool {
return code == 400
}
func (o *PostSilencesBadRequest) Error() string {
return fmt.Sprintf("[POST /silences][%d] postSilencesBadRequest %+v", 400, o.Payload)
}
func (o *PostSilencesBadRequest) String() string {
return fmt.Sprintf("[POST /silences][%d] postSilencesBadRequest %+v", 400, o.Payload)
}
func (o *PostSilencesBadRequest) GetPayload() string {
return o.Payload
}
func (o *PostSilencesBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
// response payload
if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
// NewPostSilencesNotFound creates a PostSilencesNotFound with default headers values
func NewPostSilencesNotFound() *PostSilencesNotFound {
return &PostSilencesNotFound{}
}
/*
PostSilencesNotFound describes a response with status code 404, with default header values.
A silence with the specified ID was not found
*/
type PostSilencesNotFound struct {
Payload string
}
// IsSuccess returns true when this post silences not found response has a 2xx status code
func (o *PostSilencesNotFound) IsSuccess() bool {
return false
}
// IsRedirect returns true when this post silences not found response has a 3xx status code
func (o *PostSilencesNotFound) IsRedirect() bool {
return false
}
// IsClientError returns true when this post silences not found response has a 4xx status code
func (o *PostSilencesNotFound) IsClientError() bool {
return true
}
// IsServerError returns true when this post silences not found response has a 5xx status code
func (o *PostSilencesNotFound) IsServerError() bool {
return false
}
// IsCode returns true when this post silences not found response a status code equal to that given
func (o *PostSilencesNotFound) IsCode(code int) bool {
return code == 404
}
func (o *PostSilencesNotFound) Error() string {
return fmt.Sprintf("[POST /silences][%d] postSilencesNotFound %+v", 404, o.Payload)
}
func (o *PostSilencesNotFound) String() string {
return fmt.Sprintf("[POST /silences][%d] postSilencesNotFound %+v", 404, o.Payload)
}
func (o *PostSilencesNotFound) GetPayload() string {
return o.Payload
}
func (o *PostSilencesNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
// response payload
if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
/*
PostSilencesOKBody post silences o k body
swagger:model PostSilencesOKBody
*/
type PostSilencesOKBody struct {
// silence ID
SilenceID string `json:"silenceID,omitempty"`
}
// Validate validates this post silences o k body
func (o *PostSilencesOKBody) Validate(formats strfmt.Registry) error {
return nil
}
// ContextValidate validates this post silences o k body based on context it is used
func (o *PostSilencesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}
// MarshalBinary interface implementation
func (o *PostSilencesOKBody) MarshalBinary() ([]byte, error) {
if o == nil {
return nil, nil
}
return swag.WriteJSON(o)
}
// UnmarshalBinary interface implementation
func (o *PostSilencesOKBody) UnmarshalBinary(b []byte) error {
var res PostSilencesOKBody
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*o = res
return nil
}

View File

@@ -1,213 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package silence
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
)
// New creates a new silence API client.
func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService {
return &Client{transport: transport, formats: formats}
}
/*
Client for silence API
*/
type Client struct {
transport runtime.ClientTransport
formats strfmt.Registry
}
// ClientOption is the option for Client methods
type ClientOption func(*runtime.ClientOperation)
// ClientService is the interface for Client methods
type ClientService interface {
DeleteSilence(params *DeleteSilenceParams, opts ...ClientOption) (*DeleteSilenceOK, error)
GetSilence(params *GetSilenceParams, opts ...ClientOption) (*GetSilenceOK, error)
GetSilences(params *GetSilencesParams, opts ...ClientOption) (*GetSilencesOK, error)
PostSilences(params *PostSilencesParams, opts ...ClientOption) (*PostSilencesOK, error)
SetTransport(transport runtime.ClientTransport)
}
/*
DeleteSilence Delete a silence by its ID
*/
func (a *Client) DeleteSilence(params *DeleteSilenceParams, opts ...ClientOption) (*DeleteSilenceOK, error) {
// TODO: Validate the params before sending
if params == nil {
params = NewDeleteSilenceParams()
}
op := &runtime.ClientOperation{
ID: "deleteSilence",
Method: "DELETE",
PathPattern: "/silence/{silenceID}",
ProducesMediaTypes: []string{"application/json"},
ConsumesMediaTypes: []string{"application/json"},
Schemes: []string{"http"},
Params: params,
Reader: &DeleteSilenceReader{formats: a.formats},
Context: params.Context,
Client: params.HTTPClient,
}
for _, opt := range opts {
opt(op)
}
result, err := a.transport.Submit(op)
if err != nil {
return nil, err
}
success, ok := result.(*DeleteSilenceOK)
if ok {
return success, nil
}
// unexpected success response
// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue
msg := fmt.Sprintf("unexpected success response for deleteSilence: API contract not enforced by server. Client expected to get an error, but got: %T", result)
panic(msg)
}
/*
GetSilence Get a silence by its ID
*/
func (a *Client) GetSilence(params *GetSilenceParams, opts ...ClientOption) (*GetSilenceOK, error) {
// TODO: Validate the params before sending
if params == nil {
params = NewGetSilenceParams()
}
op := &runtime.ClientOperation{
ID: "getSilence",
Method: "GET",
PathPattern: "/silence/{silenceID}",
ProducesMediaTypes: []string{"application/json"},
ConsumesMediaTypes: []string{"application/json"},
Schemes: []string{"http"},
Params: params,
Reader: &GetSilenceReader{formats: a.formats},
Context: params.Context,
Client: params.HTTPClient,
}
for _, opt := range opts {
opt(op)
}
result, err := a.transport.Submit(op)
if err != nil {
return nil, err
}
success, ok := result.(*GetSilenceOK)
if ok {
return success, nil
}
// unexpected success response
// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue
msg := fmt.Sprintf("unexpected success response for getSilence: API contract not enforced by server. Client expected to get an error, but got: %T", result)
panic(msg)
}
/*
GetSilences Get a list of silences
*/
func (a *Client) GetSilences(params *GetSilencesParams, opts ...ClientOption) (*GetSilencesOK, error) {
// TODO: Validate the params before sending
if params == nil {
params = NewGetSilencesParams()
}
op := &runtime.ClientOperation{
ID: "getSilences",
Method: "GET",
PathPattern: "/silences",
ProducesMediaTypes: []string{"application/json"},
ConsumesMediaTypes: []string{"application/json"},
Schemes: []string{"http"},
Params: params,
Reader: &GetSilencesReader{formats: a.formats},
Context: params.Context,
Client: params.HTTPClient,
}
for _, opt := range opts {
opt(op)
}
result, err := a.transport.Submit(op)
if err != nil {
return nil, err
}
success, ok := result.(*GetSilencesOK)
if ok {
return success, nil
}
// unexpected success response
// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue
msg := fmt.Sprintf("unexpected success response for getSilences: API contract not enforced by server. Client expected to get an error, but got: %T", result)
panic(msg)
}
/*
PostSilences Post a new silence or update an existing one
*/
func (a *Client) PostSilences(params *PostSilencesParams, opts ...ClientOption) (*PostSilencesOK, error) {
// TODO: Validate the params before sending
if params == nil {
params = NewPostSilencesParams()
}
op := &runtime.ClientOperation{
ID: "postSilences",
Method: "POST",
PathPattern: "/silences",
ProducesMediaTypes: []string{"application/json"},
ConsumesMediaTypes: []string{"application/json"},
Schemes: []string{"http"},
Params: params,
Reader: &PostSilencesReader{formats: a.formats},
Context: params.Context,
Client: params.HTTPClient,
}
for _, opt := range opts {
opt(op)
}
result, err := a.transport.Submit(op)
if err != nil {
return nil, err
}
success, ok := result.(*PostSilencesOK)
if ok {
return success, nil
}
// unexpected success response
// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue
msg := fmt.Sprintf("unexpected success response for postSilences: API contract not enforced by server. Client expected to get an error, but got: %T", result)
panic(msg)
}
// SetTransport changes the transport on the client
func (a *Client) SetTransport(transport runtime.ClientTransport) {
a.transport = transport
}

View File

@@ -1,139 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
)
// Alert alert
//
// swagger:model alert
type Alert struct {
// generator URL
// Format: uri
GeneratorURL strfmt.URI `json:"generatorURL,omitempty"`
// labels
// Required: true
Labels LabelSet `json:"labels"`
}
// Validate validates this alert
func (m *Alert) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateGeneratorURL(formats); err != nil {
res = append(res, err)
}
if err := m.validateLabels(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *Alert) validateGeneratorURL(formats strfmt.Registry) error {
if swag.IsZero(m.GeneratorURL) { // not required
return nil
}
if err := validate.FormatOf("generatorURL", "body", "uri", m.GeneratorURL.String(), formats); err != nil {
return err
}
return nil
}
func (m *Alert) validateLabels(formats strfmt.Registry) error {
if err := validate.Required("labels", "body", m.Labels); err != nil {
return err
}
if m.Labels != nil {
if err := m.Labels.Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("labels")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("labels")
}
return err
}
}
return nil
}
// ContextValidate validate this alert based on the context it is used
func (m *Alert) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
var res []error
if err := m.contextValidateLabels(ctx, formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *Alert) contextValidateLabels(ctx context.Context, formats strfmt.Registry) error {
if err := m.Labels.ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("labels")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("labels")
}
return err
}
return nil
}
// MarshalBinary interface implementation
func (m *Alert) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *Alert) UnmarshalBinary(b []byte) error {
var res Alert
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,227 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"strconv"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
)
// AlertGroup alert group
//
// swagger:model alertGroup
type AlertGroup struct {
// alerts
// Required: true
Alerts []*GettableAlert `json:"alerts"`
// labels
// Required: true
Labels LabelSet `json:"labels"`
// receiver
// Required: true
Receiver *Receiver `json:"receiver"`
}
// Validate validates this alert group
func (m *AlertGroup) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateAlerts(formats); err != nil {
res = append(res, err)
}
if err := m.validateLabels(formats); err != nil {
res = append(res, err)
}
if err := m.validateReceiver(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *AlertGroup) validateAlerts(formats strfmt.Registry) error {
if err := validate.Required("alerts", "body", m.Alerts); err != nil {
return err
}
for i := 0; i < len(m.Alerts); i++ {
if swag.IsZero(m.Alerts[i]) { // not required
continue
}
if m.Alerts[i] != nil {
if err := m.Alerts[i].Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("alerts" + "." + strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("alerts" + "." + strconv.Itoa(i))
}
return err
}
}
}
return nil
}
func (m *AlertGroup) validateLabels(formats strfmt.Registry) error {
if err := validate.Required("labels", "body", m.Labels); err != nil {
return err
}
if m.Labels != nil {
if err := m.Labels.Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("labels")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("labels")
}
return err
}
}
return nil
}
func (m *AlertGroup) validateReceiver(formats strfmt.Registry) error {
if err := validate.Required("receiver", "body", m.Receiver); err != nil {
return err
}
if m.Receiver != nil {
if err := m.Receiver.Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("receiver")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("receiver")
}
return err
}
}
return nil
}
// ContextValidate validate this alert group based on the context it is used
func (m *AlertGroup) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
var res []error
if err := m.contextValidateAlerts(ctx, formats); err != nil {
res = append(res, err)
}
if err := m.contextValidateLabels(ctx, formats); err != nil {
res = append(res, err)
}
if err := m.contextValidateReceiver(ctx, formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *AlertGroup) contextValidateAlerts(ctx context.Context, formats strfmt.Registry) error {
for i := 0; i < len(m.Alerts); i++ {
if m.Alerts[i] != nil {
if err := m.Alerts[i].ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("alerts" + "." + strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("alerts" + "." + strconv.Itoa(i))
}
return err
}
}
}
return nil
}
func (m *AlertGroup) contextValidateLabels(ctx context.Context, formats strfmt.Registry) error {
if err := m.Labels.ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("labels")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("labels")
}
return err
}
return nil
}
func (m *AlertGroup) contextValidateReceiver(ctx context.Context, formats strfmt.Registry) error {
if m.Receiver != nil {
if err := m.Receiver.ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("receiver")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("receiver")
}
return err
}
}
return nil
}
// MarshalBinary interface implementation
func (m *AlertGroup) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *AlertGroup) UnmarshalBinary(b []byte) error {
var res AlertGroup
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,87 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"strconv"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// AlertGroups alert groups
//
// swagger:model alertGroups
type AlertGroups []*AlertGroup
// Validate validates this alert groups
func (m AlertGroups) Validate(formats strfmt.Registry) error {
var res []error
for i := 0; i < len(m); i++ {
if swag.IsZero(m[i]) { // not required
continue
}
if m[i] != nil {
if err := m[i].Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName(strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName(strconv.Itoa(i))
}
return err
}
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
// ContextValidate validate this alert groups based on the context it is used
func (m AlertGroups) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
var res []error
for i := 0; i < len(m); i++ {
if m[i] != nil {
if err := m[i].ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName(strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName(strconv.Itoa(i))
}
return err
}
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,158 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"encoding/json"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
)
// AlertStatus alert status
//
// swagger:model alertStatus
type AlertStatus struct {
// inhibited by
// Required: true
InhibitedBy []string `json:"inhibitedBy"`
// silenced by
// Required: true
SilencedBy []string `json:"silencedBy"`
// state
// Required: true
// Enum: [unprocessed active suppressed]
State *string `json:"state"`
}
// Validate validates this alert status
func (m *AlertStatus) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateInhibitedBy(formats); err != nil {
res = append(res, err)
}
if err := m.validateSilencedBy(formats); err != nil {
res = append(res, err)
}
if err := m.validateState(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *AlertStatus) validateInhibitedBy(formats strfmt.Registry) error {
if err := validate.Required("inhibitedBy", "body", m.InhibitedBy); err != nil {
return err
}
return nil
}
func (m *AlertStatus) validateSilencedBy(formats strfmt.Registry) error {
if err := validate.Required("silencedBy", "body", m.SilencedBy); err != nil {
return err
}
return nil
}
var alertStatusTypeStatePropEnum []interface{}
func init() {
var res []string
if err := json.Unmarshal([]byte(`["unprocessed","active","suppressed"]`), &res); err != nil {
panic(err)
}
for _, v := range res {
alertStatusTypeStatePropEnum = append(alertStatusTypeStatePropEnum, v)
}
}
const (
// AlertStatusStateUnprocessed captures enum value "unprocessed"
AlertStatusStateUnprocessed string = "unprocessed"
// AlertStatusStateActive captures enum value "active"
AlertStatusStateActive string = "active"
// AlertStatusStateSuppressed captures enum value "suppressed"
AlertStatusStateSuppressed string = "suppressed"
)
// prop value enum
func (m *AlertStatus) validateStateEnum(path, location string, value string) error {
if err := validate.EnumCase(path, location, value, alertStatusTypeStatePropEnum, true); err != nil {
return err
}
return nil
}
func (m *AlertStatus) validateState(formats strfmt.Registry) error {
if err := validate.Required("state", "body", m.State); err != nil {
return err
}
// value enum
if err := m.validateStateEnum("state", "body", *m.State); err != nil {
return err
}
return nil
}
// ContextValidate validates this alert status based on context it is used
func (m *AlertStatus) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}
// MarshalBinary interface implementation
func (m *AlertStatus) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *AlertStatus) UnmarshalBinary(b []byte) error {
var res AlertStatus
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,85 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
)
// AlertmanagerConfig alertmanager config
//
// swagger:model alertmanagerConfig
type AlertmanagerConfig struct {
// original
// Required: true
Original *string `json:"original"`
}
// Validate validates this alertmanager config
func (m *AlertmanagerConfig) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateOriginal(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *AlertmanagerConfig) validateOriginal(formats strfmt.Registry) error {
if err := validate.Required("original", "body", m.Original); err != nil {
return err
}
return nil
}
// ContextValidate validates this alertmanager config based on context it is used
func (m *AlertmanagerConfig) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}
// MarshalBinary interface implementation
func (m *AlertmanagerConfig) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *AlertmanagerConfig) UnmarshalBinary(b []byte) error {
var res AlertmanagerConfig
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,239 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
)
// AlertmanagerStatus alertmanager status
//
// swagger:model alertmanagerStatus
type AlertmanagerStatus struct {
// cluster
// Required: true
Cluster *ClusterStatus `json:"cluster"`
// config
// Required: true
Config *AlertmanagerConfig `json:"config"`
// uptime
// Required: true
// Format: date-time
Uptime *strfmt.DateTime `json:"uptime"`
// version info
// Required: true
VersionInfo *VersionInfo `json:"versionInfo"`
}
// Validate validates this alertmanager status
func (m *AlertmanagerStatus) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateCluster(formats); err != nil {
res = append(res, err)
}
if err := m.validateConfig(formats); err != nil {
res = append(res, err)
}
if err := m.validateUptime(formats); err != nil {
res = append(res, err)
}
if err := m.validateVersionInfo(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *AlertmanagerStatus) validateCluster(formats strfmt.Registry) error {
if err := validate.Required("cluster", "body", m.Cluster); err != nil {
return err
}
if m.Cluster != nil {
if err := m.Cluster.Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("cluster")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("cluster")
}
return err
}
}
return nil
}
func (m *AlertmanagerStatus) validateConfig(formats strfmt.Registry) error {
if err := validate.Required("config", "body", m.Config); err != nil {
return err
}
if m.Config != nil {
if err := m.Config.Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("config")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("config")
}
return err
}
}
return nil
}
func (m *AlertmanagerStatus) validateUptime(formats strfmt.Registry) error {
if err := validate.Required("uptime", "body", m.Uptime); err != nil {
return err
}
if err := validate.FormatOf("uptime", "body", "date-time", m.Uptime.String(), formats); err != nil {
return err
}
return nil
}
func (m *AlertmanagerStatus) validateVersionInfo(formats strfmt.Registry) error {
if err := validate.Required("versionInfo", "body", m.VersionInfo); err != nil {
return err
}
if m.VersionInfo != nil {
if err := m.VersionInfo.Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("versionInfo")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("versionInfo")
}
return err
}
}
return nil
}
// ContextValidate validate this alertmanager status based on the context it is used
func (m *AlertmanagerStatus) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
var res []error
if err := m.contextValidateCluster(ctx, formats); err != nil {
res = append(res, err)
}
if err := m.contextValidateConfig(ctx, formats); err != nil {
res = append(res, err)
}
if err := m.contextValidateVersionInfo(ctx, formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *AlertmanagerStatus) contextValidateCluster(ctx context.Context, formats strfmt.Registry) error {
if m.Cluster != nil {
if err := m.Cluster.ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("cluster")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("cluster")
}
return err
}
}
return nil
}
func (m *AlertmanagerStatus) contextValidateConfig(ctx context.Context, formats strfmt.Registry) error {
if m.Config != nil {
if err := m.Config.ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("config")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("config")
}
return err
}
}
return nil
}
func (m *AlertmanagerStatus) contextValidateVersionInfo(ctx context.Context, formats strfmt.Registry) error {
if m.VersionInfo != nil {
if err := m.VersionInfo.ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("versionInfo")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("versionInfo")
}
return err
}
}
return nil
}
// MarshalBinary interface implementation
func (m *AlertmanagerStatus) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *AlertmanagerStatus) UnmarshalBinary(b []byte) error {
var res AlertmanagerStatus
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,190 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"encoding/json"
"strconv"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
)
// ClusterStatus cluster status
//
// swagger:model clusterStatus
type ClusterStatus struct {
// name
Name string `json:"name,omitempty"`
// peers
Peers []*PeerStatus `json:"peers"`
// status
// Required: true
// Enum: [ready settling disabled]
Status *string `json:"status"`
}
// Validate validates this cluster status
func (m *ClusterStatus) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validatePeers(formats); err != nil {
res = append(res, err)
}
if err := m.validateStatus(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *ClusterStatus) validatePeers(formats strfmt.Registry) error {
if swag.IsZero(m.Peers) { // not required
return nil
}
for i := 0; i < len(m.Peers); i++ {
if swag.IsZero(m.Peers[i]) { // not required
continue
}
if m.Peers[i] != nil {
if err := m.Peers[i].Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("peers" + "." + strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("peers" + "." + strconv.Itoa(i))
}
return err
}
}
}
return nil
}
var clusterStatusTypeStatusPropEnum []interface{}
func init() {
var res []string
if err := json.Unmarshal([]byte(`["ready","settling","disabled"]`), &res); err != nil {
panic(err)
}
for _, v := range res {
clusterStatusTypeStatusPropEnum = append(clusterStatusTypeStatusPropEnum, v)
}
}
const (
// ClusterStatusStatusReady captures enum value "ready"
ClusterStatusStatusReady string = "ready"
// ClusterStatusStatusSettling captures enum value "settling"
ClusterStatusStatusSettling string = "settling"
// ClusterStatusStatusDisabled captures enum value "disabled"
ClusterStatusStatusDisabled string = "disabled"
)
// prop value enum
func (m *ClusterStatus) validateStatusEnum(path, location string, value string) error {
if err := validate.EnumCase(path, location, value, clusterStatusTypeStatusPropEnum, true); err != nil {
return err
}
return nil
}
func (m *ClusterStatus) validateStatus(formats strfmt.Registry) error {
if err := validate.Required("status", "body", m.Status); err != nil {
return err
}
// value enum
if err := m.validateStatusEnum("status", "body", *m.Status); err != nil {
return err
}
return nil
}
// ContextValidate validate this cluster status based on the context it is used
func (m *ClusterStatus) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
var res []error
if err := m.contextValidatePeers(ctx, formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *ClusterStatus) contextValidatePeers(ctx context.Context, formats strfmt.Registry) error {
for i := 0; i < len(m.Peers); i++ {
if m.Peers[i] != nil {
if err := m.Peers[i].ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("peers" + "." + strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("peers" + "." + strconv.Itoa(i))
}
return err
}
}
}
return nil
}
// MarshalBinary interface implementation
func (m *ClusterStatus) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *ClusterStatus) UnmarshalBinary(b []byte) error {
var res ClusterStatus
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,416 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"strconv"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
)
// GettableAlert gettable alert
//
// swagger:model gettableAlert
type GettableAlert struct {
// annotations
// Required: true
Annotations LabelSet `json:"annotations"`
// ends at
// Required: true
// Format: date-time
EndsAt *strfmt.DateTime `json:"endsAt"`
// fingerprint
// Required: true
Fingerprint *string `json:"fingerprint"`
// receivers
// Required: true
Receivers []*Receiver `json:"receivers"`
// starts at
// Required: true
// Format: date-time
StartsAt *strfmt.DateTime `json:"startsAt"`
// status
// Required: true
Status *AlertStatus `json:"status"`
// updated at
// Required: true
// Format: date-time
UpdatedAt *strfmt.DateTime `json:"updatedAt"`
Alert
}
// UnmarshalJSON unmarshals this object from a JSON structure
func (m *GettableAlert) UnmarshalJSON(raw []byte) error {
// AO0
var dataAO0 struct {
Annotations LabelSet `json:"annotations"`
EndsAt *strfmt.DateTime `json:"endsAt"`
Fingerprint *string `json:"fingerprint"`
Receivers []*Receiver `json:"receivers"`
StartsAt *strfmt.DateTime `json:"startsAt"`
Status *AlertStatus `json:"status"`
UpdatedAt *strfmt.DateTime `json:"updatedAt"`
}
if err := swag.ReadJSON(raw, &dataAO0); err != nil {
return err
}
m.Annotations = dataAO0.Annotations
m.EndsAt = dataAO0.EndsAt
m.Fingerprint = dataAO0.Fingerprint
m.Receivers = dataAO0.Receivers
m.StartsAt = dataAO0.StartsAt
m.Status = dataAO0.Status
m.UpdatedAt = dataAO0.UpdatedAt
// AO1
var aO1 Alert
if err := swag.ReadJSON(raw, &aO1); err != nil {
return err
}
m.Alert = aO1
return nil
}
// MarshalJSON marshals this object to a JSON structure
func (m GettableAlert) MarshalJSON() ([]byte, error) {
_parts := make([][]byte, 0, 2)
var dataAO0 struct {
Annotations LabelSet `json:"annotations"`
EndsAt *strfmt.DateTime `json:"endsAt"`
Fingerprint *string `json:"fingerprint"`
Receivers []*Receiver `json:"receivers"`
StartsAt *strfmt.DateTime `json:"startsAt"`
Status *AlertStatus `json:"status"`
UpdatedAt *strfmt.DateTime `json:"updatedAt"`
}
dataAO0.Annotations = m.Annotations
dataAO0.EndsAt = m.EndsAt
dataAO0.Fingerprint = m.Fingerprint
dataAO0.Receivers = m.Receivers
dataAO0.StartsAt = m.StartsAt
dataAO0.Status = m.Status
dataAO0.UpdatedAt = m.UpdatedAt
jsonDataAO0, errAO0 := swag.WriteJSON(dataAO0)
if errAO0 != nil {
return nil, errAO0
}
_parts = append(_parts, jsonDataAO0)
aO1, err := swag.WriteJSON(m.Alert)
if err != nil {
return nil, err
}
_parts = append(_parts, aO1)
return swag.ConcatJSON(_parts...), nil
}
// Validate validates this gettable alert
func (m *GettableAlert) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateAnnotations(formats); err != nil {
res = append(res, err)
}
if err := m.validateEndsAt(formats); err != nil {
res = append(res, err)
}
if err := m.validateFingerprint(formats); err != nil {
res = append(res, err)
}
if err := m.validateReceivers(formats); err != nil {
res = append(res, err)
}
if err := m.validateStartsAt(formats); err != nil {
res = append(res, err)
}
if err := m.validateStatus(formats); err != nil {
res = append(res, err)
}
if err := m.validateUpdatedAt(formats); err != nil {
res = append(res, err)
}
// validation for a type composition with Alert
if err := m.Alert.Validate(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *GettableAlert) validateAnnotations(formats strfmt.Registry) error {
if err := validate.Required("annotations", "body", m.Annotations); err != nil {
return err
}
if m.Annotations != nil {
if err := m.Annotations.Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("annotations")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("annotations")
}
return err
}
}
return nil
}
func (m *GettableAlert) validateEndsAt(formats strfmt.Registry) error {
if err := validate.Required("endsAt", "body", m.EndsAt); err != nil {
return err
}
if err := validate.FormatOf("endsAt", "body", "date-time", m.EndsAt.String(), formats); err != nil {
return err
}
return nil
}
func (m *GettableAlert) validateFingerprint(formats strfmt.Registry) error {
if err := validate.Required("fingerprint", "body", m.Fingerprint); err != nil {
return err
}
return nil
}
func (m *GettableAlert) validateReceivers(formats strfmt.Registry) error {
if err := validate.Required("receivers", "body", m.Receivers); err != nil {
return err
}
for i := 0; i < len(m.Receivers); i++ {
if swag.IsZero(m.Receivers[i]) { // not required
continue
}
if m.Receivers[i] != nil {
if err := m.Receivers[i].Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("receivers" + "." + strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("receivers" + "." + strconv.Itoa(i))
}
return err
}
}
}
return nil
}
func (m *GettableAlert) validateStartsAt(formats strfmt.Registry) error {
if err := validate.Required("startsAt", "body", m.StartsAt); err != nil {
return err
}
if err := validate.FormatOf("startsAt", "body", "date-time", m.StartsAt.String(), formats); err != nil {
return err
}
return nil
}
func (m *GettableAlert) validateStatus(formats strfmt.Registry) error {
if err := validate.Required("status", "body", m.Status); err != nil {
return err
}
if m.Status != nil {
if err := m.Status.Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("status")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("status")
}
return err
}
}
return nil
}
func (m *GettableAlert) validateUpdatedAt(formats strfmt.Registry) error {
if err := validate.Required("updatedAt", "body", m.UpdatedAt); err != nil {
return err
}
if err := validate.FormatOf("updatedAt", "body", "date-time", m.UpdatedAt.String(), formats); err != nil {
return err
}
return nil
}
// ContextValidate validate this gettable alert based on the context it is used
func (m *GettableAlert) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
var res []error
if err := m.contextValidateAnnotations(ctx, formats); err != nil {
res = append(res, err)
}
if err := m.contextValidateReceivers(ctx, formats); err != nil {
res = append(res, err)
}
if err := m.contextValidateStatus(ctx, formats); err != nil {
res = append(res, err)
}
// validation for a type composition with Alert
if err := m.Alert.ContextValidate(ctx, formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *GettableAlert) contextValidateAnnotations(ctx context.Context, formats strfmt.Registry) error {
if err := m.Annotations.ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("annotations")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("annotations")
}
return err
}
return nil
}
func (m *GettableAlert) contextValidateReceivers(ctx context.Context, formats strfmt.Registry) error {
for i := 0; i < len(m.Receivers); i++ {
if m.Receivers[i] != nil {
if err := m.Receivers[i].ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("receivers" + "." + strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("receivers" + "." + strconv.Itoa(i))
}
return err
}
}
}
return nil
}
func (m *GettableAlert) contextValidateStatus(ctx context.Context, formats strfmt.Registry) error {
if m.Status != nil {
if err := m.Status.ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("status")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("status")
}
return err
}
}
return nil
}
// MarshalBinary interface implementation
func (m *GettableAlert) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *GettableAlert) UnmarshalBinary(b []byte) error {
var res GettableAlert
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,87 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"strconv"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// GettableAlerts gettable alerts
//
// swagger:model gettableAlerts
type GettableAlerts []*GettableAlert
// Validate validates this gettable alerts
func (m GettableAlerts) Validate(formats strfmt.Registry) error {
var res []error
for i := 0; i < len(m); i++ {
if swag.IsZero(m[i]) { // not required
continue
}
if m[i] != nil {
if err := m[i].Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName(strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName(strconv.Itoa(i))
}
return err
}
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
// ContextValidate validate this gettable alerts based on the context it is used
func (m GettableAlerts) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
var res []error
for i := 0; i < len(m); i++ {
if m[i] != nil {
if err := m[i].ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName(strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName(strconv.Itoa(i))
}
return err
}
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,234 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
)
// GettableSilence gettable silence
//
// swagger:model gettableSilence
type GettableSilence struct {
// id
// Required: true
ID *string `json:"id"`
// status
// Required: true
Status *SilenceStatus `json:"status"`
// updated at
// Required: true
// Format: date-time
UpdatedAt *strfmt.DateTime `json:"updatedAt"`
Silence
}
// UnmarshalJSON unmarshals this object from a JSON structure
func (m *GettableSilence) UnmarshalJSON(raw []byte) error {
// AO0
var dataAO0 struct {
ID *string `json:"id"`
Status *SilenceStatus `json:"status"`
UpdatedAt *strfmt.DateTime `json:"updatedAt"`
}
if err := swag.ReadJSON(raw, &dataAO0); err != nil {
return err
}
m.ID = dataAO0.ID
m.Status = dataAO0.Status
m.UpdatedAt = dataAO0.UpdatedAt
// AO1
var aO1 Silence
if err := swag.ReadJSON(raw, &aO1); err != nil {
return err
}
m.Silence = aO1
return nil
}
// MarshalJSON marshals this object to a JSON structure
func (m GettableSilence) MarshalJSON() ([]byte, error) {
_parts := make([][]byte, 0, 2)
var dataAO0 struct {
ID *string `json:"id"`
Status *SilenceStatus `json:"status"`
UpdatedAt *strfmt.DateTime `json:"updatedAt"`
}
dataAO0.ID = m.ID
dataAO0.Status = m.Status
dataAO0.UpdatedAt = m.UpdatedAt
jsonDataAO0, errAO0 := swag.WriteJSON(dataAO0)
if errAO0 != nil {
return nil, errAO0
}
_parts = append(_parts, jsonDataAO0)
aO1, err := swag.WriteJSON(m.Silence)
if err != nil {
return nil, err
}
_parts = append(_parts, aO1)
return swag.ConcatJSON(_parts...), nil
}
// Validate validates this gettable silence
func (m *GettableSilence) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateID(formats); err != nil {
res = append(res, err)
}
if err := m.validateStatus(formats); err != nil {
res = append(res, err)
}
if err := m.validateUpdatedAt(formats); err != nil {
res = append(res, err)
}
// validation for a type composition with Silence
if err := m.Silence.Validate(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *GettableSilence) validateID(formats strfmt.Registry) error {
if err := validate.Required("id", "body", m.ID); err != nil {
return err
}
return nil
}
func (m *GettableSilence) validateStatus(formats strfmt.Registry) error {
if err := validate.Required("status", "body", m.Status); err != nil {
return err
}
if m.Status != nil {
if err := m.Status.Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("status")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("status")
}
return err
}
}
return nil
}
func (m *GettableSilence) validateUpdatedAt(formats strfmt.Registry) error {
if err := validate.Required("updatedAt", "body", m.UpdatedAt); err != nil {
return err
}
if err := validate.FormatOf("updatedAt", "body", "date-time", m.UpdatedAt.String(), formats); err != nil {
return err
}
return nil
}
// ContextValidate validate this gettable silence based on the context it is used
func (m *GettableSilence) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
var res []error
if err := m.contextValidateStatus(ctx, formats); err != nil {
res = append(res, err)
}
// validation for a type composition with Silence
if err := m.Silence.ContextValidate(ctx, formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *GettableSilence) contextValidateStatus(ctx context.Context, formats strfmt.Registry) error {
if m.Status != nil {
if err := m.Status.ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("status")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("status")
}
return err
}
}
return nil
}
// MarshalBinary interface implementation
func (m *GettableSilence) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *GettableSilence) UnmarshalBinary(b []byte) error {
var res GettableSilence
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,87 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"strconv"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// GettableSilences gettable silences
//
// swagger:model gettableSilences
type GettableSilences []*GettableSilence
// Validate validates this gettable silences
func (m GettableSilences) Validate(formats strfmt.Registry) error {
var res []error
for i := 0; i < len(m); i++ {
if swag.IsZero(m[i]) { // not required
continue
}
if m[i] != nil {
if err := m[i].Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName(strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName(strconv.Itoa(i))
}
return err
}
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
// ContextValidate validate this gettable silences based on the context it is used
func (m GettableSilences) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
var res []error
for i := 0; i < len(m); i++ {
if m[i] != nil {
if err := m[i].ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName(strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName(strconv.Itoa(i))
}
return err
}
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,41 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/strfmt"
)
// LabelSet label set
//
// swagger:model labelSet
type LabelSet map[string]string
// Validate validates this label set
func (m LabelSet) Validate(formats strfmt.Registry) error {
return nil
}
// ContextValidate validates this label set based on context it is used
func (m LabelSet) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}

View File

@@ -1,122 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
)
// Matcher matcher
//
// swagger:model matcher
type Matcher struct {
// is equal
IsEqual *bool `json:"isEqual,omitempty"`
// is regex
// Required: true
IsRegex *bool `json:"isRegex"`
// name
// Required: true
Name *string `json:"name"`
// value
// Required: true
Value *string `json:"value"`
}
// Validate validates this matcher
func (m *Matcher) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateIsRegex(formats); err != nil {
res = append(res, err)
}
if err := m.validateName(formats); err != nil {
res = append(res, err)
}
if err := m.validateValue(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *Matcher) validateIsRegex(formats strfmt.Registry) error {
if err := validate.Required("isRegex", "body", m.IsRegex); err != nil {
return err
}
return nil
}
func (m *Matcher) validateName(formats strfmt.Registry) error {
if err := validate.Required("name", "body", m.Name); err != nil {
return err
}
return nil
}
func (m *Matcher) validateValue(formats strfmt.Registry) error {
if err := validate.Required("value", "body", m.Value); err != nil {
return err
}
return nil
}
// ContextValidate validates this matcher based on context it is used
func (m *Matcher) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}
// MarshalBinary interface implementation
func (m *Matcher) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *Matcher) UnmarshalBinary(b []byte) error {
var res Matcher
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,94 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"strconv"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
)
// Matchers matchers
//
// swagger:model matchers
type Matchers []*Matcher
// Validate validates this matchers
func (m Matchers) Validate(formats strfmt.Registry) error {
var res []error
iMatchersSize := int64(len(m))
if err := validate.MinItems("", "body", iMatchersSize, 1); err != nil {
return err
}
for i := 0; i < len(m); i++ {
if swag.IsZero(m[i]) { // not required
continue
}
if m[i] != nil {
if err := m[i].Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName(strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName(strconv.Itoa(i))
}
return err
}
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
// ContextValidate validate this matchers based on the context it is used
func (m Matchers) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
var res []error
for i := 0; i < len(m); i++ {
if m[i] != nil {
if err := m[i].ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName(strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName(strconv.Itoa(i))
}
return err
}
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,102 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
)
// PeerStatus peer status
//
// swagger:model peerStatus
type PeerStatus struct {
// address
// Required: true
Address *string `json:"address"`
// name
// Required: true
Name *string `json:"name"`
}
// Validate validates this peer status
func (m *PeerStatus) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateAddress(formats); err != nil {
res = append(res, err)
}
if err := m.validateName(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *PeerStatus) validateAddress(formats strfmt.Registry) error {
if err := validate.Required("address", "body", m.Address); err != nil {
return err
}
return nil
}
func (m *PeerStatus) validateName(formats strfmt.Registry) error {
if err := validate.Required("name", "body", m.Name); err != nil {
return err
}
return nil
}
// ContextValidate validates this peer status based on context it is used
func (m *PeerStatus) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}
// MarshalBinary interface implementation
func (m *PeerStatus) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *PeerStatus) UnmarshalBinary(b []byte) error {
var res PeerStatus
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,234 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
)
// PostableAlert postable alert
//
// swagger:model postableAlert
type PostableAlert struct {
// annotations
Annotations LabelSet `json:"annotations,omitempty"`
// ends at
// Format: date-time
EndsAt strfmt.DateTime `json:"endsAt,omitempty"`
// starts at
// Format: date-time
StartsAt strfmt.DateTime `json:"startsAt,omitempty"`
Alert
}
// UnmarshalJSON unmarshals this object from a JSON structure
func (m *PostableAlert) UnmarshalJSON(raw []byte) error {
// AO0
var dataAO0 struct {
Annotations LabelSet `json:"annotations,omitempty"`
EndsAt strfmt.DateTime `json:"endsAt,omitempty"`
StartsAt strfmt.DateTime `json:"startsAt,omitempty"`
}
if err := swag.ReadJSON(raw, &dataAO0); err != nil {
return err
}
m.Annotations = dataAO0.Annotations
m.EndsAt = dataAO0.EndsAt
m.StartsAt = dataAO0.StartsAt
// AO1
var aO1 Alert
if err := swag.ReadJSON(raw, &aO1); err != nil {
return err
}
m.Alert = aO1
return nil
}
// MarshalJSON marshals this object to a JSON structure
func (m PostableAlert) MarshalJSON() ([]byte, error) {
_parts := make([][]byte, 0, 2)
var dataAO0 struct {
Annotations LabelSet `json:"annotations,omitempty"`
EndsAt strfmt.DateTime `json:"endsAt,omitempty"`
StartsAt strfmt.DateTime `json:"startsAt,omitempty"`
}
dataAO0.Annotations = m.Annotations
dataAO0.EndsAt = m.EndsAt
dataAO0.StartsAt = m.StartsAt
jsonDataAO0, errAO0 := swag.WriteJSON(dataAO0)
if errAO0 != nil {
return nil, errAO0
}
_parts = append(_parts, jsonDataAO0)
aO1, err := swag.WriteJSON(m.Alert)
if err != nil {
return nil, err
}
_parts = append(_parts, aO1)
return swag.ConcatJSON(_parts...), nil
}
// Validate validates this postable alert
func (m *PostableAlert) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateAnnotations(formats); err != nil {
res = append(res, err)
}
if err := m.validateEndsAt(formats); err != nil {
res = append(res, err)
}
if err := m.validateStartsAt(formats); err != nil {
res = append(res, err)
}
// validation for a type composition with Alert
if err := m.Alert.Validate(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *PostableAlert) validateAnnotations(formats strfmt.Registry) error {
if swag.IsZero(m.Annotations) { // not required
return nil
}
if m.Annotations != nil {
if err := m.Annotations.Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("annotations")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("annotations")
}
return err
}
}
return nil
}
func (m *PostableAlert) validateEndsAt(formats strfmt.Registry) error {
if swag.IsZero(m.EndsAt) { // not required
return nil
}
if err := validate.FormatOf("endsAt", "body", "date-time", m.EndsAt.String(), formats); err != nil {
return err
}
return nil
}
func (m *PostableAlert) validateStartsAt(formats strfmt.Registry) error {
if swag.IsZero(m.StartsAt) { // not required
return nil
}
if err := validate.FormatOf("startsAt", "body", "date-time", m.StartsAt.String(), formats); err != nil {
return err
}
return nil
}
// ContextValidate validate this postable alert based on the context it is used
func (m *PostableAlert) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
var res []error
if err := m.contextValidateAnnotations(ctx, formats); err != nil {
res = append(res, err)
}
// validation for a type composition with Alert
if err := m.Alert.ContextValidate(ctx, formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *PostableAlert) contextValidateAnnotations(ctx context.Context, formats strfmt.Registry) error {
if err := m.Annotations.ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("annotations")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("annotations")
}
return err
}
return nil
}
// MarshalBinary interface implementation
func (m *PostableAlert) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *PostableAlert) UnmarshalBinary(b []byte) error {
var res PostableAlert
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,87 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"strconv"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// PostableAlerts postable alerts
//
// swagger:model postableAlerts
type PostableAlerts []*PostableAlert
// Validate validates this postable alerts
func (m PostableAlerts) Validate(formats strfmt.Registry) error {
var res []error
for i := 0; i < len(m); i++ {
if swag.IsZero(m[i]) { // not required
continue
}
if m[i] != nil {
if err := m[i].Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName(strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName(strconv.Itoa(i))
}
return err
}
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
// ContextValidate validate this postable alerts based on the context it is used
func (m PostableAlerts) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
var res []error
for i := 0; i < len(m); i++ {
if m[i] != nil {
if err := m[i].ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName(strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName(strconv.Itoa(i))
}
return err
}
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@@ -1,133 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// PostableSilence postable silence
//
// swagger:model postableSilence
type PostableSilence struct {
// id
ID string `json:"id,omitempty"`
Silence
}
// UnmarshalJSON unmarshals this object from a JSON structure
func (m *PostableSilence) UnmarshalJSON(raw []byte) error {
// AO0
var dataAO0 struct {
ID string `json:"id,omitempty"`
}
if err := swag.ReadJSON(raw, &dataAO0); err != nil {
return err
}
m.ID = dataAO0.ID
// AO1
var aO1 Silence
if err := swag.ReadJSON(raw, &aO1); err != nil {
return err
}
m.Silence = aO1
return nil
}
// MarshalJSON marshals this object to a JSON structure
func (m PostableSilence) MarshalJSON() ([]byte, error) {
_parts := make([][]byte, 0, 2)
var dataAO0 struct {
ID string `json:"id,omitempty"`
}
dataAO0.ID = m.ID
jsonDataAO0, errAO0 := swag.WriteJSON(dataAO0)
if errAO0 != nil {
return nil, errAO0
}
_parts = append(_parts, jsonDataAO0)
aO1, err := swag.WriteJSON(m.Silence)
if err != nil {
return nil, err
}
_parts = append(_parts, aO1)
return swag.ConcatJSON(_parts...), nil
}
// Validate validates this postable silence
func (m *PostableSilence) Validate(formats strfmt.Registry) error {
var res []error
// validation for a type composition with Silence
if err := m.Silence.Validate(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
// ContextValidate validate this postable silence based on the context it is used
func (m *PostableSilence) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
var res []error
// validation for a type composition with Silence
if err := m.Silence.ContextValidate(ctx, formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
// MarshalBinary interface implementation
func (m *PostableSilence) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *PostableSilence) UnmarshalBinary(b []byte) error {
var res PostableSilence
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,85 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
)
// Receiver receiver
//
// swagger:model receiver
type Receiver struct {
// name
// Required: true
Name *string `json:"name"`
}
// Validate validates this receiver
func (m *Receiver) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateName(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *Receiver) validateName(formats strfmt.Registry) error {
if err := validate.Required("name", "body", m.Name); err != nil {
return err
}
return nil
}
// ContextValidate validates this receiver based on context it is used
func (m *Receiver) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}
// MarshalBinary interface implementation
func (m *Receiver) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *Receiver) UnmarshalBinary(b []byte) error {
var res Receiver
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,195 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
)
// Silence silence
//
// swagger:model silence
type Silence struct {
// comment
// Required: true
Comment *string `json:"comment"`
// created by
// Required: true
CreatedBy *string `json:"createdBy"`
// ends at
// Required: true
// Format: date-time
EndsAt *strfmt.DateTime `json:"endsAt"`
// matchers
// Required: true
Matchers Matchers `json:"matchers"`
// starts at
// Required: true
// Format: date-time
StartsAt *strfmt.DateTime `json:"startsAt"`
}
// Validate validates this silence
func (m *Silence) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateComment(formats); err != nil {
res = append(res, err)
}
if err := m.validateCreatedBy(formats); err != nil {
res = append(res, err)
}
if err := m.validateEndsAt(formats); err != nil {
res = append(res, err)
}
if err := m.validateMatchers(formats); err != nil {
res = append(res, err)
}
if err := m.validateStartsAt(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *Silence) validateComment(formats strfmt.Registry) error {
if err := validate.Required("comment", "body", m.Comment); err != nil {
return err
}
return nil
}
func (m *Silence) validateCreatedBy(formats strfmt.Registry) error {
if err := validate.Required("createdBy", "body", m.CreatedBy); err != nil {
return err
}
return nil
}
func (m *Silence) validateEndsAt(formats strfmt.Registry) error {
if err := validate.Required("endsAt", "body", m.EndsAt); err != nil {
return err
}
if err := validate.FormatOf("endsAt", "body", "date-time", m.EndsAt.String(), formats); err != nil {
return err
}
return nil
}
func (m *Silence) validateMatchers(formats strfmt.Registry) error {
if err := validate.Required("matchers", "body", m.Matchers); err != nil {
return err
}
if err := m.Matchers.Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("matchers")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("matchers")
}
return err
}
return nil
}
func (m *Silence) validateStartsAt(formats strfmt.Registry) error {
if err := validate.Required("startsAt", "body", m.StartsAt); err != nil {
return err
}
if err := validate.FormatOf("startsAt", "body", "date-time", m.StartsAt.String(), formats); err != nil {
return err
}
return nil
}
// ContextValidate validate this silence based on the context it is used
func (m *Silence) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
var res []error
if err := m.contextValidateMatchers(ctx, formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *Silence) contextValidateMatchers(ctx context.Context, formats strfmt.Registry) error {
if err := m.Matchers.ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("matchers")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("matchers")
}
return err
}
return nil
}
// MarshalBinary interface implementation
func (m *Silence) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *Silence) UnmarshalBinary(b []byte) error {
var res Silence
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,124 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"encoding/json"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
)
// SilenceStatus silence status
//
// swagger:model silenceStatus
type SilenceStatus struct {
// state
// Required: true
// Enum: [expired active pending]
State *string `json:"state"`
}
// Validate validates this silence status
func (m *SilenceStatus) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateState(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
var silenceStatusTypeStatePropEnum []interface{}
func init() {
var res []string
if err := json.Unmarshal([]byte(`["expired","active","pending"]`), &res); err != nil {
panic(err)
}
for _, v := range res {
silenceStatusTypeStatePropEnum = append(silenceStatusTypeStatePropEnum, v)
}
}
const (
// SilenceStatusStateExpired captures enum value "expired"
SilenceStatusStateExpired string = "expired"
// SilenceStatusStateActive captures enum value "active"
SilenceStatusStateActive string = "active"
// SilenceStatusStatePending captures enum value "pending"
SilenceStatusStatePending string = "pending"
)
// prop value enum
func (m *SilenceStatus) validateStateEnum(path, location string, value string) error {
if err := validate.EnumCase(path, location, value, silenceStatusTypeStatePropEnum, true); err != nil {
return err
}
return nil
}
func (m *SilenceStatus) validateState(formats strfmt.Registry) error {
if err := validate.Required("state", "body", m.State); err != nil {
return err
}
// value enum
if err := m.validateStateEnum("state", "body", *m.State); err != nil {
return err
}
return nil
}
// ContextValidate validates this silence status based on context it is used
func (m *SilenceStatus) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}
// MarshalBinary interface implementation
func (m *SilenceStatus) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *SilenceStatus) UnmarshalBinary(b []byte) error {
var res SilenceStatus
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,170 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
// Copyright 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.
//
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
)
// VersionInfo version info
//
// swagger:model versionInfo
type VersionInfo struct {
// branch
// Required: true
Branch *string `json:"branch"`
// build date
// Required: true
BuildDate *string `json:"buildDate"`
// build user
// Required: true
BuildUser *string `json:"buildUser"`
// go version
// Required: true
GoVersion *string `json:"goVersion"`
// revision
// Required: true
Revision *string `json:"revision"`
// version
// Required: true
Version *string `json:"version"`
}
// Validate validates this version info
func (m *VersionInfo) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateBranch(formats); err != nil {
res = append(res, err)
}
if err := m.validateBuildDate(formats); err != nil {
res = append(res, err)
}
if err := m.validateBuildUser(formats); err != nil {
res = append(res, err)
}
if err := m.validateGoVersion(formats); err != nil {
res = append(res, err)
}
if err := m.validateRevision(formats); err != nil {
res = append(res, err)
}
if err := m.validateVersion(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *VersionInfo) validateBranch(formats strfmt.Registry) error {
if err := validate.Required("branch", "body", m.Branch); err != nil {
return err
}
return nil
}
func (m *VersionInfo) validateBuildDate(formats strfmt.Registry) error {
if err := validate.Required("buildDate", "body", m.BuildDate); err != nil {
return err
}
return nil
}
func (m *VersionInfo) validateBuildUser(formats strfmt.Registry) error {
if err := validate.Required("buildUser", "body", m.BuildUser); err != nil {
return err
}
return nil
}
func (m *VersionInfo) validateGoVersion(formats strfmt.Registry) error {
if err := validate.Required("goVersion", "body", m.GoVersion); err != nil {
return err
}
return nil
}
func (m *VersionInfo) validateRevision(formats strfmt.Registry) error {
if err := validate.Required("revision", "body", m.Revision); err != nil {
return err
}
return nil
}
func (m *VersionInfo) validateVersion(formats strfmt.Registry) error {
if err := validate.Required("version", "body", m.Version); err != nil {
return err
}
return nil
}
// ContextValidate validates this version info based on context it is used
func (m *VersionInfo) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}
// MarshalBinary interface implementation
func (m *VersionInfo) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *VersionInfo) UnmarshalBinary(b []byte) error {
var res VersionInfo
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@@ -1,201 +0,0 @@
// Copyright 2017 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 labels
import (
"bytes"
"encoding/json"
"fmt"
"regexp"
"strings"
"github.com/prometheus/common/model"
)
// MatchType is an enum for label matching types.
type MatchType int
// Possible MatchTypes.
const (
MatchEqual MatchType = iota
MatchNotEqual
MatchRegexp
MatchNotRegexp
)
func (m MatchType) String() string {
typeToStr := map[MatchType]string{
MatchEqual: "=",
MatchNotEqual: "!=",
MatchRegexp: "=~",
MatchNotRegexp: "!~",
}
if str, ok := typeToStr[m]; ok {
return str
}
panic("unknown match type")
}
// Matcher models the matching of a label.
type Matcher struct {
Type MatchType
Name string
Value string
re *regexp.Regexp
}
// NewMatcher returns a matcher object.
func NewMatcher(t MatchType, n, v string) (*Matcher, error) {
m := &Matcher{
Type: t,
Name: n,
Value: v,
}
if t == MatchRegexp || t == MatchNotRegexp {
re, err := regexp.Compile("^(?:" + v + ")$")
if err != nil {
return nil, err
}
m.re = re
}
return m, nil
}
func (m *Matcher) String() string {
return fmt.Sprintf(`%s%s"%s"`, m.Name, m.Type, openMetricsEscape(m.Value))
}
// Matches returns whether the matcher matches the given string value.
func (m *Matcher) Matches(s string) bool {
switch m.Type {
case MatchEqual:
return s == m.Value
case MatchNotEqual:
return s != m.Value
case MatchRegexp:
return m.re.MatchString(s)
case MatchNotRegexp:
return !m.re.MatchString(s)
}
panic("labels.Matcher.Matches: invalid match type")
}
type apiV1Matcher struct {
Name string `json:"name"`
Value string `json:"value"`
IsRegex bool `json:"isRegex"`
IsEqual bool `json:"isEqual"`
}
// MarshalJSON retains backwards compatibility with types.Matcher for the v1 API.
func (m Matcher) MarshalJSON() ([]byte, error) {
return json.Marshal(apiV1Matcher{
Name: m.Name,
Value: m.Value,
IsRegex: m.Type == MatchRegexp || m.Type == MatchNotRegexp,
IsEqual: m.Type == MatchRegexp || m.Type == MatchEqual,
})
}
func (m *Matcher) UnmarshalJSON(data []byte) error {
v1m := apiV1Matcher{
IsEqual: true,
}
if err := json.Unmarshal(data, &v1m); err != nil {
return err
}
var t MatchType
switch {
case v1m.IsEqual && !v1m.IsRegex:
t = MatchEqual
case !v1m.IsEqual && !v1m.IsRegex:
t = MatchNotEqual
case v1m.IsEqual && v1m.IsRegex:
t = MatchRegexp
case !v1m.IsEqual && v1m.IsRegex:
t = MatchNotRegexp
}
matcher, err := NewMatcher(t, v1m.Name, v1m.Value)
if err != nil {
return err
}
*m = *matcher
return nil
}
// openMetricsEscape is similar to the usual string escaping, but more
// restricted. It merely replaces a new-line character with '\n', a double-quote
// character with '\"', and a backslash with '\\', which is the escaping used by
// OpenMetrics.
func openMetricsEscape(s string) string {
r := strings.NewReplacer(
`\`, `\\`,
"\n", `\n`,
`"`, `\"`,
)
return r.Replace(s)
}
// Matchers is a slice of Matchers that is sortable, implements Stringer, and
// provides a Matches method to match a LabelSet against all Matchers in the
// slice. Note that some users of Matchers might require it to be sorted.
type Matchers []*Matcher
func (ms Matchers) Len() int { return len(ms) }
func (ms Matchers) Swap(i, j int) { ms[i], ms[j] = ms[j], ms[i] }
func (ms Matchers) Less(i, j int) bool {
if ms[i].Name > ms[j].Name {
return false
}
if ms[i].Name < ms[j].Name {
return true
}
if ms[i].Value > ms[j].Value {
return false
}
if ms[i].Value < ms[j].Value {
return true
}
return ms[i].Type < ms[j].Type
}
// Matches checks whether all matchers are fulfilled against the given label set.
func (ms Matchers) Matches(lset model.LabelSet) bool {
for _, m := range ms {
if !m.Matches(string(lset[model.LabelName(m.Name)])) {
return false
}
}
return true
}
func (ms Matchers) String() string {
var buf bytes.Buffer
buf.WriteByte('{')
for i, m := range ms {
if i > 0 {
buf.WriteByte(',')
}
buf.WriteString(m.String())
}
buf.WriteByte('}')
return buf.String()
}

View File

@@ -1,179 +0,0 @@
// Copyright 2018 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.
package labels
import (
"regexp"
"strings"
"unicode/utf8"
"github.com/pkg/errors"
)
var (
// '=~' has to come before '=' because otherwise only the '='
// will be consumed, and the '~' will be part of the 3rd token.
re = regexp.MustCompile(`^\s*([a-zA-Z_:][a-zA-Z0-9_:]*)\s*(=~|=|!=|!~)\s*((?s).*?)\s*$`)
typeMap = map[string]MatchType{
"=": MatchEqual,
"!=": MatchNotEqual,
"=~": MatchRegexp,
"!~": MatchNotRegexp,
}
)
// ParseMatchers parses a comma-separated list of Matchers. A leading '{' and/or
// a trailing '}' is optional and will be trimmed before further
// parsing. Individual Matchers are separated by commas outside of quoted parts
// of the input string. Those commas may be surrounded by whitespace. Parts of the
// string inside unescaped double quotes ('"…"') are considered quoted (and
// commas don't act as separators there). If double quotes are escaped with a
// single backslash ('\"'), they are ignored for the purpose of identifying
// quoted parts of the input string. If the input string, after trimming the
// optional trailing '}', ends with a comma, followed by optional whitespace,
// this comma and whitespace will be trimmed.
//
// Examples for valid input strings:
//
// {foo = "bar", dings != "bums", }
// foo=bar,dings!=bums
// foo=bar, dings!=bums
// {quote="She said: \"Hi, ladies! That's gender-neutral…\""}
// statuscode=~"5.."
//
// See ParseMatcher for details on how an individual Matcher is parsed.
func ParseMatchers(s string) ([]*Matcher, error) {
matchers := []*Matcher{}
s = strings.TrimPrefix(s, "{")
s = strings.TrimSuffix(s, "}")
var (
insideQuotes bool
escaped bool
token strings.Builder
tokens []string
)
for _, r := range s {
switch r {
case ',':
if !insideQuotes {
tokens = append(tokens, token.String())
token.Reset()
continue
}
case '"':
if !escaped {
insideQuotes = !insideQuotes
} else {
escaped = false
}
case '\\':
escaped = !escaped
default:
escaped = false
}
token.WriteRune(r)
}
if s := strings.TrimSpace(token.String()); s != "" {
tokens = append(tokens, s)
}
for _, token := range tokens {
m, err := ParseMatcher(token)
if err != nil {
return nil, err
}
matchers = append(matchers, m)
}
return matchers, nil
}
// ParseMatcher parses a matcher with a syntax inspired by PromQL and
// OpenMetrics. This syntax is convenient to describe filters and selectors in
// UIs and config files. To support the interactive nature of the use cases, the
// parser is in various aspects fairly tolerant.
//
// The syntax of a matcher consists of three tokens: (1) A valid Prometheus
// label name. (2) One of '=', '!=', '=~', or '!~', with the same meaning as
// known from PromQL selectors. (3) A UTF-8 string, which may be enclosed in
// double quotes. Before or after each token, there may be any amount of
// whitespace, which will be discarded. The 3rd token may be the empty
// string. Within the 3rd token, OpenMetrics escaping rules apply: '\"' for a
// double-quote, '\n' for a line feed, '\\' for a literal backslash. Unescaped
// '"' must not occur inside the 3rd token (only as the 1st or last
// character). However, literal line feed characters are tolerated, as are
// single '\' characters not followed by '\', 'n', or '"'. They act as a literal
// backslash in that case.
func ParseMatcher(s string) (_ *Matcher, err error) {
ms := re.FindStringSubmatch(s)
if len(ms) == 0 {
return nil, errors.Errorf("bad matcher format: %s", s)
}
var (
rawValue = ms[3]
value strings.Builder
escaped bool
expectTrailingQuote bool
)
if strings.HasPrefix(rawValue, "\"") {
rawValue = strings.TrimPrefix(rawValue, "\"")
expectTrailingQuote = true
}
if !utf8.ValidString(rawValue) {
return nil, errors.Errorf("matcher value not valid UTF-8: %s", ms[3])
}
// Unescape the rawValue:
for i, r := range rawValue {
if escaped {
escaped = false
switch r {
case 'n':
value.WriteByte('\n')
case '"', '\\':
value.WriteRune(r)
default:
// This was a spurious escape, so treat the '\' as literal.
value.WriteByte('\\')
value.WriteRune(r)
}
continue
}
switch r {
case '\\':
if i < len(rawValue)-1 {
escaped = true
continue
}
// '\' encountered as last byte. Treat it as literal.
value.WriteByte('\\')
case '"':
if !expectTrailingQuote || i < len(rawValue)-1 {
return nil, errors.Errorf("matcher value contains unescaped double quote: %s", ms[3])
}
expectTrailingQuote = false
default:
value.WriteRune(r)
}
}
if expectTrailingQuote {
return nil, errors.Errorf("matcher value contains unescaped double quote: %s", ms[3])
}
return NewMatcher(typeMap[ms[2]], ms[1], value.String())
}

View File

@@ -1,156 +0,0 @@
// Copyright 2015 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 api provides clients for the HTTP APIs.
package api
import (
"bytes"
"context"
"errors"
"net"
"net/http"
"net/url"
"path"
"strings"
"time"
)
// DefaultRoundTripper is used if no RoundTripper is set in Config.
var DefaultRoundTripper http.RoundTripper = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
TLSHandshakeTimeout: 10 * time.Second,
}
// Config defines configuration parameters for a new client.
type Config struct {
// The address of the Prometheus to connect to.
Address string
// Client is used by the Client to drive HTTP requests. If not provided,
// a new one based on the provided RoundTripper (or DefaultRoundTripper) will be used.
Client *http.Client
// RoundTripper is used by the Client to drive HTTP requests. If not
// provided, DefaultRoundTripper will be used.
RoundTripper http.RoundTripper
}
func (cfg *Config) roundTripper() http.RoundTripper {
if cfg.RoundTripper == nil {
return DefaultRoundTripper
}
return cfg.RoundTripper
}
func (cfg *Config) client() http.Client {
if cfg.Client == nil {
return http.Client{
Transport: cfg.roundTripper(),
}
}
return *cfg.Client
}
func (cfg *Config) validate() error {
if cfg.Client != nil && cfg.RoundTripper != nil {
return errors.New("api.Config.RoundTripper and api.Config.Client are mutually exclusive")
}
return nil
}
// Client is the interface for an API client.
type Client interface {
URL(ep string, args map[string]string) *url.URL
Do(context.Context, *http.Request) (*http.Response, []byte, error)
}
// NewClient returns a new Client.
//
// It is safe to use the returned Client from multiple goroutines.
func NewClient(cfg Config) (Client, error) {
u, err := url.Parse(cfg.Address)
if err != nil {
return nil, err
}
u.Path = strings.TrimRight(u.Path, "/")
if err := cfg.validate(); err != nil {
return nil, err
}
return &httpClient{
endpoint: u,
client: cfg.client(),
}, nil
}
type httpClient struct {
endpoint *url.URL
client http.Client
}
func (c *httpClient) URL(ep string, args map[string]string) *url.URL {
p := path.Join(c.endpoint.Path, ep)
for arg, val := range args {
arg = ":" + arg
p = strings.ReplaceAll(p, arg, val)
}
u := *c.endpoint
u.Path = p
return &u
}
func (c *httpClient) Do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) {
if ctx != nil {
req = req.WithContext(ctx)
}
resp, err := c.client.Do(req)
defer func() {
if resp != nil {
resp.Body.Close()
}
}()
if err != nil {
return nil, nil, err
}
var body []byte
done := make(chan struct{})
go func() {
var buf bytes.Buffer
_, err = buf.ReadFrom(resp.Body)
body = buf.Bytes()
close(done)
}()
select {
case <-ctx.Done():
<-done
err = resp.Body.Close()
if err == nil {
err = ctx.Err()
}
case <-done:
}
return resp, body, err
}

File diff suppressed because it is too large Load Diff

View File

@@ -22,7 +22,7 @@ import "github.com/prometheus/client_golang/prometheus"
// Prometheus metrics. Note that the data models of expvar and Prometheus are
// fundamentally different, and that the expvar Collector is inherently slower
// than native Prometheus metrics. Thus, the expvar Collector is probably great
// for experiments and prototying, but you should seriously consider a more
// for experiments and prototyping, but you should seriously consider a more
// direct implementation of Prometheus metrics for monitoring production
// systems.
//

View File

@@ -28,6 +28,8 @@ var (
MetricsAll = GoRuntimeMetricsRule{regexp.MustCompile("/.*")}
// MetricsGC allows only GC metrics to be collected from Go runtime.
// e.g. go_gc_cycles_automatic_gc_cycles_total
// NOTE: This does not include new class of "/cpu/classes/gc/..." metrics.
// Use custom metric rule to access those.
MetricsGC = GoRuntimeMetricsRule{regexp.MustCompile(`^/gc/.*`)}
// MetricsMemory allows only memory metrics to be collected from Go runtime.
// e.g. go_memory_classes_heap_free_bytes
@@ -130,16 +132,19 @@ type GoCollectionOption uint32
const (
// GoRuntimeMemStatsCollection represents the metrics represented by runtime.MemStats structure.
// Deprecated. Use WithGoCollectorMemStatsMetricsDisabled() function to disable those metrics in the collector.
//
// Deprecated: Use WithGoCollectorMemStatsMetricsDisabled() function to disable those metrics in the collector.
GoRuntimeMemStatsCollection GoCollectionOption = 1 << iota
// GoRuntimeMetricsCollection is the new set of metrics represented by runtime/metrics package.
// Deprecated. Use WithGoCollectorRuntimeMetrics(GoRuntimeMetricsRule{Matcher: regexp.MustCompile("/.*")})
//
// Deprecated: Use WithGoCollectorRuntimeMetrics(GoRuntimeMetricsRule{Matcher: regexp.MustCompile("/.*")})
// function to enable those metrics in the collector.
GoRuntimeMetricsCollection
)
// WithGoCollections allows enabling different collections for Go collector on top of base metrics.
// Deprecated. Use WithGoCollectorRuntimeMetrics() and WithGoCollectorMemStatsMetricsDisabled() instead to control metrics.
//
// Deprecated: Use WithGoCollectorRuntimeMetrics() and WithGoCollectorMemStatsMetricsDisabled() instead to control metrics.
func WithGoCollections(flags GoCollectionOption) func(options *internal.GoCollectorOptions) {
return func(options *internal.GoCollectorOptions) {
if flags&GoRuntimeMemStatsCollection == 0 {

View File

@@ -20,6 +20,7 @@ import (
"time"
dto "github.com/prometheus/client_model/go"
"google.golang.org/protobuf/types/known/timestamppb"
)
// Counter is a Metric that represents a single numerical value that only ever
@@ -59,6 +60,18 @@ type ExemplarAdder interface {
// CounterOpts is an alias for Opts. See there for doc comments.
type CounterOpts Opts
// CounterVecOpts bundles the options to create a CounterVec metric.
// It is mandatory to set CounterOpts, see there for mandatory fields. VariableLabels
// is optional and can safely be left to its default value.
type CounterVecOpts struct {
CounterOpts
// VariableLabels are used to partition the metric vector by the given set
// of labels. Each label value will be constrained with the optional Constraint
// function, if provided.
VariableLabels ConstrainableLabels
}
// NewCounter creates a new Counter based on the provided CounterOpts.
//
// The returned implementation also implements ExemplarAdder. It is safe to
@@ -78,8 +91,12 @@ func NewCounter(opts CounterOpts) Counter {
nil,
opts.ConstLabels,
)
result := &counter{desc: desc, labelPairs: desc.constLabelPairs, now: time.Now}
if opts.now == nil {
opts.now = time.Now
}
result := &counter{desc: desc, labelPairs: desc.constLabelPairs, now: opts.now}
result.init(result) // Init self-collection.
result.createdTs = timestamppb.New(opts.now())
return result
}
@@ -94,10 +111,12 @@ type counter struct {
selfCollector
desc *Desc
createdTs *timestamppb.Timestamp
labelPairs []*dto.LabelPair
exemplar atomic.Value // Containing nil or a *dto.Exemplar.
now func() time.Time // To mock out time.Now() for testing.
// now is for testing purposes, by default it's time.Now.
now func() time.Time
}
func (c *counter) Desc() *Desc {
@@ -147,8 +166,7 @@ func (c *counter) Write(out *dto.Metric) error {
exemplar = e.(*dto.Exemplar)
}
val := c.get()
return populateMetric(CounterValue, val, c.labelPairs, exemplar, out)
return populateMetric(CounterValue, val, c.labelPairs, exemplar, out, c.createdTs)
}
func (c *counter) updateExemplar(v float64, l Labels) {
@@ -174,19 +192,31 @@ type CounterVec struct {
// NewCounterVec creates a new CounterVec based on the provided CounterOpts and
// partitioned by the given label names.
func NewCounterVec(opts CounterOpts, labelNames []string) *CounterVec {
desc := NewDesc(
return V2.NewCounterVec(CounterVecOpts{
CounterOpts: opts,
VariableLabels: UnconstrainedLabels(labelNames),
})
}
// NewCounterVec creates a new CounterVec based on the provided CounterVecOpts.
func (v2) NewCounterVec(opts CounterVecOpts) *CounterVec {
desc := V2.NewDesc(
BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
opts.Help,
labelNames,
opts.VariableLabels,
opts.ConstLabels,
)
if opts.now == nil {
opts.now = time.Now
}
return &CounterVec{
MetricVec: NewMetricVec(desc, func(lvs ...string) Metric {
if len(lvs) != len(desc.variableLabels) {
panic(makeInconsistentCardinalityError(desc.fqName, desc.variableLabels, lvs))
if len(lvs) != len(desc.variableLabels.names) {
panic(makeInconsistentCardinalityError(desc.fqName, desc.variableLabels.names, lvs))
}
result := &counter{desc: desc, labelPairs: MakeLabelPairs(desc, lvs), now: time.Now}
result := &counter{desc: desc, labelPairs: MakeLabelPairs(desc, lvs), now: opts.now}
result.init(result) // Init self-collection.
result.createdTs = timestamppb.New(opts.now())
return result
}),
}

View File

@@ -14,20 +14,16 @@
package prometheus
import (
"errors"
"fmt"
"sort"
"strings"
"github.com/cespare/xxhash/v2"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/common/model"
"google.golang.org/protobuf/proto"
"github.com/prometheus/client_golang/prometheus/internal"
//nolint:staticcheck // Ignore SA1019. Need to keep deprecated package for compatibility.
"github.com/golang/protobuf/proto"
"github.com/prometheus/common/model"
dto "github.com/prometheus/client_model/go"
)
// Desc is the descriptor used by every Prometheus Metric. It is essentially
@@ -54,9 +50,9 @@ type Desc struct {
// constLabelPairs contains precalculated DTO label pairs based on
// the constant labels.
constLabelPairs []*dto.LabelPair
// variableLabels contains names of labels for which the metric
// maintains variable values.
variableLabels []string
// variableLabels contains names of labels and normalization function for
// which the metric maintains variable values.
variableLabels *compiledLabels
// id is a hash of the values of the ConstLabels and fqName. This
// must be unique among all registered descriptors and can therefore be
// used as an identifier of the descriptor.
@@ -80,10 +76,24 @@ type Desc struct {
// For constLabels, the label values are constant. Therefore, they are fully
// specified in the Desc. See the Collector example for a usage pattern.
func NewDesc(fqName, help string, variableLabels []string, constLabels Labels) *Desc {
return V2.NewDesc(fqName, help, UnconstrainedLabels(variableLabels), constLabels)
}
// NewDesc allocates and initializes a new Desc. Errors are recorded in the Desc
// and will be reported on registration time. variableLabels and constLabels can
// be nil if no such labels should be set. fqName must not be empty.
//
// variableLabels only contain the label names and normalization functions. Their
// label values are variable and therefore not part of the Desc. (They are managed
// within the Metric.)
//
// For constLabels, the label values are constant. Therefore, they are fully
// specified in the Desc. See the Collector example for a usage pattern.
func (v2) NewDesc(fqName, help string, variableLabels ConstrainableLabels, constLabels Labels) *Desc {
d := &Desc{
fqName: fqName,
help: help,
variableLabels: variableLabels,
variableLabels: variableLabels.compile(),
}
if !model.IsValidMetricName(model.LabelValue(fqName)) {
d.err = fmt.Errorf("%q is not a valid metric name", fqName)
@@ -93,7 +103,7 @@ func NewDesc(fqName, help string, variableLabels []string, constLabels Labels) *
// their sorted label names) plus the fqName (at position 0).
labelValues := make([]string, 1, len(constLabels)+1)
labelValues[0] = fqName
labelNames := make([]string, 0, len(constLabels)+len(variableLabels))
labelNames := make([]string, 0, len(constLabels)+len(d.variableLabels.names))
labelNameSet := map[string]struct{}{}
// First add only the const label names and sort them...
for labelName := range constLabels {
@@ -118,16 +128,16 @@ func NewDesc(fqName, help string, variableLabels []string, constLabels Labels) *
// Now add the variable label names, but prefix them with something that
// cannot be in a regular label name. That prevents matching the label
// dimension with a different mix between preset and variable labels.
for _, labelName := range variableLabels {
if !checkLabelName(labelName) {
d.err = fmt.Errorf("%q is not a valid label name for metric %q", labelName, fqName)
for _, label := range d.variableLabels.names {
if !checkLabelName(label) {
d.err = fmt.Errorf("%q is not a valid label name for metric %q", label, fqName)
return d
}
labelNames = append(labelNames, "$"+labelName)
labelNameSet[labelName] = struct{}{}
labelNames = append(labelNames, "$"+label)
labelNameSet[label] = struct{}{}
}
if len(labelNames) != len(labelNameSet) {
d.err = errors.New("duplicate label names")
d.err = fmt.Errorf("duplicate label names in constant and variable labels for metric %q", fqName)
return d
}
@@ -179,11 +189,19 @@ func (d *Desc) String() string {
fmt.Sprintf("%s=%q", lp.GetName(), lp.GetValue()),
)
}
vlStrings := make([]string, 0, len(d.variableLabels.names))
for _, vl := range d.variableLabels.names {
if fn, ok := d.variableLabels.labelConstraints[vl]; ok && fn != nil {
vlStrings = append(vlStrings, fmt.Sprintf("c(%s)", vl))
} else {
vlStrings = append(vlStrings, vl)
}
}
return fmt.Sprintf(
"Desc{fqName: %q, help: %q, constLabels: {%s}, variableLabels: %v}",
"Desc{fqName: %q, help: %q, constLabels: {%s}, variableLabels: {%s}}",
d.fqName,
d.help,
strings.Join(lpStrings, ","),
d.variableLabels,
strings.Join(vlStrings, ","),
)
}

View File

@@ -37,35 +37,35 @@
//
// type metrics struct {
// cpuTemp prometheus.Gauge
// hdFailures *prometheus.CounterVec
// hdFailures *prometheus.CounterVec
// }
//
// func NewMetrics(reg prometheus.Registerer) *metrics {
// m := &metrics{
// cpuTemp: prometheus.NewGauge(prometheus.GaugeOpts{
// Name: "cpu_temperature_celsius",
// Help: "Current temperature of the CPU.",
// }),
// hdFailures: prometheus.NewCounterVec(
// prometheus.CounterOpts{
// Name: "hd_errors_total",
// Help: "Number of hard-disk errors.",
// },
// []string{"device"},
// ),
// }
// reg.MustRegister(m.cpuTemp)
// reg.MustRegister(m.hdFailures)
// return m
// m := &metrics{
// cpuTemp: prometheus.NewGauge(prometheus.GaugeOpts{
// Name: "cpu_temperature_celsius",
// Help: "Current temperature of the CPU.",
// }),
// hdFailures: prometheus.NewCounterVec(
// prometheus.CounterOpts{
// Name: "hd_errors_total",
// Help: "Number of hard-disk errors.",
// },
// []string{"device"},
// ),
// }
// reg.MustRegister(m.cpuTemp)
// reg.MustRegister(m.hdFailures)
// return m
// }
//
// func main() {
// // Create a non-global registry.
// reg := prometheus.NewRegistry()
// // Create a non-global registry.
// reg := prometheus.NewRegistry()
//
// // Create new metrics and register them using the custom registry.
// m := NewMetrics(reg)
// // Set values for the new created metrics.
// // Create new metrics and register them using the custom registry.
// m := NewMetrics(reg)
// // Set values for the new created metrics.
// m.cpuTemp.Set(65.3)
// m.hdFailures.With(prometheus.Labels{"device":"/dev/sda"}).Inc()
//

View File

@@ -48,7 +48,7 @@ func (e *expvarCollector) Collect(ch chan<- Metric) {
continue
}
var v interface{}
labels := make([]string, len(desc.variableLabels))
labels := make([]string, len(desc.variableLabels.names))
if err := json.Unmarshal([]byte(expVar.String()), &v); err != nil {
ch <- NewInvalidMetric(desc, err)
continue

View File

@@ -55,6 +55,18 @@ type Gauge interface {
// GaugeOpts is an alias for Opts. See there for doc comments.
type GaugeOpts Opts
// GaugeVecOpts bundles the options to create a GaugeVec metric.
// It is mandatory to set GaugeOpts, see there for mandatory fields. VariableLabels
// is optional and can safely be left to its default value.
type GaugeVecOpts struct {
GaugeOpts
// VariableLabels are used to partition the metric vector by the given set
// of labels. Each label value will be constrained with the optional Constraint
// function, if provided.
VariableLabels ConstrainableLabels
}
// NewGauge creates a new Gauge based on the provided GaugeOpts.
//
// The returned implementation is optimized for a fast Set method. If you have a
@@ -123,7 +135,7 @@ func (g *gauge) Sub(val float64) {
func (g *gauge) Write(out *dto.Metric) error {
val := math.Float64frombits(atomic.LoadUint64(&g.valBits))
return populateMetric(GaugeValue, val, g.labelPairs, nil, out)
return populateMetric(GaugeValue, val, g.labelPairs, nil, out, nil)
}
// GaugeVec is a Collector that bundles a set of Gauges that all share the same
@@ -138,16 +150,24 @@ type GaugeVec struct {
// NewGaugeVec creates a new GaugeVec based on the provided GaugeOpts and
// partitioned by the given label names.
func NewGaugeVec(opts GaugeOpts, labelNames []string) *GaugeVec {
desc := NewDesc(
return V2.NewGaugeVec(GaugeVecOpts{
GaugeOpts: opts,
VariableLabels: UnconstrainedLabels(labelNames),
})
}
// NewGaugeVec creates a new GaugeVec based on the provided GaugeVecOpts.
func (v2) NewGaugeVec(opts GaugeVecOpts) *GaugeVec {
desc := V2.NewDesc(
BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
opts.Help,
labelNames,
opts.VariableLabels,
opts.ConstLabels,
)
return &GaugeVec{
MetricVec: NewMetricVec(desc, func(lvs ...string) Metric {
if len(lvs) != len(desc.variableLabels) {
panic(makeInconsistentCardinalityError(desc.fqName, desc.variableLabels, lvs))
if len(lvs) != len(desc.variableLabels.names) {
panic(makeInconsistentCardinalityError(desc.fqName, desc.variableLabels.names, lvs))
}
result := &gauge{desc: desc, labelPairs: MakeLabelPairs(desc, lvs)}
result.init(result) // Init self-collection.

View File

@@ -23,11 +23,10 @@ import (
"strings"
"sync"
//nolint:staticcheck // Ignore SA1019. Need to keep deprecated package for compatibility.
"github.com/golang/protobuf/proto"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/client_golang/prometheus/internal"
dto "github.com/prometheus/client_model/go"
"google.golang.org/protobuf/proto"
)
const (

View File

@@ -22,10 +22,10 @@ import (
"sync/atomic"
"time"
//nolint:staticcheck // Ignore SA1019. Need to keep deprecated package for compatibility.
"github.com/golang/protobuf/proto"
dto "github.com/prometheus/client_model/go"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/timestamppb"
)
// nativeHistogramBounds for the frac of observed values. Only relevant for
@@ -392,7 +392,7 @@ type HistogramOpts struct {
// zero, it is replaced by default buckets. The default buckets are
// DefBuckets if no buckets for a native histogram (see below) are used,
// otherwise the default is no buckets. (In other words, if you want to
// use both reguler buckets and buckets for a native histogram, you have
// use both regular buckets and buckets for a native histogram, you have
// to define the regular buckets here explicitly.)
Buckets []float64
@@ -402,7 +402,7 @@ type HistogramOpts struct {
// Histogram by a Prometheus server with that feature enabled (requires
// Prometheus v2.40+). Sparse buckets are exponential buckets covering
// the whole float64 range (with the exception of the “zero” bucket, see
// SparseBucketsZeroThreshold below). From any one bucket to the next,
// NativeHistogramZeroThreshold below). From any one bucket to the next,
// the width of the bucket grows by a constant
// factor. NativeHistogramBucketFactor provides an upper bound for this
// factor (exception see below). The smaller
@@ -414,8 +414,8 @@ type HistogramOpts struct {
// and 2, same as between 2 and 4, and 4 and 8, etc.).
//
// Details about the actually used factor: The factor is calculated as
// 2^(2^n), where n is an integer number between (and including) -8 and
// 4. n is chosen so that the resulting factor is the largest that is
// 2^(2^-n), where n is an integer number between (and including) -4 and
// 8. n is chosen so that the resulting factor is the largest that is
// still smaller or equal to NativeHistogramBucketFactor. Note that the
// smallest possible factor is therefore approx. 1.00271 (i.e. 2^(2^-8)
// ). If NativeHistogramBucketFactor is greater than 1 but smaller than
@@ -429,12 +429,12 @@ type HistogramOpts struct {
// a major version bump.
NativeHistogramBucketFactor float64
// All observations with an absolute value of less or equal
// NativeHistogramZeroThreshold are accumulated into a “zero”
// bucket. For best results, this should be close to a bucket
// boundary. This is usually the case if picking a power of two. If
// NativeHistogramZeroThreshold are accumulated into a “zero” bucket.
// For best results, this should be close to a bucket boundary. This is
// usually the case if picking a power of two. If
// NativeHistogramZeroThreshold is left at zero,
// DefSparseBucketsZeroThreshold is used as the threshold. To configure
// a zero bucket with an actual threshold of zero (i.e. only
// DefNativeHistogramZeroThreshold is used as the threshold. To
// configure a zero bucket with an actual threshold of zero (i.e. only
// observations of precisely zero will go into the zero bucket), set
// NativeHistogramZeroThreshold to the NativeHistogramZeroThresholdZero
// constant (or any negative float value).
@@ -447,26 +447,49 @@ type HistogramOpts struct {
// Histogram are sufficiently wide-spread. In particular, this could be
// used as a DoS attack vector. Where the observed values depend on
// external inputs, it is highly recommended to set a
// NativeHistogramMaxBucketNumber.) Once the set
// NativeHistogramMaxBucketNumber.) Once the set
// NativeHistogramMaxBucketNumber is exceeded, the following strategy is
// enacted: First, if the last reset (or the creation) of the histogram
// is at least NativeHistogramMinResetDuration ago, then the whole
// histogram is reset to its initial state (including regular
// buckets). If less time has passed, or if
// NativeHistogramMinResetDuration is zero, no reset is
// performed. Instead, the zero threshold is increased sufficiently to
// reduce the number of buckets to or below
// NativeHistogramMaxBucketNumber, but not to more than
// NativeHistogramMaxZeroThreshold. Thus, if
// NativeHistogramMaxZeroThreshold is already at or below the current
// zero threshold, nothing happens at this step. After that, if the
// number of buckets still exceeds NativeHistogramMaxBucketNumber, the
// resolution of the histogram is reduced by doubling the width of the
// sparse buckets (up to a growth factor between one bucket to the next
// of 2^(2^4) = 65536, see above).
// enacted:
// - First, if the last reset (or the creation) of the histogram is at
// least NativeHistogramMinResetDuration ago, then the whole
// histogram is reset to its initial state (including regular
// buckets).
// - If less time has passed, or if NativeHistogramMinResetDuration is
// zero, no reset is performed. Instead, the zero threshold is
// increased sufficiently to reduce the number of buckets to or below
// NativeHistogramMaxBucketNumber, but not to more than
// NativeHistogramMaxZeroThreshold. Thus, if
// NativeHistogramMaxZeroThreshold is already at or below the current
// zero threshold, nothing happens at this step.
// - After that, if the number of buckets still exceeds
// NativeHistogramMaxBucketNumber, the resolution of the histogram is
// reduced by doubling the width of the sparse buckets (up to a
// growth factor between one bucket to the next of 2^(2^4) = 65536,
// see above).
// - Any increased zero threshold or reduced resolution is reset back
// to their original values once NativeHistogramMinResetDuration has
// passed (since the last reset or the creation of the histogram).
NativeHistogramMaxBucketNumber uint32
NativeHistogramMinResetDuration time.Duration
NativeHistogramMaxZeroThreshold float64
// now is for testing purposes, by default it's time.Now.
now func() time.Time
// afterFunc is for testing purposes, by default it's time.AfterFunc.
afterFunc func(time.Duration, func()) *time.Timer
}
// HistogramVecOpts bundles the options to create a HistogramVec metric.
// It is mandatory to set HistogramOpts, see there for mandatory fields. VariableLabels
// is optional and can safely be left to its default value.
type HistogramVecOpts struct {
HistogramOpts
// VariableLabels are used to partition the metric vector by the given set
// of labels. Each label value will be constrained with the optional Constraint
// function, if provided.
VariableLabels ConstrainableLabels
}
// NewHistogram creates a new Histogram based on the provided HistogramOpts. It
@@ -488,11 +511,11 @@ func NewHistogram(opts HistogramOpts) Histogram {
}
func newHistogram(desc *Desc, opts HistogramOpts, labelValues ...string) Histogram {
if len(desc.variableLabels) != len(labelValues) {
panic(makeInconsistentCardinalityError(desc.fqName, desc.variableLabels, labelValues))
if len(desc.variableLabels.names) != len(labelValues) {
panic(makeInconsistentCardinalityError(desc.fqName, desc.variableLabels.names, labelValues))
}
for _, n := range desc.variableLabels {
for _, n := range desc.variableLabels.names {
if n == bucketLabel {
panic(errBucketLabelNotAllowed)
}
@@ -503,6 +526,12 @@ func newHistogram(desc *Desc, opts HistogramOpts, labelValues ...string) Histogr
}
}
if opts.now == nil {
opts.now = time.Now
}
if opts.afterFunc == nil {
opts.afterFunc = time.AfterFunc
}
h := &histogram{
desc: desc,
upperBounds: opts.Buckets,
@@ -510,8 +539,9 @@ func newHistogram(desc *Desc, opts HistogramOpts, labelValues ...string) Histogr
nativeHistogramMaxBuckets: opts.NativeHistogramMaxBucketNumber,
nativeHistogramMaxZeroThreshold: opts.NativeHistogramMaxZeroThreshold,
nativeHistogramMinResetDuration: opts.NativeHistogramMinResetDuration,
lastResetTime: time.Now(),
now: time.Now,
lastResetTime: opts.now(),
now: opts.now,
afterFunc: opts.afterFunc,
}
if len(h.upperBounds) == 0 && opts.NativeHistogramBucketFactor <= 1 {
h.upperBounds = DefBuckets
@@ -544,16 +574,12 @@ func newHistogram(desc *Desc, opts HistogramOpts, labelValues ...string) Histogr
}
// Finally we know the final length of h.upperBounds and can make buckets
// for both counts as well as exemplars:
h.counts[0] = &histogramCounts{
buckets: make([]uint64, len(h.upperBounds)),
nativeHistogramZeroThresholdBits: math.Float64bits(h.nativeHistogramZeroThreshold),
nativeHistogramSchema: h.nativeHistogramSchema,
}
h.counts[1] = &histogramCounts{
buckets: make([]uint64, len(h.upperBounds)),
nativeHistogramZeroThresholdBits: math.Float64bits(h.nativeHistogramZeroThreshold),
nativeHistogramSchema: h.nativeHistogramSchema,
}
h.counts[0] = &histogramCounts{buckets: make([]uint64, len(h.upperBounds))}
atomic.StoreUint64(&h.counts[0].nativeHistogramZeroThresholdBits, math.Float64bits(h.nativeHistogramZeroThreshold))
atomic.StoreInt32(&h.counts[0].nativeHistogramSchema, h.nativeHistogramSchema)
h.counts[1] = &histogramCounts{buckets: make([]uint64, len(h.upperBounds))}
atomic.StoreUint64(&h.counts[1].nativeHistogramZeroThresholdBits, math.Float64bits(h.nativeHistogramZeroThreshold))
atomic.StoreInt32(&h.counts[1].nativeHistogramSchema, h.nativeHistogramSchema)
h.exemplars = make([]atomic.Value, len(h.upperBounds)+1)
h.init(h) // Init self-collection.
@@ -632,8 +658,8 @@ func (hc *histogramCounts) observe(v float64, bucket int, doSparse bool) {
if frac == 0.5 {
key--
}
div := 1 << -schema
key = (key + div - 1) / div
offset := (1 << -schema) - 1
key = (key + offset) >> -schema
}
if isInf {
key++
@@ -694,9 +720,18 @@ type histogram struct {
nativeHistogramMaxZeroThreshold float64
nativeHistogramMaxBuckets uint32
nativeHistogramMinResetDuration time.Duration
lastResetTime time.Time // Protected by mtx.
// lastResetTime is protected by mtx. It is also used as created timestamp.
lastResetTime time.Time
// resetScheduled is protected by mtx. It is true if a reset is
// scheduled for a later time (when nativeHistogramMinResetDuration has
// passed).
resetScheduled bool
now func() time.Time // To mock out time.Now() for testing.
// now is for testing purposes, by default it's time.Now.
now func() time.Time
// afterFunc is for testing purposes, by default it's time.AfterFunc.
afterFunc func(time.Duration, func()) *time.Timer
}
func (h *histogram) Desc() *Desc {
@@ -735,9 +770,10 @@ func (h *histogram) Write(out *dto.Metric) error {
waitForCooldown(count, coldCounts)
his := &dto.Histogram{
Bucket: make([]*dto.Bucket, len(h.upperBounds)),
SampleCount: proto.Uint64(count),
SampleSum: proto.Float64(math.Float64frombits(atomic.LoadUint64(&coldCounts.sumBits))),
Bucket: make([]*dto.Bucket, len(h.upperBounds)),
SampleCount: proto.Uint64(count),
SampleSum: proto.Float64(math.Float64frombits(atomic.LoadUint64(&coldCounts.sumBits))),
CreatedTimestamp: timestamppb.New(h.lastResetTime),
}
out.Histogram = his
out.Label = h.labelPairs
@@ -775,6 +811,16 @@ func (h *histogram) Write(out *dto.Metric) error {
his.ZeroCount = proto.Uint64(zeroBucket)
his.NegativeSpan, his.NegativeDelta = makeBuckets(&coldCounts.nativeHistogramBucketsNegative)
his.PositiveSpan, his.PositiveDelta = makeBuckets(&coldCounts.nativeHistogramBucketsPositive)
// Add a no-op span to a histogram without observations and with
// a zero threshold of zero. Otherwise, a native histogram would
// look like a classic histogram to scrapers.
if *his.ZeroThreshold == 0 && *his.ZeroCount == 0 && len(his.PositiveSpan) == 0 && len(his.NegativeSpan) == 0 {
his.PositiveSpan = []*dto.BucketSpan{{
Offset: proto.Int32(0),
Length: proto.Uint32(0),
}}
}
}
addAndResetCounts(hotCounts, coldCounts)
return nil
@@ -810,7 +856,7 @@ func (h *histogram) observe(v float64, bucket int) {
}
}
// limitSparsebuckets applies a strategy to limit the number of populated sparse
// limitBuckets applies a strategy to limit the number of populated sparse
// buckets. It's generally best effort, and there are situations where the
// number can go higher (if even the lowest resolution isn't enough to reduce
// the number sufficiently, or if the provided counts aren't fully updated yet
@@ -841,26 +887,39 @@ func (h *histogram) limitBuckets(counts *histogramCounts, value float64, bucket
if h.maybeReset(hotCounts, coldCounts, coldIdx, value, bucket) {
return
}
// One of the other strategies will happen. To undo what they will do as
// soon as enough time has passed to satisfy
// h.nativeHistogramMinResetDuration, schedule a reset at the right time
// if we haven't done so already.
if h.nativeHistogramMinResetDuration > 0 && !h.resetScheduled {
h.resetScheduled = true
h.afterFunc(h.nativeHistogramMinResetDuration-h.now().Sub(h.lastResetTime), h.reset)
}
if h.maybeWidenZeroBucket(hotCounts, coldCounts) {
return
}
h.doubleBucketWidth(hotCounts, coldCounts)
}
// maybeReset resests the whole histogram if at least h.nativeHistogramMinResetDuration
// has been passed. It returns true if the histogram has been reset. The caller
// must have locked h.mtx.
func (h *histogram) maybeReset(hot, cold *histogramCounts, coldIdx uint64, value float64, bucket int) bool {
// maybeReset resets the whole histogram if at least
// h.nativeHistogramMinResetDuration has been passed. It returns true if the
// histogram has been reset. The caller must have locked h.mtx.
func (h *histogram) maybeReset(
hot, cold *histogramCounts, coldIdx uint64, value float64, bucket int,
) bool {
// We are using the possibly mocked h.now() rather than
// time.Since(h.lastResetTime) to enable testing.
if h.nativeHistogramMinResetDuration == 0 || h.now().Sub(h.lastResetTime) < h.nativeHistogramMinResetDuration {
if h.nativeHistogramMinResetDuration == 0 || // No reset configured.
h.resetScheduled || // Do not interefere if a reset is already scheduled.
h.now().Sub(h.lastResetTime) < h.nativeHistogramMinResetDuration {
return false
}
// Completely reset coldCounts.
h.resetCounts(cold)
// Repeat the latest observation to not lose it completely.
cold.observe(value, bucket, true)
// Make coldCounts the new hot counts while ressetting countAndHotIdx.
// Make coldCounts the new hot counts while resetting countAndHotIdx.
n := atomic.SwapUint64(&h.countAndHotIdx, (coldIdx<<63)+1)
count := n & ((1 << 63) - 1)
waitForCooldown(count, hot)
@@ -870,6 +929,29 @@ func (h *histogram) maybeReset(hot, cold *histogramCounts, coldIdx uint64, value
return true
}
// reset resets the whole histogram. It locks h.mtx itself, i.e. it has to be
// called without having locked h.mtx.
func (h *histogram) reset() {
h.mtx.Lock()
defer h.mtx.Unlock()
n := atomic.LoadUint64(&h.countAndHotIdx)
hotIdx := n >> 63
coldIdx := (^n) >> 63
hot := h.counts[hotIdx]
cold := h.counts[coldIdx]
// Completely reset coldCounts.
h.resetCounts(cold)
// Make coldCounts the new hot counts while resetting countAndHotIdx.
n = atomic.SwapUint64(&h.countAndHotIdx, coldIdx<<63)
count := n & ((1 << 63) - 1)
waitForCooldown(count, hot)
// Finally, reset the formerly hot counts, too.
h.resetCounts(hot)
h.lastResetTime = h.now()
h.resetScheduled = false
}
// maybeWidenZeroBucket widens the zero bucket until it includes the existing
// buckets closest to the zero bucket (which could be two, if an equidistant
// negative and a positive bucket exists, but usually it's only one bucket to be
@@ -1034,15 +1116,23 @@ type HistogramVec struct {
// NewHistogramVec creates a new HistogramVec based on the provided HistogramOpts and
// partitioned by the given label names.
func NewHistogramVec(opts HistogramOpts, labelNames []string) *HistogramVec {
desc := NewDesc(
return V2.NewHistogramVec(HistogramVecOpts{
HistogramOpts: opts,
VariableLabels: UnconstrainedLabels(labelNames),
})
}
// NewHistogramVec creates a new HistogramVec based on the provided HistogramVecOpts.
func (v2) NewHistogramVec(opts HistogramVecOpts) *HistogramVec {
desc := V2.NewDesc(
BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
opts.Help,
labelNames,
opts.VariableLabels,
opts.ConstLabels,
)
return &HistogramVec{
MetricVec: NewMetricVec(desc, func(lvs ...string) Metric {
return newHistogram(desc, opts, lvs...)
return newHistogram(desc, opts.HistogramOpts, lvs...)
}),
}
}
@@ -1161,6 +1251,7 @@ type constHistogram struct {
sum float64
buckets map[float64]uint64
labelPairs []*dto.LabelPair
createdTs *timestamppb.Timestamp
}
func (h *constHistogram) Desc() *Desc {
@@ -1168,7 +1259,9 @@ func (h *constHistogram) Desc() *Desc {
}
func (h *constHistogram) Write(out *dto.Metric) error {
his := &dto.Histogram{}
his := &dto.Histogram{
CreatedTimestamp: h.createdTs,
}
buckets := make([]*dto.Bucket, 0, len(h.buckets))
@@ -1215,7 +1308,7 @@ func NewConstHistogram(
if desc.err != nil {
return nil, desc.err
}
if err := validateLabelValues(labelValues, len(desc.variableLabels)); err != nil {
if err := validateLabelValues(labelValues, len(desc.variableLabels.names)); err != nil {
return nil, err
}
return &constHistogram{
@@ -1309,7 +1402,7 @@ func makeBuckets(buckets *sync.Map) ([]*dto.BucketSpan, []int64) {
// Multiple spans with only small gaps in between are probably
// encoded more efficiently as one larger span with a few empty
// buckets. Needs some research to find the sweet spot. For now,
// we assume that gaps of one ore two buckets should not create
// we assume that gaps of one or two buckets should not create
// a new span.
iDelta := int32(i - nextI)
if n == 0 || iDelta > 2 {

View File

@@ -14,7 +14,7 @@
// It provides tools to compare sequences of strings and generate textual diffs.
//
// Maintaining `GetUnifiedDiffString` here because original repository
// (https://github.com/pmezard/go-difflib) is no loger maintained.
// (https://github.com/pmezard/go-difflib) is no longer maintained.
package internal
import (

View File

@@ -32,6 +32,104 @@ import (
// create a Desc.
type Labels map[string]string
// LabelConstraint normalizes label values.
type LabelConstraint func(string) string
// ConstrainedLabels represents a label name and its constrain function
// to normalize label values. This type is commonly used when constructing
// metric vector Collectors.
type ConstrainedLabel struct {
Name string
Constraint LabelConstraint
}
// ConstrainableLabels is an interface that allows creating of labels that can
// be optionally constrained.
//
// prometheus.V2().NewCounterVec(CounterVecOpts{
// CounterOpts: {...}, // Usual CounterOpts fields
// VariableLabels: []ConstrainedLabels{
// {Name: "A"},
// {Name: "B", Constraint: func(v string) string { ... }},
// },
// })
type ConstrainableLabels interface {
compile() *compiledLabels
labelNames() []string
}
// ConstrainedLabels represents a collection of label name -> constrain function
// to normalize label values. This type is commonly used when constructing
// metric vector Collectors.
type ConstrainedLabels []ConstrainedLabel
func (cls ConstrainedLabels) compile() *compiledLabels {
compiled := &compiledLabels{
names: make([]string, len(cls)),
labelConstraints: map[string]LabelConstraint{},
}
for i, label := range cls {
compiled.names[i] = label.Name
if label.Constraint != nil {
compiled.labelConstraints[label.Name] = label.Constraint
}
}
return compiled
}
func (cls ConstrainedLabels) labelNames() []string {
names := make([]string, len(cls))
for i, label := range cls {
names[i] = label.Name
}
return names
}
// UnconstrainedLabels represents collection of label without any constraint on
// their value. Thus, it is simply a collection of label names.
//
// UnconstrainedLabels([]string{ "A", "B" })
//
// is equivalent to
//
// ConstrainedLabels {
// { Name: "A" },
// { Name: "B" },
// }
type UnconstrainedLabels []string
func (uls UnconstrainedLabels) compile() *compiledLabels {
return &compiledLabels{
names: uls,
}
}
func (uls UnconstrainedLabels) labelNames() []string {
return uls
}
type compiledLabels struct {
names []string
labelConstraints map[string]LabelConstraint
}
func (cls *compiledLabels) compile() *compiledLabels {
return cls
}
func (cls *compiledLabels) labelNames() []string {
return cls.names
}
func (cls *compiledLabels) constrain(labelName, value string) string {
if fn, ok := cls.labelConstraints[labelName]; ok && fn != nil {
return fn(value)
}
return value
}
// reservedLabelPrefix is a prefix which is not legal in user-supplied
// label names.
const reservedLabelPrefix = "__"
@@ -67,6 +165,8 @@ func validateValuesInLabels(labels Labels, expectedNumberOfValues int) error {
func validateLabelValues(vals []string, expectedNumberOfValues int) error {
if len(vals) != expectedNumberOfValues {
// The call below makes vals escape, copy them to avoid that.
vals := append([]string(nil), vals...)
return fmt.Errorf(
"%w: expected %d label values but got %d in %#v",
errInconsistentCardinality, expectedNumberOfValues,

View File

@@ -20,11 +20,9 @@ import (
"strings"
"time"
//nolint:staticcheck // Ignore SA1019. Need to keep deprecated package for compatibility.
"github.com/golang/protobuf/proto"
"github.com/prometheus/common/model"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/common/model"
"google.golang.org/protobuf/proto"
)
var separatorByteSlice = []byte{model.SeparatorByte} // For convenient use with xxhash.
@@ -94,6 +92,9 @@ type Opts struct {
// machine_role metric). See also
// https://prometheus.io/docs/instrumenting/writing_exporters/#target-labels-not-static-scraped-labels
ConstLabels Labels
// now is for testing purposes, by default it's time.Now.
now func() time.Time
}
// BuildFQName joins the given three name components by "_". Empty name

View File

@@ -11,8 +11,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build !windows && !js
// +build !windows,!js
//go:build !windows && !js && !wasip1
// +build !windows,!js,!wasip1
package prometheus

View File

@@ -1,4 +1,4 @@
// Copyright 2018 The Prometheus Authors
// 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
@@ -11,9 +11,16 @@
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build windows
// +build windows
//go:build wasip1
// +build wasip1
package fileutil
package prometheus
const maxMapSize = 0x7FFFFFFF // 2GB
func canCollectProcess() bool {
return false
}
func (*processCollector) processCollect(chan<- Metric) {
// noop on this platform
return
}

View File

@@ -37,6 +37,7 @@ import (
"fmt"
"io"
"net/http"
"strconv"
"strings"
"sync"
"time"
@@ -47,9 +48,10 @@ import (
)
const (
contentTypeHeader = "Content-Type"
contentEncodingHeader = "Content-Encoding"
acceptEncodingHeader = "Accept-Encoding"
contentTypeHeader = "Content-Type"
contentEncodingHeader = "Content-Encoding"
acceptEncodingHeader = "Accept-Encoding"
processStartTimeHeader = "Process-Start-Time-Unix"
)
var gzipPool = sync.Pool{
@@ -121,6 +123,9 @@ func HandlerForTransactional(reg prometheus.TransactionalGatherer, opts HandlerO
}
h := http.HandlerFunc(func(rsp http.ResponseWriter, req *http.Request) {
if !opts.ProcessStartTime.IsZero() {
rsp.Header().Set(processStartTimeHeader, strconv.FormatInt(opts.ProcessStartTime.Unix(), 10))
}
if inFlightSem != nil {
select {
case inFlightSem <- struct{}{}: // All good, carry on.
@@ -366,6 +371,14 @@ type HandlerOpts struct {
// (which changes the identity of the resulting series on the Prometheus
// server).
EnableOpenMetrics bool
// ProcessStartTime allows setting process start timevalue that will be exposed
// with "Process-Start-Time-Unix" response header along with the metrics
// payload. This allow callers to have efficient transformations to cumulative
// counters (e.g. OpenTelemetry) or generally _created timestamp estimation per
// scrape target.
// NOTE: This feature is experimental and not covered by OpenMetrics or Prometheus
// exposition format.
ProcessStartTime time.Time
}
// gzipAccepted returns whether the client will accept gzip-encoded content.

View File

@@ -68,16 +68,17 @@ func InstrumentRoundTripperCounter(counter *prometheus.CounterVec, next http.Rou
o.apply(rtOpts)
}
code, method := checkLabels(counter)
// Curry the counter with dynamic labels before checking the remaining labels.
code, method := checkLabels(counter.MustCurryWith(rtOpts.emptyDynamicLabels()))
return func(r *http.Request) (*http.Response, error) {
resp, err := next.RoundTrip(r)
if err == nil {
addWithExemplar(
counter.With(labels(code, method, r.Method, resp.StatusCode, rtOpts.extraMethods...)),
1,
rtOpts.getExemplarFn(r.Context()),
)
l := labels(code, method, r.Method, resp.StatusCode, rtOpts.extraMethods...)
for label, resolve := range rtOpts.extraLabelsFromCtx {
l[label] = resolve(resp.Request.Context())
}
addWithExemplar(counter.With(l), 1, rtOpts.getExemplarFn(r.Context()))
}
return resp, err
}
@@ -110,17 +111,18 @@ func InstrumentRoundTripperDuration(obs prometheus.ObserverVec, next http.RoundT
o.apply(rtOpts)
}
code, method := checkLabels(obs)
// Curry the observer with dynamic labels before checking the remaining labels.
code, method := checkLabels(obs.MustCurryWith(rtOpts.emptyDynamicLabels()))
return func(r *http.Request) (*http.Response, error) {
start := time.Now()
resp, err := next.RoundTrip(r)
if err == nil {
observeWithExemplar(
obs.With(labels(code, method, r.Method, resp.StatusCode, rtOpts.extraMethods...)),
time.Since(start).Seconds(),
rtOpts.getExemplarFn(r.Context()),
)
l := labels(code, method, r.Method, resp.StatusCode, rtOpts.extraMethods...)
for label, resolve := range rtOpts.extraLabelsFromCtx {
l[label] = resolve(resp.Request.Context())
}
observeWithExemplar(obs.With(l), time.Since(start).Seconds(), rtOpts.getExemplarFn(r.Context()))
}
return resp, err
}

View File

@@ -87,7 +87,8 @@ func InstrumentHandlerDuration(obs prometheus.ObserverVec, next http.Handler, op
o.apply(hOpts)
}
code, method := checkLabels(obs)
// Curry the observer with dynamic labels before checking the remaining labels.
code, method := checkLabels(obs.MustCurryWith(hOpts.emptyDynamicLabels()))
if code {
return func(w http.ResponseWriter, r *http.Request) {
@@ -95,23 +96,22 @@ func InstrumentHandlerDuration(obs prometheus.ObserverVec, next http.Handler, op
d := newDelegator(w, nil)
next.ServeHTTP(d, r)
observeWithExemplar(
obs.With(labels(code, method, r.Method, d.Status(), hOpts.extraMethods...)),
time.Since(now).Seconds(),
hOpts.getExemplarFn(r.Context()),
)
l := labels(code, method, r.Method, d.Status(), hOpts.extraMethods...)
for label, resolve := range hOpts.extraLabelsFromCtx {
l[label] = resolve(r.Context())
}
observeWithExemplar(obs.With(l), time.Since(now).Seconds(), hOpts.getExemplarFn(r.Context()))
}
}
return func(w http.ResponseWriter, r *http.Request) {
now := time.Now()
next.ServeHTTP(w, r)
observeWithExemplar(
obs.With(labels(code, method, r.Method, 0, hOpts.extraMethods...)),
time.Since(now).Seconds(),
hOpts.getExemplarFn(r.Context()),
)
l := labels(code, method, r.Method, 0, hOpts.extraMethods...)
for label, resolve := range hOpts.extraLabelsFromCtx {
l[label] = resolve(r.Context())
}
observeWithExemplar(obs.With(l), time.Since(now).Seconds(), hOpts.getExemplarFn(r.Context()))
}
}
@@ -138,28 +138,30 @@ func InstrumentHandlerCounter(counter *prometheus.CounterVec, next http.Handler,
o.apply(hOpts)
}
code, method := checkLabels(counter)
// Curry the counter with dynamic labels before checking the remaining labels.
code, method := checkLabels(counter.MustCurryWith(hOpts.emptyDynamicLabels()))
if code {
return func(w http.ResponseWriter, r *http.Request) {
d := newDelegator(w, nil)
next.ServeHTTP(d, r)
addWithExemplar(
counter.With(labels(code, method, r.Method, d.Status(), hOpts.extraMethods...)),
1,
hOpts.getExemplarFn(r.Context()),
)
l := labels(code, method, r.Method, d.Status(), hOpts.extraMethods...)
for label, resolve := range hOpts.extraLabelsFromCtx {
l[label] = resolve(r.Context())
}
addWithExemplar(counter.With(l), 1, hOpts.getExemplarFn(r.Context()))
}
}
return func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(w, r)
addWithExemplar(
counter.With(labels(code, method, r.Method, 0, hOpts.extraMethods...)),
1,
hOpts.getExemplarFn(r.Context()),
)
l := labels(code, method, r.Method, 0, hOpts.extraMethods...)
for label, resolve := range hOpts.extraLabelsFromCtx {
l[label] = resolve(r.Context())
}
addWithExemplar(counter.With(l), 1, hOpts.getExemplarFn(r.Context()))
}
}
@@ -191,16 +193,17 @@ func InstrumentHandlerTimeToWriteHeader(obs prometheus.ObserverVec, next http.Ha
o.apply(hOpts)
}
code, method := checkLabels(obs)
// Curry the observer with dynamic labels before checking the remaining labels.
code, method := checkLabels(obs.MustCurryWith(hOpts.emptyDynamicLabels()))
return func(w http.ResponseWriter, r *http.Request) {
now := time.Now()
d := newDelegator(w, func(status int) {
observeWithExemplar(
obs.With(labels(code, method, r.Method, status, hOpts.extraMethods...)),
time.Since(now).Seconds(),
hOpts.getExemplarFn(r.Context()),
)
l := labels(code, method, r.Method, status, hOpts.extraMethods...)
for label, resolve := range hOpts.extraLabelsFromCtx {
l[label] = resolve(r.Context())
}
observeWithExemplar(obs.With(l), time.Since(now).Seconds(), hOpts.getExemplarFn(r.Context()))
})
next.ServeHTTP(d, r)
}
@@ -231,28 +234,32 @@ func InstrumentHandlerRequestSize(obs prometheus.ObserverVec, next http.Handler,
o.apply(hOpts)
}
code, method := checkLabels(obs)
// Curry the observer with dynamic labels before checking the remaining labels.
code, method := checkLabels(obs.MustCurryWith(hOpts.emptyDynamicLabels()))
if code {
return func(w http.ResponseWriter, r *http.Request) {
d := newDelegator(w, nil)
next.ServeHTTP(d, r)
size := computeApproximateRequestSize(r)
observeWithExemplar(
obs.With(labels(code, method, r.Method, d.Status(), hOpts.extraMethods...)),
float64(size),
hOpts.getExemplarFn(r.Context()),
)
l := labels(code, method, r.Method, d.Status(), hOpts.extraMethods...)
for label, resolve := range hOpts.extraLabelsFromCtx {
l[label] = resolve(r.Context())
}
observeWithExemplar(obs.With(l), float64(size), hOpts.getExemplarFn(r.Context()))
}
}
return func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(w, r)
size := computeApproximateRequestSize(r)
observeWithExemplar(
obs.With(labels(code, method, r.Method, 0, hOpts.extraMethods...)),
float64(size),
hOpts.getExemplarFn(r.Context()),
)
l := labels(code, method, r.Method, 0, hOpts.extraMethods...)
for label, resolve := range hOpts.extraLabelsFromCtx {
l[label] = resolve(r.Context())
}
observeWithExemplar(obs.With(l), float64(size), hOpts.getExemplarFn(r.Context()))
}
}
@@ -281,16 +288,18 @@ func InstrumentHandlerResponseSize(obs prometheus.ObserverVec, next http.Handler
o.apply(hOpts)
}
code, method := checkLabels(obs)
// Curry the observer with dynamic labels before checking the remaining labels.
code, method := checkLabels(obs.MustCurryWith(hOpts.emptyDynamicLabels()))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
d := newDelegator(w, nil)
next.ServeHTTP(d, r)
observeWithExemplar(
obs.With(labels(code, method, r.Method, d.Status(), hOpts.extraMethods...)),
float64(d.Written()),
hOpts.getExemplarFn(r.Context()),
)
l := labels(code, method, r.Method, d.Status(), hOpts.extraMethods...)
for label, resolve := range hOpts.extraLabelsFromCtx {
l[label] = resolve(r.Context())
}
observeWithExemplar(obs.With(l), float64(d.Written()), hOpts.getExemplarFn(r.Context()))
})
}
@@ -380,16 +389,13 @@ func isLabelCurried(c prometheus.Collector, label string) bool {
return true
}
// emptyLabels is a one-time allocation for non-partitioned metrics to avoid
// unnecessary allocations on each request.
var emptyLabels = prometheus.Labels{}
func labels(code, method bool, reqMethod string, status int, extraMethods ...string) prometheus.Labels {
if !(code || method) {
return emptyLabels
}
labels := prometheus.Labels{}
if !(code || method) {
return labels
}
if code {
labels["code"] = sanitizeCode(status)
}

View File

@@ -24,14 +24,32 @@ type Option interface {
apply(*options)
}
// LabelValueFromCtx are used to compute the label value from request context.
// Context can be filled with values from request through middleware.
type LabelValueFromCtx func(ctx context.Context) string
// options store options for both a handler or round tripper.
type options struct {
extraMethods []string
getExemplarFn func(requestCtx context.Context) prometheus.Labels
extraMethods []string
getExemplarFn func(requestCtx context.Context) prometheus.Labels
extraLabelsFromCtx map[string]LabelValueFromCtx
}
func defaultOptions() *options {
return &options{getExemplarFn: func(ctx context.Context) prometheus.Labels { return nil }}
return &options{
getExemplarFn: func(ctx context.Context) prometheus.Labels { return nil },
extraLabelsFromCtx: map[string]LabelValueFromCtx{},
}
}
func (o *options) emptyDynamicLabels() prometheus.Labels {
labels := prometheus.Labels{}
for label := range o.extraLabelsFromCtx {
labels[label] = ""
}
return labels
}
type optionApplyFunc func(*options)
@@ -48,11 +66,19 @@ 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
})
}
// WithLabelFromCtx registers a label for dynamic resolution with access to context.
// See the example for ExampleInstrumentHandlerWithLabelResolver for example usage
func WithLabelFromCtx(name string, valueFn LabelValueFromCtx) Option {
return optionApplyFunc(func(o *options) {
o.extraLabelsFromCtx[name] = valueFn
})
}

View File

@@ -21,18 +21,17 @@ import (
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"unicode/utf8"
"github.com/cespare/xxhash/v2"
//nolint:staticcheck // Ignore SA1019. Need to keep deprecated package for compatibility.
"github.com/golang/protobuf/proto"
"github.com/prometheus/common/expfmt"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/client_golang/prometheus/internal"
"github.com/cespare/xxhash/v2"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/common/expfmt"
"google.golang.org/protobuf/proto"
)
const (
@@ -549,7 +548,7 @@ func (r *Registry) Gather() ([]*dto.MetricFamily, error) {
goroutineBudget--
runtime.Gosched()
}
// Once both checkedMetricChan and uncheckdMetricChan are closed
// Once both checkedMetricChan and uncheckedMetricChan are closed
// and drained, the contraption above will nil out cmc and umc,
// and then we can leave the collect loop here.
if cmc == nil && umc == nil {
@@ -933,6 +932,10 @@ func checkMetricConsistency(
h.WriteString(lp.GetValue())
h.Write(separatorByteSlice)
}
if dtoMetric.TimestampMs != nil {
h.WriteString(strconv.FormatInt(*(dtoMetric.TimestampMs), 10))
h.Write(separatorByteSlice)
}
hSum := h.Sum64()
if _, exists := metricHashes[hSum]; exists {
return fmt.Errorf(
@@ -960,7 +963,7 @@ func checkDescConsistency(
// Is the desc consistent with the content of the metric?
lpsFromDesc := make([]*dto.LabelPair, len(desc.constLabelPairs), len(dtoMetric.Label))
copy(lpsFromDesc, desc.constLabelPairs)
for _, l := range desc.variableLabels {
for _, l := range desc.variableLabels.names {
lpsFromDesc = append(lpsFromDesc, &dto.LabelPair{
Name: proto.String(l),
})

View File

@@ -22,11 +22,11 @@ import (
"sync/atomic"
"time"
"github.com/beorn7/perks/quantile"
//nolint:staticcheck // Ignore SA1019. Need to keep deprecated package for compatibility.
"github.com/golang/protobuf/proto"
dto "github.com/prometheus/client_model/go"
"github.com/beorn7/perks/quantile"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/timestamppb"
)
// quantileLabel is used for the label that defines the quantile in a
@@ -146,6 +146,21 @@ type SummaryOpts struct {
// is the internal buffer size of the underlying package
// "github.com/bmizerany/perks/quantile").
BufCap uint32
// now is for testing purposes, by default it's time.Now.
now func() time.Time
}
// SummaryVecOpts bundles the options to create a SummaryVec metric.
// It is mandatory to set SummaryOpts, see there for mandatory fields. VariableLabels
// is optional and can safely be left to its default value.
type SummaryVecOpts struct {
SummaryOpts
// VariableLabels are used to partition the metric vector by the given set
// of labels. Each label value will be constrained with the optional Constraint
// function, if provided.
VariableLabels ConstrainableLabels
}
// Problem with the sliding-window decay algorithm... The Merge method of
@@ -177,11 +192,11 @@ func NewSummary(opts SummaryOpts) Summary {
}
func newSummary(desc *Desc, opts SummaryOpts, labelValues ...string) Summary {
if len(desc.variableLabels) != len(labelValues) {
panic(makeInconsistentCardinalityError(desc.fqName, desc.variableLabels, labelValues))
if len(desc.variableLabels.names) != len(labelValues) {
panic(makeInconsistentCardinalityError(desc.fqName, desc.variableLabels.names, labelValues))
}
for _, n := range desc.variableLabels {
for _, n := range desc.variableLabels.names {
if n == quantileLabel {
panic(errQuantileLabelNotAllowed)
}
@@ -211,6 +226,9 @@ func newSummary(desc *Desc, opts SummaryOpts, labelValues ...string) Summary {
opts.BufCap = DefBufCap
}
if opts.now == nil {
opts.now = time.Now
}
if len(opts.Objectives) == 0 {
// Use the lock-free implementation of a Summary without objectives.
s := &noObjectivesSummary{
@@ -219,6 +237,7 @@ func newSummary(desc *Desc, opts SummaryOpts, labelValues ...string) Summary {
counts: [2]*summaryCounts{{}, {}},
}
s.init(s) // Init self-collection.
s.createdTs = timestamppb.New(opts.now())
return s
}
@@ -234,7 +253,7 @@ func newSummary(desc *Desc, opts SummaryOpts, labelValues ...string) Summary {
coldBuf: make([]float64, 0, opts.BufCap),
streamDuration: opts.MaxAge / time.Duration(opts.AgeBuckets),
}
s.headStreamExpTime = time.Now().Add(s.streamDuration)
s.headStreamExpTime = opts.now().Add(s.streamDuration)
s.hotBufExpTime = s.headStreamExpTime
for i := uint32(0); i < opts.AgeBuckets; i++ {
@@ -248,6 +267,7 @@ func newSummary(desc *Desc, opts SummaryOpts, labelValues ...string) Summary {
sort.Float64s(s.sortedObjectives)
s.init(s) // Init self-collection.
s.createdTs = timestamppb.New(opts.now())
return s
}
@@ -275,6 +295,8 @@ type summary struct {
headStream *quantile.Stream
headStreamIdx int
headStreamExpTime, hotBufExpTime time.Time
createdTs *timestamppb.Timestamp
}
func (s *summary) Desc() *Desc {
@@ -296,7 +318,9 @@ func (s *summary) Observe(v float64) {
}
func (s *summary) Write(out *dto.Metric) error {
sum := &dto.Summary{}
sum := &dto.Summary{
CreatedTimestamp: s.createdTs,
}
qs := make([]*dto.Quantile, 0, len(s.objectives))
s.bufMtx.Lock()
@@ -429,6 +453,8 @@ type noObjectivesSummary struct {
counts [2]*summaryCounts
labelPairs []*dto.LabelPair
createdTs *timestamppb.Timestamp
}
func (s *noObjectivesSummary) Desc() *Desc {
@@ -479,8 +505,9 @@ func (s *noObjectivesSummary) Write(out *dto.Metric) error {
}
sum := &dto.Summary{
SampleCount: proto.Uint64(count),
SampleSum: proto.Float64(math.Float64frombits(atomic.LoadUint64(&coldCounts.sumBits))),
SampleCount: proto.Uint64(count),
SampleSum: proto.Float64(math.Float64frombits(atomic.LoadUint64(&coldCounts.sumBits))),
CreatedTimestamp: s.createdTs,
}
out.Summary = sum
@@ -530,20 +557,28 @@ type SummaryVec struct {
// it is handled by the Prometheus server internally, “quantile” is an illegal
// label name. NewSummaryVec will panic if this label name is used.
func NewSummaryVec(opts SummaryOpts, labelNames []string) *SummaryVec {
for _, ln := range labelNames {
return V2.NewSummaryVec(SummaryVecOpts{
SummaryOpts: opts,
VariableLabels: UnconstrainedLabels(labelNames),
})
}
// NewSummaryVec creates a new SummaryVec based on the provided SummaryVecOpts.
func (v2) NewSummaryVec(opts SummaryVecOpts) *SummaryVec {
for _, ln := range opts.VariableLabels.labelNames() {
if ln == quantileLabel {
panic(errQuantileLabelNotAllowed)
}
}
desc := NewDesc(
desc := V2.NewDesc(
BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
opts.Help,
labelNames,
opts.VariableLabels,
opts.ConstLabels,
)
return &SummaryVec{
MetricVec: NewMetricVec(desc, func(lvs ...string) Metric {
return newSummary(desc, opts, lvs...)
return newSummary(desc, opts.SummaryOpts, lvs...)
}),
}
}
@@ -662,6 +697,7 @@ type constSummary struct {
sum float64
quantiles map[float64]float64
labelPairs []*dto.LabelPair
createdTs *timestamppb.Timestamp
}
func (s *constSummary) Desc() *Desc {
@@ -669,7 +705,9 @@ func (s *constSummary) Desc() *Desc {
}
func (s *constSummary) Write(out *dto.Metric) error {
sum := &dto.Summary{}
sum := &dto.Summary{
CreatedTimestamp: s.createdTs,
}
qs := make([]*dto.Quantile, 0, len(s.quantiles))
sum.SampleCount = proto.Uint64(s.count)
@@ -718,7 +756,7 @@ func NewConstSummary(
if desc.err != nil {
return nil, desc.err
}
if err := validateLabelValues(labelValues, len(desc.variableLabels)); err != nil {
if err := validateLabelValues(labelValues, len(desc.variableLabels.names)); err != nil {
return nil, err
}
return &constSummary{

View File

@@ -1,4 +1,4 @@
// Copyright 2016 The Prometheus Authors
// Copyright 2020 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
@@ -11,22 +11,23 @@
// See the License for the specific language governing permissions and
// limitations under the License.
package fileutil
package promlint
import "os"
import dto "github.com/prometheus/client_model/go"
type plan9Lock struct {
f *os.File
// A Problem is an issue detected by a linter.
type Problem struct {
// The name of the metric indicated by this Problem.
Metric string
// A description of the issue for this Problem.
Text string
}
func (l *plan9Lock) Release() error {
return l.f.Close()
}
func newLock(fileName string) (Releaser, error) {
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, os.ModeExclusive|0o666)
if err != nil {
return nil, err
// newProblem is helper function to create a Problem.
func newProblem(mf *dto.MetricFamily, text string) Problem {
return Problem{
Metric: mf.GetName(),
Text: text,
}
return &plan9Lock{f}, nil
}

View File

@@ -16,15 +16,11 @@ package promlint
import (
"errors"
"fmt"
"io"
"regexp"
"sort"
"strings"
"github.com/prometheus/common/expfmt"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/common/expfmt"
)
// A Linter is a Prometheus metrics linter. It identifies issues with metric
@@ -37,23 +33,8 @@ type Linter struct {
// of them.
r io.Reader
mfs []*dto.MetricFamily
}
// A Problem is an issue detected by a Linter.
type Problem struct {
// The name of the metric indicated by this Problem.
Metric string
// A description of the issue for this Problem.
Text string
}
// newProblem is helper function to create a Problem.
func newProblem(mf *dto.MetricFamily, text string) Problem {
return Problem{
Metric: mf.GetName(),
Text: text,
}
customValidations []Validation
}
// New creates a new Linter that reads an input stream of Prometheus metrics in
@@ -72,6 +53,14 @@ func NewWithMetricFamilies(mfs []*dto.MetricFamily) *Linter {
}
}
// AddCustomValidations adds custom validations to the linter.
func (l *Linter) AddCustomValidations(vs ...Validation) {
if l.customValidations == nil {
l.customValidations = make([]Validation, 0, len(vs))
}
l.customValidations = append(l.customValidations, vs...)
}
// Lint performs a linting pass, returning a slice of Problems indicating any
// issues found in the metrics stream. The slice is sorted by metric name
// and issue description.
@@ -91,11 +80,11 @@ func (l *Linter) Lint() ([]Problem, error) {
return nil, err
}
problems = append(problems, lint(mf)...)
problems = append(problems, l.lint(mf)...)
}
}
for _, mf := range l.mfs {
problems = append(problems, lint(mf)...)
problems = append(problems, l.lint(mf)...)
}
// Ensure deterministic output.
@@ -110,278 +99,25 @@ func (l *Linter) Lint() ([]Problem, error) {
}
// lint is the entry point for linting a single metric.
func lint(mf *dto.MetricFamily) []Problem {
fns := []func(mf *dto.MetricFamily) []Problem{
lintHelp,
lintMetricUnits,
lintCounter,
lintHistogramSummaryReserved,
lintMetricTypeInName,
lintReservedChars,
lintCamelCase,
lintUnitAbbreviations,
func (l *Linter) lint(mf *dto.MetricFamily) []Problem {
var problems []Problem
for _, fn := range defaultValidations {
errs := fn(mf)
for _, err := range errs {
problems = append(problems, newProblem(mf, err.Error()))
}
}
var problems []Problem
for _, fn := range fns {
problems = append(problems, fn(mf)...)
if l.customValidations != nil {
for _, fn := range l.customValidations {
errs := fn(mf)
for _, err := range errs {
problems = append(problems, newProblem(mf, err.Error()))
}
}
}
// TODO(mdlayher): lint rules for specific metrics types.
return problems
}
// lintHelp detects issues related to the help text for a metric.
func lintHelp(mf *dto.MetricFamily) []Problem {
var problems []Problem
// Expect all metrics to have help text available.
if mf.Help == nil {
problems = append(problems, newProblem(mf, "no help text"))
}
return problems
}
// lintMetricUnits detects issues with metric unit names.
func lintMetricUnits(mf *dto.MetricFamily) []Problem {
var problems []Problem
unit, base, ok := metricUnits(*mf.Name)
if !ok {
// No known units detected.
return nil
}
// Unit is already a base unit.
if unit == base {
return nil
}
problems = append(problems, newProblem(mf, fmt.Sprintf("use base unit %q instead of %q", base, unit)))
return problems
}
// lintCounter detects issues specific to counters, as well as patterns that should
// only be used with counters.
func lintCounter(mf *dto.MetricFamily) []Problem {
var problems []Problem
isCounter := mf.GetType() == dto.MetricType_COUNTER
isUntyped := mf.GetType() == dto.MetricType_UNTYPED
hasTotalSuffix := strings.HasSuffix(mf.GetName(), "_total")
switch {
case isCounter && !hasTotalSuffix:
problems = append(problems, newProblem(mf, `counter metrics should have "_total" suffix`))
case !isUntyped && !isCounter && hasTotalSuffix:
problems = append(problems, newProblem(mf, `non-counter metrics should not have "_total" suffix`))
}
return problems
}
// lintHistogramSummaryReserved detects when other types of metrics use names or labels
// reserved for use by histograms and/or summaries.
func lintHistogramSummaryReserved(mf *dto.MetricFamily) []Problem {
// These rules do not apply to untyped metrics.
t := mf.GetType()
if t == dto.MetricType_UNTYPED {
return nil
}
var problems []Problem
isHistogram := t == dto.MetricType_HISTOGRAM
isSummary := t == dto.MetricType_SUMMARY
n := mf.GetName()
if !isHistogram && strings.HasSuffix(n, "_bucket") {
problems = append(problems, newProblem(mf, `non-histogram metrics should not have "_bucket" suffix`))
}
if !isHistogram && !isSummary && strings.HasSuffix(n, "_count") {
problems = append(problems, newProblem(mf, `non-histogram and non-summary metrics should not have "_count" suffix`))
}
if !isHistogram && !isSummary && strings.HasSuffix(n, "_sum") {
problems = append(problems, newProblem(mf, `non-histogram and non-summary metrics should not have "_sum" suffix`))
}
for _, m := range mf.GetMetric() {
for _, l := range m.GetLabel() {
ln := l.GetName()
if !isHistogram && ln == "le" {
problems = append(problems, newProblem(mf, `non-histogram metrics should not have "le" label`))
}
if !isSummary && ln == "quantile" {
problems = append(problems, newProblem(mf, `non-summary metrics should not have "quantile" label`))
}
}
}
return problems
}
// lintMetricTypeInName detects when metric types are included in the metric name.
func lintMetricTypeInName(mf *dto.MetricFamily) []Problem {
var problems []Problem
n := strings.ToLower(mf.GetName())
for i, t := range dto.MetricType_name {
if i == int32(dto.MetricType_UNTYPED) {
continue
}
typename := strings.ToLower(t)
if strings.Contains(n, "_"+typename+"_") || strings.HasSuffix(n, "_"+typename) {
problems = append(problems, newProblem(mf, fmt.Sprintf(`metric name should not include type '%s'`, typename)))
}
}
return problems
}
// lintReservedChars detects colons in metric names.
func lintReservedChars(mf *dto.MetricFamily) []Problem {
var problems []Problem
if strings.Contains(mf.GetName(), ":") {
problems = append(problems, newProblem(mf, "metric names should not contain ':'"))
}
return problems
}
var camelCase = regexp.MustCompile(`[a-z][A-Z]`)
// lintCamelCase detects metric names and label names written in camelCase.
func lintCamelCase(mf *dto.MetricFamily) []Problem {
var problems []Problem
if camelCase.FindString(mf.GetName()) != "" {
problems = append(problems, newProblem(mf, "metric names should be written in 'snake_case' not 'camelCase'"))
}
for _, m := range mf.GetMetric() {
for _, l := range m.GetLabel() {
if camelCase.FindString(l.GetName()) != "" {
problems = append(problems, newProblem(mf, "label names should be written in 'snake_case' not 'camelCase'"))
}
}
}
return problems
}
// lintUnitAbbreviations detects abbreviated units in the metric name.
func lintUnitAbbreviations(mf *dto.MetricFamily) []Problem {
var problems []Problem
n := strings.ToLower(mf.GetName())
for _, s := range unitAbbreviations {
if strings.Contains(n, "_"+s+"_") || strings.HasSuffix(n, "_"+s) {
problems = append(problems, newProblem(mf, "metric names should not contain abbreviated units"))
}
}
return problems
}
// metricUnits attempts to detect known unit types used as part of a metric name,
// e.g. "foo_bytes_total" or "bar_baz_milligrams".
func metricUnits(m string) (unit, base string, ok bool) {
ss := strings.Split(m, "_")
for unit, base := range units {
// Also check for "no prefix".
for _, p := range append(unitPrefixes, "") {
for _, s := range ss {
// Attempt to explicitly match a known unit with a known prefix,
// as some words may look like "units" when matching suffix.
//
// As an example, "thermometers" should not match "meters", but
// "kilometers" should.
if s == p+unit {
return p + unit, base, true
}
}
}
}
return "", "", false
}
// Units and their possible prefixes recognized by this library. More can be
// added over time as needed.
var (
// map a unit to the appropriate base unit.
units = map[string]string{
// Base units.
"amperes": "amperes",
"bytes": "bytes",
"celsius": "celsius", // Also allow Celsius because it is common in typical Prometheus use cases.
"grams": "grams",
"joules": "joules",
"kelvin": "kelvin", // SI base unit, used in special cases (e.g. color temperature, scientific measurements).
"meters": "meters", // Both American and international spelling permitted.
"metres": "metres",
"seconds": "seconds",
"volts": "volts",
// Non base units.
// Time.
"minutes": "seconds",
"hours": "seconds",
"days": "seconds",
"weeks": "seconds",
// Temperature.
"kelvins": "kelvin",
"fahrenheit": "celsius",
"rankine": "celsius",
// Length.
"inches": "meters",
"yards": "meters",
"miles": "meters",
// Bytes.
"bits": "bytes",
// Energy.
"calories": "joules",
// Mass.
"pounds": "grams",
"ounces": "grams",
}
unitPrefixes = []string{
"pico",
"nano",
"micro",
"milli",
"centi",
"deci",
"deca",
"hecto",
"kilo",
"kibi",
"mega",
"mibi",
"giga",
"gibi",
"tera",
"tebi",
"peta",
"pebi",
}
// Common abbreviations that we'd like to discourage.
unitAbbreviations = []string{
"s",
"ms",
"us",
"ns",
"sec",
"b",
"kb",
"mb",
"gb",
"tb",
"pb",
"m",
"h",
"d",
}
)

View File

@@ -1,5 +1,4 @@
// Copyright 2016 The etcd Authors
//
// Copyright 2020 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
@@ -12,17 +11,23 @@
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build darwin
// +build darwin
package fileutil
package promlint
import (
"os"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/client_golang/prometheus/testutil/promlint/validations"
)
// Fdatasync on darwin platform invokes fcntl(F_FULLFSYNC) for actual persistence
// on physical drive media.
func Fdatasync(f *os.File) error {
return f.Sync()
type Validation = func(mf *dto.MetricFamily) []error
var defaultValidations = []Validation{
validations.LintHelp,
validations.LintMetricUnits,
validations.LintCounter,
validations.LintHistogramSummaryReserved,
validations.LintMetricTypeInName,
validations.LintReservedChars,
validations.LintCamelCase,
validations.LintUnitAbbreviations,
}

View File

@@ -0,0 +1,40 @@
// Copyright 2020 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 validations
import (
"errors"
"strings"
dto "github.com/prometheus/client_model/go"
)
// LintCounter detects issues specific to counters, as well as patterns that should
// only be used with counters.
func LintCounter(mf *dto.MetricFamily) []error {
var problems []error
isCounter := mf.GetType() == dto.MetricType_COUNTER
isUntyped := mf.GetType() == dto.MetricType_UNTYPED
hasTotalSuffix := strings.HasSuffix(mf.GetName(), "_total")
switch {
case isCounter && !hasTotalSuffix:
problems = append(problems, errors.New(`counter metrics should have "_total" suffix`))
case !isUntyped && !isCounter && hasTotalSuffix:
problems = append(problems, errors.New(`non-counter metrics should not have "_total" suffix`))
}
return problems
}

View File

@@ -0,0 +1,101 @@
// Copyright 2020 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 validations
import (
"errors"
"fmt"
"regexp"
"strings"
dto "github.com/prometheus/client_model/go"
)
var camelCase = regexp.MustCompile(`[a-z][A-Z]`)
// LintMetricUnits detects issues with metric unit names.
func LintMetricUnits(mf *dto.MetricFamily) []error {
var problems []error
unit, base, ok := metricUnits(*mf.Name)
if !ok {
// No known units detected.
return nil
}
// Unit is already a base unit.
if unit == base {
return nil
}
problems = append(problems, fmt.Errorf("use base unit %q instead of %q", base, unit))
return problems
}
// LintMetricTypeInName detects when metric types are included in the metric name.
func LintMetricTypeInName(mf *dto.MetricFamily) []error {
var problems []error
n := strings.ToLower(mf.GetName())
for i, t := range dto.MetricType_name {
if i == int32(dto.MetricType_UNTYPED) {
continue
}
typename := strings.ToLower(t)
if strings.Contains(n, "_"+typename+"_") || strings.HasSuffix(n, "_"+typename) {
problems = append(problems, fmt.Errorf(`metric name should not include type '%s'`, typename))
}
}
return problems
}
// LintReservedChars detects colons in metric names.
func LintReservedChars(mf *dto.MetricFamily) []error {
var problems []error
if strings.Contains(mf.GetName(), ":") {
problems = append(problems, errors.New("metric names should not contain ':'"))
}
return problems
}
// LintCamelCase detects metric names and label names written in camelCase.
func LintCamelCase(mf *dto.MetricFamily) []error {
var problems []error
if camelCase.FindString(mf.GetName()) != "" {
problems = append(problems, errors.New("metric names should be written in 'snake_case' not 'camelCase'"))
}
for _, m := range mf.GetMetric() {
for _, l := range m.GetLabel() {
if camelCase.FindString(l.GetName()) != "" {
problems = append(problems, errors.New("label names should be written in 'snake_case' not 'camelCase'"))
}
}
}
return problems
}
// LintUnitAbbreviations detects abbreviated units in the metric name.
func LintUnitAbbreviations(mf *dto.MetricFamily) []error {
var problems []error
n := strings.ToLower(mf.GetName())
for _, s := range unitAbbreviations {
if strings.Contains(n, "_"+s+"_") || strings.HasSuffix(n, "_"+s) {
problems = append(problems, errors.New("metric names should not contain abbreviated units"))
}
}
return problems
}

View File

@@ -1,5 +1,4 @@
// Copyright 2016 The etcd Authors
//
// Copyright 2020 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
@@ -12,19 +11,22 @@
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build linux
// +build linux
package fileutil
package validations
import (
"os"
"syscall"
"errors"
dto "github.com/prometheus/client_model/go"
)
// Fdatasync is similar to fsync(), but does not flush modified metadata
// unless that metadata is needed in order to allow a subsequent data retrieval
// to be correctly handled.
func Fdatasync(f *os.File) error {
return syscall.Fdatasync(int(f.Fd()))
// LintHelp detects issues related to the help text for a metric.
func LintHelp(mf *dto.MetricFamily) []error {
var problems []error
// Expect all metrics to have help text available.
if mf.Help == nil {
problems = append(problems, errors.New("no help text"))
}
return problems
}

View File

@@ -0,0 +1,63 @@
// Copyright 2020 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 validations
import (
"errors"
"strings"
dto "github.com/prometheus/client_model/go"
)
// LintHistogramSummaryReserved detects when other types of metrics use names or labels
// reserved for use by histograms and/or summaries.
func LintHistogramSummaryReserved(mf *dto.MetricFamily) []error {
// These rules do not apply to untyped metrics.
t := mf.GetType()
if t == dto.MetricType_UNTYPED {
return nil
}
var problems []error
isHistogram := t == dto.MetricType_HISTOGRAM
isSummary := t == dto.MetricType_SUMMARY
n := mf.GetName()
if !isHistogram && strings.HasSuffix(n, "_bucket") {
problems = append(problems, errors.New(`non-histogram metrics should not have "_bucket" suffix`))
}
if !isHistogram && !isSummary && strings.HasSuffix(n, "_count") {
problems = append(problems, errors.New(`non-histogram and non-summary metrics should not have "_count" suffix`))
}
if !isHistogram && !isSummary && strings.HasSuffix(n, "_sum") {
problems = append(problems, errors.New(`non-histogram and non-summary metrics should not have "_sum" suffix`))
}
for _, m := range mf.GetMetric() {
for _, l := range m.GetLabel() {
ln := l.GetName()
if !isHistogram && ln == "le" {
problems = append(problems, errors.New(`non-histogram metrics should not have "le" label`))
}
if !isSummary && ln == "quantile" {
problems = append(problems, errors.New(`non-summary metrics should not have "quantile" label`))
}
}
}
return problems
}

View File

@@ -0,0 +1,118 @@
// Copyright 2020 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 validations
import "strings"
// Units and their possible prefixes recognized by this library. More can be
// added over time as needed.
var (
// map a unit to the appropriate base unit.
units = map[string]string{
// Base units.
"amperes": "amperes",
"bytes": "bytes",
"celsius": "celsius", // Also allow Celsius because it is common in typical Prometheus use cases.
"grams": "grams",
"joules": "joules",
"kelvin": "kelvin", // SI base unit, used in special cases (e.g. color temperature, scientific measurements).
"meters": "meters", // Both American and international spelling permitted.
"metres": "metres",
"seconds": "seconds",
"volts": "volts",
// Non base units.
// Time.
"minutes": "seconds",
"hours": "seconds",
"days": "seconds",
"weeks": "seconds",
// Temperature.
"kelvins": "kelvin",
"fahrenheit": "celsius",
"rankine": "celsius",
// Length.
"inches": "meters",
"yards": "meters",
"miles": "meters",
// Bytes.
"bits": "bytes",
// Energy.
"calories": "joules",
// Mass.
"pounds": "grams",
"ounces": "grams",
}
unitPrefixes = []string{
"pico",
"nano",
"micro",
"milli",
"centi",
"deci",
"deca",
"hecto",
"kilo",
"kibi",
"mega",
"mibi",
"giga",
"gibi",
"tera",
"tebi",
"peta",
"pebi",
}
// Common abbreviations that we'd like to discourage.
unitAbbreviations = []string{
"s",
"ms",
"us",
"ns",
"sec",
"b",
"kb",
"mb",
"gb",
"tb",
"pb",
"m",
"h",
"d",
}
)
// metricUnits attempts to detect known unit types used as part of a metric name,
// e.g. "foo_bytes_total" or "bar_baz_milligrams".
func metricUnits(m string) (unit, base string, ok bool) {
ss := strings.Split(m, "_")
for _, s := range ss {
if base, found := units[s]; found {
return s, base, true
}
for _, p := range unitPrefixes {
if strings.HasPrefix(s, p) {
if base, found := units[s[len(p):]]; found {
return s, base, true
}
}
}
}
return "", "", false
}

View File

@@ -47,6 +47,7 @@ import (
"github.com/davecgh/go-spew/spew"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/common/expfmt"
"google.golang.org/protobuf/proto"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/internal"
@@ -230,6 +231,20 @@ func convertReaderToMetricFamily(reader io.Reader) ([]*dto.MetricFamily, error)
return nil, fmt.Errorf("converting reader to metric families failed: %w", err)
}
// The text protocol handles empty help fields inconsistently. When
// encoding, any non-nil value, include the empty string, produces a
// "# HELP" line. But when decoding, the help field is only set to a
// non-nil value if the "# HELP" line contains a non-empty value.
//
// Because metrics in a registry always have non-nil help fields, populate
// any nil help fields in the parsed metrics with the empty string so that
// when we compare text encodings, the results are consistent.
for _, metric := range notNormalized {
if metric.Help == nil {
metric.Help = proto.String("")
}
}
return internal.NormalizeMetricFamilies(notNormalized), nil
}
@@ -238,6 +253,7 @@ func convertReaderToMetricFamily(reader io.Reader) ([]*dto.MetricFamily, error)
func compareMetricFamilies(got, expected []*dto.MetricFamily, metricNames ...string) error {
if metricNames != nil {
got = filterMetrics(got, metricNames)
expected = filterMetrics(expected, metricNames)
}
return compare(got, expected)

View File

@@ -23,7 +23,9 @@ type Timer struct {
}
// NewTimer creates a new Timer. The provided Observer is used to observe a
// duration in seconds. Timer is usually used to time a function call in the
// duration in seconds. If the Observer implements ExemplarObserver, passing exemplar
// later on will be also supported.
// Timer is usually used to time a function call in the
// following way:
//
// func TimeMe() {
@@ -31,6 +33,14 @@ type Timer struct {
// defer timer.ObserveDuration()
// // Do actual work.
// }
//
// or
//
// func TimeMeWithExemplar() {
// timer := NewTimer(myHistogram)
// defer timer.ObserveDurationWithExemplar(exemplar)
// // Do actual work.
// }
func NewTimer(o Observer) *Timer {
return &Timer{
begin: time.Now(),
@@ -53,3 +63,19 @@ func (t *Timer) ObserveDuration() time.Duration {
}
return d
}
// ObserveDurationWithExemplar is like ObserveDuration, but it will also
// observe exemplar with the duration unless exemplar is nil or provided Observer can't
// be casted to ExemplarObserver.
func (t *Timer) ObserveDurationWithExemplar(exemplar Labels) time.Duration {
d := time.Since(t.begin)
eo, ok := t.observer.(ExemplarObserver)
if ok && exemplar != nil {
eo.ObserveWithExemplar(d.Seconds(), exemplar)
return d
}
if t.observer != nil {
t.observer.Observe(d.Seconds())
}
return d
}

View File

@@ -14,18 +14,17 @@
package prometheus
import (
"errors"
"fmt"
"sort"
"time"
"unicode/utf8"
//nolint:staticcheck // Ignore SA1019. Need to keep deprecated package for compatibility.
"github.com/golang/protobuf/proto"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/prometheus/client_golang/prometheus/internal"
dto "github.com/prometheus/client_model/go"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/timestamppb"
)
// ValueType is an enumeration of metric types that represent a simple value.
@@ -93,7 +92,7 @@ func (v *valueFunc) Desc() *Desc {
}
func (v *valueFunc) Write(out *dto.Metric) error {
return populateMetric(v.valType, v.function(), v.labelPairs, nil, out)
return populateMetric(v.valType, v.function(), v.labelPairs, nil, out, nil)
}
// NewConstMetric returns a metric with one fixed value that cannot be
@@ -107,12 +106,12 @@ func NewConstMetric(desc *Desc, valueType ValueType, value float64, labelValues
if desc.err != nil {
return nil, desc.err
}
if err := validateLabelValues(labelValues, len(desc.variableLabels)); err != nil {
if err := validateLabelValues(labelValues, len(desc.variableLabels.names)); err != nil {
return nil, err
}
metric := &dto.Metric{}
if err := populateMetric(valueType, value, MakeLabelPairs(desc, labelValues), nil, metric); err != nil {
if err := populateMetric(valueType, value, MakeLabelPairs(desc, labelValues), nil, metric, nil); err != nil {
return nil, err
}
@@ -132,6 +131,43 @@ func MustNewConstMetric(desc *Desc, valueType ValueType, value float64, labelVal
return m
}
// NewConstMetricWithCreatedTimestamp does the same thing as NewConstMetric, but generates Counters
// with created timestamp set and returns an error for other metric types.
func NewConstMetricWithCreatedTimestamp(desc *Desc, valueType ValueType, value float64, ct time.Time, labelValues ...string) (Metric, error) {
if desc.err != nil {
return nil, desc.err
}
if err := validateLabelValues(labelValues, len(desc.variableLabels.names)); err != nil {
return nil, err
}
switch valueType {
case CounterValue:
break
default:
return nil, errors.New("created timestamps are only supported for counters")
}
metric := &dto.Metric{}
if err := populateMetric(valueType, value, MakeLabelPairs(desc, labelValues), nil, metric, timestamppb.New(ct)); err != nil {
return nil, err
}
return &constMetric{
desc: desc,
metric: metric,
}, nil
}
// MustNewConstMetricWithCreatedTimestamp is a version of NewConstMetricWithCreatedTimestamp that panics where
// NewConstMetricWithCreatedTimestamp would have returned an error.
func MustNewConstMetricWithCreatedTimestamp(desc *Desc, valueType ValueType, value float64, ct time.Time, labelValues ...string) Metric {
m, err := NewConstMetricWithCreatedTimestamp(desc, valueType, value, ct, labelValues...)
if err != nil {
panic(err)
}
return m
}
type constMetric struct {
desc *Desc
metric *dto.Metric
@@ -155,11 +191,12 @@ func populateMetric(
labelPairs []*dto.LabelPair,
e *dto.Exemplar,
m *dto.Metric,
ct *timestamppb.Timestamp,
) error {
m.Label = labelPairs
switch t {
case CounterValue:
m.Counter = &dto.Counter{Value: proto.Float64(v), Exemplar: e}
m.Counter = &dto.Counter{Value: proto.Float64(v), Exemplar: e, CreatedTimestamp: ct}
case GaugeValue:
m.Gauge = &dto.Gauge{Value: proto.Float64(v)}
case UntypedValue:
@@ -178,19 +215,19 @@ func populateMetric(
// This function is only needed for custom Metric implementations. See MetricVec
// example.
func MakeLabelPairs(desc *Desc, labelValues []string) []*dto.LabelPair {
totalLen := len(desc.variableLabels) + len(desc.constLabelPairs)
totalLen := len(desc.variableLabels.names) + len(desc.constLabelPairs)
if totalLen == 0 {
// Super fast path.
return nil
}
if len(desc.variableLabels) == 0 {
if len(desc.variableLabels.names) == 0 {
// Moderately fast path.
return desc.constLabelPairs
}
labelPairs := make([]*dto.LabelPair, 0, totalLen)
for i, n := range desc.variableLabels {
for i, l := range desc.variableLabels.names {
labelPairs = append(labelPairs, &dto.LabelPair{
Name: proto.String(n),
Name: proto.String(l),
Value: proto.String(labelValues[i]),
})
}

View File

@@ -72,6 +72,8 @@ func NewMetricVec(desc *Desc, newMetric func(lvs ...string) Metric) *MetricVec {
// with a performance overhead (for creating and processing the Labels map).
// See also the CounterVec example.
func (m *MetricVec) DeleteLabelValues(lvs ...string) bool {
lvs = constrainLabelValues(m.desc, lvs, m.curry)
h, err := m.hashLabelValues(lvs)
if err != nil {
return false
@@ -91,6 +93,9 @@ func (m *MetricVec) DeleteLabelValues(lvs ...string) bool {
// This method is used for the same purpose as DeleteLabelValues(...string). See
// there for pros and cons of the two methods.
func (m *MetricVec) Delete(labels Labels) bool {
labels, closer := constrainLabels(m.desc, labels)
defer closer()
h, err := m.hashLabels(labels)
if err != nil {
return false
@@ -106,6 +111,9 @@ func (m *MetricVec) Delete(labels Labels) bool {
// Note that curried labels will never be matched if deleting from the curried vector.
// To match curried labels with DeletePartialMatch, it must be called on the base vector.
func (m *MetricVec) DeletePartialMatch(labels Labels) int {
labels, closer := constrainLabels(m.desc, labels)
defer closer()
return m.metricMap.deleteByLabels(labels, m.curry)
}
@@ -144,11 +152,11 @@ func (m *MetricVec) CurryWith(labels Labels) (*MetricVec, error) {
oldCurry = m.curry
iCurry int
)
for i, label := range m.desc.variableLabels {
val, ok := labels[label]
for i, labelName := range m.desc.variableLabels.names {
val, ok := labels[labelName]
if iCurry < len(oldCurry) && oldCurry[iCurry].index == i {
if ok {
return nil, fmt.Errorf("label name %q is already curried", label)
return nil, fmt.Errorf("label name %q is already curried", labelName)
}
newCurry = append(newCurry, oldCurry[iCurry])
iCurry++
@@ -156,7 +164,10 @@ func (m *MetricVec) CurryWith(labels Labels) (*MetricVec, error) {
if !ok {
continue // Label stays uncurried.
}
newCurry = append(newCurry, curriedLabelValue{i, val})
newCurry = append(newCurry, curriedLabelValue{
i,
m.desc.variableLabels.constrain(labelName, val),
})
}
}
if l := len(oldCurry) + len(labels) - len(newCurry); l > 0 {
@@ -199,6 +210,7 @@ func (m *MetricVec) CurryWith(labels Labels) (*MetricVec, error) {
// a wrapper around MetricVec, implementing a vector for a specific Metric
// implementation, for example GaugeVec.
func (m *MetricVec) GetMetricWithLabelValues(lvs ...string) (Metric, error) {
lvs = constrainLabelValues(m.desc, lvs, m.curry)
h, err := m.hashLabelValues(lvs)
if err != nil {
return nil, err
@@ -224,6 +236,9 @@ func (m *MetricVec) GetMetricWithLabelValues(lvs ...string) (Metric, error) {
// around MetricVec, implementing a vector for a specific Metric implementation,
// for example GaugeVec.
func (m *MetricVec) GetMetricWith(labels Labels) (Metric, error) {
labels, closer := constrainLabels(m.desc, labels)
defer closer()
h, err := m.hashLabels(labels)
if err != nil {
return nil, err
@@ -233,7 +248,7 @@ func (m *MetricVec) GetMetricWith(labels Labels) (Metric, error) {
}
func (m *MetricVec) hashLabelValues(vals []string) (uint64, error) {
if err := validateLabelValues(vals, len(m.desc.variableLabels)-len(m.curry)); err != nil {
if err := validateLabelValues(vals, len(m.desc.variableLabels.names)-len(m.curry)); err != nil {
return 0, err
}
@@ -242,7 +257,7 @@ func (m *MetricVec) hashLabelValues(vals []string) (uint64, error) {
curry = m.curry
iVals, iCurry int
)
for i := 0; i < len(m.desc.variableLabels); i++ {
for i := 0; i < len(m.desc.variableLabels.names); i++ {
if iCurry < len(curry) && curry[iCurry].index == i {
h = m.hashAdd(h, curry[iCurry].value)
iCurry++
@@ -256,7 +271,7 @@ func (m *MetricVec) hashLabelValues(vals []string) (uint64, error) {
}
func (m *MetricVec) hashLabels(labels Labels) (uint64, error) {
if err := validateValuesInLabels(labels, len(m.desc.variableLabels)-len(m.curry)); err != nil {
if err := validateValuesInLabels(labels, len(m.desc.variableLabels.names)-len(m.curry)); err != nil {
return 0, err
}
@@ -265,17 +280,17 @@ func (m *MetricVec) hashLabels(labels Labels) (uint64, error) {
curry = m.curry
iCurry int
)
for i, label := range m.desc.variableLabels {
val, ok := labels[label]
for i, labelName := range m.desc.variableLabels.names {
val, ok := labels[labelName]
if iCurry < len(curry) && curry[iCurry].index == i {
if ok {
return 0, fmt.Errorf("label name %q is already curried", label)
return 0, fmt.Errorf("label name %q is already curried", labelName)
}
h = m.hashAdd(h, curry[iCurry].value)
iCurry++
} else {
if !ok {
return 0, fmt.Errorf("label name %q missing in label map", label)
return 0, fmt.Errorf("label name %q missing in label map", labelName)
}
h = m.hashAdd(h, val)
}
@@ -453,7 +468,7 @@ func valueMatchesVariableOrCurriedValue(targetValue string, index int, values []
func matchPartialLabels(desc *Desc, values []string, labels Labels, curry []curriedLabelValue) bool {
for l, v := range labels {
// Check if the target label exists in our metrics and get the index.
varLabelIndex, validLabel := indexOf(l, desc.variableLabels)
varLabelIndex, validLabel := indexOf(l, desc.variableLabels.names)
if validLabel {
// Check the value of that label against the target value.
// We don't consider curried values in partial matches.
@@ -597,7 +612,7 @@ func matchLabels(desc *Desc, values []string, labels Labels, curry []curriedLabe
return false
}
iCurry := 0
for i, k := range desc.variableLabels {
for i, k := range desc.variableLabels.names {
if iCurry < len(curry) && curry[iCurry].index == i {
if values[i] != curry[iCurry].value {
return false
@@ -615,7 +630,7 @@ func matchLabels(desc *Desc, values []string, labels Labels, curry []curriedLabe
func extractLabelValues(desc *Desc, labels Labels, curry []curriedLabelValue) []string {
labelValues := make([]string, len(labels)+len(curry))
iCurry := 0
for i, k := range desc.variableLabels {
for i, k := range desc.variableLabels.names {
if iCurry < len(curry) && curry[iCurry].index == i {
labelValues[i] = curry[iCurry].value
iCurry++
@@ -640,3 +655,55 @@ func inlineLabelValues(lvs []string, curry []curriedLabelValue) []string {
}
return labelValues
}
var labelsPool = &sync.Pool{
New: func() interface{} {
return make(Labels)
},
}
func constrainLabels(desc *Desc, labels Labels) (Labels, func()) {
if len(desc.variableLabels.labelConstraints) == 0 {
// Fast path when there's no constraints
return labels, func() {}
}
constrainedLabels := labelsPool.Get().(Labels)
for l, v := range labels {
constrainedLabels[l] = desc.variableLabels.constrain(l, v)
}
return constrainedLabels, func() {
for k := range constrainedLabels {
delete(constrainedLabels, k)
}
labelsPool.Put(constrainedLabels)
}
}
func constrainLabelValues(desc *Desc, lvs []string, curry []curriedLabelValue) []string {
if len(desc.variableLabels.labelConstraints) == 0 {
// Fast path when there's no constraints
return lvs
}
constrainedValues := make([]string, len(lvs))
var iCurry, iLVs int
for i := 0; i < len(lvs)+len(curry); i++ {
if iCurry < len(curry) && curry[iCurry].index == i {
iCurry++
continue
}
if i < len(desc.variableLabels.names) {
constrainedValues[iLVs] = desc.variableLabels.constrain(
desc.variableLabels.names[i],
lvs[iLVs],
)
} else {
constrainedValues[iLVs] = lvs[iLVs]
}
iLVs++
}
return constrainedValues
}

View File

@@ -11,20 +11,13 @@
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build js
// +build js
package prometheus
package fileutil
type v2 struct{}
import (
"errors"
"os"
)
func mmap(f *os.File, length int) ([]byte, error) {
return nil, errors.New("unsupported")
}
func munmap(b []byte) (err error) {
return errors.New("unsupported")
}
// V2 is a struct that can be referenced to access experimental API that might
// be present in v2 of client golang someday. It offers extended functionality
// of v1 with slightly changed API. It is acceptable to use some pieces from v1
// and e.g `prometheus.NewGauge` and some from v2 e.g. `prometheus.V2.NewDesc`
// in the same codebase.
var V2 = v2{}

View File

@@ -17,12 +17,10 @@ import (
"fmt"
"sort"
//nolint:staticcheck // Ignore SA1019. Need to keep deprecated package for compatibility.
"github.com/golang/protobuf/proto"
"github.com/prometheus/client_golang/prometheus/internal"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/client_golang/prometheus/internal"
"google.golang.org/protobuf/proto"
)
// WrapRegistererWith returns a Registerer wrapping the provided
@@ -206,7 +204,7 @@ func wrapDesc(desc *Desc, prefix string, labels Labels) *Desc {
constLabels[ln] = lv
}
// NewDesc will do remaining validations.
newDesc := NewDesc(prefix+desc.fqName, desc.help, desc.variableLabels, constLabels)
newDesc := V2.NewDesc(prefix+desc.fqName, desc.help, desc.variableLabels, constLabels)
// Propagate errors if there was any. This will override any errer
// created by NewDesc above, i.e. earlier errors get precedence.
if desc.err != nil {

File diff suppressed because it is too large Load Diff

View File

@@ -1,90 +0,0 @@
// Copyright 2016 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.
// This package no longer handles safe yaml parsing. In order to
// ensure correct yaml unmarshalling, use "yaml.UnmarshalStrict()".
package config
import (
"encoding/json"
"net/http"
"path/filepath"
)
const secretToken = "<secret>"
// Secret special type for storing secrets.
type Secret string
// MarshalYAML implements the yaml.Marshaler interface for Secrets.
func (s Secret) MarshalYAML() (interface{}, error) {
if s != "" {
return secretToken, nil
}
return nil, nil
}
// UnmarshalYAML implements the yaml.Unmarshaler interface for Secrets.
func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {
type plain Secret
return unmarshal((*plain)(s))
}
// MarshalJSON implements the json.Marshaler interface for Secret.
func (s Secret) MarshalJSON() ([]byte, error) {
if len(s) == 0 {
return json.Marshal("")
}
return json.Marshal(secretToken)
}
type Header map[string][]Secret
func (h *Header) HTTPHeader() http.Header {
if h == nil || *h == nil {
return nil
}
header := make(http.Header)
for name, values := range *h {
var s []string
if values != nil {
s = make([]string, 0, len(values))
for _, value := range values {
s = append(s, string(value))
}
}
header[name] = s
}
return header
}
// DirectorySetter is a config type that contains file paths that may
// be relative to the file containing the config.
type DirectorySetter interface {
// SetDirectory joins any relative file paths with dir.
// Any paths that are empty or absolute remain unchanged.
SetDirectory(dir string)
}
// JoinDir joins dir and path if path is relative.
// If path is empty or absolute, it is returned unchanged.
func JoinDir(dir, path string) string {
if path == "" || filepath.IsAbs(path) {
return path
}
return filepath.Join(dir, path)
}

File diff suppressed because it is too large Load Diff

View File

@@ -22,7 +22,7 @@ import (
dto "github.com/prometheus/client_model/go"
"github.com/matttproud/golang_protobuf_extensions/pbutil"
"github.com/matttproud/golang_protobuf_extensions/v2/pbutil"
"github.com/prometheus/common/model"
)
@@ -115,32 +115,31 @@ func (d *protoDecoder) Decode(v *dto.MetricFamily) error {
// textDecoder implements the Decoder interface for the text protocol.
type textDecoder struct {
r io.Reader
p TextParser
fams []*dto.MetricFamily
fams map[string]*dto.MetricFamily
err error
}
// Decode implements the Decoder interface.
func (d *textDecoder) Decode(v *dto.MetricFamily) error {
// TODO(fabxc): Wrap this as a line reader to make streaming safer.
if len(d.fams) == 0 {
// No cached metric families, read everything and parse metrics.
fams, err := d.p.TextToMetricFamilies(d.r)
if err != nil {
return err
}
if len(fams) == 0 {
return io.EOF
}
d.fams = make([]*dto.MetricFamily, 0, len(fams))
for _, f := range fams {
d.fams = append(d.fams, f)
if d.err == nil {
// Read all metrics in one shot.
var p TextParser
d.fams, d.err = p.TextToMetricFamilies(d.r)
// If we don't get an error, store io.EOF for the end.
if d.err == nil {
d.err = io.EOF
}
}
*v = *d.fams[0]
d.fams = d.fams[1:]
return nil
// Pick off one MetricFamily per Decode until there's nothing left.
for key, fam := range d.fams {
v.Name = fam.Name
v.Help = fam.Help
v.Type = fam.Type
v.Metric = fam.Metric
delete(d.fams, key)
return nil
}
return d.err
}
// SampleDecoder wraps a Decoder to extract samples from the metric families

View File

@@ -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/matttproud/golang_protobuf_extensions/v2/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)

View File

@@ -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 = `<unknown>`
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 = `<unknown>`
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 (

View File

@@ -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
@@ -142,9 +142,13 @@ func (p *TextParser) reset(in io.Reader) {
func (p *TextParser) startOfLine() stateFn {
p.lineCount++
if p.skipBlankTab(); p.err != nil {
// End of input reached. This is the only case where
// that is not an error but a signal that we are done.
p.err = nil
// This is the only place that we expect to see io.EOF,
// which is not an error but the signal that we are done.
// Any other error that happens to align with the start of
// a line is still an error.
if p.err == io.EOF {
p.err = nil
}
return nil
}
switch p.currentByte {

View File

@@ -18,7 +18,6 @@ import (
"errors"
"fmt"
"math"
"regexp"
"strconv"
"strings"
"time"
@@ -183,54 +182,78 @@ func (d *Duration) Type() string {
return "duration"
}
var durationRE = regexp.MustCompile("^(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?$")
func isdigit(c byte) bool { return c >= '0' && c <= '9' }
// Units are required to go in order from biggest to smallest.
// This guards against confusion from "1m1d" being 1 minute + 1 day, not 1 month + 1 day.
var unitMap = map[string]struct {
pos int
mult uint64
}{
"ms": {7, uint64(time.Millisecond)},
"s": {6, uint64(time.Second)},
"m": {5, uint64(time.Minute)},
"h": {4, uint64(time.Hour)},
"d": {3, uint64(24 * time.Hour)},
"w": {2, uint64(7 * 24 * time.Hour)},
"y": {1, uint64(365 * 24 * time.Hour)},
}
// ParseDuration parses a string into a time.Duration, assuming that a year
// always has 365d, a week always has 7d, and a day always has 24h.
func ParseDuration(durationStr string) (Duration, error) {
switch durationStr {
func ParseDuration(s string) (Duration, error) {
switch s {
case "0":
// Allow 0 without a unit.
return 0, nil
case "":
return 0, errors.New("empty duration string")
}
matches := durationRE.FindStringSubmatch(durationStr)
if matches == nil {
return 0, fmt.Errorf("not a valid duration string: %q", durationStr)
}
var dur time.Duration
// Parse the match at pos `pos` in the regex and use `mult` to turn that
// into ms, then add that value to the total parsed duration.
var overflowErr error
m := func(pos int, mult time.Duration) {
if matches[pos] == "" {
return
orig := s
var dur uint64
lastUnitPos := 0
for s != "" {
if !isdigit(s[0]) {
return 0, fmt.Errorf("not a valid duration string: %q", orig)
}
n, _ := strconv.Atoi(matches[pos])
// Consume [0-9]*
i := 0
for ; i < len(s) && isdigit(s[i]); i++ {
}
v, err := strconv.ParseUint(s[:i], 10, 0)
if err != nil {
return 0, fmt.Errorf("not a valid duration string: %q", orig)
}
s = s[i:]
// Consume unit.
for i = 0; i < len(s) && !isdigit(s[i]); i++ {
}
if i == 0 {
return 0, fmt.Errorf("not a valid duration string: %q", orig)
}
u := s[:i]
s = s[i:]
unit, ok := unitMap[u]
if !ok {
return 0, fmt.Errorf("unknown unit %q in duration %q", u, orig)
}
if unit.pos <= lastUnitPos { // Units must go in order from biggest to smallest.
return 0, fmt.Errorf("not a valid duration string: %q", orig)
}
lastUnitPos = unit.pos
// Check if the provided duration overflows time.Duration (> ~ 290years).
if n > int((1<<63-1)/mult/time.Millisecond) {
overflowErr = errors.New("duration out of range")
if v > 1<<63/unit.mult {
return 0, errors.New("duration out of range")
}
d := time.Duration(n) * time.Millisecond
dur += d * mult
if dur < 0 {
overflowErr = errors.New("duration out of range")
dur += v * unit.mult
if dur > 1<<63-1 {
return 0, errors.New("duration out of range")
}
}
m(2, 1000*60*60*24*365) // y
m(4, 1000*60*60*24*7) // w
m(6, 1000*60*60*24) // d
m(8, 1000*60*60) // h
m(10, 1000*60) // m
m(12, 1000) // s
m(14, 1) // ms
return Duration(dur), overflowErr
return Duration(dur), nil
}
func (d Duration) String() string {

View File

@@ -16,20 +16,12 @@ package model
import (
"encoding/json"
"fmt"
"math"
"sort"
"strconv"
"strings"
)
var (
// ZeroSamplePair is the pseudo zero-value of SamplePair used to signal a
// non-existing sample pair. It is a SamplePair with timestamp Earliest and
// value 0.0. Note that the natural zero value of SamplePair has a timestamp
// of 0, which is possible to appear in a real SamplePair and thus not
// suitable to signal a non-existing SamplePair.
ZeroSamplePair = SamplePair{Timestamp: Earliest}
// ZeroSample is the pseudo zero-value of Sample used to signal a
// non-existing sample. It is a Sample with timestamp Earliest, value 0.0,
// and metric nil. Note that the natural zero value of Sample has a timestamp
@@ -38,82 +30,14 @@ var (
ZeroSample = Sample{Timestamp: Earliest}
)
// A SampleValue is a representation of a value for a given sample at a given
// time.
type SampleValue float64
// MarshalJSON implements json.Marshaler.
func (v SampleValue) MarshalJSON() ([]byte, error) {
return json.Marshal(v.String())
}
// UnmarshalJSON implements json.Unmarshaler.
func (v *SampleValue) UnmarshalJSON(b []byte) error {
if len(b) < 2 || b[0] != '"' || b[len(b)-1] != '"' {
return fmt.Errorf("sample value must be a quoted string")
}
f, err := strconv.ParseFloat(string(b[1:len(b)-1]), 64)
if err != nil {
return err
}
*v = SampleValue(f)
return nil
}
// Equal returns true if the value of v and o is equal or if both are NaN. Note
// that v==o is false if both are NaN. If you want the conventional float
// behavior, use == to compare two SampleValues.
func (v SampleValue) Equal(o SampleValue) bool {
if v == o {
return true
}
return math.IsNaN(float64(v)) && math.IsNaN(float64(o))
}
func (v SampleValue) String() string {
return strconv.FormatFloat(float64(v), 'f', -1, 64)
}
// SamplePair pairs a SampleValue with a Timestamp.
type SamplePair struct {
Timestamp Time
Value SampleValue
}
// MarshalJSON implements json.Marshaler.
func (s SamplePair) MarshalJSON() ([]byte, error) {
t, err := json.Marshal(s.Timestamp)
if err != nil {
return nil, err
}
v, err := json.Marshal(s.Value)
if err != nil {
return nil, err
}
return []byte(fmt.Sprintf("[%s,%s]", t, v)), nil
}
// UnmarshalJSON implements json.Unmarshaler.
func (s *SamplePair) UnmarshalJSON(b []byte) error {
v := [...]json.Unmarshaler{&s.Timestamp, &s.Value}
return json.Unmarshal(b, &v)
}
// Equal returns true if this SamplePair and o have equal Values and equal
// Timestamps. The semantics of Value equality is defined by SampleValue.Equal.
func (s *SamplePair) Equal(o *SamplePair) bool {
return s == o || (s.Value.Equal(o.Value) && s.Timestamp.Equal(o.Timestamp))
}
func (s SamplePair) String() string {
return fmt.Sprintf("%s @[%s]", s.Value, s.Timestamp)
}
// Sample is a sample pair associated with a metric.
// Sample is a sample pair associated with a metric. A single sample must either
// define Value or Histogram but not both. Histogram == nil implies the Value
// field is used, otherwise it should be ignored.
type Sample struct {
Metric Metric `json:"metric"`
Value SampleValue `json:"value"`
Timestamp Time `json:"timestamp"`
Metric Metric `json:"metric"`
Value SampleValue `json:"value"`
Timestamp Time `json:"timestamp"`
Histogram *SampleHistogram `json:"histogram"`
}
// Equal compares first the metrics, then the timestamp, then the value. The
@@ -129,11 +53,19 @@ func (s *Sample) Equal(o *Sample) bool {
if !s.Timestamp.Equal(o.Timestamp) {
return false
}
if s.Histogram != nil {
return s.Histogram.Equal(o.Histogram)
}
return s.Value.Equal(o.Value)
}
func (s Sample) String() string {
if s.Histogram != nil {
return fmt.Sprintf("%s => %s", s.Metric, SampleHistogramPair{
Timestamp: s.Timestamp,
Histogram: s.Histogram,
})
}
return fmt.Sprintf("%s => %s", s.Metric, SamplePair{
Timestamp: s.Timestamp,
Value: s.Value,
@@ -142,6 +74,19 @@ func (s Sample) String() string {
// MarshalJSON implements json.Marshaler.
func (s Sample) MarshalJSON() ([]byte, error) {
if s.Histogram != nil {
v := struct {
Metric Metric `json:"metric"`
Histogram SampleHistogramPair `json:"histogram"`
}{
Metric: s.Metric,
Histogram: SampleHistogramPair{
Timestamp: s.Timestamp,
Histogram: s.Histogram,
},
}
return json.Marshal(&v)
}
v := struct {
Metric Metric `json:"metric"`
Value SamplePair `json:"value"`
@@ -152,21 +97,25 @@ func (s Sample) MarshalJSON() ([]byte, error) {
Value: s.Value,
},
}
return json.Marshal(&v)
}
// UnmarshalJSON implements json.Unmarshaler.
func (s *Sample) UnmarshalJSON(b []byte) error {
v := struct {
Metric Metric `json:"metric"`
Value SamplePair `json:"value"`
Metric Metric `json:"metric"`
Value SamplePair `json:"value"`
Histogram SampleHistogramPair `json:"histogram"`
}{
Metric: s.Metric,
Value: SamplePair{
Timestamp: s.Timestamp,
Value: s.Value,
},
Histogram: SampleHistogramPair{
Timestamp: s.Timestamp,
Histogram: s.Histogram,
},
}
if err := json.Unmarshal(b, &v); err != nil {
@@ -174,8 +123,13 @@ func (s *Sample) UnmarshalJSON(b []byte) error {
}
s.Metric = v.Metric
s.Timestamp = v.Value.Timestamp
s.Value = v.Value.Value
if v.Histogram.Histogram != nil {
s.Timestamp = v.Histogram.Timestamp
s.Histogram = v.Histogram.Histogram
} else {
s.Timestamp = v.Value.Timestamp
s.Value = v.Value.Value
}
return nil
}
@@ -221,80 +175,76 @@ func (s Samples) Equal(o Samples) bool {
// SampleStream is a stream of Values belonging to an attached COWMetric.
type SampleStream struct {
Metric Metric `json:"metric"`
Values []SamplePair `json:"values"`
Metric Metric `json:"metric"`
Values []SamplePair `json:"values"`
Histograms []SampleHistogramPair `json:"histograms"`
}
func (ss SampleStream) String() string {
vals := make([]string, len(ss.Values))
valuesLength := len(ss.Values)
vals := make([]string, valuesLength+len(ss.Histograms))
for i, v := range ss.Values {
vals[i] = v.String()
}
for i, v := range ss.Histograms {
vals[i+valuesLength] = v.String()
}
return fmt.Sprintf("%s =>\n%s", ss.Metric, strings.Join(vals, "\n"))
}
// Value is a generic interface for values resulting from a query evaluation.
type Value interface {
Type() ValueType
String() string
func (ss SampleStream) MarshalJSON() ([]byte, error) {
if len(ss.Histograms) > 0 && len(ss.Values) > 0 {
v := struct {
Metric Metric `json:"metric"`
Values []SamplePair `json:"values"`
Histograms []SampleHistogramPair `json:"histograms"`
}{
Metric: ss.Metric,
Values: ss.Values,
Histograms: ss.Histograms,
}
return json.Marshal(&v)
} else if len(ss.Histograms) > 0 {
v := struct {
Metric Metric `json:"metric"`
Histograms []SampleHistogramPair `json:"histograms"`
}{
Metric: ss.Metric,
Histograms: ss.Histograms,
}
return json.Marshal(&v)
} else {
v := struct {
Metric Metric `json:"metric"`
Values []SamplePair `json:"values"`
}{
Metric: ss.Metric,
Values: ss.Values,
}
return json.Marshal(&v)
}
}
func (Matrix) Type() ValueType { return ValMatrix }
func (Vector) Type() ValueType { return ValVector }
func (*Scalar) Type() ValueType { return ValScalar }
func (*String) Type() ValueType { return ValString }
func (ss *SampleStream) UnmarshalJSON(b []byte) error {
v := struct {
Metric Metric `json:"metric"`
Values []SamplePair `json:"values"`
Histograms []SampleHistogramPair `json:"histograms"`
}{
Metric: ss.Metric,
Values: ss.Values,
Histograms: ss.Histograms,
}
type ValueType int
const (
ValNone ValueType = iota
ValScalar
ValVector
ValMatrix
ValString
)
// MarshalJSON implements json.Marshaler.
func (et ValueType) MarshalJSON() ([]byte, error) {
return json.Marshal(et.String())
}
func (et *ValueType) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
if err := json.Unmarshal(b, &v); err != nil {
return err
}
switch s {
case "<ValNone>":
*et = ValNone
case "scalar":
*et = ValScalar
case "vector":
*et = ValVector
case "matrix":
*et = ValMatrix
case "string":
*et = ValString
default:
return fmt.Errorf("unknown value type %q", s)
}
return nil
}
func (e ValueType) String() string {
switch e {
case ValNone:
return "<ValNone>"
case ValScalar:
return "scalar"
case ValVector:
return "vector"
case ValMatrix:
return "matrix"
case ValString:
return "string"
}
panic("ValueType.String: unhandled value type")
ss.Metric = v.Metric
ss.Values = v.Values
ss.Histograms = v.Histograms
return nil
}
// Scalar is a scalar value evaluated at the set timestamp.

View File

@@ -0,0 +1,100 @@
// Copyright 2013 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 model
import (
"encoding/json"
"fmt"
"math"
"strconv"
)
var (
// ZeroSamplePair is the pseudo zero-value of SamplePair used to signal a
// non-existing sample pair. It is a SamplePair with timestamp Earliest and
// value 0.0. Note that the natural zero value of SamplePair has a timestamp
// of 0, which is possible to appear in a real SamplePair and thus not
// suitable to signal a non-existing SamplePair.
ZeroSamplePair = SamplePair{Timestamp: Earliest}
)
// A SampleValue is a representation of a value for a given sample at a given
// time.
type SampleValue float64
// MarshalJSON implements json.Marshaler.
func (v SampleValue) MarshalJSON() ([]byte, error) {
return json.Marshal(v.String())
}
// UnmarshalJSON implements json.Unmarshaler.
func (v *SampleValue) UnmarshalJSON(b []byte) error {
if len(b) < 2 || b[0] != '"' || b[len(b)-1] != '"' {
return fmt.Errorf("sample value must be a quoted string")
}
f, err := strconv.ParseFloat(string(b[1:len(b)-1]), 64)
if err != nil {
return err
}
*v = SampleValue(f)
return nil
}
// Equal returns true if the value of v and o is equal or if both are NaN. Note
// that v==o is false if both are NaN. If you want the conventional float
// behavior, use == to compare two SampleValues.
func (v SampleValue) Equal(o SampleValue) bool {
if v == o {
return true
}
return math.IsNaN(float64(v)) && math.IsNaN(float64(o))
}
func (v SampleValue) String() string {
return strconv.FormatFloat(float64(v), 'f', -1, 64)
}
// SamplePair pairs a SampleValue with a Timestamp.
type SamplePair struct {
Timestamp Time
Value SampleValue
}
func (s SamplePair) MarshalJSON() ([]byte, error) {
t, err := json.Marshal(s.Timestamp)
if err != nil {
return nil, err
}
v, err := json.Marshal(s.Value)
if err != nil {
return nil, err
}
return []byte(fmt.Sprintf("[%s,%s]", t, v)), nil
}
// UnmarshalJSON implements json.Unmarshaler.
func (s *SamplePair) UnmarshalJSON(b []byte) error {
v := [...]json.Unmarshaler{&s.Timestamp, &s.Value}
return json.Unmarshal(b, &v)
}
// Equal returns true if this SamplePair and o have equal Values and equal
// Timestamps. The semantics of Value equality is defined by SampleValue.Equal.
func (s *SamplePair) Equal(o *SamplePair) bool {
return s == o || (s.Value.Equal(o.Value) && s.Timestamp.Equal(o.Timestamp))
}
func (s SamplePair) String() string {
return fmt.Sprintf("%s @[%s]", s.Value, s.Timestamp)
}

View File

@@ -0,0 +1,178 @@
// Copyright 2013 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 model
import (
"encoding/json"
"fmt"
"strconv"
"strings"
)
type FloatString float64
func (v FloatString) String() string {
return strconv.FormatFloat(float64(v), 'f', -1, 64)
}
func (v FloatString) MarshalJSON() ([]byte, error) {
return json.Marshal(v.String())
}
func (v *FloatString) UnmarshalJSON(b []byte) error {
if len(b) < 2 || b[0] != '"' || b[len(b)-1] != '"' {
return fmt.Errorf("float value must be a quoted string")
}
f, err := strconv.ParseFloat(string(b[1:len(b)-1]), 64)
if err != nil {
return err
}
*v = FloatString(f)
return nil
}
type HistogramBucket struct {
Boundaries int32
Lower FloatString
Upper FloatString
Count FloatString
}
func (s HistogramBucket) MarshalJSON() ([]byte, error) {
b, err := json.Marshal(s.Boundaries)
if err != nil {
return nil, err
}
l, err := json.Marshal(s.Lower)
if err != nil {
return nil, err
}
u, err := json.Marshal(s.Upper)
if err != nil {
return nil, err
}
c, err := json.Marshal(s.Count)
if err != nil {
return nil, err
}
return []byte(fmt.Sprintf("[%s,%s,%s,%s]", b, l, u, c)), nil
}
func (s *HistogramBucket) UnmarshalJSON(buf []byte) error {
tmp := []interface{}{&s.Boundaries, &s.Lower, &s.Upper, &s.Count}
wantLen := len(tmp)
if err := json.Unmarshal(buf, &tmp); err != nil {
return err
}
if gotLen := len(tmp); gotLen != wantLen {
return fmt.Errorf("wrong number of fields: %d != %d", gotLen, wantLen)
}
return nil
}
func (s *HistogramBucket) Equal(o *HistogramBucket) bool {
return s == o || (s.Boundaries == o.Boundaries && s.Lower == o.Lower && s.Upper == o.Upper && s.Count == o.Count)
}
func (b HistogramBucket) String() string {
var sb strings.Builder
lowerInclusive := b.Boundaries == 1 || b.Boundaries == 3
upperInclusive := b.Boundaries == 0 || b.Boundaries == 3
if lowerInclusive {
sb.WriteRune('[')
} else {
sb.WriteRune('(')
}
fmt.Fprintf(&sb, "%g,%g", b.Lower, b.Upper)
if upperInclusive {
sb.WriteRune(']')
} else {
sb.WriteRune(')')
}
fmt.Fprintf(&sb, ":%v", b.Count)
return sb.String()
}
type HistogramBuckets []*HistogramBucket
func (s HistogramBuckets) Equal(o HistogramBuckets) bool {
if len(s) != len(o) {
return false
}
for i, bucket := range s {
if !bucket.Equal(o[i]) {
return false
}
}
return true
}
type SampleHistogram struct {
Count FloatString `json:"count"`
Sum FloatString `json:"sum"`
Buckets HistogramBuckets `json:"buckets"`
}
func (s SampleHistogram) String() string {
return fmt.Sprintf("Count: %f, Sum: %f, Buckets: %v", s.Count, s.Sum, s.Buckets)
}
func (s *SampleHistogram) Equal(o *SampleHistogram) bool {
return s == o || (s.Count == o.Count && s.Sum == o.Sum && s.Buckets.Equal(o.Buckets))
}
type SampleHistogramPair struct {
Timestamp Time
// Histogram should never be nil, it's only stored as pointer for efficiency.
Histogram *SampleHistogram
}
func (s SampleHistogramPair) MarshalJSON() ([]byte, error) {
if s.Histogram == nil {
return nil, fmt.Errorf("histogram is nil")
}
t, err := json.Marshal(s.Timestamp)
if err != nil {
return nil, err
}
v, err := json.Marshal(s.Histogram)
if err != nil {
return nil, err
}
return []byte(fmt.Sprintf("[%s,%s]", t, v)), nil
}
func (s *SampleHistogramPair) UnmarshalJSON(buf []byte) error {
tmp := []interface{}{&s.Timestamp, &s.Histogram}
wantLen := len(tmp)
if err := json.Unmarshal(buf, &tmp); err != nil {
return err
}
if gotLen := len(tmp); gotLen != wantLen {
return fmt.Errorf("wrong number of fields: %d != %d", gotLen, wantLen)
}
if s.Histogram == nil {
return fmt.Errorf("histogram is null")
}
return nil
}
func (s SampleHistogramPair) String() string {
return fmt.Sprintf("%s @[%s]", s.Histogram, s.Timestamp)
}
func (s *SampleHistogramPair) Equal(o *SampleHistogramPair) bool {
return s == o || (s.Histogram.Equal(o.Histogram) && s.Timestamp.Equal(o.Timestamp))
}

View File

@@ -0,0 +1,83 @@
// Copyright 2013 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 model
import (
"encoding/json"
"fmt"
)
// Value is a generic interface for values resulting from a query evaluation.
type Value interface {
Type() ValueType
String() string
}
func (Matrix) Type() ValueType { return ValMatrix }
func (Vector) Type() ValueType { return ValVector }
func (*Scalar) Type() ValueType { return ValScalar }
func (*String) Type() ValueType { return ValString }
type ValueType int
const (
ValNone ValueType = iota
ValScalar
ValVector
ValMatrix
ValString
)
// MarshalJSON implements json.Marshaler.
func (et ValueType) MarshalJSON() ([]byte, error) {
return json.Marshal(et.String())
}
func (et *ValueType) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
switch s {
case "<ValNone>":
*et = ValNone
case "scalar":
*et = ValScalar
case "vector":
*et = ValVector
case "matrix":
*et = ValMatrix
case "string":
*et = ValString
default:
return fmt.Errorf("unknown value type %q", s)
}
return nil
}
func (e ValueType) String() string {
switch e {
case ValNone:
return "<ValNone>"
case ValScalar:
return "scalar"
case ValVector:
return "vector"
case ValMatrix:
return "matrix"
case ValString:
return "string"
}
panic("ValueType.String: unhandled value type")
}

View File

@@ -1,201 +0,0 @@
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.

Some files were not shown because too many files have changed in this diff Show More