mirror of
https://github.com/grafana/grafana.git
synced 2025-02-25 18:55:37 -06:00
Chore/fix lint issues (#27704)
* Chore: Fix linting issues Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com>
This commit is contained in:
parent
ffc11cb63c
commit
a5d9196a53
@ -417,7 +417,7 @@ func DeleteAlertNotificationByUID(c *models.ReqContext) Response {
|
||||
})
|
||||
}
|
||||
|
||||
//POST /api/alert-notifications/test
|
||||
// POST /api/alert-notifications/test
|
||||
func NotificationTest(c *models.ReqContext, dto dtos.NotificationTestCommand) Response {
|
||||
cmd := &alerting.NotificationTestCommand{
|
||||
OrgID: c.OrgId,
|
||||
@ -438,7 +438,7 @@ func NotificationTest(c *models.ReqContext, dto dtos.NotificationTestCommand) Re
|
||||
return Success("Test notification sent")
|
||||
}
|
||||
|
||||
//POST /api/alerts/:alertId/pause
|
||||
// POST /api/alerts/:alertId/pause
|
||||
func PauseAlert(c *models.ReqContext, dto dtos.PauseAlertCommand) Response {
|
||||
alertID := c.ParamsInt64("alertId")
|
||||
result := make(map[string]interface{})
|
||||
@ -491,7 +491,7 @@ func PauseAlert(c *models.ReqContext, dto dtos.PauseAlertCommand) Response {
|
||||
return JSON(200, result)
|
||||
}
|
||||
|
||||
//POST /api/admin/pause-all-alerts
|
||||
// POST /api/admin/pause-all-alerts
|
||||
func PauseAllAlerts(c *models.ReqContext, dto dtos.PauseAllAlertsCommand) Response {
|
||||
updateCmd := models.PauseAllAlertCommand{
|
||||
Paused: dto.Paused,
|
||||
|
@ -43,9 +43,9 @@ func (m *LDAPMock) User(login string) (*models.ExternalUserInfo, ldap.ServerConf
|
||||
return userSearchResult, userSearchConfig, userSearchError
|
||||
}
|
||||
|
||||
//***
|
||||
// ***
|
||||
// GetUserFromLDAP tests
|
||||
//***
|
||||
// ***
|
||||
|
||||
func getUserFromLDAPContext(t *testing.T, requestURL string) *scenarioContext {
|
||||
t.Helper()
|
||||
@ -311,9 +311,9 @@ func TestGetUserFromLDAPApiEndpoint_WithTeamHandler(t *testing.T) {
|
||||
assert.JSONEq(t, expected, sc.resp.Body.String())
|
||||
}
|
||||
|
||||
//***
|
||||
// ***
|
||||
// GetLDAPStatus tests
|
||||
//***
|
||||
// ***
|
||||
|
||||
func getLDAPStatusContext(t *testing.T) *scenarioContext {
|
||||
t.Helper()
|
||||
@ -371,9 +371,9 @@ func TestGetLDAPStatusApiEndpoint(t *testing.T) {
|
||||
assert.JSONEq(t, expected, sc.resp.Body.String())
|
||||
}
|
||||
|
||||
//***
|
||||
// ***
|
||||
// PostSyncUserWithLDAP tests
|
||||
//***
|
||||
// ***
|
||||
|
||||
func postSyncUserWithLDAPContext(t *testing.T, requestURL string) *scenarioContext {
|
||||
t.Helper()
|
||||
|
@ -90,10 +90,10 @@ func (hs *HTTPServer) LoginView(c *models.ReqContext) {
|
||||
viewData.Settings["samlEnabled"] = hs.License.HasValidLicense() && hs.Cfg.SAMLEnabled
|
||||
|
||||
if loginError, ok := tryGetEncryptedCookie(c, LoginErrorCookieName); ok {
|
||||
//this cookie is only set whenever an OAuth login fails
|
||||
//therefore the loginError should be passed to the view data
|
||||
//and the view should return immediately before attempting
|
||||
//to login again via OAuth and enter to a redirect loop
|
||||
// this cookie is only set whenever an OAuth login fails
|
||||
// therefore the loginError should be passed to the view data
|
||||
// and the view should return immediately before attempting
|
||||
// to login again via OAuth and enter to a redirect loop
|
||||
middleware.DeleteCookie(c.Resp, LoginErrorCookieName, hs.CookieOptionsFromCfg)
|
||||
viewData.Settings["loginError"] = loginError
|
||||
c.HTML(200, getViewIndex(), viewData)
|
||||
|
@ -13,7 +13,7 @@ import (
|
||||
"golang.org/x/oauth2/google"
|
||||
)
|
||||
|
||||
//ApplyRoute should use the plugin route data to set auth headers and custom headers
|
||||
// ApplyRoute should use the plugin route data to set auth headers and custom headers
|
||||
func ApplyRoute(ctx context.Context, req *http.Request, proxyPath string, route *plugins.AppPluginRoute, ds *models.DataSource) {
|
||||
proxyPath = strings.TrimPrefix(proxyPath, route.Path)
|
||||
|
||||
|
@ -72,7 +72,7 @@ type routeRegister struct {
|
||||
}
|
||||
|
||||
func (rr *routeRegister) Insert(pattern string, fn func(RouteRegister), handlers ...macaron.Handler) {
|
||||
//loop over all groups at current level
|
||||
// loop over all groups at current level
|
||||
for _, g := range rr.groups {
|
||||
// apply routes if the prefix matches the pattern
|
||||
if g.prefix == pattern {
|
||||
|
@ -85,7 +85,7 @@ func UpdateUser(c *models.ReqContext, cmd models.UpdateUserCommand) Response {
|
||||
return handleUpdateUser(cmd)
|
||||
}
|
||||
|
||||
//POST /api/users/:id/using/:orgId
|
||||
// POST /api/users/:id/using/:orgId
|
||||
func UpdateUserActiveOrg(c *models.ReqContext) Response {
|
||||
userID := c.ParamsInt64(":id")
|
||||
orgID := c.ParamsInt64(":orgId")
|
||||
|
@ -13,7 +13,7 @@ import (
|
||||
)
|
||||
|
||||
func TestPasswordMigrationCommand(t *testing.T) {
|
||||
//setup datasources with password, basic_auth and none
|
||||
// setup datasources with password, basic_auth and none
|
||||
sqlstore := sqlstore.InitTestDB(t)
|
||||
session := sqlstore.NewSession()
|
||||
defer session.Close()
|
||||
@ -45,13 +45,13 @@ func TestPasswordMigrationCommand(t *testing.T) {
|
||||
_, err = session.Exec("update data_source set secure_json_data = null where name = 'influxdb'")
|
||||
require.NoError(t, err)
|
||||
|
||||
//run migration
|
||||
// run migration
|
||||
c, err := commandstest.NewCliContext(map[string]string{})
|
||||
require.Nil(t, err)
|
||||
err = EncryptDatasourcePasswords(c, sqlstore)
|
||||
require.NoError(t, err)
|
||||
|
||||
//verify that no datasources still have password or basic_auth
|
||||
// verify that no datasources still have password or basic_auth
|
||||
var dss []*models.DataSource
|
||||
err = session.SQL("select * from data_source").Find(&dss)
|
||||
require.NoError(t, err)
|
||||
|
@ -40,23 +40,23 @@ func TestExtractFiles(t *testing.T) {
|
||||
err := extractFiles(archive, "grafana-simple-json-datasource", pluginDir, false)
|
||||
require.NoError(t, err)
|
||||
|
||||
//File in zip has permissions 755
|
||||
// File in zip has permissions 755
|
||||
fileInfo, err := os.Stat(filepath.Join(pluginDir, "grafana-simple-json-datasource",
|
||||
"simple-plugin_darwin_amd64"))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "-rwxr-xr-x", fileInfo.Mode().String())
|
||||
|
||||
//File in zip has permission 755
|
||||
// File in zip has permission 755
|
||||
fileInfo, err = os.Stat(pluginDir + "/grafana-simple-json-datasource/simple-plugin_linux_amd64")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "-rwxr-xr-x", fileInfo.Mode().String())
|
||||
|
||||
//File in zip has permission 644
|
||||
// File in zip has permission 644
|
||||
fileInfo, err = os.Stat(pluginDir + "/grafana-simple-json-datasource/simple-plugin_windows_amd64.exe")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "-rw-r--r--", fileInfo.Mode().String())
|
||||
|
||||
//File in zip has permission 755
|
||||
// File in zip has permission 755
|
||||
fileInfo, err = os.Stat(pluginDir + "/grafana-simple-json-datasource/non-plugin-binary")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "-rwxr-xr-x", fileInfo.Mode().String())
|
||||
|
@ -64,7 +64,7 @@ func returnOsDefault(currentOs string) string {
|
||||
return "/var/db/grafana/plugins"
|
||||
case "openbsd":
|
||||
return "/var/grafana/plugins"
|
||||
default: //"linux"
|
||||
default: // "linux"
|
||||
return "/var/lib/grafana/plugins"
|
||||
}
|
||||
}
|
||||
|
@ -155,7 +155,7 @@ func (b *BasicDiff) Basic(lines []*JSONLine) []*BasicBlock {
|
||||
b.Block.Changes = append(b.Block.Changes, b.Change)
|
||||
|
||||
default:
|
||||
//ok
|
||||
// ok
|
||||
}
|
||||
|
||||
// otherwise, we're dealing with a change at a deeper level. We
|
||||
|
@ -243,7 +243,7 @@ func (f *JSONFormatter) processItem(value interface{}, deltas []diff.Delta, posi
|
||||
case *diff.Object:
|
||||
switch value.(type) {
|
||||
case map[string]interface{}:
|
||||
//ok
|
||||
// ok
|
||||
default:
|
||||
return errors.New("Type mismatch")
|
||||
}
|
||||
@ -268,7 +268,7 @@ func (f *JSONFormatter) processItem(value interface{}, deltas []diff.Delta, posi
|
||||
case *diff.Array:
|
||||
switch value.(type) {
|
||||
case []interface{}:
|
||||
//ok
|
||||
// ok
|
||||
default:
|
||||
return errors.New("Type mismatch")
|
||||
}
|
||||
|
@ -201,9 +201,9 @@ func (c *StorageClient) FileUpload(ctx context.Context, container, blobName stri
|
||||
func escape(content string) string {
|
||||
content = url.QueryEscape(content)
|
||||
// the Azure's behavior uses %20 to represent whitespace instead of + (plus)
|
||||
content = strings.Replace(content, "+", "%20", -1)
|
||||
content = strings.ReplaceAll(content, "+", "%20")
|
||||
// the Azure's behavior uses slash instead of + %2F
|
||||
content = strings.Replace(content, "%2F", "/", -1)
|
||||
content = strings.ReplaceAll(content, "%2F", "/")
|
||||
|
||||
return content
|
||||
}
|
||||
|
@ -12,7 +12,7 @@ import (
|
||||
|
||||
const (
|
||||
pngExt = ".png"
|
||||
defaultSGcsSignedUrlExpiration = 7 * 24 * time.Hour //7 days
|
||||
defaultSGcsSignedUrlExpiration = 7 * 24 * time.Hour // 7 days
|
||||
)
|
||||
|
||||
type ImageUploader interface {
|
||||
|
@ -37,7 +37,7 @@ var netClient = &http.Client{
|
||||
|
||||
func (u *WebdavUploader) PublicURL(filename string) string {
|
||||
if strings.Contains(u.public_url, "${file}") {
|
||||
return strings.Replace(u.public_url, "${file}", filename, -1)
|
||||
return strings.ReplaceAll(u.public_url, "${file}", filename)
|
||||
}
|
||||
|
||||
publicURL, _ := url.Parse(u.public_url)
|
||||
|
@ -68,7 +68,7 @@ func NewFileWriter() *FileLogWriter {
|
||||
Filename: "",
|
||||
Format: log15.LogfmtFormat(),
|
||||
Maxlines: 1000000,
|
||||
Maxsize: 1 << 28, //256 MB
|
||||
Maxsize: 1 << 28, // 256 MB
|
||||
Daily: true,
|
||||
Maxdays: 7,
|
||||
Rotate: true,
|
||||
|
@ -306,7 +306,7 @@ prefix.page.response.constname.constvalue.labelname.val2.count 1 1477043
|
||||
t.Fatalf("wanted \n%s\n, got \n%s\n", want, got)
|
||||
}
|
||||
|
||||
//next collect
|
||||
// next collect
|
||||
cntVec.WithLabelValues("val1").Inc()
|
||||
cntVec.WithLabelValues("val2").Inc()
|
||||
apicntVec.WithLabelValues("val1").Inc()
|
||||
@ -373,7 +373,7 @@ func TestCounter(t *testing.T) {
|
||||
t.Fatalf("wanted \n%s\n, got \n%s\n", want, got)
|
||||
}
|
||||
|
||||
//next collect
|
||||
// next collect
|
||||
cntVec.Inc()
|
||||
|
||||
mfs, err = reg.Gather()
|
||||
|
@ -48,14 +48,14 @@ func (im *InternalMetricsService) parseGraphiteSettings() error {
|
||||
ErrorHandling: graphitebridge.ContinueOnError,
|
||||
}
|
||||
|
||||
safeInstanceName := strings.Replace(setting.InstanceName, ".", "_", -1)
|
||||
safeInstanceName := strings.ReplaceAll(setting.InstanceName, ".", "_")
|
||||
prefix := graphiteSection.Key("prefix").Value()
|
||||
|
||||
if prefix == "" {
|
||||
prefix = "prod.grafana.%(instance_name)s."
|
||||
}
|
||||
|
||||
bridgeCfg.Prefix = strings.Replace(prefix, "%(instance_name)s", safeInstanceName, -1)
|
||||
bridgeCfg.Prefix = strings.ReplaceAll(prefix, "%(instance_name)s", safeInstanceName)
|
||||
|
||||
im.graphiteCfg = bridgeCfg
|
||||
return nil
|
||||
|
@ -70,7 +70,7 @@ func (dc *databaseCache) Get(key string) (interface{}, error) {
|
||||
if cacheHit.Expires > 0 {
|
||||
existedButExpired := getTime().Unix()-cacheHit.CreatedAt >= cacheHit.Expires
|
||||
if existedButExpired {
|
||||
err = dc.Delete(key) //ignore this error since we will return `ErrCacheItemNotFound` anyway
|
||||
err = dc.Delete(key) // ignore this error since we will return `ErrCacheItemNotFound` anyway
|
||||
if err != nil {
|
||||
dc.log.Debug("Deletion of expired key failed: %v", err)
|
||||
}
|
||||
|
@ -19,7 +19,7 @@ func TestDatabaseStorageGarbageCollection(t *testing.T) {
|
||||
|
||||
obj := &CacheableStruct{String: "foolbar"}
|
||||
|
||||
//set time.now to 2 weeks ago
|
||||
// set time.now to 2 weeks ago
|
||||
var err error
|
||||
getTime = func() time.Time { return time.Now().AddDate(0, 0, -2) }
|
||||
err = db.Set("key1", obj, 1000*time.Second)
|
||||
@ -39,10 +39,10 @@ func TestDatabaseStorageGarbageCollection(t *testing.T) {
|
||||
err = db.Set("key5", obj, 1000*time.Second)
|
||||
assert.Equal(t, err, nil)
|
||||
|
||||
//run GC
|
||||
// run GC
|
||||
db.internalRunGC()
|
||||
|
||||
//try to read values
|
||||
// try to read values
|
||||
_, err = db.Get("key1")
|
||||
assert.Equal(t, err, ErrCacheItemNotFound, "expected cache item not found. got: ", err)
|
||||
_, err = db.Get("key2")
|
||||
|
@ -79,7 +79,7 @@ func (ds *RemoteCache) Init() error {
|
||||
|
||||
// Run start the backend processes for cache clients
|
||||
func (ds *RemoteCache) Run(ctx context.Context) error {
|
||||
//create new interface if more clients need GC jobs
|
||||
// create new interface if more clients need GC jobs
|
||||
backgroundjob, ok := ds.client.(registry.BackgroundService)
|
||||
if ok {
|
||||
return backgroundjob.Run(ctx)
|
||||
|
@ -83,7 +83,7 @@ func canNotFetchExpiredItems(t *testing.T, client CacheStorage) {
|
||||
err := client.Set("key1", cacheableStruct, time.Second)
|
||||
assert.Equal(t, err, nil)
|
||||
|
||||
//not sure how this can be avoided when testing redis/memcached :/
|
||||
// not sure how this can be avoided when testing redis/memcached :/
|
||||
<-time.After(time.Second + time.Millisecond)
|
||||
|
||||
// should not be able to read that value since its expired
|
||||
|
@ -28,7 +28,7 @@ type UsageReport struct {
|
||||
}
|
||||
|
||||
func (uss *UsageStatsService) GetUsageReport() (UsageReport, error) {
|
||||
version := strings.Replace(setting.BuildVersion, ".", "_", -1)
|
||||
version := strings.ReplaceAll(setting.BuildVersion, ".", "_")
|
||||
|
||||
metrics := map[string]interface{}{}
|
||||
|
||||
|
@ -93,7 +93,7 @@ func function(pc uintptr) []byte {
|
||||
if period := bytes.Index(name, dot); period >= 0 {
|
||||
name = name[period+1:]
|
||||
}
|
||||
name = bytes.Replace(name, centerDot, dot, -1)
|
||||
name = bytes.ReplaceAll(name, centerDot, dot)
|
||||
return name
|
||||
}
|
||||
|
||||
|
@ -71,9 +71,9 @@ type Alert struct {
|
||||
PanelId int64
|
||||
Name string
|
||||
Message string
|
||||
Severity string //Unused
|
||||
Severity string // Unused
|
||||
State AlertStateType
|
||||
Handler int64 //Unused
|
||||
Handler int64 // Unused
|
||||
Silenced bool
|
||||
ExecutionError string
|
||||
Frequency int64
|
||||
@ -113,7 +113,7 @@ func (this *Alert) ContainsUpdates(other *Alert) bool {
|
||||
result = result || string(json1) != string(json2)
|
||||
}
|
||||
|
||||
//don't compare .State! That would be insane.
|
||||
// don't compare .State! That would be insane.
|
||||
return result
|
||||
}
|
||||
|
||||
@ -180,7 +180,7 @@ type SetAlertStateCommand struct {
|
||||
Result Alert
|
||||
}
|
||||
|
||||
//Queries
|
||||
// Queries
|
||||
type GetAlertsQuery struct {
|
||||
OrgId int64
|
||||
State []string
|
||||
|
@ -41,7 +41,7 @@ func getPluginLogoUrl(pluginType, path, baseUrl string) string {
|
||||
}
|
||||
|
||||
func (fp *FrontendPluginBase) setPathsBasedOnApp(app *AppPlugin) {
|
||||
appSubPath := strings.Replace(strings.Replace(fp.PluginDir, app.PluginDir, "", 1), "\\", "/", -1)
|
||||
appSubPath := strings.ReplaceAll(strings.Replace(fp.PluginDir, app.PluginDir, "", 1), "\\", "/")
|
||||
fp.IncludedInAppId = app.Id
|
||||
fp.BaseUrl = app.BaseUrl
|
||||
|
||||
|
@ -103,7 +103,7 @@ func (dn *DiscordNotifier) Notify(evalContext *alerting.EvalContext) error {
|
||||
|
||||
embed := simplejson.New()
|
||||
embed.Set("title", evalContext.GetNotificationTitle())
|
||||
//Discord takes integer for color
|
||||
// Discord takes integer for color
|
||||
embed.Set("color", color)
|
||||
embed.Set("url", ruleURL)
|
||||
embed.Set("description", evalContext.Rule.Message)
|
||||
|
@ -121,7 +121,7 @@ func (hc *HipChatNotifier) Notify(evalContext *alerting.EvalContext) error {
|
||||
}
|
||||
|
||||
message := ""
|
||||
if evalContext.Rule.State != models.AlertStateOK { //don't add message when going back to alert state ok.
|
||||
if evalContext.Rule.State != models.AlertStateOK { // don't add message when going back to alert state ok.
|
||||
message += " " + evalContext.Rule.Message
|
||||
}
|
||||
|
||||
@ -129,7 +129,7 @@ func (hc *HipChatNotifier) Notify(evalContext *alerting.EvalContext) error {
|
||||
message = evalContext.GetNotificationTitle() + " in state " + evalContext.GetStateModel().Text
|
||||
}
|
||||
|
||||
//HipChat has a set list of colors
|
||||
// HipChat has a set list of colors
|
||||
var color string
|
||||
switch evalContext.Rule.State {
|
||||
case models.AlertStateOK:
|
||||
|
@ -83,7 +83,7 @@ func (kn *KafkaNotifier) Notify(evalContext *alerting.EvalContext) error {
|
||||
records := make([]interface{}, 1)
|
||||
|
||||
bodyJSON := simplejson.New()
|
||||
//get alert state in the kafka output issue #11401
|
||||
// get alert state in the kafka output issue #11401
|
||||
bodyJSON.Set("alert_state", state)
|
||||
bodyJSON.Set("description", evalContext.Rule.Name+" - "+evalContext.Rule.Message)
|
||||
bodyJSON.Set("client", "Grafana")
|
||||
|
@ -68,7 +68,7 @@ func TestOpsGenieNotifier(t *testing.T) {
|
||||
Settings: settingsJSON,
|
||||
}
|
||||
|
||||
notifier, notifierErr := NewOpsGenieNotifier(model) //unhandled error
|
||||
notifier, notifierErr := NewOpsGenieNotifier(model) // unhandled error
|
||||
|
||||
opsgenieNotifier := notifier.(*OpsGenieNotifier)
|
||||
|
||||
|
@ -95,7 +95,7 @@ func (sn *SensuNotifier) Notify(evalContext *alerting.EvalContext) error {
|
||||
bodyJSON := simplejson.New()
|
||||
bodyJSON.Set("ruleId", evalContext.Rule.ID)
|
||||
// Sensu alerts cannot have spaces in them
|
||||
bodyJSON.Set("name", strings.Replace(evalContext.Rule.Name, " ", "_", -1))
|
||||
bodyJSON.Set("name", strings.ReplaceAll(evalContext.Rule.Name, " ", "_"))
|
||||
// Sensu alerts require a source. We set it to the user-specified value (optional),
|
||||
// else we fallback and use the grafana ruleID.
|
||||
if sn.Source != "" {
|
||||
|
@ -241,7 +241,7 @@ func (sn *SlackNotifier) Notify(evalContext *alerting.EvalContext) error {
|
||||
}
|
||||
}
|
||||
msg := ""
|
||||
if evalContext.Rule.State != models.AlertStateOK { //don't add message when going back to alert state ok.
|
||||
if evalContext.Rule.State != models.AlertStateOK { // don't add message when going back to alert state ok.
|
||||
msg = evalContext.Rule.Message
|
||||
}
|
||||
imageURL := ""
|
||||
@ -287,7 +287,7 @@ func (sn *SlackNotifier) Notify(evalContext *alerting.EvalContext) error {
|
||||
body["blocks"] = blocks
|
||||
}
|
||||
|
||||
//recipient override
|
||||
// recipient override
|
||||
if sn.Recipient != "" {
|
||||
body["channel"] = sn.Recipient
|
||||
}
|
||||
|
@ -81,7 +81,7 @@ func (tn *TeamsNotifier) Notify(evalContext *alerting.EvalContext) error {
|
||||
}
|
||||
|
||||
message := ""
|
||||
if evalContext.Rule.State != models.AlertStateOK { //don't add message when going back to alert state ok.
|
||||
if evalContext.Rule.State != models.AlertStateOK { // don't add message when going back to alert state ok.
|
||||
message = evalContext.Rule.Message
|
||||
}
|
||||
|
||||
|
@ -39,7 +39,7 @@ func (s *schedulerImpl) Update(rules []*Rule) {
|
||||
|
||||
offset := ((rule.Frequency * 1000) / int64(len(rules))) * int64(i)
|
||||
job.Offset = int64(math.Floor(float64(offset) / 1000))
|
||||
if job.Offset == 0 { //zero offset causes division with 0 panics.
|
||||
if job.Offset == 0 { // zero offset causes division with 0 panics.
|
||||
job.Offset = 1
|
||||
}
|
||||
jobs[rule.ID] = job
|
||||
|
@ -1,121 +1,121 @@
|
||||
package alerting
|
||||
|
||||
//import (
|
||||
// "testing"
|
||||
// "time"
|
||||
// import (
|
||||
// "testing"
|
||||
// "time"
|
||||
//
|
||||
// "github.com/benbjohnson/clock"
|
||||
//)
|
||||
// "github.com/benbjohnson/clock"
|
||||
// )
|
||||
//
|
||||
//func inspectTick(tick time.Time, last time.Time, offset time.Duration, t *testing.T) {
|
||||
// if !tick.Equal(last.Add(time.Duration(1) * time.Second)) {
|
||||
// t.Fatalf("expected a tick 1 second more than prev, %s. got: %s", last, tick)
|
||||
// }
|
||||
//}
|
||||
// func inspectTick(tick time.Time, last time.Time, offset time.Duration, t *testing.T) {
|
||||
// if !tick.Equal(last.Add(time.Duration(1) * time.Second)) {
|
||||
// t.Fatalf("expected a tick 1 second more than prev, %s. got: %s", last, tick)
|
||||
// }
|
||||
// }
|
||||
//
|
||||
//// returns the new last tick seen
|
||||
//func assertAdvanceUntil(ticker *Ticker, last, desiredLast time.Time, offset, wait time.Duration, t *testing.T) time.Time {
|
||||
// for {
|
||||
// select {
|
||||
// case tick := <-ticker.C:
|
||||
// inspectTick(tick, last, offset, t)
|
||||
// last = tick
|
||||
// case <-time.NewTimer(wait).C:
|
||||
// if last.Before(desiredLast) {
|
||||
// t.Fatalf("waited %s for ticker to advance to %s, but only went up to %s", wait, desiredLast, last)
|
||||
// }
|
||||
// if last.After(desiredLast) {
|
||||
// t.Fatalf("timer advanced too far. should only have gone up to %s, but it went up to %s", desiredLast, last)
|
||||
// }
|
||||
// return last
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
// returns the new last tick seen
|
||||
// func assertAdvanceUntil(ticker *Ticker, last, desiredLast time.Time, offset, wait time.Duration, t *testing.T) time.Time {
|
||||
// for {
|
||||
// select {
|
||||
// case tick := <-ticker.C:
|
||||
// inspectTick(tick, last, offset, t)
|
||||
// last = tick
|
||||
// case <-time.NewTimer(wait).C:
|
||||
// if last.Before(desiredLast) {
|
||||
// t.Fatalf("waited %s for ticker to advance to %s, but only went up to %s", wait, desiredLast, last)
|
||||
// }
|
||||
// if last.After(desiredLast) {
|
||||
// t.Fatalf("timer advanced too far. should only have gone up to %s, but it went up to %s", desiredLast, last)
|
||||
// }
|
||||
// return last
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
//func assertNoAdvance(ticker *Ticker, desiredLast time.Time, wait time.Duration, t *testing.T) {
|
||||
// for {
|
||||
// select {
|
||||
// case tick := <-ticker.C:
|
||||
// t.Fatalf("timer should have stayed at %s, instead it advanced to %s", desiredLast, tick)
|
||||
// case <-time.NewTimer(wait).C:
|
||||
// return
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
// func assertNoAdvance(ticker *Ticker, desiredLast time.Time, wait time.Duration, t *testing.T) {
|
||||
// for {
|
||||
// select {
|
||||
// case tick := <-ticker.C:
|
||||
// t.Fatalf("timer should have stayed at %s, instead it advanced to %s", desiredLast, tick)
|
||||
// case <-time.NewTimer(wait).C:
|
||||
// return
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
//func TestTickerRetro1Hour(t *testing.T) {
|
||||
// offset := time.Duration(10) * time.Second
|
||||
// last := time.Unix(0, 0)
|
||||
// mock := clock.NewMock()
|
||||
// mock.Add(time.Duration(1) * time.Hour)
|
||||
// desiredLast := mock.Now().Add(-offset)
|
||||
// ticker := NewTicker(last, offset, mock)
|
||||
// func TestTickerRetro1Hour(t *testing.T) {
|
||||
// offset := time.Duration(10) * time.Second
|
||||
// last := time.Unix(0, 0)
|
||||
// mock := clock.NewMock()
|
||||
// mock.Add(time.Duration(1) * time.Hour)
|
||||
// desiredLast := mock.Now().Add(-offset)
|
||||
// ticker := NewTicker(last, offset, mock)
|
||||
//
|
||||
// last = assertAdvanceUntil(ticker, last, desiredLast, offset, time.Duration(10)*time.Millisecond, t)
|
||||
// assertNoAdvance(ticker, last, time.Duration(500)*time.Millisecond, t)
|
||||
// last = assertAdvanceUntil(ticker, last, desiredLast, offset, time.Duration(10)*time.Millisecond, t)
|
||||
// assertNoAdvance(ticker, last, time.Duration(500)*time.Millisecond, t)
|
||||
//
|
||||
//}
|
||||
// }
|
||||
//
|
||||
//func TestAdvanceWithUpdateOffset(t *testing.T) {
|
||||
// offset := time.Duration(10) * time.Second
|
||||
// last := time.Unix(0, 0)
|
||||
// mock := clock.NewMock()
|
||||
// mock.Add(time.Duration(1) * time.Hour)
|
||||
// desiredLast := mock.Now().Add(-offset)
|
||||
// ticker := NewTicker(last, offset, mock)
|
||||
// func TestAdvanceWithUpdateOffset(t *testing.T) {
|
||||
// offset := time.Duration(10) * time.Second
|
||||
// last := time.Unix(0, 0)
|
||||
// mock := clock.NewMock()
|
||||
// mock.Add(time.Duration(1) * time.Hour)
|
||||
// desiredLast := mock.Now().Add(-offset)
|
||||
// ticker := NewTicker(last, offset, mock)
|
||||
//
|
||||
// last = assertAdvanceUntil(ticker, last, desiredLast, offset, time.Duration(10)*time.Millisecond, t)
|
||||
// assertNoAdvance(ticker, last, time.Duration(500)*time.Millisecond, t)
|
||||
// last = assertAdvanceUntil(ticker, last, desiredLast, offset, time.Duration(10)*time.Millisecond, t)
|
||||
// assertNoAdvance(ticker, last, time.Duration(500)*time.Millisecond, t)
|
||||
//
|
||||
// // lowering offset should see a few more ticks
|
||||
// offset = time.Duration(5) * time.Second
|
||||
// ticker.updateOffset(offset)
|
||||
// desiredLast = mock.Now().Add(-offset)
|
||||
// last = assertAdvanceUntil(ticker, last, desiredLast, offset, time.Duration(9)*time.Millisecond, t)
|
||||
// assertNoAdvance(ticker, last, time.Duration(500)*time.Millisecond, t)
|
||||
// // lowering offset should see a few more ticks
|
||||
// offset = time.Duration(5) * time.Second
|
||||
// ticker.updateOffset(offset)
|
||||
// desiredLast = mock.Now().Add(-offset)
|
||||
// last = assertAdvanceUntil(ticker, last, desiredLast, offset, time.Duration(9)*time.Millisecond, t)
|
||||
// assertNoAdvance(ticker, last, time.Duration(500)*time.Millisecond, t)
|
||||
//
|
||||
// // advancing clock should see even more ticks
|
||||
// mock.Add(time.Duration(1) * time.Hour)
|
||||
// desiredLast = mock.Now().Add(-offset)
|
||||
// last = assertAdvanceUntil(ticker, last, desiredLast, offset, time.Duration(8)*time.Millisecond, t)
|
||||
// assertNoAdvance(ticker, last, time.Duration(500)*time.Millisecond, t)
|
||||
// // advancing clock should see even more ticks
|
||||
// mock.Add(time.Duration(1) * time.Hour)
|
||||
// desiredLast = mock.Now().Add(-offset)
|
||||
// last = assertAdvanceUntil(ticker, last, desiredLast, offset, time.Duration(8)*time.Millisecond, t)
|
||||
// assertNoAdvance(ticker, last, time.Duration(500)*time.Millisecond, t)
|
||||
//
|
||||
//}
|
||||
// }
|
||||
//
|
||||
//func getCase(lastSeconds, offsetSeconds int) (time.Time, time.Duration) {
|
||||
// last := time.Unix(int64(lastSeconds), 0)
|
||||
// offset := time.Duration(offsetSeconds) * time.Second
|
||||
// return last, offset
|
||||
//}
|
||||
// func getCase(lastSeconds, offsetSeconds int) (time.Time, time.Duration) {
|
||||
// last := time.Unix(int64(lastSeconds), 0)
|
||||
// offset := time.Duration(offsetSeconds) * time.Second
|
||||
// return last, offset
|
||||
// }
|
||||
//
|
||||
//func TestTickerNoAdvance(t *testing.T) {
|
||||
// func TestTickerNoAdvance(t *testing.T) {
|
||||
//
|
||||
// // it's 00:01:00 now. what are some cases where we don't want the ticker to advance?
|
||||
// mock := clock.NewMock()
|
||||
// mock.Add(time.Duration(60) * time.Second)
|
||||
// // it's 00:01:00 now. what are some cases where we don't want the ticker to advance?
|
||||
// mock := clock.NewMock()
|
||||
// mock.Add(time.Duration(60) * time.Second)
|
||||
//
|
||||
// type Case struct {
|
||||
// last int
|
||||
// offset int
|
||||
// }
|
||||
// type Case struct {
|
||||
// last int
|
||||
// offset int
|
||||
// }
|
||||
//
|
||||
// // note that some cases add up to now, others go into the future
|
||||
// cases := []Case{
|
||||
// {50, 10},
|
||||
// {50, 30},
|
||||
// {59, 1},
|
||||
// {59, 10},
|
||||
// {59, 30},
|
||||
// {60, 1},
|
||||
// {60, 10},
|
||||
// {60, 30},
|
||||
// {90, 1},
|
||||
// {90, 10},
|
||||
// {90, 30},
|
||||
// }
|
||||
// for _, c := range cases {
|
||||
// last, offset := getCase(c.last, c.offset)
|
||||
// ticker := NewTicker(last, offset, mock)
|
||||
// assertNoAdvance(ticker, last, time.Duration(500)*time.Millisecond, t)
|
||||
// }
|
||||
//}
|
||||
// // note that some cases add up to now, others go into the future
|
||||
// cases := []Case{
|
||||
// {50, 10},
|
||||
// {50, 30},
|
||||
// {59, 1},
|
||||
// {59, 10},
|
||||
// {59, 30},
|
||||
// {60, 1},
|
||||
// {60, 10},
|
||||
// {60, 30},
|
||||
// {90, 1},
|
||||
// {90, 10},
|
||||
// {90, 30},
|
||||
// }
|
||||
// for _, c := range cases {
|
||||
// last, offset := getCase(c.last, c.offset)
|
||||
// ticker := NewTicker(last, offset, mock)
|
||||
// assertNoAdvance(ticker, last, time.Duration(500)*time.Millisecond, t)
|
||||
// }
|
||||
// }
|
||||
|
@ -244,7 +244,7 @@ func (dr *dashboardServiceImpl) SaveProvisionedDashboard(dto *SaveDashboardDTO,
|
||||
return nil, err
|
||||
}
|
||||
|
||||
//alerts
|
||||
// alerts
|
||||
err = dr.updateAlerting(cmd, dto)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
@ -363,10 +363,9 @@ func (server *Server) getSearchRequest(
|
||||
|
||||
search := ""
|
||||
for _, login := range logins {
|
||||
query := strings.Replace(
|
||||
query := strings.ReplaceAll(
|
||||
server.Config.SearchFilter,
|
||||
"%s", ldap.EscapeFilter(login),
|
||||
-1,
|
||||
)
|
||||
|
||||
search += query
|
||||
@ -509,10 +508,9 @@ func (server *Server) requestMemberOf(entry *ldap.Entry) ([]string, error) {
|
||||
)
|
||||
}
|
||||
|
||||
filter := strings.Replace(
|
||||
filter := strings.ReplaceAll(
|
||||
config.GroupSearchFilter, "%s",
|
||||
ldap.EscapeFilter(filterReplace),
|
||||
-1,
|
||||
)
|
||||
|
||||
server.log.Info("Searching for user's groups", "filter", filter)
|
||||
|
@ -303,7 +303,7 @@ func SetAlertState(cmd *models.SetAlertStateCommand) error {
|
||||
alert.EvalData = cmd.EvalData
|
||||
|
||||
if cmd.Error == "" {
|
||||
alert.ExecutionError = " " //without this space, xorm skips updating this field
|
||||
alert.ExecutionError = " " // without this space, xorm skips updating this field
|
||||
} else {
|
||||
alert.ExecutionError = cmd.Error
|
||||
}
|
||||
|
@ -97,7 +97,7 @@ func (ss *SqlStore) GetAlertNotificationUidWithId(query *models.GetAlertNotifica
|
||||
return err
|
||||
}
|
||||
|
||||
ss.CacheService.Set(cacheKey, query.Result, -1) //Infinite, never changes
|
||||
ss.CacheService.Set(cacheKey, query.Result, -1) // Infinite, never changes
|
||||
|
||||
return nil
|
||||
}
|
||||
|
@ -23,9 +23,7 @@ func validateTimeRange(item *annotations.Item) error {
|
||||
item.Epoch = item.EpochEnd
|
||||
}
|
||||
if item.EpochEnd < item.Epoch {
|
||||
tmp := item.Epoch
|
||||
item.Epoch = item.EpochEnd
|
||||
item.EpochEnd = tmp
|
||||
item.Epoch, item.EpochEnd = item.EpochEnd, item.Epoch
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
@ -102,7 +102,7 @@ func TestOldAnnotationsAreDeletedFirst(t *testing.T) {
|
||||
})
|
||||
})
|
||||
|
||||
//create some test annotations
|
||||
// create some test annotations
|
||||
a := annotations.Item{
|
||||
DashboardId: 1,
|
||||
OrgId: 1,
|
||||
|
@ -153,7 +153,7 @@ func TestAnnotations(t *testing.T) {
|
||||
OrgId: 1,
|
||||
DashboardId: 1,
|
||||
From: 1,
|
||||
To: 15, //this will exclude the second test annotation
|
||||
To: 15, // this will exclude the second test annotation
|
||||
Tags: []string{"outage", "error"},
|
||||
})
|
||||
|
||||
|
@ -42,7 +42,7 @@ func TestApiKeyDataAccess(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("Add an expiring key", func(t *testing.T) {
|
||||
//expires in one hour
|
||||
// expires in one hour
|
||||
cmd := models.AddApiKeyCommand{OrgId: 1, Name: "expiring-in-an-hour", Key: "asd2", SecondsToLive: 3600}
|
||||
err := AddApiKey(&cmd)
|
||||
assert.Nil(t, err)
|
||||
@ -62,7 +62,7 @@ func TestApiKeyDataAccess(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("Add a key with negative lifespan", func(t *testing.T) {
|
||||
//expires in one day
|
||||
// expires in one day
|
||||
cmd := models.AddApiKeyCommand{OrgId: 1, Name: "key-with-negative-lifespan", Key: "asd3", SecondsToLive: -3600}
|
||||
err := AddApiKey(&cmd)
|
||||
assert.EqualError(t, err, models.ErrInvalidApiKeyExpiration.Error())
|
||||
@ -73,17 +73,17 @@ func TestApiKeyDataAccess(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("Add keys", func(t *testing.T) {
|
||||
//never expires
|
||||
// never expires
|
||||
cmd := models.AddApiKeyCommand{OrgId: 1, Name: "key1", Key: "key1", SecondsToLive: 0}
|
||||
err := AddApiKey(&cmd)
|
||||
assert.Nil(t, err)
|
||||
|
||||
//expires in 1s
|
||||
// expires in 1s
|
||||
cmd = models.AddApiKeyCommand{OrgId: 1, Name: "key2", Key: "key2", SecondsToLive: 1}
|
||||
err = AddApiKey(&cmd)
|
||||
assert.Nil(t, err)
|
||||
|
||||
//expires in one hour
|
||||
// expires in one hour
|
||||
cmd = models.AddApiKeyCommand{OrgId: 1, Name: "key3", Key: "key3", SecondsToLive: 3600}
|
||||
err = AddApiKey(&cmd)
|
||||
assert.Nil(t, err)
|
||||
|
@ -454,7 +454,7 @@ func GetDashboardPermissionsForUser(query *models.GetDashboardPermissionsForUser
|
||||
`
|
||||
params = append(params, query.UserId)
|
||||
|
||||
//check the user's role for dashboards that do not have hasAcl set
|
||||
// check the user's role for dashboards that do not have hasAcl set
|
||||
sql += `LEFT JOIN org_user ouRole ON ouRole.user_id = ? AND ouRole.org_id = ?`
|
||||
params = append(params, query.UserId)
|
||||
params = append(params, query.OrgId)
|
||||
|
@ -65,9 +65,9 @@ func addAnnotationMig(mg *Migrator) {
|
||||
Name: "tags", Type: DB_NVarchar, Nullable: true, Length: 500,
|
||||
}))
|
||||
|
||||
///
|
||||
/// Annotation tag
|
||||
///
|
||||
//
|
||||
// Annotation tag
|
||||
//
|
||||
annotationTagTable := Table{
|
||||
Name: "annotation_tag",
|
||||
Columns: []*Column{
|
||||
|
@ -40,7 +40,9 @@ func TestMigrations(t *testing.T) {
|
||||
has, err := x.SQL(sql).Get(&r)
|
||||
So(err, ShouldBeNil)
|
||||
So(has, ShouldBeTrue)
|
||||
expectedMigrations := mg.MigrationsCount() //we currently skip to migrations. We should rewrite skipped migrations to write in the log as well. until then we have to keep this
|
||||
// we currently skip to migrations. We should rewrite skipped migrations to write in the log as well.
|
||||
// until then we have to keep this
|
||||
expectedMigrations := mg.MigrationsCount()
|
||||
So(r.Count, ShouldEqual, expectedMigrations)
|
||||
|
||||
mg = NewMigrator(x)
|
||||
|
@ -3,7 +3,7 @@ package migrations
|
||||
import . "github.com/grafana/grafana/pkg/services/sqlstore/migrator"
|
||||
|
||||
// commented out because of the deadcode CI check
|
||||
//func addStatsMigrations(mg *Migrator) {
|
||||
// func addStatsMigrations(mg *Migrator) {
|
||||
// statTable := Table{
|
||||
// Name: "stat",
|
||||
// Columns: []*Column{
|
||||
@ -33,7 +33,7 @@ import . "github.com/grafana/grafana/pkg/services/sqlstore/migrator"
|
||||
//
|
||||
// // create table
|
||||
// mg.AddMigration("create stat_value table", NewAddTableMigration(statValue))
|
||||
//}
|
||||
// }
|
||||
|
||||
func addTestDataMigrations(mg *Migrator) {
|
||||
testData := Table{
|
||||
|
@ -201,7 +201,7 @@ type CopyTableDataMigration struct {
|
||||
targetTable string
|
||||
sourceCols []string
|
||||
targetCols []string
|
||||
//colMap map[string]string
|
||||
// colMap map[string]string
|
||||
}
|
||||
|
||||
func NewCopyTableDataMigration(targetTable string, sourceTable string, colMap map[string]string) *CopyTableDataMigration {
|
||||
|
@ -76,7 +76,7 @@ func (db *Sqlite3) IndexCheckSql(tableName, indexName string) (string, []interfa
|
||||
|
||||
func (db *Sqlite3) DropIndexSql(tableName string, index *Index) string {
|
||||
quote := db.Quote
|
||||
//var unique string
|
||||
// var unique string
|
||||
idxName := index.XName(tableName)
|
||||
return fmt.Sprintf("DROP INDEX %v", quote(idxName))
|
||||
}
|
||||
|
@ -35,7 +35,7 @@ func GetOrgQuotaByTarget(query *models.GetOrgQuotaByTargetQuery) error {
|
||||
quota.Limit = query.Default
|
||||
}
|
||||
|
||||
//get quota used.
|
||||
// get quota used.
|
||||
rawSql := fmt.Sprintf("SELECT COUNT(*) as count from %s where org_id=?", dialect.Quote(query.Target))
|
||||
resp := make([]*targetCount, 0)
|
||||
if err := x.SQL(rawSql, query.OrgId).Find(&resp); err != nil {
|
||||
@ -78,7 +78,7 @@ func GetOrgQuotas(query *models.GetOrgQuotasQuery) error {
|
||||
|
||||
result := make([]*models.OrgQuotaDTO, len(quotas))
|
||||
for i, q := range quotas {
|
||||
//get quota used.
|
||||
// get quota used.
|
||||
rawSql := fmt.Sprintf("SELECT COUNT(*) as count from %s where org_id=?", dialect.Quote(q.Target))
|
||||
resp := make([]*targetCount, 0)
|
||||
if err := x.SQL(rawSql, q.OrgId).Find(&resp); err != nil {
|
||||
@ -97,7 +97,7 @@ func GetOrgQuotas(query *models.GetOrgQuotasQuery) error {
|
||||
|
||||
func UpdateOrgQuota(cmd *models.UpdateOrgQuotaCmd) error {
|
||||
return inTransaction(func(sess *DBSession) error {
|
||||
//Check if quota is already defined in the DB
|
||||
// Check if quota is already defined in the DB
|
||||
quota := models.Quota{
|
||||
Target: cmd.Target,
|
||||
OrgId: cmd.OrgId,
|
||||
@ -110,12 +110,12 @@ func UpdateOrgQuota(cmd *models.UpdateOrgQuotaCmd) error {
|
||||
quota.Limit = cmd.Limit
|
||||
if !has {
|
||||
quota.Created = time.Now()
|
||||
//No quota in the DB for this target, so create a new one.
|
||||
// No quota in the DB for this target, so create a new one.
|
||||
if _, err := sess.Insert("a); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
//update existing quota entry in the DB.
|
||||
// update existing quota entry in the DB.
|
||||
_, err := sess.ID(quota.Id).Update("a)
|
||||
if err != nil {
|
||||
return err
|
||||
@ -138,7 +138,7 @@ func GetUserQuotaByTarget(query *models.GetUserQuotaByTargetQuery) error {
|
||||
quota.Limit = query.Default
|
||||
}
|
||||
|
||||
//get quota used.
|
||||
// get quota used.
|
||||
rawSql := fmt.Sprintf("SELECT COUNT(*) as count from %s where user_id=?", dialect.Quote(query.Target))
|
||||
resp := make([]*targetCount, 0)
|
||||
if err := x.SQL(rawSql, query.UserId).Find(&resp); err != nil {
|
||||
@ -181,7 +181,7 @@ func GetUserQuotas(query *models.GetUserQuotasQuery) error {
|
||||
|
||||
result := make([]*models.UserQuotaDTO, len(quotas))
|
||||
for i, q := range quotas {
|
||||
//get quota used.
|
||||
// get quota used.
|
||||
rawSql := fmt.Sprintf("SELECT COUNT(*) as count from %s where user_id=?", dialect.Quote(q.Target))
|
||||
resp := make([]*targetCount, 0)
|
||||
if err := x.SQL(rawSql, q.UserId).Find(&resp); err != nil {
|
||||
@ -200,7 +200,7 @@ func GetUserQuotas(query *models.GetUserQuotasQuery) error {
|
||||
|
||||
func UpdateUserQuota(cmd *models.UpdateUserQuotaCmd) error {
|
||||
return inTransaction(func(sess *DBSession) error {
|
||||
//Check if quota is already defined in the DB
|
||||
// Check if quota is already defined in the DB
|
||||
quota := models.Quota{
|
||||
Target: cmd.Target,
|
||||
UserId: cmd.UserId,
|
||||
@ -213,12 +213,12 @@ func UpdateUserQuota(cmd *models.UpdateUserQuotaCmd) error {
|
||||
quota.Limit = cmd.Limit
|
||||
if !has {
|
||||
quota.Created = time.Now()
|
||||
//No quota in the DB for this target, so create a new one.
|
||||
// No quota in the DB for this target, so create a new one.
|
||||
if _, err := sess.Insert("a); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
//update existing quota entry in the DB.
|
||||
// update existing quota entry in the DB.
|
||||
_, err := sess.ID(quota.Id).Update("a)
|
||||
if err != nil {
|
||||
return err
|
||||
@ -230,7 +230,7 @@ func UpdateUserQuota(cmd *models.UpdateUserQuotaCmd) error {
|
||||
}
|
||||
|
||||
func GetGlobalQuotaByTarget(query *models.GetGlobalQuotaByTargetQuery) error {
|
||||
//get quota used.
|
||||
// get quota used.
|
||||
rawSql := fmt.Sprintf("SELECT COUNT(*) as count from %s", dialect.Quote(query.Target))
|
||||
resp := make([]*targetCount, 0)
|
||||
if err := x.SQL(rawSql).Find(&resp); err != nil {
|
||||
|
@ -92,10 +92,10 @@ func TestQuotaCommandsAndQueries(t *testing.T) {
|
||||
So(err, ShouldBeNil)
|
||||
So(len(query.Result), ShouldEqual, 4)
|
||||
for _, res := range query.Result {
|
||||
limit := 5 //default quota limit
|
||||
limit := 5 // default quota limit
|
||||
used := 0
|
||||
if res.Target == "org_user" {
|
||||
limit = 10 //customized quota limit.
|
||||
limit = 10 // customized quota limit.
|
||||
used = 1
|
||||
}
|
||||
So(res.Limit, ShouldEqual, limit)
|
||||
|
@ -560,7 +560,7 @@ func DeleteUser(cmd *models.DeleteUserCommand) error {
|
||||
}
|
||||
|
||||
func deleteUserInTransaction(sess *DBSession, cmd *models.DeleteUserCommand) error {
|
||||
//Check if user exists
|
||||
// Check if user exists
|
||||
user := models.User{Id: cmd.UserId}
|
||||
has, err := sess.Get(&user)
|
||||
if err != nil {
|
||||
|
@ -423,9 +423,9 @@ type AnnotationCleanupSettings struct {
|
||||
}
|
||||
|
||||
func envKey(sectionName string, keyName string) string {
|
||||
sN := strings.ToUpper(strings.Replace(sectionName, ".", "_", -1))
|
||||
sN = strings.Replace(sN, "-", "_", -1)
|
||||
kN := strings.ToUpper(strings.Replace(keyName, ".", "_", -1))
|
||||
sN := strings.ToUpper(strings.ReplaceAll(sectionName, ".", "_"))
|
||||
sN = strings.ReplaceAll(sN, "-", "_")
|
||||
kN := strings.ToUpper(strings.ReplaceAll(keyName, ".", "_"))
|
||||
envKey := fmt.Sprintf("GF_%s_%s", sN, kN)
|
||||
return envKey
|
||||
}
|
||||
|
@ -27,7 +27,7 @@ type kqlMacroEngine struct {
|
||||
// - $__contains(col, 'val1','val2') -> col in ('val1', 'val2')
|
||||
// - $__escapeMulti('\\vm\eth0\Total','\\vm\eth2\Total') -> @'\\vm\eth0\Total',@'\\vm\eth2\Total'
|
||||
|
||||
//KqlInterpolate interpolates macros for Kusto Query Language (KQL) queries
|
||||
// KqlInterpolate interpolates macros for Kusto Query Language (KQL) queries
|
||||
func KqlInterpolate(query *tsdb.Query, timeRange *tsdb.TimeRange, kql string, defaultTimeField ...string) (string, error) {
|
||||
engine := kqlMacroEngine{}
|
||||
|
||||
@ -46,7 +46,7 @@ func (m *kqlMacroEngine) Interpolate(query *tsdb.Query, timeRange *tsdb.TimeRang
|
||||
|
||||
var macroError error
|
||||
|
||||
//First pass for the escapeMulti macro
|
||||
// First pass for the escapeMulti macro
|
||||
kql = m.ReplaceAllStringSubmatchFunc(escapeMultiRegex, kql, func(groups []string) string {
|
||||
args := []string{}
|
||||
|
||||
@ -58,7 +58,7 @@ func (m *kqlMacroEngine) Interpolate(query *tsdb.Query, timeRange *tsdb.TimeRang
|
||||
return fmt.Sprintf("@%s", expr)
|
||||
})
|
||||
|
||||
//second pass for all the other macros
|
||||
// second pass for all the other macros
|
||||
kql = m.ReplaceAllStringSubmatchFunc(rExp, kql, func(groups []string) string {
|
||||
args := []string{}
|
||||
if len(groups) > 2 {
|
||||
|
@ -54,7 +54,7 @@ type AzureMonitorResponse struct {
|
||||
Resourceregion string `json:"resourceregion"`
|
||||
}
|
||||
|
||||
//ApplicationInsightsQueryResponse is the json response from the Application Insights API
|
||||
// ApplicationInsightsQueryResponse is the json response from the Application Insights API
|
||||
type ApplicationInsightsQueryResponse struct {
|
||||
Tables []struct {
|
||||
Name string `json:"name"`
|
||||
@ -71,7 +71,7 @@ type AzureLogAnalyticsResponse struct {
|
||||
Tables []AzureLogAnalyticsTable `json:"tables"`
|
||||
}
|
||||
|
||||
//AzureLogAnalyticsTable is the table format for Log Analytics responses
|
||||
// AzureLogAnalyticsTable is the table format for Log Analytics responses
|
||||
type AzureLogAnalyticsTable struct {
|
||||
Name string `json:"name"`
|
||||
Columns []struct {
|
||||
|
@ -320,7 +320,7 @@ func interpolateFilterWildcards(value string) string {
|
||||
matches := strings.Count(value, "*")
|
||||
switch {
|
||||
case matches == 2 && strings.HasSuffix(value, "*") && strings.HasPrefix(value, "*"):
|
||||
value = strings.Replace(value, "*", "", -1)
|
||||
value = strings.ReplaceAll(value, "*", "")
|
||||
value = fmt.Sprintf(`has_substring("%s")`, value)
|
||||
case matches == 1 && strings.HasPrefix(value, "*"):
|
||||
value = strings.Replace(value, "*", "", 1)
|
||||
@ -332,8 +332,8 @@ func interpolateFilterWildcards(value string) string {
|
||||
value = string(wildcardRegexRe.ReplaceAllFunc([]byte(value), func(in []byte) []byte {
|
||||
return []byte(strings.Replace(string(in), string(in), `\\`+string(in), 1))
|
||||
}))
|
||||
value = strings.Replace(value, "*", ".*", -1)
|
||||
value = strings.Replace(value, `"`, `\\"`, -1)
|
||||
value = strings.ReplaceAll(value, "*", ".*")
|
||||
value = strings.ReplaceAll(value, `"`, `\\"`)
|
||||
value = fmt.Sprintf(`monitoring.regex.full_match("^%s$")`, value)
|
||||
}
|
||||
|
||||
|
@ -12,9 +12,9 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
//***
|
||||
// ***
|
||||
// LogQuery tests
|
||||
//***
|
||||
// ***
|
||||
|
||||
func TestLogsResultsToDataframes(t *testing.T) {
|
||||
fakeCloudwatchResponse := &cloudwatchlogs.GetQueryResultsOutput{
|
||||
|
@ -141,8 +141,8 @@ func (c *baseClientImpl) encodeBatchRequests(requests []*multiRequest) ([]byte,
|
||||
}
|
||||
|
||||
body := string(reqBody)
|
||||
body = strings.Replace(body, "$__interval_ms", strconv.FormatInt(r.interval.Milliseconds(), 10), -1)
|
||||
body = strings.Replace(body, "$__interval", r.interval.Text, -1)
|
||||
body = strings.ReplaceAll(body, "$__interval_ms", strconv.FormatInt(r.interval.Milliseconds(), 10))
|
||||
body = strings.ReplaceAll(body, "$__interval", r.interval.Text)
|
||||
|
||||
payload.WriteString(body + "\n")
|
||||
}
|
||||
|
@ -220,7 +220,7 @@ var datePatternReplacements = map[string]string{
|
||||
"YYYY": "2006", // stdLongYear 1970 1971 ... 2029 2030
|
||||
"gg": "<stdIsoYearShort>", // ISO-8601 year number 70 71 ... 29 30
|
||||
"gggg": "<stdIsoYear>", // ***1970 1971 ... 2029 2030
|
||||
"GG": "<stdIsoYearShort>", //70 71 ... 29 30
|
||||
"GG": "<stdIsoYearShort>", // 70 71 ... 29 30
|
||||
"GGGG": "<stdIsoYear>", // ***1970 1971 ... 2029 2030
|
||||
"Q": "<stdQuarter>", // 1, 2, 3, 4
|
||||
"A": "PM", // stdPM AM PM
|
||||
@ -233,17 +233,17 @@ var datePatternReplacements = map[string]string{
|
||||
"mm": "04", // stdZeroMinute 00 01 ... 58 59
|
||||
"s": "5", // stdSecond 0 1 ... 58 59
|
||||
"ss": "05", // stdZeroSecond ***00 01 ... 58 59
|
||||
"z": "MST", //EST CST ... MST PST
|
||||
"zz": "MST", //EST CST ... MST PST
|
||||
"z": "MST", // EST CST ... MST PST
|
||||
"zz": "MST", // EST CST ... MST PST
|
||||
"Z": "Z07:00", // stdNumColonTZ -07:00 -06:00 ... +06:00 +07:00
|
||||
"ZZ": "-0700", // stdNumTZ -0700 -0600 ... +0600 +0700
|
||||
"X": "<stdUnix>", // Seconds since unix epoch 1360013296
|
||||
"LT": "3:04 PM", // 8:30 PM
|
||||
"L": "01/02/2006", //09/04/1986
|
||||
"l": "1/2/2006", //9/4/1986
|
||||
"ll": "Jan 2 2006", //Sep 4 1986
|
||||
"lll": "Jan 2 2006 3:04 PM", //Sep 4 1986 8:30 PM
|
||||
"llll": "Mon, Jan 2 2006 3:04 PM", //Thu, Sep 4 1986 8:30 PM
|
||||
"L": "01/02/2006", // 09/04/1986
|
||||
"l": "1/2/2006", // 9/4/1986
|
||||
"ll": "Jan 2 2006", // Sep 4 1986
|
||||
"lll": "Jan 2 2006 3:04 PM", // Sep 4 1986 8:30 PM
|
||||
"llll": "Mon, Jan 2 2006 3:04 PM", // Thu, Sep 4 1986 8:30 PM
|
||||
}
|
||||
|
||||
func formatDate(t time.Time, pattern string) string {
|
||||
@ -277,11 +277,11 @@ func formatDate(t time.Time, pattern string) string {
|
||||
if strings.Contains(formatted, "<std") {
|
||||
isoYear, isoWeek := t.ISOWeek()
|
||||
isoYearShort := fmt.Sprintf("%d", isoYear)[2:4]
|
||||
formatted = strings.Replace(formatted, "<stdIsoYear>", fmt.Sprintf("%d", isoYear), -1)
|
||||
formatted = strings.Replace(formatted, "<stdIsoYearShort>", isoYearShort, -1)
|
||||
formatted = strings.Replace(formatted, "<stdWeekOfYear>", fmt.Sprintf("%02d", isoWeek), -1)
|
||||
formatted = strings.ReplaceAll(formatted, "<stdIsoYear>", fmt.Sprintf("%d", isoYear))
|
||||
formatted = strings.ReplaceAll(formatted, "<stdIsoYearShort>", isoYearShort)
|
||||
formatted = strings.ReplaceAll(formatted, "<stdWeekOfYear>", fmt.Sprintf("%02d", isoWeek))
|
||||
|
||||
formatted = strings.Replace(formatted, "<stdUnix>", fmt.Sprintf("%d", t.Unix()), -1)
|
||||
formatted = strings.ReplaceAll(formatted, "<stdUnix>", fmt.Sprintf("%d", t.Unix()))
|
||||
|
||||
day := t.Weekday()
|
||||
dayOfWeekIso := int(day)
|
||||
@ -289,9 +289,9 @@ func formatDate(t time.Time, pattern string) string {
|
||||
dayOfWeekIso = 7
|
||||
}
|
||||
|
||||
formatted = strings.Replace(formatted, "<stdDayOfWeek>", fmt.Sprintf("%d", day), -1)
|
||||
formatted = strings.Replace(formatted, "<stdDayOfWeekISO>", fmt.Sprintf("%d", dayOfWeekIso), -1)
|
||||
formatted = strings.Replace(formatted, "<stdDayOfYear>", fmt.Sprintf("%d", t.YearDay()), -1)
|
||||
formatted = strings.ReplaceAll(formatted, "<stdDayOfWeek>", fmt.Sprintf("%d", day))
|
||||
formatted = strings.ReplaceAll(formatted, "<stdDayOfWeekISO>", fmt.Sprintf("%d", dayOfWeekIso))
|
||||
formatted = strings.ReplaceAll(formatted, "<stdDayOfYear>", fmt.Sprintf("%d", t.YearDay()))
|
||||
|
||||
quarter := 4
|
||||
|
||||
@ -304,8 +304,8 @@ func formatDate(t time.Time, pattern string) string {
|
||||
quarter = 3
|
||||
}
|
||||
|
||||
formatted = strings.Replace(formatted, "<stdQuarter>", fmt.Sprintf("%d", quarter), -1)
|
||||
formatted = strings.Replace(formatted, "<stdHourNoZero>", fmt.Sprintf("%d", t.Hour()), -1)
|
||||
formatted = strings.ReplaceAll(formatted, "<stdQuarter>", fmt.Sprintf("%d", quarter))
|
||||
formatted = strings.ReplaceAll(formatted, "<stdHourNoZero>", fmt.Sprintf("%d", t.Hour()))
|
||||
}
|
||||
|
||||
if ltr {
|
||||
|
@ -375,7 +375,7 @@ func (rp *responseParser) processAggregationDocs(esAgg *simplejson.Json, aggDef
|
||||
if len(otherMetrics) > 1 {
|
||||
metricName += " " + metric.Field
|
||||
if metric.Type == "bucket_script" {
|
||||
//Use the formula in the column name
|
||||
// Use the formula in the column name
|
||||
metricName = metric.Settings.Get("script").MustString("")
|
||||
}
|
||||
}
|
||||
@ -484,7 +484,7 @@ func (rp *responseParser) getSeriesName(series *tsdb.TimeSeries, target *Query,
|
||||
for name, pipelineAgg := range metric.PipelineVariables {
|
||||
for _, m := range target.Metrics {
|
||||
if m.ID == pipelineAgg {
|
||||
metricName = strings.Replace(metricName, "params."+name, describeMetric(m.Type, m.Field), -1)
|
||||
metricName = strings.ReplaceAll(metricName, "params."+name, describeMetric(m.Type, m.Field))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -178,17 +178,17 @@ func formatTimeRange(input string) string {
|
||||
if input == "now" {
|
||||
return input
|
||||
}
|
||||
return strings.Replace(strings.Replace(strings.Replace(input, "now", "", -1), "m", "min", -1), "M", "mon", -1)
|
||||
return strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(input, "now", ""), "m", "min"), "M", "mon")
|
||||
}
|
||||
|
||||
func fixIntervalFormat(target string) string {
|
||||
rMinute := regexp.MustCompile(`'(\d+)m'`)
|
||||
target = rMinute.ReplaceAllStringFunc(target, func(m string) string {
|
||||
return strings.Replace(m, "m", "min", -1)
|
||||
return strings.ReplaceAll(m, "m", "min")
|
||||
})
|
||||
rMonth := regexp.MustCompile(`'(\d+)M'`)
|
||||
target = rMonth.ReplaceAllStringFunc(target, func(M string) string {
|
||||
return strings.Replace(M, "M", "mon", -1)
|
||||
return strings.ReplaceAll(M, "M", "mon")
|
||||
})
|
||||
return target
|
||||
}
|
||||
|
@ -18,7 +18,7 @@ import (
|
||||
)
|
||||
|
||||
type InfluxDBExecutor struct {
|
||||
//*models.DataSource
|
||||
// *models.DataSource
|
||||
QueryParser *InfluxdbQueryParser
|
||||
ResponseParser *ResponseParser
|
||||
}
|
||||
|
@ -30,10 +30,10 @@ func (query *Query) Build(queryContext *tsdb.TsdbQuery) (string, error) {
|
||||
calculator := tsdb.NewIntervalCalculator(&tsdb.IntervalOptions{})
|
||||
interval := calculator.Calculate(queryContext.TimeRange, query.Interval)
|
||||
|
||||
res = strings.Replace(res, "$timeFilter", query.renderTimeFilter(queryContext), -1)
|
||||
res = strings.Replace(res, "$interval", interval.Text, -1)
|
||||
res = strings.Replace(res, "$__interval_ms", strconv.FormatInt(interval.Milliseconds(), 10), -1)
|
||||
res = strings.Replace(res, "$__interval", interval.Text, -1)
|
||||
res = strings.ReplaceAll(res, "$timeFilter", query.renderTimeFilter(queryContext))
|
||||
res = strings.ReplaceAll(res, "$interval", interval.Text)
|
||||
res = strings.ReplaceAll(res, "$__interval_ms", strconv.FormatInt(interval.Milliseconds(), 10))
|
||||
res = strings.ReplaceAll(res, "$__interval", interval.Text)
|
||||
return res, nil
|
||||
}
|
||||
|
||||
@ -51,7 +51,7 @@ func (query *Query) renderTags() []string {
|
||||
str += " "
|
||||
}
|
||||
|
||||
//If the operator is missing we fall back to sensible defaults
|
||||
// If the operator is missing we fall back to sensible defaults
|
||||
if tag.Operator == "" {
|
||||
if regexpOperatorPattern.Match([]byte(tag.Value)) {
|
||||
tag.Operator = "=~"
|
||||
@ -68,7 +68,7 @@ func (query *Query) renderTags() []string {
|
||||
case "<", ">":
|
||||
textValue = tag.Value
|
||||
default:
|
||||
textValue = fmt.Sprintf("'%s'", strings.Replace(tag.Value, `\`, `\\`, -1))
|
||||
textValue = fmt.Sprintf("'%s'", strings.ReplaceAll(tag.Value, `\`, `\\`))
|
||||
}
|
||||
|
||||
res = append(res, fmt.Sprintf(`%s"%s" %s %s`, str, tag.Key, tag.Operator, textValue))
|
||||
@ -143,7 +143,7 @@ func (query *Query) renderGroupBy(queryContext *tsdb.TsdbQuery) string {
|
||||
}
|
||||
|
||||
if i > 0 && group.Type != "fill" {
|
||||
groupBy += ", " //fill is so very special. fill is a creep, fill is a weirdo
|
||||
groupBy += ", " // fill is so very special. fill is a creep, fill is a weirdo
|
||||
} else {
|
||||
groupBy += " "
|
||||
}
|
||||
|
@ -983,7 +983,7 @@ func TestMSSQL(t *testing.T) {
|
||||
So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
|
||||
columns := queryResult.Tables[0].Rows[0]
|
||||
|
||||
//Should be in milliseconds
|
||||
// Should be in milliseconds
|
||||
So(columns[0].(float64), ShouldEqual, float64(dt.UnixNano()/1e6))
|
||||
})
|
||||
|
||||
@ -1013,7 +1013,7 @@ func TestMSSQL(t *testing.T) {
|
||||
So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
|
||||
columns := queryResult.Tables[0].Rows[0]
|
||||
|
||||
//Should be in milliseconds
|
||||
// Should be in milliseconds
|
||||
So(columns[0].(int64), ShouldEqual, dt.Unix()*1000)
|
||||
})
|
||||
|
||||
@ -1043,7 +1043,7 @@ func TestMSSQL(t *testing.T) {
|
||||
So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
|
||||
columns := queryResult.Tables[0].Rows[0]
|
||||
|
||||
//Should be in milliseconds
|
||||
// Should be in milliseconds
|
||||
So(columns[0].(int64), ShouldEqual, dt.Unix()*1000)
|
||||
})
|
||||
|
||||
@ -1073,7 +1073,7 @@ func TestMSSQL(t *testing.T) {
|
||||
So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
|
||||
columns := queryResult.Tables[0].Rows[0]
|
||||
|
||||
//Should be in milliseconds
|
||||
// Should be in milliseconds
|
||||
So(columns[0].(float64), ShouldEqual, float64(dt.Unix()*1000))
|
||||
})
|
||||
|
||||
@ -1101,7 +1101,7 @@ func TestMSSQL(t *testing.T) {
|
||||
So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
|
||||
columns := queryResult.Tables[0].Rows[0]
|
||||
|
||||
//Should be in milliseconds
|
||||
// Should be in milliseconds
|
||||
So(columns[0], ShouldBeNil)
|
||||
})
|
||||
|
||||
@ -1129,7 +1129,7 @@ func TestMSSQL(t *testing.T) {
|
||||
So(len(queryResult.Tables[0].Rows), ShouldEqual, 1)
|
||||
columns := queryResult.Tables[0].Rows[0]
|
||||
|
||||
//Should be in milliseconds
|
||||
// Should be in milliseconds
|
||||
So(columns[0], ShouldBeNil)
|
||||
})
|
||||
})
|
||||
|
@ -25,7 +25,7 @@ func init() {
|
||||
}
|
||||
|
||||
func characterEscape(s string, escapeChar string) string {
|
||||
return strings.Replace(s, escapeChar, url.QueryEscape(escapeChar), -1)
|
||||
return strings.ReplaceAll(s, escapeChar, url.QueryEscape(escapeChar))
|
||||
}
|
||||
|
||||
func newMysqlQueryEndpoint(datasource *models.DataSource) (tsdb.TsdbQueryEndpoint, error) {
|
||||
|
@ -160,7 +160,7 @@ func (e *OpenTsdbExecutor) buildMetric(query *tsdb.Query) map[string]interface{}
|
||||
if !disableDownsampling {
|
||||
downsampleInterval := query.Model.Get("downsampleInterval").MustString()
|
||||
if downsampleInterval == "" {
|
||||
downsampleInterval = "1m" //default value for blank
|
||||
downsampleInterval = "1m" // default value for blank
|
||||
}
|
||||
downsample := downsampleInterval + "-" + query.Model.Get("downsampleAggregator").MustString()
|
||||
if query.Model.Get("downsampleFillPolicy").MustString() != "none" {
|
||||
|
@ -58,7 +58,7 @@ func newPostgresQueryEndpoint(datasource *models.DataSource) (tsdb.TsdbQueryEndp
|
||||
|
||||
// escape single quotes and backslashes in Postgres connection string parameters.
|
||||
func escape(input string) string {
|
||||
return strings.Replace(strings.Replace(input, `\`, `\\`, -1), "'", `\'`, -1)
|
||||
return strings.ReplaceAll(strings.ReplaceAll(input, `\`, `\\`), "'", `\'`)
|
||||
}
|
||||
|
||||
func generateConnectionString(datasource *models.DataSource, logger log.Logger) (string, error) {
|
||||
|
@ -207,10 +207,10 @@ var Interpolate = func(query *tsdb.Query, timeRange *tsdb.TimeRange, sql string)
|
||||
}
|
||||
interval := sqlIntervalCalculator.Calculate(timeRange, minInterval)
|
||||
|
||||
sql = strings.Replace(sql, "$__interval_ms", strconv.FormatInt(interval.Milliseconds(), 10), -1)
|
||||
sql = strings.Replace(sql, "$__interval", interval.Text, -1)
|
||||
sql = strings.Replace(sql, "$__unixEpochFrom()", fmt.Sprintf("%d", timeRange.GetFromAsSecondsEpoch()), -1)
|
||||
sql = strings.Replace(sql, "$__unixEpochTo()", fmt.Sprintf("%d", timeRange.GetToAsSecondsEpoch()), -1)
|
||||
sql = strings.ReplaceAll(sql, "$__interval_ms", strconv.FormatInt(interval.Milliseconds(), 10))
|
||||
sql = strings.ReplaceAll(sql, "$__interval", interval.Text)
|
||||
sql = strings.ReplaceAll(sql, "$__unixEpochFrom()", fmt.Sprintf("%d", timeRange.GetFromAsSecondsEpoch()))
|
||||
sql = strings.ReplaceAll(sql, "$__unixEpochTo()", fmt.Sprintf("%d", timeRange.GetToAsSecondsEpoch()))
|
||||
|
||||
return sql, nil
|
||||
}
|
||||
|
@ -218,7 +218,7 @@ func init() {
|
||||
queryRes := tsdb.NewQueryResult()
|
||||
|
||||
stringInput := query.Model.Get("stringInput").MustString()
|
||||
stringInput = strings.Replace(stringInput, " ", "", -1)
|
||||
stringInput = strings.ReplaceAll(stringInput, " ", "")
|
||||
|
||||
values := []null.Float{}
|
||||
for _, strVal := range strings.Split(stringInput, ",") {
|
||||
|
@ -61,7 +61,7 @@ func Encrypt(payload []byte, secret string) ([]byte, error) {
|
||||
// The IV needs to be unique, but not secure. Therefore it's common to
|
||||
// include it at the beginning of the ciphertext.
|
||||
ciphertext := make([]byte, saltLength+aes.BlockSize+len(payload))
|
||||
copy(ciphertext[:saltLength], []byte(salt))
|
||||
copy(ciphertext[:saltLength], salt)
|
||||
iv := ciphertext[saltLength : saltLength+aes.BlockSize]
|
||||
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
|
||||
return nil, err
|
||||
|
@ -8,20 +8,20 @@ import (
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
//ErrWalkSkipDir is the Error returned when we want to skip descending into a directory
|
||||
// ErrWalkSkipDir is the Error returned when we want to skip descending into a directory
|
||||
var ErrWalkSkipDir = errors.New("skip this directory")
|
||||
|
||||
//WalkFunc is a callback function called for each path as a directory is walked
|
||||
//If resolvedPath != "", then we are following symbolic links.
|
||||
// WalkFunc is a callback function called for each path as a directory is walked
|
||||
// If resolvedPath != "", then we are following symbolic links.
|
||||
type WalkFunc func(resolvedPath string, info os.FileInfo, err error) error
|
||||
|
||||
//Walk walks a path, optionally following symbolic links, and for each path,
|
||||
//it calls the walkFn passed.
|
||||
// Walk walks a path, optionally following symbolic links, and for each path,
|
||||
// it calls the walkFn passed.
|
||||
//
|
||||
//It is similar to filepath.Walk, except that it supports symbolic links and
|
||||
//can detect infinite loops while following sym links.
|
||||
//It solves the issue where your WalkFunc needs a path relative to the symbolic link
|
||||
//(resolving links within walkfunc loses the path to the symbolic link for each traversal).
|
||||
// It is similar to filepath.Walk, except that it supports symbolic links and
|
||||
// can detect infinite loops while following sym links.
|
||||
// It solves the issue where your WalkFunc needs a path relative to the symbolic link
|
||||
// (resolving links within walkfunc loses the path to the symbolic link for each traversal).
|
||||
func Walk(path string, followSymlinks bool, detectSymlinkInfiniteLoop bool, walkFn WalkFunc) error {
|
||||
info, err := os.Lstat(path)
|
||||
if err != nil {
|
||||
@ -38,12 +38,12 @@ func Walk(path string, followSymlinks bool, detectSymlinkInfiniteLoop bool, walk
|
||||
return walk(path, info, resolvedPath, symlinkPathsFollowed, walkFn)
|
||||
}
|
||||
|
||||
//walk walks the path. It is a helper/sibling function to Walk.
|
||||
//It takes a resolvedPath into consideration. This way, paths being walked are
|
||||
//always relative to the path argument, even if symbolic links were resolved).
|
||||
// walk walks the path. It is a helper/sibling function to Walk.
|
||||
// It takes a resolvedPath into consideration. This way, paths being walked are
|
||||
// always relative to the path argument, even if symbolic links were resolved).
|
||||
//
|
||||
//If resolvedPath is "", then we are not following symbolic links.
|
||||
//If symlinkPathsFollowed is not nil, then we need to detect infinite loop.
|
||||
// If resolvedPath is "", then we are not following symbolic links.
|
||||
// If symlinkPathsFollowed is not nil, then we need to detect infinite loop.
|
||||
func walk(path string, info os.FileInfo, resolvedPath string, symlinkPathsFollowed map[string]bool, walkFn WalkFunc) error {
|
||||
if info == nil {
|
||||
return errors.New("Walk: Nil FileInfo passed")
|
||||
@ -60,7 +60,7 @@ func walk(path string, info os.FileInfo, resolvedPath string, symlinkPathsFollow
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
//vout("SymLink Path: %v, links to: %v", resolvedPath, path2)
|
||||
// vout("SymLink Path: %v, links to: %v", resolvedPath, path2)
|
||||
if symlinkPathsFollowed != nil {
|
||||
if _, ok := symlinkPathsFollowed[path2]; ok {
|
||||
errMsg := "Potential SymLink Infinite Loop. Path: %v, Link To: %v"
|
||||
|
Loading…
Reference in New Issue
Block a user