Welcome to mirror list, hosted at ThFree Co, Russian Federation.

hooks.go « gitaly-hooks « cmd - gitlab.com/gitlab-org/gitaly.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 3c44b80baf0e10c10d2c31be356782e42747622a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"os"
	"strconv"
	"strings"

	"github.com/golang/protobuf/jsonpb"
	"github.com/sirupsen/logrus"
	gitalyauth "gitlab.com/gitlab-org/gitaly/auth"
	"gitlab.com/gitlab-org/gitaly/client"
	"gitlab.com/gitlab-org/gitaly/internal/command"
	"gitlab.com/gitlab-org/gitaly/internal/gitaly/config"
	"gitlab.com/gitlab-org/gitaly/internal/gitaly/hook"
	gitalylog "gitlab.com/gitlab-org/gitaly/internal/log"
	"gitlab.com/gitlab-org/gitaly/internal/metadata/featureflag"
	"gitlab.com/gitlab-org/gitaly/internal/praefect/metadata"
	"gitlab.com/gitlab-org/gitaly/internal/stream"
	"gitlab.com/gitlab-org/gitaly/proto/go/gitalypb"
	"gitlab.com/gitlab-org/gitaly/streamio"
	"gitlab.com/gitlab-org/labkit/tracing"
	"google.golang.org/grpc"
)

// fixupReftxHook fixes up the subcommand in case case the wrong hook was executed instead of the
// reference-transaction hook. This bug was introduced together with the reference-transaction hook
// in Git v2.28.0. As pre-receive and post-receive don't have any arguments and update has the fully
// qualified reference as first argument, none should ever be invoked with the verbs that the
// reference-transaction hook receives.
func fixupReftxHook(args []string) []string {
	if len(args) != 3 {
		return args
	}

	name := args[1]
	if name != "pre-receive" && name != "post-receive" && name != "update" {
		return args
	}

	arg := args[2]
	if arg != "prepared" && arg != "committed" && arg != "aborted" {
		return args
	}

	return append(
		[]string{args[0], "reference-transaction"},
		args[2:]...,
	)
}

