configstore: fix linter errors

Fix errors reported by default golangci-lint linters
This commit is contained in:
Simone Gotti 2019-07-02 14:46:00 +02:00
parent c5abbee3d8
commit 5643dd5dcd
11 changed files with 65 additions and 134 deletions

View File

@ -179,7 +179,6 @@ func (h *ActionHandler) CreateOrg(ctx context.Context, org *types.Organization)
func (h *ActionHandler) DeleteOrg(ctx context.Context, orgRef string) error { func (h *ActionHandler) DeleteOrg(ctx context.Context, orgRef string) error {
var org *types.Organization var org *types.Organization
var projects []*types.Project
var cgt *datamanager.ChangeGroupsUpdateToken var cgt *datamanager.ChangeGroupsUpdateToken
// must do all the checks in a single transaction to avoid concurrent changes // must do all the checks in a single transaction to avoid concurrent changes
@ -215,14 +214,6 @@ func (h *ActionHandler) DeleteOrg(ctx context.Context, orgRef string) error {
ID: org.ID, ID: org.ID,
}, },
} }
// delete all org projects
for _, project := range projects {
actions = append(actions, &datamanager.Action{
ActionType: datamanager.ActionTypeDelete,
DataType: string(types.ConfigTypeProject),
ID: project.ID,
})
}
_, err = h.dm.WriteWal(ctx, actions, cgt) _, err = h.dm.WriteWal(ctx, actions, cgt)
return err return err

View File

@ -77,22 +77,22 @@ func httpError(w http.ResponseWriter, err error) bool {
switch { switch {
case errors.Is(err, &util.ErrBadRequest{}): case errors.Is(err, &util.ErrBadRequest{}):
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
w.Write(resj) _, _ = w.Write(resj)
case errors.Is(err, &util.ErrNotFound{}): case errors.Is(err, &util.ErrNotFound{}):
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
w.Write(resj) _, _ = w.Write(resj)
case errors.Is(err, &util.ErrForbidden{}): case errors.Is(err, &util.ErrForbidden{}):
w.WriteHeader(http.StatusForbidden) w.WriteHeader(http.StatusForbidden)
w.Write(resj) _, _ = w.Write(resj)
case errors.Is(err, &util.ErrUnauthorized{}): case errors.Is(err, &util.ErrUnauthorized{}):
w.WriteHeader(http.StatusUnauthorized) w.WriteHeader(http.StatusUnauthorized)
w.Write(resj) _, _ = w.Write(resj)
case errors.Is(err, &util.ErrInternal{}): case errors.Is(err, &util.ErrInternal{}):
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
w.Write(resj) _, _ = w.Write(resj)
default: default:
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
w.Write(resj) _, _ = w.Write(resj)
} }
return true return true
} }

View File

