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

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

import (
	"context"
	"errors"
	"io"

	"gitlab.com/gitlab-org/gitaly/v14/internal/helper"
	"gitlab.com/gitlab-org/gitaly/v14/internal/middleware/metadatahandler"
	"gitlab.com/gitlab-org/gitaly/v14/internal/praefect/config"
	"gitlab.com/gitlab-org/gitaly/v14/internal/praefect/datastore"
	"gitlab.com/gitlab-org/gitaly/v14/internal/praefect/nodes"
	"gitlab.com/gitlab-org/gitaly/v14/proto/go/gitalypb"
	"gitlab.com/gitlab-org/labkit/correlation"
	"golang.org/x/sync/errgroup"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

var errRepositorySpecificPrimariesUnsupported = status.Error(codes.FailedPrecondition, "`praefect reconcile` should not be used with repository specific primaries enabled. Please enable automatic reconciler instead.")

var errReconciliationInternal = errors.New("internal error(s) occurred during execution")

func (s *Server) validateConsistencyCheckRequest(req *gitalypb.ConsistencyCheckRequest) error {
	if s.conf.Failover.ElectionStrategy == config.ElectionStrategyPerRepository {
		return errRepositorySpecificPrimariesUnsupported
	}

	if req.GetTargetStorage() == "" {
		return status.Error(codes.InvalidArgument, "missing target storage")
	}
	if req.GetVirtualStorage() == "" {
		return status.Error(codes.InvalidArgument, "missing virtual storage")
	}
	if req.GetReferenceStorage() == req.GetTargetStorage() {
		return status.Errorf(
			codes.InvalidArgument,
			"target storage %q cannot match reference storage %q",
			req.GetTargetStorage(), req.GetReferenceStorage(),
		)
	}

	return nil
}

func (s *Server) getNodes(ctx context.Context, req *gitalypb.ConsistencyCheckRequest) (target, reference nodes.Node, _ error) {
	shard, err := s.nodeMgr.GetShard(ctx, req.GetVirtualStorage())
	if err != nil {
		return nil, nil, status.Error(codes.NotFound, err.Error())
	}

	// search for target node amongst all nodes in shard
	for _, n := range append(shard.Secondaries, shard.Primary) {
		if n.GetStorage() == req.GetTargetStorage() {
			target = n
			break
		}
	}
	if target == nil {
		return nil, nil, status.Errorf(
			codes.NotFound,
			"unable to find target storage %q",
			req.GetTargetStorage(),
		)
	}

	// set reference node to default or requested storage
	switch {
	case req.GetReferenceStorage() == "" && req.GetTargetStorage() == shard.Primary.GetStorage():
		return nil, nil, status.Errorf(
			codes.InvalidArgument,
			"target storage %q is same as current primary, must provide alternate reference",
			req.GetTargetStorage(),
		)
	case req.GetReferenceStorage() == "":
		reference = shard.Primary // default
	case req.GetReferenceStorage() != "":
		for _, secondary := range append(shard.Secondaries, shard.Primary) {
			if secondary.GetStorage() == req.GetReferenceStorage() {
				reference = secondary
				break
			}
		}
		if reference == nil {
			return nil, nil, status.Errorf(
				codes.NotFound,
				"unable to find reference storage %q in nodes for shard %q",
				req.GetReferenceStorage(),
				req.GetVirtualStorage(),
			)
		}
	}

	return target, reference, nil
}

func walkRepos(ctx context.Context, walkerQ chan<- string, reference nodes.Node) error {
	defer close(walkerQ)

	iClient := gitalypb.NewInternalGitalyClient(reference.GetConnection())
	req := &gitalypb.WalkReposRequest{
		StorageName: reference.GetStorage(),
	}

	walkStream, err := iClient.WalkRepos(ctx, req)
	if err != nil {
		return err
	}

	for {
		resp, err := walkStream.Recv()
		if err == io.EOF {
			return nil
		}
		if err != nil {
			return err
		}

		select {
		case <-ctx.Done():
			return ctx.Err()
		case walkerQ <- resp.GetRelativePath():
		}
	}
}

func checksumRepo(ctx context.Context, relpath string, node nodes.Node) (string, error) {
	cli := gitalypb.NewRepositoryServiceClient(node.GetConnection())
	resp, err := cli.CalculateChecksum(ctx, &gitalypb.CalculateChecksumRequest{
		Repository: &gitalypb.Repository{
			RelativePath: relpath,
			StorageName:  node.GetStorage(),
		},
	})
	if err != nil {
		return "", err
	}

	return resp.GetChecksum(), nil
}

type checksumResult struct {
	virtualStorage   string
	relativePath     string
	target           string
	reference        string
	targetStorage    string
	referenceStorage string
	errs             []error
}

func checksumRepos(ctx context.Context, relpathQ <-chan string, checksumResultQ chan<- checksumResult, target, reference nodes.Node, virtualStorage string) error {
	defer close(checksumResultQ)

	for {
		var repoRelPath string
		select {
		case <-ctx.Done():
			return ctx.Err()
		case repoPath, ok := <-relpathQ:
			if !ok {
				return nil
			}
			repoRelPath = repoPath
		}

		cs := checksumResult{
			virtualStorage:   virtualStorage,
			relativePath:     repoRelPath,
			targetStorage:    target.GetStorage(),
			referenceStorage: reference.GetStorage(),
		}

		g, gctx := errgroup.WithContext(ctx)

		var targetErr error
		g.Go(func() error {
			cs.target, targetErr = checksumRepo(gctx, repoRelPath, target)
			if status.Code(targetErr) == codes.NotFound {
				// missing repo on target is okay, we need to
				// replicate from reference
				targetErr = nil
				return nil
			}
			return targetErr
		})

		var referenceErr error
		g.Go(func() error {
			cs.reference, referenceErr = checksumRepo(gctx, repoRelPath, reference)
			return referenceErr
		})

		if err := g.Wait(); err != nil {
			// we don't care about err as it is one of the targetErr or referenceErr
			// and we return it back to the caller to make the opeartion execution more verbose
			if targetErr != nil {
				cs.errs = append(cs.errs, targetErr)
			}

			if referenceErr != nil {
				cs.errs = append(cs.errs, referenceErr)
			}
		}

		select {
		case <-ctx.Done():
			return ctx.Err()
		case checksumResultQ <- cs:
		}
	}
}

func scheduleReplication(ctx context.Context, csr checksumResult, q datastore.ReplicationEventQueue, resp *gitalypb.ConsistencyCheckResponse) error {
	event, err := q.Enqueue(ctx, datastore.ReplicationEvent{
		Job: datastore.ReplicationJob{
			Change:            datastore.UpdateRepo,
			VirtualStorage:    csr.virtualStorage,
			RelativePath:      csr.relativePath,
			TargetNodeStorage: csr.targetStorage,
			SourceNodeStorage: csr.referenceStorage,
		},
		Meta: datastore.Params{metadatahandler.CorrelationIDKey: correlation.ExtractFromContext(ctx)},
	})

	if err != nil {
		return err
	}

	resp.ReplJobId = event.ID

	return nil
}

func ensureConsistency(ctx context.Context, disableReconcile bool, checksumResultQ <-chan checksumResult, q datastore.ReplicationEventQueue, stream gitalypb.PraefectInfoService_ConsistencyCheckServer) error {
	var erroneous bool
	for {
		var csr checksumResult
		select {
		case res, ok := <-checksumResultQ:
			if !ok {
				if erroneous {
					return helper.ErrInternal(errReconciliationInternal)
				}
				return nil
			}
			csr = res
		case <-ctx.Done():
			return ctx.Err()
		}

		resp := &gitalypb.ConsistencyCheckResponse{
			RepoRelativePath:  csr.relativePath,
			ReferenceChecksum: csr.reference,
			TargetChecksum:    csr.target,
			ReferenceStorage:  csr.referenceStorage,
		}
		for _, err := range csr.errs {
			resp.Errors = append(resp.Errors, err.Error())
			erroneous = true
		}

		if csr.reference != csr.target && !disableReconcile {
			if err := scheduleReplication(ctx, csr, q, resp); err != nil {
				resp.Errors = append(resp.Errors, err.Error())
				erroneous = true
			}
		}

		if err := stream.Send(resp); err != nil {
			return err
		}
	}
}

func (s *Server) ConsistencyCheck(req *gitalypb.ConsistencyCheckRequest, stream gitalypb.PraefectInfoService_ConsistencyCheckServer) error {
	if err := s.validateConsistencyCheckRequest(req); err != nil {
		return err
	}

	g, ctx := errgroup.WithContext(stream.Context())

	// target is the node we are checking, reference is the node we are
	// checking against (e.g. the primary node)
	target, reference, err := s.getNodes(ctx, req)
	if err != nil {
		return err
	}

	walkerQ := make(chan string)
	checksumResultQ := make(chan checksumResult)

	// the following goroutines form a pipeline where data flows from top
	// to bottom
	g.Go(func() error {
		return walkRepos(ctx, walkerQ, reference)
	})
	g.Go(func() error {
		return checksumRepos(ctx, walkerQ, checksumResultQ, target, reference, req.GetVirtualStorage())
	})
	g.Go(func() error {
		return ensureConsistency(ctx, req.GetDisableReconcilliation(), checksumResultQ, s.queue, stream)
	})

	return g.Wait()
}