func main() {
	var logger = gitalylog.NewHookLogger()

	if len(os.Args) < 2 {
		logger.Fatalf("requires hook name. args: %v", os.Args)
	}

	fixedArgs := fixupReftxHook(os.Args)

	subCmd := fixedArgs[1]

	if subCmd == "check" {
		logrus.SetLevel(logrus.ErrorLevel)
		if len(fixedArgs) != 3 {
			logger.Fatal(errors.New("no configuration file path provided invoke with: gitaly-hooks check <config_path>"))
		}

		configPath := fixedArgs[2]
		fmt.Print("Checking GitLab API access: ")

		info, err := check(configPath)
		if err != nil {
			fmt.Print("FAIL\n")
			log.Fatal(err)
		}

		fmt.Print("OK\n")
		fmt.Printf("GitLab version: %s\n", info.Version)
		fmt.Printf("GitLab revision: %s\n", info.Revision)
		fmt.Printf("GitLab Api version: %s\n", info.APIVersion)
		fmt.Printf("Redis reachable for GitLab: %t\n", info.RedisReachable)
		fmt.Println("OK")
		os.Exit(0)
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// Since the environment is sanitized at the moment, we're only
	// using this to extract the correlation ID. The finished() call
	// to clean up the tracing will be a NOP here.
	ctx, finished := tracing.ExtractFromEnv(ctx)
	defer finished()

	repository, err := repositoryFromEnv()
	if err != nil {
		logger.Fatalf("error when getting repository: %v", err)
	}

	conn, err := gitalyFromEnv()
	if err != nil {
		logger.Fatalf("error when connecting to gitaly: %v", err)
	}

	hookClient := gitalypb.NewHookServiceClient(conn)

	hookStatus := int32(1)

	switch subCmd {
	case "update":
		args := fixedArgs[2:]
		if len(args) != 3 {
			logger.Fatalf("hook %q expects exactly three arguments", subCmd)
		}
		ref, oldValue, newValue := args[0], args[1], args[2]

		req := &gitalypb.UpdateHookRequest{
			Repository:           repository,
			EnvironmentVariables: glValues(),
			Ref:                  []byte(ref),
			OldValue:             oldValue,
			NewValue:             newValue,
		}

		updateHookStream, err := hookClient.UpdateHook(ctx, req)
		if err != nil {
			logger.Fatalf("error when starting command for %q: %v", subCmd, err)
		}

		if hookStatus, err = stream.Handler(func() (stream.StdoutStderrResponse, error) {
			return updateHookStream.Recv()
		}, noopSender, os.Stdout, os.Stderr); err != nil {
			logger.Fatalf("error when receiving data for %q: %v", subCmd, err)
		}
	case "pre-receive":
		preReceiveHookStream, err := hookClient.PreReceiveHook(ctx)
		if err != nil {
			logger.Fatalf("error when getting preReceiveHookStream client for %q: %v", subCmd, err)
		}

		environment := append(glValues(), gitObjectDirs()...)
		for _, key := range []string{metadata.PraefectEnvKey, metadata.TransactionEnvKey} {
			if value, ok := os.LookupEnv(key); ok {
				env := fmt.Sprintf("%s=%s", key, value)
				environment = append(environment, env)
			}
		}

		if err := preReceiveHookStream.Send(&gitalypb.PreReceiveHookRequest{
			Repository:           repository,
			EnvironmentVariables: environment,
			GitPushOptions:       gitPushOptions(),
		}); err != nil {
			logger.Fatalf("error when sending request for %q: %v", subCmd, err)
		}

		f := sendFunc(streamio.NewWriter(func(p []byte) error {
			return preReceiveHookStream.Send(&gitalypb.PreReceiveHookRequest{Stdin: p})
		}), preReceiveHookStream, os.Stdin)

		if hookStatus, err = stream.Handler(func() (stream.StdoutStderrResponse, error) {
			return preReceiveHookStream.Recv()
		}, f, os.Stdout, os.Stderr); err != nil {
			logger.Fatalf("error when receiving data for %q: %v", subCmd, err)
		}
	case "post-receive":
		postReceiveHookStream, err := hookClient.PostReceiveHook(ctx)
		if err != nil {
			logger.Fatalf("error when getting stream client for %q: %v", subCmd, err)
		}

		environment := glValues()

		for _, key := range []string{metadata.PraefectEnvKey, metadata.TransactionEnvKey} {
			if value, ok := os.LookupEnv(key); ok {
				env := fmt.Sprintf("%s=%s", key, value)
				environment = append(environment, env)
			}
		}

		if err := postReceiveHookStream.Send(&gitalypb.PostReceiveHookRequest{
			Repository:           repository,
			EnvironmentVariables: environment,
			GitPushOptions:       gitPushOptions(),
		}); err != nil {
			logger.Fatalf("error when sending request for %q: %v", subCmd, err)
		}

		f := sendFunc(streamio.NewWriter(func(p []byte) error {
			return postReceiveHookStream.Send(&gitalypb.PostReceiveHookRequest{Stdin: p})
		}), postReceiveHookStream, os.Stdin)

		if hookStatus, err = stream.Handler(func() (stream.StdoutStderrResponse, error) {
			return postReceiveHookStream.Recv()
		}, f, os.Stdout, os.Stderr); err != nil {
			logger.Fatalf("error when receiving data for %q: %v", subCmd, err)
		}
	case "reference-transaction":
		if os.Getenv(featureflag.ReferenceTransactionHookEnvVar) != "true" {
			os.Exit(0)
		}

		if len(fixedArgs) != 3 {
			logger.Fatalf("hook %q is missing required arguments", subCmd)
		}

		var state gitalypb.ReferenceTransactionHookRequest_State
		switch fixedArgs[2] {
		case "prepared":
			state = gitalypb.ReferenceTransactionHookRequest_PREPARED
		case "committed":
			state = gitalypb.ReferenceTransactionHookRequest_COMMITTED
		case "aborted":
			state = gitalypb.ReferenceTransactionHookRequest_ABORTED
		default:
			logger.Fatalf("hook %q has invalid state %s", subCmd, fixedArgs[2])
		}

		referenceTransactionHookStream, err := hookClient.ReferenceTransactionHook(ctx)
		if err != nil {
			logger.Fatalf("error when getting referenceTransactionHookStream client for %q: %v", subCmd, err)
		}

		environment := glValues()

		for _, key := range []string{metadata.PraefectEnvKey, metadata.TransactionEnvKey} {
			if value, ok := os.LookupEnv(key); ok {
				env := fmt.Sprintf("%s=%s", key, value)
				environment = append(environment, env)
			}
		}

		if err := referenceTransactionHookStream.Send(&gitalypb.ReferenceTransactionHookRequest{
			Repository:           repository,
			EnvironmentVariables: environment,
			State:                state,
		}); err != nil {
			logger.Fatalf("error when sending request for %q: %v", subCmd, err)
		}

		f := sendFunc(streamio.NewWriter(func(p []byte) error {
			return referenceTransactionHookStream.Send(&gitalypb.ReferenceTransactionHookRequest{Stdin: p})
		}), referenceTransactionHookStream, os.Stdin)

		if hookStatus, err = stream.Handler(func() (stream.StdoutStderrResponse, error) {
			return referenceTransactionHookStream.Recv()
		}, f, os.Stdout, os.Stderr); err != nil {
			logger.Fatalf("error when receiving data for %q: %v", subCmd, err)
		}
	default:
		logger.Fatalf("subcommand name invalid: %q", subCmd)
	}

	os.Exit(int(hookStatus))
}

func noopSender(c chan error) {}

func repositoryFromEnv() (*gitalypb.Repository, error) {
	repoString, ok := os.LookupEnv("GITALY_REPO")
	if !ok {
		return nil, errors.New("GITALY_REPO not found")
	}

	var repo gitalypb.Repository
	if err := jsonpb.UnmarshalString(repoString, &repo); err != nil {
		return nil, fmt.Errorf("unmarshal JSON %q: %w", repoString, err)
	}

	return &repo, nil
}

func gitalyFromEnv() (*grpc.ClientConn, error) {
	gitalySocket := os.Getenv("GITALY_SOCKET")
	if gitalySocket == "" {
		return nil, errors.New("GITALY_SOCKET not set")
	}

	gitalyToken, ok := os.LookupEnv("GITALY_TOKEN")
	if !ok {
		return nil, errors.New("GITALY_TOKEN not set")
	}

	dialOpts := client.DefaultDialOpts
	if gitalyToken != "" {
		dialOpts = append(dialOpts, grpc.WithPerRPCCredentials(gitalyauth.RPCCredentialsV2(gitalyToken)))
	}

	conn, err := client.Dial("unix://"+gitalySocket, dialOpts)
	if err != nil {
		return nil, fmt.Errorf("error when dialing: %w", err)
	}

	return conn, nil
}

func glValues() []string {
	glEnvVars := command.AllowedEnvironment()

	for _, kv := range os.Environ() {
		if strings.HasPrefix(kv, "GL_") {
			glEnvVars = append(glEnvVars, kv)
		}
	}

	return glEnvVars
}

func gitObjectDirs() []string {
	var objectDirs []string
	gitObjectDirectory, ok := os.LookupEnv("GIT_OBJECT_DIRECTORY")
	if ok {
		objectDirs = append(objectDirs, "GIT_OBJECT_DIRECTORY="+gitObjectDirectory)
	}
	gitAlternateObjectDirectories, ok := os.LookupEnv("GIT_ALTERNATE_OBJECT_DIRECTORIES")
	if ok {
		objectDirs = append(objectDirs, "GIT_ALTERNATE_OBJECT_DIRECTORIES="+gitAlternateObjectDirectories)
	}

	return objectDirs
}

func gitPushOptions() []string {
	var gitPushOptions []string

	gitPushOptionCount, err := strconv.Atoi(os.Getenv("GIT_PUSH_OPTION_COUNT"))
	if err != nil {
		return gitPushOptions
	}

	for i := 0; i < gitPushOptionCount; i++ {
		gitPushOptions = append(gitPushOptions, os.Getenv(fmt.Sprintf("GIT_PUSH_OPTION_%d", i)))
	}

	return gitPushOptions
}

func sendFunc(reqWriter io.Writer, stream grpc.ClientStream, stdin io.Reader) func(errC chan error) {
	return func(errC chan error) {
		_, errSend := io.Copy(reqWriter, stdin)
		stream.CloseSend()
		errC <- errSend
	}
}

func check(configPath string) (*hook.CheckInfo, error) {
	cfgFile, err := os.Open(configPath)
	if err != nil {
		return nil, fmt.Errorf("failed to open config file: %w", err)
	}
	defer cfgFile.Close()

	if err := config.Load(cfgFile); err != nil {
		return nil, err
	}

	gitlabAPI, err := hook.NewGitlabAPI(config.Config.Gitlab)
	if err != nil {
		return nil, err
	}

	return hook.NewManager(gitlabAPI, config.Config).Check(context.TODO())
}