/
storage.go
292 lines (247 loc) · 7.7 KB
/
storage.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
// Package storage implements the storage sub-commands.
package storage
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"time"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/oasisprotocol/oasis-core/go/common"
"github.com/oasisprotocol/oasis-core/go/common/crypto/hash"
"github.com/oasisprotocol/oasis-core/go/common/logging"
cmdCommon "github.com/oasisprotocol/oasis-core/go/oasis-node/cmd/common"
roothash "github.com/oasisprotocol/oasis-core/go/roothash/api"
"github.com/oasisprotocol/oasis-core/go/runtime/history"
"github.com/oasisprotocol/oasis-core/go/runtime/registry"
db "github.com/oasisprotocol/oasis-core/go/storage/mkvs/db/api"
"github.com/oasisprotocol/oasis-core/go/storage/mkvs/db/badger"
"github.com/oasisprotocol/oasis-core/go/storage/mkvs/node"
workerStorage "github.com/oasisprotocol/oasis-core/go/worker/storage"
)
var (
storageCmd = &cobra.Command{
Use: "storage",
Short: "storage node utilities",
}
storageMigrateCmd = &cobra.Command{
Use: "migrate <runtime...>",
Args: cobra.MinimumNArgs(1),
Short: "perform node database migration",
RunE: doMigrate,
}
storageCheckCmd = &cobra.Command{
Use: "check <runtime...>",
Args: cobra.MinimumNArgs(1),
Short: "check node databases for consistency",
RunE: doCheck,
}
storageRenameNsCmd = &cobra.Command{
Use: "rename-ns <src-ns> <dst-ns>",
Args: cobra.ExactArgs(2),
Short: "change the namespace of a runtime database",
RunE: doRenameNs,
}
logger = logging.GetLogger("cmd/storage")
pretty = cmdCommon.Isatty(1)
)
type displayHelper struct {
lastTime time.Time
lastStatus string
lastProgress bool
}
func (dh *displayHelper) displayf(base, format string, args ...interface{}) {
dh.lastTime = time.Time{}
if pretty {
if dh.lastProgress {
fmt.Printf("\n"+format, args...)
} else {
fmt.Printf(format, args...)
}
} else {
logger.Info(base)
}
dh.lastProgress = false
dh.lastStatus = base
}
func (dh *displayHelper) Display(msg string) {
dh.displayf(msg, "- %s\n", msg)
}
func (dh *displayHelper) DisplayStepBegin(msg string) {
dh.displayf(msg, "- %s... ", msg)
}
func (dh *displayHelper) DisplayStepEnd(msg string) {
dh.displayf(msg, "\r- %s: %s\n", dh.lastStatus, msg)
}
func (dh *displayHelper) DisplayStep(msg string) {
dh.displayf(msg, "- %s...\n", msg)
}
func (dh *displayHelper) DisplayProgress(msg string, current, total uint64) {
if pretty {
if time.Since(dh.lastTime).Seconds() < 0.1 && current < total {
return
}
dh.lastTime = time.Now()
var leadin string
if len(dh.lastStatus) > 0 {
leadin = fmt.Sprintf("- %s:", dh.lastStatus)
} else {
leadin = "-"
}
fmt.Printf("\r%s %s %.2f%% (%d / %d)\033[K", leadin, msg, (float64(current)/float64(total))*100.0, current, total)
dh.lastProgress = true
}
}
type migrateHelper struct {
displayHelper
ctx context.Context
history history.History
roots map[hash.Hash]node.RootType
}
func (mh *migrateHelper) GetRootForHash(root hash.Hash, version uint64) ([]node.Root, error) {
block, err := mh.history.GetBlock(mh.ctx, version)
if err != nil {
if errors.Is(err, roothash.ErrNotFound) {
return nil, badger.ErrVersionNotFound
}
return nil, err
}
var roots []node.Root
for _, blockRoot := range block.Header.StorageRoots() {
if blockRoot.Hash.Equal(&root) {
roots = append(roots, blockRoot)
}
}
return roots, nil
}
func parseRuntimes(args []string) ([]common.Namespace, error) {
var runtimes []common.Namespace
for _, arg := range args {
var runtimeID common.Namespace
if err := runtimeID.UnmarshalHex(arg); err != nil {
return nil, fmt.Errorf("malformed runtime identifier '%s': %w", arg, err)
}
runtimes = append(runtimes, runtimeID)
}
return runtimes, nil
}
func doMigrate(cmd *cobra.Command, args []string) error {
dataDir := cmdCommon.DataDir()
ctx := context.Background()
runtimes, err := parseRuntimes(args)
cobra.CheckErr(err)
for _, rt := range runtimes {
if pretty {
fmt.Printf(" ** Upgrading storage database for runtime %v...\n", rt)
}
err := func() error {
runtimeDir := registry.GetRuntimeStateDir(dataDir, rt)
history, err := history.New(runtimeDir, rt, nil, false)
if err != nil {
return fmt.Errorf("error creating history provider: %w", err)
}
defer history.Close()
nodeCfg := &db.Config{
DB: workerStorage.GetLocalBackendDBDir(runtimeDir, viper.GetString(workerStorage.CfgBackend)),
Namespace: rt,
}
helper := &migrateHelper{
ctx: ctx,
history: history,
roots: map[hash.Hash]node.RootType{},
}
newVersion, err := badger.Migrate(nodeCfg, helper)
if err != nil {
return fmt.Errorf("node database migrator returned error: %w", err)
}
logger.Info("successfully migrated node database", "new_version", newVersion)
return nil
}()
if err != nil {
logger.Error("error upgrading runtime", "rt", rt, "err", err)
if pretty {
fmt.Printf("error upgrading runtime %v: %v\n", rt, err)
}
return fmt.Errorf("error upgrading runtime %v: %w", rt, err)
}
}
return nil
}
func doCheck(cmd *cobra.Command, args []string) error {
dataDir := cmdCommon.DataDir()
ctx := context.Background()
runtimes, err := parseRuntimes(args)
cobra.CheckErr(err)
for _, rt := range runtimes {
if pretty {
fmt.Printf("Checking storage database for runtime %v...\n", rt)
}
err := func() error {
runtimeDir := registry.GetRuntimeStateDir(dataDir, rt)
nodeCfg := &db.Config{
DB: workerStorage.GetLocalBackendDBDir(runtimeDir, viper.GetString(workerStorage.CfgBackend)),
Namespace: rt,
}
display := &displayHelper{}
err := badger.CheckSanity(ctx, nodeCfg, display)
if err != nil {
return fmt.Errorf("node database checker returned error: %w", err)
}
logger.Info("node database seems to be error-free", "rt", rt)
return nil
}()
if err != nil {
logger.Error("error checking node database", "rt", rt, "err", err)
if pretty {
fmt.Printf("error checking node database for runtime %v: %v\n", rt, err)
}
return fmt.Errorf("error checking node database for runtime %v: %w", rt, err)
}
}
return nil
}
func doRenameNs(cmd *cobra.Command, args []string) error {
dataDir := cmdCommon.DataDir()
if len(args) != 2 {
return fmt.Errorf("need exactly two arguments (source and destination runtime IDs)")
}
var srcID, dstID common.Namespace
if err := srcID.UnmarshalHex(args[0]); err != nil {
return fmt.Errorf("malformed source runtime ID: %s", args[0])
}
if err := dstID.UnmarshalHex(args[1]); err != nil {
return fmt.Errorf("malformed source runtime ID: %s", args[0])
}
if pretty {
fmt.Printf("Renaming storage database for runtime from %s to %s...\n", srcID, dstID)
}
srcDir := registry.GetRuntimeStateDir(dataDir, srcID)
dstDir := registry.GetRuntimeStateDir(dataDir, dstID)
nodeCfg := &db.Config{
DB: workerStorage.GetLocalBackendDBDir(srcDir, viper.GetString(workerStorage.CfgBackend)),
Namespace: srcID,
}
err := badger.RenameNamespace(nodeCfg, dstID)
if err != nil {
return fmt.Errorf("failed to rename namespace: %w", err)
}
if err = os.Rename(srcDir, dstDir); err != nil {
return fmt.Errorf("failed to move directory: %w", err)
}
// Remove history directory as that will be invalid now.
if err = os.RemoveAll(filepath.Join(dstDir, history.DbFilename)); err != nil {
return fmt.Errorf("failed to remove history directory: %w", err)
}
return nil
}
// Register registers the client sub-command and all of its children.
func Register(parentCmd *cobra.Command) {
storageMigrateCmd.Flags().AddFlagSet(registry.Flags)
storageCheckCmd.Flags().AddFlagSet(registry.Flags)
storageCmd.AddCommand(storageMigrateCmd)
storageCmd.AddCommand(storageCheckCmd)
storageCmd.AddCommand(storageRenameNsCmd)
parentCmd.AddCommand(storageCmd)
}