File: server.go

package info (click to toggle)
golang-github-canonical-go-dqlite 2.0.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 712 kB
  • sloc: sh: 380; makefile: 5
file content (340 lines) | stat: -rw-r--r-- 9,327 bytes parent folder | download | duplicates (2)
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
335
336
337
338
339
340
package bindings

/*
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <assert.h>
#include <stdint.h>
#include <signal.h>
#include <stdbool.h>

#include <dqlite.h>

#define RAFT_NOCONNECTION 16

#define EMIT_BUF_LEN 1024

typedef unsigned long long nanoseconds_t;
typedef unsigned long long failure_domain_t;

// Duplicate a file descriptor and prevent it from being cloned into child processes.
static int dupCloexec(int oldfd) {
	int newfd = -1;

	newfd = dup(oldfd);
	if (newfd < 0) {
		return -1;
	}

	if (fcntl(newfd, F_SETFD, FD_CLOEXEC) < 0) {
		close(newfd);
		return -1;
	}

	return newfd;
}

// C to Go trampoline for custom connect function.
int connectWithDial(uintptr_t handle, char *address, int *fd);

// Wrapper to call the Go trampoline.
static int connectTrampoline(void *data, const char *address, int *fd) {
        uintptr_t handle = (uintptr_t)(data);
        return connectWithDial(handle, (char*)address, fd);
}

// Configure a custom connect function.
static int configConnectFunc(dqlite_node *t, uintptr_t handle) {
        return dqlite_node_set_connect_func(t, connectTrampoline, (void*)handle);
}

static dqlite_node_info_ext *makeInfos(int n) {
	return calloc(n, sizeof(dqlite_node_info_ext));
}

static void setInfo(dqlite_node_info_ext *infos, unsigned i, dqlite_node_id id,
		    const char *address, int role) {
	dqlite_node_info_ext *info = &infos[i];
	info->size = sizeof(dqlite_node_info_ext);
	info->id = id;
	info->address = (uint64_t)(uintptr_t)address;
	info->dqlite_role = role;
}

__attribute__((weak))
int dqlite_node_set_auto_recovery(dqlite_node *t, bool on);

static int setAutoRecovery(dqlite_node *t, bool on) {
	if (dqlite_node_set_auto_recovery == NULL) {
		return DQLITE_ERROR;
	}
	return dqlite_node_set_auto_recovery(t, on);
}

*/
import "C"
import (
	"context"
	"fmt"
	"net"
	"os"
	"sync"
	"time"
	"unsafe"

	"github.com/canonical/go-dqlite/v2/internal/protocol"
)

type Node struct {
	node   *C.dqlite_node
	ctx    context.Context
	cancel context.CancelFunc
}

type SnapshotParams struct {
	Threshold uint64
	Trailing  uint64
}

// Initializes state.
func init() {
	// FIXME: ignore SIGPIPE, see https://github.com/joyent/libuv/issues/1254
	C.signal(C.SIGPIPE, C.SIG_IGN)
}

// NewNode creates a new Node instance.
func NewNode(ctx context.Context, id uint64, address string, dir string) (*Node, error) {
	requiredVersion := dqliteMajorVersion*100 + dqliteMinorVersion
	// Remove the patch version, as patch versions should be compatible.
	runtimeVersion := int(C.dqlite_version_number()) / 100
	if requiredVersion > runtimeVersion {
		return nil, fmt.Errorf("version mismatch: required version(%d.%d.x) current version(%d.%d.x)",
			dqliteMajorVersion, dqliteMinorVersion, runtimeVersion/100, runtimeVersion%100)
	}

	var server *C.dqlite_node
	cid := C.dqlite_node_id(id)

	caddress := C.CString(address)
	defer C.free(unsafe.Pointer(caddress))

	cdir := C.CString(dir)
	defer C.free(unsafe.Pointer(cdir))

	if rc := C.dqlite_node_create(cid, caddress, cdir, &server); rc != 0 {
		errmsg := C.GoString(C.dqlite_node_errmsg(server))
		C.dqlite_node_destroy(server)
		return nil, fmt.Errorf("%s", errmsg)
	}

	node := &Node{node: (*C.dqlite_node)(unsafe.Pointer(server))}
	node.ctx, node.cancel = context.WithCancel(ctx)

	return node, nil
}

