code.vegaprotocol.io/vega@v0.79.0/datanode/networkhistory/snapshot/service.go (about) 1 // Copyright (C) 2023 Gobalsky Labs Limited 2 // 3 // This program is free software: you can redistribute it and/or modify 4 // it under the terms of the GNU Affero General Public License as 5 // published by the Free Software Foundation, either version 3 of the 6 // License, or (at your option) any later version. 7 // 8 // This program is distributed in the hope that it will be useful, 9 // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 // GNU Affero General Public License for more details. 12 // 13 // You should have received a copy of the GNU Affero General Public License 14 // along with this program. If not, see <http://www.gnu.org/licenses/>. 15 16 package snapshot 17 18 import ( 19 "context" 20 "fmt" 21 "io/fs" 22 "os" 23 "path/filepath" 24 25 "code.vegaprotocol.io/vega/datanode/networkhistory/segment" 26 "code.vegaprotocol.io/vega/datanode/networkhistory/snapshot/mutex" 27 "code.vegaprotocol.io/vega/logging" 28 29 "github.com/jackc/pgx/v4/pgxpool" 30 ) 31 32 type HistoryStore interface { 33 StagedSegment(ctx context.Context, s segment.Full) (segment.Staged, error) 34 } 35 36 type Service struct { 37 log *logging.Logger 38 config Config 39 connPool *pgxpool.Pool 40 41 historyStore HistoryStore 42 43 createSnapshotLock mutex.CtxMutex 44 copyToPath string 45 migrateSchemaUpToVersion func(version int64) error 46 migrateSchemaDownToVersion func(version int64) error 47 } 48 49 func NewSnapshotService(log *logging.Logger, config Config, connPool *pgxpool.Pool, 50 historyStore HistoryStore, 51 snapshotsCopyToPath string, 52 migrateDatabaseToVersion func(version int64) error, 53 migrateSchemaDownToVersion func(version int64) error, 54 ) (*Service, error) { 55 var err error 56 57 if snapshotsCopyToPath, err = filepath.Abs(snapshotsCopyToPath); err != nil { 58 return nil, err 59 } 60 61 s := &Service{ 62 log: log, 63 config: config, 64 connPool: connPool, 65 createSnapshotLock: mutex.New(), 66 copyToPath: snapshotsCopyToPath, 67 migrateSchemaUpToVersion: migrateDatabaseToVersion, 68 migrateSchemaDownToVersion: migrateSchemaDownToVersion, 69 historyStore: historyStore, 70 } 71 72 err = os.MkdirAll(s.copyToPath, fs.ModePerm) 73 if err != nil { 74 return nil, fmt.Errorf("failed to create the snapshots dir %s: %w", s.copyToPath, err) 75 } 76 77 return s, nil 78 } 79 80 func (b *Service) SnapshotData(ctx context.Context, chainID string, toHeight int64) error { 81 _, err := b.CreateSnapshotAsynchronously(ctx, chainID, toHeight) 82 if err != nil { 83 return fmt.Errorf("failed to create snapshot for height %d: %w", toHeight, err) 84 } 85 86 return nil 87 }