From 4ba540cb2c94eb9e38ebeac55598fb886c3d994d Mon Sep 17 00:00:00 2001 From: Johan Siebens Date: Sun, 19 Mar 2023 10:24:23 +0100 Subject: [PATCH] chore: replace hclog with zap --- internal/database/database.go | 24 ++++----- internal/errors/errors.go | 42 --------------- internal/handlers/authentication.go | 73 +++++++++++++------------- internal/handlers/dns.go | 7 ++- internal/handlers/id_token.go | 13 +++-- internal/handlers/noise.go | 3 +- internal/handlers/poll_net_map.go | 27 +++++----- internal/handlers/registration.go | 27 +++++----- internal/handlers/ssh_action.go | 9 ++-- internal/handlers/version.go | 6 +++ internal/server/echo.go | 51 +++++------------- internal/server/rpc.go | 5 +- internal/server/server.go | 77 ++++++++++++++------------- internal/service/acl.go | 11 ++-- internal/service/auth.go | 11 ++-- internal/service/auth_keys.go | 19 ++++--- internal/service/derp_map.go | 15 +++--- internal/service/dns.go | 7 ++- internal/service/iam.go | 7 ++- internal/service/interceptors.go | 28 ++++------ internal/service/machine.go | 45 ++++++++-------- internal/service/tailnet.go | 81 ++++++++++++++--------------- internal/service/users.go | 9 ++-- tests/config/config.yaml | 2 +- 24 files changed, 258 insertions(+), 341 deletions(-) delete mode 100644 internal/errors/errors.go diff --git a/internal/database/database.go b/internal/database/database.go index 4dbbd590..d1d214a7 100644 --- a/internal/database/database.go +++ b/internal/database/database.go @@ -5,9 +5,9 @@ import ( "errors" "fmt" "github.com/go-gormigrate/gormigrate/v2" - "github.com/hashicorp/go-hclog" "github.com/jsiebens/ionscale/internal/database/migration" "github.com/jsiebens/ionscale/internal/util" + "go.uber.org/zap" "tailscale.com/types/key" "time" @@ -23,7 +23,7 @@ type dbLock interface { UnlockErr(error) error } -func OpenDB(config *config.Database, logger hclog.Logger) (domain.Repository, error) { +func OpenDB(config *config.Database, logger *zap.Logger) (domain.Repository, error) { db, lock, err := createDB(config, logger) if err != nil { return nil, err @@ -54,9 +54,9 @@ func OpenDB(config *config.Database, logger hclog.Logger) (domain.Repository, er return repository, nil } -func createDB(config *config.Database, logger hclog.Logger) (*gorm.DB, dbLock, error) { +func createDB(config *config.Database, logger *zap.Logger) (*gorm.DB, dbLock, error) { gormConfig := &gorm.Config{ - Logger: &GormLoggerAdapter{logger: logger.Named("db")}, + Logger: &GormLoggerAdapter{logger: logger.Sugar()}, } switch config.Type { @@ -134,7 +134,7 @@ func createJSONWebKeySet(ctx context.Context, repository domain.Repository) erro } type GormLoggerAdapter struct { - logger hclog.Logger + logger *zap.SugaredLogger } func (g *GormLoggerAdapter) LogMode(level logger.LogLevel) logger.Interface { @@ -142,11 +142,11 @@ func (g *GormLoggerAdapter) LogMode(level logger.LogLevel) logger.Interface { } func (g *GormLoggerAdapter) Info(ctx context.Context, s string, i ...interface{}) { - g.logger.Info(s, i) + g.logger.Infow(s, i) } func (g *GormLoggerAdapter) Warn(ctx context.Context, s string, i ...interface{}) { - g.logger.Warn(s, i) + g.logger.Warnw(s, i) } func (g *GormLoggerAdapter) Error(ctx context.Context, s string, i ...interface{}) { @@ -154,22 +154,22 @@ func (g *GormLoggerAdapter) Error(ctx context.Context, s string, i ...interface{ } func (g *GormLoggerAdapter) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) { - if g.logger.IsTrace() { + if g.logger.Level().Enabled(zap.DebugLevel) { elapsed := time.Since(begin) switch { case err != nil && !errors.Is(err, gorm.ErrRecordNotFound): sql, rows := fc() if rows == -1 { - g.logger.Trace("Error executing query", "sql", sql, "start_time", begin.Format(time.RFC3339), "duration", elapsed, "err", err) + g.logger.Debugw("Error executing query", "sql", sql, "start_time", begin.Format(time.RFC3339), "duration", elapsed, "err", err) } else { - g.logger.Trace("Error executing query", "sql", sql, "start_time", begin.Format(time.RFC3339), "duration", elapsed, "rows", rows, "err", err) + g.logger.Debugw("Error executing query", "sql", sql, "start_time", begin.Format(time.RFC3339), "duration", elapsed, "rows", rows, "err", err) } default: sql, rows := fc() if rows == -1 { - g.logger.Trace("Statement executed", "sql", sql, "start_time", begin.Format(time.RFC3339), "duration", elapsed) + g.logger.Debugw("Statement executed", "sql", sql, "start_time", begin.Format(time.RFC3339), "duration", elapsed) } else { - g.logger.Trace("Statement executed", "sql", sql, "start_time", begin.Format(time.RFC3339), "duration", elapsed, "rows", rows) + g.logger.Debugw("Statement executed", "sql", sql, "start_time", begin.Format(time.RFC3339), "duration", elapsed, "rows", rows) } } } diff --git a/internal/errors/errors.go b/internal/errors/errors.go deleted file mode 100644 index 28156458..00000000 --- a/internal/errors/errors.go +++ /dev/null @@ -1,42 +0,0 @@ -package errors - -import ( - "fmt" - "runtime" -) - -type Error struct { - Cause error - Location string -} - -func Wrap(err error, skip int) error { - if err == nil { - return nil - } - - c := &Error{ - Cause: err, - Location: getLocation(skip), - } - - return c -} - -func (w *Error) Error() string { - return w.Cause.Error() -} - -func (f *Error) Unwrap() error { - return f.Cause -} - -func (f *Error) Format(s fmt.State, verb rune) { - fmt.Fprintf(s, "%s\n", f.Cause.Error()) - fmt.Fprintf(s, "\t%s\n", f.Location) -} - -func getLocation(skip int) string { - _, file, line, _ := runtime.Caller(2 + skip) - return fmt.Sprintf("%s:%d", file, line) -} diff --git a/internal/handlers/authentication.go b/internal/handlers/authentication.go index 3d27b6ca..2c804d3a 100644 --- a/internal/handlers/authentication.go +++ b/internal/handlers/authentication.go @@ -6,7 +6,6 @@ import ( "fmt" "github.com/jsiebens/ionscale/internal/addr" "github.com/jsiebens/ionscale/internal/auth" - "github.com/jsiebens/ionscale/internal/errors" "github.com/labstack/echo/v4/middleware" "github.com/mr-tron/base58" "net/http" @@ -66,7 +65,7 @@ func (h *AuthenticationHandlers) StartAuth(c echo.Context) error { // machine registration auth flow if flow == "r" || flow == "" { if req, err := h.repository.GetRegistrationRequestByKey(ctx, key); err != nil || req == nil { - return errors.Wrap(err, 0) + return logError(err) } csrf := c.Get(middleware.DefaultCSRFConfig.ContextKey).(string) @@ -76,24 +75,24 @@ func (h *AuthenticationHandlers) StartAuth(c echo.Context) error { // cli auth flow if flow == "c" { if s, err := h.repository.GetAuthenticationRequest(ctx, key); err != nil || s == nil { - return errors.Wrap(err, 0) + return logError(err) } } // ssh check auth flow if flow == "s" { if s, err := h.repository.GetSSHActionRequest(ctx, key); err != nil || s == nil { - return errors.Wrap(err, 0) + return logError(err) } } if h.authProvider == nil { - return errors.Wrap(fmt.Errorf("unable to start auth flow as no auth provider is configured"), 0) + return logError(fmt.Errorf("unable to start auth flow as no auth provider is configured")) } state, err := h.createState(flow, key) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } redirectUrl := h.authProvider.GetLoginURL(h.config.CreateUrl("/a/callback"), state) @@ -110,7 +109,7 @@ func (h *AuthenticationHandlers) ProcessAuth(c echo.Context) error { req, err := h.repository.GetRegistrationRequestByKey(ctx, key) if err != nil || req == nil { - return errors.Wrap(err, 0) + return logError(err) } if authKey != "" { @@ -120,7 +119,7 @@ func (h *AuthenticationHandlers) ProcessAuth(c echo.Context) error { if interactive != "" { state, err := h.createState("r", key) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } redirectUrl := h.authProvider.GetLoginURL(h.config.CreateUrl("/a/callback"), state) @@ -142,12 +141,12 @@ func (h *AuthenticationHandlers) Callback(c echo.Context) error { user, err := h.exchangeUser(code) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } account, _, err := h.repository.GetOrCreateAccount(ctx, user.ID, user.Name) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } if state.Flow == "s" { @@ -158,27 +157,27 @@ func (h *AuthenticationHandlers) Callback(c echo.Context) error { machine, err := h.repository.GetMachine(ctx, sshActionReq.SrcMachineID) if err != nil || sshActionReq == nil { - return errors.Wrap(err, 0) + return logError(err) } if !machine.HasTags() && machine.User.AccountID != nil && *machine.User.AccountID == account.ID { sshActionReq.Action = "accept" if err := h.repository.SaveSSHActionRequest(ctx, sshActionReq); err != nil { - return errors.Wrap(err, 0) + return logError(err) } return c.Redirect(http.StatusFound, "/a/success") } sshActionReq.Action = "reject" if err := h.repository.SaveSSHActionRequest(ctx, sshActionReq); err != nil { - return errors.Wrap(err, 0) + return logError(err) } return c.Redirect(http.StatusFound, "/a/error?e=nmo") } tailnets, err := h.listAvailableTailnets(ctx, user) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } csrf := c.Get(middleware.DefaultCSRFConfig.ContextKey).(string) @@ -203,7 +202,7 @@ func (h *AuthenticationHandlers) Callback(c echo.Context) error { if state.Flow == "c" { isSystemAdmin, err := h.isSystemAdmin(ctx, user) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } if !isSystemAdmin && len(tailnets) == 0 { @@ -258,7 +257,7 @@ func (h *AuthenticationHandlers) EndOAuth(c echo.Context) error { if state.Flow == "r" { req, err := h.repository.GetRegistrationRequestByKey(ctx, state.Key) if err != nil || req == nil { - return errors.Wrap(err, 0) + return logError(err) } return h.endMachineRegistrationFlow(c, req, state) @@ -266,7 +265,7 @@ func (h *AuthenticationHandlers) EndOAuth(c echo.Context) error { req, err := h.repository.GetAuthenticationRequest(ctx, state.Key) if err != nil || req == nil { - return errors.Wrap(err, 0) + return logError(err) } return h.endCliAuthenticationFlow(c, req, state) @@ -308,12 +307,12 @@ func (h *AuthenticationHandlers) endCliAuthenticationFlow(c echo.Context, req *d var form TailnetSelectionForm if err := c.Bind(&form); err != nil { - return errors.Wrap(err, 0) + return logError(err) } account, err := h.repository.GetAccount(ctx, form.AccountID) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } // continue as system admin? @@ -324,27 +323,27 @@ func (h *AuthenticationHandlers) endCliAuthenticationFlow(c echo.Context, req *d err := h.repository.Transaction(func(rp domain.Repository) error { if err := rp.SaveSystemApiKey(ctx, apiKey); err != nil { - return errors.Wrap(err, 0) + return logError(err) } if err := rp.SaveAuthenticationRequest(ctx, req); err != nil { - return errors.Wrap(err, 0) + return logError(err) } return nil }) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } return c.Redirect(http.StatusFound, "/a/success") } tailnet, err := h.repository.GetTailnet(ctx, form.TailnetID) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } user, _, err := h.repository.GetOrCreateUserWithAccount(ctx, tailnet, account) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } expiresAt := time.Now().Add(24 * time.Hour) @@ -362,7 +361,7 @@ func (h *AuthenticationHandlers) endCliAuthenticationFlow(c echo.Context, req *d return nil }) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } return c.Redirect(http.StatusFound, "/a/success") @@ -373,7 +372,7 @@ func (h *AuthenticationHandlers) endMachineRegistrationFlow(c echo.Context, regi var form TailnetSelectionForm if err := c.Bind(&form); err != nil { - return errors.Wrap(err, 0) + return logError(err) } req := tailcfg.RegisterRequest(registrationRequest.Data) @@ -389,7 +388,7 @@ func (h *AuthenticationHandlers) endMachineRegistrationFlow(c echo.Context, regi if form.AuthKey != "" { authKey, err := h.repository.LoadAuthKey(ctx, form.AuthKey) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } if authKey == nil { @@ -398,7 +397,7 @@ func (h *AuthenticationHandlers) endMachineRegistrationFlow(c echo.Context, regi registrationRequest.Error = "invalid auth key" if err := h.repository.SaveRegistrationRequest(ctx, registrationRequest); err != nil { - return errors.Wrap(err, 0) + return logError(err) } return c.Redirect(http.StatusFound, "/a/error?e=iak") @@ -412,17 +411,17 @@ func (h *AuthenticationHandlers) endMachineRegistrationFlow(c echo.Context, regi } else { selectedTailnet, err := h.repository.GetTailnet(ctx, form.TailnetID) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } account, err := h.repository.GetAccount(ctx, form.AccountID) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } selectedUser, _, err := h.repository.GetOrCreateUserWithAccount(ctx, selectedTailnet, account) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } user = selectedUser @@ -434,7 +433,7 @@ func (h *AuthenticationHandlers) endMachineRegistrationFlow(c echo.Context, regi registrationRequest.Authenticated = false registrationRequest.Error = err.Error() if err := h.repository.SaveRegistrationRequest(ctx, registrationRequest); err != nil { - return errors.Wrap(err, 0) + return logError(err) } return c.Redirect(http.StatusFound, "/a/error?e=nto") } @@ -445,7 +444,7 @@ func (h *AuthenticationHandlers) endMachineRegistrationFlow(c echo.Context, regi m, err := h.repository.GetMachineByKey(ctx, tailnet.ID, machineKey) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } now := time.Now().UTC() @@ -458,7 +457,7 @@ func (h *AuthenticationHandlers) endMachineRegistrationFlow(c echo.Context, regi sanitizeHostname := dnsname.SanitizeHostname(req.Hostinfo.Hostname) nameIdx, err := h.repository.GetNextMachineNameIndex(ctx, tailnet.ID, sanitizeHostname) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } m = &domain.Machine{ @@ -482,7 +481,7 @@ func (h *AuthenticationHandlers) endMachineRegistrationFlow(c echo.Context, regi ipv4, ipv6, err := addr.SelectIP(checkIP(ctx, h.repository.CountMachinesWithIPv4)) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } m.IPv4 = domain.IP{Addr: ipv4} m.IPv6 = domain.IP{Addr: ipv6} @@ -495,7 +494,7 @@ func (h *AuthenticationHandlers) endMachineRegistrationFlow(c echo.Context, regi if m.Name != sanitizeHostname { nameIdx, err := h.repository.GetNextMachineNameIndex(ctx, tailnet.ID, sanitizeHostname) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } m.Name = sanitizeHostname m.NameIdx = nameIdx @@ -529,7 +528,7 @@ func (h *AuthenticationHandlers) endMachineRegistrationFlow(c echo.Context, regi }) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } if m.Authorized { diff --git a/internal/handlers/dns.go b/internal/handlers/dns.go index 578a3ca5..27afdbdd 100644 --- a/internal/handlers/dns.go +++ b/internal/handlers/dns.go @@ -3,7 +3,6 @@ package handlers import ( "github.com/jsiebens/ionscale/internal/bind" "github.com/jsiebens/ionscale/internal/dns" - "github.com/jsiebens/ionscale/internal/errors" "github.com/labstack/echo/v4" "net" "net/http" @@ -29,12 +28,12 @@ func (h *DNSHandlers) SetDNS(c echo.Context) error { binder, err := h.createBinder(c) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } req := &tailcfg.SetDNSRequest{} if err := binder.BindRequest(c, req); err != nil { - return errors.Wrap(err, 0) + return logError(err) } if h.provider == nil { @@ -42,7 +41,7 @@ func (h *DNSHandlers) SetDNS(c echo.Context) error { } if err := h.provider.SetRecord(ctx, req.Type, req.Name, req.Value); err != nil { - return errors.Wrap(err, 0) + return logError(err) } if strings.HasPrefix(req.Name, "_acme-challenge") && req.Type == "TXT" { diff --git a/internal/handlers/id_token.go b/internal/handlers/id_token.go index a6a79cc9..445d6a68 100644 --- a/internal/handlers/id_token.go +++ b/internal/handlers/id_token.go @@ -6,7 +6,6 @@ import ( "github.com/jsiebens/ionscale/internal/bind" "github.com/jsiebens/ionscale/internal/config" "github.com/jsiebens/ionscale/internal/domain" - "github.com/jsiebens/ionscale/internal/errors" "github.com/jsiebens/ionscale/internal/util" "github.com/labstack/echo/v4" "gopkg.in/square/go-jose.v2" @@ -56,7 +55,7 @@ func (h *IDTokenHandlers) OpenIDConfig(c echo.Context) error { func (h *IDTokenHandlers) Jwks(c echo.Context) error { keySet, err := h.repository.GetJSONWebKeySet(c.Request().Context()) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } pub := jose.JSONWebKey{Key: keySet.Key.Public(), KeyID: keySet.Key.Id, Algorithm: "RS256", Use: "sig"} @@ -69,17 +68,17 @@ func (h *IDTokenHandlers) FetchToken(c echo.Context) error { keySet, err := h.repository.GetJSONWebKeySet(c.Request().Context()) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } binder, err := h.createBinder(c) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } req := &tailcfg.TokenRequest{} if err := binder.BindRequest(c, req); err != nil { - return errors.Wrap(err, 0) + return logError(err) } machineKey := binder.Peer().String() @@ -88,7 +87,7 @@ func (h *IDTokenHandlers) FetchToken(c echo.Context) error { var m *domain.Machine m, err = h.repository.GetMachineByKeys(ctx, machineKey, nodeKey) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } if m == nil { @@ -131,7 +130,7 @@ func (h *IDTokenHandlers) FetchToken(c echo.Context) error { jwtB64, err := unsignedToken.SignedString(&keySet.Key.PrivateKey) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } resp := tailcfg.TokenResponse{IDToken: jwtB64} diff --git a/internal/handlers/noise.go b/internal/handlers/noise.go index af22b175..2c0548a1 100644 --- a/internal/handlers/noise.go +++ b/internal/handlers/noise.go @@ -2,7 +2,6 @@ package handlers import ( stderrors "errors" - "github.com/jsiebens/ionscale/internal/errors" "github.com/labstack/echo/v4" "golang.org/x/net/http2" "golang.org/x/net/http2/h2c" @@ -30,7 +29,7 @@ func NewNoiseHandlers(controlKey key.MachinePrivate, createPeerHandler CreatePee func (h *NoiseHandlers) Upgrade(c echo.Context) error { conn, err := controlhttp.AcceptHTTP(c.Request().Context(), c.Response(), c.Request(), h.controlKey, nil) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } handler := h.createPeerHandler(conn.Peer()) diff --git a/internal/handlers/poll_net_map.go b/internal/handlers/poll_net_map.go index 8039b7d0..38aec7e8 100644 --- a/internal/handlers/poll_net_map.go +++ b/internal/handlers/poll_net_map.go @@ -6,7 +6,6 @@ import ( "github.com/jsiebens/ionscale/internal/config" "github.com/jsiebens/ionscale/internal/core" "github.com/jsiebens/ionscale/internal/domain" - "github.com/jsiebens/ionscale/internal/errors" "github.com/jsiebens/ionscale/internal/mapping" "github.com/labstack/echo/v4" "net/http" @@ -40,12 +39,12 @@ func (h *PollNetMapHandler) PollNetMap(c echo.Context) error { ctx := c.Request().Context() binder, err := h.createBinder(c) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } req := &tailcfg.MapRequest{} if err := binder.BindRequest(c, req); err != nil { - return errors.Wrap(err, 0) + return logError(err) } machineKey := binder.Peer().String() @@ -54,7 +53,7 @@ func (h *PollNetMapHandler) PollNetMap(c echo.Context) error { var m *domain.Machine m, err = h.repository.GetMachineByKeys(ctx, machineKey, nodeKey) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } if m == nil { @@ -79,7 +78,7 @@ func (h *PollNetMapHandler) handleUpdate(c echo.Context, binder bind.Binder, m * m.LastSeen = &now if err := h.repository.SaveMachine(ctx, m); err != nil { - return errors.Wrap(err, 0) + return logError(err) } tailnetID := m.TailnetID @@ -96,7 +95,7 @@ func (h *PollNetMapHandler) handleUpdate(c echo.Context, binder bind.Binder, m * response, syncedPeers, derpMapChecksum, err := h.createMapResponse(m, binder, mapRequest, false, make(map[uint64]bool), derpMapChecksum) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } updateChan := make(chan *core.Ping, 20) @@ -107,13 +106,13 @@ func (h *PollNetMapHandler) handleUpdate(c echo.Context, binder bind.Binder, m * keepAliveResponse, err := h.createKeepAliveResponse(binder, mapRequest) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } c.Response().WriteHeader(http.StatusOK) if _, err := c.Response().Write(response); err != nil { - return errors.Wrap(err, 0) + return logError(err) } c.Response().Flush() @@ -140,7 +139,7 @@ func (h *PollNetMapHandler) handleUpdate(c echo.Context, binder bind.Binder, m * case <-keepAliveTicker.C: if mapRequest.KeepAlive { if _, err := c.Response().Write(keepAliveResponse); err != nil { - return errors.Wrap(err, 0) + return logError(err) } _ = h.repository.SetMachineLastSeen(ctx, machineID) c.Response().Flush() @@ -149,7 +148,7 @@ func (h *PollNetMapHandler) handleUpdate(c echo.Context, binder bind.Binder, m * if latestSync.Before(latestUpdate) { machine, err := h.repository.GetMachine(ctx, machineID) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } if machine == nil { return nil @@ -165,7 +164,7 @@ func (h *PollNetMapHandler) handleUpdate(c echo.Context, binder bind.Binder, m * } if _, err := c.Response().Write(payload); err != nil { - return errors.Wrap(err, 0) + return logError(err) } c.Response().Flush() @@ -184,16 +183,16 @@ func (h *PollNetMapHandler) handleReadOnly(c echo.Context, binder bind.Binder, m m.DiscoKey = request.DiscoKey.String() if err := h.repository.SaveMachine(ctx, m); err != nil { - return errors.Wrap(err, 0) + return logError(err) } response, _, _, err := h.createMapResponse(m, binder, request, false, map[uint64]bool{}, "") if err != nil { - return errors.Wrap(err, 0) + return logError(err) } _, err = c.Response().Write(response) - return errors.Wrap(err, 0) + return logError(err) } func (h *PollNetMapHandler) createKeepAliveResponse(binder bind.Binder, request *tailcfg.MapRequest) ([]byte, error) { diff --git a/internal/handlers/registration.go b/internal/handlers/registration.go index 0516f8f2..65284573 100644 --- a/internal/handlers/registration.go +++ b/internal/handlers/registration.go @@ -7,7 +7,6 @@ import ( "github.com/jsiebens/ionscale/internal/config" "github.com/jsiebens/ionscale/internal/core" "github.com/jsiebens/ionscale/internal/domain" - "github.com/jsiebens/ionscale/internal/errors" "github.com/jsiebens/ionscale/internal/mapping" "github.com/jsiebens/ionscale/internal/util" "github.com/labstack/echo/v4" @@ -43,12 +42,12 @@ func (h *RegistrationHandlers) Register(c echo.Context) error { binder, err := h.createBinder(c) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } req := &tailcfg.RegisterRequest{} if err := binder.BindRequest(c, req); err != nil { - return errors.Wrap(err, 0) + return logError(err) } machineKey := binder.Peer().String() @@ -58,7 +57,7 @@ func (h *RegistrationHandlers) Register(c echo.Context) error { m, err = h.repository.GetMachineByKeys(ctx, machineKey, nodeKey) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } if m != nil { @@ -72,12 +71,12 @@ func (h *RegistrationHandlers) Register(c echo.Context) error { if m.Ephemeral { if _, err := h.repository.DeleteMachine(ctx, m.ID); err != nil { - return errors.Wrap(err, 0) + return logError(err) } h.sessionManager.NotifyAll(m.TailnetID) } else { if err := h.repository.SaveMachine(ctx, m); err != nil { - return errors.Wrap(err, 0) + return logError(err) } h.sessionManager.NotifyAll(m.TailnetID) } @@ -90,7 +89,7 @@ func (h *RegistrationHandlers) Register(c echo.Context) error { if m.Name != sanitizeHostname { nameIdx, err := h.repository.GetNextMachineNameIndex(ctx, m.TailnetID, sanitizeHostname) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } m.Name = sanitizeHostname m.NameIdx = nameIdx @@ -101,7 +100,7 @@ func (h *RegistrationHandlers) Register(c echo.Context) error { m.Tags = append(m.RegisteredTags, advertisedTags...) if err := h.repository.SaveMachine(ctx, m); err != nil { - return errors.Wrap(err, 0) + return logError(err) } tUser, tLogin := mapping.ToUser(m.User) @@ -155,7 +154,7 @@ func (h *RegistrationHandlers) authenticateMachineWithAuthKey(c echo.Context, bi authKey, err := h.repository.LoadAuthKey(ctx, req.Auth.AuthKey) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } if authKey == nil { @@ -181,7 +180,7 @@ func (h *RegistrationHandlers) authenticateMachineWithAuthKey(c echo.Context, bi m, err = h.repository.GetMachineByKey(ctx, tailnet.ID, machineKey) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } now := time.Now().UTC() @@ -190,7 +189,7 @@ func (h *RegistrationHandlers) authenticateMachineWithAuthKey(c echo.Context, bi sanitizeHostname := dnsname.SanitizeHostname(req.Hostinfo.Hostname) nameIdx, err := h.repository.GetNextMachineNameIndex(ctx, tailnet.ID, sanitizeHostname) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } m = &domain.Machine{ @@ -218,7 +217,7 @@ func (h *RegistrationHandlers) authenticateMachineWithAuthKey(c echo.Context, bi ipv4, ipv6, err := addr.SelectIP(checkIP(ctx, h.repository.CountMachinesWithIPv4)) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } m.IPv4 = domain.IP{Addr: ipv4} m.IPv6 = domain.IP{Addr: ipv6} @@ -227,7 +226,7 @@ func (h *RegistrationHandlers) authenticateMachineWithAuthKey(c echo.Context, bi if m.Name != sanitizeHostname { nameIdx, err := h.repository.GetNextMachineNameIndex(ctx, tailnet.ID, sanitizeHostname) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } m.Name = sanitizeHostname m.NameIdx = nameIdx @@ -245,7 +244,7 @@ func (h *RegistrationHandlers) authenticateMachineWithAuthKey(c echo.Context, bi } if err := h.repository.SaveMachine(ctx, m); err != nil { - return errors.Wrap(err, 0) + return logError(err) } tUser, tLogin := mapping.ToUser(m.User) diff --git a/internal/handlers/ssh_action.go b/internal/handlers/ssh_action.go index 2b9d728a..dd049ffe 100644 --- a/internal/handlers/ssh_action.go +++ b/internal/handlers/ssh_action.go @@ -5,7 +5,6 @@ import ( "github.com/jsiebens/ionscale/internal/bind" "github.com/jsiebens/ionscale/internal/config" "github.com/jsiebens/ionscale/internal/domain" - "github.com/jsiebens/ionscale/internal/errors" "github.com/jsiebens/ionscale/internal/util" "github.com/labstack/echo/v4" "net/http" @@ -37,12 +36,12 @@ func (h *SSHActionHandlers) StartAuth(c echo.Context) error { binder, err := h.createBinder(c) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } data := new(sshActionRequestData) if err = c.Bind(data); err != nil { - return errors.Wrap(err, 0) + return logError(err) } key := util.RandStringBytes(8) @@ -56,7 +55,7 @@ func (h *SSHActionHandlers) StartAuth(c echo.Context) error { authUrl := h.config.CreateUrl("/a/s/%s", key) if err := h.repository.SaveSSHActionRequest(ctx, request); err != nil { - return errors.Wrap(err, 0) + return logError(err) } resp := &tailcfg.SSHAction{ @@ -74,7 +73,7 @@ func (h *SSHActionHandlers) CheckAuth(c echo.Context) error { binder, err := h.createBinder(c) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } tick := time.NewTicker(2 * time.Second) diff --git a/internal/handlers/version.go b/internal/handlers/version.go index 8b9c82c4..7795bf6f 100644 --- a/internal/handlers/version.go +++ b/internal/handlers/version.go @@ -3,6 +3,7 @@ package handlers import ( "github.com/jsiebens/ionscale/internal/version" "github.com/labstack/echo/v4" + "go.uber.org/zap" "net/http" ) @@ -14,3 +15,8 @@ func Version(c echo.Context) error { } return c.JSON(http.StatusOK, resp) } + +func logError(err error) error { + zap.L().WithOptions(zap.AddCallerSkip(1)).Error("error processing request", zap.Error(err)) + return err +} diff --git a/internal/server/echo.go b/internal/server/echo.go index 6d01dfcc..136982a8 100644 --- a/internal/server/echo.go +++ b/internal/server/echo.go @@ -2,54 +2,35 @@ package server import ( "fmt" - "github.com/hashicorp/go-hclog" - "github.com/jsiebens/ionscale/internal/errors" "github.com/labstack/echo-contrib/prometheus" "github.com/labstack/echo/v4" + "go.uber.org/zap" "net/http" "strings" "time" ) -func EchoErrorHandler(logger hclog.Logger) echo.MiddlewareFunc { +func EchoErrorHandler() echo.MiddlewareFunc { return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { request := c.Request() - if err := next(c); err != nil { - switch t := err.(type) { - case *echo.HTTPError: - return err - case *errors.Error: - logger.Error("error processing request", - "err", t.Cause, - "location", t.Location, - "http.method", request.Method, - "http.uri", request.RequestURI, - ) - default: - logger.Error("error processing request", - "err", err, - "http.method", request.Method, - "http.uri", request.RequestURI, - ) - } + err := next(c) - if strings.HasPrefix(request.RequestURI, "/a/") { - return c.Render(http.StatusInternalServerError, "error.html", nil) - } + if err != nil && strings.HasPrefix(request.RequestURI, "/a/") { + return c.Render(http.StatusInternalServerError, "error.html", nil) } - return nil + return err } } } -func EchoLogger(logger hclog.Logger) echo.MiddlewareFunc { - httpLogger := logger.Named("http") +func EchoLogger(logger *zap.Logger) echo.MiddlewareFunc { + httpLogger := logger.Sugar() return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) (err error) { - if !httpLogger.IsTrace() { + if !httpLogger.Level().Enabled(zap.DebugLevel) { return next(c) } @@ -60,7 +41,7 @@ func EchoLogger(logger hclog.Logger) echo.MiddlewareFunc { c.Error(err) } - httpLogger.Trace("finished server http call", + httpLogger.Debugw("finished server http call", "http.code", response.Status, "http.method", request.Method, "http.uri", request.RequestURI, @@ -72,7 +53,7 @@ func EchoLogger(logger hclog.Logger) echo.MiddlewareFunc { } } -func EchoRecover(logger hclog.Logger) echo.MiddlewareFunc { +func EchoRecover() echo.MiddlewareFunc { return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { apply := func() (topErr error) { @@ -82,6 +63,7 @@ func EchoRecover(logger hclog.Logger) echo.MiddlewareFunc { if !ok { err = fmt.Errorf("%v", r) } + zap.L().Error("panic when processing request", zap.Error(err)) topErr = err } }() @@ -92,15 +74,6 @@ func EchoRecover(logger hclog.Logger) echo.MiddlewareFunc { } } -func ErrorRedirect() echo.MiddlewareFunc { - return func(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) error { - c.Set("redirect_on_error", true) - return next(c) - } - } -} - func EchoMetrics(p *prometheus.Prometheus) echo.MiddlewareFunc { return p.HandlerFunc } diff --git a/internal/server/rpc.go b/internal/server/rpc.go index 56240e04..0c6268bd 100644 --- a/internal/server/rpc.go +++ b/internal/server/rpc.go @@ -2,7 +2,6 @@ package server import ( "github.com/bufbuild/connect-go" - "github.com/hashicorp/go-hclog" "github.com/jsiebens/ionscale/internal/domain" "github.com/jsiebens/ionscale/internal/key" "github.com/jsiebens/ionscale/internal/service" @@ -10,7 +9,7 @@ import ( "net/http" ) -func NewRpcHandler(systemAdminKey *key.ServerPrivate, repository domain.Repository, logger hclog.Logger, handler apiconnect.IonscaleServiceHandler) (string, http.Handler) { - interceptors := connect.WithInterceptors(service.NewErrorInterceptor(logger), service.AuthenticationInterceptor(systemAdminKey, repository)) +func NewRpcHandler(systemAdminKey *key.ServerPrivate, repository domain.Repository, handler apiconnect.IonscaleServiceHandler) (string, http.Handler) { + interceptors := connect.WithInterceptors(service.NewErrorInterceptor(), service.AuthenticationInterceptor(systemAdminKey, repository)) return apiconnect.NewIonscaleServiceHandler(handler, interceptors) } diff --git a/internal/server/server.go b/internal/server/server.go index a51c7f54..1cc4dbf9 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -5,7 +5,6 @@ import ( "crypto/tls" "fmt" "github.com/caddyserver/certmagic" - "github.com/hashicorp/go-hclog" "github.com/jsiebens/ionscale/internal/auth" "github.com/jsiebens/ionscale/internal/bind" "github.com/jsiebens/ionscale/internal/config" @@ -19,15 +18,15 @@ import ( echo_prometheus "github.com/labstack/echo-contrib/prometheus" "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" + "go.uber.org/zap" + "go.uber.org/zap/zapcore" "golang.org/x/net/http2" "golang.org/x/net/http2/h2c" "golang.org/x/sync/errgroup" - "log" "net" "net/http" "net/url" "os" - "strings" "tailscale.com/types/key" ) @@ -39,7 +38,10 @@ func Start(c *config.Config) error { logger.Info("Starting ionscale server") - repository, err := database.OpenDB(&c.Database, logger) + httpLogger := logger.Named("http") + dbLogger := logger.Named("db") + + repository, err := database.OpenDB(&c.Database, dbLogger) if err != nil { return err } @@ -68,6 +70,7 @@ func Start(c *config.Config) error { certmagic.DefaultACME.Agreed = true certmagic.DefaultACME.Email = c.Tls.AcmeEmail certmagic.DefaultACME.CA = c.Tls.AcmeCA + certmagic.Default.Logger = logger.Named("certmagic") if c.Tls.AcmePath != "" { certmagic.Default.Storage = &certmagic.FileStorage{Path: c.Tls.AcmePath} } @@ -106,7 +109,7 @@ func Start(c *config.Config) error { sshActionHandlers := handlers.NewSSHActionHandlers(binder, c, repository) e := echo.New() - e.Use(EchoMetrics(p), EchoLogger(logger), EchoErrorHandler(logger), EchoRecover(logger)) + e.Use(EchoMetrics(p), EchoLogger(httpLogger), EchoErrorHandler(), EchoRecover()) e.POST("/machine/register", registrationHandlers.Register) e.POST("/machine/map", pollNetMapHandler.PollNetMap) e.POST("/machine/set-dns", dnsHandlers.SetDNS) @@ -130,17 +133,17 @@ func Start(c *config.Config) error { ) rpcService := service.NewService(c, authProvider, repository, sessionManager) - rpcPath, rpcHandler := NewRpcHandler(serverKey.SystemAdminKey, repository, logger, rpcService) + rpcPath, rpcHandler := NewRpcHandler(serverKey.SystemAdminKey, repository, rpcService) nonTlsAppHandler := echo.New() - nonTlsAppHandler.Use(EchoMetrics(p), EchoLogger(logger), EchoErrorHandler(logger), EchoRecover(logger)) + nonTlsAppHandler.Use(EchoMetrics(p), EchoLogger(httpLogger), EchoErrorHandler(), EchoRecover()) nonTlsAppHandler.POST("/ts2021", noiseHandlers.Upgrade) nonTlsAppHandler.Any("/*", handlers.HttpRedirectHandler(c.Tls)) tlsAppHandler := echo.New() tlsAppHandler.Renderer = templates.NewTemplates() tlsAppHandler.Pre(handlers.HttpsRedirect(c.Tls)) - tlsAppHandler.Use(EchoMetrics(p), EchoLogger(logger), EchoErrorHandler(logger), EchoRecover(logger)) + tlsAppHandler.Use(EchoMetrics(p), EchoLogger(logger), EchoErrorHandler(), EchoRecover()) tlsAppHandler.Any("/*", handlers.IndexHandler(http.StatusNotFound)) tlsAppHandler.Any("/", handlers.IndexHandler(http.StatusOK)) @@ -192,14 +195,14 @@ func Start(c *config.Config) error { } if c.Tls.AcmeEnabled { - logger.Info("TLS is enabled with ACME", "domain", serverUrl.Host) - logger.Info("Server is running", "http_addr", c.HttpListenAddr, "https_addr", c.HttpsListenAddr, "metrics_addr", c.MetricsListenAddr) + logger.Sugar().Infow("TLS is enabled with ACME", "domain", serverUrl.Host) + logger.Sugar().Infow("Server is running", "http_addr", c.HttpListenAddr, "https_addr", c.HttpsListenAddr, "metrics_addr", c.MetricsListenAddr) } else if !c.Tls.Disable { - logger.Info("TLS is enabled", "cert", c.Tls.CertFile) - logger.Info("Server is running", "http_addr", c.HttpListenAddr, "https_addr", c.HttpsListenAddr, "metrics_addr", c.MetricsListenAddr) + logger.Sugar().Infow("TLS is enabled", "cert", c.Tls.CertFile) + logger.Sugar().Infow("Server is running", "http_addr", c.HttpListenAddr, "https_addr", c.HttpsListenAddr, "metrics_addr", c.MetricsListenAddr) } else { - logger.Warn("TLS is disabled") - logger.Info("Server is running", "http_addr", c.HttpListenAddr, "metrics_addr", c.MetricsListenAddr) + logger.Sugar().Warnw("TLS is disabled") + logger.Sugar().Infow("Server is running", "http_addr", c.HttpListenAddr, "metrics_addr", c.MetricsListenAddr) } return g.Wait() @@ -268,32 +271,34 @@ func selectListener(a net.Listener, b net.Listener) net.Listener { return b } -func setupLogging(config config.Logging) (hclog.Logger, error) { - file, err := createLogFile(config) +func setupLogging(config config.Logging) (*zap.Logger, error) { + level, err := zap.ParseAtomicLevel(config.Level) if err != nil { return nil, err } - appLogger := hclog.New(&hclog.LoggerOptions{ - Name: "ionscale", - Level: hclog.LevelFromString(config.Level), - JSONFormat: strings.ToLower(config.Format) == "json", - Output: file, - }) - - log.SetOutput(appLogger.StandardWriter(&hclog.StandardLoggerOptions{InferLevels: true})) - log.SetPrefix("") - log.SetFlags(0) - - return appLogger, nil -} -func createLogFile(config config.Logging) (*os.File, error) { + pc := zap.NewProductionConfig() + pc.Level = level + pc.DisableStacktrace = true + pc.OutputPaths = []string{"stdout"} + pc.Encoding = "console" + pc.EncoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder + pc.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder + if config.File != "" { - f, err := os.OpenFile(config.File, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) - if err != nil { - return nil, err - } - return f, nil + pc.OutputPaths = []string{config.File} + } + + if config.Format == "json" { + pc.Encoding = "json" } - return os.Stdout, nil + + logger, err := pc.Build() + if err != nil { + return nil, err + } + + zap.ReplaceGlobals(logger) + + return logger, nil } diff --git a/internal/service/acl.go b/internal/service/acl.go index d4251fd7..5c527322 100644 --- a/internal/service/acl.go +++ b/internal/service/acl.go @@ -5,7 +5,6 @@ import ( "fmt" "github.com/bufbuild/connect-go" "github.com/jsiebens/ionscale/internal/domain" - "github.com/jsiebens/ionscale/internal/errors" "github.com/jsiebens/ionscale/internal/mapping" api "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1" ) @@ -18,7 +17,7 @@ func (s *Service) GetACLPolicy(ctx context.Context, req *connect.Request[api.Get tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if tailnet == nil { return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet does not exist")) @@ -26,7 +25,7 @@ func (s *Service) GetACLPolicy(ctx context.Context, req *connect.Request[api.Get var policy api.ACLPolicy if err := mapping.CopyViaJson(&tailnet.ACLPolicy, &policy); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } return connect.NewResponse(&api.GetACLPolicyResponse{Policy: &policy}), nil @@ -40,7 +39,7 @@ func (s *Service) SetACLPolicy(ctx context.Context, req *connect.Request[api.Set tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if tailnet == nil { return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet does not exist")) @@ -48,12 +47,12 @@ func (s *Service) SetACLPolicy(ctx context.Context, req *connect.Request[api.Set var policy domain.ACLPolicy if err := mapping.CopyViaJson(req.Msg.Policy, &policy); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } tailnet.ACLPolicy = policy if err := s.repository.SaveTailnet(ctx, tailnet); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } s.sessionManager.NotifyAll(tailnet.ID) diff --git a/internal/service/auth.go b/internal/service/auth.go index ae453f2d..e271e351 100644 --- a/internal/service/auth.go +++ b/internal/service/auth.go @@ -5,7 +5,6 @@ import ( "fmt" "github.com/bufbuild/connect-go" "github.com/jsiebens/ionscale/internal/domain" - "github.com/jsiebens/ionscale/internal/errors" "github.com/jsiebens/ionscale/internal/util" api "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1" "time" @@ -25,11 +24,11 @@ func (s *Service) Authenticate(ctx context.Context, req *connect.Request[api.Aut } if err := s.repository.SaveAuthenticationRequest(ctx, session); err != nil { - return errors.Wrap(err, 0) + return logError(err) } if err := stream.Send(&api.AuthenticateResponse{AuthUrl: authUrl}); err != nil { - return errors.Wrap(err, 0) + return logError(err) } notify := ctx.Done() @@ -45,7 +44,7 @@ func (s *Service) Authenticate(ctx context.Context, req *connect.Request[api.Aut case <-tick.C: m, err := s.repository.GetAuthenticationRequest(ctx, key) if err != nil { - return errors.Wrap(err, 0) + return logError(err) } if m == nil { @@ -54,7 +53,7 @@ func (s *Service) Authenticate(ctx context.Context, req *connect.Request[api.Aut if len(m.Token) != 0 { if err := stream.Send(&api.AuthenticateResponse{Token: m.Token, TailnetId: m.TailnetID}); err != nil { - return errors.Wrap(err, 0) + return logError(err) } return nil } @@ -64,7 +63,7 @@ func (s *Service) Authenticate(ctx context.Context, req *connect.Request[api.Aut } if err := stream.Send(&api.AuthenticateResponse{AuthUrl: authUrl}); err != nil { - return errors.Wrap(err, 0) + return logError(err) } case <-notify: diff --git a/internal/service/auth_keys.go b/internal/service/auth_keys.go index 9fd3bd46..c9775939 100644 --- a/internal/service/auth_keys.go +++ b/internal/service/auth_keys.go @@ -5,7 +5,6 @@ import ( "fmt" "github.com/bufbuild/connect-go" "github.com/jsiebens/ionscale/internal/domain" - "github.com/jsiebens/ionscale/internal/errors" api "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1" "google.golang.org/protobuf/types/known/timestamppb" "time" @@ -16,7 +15,7 @@ func (s *Service) GetAuthKey(ctx context.Context, req *connect.Request[api.GetAu key, err := s.repository.GetAuthKey(ctx, req.Msg.AuthKeyId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if key == nil { @@ -80,7 +79,7 @@ func (s *Service) ListAuthKeys(ctx context.Context, req *connect.Request[api.Lis tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if tailnet == nil { @@ -92,7 +91,7 @@ func (s *Service) ListAuthKeys(ctx context.Context, req *connect.Request[api.Lis if principal.IsSystemAdmin() { authKeys, err := s.repository.ListAuthKeys(ctx, req.Msg.TailnetId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } response.AuthKeys = mapAuthKeysToApi(authKeys) @@ -102,7 +101,7 @@ func (s *Service) ListAuthKeys(ctx context.Context, req *connect.Request[api.Lis if principal.User != nil { authKeys, err := s.repository.ListAuthKeysByTailnetAndUser(ctx, req.Msg.TailnetId, principal.User.ID) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } response.AuthKeys = mapAuthKeysToApi(authKeys) @@ -128,7 +127,7 @@ func (s *Service) CreateAuthKey(ctx context.Context, req *connect.Request[api.Cr tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if tailnet == nil { @@ -155,7 +154,7 @@ func (s *Service) CreateAuthKey(ctx context.Context, req *connect.Request[api.Cr if user == nil { u, _, err := s.repository.GetOrCreateServiceUser(ctx, tailnet) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } user = u } @@ -165,7 +164,7 @@ func (s *Service) CreateAuthKey(ctx context.Context, req *connect.Request[api.Cr v, authKey := domain.CreateAuthKey(tailnet, user, req.Msg.Ephemeral, req.Msg.PreAuthorized, tags, expiresAt) if err := s.repository.SaveAuthKey(ctx, authKey); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } response := api.CreateAuthKeyResponse{ @@ -191,7 +190,7 @@ func (s *Service) DeleteAuthKey(ctx context.Context, req *connect.Request[api.De key, err := s.repository.GetAuthKey(ctx, req.Msg.AuthKeyId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if key == nil { @@ -203,7 +202,7 @@ func (s *Service) DeleteAuthKey(ctx context.Context, req *connect.Request[api.De } if _, err := s.repository.DeleteAuthKey(ctx, req.Msg.AuthKeyId); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } return connect.NewResponse(&api.DeleteAuthKeyResponse{}), nil } diff --git a/internal/service/derp_map.go b/internal/service/derp_map.go index 029c8074..20de95bc 100644 --- a/internal/service/derp_map.go +++ b/internal/service/derp_map.go @@ -6,7 +6,6 @@ import ( "fmt" "github.com/bufbuild/connect-go" "github.com/jsiebens/ionscale/internal/domain" - "github.com/jsiebens/ionscale/internal/errors" "github.com/jsiebens/ionscale/internal/util" api "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1" "tailscale.com/tailcfg" @@ -20,12 +19,12 @@ func (s *Service) GetDefaultDERPMap(ctx context.Context, _ *connect.Request[api. dm, err := s.repository.GetDERPMap(ctx) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } raw, err := json.Marshal(dm.DERPMap) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } return connect.NewResponse(&api.GetDefaultDERPMapResponse{Value: raw}), nil @@ -39,7 +38,7 @@ func (s *Service) SetDefaultDERPMap(ctx context.Context, req *connect.Request[ap var derpMap tailcfg.DERPMap if err := json.Unmarshal(req.Msg.Value, &derpMap); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } dp := domain.DERPMap{ @@ -48,12 +47,12 @@ func (s *Service) SetDefaultDERPMap(ctx context.Context, req *connect.Request[ap } if err := s.repository.SetDERPMap(ctx, &dp); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } tailnets, err := s.repository.ListTailnets(ctx) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } for _, t := range tailnets { @@ -72,12 +71,12 @@ func (s *Service) ResetDefaultDERPMap(ctx context.Context, req *connect.Request[ dp := domain.DERPMap{} if err := s.repository.SetDERPMap(ctx, &dp); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } tailnets, err := s.repository.ListTailnets(ctx) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } for _, t := range tailnets { diff --git a/internal/service/dns.go b/internal/service/dns.go index 5e25217a..bc4aa472 100644 --- a/internal/service/dns.go +++ b/internal/service/dns.go @@ -6,7 +6,6 @@ import ( "github.com/bufbuild/connect-go" "github.com/jsiebens/ionscale/internal/config" "github.com/jsiebens/ionscale/internal/domain" - "github.com/jsiebens/ionscale/internal/errors" api "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1" ) @@ -18,7 +17,7 @@ func (s *Service) GetDNSConfig(ctx context.Context, req *connect.Request[api.Get tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if tailnet == nil { return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found")) @@ -45,7 +44,7 @@ func (s *Service) SetDNSConfig(ctx context.Context, req *connect.Request[api.Set tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if tailnet == nil { return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found")) @@ -60,7 +59,7 @@ func (s *Service) SetDNSConfig(ctx context.Context, req *connect.Request[api.Set } if err := s.repository.SaveTailnet(ctx, tailnet); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } s.sessionManager.NotifyAll(tailnet.ID) diff --git a/internal/service/iam.go b/internal/service/iam.go index bb1061b3..edbbd33b 100644 --- a/internal/service/iam.go +++ b/internal/service/iam.go @@ -5,7 +5,6 @@ import ( "fmt" "github.com/bufbuild/connect-go" "github.com/jsiebens/ionscale/internal/domain" - "github.com/jsiebens/ionscale/internal/errors" api "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1" ) @@ -17,7 +16,7 @@ func (s *Service) GetIAMPolicy(ctx context.Context, req *connect.Request[api.Get tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if tailnet == nil { return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet does not exist")) @@ -41,7 +40,7 @@ func (s *Service) SetIAMPolicy(ctx context.Context, req *connect.Request[api.Set tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if tailnet == nil { return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet does not exist")) @@ -55,7 +54,7 @@ func (s *Service) SetIAMPolicy(ctx context.Context, req *connect.Request[api.Set } if err := s.repository.SaveTailnet(ctx, tailnet); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } return connect.NewResponse(&api.SetIAMPolicyResponse{}), nil diff --git a/internal/service/interceptors.go b/internal/service/interceptors.go index ea223b26..6e76d59b 100644 --- a/internal/service/interceptors.go +++ b/internal/service/interceptors.go @@ -4,11 +4,10 @@ import ( "context" "fmt" "github.com/bufbuild/connect-go" - "github.com/hashicorp/go-hclog" "github.com/jsiebens/ionscale/internal/domain" - "github.com/jsiebens/ionscale/internal/errors" "github.com/jsiebens/ionscale/internal/key" "github.com/jsiebens/ionscale/internal/token" + "go.uber.org/zap" "strings" ) @@ -78,14 +77,11 @@ func exchangeToken(ctx context.Context, systemAdminKey *key.ServerPrivate, repos return nil } -func NewErrorInterceptor(logger hclog.Logger) *ErrorInterceptor { - return &ErrorInterceptor{ - logger: logger, - } +func NewErrorInterceptor() *ErrorInterceptor { + return &ErrorInterceptor{} } type ErrorInterceptor struct { - logger hclog.Logger } func (e *ErrorInterceptor) handleError(err error) error { @@ -93,23 +89,14 @@ func (e *ErrorInterceptor) handleError(err error) error { return err } - switch t := err.(type) { + switch err.(type) { case *connect.Error: return err - case *errors.Error: - e.logger.Error("error processing grpc request", - "err", t.Cause, - "location", t.Location, - ) - return connect.NewError(connect.CodeInternal, fmt.Errorf("internal server error")) default: - e.logger.Error("error processing grpc request", - "err", err, - ) return connect.NewError(connect.CodeInternal, fmt.Errorf("internal server error")) } - } + func (e *ErrorInterceptor) WrapUnary(next connect.UnaryFunc) connect.UnaryFunc { return func(ctx context.Context, request connect.AnyRequest) (connect.AnyResponse, error) { response, err := next(ctx, request) @@ -129,3 +116,8 @@ func (e *ErrorInterceptor) WrapStreamingHandler(next connect.StreamingHandlerFun return e.handleError(err) } } + +func logError(err error) error { + zap.L().WithOptions(zap.AddCallerSkip(1)).Error("error processing request", zap.Error(err)) + return err +} diff --git a/internal/service/machine.go b/internal/service/machine.go index a1c75718..d5da4358 100644 --- a/internal/service/machine.go +++ b/internal/service/machine.go @@ -5,7 +5,6 @@ import ( "fmt" "github.com/bufbuild/connect-go" "github.com/jsiebens/ionscale/internal/domain" - "github.com/jsiebens/ionscale/internal/errors" api "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1" "google.golang.org/protobuf/types/known/timestamppb" "net/netip" @@ -66,7 +65,7 @@ func (s *Service) ListMachines(ctx context.Context, req *connect.Request[api.Lis tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if tailnet == nil { return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found")) @@ -74,7 +73,7 @@ func (s *Service) ListMachines(ctx context.Context, req *connect.Request[api.Lis machines, err := s.repository.ListMachineByTailnet(ctx, tailnet.ID) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } response := &api.ListMachinesResponse{} @@ -90,7 +89,7 @@ func (s *Service) GetMachine(ctx context.Context, req *connect.Request[api.GetMa m, err := s.repository.GetMachine(ctx, req.Msg.MachineId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if m == nil { @@ -109,7 +108,7 @@ func (s *Service) DeleteMachine(ctx context.Context, req *connect.Request[api.De m, err := s.repository.GetMachine(ctx, req.Msg.MachineId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if m == nil { @@ -121,7 +120,7 @@ func (s *Service) DeleteMachine(ctx context.Context, req *connect.Request[api.De } if _, err := s.repository.DeleteMachine(ctx, req.Msg.MachineId); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } s.sessionManager.NotifyAll(m.TailnetID) @@ -134,7 +133,7 @@ func (s *Service) ExpireMachine(ctx context.Context, req *connect.Request[api.Ex m, err := s.repository.GetMachine(ctx, req.Msg.MachineId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if m == nil { @@ -150,7 +149,7 @@ func (s *Service) ExpireMachine(ctx context.Context, req *connect.Request[api.Ex m.KeyExpiryDisabled = false if err := s.repository.SaveMachine(ctx, m); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } s.sessionManager.NotifyAll(m.TailnetID) @@ -163,7 +162,7 @@ func (s *Service) AuthorizeMachine(ctx context.Context, req *connect.Request[api m, err := s.repository.GetMachine(ctx, req.Msg.MachineId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if m == nil { @@ -177,7 +176,7 @@ func (s *Service) AuthorizeMachine(ctx context.Context, req *connect.Request[api if !m.Authorized { m.Authorized = true if err := s.repository.SaveMachine(ctx, m); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } } @@ -191,7 +190,7 @@ func (s *Service) GetMachineRoutes(ctx context.Context, req *connect.Request[api m, err := s.repository.GetMachine(ctx, req.Msg.MachineId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if m == nil { @@ -220,7 +219,7 @@ func (s *Service) EnableMachineRoutes(ctx context.Context, req *connect.Request[ m, err := s.repository.GetMachine(ctx, req.Msg.MachineId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if m == nil { @@ -242,7 +241,7 @@ func (s *Service) EnableMachineRoutes(ctx context.Context, req *connect.Request[ for _, r := range req.Msg.Routes { prefix, err := netip.ParsePrefix(r) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } allowIPs.Add(prefix) } @@ -250,7 +249,7 @@ func (s *Service) EnableMachineRoutes(ctx context.Context, req *connect.Request[ m.AllowIPs = allowIPs.Items() m.AutoAllowIPs = autoAllowIPs.Items() if err := s.repository.SaveMachine(ctx, m); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } s.sessionManager.NotifyAll(m.TailnetID) @@ -273,7 +272,7 @@ func (s *Service) DisableMachineRoutes(ctx context.Context, req *connect.Request m, err := s.repository.GetMachine(ctx, req.Msg.MachineId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if m == nil { @@ -290,7 +289,7 @@ func (s *Service) DisableMachineRoutes(ctx context.Context, req *connect.Request for _, r := range req.Msg.Routes { prefix, err := netip.ParsePrefix(r) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } allowIPs.Remove(prefix) autoAllowIPs.Remove(prefix) @@ -299,7 +298,7 @@ func (s *Service) DisableMachineRoutes(ctx context.Context, req *connect.Request m.AllowIPs = allowIPs.Items() m.AutoAllowIPs = autoAllowIPs.Items() if err := s.repository.SaveMachine(ctx, m); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } s.sessionManager.NotifyAll(m.TailnetID) @@ -322,7 +321,7 @@ func (s *Service) EnableExitNode(ctx context.Context, req *connect.Request[api.E m, err := s.repository.GetMachine(ctx, req.Msg.MachineId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if m == nil { @@ -346,7 +345,7 @@ func (s *Service) EnableExitNode(ctx context.Context, req *connect.Request[api.E m.AllowIPs = allowIPs.Items() if err := s.repository.SaveMachine(ctx, m); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } s.sessionManager.NotifyAll(m.TailnetID) @@ -369,7 +368,7 @@ func (s *Service) DisableExitNode(ctx context.Context, req *connect.Request[api. m, err := s.repository.GetMachine(ctx, req.Msg.MachineId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if m == nil { @@ -397,7 +396,7 @@ func (s *Service) DisableExitNode(ctx context.Context, req *connect.Request[api. m.AutoAllowIPs = autoAllowIPs.Items() if err := s.repository.SaveMachine(ctx, m); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } s.sessionManager.NotifyAll(m.TailnetID) @@ -420,7 +419,7 @@ func (s *Service) SetMachineKeyExpiry(ctx context.Context, req *connect.Request[ m, err := s.repository.GetMachine(ctx, req.Msg.MachineId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if m == nil { @@ -434,7 +433,7 @@ func (s *Service) SetMachineKeyExpiry(ctx context.Context, req *connect.Request[ m.KeyExpiryDisabled = req.Msg.Disabled if err := s.repository.SaveMachine(ctx, m); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } s.sessionManager.NotifyAll(m.TailnetID) diff --git a/internal/service/tailnet.go b/internal/service/tailnet.go index fd162afb..7cefe29f 100644 --- a/internal/service/tailnet.go +++ b/internal/service/tailnet.go @@ -6,7 +6,6 @@ import ( "fmt" "github.com/bufbuild/connect-go" "github.com/jsiebens/ionscale/internal/domain" - "github.com/jsiebens/ionscale/internal/errors" "github.com/jsiebens/ionscale/internal/mapping" "github.com/jsiebens/ionscale/internal/util" api "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1" @@ -57,7 +56,7 @@ func (s *Service) CreateTailnet(ctx context.Context, req *connect.Request[api.Cr if req.Msg.IamPolicy != nil { if err := mapping.CopyViaJson(req.Msg.IamPolicy, &tailnet.IAMPolicy); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } } else { tailnet.IAMPolicy = domain.DefaultIAMPolicy() @@ -65,19 +64,19 @@ func (s *Service) CreateTailnet(ctx context.Context, req *connect.Request[api.Cr if req.Msg.AclPolicy != nil { if err := mapping.CopyViaJson(req.Msg.AclPolicy, &tailnet.ACLPolicy); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } } else { tailnet.ACLPolicy = domain.DefaultACLPolicy() } if err := s.repository.SaveTailnet(ctx, tailnet); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } t, err := domainTailnetToApiTailnet(tailnet) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } resp := &api.CreateTailnetResponse{Tailnet: t} @@ -93,7 +92,7 @@ func (s *Service) UpdateTailnet(ctx context.Context, req *connect.Request[api.Up tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if tailnet == nil { @@ -103,14 +102,14 @@ func (s *Service) UpdateTailnet(ctx context.Context, req *connect.Request[api.Up if req.Msg.IamPolicy != nil { tailnet.IAMPolicy = domain.IAMPolicy{} if err := mapping.CopyViaJson(req.Msg.IamPolicy, &tailnet.IAMPolicy); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } } if req.Msg.AclPolicy != nil { tailnet.ACLPolicy = domain.ACLPolicy{} if err := mapping.CopyViaJson(req.Msg.AclPolicy, &tailnet.ACLPolicy); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } } @@ -124,14 +123,14 @@ func (s *Service) UpdateTailnet(ctx context.Context, req *connect.Request[api.Up tailnet.MachineAuthorizationEnabled = req.Msg.MachineAuthorizationEnabled if err := s.repository.SaveTailnet(ctx, tailnet); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } s.sessionManager.NotifyAll(tailnet.ID) t, err := domainTailnetToApiTailnet(tailnet) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } resp := &api.UpdateTailnetResponse{Tailnet: t} @@ -147,7 +146,7 @@ func (s *Service) GetTailnet(ctx context.Context, req *connect.Request[api.GetTa tailnet, err := s.repository.GetTailnet(ctx, req.Msg.Id) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if tailnet == nil { @@ -156,7 +155,7 @@ func (s *Service) GetTailnet(ctx context.Context, req *connect.Request[api.GetTa t, err := domainTailnetToApiTailnet(tailnet) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } return connect.NewResponse(&api.GetTailnetResponse{Tailnet: t}), nil @@ -170,7 +169,7 @@ func (s *Service) ListTailnets(ctx context.Context, req *connect.Request[api.Lis if principal.IsSystemAdmin() { tailnets, err := s.repository.ListTailnets(ctx) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } for _, t := range tailnets { gt := api.Tailnet{Id: t.ID, Name: t.Name} @@ -181,7 +180,7 @@ func (s *Service) ListTailnets(ctx context.Context, req *connect.Request[api.Lis if principal.User != nil { tailnet, err := s.repository.GetTailnet(ctx, principal.User.TailnetID) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } gt := api.Tailnet{Id: tailnet.ID, Name: tailnet.Name} resp.Tailnet = append(resp.Tailnet, >) @@ -198,7 +197,7 @@ func (s *Service) DeleteTailnet(ctx context.Context, req *connect.Request[api.De count, err := s.repository.CountMachineByTailnet(ctx, req.Msg.TailnetId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if !req.Msg.Force && count > 0 { @@ -230,7 +229,7 @@ func (s *Service) DeleteTailnet(ctx context.Context, req *connect.Request[api.De }) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } s.sessionManager.NotifyAll(req.Msg.TailnetId) @@ -246,12 +245,12 @@ func (s *Service) SetDERPMap(ctx context.Context, req *connect.Request[api.SetDE derpMap := tailcfg.DERPMap{} if err := json.Unmarshal(req.Msg.Value, &derpMap); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if tailnet == nil { return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found")) @@ -263,14 +262,14 @@ func (s *Service) SetDERPMap(ctx context.Context, req *connect.Request[api.SetDE } if err := s.repository.SaveTailnet(ctx, tailnet); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } s.sessionManager.NotifyAll(tailnet.ID) raw, err := json.Marshal(derpMap) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } return connect.NewResponse(&api.SetDERPMapResponse{Value: raw}), nil @@ -284,7 +283,7 @@ func (s *Service) ResetDERPMap(ctx context.Context, req *connect.Request[api.Res tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if tailnet == nil { return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found")) @@ -293,7 +292,7 @@ func (s *Service) ResetDERPMap(ctx context.Context, req *connect.Request[api.Res tailnet.DERPMap = domain.DERPMap{} if err := s.repository.SaveTailnet(ctx, tailnet); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } s.sessionManager.NotifyAll(tailnet.ID) @@ -309,7 +308,7 @@ func (s *Service) GetDERPMap(ctx context.Context, req *connect.Request[api.GetDE tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if tailnet == nil { return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found")) @@ -317,12 +316,12 @@ func (s *Service) GetDERPMap(ctx context.Context, req *connect.Request[api.GetDE derpMap, err := tailnet.GetDERPMap(ctx, s.repository) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } raw, err := json.Marshal(derpMap.DERPMap) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } return connect.NewResponse(&api.GetDERPMapResponse{Value: raw}), nil @@ -336,7 +335,7 @@ func (s *Service) EnableFileSharing(ctx context.Context, req *connect.Request[ap tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if tailnet == nil { return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found")) @@ -345,7 +344,7 @@ func (s *Service) EnableFileSharing(ctx context.Context, req *connect.Request[ap if !tailnet.FileSharingEnabled { tailnet.FileSharingEnabled = true if err := s.repository.SaveTailnet(ctx, tailnet); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } s.sessionManager.NotifyAll(tailnet.ID) @@ -362,7 +361,7 @@ func (s *Service) DisableFileSharing(ctx context.Context, req *connect.Request[a tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if tailnet == nil { return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found")) @@ -371,7 +370,7 @@ func (s *Service) DisableFileSharing(ctx context.Context, req *connect.Request[a if tailnet.FileSharingEnabled { tailnet.FileSharingEnabled = false if err := s.repository.SaveTailnet(ctx, tailnet); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } s.sessionManager.NotifyAll(tailnet.ID) @@ -388,7 +387,7 @@ func (s *Service) EnableServiceCollection(ctx context.Context, req *connect.Requ tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if tailnet == nil { return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found")) @@ -397,7 +396,7 @@ func (s *Service) EnableServiceCollection(ctx context.Context, req *connect.Requ if !tailnet.ServiceCollectionEnabled { tailnet.ServiceCollectionEnabled = true if err := s.repository.SaveTailnet(ctx, tailnet); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } s.sessionManager.NotifyAll(tailnet.ID) @@ -414,7 +413,7 @@ func (s *Service) DisableServiceCollection(ctx context.Context, req *connect.Req tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if tailnet == nil { return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found")) @@ -423,7 +422,7 @@ func (s *Service) DisableServiceCollection(ctx context.Context, req *connect.Req if tailnet.ServiceCollectionEnabled { tailnet.ServiceCollectionEnabled = false if err := s.repository.SaveTailnet(ctx, tailnet); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } s.sessionManager.NotifyAll(tailnet.ID) @@ -440,7 +439,7 @@ func (s *Service) EnableSSH(ctx context.Context, req *connect.Request[api.Enable tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if tailnet == nil { return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found")) @@ -449,7 +448,7 @@ func (s *Service) EnableSSH(ctx context.Context, req *connect.Request[api.Enable if !tailnet.SSHEnabled { tailnet.SSHEnabled = true if err := s.repository.SaveTailnet(ctx, tailnet); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } s.sessionManager.NotifyAll(tailnet.ID) @@ -466,7 +465,7 @@ func (s *Service) DisableSSH(ctx context.Context, req *connect.Request[api.Disab tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if tailnet == nil { return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found")) @@ -475,7 +474,7 @@ func (s *Service) DisableSSH(ctx context.Context, req *connect.Request[api.Disab if tailnet.SSHEnabled { tailnet.SSHEnabled = false if err := s.repository.SaveTailnet(ctx, tailnet); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } s.sessionManager.NotifyAll(tailnet.ID) @@ -492,7 +491,7 @@ func (s *Service) EnableMachineAuthorization(ctx context.Context, req *connect.R tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if tailnet == nil { return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found")) @@ -501,7 +500,7 @@ func (s *Service) EnableMachineAuthorization(ctx context.Context, req *connect.R if !tailnet.MachineAuthorizationEnabled { tailnet.MachineAuthorizationEnabled = true if err := s.repository.SaveTailnet(ctx, tailnet); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } } @@ -516,7 +515,7 @@ func (s *Service) DisableMachineAuthorization(ctx context.Context, req *connect. tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if tailnet == nil { return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("tailnet not found")) @@ -525,7 +524,7 @@ func (s *Service) DisableMachineAuthorization(ctx context.Context, req *connect. if tailnet.MachineAuthorizationEnabled { tailnet.MachineAuthorizationEnabled = false if err := s.repository.SaveTailnet(ctx, tailnet); err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } } diff --git a/internal/service/users.go b/internal/service/users.go index c1509209..08f5d9ac 100644 --- a/internal/service/users.go +++ b/internal/service/users.go @@ -5,7 +5,6 @@ import ( "fmt" "github.com/bufbuild/connect-go" "github.com/jsiebens/ionscale/internal/domain" - "github.com/jsiebens/ionscale/internal/errors" api "github.com/jsiebens/ionscale/pkg/gen/ionscale/v1" ) @@ -14,7 +13,7 @@ func (s *Service) ListUsers(ctx context.Context, req *connect.Request[api.ListUs tailnet, err := s.repository.GetTailnet(ctx, req.Msg.TailnetId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if tailnet == nil { @@ -27,7 +26,7 @@ func (s *Service) ListUsers(ctx context.Context, req *connect.Request[api.ListUs users, err := s.repository.ListUsers(ctx, tailnet.ID) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } resp := &api.ListUsersResponse{} @@ -51,7 +50,7 @@ func (s *Service) DeleteUser(ctx context.Context, req *connect.Request[api.Delet user, err := s.repository.GetUser(ctx, req.Msg.UserId) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } if user == nil { @@ -87,7 +86,7 @@ func (s *Service) DeleteUser(ctx context.Context, req *connect.Request[api.Delet }) if err != nil { - return nil, errors.Wrap(err, 0) + return nil, logError(err) } s.sessionManager.NotifyAll(user.TailnetID) diff --git a/tests/config/config.yaml b/tests/config/config.yaml index 7e9c7ff2..a3191b0b 100644 --- a/tests/config/config.yaml +++ b/tests/config/config.yaml @@ -13,4 +13,4 @@ database: url: /opt/ionscale.db?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)&_pragma=foreign_keys(ON) logging: - level: trace \ No newline at end of file + level: debug \ No newline at end of file