stateleveldb.go 7.15 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*
Copyright IBM Corp. 2016 All Rights Reserved.

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.
*/

package stateleveldb

import (
	"bytes"
21
	"fmt"
22

23
24
	"sync"

25
26
27
28
29
30
31
32
	"github.com/hyperledger/fabric/core/ledger/kvledger/txmgmt/statedb"
	"github.com/hyperledger/fabric/core/ledger/kvledger/txmgmt/version"
	"github.com/hyperledger/fabric/core/ledger/util/db"
	logging "github.com/op/go-logging"
	"github.com/syndtr/goleveldb/leveldb"
	"github.com/syndtr/goleveldb/leveldb/iterator"
)

33
var logger = logging.MustGetLogger("stateleveldb")
34
35
36
37
38
39
40

var compositeKeySep = []byte{0x00}
var lastKeyIndicator = byte(0x01)
var savePointKey = []byte{0x00}

// VersionedDBProvider implements interface VersionedDBProvider
type VersionedDBProvider struct {
41
42
43
44
	db         *db.DB
	databases  map[string]*VersionedDB
	mux        sync.Mutex
	openCounts uint64
45
46
47
}

// NewVersionedDBProvider instantiates VersionedDBProvider
48
49
50
51
52
53
54
func NewVersionedDBProvider() *VersionedDBProvider {
	dbPath := getDBPath()
	logger.Debugf("constructing VersionedDBProvider dbPath=%s", dbPath)
	db := db.CreateDB(&db.Conf{DBPath: dbPath})
	db.Open()
	logger.Debugf("Opened db dbPath=%s", dbPath)
	return &VersionedDBProvider{db, make(map[string]*VersionedDB), sync.Mutex{}, 0}
55
56
57
}

// GetDBHandle gets the handle to a named database
58
func (provider *VersionedDBProvider) GetDBHandle(dbName string) (statedb.VersionedDB, error) {
59
60
61
62
63
64
65
	provider.mux.Lock()
	defer provider.mux.Unlock()
	vdb := provider.databases[dbName]
	if vdb == nil {
		vdb = newVersionedDB(provider.db, dbName)
		provider.databases[dbName] = vdb
	}
66
	return vdb, nil
67
68
69
70
71
}

// Close closes the underlying db
func (provider *VersionedDBProvider) Close() {
	provider.db.Close()
72
73
74
75
}

// VersionedDB implements VersionedDB interface
type VersionedDB struct {
76
77
	db     *db.DB
	dbName string
78
79
80
}

// newVersionedDB constructs an instance of VersionedDB
81
82
func newVersionedDB(db *db.DB, dbName string) *VersionedDB {
	return &VersionedDB{db, dbName}
83
84
85
86
}

// Open implements method in VersionedDB interface
func (vdb *VersionedDB) Open() error {
87
	// do nothing because shared db is used
88
89
90
91
92
	return nil
}

// Close implements method in VersionedDB interface
func (vdb *VersionedDB) Close() {
93
	// do nothing because shared db is used
94
95
96
97
98
}

// GetState implements method in VersionedDB interface
func (vdb *VersionedDB) GetState(namespace string, key string) (*statedb.VersionedValue, error) {
	logger.Debugf("GetState(). ns=%s, key=%s", namespace, key)
99
	compositeKey := constructCompositeKey(vdb.dbName, namespace, key)
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
	dbVal, err := vdb.db.Get(compositeKey)
	if err != nil {
		return nil, err
	}
	if dbVal == nil {
		return nil, nil
	}
	val, ver := decodeValue(dbVal)
	return &statedb.VersionedValue{Value: val, Version: ver}, nil
}

// GetStateMultipleKeys implements method in VersionedDB interface
func (vdb *VersionedDB) GetStateMultipleKeys(namespace string, keys []string) ([]*statedb.VersionedValue, error) {
	vals := make([]*statedb.VersionedValue, len(keys))
	for i, key := range keys {
		val, err := vdb.GetState(namespace, key)
		if err != nil {
			return nil, err
		}
		vals[i] = val
	}
	return vals, nil
}