@ -68,7 +68,6 @@ func (h *RemoteSourceHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
type CreateRemoteSourceHandler struct { type CreateRemoteSourceHandler struct {
log *zap.SugaredLogger log *zap.SugaredLogger
ah *action.ActionHandler ah *action.ActionHandler
readDB *readdb.ReadDB
} }
func NewCreateRemoteSourceHandler(logger *zap.Logger, ah *action.ActionHandler) *CreateRemoteSourceHandler { func NewCreateRemoteSourceHandler(logger *zap.Logger, ah *action.ActionHandler) *CreateRemoteSourceHandler {
@ -99,7 +98,6 @@ func (h *CreateRemoteSourceHandler) ServeHTTP(w http.ResponseWriter, r *http.Req
type UpdateRemoteSourceHandler struct { type UpdateRemoteSourceHandler struct {
log *zap.SugaredLogger log *zap.SugaredLogger
ah *action.ActionHandler ah *action.ActionHandler
readDB *readdb.ReadDB
} }
func NewUpdateRemoteSourceHandler(logger *zap.Logger, ah *action.ActionHandler) *UpdateRemoteSourceHandler { func NewUpdateRemoteSourceHandler(logger *zap.Logger, ah *action.ActionHandler) *UpdateRemoteSourceHandler {

View File

@ -119,7 +119,6 @@ func (h *SecretsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
type CreateSecretHandler struct { type CreateSecretHandler struct {
log *zap.SugaredLogger log *zap.SugaredLogger
ah *action.ActionHandler ah *action.ActionHandler
readDB *readdb.ReadDB
} }
func NewCreateSecretHandler(logger *zap.Logger, ah *action.ActionHandler) *CreateSecretHandler { func NewCreateSecretHandler(logger *zap.Logger, ah *action.ActionHandler) *CreateSecretHandler {

View File

@ -92,7 +92,6 @@ func (h *VariablesHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
type CreateVariableHandler struct { type CreateVariableHandler struct {
log *zap.SugaredLogger log *zap.SugaredLogger
ah *action.ActionHandler ah *action.ActionHandler
readDB *readdb.ReadDB
} }
func NewCreateVariableHandler(logger *zap.Logger, ah *action.ActionHandler) *CreateVariableHandler { func NewCreateVariableHandler(logger *zap.Logger, ah *action.ActionHandler) *CreateVariableHandler {

View File

@ -21,10 +21,6 @@ import (
uuid "github.com/satori/go.uuid" uuid "github.com/satori/go.uuid"
) )
const (
etcdWalsMinRevisionRange = 100
)
type RefType int type RefType int
const ( const (

View File

@ -49,7 +49,6 @@ type Configstore struct {
readDB *readdb.ReadDB readDB *readdb.ReadDB
ost *objectstorage.ObjStorage ost *objectstorage.ObjStorage
ah *action.ActionHandler ah *action.ActionHandler
listenAddress string
} }
func NewConfigstore(ctx context.Context, c *config.Configstore) (*Configstore, error) { func NewConfigstore(ctx context.Context, c *config.Configstore) (*Configstore, error) {
@ -115,15 +114,10 @@ func (s *Configstore) Run(ctx context.Context) error {
go func() { errCh <- s.readDB.Run(ctx) }() go func() { errCh <- s.readDB.Run(ctx) }()
// noop coors handler
corsHandler := func(h http.Handler) http.Handler {
return h
}
corsAllowedMethodsOptions := ghandlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "DELETE"}) corsAllowedMethodsOptions := ghandlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "DELETE"})
corsAllowedHeadersOptions := ghandlers.AllowedHeaders([]string{"Accept", "Accept-Encoding", "Authorization", "Content-Length", "Content-Type", "X-CSRF-Token", "Authorization"}) corsAllowedHeadersOptions := ghandlers.AllowedHeaders([]string{"Accept", "Accept-Encoding", "Authorization", "Content-Length", "Content-Type", "X-CSRF-Token", "Authorization"})
corsAllowedOriginsOptions := ghandlers.AllowedOrigins([]string{"*"}) corsAllowedOriginsOptions := ghandlers.AllowedOrigins([]string{"*"})
corsHandler = ghandlers.CORS(corsAllowedMethodsOptions, corsAllowedHeadersOptions, corsAllowedOriginsOptions) corsHandler := ghandlers.CORS(corsAllowedMethodsOptions, corsAllowedHeadersOptions, corsAllowedOriginsOptions)
projectGroupHandler := api.NewProjectGroupHandler(logger, s.readDB) projectGroupHandler := api.NewProjectGroupHandler(logger, s.readDB)
projectGroupSubgroupsHandler := api.NewProjectGroupSubgroupsHandler(logger, s.ah, s.readDB) projectGroupSubgroupsHandler := api.NewProjectGroupSubgroupsHandler(logger, s.ah, s.readDB)

View File

@ -51,12 +51,15 @@ func setupEtcd(t *testing.T, dir string) *testutil.TestEmbeddedEtcd {
func shutdownEtcd(tetcd *testutil.TestEmbeddedEtcd) { func shutdownEtcd(tetcd *testutil.TestEmbeddedEtcd) {
if tetcd.Etcd != nil { if tetcd.Etcd != nil {
tetcd.Kill() _ = tetcd.Kill()
} }
} }
func setupConfigstore(t *testing.T, ctx context.Context, dir string) (*Configstore, *testutil.TestEmbeddedEtcd) { func setupConfigstore(t *testing.T, ctx context.Context, dir string) (*Configstore, *testutil.TestEmbeddedEtcd) {
etcdDir, err := ioutil.TempDir(dir, "etcd") etcdDir, err := ioutil.TempDir(dir, "etcd")
if err != nil {
t.Fatalf("unexpected err: %v", err)
}
tetcd := setupEtcd(t, etcdDir) tetcd := setupEtcd(t, etcdDir)
listenAddress, port, err := testutil.GetFreePort(true, false) listenAddress, port, err := testutil.GetFreePort(true, false)
@ -65,7 +68,13 @@ func setupConfigstore(t *testing.T, ctx context.Context, dir string) (*Configsto
} }
ostDir, err := ioutil.TempDir(dir, "ost") ostDir, err := ioutil.TempDir(dir, "ost")
if err != nil {
t.Fatalf("unexpected err: %v", err)
}
csDir, err := ioutil.TempDir(dir, "cs") csDir, err := ioutil.TempDir(dir, "cs")
if err != nil {
t.Fatalf("unexpected err: %v", err)
}
baseConfig := config.Configstore{ baseConfig := config.Configstore{
Etcd: config.Etcd{ Etcd: config.Etcd{
@ -117,6 +126,9 @@ func TestResync(t *testing.T) {
defer os.RemoveAll(dir) defer os.RemoveAll(dir)
etcdDir, err := ioutil.TempDir(dir, "etcd") etcdDir, err := ioutil.TempDir(dir, "etcd")
if err != nil {
t.Fatalf("unexpected err: %v", err)
}
tetcd := setupEtcd(t, etcdDir) tetcd := setupEtcd(t, etcdDir)
defer shutdownEtcd(tetcd) defer shutdownEtcd(tetcd)
@ -136,9 +148,21 @@ func TestResync(t *testing.T) {
ctx := context.Background() ctx := context.Background()
ostDir, err := ioutil.TempDir(dir, "ost") ostDir, err := ioutil.TempDir(dir, "ost")
if err != nil {
t.Fatalf("unexpected err: %v", err)
}
csDir1, err := ioutil.TempDir(dir, "cs1") csDir1, err := ioutil.TempDir(dir, "cs1")
if err != nil {
t.Fatalf("unexpected err: %v", err)
}
csDir2, err := ioutil.TempDir(dir, "cs2") csDir2, err := ioutil.TempDir(dir, "cs2")
if err != nil {
t.Fatalf("unexpected err: %v", err)
}
csDir3, err := ioutil.TempDir(dir, "cs3") csDir3, err := ioutil.TempDir(dir, "cs3")
if err != nil {
t.Fatalf("unexpected err: %v", err)
}
baseConfig := config.Configstore{ baseConfig := config.Configstore{
Etcd: config.Etcd{ Etcd: config.Etcd{
@ -171,17 +195,9 @@ func TestResync(t *testing.T) {
ctx2, cancel2 := context.WithCancel(context.Background()) ctx2, cancel2 := context.WithCancel(context.Background())
t.Logf("starting cs1") t.Logf("starting cs1")
go func() { go func() { _ = cs1.Run(ctx1) }()
if err := cs1.Run(ctx1); err != nil {
t.Fatalf("err: %v", err)
}
}()
t.Logf("starting cs2") t.Logf("starting cs2")
go func() { go func() { _ = cs2.Run(ctx2) }()
if err := cs2.Run(ctx2); err != nil {
t.Fatalf("err: %v", err)
}
}()
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
@ -221,7 +237,7 @@ func TestResync(t *testing.T) {
} }
log.Infof("starting cs2") log.Infof("starting cs2")
ctx2 = context.Background() ctx2 = context.Background()
go cs2.Run(ctx2) go func() { _ = cs2.Run(ctx2) }()
time.Sleep(5 * time.Second) time.Sleep(5 * time.Second)
@ -254,7 +270,7 @@ func TestResync(t *testing.T) {
t.Fatalf("err: %v", err) t.Fatalf("err: %v", err)
} }
ctx3 := context.Background() ctx3 := context.Background()
go cs3.Run(ctx3) go func() { _ = cs3.Run(ctx3) }()
time.Sleep(5 * time.Second) time.Sleep(5 * time.Second)
@ -305,9 +321,7 @@ func TestUser(t *testing.T) {
t.Logf("starting cs") t.Logf("starting cs")
go func() { go func() {
if err := cs.Run(ctx); err != nil { _ = cs.Run(ctx)
t.Fatalf("err: %v", err)
}
}() }()
// TODO(sgotti) change the sleep with a real check that all is ready // TODO(sgotti) change the sleep with a real check that all is ready
@ -342,7 +356,7 @@ func TestUser(t *testing.T) {
wg := sync.WaitGroup{} wg := sync.WaitGroup{}
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {
wg.Add(1) wg.Add(1)
go cs.ah.CreateUser(ctx, &action.CreateUserRequest{UserName: "user02"}) go func() { _, _ = cs.ah.CreateUser(ctx, &action.CreateUserRequest{UserName: "user02"}) }()
wg.Done() wg.Done()
} }
wg.Wait() wg.Wait()
@ -374,9 +388,7 @@ func TestProjectGroupsAndProjects(t *testing.T) {
t.Logf("starting cs") t.Logf("starting cs")
go func() { go func() {
if err := cs.Run(ctx); err != nil { _ = cs.Run(ctx)
t.Fatalf("err: %v", err)
}
}() }()
// TODO(sgotti) change the sleep with a real check that all is ready // TODO(sgotti) change the sleep with a real check that all is ready
@ -489,7 +501,9 @@ func TestProjectGroupsAndProjects(t *testing.T) {
wg := sync.WaitGroup{} wg := sync.WaitGroup{}
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {
wg.Add(1) wg.Add(1)
go cs.ah.CreateProject(ctx, &types.Project{Name: "project02", Parent: types.Parent{Type: types.ConfigTypeProjectGroup, ID: path.Join("user", user.Name)}, Visibility: types.VisibilityPublic, RemoteRepositoryConfigType: types.RemoteRepositoryConfigTypeManual}) go func() {
_, _ = cs.ah.CreateProject(ctx, &types.Project{Name: "project02", Parent: types.Parent{Type: types.ConfigTypeProjectGroup, ID: path.Join("user", user.Name)}, Visibility: types.VisibilityPublic, RemoteRepositoryConfigType: types.RemoteRepositoryConfigTypeManual})
}()
wg.Done() wg.Done()
} }
wg.Wait() wg.Wait()
@ -521,9 +535,7 @@ func TestProjectGroupDelete(t *testing.T) {
t.Logf("starting cs") t.Logf("starting cs")
go func() { go func() {
if err := cs.Run(ctx); err != nil { _ = cs.Run(ctx)
t.Fatalf("err: %v", err)
}
}() }()
// TODO(sgotti) change the sleep with a real check that all is ready // TODO(sgotti) change the sleep with a real check that all is ready
@ -661,11 +673,7 @@ func TestOrgMembers(t *testing.T) {
defer shutdownEtcd(tetcd) defer shutdownEtcd(tetcd)
t.Logf("starting cs") t.Logf("starting cs")
go func() { go func() { _ = cs.Run(ctx) }()
if err := cs.Run(ctx); err != nil {
t.Fatalf("err: %v", err)
}
}()
// TODO(sgotti) change the sleep with a real check that all is ready // TODO(sgotti) change the sleep with a real check that all is ready
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)

View File

@ -49,7 +49,7 @@ func (r *ReadDB) insertProjectGroup(tx *db.Tx, data []byte) error {
return errors.Errorf("failed to build query: %w", err) return errors.Errorf("failed to build query: %w", err)
} }
if _, err = tx.Exec(q, args...); err != nil { if _, err = tx.Exec(q, args...); err != nil {
errors.Errorf("failed to insert group: %w", err) return errors.Errorf("failed to insert group: %w", err)
} }
return nil return nil

View File

@ -21,7 +21,6 @@ import (
"io" "io"
"os" "os"
"path/filepath" "path/filepath"
"sync"
"time" "time"
"agola.io/agola/internal/datamanager" "agola.io/agola/internal/datamanager"
@ -61,7 +60,6 @@ type ReadDB struct {
dm *datamanager.DataManager dm *datamanager.DataManager
Initialized bool Initialized bool
initMutex sync.Mutex
} }
func NewReadDB(ctx context.Context, logger *zap.Logger, dataDir string, e *etcd.Store, ost *objectstorage.ObjStorage, dm *datamanager.DataManager) (*ReadDB, error) { func NewReadDB(ctx context.Context, logger *zap.Logger, dataDir string, e *etcd.Store, ost *objectstorage.ObjStorage, dm *datamanager.DataManager) (*ReadDB, error) {
@ -407,9 +405,6 @@ func (r *ReadDB) Run(ctx context.Context) error {
} }
for { for {
if !r.Initialized {
r.Initialize(ctx)
}
if err := r.HandleEvents(ctx); err != nil { if err := r.HandleEvents(ctx); err != nil {
r.log.Errorf("handleevents err: %+v", err) r.log.Errorf("handleevents err: %+v", err)
} }

View File

@ -31,13 +31,13 @@ var (
userSelect = sb.Select("user.id", "user.data").From("user") userSelect = sb.Select("user.id", "user.data").From("user")
userInsert = sb.Insert("user").Columns("id", "name", "data") userInsert = sb.Insert("user").Columns("id", "name", "data")
linkedaccountSelect = sb.Select("id", "data").From("linkedaccount") //linkedaccountSelect = sb.Select("id", "data").From("linkedaccount")
linkedaccountInsert = sb.Insert("linkedaccount").Columns("id", "name", "data") //linkedaccountInsert = sb.Insert("linkedaccount").Columns("id", "name", "data")
linkedaccountuserInsert = sb.Insert("linkedaccount_user").Columns("id", "remotesourceid", "userid", "remoteuserid") linkedaccountuserInsert = sb.Insert("linkedaccount_user").Columns("id", "remotesourceid", "userid", "remoteuserid")
linkedaccountuserSelect = sb.Select("id", "userid").From("linkedaccount_user") //linkedaccountuserSelect = sb.Select("id", "userid").From("linkedaccount_user")
linkedaccountprojectInsert = sb.Insert("linkedaccount_project").Columns("id", "userid") //linkedaccountprojectInsert = sb.Insert("linkedaccount_project").Columns("id", "userid")
usertokenSelect = sb.Select("tokenvalue", "userid").From("user_token") //usertokenSelect = sb.Select("tokenvalue", "userid").From("user_token")
usertokenInsert = sb.Insert("user_token").Columns("tokenvalue", "userid") usertokenInsert = sb.Insert("user_token").Columns("tokenvalue", "userid")
) )
@ -131,14 +131,6 @@ func (r *ReadDB) deleteUserLinkedAccount(tx *db.Tx, id string) error {
return nil return nil
} }
func (r *ReadDB) deleteAllUserTokens(tx *db.Tx, userID string) error {
// poor man insert or update...
if _, err := tx.Exec("delete from user_token where userid = $1", userID); err != nil {
return errors.Errorf("failed to delete user_token: %w", err)
}
return nil
}
func (r *ReadDB) deleteUserToken(tx *db.Tx, tokenValue string) error { func (r *ReadDB) deleteUserToken(tx *db.Tx, tokenValue string) error {
// poor man insert or update... // poor man insert or update...
if _, err := tx.Exec("delete from user_token where tokenvalue = $1", tokenValue); err != nil { if _, err := tx.Exec("delete from user_token where tokenvalue = $1", tokenValue); err != nil {
@ -356,44 +348,3 @@ func scanUsers(rows *sql.Rows) ([]*types.User, []string, error) {
} }
return users, ids, nil return users, ids, nil
} }
type LinkedAccountUser struct {
ID string
UserID string
}
func fetchLinkedAccounts(tx *db.Tx, q string, args ...interface{}) ([]*LinkedAccountUser, error) {
rows, err := tx.Query(q, args...)
if err != nil {
return nil, err
}
defer rows.Close()
linkedAccounts, err := scanLinkedAccounts(rows)
return linkedAccounts, err
}
func scanLinkedAccount(rows *sql.Rows, additionalFields ...interface{}) (*LinkedAccountUser, error) {
var id, userid string
if err := rows.Scan(&id, &userid); err != nil {
return nil, errors.Errorf("failed to scan rows: %w", err)
}
return &LinkedAccountUser{ID: id, UserID: userid}, nil
}
func scanLinkedAccounts(rows *sql.Rows) ([]*LinkedAccountUser, error) {
linkedAccounts := []*LinkedAccountUser{}
for rows.Next() {
linkedAccount, err := scanLinkedAccount(rows)
if err != nil {
rows.Close()
return nil, err
}
linkedAccounts = append(linkedAccounts, linkedAccount)
}
if err := rows.Err(); err != nil {
return nil, err
}
return linkedAccounts, nil
}