~tsileo/blobstash

ref: b178995e346d blobstash/pkg/replication/replication.go -rw-r--r-- 3.2 KiB
b178995eThomas Sileo vendor: update deps 2 years ago
                                                                                
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
package replication // import "a4.io/blobstash/pkg/replication"

import (
	"context"
	"math"
	"sync"
	"time"

	"a4.io/blobstash/pkg/blob"
	"a4.io/blobstash/pkg/client/clientutil"
	"a4.io/blobstash/pkg/client/oplog"
	"a4.io/blobstash/pkg/config"
	"a4.io/blobstash/pkg/stash/store"
	bsync "a4.io/blobstash/pkg/sync"

	log "github.com/inconshreveable/log15"
)

type Backoff struct {
	delay    time.Duration
	factor   float64
	maxDelay time.Duration
	attempt  int
}

func (b *Backoff) Reset() {
	b.attempt = 1
}

func (b *Backoff) Delay() time.Duration {
	d := float64(b.delay) * math.Pow(b.factor, float64(b.attempt))
	maxD := float64(b.maxDelay)
	b.attempt++
	if d > maxD {
		return time.Duration(maxD)
	}
	return time.Duration(d)
}

type Replication struct {
	log       log.Logger
	synctable *bsync.Sync
	blobstore store.BlobStore
	backoff   *Backoff

	remoteOplog *oplog.Oplog

	conf *config.ReplicateFrom

	wg *sync.WaitGroup
}

func New(logger log.Logger, conf *config.Config, bs store.BlobStore, s *bsync.Sync, wg *sync.WaitGroup) (*Replication, error) {
	logger.Debug("init")
	rep := &Replication{
		conf:        conf.ReplicateFrom,
		blobstore:   bs,
		log:         logger,
		remoteOplog: oplog.New(clientutil.NewClientUtil(conf.ReplicateFrom.URL, clientutil.WithAPIKey(conf.ReplicateFrom.APIKey))),
		synctable:   s,
		backoff: &Backoff{
			delay:    1 * time.Second,
			maxDelay: 120 * time.Second,
			factor:   1.6,
		},
		wg: wg,
	}
	if err := rep.init(); err != nil {
		return nil, err
	}
	// FIXME(tsileo): clean shutdown
	return rep, nil
}

func (r *Replication) sync() error {
	// Initiate a one-way synchronization
	stats, err := r.synctable.Sync(r.conf.URL, r.conf.APIKey, true)
	if err != nil {
		return err
	}
	r.log.Info("sync done", "stats", stats)
	return nil
}

func (r *Replication) init() error {
	r.log.Debug("initial sync")
	r.backoff.Reset()
	if err := r.sync(); err != nil {
		return err
	}
	var resync bool

	ops := make(chan *oplog.Op)

	// This should run forever (can't disable replication while BlobStash is already running)
	go func() {
		for {
			if resync {
				r.log.Debug("trying to resync")
				if err := r.sync(); err != nil {
					r.log.Error("failed to sync", "err", err, "attempt", r.backoff.attempt)
					time.Sleep(r.backoff.Delay())
					continue
				}
				r.backoff.Reset()
				r.log.Debug("sync successful")
				resync = false
			}

			r.log.Debug("listen to remote oplog")
			if err := r.remoteOplog.Notify(context.TODO(), ops, nil); err != nil {
				r.log.Error("remote oplog SSE error", "err", err, "attempt", r.backoff.attempt)
				resync = true
				time.Sleep(r.backoff.Delay())
			}
			r.backoff.Reset()
		}
	}()

	go func() {
		for op := range ops {
			if op.Event == "blob" {
				hash := op.Data
				r.log.Info("new blob from replication", "hash", hash)

				// Fetch the blob from the remote BlobStash instance
				data, err := r.remoteOplog.GetBlob(context.TODO(), hash)
				if err != nil {
					panic(err)
				}

				// Ensure the blob is not corrupted
				blob := &blob.Blob{Hash: hash, Data: data}
				r.log.Debug("fetched blob", "blob", blob)

				// Save it locally
				if r.blobstore.Put(context.Background(), blob); err != nil {
					panic(err)
				}
			}
		}
		r.log.Debug("done listening the remote oplog")
	}()

	return nil
}