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

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

import (
	"context"
	"encoding/json"
	"errors"
	"strings"
	"sync"
	"sync/atomic"

	"github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus/ctxlogrus"
	lru "github.com/hashicorp/golang-lru"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/sirupsen/logrus"
	"gitlab.com/gitlab-org/gitaly/internal/praefect/datastore/glsql"
)

// SecondariesProvider should provide information about secondary storages.
type SecondariesProvider interface {
	// GetConsistentSecondaries returns all secondaries with the same generation as the primary.
	GetConsistentSecondaries(ctx context.Context, virtualStorage, relativePath, primary string) (map[string]struct{}, error)
}

// DirectStorageProvider provides the latest state of the synced nodes.
type DirectStorageProvider struct {
	sp          SecondariesProvider
	errorsTotal *prometheus.CounterVec
}

// NewDirectStorageProvider returns a new storage provider.
func NewDirectStorageProvider(sp SecondariesProvider) *DirectStorageProvider {
	csp := &DirectStorageProvider{
		sp: sp,
		errorsTotal: prometheus.NewCounterVec(
			prometheus.CounterOpts{
				Name: "gitaly_praefect_uptodate_storages_errors_total",
				Help: "Total number of errors raised during defining up to date storages for reads distribution",
			},
			[]string{"type"},
		),
	}

	return csp
}

func (c *DirectStorageProvider) Describe(descs chan<- *prometheus.Desc) {
	prometheus.DescribeByCollect(c, descs)
}

func (c *DirectStorageProvider) Collect(collector chan<- prometheus.Metric) {
	c.errorsTotal.Collect(collector)
}

func (c *DirectStorageProvider) GetSyncedNodes(ctx context.Context, virtualStorage, relativePath, primaryStorage string) []string {
	storages, _ := c.getSyncedNodes(ctx, virtualStorage, relativePath, primaryStorage)
	return storages
}

func (c *DirectStorageProvider) getSyncedNodes(ctx context.Context, virtualStorage, relativePath, primaryStorage string) ([]string, bool) {
	upToDateStorages, err := c.sp.GetConsistentSecondaries(ctx, virtualStorage, relativePath, primaryStorage)
	if err != nil {
		c.errorsTotal.WithLabelValues("retrieve").Inc()
		// this is recoverable error - we can proceed with primary node
		ctxlogrus.Extract(ctx).WithError(err).Warn("get consistent secondaries")
		return []string{primaryStorage}, false
	}

	return combineStorages(upToDateStorages, primaryStorage), true
}

func combineStorages(upToDateStorages map[string]struct{}, primaryStorage string) []string {
	storages := make([]string, 0, len(upToDateStorages)+1)
	for upToDateStorage := range upToDateStorages {
		if upToDateStorage != primaryStorage {
			storages = append(storages, upToDateStorage)
		}
	}

	return append(storages, primaryStorage)
}

// errNotExistingVirtualStorage indicates that the requested virtual storage can't be found or not configured.
var errNotExistingVirtualStorage = errors.New("virtual storage does not exist")

// CachingStorageProvider is a storage provider that caches up to date storages by repository.
// Each virtual storage has it's own cache that invalidates entries based on notifications.
type CachingStorageProvider struct {
	*DirectStorageProvider
	// caches is per virtual storage cache. It is initialized once on construction.
	caches map[string]*lru.Cache
	// access is access method to use: 0 - without caching; 1 - with caching.
	access int32
	// syncer allows to sync retrieval operations to omit unnecessary runs.
	syncer syncer
	// callbackLogger should be used only inside of the methods used as callbacks.
	callbackLogger   logrus.FieldLogger
	cacheAccessTotal *prometheus.CounterVec
}

// NewCachingStorageProvider returns a storage provider that uses caching.
func NewCachingStorageProvider(logger logrus.FieldLogger, sp SecondariesProvider, virtualStorages []string) (*CachingStorageProvider, error) {
	csp := &CachingStorageProvider{
		DirectStorageProvider: NewDirectStorageProvider(sp),
		caches:                make(map[string]*lru.Cache, len(virtualStorages)),
		syncer:                syncer{inflight: map[string]chan struct{}{}},
		callbackLogger:        logger.WithField("component", "caching_storage_provider"),
		cacheAccessTotal: prometheus.NewCounterVec(
			prometheus.CounterOpts{
				Name: "gitaly_praefect_uptodate_storages_cache_access_total",
				Help: "Total number of cache access operations during defining of up to date storages for reads distribution (per virtual storage)",
			},
			[]string{"virtual_storage", "type"},
		),
	}

	for _, virtualStorage := range virtualStorages {
		virtualStorage := virtualStorage
		cache, err := lru.NewWithEvict(2<<20, func(key interface{}, value interface{}) {
			csp.cacheAccessTotal.WithLabelValues(virtualStorage, "evict").Inc()
		})
		if err != nil {
			return nil, err
		}
		csp.caches[virtualStorage] = cache
	}

	return csp, nil
}

type (
	notificationEntry struct {
		VirtualStorage string `json:"virtual_storage"`
		RelativePath   string `json:"relative_path"`
	}

	changeNotification struct {
		Old []notificationEntry `json:"old"`
		New []notificationEntry `json:"new"`
	}
)

