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

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

import (
	"context"
	"errors"
	"fmt"
	"strings"
	"sync"

	"github.com/sirupsen/logrus"
	"gitlab.com/gitlab-org/gitaly/v14/internal/gitaly/storage"
	"gitlab.com/gitlab-org/gitaly/v14/proto/go/gitalypb"
)

// Strategy used to create/restore backups
type Strategy interface {
	Create(context.Context, *CreateRequest) error
	Restore(context.Context, *RestoreRequest) error
}

// Command handles a specific backup operation
type Command interface {
	Repository() *gitalypb.Repository
	Name() string
	Execute(context.Context) error
}

// Pipeline executes a series of commands and encapsulates error handling for
// the caller.
type Pipeline interface {
	Handle(context.Context, Command)
	Done() error
}

// CreateCommand creates a backup for a repository
type CreateCommand struct {
	strategy    Strategy
	server      storage.ServerInfo
	repository  *gitalypb.Repository
	incremental bool
}

// NewCreateCommand builds a CreateCommand
func NewCreateCommand(strategy Strategy, server storage.ServerInfo, repo *gitalypb.Repository, incremental bool) *CreateCommand {
	return &CreateCommand{
		strategy:    strategy,
		server:      server,
		repository:  repo,
		incremental: incremental,
	}
}

// Repository is the repository that will be acted on
func (cmd CreateCommand) Repository() *gitalypb.Repository {
	return cmd.repository
}

// Name is the name of the command
func (cmd CreateCommand) Name() string {
	return "create"
}

// Execute performs the backup
func (cmd CreateCommand) Execute(ctx context.Context) error {
	return cmd.strategy.Create(ctx, &CreateRequest{
		Server:      cmd.server,
		Repository:  cmd.repository,
		Incremental: cmd.incremental,
	})
}

// RestoreCommand restores a backup for a repository
type RestoreCommand struct {
	strategy     Strategy
	server       storage.ServerInfo
	repository   *gitalypb.Repository
	alwaysCreate bool
}

// NewRestoreCommand builds a RestoreCommand
func NewRestoreCommand(strategy Strategy, server storage.ServerInfo, repo *gitalypb.Repository, alwaysCreate bool) *RestoreCommand {
	return &RestoreCommand{
		strategy:     strategy,
		server:       server,
		repository:   repo,
		alwaysCreate: alwaysCreate,
	}
}

// Repository is the repository that will be acted on
func (cmd RestoreCommand) Repository() *gitalypb.Repository {
	return cmd.repository
}

// Name is the name of the command
func (cmd RestoreCommand) Name() string {
	return "restore"
}

// Execute performs the restore
func (cmd RestoreCommand) Execute(ctx context.Context) error {
	return cmd.strategy.Restore(ctx, &RestoreRequest{
		Server:       cmd.server,
		Repository:   cmd.repository,
		AlwaysCreate: cmd.alwaysCreate,
	})
}

// PipelineError represents a summary of errors by repository
type PipelineError []error

// AddError adds an error associated with a repository to the summary.
func (e *PipelineError) AddError(repo *gitalypb.Repository, err error) {
	if repo.GetGlProjectPath() != "" {
		err = fmt.Errorf("%s (%s): %w", repo.GetRelativePath(), repo.GetGlProjectPath(), err)
	} else {
		err = fmt.Errorf("%s: %w", repo.GetRelativePath(), err)
	}
	*e = append(*e, err)
}

func (e PipelineError) Error() string {
	var builder strings.Builder
	_, _ = fmt.Fprintf(&builder, "%d failures encountered:\n", len(e))
	for _, err := range e {
		_, _ = fmt.Fprintf(&builder, " - %s\n", err.Error())
	}
	return builder.String()
}

// LoggingPipeline outputs logging for each command executed
type LoggingPipeline struct {
	log logrus.FieldLogger

	mu   sync.Mutex
	errs PipelineError
}

// NewLoggingPipeline creates a new logging pipeline
func NewLoggingPipeline(log logrus.FieldLogger) *LoggingPipeline {
	return &LoggingPipeline{
		log: log,
	}
}

// Handle takes a command to process. Commands are logged and executed immediately.
func (p *LoggingPipeline) Handle(ctx context.Context, cmd Command) {
	log := p.cmdLogger(cmd)
	log.Infof("started %s", cmd.Name())

	if err := cmd.Execute(ctx); err != nil {
		if errors.Is(err, ErrSkipped) {
			log.WithError(err).Warnf("skipped %s", cmd.Name())
		} else {
			log.WithError(err).Errorf("%s failed", cmd.Name())
			p.addError(cmd.Repository(), err)
		}
		return
	}

	log.Infof("completed %s", cmd.Name())
}

func (p *LoggingPipeline) addError(repo *gitalypb.Repository, err error) {
	p.mu.Lock()
	defer p.mu.Unlock()

	p.errs.AddError(repo, err)
}