// GetStateRangeScanIterator implements method in VersionedDB interface
125
126
// startKey is inclusive
// endKey is exclusive
127
func (vdb *VersionedDB) GetStateRangeScanIterator(namespace string, startKey string, endKey string) (statedb.ResultsIterator, error) {
128
129
	compositeStartKey := constructCompositeKey(vdb.dbName, namespace, startKey)
	compositeEndKey := constructCompositeKey(vdb.dbName, namespace, endKey)
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
	if endKey == "" {
		compositeEndKey[len(compositeEndKey)-1] = lastKeyIndicator
	}
	dbItr := vdb.db.GetIterator(compositeStartKey, compositeEndKey)
	return newKVScanner(namespace, dbItr), nil
}

// ExecuteQuery implements method in VersionedDB interface
func (vdb *VersionedDB) ExecuteQuery(query string) (statedb.ResultsIterator, error) {
	panic("Method not supported for leveldb")
}

// ApplyUpdates implements method in VersionedDB interface
func (vdb *VersionedDB) ApplyUpdates(batch *statedb.UpdateBatch, height *version.Height) error {
	levelBatch := &leveldb.Batch{}
	for ck, vv := range batch.KVs {
146
		compositeKey := constructCompositeKey(vdb.dbName, ck.Namespace, ck.Key)
147
148
149
150
151
152
153
154
155
156

		// trace the first 200 characters of versioned value only, in case it is huge
		if logger.IsEnabledFor(logging.DEBUG) {
			versionedValueDump := fmt.Sprintf("%#v", vv)
			if len(versionedValueDump) > 200 {
				versionedValueDump = versionedValueDump[0:200] + "..."
			}
			logger.Debugf("Applying key=%#v, versionedValue=%s", ck, versionedValueDump)
		}

157
158
159
160
161
162
		if vv.Value == nil {
			levelBatch.Delete(compositeKey)
		} else {
			levelBatch.Put(compositeKey, encodeValue(vv.Value, vv.Version))
		}
	}
163
	levelBatch.Put(constructSavepointKey(vdb.dbName), height.ToBytes())
164
165
166
167
168
169
170
171
	if err := vdb.db.WriteBatch(levelBatch, false); err != nil {
		return err
	}
	return nil
}

// GetLatestSavePoint implements method in VersionedDB interface
func (vdb *VersionedDB) GetLatestSavePoint() (*version.Height, error) {
172
	versionBytes, err := vdb.db.Get(constructSavepointKey(vdb.dbName))
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
	if err != nil {
		return nil, err
	}
	version, _ := version.NewHeightFromBytes(versionBytes)
	return version, nil
}

func encodeValue(value []byte, version *version.Height) []byte {
	encodedValue := version.ToBytes()
	if value != nil {
		encodedValue = append(encodedValue, value...)
	}
	return encodedValue
}

func decodeValue(encodedValue []byte) ([]byte, *version.Height) {
	version, n := version.NewHeightFromBytes(encodedValue)
	value := encodedValue[n:]
	return value, version
}

194
195
196
197
func constructCompositeKey(dbName string, ns string, key string) []byte {
	compositeKey := []byte(dbName)
	compositeKey = append(compositeKey, compositeKeySep...)
	compositeKey = append(compositeKey, []byte(ns)...)
198
199
200
201
202
	compositeKey = append(compositeKey, compositeKeySep...)
	compositeKey = append(compositeKey, []byte(key)...)
	return compositeKey
}

203
204
205
206
207
208
209
210
func splitCompositeKey(compositeKey []byte) (string, string, string) {
	split := bytes.SplitN(compositeKey, compositeKeySep, 3)
	return string(split[0]), string(split[1]), string(split[2])
}

func constructSavepointKey(dbName string) []byte {
	key := savePointKey
	return append(key, []byte(dbName)...)
211
212
213
214
215
216
217
218
219
220
221
}

type kvScanner struct {
	namespace string
	dbItr     iterator.Iterator
}

func newKVScanner(namespace string, dbItr iterator.Iterator) *kvScanner {
	return &kvScanner{namespace, dbItr}
}

222
func (scanner *kvScanner) Next() (statedb.QueryResult, error) {
223
224
225
	if !scanner.dbItr.Next() {
		return nil, nil
	}
226
	_, _, key := splitCompositeKey(scanner.dbItr.Key())
227
228
229
230
231
232
233
234
235
	value, version := decodeValue(scanner.dbItr.Value())
	return &statedb.VersionedKV{
		CompositeKey:   statedb.CompositeKey{Namespace: scanner.namespace, Key: key},
		VersionedValue: statedb.VersionedValue{Value: value, Version: version}}, nil
}

func (scanner *kvScanner) Close() {
	scanner.dbItr.Release()
}