|
| 1 | +/* |
| 2 | +Copyright 2026 The Kubernetes Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package ipam |
| 18 | + |
| 19 | +import ( |
| 20 | + "database/sql" |
| 21 | + _ "embed" |
| 22 | + "fmt" |
| 23 | + "os" |
| 24 | + "path/filepath" |
| 25 | + |
| 26 | + "github.com/go-logr/logr" |
| 27 | + _ "github.com/mattn/go-sqlite3" // SQLite driver |
| 28 | +) |
| 29 | + |
| 30 | +//go:embed schema.sql |
| 31 | +var schemaSQL string |
| 32 | + |
| 33 | +const ( |
| 34 | + // dbSchemaVersion tracks the SQLite schema version to allow safe local |
| 35 | + // migrations and prevent state corruption across daemon restarts. |
| 36 | + dbSchemaVersion = 1 |
| 37 | + maxOpenConns = 10 |
| 38 | + maxIdleConns = 10 |
| 39 | +) |
| 40 | + |
| 41 | +// Store manages database operations for IPAM. |
| 42 | +type Store struct { |
| 43 | + db *sql.DB |
| 44 | + log logr.Logger |
| 45 | +} |
| 46 | + |
| 47 | +// NewStore creates a new Store instance and initializes the database. |
| 48 | +func NewStore(log logr.Logger, dbPath string) (*Store, error) { |
| 49 | + if dbPath == "" { |
| 50 | + return nil, fmt.Errorf("dbPath cannot be empty: an absolute path must be explicitly provided") |
| 51 | + } |
| 52 | + |
| 53 | + log.Info("Opening or creating database", "path", dbPath) |
| 54 | + |
| 55 | + if err := os.MkdirAll(filepath.Dir(dbPath), 0755); err != nil { |
| 56 | + return nil, fmt.Errorf("failed to create db directory: %w", err) |
| 57 | + } |
| 58 | + |
| 59 | + // SQLite is configured directly through the DSN string. This approach |
| 60 | + // guarantees every new connection spawned by the sql.DB pool inherits these |
| 61 | + // exact configurations natively. |
| 62 | + dsn := dbPath + |
| 63 | + // Enables Write-Ahead Logging (WAL) mode. This significantly improves |
| 64 | + // concurrency by allowing multiple readers to access the database |
| 65 | + // simultaneously without blocking a writer, which is critical for burst |
| 66 | + // requests. |
| 67 | + // See: https://www.sqlite.org/pragma.html#pragma_journal_mode |
| 68 | + "?_journal_mode=WAL" + |
| 69 | + // Enforces foreign key constraints. SQLite ignores these by default. |
| 70 | + // This is required to ensure ON DELETE CASCADE functions correctly on the |
| 71 | + // ip_addresses table when a draining CIDR block is officially removed. |
| 72 | + // See: https://www.sqlite.org/pragma.html#pragma_foreign_keys |
| 73 | + "&_foreign_keys=on" + |
| 74 | + // Sets the busy timeout to 5000 milliseconds. If the database is locked |
| 75 | + // by another transaction, this tells the SQLite driver to wait for up |
| 76 | + // to 5 seconds before giving up and returning a locked error. |
| 77 | + // See: https://www.sqlite.org/pragma.html#pragma_busy_timeout |
| 78 | + "&_busy_timeout=5000" + |
| 79 | + // Instructs the Go driver to send "BEGIN IMMEDIATE" instead of standard |
| 80 | + // "BEGIN" when starting a transaction. This grabs a write lock instantly, |
| 81 | + // preventing deadlocks when concurrent requests try to upgrade their |
| 82 | + // read locks to write locks simultaneously. Note: This is a go-sqlite3 |
| 83 | + // driver feature, not a native SQLite PRAGMA. |
| 84 | + // See: https://github.com/mattn/go-sqlite3#connection-string |
| 85 | + "&_txlock=immediate" + |
| 86 | + // Maps to PRAGMA synchronous = NORMAL. In WAL mode, this is the optimal |
| 87 | + // setting for high-concurrency daemons. It prevents database corruption |
| 88 | + // during power loss or hard crashes while offering much faster write |
| 89 | + // performance than FULL mode, sacrificing only a few milliseconds of |
| 90 | + // un-checkpointed durability. |
| 91 | + // See: https://www.sqlite.org/pragma.html#pragma_synchronous |
| 92 | + "&_synchronous=1" |
| 93 | + |
| 94 | + db, err := sql.Open("sqlite3", dsn) |
| 95 | + if err != nil { |
| 96 | + return nil, fmt.Errorf("failed to open database: %w", err) |
| 97 | + } |
| 98 | + |
| 99 | + db.SetMaxOpenConns(maxOpenConns) |
| 100 | + db.SetMaxIdleConns(maxIdleConns) |
| 101 | + // Sets the maximum amount of time a connection may be reused to infinity |
| 102 | + // (0). This guarantees the single connection never expires. |
| 103 | + db.SetConnMaxLifetime(0) |
| 104 | + |
| 105 | + store := &Store{ |
| 106 | + db: db, |
| 107 | + log: log, |
| 108 | + } |
| 109 | + |
| 110 | + // Only a single process enters this execution block at a time. |
| 111 | + if err := store.initSchema(); err != nil { |
| 112 | + db.Close() |
| 113 | + return nil, fmt.Errorf("failed to initialize schema: %w", err) |
| 114 | + } |
| 115 | + |
| 116 | + log.Info("Initialized or updated database schema", "path", dbPath) |
| 117 | + |
| 118 | + return store, nil |
| 119 | +} |
| 120 | + |
| 121 | +// initSchema creates the necessary tables if they don't exist. |
| 122 | +func (s *Store) initSchema() error { |
| 123 | + var currentVersion int |
| 124 | + err := s.db.QueryRow("PRAGMA user_version").Scan(¤tVersion) |
| 125 | + if err != nil { |
| 126 | + return fmt.Errorf("failed to check schema version: %w", err) |
| 127 | + } |
| 128 | + |
| 129 | + if currentVersion == dbSchemaVersion { |
| 130 | + s.log.V(4).Info("Database schema already initialized", "version", currentVersion) |
| 131 | + return nil |
| 132 | + } |
| 133 | + |
| 134 | + s.log.Info("Initializing DB schema", "currentVersion", currentVersion, "expectedVersion", dbSchemaVersion) |
| 135 | + |
| 136 | + // 1. Begin an atomic transaction |
| 137 | + tx, err := s.db.Begin() |
| 138 | + if err != nil { |
| 139 | + return fmt.Errorf("failed to begin transaction: %w", err) |
| 140 | + } |
| 141 | + // Safe to defer; Rollback does nothing if Commit() is successful |
| 142 | + defer tx.Rollback() |
| 143 | + |
| 144 | + // 2. Execute the embedded schema.sql file |
| 145 | + if _, err := tx.Exec(schemaSQL); err != nil { |
| 146 | + return fmt.Errorf("failed to execute schema.sql: %w", err) |
| 147 | + } |
| 148 | + |
| 149 | + // 3. Set User Version |
| 150 | + setVersion := fmt.Sprintf("PRAGMA user_version = %d;", dbSchemaVersion) |
| 151 | + if _, err := tx.Exec(setVersion); err != nil { |
| 152 | + return fmt.Errorf("failed to set user_version: %w", err) |
| 153 | + } |
| 154 | + |
| 155 | + // 4. Commit everything atomically |
| 156 | + if err := tx.Commit(); err != nil { |
| 157 | + return fmt.Errorf("failed to commit schema transaction: %w", err) |
| 158 | + } |
| 159 | + |
| 160 | + s.log.Info("Database schema initialized or updated successfully") |
| 161 | + return nil |
| 162 | +} |
| 163 | + |
| 164 | +// Close safely closes the database connection and releases any file locks. |
| 165 | +// This should be called during the daemon's graceful shutdown sequence. |
| 166 | +func (s *Store) Close() error { |
| 167 | + s.log.Info("Closing IPAM database connection") |
| 168 | + |
| 169 | + if err := s.db.Close(); err != nil { |
| 170 | + return fmt.Errorf("failed to close database connection: %w", err) |
| 171 | + } |
| 172 | + |
| 173 | + return nil |
| 174 | +} |
0 commit comments