func (c *CachingStorageProvider) Notification(n glsql.Notification) {
	var change changeNotification
	if err := json.NewDecoder(strings.NewReader(n.Payload)).Decode(&change); err != nil {
		c.disableCaching() // as we can't update cache properly we should disable it
		c.errorsTotal.WithLabelValues("notification_decode").Inc()
		c.callbackLogger.WithError(err).WithField("channel", n.Channel).Error("received payload can't be processed")
		return
	}

	c.enableCaching()

	entries := map[string][]string{}
	for _, notificationEntries := range [][]notificationEntry{change.Old, change.New} {
		for _, entry := range notificationEntries {
			entries[entry.VirtualStorage] = append(entries[entry.VirtualStorage], entry.RelativePath)
		}
	}

	for virtualStorage, relativePaths := range entries {
		cache, found := c.getCache(virtualStorage)
		if !found {
			c.callbackLogger.WithError(errNotExistingVirtualStorage).WithField("virtual_storage", virtualStorage).Error("cache not found")
			continue
		}

		for _, relativePath := range relativePaths {
			cache.Remove(relativePath)
		}
	}
}

func (c *CachingStorageProvider) Connected() {
	c.enableCaching() // (re-)enable cache usage
}

func (c *CachingStorageProvider) Disconnect(error) {
	// disable cache usage as it could be outdated
	c.disableCaching()
}

func (c *CachingStorageProvider) Describe(descs chan<- *prometheus.Desc) {
	prometheus.DescribeByCollect(c, descs)
}

func (c *CachingStorageProvider) Collect(collector chan<- prometheus.Metric) {
	c.errorsTotal.Collect(collector)
	c.cacheAccessTotal.Collect(collector)
}

func (c *CachingStorageProvider) enableCaching() {
	atomic.StoreInt32(&c.access, 1)
}

func (c *CachingStorageProvider) disableCaching() {
	atomic.StoreInt32(&c.access, 0)

	for _, cache := range c.caches {
		cache.Purge()
	}
}

func (c *CachingStorageProvider) getCache(virtualStorage string) (*lru.Cache, bool) {
	val, found := c.caches[virtualStorage]
	return val, found
}

func (c *CachingStorageProvider) cacheMiss(ctx context.Context, virtualStorage, relativePath, primaryStorage string) ([]string, bool) {
	c.cacheAccessTotal.WithLabelValues(virtualStorage, "miss").Inc()
	return c.getSyncedNodes(ctx, virtualStorage, relativePath, primaryStorage)
}

func (c *CachingStorageProvider) tryCache(ctx context.Context, virtualStorage, relativePath, primaryStorage string) (*lru.Cache, []string, bool) {
	cache, found := c.getCache(virtualStorage)
	if !found {
		return nil, nil, false
	}

	if storages, found := getStringSlice(cache, relativePath); found {
		return cache, storages, true
	}

	// synchronises concurrent attempts to update cache for the same key.
	defer c.syncer.await(ctx, relativePath)()

	if storages, found := getStringSlice(cache, relativePath); found {
		return cache, storages, true
	}

	return cache, nil, false
}

func (c *CachingStorageProvider) isCacheEnabled() bool { return atomic.LoadInt32(&c.access) != 0 }

func (c *CachingStorageProvider) GetSyncedNodes(ctx context.Context, virtualStorage, relativePath, primaryStorage string) []string {
	var cache *lru.Cache

	if c.isCacheEnabled() {
		var storages []string
		var ok bool
		cache, storages, ok = c.tryCache(ctx, virtualStorage, relativePath, primaryStorage)
		if ok {
			c.cacheAccessTotal.WithLabelValues(virtualStorage, "hit").Inc()
			return storages
		}
	}

	storages, ok := c.cacheMiss(ctx, virtualStorage, relativePath, primaryStorage)
	if ok && cache != nil {
		cache.Add(relativePath, storages)
		c.cacheAccessTotal.WithLabelValues(virtualStorage, "populate").Inc()
	}
	return storages
}

func getStringSlice(cache *lru.Cache, key string) ([]string, bool) {
	val, found := cache.Get(key)
	vals, _ := val.([]string)
	return vals, found
}

// syncer allows to sync access to a particular key.
type syncer struct {
	// inflight contains set of keys already acquired for sync.
	inflight map[string]chan struct{}
	mtx      sync.Mutex
}

// await acquires lock for provided key and returns a callback to invoke once the key could be released.
// If key is already acquired the call will be blocked until callback for that key won't be called.
func (sc *syncer) await(ctx context.Context, key string) func() {
	sc.mtx.Lock()

	if cond, found := sc.inflight[key]; found {
		sc.mtx.Unlock()

		select {
		case <-cond: // the key is acquired, wait until it is released
		case <-ctx.Done():
		}

		return func() {}
	}

	defer sc.mtx.Unlock()

	cond := make(chan struct{})
	sc.inflight[key] = cond

	return func() {
		sc.mtx.Lock()
		defer sc.mtx.Unlock()

		delete(sc.inflight, key)

		close(cond)
	}
}