Chore: Upgrade Go version to 1.19.1 (backport) (#55733)
Upgrades the version of Go used to build Grafana v9.1.x to 1.19.1. Backport of Chore: Upgrade Go to 1.19.1 #54902 Backport of Chore: Update swagger to v0.30.2 #55159
This commit is contained in:
+1
-1
@@ -342,7 +342,7 @@ func (hs *HTTPServer) GetAlertNotificationByID(c *models.ReqContext) response.Re
|
||||
|
||||
// swagger:route GET /alert-notifications/uid/{notification_channel_uid} legacy_alerts_notification_channels getAlertNotificationChannelByUID
|
||||
//
|
||||
// Get notification channel by UID
|
||||
// Get notification channel by UID.
|
||||
//
|
||||
// Returns the notification channel given the notification channel UID.
|
||||
//
|
||||
|
||||
@@ -289,7 +289,7 @@ func (hs *HTTPServer) UpdateAnnotation(c *models.ReqContext) response.Response {
|
||||
|
||||
// swagger:route PATCH /annotations/{annotation_id} annotations patchAnnotation
|
||||
//
|
||||
// Patch Annotation
|
||||
// Patch Annotation.
|
||||
//
|
||||
// Updates one or more properties of an annotation that matches the specified ID.
|
||||
// This operation currently supports updating of the `text`, `tags`, `time` and `timeEnd` properties.
|
||||
|
||||
+20
-19
@@ -3,29 +3,30 @@
|
||||
// The Grafana backend exposes an HTTP API, the same API is used by the frontend to do
|
||||
// everything from saving dashboards, creating users and updating data sources.
|
||||
//
|
||||
// Schemes: http, https
|
||||
// BasePath: /api
|
||||
// Version: 0.0.1
|
||||
// License: GNU Affero General Public License v3.0 https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
// Contact: Grafana Labs<hello@grafana.com> https://grafana.com
|
||||
// Schemes: http, https
|
||||
// BasePath: /api
|
||||
// Version: 0.0.1
|
||||
// License: GNU Affero General Public License v3.0 https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
// Contact: Grafana Labs<hello@grafana.com> https://grafana.com
|
||||
//
|
||||
// Consumes:
|
||||
// - application/json
|
||||
// Consumes:
|
||||
// - application/json
|
||||
//
|
||||
// Produces:
|
||||
// - application/json
|
||||
// Produces:
|
||||
// - application/json
|
||||
//
|
||||
// Security:
|
||||
// - basic:
|
||||
// - api_key:
|
||||
// Security:
|
||||
// - basic:
|
||||
// - api_key:
|
||||
//
|
||||
// SecurityDefinitions:
|
||||
// basic:
|
||||
// type: basic
|
||||
// api_key:
|
||||
// type: apiKey
|
||||
// name: Authorization
|
||||
// in: header
|
||||
// SecurityDefinitions:
|
||||
// basic:
|
||||
// type: basic
|
||||
//
|
||||
// api_key:
|
||||
// type: apiKey
|
||||
// name: Authorization
|
||||
// in: header
|
||||
//
|
||||
// swagger:meta
|
||||
package api
|
||||
|
||||
+1
-1
@@ -94,7 +94,7 @@ func (hs *HTTPServer) DeleteAPIKey(c *models.ReqContext) response.Response {
|
||||
//
|
||||
// Creates an API key.
|
||||
//
|
||||
// Will return details of the created API key
|
||||
// Will return details of the created API key.
|
||||
//
|
||||
// Responses:
|
||||
// 200: postAPIkeyResponse
|
||||
|
||||
+1
-1
@@ -46,7 +46,7 @@ func (hs *HTTPServer) handleQueryMetricsError(err error) *response.NormalRespons
|
||||
// QueryMetricsV2 returns query metrics.
|
||||
// swagger:route POST /ds/query ds queryMetricsWithExpressions
|
||||
//
|
||||
// DataSource query metrics with expressions
|
||||
// DataSource query metrics with expressions.
|
||||
//
|
||||
// If you are running Grafana Enterprise and have Fine-grained access control enabled
|
||||
// you need to have a permission with action: `datasources:query`.
|
||||
|
||||
+2
-2
@@ -17,7 +17,7 @@ import (
|
||||
|
||||
// swagger:route GET /org org getCurrentOrg
|
||||
//
|
||||
// Get current Organization
|
||||
// Get current Organization.
|
||||
//
|
||||
// Responses:
|
||||
// 200: getCurrentOrgResponse
|
||||
@@ -300,7 +300,7 @@ func (hs *HTTPServer) DeleteOrgByID(c *models.ReqContext) response.Response {
|
||||
|
||||
// swagger:route GET /orgs orgs searchOrgs
|
||||
//
|
||||
// Search all Organizations
|
||||
// Search all Organizations.
|
||||
//
|
||||
// Security:
|
||||
// - basic:
|
||||
|
||||
@@ -16,7 +16,7 @@ import (
|
||||
|
||||
// swagger:route POST /org/users org addOrgUserToCurrentOrg
|
||||
//
|
||||
// Add a new user to the current organization
|
||||
// Add a new user to the current organization.
|
||||
//
|
||||
// Adds a global user to the current organization.
|
||||
//
|
||||
@@ -39,7 +39,7 @@ func (hs *HTTPServer) AddOrgUserToCurrentOrg(c *models.ReqContext) response.Resp
|
||||
|
||||
// swagger:route POST /orgs/{org_id}/users orgs addOrgUser
|
||||
//
|
||||
// Add a new user to the current organization
|
||||
// Add a new user to the current organization.
|
||||
//
|
||||
// Adds a global user to the current organization.
|
||||
//
|
||||
@@ -275,7 +275,7 @@ func (hs *HTTPServer) SearchOrgUsersWithPaging(c *models.ReqContext) response.Re
|
||||
|
||||
// swagger:route PATCH /org/users/{user_id} org updateOrgUserForCurrentOrg
|
||||
//
|
||||
// Updates the given user
|
||||
// Updates the given user.
|
||||
//
|
||||
// If you are running Grafana Enterprise and have Fine-grained access control enabled
|
||||
// you need to have a permission with action: `org.users.role:update` with scope `users:*`.
|
||||
@@ -349,7 +349,7 @@ func (hs *HTTPServer) updateOrgUserHelper(c *models.ReqContext, cmd models.Updat
|
||||
|
||||
// swagger:route DELETE /org/users/{user_id} org removeOrgUserForCurrentOrg
|
||||
//
|
||||
// Delete user in current organization
|
||||
// Delete user in current organization.
|
||||
//
|
||||
// If you are running Grafana Enterprise and have Fine-grained access control enabled
|
||||
// you need to have a permission with action: `org.users:remove` with scope `users:*`.
|
||||
@@ -375,7 +375,7 @@ func (hs *HTTPServer) RemoveOrgUserForCurrentOrg(c *models.ReqContext) response.
|
||||
|
||||
// swagger:route DELETE /orgs/{org_id}/users/{user_id} orgs removeOrgUser
|
||||
//
|
||||
// Delete user in current organization
|
||||
// Delete user in current organization.
|
||||
//
|
||||
// If you are running Grafana Enterprise and have Fine-grained access control enabled
|
||||
// you need to have a permission with action: `org.users:remove` with scope `users:*`.
|
||||
|
||||
@@ -19,7 +19,6 @@ func (hs *HTTPServer) GetCurrentOrgQuotas(c *models.ReqContext) response.Respons
|
||||
// Fetch Organization quota.
|
||||
//
|
||||
// If you are running Grafana Enterprise and have Fine-grained access control enabled, you need to have a permission with action `orgs.quotas:read` and scope `org:id:1` (orgIDScope).
|
||||
//list
|
||||
// Responses:
|
||||
// 200: getQuotaResponse
|
||||
// 401: unauthorisedError
|
||||
|
||||
+1
-1
@@ -131,7 +131,7 @@ func (hs *HTTPServer) searchHitsWithMetadata(c *models.ReqContext, hits models.H
|
||||
|
||||
// swagger:route GET /search/sorting search listSortOptions
|
||||
//
|
||||
// List search sorting options
|
||||
// List search sorting options.
|
||||
//
|
||||
// Responses:
|
||||
// 200: listSortOptionsResponse
|
||||
|
||||
@@ -97,6 +97,10 @@ func RunServer(opt ServerOptions) int {
|
||||
fmt.Println("diagnostics: pprof profiling enabled", "addr", profileDiagnostics.addr, "port", profileDiagnostics.port)
|
||||
runtime.SetBlockProfileRate(1)
|
||||
go func() {
|
||||
// TODO: We should enable the linter and fix G114 here.
|
||||
// G114: Use of net/http serve function that has no support for setting timeouts (gosec)
|
||||
//
|
||||
//nolint:gosec
|
||||
err := http.ListenAndServe(fmt.Sprintf("%s:%d", profileDiagnostics.addr, profileDiagnostics.port), nil)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
|
||||
@@ -256,14 +256,15 @@ func tryget(headers map[string][]string, key string) string {
|
||||
|
||||
/*
|
||||
Based on Azure docs:
|
||||
Link: http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx#Constructing_Element
|
||||
|
||||
1) Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header.
|
||||
2) Convert each HTTP header name to lowercase.
|
||||
3) Sort the headers lexicographically by header name, in ascending order. Note that each header may appear only once in the string.
|
||||
4) Unfold the string by replacing any breaking white space with a single space.
|
||||
5) Trim any white space around the colon in the header.
|
||||
6) Finally, append a new line character to each canonicalized header in the resulting list. Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string.
|
||||
Link: http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx#Constructing_Element
|
||||
|
||||
1) Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header.
|
||||
2) Convert each HTTP header name to lowercase.
|
||||
3) Sort the headers lexicographically by header name, in ascending order. Note that each header may appear only once in the string.
|
||||
4) Unfold the string by replacing any breaking white space with a single space.
|
||||
5) Trim any white space around the colon in the header.
|
||||
6) Finally, append a new line character to each canonicalized header in the resulting list. Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string.
|
||||
*/
|
||||
func (a *Auth) canonicalizedHeaders(req *http.Request) string {
|
||||
var buffer bytes.Buffer
|
||||
@@ -288,25 +289,26 @@ func (a *Auth) canonicalizedHeaders(req *http.Request) string {
|
||||
|
||||
/*
|
||||
Based on Azure docs
|
||||
Link: http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx#Constructing_Element
|
||||
|
||||
1) Beginning with an empty string (""), append a forward slash (/), followed by the name of the account that owns the resource being accessed.
|
||||
2) Append the resource's encoded URI path, without any query parameters.
|
||||
3) Retrieve all query parameters on the resource URI, including the comp parameter if it exists.
|
||||
4) Convert all parameter names to lowercase.
|
||||
5) Sort the query parameters lexicographically by parameter name, in ascending order.
|
||||
6) URL-decode each query parameter name and value.
|
||||
7) Append each query parameter name and value to the string in the following format, making sure to include the colon (:) between the name and the value:
|
||||
parameter-name:parameter-value
|
||||
Link: http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx#Constructing_Element
|
||||
|
||||
8) If a query parameter has more than one value, sort all values lexicographically, then include them in a comma-separated list:
|
||||
parameter-name:parameter-value-1,parameter-value-2,parameter-value-n
|
||||
1. Beginning with an empty string (""), append a forward slash (/), followed by the name of the account that owns the resource being accessed.
|
||||
2. Append the resource's encoded URI path, without any query parameters.
|
||||
3. Retrieve all query parameters on the resource URI, including the comp parameter if it exists.
|
||||
4. Convert all parameter names to lowercase.
|
||||
5. Sort the query parameters lexicographically by parameter name, in ascending order.
|
||||
6. URL-decode each query parameter name and value.
|
||||
7. Append each query parameter name and value to the string in the following format, making sure to include the colon (:) between the name and the value:
|
||||
parameter-name:parameter-value
|
||||
|
||||
8. If a query parameter has more than one value, sort all values lexicographically, then include them in a comma-separated list:
|
||||
parameter-name:parameter-value-1,parameter-value-2,parameter-value-n
|
||||
|
||||
9) Append a new line character (\n) after each name-value pair.
|
||||
|
||||
Rules:
|
||||
1) Avoid using the new line character (\n) in values for query parameters. If it must be used, ensure that it does not affect the format of the canonicalized resource string.
|
||||
2) Avoid using commas in query parameter values.
|
||||
1. Avoid using the new line character (\n) in values for query parameters. If it must be used, ensure that it does not affect the format of the canonicalized resource string.
|
||||
2. Avoid using commas in query parameter values.
|
||||
*/
|
||||
func (a *Auth) canonicalizedResource(req *http.Request) string {
|
||||
var buffer bytes.Buffer
|
||||
|
||||
@@ -6,6 +6,13 @@ package logproto
|
||||
import (
|
||||
context "context"
|
||||
fmt "fmt"
|
||||
io "io"
|
||||
math "math"
|
||||
math_bits "math/bits"
|
||||
reflect "reflect"
|
||||
strings "strings"
|
||||
time "time"
|
||||
|
||||
_ "github.com/gogo/protobuf/gogoproto"
|
||||
proto "github.com/gogo/protobuf/proto"
|
||||
github_com_gogo_protobuf_types "github.com/gogo/protobuf/types"
|
||||
@@ -13,12 +20,6 @@ import (
|
||||
grpc "google.golang.org/grpc"
|
||||
codes "google.golang.org/grpc/codes"
|
||||
status "google.golang.org/grpc/status"
|
||||
io "io"
|
||||
math "math"
|
||||
math_bits "math/bits"
|
||||
reflect "reflect"
|
||||
strings "strings"
|
||||
time "time"
|
||||
)
|
||||
|
||||
// Reference imports to suppress errors if they are not otherwise used.
|
||||
|
||||
@@ -108,7 +108,7 @@ func (m *Entry) MarshalToSizedBuffer(dAtA []byte) (int, error) {
|
||||
return len(dAtA) - i, nil
|
||||
}
|
||||
|
||||
//nolint: gocyclo
|
||||
//nolint:gocyclo
|
||||
func (m *Stream) Unmarshal(dAtA []byte) error {
|
||||
l := len(dAtA)
|
||||
iNdEx := 0
|
||||
@@ -248,7 +248,7 @@ func (m *Stream) Unmarshal(dAtA []byte) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
//nolint: gocyclo
|
||||
//nolint:gocyclo
|
||||
func (m *Entry) Unmarshal(dAtA []byte) error {
|
||||
l := len(dAtA)
|
||||
iNdEx := 0
|
||||
|
||||
@@ -154,7 +154,8 @@ func (j *Json) Del(key string) {
|
||||
// for `key` in its `map` representation
|
||||
//
|
||||
// useful for chaining operations (to traverse a nested JSON):
|
||||
// js.Get("top_level").Get("dict").Get("value").Int()
|
||||
//
|
||||
// js.Get("top_level").Get("dict").Get("value").Int()
|
||||
func (j *Json) Get(key string) *Json {
|
||||
m, err := j.Map()
|
||||
if err == nil {
|
||||
@@ -168,7 +169,7 @@ func (j *Json) Get(key string) *Json {
|
||||
// GetPath searches for the item as specified by the branch
|
||||
// without the need to deep dive using Get()'s.
|
||||
//
|
||||
// js.GetPath("top_level", "dict")
|
||||
// js.GetPath("top_level", "dict")
|
||||
func (j *Json) GetPath(branch ...string) *Json {
|
||||
jin := j
|
||||
for _, p := range branch {
|
||||
@@ -182,7 +183,8 @@ func (j *Json) GetPath(branch ...string) *Json {
|
||||
//
|
||||
// this is the analog to Get when accessing elements of
|
||||
// a json array instead of a json object:
|
||||
// js.Get("top_level").Get("array").GetIndex(1).Get("key").Int()
|
||||
//
|
||||
// js.Get("top_level").Get("array").GetIndex(1).Get("key").Int()
|
||||
func (j *Json) GetIndex(index int) *Json {
|
||||
a, err := j.Array()
|
||||
if err == nil {
|
||||
@@ -198,9 +200,10 @@ func (j *Json) GetIndex(index int) *Json {
|
||||
// indicating success or failure
|
||||
//
|
||||
// useful for chained operations when success is important:
|
||||
// if data, ok := js.Get("top_level").CheckGetIndex(0); ok {
|
||||
// log.Println(data)
|
||||
// }
|
||||
//
|
||||
// if data, ok := js.Get("top_level").CheckGetIndex(0); ok {
|
||||
// log.Println(data)
|
||||
// }
|
||||
func (j *Json) CheckGetIndex(index int) (*Json, bool) {
|
||||
a, err := j.Array()
|
||||
if err == nil {
|
||||
@@ -226,9 +229,10 @@ func (j *Json) SetIndex(index int, val interface{}) {
|
||||
// a `bool` identifying success or failure
|
||||
//
|
||||
// useful for chained operations when success is important:
|
||||
// if data, ok := js.Get("top_level").CheckGet("inner"); ok {
|
||||
// log.Println(data)
|
||||
// }
|
||||
//
|
||||
// if data, ok := js.Get("top_level").CheckGet("inner"); ok {
|
||||
// log.Println(data)
|
||||
// }
|
||||
func (j *Json) CheckGet(key string) (*Json, bool) {
|
||||
m, err := j.Map()
|
||||
if err == nil {
|
||||
@@ -303,9 +307,10 @@ func (j *Json) StringArray() ([]string, error) {
|
||||
// MustArray guarantees the return of a `[]interface{}` (with optional default)
|
||||
//
|
||||
// useful when you want to iterate over array values in a succinct manner:
|
||||
// for i, v := range js.Get("results").MustArray() {
|
||||
// fmt.Println(i, v)
|
||||
// }
|
||||
//
|
||||
// for i, v := range js.Get("results").MustArray() {
|
||||
// fmt.Println(i, v)
|
||||
// }
|
||||
func (j *Json) MustArray(args ...[]interface{}) []interface{} {
|
||||
var def []interface{}
|
||||
|
||||
@@ -328,9 +333,10 @@ func (j *Json) MustArray(args ...[]interface{}) []interface{} {
|
||||
// MustMap guarantees the return of a `map[string]interface{}` (with optional default)
|
||||
//
|
||||
// useful when you want to iterate over map values in a succinct manner:
|
||||
// for k, v := range js.Get("dictionary").MustMap() {
|
||||
// fmt.Println(k, v)
|
||||
// }
|
||||
//
|
||||
// for k, v := range js.Get("dictionary").MustMap() {
|
||||
// fmt.Println(k, v)
|
||||
// }
|
||||
func (j *Json) MustMap(args ...map[string]interface{}) map[string]interface{} {
|
||||
var def map[string]interface{}
|
||||
|
||||
@@ -353,7 +359,8 @@ func (j *Json) MustMap(args ...map[string]interface{}) map[string]interface{} {
|
||||
// MustString guarantees the return of a `string` (with optional default)
|
||||
//
|
||||
// useful when you explicitly want a `string` in a single value return context:
|
||||
// myFunc(js.Get("param1").MustString(), js.Get("optional_param").MustString("my_default"))
|
||||
//
|
||||
// myFunc(js.Get("param1").MustString(), js.Get("optional_param").MustString("my_default"))
|
||||
func (j *Json) MustString(args ...string) string {
|
||||
var def string
|
||||
|
||||
@@ -376,9 +383,10 @@ func (j *Json) MustString(args ...string) string {
|
||||
// MustStringArray guarantees the return of a `[]string` (with optional default)
|
||||
//
|
||||
// useful when you want to iterate over array values in a succinct manner:
|
||||
// for i, s := range js.Get("results").MustStringArray() {
|
||||
// fmt.Println(i, s)
|
||||
// }
|
||||
//
|
||||
// for i, s := range js.Get("results").MustStringArray() {
|
||||
// fmt.Println(i, s)
|
||||
// }
|
||||
func (j *Json) MustStringArray(args ...[]string) []string {
|
||||
var def []string
|
||||
|
||||
@@ -401,7 +409,8 @@ func (j *Json) MustStringArray(args ...[]string) []string {
|
||||
// MustInt guarantees the return of an `int` (with optional default)
|
||||
//
|
||||
// useful when you explicitly want an `int` in a single value return context:
|
||||
// myFunc(js.Get("param1").MustInt(), js.Get("optional_param").MustInt(5150))
|
||||
//
|
||||
// myFunc(js.Get("param1").MustInt(), js.Get("optional_param").MustInt(5150))
|
||||
func (j *Json) MustInt(args ...int) int {
|
||||
var def int
|
||||
|
||||
@@ -424,7 +433,8 @@ func (j *Json) MustInt(args ...int) int {
|
||||
// MustFloat64 guarantees the return of a `float64` (with optional default)
|
||||
//
|
||||
// useful when you explicitly want a `float64` in a single value return context:
|
||||
// myFunc(js.Get("param1").MustFloat64(), js.Get("optional_param").MustFloat64(5.150))
|
||||
//
|
||||
// myFunc(js.Get("param1").MustFloat64(), js.Get("optional_param").MustFloat64(5.150))
|
||||
func (j *Json) MustFloat64(args ...float64) float64 {
|
||||
var def float64
|
||||
|
||||
@@ -447,7 +457,8 @@ func (j *Json) MustFloat64(args ...float64) float64 {
|
||||
// MustBool guarantees the return of a `bool` (with optional default)
|
||||
//
|
||||
// useful when you explicitly want a `bool` in a single value return context:
|
||||
// myFunc(js.Get("param1").MustBool(), js.Get("optional_param").MustBool(true))
|
||||
//
|
||||
// myFunc(js.Get("param1").MustBool(), js.Get("optional_param").MustBool(true))
|
||||
func (j *Json) MustBool(args ...bool) bool {
|
||||
var def bool
|
||||
|
||||
@@ -470,7 +481,8 @@ func (j *Json) MustBool(args ...bool) bool {
|
||||
// MustInt64 guarantees the return of an `int64` (with optional default)
|
||||
//
|
||||
// useful when you explicitly want an `int64` in a single value return context:
|
||||
// myFunc(js.Get("param1").MustInt64(), js.Get("optional_param").MustInt64(5150))
|
||||
//
|
||||
// myFunc(js.Get("param1").MustInt64(), js.Get("optional_param").MustInt64(5150))
|
||||
func (j *Json) MustInt64(args ...int64) int64 {
|
||||
var def int64
|
||||
|
||||
@@ -493,7 +505,8 @@ func (j *Json) MustInt64(args ...int64) int64 {
|
||||
// MustUInt64 guarantees the return of an `uint64` (with optional default)
|
||||
//
|
||||
// useful when you explicitly want an `uint64` in a single value return context:
|
||||
// myFunc(js.Get("param1").MustUint64(), js.Get("optional_param").MustUint64(5150))
|
||||
//
|
||||
// myFunc(js.Get("param1").MustUint64(), js.Get("optional_param").MustUint64(5150))
|
||||
func (j *Json) MustUint64(args ...uint64) uint64 {
|
||||
var def uint64
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ func (cr classicReducer) ValidReduceFunc() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
//nolint: gocyclo
|
||||
//nolint:gocyclo
|
||||
func (cr classicReducer) Reduce(series mathexp.Series) mathexp.Number {
|
||||
num := mathexp.NewNumber("", nil)
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// Package gcsifaces provides interfaces for Google Cloud Storage.
|
||||
//
|
||||
//go:generate mockgen -source $GOFILE -destination ../../mocks/mock_gcsifaces/mocks.go StorageClient
|
||||
package gcsifaces
|
||||
|
||||
|
||||
@@ -7,11 +7,12 @@ import (
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/grafana/grafana/pkg/infra/log"
|
||||
"gocloud.dev/blob"
|
||||
_ "gocloud.dev/blob/fileblob"
|
||||
_ "gocloud.dev/blob/memblob"
|
||||
"gocloud.dev/gcerrors"
|
||||
|
||||
"github.com/grafana/grafana/pkg/infra/log"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -272,7 +273,7 @@ func (c cdkBlobStorage) DeleteFolder(ctx context.Context, folderPath string, opt
|
||||
return lastErr
|
||||
}
|
||||
|
||||
//nolint: gocyclo
|
||||
//nolint:gocyclo
|
||||
func (c cdkBlobStorage) list(ctx context.Context, folderPath string, paging *Paging, options *ListOptions) (*ListResponse, error) {
|
||||
lowerRootPath := strings.ToLower(folderPath)
|
||||
iterators := []*blob.ListIterator{c.bucket.List(&blob.ListOptions{
|
||||
|
||||
@@ -275,7 +275,7 @@ func upsertProperty(dialect migrator.Dialect, sess *sqlstore.DBSession, now time
|
||||
return err
|
||||
}
|
||||
|
||||
//nolint: gocyclo
|
||||
//nolint:gocyclo
|
||||
func (s dbFileStorage) List(ctx context.Context, folderPath string, paging *Paging, options *ListOptions) (*ListResponse, error) {
|
||||
var resp *ListResponse
|
||||
|
||||
|
||||
@@ -76,6 +76,7 @@ func copyFileContents(src, dst string) (err error) {
|
||||
}
|
||||
}()
|
||||
|
||||
//nolint:gosec
|
||||
out, err := os.Create(dst)
|
||||
if err != nil {
|
||||
return
|
||||
|
||||
@@ -11,7 +11,7 @@ var dbCallCounterNameKey = contextKey{}
|
||||
|
||||
// InitCounter creates a pointer on the context that can be incremented later
|
||||
func InitCounter(ctx context.Context) context.Context {
|
||||
var ptr *int64 = new(int64)
|
||||
var ptr = new(int64)
|
||||
return context.WithValue(ctx, dbCallCounterNameKey, ptr)
|
||||
}
|
||||
|
||||
|
||||
@@ -205,9 +205,12 @@ func (cl *ConcreteLogger) New(ctx ...interface{}) *ConcreteLogger {
|
||||
// name plus additional contextual information, you must use the
|
||||
// Logger interface New method for it to work as expected.
|
||||
// Example creating a shared logger:
|
||||
// requestLogger := log.New("request-logger")
|
||||
//
|
||||
// requestLogger := log.New("request-logger")
|
||||
//
|
||||
// Example creating a contextual logger:
|
||||
// contextualLogger := requestLogger.New("username", "user123")
|
||||
//
|
||||
// contextualLogger := requestLogger.New("username", "user123")
|
||||
func New(ctx ...interface{}) *ConcreteLogger {
|
||||
if len(ctx) == 0 {
|
||||
return root.New()
|
||||
|
||||
@@ -34,12 +34,11 @@ type terminalLogger struct {
|
||||
// level output and terser human friendly timestamp.
|
||||
// This format should only be used for interactive programs or while developing.
|
||||
//
|
||||
// [TIME] [LEVEL] MESSAGE key=value key=value ...
|
||||
// [TIME] [LEVEL] MESSAGE key=value key=value ...
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// [May 16 20:58:45] [DBUG] remove route ns=haproxy addr=127.0.0.1:50002
|
||||
//
|
||||
// [May 16 20:58:45] [DBUG] remove route ns=haproxy addr=127.0.0.1:50002
|
||||
func NewTerminalLogger(w io.Writer) gokitlog.Logger {
|
||||
return &terminalLogger{w}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/go-kit/log"
|
||||
|
||||
glog "github.com/grafana/grafana/pkg/infra/log"
|
||||
"github.com/grafana/grafana/pkg/registry"
|
||||
"github.com/grafana/grafana/pkg/services/sqlstore"
|
||||
@@ -45,7 +46,7 @@ func ProvideService(cfg *setting.Cfg, sqlStore *sqlstore.SQLStore) (*RemoteCache
|
||||
// CacheStorage allows the caller to set, get and delete items in the cache.
|
||||
// Cached items are stored as byte arrays and marshalled using "encoding/gob"
|
||||
// so any struct added to the cache needs to be registered with `remotecache.Register`
|
||||
// ex `remotecache.Register(CacheableStruct{})``
|
||||
// ex `remotecache.Register(CacheableStruct{})`
|
||||
type CacheStorage interface {
|
||||
// Get reads object from Cache
|
||||
Get(ctx context.Context, key string) (interface{}, error)
|
||||
|
||||
@@ -96,9 +96,7 @@ func (dto *DashboardACLInfoDTO) IsDuplicateOf(other *DashboardACLInfoDTO) bool {
|
||||
return dto.hasSameRoleAs(other) || dto.hasSameUserAs(other) || dto.hasSameTeamAs(other)
|
||||
}
|
||||
|
||||
//
|
||||
// QUERIES
|
||||
//
|
||||
type GetDashboardACLInfoListQuery struct {
|
||||
DashboardID int64
|
||||
OrgID int64
|
||||
|
||||
@@ -8,13 +8,14 @@ package pluginextensionv2
|
||||
|
||||
import (
|
||||
context "context"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
|
||||
grpc "google.golang.org/grpc"
|
||||
codes "google.golang.org/grpc/codes"
|
||||
status "google.golang.org/grpc/status"
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -8,13 +8,14 @@ package pluginextensionv2
|
||||
|
||||
import (
|
||||
context "context"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
|
||||
grpc "google.golang.org/grpc"
|
||||
codes "google.golang.org/grpc/codes"
|
||||
status "google.golang.org/grpc/status"
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -7,10 +7,11 @@
|
||||
package secretsmanagerplugin
|
||||
|
||||
import (
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -8,6 +8,7 @@ package secretsmanagerplugin
|
||||
|
||||
import (
|
||||
context "context"
|
||||
|
||||
grpc "google.golang.org/grpc"
|
||||
codes "google.golang.org/grpc/codes"
|
||||
status "google.golang.org/grpc/status"
|
||||
|
||||
@@ -47,6 +47,7 @@ func TestUninstall(t *testing.T) {
|
||||
|
||||
pluginDir := t.TempDir()
|
||||
pluginJSON := filepath.Join(pluginDir, "plugin.json")
|
||||
//nolint:gosec
|
||||
_, err := os.Create(pluginJSON)
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -61,6 +62,7 @@ func TestUninstall(t *testing.T) {
|
||||
err = os.Mkdir(pluginDistDir, os.ModePerm)
|
||||
require.NoError(t, err)
|
||||
pluginJSON = filepath.Join(pluginDistDir, "plugin.json")
|
||||
//nolint:gosec
|
||||
_, err = os.Create(pluginJSON)
|
||||
require.NoError(t, err)
|
||||
|
||||
|
||||
@@ -29,7 +29,8 @@ import (
|
||||
)
|
||||
|
||||
// Soon we can fetch keys from:
|
||||
// https://grafana.com/api/plugins/ci/keys
|
||||
//
|
||||
// https://grafana.com/api/plugins/ci/keys
|
||||
const publicKeyText = `-----BEGIN PGP PUBLIC KEY BLOCK-----
|
||||
Version: OpenPGP.js v4.10.1
|
||||
Comment: https://openpgpjs.org
|
||||
|
||||
@@ -120,7 +120,7 @@ func getScopeCacheKey(orgID int64, scope string) string {
|
||||
return fmt.Sprintf("%s-%v", scope, orgID)
|
||||
}
|
||||
|
||||
//ScopeInjector inject request params into the templated scopes. e.g. "settings:" + eval.Parameters(":id")
|
||||
// ScopeInjector inject request params into the templated scopes. e.g. "settings:" + eval.Parameters(":id")
|
||||
func ScopeInjector(params ScopeParams) ScopeAttributeMutator {
|
||||
return func(_ context.Context, scope string) ([]string, error) {
|
||||
tmpl, err := template.New("scope").Parse(scope)
|
||||
|
||||
@@ -126,7 +126,7 @@ type fakeIntervalTestReqHandler struct {
|
||||
verifier queryIntervalVerifier
|
||||
}
|
||||
|
||||
//nolint: staticcheck // legacydata.DataResponse deprecated
|
||||
//nolint:staticcheck // legacydata.DataResponse deprecated
|
||||
func (rh fakeIntervalTestReqHandler) HandleRequest(ctx context.Context, dsInfo *datasources.DataSource, query legacydata.DataQuery) (
|
||||
legacydata.DataResponse, error) {
|
||||
q := query.Queries[0]
|
||||
@@ -134,7 +134,7 @@ func (rh fakeIntervalTestReqHandler) HandleRequest(ctx context.Context, dsInfo *
|
||||
return rh.response, nil
|
||||
}
|
||||
|
||||
//nolint: staticcheck // legacydata.DataResponse deprecated
|
||||
//nolint:staticcheck // legacydata.DataResponse deprecated
|
||||
func applyScenario(t *testing.T, timeRange string, dataSourceJsonData *simplejson.Json, queryModel string, verifier func(query legacydata.DataSubQuery)) {
|
||||
t.Run("desc", func(t *testing.T) {
|
||||
store := mockstore.NewSQLStoreMock()
|
||||
|
||||
@@ -205,7 +205,7 @@ type queryConditionTestContext struct {
|
||||
condition *QueryCondition
|
||||
}
|
||||
|
||||
//nolint: staticcheck // legacydata.DataPlugin deprecated
|
||||
//nolint:staticcheck // legacydata.DataPlugin deprecated
|
||||
func (ctx *queryConditionTestContext) exec(t *testing.T) (*alerting.ConditionResult, error) {
|
||||
jsonModel, err := simplejson.NewJson([]byte(`{
|
||||
"type": "query",
|
||||
@@ -249,7 +249,7 @@ type fakeReqHandler struct {
|
||||
response legacydata.DataResponse
|
||||
}
|
||||
|
||||
//nolint: staticcheck // legacydata.DataPlugin deprecated
|
||||
//nolint:staticcheck // legacydata.DataPlugin deprecated
|
||||
func (rh fakeReqHandler) HandleRequest(context.Context, *datasources.DataSource, legacydata.DataQuery) (
|
||||
legacydata.DataResponse, error) {
|
||||
return rh.response, nil
|
||||
|
||||
@@ -17,7 +17,7 @@ type queryReducer struct {
|
||||
Type string
|
||||
}
|
||||
|
||||
//nolint: gocyclo
|
||||
//nolint:gocyclo
|
||||
func (s *queryReducer) Reduce(series legacydata.DataTimeSeries) null.Float {
|
||||
if len(series.Points) == 0 {
|
||||
return null.FloatFromPtr(nil)
|
||||
|
||||
@@ -16,7 +16,8 @@ import (
|
||||
)
|
||||
|
||||
// for stubbing in tests
|
||||
//nolint: gocritic
|
||||
//
|
||||
//nolint:gocritic
|
||||
var newImageUploaderProvider = func() (imguploader.ImageUploader, error) {
|
||||
return imguploader.NewImageUploader()
|
||||
}
|
||||
|
||||
@@ -54,7 +54,8 @@ type GoogleChatNotifier struct {
|
||||
log log.Logger
|
||||
}
|
||||
|
||||
/**
|
||||
/*
|
||||
*
|
||||
Structs used to build a custom Google Hangouts Chat message card.
|
||||
See: https://developers.google.com/hangouts/chat/reference/message-formats/cards
|
||||
*/
|
||||
|
||||
@@ -11,10 +11,10 @@ import (
|
||||
)
|
||||
|
||||
// Ticker is a ticker to power the alerting scheduler. it's like a time.Ticker, except:
|
||||
// * it doesn't drop ticks for slow receivers, rather, it queues up. so that callers are in control to instrument what's going on.
|
||||
// * it ticks on interval marks or very shortly after. this provides a predictable load pattern
|
||||
// (this shouldn't cause too much load contention issues because the next steps in the pipeline just process at their own pace)
|
||||
// * the timestamps are used to mark "last datapoint to query for" and as such, are a configurable amount of seconds in the past
|
||||
// - it doesn't drop ticks for slow receivers, rather, it queues up. so that callers are in control to instrument what's going on.
|
||||
// - it ticks on interval marks or very shortly after. this provides a predictable load pattern
|
||||
// (this shouldn't cause too much load contention issues because the next steps in the pipeline just process at their own pace)
|
||||
// - the timestamps are used to mark "last datapoint to query for" and as such, are a configurable amount of seconds in the past
|
||||
type Ticker struct {
|
||||
C chan time.Time
|
||||
clock clock.Clock
|
||||
|
||||
@@ -6,8 +6,9 @@ import (
|
||||
"reflect"
|
||||
"time"
|
||||
|
||||
"github.com/grafana/grafana/pkg/models"
|
||||
"gopkg.in/square/go-jose.v2/jwt"
|
||||
|
||||
"github.com/grafana/grafana/pkg/models"
|
||||
)
|
||||
|
||||
func (s *AuthService) initClaimExpectations() error {
|
||||
@@ -35,8 +36,8 @@ func (s *AuthService) initClaimExpectations() error {
|
||||
switch value := value.(type) {
|
||||
case []interface{}:
|
||||
for _, val := range value {
|
||||
if val, ok := val.(string); ok {
|
||||
s.expectRegistered.Audience = append(s.expectRegistered.Audience, val)
|
||||
if v, ok := val.(string); ok {
|
||||
s.expectRegistered.Audience = append(s.expectRegistered.Audience, v)
|
||||
} else {
|
||||
return fmt.Errorf("%q expectation contains value with invalid type %T, string expected", key, val)
|
||||
}
|
||||
@@ -73,8 +74,8 @@ func (s *AuthService) validateClaims(claims models.JWTClaims) error {
|
||||
switch value := value.(type) {
|
||||
case []interface{}:
|
||||
for _, val := range value {
|
||||
if val, ok := val.(string); ok {
|
||||
registeredClaims.Audience = append(registeredClaims.Audience, val)
|
||||
if v, ok := val.(string); ok {
|
||||
registeredClaims.Audience = append(registeredClaims.Audience, v)
|
||||
} else {
|
||||
return fmt.Errorf("%q claim contains value with invalid type %T, string expected", key, val)
|
||||
}
|
||||
|
||||
@@ -6,8 +6,9 @@ import (
|
||||
"github.com/grafana/grafana/pkg/models"
|
||||
)
|
||||
|
||||
//go:generate mockery --name DashboardService --structname FakeDashboardService --inpackage --filename dashboard_service_mock.go
|
||||
// DashboardService is a service for operating on dashboards.
|
||||
//
|
||||
//go:generate mockery --name DashboardService --structname FakeDashboardService --inpackage --filename dashboard_service_mock.go
|
||||
type DashboardService interface {
|
||||
BuildSaveDashboardCommand(ctx context.Context, dto *SaveDashboardDTO, shouldValidateAlerts bool, validateProvisionedDashboard bool) (*models.SaveDashboardCommand, error)
|
||||
DeleteDashboard(ctx context.Context, dashboardId int64, orgId int64) error
|
||||
@@ -32,8 +33,9 @@ type PluginService interface {
|
||||
GetDashboardsByPluginID(ctx context.Context, query *models.GetDashboardsByPluginIdQuery) error
|
||||
}
|
||||
|
||||
//go:generate mockery --name DashboardProvisioningService --structname FakeDashboardProvisioning --inpackage --filename dashboard_provisioning_mock.go
|
||||
// DashboardProvisioningService is a service for operating on provisioned dashboards.
|
||||
//
|
||||
//go:generate mockery --name DashboardProvisioningService --structname FakeDashboardProvisioning --inpackage --filename dashboard_provisioning_mock.go
|
||||
type DashboardProvisioningService interface {
|
||||
DeleteOrphanedProvisionedDashboards(ctx context.Context, cmd *models.DeleteOrphanedProvisionedDashboardsCommand) error
|
||||
DeleteProvisionedDashboard(ctx context.Context, dashboardID int64, orgID int64) error
|
||||
@@ -45,8 +47,9 @@ type DashboardProvisioningService interface {
|
||||
UnprovisionDashboard(ctx context.Context, dashboardID int64) error
|
||||
}
|
||||
|
||||
//go:generate mockery --name Store --structname FakeDashboardStore --inpackage --filename store_mock.go
|
||||
// Store is a dashboard store.
|
||||
//
|
||||
//go:generate mockery --name Store --structname FakeDashboardStore --inpackage --filename store_mock.go
|
||||
type Store interface {
|
||||
DeleteDashboard(ctx context.Context, cmd *models.DeleteDashboardCommand) error
|
||||
DeleteOrphanedProvisionedDashboards(ctx context.Context, cmd *models.DeleteOrphanedProvisionedDashboardsCommand) error
|
||||
@@ -76,8 +79,9 @@ type Store interface {
|
||||
FolderStore
|
||||
}
|
||||
|
||||
//go:generate mockery --name FolderStore --structname FakeFolderStore --inpackage --filename folder_store_mock.go
|
||||
// FolderStore is a folder store.
|
||||
//
|
||||
//go:generate mockery --name FolderStore --structname FakeFolderStore --inpackage --filename folder_store_mock.go
|
||||
type FolderStore interface {
|
||||
// GetFolderByTitle retrieves a folder by its title
|
||||
GetFolderByTitle(ctx context.Context, orgID int64, title string) (*models.Folder, error)
|
||||
|
||||
@@ -6,8 +6,9 @@ import (
|
||||
"github.com/grafana/grafana/pkg/models"
|
||||
)
|
||||
|
||||
//go:generate mockery --name FolderService --structname FakeFolderService --inpackage --filename folder_service_mock.go
|
||||
// FolderService is a service for operating on folders.
|
||||
//
|
||||
//go:generate mockery --name FolderService --structname FakeFolderService --inpackage --filename folder_service_mock.go
|
||||
type FolderService interface {
|
||||
GetFolders(ctx context.Context, user *models.SignedInUser, orgID int64, limit int64, page int64) ([]*models.Folder, error)
|
||||
GetFolderByID(ctx context.Context, user *models.SignedInUser, id int64, orgID int64) (*models.Folder, error)
|
||||
|
||||
@@ -65,7 +65,8 @@ func ToDelimited(s string, delimiter uint8) string {
|
||||
// (in this case `delimiter = '.'; screaming = true`)
|
||||
// or delimited.snake.case
|
||||
// (in this case `delimiter = '.'; screaming = false`)
|
||||
//nolint: gocyclo
|
||||
//
|
||||
//nolint:gocyclo
|
||||
func ToScreamingDelimited(s string, delimiter uint8, ignore string, screaming bool) string {
|
||||
s = strings.TrimSpace(s)
|
||||
n := strings.Builder{}
|
||||
|
||||
@@ -3,23 +3,22 @@
|
||||
// Package definitions includes the types required for generating or consuming an OpenAPI
|
||||
// spec for the Grafana Alerting API.
|
||||
//
|
||||
// Schemes: http, https
|
||||
// BasePath: /api/v1
|
||||
// Version: 1.1.0
|
||||
//
|
||||
// Schemes: http, https
|
||||
// BasePath: /api/v1
|
||||
// Version: 1.1.0
|
||||
// Consumes:
|
||||
// - application/json
|
||||
//
|
||||
// Consumes:
|
||||
// - application/json
|
||||
// Produces:
|
||||
// - application/json
|
||||
//
|
||||
// Produces:
|
||||
// - application/json
|
||||
// Security:
|
||||
// - basic
|
||||
//
|
||||
// Security:
|
||||
// - basic
|
||||
//
|
||||
// SecurityDefinitions:
|
||||
// basic:
|
||||
// type: basic
|
||||
// SecurityDefinitions:
|
||||
// basic:
|
||||
// type: basic
|
||||
//
|
||||
// swagger:meta
|
||||
package definitions
|
||||
|
||||
@@ -330,18 +330,18 @@ func executeQueriesAndExpressions(ctx AlertExecCtx, data []models.AlertQuery, no
|
||||
//
|
||||
// For example, given the following:
|
||||
//
|
||||
// map[string]string{
|
||||
// "ref1": "datasource1",
|
||||
// "ref2": "datasource1",
|
||||
// "ref3": "datasource2",
|
||||
// }
|
||||
// map[string]string{
|
||||
// "ref1": "datasource1",
|
||||
// "ref2": "datasource1",
|
||||
// "ref3": "datasource2",
|
||||
// }
|
||||
//
|
||||
// we would expect:
|
||||
//
|
||||
// map[string][]string{
|
||||
// "datasource1": []string{"ref1", "ref2"},
|
||||
// "datasource2": []string{"ref3"},
|
||||
// }
|
||||
// map[string][]string{
|
||||
// "datasource1": []string{"ref1", "ref2"},
|
||||
// "datasource2": []string{"ref3"},
|
||||
// }
|
||||
func datasourceUIDsToRefIDs(refIDsToDatasourceUIDs map[string]string) map[string][]string {
|
||||
if refIDsToDatasourceUIDs == nil {
|
||||
return nil
|
||||
@@ -376,12 +376,15 @@ func datasourceUIDsToRefIDs(refIDsToDatasourceUIDs map[string]string) map[string
|
||||
// Also, each Frame must be uniquely identified by its Field.Labels or a single Error result will be returned.
|
||||
//
|
||||
// Per Frame, data becomes a State based on the following rules:
|
||||
// - Empty or zero length Frames result in NoData.
|
||||
// - If a value:
|
||||
// - 0 results in Normal.
|
||||
// - Nonzero (e.g 1.2, NaN) results in Alerting.
|
||||
// - nil results in noData.
|
||||
// - unsupported Frame schemas results in Error.
|
||||
//
|
||||
// If no value is set:
|
||||
// - Empty or zero length Frames result in NoData.
|
||||
//
|
||||
// If a value is set:
|
||||
// - 0 results in Normal.
|
||||
// - Nonzero (e.g 1.2, NaN) results in Alerting.
|
||||
// - nil results in noData.
|
||||
// - unsupported Frame schemas results in Error.
|
||||
func evaluateExecutionResult(execResults ExecutionResults, ts time.Time) Results {
|
||||
evalResults := make([]Result, 0)
|
||||
|
||||
|
||||
@@ -48,8 +48,8 @@ type FakeEvaluator_ConditionEval_Call struct {
|
||||
}
|
||||
|
||||
// ConditionEval is a helper method to define mock.On call
|
||||
// - condition models.Condition
|
||||
// - now time.Time
|
||||
// - condition models.Condition
|
||||
// - now time.Time
|
||||
func (_e *FakeEvaluator_Expecter) ConditionEval(condition interface{}, now interface{}) *FakeEvaluator_ConditionEval_Call {
|
||||
return &FakeEvaluator_ConditionEval_Call{Call: _e.mock.On("ConditionEval", condition, now)}
|
||||
}
|
||||
@@ -95,9 +95,9 @@ type FakeEvaluator_QueriesAndExpressionsEval_Call struct {
|
||||
}
|
||||
|
||||
// QueriesAndExpressionsEval is a helper method to define mock.On call
|
||||
// - orgID int64
|
||||
// - data []models.AlertQuery
|
||||
// - now time.Time
|
||||
// - orgID int64
|
||||
// - data []models.AlertQuery
|
||||
// - now time.Time
|
||||
func (_e *FakeEvaluator_Expecter) QueriesAndExpressionsEval(orgID interface{}, data interface{}, now interface{}) *FakeEvaluator_QueriesAndExpressionsEval_Call {
|
||||
return &FakeEvaluator_QueriesAndExpressionsEval_Call{Call: _e.mock.On("QueriesAndExpressionsEval", orgID, data, now)}
|
||||
}
|
||||
|
||||
@@ -394,7 +394,8 @@ func (c Condition) IsValid() bool {
|
||||
// There are several exceptions:
|
||||
// 1. Following fields are not patched and therefore will be ignored: AlertRule.ID, AlertRule.OrgID, AlertRule.Updated, AlertRule.Version, AlertRule.UID, AlertRule.DashboardUID, AlertRule.PanelID, AlertRule.Annotations and AlertRule.Labels
|
||||
// 2. There are fields that are patched together:
|
||||
// - AlertRule.Condition and AlertRule.Data
|
||||
// - AlertRule.Condition and AlertRule.Data
|
||||
//
|
||||
// If either of the pair is specified, neither is patched.
|
||||
func PatchPartialAlertRule(existingRule *AlertRule, ruleToPatch *AlertRule) {
|
||||
if ruleToPatch.Title == "" {
|
||||
|
||||
@@ -110,11 +110,12 @@ func newTestImage() (string, error) {
|
||||
// mockTimeNow replaces function timeNow to return constant time.
|
||||
// It returns a function that resets the variable back to its original value.
|
||||
// This allows usage of this function with defer:
|
||||
// func Test (t *testing.T) {
|
||||
// now := time.Now()
|
||||
// defer mockTimeNow(now)()
|
||||
// ...
|
||||
// }
|
||||
//
|
||||
// func Test (t *testing.T) {
|
||||
// now := time.Now()
|
||||
// defer mockTimeNow(now)()
|
||||
// ...
|
||||
// }
|
||||
func mockTimeNow(constTime time.Time) func() {
|
||||
timeNow = func() time.Time {
|
||||
return constTime
|
||||
|
||||
@@ -96,6 +96,7 @@ func withStoredImages(ctx context.Context, l log.Logger, imageStore ImageStore,
|
||||
|
||||
// The path argument here comes from reading internal image storage, not user
|
||||
// input, so we ignore the security check here.
|
||||
//
|
||||
//nolint:gosec
|
||||
func openImage(path string) (io.ReadCloser, error) {
|
||||
fp := filepath.Clean(path)
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
)
|
||||
|
||||
// AMStore is a store of Alertmanager configurations.
|
||||
//
|
||||
//go:generate mockery --name AMConfigStore --structname MockAMConfigStore --inpackage --filename persist_mock.go --with-expecter
|
||||
type AMConfigStore interface {
|
||||
GetLatestAlertmanagerConfiguration(ctx context.Context, query *models.GetLatestAlertmanagerConfigurationQuery) error
|
||||
@@ -19,6 +20,7 @@ type AMConfigStore interface {
|
||||
}
|
||||
|
||||
// ProvisioningStore is a store of provisioning data for arbitrary objects.
|
||||
//
|
||||
//go:generate mockery --name ProvisioningStore --structname MockProvisioningStore --inpackage --filename provisioning_store_mock.go --with-expecter
|
||||
type ProvisioningStore interface {
|
||||
GetProvenance(ctx context.Context, o models.Provisionable, org int64) (models.Provenance, error)
|
||||
@@ -44,6 +46,7 @@ type RuleStore interface {
|
||||
}
|
||||
|
||||
// QuotaChecker represents the ability to evaluate whether quotas are met.
|
||||
//
|
||||
//go:generate mockery --name QuotaChecker --structname MockQuotaChecker --inpackage --filename quota_checker_mock.go --with-expecter
|
||||
type QuotaChecker interface {
|
||||
CheckQuotaReached(ctx context.Context, target string, scopeParams *quota.ScopeParameters) (bool, error)
|
||||
|
||||
@@ -44,8 +44,8 @@ type MockAMConfigStore_GetLatestAlertmanagerConfiguration_Call struct {
|
||||
}
|
||||
|
||||
// GetLatestAlertmanagerConfiguration is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - query *models.GetLatestAlertmanagerConfigurationQuery
|
||||
// - ctx context.Context
|
||||
// - query *models.GetLatestAlertmanagerConfigurationQuery
|
||||
func (_e *MockAMConfigStore_Expecter) GetLatestAlertmanagerConfiguration(ctx interface{}, query interface{}) *MockAMConfigStore_GetLatestAlertmanagerConfiguration_Call {
|
||||
return &MockAMConfigStore_GetLatestAlertmanagerConfiguration_Call{Call: _e.mock.On("GetLatestAlertmanagerConfiguration", ctx, query)}
|
||||
}
|
||||
@@ -82,8 +82,8 @@ type MockAMConfigStore_UpdateAlertmanagerConfiguration_Call struct {
|
||||
}
|
||||
|
||||
// UpdateAlertmanagerConfiguration is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - cmd *models.SaveAlertmanagerConfigurationCmd
|
||||
// - ctx context.Context
|
||||
// - cmd *models.SaveAlertmanagerConfigurationCmd
|
||||
func (_e *MockAMConfigStore_Expecter) UpdateAlertmanagerConfiguration(ctx interface{}, cmd interface{}) *MockAMConfigStore_UpdateAlertmanagerConfiguration_Call {
|
||||
return &MockAMConfigStore_UpdateAlertmanagerConfiguration_Call{Call: _e.mock.On("UpdateAlertmanagerConfiguration", ctx, cmd)}
|
||||
}
|
||||
|
||||
@@ -44,9 +44,9 @@ type MockProvisioningStore_DeleteProvenance_Call struct {
|
||||
}
|
||||
|
||||
// DeleteProvenance is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - o models.Provisionable
|
||||
// - org int64
|
||||
// - ctx context.Context
|
||||
// - o models.Provisionable
|
||||
// - org int64
|
||||
func (_e *MockProvisioningStore_Expecter) DeleteProvenance(ctx interface{}, o interface{}, org interface{}) *MockProvisioningStore_DeleteProvenance_Call {
|
||||
return &MockProvisioningStore_DeleteProvenance_Call{Call: _e.mock.On("DeleteProvenance", ctx, o, org)}
|
||||
}
|
||||
@@ -90,9 +90,9 @@ type MockProvisioningStore_GetProvenance_Call struct {
|
||||
}
|
||||
|
||||
// GetProvenance is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - o models.Provisionable
|
||||
// - org int64
|
||||
// - ctx context.Context
|
||||
// - o models.Provisionable
|
||||
// - org int64
|
||||
func (_e *MockProvisioningStore_Expecter) GetProvenance(ctx interface{}, o interface{}, org interface{}) *MockProvisioningStore_GetProvenance_Call {
|
||||
return &MockProvisioningStore_GetProvenance_Call{Call: _e.mock.On("GetProvenance", ctx, o, org)}
|
||||
}
|
||||
@@ -138,9 +138,9 @@ type MockProvisioningStore_GetProvenances_Call struct {
|
||||
}
|
||||
|
||||
// GetProvenances is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - org int64
|
||||
// - resourceType string
|
||||
// - ctx context.Context
|
||||
// - org int64
|
||||
// - resourceType string
|
||||
func (_e *MockProvisioningStore_Expecter) GetProvenances(ctx interface{}, org interface{}, resourceType interface{}) *MockProvisioningStore_GetProvenances_Call {
|
||||
return &MockProvisioningStore_GetProvenances_Call{Call: _e.mock.On("GetProvenances", ctx, org, resourceType)}
|
||||
}
|
||||
@@ -177,10 +177,10 @@ type MockProvisioningStore_SetProvenance_Call struct {
|
||||
}
|
||||
|
||||
// SetProvenance is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - o models.Provisionable
|
||||
// - org int64
|
||||
// - p models.Provenance
|
||||
// - ctx context.Context
|
||||
// - o models.Provisionable
|
||||
// - org int64
|
||||
// - p models.Provenance
|
||||
func (_e *MockProvisioningStore_Expecter) SetProvenance(ctx interface{}, o interface{}, org interface{}, p interface{}) *MockProvisioningStore_SetProvenance_Call {
|
||||
return &MockProvisioningStore_SetProvenance_Call{Call: _e.mock.On("SetProvenance", ctx, o, org, p)}
|
||||
}
|
||||
|
||||
@@ -51,9 +51,9 @@ type MockQuotaChecker_CheckQuotaReached_Call struct {
|
||||
}
|
||||
|
||||
// CheckQuotaReached is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - target string
|
||||
// - scopeParams *quota.ScopeParameters
|
||||
// - ctx context.Context
|
||||
// - target string
|
||||
// - scopeParams *quota.ScopeParameters
|
||||
func (_e *MockQuotaChecker_Expecter) CheckQuotaReached(ctx interface{}, target interface{}, scopeParams interface{}) *MockQuotaChecker_CheckQuotaReached_Call {
|
||||
return &MockQuotaChecker_CheckQuotaReached_Call{Call: _e.mock.On("CheckQuotaReached", ctx, target, scopeParams)}
|
||||
}
|
||||
|
||||
@@ -33,8 +33,8 @@ type AlertsSenderMock_Send_Call struct {
|
||||
}
|
||||
|
||||
// Send is a helper method to define mock.On call
|
||||
// - key models.AlertRuleKey
|
||||
// - alerts definitions.PostableAlerts
|
||||
// - key models.AlertRuleKey
|
||||
// - alerts definitions.PostableAlerts
|
||||
func (_e *AlertsSenderMock_Expecter) Send(key interface{}, alerts interface{}) *AlertsSenderMock_Send_Call {
|
||||
return &AlertsSenderMock_Send_Call{Call: _e.mock.On("Send", key, alerts)}
|
||||
}
|
||||
|
||||
@@ -91,6 +91,7 @@ func newAlertRuleInfo(parent context.Context) *alertRuleInfo {
|
||||
// Returns a tuple where first element is
|
||||
// - true when message was sent
|
||||
// - false when the send operation is stopped
|
||||
//
|
||||
// the second element contains a dropped message that was sent by a concurrent sender.
|
||||
func (a *alertRuleInfo) eval(t time.Time, rule *models.AlertRule) (bool, *evaluation) {
|
||||
// read the channel in unblocking manner to make sure that there is no concurrent send operation.
|
||||
|
||||
@@ -25,6 +25,7 @@ import (
|
||||
|
||||
// ScheduleService is an interface for a service that schedules the evaluation
|
||||
// of alert rules.
|
||||
//
|
||||
//go:generate mockery --name ScheduleService --structname FakeScheduleService --inpackage --filename schedule_mock.go --unroll-variadic=False
|
||||
type ScheduleService interface {
|
||||
// Run the scheduler until the context is canceled or the scheduler returns
|
||||
@@ -40,8 +41,9 @@ type ScheduleService interface {
|
||||
overrideCfg(cfg SchedulerCfg)
|
||||
}
|
||||
|
||||
//go:generate mockery --name AlertsSender --structname AlertsSenderMock --inpackage --filename alerts_sender_mock.go --with-expecter
|
||||
// AlertsSender is an interface for a service that is responsible for sending notifications to the end-user.
|
||||
//
|
||||
//go:generate mockery --name AlertsSender --structname AlertsSenderMock --inpackage --filename alerts_sender_mock.go --with-expecter
|
||||
type AlertsSender interface {
|
||||
Send(key ngmodels.AlertRuleKey, alerts definitions.PostableAlerts)
|
||||
}
|
||||
|
||||
@@ -252,7 +252,7 @@ func assertEvalRun(t *testing.T, ch <-chan evalAppliedInfo, tick time.Time, keys
|
||||
case info := <-ch:
|
||||
_, ok := expected[info.alertDefKey]
|
||||
if !ok {
|
||||
t.Fatal(fmt.Sprintf("alert rule: %v should not have been evaluated at: %v", info.alertDefKey, info.now))
|
||||
t.Fatalf("alert rule: %v should not have been evaluated at: %v", info.alertDefKey, info.now)
|
||||
}
|
||||
t.Logf("alert rule: %v evaluated at: %v", info.alertDefKey, info.now)
|
||||
assert.Equal(t, tick, info.now)
|
||||
|
||||
@@ -40,7 +40,7 @@ type AdminConfigurationStoreMock_DeleteAdminConfiguration_Call struct {
|
||||
}
|
||||
|
||||
// DeleteAdminConfiguration is a helper method to define mock.On call
|
||||
// - orgID int64
|
||||
// - orgID int64
|
||||
func (_e *AdminConfigurationStoreMock_Expecter) DeleteAdminConfiguration(orgID interface{}) *AdminConfigurationStoreMock_DeleteAdminConfiguration_Call {
|
||||
return &AdminConfigurationStoreMock_DeleteAdminConfiguration_Call{Call: _e.mock.On("DeleteAdminConfiguration", orgID)}
|
||||
}
|
||||
@@ -86,7 +86,7 @@ type AdminConfigurationStoreMock_GetAdminConfiguration_Call struct {
|
||||
}
|
||||
|
||||
// GetAdminConfiguration is a helper method to define mock.On call
|
||||
// - orgID int64
|
||||
// - orgID int64
|
||||
func (_e *AdminConfigurationStoreMock_Expecter) GetAdminConfiguration(orgID interface{}) *AdminConfigurationStoreMock_GetAdminConfiguration_Call {
|
||||
return &AdminConfigurationStoreMock_GetAdminConfiguration_Call{Call: _e.mock.On("GetAdminConfiguration", orgID)}
|
||||
}
|
||||
@@ -168,7 +168,7 @@ type AdminConfigurationStoreMock_UpdateAdminConfiguration_Call struct {
|
||||
}
|
||||
|
||||
// UpdateAdminConfiguration is a helper method to define mock.On call
|
||||
// - _a0 UpdateAdminConfigurationCmd
|
||||
// - _a0 UpdateAdminConfigurationCmd
|
||||
func (_e *AdminConfigurationStoreMock_Expecter) UpdateAdminConfiguration(_a0 interface{}) *AdminConfigurationStoreMock_UpdateAdminConfiguration_Call {
|
||||
return &AdminConfigurationStoreMock_UpdateAdminConfiguration_Call{Call: _e.mock.On("UpdateAdminConfiguration", _a0)}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
// Package values is a set of value types to use in provisioning. They add custom unmarshaling logic that puts the string values
|
||||
// through os.ExpandEnv.
|
||||
// Usage:
|
||||
// type Data struct {
|
||||
// Field StringValue `yaml:"field"` // Instead of string
|
||||
// }
|
||||
//
|
||||
// type Data struct {
|
||||
// Field StringValue `yaml:"field"` // Instead of string
|
||||
// }
|
||||
//
|
||||
// d := &Data{}
|
||||
// // unmarshal into d
|
||||
// d.Field.Value() // returns the final interpolated value from the yaml file
|
||||
//
|
||||
package values
|
||||
|
||||
import (
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
|
||||
"github.com/grafana/grafana-plugin-sdk-go/backend"
|
||||
"github.com/grafana/grafana-plugin-sdk-go/data"
|
||||
|
||||
"github.com/grafana/grafana/pkg/api/dtos"
|
||||
"github.com/grafana/grafana/pkg/components/simplejson"
|
||||
"github.com/grafana/grafana/pkg/infra/localcache"
|
||||
@@ -265,7 +266,7 @@ func TestApiSavePublicDashboardConfig(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// `/public/dashboards/:uid/query`` endpoint test
|
||||
// `/public/dashboards/:uid/query` endpoint test
|
||||
func TestAPIQueryPublicDashboard(t *testing.T) {
|
||||
cacheService := &fakeDatasources.FakeCacheService{
|
||||
DataSources: []*datasources.DataSource{
|
||||
|
||||
@@ -137,7 +137,7 @@ func buildQueryDataService(t *testing.T, cs datasources.CacheService, fpc *fakeP
|
||||
)
|
||||
}
|
||||
|
||||
//copied from pkg/api/metrics_test.go
|
||||
// copied from pkg/api/metrics_test.go
|
||||
type fakePluginRequestValidator struct {
|
||||
err error
|
||||
}
|
||||
|
||||
@@ -98,9 +98,7 @@ func (pd PublicDashboard) BuildTimeSettings(dashboard *models.Dashboard) *TimeSe
|
||||
return ts
|
||||
}
|
||||
|
||||
//
|
||||
// DTO for transforming user input in the api
|
||||
//
|
||||
type SavePublicDashboardConfigDTO struct {
|
||||
DashboardUid string
|
||||
OrgId int64
|
||||
|
||||
@@ -175,6 +175,7 @@ func (rs *RenderingService) readFileResponse(ctx context.Context, resp *http.Res
|
||||
resp.Status)
|
||||
}
|
||||
|
||||
//nolint:gosec
|
||||
out, err := os.Create(filePath)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -77,6 +77,7 @@ func (s ScreenshotOptions) SetDefaults() ScreenshotOptions {
|
||||
}
|
||||
|
||||
// ScreenshotService is an interface for taking screenshots.
|
||||
//
|
||||
//go:generate mockgen -destination=mock.go -package=screenshot github.com/grafana/grafana/pkg/services/screenshot ScreenshotService
|
||||
type ScreenshotService interface {
|
||||
Take(ctx context.Context, opts ScreenshotOptions) (*Screenshot, error)
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"github.com/blugelabs/bluge/search/aggregations"
|
||||
"github.com/grafana/grafana-plugin-sdk-go/backend"
|
||||
"github.com/grafana/grafana-plugin-sdk-go/data"
|
||||
|
||||
"github.com/grafana/grafana/pkg/infra/log"
|
||||
)
|
||||
|
||||
@@ -349,7 +350,7 @@ func getDashboardLocation(index *orgIndex, dashboardUID string) (string, bool, e
|
||||
return dashboardLocation, found, err
|
||||
}
|
||||
|
||||
//nolint: gocyclo
|
||||
//nolint:gocyclo
|
||||
func doSearchQuery(
|
||||
ctx context.Context,
|
||||
logger log.Logger,
|
||||
|
||||
@@ -8,9 +8,10 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/grafana/grafana/pkg/services/searchV2/dslookup"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/grafana/grafana/pkg/services/searchV2/dslookup"
|
||||
)
|
||||
|
||||
func dsLookup() dslookup.DatasourceLookup {
|
||||
@@ -98,6 +99,7 @@ func TestReadDashboard(t *testing.T) {
|
||||
|
||||
update := false
|
||||
savedPath := filepath.Join("testdata/", input+"-info.json")
|
||||
//nolint:gosec
|
||||
saved, err := os.ReadFile(savedPath)
|
||||
if err != nil {
|
||||
update = true
|
||||
|
||||
@@ -63,7 +63,6 @@ func validateSecretWasStoreInPlugin(t *testing.T, secretsStore SecretsKVStore, c
|
||||
require.Equal(t, 1, len(resPlugin))
|
||||
}
|
||||
|
||||
//
|
||||
func setupTestMigratorService(t *testing.T) (*PluginSecretMigrationService, SecretsKVStore, *secretsKVStoreSQL) {
|
||||
t.Helper()
|
||||
|
||||
|
||||
@@ -82,7 +82,7 @@ func (api *ServiceAccountsAPI) RegisterAPIEndpoints() {
|
||||
|
||||
// swagger:route POST /serviceaccounts service_accounts createServiceAccount
|
||||
//
|
||||
// Create service account
|
||||
// Create service account.
|
||||
//
|
||||
// Required permissions (See note in the [introduction](https://grafana.com/docs/grafana/latest/developers/http_api/serviceaccount/#service-account-api) for an explanation):
|
||||
// action: `serviceaccounts:write` scope: `serviceaccounts:*`
|
||||
@@ -133,7 +133,7 @@ func (api *ServiceAccountsAPI) CreateServiceAccount(c *models.ReqContext) respon
|
||||
|
||||
// swagger:route GET /serviceaccounts/{serviceAccountId} service_accounts retrieveServiceAccount
|
||||
//
|
||||
// Get single serviceaccount by Id
|
||||
// Get single serviceaccount by Id.
|
||||
//
|
||||
// Required permissions (See note in the [introduction](https://grafana.com/docs/grafana/latest/developers/http_api/serviceaccount/#service-account-api) for an explanation):
|
||||
// action: `serviceaccounts:read` scope: `serviceaccounts:id:1` (single service account)
|
||||
@@ -177,7 +177,7 @@ func (api *ServiceAccountsAPI) RetrieveServiceAccount(ctx *models.ReqContext) re
|
||||
|
||||
// swagger:route PATCH /serviceaccounts/{serviceAccountId} service_accounts updateServiceAccount
|
||||
//
|
||||
// Update service account
|
||||
// Update service account.
|
||||
//
|
||||
// Required permissions (See note in the [introduction](https://grafana.com/docs/grafana/latest/developers/http_api/serviceaccount/#service-account-api) for an explanation):
|
||||
// action: `serviceaccounts:write` scope: `serviceaccounts:id:1` (single service account)
|
||||
@@ -246,7 +246,7 @@ func (api *ServiceAccountsAPI) validateRole(r *models.RoleType, orgRole *models.
|
||||
|
||||
// swagger:route DELETE /serviceaccounts/{serviceAccountId} service_accounts deleteServiceAccount
|
||||
//
|
||||
// Delete service account
|
||||
// Delete service account.
|
||||
//
|
||||
// Required permissions (See note in the [introduction](https://grafana.com/docs/grafana/latest/developers/http_api/serviceaccount/#service-account-api) for an explanation):
|
||||
// action: `serviceaccounts:delete` scope: `serviceaccounts:id:1` (single service account)
|
||||
@@ -271,7 +271,7 @@ func (api *ServiceAccountsAPI) DeleteServiceAccount(ctx *models.ReqContext) resp
|
||||
|
||||
// swagger:route GET /serviceaccounts/search service_accounts searchOrgServiceAccountsWithPaging
|
||||
//
|
||||
// Search service accounts with paging
|
||||
// Search service accounts with paging.
|
||||
//
|
||||
// Required permissions (See note in the [introduction](https://grafana.com/docs/grafana/latest/developers/http_api/serviceaccount/#service-account-api) for an explanation):
|
||||
// action: `serviceaccounts:read` scope: `serviceaccounts:*`
|
||||
|
||||
@@ -50,7 +50,7 @@ const sevenDaysAhead = 7 * 24 * time.Hour
|
||||
|
||||
// swagger:route GET /serviceaccounts/{serviceAccountId}/tokens service_accounts listTokens
|
||||
//
|
||||
// Get service account tokens
|
||||
// Get service account tokens.
|
||||
//
|
||||
// Required permissions (See note in the [introduction](https://grafana.com/docs/grafana/latest/developers/http_api/serviceaccount/#service-account-api) for an explanation):
|
||||
// action: `serviceaccounts:read` scope: `global:serviceaccounts:id:1` (single service account)
|
||||
@@ -104,7 +104,7 @@ func (api *ServiceAccountsAPI) ListTokens(ctx *models.ReqContext) response.Respo
|
||||
|
||||
// swagger:route POST /serviceaccounts/{serviceAccountId}/tokens service_accounts createToken
|
||||
//
|
||||
// CreateNewToken adds a token to a service account
|
||||
// CreateNewToken adds a token to a service account.
|
||||
//
|
||||
// Required permissions (See note in the [introduction](https://grafana.com/docs/grafana/latest/developers/http_api/serviceaccount/#service-account-api) for an explanation):
|
||||
// action: `serviceaccounts:write` scope: `serviceaccounts:id:1` (single service account)
|
||||
@@ -178,7 +178,7 @@ func (api *ServiceAccountsAPI) CreateToken(c *models.ReqContext) response.Respon
|
||||
|
||||
// swagger:route DELETE /serviceaccounts/{serviceAccountId}/tokens/{tokenId} service_accounts deleteToken
|
||||
//
|
||||
// DeleteToken deletes service account tokens
|
||||
// DeleteToken deletes service account tokens.
|
||||
//
|
||||
// Required permissions (See note in the [introduction](https://grafana.com/docs/grafana/latest/developers/http_api/serviceaccount/#service-account-api) for an explanation):
|
||||
// action: `serviceaccounts:write` scope: `serviceaccounts:id:1` (single service account)
|
||||
|
||||
@@ -199,6 +199,7 @@ func openReplace(filename string) (*replaceFile, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
//nolint:gosec
|
||||
f, err := os.Create(tmpFilename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -232,7 +232,7 @@ func (m *migration) SQL(dialect migrator.Dialect) string {
|
||||
return codeMigration
|
||||
}
|
||||
|
||||
// nolint: gocyclo
|
||||
//nolint:gocyclo
|
||||
func (m *migration) Exec(sess *xorm.Session, mg *migrator.Migrator) error {
|
||||
m.sess = sess
|
||||
m.mg = mg
|
||||
|
||||
@@ -313,7 +313,7 @@ func (b *BaseDialect) TruncateDBTables() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
//UpsertSQL returns empty string
|
||||
// UpsertSQL returns empty string
|
||||
func (b *BaseDialect) UpsertSQL(tableName string, keyCols, updateCols []string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -415,7 +415,7 @@ func TestIntegrationAccountDataAccess(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
//TODO: Use FakeDashboardStore when org has its own service
|
||||
// TODO: Use FakeDashboardStore when org has its own service
|
||||
func insertTestDashboard(t *testing.T, sqlStore *SQLStore, title string, orgId int64,
|
||||
folderId int64, isFolder bool, tags ...interface{}) *models.Dashboard {
|
||||
t.Helper()
|
||||
@@ -472,7 +472,7 @@ func insertTestDashboard(t *testing.T, sqlStore *SQLStore, title string, orgId i
|
||||
return dash
|
||||
}
|
||||
|
||||
//TODO: Use FakeDashboardStore when org has its own service
|
||||
// TODO: Use FakeDashboardStore when org has its own service
|
||||
func updateDashboardACL(t *testing.T, sqlStore *SQLStore, dashboardID int64, items ...*models.DashboardACL) error {
|
||||
t.Helper()
|
||||
|
||||
|
||||
@@ -21,11 +21,11 @@
|
||||
//
|
||||
// Filters will be applied in order with the final result like such:
|
||||
//
|
||||
// SELECT id FROM dashboard LEFT OUTER JOIN <FilterLeftJoin...>
|
||||
// WHERE <FilterWhere[0]> AND ... AND <FilterWhere[n]>
|
||||
// GROUP BY <FilterGroupBy...>
|
||||
// ORDER BY <FilterOrderBy...>
|
||||
// LIMIT <limit> OFFSET <(page-1)*limit>;
|
||||
// SELECT id FROM dashboard LEFT OUTER JOIN <FilterLeftJoin...>
|
||||
// WHERE <FilterWhere[0]> AND ... AND <FilterWhere[n]>
|
||||
// GROUP BY <FilterGroupBy...>
|
||||
// ORDER BY <FilterOrderBy...>
|
||||
// LIMIT <limit> OFFSET <(page-1)*limit>;
|
||||
//
|
||||
// This structure is intended to isolate the filters from each other
|
||||
// and implementors are expected to add all the required joins, where
|
||||
|
||||
@@ -178,7 +178,7 @@ func (ss *SQLStore) createUser(ctx context.Context, sess *DBSession, args user.C
|
||||
return usr, nil
|
||||
}
|
||||
|
||||
// deprecated method, use only for tests
|
||||
// deprecated method, use only for tests
|
||||
func (ss *SQLStore) CreateUser(ctx context.Context, cmd user.CreateUserCommand) (*user.User, error) {
|
||||
var user user.User
|
||||
createErr := ss.WithTransactionalDbSession(ctx, func(sess *DBSession) (err error) {
|
||||
|
||||
@@ -58,6 +58,7 @@ type EventHandler func(ctx context.Context, e *EntityEvent) error
|
||||
|
||||
// EntityEventsService is a temporary solution to support change notifications in an HA setup
|
||||
// With this service each system can query for any events that have happened since a fixed time
|
||||
//
|
||||
//go:generate mockery --name EntityEventsService --structname MockEntityEventsService --inpackage --filename entity_events_mock.go
|
||||
type EntityEventsService interface {
|
||||
registry.BackgroundService
|
||||
|
||||
@@ -23,9 +23,10 @@ type rootStorageSQL struct {
|
||||
|
||||
// getDbRootFolder creates a DB path prefix for a given storage name and orgId.
|
||||
// example:
|
||||
// orgId: 5
|
||||
// storageName: "upload"
|
||||
// => prefix: "/5/upload/"
|
||||
//
|
||||
// orgId: 5
|
||||
// storageName: "upload"
|
||||
// => prefix: "/5/upload/"
|
||||
func getDbStoragePathPrefix(orgId int64, storageName string) string {
|
||||
return filestorage.Join(fmt.Sprintf("%d", orgId), storageName+filestorage.Delimiter)
|
||||
}
|
||||
|
||||
@@ -913,6 +913,9 @@ func newMockNotificationChannel(t *testing.T, grafanaListedAddr string) *mockNot
|
||||
require.NoError(t, err)
|
||||
|
||||
nc := &mockNotificationChannel{
|
||||
// Skip gosec linter since this is in test code.
|
||||
//
|
||||
//nolint:gosec
|
||||
server: &http.Server{
|
||||
Addr: listener.Addr().String(),
|
||||
},
|
||||
|
||||
@@ -450,9 +450,12 @@ func formatAzureMonitorLegendKey(alias string, resourceName string, metricName s
|
||||
}
|
||||
|
||||
// Map values from:
|
||||
// https://docs.microsoft.com/en-us/rest/api/monitor/metrics/list#unit
|
||||
//
|
||||
// https://docs.microsoft.com/en-us/rest/api/monitor/metrics/list#unit
|
||||
//
|
||||
// to
|
||||
// https://github.com/grafana/grafana/blob/main/packages/grafana-data/src/valueFormats/categories.ts#L24
|
||||
//
|
||||
// https://github.com/grafana/grafana/blob/main/packages/grafana-data/src/valueFormats/categories.ts#L24
|
||||
func toGrafanaUnit(unit string) string {
|
||||
switch unit {
|
||||
case "BitsPerSecond":
|
||||
|
||||
@@ -12,8 +12,9 @@ import (
|
||||
|
||||
"github.com/grafana/grafana-plugin-sdk-go/backend"
|
||||
"github.com/grafana/grafana-plugin-sdk-go/data"
|
||||
"github.com/grafana/grafana/pkg/infra/tracing"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
|
||||
"github.com/grafana/grafana/pkg/infra/tracing"
|
||||
)
|
||||
|
||||
func (timeSeriesFilter *cloudMonitoringTimeSeriesFilter) run(ctx context.Context, req *backend.QueryDataRequest,
|
||||
@@ -82,7 +83,7 @@ func (timeSeriesFilter *cloudMonitoringTimeSeriesFilter) run(ctx context.Context
|
||||
return dr, d, r.URL.RawQuery, nil
|
||||
}
|
||||
|
||||
//nolint: gocyclo
|
||||
//nolint:gocyclo
|
||||
func (timeSeriesFilter *cloudMonitoringTimeSeriesFilter) parseResponse(queryRes *backend.DataResponse,
|
||||
response cloudMonitoringResponse, executedQueryString string) error {
|
||||
frames := data.Frames{}
|
||||
|
||||
@@ -29,18 +29,18 @@ const (
|
||||
//
|
||||
// we also try to detect some often used patterns in the data,
|
||||
// and make the data easier to graph in the browser for such cases:
|
||||
// - if there is only one timestamp-column and it's named "_time",
|
||||
// we will not add the labels to this data-column, because timestamp
|
||||
// columns usually do not have labels in grafana.
|
||||
// we use the `columnInfo.shouldGetLabels` attribute to handle this.
|
||||
// - if there is only one timestamp-column and it's named "_time",
|
||||
// and there is only one non-timestamp-column and it's named "_value",
|
||||
// we rename "_time" to "Time" (using `columnInfo.isTheSimpleTime`),
|
||||
// and we rename "_value" too (using `columnInfo.isTheSimpleValue`):
|
||||
// if there is a tag called "_field" we use it's value as the name
|
||||
// (because that's the usual approach in influxdb), and if there is not,
|
||||
// we name it "Value". with these new names, they are more compatible
|
||||
// with the visualizations in grafana.
|
||||
// - if there is only one timestamp-column and it's named "_time",
|
||||
// we will not add the labels to this data-column, because timestamp
|
||||
// columns usually do not have labels in grafana.
|
||||
// we use the `columnInfo.shouldGetLabels` attribute to handle this.
|
||||
// - if there is only one timestamp-column and it's named "_time",
|
||||
// and there is only one non-timestamp-column and it's named "_value",
|
||||
// we rename "_time" to "Time" (using `columnInfo.isTheSimpleTime`),
|
||||
// and we rename "_value" too (using `columnInfo.isTheSimpleValue`):
|
||||
// if there is a tag called "_field" we use it's value as the name
|
||||
// (because that's the usual approach in influxdb), and if there is not,
|
||||
// we name it "Value". with these new names, they are more compatible
|
||||
// with the visualizations in grafana.
|
||||
type columnInfo struct {
|
||||
name string
|
||||
converter *data.FieldConverter
|
||||
|
||||
@@ -156,7 +156,7 @@ func FormatDuration(inter time.Duration) string {
|
||||
return "1ms"
|
||||
}
|
||||
|
||||
//nolint: gocyclo
|
||||
//nolint:gocyclo
|
||||
func roundInterval(interval time.Duration) time.Duration {
|
||||
switch {
|
||||
// 0.01s
|
||||
|
||||
@@ -146,7 +146,7 @@ func FormatDuration(inter time.Duration) string {
|
||||
return "1ms"
|
||||
}
|
||||
|
||||
//nolint: gocyclo
|
||||
//nolint:gocyclo
|
||||
func roundInterval(interval time.Duration) time.Duration {
|
||||
switch {
|
||||
// 0.015s
|
||||
|
||||
@@ -33,7 +33,7 @@ func ProvideService(pluginsClient plugins.Client, oAuthTokenService oauthtoken.O
|
||||
}
|
||||
}
|
||||
|
||||
//nolint: staticcheck // legacydata.DataResponse deprecated
|
||||
//nolint:staticcheck // legacydata.DataResponse deprecated
|
||||
func (h *Service) HandleRequest(ctx context.Context, ds *datasources.DataSource, query legacydata.DataQuery) (legacydata.DataResponse, error) {
|
||||
decryptedJsonData, err := h.dataSourcesService.DecryptedValues(ctx, ds)
|
||||
if err != nil {
|
||||
|
||||
@@ -189,7 +189,7 @@ func formatNamePrometheusStyle(labels map[string]string) string {
|
||||
return fmt.Sprintf("{%s}", strings.Join(parts, ", "))
|
||||
}
|
||||
|
||||
//If legend (using of name or pattern instead of time series name) is used, use that name/pattern for formatting
|
||||
// If legend (using of name or pattern instead of time series name) is used, use that name/pattern for formatting
|
||||
func formatName(labels map[string]string, query *lokiQuery) string {
|
||||
if query.LegendFormat == "" {
|
||||
return formatNamePrometheusStyle(labels)
|
||||
|
||||
@@ -57,6 +57,7 @@ func TestSuccessResponse(t *testing.T) {
|
||||
responseFileName := filepath.Join("testdata", test.filepath+".json")
|
||||
goldenFileName := test.filepath + ".golden"
|
||||
|
||||
//nolint:gosec
|
||||
bytes, err := os.ReadFile(responseFileName)
|
||||
require.NoError(t, err)
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
"github.com/grafana/grafana-plugin-sdk-go/backend"
|
||||
"github.com/grafana/grafana-plugin-sdk-go/backend/gtime"
|
||||
|
||||
"github.com/grafana/grafana/pkg/tsdb/sqleng"
|
||||
)
|
||||
|
||||
@@ -65,7 +66,7 @@ func (m *postgresMacroEngine) Interpolate(query *backend.DataQuery, timeRange ba
|
||||
return sql, nil
|
||||
}
|
||||
|
||||
//nolint: gocyclo
|
||||
//nolint:gocyclo
|
||||
func (m *postgresMacroEngine) evaluateMacro(timeRange backend.TimeRange, query *backend.DataQuery, name string, args []string) (string, error) {
|
||||
switch name {
|
||||
case "__time":
|
||||
|
||||
@@ -15,11 +15,12 @@ import (
|
||||
|
||||
"github.com/grafana/grafana-plugin-sdk-go/backend"
|
||||
"github.com/grafana/grafana-plugin-sdk-go/experimental"
|
||||
"github.com/prometheus/client_golang/api"
|
||||
apiv1 "github.com/prometheus/client_golang/api/prometheus/v1"
|
||||
|
||||
"github.com/grafana/grafana/pkg/infra/log"
|
||||
"github.com/grafana/grafana/pkg/infra/tracing"
|
||||
"github.com/grafana/grafana/pkg/tsdb/intervalv2"
|
||||
"github.com/prometheus/client_golang/api"
|
||||
apiv1 "github.com/prometheus/client_golang/api/prometheus/v1"
|
||||
)
|
||||
|
||||
var update = true
|
||||
@@ -44,6 +45,7 @@ func TestMatrixResponses(t *testing.T) {
|
||||
query, err := loadStoredPrometheusQuery(queryFileName)
|
||||
require.NoError(t, err)
|
||||
|
||||
//nolint:gosec
|
||||
responseBytes, err := os.ReadFile(responseFileName)
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -101,6 +103,7 @@ type storedPrometheusQuery struct {
|
||||
}
|
||||
|
||||
func loadStoredPrometheusQuery(fileName string) (PrometheusQuery, error) {
|
||||
//nolint:gosec
|
||||
bytes, err := os.ReadFile(fileName)
|
||||
if err != nil {
|
||||
return PrometheusQuery{}, err
|
||||
|
||||
@@ -26,7 +26,7 @@ import (
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
)
|
||||
|
||||
//Internal interval and range variables
|
||||
// Internal interval and range variables
|
||||
const (
|
||||
varInterval = "$__interval"
|
||||
varIntervalMs = "$__interval_ms"
|
||||
@@ -36,8 +36,8 @@ const (
|
||||
varRateInterval = "$__rate_interval"
|
||||
)
|
||||
|
||||
//Internal interval and range variables with {} syntax
|
||||
//Repetitive code, we should have functionality to unify these
|
||||
// Internal interval and range variables with {} syntax
|
||||
// Repetitive code, we should have functionality to unify these
|
||||
const (
|
||||
varIntervalAlt = "${__interval}"
|
||||
varIntervalMsAlt = "${__interval_ms}"
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
"github.com/grafana/grafana/pkg/tsdb/intervalv2"
|
||||
)
|
||||
|
||||
//Internal interval and range variables
|
||||
// Internal interval and range variables
|
||||
const (
|
||||
varInterval = "$__interval"
|
||||
varIntervalMs = "$__interval_ms"
|
||||
@@ -21,8 +21,8 @@ const (
|
||||
varRateInterval = "$__rate_interval"
|
||||
)
|
||||
|
||||
//Internal interval and range variables with {} syntax
|
||||
//Repetitive code, we should have functionality to unify these
|
||||
// Internal interval and range variables with {} syntax
|
||||
// Repetitive code, we should have functionality to unify these
|
||||
const (
|
||||
varIntervalAlt = "${__interval}"
|
||||
varIntervalMsAlt = "${__interval_ms}"
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
|
||||
"github.com/grafana/grafana-plugin-sdk-go/backend"
|
||||
"github.com/grafana/grafana-plugin-sdk-go/experimental"
|
||||
|
||||
"github.com/grafana/grafana/pkg/infra/log"
|
||||
"github.com/grafana/grafana/pkg/tsdb/prometheus/models"
|
||||
)
|
||||
@@ -50,6 +51,7 @@ func goldenScenario(name, queryFileName, responseFileName, goldenFileName string
|
||||
query, err := loadStoredQuery(queryFileName)
|
||||
require.NoError(t, err)
|
||||
|
||||
//nolint:gosec
|
||||
responseBytes, err := os.ReadFile(responseFileName)
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -78,6 +80,7 @@ type storedPrometheusQuery struct {
|
||||
}
|
||||
|
||||
func loadStoredQuery(fileName string) (*backend.QueryDataRequest, error) {
|
||||
//nolint:gosec
|
||||
bytes, err := os.ReadFile(fileName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -16,10 +16,11 @@ import (
|
||||
"github.com/grafana/grafana-plugin-sdk-go/backend"
|
||||
"github.com/grafana/grafana-plugin-sdk-go/data"
|
||||
"github.com/grafana/grafana-plugin-sdk-go/data/sqlutil"
|
||||
"github.com/grafana/grafana/pkg/infra/log"
|
||||
"github.com/grafana/grafana/pkg/tsdb/intervalv2"
|
||||
"xorm.io/core"
|
||||
"xorm.io/xorm"
|
||||
|
||||
"github.com/grafana/grafana/pkg/infra/log"
|
||||
"github.com/grafana/grafana/pkg/tsdb/intervalv2"
|
||||
)
|
||||
|
||||
// MetaKeyExecutedQueryString is the key where the executed query should get stored
|
||||
@@ -43,6 +44,7 @@ type SqlQueryResultTransformer interface {
|
||||
var sqlIntervalCalculator = intervalv2.NewCalculator()
|
||||
|
||||
// NewXormEngine is an xorm.Engine factory, that can be stubbed by tests.
|
||||
//
|
||||
//nolint:gocritic
|
||||
var NewXormEngine = func(driverName string, connectionString string) (*xorm.Engine, error) {
|
||||
return xorm.NewEngine(driverName, connectionString)
|
||||
@@ -886,7 +888,8 @@ func convertSQLTimeColumnToEpochMS(frame *data.Frame, timeIndex int) error {
|
||||
}
|
||||
|
||||
// convertSQLValueColumnToFloat converts timeseries value column to float.
|
||||
//nolint: gocyclo
|
||||
//
|
||||
//nolint:gocyclo
|
||||
func convertSQLValueColumnToFloat(frame *data.Frame, Index int) (*data.Frame, error) {
|
||||
if Index < 0 || Index >= len(frame.Fields) {
|
||||
return frame, fmt.Errorf("metricIndex %d is out of range", Index)
|
||||
|
||||
@@ -115,8 +115,9 @@ func describeReflectValue(v reflect.Value) interface{} {
|
||||
}
|
||||
|
||||
// IsAddOperation returns true when
|
||||
// - Left does not have value and Right has
|
||||
// - the kind of Left and Right is either reflect.Slice or reflect.Map and the length of Left is less than length of Right
|
||||
// - Left does not have value and Right has
|
||||
// - the kind of Left and Right is either reflect.Slice or reflect.Map and the length of Left is less than length of Right
|
||||
//
|
||||
// In all other cases it returns false.
|
||||
// NOTE: this is applicable to diff of Maps and Slices only
|
||||
func (d *Diff) IsAddOperation() bool {
|
||||
@@ -125,8 +126,9 @@ func (d *Diff) IsAddOperation() bool {
|
||||
}
|
||||
|
||||
// IsDeleteOperation returns true when
|
||||
// - Right does not have value and Left has
|
||||
// - the kind of Left and Right is either reflect.Slice or reflect.Map and the length of Right is less than length of Left
|
||||
// - Right does not have value and Left has
|
||||
// - the kind of Left and Right is either reflect.Slice or reflect.Map and the length of Right is less than length of Left
|
||||
//
|
||||
// In all other cases it returns false.
|
||||
// NOTE: this is applicable to diff of Maps and Slices only
|
||||
func (d *Diff) IsDeleteOperation() bool {
|
||||
|
||||
@@ -45,6 +45,7 @@ func TestReadPromFrames(t *testing.T) {
|
||||
}
|
||||
|
||||
// FIXME:
|
||||
//
|
||||
//lint:ignore U1000 Ignore used function for now
|
||||
func runScenario(name string, opts Options) func(t *testing.T) {
|
||||
return func(t *testing.T) {
|
||||
|
||||
@@ -26,16 +26,21 @@
|
||||
// service using the NewBase constructor with a CoreStatus and a unique
|
||||
// static message ID that identifies the general structure of the public
|
||||
// message attached to the specific error.
|
||||
// var errNotFound = errutil.NewBase(errutil.StatusNotFound, "service.not-found")
|
||||
//
|
||||
// var errNotFound = errutil.NewBase(errutil.StatusNotFound, "service.not-found")
|
||||
//
|
||||
// This Base can now be used to construct a regular Go error with the
|
||||
// Base.Errorf method using the same structure as fmt.Errorf:
|
||||
// return errNotFound.Errorf("looked for thing with ID %d, but it wasn't there: %w", id, err)
|
||||
//
|
||||
// return errNotFound.Errorf("looked for thing with ID %d, but it wasn't there: %w", id, err)
|
||||
//
|
||||
// By default, the end user will be sent the static message ID and a
|
||||
// message which is the string representation of the CoreStatus. It is
|
||||
// possible to override the message sent to the end user by using
|
||||
// the WithPublicMessage functional option when creating a new Base
|
||||
// var errNotFound = errutil.NewBase(errutil.StatusNotFound "service.not-found", WithPublicMessage("The thing is missing."))
|
||||
//
|
||||
// var errNotFound = errutil.NewBase(errutil.StatusNotFound "service.not-found", WithPublicMessage("The thing is missing."))
|
||||
//
|
||||
// If a dynamic message is needed, the Template type extends Base with a
|
||||
// Go template using text/template from the standard library, refer to
|
||||
// the documentation related to the Template type for usage examples.
|
||||
|
||||
@@ -23,9 +23,10 @@ type Base struct {
|
||||
// to serve as the base for user facing error messages.
|
||||
//
|
||||
// msgID should be structured as component.error-brief, for example
|
||||
// login.failed-authentication
|
||||
// dashboards.validation-error
|
||||
// dashboards.uid-already-exists
|
||||
//
|
||||
// login.failed-authentication
|
||||
// dashboards.validation-error
|
||||
// dashboards.uid-already-exists
|
||||
func NewBase(reason StatusReason, msgID string, opts ...BaseOpt) Base {
|
||||
b := Base{
|
||||
reason: reason,
|
||||
|
||||
Reference in New Issue
Block a user