Skip to content

Commit

Permalink
Convert tool to use slog (#50623)
Browse files Browse the repository at this point in the history
  • Loading branch information
rosstimothy authored Jan 6, 2025
1 parent ffacd99 commit 58abfdb
Show file tree
Hide file tree
Showing 43 changed files with 391 additions and 292 deletions.
5 changes: 3 additions & 2 deletions tool/common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@ import (
"encoding/json"
"fmt"
"io"
"log/slog"
"sort"
"strings"

"github.com/gravitational/trace"
log "github.com/sirupsen/logrus"

"github.com/gravitational/teleport"
"github.com/gravitational/teleport/api/constants"
Expand All @@ -36,6 +36,7 @@ import (
"github.com/gravitational/teleport/lib/asciitable"
libevents "github.com/gravitational/teleport/lib/events"
"github.com/gravitational/teleport/lib/utils"
logutils "github.com/gravitational/teleport/lib/utils/log"
)

// ExitCodeError wraps an exit code as an error.
Expand Down Expand Up @@ -85,7 +86,7 @@ func (e *SessionsCollection) WriteText(w io.Writer) error {
target = session.DatabaseName
timestamp = session.GetTime().Format(constants.HumanDateFormatSeconds)
default:
log.Warn(trace.BadParameter("unsupported event type: expected SessionEnd, WindowsDesktopSessionEnd or DatabaseSessionEnd: got: %T", event))
slog.WarnContext(context.Background(), "unsupported event type: expected SessionEnd, WindowsDesktopSessionEnd or DatabaseSessionEnd", "event_type", logutils.TypeAttr(event))
continue
}

Expand Down
7 changes: 5 additions & 2 deletions tool/common/fido2/fido2.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,14 @@ import (
"encoding/json"
"errors"
"fmt"
"log/slog"
"os"

"github.com/alecthomas/kingpin/v2"
"github.com/go-webauthn/webauthn/protocol"
"github.com/go-webauthn/webauthn/protocol/webauthncbor"
"github.com/go-webauthn/webauthn/protocol/webauthncose"
"github.com/gravitational/trace"
log "github.com/sirupsen/logrus"

wancli "github.com/gravitational/teleport/lib/auth/webauthncli"
)
Expand Down Expand Up @@ -161,7 +161,10 @@ func (c *AttobjCommand) Run() error {

cert, err := x509.ParseCertificate(certDER)
if err != nil {
log.WithError(err).Warnf("Failed to parse X.509 from x5c[%v], continuing", i)
slog.WarnContext(context.Background(), "Failed to parse X.509 from x5c, continuing",
"index", i,
"error", err,
)
continue
}

Expand Down
18 changes: 13 additions & 5 deletions tool/tctl/common/auth_command.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"context"
"fmt"
"io"
"log/slog"
"net/url"
"os"
"strings"
Expand All @@ -31,7 +32,6 @@ import (
"github.com/alecthomas/kingpin/v2"
"github.com/gravitational/trace"
"github.com/jonboulle/clockwork"
log "github.com/sirupsen/logrus"
"google.golang.org/protobuf/types/known/durationpb"

"github.com/gravitational/teleport"
Expand Down Expand Up @@ -996,7 +996,7 @@ func (a *AuthCommand) generateUserKeys(ctx context.Context, clusterAPI certifica
// If we're in multiplexed mode get SNI name for kube from single multiplexed proxy addr
kubeTLSServerName := ""
if proxyListenerMode == types.ProxyListenerMode_Multiplex {
log.Debug("Using Proxy SNI for kube TLS server name")
slog.DebugContext(ctx, "Using Proxy SNI for kube TLS server name")
u, err := parseURL(a.proxyAddr)
if err != nil {
return trace.Wrap(err)
Expand All @@ -1008,7 +1008,7 @@ func (a *AuthCommand) generateUserKeys(ctx context.Context, clusterAPI certifica

expires, err := keyRing.TeleportTLSCertValidBefore()
if err != nil {
log.WithError(err).Warn("Failed to check TTL validity")
slog.WarnContext(ctx, "Failed to check TTL validity", "error", err)
// err swallowed on purpose
} else if reqExpiry.Sub(expires) > time.Minute {
maxAllowedTTL := time.Until(expires).Round(time.Second)
Expand Down Expand Up @@ -1165,7 +1165,11 @@ func (a *AuthCommand) checkProxyAddr(ctx context.Context, clusterAPI certificate

_, err := utils.ParseAddr(addr)
if err != nil {
log.Warningf("Invalid public address on the proxy %q: %q: %v.", p.GetName(), addr, err)
slog.WarnContext(ctx, "Invalid public address on the proxy",
"proxy", p.GetName(),
"public_address", addr,
"error", err,
)
continue
}

Expand All @@ -1178,7 +1182,11 @@ func (a *AuthCommand) checkProxyAddr(ctx context.Context, clusterAPI certificate
},
)
if err != nil {
log.Warningf("Unable to ping proxy public address on the proxy %q: %q: %v.", p.GetName(), addr, err)
slog.WarnContext(ctx, "Unable to ping proxy public address on the proxy",
"proxy", p.GetName(),
"public_address", addr,
"error", err,
)
continue
}

Expand Down
2 changes: 0 additions & 2 deletions tool/tctl/common/auth_rotate_command.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ import (
"github.com/charmbracelet/huh"
"github.com/charmbracelet/lipgloss"
"github.com/gravitational/trace"
"github.com/sirupsen/logrus"
"golang.org/x/term"

apiclient "github.com/gravitational/teleport/api/client"
Expand Down Expand Up @@ -1288,7 +1287,6 @@ func setupLoggers(logWriter io.Writer) {
logWriter,
logutils.SlogTextHandlerConfig{EnableColors: true},
)))
logrus.StandardLogger().SetOutput(logWriter)
}

func setupMFAPrompt(client *authclient.Client, pingResp proto.PingResponse, promptWriter io.Writer) {
Expand Down
22 changes: 11 additions & 11 deletions tool/tctl/common/bots_command.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"errors"
"fmt"
"io"
"log/slog"
"maps"
"os"
"strings"
Expand All @@ -34,7 +35,6 @@ import (
"github.com/alecthomas/kingpin/v2"
"github.com/google/uuid"
"github.com/gravitational/trace"
log "github.com/sirupsen/logrus"
"google.golang.org/protobuf/types/known/fieldmaskpb"

"github.com/gravitational/teleport"
Expand Down Expand Up @@ -260,7 +260,7 @@ func (c *BotsCommand) AddBot(ctx context.Context, client *authclient.Client) err

roles := splitEntries(c.botRoles)
if len(roles) == 0 {
log.Warning("No roles specified. The bot will not be able to produce outputs until a role is added to the bot.")
slog.WarnContext(ctx, "No roles specified - the bot will not be able to produce outputs until a role is added to the bot")
}
var token types.ProvisionToken
if c.tokenID == "" {
Expand Down Expand Up @@ -386,7 +386,7 @@ func (c *BotsCommand) LockBot(ctx context.Context, client *authclient.Client) er

// updateBotLogins applies updates from CLI arguments to a bot's logins trait,
// updating the field mask if any updates were made.
func (c *BotsCommand) updateBotLogins(bot *machineidv1pb.Bot, mask *fieldmaskpb.FieldMask) error {
func (c *BotsCommand) updateBotLogins(ctx context.Context, bot *machineidv1pb.Bot, mask *fieldmaskpb.FieldMask) error {
traits := map[string][]string{}
for _, t := range bot.Spec.GetTraits() {
traits[t.Name] = t.Values
Expand Down Expand Up @@ -419,15 +419,15 @@ func (c *BotsCommand) updateBotLogins(bot *machineidv1pb.Bot, mask *fieldmaskpb.
desiredLoginsArray := utils.StringsSliceFromSet(desiredLogins)

if maps.Equal(currentLogins, desiredLogins) {
log.Infof("Logins will be left unchanged: %+v", desiredLoginsArray)
slog.InfoContext(ctx, "Logins will be left unchanged", "logins", desiredLoginsArray)
return nil
}

log.Infof("Desired logins for bot %q: %+v", c.botName, desiredLoginsArray)
slog.InfoContext(ctx, "Desired logins for bot", "bot", c.botName, "logins", desiredLoginsArray)

if len(desiredLogins) == 0 {
delete(traits, constants.TraitLogins)
log.Infof("Removing logins trait from bot user")
slog.InfoContext(ctx, "Removing logins trait from bot user")
} else {
traits[constants.TraitLogins] = desiredLoginsArray
}
Expand Down Expand Up @@ -477,11 +477,11 @@ func (c *BotsCommand) updateBotRoles(ctx context.Context, client clientRoleGette
desiredRolesArray := utils.StringsSliceFromSet(desiredRoles)

if maps.Equal(currentRoles, desiredRoles) {
log.Infof("Roles will be left unchanged: %+v", desiredRolesArray)
slog.InfoContext(ctx, "Roles will be left unchanged", "roles", desiredRolesArray)
return nil
}

log.Infof("Desired roles for bot %q: %+v", c.botName, desiredRolesArray)
slog.InfoContext(ctx, "Desired roles for bot", "bot", c.botName, "roles", desiredRolesArray)

// Validate roles (server does not do this yet).
for roleName := range desiredRoles {
Expand Down Expand Up @@ -510,7 +510,7 @@ func (c *BotsCommand) UpdateBot(ctx context.Context, client *authclient.Client)
}

if c.setLogins != "" || c.addLogins != "" {
if err := c.updateBotLogins(bot, fieldMask); err != nil {
if err := c.updateBotLogins(ctx, bot, fieldMask); err != nil {
return trace.Wrap(err)
}
}
Expand All @@ -522,7 +522,7 @@ func (c *BotsCommand) UpdateBot(ctx context.Context, client *authclient.Client)
}

if len(fieldMask.Paths) == 0 {
log.Infof("No changes requested, nothing to do.")
slog.InfoContext(ctx, "No changes requested, nothing to do")
return nil
}

Expand All @@ -534,7 +534,7 @@ func (c *BotsCommand) UpdateBot(ctx context.Context, client *authclient.Client)
return trace.Wrap(err)
}

log.Infof("Bot %q has been updated. Roles will take effect on its next renewal.", c.botName)
slog.InfoContext(ctx, "Bot has been updated, roles will take effect on its next renewal", "bot", c.botName)

return nil
}
Expand Down
2 changes: 1 addition & 1 deletion tool/tctl/common/bots_command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ func TestUpdateBotLogins(t *testing.T) {
setLogins: tt.set,
}

err = cmd.updateBotLogins(bot, fieldMask)
err = cmd.updateBotLogins(context.Background(), bot, fieldMask)
tt.assert(t, bot, fieldMask, err)
})
}
Expand Down
10 changes: 5 additions & 5 deletions tool/tctl/common/config/global.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,14 @@
package config

import (
"context"
"errors"
"io/fs"
"log/slog"
"path/filepath"
"runtime"

"github.com/gravitational/trace"
log "github.com/sirupsen/logrus"

"github.com/gravitational/teleport"
"github.com/gravitational/teleport/api/constants"
Expand Down Expand Up @@ -65,13 +65,13 @@ type GlobalCLIFlags struct {
// The returned authclient.Config has the credentials needed to dial the auth
// server.
func ApplyConfig(ccf *GlobalCLIFlags, cfg *servicecfg.Config) (*authclient.Config, error) {
ctx := context.TODO()
// --debug flag
if ccf.Debug {
cfg.Debug = ccf.Debug
utils.InitLogger(utils.LoggingForCLI, slog.LevelDebug)
log.Debugf("Debug logging has been enabled.")
slog.DebugContext(ctx, "Debug logging has been enabled")
}
cfg.Log = log.StandardLogger()
cfg.Logger = slog.Default()

if cfg.Version == "" {
Expand Down Expand Up @@ -126,9 +126,9 @@ func ApplyConfig(ccf *GlobalCLIFlags, cfg *servicecfg.Config) (*authclient.Confi
if !localAuthSvcConf {
// Try profile or identity file.
if fileConf == nil {
log.Debug("no config file, loading auth config via extension")
slog.DebugContext(ctx, "no config file, loading auth config via extension")
} else {
log.Debug("auth_service disabled in config file, loading auth config via extension")
slog.DebugContext(ctx, "auth_service disabled in config file, loading auth config via extension")
}
authConfig, err := LoadConfigFromProfile(ccf, cfg)
if err == nil {
Expand Down
12 changes: 9 additions & 3 deletions tool/tctl/common/config/profile.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,12 @@
package config

import (
"context"
"errors"
"log/slog"
"time"

"github.com/gravitational/trace"
log "github.com/sirupsen/logrus"

"github.com/gravitational/teleport"
"github.com/gravitational/teleport/api/metadata"
Expand All @@ -33,10 +34,12 @@ import (
"github.com/gravitational/teleport/lib/client/identityfile"
"github.com/gravitational/teleport/lib/service/servicecfg"
"github.com/gravitational/teleport/lib/utils"
logutils "github.com/gravitational/teleport/lib/utils/log"
)

// LoadConfigFromProfile applies config from ~/.tsh/ profile if it's present
func LoadConfigFromProfile(ccf *GlobalCLIFlags, cfg *servicecfg.Config) (*authclient.Config, error) {
ctx := context.TODO()
proxyAddr := ""
if len(ccf.AuthServerAddr) != 0 {
proxyAddr = ccf.AuthServerAddr[0]
Expand Down Expand Up @@ -68,7 +71,10 @@ func LoadConfigFromProfile(ccf *GlobalCLIFlags, cfg *servicecfg.Config) (*authcl
}

c := client.MakeDefaultConfig()
log.WithFields(log.Fields{"proxy": profile.ProxyURL.String(), "user": profile.Username}).Debugf("Found profile.")
slog.DebugContext(ctx, "Found profile",
"proxy", logutils.StringerAttr(&profile.ProxyURL),
"user", profile.Username,
)
if err := c.LoadProfile(clientStore, proxyAddr); err != nil {
return nil, trace.Wrap(err)
}
Expand Down Expand Up @@ -106,7 +112,7 @@ func LoadConfigFromProfile(ccf *GlobalCLIFlags, cfg *servicecfg.Config) (*authcl
if err != nil {
return nil, trace.Wrap(err)
}
log.Debugf("Setting auth server to web proxy %v.", webProxyAddr)
slog.DebugContext(ctx, "Setting auth server to web proxy", "web_proxy_addr", webProxyAddr)
cfg.SetAuthServerAddress(*webProxyAddr)
}
authConfig.AuthServers = cfg.AuthServerAddresses()
Expand Down
11 changes: 6 additions & 5 deletions tool/tctl/common/devices.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,14 @@ package common
import (
"context"
"fmt"
"log/slog"
"sort"
"time"

"github.com/alecthomas/kingpin/v2"
"github.com/google/uuid"
"github.com/gravitational/trace"
"github.com/gravitational/trace/trail"
log "github.com/sirupsen/logrus"
"google.golang.org/protobuf/types/known/timestamppb"

devicepb "github.com/gravitational/teleport/api/gen/proto/go/teleport/devicetrust/v1"
Expand Down Expand Up @@ -490,10 +490,11 @@ func (c *canOperateOnCurrentDevice) setCurrentDevice() (bool, error) {

c.osType = cdd.OsType
c.assetTag = cdd.SerialNumber
log.Debugf(
"Running device command against current device: %q/%v",
c.assetTag,
devicetrust.FriendlyOSType(c.osType),
slog.DebugContext(
context.Background(),
"Running device command against current device",
"asset_tag", c.assetTag,
"os_type", devicetrust.FriendlyOSType(c.osType),
)
return true, nil
}
3 changes: 1 addition & 2 deletions tool/tctl/common/loadtest_command.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ import (
"github.com/alecthomas/kingpin/v2"
"github.com/google/uuid"
"github.com/gravitational/trace"
log "github.com/sirupsen/logrus"

"github.com/gravitational/teleport"
auditlogpb "github.com/gravitational/teleport/api/gen/proto/go/teleport/auditlog/v1"
Expand Down Expand Up @@ -186,7 +185,7 @@ func (c *LoadtestCommand) NodeHeartbeats(ctx context.Context, client *authclient
return
}
if err != nil {
log.Debugf("Failed to upsert node: %v", err)
slog.DebugContext(ctx, "Failed to upsert node", "error", err)
select {
case errch <- err:
default:
Expand Down
4 changes: 2 additions & 2 deletions tool/tctl/common/loginrule/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@ import (
"context"
"errors"
"io"
"log/slog"
"os"

"github.com/alecthomas/kingpin/v2"
"github.com/gravitational/trace"
"github.com/sirupsen/logrus"
kyaml "k8s.io/apimachinery/pkg/util/yaml"

"github.com/gravitational/teleport"
Expand Down Expand Up @@ -141,7 +141,7 @@ func (t *testCommand) run(ctx context.Context, c *authclient.Client) error {
}

if len(t.inputResourceFiles) > 0 {
logrus.Debugf("Loaded %d login rule(s) from input resource files", len(loginRules))
slog.DebugContext(ctx, "Loaded login rule(s) from input resource files", "login_rule_count", len(loginRules))
}

traits, err := parseTraitsFile(t.inputTraitsFile)
Expand Down
Loading

0 comments on commit 58abfdb

Please sign in to comment.