-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
fdb.go
416 lines (352 loc) · 11.3 KB
/
fdb.go
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
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
408
409
410
411
412
413
414
415
416
/*
* fdb.go
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2013-2018 Apple Inc. and the FoundationDB project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// FoundationDB Go API
package fdb
// #define FDB_API_VERSION 700
// #include <foundationdb/fdb_c.h>
// #include <stdlib.h>
import "C"
import (
"bytes"
"fmt"
"log"
"runtime"
"sync"
"unsafe"
)
// Would put this in futures.go but for the documented issue with
// exports and functions in preamble
// (https://code.google.com/p/go-wiki/wiki/cgo#Global_functions)
//export unlockMutex
func unlockMutex(p unsafe.Pointer) {
m := (*sync.Mutex)(p)
m.Unlock()
}
// A Transactor can execute a function that requires a Transaction. Functions
// written to accept a Transactor are called transactional functions, and may be
// called with either a Database or a Transaction.
type Transactor interface {
// Transact executes the caller-provided function, providing it with a
// Transaction (itself a Transactor, allowing composition of transactional
// functions).
Transact(func(Transaction) (interface{}, error)) (interface{}, error)
// All Transactors are also ReadTransactors, allowing them to be used with
// read-only transactional functions.
ReadTransactor
}
// A ReadTransactor can execute a function that requires a
// ReadTransaction. Functions written to accept a ReadTransactor are called
// read-only transactional functions, and may be called with a Database,
// Transaction or Snapshot.
type ReadTransactor interface {
// ReadTransact executes the caller-provided function, providing it with a
// ReadTransaction (itself a ReadTransactor, allowing composition of
// read-only transactional functions).
ReadTransact(func(ReadTransaction) (interface{}, error)) (interface{}, error)
}
func setOpt(setter func(*C.uint8_t, C.int) C.fdb_error_t, param []byte) error {
if err := setter(byteSliceToPtr(param), C.int(len(param))); err != 0 {
return Error{int(err)}
}
return nil
}
// NetworkOptions is a handle with which to set options that affect the entire
// FoundationDB client. A NetworkOptions instance should be obtained with the
// fdb.Options function.
type NetworkOptions struct {
}
// Options returns a NetworkOptions instance suitable for setting options that
// affect the entire FoundationDB client.
func Options() NetworkOptions {
return NetworkOptions{}
}
func (opt NetworkOptions) setOpt(code int, param []byte) error {
networkMutex.Lock()
defer networkMutex.Unlock()
if apiVersion == 0 {
return errAPIVersionUnset
}
return setOpt(func(p *C.uint8_t, pl C.int) C.fdb_error_t {
return C.fdb_network_set_option(C.FDBNetworkOption(code), p, pl)
}, param)
}
// APIVersion determines the runtime behavior the fdb package. If the requested
// version is not supported by both the fdb package and the FoundationDB C
// library, an error will be returned. APIVersion must be called prior to any
// other functions in the fdb package.
//
// Currently, this package supports API versions 200 through 700.
//
// Warning: When using the multi-version client API, setting an API version that
// is not supported by a particular client library will prevent that client from
// being used to connect to the cluster. In particular, you should not advance
// the API version of your application after upgrading your client until the
// cluster has also been upgraded.
func APIVersion(version int) error {
headerVersion := 700
networkMutex.Lock()
defer networkMutex.Unlock()
if apiVersion != 0 {
if apiVersion == version {
return nil
}
return errAPIVersionAlreadySet
}
if version < 200 || version > 700 {
return errAPIVersionNotSupported
}
if e := C.fdb_select_api_version_impl(C.int(version), C.int(headerVersion)); e != 0 {
if e != 0 {
if e == 2203 {
maxSupportedVersion := C.fdb_get_max_api_version()
if headerVersion > int(maxSupportedVersion) {
return fmt.Errorf("This version of the FoundationDB Go binding is "+
"not supported by the installed FoundationDB C library. "+
"The binding requires a library that supports API version %d, "+
"but the installed library supports a maximum version of %d.", headerVersion, maxSupportedVersion)
}
return fmt.Errorf("API version %d is not supported by the installed FoundationDB C library.", version)
}
return Error{int(e)}
}
}
apiVersion = version
return nil
}
// Determines if an API version has already been selected, i.e., if
// APIVersion or MustAPIVersion have already been called.
func IsAPIVersionSelected() bool {
return apiVersion != 0
}
// Returns the API version that has been selected through APIVersion
// or MustAPIVersion. If the version has already been selected, then
// the first value returned is the API version and the error is
// nil. If the API version has not yet been set, then the error
// will be non-nil.
func GetAPIVersion() (int, error) {
if IsAPIVersionSelected() {
return apiVersion, nil
}
return 0, errAPIVersionUnset
}
// MustAPIVersion is like APIVersion but panics if the API version is not
// supported.
func MustAPIVersion(version int) {
err := APIVersion(version)
if err != nil {
panic(err)
}
}
// MustGetAPIVersion is like GetAPIVersion but panics if the API version
// has not yet been set.
func MustGetAPIVersion() int {
apiVersion, err := GetAPIVersion()
if err != nil {
panic(err)
}
return apiVersion
}
var apiVersion int
var networkStarted bool
var networkMutex sync.Mutex
var openDatabases map[string]Database
func init() {
openDatabases = make(map[string]Database)
}
func startNetwork() error {
if e := C.fdb_setup_network(); e != 0 {
return Error{int(e)}
}
go func() {
e := C.fdb_run_network()
if e != 0 {
log.Printf("Unhandled error in FoundationDB network thread: %v (%v)\n", C.GoString(C.fdb_get_error(e)), e)
}
}()
networkStarted = true
return nil
}
// Deprecated: the network is started automatically when a database is opened.
// StartNetwork initializes the FoundationDB client networking engine. StartNetwork
// must not be called more than once.
func StartNetwork() error {
networkMutex.Lock()
defer networkMutex.Unlock()
if apiVersion == 0 {
return errAPIVersionUnset
}
return startNetwork()
}
// DefaultClusterFile should be passed to fdb.Open to allow the FoundationDB C
// library to select the platform-appropriate default cluster file on the current machine.
const DefaultClusterFile string = ""
// OpenDefault returns a database handle to the FoundationDB cluster identified
// by the DefaultClusterFile on the current machine.
//
// A single client can use this function multiple times to connect to different
// clusters simultaneously, with each invocation requiring its own cluster file.
// To connect to multiple clusters running at different, incompatible versions,
// the multi-version client API must be used.
func OpenDefault() (Database, error) {
return OpenDatabase(DefaultClusterFile)
}
// MustOpenDefault is like OpenDefault but panics if the default database cannot
// be opened.
func MustOpenDefault() Database {
db, err := OpenDefault()
if err != nil {
panic(err)
}
return db
}
// Open returns a database handle to the FoundationDB cluster identified
// by the provided cluster file and database name.
//
// A single client can use this function multiple times to connect to different
// clusters simultaneously, with each invocation requiring its own cluster file.
// To connect to multiple clusters running at different, incompatible versions,
// the multi-version client API must be used.
func OpenDatabase(clusterFile string) (Database, error) {
networkMutex.Lock()
defer networkMutex.Unlock()
if apiVersion == 0 {
return Database{}, errAPIVersionUnset
}
var e error
if !networkStarted {
e = startNetwork()
if e != nil {
return Database{}, e
}
}
db, ok := openDatabases[clusterFile]
if !ok {
db, e = createDatabase(clusterFile)
if e != nil {
return Database{}, e
}
openDatabases[clusterFile] = db
}
return db, nil
}
// MustOpenDatabase is like OpenDatabase but panics if the default database cannot
// be opened.
func MustOpenDatabase(clusterFile string) Database {
db, err := OpenDatabase(clusterFile)
if err != nil {
panic(err)
}
return db
}
// Deprecated: Use OpenDatabase instead.
// The database name must be []byte("DB").
func Open(clusterFile string, dbName []byte) (Database, error) {
if bytes.Compare(dbName, []byte("DB")) != 0 {
return Database{}, Error{2013} // invalid_database_name
}
return OpenDatabase(clusterFile)
}
// Deprecated: Use MustOpenDatabase instead.
// MustOpen is like Open but panics if the database cannot be opened.
func MustOpen(clusterFile string, dbName []byte) Database {
db, err := Open(clusterFile, dbName)
if err != nil {
panic(err)
}
return db
}
func createDatabase(clusterFile string) (Database, error) {
var cf *C.char
if len(clusterFile) != 0 {
cf = C.CString(clusterFile)
defer C.free(unsafe.Pointer(cf))
}
var outdb *C.FDBDatabase
if err := C.fdb_create_database(cf, &outdb); err != 0 {
return Database{}, Error{int(err)}
}
db := &database{outdb}
runtime.SetFinalizer(db, (*database).destroy)
return Database{db}, nil
}
// Deprecated: Use OpenDatabase instead.
// CreateCluster returns a cluster handle to the FoundationDB cluster identified
// by the provided cluster file.
func CreateCluster(clusterFile string) (Cluster, error) {
networkMutex.Lock()
defer networkMutex.Unlock()
if apiVersion == 0 {
return Cluster{}, errAPIVersionUnset
}
if !networkStarted {
return Cluster{}, errNetworkNotSetup
}
return Cluster{clusterFile}, nil
}
func byteSliceToPtr(b []byte) *C.uint8_t {
if len(b) > 0 {
return (*C.uint8_t)(unsafe.Pointer(&b[0]))
}
return nil
}
// A KeyConvertible can be converted to a FoundationDB Key. All functions in the
// FoundationDB API that address a specific key accept a KeyConvertible.
type KeyConvertible interface {
FDBKey() Key
}
// Key represents a FoundationDB key, a lexicographically-ordered sequence of
// bytes. Key implements the KeyConvertible interface.
type Key []byte
// FDBKey allows Key to (trivially) satisfy the KeyConvertible interface.
func (k Key) FDBKey() Key {
return k
}
// String describes the key as a human readable string.
func (k Key) String() string {
return Printable(k)
}
// Printable returns a human readable version of a byte array. The bytes that correspond with
// ASCII printable characters [32-127) are passed through. Other bytes are
// replaced with \x followed by a two character zero-padded hex code for byte.
func Printable(d []byte) string {
buf := new(bytes.Buffer)
for _, b := range d {
if b >= 32 && b < 127 && b != '\\' {
buf.WriteByte(b)
continue
}
if b == '\\' {
buf.WriteString("\\\\")
continue
}
buf.WriteString(fmt.Sprintf("\\x%02x", b))
}
return buf.String()
}
func panicToError(e *error) {
if r := recover(); r != nil {
fe, ok := r.(Error)
if ok {
*e = fe
} else {
panic(r)
}
}
}