Serge Bazanski | a5baa87 | 2022-09-15 18:49:35 +0200 | [diff] [blame] | 1 | package component |
| 2 | |
| 3 | import ( |
| 4 | "database/sql" |
Serge Bazanski | 2fd37ea | 2023-04-06 14:48:53 +0200 | [diff] [blame] | 5 | "errors" |
Serge Bazanski | a5baa87 | 2022-09-15 18:49:35 +0200 | [diff] [blame] | 6 | "flag" |
Serge Bazanski | 48e9bab | 2023-02-20 15:28:59 +0100 | [diff] [blame] | 7 | "fmt" |
Serge Bazanski | a5baa87 | 2022-09-15 18:49:35 +0200 | [diff] [blame] | 8 | "net/url" |
| 9 | "os" |
| 10 | "sync" |
| 11 | |
| 12 | "github.com/cockroachdb/cockroach-go/v2/testserver" |
| 13 | "github.com/golang-migrate/migrate/v4" |
| 14 | _ "github.com/golang-migrate/migrate/v4/database/cockroachdb" |
| 15 | "github.com/golang-migrate/migrate/v4/source" |
| 16 | _ "github.com/lib/pq" |
| 17 | "k8s.io/klog/v2" |
| 18 | |
| 19 | "source.monogon.dev/metropolis/cli/pkg/datafile" |
| 20 | ) |
| 21 | |
| 22 | // CockroachConfig is the common configuration of a components' connection to |
| 23 | // CockroachDB. It's supposed to be instantiated within a Configuration struct |
| 24 | // of a component. |
| 25 | // |
| 26 | // It can be configured by flags (via RegisterFlags) or manually (eg. in tests). |
| 27 | type CockroachConfig struct { |
| 28 | // Migrations is the go-migrate source of migrations for this database. Usually |
| 29 | // this can be taken from a go-embedded set of migration files. |
| 30 | Migrations source.Driver |
| 31 | |
| 32 | // EndpointHost is the host part of the endpoint address of the database server. |
| 33 | EndpointHost string |
| 34 | // TLSKeyPath is the filesystem path of the x509 key used to authenticate to the |
| 35 | // database server. |
| 36 | TLSKeyPath string |
| 37 | // TLSKeyPath is the filesystem path of the x509 certificate used to |
| 38 | // authenticate to the database server. |
| 39 | TLSCertificatePath string |
| 40 | // TLSCACertificatePath is the filesystem path of the x509 CA certificate used |
| 41 | // to verify the database server's certificate. |
| 42 | TLSCACertificatePath string |
| 43 | // UserName is the username to be used on the database server. |
| 44 | UserName string |
| 45 | // UserName is the database name to be used on the database server. |
| 46 | DatabaseName string |
| 47 | |
| 48 | // InMemory indicates that an in-memory CockroachDB instance should be used. |
| 49 | // Data will be lost after the component shuts down. |
| 50 | InMemory bool |
| 51 | |
| 52 | // mu guards inMemoryInstance. |
| 53 | mu sync.Mutex |
| 54 | // inMemoryInstance is populated with a CockroachDB test server handle when |
| 55 | // InMemory is set and Connect()/MigrateUp() is called. |
| 56 | inMemoryInstance testserver.TestServer |
| 57 | } |
| 58 | |
| 59 | // RegisterFlags registers the connection configuration to be provided by flags. |
| 60 | // This must be called exactly once before then calling flags.Parse(). |
| 61 | func (c *CockroachConfig) RegisterFlags(prefix string) { |
| 62 | flag.StringVar(&c.EndpointHost, prefix+"_endpoint_host", "", "Host of CockroachDB endpoint for "+prefix) |
| 63 | flag.StringVar(&c.TLSKeyPath, prefix+"_tls_key_path", "", "Path to CockroachDB TLS client key for "+prefix) |
| 64 | flag.StringVar(&c.TLSCertificatePath, prefix+"_tls_certificate_path", "", "Path to CockroachDB TLS client certificate for "+prefix) |
| 65 | flag.StringVar(&c.TLSCACertificatePath, prefix+"_tls_ca_certificate_path", "", "Path to CockroachDB CA certificate for "+prefix) |
| 66 | flag.StringVar(&c.UserName, prefix+"_user_name", prefix, "CockroachDB user name for "+prefix) |
| 67 | flag.StringVar(&c.DatabaseName, prefix+"_database_name", prefix, "CockroachDB database name for "+prefix) |
| 68 | flag.BoolVar(&c.InMemory, prefix+"_eat_my_data", false, "Use in-memory CockroachDB for "+prefix+". Warning: Data will be lost at process shutdown!") |
| 69 | } |
| 70 | |
| 71 | // startInMemory starts an in-memory cockroachdb server as a subprocess, and |
| 72 | // returns a DSN that connects to the newly created database. |
| 73 | func (c *CockroachConfig) startInMemory(scheme string) string { |
| 74 | c.mu.Lock() |
| 75 | defer c.mu.Unlock() |
| 76 | |
| 77 | klog.Warningf("STARTING IN-MEMORY COCKROACHDB FOR TESTS") |
| 78 | klog.Warningf("ALL DATA WILL BE LOST AFTER SERVER SHUTDOWN!") |
| 79 | |
| 80 | if c.inMemoryInstance == nil { |
| 81 | opts := []testserver.TestServerOpt{ |
| 82 | testserver.SecureOpt(), |
| 83 | } |
| 84 | if path, err := datafile.ResolveRunfile("external/cockroach/cockroach"); err == nil { |
| 85 | opts = append(opts, testserver.CockroachBinaryPathOpt(path)) |
| 86 | } else { |
| 87 | if os.Getenv("TEST_TMPDIR") != "" { |
| 88 | klog.Exitf("In test which requires in-memory cockroachdb, but @cockroach//:cockroach missing as a dependency. Failing.") |
| 89 | } |
| 90 | klog.Warningf("CockroachDB in-memory database requested, but not available as a build dependency. Trying to download it...") |
| 91 | } |
| 92 | |
| 93 | inst, err := testserver.NewTestServer(opts...) |
| 94 | if err != nil { |
| 95 | klog.Exitf("Failed to create crdb test server: %v", err) |
| 96 | } |
| 97 | c.inMemoryInstance = inst |
| 98 | } |
| 99 | |
| 100 | u := *c.inMemoryInstance.PGURL() |
| 101 | u.Scheme = scheme |
| 102 | return u.String() |
| 103 | } |
| 104 | |
| 105 | // buildDSN returns a DSN to the configured database connection with a given DSN |
| 106 | // scheme. The scheme will usually be 'postgres' or 'cockroach', depending on |
| 107 | // whether it's used for lib/pq or for golang-migrate. |
| 108 | func (c *CockroachConfig) buildDSN(scheme string) string { |
| 109 | if c.InMemory { |
| 110 | return c.startInMemory(scheme) |
| 111 | } |
| 112 | |
| 113 | query := make(url.Values) |
| 114 | query.Set("sslmode", "verify-full") |
| 115 | query.Set("sslcert", c.TLSCertificatePath) |
| 116 | query.Set("sslkey", c.TLSKeyPath) |
| 117 | query.Set("sslrootcert", c.TLSCACertificatePath) |
| 118 | u := url.URL{ |
| 119 | Scheme: scheme, |
| 120 | User: url.User(c.UserName), |
| 121 | Host: c.EndpointHost, |
| 122 | Path: c.DatabaseName, |
| 123 | RawQuery: query.Encode(), |
| 124 | } |
| 125 | return u.String() |
| 126 | } |
| 127 | |
| 128 | // Connect returns a working *sql.DB handle to the database described by this |
| 129 | // CockroachConfig. |
| 130 | func (d *CockroachConfig) Connect() (*sql.DB, error) { |
| 131 | dsn := d.buildDSN("postgres") |
| 132 | klog.Infof("Connecting to %s...", dsn) |
| 133 | return sql.Open("postgres", d.buildDSN("postgres")) |
| 134 | } |
| 135 | |
| 136 | // MigrateUp performs all possible migrations upwards for the database described |
| 137 | // by this CockroachConfig. |
| 138 | func (d *CockroachConfig) MigrateUp() error { |
| 139 | dsn := d.buildDSN("cockroachdb") |
Serge Bazanski | 3ea40da | 2023-04-19 14:32:37 +0200 | [diff] [blame] | 140 | klog.Infof("Running migrations up...") |
Serge Bazanski | a5baa87 | 2022-09-15 18:49:35 +0200 | [diff] [blame] | 141 | m, err := migrate.NewWithSourceInstance("iofs", d.Migrations, dsn) |
| 142 | if err != nil { |
| 143 | return err |
| 144 | } |
Serge Bazanski | 2fd37ea | 2023-04-06 14:48:53 +0200 | [diff] [blame] | 145 | err = m.Up() |
| 146 | switch { |
| 147 | case err == nil: |
| 148 | return nil |
| 149 | case errors.Is(err, migrate.ErrNoChange): |
| 150 | return nil |
| 151 | default: |
| 152 | return err |
| 153 | } |
Serge Bazanski | a5baa87 | 2022-09-15 18:49:35 +0200 | [diff] [blame] | 154 | } |
Serge Bazanski | 48e9bab | 2023-02-20 15:28:59 +0100 | [diff] [blame] | 155 | |
Serge Bazanski | 3ea40da | 2023-04-19 14:32:37 +0200 | [diff] [blame] | 156 | func (d *CockroachConfig) MigrateUpToIncluding(ver uint) error { |
| 157 | dsn := d.buildDSN("cockroachdb") |
| 158 | klog.Infof("Running migrations up to %d...", ver) |
| 159 | m, err := migrate.NewWithSourceInstance("iofs", d.Migrations, dsn) |
| 160 | if err != nil { |
| 161 | return err |
| 162 | } |
| 163 | |
| 164 | return m.Migrate(ver) |
| 165 | } |
| 166 | |
Serge Bazanski | 48e9bab | 2023-02-20 15:28:59 +0100 | [diff] [blame] | 167 | // MigrateDownDangerDanger removes all data from the database by performing a |
| 168 | // full migration down. |
| 169 | // |
| 170 | // Let me reiterate: this function, by design, DESTROYS YOUR DATA. |
| 171 | // |
| 172 | // Obviously, this is a dangerous method. Thus, to prevent accidental nuking of |
| 173 | // production data, we currently only allow this to be performed on InMemory |
| 174 | // databases. |
| 175 | func (d *CockroachConfig) MigrateDownDangerDanger() error { |
| 176 | if !d.InMemory { |
| 177 | return fmt.Errorf("refusing to migrate down a non-in-memory database") |
| 178 | } |
| 179 | // Sneaky extra check to make sure the caller didn't just set InMemory after |
| 180 | // connecting to an external database. We really need to be safe here. |
| 181 | if d.inMemoryInstance == nil { |
| 182 | return fmt.Errorf("no really, this cannot be run on non-in-memory databases") |
| 183 | } |
| 184 | dsn := d.buildDSN("cockroachdb") |
Serge Bazanski | 3ea40da | 2023-04-19 14:32:37 +0200 | [diff] [blame] | 185 | klog.Infof("Running migrations down...") |
Serge Bazanski | 48e9bab | 2023-02-20 15:28:59 +0100 | [diff] [blame] | 186 | m, err := migrate.NewWithSourceInstance("iofs", d.Migrations, dsn) |
| 187 | if err != nil { |
| 188 | return err |
| 189 | } |
| 190 | // Final sneaky check, make sure the remote schema version is our maximum locally |
| 191 | // supported version. |
| 192 | v, _, err := m.Version() |
| 193 | if err != nil { |
| 194 | return fmt.Errorf("could not retrieve remote version: %w", err) |
| 195 | } |
| 196 | if v2, err := d.Migrations.Next(v); !os.IsNotExist(err) { |
| 197 | return fmt.Errorf("remote running version %d, but we know %d which is newer", v, v2) |
| 198 | } |
| 199 | return m.Down() |
| 200 | } |