-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Expand file tree
/
Copy pathmigration_legacy_15_to_17_test.go
More file actions
454 lines (368 loc) · 15.9 KB
/
migration_legacy_15_to_17_test.go
File metadata and controls
454 lines (368 loc) · 15.9 KB
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
package migrations
// NOTE: These legacy migration tests require the local Kubo binary (built with 'make build') to be in PATH.
// The tests migrate from repo version 15 to 17, which requires both external (15→16) and embedded (16→17) migrations.
// This validates the transition from legacy external binaries to modern embedded migrations.
//
// To run these tests successfully:
// export PATH="$(pwd)/cmd/ipfs:$PATH"
// go test ./test/cli/migrations/
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
"testing"
"time"
"github.com/ipfs/kubo/test/cli/harness"
"github.com/stretchr/testify/require"
)
func TestMigration15To17(t *testing.T) {
t.Parallel()
// Test legacy migration from v15 to v17 (combines external 15→16 + embedded 16→17)
t.Run("daemon migrate: legacy 15 to 17", testDaemonMigration15To17)
t.Run("repo migrate: legacy 15 to 17", testRepoMigration15To17)
}
func TestMigration17To15Downgrade(t *testing.T) {
t.Parallel()
// Test reverse hybrid migration from v17 to v15 (embedded 17→16 + external 16→15)
t.Run("repo migrate: reverse hybrid 17 to 15", testRepoReverseHybridMigration17To15)
}
func testDaemonMigration15To17(t *testing.T) {
// TEST: Migration from v15 to v17 using 'ipfs daemon --migrate'
// This tests the dual migration path: external binary (15→16) + embedded (16→17)
// NOTE: This test may need to be revised/updated once repo version 18 is released,
// at that point only keep tests that use 'ipfs repo migrate'
node := setupStaticV15Repo(t)
// Create mock migration binary for 15→16 (16→17 will use embedded migration)
createMockMigrationBinary(t, "15", "16")
configPath := filepath.Join(node.Dir, "config")
versionPath := filepath.Join(node.Dir, "version")
// Verify starting conditions
versionData, err := os.ReadFile(versionPath)
require.NoError(t, err)
require.Equal(t, "15", strings.TrimSpace(string(versionData)), "Should start at version 15")
// Read original config to verify preservation of key fields
var originalConfig map[string]interface{}
configData, err := os.ReadFile(configPath)
require.NoError(t, err)
require.NoError(t, json.Unmarshal(configData, &originalConfig))
originalPeerID := getNestedValue(originalConfig, "Identity.PeerID")
// Run dual migration using daemon --migrate
stdoutOutput, migrationSuccess := runDaemonWithLegacyMigrationMonitoring(t, node)
// Debug output
t.Logf("Daemon output:\n%s", stdoutOutput)
// Verify hybrid migration was successful
require.True(t, migrationSuccess, "Hybrid migration should have been successful")
require.Contains(t, stdoutOutput, "Phase 1: External migration from v15 to v16", "Should detect external migration phase")
require.Contains(t, stdoutOutput, "Phase 2: Embedded migration from v16 to v17", "Should detect embedded migration phase")
require.Contains(t, stdoutOutput, "Hybrid migration completed successfully", "Should confirm hybrid migration completion")
// Verify final version is 17
versionData, err = os.ReadFile(versionPath)
require.NoError(t, err)
require.Equal(t, "17", strings.TrimSpace(string(versionData)), "Version should be updated to 17")
// Verify config is still valid JSON and key fields preserved
var finalConfig map[string]interface{}
configData, err = os.ReadFile(configPath)
require.NoError(t, err)
require.NoError(t, json.Unmarshal(configData, &finalConfig), "Config should remain valid JSON")
// Verify essential fields preserved
finalPeerID := getNestedValue(finalConfig, "Identity.PeerID")
require.Equal(t, originalPeerID, finalPeerID, "Identity.PeerID should be preserved")
// Verify bootstrap exists (may be modified by 16→17 migration)
finalBootstrap := getNestedValue(finalConfig, "Bootstrap")
require.NotNil(t, finalBootstrap, "Bootstrap should exist after migration")
// Verify AutoConf was added by 16→17 migration
autoConf := getNestedValue(finalConfig, "AutoConf")
require.NotNil(t, autoConf, "AutoConf should be added by 16→17 migration")
}
func testRepoMigration15To17(t *testing.T) {
// TEST: Migration from v15 to v17 using 'ipfs repo migrate'
// Comparison test to verify repo migrate produces same results as daemon migrate
node := setupStaticV15Repo(t)
// Create mock migration binary for 15→16 (16→17 will use embedded migration)
createMockMigrationBinary(t, "15", "16")
configPath := filepath.Join(node.Dir, "config")
versionPath := filepath.Join(node.Dir, "version")
// Verify starting version
versionData, err := os.ReadFile(versionPath)
require.NoError(t, err)
require.Equal(t, "15", strings.TrimSpace(string(versionData)), "Should start at version 15")
// Run migration using 'ipfs repo migrate' with custom PATH
result := node.Runner.Run(harness.RunRequest{
Path: node.IPFSBin,
Args: []string{"repo", "migrate"},
CmdOpts: []harness.CmdOpt{
func(cmd *exec.Cmd) {
// Ensure the command inherits our modified PATH with mock binaries
cmd.Env = append(cmd.Env, "PATH="+os.Getenv("PATH"))
},
},
})
require.Empty(t, result.Stderr.String(), "Migration should succeed without errors")
// Verify final version is 17
versionData, err = os.ReadFile(versionPath)
require.NoError(t, err)
require.Equal(t, "17", strings.TrimSpace(string(versionData)), "Version should be updated to 17")
// Verify config is valid JSON
var finalConfig map[string]interface{}
configData, err := os.ReadFile(configPath)
require.NoError(t, err)
require.NoError(t, json.Unmarshal(configData, &finalConfig), "Config should remain valid JSON")
// Verify essential fields exist
require.NotNil(t, getNestedValue(finalConfig, "Identity.PeerID"), "Identity.PeerID should exist")
require.NotNil(t, getNestedValue(finalConfig, "Bootstrap"), "Bootstrap should exist")
require.NotNil(t, getNestedValue(finalConfig, "AutoConf"), "AutoConf should be added")
}
// setupStaticV15Repo creates a test node using static v15 repo fixture
// This ensures tests remain stable and validates migration from very old repos
func setupStaticV15Repo(t *testing.T) *harness.Node {
// Get path to static v15 repo fixture
v15FixturePath := "testdata/v15-repo"
// Create temporary test directory using Go's testing temp dir
tmpDir := t.TempDir()
// Use the built binary (should be in PATH)
node := harness.BuildNode("ipfs", tmpDir, 0)
// Copy static fixture to test directory
cloneStaticRepoFixture(t, v15FixturePath, node.Dir)
return node
}
// runDaemonWithLegacyMigrationMonitoring monitors for hybrid migration patterns
func runDaemonWithLegacyMigrationMonitoring(t *testing.T, node *harness.Node) (string, bool) {
// Monitor for hybrid migration completion - use "Hybrid migration completed successfully" as success pattern
stdoutOutput, daemonStarted := runDaemonWithMigrationMonitoringCustomEnv(t, node, "Using hybrid migration strategy", "Hybrid migration completed successfully", map[string]string{
"PATH": os.Getenv("PATH"), // Pass current PATH which includes our mock binaries
})
// Check for hybrid migration patterns in output
hasHybridStart := strings.Contains(stdoutOutput, "Using hybrid migration strategy")
hasPhase1 := strings.Contains(stdoutOutput, "Phase 1: External migration from v15 to v16")
hasPhase2 := strings.Contains(stdoutOutput, "Phase 2: Embedded migration from v16 to v17")
hasHybridSuccess := strings.Contains(stdoutOutput, "Hybrid migration completed successfully")
// Success requires daemon to start and hybrid migration patterns to be detected
hybridMigrationSuccess := daemonStarted && hasHybridStart && hasPhase1 && hasPhase2 && hasHybridSuccess
return stdoutOutput, hybridMigrationSuccess
}
// runDaemonWithMigrationMonitoringCustomEnv is like runDaemonWithMigrationMonitoring but allows custom environment
func runDaemonWithMigrationMonitoringCustomEnv(t *testing.T, node *harness.Node, migrationPattern, successPattern string, extraEnv map[string]string) (string, bool) {
// Create context with timeout as safety net
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
// Set up daemon command with output monitoring
cmd := exec.CommandContext(ctx, node.IPFSBin, "daemon", "--migrate")
cmd.Dir = node.Dir
// Set environment (especially IPFS_PATH)
for k, v := range node.Runner.Env {
cmd.Env = append(cmd.Env, k+"="+v)
}
// Add extra environment variables (like PATH with mock binaries)
for k, v := range extraEnv {
cmd.Env = append(cmd.Env, k+"="+v)
}
// Set up pipes for output monitoring
stdout, err := cmd.StdoutPipe()
require.NoError(t, err)
stderr, err := cmd.StderrPipe()
require.NoError(t, err)
// Start the daemon
require.NoError(t, cmd.Start())
// Register for cleanup in case of test failure
harness.RegisterBackgroundProcess(cmd.Process)
// Monitor output from both streams
var outputBuffer strings.Builder
done := make(chan bool)
migrationStarted := false
migrationCompleted := false
go func() {
scanner := bufio.NewScanner(io.MultiReader(stdout, stderr))
for scanner.Scan() {
line := scanner.Text()
outputBuffer.WriteString(line + "\n")
// Check for migration start
if strings.Contains(line, migrationPattern) {
migrationStarted = true
}
// Check for migration completion
if strings.Contains(line, successPattern) {
migrationCompleted = true
}
// Check for daemon ready
if strings.Contains(line, "Daemon is ready") {
done <- true
return
}
}
done <- false
}()
// Wait for daemon to be ready or timeout
daemonReady := false
select {
case ready := <-done:
daemonReady = ready
case <-ctx.Done():
t.Log("Daemon startup timed out")
}
// Stop the daemon
if cmd.Process != nil {
_ = cmd.Process.Signal(syscall.SIGTERM)
_ = cmd.Wait()
}
return outputBuffer.String(), daemonReady && migrationStarted && migrationCompleted
}
// createMockMigrationBinary creates a platform-agnostic Go binary for migration on PATH
func createMockMigrationBinary(t *testing.T, fromVer, toVer string) {
// Create bin directory for migration binaries
binDir := t.TempDir()
// Create Go source for mock migration binary
scriptName := fmt.Sprintf("fs-repo-%s-to-%s", fromVer, toVer)
sourceFile := filepath.Join(binDir, scriptName+".go")
binaryPath := filepath.Join(binDir, scriptName)
goSource := fmt.Sprintf(`package main
import (
"fmt"
"os"
"path/filepath"
"strings"
)
func main() {
// Parse command line arguments - real migration binaries expect -path=<repo-path>
var repoPath string
var revert bool
for _, arg := range os.Args[1:] {
if strings.HasPrefix(arg, "-path=") {
repoPath = strings.TrimPrefix(arg, "-path=")
} else if arg == "-revert" {
revert = true
}
}
if repoPath == "" {
fmt.Fprintf(os.Stderr, "Usage: %%s -path=<repo-path> [-verbose=true] [-revert]\n", os.Args[0])
os.Exit(1)
}
// Determine source and target versions based on revert flag
var sourceVer, targetVer string
if revert {
// When reverting, we go backwards: fs-repo-15-to-16 with -revert goes 16→15
sourceVer = "%s"
targetVer = "%s"
} else {
// Normal forward migration: fs-repo-15-to-16 goes 15→16
sourceVer = "%s"
targetVer = "%s"
}
// Print migration message (same format as real migrations)
fmt.Printf("fake applying %%s-to-%%s repo migration\n", sourceVer, targetVer)
// Update version file
versionFile := filepath.Join(repoPath, "version")
err := os.WriteFile(versionFile, []byte(targetVer), 0644)
if err != nil {
fmt.Fprintf(os.Stderr, "Error updating version: %%v\n", err)
os.Exit(1)
}
}
`, toVer, fromVer, fromVer, toVer)
require.NoError(t, os.WriteFile(sourceFile, []byte(goSource), 0644))
// Compile the Go binary
require.NoError(t, os.Setenv("CGO_ENABLED", "0")) // Ensure static binary
require.NoError(t, exec.Command("go", "build", "-o", binaryPath, sourceFile).Run())
// Add bin directory to PATH for this test
currentPath := os.Getenv("PATH")
newPath := binDir + string(filepath.ListSeparator) + currentPath
require.NoError(t, os.Setenv("PATH", newPath))
t.Cleanup(func() { os.Setenv("PATH", currentPath) })
// Verify the binary exists and is executable
_, err := os.Stat(binaryPath)
require.NoError(t, err, "Mock binary should exist")
}
// getNestedValue retrieves a nested value from a config map using dot notation
func getNestedValue(config map[string]interface{}, path string) interface{} {
parts := strings.Split(path, ".")
current := interface{}(config)
for _, part := range parts {
switch v := current.(type) {
case map[string]interface{}:
current = v[part]
default:
return nil
}
if current == nil {
return nil
}
}
return current
}
func testRepoReverseHybridMigration17To15(t *testing.T) {
// TEST: Reverse hybrid migration from v17 to v15 using 'ipfs repo migrate --to=15 --allow-downgrade'
// This tests reverse hybrid migration: embedded (17→16) + external (16→15)
// Start with v15 fixture and migrate forward to v17 to create proper backup files
node := setupStaticV15Repo(t)
// Create mock migration binary for 15→16 (needed for forward migration)
createMockMigrationBinary(t, "15", "16")
// Create mock migration binary for 16→15 (needed for downgrade)
createMockMigrationBinary(t, "16", "15")
configPath := filepath.Join(node.Dir, "config")
versionPath := filepath.Join(node.Dir, "version")
// Step 1: Forward migration from v15 to v17 to create backup files
t.Log("Step 1: Forward migration v15 → v17")
result := node.Runner.Run(harness.RunRequest{
Path: node.IPFSBin,
Args: []string{"repo", "migrate"},
CmdOpts: []harness.CmdOpt{
func(cmd *exec.Cmd) {
// Ensure the command inherits our modified PATH with mock binaries
cmd.Env = append(cmd.Env, "PATH="+os.Getenv("PATH"))
},
},
})
// Debug: print the output to see what happened
t.Logf("Forward migration stdout:\n%s", result.Stdout.String())
t.Logf("Forward migration stderr:\n%s", result.Stderr.String())
require.Empty(t, result.Stderr.String(), "Forward migration should succeed without errors")
// Verify we're at v17 after forward migration
versionData, err := os.ReadFile(versionPath)
require.NoError(t, err)
require.Equal(t, "17", strings.TrimSpace(string(versionData)), "Should be at version 17 after forward migration")
// Read config after forward migration to use as baseline for downgrade
var v17Config map[string]interface{}
configData, err := os.ReadFile(configPath)
require.NoError(t, err)
require.NoError(t, json.Unmarshal(configData, &v17Config))
originalPeerID := getNestedValue(v17Config, "Identity.PeerID")
// Step 2: Reverse hybrid migration from v17 to v15
t.Log("Step 2: Reverse hybrid migration v17 → v15")
result = node.Runner.Run(harness.RunRequest{
Path: node.IPFSBin,
Args: []string{"repo", "migrate", "--to=15", "--allow-downgrade"},
CmdOpts: []harness.CmdOpt{
func(cmd *exec.Cmd) {
// Ensure the command inherits our modified PATH with mock binaries
cmd.Env = append(cmd.Env, "PATH="+os.Getenv("PATH"))
},
},
})
require.Empty(t, result.Stderr.String(), "Reverse hybrid migration should succeed without errors")
// Debug output
t.Logf("Downgrade migration output:\n%s", result.Stdout.String())
// Verify final version is 15
versionData, err = os.ReadFile(versionPath)
require.NoError(t, err)
require.Equal(t, "15", strings.TrimSpace(string(versionData)), "Version should be updated to 15")
// Verify config is still valid JSON and key fields preserved
var finalConfig map[string]interface{}
configData, err = os.ReadFile(configPath)
require.NoError(t, err)
require.NoError(t, json.Unmarshal(configData, &finalConfig), "Config should remain valid JSON")
// Verify essential fields preserved
finalPeerID := getNestedValue(finalConfig, "Identity.PeerID")
require.Equal(t, originalPeerID, finalPeerID, "Identity.PeerID should be preserved")
// Verify bootstrap exists (may be modified by migrations)
finalBootstrap := getNestedValue(finalConfig, "Bootstrap")
require.NotNil(t, finalBootstrap, "Bootstrap should exist after migration")
// AutoConf should be removed by the downgrade (was added in 16→17)
autoConf := getNestedValue(finalConfig, "AutoConf")
require.Nil(t, autoConf, "AutoConf should be removed by downgrade to v15")
}