func (s *Node) SetDialFunc(dial protocol.DialFunc) error {
	server := (*C.dqlite_node)(unsafe.Pointer(s.node))
	connectLock.Lock()
	defer connectLock.Unlock()
	connectIndex++
	connectRegistry[connectIndex] = dial
	contextRegistry[connectIndex] = s.ctx
	if rc := C.configConnectFunc(server, connectIndex); rc != 0 {
		return fmt.Errorf("failed to set connect func")
	}
	return nil
}

func (s *Node) SetBindAddress(address string) error {
	server := (*C.dqlite_node)(unsafe.Pointer(s.node))
	caddress := C.CString(address)
	defer C.free(unsafe.Pointer(caddress))
	if rc := C.dqlite_node_set_bind_address(server, caddress); rc != 0 {
		return fmt.Errorf("failed to set bind address %q: %d", address, rc)
	}
	return nil
}

func (s *Node) SetNetworkLatency(nanoseconds uint64) error {
	server := (*C.dqlite_node)(unsafe.Pointer(s.node))
	cnanoseconds := C.nanoseconds_t(nanoseconds)
	if rc := C.dqlite_node_set_network_latency(server, cnanoseconds); rc != 0 {
		return fmt.Errorf("failed to set network latency")
	}
	return nil
}

func (s *Node) SetSnapshotParams(params SnapshotParams) error {
	server := (*C.dqlite_node)(unsafe.Pointer(s.node))
	cthreshold := C.unsigned(params.Threshold)
	ctrailing := C.unsigned(params.Trailing)
	if rc := C.dqlite_node_set_snapshot_params(server, cthreshold, ctrailing); rc != 0 {
		return fmt.Errorf("failed to set snapshot params")
	}
	return nil
}

func (s *Node) SetFailureDomain(code uint64) error {
	server := (*C.dqlite_node)(unsafe.Pointer(s.node))
	ccode := C.failure_domain_t(code)
	if rc := C.dqlite_node_set_failure_domain(server, ccode); rc != 0 {
		return fmt.Errorf("set failure domain: %d", rc)
	}
	return nil
}

func (s *Node) EnableDiskMode() error {
	server := (*C.dqlite_node)(unsafe.Pointer(s.node))
	if rc := C.dqlite_node_enable_disk_mode(server); rc != 0 {
		return fmt.Errorf("failed to set disk mode")
	}
	return nil
}

func (s *Node) SetAutoRecovery(on bool) error {
	server := (*C.dqlite_node)(unsafe.Pointer(s.node))
	if rc := C.setAutoRecovery(server, C.bool(on)); rc != 0 {
		return fmt.Errorf("failed to set auto-recovery behavior")
	}
	return nil
}

func (s *Node) GetBindAddress() string {
	server := (*C.dqlite_node)(unsafe.Pointer(s.node))
	return C.GoString(C.dqlite_node_get_bind_address(server))
}

func (s *Node) Start() error {
	server := (*C.dqlite_node)(unsafe.Pointer(s.node))
	if rc := C.dqlite_node_start(server); rc != 0 {
		errmsg := C.GoString(C.dqlite_node_errmsg(server))
		return fmt.Errorf("%s", errmsg)
	}
	return nil
}

func (s *Node) Stop() error {
	server := (*C.dqlite_node)(unsafe.Pointer(s.node))
	if rc := C.dqlite_node_stop(server); rc != 0 {
		return fmt.Errorf("task stopped with error code %d", rc)
	}
	return nil
}

