server.go 9.48 KB
Newer Older
ale's avatar
ale committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package replds

import (
	"context"
	"errors"
	"log"
	"strings"
	"sync"
	"time"

	"git.autistici.org/ai3/go-common/clientutil"
	"github.com/prometheus/client_golang/prometheus"
)

var (
	// Maximum size of node values in a single InternalGetNodesResponse,
	// used to avoid excessively large JSON replies.
	maxResponseSize uint64 = 64 * 1024

	// How often to exchange data with peers.
	pollPeriod = 120 * time.Second

	// Timeout for InternalGetNodes requests.
24
	getNodesTimeout = 120 * time.Second
ale's avatar
ale committed
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
)

// Node is an annotated path/value entry.
type Node struct {
	Path  string `json:"path"`
	Value []byte `json:"value"`

	Timestamp time.Time `json:"timestamp"`

	Deleted bool `json:"deleted,omitempty"`
}

func (n *Node) withoutValue() *Node {
	return &Node{
		Path:      n.Path,
		Timestamp: n.Timestamp,
		Deleted:   n.Deleted,
	}
}

func (n *Node) metadataOnly() Node {
	return Node{
		Path:      n.Path,
		Timestamp: n.Timestamp,
	}
}

type internalGetNodesRequest struct {
	Nodes []Node `json:"nodes"`
}

type internalGetNodesResponse struct {
	Nodes   []Node `json:"nodes"`
	Partial bool   `json:"partial,omitempty"`
}

type internalUpdateNodesRequest struct {
	Nodes []Node `json:"nodes"`
}

// SetNodesRequest is the request type for the SetNodes method.
type SetNodesRequest struct {
	Nodes []Node `json:"nodes"`
}

// SetNodesResponse is the response returned by the SetNodes method.
type SetNodesResponse struct {
	HostsOk  int `json:"hosts_ok"`
	HostsErr int `json:"hosts_err"`
}

var errTooOld = errors.New("a more recent value exists for this key")

type storage interface {
	getAllNodes() []Node
	getNodeValue(string) ([]byte, error)
	setNode(Node) error
}

// Server for the replicated filesync.
type Server struct {
	peers   []string
	network *network
	storage storage
	logger  *log.Logger

	wg    sync.WaitGroup
	stop  chan bool
	mx    sync.Mutex
	nodes map[string]*Node
}

func stripTrailingSlash(peers []string) []string {
	var out []string
	for _, peer := range peers {
		out = append(out, strings.TrimRight(peer, "/"))
	}
	return out
}

// NewServer creates a new Server with the given peers and backends.
func NewServer(peers []string, dir string, tlsConfig *clientutil.TLSClientConfig) (*Server, error) {
	peers = stripTrailingSlash(peers)

	network, err := newNetwork(peers, tlsConfig)
	if err != nil {
		return nil, err
	}

	s := &Server{
		peers:   peers,
		network: network,
		storage: newFS(dir),
		stop:    make(chan bool),
		nodes:   make(map[string]*Node),
	}

	for _, node := range s.storage.getAllNodes() {
		s.nodes[node.Path] = &node
	}
	if len(s.nodes) > 0 {
		log.Printf("found %d entries in %s", len(s.nodes), dir)
	}

	for _, peer := range peers {
		s.wg.Add(1)
		go func(peer string) {
			s.pollThread(peer)
			s.wg.Done()
		}(peer)
	}

	return s, nil
}

// Close the server and all its associated resources. Wait for poll
// goroutines to terminate.
func (s *Server) Close() {
	close(s.stop)
	s.wg.Wait()
}

// Allow to switch logger to make tests easier to debug.
func (s *Server) log(fmt string, args ...interface{}) {
	if s.logger != nil {
		s.logger.Printf(fmt, args...)
	} else {
		log.Printf(fmt, args...)
	}
}

// Update one or more nodes as a "transaction": if one update fails,
// the rest are aborted (but previous commits are not reverted, yet).
// Will ping peers with the data when updatePeers is true.
func (s *Server) doSetNodes(ctx context.Context, nodes []Node, updatePeers bool) (*SetNodesResponse, error) {
	// Update local state.
	for _, node := range nodes {
		cur, ok := s.nodes[node.Path]
		if ok {
			if node.Timestamp.Before(cur.Timestamp) {
				return nil, errTooOld
			} else if node.Timestamp == cur.Timestamp {
				// This can happen because the lock is not kept
				// in pollPeer between the generation of the
				// node metadata and the internal call to
				// InternalUpdateNodes. It is not an error.
				s.log("de-duplicated update of %s", node.Path)
				continue
			}
		}
		if err := s.storage.setNode(node); err != nil {
			return nil, err
		}
		// Keep the value out of our in-memory node map.
		s.nodes[node.Path] = node.withoutValue()
		s.log("received %s @%d", node.Path, node.Timestamp.Unix())
	}

	// Update the global max_seen_timestamp value.
	updateMaxTimestamp(nodes)

	var res SetNodesResponse
	if updatePeers {
		// Ping remote nodes with updated state.
		res.HostsOk = 1
		for _, peer := range s.peers {
			err := s.network.Client(peer).internalUpdateNodes(ctx, &internalUpdateNodesRequest{
				Nodes: nodes,
			})
			if err != nil {
				log.Printf("error updating peer %s: %v", peer, err)
				res.HostsErr++
			} else {
				res.HostsOk++
			}
		}
	}

	return &res, nil
}

func (s *Server) setNodes(ctx context.Context, req *SetNodesRequest) (*SetNodesResponse, error) {
	s.mx.Lock()
	defer s.mx.Unlock()
	return s.doSetNodes(ctx, req.Nodes, true)
}

