diff --git a/.circleci/config.yml b/.circleci/config.yml index 4fb96bf5c3..373fdbc0de 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -29,7 +29,7 @@ jobs: - image: circleci/golang:1.11 environment: GOCACHE: /tmp/go-cache - GOFLAGs: "-mod=readonly" + GOFLAGS: "-mod=readonly" working_directory: /go/src/github.com/influxdata/platform steps: - checkout @@ -56,8 +56,13 @@ jobs: # - run: make test-go-race # This doesn't use the test cache, and will not complete quickly. # TODO add these checks to the Makefile # - run: go get -v -t -d ./... - # - run: go get honnef.co/go/tools/cmd/megacheck - # - run: megacheck ./... + + # TODO(#544): fix the remaining static check in the generated promql file, and enable exit-non-zero. + # Not yet sure if that's a bug in staticcheck or if we need to submit a patch to pigeon to fix the generator. + - run: GO111MODULE=on go mod vendor # megacheck isn't module-aware yet, so install module dependencies to vendor. + - run: GO111MODULE=on go install honnef.co/go/tools/cmd/megacheck # Install megacheck from the version we specify in go.mod. + - run: megacheck -staticcheck.exit-non-zero=false ./... + - save_cache: name: Saving GOCACHE key: platform-gocache-{{ .Branch }}-{{ .Revision }} @@ -76,7 +81,7 @@ jobs: - image: circleci/golang:1.11-node-browsers environment: GOCACHE: /tmp/go-cache - GOFLAGs: "-mod=readonly" + GOFLAGS: "-mod=readonly" working_directory: /go/src/github.com/influxdata/platform steps: - checkout diff --git a/bolt/keyvalue_log.go b/bolt/keyvalue_log.go index 3ae6d49663..3f16f6ff43 100644 --- a/bolt/keyvalue_log.go +++ b/bolt/keyvalue_log.go @@ -39,8 +39,6 @@ func (b *keyValueLogBounds) update(t time.Time) { } else if b.Stop < now { b.Stop = now } - - return } // StartTime retrieves the start value of a bounds as a time.Time diff --git a/bolt/user_resource_mapping.go b/bolt/user_resource_mapping.go index 785de6a928..9aca07e873 100644 --- a/bolt/user_resource_mapping.go +++ b/bolt/user_resource_mapping.go @@ -64,29 +64,6 @@ func (c *Client) findUserResourceMappings(ctx context.Context, tx *bolt.Tx, filt return ms, nil } -func (c *Client) findUserResourceMapping(ctx context.Context, tx *bolt.Tx, resourceID platform.ID, userID platform.ID) (*platform.UserResourceMapping, error) { - var m platform.UserResourceMapping - - key, err := userResourceKey(&platform.UserResourceMapping{ - ResourceID: resourceID, - UserID: userID, - }) - if err != nil { - return nil, err - } - - v := tx.Bucket(userResourceMappingBucket).Get(key) - if len(v) == 0 { - return nil, fmt.Errorf("userResource mapping not found") - } - - if err := json.Unmarshal(v, &m); err != nil { - return nil, err - } - - return &m, nil -} - func (c *Client) CreateUserResourceMapping(ctx context.Context, m *platform.UserResourceMapping) error { return c.db.Update(func(tx *bolt.Tx) error { return c.createUserResourceMapping(ctx, tx, m) diff --git a/chronograf/bolt/client.go b/chronograf/bolt/client.go index e66ed9eb8b..47807c4770 100644 --- a/chronograf/bolt/client.go +++ b/chronograf/bolt/client.go @@ -287,7 +287,3 @@ func (c *Client) backup(ctx context.Context, build chronograf.BuildInfo) error { return c.copy(ctx, lastBuild.Version) } - -func bucket(b []byte, org string) []byte { - return []byte(path.Join(string(b), org)) -} diff --git a/chronograf/bolt/mapping_test.go b/chronograf/bolt/mapping_test.go index efbbaf6c20..0f81999518 100644 --- a/chronograf/bolt/mapping_test.go +++ b/chronograf/bolt/mapping_test.go @@ -111,8 +111,6 @@ func TestMappingStore_All(t *testing.T) { type fields struct { mappings []*chronograf.Mapping } - type args struct { - } type wants struct { mappings []chronograf.Mapping err error @@ -120,7 +118,6 @@ func TestMappingStore_All(t *testing.T) { tests := []struct { name string fields fields - args args wants wants }{ { diff --git a/chronograf/bolt/organizations_test.go b/chronograf/bolt/organizations_test.go index 4ab3ad10e1..4a534da12e 100644 --- a/chronograf/bolt/organizations_test.go +++ b/chronograf/bolt/organizations_test.go @@ -406,6 +406,9 @@ func TestOrganizationsStore_Update(t *testing.T) { if tt.addFirst { tt.args.initial, err = s.Add(tt.args.ctx, tt.args.initial) + if err != nil { + t.Fatal(err) + } } if tt.args.updates.Name != "" { diff --git a/chronograf/bolt/servers_test.go b/chronograf/bolt/servers_test.go index d9b0082fea..e235ab62ee 100644 --- a/chronograf/bolt/servers_test.go +++ b/chronograf/bolt/servers_test.go @@ -90,7 +90,7 @@ func TestServerStore(t *testing.T) { if actual, err := s.Get(ctx, srcs[0].ID); err != nil { t.Fatal(err) - } else if actual.Active == true { + } else if actual.Active { t.Fatal("Able to set two active servers when only one should be permitted") } diff --git a/chronograf/bolt/sources_test.go b/chronograf/bolt/sources_test.go index 17abe6a561..6cb29e2212 100644 --- a/chronograf/bolt/sources_test.go +++ b/chronograf/bolt/sources_test.go @@ -98,7 +98,7 @@ func TestSourceStore(t *testing.T) { if actual, err := s.Get(ctx, srcs[0].ID); err != nil { t.Fatal(err) - } else if actual.Default == true { + } else if actual.Default { t.Fatal("Able to set two default sources when only one should be permitted") } diff --git a/chronograf/bolt/users_test.go b/chronograf/bolt/users_test.go index 1cf1df4543..0df5b1b6ef 100644 --- a/chronograf/bolt/users_test.go +++ b/chronograf/bolt/users_test.go @@ -83,10 +83,8 @@ func TestUsersStore_GetWithID(t *testing.T) { func TestUsersStore_GetWithNameProviderScheme(t *testing.T) { type args struct { - ctx context.Context - name string - provider string - usr *chronograf.User + ctx context.Context + usr *chronograf.User } tests := []struct { name string diff --git a/chronograf/enterprise/enterprise_test.go b/chronograf/enterprise/enterprise_test.go index 7a128bbce0..47b6cb00cd 100644 --- a/chronograf/enterprise/enterprise_test.go +++ b/chronograf/enterprise/enterprise_test.go @@ -34,7 +34,7 @@ func Test_Enterprise_FetchesDataNodes(t *testing.T) { t.Fatal("Unexpected error while creating enterprise client. err:", err) } - if showClustersCalled != true { + if !showClustersCalled { t.Fatal("Expected request to meta node but none was issued") } } @@ -68,7 +68,7 @@ func Test_Enterprise_IssuesQueries(t *testing.T) { t.Fatal("Unexpected error while querying data node: err:", err) } - if called == false { + if !called { t.Fatal("Expected request to data node but none was received") } } diff --git a/chronograf/enterprise/meta_test.go b/chronograf/enterprise/meta_test.go index 0b2d413cfd..1d0f7be146 100644 --- a/chronograf/enterprise/meta_test.go +++ b/chronograf/enterprise/meta_test.go @@ -19,9 +19,7 @@ import ( func TestMetaClient_ShowCluster(t *testing.T) { type fields struct { URL *url.URL - client interface { - Do(URL *url.URL, path, method string, authorizer influx.Authorizer, params map[string]string, body io.Reader) (*http.Response, error) - } + client *MockClient } tests := []struct { name string @@ -112,7 +110,7 @@ func TestMetaClient_ShowCluster(t *testing.T) { if tt.wantErr { continue } - reqs := tt.fields.client.(*MockClient).Requests + reqs := tt.fields.client.Requests if len(reqs) != 1 { t.Errorf("%q. MetaClient.ShowCluster() expected 1 but got %d", tt.name, len(reqs)) continue @@ -130,9 +128,7 @@ func TestMetaClient_ShowCluster(t *testing.T) { func TestMetaClient_Users(t *testing.T) { type fields struct { URL *url.URL - client interface { - Do(URL *url.URL, path, method string, authorizer influx.Authorizer, params map[string]string, body io.Reader) (*http.Response, error) - } + client *MockClient } type args struct { ctx context.Context @@ -267,9 +263,7 @@ func TestMetaClient_Users(t *testing.T) { func TestMetaClient_User(t *testing.T) { type fields struct { URL *url.URL - client interface { - Do(URL *url.URL, path, method string, authorizer influx.Authorizer, params map[string]string, body io.Reader) (*http.Response, error) - } + client *MockClient } type args struct { ctx context.Context @@ -368,9 +362,7 @@ func TestMetaClient_User(t *testing.T) { func TestMetaClient_CreateUser(t *testing.T) { type fields struct { URL *url.URL - client interface { - Do(URL *url.URL, path, method string, authorizer influx.Authorizer, params map[string]string, body io.Reader) (*http.Response, error) - } + client *MockClient } type args struct { ctx context.Context @@ -417,7 +409,7 @@ func TestMetaClient_CreateUser(t *testing.T) { if tt.wantErr { continue } - reqs := tt.fields.client.(*MockClient).Requests + reqs := tt.fields.client.Requests if len(reqs) != 1 { t.Errorf("%q. MetaClient.CreateUser() expected 1 but got %d", tt.name, len(reqs)) continue @@ -439,9 +431,7 @@ func TestMetaClient_CreateUser(t *testing.T) { func TestMetaClient_ChangePassword(t *testing.T) { type fields struct { URL *url.URL - client interface { - Do(URL *url.URL, path, method string, authorizer influx.Authorizer, params map[string]string, body io.Reader) (*http.Response, error) - } + client *MockClient } type args struct { ctx context.Context @@ -489,7 +479,7 @@ func TestMetaClient_ChangePassword(t *testing.T) { if tt.wantErr { continue } - reqs := tt.fields.client.(*MockClient).Requests + reqs := tt.fields.client.Requests if len(reqs) != 1 { t.Errorf("%q. MetaClient.ChangePassword() expected 1 but got %d", tt.name, len(reqs)) continue @@ -511,9 +501,7 @@ func TestMetaClient_ChangePassword(t *testing.T) { func TestMetaClient_DeleteUser(t *testing.T) { type fields struct { URL *url.URL - client interface { - Do(URL *url.URL, path, method string, authorizer influx.Authorizer, params map[string]string, body io.Reader) (*http.Response, error) - } + client *MockClient } type args struct { ctx context.Context @@ -558,7 +546,7 @@ func TestMetaClient_DeleteUser(t *testing.T) { if tt.wantErr { continue } - reqs := tt.fields.client.(*MockClient).Requests + reqs := tt.fields.client.Requests if len(reqs) != 1 { t.Errorf("%q. MetaClient.DeleteUser() expected 1 but got %d", tt.name, len(reqs)) continue @@ -580,9 +568,7 @@ func TestMetaClient_DeleteUser(t *testing.T) { func TestMetaClient_SetUserPerms(t *testing.T) { type fields struct { URL *url.URL - client interface { - Do(URL *url.URL, path, method string, authorizer influx.Authorizer, params map[string]string, body io.Reader) (*http.Response, error) - } + client *MockClient } type args struct { ctx context.Context @@ -655,7 +641,7 @@ func TestMetaClient_SetUserPerms(t *testing.T) { if tt.wantErr { continue } - reqs := tt.fields.client.(*MockClient).Requests + reqs := tt.fields.client.Requests if len(reqs) < 2 { t.Errorf("%q. MetaClient.SetUserPerms() expected 2 but got %d", tt.name, len(reqs)) continue @@ -701,9 +687,7 @@ func TestMetaClient_SetUserPerms(t *testing.T) { func TestMetaClient_Roles(t *testing.T) { type fields struct { URL *url.URL - client interface { - Do(URL *url.URL, path, method string, authorizer influx.Authorizer, params map[string]string, body io.Reader) (*http.Response, error) - } + client *MockClient } type args struct { ctx context.Context @@ -800,9 +784,7 @@ func TestMetaClient_Roles(t *testing.T) { func TestMetaClient_Role(t *testing.T) { type fields struct { URL *url.URL - client interface { - Do(URL *url.URL, path, method string, authorizer influx.Authorizer, params map[string]string, body io.Reader) (*http.Response, error) - } + client *MockClient } type args struct { ctx context.Context @@ -883,9 +865,7 @@ func TestMetaClient_Role(t *testing.T) { func TestMetaClient_UserRoles(t *testing.T) { type fields struct { URL *url.URL - client interface { - Do(URL *url.URL, path, method string, authorizer influx.Authorizer, params map[string]string, body io.Reader) (*http.Response, error) - } + client *MockClient } type args struct { ctx context.Context @@ -987,9 +967,7 @@ func TestMetaClient_UserRoles(t *testing.T) { func TestMetaClient_CreateRole(t *testing.T) { type fields struct { URL *url.URL - client interface { - Do(URL *url.URL, path, method string, authorizer influx.Authorizer, params map[string]string, body io.Reader) (*http.Response, error) - } + client *MockClient } type args struct { ctx context.Context @@ -1031,7 +1009,7 @@ func TestMetaClient_CreateRole(t *testing.T) { if err := m.CreateRole(tt.args.ctx, tt.args.name); (err != nil) != tt.wantErr { t.Errorf("%q. MetaClient.CreateRole() error = %v, wantErr %v", tt.name, err, tt.wantErr) } - reqs := tt.fields.client.(*MockClient).Requests + reqs := tt.fields.client.Requests if len(reqs) != 1 { t.Errorf("%q. MetaClient.CreateRole() expected 1 but got %d", tt.name, len(reqs)) continue @@ -1053,9 +1031,7 @@ func TestMetaClient_CreateRole(t *testing.T) { func TestMetaClient_DeleteRole(t *testing.T) { type fields struct { URL *url.URL - client interface { - Do(URL *url.URL, path, method string, authorizer influx.Authorizer, params map[string]string, body io.Reader) (*http.Response, error) - } + client *MockClient } type args struct { ctx context.Context @@ -1100,7 +1076,7 @@ func TestMetaClient_DeleteRole(t *testing.T) { if tt.wantErr { continue } - reqs := tt.fields.client.(*MockClient).Requests + reqs := tt.fields.client.Requests if len(reqs) != 1 { t.Errorf("%q. MetaClient.DeleteRole() expected 1 but got %d", tt.name, len(reqs)) continue @@ -1122,9 +1098,7 @@ func TestMetaClient_DeleteRole(t *testing.T) { func TestMetaClient_SetRolePerms(t *testing.T) { type fields struct { URL *url.URL - client interface { - Do(URL *url.URL, path, method string, authorizer influx.Authorizer, params map[string]string, body io.Reader) (*http.Response, error) - } + client *MockClient } type args struct { ctx context.Context @@ -1197,7 +1171,7 @@ func TestMetaClient_SetRolePerms(t *testing.T) { if tt.wantErr { continue } - reqs := tt.fields.client.(*MockClient).Requests + reqs := tt.fields.client.Requests if len(reqs) < 2 { t.Errorf("%q. MetaClient.SetRolePerms() expected 2 but got %d", tt.name, len(reqs)) continue @@ -1243,9 +1217,7 @@ func TestMetaClient_SetRolePerms(t *testing.T) { func TestMetaClient_SetRoleUsers(t *testing.T) { type fields struct { URL *url.URL - client interface { - Do(URL *url.URL, path, method string, authorizer influx.Authorizer, params map[string]string, body io.Reader) (*http.Response, error) - } + client *MockClient } type args struct { ctx context.Context @@ -1315,7 +1287,7 @@ func TestMetaClient_SetRoleUsers(t *testing.T) { if tt.wantErr { continue } - reqs := tt.fields.client.(*MockClient).Requests + reqs := tt.fields.client.Requests if len(reqs) != len(tt.wants)+1 { t.Errorf("%q. MetaClient.SetRoleUsers() expected %d but got %d", tt.name, len(tt.wants)+1, len(reqs)) continue diff --git a/chronograf/filestore/organizations.go b/chronograf/filestore/organizations.go index 444185dbf3..6c6f1d43ff 100644 --- a/chronograf/filestore/organizations.go +++ b/chronograf/filestore/organizations.go @@ -13,7 +13,7 @@ import ( // OrgExt is the the file extension searched for in the directory for org files const OrgExt = ".org" -var _ chronograf.OrganizationsStore = &Organizations{} +var _ chronograf.OrganizationsStore = (*Organizations)(nil) // Organizations are JSON orgs stored in the filesystem type Organizations struct { @@ -33,11 +33,6 @@ func NewOrganizations(dir string, logger chronograf.Logger) chronograf.Organizat } } -func orgFile(dir string, org chronograf.Organization) string { - base := fmt.Sprintf("%s%s", org.Name, OrgExt) - return path.Join(dir, base) -} - // All returns all orgs from the directory func (o *Organizations) All(ctx context.Context) ([]chronograf.Organization, error) { files, err := o.ReadDir(o.Dir) diff --git a/chronograf/influx/databases.go b/chronograf/influx/databases.go index 44d34e8717..13ce69d457 100644 --- a/chronograf/influx/databases.go +++ b/chronograf/influx/databases.go @@ -99,7 +99,7 @@ func (c *Client) UpdateRP(ctx context.Context, db string, rp string, upd *chrono if len(upd.ShardDuration) > 0 { buffer.WriteString(" SHARD DURATION " + upd.ShardDuration) } - if upd.Default == true { + if upd.Default { buffer.WriteString(" DEFAULT") } queryRes, err := c.Query(ctx, chronograf.Query{ diff --git a/chronograf/influx/influx.go b/chronograf/influx/influx.go index 0fcc71303d..02c8e69fb4 100644 --- a/chronograf/influx/influx.go +++ b/chronograf/influx/influx.go @@ -349,7 +349,6 @@ func (c *Client) write(ctx context.Context, u *url.URL, db, rp, lp string) error } errChan <- errors.New(response.Err) - return }() select { diff --git a/chronograf/influx/influx_test.go b/chronograf/influx/influx_test.go index 35aeba24ff..8c5bc9ae4a 100644 --- a/chronograf/influx/influx_test.go +++ b/chronograf/influx/influx_test.go @@ -58,7 +58,7 @@ func Test_Influx_MakesRequestsToQueryEndpoint(t *testing.T) { t.Fatal("Expected no error but was", err) } - if called == false { + if !called { t.Error("Expected http request to Influx but there was none") } } @@ -164,6 +164,9 @@ func Test_Influx_AuthorizationBearerCtx(t *testing.T) { URL: ts.URL, InsecureSkipVerify: true, }) + if err != nil { + t.Fatal(err) + } query := chronograf.Query{ Command: "show databases", @@ -226,10 +229,9 @@ func Test_Influx_HTTPS_Failure(t *testing.T) { t.Error("Expected error but was successful") } - if called == true { + if called { t.Error("Expected http request to fail, but, succeeded") } - } func Test_Influx_HTTPS_InsecureSkipVerify(t *testing.T) { @@ -271,7 +273,7 @@ func Test_Influx_HTTPS_InsecureSkipVerify(t *testing.T) { t.Fatal("Expected no error but was", err) } - if called == false { + if !called { t.Error("Expected http request to Influx but there was none") } called = false @@ -284,7 +286,7 @@ func Test_Influx_HTTPS_InsecureSkipVerify(t *testing.T) { t.Fatal("Expected no error but was", err) } - if called == false { + if !called { t.Error("Expected http request to Influx but there was none") } diff --git a/chronograf/influx/query.go b/chronograf/influx/query.go index 072d55f31d..51cf15445f 100644 --- a/chronograf/influx/query.go +++ b/chronograf/influx/query.go @@ -95,13 +95,13 @@ func Convert(influxQL string) (chronograf.QueryConfig, error) { GroupBy: chronograf.GroupBy{ Tags: []string{}, }, - Tags: make(map[string][]string, 0), + Tags: make(map[string][]string), } qc := chronograf.QueryConfig{ GroupBy: chronograf.GroupBy{ Tags: []string{}, }, - Tags: make(map[string][]string, 0), + Tags: make(map[string][]string), } if len(query.Statements) != 1 { @@ -286,8 +286,6 @@ func Convert(influxQL string) (chronograf.QueryConfig, error) { qc.Range = &chronograf.DurationRange{ Lower: "now() - " + shortDur(dur), } - } else { - strings.Replace(influxQL, "now() - 15m", ":dashboardTime:", 1) } } diff --git a/chronograf/oauth2/cookies_test.go b/chronograf/oauth2/cookies_test.go index 18ef96191e..004d0836d4 100644 --- a/chronograf/oauth2/cookies_test.go +++ b/chronograf/oauth2/cookies_test.go @@ -3,7 +3,6 @@ package oauth2 import ( "context" "fmt" - gojwt "github.com/dgrijalva/jwt-go" "log" "net/http" "net/http/httptest" @@ -11,6 +10,8 @@ import ( "strings" "testing" "time" + + gojwt "github.com/dgrijalva/jwt-go" ) type MockTokenizer struct { @@ -78,7 +79,7 @@ func TestCookieAuthorize(t *testing.T) { continue } - cookies := w.HeaderMap["Set-Cookie"] + cookies := w.Header()["Set-Cookie"] if len(cookies) == 0 { t.Fatal("Expected some cookies but got zero") @@ -275,12 +276,12 @@ func TestCookieExtend(t *testing.T) { t.Errorf("cookie.Extend() error = %v, wantErr %v", err, tt.wantErr) return } - if tt.wantErr == false { + if !tt.wantErr { if !reflect.DeepEqual(got, tt.want) { t.Errorf("cookie.Extend() = %v, want %v", got, tt.want) } - cookies := tt.args.w.HeaderMap["Set-Cookie"] + cookies := tt.args.w.Header()["Set-Cookie"] if len(cookies) == 0 { t.Fatal("Expected some cookies but got zero") } diff --git a/chronograf/oauth2/heroku.go b/chronograf/oauth2/heroku.go index 697182231f..a44d75fa12 100644 --- a/chronograf/oauth2/heroku.go +++ b/chronograf/oauth2/heroku.go @@ -63,6 +63,10 @@ func (h *Heroku) PrincipalID(provider *http.Client) (string, error) { } req, err := http.NewRequest("GET", HerokuAccountRoute, nil) + if err != nil { + return "", err + } + // Requests fail to Heroku unless this Accept header is set. req.Header.Set("Accept", "application/vnd.heroku+json; version=3") resp, err := provider.Do(req) diff --git a/chronograf/organizations/dashboards_test.go b/chronograf/organizations/dashboards_test.go index 46ef23f77c..8ff6827082 100644 --- a/chronograf/organizations/dashboards_test.go +++ b/chronograf/organizations/dashboards_test.go @@ -32,7 +32,6 @@ func TestDashboards_All(t *testing.T) { args args fields fields want []chronograf.Dashboard - wantRaw []chronograf.Dashboard wantErr bool }{ { @@ -147,6 +146,9 @@ func TestDashboards_Add(t *testing.T) { continue } got, err := s.Get(tt.args.ctx, d.ID) + if err != nil { + t.Fatal(err) + } if diff := cmp.Diff(got, tt.want, dashboardCmpOptions...); diff != "" { t.Errorf("%q. DashboardsStore.Add():\n-got/+want\ndiff %s", tt.name, diff) } @@ -166,7 +168,6 @@ func TestDashboards_Delete(t *testing.T) { name string fields fields args args - want []chronograf.Dashboard addFirst bool wantErr bool }{ @@ -219,12 +220,11 @@ func TestDashboards_Get(t *testing.T) { dashboard chronograf.Dashboard } tests := []struct { - name string - fields fields - args args - want chronograf.Dashboard - addFirst bool - wantErr bool + name string + fields fields + args args + want chronograf.Dashboard + wantErr bool }{ { name: "Get Dashboard", @@ -332,6 +332,9 @@ func TestDashboards_Update(t *testing.T) { continue } got, err := s.Get(tt.args.ctx, tt.args.dashboard.ID) + if err != nil { + t.Fatal(err) + } if diff := cmp.Diff(got, tt.want, dashboardCmpOptions...); diff != "" { t.Errorf("%q. DashboardsStore.Update():\n-got/+want\ndiff %s", tt.name, diff) } diff --git a/chronograf/organizations/organizations_test.go b/chronograf/organizations/organizations_test.go index 9df04c955c..e95398f1ce 100644 --- a/chronograf/organizations/organizations_test.go +++ b/chronograf/organizations/organizations_test.go @@ -32,7 +32,6 @@ func TestOrganizations_All(t *testing.T) { args args fields fields want []chronograf.Organization - wantRaw []chronograf.Organization wantErr bool }{ { @@ -161,6 +160,9 @@ func TestOrganizations_Add(t *testing.T) { continue } got, err := s.Get(tt.args.ctx, chronograf.OrganizationQuery{ID: &d.ID}) + if err != nil { + t.Fatal(err) + } if diff := cmp.Diff(got, tt.want, organizationCmpOptions...); diff != "" { t.Errorf("%q. OrganizationsStore.Add():\n-got/+want\ndiff %s", tt.name, diff) } @@ -180,7 +182,6 @@ func TestOrganizations_Delete(t *testing.T) { name string fields fields args args - want []chronograf.Organization addFirst bool wantErr bool }{ @@ -231,12 +232,11 @@ func TestOrganizations_Get(t *testing.T) { organization *chronograf.Organization } tests := []struct { - name string - fields fields - args args - want *chronograf.Organization - addFirst bool - wantErr bool + name string + fields fields + args args + want *chronograf.Organization + wantErr bool }{ { name: "Get Organization", @@ -338,6 +338,9 @@ func TestOrganizations_Update(t *testing.T) { continue } got, err := s.Get(tt.args.ctx, chronograf.OrganizationQuery{ID: &tt.args.organization.ID}) + if err != nil { + t.Fatal(err) + } if diff := cmp.Diff(got, tt.want, organizationCmpOptions...); diff != "" { t.Errorf("%q. OrganizationsStore.Update():\n-got/+want\ndiff %s", tt.name, diff) } diff --git a/chronograf/organizations/servers_test.go b/chronograf/organizations/servers_test.go index b67153961d..64eafea694 100644 --- a/chronograf/organizations/servers_test.go +++ b/chronograf/organizations/servers_test.go @@ -33,7 +33,6 @@ func TestServers_All(t *testing.T) { args args fields fields want []chronograf.Server - wantRaw []chronograf.Server wantErr bool }{ { @@ -148,6 +147,9 @@ func TestServers_Add(t *testing.T) { continue } got, err := s.Get(tt.args.ctx, d.ID) + if err != nil { + t.Fatal(err) + } if diff := cmp.Diff(got, tt.want, serverCmpOptions...); diff != "" { t.Errorf("%q. ServersStore.Add():\n-got/+want\ndiff %s", tt.name, diff) } @@ -167,7 +169,6 @@ func TestServers_Delete(t *testing.T) { name string fields fields args args - want []chronograf.Server addFirst bool wantErr bool }{ @@ -220,12 +221,11 @@ func TestServers_Get(t *testing.T) { server chronograf.Server } tests := []struct { - name string - fields fields - args args - want chronograf.Server - addFirst bool - wantErr bool + name string + fields fields + args args + want chronograf.Server + wantErr bool }{ { name: "Get Server", @@ -333,6 +333,9 @@ func TestServers_Update(t *testing.T) { continue } got, err := s.Get(tt.args.ctx, tt.args.server.ID) + if err != nil { + t.Fatal(err) + } if diff := cmp.Diff(got, tt.want, serverCmpOptions...); diff != "" { t.Errorf("%q. ServersStore.Update():\n-got/+want\ndiff %s", tt.name, diff) } diff --git a/chronograf/organizations/sources_test.go b/chronograf/organizations/sources_test.go index b35401466a..e97030f4f1 100644 --- a/chronograf/organizations/sources_test.go +++ b/chronograf/organizations/sources_test.go @@ -33,7 +33,6 @@ func TestSources_All(t *testing.T) { args args fields fields want []chronograf.Source - wantRaw []chronograf.Source wantErr bool }{ { @@ -148,6 +147,9 @@ func TestSources_Add(t *testing.T) { continue } got, err := s.Get(tt.args.ctx, d.ID) + if err != nil { + t.Fatal(err) + } if diff := cmp.Diff(got, tt.want, sourceCmpOptions...); diff != "" { t.Errorf("%q. SourcesStore.Add():\n-got/+want\ndiff %s", tt.name, diff) } @@ -167,7 +169,6 @@ func TestSources_Delete(t *testing.T) { name string fields fields args args - want []chronograf.Source addFirst bool wantErr bool }{ @@ -220,12 +221,11 @@ func TestSources_Get(t *testing.T) { source chronograf.Source } tests := []struct { - name string - fields fields - args args - want chronograf.Source - addFirst bool - wantErr bool + name string + fields fields + args args + want chronograf.Source + wantErr bool }{ { name: "Get Source", @@ -333,6 +333,9 @@ func TestSources_Update(t *testing.T) { continue } got, err := s.Get(tt.args.ctx, tt.args.source.ID) + if err != nil { + t.Fatal(err) + } if diff := cmp.Diff(got, tt.want, sourceCmpOptions...); diff != "" { t.Errorf("%q. SourcesStore.Update():\n-got/+want\ndiff %s", tt.name, diff) } diff --git a/chronograf/organizations/users.go b/chronograf/organizations/users.go index bdada80b06..b2706c4dc7 100644 --- a/chronograf/organizations/users.go +++ b/chronograf/organizations/users.go @@ -152,7 +152,7 @@ func (s *UsersStore) Add(ctx context.Context, u *chronograf.User) (*chronograf.U // If the user being added already existed in a previous organization, and was already a SuperAdmin, // then this ensures that they retain their SuperAdmin status. And if they weren't a SuperAdmin, and // the user being added has been granted SuperAdmin status, they will be promoted - if u.SuperAdmin == true { + if u.SuperAdmin { usr.SuperAdmin = true } diff --git a/chronograf/organizations/users_test.go b/chronograf/organizations/users_test.go index 3eb3f0b45d..25359fe761 100644 --- a/chronograf/organizations/users_test.go +++ b/chronograf/organizations/users_test.go @@ -24,7 +24,6 @@ func TestUsersStore_Get(t *testing.T) { } type args struct { ctx context.Context - usr *chronograf.User userID uint64 orgID string } @@ -149,10 +148,9 @@ func TestUsersStore_Add(t *testing.T) { UsersStore chronograf.UsersStore } type args struct { - ctx context.Context - u *chronograf.User - orgID string - uInitial *chronograf.User + ctx context.Context + u *chronograf.User + orgID string } tests := []struct { name string @@ -576,7 +574,6 @@ func TestUsersStore_Delete(t *testing.T) { fields fields args args wantErr bool - wantRaw *chronograf.User }{ { name: "No such user", @@ -672,7 +669,6 @@ func TestUsersStore_Update(t *testing.T) { fields fields args args want *chronograf.User - wantRaw *chronograf.User wantErr bool }{ { diff --git a/chronograf/server/auth.go b/chronograf/server/auth.go index a254c82946..3a4996824e 100644 --- a/chronograf/server/auth.go +++ b/chronograf/server/auth.go @@ -52,7 +52,6 @@ func AuthorizedToken(auth oauth2.Authenticator, logger chronograf.Logger, next h // Send the principal to the next handler ctx = context.WithValue(ctx, oauth2.PrincipalKey, principal) next.ServeHTTP(w, r.WithContext(ctx)) - return }) } @@ -210,7 +209,6 @@ func AuthorizedUser( } Error(w, http.StatusForbidden, "User is not authorized", logger) - return }) } diff --git a/chronograf/server/cells_test.go b/chronograf/server/cells_test.go index 32a3eaee70..42917b417b 100644 --- a/chronograf/server/cells_test.go +++ b/chronograf/server/cells_test.go @@ -212,7 +212,6 @@ func Test_Service_DashboardCells(t *testing.T) { t.Parallel() // setup context with params - ctx := context.Background() params := httprouter.Params{} for k, v := range test.ctxParams { params = append(params, httprouter.Param{ @@ -220,8 +219,8 @@ func Test_Service_DashboardCells(t *testing.T) { Value: v, }) } - ctx = context.WithValue( - context.TODO(), + ctx := context.WithValue( + context.Background(), httprouter.ParamsKey, params, ) diff --git a/chronograf/server/dashboards_test.go b/chronograf/server/dashboards_test.go index 97cb843a36..d2d489d3f1 100644 --- a/chronograf/server/dashboards_test.go +++ b/chronograf/server/dashboards_test.go @@ -277,7 +277,7 @@ func Test_newDashboardResponse(t *testing.T) { GroupBy: chronograf.GroupBy{ Tags: []string{}, }, - Tags: make(map[string][]string, 0), + Tags: make(map[string][]string), AreTagsAccepted: false, Shifts: []chronograf.TimeShift{ { @@ -339,7 +339,7 @@ func Test_newDashboardResponse(t *testing.T) { GroupBy: chronograf.GroupBy{ Tags: []string{}, }, - Tags: make(map[string][]string, 0), + Tags: make(map[string][]string), AreTagsAccepted: false, Range: &chronograf.DurationRange{ Lower: "now() - 15m", diff --git a/chronograf/server/databases.go b/chronograf/server/databases.go index 73b726b022..49f1a090aa 100644 --- a/chronograf/server/databases.go +++ b/chronograf/server/databases.go @@ -71,10 +71,6 @@ func (r *rpResponse) WithLinks(srcID int, db string) { } } -type rpsResponse struct { - RetentionPolicies []rpResponse `json:"retentionPolicies"` -} - type measurementLinks struct { Self string `json:"self"` First string `json:"first"` diff --git a/chronograf/server/mapping_test.go b/chronograf/server/mapping_test.go index a564705397..0a0cdf2c68 100644 --- a/chronograf/server/mapping_test.go +++ b/chronograf/server/mapping_test.go @@ -19,8 +19,6 @@ func TestMappings_All(t *testing.T) { type fields struct { MappingsStore chronograf.MappingsStore } - type args struct { - } type wants struct { statusCode int contentType string @@ -30,7 +28,6 @@ func TestMappings_All(t *testing.T) { tests := []struct { name string fields fields - args args wants wants }{ { diff --git a/chronograf/server/me.go b/chronograf/server/me.go index b908016199..235550420b 100644 --- a/chronograf/server/me.go +++ b/chronograf/server/me.go @@ -153,7 +153,7 @@ func (s *Service) UpdateMe(auth oauth2.Authenticator) func(http.ResponseWriter, return } - if u.SuperAdmin == false { + if !u.SuperAdmin { // Since a user is not a part of this organization and not a super admin, // we should tell them that they are Forbidden (403) from accessing this resource Error(w, http.StatusForbidden, chronograf.ErrUserNotFound.Error(), s.Logger) @@ -399,13 +399,3 @@ func (s *Service) usersOrganizations(ctx context.Context, u *chronograf.User) ([ return orgs, nil } - -func hasRoleInDefaultOrganization(u *chronograf.User, orgID string) bool { - for _, role := range u.Roles { - if role.Organization == orgID { - return true - } - } - - return false -} diff --git a/chronograf/server/me_test.go b/chronograf/server/me_test.go index 7f99045f47..70db5bd746 100644 --- a/chronograf/server/me_test.go +++ b/chronograf/server/me_test.go @@ -17,8 +17,6 @@ import ( "github.com/influxdata/platform/chronograf/roles" ) -type MockUsers struct{} - func TestService_Me(t *testing.T) { type fields struct { UsersStore chronograf.UsersStore diff --git a/chronograf/server/mux.go b/chronograf/server/mux.go index d41d5e3cca..aa9bd8a46b 100644 --- a/chronograf/server/mux.go +++ b/chronograf/server/mux.go @@ -448,16 +448,6 @@ func paramID(key string, r *http.Request) (int, error) { return id, nil } -func paramInt64(key string, r *http.Request) (int64, error) { - ctx := r.Context() - param := jhttprouter.ParamsFromContext(ctx).ByName(key) - v, err := strconv.ParseInt(param, 10, 64) - if err != nil { - return -1, fmt.Errorf("Error converting parameter %s", param) - } - return v, nil -} - func paramStr(key string, r *http.Request) (string, error) { ctx := r.Context() param := jhttprouter.ParamsFromContext(ctx).ByName(key) diff --git a/chronograf/server/org_config_test.go b/chronograf/server/org_config_test.go index 9c3b1e1495..3b5d117940 100644 --- a/chronograf/server/org_config_test.go +++ b/chronograf/server/org_config_test.go @@ -1069,7 +1069,7 @@ func Test_validLogViewerConfig(t *testing.T) { t.Run(tt.name, func(t *testing.T) { got := validLogViewerConfig(tt.args.LogViewer) - if (tt.wantErr == true && got == nil) || (tt.wantErr == false && got != nil) { + if (tt.wantErr && got == nil) || (!tt.wantErr && got != nil) { t.Errorf("%q. validLogViewerConfig().\ngot: %v\nwantErr: %v", tt.name, got, tt.wantErr) } }) diff --git a/chronograf/server/organizations_test.go b/chronograf/server/organizations_test.go index c655f9cf1e..f760076ccb 100644 --- a/chronograf/server/organizations_test.go +++ b/chronograf/server/organizations_test.go @@ -220,10 +220,9 @@ func TestService_UpdateOrganization(t *testing.T) { Logger chronograf.Logger } type args struct { - w *httptest.ResponseRecorder - r *http.Request - org *organizationRequest - setPtr bool + w *httptest.ResponseRecorder + r *http.Request + org *organizationRequest } tests := []struct { name string @@ -520,7 +519,6 @@ func TestService_NewOrganization(t *testing.T) { name string fields fields args args - id string wantStatus int wantContentType string wantBody string diff --git a/chronograf/server/queryconfig.go b/chronograf/server/queryconfig.go index d2e20d207c..15b33c70d6 100644 --- a/chronograf/server/queryconfig.go +++ b/chronograf/server/queryconfig.go @@ -21,7 +21,7 @@ func ToQueryConfig(query string) chronograf.QueryConfig { GroupBy: chronograf.GroupBy{ Tags: []string{}, }, - Tags: make(map[string][]string, 0), + Tags: make(map[string][]string), } } diff --git a/chronograf/server/redoc.go b/chronograf/server/redoc.go index 77f4e83c0a..4cc39bf27d 100644 --- a/chronograf/server/redoc.go +++ b/chronograf/server/redoc.go @@ -35,6 +35,5 @@ func Redoc(swagger string) http.HandlerFunc { rw.WriteHeader(http.StatusOK) _, _ = rw.Write([]byte(fmt.Sprintf(index, swagger))) - return }) } diff --git a/chronograf/server/routes.go b/chronograf/server/routes.go index 43036b8e9f..659b3e2292 100644 --- a/chronograf/server/routes.go +++ b/chronograf/server/routes.go @@ -116,9 +116,7 @@ func (a *AllRoutes) ServeHTTP(w http.ResponseWriter, r *http.Request) { routes.Logout = &a.LogoutLink } - for i, route := range a.AuthRoutes { - routes.Auth[i] = route - } + copy(routes.Auth, a.AuthRoutes) encodeJSON(w, http.StatusOK, routes, a.Logger) } diff --git a/chronograf/server/users.go b/chronograf/server/users.go index ea2c5ece9c..c286610ecf 100644 --- a/chronograf/server/users.go +++ b/chronograf/server/users.go @@ -301,7 +301,7 @@ func (s *Service) UpdateUser(w http.ResponseWriter, r *http.Request) { } // If the user being updated is the user making the request and they are // changing their SuperAdmin status, return an unauthorized error - if ctxUser.ID == u.ID && u.SuperAdmin == true && req.SuperAdmin == false { + if ctxUser.ID == u.ID && u.SuperAdmin && !req.SuperAdmin { Error(w, http.StatusUnauthorized, "user cannot modify their own SuperAdmin status", s.Logger) return } diff --git a/cmd/influx/setup.go b/cmd/influx/setup.go index ebc63c315a..6a5bdc1432 100644 --- a/cmd/influx/setup.go +++ b/cmd/influx/setup.go @@ -93,16 +93,11 @@ func getOnboardingRequest() (req *platform.OnboardingRequest) { // vt100EscapeCodes var ( - keyEscape = byte(27) - colorBlack = []byte{keyEscape, '[', '3', '0', 'm'} - colorRed = []byte{keyEscape, '[', '3', '1', 'm'} - colorGreen = []byte{keyEscape, '[', '3', '2', 'm'} - colorYellow = []byte{keyEscape, '[', '3', '3', 'm'} - colorBlue = []byte{keyEscape, '[', '3', '4', 'm'} - colorMagenta = []byte{keyEscape, '[', '3', '5', 'm'} - colorCyan = []byte{keyEscape, '[', '3', '6', 'm'} - colorWhite = []byte{keyEscape, '[', '3', '7', 'm'} - keyReset = []byte{keyEscape, '[', '0', 'm'} + keyEscape = byte(27) + colorRed = []byte{keyEscape, '[', '3', '1', 'm'} + colorYellow = []byte{keyEscape, '[', '3', '3', 'm'} + colorCyan = []byte{keyEscape, '[', '3', '6', 'm'} + keyReset = []byte{keyEscape, '[', '0', 'm'} ) func promptWithColor(s string, color []byte) string { @@ -180,7 +175,7 @@ enterPasswd: case input.ErrInterrupted: os.Exit(1) case nil: - break + // Nothing. default: fmt.Println(promptWithColor("Passwords do not match!", colorRed)) goto enterPasswd diff --git a/cmd/influxd/main.go b/cmd/influxd/main.go index 42b7080020..522cdb6553 100644 --- a/cmd/influxd/main.go +++ b/cmd/influxd/main.go @@ -95,21 +95,13 @@ func main() { } } -const ( - // IngressSubject is the subject that subscribers and publishers use for writing and consuming line protocol - IngressSubject = "ingress" - // IngressGroup is the Nats Streaming Subscriber group, allowing multiple subscribers to distribute work - IngressGroup = "ingress" -) - var ( - logLevel string - httpBindAddress string - authorizationPath string - boltPath string - natsPath string - developerMode bool - enginePath string + logLevel string + httpBindAddress string + boltPath string + natsPath string + developerMode bool + enginePath string ) func influxDir() (string, error) { diff --git a/context/token.go b/context/token.go index cf3984240c..fbb2e140f2 100644 --- a/context/token.go +++ b/context/token.go @@ -10,9 +10,7 @@ import ( type contextKey string const ( - authorizationCtxKey = contextKey("influx/authorization/v1") - authorizerCtxKey = contextKey("influx/authorizer/v1") - tokenCtxKey = contextKey("influx/token/v1") + authorizerCtxKey = contextKey("influx/authorizer/v1") ) // SetAuthorizer sets an authorizer on context. diff --git a/errors_test.go b/errors_test.go index b5daa27c06..10aee503eb 100644 --- a/errors_test.go +++ b/errors_test.go @@ -132,7 +132,6 @@ func TestJSON(t *testing.T) { cases := []struct { name string err *platform.Error - json string }{ { name: "simple error", diff --git a/gather/prometheus.go b/gather/prometheus.go index fe542474b9..604a2cace2 100644 --- a/gather/prometheus.go +++ b/gather/prometheus.go @@ -67,7 +67,7 @@ func (p *prometheusScraper) parse(r io.Reader, header http.Header) ([]Metrics, e // reading tags tags := makeLabels(m) // reading fields - fields := make(map[string]interface{}) + var fields map[string]interface{} switch family.GetType() { case dto.MetricType_SUMMARY: // summary metric diff --git a/gather/scheduler_test.go b/gather/scheduler_test.go index 96f90d13df..98d059f417 100644 --- a/gather/scheduler_test.go +++ b/gather/scheduler_test.go @@ -51,7 +51,7 @@ func TestScheduler(t *testing.T) { go func() { err = scheduler.run(ctx) if err != nil { - t.Fatal(err) + t.Error(err) } }() diff --git a/go.mod b/go.mod index 47d061da22..517051f239 100644 --- a/go.mod +++ b/go.mod @@ -86,7 +86,6 @@ require ( golang.org/x/oauth2 v0.0.0-20181017192945-9dcd33a902f4 golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f golang.org/x/sys v0.0.0-20181023152157-44b849a8bc13 - golang.org/x/text v0.3.0 golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2 golang.org/x/tools v0.0.0-20181023010539-40a48ad93fbe // indirect google.golang.org/api v0.0.0-20181021000519-a2651947f503 @@ -94,6 +93,7 @@ require ( google.golang.org/grpc v1.15.0 gopkg.in/robfig/cron.v2 v2.0.0-20150107220207-be2e0b0deed5 gopkg.in/vmihailenco/msgpack.v2 v2.9.1 // indirect + honnef.co/go/tools v0.0.0-20180728063816-88497007e858 labix.org/v2/mgo v0.0.0-20140701140051-000000000287 // indirect launchpad.net/gocheck v0.0.0-20140225173054-000000000087 // indirect ) diff --git a/go.sum b/go.sum index 16e515a962..d56710751e 100644 --- a/go.sum +++ b/go.sum @@ -149,6 +149,7 @@ github.com/jwilder/encoding v0.0.0-20170811194829-b4e1701a28ef h1:2jNeR4YUziVtsw github.com/jwilder/encoding v0.0.0-20170811194829-b4e1701a28ef/go.mod h1:Ct9fl0F6iIOGgxJ5npU/IUOhOhqlVrGjyIZc8/MagT0= github.com/kevinburke/go-bindata v3.11.0+incompatible h1:GiPs9jxaG2xY1B5Dt/d/yHUOMlTk14uS35VcmHrdo4I= github.com/kevinburke/go-bindata v3.11.0+incompatible/go.mod h1:/pEEZ72flUW2p0yi30bslSp9YqD9pysLxunQDdb2CPM= +github.com/kisielk/gotool v1.0.0 h1:AV2c/EiW3KqPNT9ZKl07ehoAGi4C5/01Cfbblndcapg= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/konsorten/go-windows-terminal-sequences v0.0.0-20180402223658-b729f2633dfe h1:CHRGQ8V7OlCYtwaKPJi3iA7J+YdNKdo8j7nG5IgDhjs= github.com/konsorten/go-windows-terminal-sequences v0.0.0-20180402223658-b729f2633dfe/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -322,6 +323,7 @@ gopkg.in/vmihailenco/msgpack.v2 v2.9.1 h1:kb0VV7NuIojvRfzwslQeP3yArBqJHW9tOl4t38 gopkg.in/vmihailenco/msgpack.v2 v2.9.1/go.mod h1:/3Dn1Npt9+MYyLpYYXjInO/5jvMLamn+AEGwNEOatn8= gopkg.in/yaml.v2 v2.2.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +honnef.co/go/tools v0.0.0-20180728063816-88497007e858 h1:wN+eVZ7U+gqdqkec6C6VXR1OFf9a5Ul9ETzeYsYv20g= honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= labix.org/v2/mgo v0.0.0-20140701140051-000000000287 h1:L0cnkNl4TfAXzvdrqsYEmxOHOCv2p5I3taaReO8BWFs= labix.org/v2/mgo v0.0.0-20140701140051-000000000287/go.mod h1:Lg7AYkt1uXJoR9oeSZ3W/8IXLdvOfIITgZnommstyz4= diff --git a/http/authentication_middleware.go b/http/authentication_middleware.go index ca05b9f0ca..606cfb6e2d 100644 --- a/http/authentication_middleware.go +++ b/http/authentication_middleware.go @@ -95,7 +95,6 @@ func (h *AuthenticationHandler) ServeHTTP(w http.ResponseWriter, r *http.Request } ForbiddenError(ctx, fmt.Errorf("unauthorized"), w) - return } func (h *AuthenticationHandler) extractAuthorization(ctx context.Context, r *http.Request) (context.Context, error) { diff --git a/http/dashboard_test.go b/http/dashboard_test.go index 5c27772752..dcc2203861 100644 --- a/http/dashboard_test.go +++ b/http/dashboard_test.go @@ -557,7 +557,6 @@ func TestService_handlePatchDashboard(t *testing.T) { type args struct { id string name string - cells []*platform.Cell } type wants struct { statusCode int diff --git a/http/macro_test.go b/http/macro_test.go index 1e87a61379..06d35704b2 100644 --- a/http/macro_test.go +++ b/http/macro_test.go @@ -427,8 +427,7 @@ func TestMacroService_handleDeleteMacro(t *testing.T) { id string } type wants struct { - statusCode int - contentType string + statusCode int } tests := []struct { diff --git a/http/session_test.go b/http/session_test.go index 6744bd8f6d..a9c612a7a0 100644 --- a/http/session_test.go +++ b/http/session_test.go @@ -23,7 +23,6 @@ func TestBasicAuthHandler_handleSignin(t *testing.T) { } type wants struct { cookie string - err error code int } diff --git a/http/telegraf.go b/http/telegraf.go index 176cda106e..c92f27c325 100644 --- a/http/telegraf.go +++ b/http/telegraf.go @@ -27,7 +27,6 @@ type TelegrafHandler struct { const ( telegrafsPath = "/api/v2/telegrafs" telegrafsIDPath = "/api/v2/telegrafs/:id" - telegrafsIDMembersPath = "/api/v2/telegrafs/:id/members" telegrafsIDMembersIDPath = "/api/v2/telegrafs/:id/members/:userID" telegrafsIDOwnersPath = "/api/v2/telegrafs/:id/owners" telegrafsIDOwnersIDPath = "/api/v2/telegrafs/:id/owners/:userID" @@ -40,7 +39,8 @@ func NewTelegrafHandler( telegrafSvc platform.TelegrafConfigStore, ) *TelegrafHandler { h := &TelegrafHandler{ - Router: httprouter.New(), + Router: httprouter.New(), + UserResourceMappingService: mappingService, TelegrafService: telegrafSvc, Logger: logger, @@ -62,11 +62,6 @@ func NewTelegrafHandler( return h } -type telegrafLinks struct { - Self string `json:"self"` - Cells string `json:"cells"` -} - type link struct { Self string `json:"self"` } diff --git a/http/tokens_test.go b/http/tokens_test.go index 8b33ac6ece..029f905721 100644 --- a/http/tokens_test.go +++ b/http/tokens_test.go @@ -6,14 +6,6 @@ import ( "testing" ) -func tokenRequest(token string) *http.Request { - req := httptest.NewRequest("GET", "/", nil) - if token != "" { - SetToken(token, req) - } - return req -} - func TestGetToken(t *testing.T) { type args struct { header string diff --git a/inmem/scraper.go b/inmem/scraper.go index 52a2ad9a07..392b94228b 100644 --- a/inmem/scraper.go +++ b/inmem/scraper.go @@ -27,21 +27,6 @@ func (s *Service) loadScraperTarget(id platform.ID) (*platform.ScraperTarget, er return &b, nil } -func (s *Service) forEachScraperTarget(ctx context.Context, fn func(b platform.ScraperTarget) bool) error { - var err error - s.scraperTargetKV.Range(func(k, v interface{}) bool { - o, ok := v.(platform.ScraperTarget) - if !ok { - err = fmt.Errorf("type %T is not a scraper target", v) - return false - } - - return fn(o) - }) - - return err -} - // ListTargets will list all scrape targets. func (s *Service) ListTargets(ctx context.Context) (list []platform.ScraperTarget, err error) { list = make([]platform.ScraperTarget, 0) @@ -77,13 +62,12 @@ func (s *Service) UpdateTarget(ctx context.Context, update *platform.ScraperTarg if !update.ID.Valid() { return nil, errors.New("update scraper: id is invalid") } - target, err = s.loadScraperTarget(update.ID) + _, err = s.loadScraperTarget(update.ID) if err != nil { return nil, err } - target = update err = s.PutTarget(ctx, update) - return target, err + return update, err } // GetTargetByID retrieves a scraper target by id. diff --git a/inmem/telegraf.go b/inmem/telegraf.go index d200be8808..2c292c5885 100644 --- a/inmem/telegraf.go +++ b/inmem/telegraf.go @@ -98,7 +98,7 @@ func (s *Service) FindTelegrafConfigs(ctx context.Context, filter platform.UserR pErr.Op = op err = pErr } - return tcs, len(tcs), err + return tcs, n, err } func (s *Service) putTelegrafConfig(ctx context.Context, tc *platform.TelegrafConfig) *platform.Error { diff --git a/kit/signals/context_test.go b/kit/signals/context_test.go index f4a2857fcd..222e3989f8 100644 --- a/kit/signals/context_test.go +++ b/kit/signals/context_test.go @@ -17,10 +17,8 @@ func ExampleWithSignals() { syscall.Kill(syscall.Getpid(), syscall.SIGUSR1) }() - select { - case <-ctx.Done(): - fmt.Println("finished") - } + <-ctx.Done() + fmt.Println("finished") // Output: // finished } @@ -36,10 +34,8 @@ func Example_withUnregisteredSignals() { syscall.Kill(syscall.Getpid(), syscall.SIGUSR2) }() - select { - case <-ctx.Done(): - fmt.Println("finished") - } + <-ctx.Done() + fmt.Println("finished") // Output: // finished } diff --git a/mock/dashboard_service.go b/mock/dashboard_service.go index ebf3140983..83c564bc3d 100644 --- a/mock/dashboard_service.go +++ b/mock/dashboard_service.go @@ -59,5 +59,5 @@ func (s *DashboardService) UpdateDashboardCell(ctx context.Context, dashboardID } func (s *DashboardService) CopyDashboardCell(ctx context.Context, dashboardID platform.ID, cellID platform.ID) (*platform.Cell, error) { - return s.CopyDashboardCell(ctx, dashboardID, cellID) + return s.CopyDashboardCellF(ctx, dashboardID, cellID) } diff --git a/mock/nats.go b/mock/nats.go index 518980bbbd..ec611db24b 100644 --- a/mock/nats.go +++ b/mock/nats.go @@ -14,11 +14,6 @@ type NatsServer struct { queue map[string]chan io.Reader } -type natsJob struct { - subject string - r io.Reader -} - // create an empty channel for a subject func (s *NatsServer) initSubject(subject string) (chan io.Reader, error) { s.Lock() @@ -71,14 +66,12 @@ func (s *NatsSubscriber) Subscribe(subject, group string, handler nats.Handler) } go func(s *NatsSubscriber, subject string, handler nats.Handler) { - for { - select { - case r := <-ch: - handler.Process(&natsSubscription{subject: subject}, - &natsMessage{ - r: r, - }) - } + for r := range ch { + handler.Process(&natsSubscription{subject: subject}, + &natsMessage{ + r: r, + }, + ) } }(s, subject, handler) return nil diff --git a/query/functions/compspecs/compspecs.go b/query/functions/compspecs/compspecs.go index a1b78c8f2d..20efec35d9 100644 --- a/query/functions/compspecs/compspecs.go +++ b/query/functions/compspecs/compspecs.go @@ -6,10 +6,9 @@ import ( "io/ioutil" "os" "path/filepath" - "regexp" - "strings" "time" + "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" "github.com/influxdata/flux" "github.com/influxdata/flux/semantic/semantictest" @@ -17,17 +16,8 @@ import ( "github.com/influxdata/platform/mock" "github.com/influxdata/platform/query/influxql" platformtesting "github.com/influxdata/platform/testing" - - "github.com/google/go-cmp/cmp" - "golang.org/x/text/unicode/norm" ) -func normalizeString(s string) []byte { - result := norm.NFC.String(strings.TrimSpace(s)) - re := regexp.MustCompile(`\r?\n`) - return []byte(re.ReplaceAllString(result, "\r\n")) -} - func printUsage() { fmt.Println("usage: prepcsvtests /path/to/testfiles [testname]") } diff --git a/query/influxql/service.go b/query/influxql/service.go index 2731992b7c..0431cd0286 100644 --- a/query/influxql/service.go +++ b/query/influxql/service.go @@ -60,7 +60,7 @@ func (s *Service) Query(ctx context.Context, req *query.Request) (flux.ResultIte if err != nil { return nil, err } - hreq.WithContext(ctx) + hreq = hreq.WithContext(ctx) hreq.SetBasicAuth(endpoint.Username, endpoint.Password) // Perform the request and look at the status code. diff --git a/query/influxql/transpiler.go b/query/influxql/transpiler.go index 1b3b2f992e..48fbc2add7 100644 --- a/query/influxql/transpiler.go +++ b/query/influxql/transpiler.go @@ -52,7 +52,6 @@ func (t *Transpiler) Transpile(ctx context.Context, txt string) (*flux.Spec, err } type transpilerState struct { - id int stmt *influxql.SelectStatement config Config spec *flux.Spec diff --git a/query/promql/types.go b/query/promql/types.go index 89aa1f0c27..c9cc208eed 100644 --- a/query/promql/types.go +++ b/query/promql/types.go @@ -209,8 +209,7 @@ var operatorLookup = map[MatchKind]ast.OperatorKind{ } func NewWhereOperation(metricName string, labels []*LabelMatcher) (*flux.Operation, error) { - var node semantic.Expression - node = &semantic.BinaryExpression{ + var node semantic.Expression = &semantic.BinaryExpression{ Operator: ast.EqualOperator, Left: &semantic.MemberExpression{ Object: &semantic.IdentifierExpression{ diff --git a/query/querytest/compile.go b/query/querytest/compile.go index 67ad60ee97..e5199860c1 100644 --- a/query/querytest/compile.go +++ b/query/querytest/compile.go @@ -55,6 +55,9 @@ func BucketAwareQueryTestHelper(t *testing.T, tc BucketAwareQueryTestCase) { var gotReadBuckets, gotWriteBuckets []platform.BucketFilter if tc.WantReadBuckets != nil || tc.WantWriteBuckets != nil { gotReadBuckets, gotWriteBuckets, err = query.BucketsAccessed(got) + if err != nil { + t.Fatal(err) + } } if tc.WantReadBuckets != nil { diff --git a/scraper.go b/scraper.go index afca9f2d5a..78455f267f 100644 --- a/scraper.go +++ b/scraper.go @@ -38,10 +38,6 @@ const ( PrometheusScraperType = "prometheus" ) -var validScraperTypes = map[ScraperType]bool{ - PrometheusScraperType: false, -} - // ValidScraperType returns true is the type string is valid func ValidScraperType(s string) bool { switch s { diff --git a/storage/reads/predicate.go b/storage/reads/predicate.go index a7ea65d85e..0a58de3adf 100644 --- a/storage/reads/predicate.go +++ b/storage/reads/predicate.go @@ -320,8 +320,6 @@ func toComparisonOperator(o ast.OperatorKind) (datatypes.Node_Comparison, error) } } -var measurementRemap = map[string]string{"_measurement": "_name"} - // NodeToExpr transforms a predicate node to an influxql.Expr. func NodeToExpr(node *datatypes.Node, remap map[string]string) (influxql.Expr, error) { v := &nodeToExprVisitor{remap: remap} diff --git a/storage/readservice/cursor.go b/storage/readservice/cursor.go index f3f669c047..583a553589 100644 --- a/storage/readservice/cursor.go +++ b/storage/readservice/cursor.go @@ -17,7 +17,6 @@ import ( type indexSeriesCursor struct { sqry storage.SeriesCursor err error - tags models.Tags cond influxql.Expr row reads.SeriesRow eof bool diff --git a/storage/readservice/service.go b/storage/readservice/service.go index 0db5b6637d..14f84c988d 100644 --- a/storage/readservice/service.go +++ b/storage/readservice/service.go @@ -2,6 +2,7 @@ package readservice import ( "context" + "github.com/influxdata/platform/query/functions/outputs" "github.com/influxdata/flux" @@ -17,7 +18,7 @@ import ( ) func NewProxyQueryService(engine *storage.Engine, bucketSvc platform.BucketService, orgSvc platform.OrganizationService, logger *zap.Logger) (query.ProxyQueryService, error) { - var ( // flux + var ( concurrencyQuota = 10 memoryBytesQuota = 1e6 ) diff --git a/task/backend/coordinator/coordinator_test.go b/task/backend/coordinator/coordinator_test.go index d4dc92ecfe..c58abf6b97 100644 --- a/task/backend/coordinator/coordinator_test.go +++ b/task/backend/coordinator/coordinator_test.go @@ -74,7 +74,7 @@ func TestCoordinator(t *testing.T) { t.Fatal(err) } - task, err = timeoutSelector(createChan) + _, err = timeoutSelector(createChan) if err != nil { t.Fatal(err) } diff --git a/task/backend/inmem_logreaderwriter.go b/task/backend/inmem_logreaderwriter.go index dbeff0c4d5..ceac6759fb 100644 --- a/task/backend/inmem_logreaderwriter.go +++ b/task/backend/inmem_logreaderwriter.go @@ -141,8 +141,7 @@ func (r *runReaderWriter) FindRunByID(ctx context.Context, orgID, runID platform return nil, ErrRunNotFound } - var rtnRun platform.Run - rtnRun = *run + rtnRun := *run return &rtnRun, nil } diff --git a/task/backend/scheduler_test.go b/task/backend/scheduler_test.go index ec05fdb445..c5b9a16880 100644 --- a/task/backend/scheduler_test.go +++ b/task/backend/scheduler_test.go @@ -287,7 +287,7 @@ func TestScheduler_UpdateTask(t *testing.T) { } s.Tick(3061) - p, err = e.PollForNumberRunning(task.ID, 0) + _, err = e.PollForNumberRunning(task.ID, 0) if err != nil { t.Fatal(err) } diff --git a/task/backend/storetest/storetest.go b/task/backend/storetest/storetest.go index b29ef85b45..f891df7b2c 100644 --- a/task/backend/storetest/storetest.go +++ b/task/backend/storetest/storetest.go @@ -80,11 +80,11 @@ from(bucket:"test") |> range(start:-1h)` defer destroy(t, s) for _, args := range []struct { - caseName string - org, user platform.ID - name, script string - status backend.TaskStatus - noerr bool + caseName string + org, user platform.ID + script string + status backend.TaskStatus + noerr bool }{ {caseName: "happy path", org: platform.ID(1), user: platform.ID(2), script: script, noerr: true}, {caseName: "missing org", org: platform.ID(0), user: platform.ID(2), script: script}, @@ -128,12 +128,6 @@ from(bucket:"x") |> range(start:-1h)` cron: "* * * * *", } -from(bucket:"y") |> range(start:-1h)` - const script3 = `option task = { - name: "a task3", - cron: "* * * * *", -} - from(bucket:"y") |> range(start:-1h)` const scriptNoName = `option task = { cron: "* * * * *", diff --git a/telegraf_test.go b/telegraf_test.go index aab97c5c19..990f6b80b8 100644 --- a/telegraf_test.go +++ b/telegraf_test.go @@ -62,7 +62,6 @@ func TestTelegrafConfigJSON(t *testing.T) { name string cfg *TelegrafConfig err error - json string }{ { name: "regular config", diff --git a/testing/auth.go b/testing/auth.go index 565b1cf9ad..17ecd456f0 100644 --- a/testing/auth.go +++ b/testing/auth.go @@ -84,7 +84,6 @@ func CreateAuthorization( ) { type args struct { authorization *platform.Authorization - user string } type wants struct { err error diff --git a/testing/cells.go b/testing/cells.go index cd9e582a1d..aad7ba9e17 100644 --- a/testing/cells.go +++ b/testing/cells.go @@ -226,8 +226,7 @@ func FindViews( t *testing.T, ) { type args struct { - ID platform.ID - name string + ID platform.ID } type wants struct { diff --git a/testing/dashboards.go b/testing/dashboards.go index 4d7fd50620..d413454362 100644 --- a/testing/dashboards.go +++ b/testing/dashboards.go @@ -434,7 +434,6 @@ func FindDashboards( ) { type args struct { IDs []*platform.ID - name string findOptions platform.FindOptions } diff --git a/testing/macro.go b/testing/macro.go index 221ac6334b..36dcb76b4c 100644 --- a/testing/macro.go +++ b/testing/macro.go @@ -16,7 +16,6 @@ import ( const ( idA = "020f755c3c082000" idB = "020f755c3c082001" - idC = "020f755c3c082002" ) var macroCmpOptions = cmp.Options{ diff --git a/testing/session.go b/testing/session.go index d9363d7ef4..b4a12619a5 100644 --- a/testing/session.go +++ b/testing/session.go @@ -14,9 +14,8 @@ import ( ) const ( - sessionOneID = "020f755c3c082000" - sessionTwoID = "020f755c3c082001" - sessionThreeID = "020f755c3c082002" + sessionOneID = "020f755c3c082000" + sessionTwoID = "020f755c3c082001" ) var sessionCmpOptions = cmp.Options{ diff --git a/testing/source.go b/testing/source.go index 4f8daf46b5..cb6c8c1ae1 100644 --- a/testing/source.go +++ b/testing/source.go @@ -17,7 +17,6 @@ const ( defaultSourceOrganizationID = "50616e67652c206c" sourceOneID = "020f755c3c082001" sourceTwoID = "020f755c3c082002" - sourceThreeID = "020f755c3c082003" sourceOrgOneID = "61726920617a696f" ) diff --git a/tools.go b/tools.go index f53fbdebe2..721c1c6eca 100644 --- a/tools.go +++ b/tools.go @@ -8,6 +8,7 @@ import ( _ "github.com/goreleaser/goreleaser" _ "github.com/kevinburke/go-bindata/go-bindata" _ "github.com/mna/pigeon" + _ "honnef.co/go/tools/cmd/megacheck" ) // This package is a workaround for adding additional paths to the go.mod file diff --git a/tsdb/index_test.go b/tsdb/index_test.go index 09394999eb..e97c9810c4 100644 --- a/tsdb/index_test.go +++ b/tsdb/index_test.go @@ -220,8 +220,7 @@ func BenchmarkIndex_TagSets(b *testing.B) { name := []byte("m4") opt := query.IteratorOptions{Condition: influxql.MustParseExpr(`"tag5"::tag = 'value0'`)} - var ts func() ([]*query.TagSet, error) - ts = func() ([]*query.TagSet, error) { + ts := func() ([]*query.TagSet, error) { return idx.Index.TagSets(name, opt) } diff --git a/tsdb/series_file.go b/tsdb/series_file.go index da99c30d9c..eeb384128f 100644 --- a/tsdb/series_file.go +++ b/tsdb/series_file.go @@ -513,12 +513,4 @@ func SeriesKeySize(name []byte, tags models.Tags) int { return n } -type seriesKeys [][]byte - -func (a seriesKeys) Len() int { return len(a) } -func (a seriesKeys) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a seriesKeys) Less(i, j int) bool { - return CompareSeriesKeys(a[i], a[j]) == -1 -} - func nop() {} diff --git a/tsdb/series_id.go b/tsdb/series_id.go index b85e67d1d8..eab229f7c4 100644 --- a/tsdb/series_id.go +++ b/tsdb/series_id.go @@ -12,7 +12,7 @@ const ( seriesIDValueMask = 0xFFFFFFFF // series ids numerically are 32 bits seriesIDTypeShift = 32 // we put the type right after the value info seriesIDTypeMask = 0xFF << seriesIDTypeShift // a mask for the type byte - seriesIDSize = 8 + seriesIDSize = 8 //lint:ignore U1000 This const is used in a discarded compile-time type assertion. ) // SeriesID is the type of a series id. It is logically a uint64, but encoded as a struct so diff --git a/tsdb/tsi1/measurement_block.go b/tsdb/tsi1/measurement_block.go index 40c690de96..2ddb612b09 100644 --- a/tsdb/tsi1/measurement_block.go +++ b/tsdb/tsi1/measurement_block.go @@ -251,8 +251,9 @@ func ReadMeasurementBlockTrailer(data []byte) (MeasurementBlockTrailer, error) { t.HashIndex.Offset, buf = int64(binary.BigEndian.Uint64(buf[0:8])), buf[8:] t.HashIndex.Size, buf = int64(binary.BigEndian.Uint64(buf[0:8])), buf[8:] - // Skip over old sketch info - buf = buf[4*8:] + // We would advance past old sketch info, but that's unused now. + _ = buf + // buf = buf[4*8:] return t, nil } diff --git a/tsdb/tsm1/batch_float_test.go b/tsdb/tsm1/batch_float_test.go index 470d908516..ffd177823f 100644 --- a/tsdb/tsm1/batch_float_test.go +++ b/tsdb/tsm1/batch_float_test.go @@ -118,13 +118,6 @@ func dumpBufs(a, b []byte) { fmt.Println() } -func dumpBuf(b []byte) { - for i, v := range b { - fmt.Printf("%d %08b\n", i, v) - } - fmt.Println() -} - func TestFloatArrayEncodeAll_NaN(t *testing.T) { examples := [][]float64{ {1.0, math.NaN(), 2.0}, @@ -179,7 +172,7 @@ func Test_FloatArrayEncodeAll_Quick(t *testing.T) { t.Fatalf("unexpected error: %v", err) } - if got, exp := result, src[:len(src)]; !reflect.DeepEqual(got, exp) { + if got, exp := result, src[:]; !reflect.DeepEqual(got, exp) { t.Fatalf("got result %v, expected %v", got, exp) } return true diff --git a/tsdb/tsm1/batch_integer_test.go b/tsdb/tsm1/batch_integer_test.go index 01089e2bd8..de9000b4da 100644 --- a/tsdb/tsm1/batch_integer_test.go +++ b/tsdb/tsm1/batch_integer_test.go @@ -34,13 +34,6 @@ func dumpBufs(a, b []byte) { fmt.Println() } -func dumpBuf(b []byte) { - for i, v := range b { - fmt.Printf("%[1]d %08[2]b (%[2]d)\n", i, v) - } - fmt.Println() -} - func TestIntegerArrayEncodeAll_NoValues(t *testing.T) { b, err := IntegerArrayEncodeAll(nil, nil) if err != nil { @@ -650,9 +643,7 @@ func TestIntegerArrayEncodeAll_Quick(t *testing.T) { // Copy over values to compare result—src is modified... exp := make([]int64, 0, len(src)) - for _, v := range src { - exp = append(exp, v) - } + exp = append(exp, src...) // Retrieve encoded bytes from encoder. b, err := IntegerArrayEncodeAll(src, nil) diff --git a/tsdb/tsm1/engine.go b/tsdb/tsm1/engine.go index b16df1d1a0..857fc84bfa 100644 --- a/tsdb/tsm1/engine.go +++ b/tsdb/tsm1/engine.go @@ -641,48 +641,6 @@ func (e *Engine) Free() error { return e.FileStore.Free() } -// addToIndexFromKey will pull the measurement names, series keys, and field -// names from composite keys, and add them to the database index and measurement -// fields. -func (e *Engine) addToIndexFromKey(keys [][]byte, fieldTypes []influxql.DataType) error { - collection := &tsdb.SeriesCollection{ - Keys: keys, - Names: make([][]byte, 0, len(keys)), - Tags: make([]models.Tags, 0, len(keys)), - Types: make([]models.FieldType, 0, len(keys)), - } - - for i := 0; i < len(keys); i++ { - // Replace tsm key format with index key format. - collection.Keys[i], _ = SeriesAndFieldFromCompositeKey(collection.Keys[i]) - name := models.ParseName(collection.Keys[i]) - collection.Names = append(collection.Names, name) - collection.Tags = append(collection.Tags, models.ParseTags(keys[i])) - collection.Types = append(collection.Types, fieldTypeFromDataType(fieldTypes[i])) - } - - if err := e.index.CreateSeriesListIfNotExists(collection); err != nil { - return err - } - - return nil -} - -func fieldTypeFromDataType(dataType influxql.DataType) models.FieldType { - switch dataType { - case influxql.Float: - return models.Float - case influxql.Integer: - return models.Integer - case influxql.String: - return models.String - case influxql.Boolean: - return models.Boolean - default: - return models.Empty - } -} - // WritePoints writes metadata and point data into the engine. // It returns an error if new points are added to an existing key. func (e *Engine) WritePoints(points []models.Point) error {