Skip to content

Commit 0998fcd

Browse files
Igor Drozdove_forbes
authored andcommitted
Merge branch 'ef-migrate-all-callsites-to-slog' into 'main'
Migrate all Logs to LabKit v2 See merge request https://gitlab.com/gitlab-org/gitlab-shell/-/merge_requests/1381 Merged-by: Igor Drozdov <idrozdov@gitlab.com> Approved-by: Igor Drozdov <idrozdov@gitlab.com> Reviewed-by: Vasilii Iakliushin <viakliushin@gitlab.com> Co-authored-by: e_forbes <eforbes@gitlab.com>
2 parents 2399e1d + 8c2ea2a commit 0998fcd

29 files changed

Lines changed: 229 additions & 398 deletions

File tree

.gitlab-ci.yml

Lines changed: 1 addition & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -75,29 +75,15 @@ default:
7575
paths:
7676
- .GOPATH/pkg/mod/
7777

78-
.cached-ruby: &cached_ruby
79-
- key:
80-
prefix: "ruby-${RUBY_VERSION}-cache"
81-
files:
82-
- Gemfile.lock
83-
policy: $POLICY
84-
paths:
85-
- ${BUNDLE_PATH}
86-
8778
.cached-go-job:
8879
variables:
8980
CACHE_COMPRESSION_LEVEL: "fastest"
9081
cache:
9182
- *cached_go
9283

93-
.cached-ruby-job:
94-
cache:
95-
- *cached_ruby
96-
9784
.cached-job:
9885
cache:
9986
- *cached_go
100-
- *cached_ruby
10187

10288
.go-matrix-job:
10389
parallel:
@@ -108,14 +94,6 @@ default:
10894
# Prepare jobs
10995
################################################################################
11096

111-
bundle:install:
112-
stage: prepare
113-
extends: .cached-ruby-job
114-
variables:
115-
POLICY: pull-push
116-
script:
117-
- bundle install --jobs $(nproc)
118-
11997
modules:download:
12098
stage: prepare
12199
extends:
@@ -131,7 +109,7 @@ modules:download:
131109
################################################################################
132110

133111
.test-job:
134-
needs: ["bundle:install", "modules:download"]
112+
needs: ["modules:download"]
135113
rules: !reference [".rules:go-changes", rules]
136114
variables:
137115
GITALY_CONNECTION_INFO: '{"address":"tcp://gitaly:8075", "storage":"default"}'
@@ -140,7 +118,6 @@ modules:download:
140118
- make build
141119
- cp config.yml.example config.yml
142120
- go version
143-
- which go
144121
services:
145122
- name: registry.gitlab.com/gitlab-org/build/cng/gitaly:master
146123
# Disable the hooks so we don't have to stub the GitLab API

Makefile

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
.PHONY: validate verify verify_ruby verify_golang test test_fancy coverage coverage_golang setup _script_install make_necessary_dirs build compile check clean install lint
1+
.PHONY: validate verify test test_fancy coverage setup make_necessary_dirs build compile check clean install lint
22

33
FIPS_MODE ?= 0
44
OS := $(shell uname | tr A-Z a-z)
@@ -67,14 +67,14 @@ test:
6767

6868
test_fancy: ${GOTESTSUM_FILE}
6969
@${GOTESTSUM_FILE} --version
70-
@${GOTESTSUM_FILE} --junitfile ./cover.xml --format pkgname -- -coverprofile=./cover.out -covermode=atomic -count 1 -tags "$(GO_TAGS)" ./...
70+
@${GOTESTSUM_FILE} --junitfile ./cover.xml --format pkgname -- -coverprofile=./cover.out -covermode=atomic -timeout 1m -count 1 -tags "$(GO_TAGS)" ./...
7171

7272
${GOTESTSUM_FILE}:
7373
mkdir -p $(shell dirname ${GOTESTSUM_FILE})
7474
curl -L https://github.com/gotestyourself/gotestsum/releases/download/v${GOTESTSUM_VERSION}/gotestsum_${GOTESTSUM_VERSION}_${OS}_${ARCH}.tar.gz | tar -zOxf - gotestsum > ${GOTESTSUM_FILE} && chmod +x ${GOTESTSUM_FILE}
7575

7676
test_race:
77-
go test -race -count 1 ./...
77+
go test -race -timeout 1m -count 1 ./... -v
7878

7979
coverage:
8080
[ -f cover.out ] && go tool cover -func cover.out

client/transport.go

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,14 @@
22
package client
33