// Done indicates that the pipeline is complete and returns any accumulated errors
func (p *LoggingPipeline) Done() error {
	if len(p.errs) > 0 {
		return fmt.Errorf("pipeline: %w", p.errs)
	}
	return nil
}

func (p *LoggingPipeline) cmdLogger(cmd Command) logrus.FieldLogger {
	return p.log.WithFields(logrus.Fields{
		"command":         cmd.Name(),
		"storage_name":    cmd.Repository().StorageName,
		"relative_path":   cmd.Repository().RelativePath,
		"gl_project_path": cmd.Repository().GlProjectPath,
	})
}

type contextCommand struct {
	Command Command
	Context context.Context
}

// ParallelPipeline is a pipeline that executes commands in parallel
type ParallelPipeline struct {
	next            Pipeline
	parallel        int
	parallelStorage int

	wg          sync.WaitGroup
	workerSlots chan struct{}
	done        chan struct{}

	mu       sync.Mutex
	requests map[string]chan *contextCommand
	err      error
}

// NewParallelPipeline creates a new ParallelPipeline where all commands are
// passed onto `next` to be processed, `parallel` is the maximum number of
// parallel backups that will run and `parallelStorage` is the maximum number
// of parallel backups that will run per storage. Since the number of storages
// is unknown at initialisation, workers are created lazily as new storage
// names are encountered.
//
// Note: When both `parallel` and `parallelStorage` are zero or less no workers
// are created and the pipeline will block forever.
func NewParallelPipeline(next Pipeline, parallel, parallelStorage int) *ParallelPipeline {
	var workerSlots chan struct{}
	if parallel > 0 && parallelStorage > 0 {
		// workerSlots allows the total number of parallel jobs to be
		// limited. This allows us to create the required workers for
		// each storage, while still limiting the absolute parallelism.
		workerSlots = make(chan struct{}, parallel)
	}
	return &ParallelPipeline{
		next:            next,
		parallel:        parallel,
		parallelStorage: parallelStorage,
		workerSlots:     workerSlots,
		done:            make(chan struct{}),
		requests:        make(map[string]chan *contextCommand),
	}
}

// Handle queues a request to create a backup. Commands are processed by
// n-workers per storage.
func (p *ParallelPipeline) Handle(ctx context.Context, cmd Command) {
	ch := p.getStorage(cmd.Repository().StorageName)

	select {
	case <-ctx.Done():
		p.setErr(ctx.Err())
	case ch <- &contextCommand{
		Command: cmd,
		Context: ctx,
	}:
	}
}

// Done waits for any in progress calls to `next` to complete then reports any
// accumulated errors
func (p *ParallelPipeline) Done() error {
	close(p.done)
	p.wg.Wait()
	if err := p.next.Done(); err != nil {
		return err
	}
	if p.err != nil {
		return fmt.Errorf("pipeline: %w", p.err)
	}
	return nil
}

// getStorage finds the channel associated with a storage. When no channel is
// found, one is created and n-workers are started to process requests.
func (p *ParallelPipeline) getStorage(storage string) chan<- *contextCommand {
	p.mu.Lock()
	defer p.mu.Unlock()

	workers := p.parallelStorage

	if p.parallelStorage < 1 {
		// if the workers are not limited by storage, then pretend there is a single storage with `parallel` workers
		storage = ""
		workers = p.parallel
	}

	ch, ok := p.requests[storage]
	if !ok {
		ch = make(chan *contextCommand)
		p.requests[storage] = ch

		for i := 0; i < workers; i++ {
			p.wg.Add(1)
			go p.worker(ch)
		}
	}
	return ch
}

func (p *ParallelPipeline) worker(ch <-chan *contextCommand) {
	defer p.wg.Done()
	for {
		select {
		case <-p.done:
			return
		case cmd := <-ch:
			p.processCommand(cmd.Context, cmd.Command)
		}
	}
}

func (p *ParallelPipeline) processCommand(ctx context.Context, cmd Command) {
	p.acquireWorkerSlot()
	defer p.releaseWorkerSlot()

	p.next.Handle(ctx, cmd)
}

func (p *ParallelPipeline) setErr(err error) {
	p.mu.Lock()
	defer p.mu.Unlock()
	if p.err != nil {
		return
	}
	p.err = err
}

// acquireWorkerSlot queues the worker until a slot is available.
// It never blocks if `parallel` or `parallelStorage` are 0
func (p *ParallelPipeline) acquireWorkerSlot() {
	if p.workerSlots == nil {
		return
	}
	p.workerSlots <- struct{}{}
}

// releaseWorkerSlot releases the worker slot.
func (p *ParallelPipeline) releaseWorkerSlot() {
	if p.workerSlots == nil {
		return
	}
	<-p.workerSlots
}