func (s *Server) internalUpdateNodes(ctx context.Context, req *internalUpdateNodesRequest) error {
	s.mx.Lock()
	defer s.mx.Unlock()
	_, err := s.doSetNodes(ctx, req.Nodes, false)
	return err
}

func (s *Server) getNodeWithValue(node *Node) (out Node, err error) {
	out = *node
	out.Value, err = s.storage.getNodeValue(node.Path)
	return
}

func nodeDiff(reqNodes []Node, myNodes map[string]*Node, adder func(*Node) bool) ([]string, bool) {
	var missing []string
	tmp := make(map[string]struct{})
	for _, reqNode := range reqNodes {
		tmp[reqNode.Path] = struct{}{}
		node, ok := myNodes[reqNode.Path]
		if ok && reqNode.Timestamp.Before(node.Timestamp) {
			if !adder(node) {
				return nil, true
			}
		} else if !ok {
			// Oh we don't have this one, want it.
			missing = append(missing, reqNode.Path)
		}
	}
	for _, node := range myNodes {
		if _, ok := tmp[node.Path]; ok {
			continue
		}
		//s.log("remote peer does not have %s", node.Path)
		if !adder(node) {
			return nil, true
		}
	}
	return missing, false
}

// Return nodes (including data) that the caller is missing.
func (s *Server) internalGetNodes(ctx context.Context, req *internalGetNodesRequest) (*internalGetNodesResponse, error) {
	s.mx.Lock()
	defer s.mx.Unlock()

	// Scan the input and local nodes, find nodes that need to be updated on
	// the caller side, and those that it is missing altogether.
	var missing []string
	var resp internalGetNodesResponse
	var totalSize uint64

	// Add a new node to the response, returns false if the response grew
	// too large and we should stop adding results to it. We add at least
	// one element to the response, regardless of its size, to ensure
	// progress.
	add := func(nodeptr *Node) bool {
		nodeWithData, err := s.getNodeWithValue(nodeptr)
		if err != nil {
			s.log("missing value for %s: %v", nodeptr.Path, err)
			return true
		}
		sz := uint64(len(nodeWithData.Value))
		if len(resp.Nodes) > 0 && totalSize+sz > maxResponseSize {
			return false
		}
		totalSize += sz
		resp.Nodes = append(resp.Nodes, nodeWithData)
		return true
	}

	missing, partial := nodeDiff(req.Nodes, s.nodes, add)

	if len(missing) > 0 {
		// We just log this but don't need to do anything, the
		// next call to pollPeer will fetch the missing nodes.
		s.log("we are missing the following nodes: %s", strings.Join(missing, ", "))
	}
	if partial {
		s.log("value size too large, sending partial response")
		resp.Partial = partial
	}
	return &resp, nil
}

func (s *Server) pollThread(peer string) {
	poll := func() {
		if err := s.pollPeer(peer); err != nil {
			s.log("error polling peer %s: %v", peer, err)
		}
	}

	poll()

	tick := time.NewTicker(pollPeriod)
	defer tick.Stop()
	for {
		select {
		case <-s.stop:
			return
		case <-tick.C:
			poll()
		}
	}
}

func (s *Server) pollPeer(peer string) error {
	for {
		partial, err := s.pollPeerRequest(peer)
		if err != nil {
			return err
		}
		if !partial {
			return nil
		}
	}
}

var (
	peerRequests = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "peer_sync_requests",
			Help: "Total number of peer sync requests.",
		},
		[]string{"peer"},
	)
	peerErrors = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "peer_sync_errors",
			Help: "Total number of failed peer sync requests.",
		},
		[]string{"peer"},
	)
	maxTimestamp = prometheus.NewGauge(
		prometheus.GaugeOpts{
			Name: "max_seen_timestamp",
			Help: "Latest timestamp of modified files.",
		},
	)

	// Does not need a lock because we're calling setMaxTimestamp
	// when holding the Server.mx mutex (a bit fragile).
	maxTSValue int64
)

func updateMaxTimestamp(nodes []Node) {
	var max int64
	for _, node := range nodes {
		t := node.Timestamp.Unix()
		if t > max {
			max = t
		}
	}
	if max > maxTSValue {
		maxTSValue = max
		maxTimestamp.Set(float64(max))
	}
}

func init() {
	prometheus.MustRegister(peerRequests, peerErrors, maxTimestamp)
}

func (s *Server) pollPeerRequest(peer string) (bool, error) {
	peerName := stripHTTP(peer)
	peerRequests.With(prometheus.Labels{"peer": peerName}).Inc()

	s.mx.Lock()
	var req internalGetNodesRequest
	for _, node := range s.nodes {
		// Create a copy of the Node with just the metadata
		// used by the sync process.
		req.Nodes = append(req.Nodes, node.metadataOnly())
	}
	s.mx.Unlock()

	ctx, cancel := context.WithTimeout(context.Background(), getNodesTimeout)
	defer cancel()

	resp, err := s.network.Client(peer).internalGetNodes(ctx, &req)
	if err != nil {
		peerErrors.With(prometheus.Labels{"peer": peerName}).Inc()
		return false, err
	}

	if len(resp.Nodes) == 0 {
		// Nothing to do.
		s.log("in sync with %s", peer)
		return false, nil
	}

	return resp.Partial, s.internalUpdateNodes(ctx, &internalUpdateNodesRequest{Nodes: resp.Nodes})
}

func stripHTTP(uri string) string {
	return strings.TrimPrefix(strings.TrimPrefix(uri, "https://"), "http://")
}