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

fetch_remote.go « repository « service « gitaly « internal - gitlab.com/gitlab-org/gitaly.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 285107ed30b1b890c8658fae84d38c385f8d2aef (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
package repository

import (
	"bytes"
	"context"
	"fmt"
	"io"
	"time"

	gitalyerrors "gitlab.com/gitlab-org/gitaly/v14/internal/errors"
	"gitlab.com/gitlab-org/gitaly/v14/internal/git"
	"gitlab.com/gitlab-org/gitaly/v14/internal/git/localrepo"
	"gitlab.com/gitlab-org/gitaly/v14/internal/gitaly/transaction"
	"gitlab.com/gitlab-org/gitaly/v14/internal/helper"
	"gitlab.com/gitlab-org/gitaly/v14/internal/transaction/txinfo"
	"gitlab.com/gitlab-org/gitaly/v14/internal/transaction/voting"
	"gitlab.com/gitlab-org/gitaly/v14/proto/go/gitalypb"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

func (s *server) FetchRemote(ctx context.Context, req *gitalypb.FetchRemoteRequest) (*gitalypb.FetchRemoteResponse, error) {
	if err := s.validateFetchRemoteRequest(req); err != nil {
		return nil, err
	}

	var stderr bytes.Buffer
	opts := localrepo.FetchOpts{
		Stderr:              &stderr,
		Force:               req.Force,
		Prune:               !req.NoPrune,
		Tags:                localrepo.FetchOptsTagsAll,
		Verbose:             req.GetCheckTagsChanged(),
		DisableTransactions: true,
	}

	if req.GetNoTags() {
		opts.Tags = localrepo.FetchOptsTagsNone
	}

	repo := s.localrepo(req.GetRepository())
	remoteName := "inmemory"
	remoteURL := req.GetRemoteParams().GetUrl()

	config := []git.ConfigPair{
		{Key: "remote.inmemory.url", Value: remoteURL},
	}

	for _, refspec := range s.getRefspecs(req.GetRemoteParams().GetMirrorRefmaps()) {
		config = append(config, git.ConfigPair{
			Key: "remote.inmemory.fetch", Value: refspec,
		})
	}

	if authHeader := req.GetRemoteParams().GetHttpAuthorizationHeader(); authHeader != "" {
		config = append(config, git.ConfigPair{
			Key:   fmt.Sprintf("http.%s.extraHeader", remoteURL),
			Value: "Authorization: " + authHeader,
		})
	}
	if host := req.GetRemoteParams().GetHttpHost(); host != "" {
		config = append(config, git.ConfigPair{
			Key:   fmt.Sprintf("http.%s.extraHeader", remoteURL),
			Value: "Host: " + host,
		})
	}

	opts.CommandOptions = append(opts.CommandOptions, git.WithConfigEnv(config...))

	sshCommand, cleanup, err := git.BuildSSHInvocation(ctx, req.GetSshKey(), req.GetKnownHosts())
	if err != nil {
		return nil, err
	}
	defer cleanup()

	opts.Env = append(opts.Env, "GIT_SSH_COMMAND="+sshCommand)

	if req.GetTimeout() > 0 {
		var cancel context.CancelFunc
		ctx, cancel = context.WithTimeout(ctx, time.Duration(req.GetTimeout())*time.Second)
		defer cancel()
	}

	if err := repo.FetchRemote(ctx, remoteName, opts); err != nil {
		if _, ok := status.FromError(err); ok {
			// this check is used because of internal call to alternates.PathAndEnv
			// which may return gRPC status as an error result
			return nil, err
		}

		errMsg := stderr.String()
		if errMsg != "" {
			return nil, fmt.Errorf("fetch remote: %q: %w", errMsg, err)
		}

		return nil, fmt.Errorf("fetch remote: %w", err)
	}

	// Ideally, we'd do the voting process via git-fetch(1) using the reference-transaction
	// hook. But by default this would lead to one hook invocation per updated ref, which is
	// infeasible performance-wise. While this could be fixed via the `--atomic` flag, that's
	// not a solution either: we rely on the fact that refs get updated even if a subset of refs
	// diverged, and with atomic transactions it would instead be an all-or-nothing operation.
	//
	// Instead, we do the second-best thing, which is to vote on the resulting references. This
	// is of course racy and may conflict with other mutators, causing the vote to fail. But it
	// is arguably preferable to accept races in favour always replicating. If loosing the race,
	// we'd fail this RPC and schedule a replication job afterwards.
	if err := transaction.RunOnContext(ctx, func(tx txinfo.Transaction) error {
		hash := voting.NewVoteHash()

		if err := repo.ExecAndWait(ctx, git.SubCmd{
			Name: "for-each-ref",
		}, git.WithStdout(hash)); err != nil {
			return fmt.Errorf("cannot compute references vote: %w", err)
		}

		vote, err := hash.Vote()
		if err != nil {
			return err
		}

		return s.txManager.Vote(ctx, tx, vote, voting.UnknownPhase)
	}); err != nil {
		return nil, status.Errorf(codes.Aborted, "failed vote on refs: %v", err)
	}

	out := &gitalypb.FetchRemoteResponse{TagsChanged: true}
	if req.GetCheckTagsChanged() {
		out.TagsChanged = didTagsChange(&stderr)
	}

	return out, nil
}

func didTagsChange(r io.Reader) bool {
	scanner := git.NewFetchScanner(r)
	for scanner.Scan() {
		status := scanner.StatusLine()

		// We can't detect if tags have been deleted, but we never call fetch
		// with --prune-tags at the moment, so it should never happen.
		if status.IsTagAdded() || status.IsTagUpdated() {
			return true
		}
	}

	// If the scanner fails for some reason, we don't know if tags changed, so
	// assume they did for safety reasons.
	return scanner.Err() != nil
}

func (s *server) validateFetchRemoteRequest(req *gitalypb.FetchRemoteRequest) error {
	if req.GetRepository() == nil {
		return helper.ErrInvalidArgument(gitalyerrors.ErrEmptyRepository)
	}

	if req.GetRemoteParams() == nil {
		return helper.ErrInvalidArgumentf("missing remote params")
	}

	if req.GetRemoteParams().GetUrl() == "" {
		return helper.ErrInvalidArgumentf("blank or empty remote URL")
	}

	return nil
}

func (s *server) getRefspecs(refmaps []string) []string {
	if len(refmaps) == 0 {
		return []string{"refs/*:refs/*"}
	}

	refspecs := make([]string, 0, len(refmaps))

	for _, refmap := range refmaps {
		switch refmap {
		case "all_refs":
			// with `all_refs`, the repository is equivalent to the result of `git clone --mirror`
			refspecs = append(refspecs, "refs/*:refs/*")
		case "heads":
			refspecs = append(refspecs, "refs/heads/*:refs/heads/*")
		case "tags":
			refspecs = append(refspecs, "refs/tags/*:refs/tags/*")
		default:
			refspecs = append(refspecs, refmap)
		}
	}
	return refspecs
}