Skip to content

Commit 76e3425

Browse files
session: add migration code from kvdb to SQL
This commit introduces the migration logic for transitioning the sessions store from kvdb to SQL. Note that as of this commit, the migration is not yet triggered by any production code, i.e. only tests execute the migration logic.
1 parent dfd0931 commit 76e3425

File tree

2 files changed

+743
-0
lines changed

2 files changed

+743
-0
lines changed

session/sql_migration.go

Lines changed: 356 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,356 @@
1+
package session
2+
3+
import (
4+
"context"
5+
"database/sql"
6+
"errors"
7+
"fmt"
8+
"reflect"
9+
"time"
10+
11+
"github.com/davecgh/go-spew/spew"
12+
"github.com/lightninglabs/lightning-terminal/accounts"
13+
"github.com/lightninglabs/lightning-terminal/db/sqlc"
14+
"github.com/lightningnetwork/lnd/sqldb"
15+
"github.com/pmezard/go-difflib/difflib"
16+
)
17+
18+
var (
19+
// ErrMigrationMismatch is returned when the migrated session does not
20+
// match the original session.
21+
ErrMigrationMismatch = fmt.Errorf("migrated session does not match " +
22+
"original session")
23+
)
24+
25+
// MigrateSessionStoreToSQL runs the migration of all sessions from the KV
26+
// database to the SQL database. The migration is done in a single transaction
27+
// to ensure that all sessions are migrated or none at all.
28+
//
29+
// NOTE: As sessions may contain linked accounts, the accounts sql migration
30+
// MUST be run prior to this migration.
31+
func MigrateSessionStoreToSQL(ctx context.Context, kvStore *BoltStore,
32+
tx SQLQueries) error {
33+
34+
log.Infof("Starting migration of the KV sessions store to SQL")
35+
36+
kvSessions, err := kvStore.ListAllSessions(ctx)
37+
if err != nil {
38+
return err
39+
}
40+
41+
// If sessions are linked to a group, we must insert the initial session
42+
// of each group before the other sessions in that group. This ensures
43+
// we can retrieve the SQL group ID when inserting the remaining
44+
// sessions. Therefore, we first insert all initial group sessions,
45+
// allowing us to fetch the group IDs and insert the rest of the
46+
// sessions afterward.
47+
// We therefore filter out the initial sessions first, and then migrate
48+
// them prior to the rest of the sessions.
49+
var (
50+
initialGroupSessions []*Session
51+
linkedSessions []*Session
52+
)
53+
54+
for _, kvSession := range kvSessions {
55+
if kvSession.GroupID == kvSession.ID {
56+
initialGroupSessions = append(
57+
initialGroupSessions, kvSession,
58+
)
59+
} else {
60+
linkedSessions = append(linkedSessions, kvSession)
61+
}
62+
}
63+
64+
err = migrateSessionsToSQLAndValidate(ctx, tx, initialGroupSessions)
65+
if err != nil {
66+
return fmt.Errorf("migration of non-linked session failed: %w",
67+
err)
68+
}
69+
70+
err = migrateSessionsToSQLAndValidate(ctx, tx, linkedSessions)
71+
if err != nil {
72+
return fmt.Errorf("migration of linked session failed: %w", err)
73+
}
74+
75+
total := len(initialGroupSessions) + len(linkedSessions)
76+
log.Infof("All sessions migrated from KV to SQL. Total number of "+
77+
"sessions migrated: %d", total)
78+
79+
return nil
80+
}
81+
82+
// migrateSessionsToSQLAndValidate runs the migration for the passed sessions
83+
// from the KV database to the SQL database, and validates that the migrated
84+
// sessions match the original sessions.
85+
func migrateSessionsToSQLAndValidate(ctx context.Context,
86+
tx SQLQueries, kvSessions []*Session) error {
87+
88+
for _, kvSession := range kvSessions {
89+
err := migrateSingleSessionToSQL(ctx, tx, kvSession)
90+
if err != nil {
91+
return fmt.Errorf("unable to migrate session(%v): %w",
92+
kvSession.ID, err)
93+
}
94+
95+
// Validate that the session was correctly migrated and matches
96+
// the original session in the kv store.
97+
sqlSess, err := tx.GetSessionByAlias(ctx, kvSession.ID[:])
98+
if err != nil {
99+
if errors.Is(err, sql.ErrNoRows) {
100+
err = ErrSessionNotFound
101+
}
102+
return fmt.Errorf("unable to get migrated session "+
103+
"from sql store: %w", err)
104+
}
105+
106+
migratedSession, err := unmarshalSession(ctx, tx, sqlSess)
107+
if err != nil {
108+
return fmt.Errorf("unable to unmarshal migrated "+
109+
"session: %w", err)
110+
}
111+
112+
overrideSessionTimeZone(kvSession)
113+
overrideSessionTimeZone(migratedSession)
114+
overrideMacaroonRecipe(kvSession, migratedSession)
115+
116+
if !reflect.DeepEqual(kvSession, migratedSession) {
117+
diff := difflib.UnifiedDiff{
118+
A: difflib.SplitLines(
119+
spew.Sdump(kvSession),
120+
),
121+
B: difflib.SplitLines(
122+
spew.Sdump(migratedSession),
123+
),
124+
FromFile: "Expected",
125+
FromDate: "",
126+
ToFile: "Actual",
127+
ToDate: "",
128+
Context: 3,
129+
}
130+
diffText, _ := difflib.GetUnifiedDiffString(diff)
131+
132+
return fmt.Errorf("%w: %v.\n%v", ErrMigrationMismatch,
133+
kvSession.ID, diffText)
134+
}
135+
}
136+
137+
return nil
138+
}
139+
140+
// migrateSingleSessionToSQL runs the migration for a single session from the
141+
// KV database to the SQL database. Note that if the session links to an
142+
// account, the linked accounts store MUST have been migrated before that
143+
// session is migrated.
144+
func migrateSingleSessionToSQL(ctx context.Context,
145+
tx SQLQueries, session *Session) error {
146+
147+
var (
148+
acctID sql.NullInt64
149+
err error
150+
remotePubKey []byte
151+
)
152+
153+
session.AccountID.WhenSome(func(alias accounts.AccountID) {
154+
// Fetch the SQL ID for the account from the SQL store.
155+
var acctAlias int64
156+
acctAlias, err = alias.ToInt64()
157+
if err != nil {
158+
return
159+
}
160+
161+
var acctDBID int64
162+
acctDBID, err = tx.GetAccountIDByAlias(ctx, acctAlias)
163+
if errors.Is(err, sql.ErrNoRows) {
164+
err = accounts.ErrAccNotFound
165+
return
166+
} else if err != nil {
167+
return
168+
}
169+
170+
acctID = sqldb.SQLInt64(acctDBID)
171+
})
172+
if err != nil {
173+
return err
174+
}
175+
176+
if session.RemotePublicKey != nil {
177+
remotePubKey = session.RemotePublicKey.SerializeCompressed()
178+
}
179+
180+
// Proceed to insert the session into the sql db.
181+
sqlId, err := tx.InsertSession(ctx, sqlc.InsertSessionParams{
182+
Alias: session.ID[:],
183+
Label: session.Label,
184+
State: int16(session.State),
185+
Type: int16(session.Type),
186+
Expiry: session.Expiry.UTC(),
187+
CreatedAt: session.CreatedAt.UTC(),
188+
ServerAddress: session.ServerAddr,
189+
DevServer: session.DevServer,
190+
MacaroonRootKey: int64(session.MacaroonRootKey),
191+
PairingSecret: session.PairingSecret[:],
192+
LocalPrivateKey: session.LocalPrivateKey.Serialize(),
193+
LocalPublicKey: session.LocalPublicKey.SerializeCompressed(),
194+
RemotePublicKey: remotePubKey,
195+
Privacy: session.WithPrivacyMapper,
196+
AccountID: acctID,
197+
})
198+
if err != nil {
199+
return err
200+
}
201+
202+
// Since the InsertSession query doesn't support that we set the revoked
203+
// field during the insert, we need to set the field after the session
204+
// has been created.
205+
if !session.RevokedAt.IsZero() {
206+
err = tx.SetSessionRevokedAt(
207+
ctx, sqlc.SetSessionRevokedAtParams{
208+
ID: sqlId,
209+
RevokedAt: sqldb.SQLTime(
210+
session.RevokedAt.UTC(),
211+
),
212+
},
213+
)
214+
if err != nil {
215+
return err
216+
}
217+
}
218+
219+
// After the session has been inserted, we need to update the session
220+
// with the group ID if it is linked to a group. We need to do this
221+
// after the session has been inserted, because the group ID can be the
222+
// session itself, and therefore the SQL id for the session won't exist
223+
// prior to inserting the session.
224+
groupID, err := tx.GetSessionIDByAlias(ctx, session.GroupID[:])
225+
if errors.Is(err, sql.ErrNoRows) {
226+
return ErrUnknownGroup
227+
} else if err != nil {
228+
return fmt.Errorf("unable to fetch group(%x): %w",
229+
session.GroupID[:], err)
230+
}
231+
232+
// Now lets set the group ID for the session.
233+
err = tx.SetSessionGroupID(ctx, sqlc.SetSessionGroupIDParams{
234+
ID: sqlId,
235+
GroupID: sqldb.SQLInt64(groupID),
236+
})
237+
if err != nil {
238+
return fmt.Errorf("unable to set group Alias: %w", err)
239+
}
240+
241+
// Once we have the sqlID for the session, we can proceed to insert rows
242+
// into the linked child tables.
243+
if session.MacaroonRecipe != nil {
244+
// We start by inserting the macaroon permissions.
245+
for _, sessionPerm := range session.MacaroonRecipe.Permissions {
246+
err = tx.InsertSessionMacaroonPermission(
247+
ctx, sqlc.InsertSessionMacaroonPermissionParams{
248+
SessionID: sqlId,
249+
Entity: sessionPerm.Entity,
250+
Action: sessionPerm.Action,
251+
},
252+
)
253+
if err != nil {
254+
return err
255+
}
256+
}
257+
258+
// Next we insert the macaroon caveats.
259+
for _, caveat := range session.MacaroonRecipe.Caveats {
260+
err = tx.InsertSessionMacaroonCaveat(
261+
ctx, sqlc.InsertSessionMacaroonCaveatParams{
262+
SessionID: sqlId,
263+
CaveatID: caveat.Id,
264+
VerificationID: caveat.VerificationId,
265+
Location: sqldb.SQLStr(
266+
caveat.Location,
267+
),
268+
},
269+
)
270+
if err != nil {
271+
return err
272+
}
273+
}
274+
}
275+
276+
// That's followed by the feature config.
277+
if session.FeatureConfig != nil {
278+
for featureName, config := range *session.FeatureConfig {
279+
err = tx.InsertSessionFeatureConfig(
280+
ctx, sqlc.InsertSessionFeatureConfigParams{
281+
SessionID: sqlId,
282+
FeatureName: featureName,
283+
Config: config,
284+
},
285+
)
286+
if err != nil {
287+
return err
288+
}
289+
}
290+
}
291+
292+
// Finally we insert the privacy flags.
293+
for _, privacyFlag := range session.PrivacyFlags {
294+
err = tx.InsertSessionPrivacyFlag(
295+
ctx, sqlc.InsertSessionPrivacyFlagParams{
296+
SessionID: sqlId,
297+
Flag: int32(privacyFlag),
298+
},
299+
)
300+
if err != nil {
301+
return err
302+
}
303+
}
304+
305+
return nil
306+
}
307+
308+
// overrideSessionTimeZone overrides the time zone of the session to the local
309+
// time zone and chops off the nanosecond part for comparison. This is needed
310+
// because KV database stores times as-is which as an unwanted side effect would
311+
// fail migration due to time comparison expecting both the original and
312+
// migrated sessions to be in the same local time zone and in microsecond
313+
// precision. Note that PostgresSQL stores times in microsecond precision while
314+
// SQLite can store times in nanosecond precision if using TEXT storage class.
315+
func overrideSessionTimeZone(session *Session) {
316+
fixTime := func(t time.Time) time.Time {
317+
return t.In(time.Local).Truncate(time.Microsecond)
318+
}
319+
320+
if !session.Expiry.IsZero() {
321+
session.Expiry = fixTime(session.Expiry)
322+
}
323+
324+
if !session.CreatedAt.IsZero() {
325+
session.CreatedAt = fixTime(session.CreatedAt)
326+
}
327+
328+
if !session.RevokedAt.IsZero() {
329+
session.RevokedAt = fixTime(session.RevokedAt)
330+
}
331+
}
332+
333+
// overrideMacaroonRecipe overrides the MacaroonRecipe for the SQL session in a
334+
// certain scenario:
335+
// In the bbolt store, a session can have a non-nil macaroon struct, despite
336+
// both the permissions and caveats being nil. There is no way to represent this
337+
// in the SQL store, as the macaroon permissions and caveats are separate
338+
// tables. Therefore, in the scenario where a MacaroonRecipe exists for the
339+
// bbolt version, but both the permissions and caveats are nil, we override the
340+
// MacaroonRecipe for the SQL version and set it to a MacaroonRecipe with
341+
// nil permissions and caveats. This is needed to ensure that the deep equals
342+
// check in the migration validation does not fail in this scenario.
343+
func overrideMacaroonRecipe(kvSession *Session, migratedSession *Session) {
344+
if kvSession.MacaroonRecipe != nil {
345+
kvPerms := kvSession.MacaroonRecipe.Permissions
346+
kvCaveats := kvSession.MacaroonRecipe.Caveats
347+
348+
if kvPerms == nil && kvCaveats == nil {
349+
migratedSession.MacaroonRecipe = &MacaroonRecipe{}
350+
} else if kvPerms == nil {
351+
migratedSession.MacaroonRecipe.Permissions = nil
352+
} else if kvCaveats == nil {
353+
migratedSession.MacaroonRecipe.Caveats = nil
354+
}
355+
}
356+
}

0 commit comments

Comments
 (0)