// Close the server releasing all used resources.
func (s *Node) Close() {
	defer s.cancel()
	server := (*C.dqlite_node)(unsafe.Pointer(s.node))
	C.dqlite_node_destroy(server)
}

// Remark that Recover doesn't take the node role into account
func (s *Node) Recover(cluster []protocol.NodeInfo) error {
	for i := range cluster {
		cluster[i].Role = protocol.Voter
	}
	return s.RecoverExt(cluster)
}

// RecoverExt has a similar purpose as `Recover` but takes the node role into account
func (s *Node) RecoverExt(cluster []protocol.NodeInfo) error {
	server := (*C.dqlite_node)(unsafe.Pointer(s.node))
	n := C.int(len(cluster))
	infos := C.makeInfos(n)
	defer C.free(unsafe.Pointer(infos))
	for i, info := range cluster {
		cid := C.dqlite_node_id(info.ID)
		caddress := C.CString(info.Address)
		crole := C.int(info.Role)
		defer C.free(unsafe.Pointer(caddress))
		C.setInfo(infos, C.unsigned(i), cid, caddress, crole)
	}
	if rc := C.dqlite_node_recover_ext(server, infos, n); rc != 0 {
		errmsg := C.GoString(C.dqlite_node_errmsg(server))
		return fmt.Errorf("recover failed with error code %d, error details: %s", rc, errmsg)
	}
	return nil
}

func (s *Node) DescribeLastEntry() (uint64, uint64, error) {
	server := (*C.dqlite_node)(unsafe.Pointer(s.node))
	index := C.uint64_t(0)
	term := C.uint64_t(0)
	if rc := C.dqlite_node_describe_last_entry(server, &index, &term); rc != 0 {
		return 0, 0, fmt.Errorf("dqlite_node_describe_last_entry failed with error code %d", rc)
	}
	return uint64(index), uint64(term), nil
}

// GenerateID generates a unique ID for a server.
func GenerateID(address string) uint64 {
	caddress := C.CString(address)
	defer C.free(unsafe.Pointer(caddress))
	id := C.dqlite_generate_node_id(caddress)
	return uint64(id)
}

// Extract the underlying socket from a connection.
func connToSocket(conn net.Conn) (C.int, error) {
	file, err := conn.(fileConn).File()
	if err != nil {
		return C.int(-1), err
	}

	fd1 := C.int(file.Fd())

	// Duplicate the file descriptor, in order to prevent Go's finalizer to
	// close it.
	fd2 := C.dupCloexec(fd1)
	if fd2 < 0 {
		return C.int(-1), fmt.Errorf("failed to dup socket fd")
	}

	conn.Close()

	return fd2, nil
}

// Interface that net.Conn must implement in order to extract the underlying
// file descriptor.
type fileConn interface {
	File() (*os.File, error)
}

//export connectWithDial
func connectWithDial(handle C.uintptr_t, address *C.char, fd *C.int) C.int {
	connectLock.Lock()
	defer connectLock.Unlock()

	dial := connectRegistry[handle]
	ctx := contextRegistry[handle]

	// TODO: make timeout customizable.
	dialCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
	defer cancel()

	conn, err := dial(dialCtx, C.GoString(address))
	if err != nil {
		return C.RAFT_NOCONNECTION
	}
	socket, err := connToSocket(conn)
	if err != nil {
		return C.RAFT_NOCONNECTION
	}
	*fd = socket
	return C.int(0)
}

// Use handles to avoid passing Go pointers to C.
var contextRegistry = make(map[C.uintptr_t]context.Context)
var connectRegistry = make(map[C.uintptr_t]protocol.DialFunc)
var connectIndex C.uintptr_t = 100
var connectLock = sync.Mutex{}

// ErrNodeStopped is returned by Node.Handle() is the server was stopped.
var ErrNodeStopped = fmt.Errorf("server was stopped")

// To compare bool values.
var cfalse C.bool