44
import (
5+
"log/slog"
56
"net/http"
67
"time"
78

89
"gitlab.com/gitlab-org/labkit/correlation"
9-
"gitlab.com/gitlab-org/labkit/log"
10+
"gitlab.com/gitlab-org/labkit/fields"
1011
"gitlab.com/gitlab-org/labkit/tracing"
12+
"gitlab.com/gitlab-org/labkit/v2/log"
1113
)
1214

1315
type transport struct {
@@ -28,32 +30,27 @@ func (rt *transport) RoundTrip(request *http.Request) (*http.Response, error) {
2830
start := time.Now()
2931

3032
response, err := rt.next.RoundTrip(request)
31-
32-
fields := log.Fields{
33-
"method": request.Method,
34-
"url": request.URL.String(),
35-
"duration_ms": time.Since(start) / time.Millisecond,
36-
}
37-
logger := log.WithContextFields(ctx, fields)
38-
33+
ctx = log.WithFields(ctx,
34+
slog.String("method", request.Method),
35+
slog.String("url", request.URL.String()),
36+
slog.Float64("duration_s", time.Since(start).Seconds()),
37+
)
3938
if err != nil {
40-
logger.WithError(err).Error("Internal API unreachable")
39+
slog.ErrorContext(ctx, "Internal API unreachable", slog.String(fields.ErrorMessage, err.Error()))
4140
return response, err
4241
}
4342

44-
logger = logger.WithField("status", response.StatusCode)
43+
ctx = log.WithFields(ctx, slog.Int("status", response.StatusCode))
4544

4645
if response.StatusCode >= 400 {
47-
logger.WithError(err).Error("Internal API error")
46+
slog.ErrorContext(ctx, "Internal API error")
4847
return response, err
4948
}
5049

5150
if response.ContentLength >= 0 {
52-
logger = logger.WithField("content_length_bytes", response.ContentLength)
51+
ctx = log.WithFields(ctx, slog.Int64("content_length_bytes", response.ContentLength))
5352
}
54-
55-
logger.Info("Finished HTTP request")
56-
53+
slog.InfoContext(ctx, "Finished HTTP request")
5754
return response, nil
5855
}
5956

cmd/gitlab-shell/main.go

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,15 @@ package main
33

44
import (
55
"fmt"
6+
"log/slog"
67
"os"
78
"reflect"
89

910
grpccodes "google.golang.org/grpc/codes"
1011
grpcstatus "google.golang.org/grpc/status"
1112

13+
"gitlab.com/gitlab-org/labkit/fields"
1214
"gitlab.com/gitlab-org/labkit/fips"
13-
"gitlab.com/gitlab-org/labkit/log"
1415

1516
shellCmd "gitlab.com/gitlab-org/gitlab-shell/v14/cmd/gitlab-shell/command"
1617
"gitlab.com/gitlab-org/gitlab-shell/v14/internal/command"
@@ -29,7 +30,7 @@ var (
2930
BuildTime = "19700101.000000" // Set at build time in the Makefile
3031
)
3132

32-
func main() {
33+
func run() int {
3334
command.CheckForVersionFlag(os.Args, Version, BuildTime)
3435

3536
readWriter := &readwriter.ReadWriter{
@@ -41,47 +42,51 @@ func main() {
4142
executable, err := executable.New(executable.GitlabShell)
4243
if err != nil {
4344
_, _ = fmt.Fprintln(readWriter.ErrOut, "Failed to determine executable, exiting")
44-
os.Exit(1)
45+
return 1
4546
}
4647

4748
config, err := config.NewFromDirExternal(executable.RootDir)
4849
if err != nil {
4950
_, _ = fmt.Fprintln(readWriter.ErrOut, "Failed to read config, exiting:", err)
50-
os.Exit(1)
51+
return 1
5152
}
5253

53-
logCloser := logger.Configure(config)
54+
logCloser := logger.ConfigureLogger(config)
55+
if logCloser != nil {
56+
defer logCloser.Close() //nolint:errcheck
57+
}
5458

5559
env := sshenv.NewFromEnv()
5660
cmd, err := shellCmd.New(os.Args[1:], env, config, readWriter)
5761
if err != nil {
5862
// For now this could happen if `SSH_CONNECTION` is not set on
5963
// the environment
6064
_, _ = fmt.Fprintf(readWriter.ErrOut, "%v\n", err)
61-
_ = logCloser.Close()
62-
os.Exit(1)
65+
return 1
6366
}
6467

6568
ctx, finished := command.Setup(executable.Name, config)
6669

6770
config.GitalyClient.InitSidechannelRegistry(ctx)
6871

6972
cmdName := reflect.TypeOf(cmd).String()
70-
ctxlog := log.ContextLogger(ctx)
71-
ctxlog.WithFields(log.Fields{"env": env, "command": cmdName}).Info("gitlab-shell: main: executing command")
73+
slog.InfoContext(ctx, "gitlab-shell: main: executing command", slog.Any("env", env), slog.String("command", cmdName))
7274
fips.Check()
7375

7476
if _, err := cmd.Execute(ctx); err != nil {
75-
ctxlog.WithError(err).Warn("gitlab-shell: main: command execution failed")
77+
slog.WarnContext(ctx, "gitlab-shell: main: command execution failed", slog.String(fields.ErrorMessage, err.Error()))
7678
if grpcstatus.Convert(err).Code() != grpccodes.Internal {
7779
console.DisplayWarningMessage(err.Error(), readWriter.ErrOut)
7880
}
7981
finished()
80-
_ = logCloser.Close()
81-
os.Exit(1)
82+
return 1
8283
}
8384

84-
ctxlog.Info("gitlab-shell: main: command executed successfully")
85+
slog.InfoContext(ctx, "gitlab-shell: main: command executed successfully")
8586
finished()
86-
_ = logCloser.Close()
87+
return 0
88+
}
89+
90+
func main() {
91+
os.Exit(run())
8792
}

cmd/gitlab-sshd/acceptance_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -325,7 +325,7 @@ func startSSHD(t *testing.T, dir string) string {
325325
t.Cleanup(func() { pw.Close() })
326326

327327
scanner := bufio.NewScanner(pr)
328-
extractor := regexp.MustCompile(`tcp_address="([0-9a-f\[\]\.:]+)"`)
328+
extractor := regexp.MustCompile(`tcp_address"?[=:]"?([0-9a-f\[\]\.:]+)"?`)
329329

330330
ctx, cancel := context.WithCancel(context.Background())
331331
cmd := exec.CommandContext(ctx, sshdPath, "-config-dir", dir)

config.yml.example

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ auth_file: "/home/git/.ssh/authorized_keys"
5151
log_level: INFO
5252

5353
# Log format. 'json' by default, can be changed to 'text' if needed
54-
# log_format: json
54+
log_format: text
5555

5656
# Audit usernames.
5757
# Set to true to see real usernames in the logs instead of key ids, which is easier to follow, but

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ require (
1414
github.com/otiai10/copy v1.14.1
1515
github.com/pires/go-proxyproto v0.8.0
1616
github.com/prometheus/client_golang v1.23.2
17-
github.com/sirupsen/logrus v1.9.4
1817
github.com/stretchr/testify v1.11.1
1918
gitlab.com/gitlab-org/cells/topology-service v0.0.0-20260213143839-af4593cd7194
2019
gitlab.com/gitlab-org/gitaly/v18 v18.9.0-rc4
@@ -89,6 +88,7 @@ require (
8988
github.com/sebest/xff v0.0.0-20210106013422-671bd2870b3a // indirect
9089
github.com/shirou/gopsutil/v3 v3.24.5 // indirect
9190
github.com/shoenig/go-m1cpu v0.1.6 // indirect
91+
github.com/sirupsen/logrus v1.9.4 // indirect
9292
github.com/tinylib/msgp v1.3.0 // indirect
9393
github.com/tklauser/go-sysconf v0.3.15 // indirect
9494
github.com/tklauser/numcpus v0.10.0 // indirect

internal/command/authorizedkeys/authorized_keys.go

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,9 @@ package authorizedkeys
44
import (
55
"context"
66
"fmt"
7+
"log/slog"
78
"strconv"
89

9-
"gitlab.com/gitlab-org/labkit/log"
10-
1110
"gitlab.com/gitlab-org/gitlab-shell/v14/internal/command/commandargs"
1211
"gitlab.com/gitlab-org/gitlab-shell/v14/internal/command/readwriter"
1312
"gitlab.com/gitlab-org/gitlab-shell/v14/internal/config"
@@ -28,10 +27,10 @@ func (c *Command) Execute(ctx context.Context) (context.Context, error) {
2827
// This can happen when the user in sshd_config doesn't match the user
2928
// trying to login. When nothing is printed, the user will be denied access.
3029
if c.Args.ExpectedUser != c.Args.ActualUser {
31-
log.ContextLogger(ctx).WithFields(log.Fields{
32-
"expected_user": c.Args.ExpectedUser,
33-
"actual_user": c.Args.ActualUser,
34-
}).Warn("authorized_keys: user mismatch, denying access")
30+
slog.WarnContext(ctx, "authorized_keys: user mismatch, denying access",
31+
slog.String("expected_user", c.Args.ExpectedUser),
32+
slog.String("actual_user", c.Args.ActualUser),
33+
)
3534
return ctx, nil
3635
}
3736

internal/command/gitauditevent/audit.go

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,35 +3,37 @@ package gitauditevent
33

44
import (
55
"context"
6+
"fmt"
7+
"log/slog"
68

79
pb "gitlab.com/gitlab-org/gitaly/v18/proto/go/gitalypb"
810
"gitlab.com/gitlab-org/gitlab-shell/v14/internal/command/commandargs"
911
"gitlab.com/gitlab-org/gitlab-shell/v14/internal/command/shared/accessverifier"
1012
"gitlab.com/gitlab-org/gitlab-shell/v14/internal/config"
1113
"gitlab.com/gitlab-org/gitlab-shell/v14/internal/gitlabnet/gitauditevent"
12-
"gitlab.com/gitlab-org/labkit/log"
14+
"gitlab.com/gitlab-org/labkit/v2/log"
1315
)
1416

1517
// Audit is called conditionally during `git-receive-pack` and `git-upload-pack` to generate streaming audit events.
1618
// Errors are not propagated since this is more a logging process.
1719
func Audit(ctx context.Context, args *commandargs.Shell, c *config.Config, response *accessverifier.Response, packfileStats *pb.PackfileNegotiationStatistics) {
18-
ctxlog := log.WithContextFields(ctx, log.Fields{
19-
"gl_repository": response.Repo,
20-
"command": args.CommandType,
21-
"username": response.Username,
22-
})
20+
ctx = log.WithFields(ctx,
21+
slog.String("gl_repository", response.Repo),
22+
slog.Any("command", args.CommandType),
23+
slog.String("username", response.Username),
24+
)
2325

24-
ctxlog.Debug("sending git audit event")
26+
slog.DebugContext(ctx, "sending git audit event")
2527

2628
gitAuditClient, errOnlyLog := gitauditevent.NewClient(c)
2729
if errOnlyLog != nil {
28-
ctxlog.Errorf("failed to create gitauditevent client: %v", errOnlyLog)
30+
slog.ErrorContext(ctx, fmt.Sprintf("failed to create gitauditevent client: %v", errOnlyLog))
2931
return
3032
}
3133

3234
errOnlyLog = gitAuditClient.Audit(ctx, response.Username, args, response.Repo, packfileStats)
3335
if errOnlyLog != nil {
34-
ctxlog.Errorf("failed to audit git event: %v", errOnlyLog)
36+
slog.ErrorContext(ctx, fmt.Sprintf("failed to audit git event: %v", errOnlyLog))
3537
return
3638
}
3739
}

internal/command/githttp/pull.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,15 @@ package githttp
77
import (
88
"context"
99
"io"
10+
"log/slog"
1011

1112
"gitlab.com/gitlab-org/gitlab-shell/v14/internal/command/commandargs"
1213
"gitlab.com/gitlab-org/gitlab-shell/v14/internal/command/readwriter"
1314
"gitlab.com/gitlab-org/gitlab-shell/v14/internal/config"
1415
"gitlab.com/gitlab-org/gitlab-shell/v14/internal/gitlabnet/accessverifier"
1516
"gitlab.com/gitlab-org/gitlab-shell/v14/internal/gitlabnet/git"
1617
"gitlab.com/gitlab-org/gitlab-shell/v14/internal/pktline"
17-
"gitlab.com/gitlab-org/labkit/log"
18+
"gitlab.com/gitlab-org/labkit/fields"
1819
)
1920

2021
const pullService = "git-upload-pack"
@@ -63,7 +64,7 @@ func (c *PullCommand) Execute(ctx context.Context) error {
6364
}
6465

6566
func (c *PullCommand) requestSSHUploadPack(ctx context.Context, client *git.Client) error {
66-
log.ContextLogger(ctx).Info("Using Git over SSH upload pack")
67+
slog.InfoContext(ctx, "Using Git over SSH upload pack")
6768

6869
return executeSSHRequest(ctx, client.SSHUploadPack, c.ReadWriter)
6970
}
@@ -91,7 +92,7 @@ func (c *PullCommand) readFromStdin(pw *io.PipeWriter) {
9192

9293
_, err := pw.Write(line)
9394
if err != nil {
94-
log.WithError(err).Error("failed to write line")
95+
slog.Error("failed to write line", slog.String(fields.ErrorMessage, err.Error()))
9596
}
9697

9798
if pktline.IsDone(line) {
@@ -101,6 +102,6 @@ func (c *PullCommand) readFromStdin(pw *io.PipeWriter) {
101102

102103
err := pw.Close()
103104
if err != nil {
104-
log.WithError(err).Error("failed to close writer")
105+
slog.Error("failed to close writer", slog.String(fields.ErrorMessage, err.Error()))
105106
}
106107
}

0 commit comments

Comments
 (0)