Skip to content

Commit

Permalink
Use flyway to perform database migrations on startup
Browse files Browse the repository at this point in the history
  • Loading branch information
posulliv authored Jan 10, 2025
1 parent 1fab8ad commit 531929a
Show file tree
Hide file tree
Showing 19 changed files with 663 additions and 14 deletions.
4 changes: 0 additions & 4 deletions docker/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,3 @@ services:
timeout: 1s
retries: 60
start_period: 10s
volumes:
- target: /docker-entrypoint-initdb.d/1-gateway-ha-persistence-postgres.sql
source: ../gateway-ha/src/main/resources/gateway-ha-persistence-postgres.sql
type: bind
33 changes: 27 additions & 6 deletions docs/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,16 +38,37 @@ distribution is installed.

### Backend database

Trino Gateway requires a MySQL or PostgreSQL database.
Trino Gateway requires a MySQL or PostgreSQL database. Database initialization
is performed automatically when the Trino Gateway process starts. Migrations
are performed using `Flyway`.

Use the following scripts in the `gateway-ha/src/main/resources/` folder to
initialize the database:

* `gateway-ha-persistence-mysql.sql` for MySQL
* `gateway-ha-persistence-postgres.sql` for PostgreSQL
The migration files can viewed in the `gateway-ha/src/main/resources/` folder.
Each database type supported has its own sub-folder.

The files are also included in the JAR file.

If you do not want migrations to be performed automatically on startup, then
you can set `runMigrationsEnabled` to `false` in the data store configuration.
For example:

```yaml
dataStore:
jdbcUrl: jdbc:postgresql://postgres:5432/trino_gateway_db
user: USER
password: PASSWORD
driver: org.postgresql.Driver
queryHistoryHoursRetention: 24
runMigrationsEnabled: false
```
`Flyway` uses a transactional lock in databases that support it such as
[PostgreSQL](https://documentation.red-gate.com/fd/postgresql-database-235241807.html#).
In the scenario where multiple Trino Gateway instances are running and sharing
the same backend database, the first Trino Gateway instance to start will get
the lock and run the database migrations with `Flyway`. Other Trino Gateway
instances might fail during startup while migrations are running but once migrations
are completed they will start as expected.

### Trino clusters

The proxied Trino clusters behind the Trino Gateway must support the Trino JDBC
Expand Down
27 changes: 27 additions & 0 deletions gateway-ha/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
<frontend.pnpmRegistryURL>https://registry.npmmirror.com</frontend.pnpmRegistryURL>

<!-- dependency versions -->
<dep.flyway.version>11.0.1</dep.flyway.version>
<dep.jeasy.version>4.1.0</dep.jeasy.version>
<dep.mockito.version>5.14.2</dep.mockito.version>
<dep.okhttp3.version>4.12.0</dep.okhttp3.version>
Expand Down Expand Up @@ -237,6 +238,12 @@
<version>1.78.1</version>
</dependency>

<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
<version>${dep.flyway.version}</version>
</dependency>

<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
Expand Down Expand Up @@ -290,6 +297,20 @@
<scope>runtime</scope>
</dependency>

<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-database-postgresql</artifactId>
<version>${dep.flyway.version}</version>
<scope>runtime</scope>
</dependency>

<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-mysql</artifactId>
<version>${dep.flyway.version}</version>
<scope>runtime</scope>
</dependency>

<dependency>
<groupId>org.mvel</groupId>
<artifactId>mvel2</artifactId>
Expand Down Expand Up @@ -371,6 +392,12 @@
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>jdbc</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>mysql</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import io.airlift.units.Duration;
import io.trino.gateway.baseapp.BaseApp;
import io.trino.gateway.ha.config.HaGatewayConfiguration;
import io.trino.gateway.ha.persistence.FlywayMigration;
import org.weakref.jmx.guice.MBeanModule;

import java.nio.file.Files;
Expand Down Expand Up @@ -109,6 +110,7 @@ public static void main(String[] args)
}
String config = Files.readString(Path.of(args[0]));
HaGatewayConfiguration haGatewayConfiguration = objectMapper.readValue(replaceEnvironmentVariables(config), HaGatewayConfiguration.class);
FlywayMigration.migrate(haGatewayConfiguration.getDataStore());
List<Module> modules = addModules(haGatewayConfiguration);
new HaGatewayLauncher().start(modules, haGatewayConfiguration);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,16 @@ public class DataStoreConfiguration
private String password;
private String driver;
private Integer queryHistoryHoursRetention = 4;
private boolean runMigrationsEnabled = true;

public DataStoreConfiguration(String jdbcUrl, String user, String password, String driver, Integer queryHistoryHoursRetention)
public DataStoreConfiguration(String jdbcUrl, String user, String password, String driver, Integer queryHistoryHoursRetention, boolean runMigrationsEnabled)
{
this.jdbcUrl = jdbcUrl;
this.user = user;
this.password = password;
this.driver = driver;
this.queryHistoryHoursRetention = queryHistoryHoursRetention;
this.runMigrationsEnabled = runMigrationsEnabled;
}

public DataStoreConfiguration() {}
Expand Down Expand Up @@ -81,4 +83,14 @@ public void setQueryHistoryHoursRetention(Integer queryHistoryHoursRetention)
{
this.queryHistoryHoursRetention = queryHistoryHoursRetention;
}

public boolean isRunMigrationsEnabled()
{
return this.runMigrationsEnabled;
}

public void setRunMigrationsEnabled(boolean runMigrationsEnabled)
{
this.runMigrationsEnabled = runMigrationsEnabled;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.gateway.ha.persistence;

import io.airlift.log.Logger;
import io.trino.gateway.ha.config.DataStoreConfiguration;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.output.MigrateResult;

import static java.lang.String.format;

public class FlywayMigration
{
private static final Logger log = Logger.get(FlywayMigration.class);

private FlywayMigration() {}

private static String getLocation(String configDbUrl)
{
if (configDbUrl.startsWith("jdbc:postgresql")) {
return "postgresql";
}
if (configDbUrl.startsWith("jdbc:mysql")) {
return "mysql";
}
throw new IllegalArgumentException(format("Invalid JDBC URL: %s. Only PostgreSQL and MySQL are supported.", configDbUrl));
}

public static void migrate(DataStoreConfiguration config)
{
if (!config.isRunMigrationsEnabled()) {
log.info("Skip migrations as automatic migrations are disabled");
return;
}
log.info("Performing migrations...");
Flyway flyway = Flyway.configure()
.dataSource(config.getJdbcUrl(), config.getUser(), config.getPassword())
.locations(getLocation(config.getJdbcUrl()))
.baselineOnMigrate(true)
.baselineVersion("0")
.load();

MigrateResult migrations = flyway.migrate();
log.info("Performed %s migrations", migrations.migrationsExecuted);
}
}
78 changes: 78 additions & 0 deletions gateway-ha/src/main/resources/mysql/V1__create_schema.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
CREATE TABLE IF NOT EXISTS gateway_backend (
name VARCHAR(256) PRIMARY KEY,
routing_group VARCHAR (256),
backend_url VARCHAR (256),
external_url VARCHAR (256),
active BOOLEAN
);

CREATE TABLE IF NOT EXISTS query_history (
query_id VARCHAR(256) PRIMARY KEY,
query_text VARCHAR (256),
created bigint,
backend_url VARCHAR (256),
user_name VARCHAR(256),
source VARCHAR(256)
);
CREATE INDEX query_history_created_idx ON query_history(created);

CREATE TABLE IF NOT EXISTS resource_groups (
resource_group_id BIGINT NOT NULL AUTO_INCREMENT,
name VARCHAR(250) NOT NULL UNIQUE,

-- OPTIONAL POLICY CONTROLS
parent BIGINT NULL,
jmx_export BOOLEAN NULL,
scheduling_policy VARCHAR(128) NULL,
scheduling_weight INT NULL,

-- REQUIRED QUOTAS
soft_memory_limit VARCHAR(128) NOT NULL,
max_queued INT NOT NULL,
hard_concurrency_limit INT NOT NULL,

-- OPTIONAL QUOTAS
soft_concurrency_limit INT NULL,
soft_cpu_limit VARCHAR(128) NULL,
hard_cpu_limit VARCHAR(128) NULL,
environment VARCHAR(128) NULL,

PRIMARY KEY(resource_group_id),
FOREIGN KEY (parent) REFERENCES resource_groups (resource_group_id)
);

CREATE TABLE IF NOT EXISTS selectors (
resource_group_id BIGINT NOT NULL,
priority BIGINT NOT NULL,

-- Regex fields -- these will be used as a regular expression pattern to
-- match against the field of the same name on queries
user_regex VARCHAR(512),
source_regex VARCHAR(512),

-- Selector fields -- these must match exactly.
query_type VARCHAR(512),
client_tags VARCHAR(512),
selector_resource_estimate VARCHAR(1024),

FOREIGN KEY (resource_group_id) REFERENCES resource_groups(resource_group_id)
);

CREATE TABLE IF NOT EXISTS resource_groups_global_properties (
name VARCHAR(128) NOT NULL PRIMARY KEY,
value VARCHAR(512) NULL,
CHECK (name in ('cpu_quota_period'))
);

CREATE TABLE IF NOT EXISTS exact_match_source_selectors (
resource_group_id VARCHAR(256) NOT NULL,
update_time DATETIME NOT NULL,

-- Selector fields which must exactly match a query
source VARCHAR(512) NOT NULL,
environment VARCHAR(128),
query_type VARCHAR(512),

PRIMARY KEY (environment, source(128), query_type),
UNIQUE (source(128), environment, query_type(128), resource_group_id)
);
78 changes: 78 additions & 0 deletions gateway-ha/src/main/resources/postgresql/V1__create_schema.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
CREATE TABLE IF NOT EXISTS gateway_backend (
name VARCHAR(256) PRIMARY KEY,
routing_group VARCHAR (256),
backend_url VARCHAR (256),
external_url VARCHAR (256),
active BOOLEAN
);

CREATE TABLE IF NOT EXISTS query_history (
query_id VARCHAR(256) PRIMARY KEY,
query_text VARCHAR (256),
created bigint,
backend_url VARCHAR (256),
user_name VARCHAR(256),
source VARCHAR(256)
);
CREATE INDEX IF NOT EXISTS query_history_created_idx ON query_history(created);

CREATE TABLE IF NOT EXISTS resource_groups (
resource_group_id SERIAL,
name VARCHAR(250) NOT NULL UNIQUE,

-- OPTIONAL POLICY CONTROLS
parent BIGINT NULL,
jmx_export BOOLEAN NULL,
scheduling_policy VARCHAR(128) NULL,
scheduling_weight INT NULL,

-- REQUIRED QUOTAS
soft_memory_limit VARCHAR(128) NOT NULL,
max_queued INT NOT NULL,
hard_concurrency_limit INT NOT NULL,

-- OPTIONAL QUOTAS
soft_concurrency_limit INT NULL,
soft_cpu_limit VARCHAR(128) NULL,
hard_cpu_limit VARCHAR(128) NULL,
environment VARCHAR(128) NULL,

PRIMARY KEY(resource_group_id),
FOREIGN KEY (parent) REFERENCES resource_groups (resource_group_id)
);

CREATE TABLE IF NOT EXISTS selectors (
resource_group_id BIGINT NOT NULL,
priority BIGINT NOT NULL,

-- Regex fields -- these will be used as a regular expression pattern to
-- match against the field of the same name on queries
user_regex VARCHAR(512),
source_regex VARCHAR(512),

-- Selector fields -- these must match exactly.
query_type VARCHAR(512),
client_tags VARCHAR(512),
selector_resource_estimate VARCHAR(1024),

FOREIGN KEY (resource_group_id) REFERENCES resource_groups(resource_group_id)
);

CREATE TABLE IF NOT EXISTS resource_groups_global_properties (
name VARCHAR(128) NOT NULL PRIMARY KEY,
value VARCHAR(512) NULL,
CHECK (name in ('cpu_quota_period'))
);

CREATE TABLE IF NOT EXISTS exact_match_source_selectors (
resource_group_id VARCHAR(256) NOT NULL,
update_time TIMESTAMP NOT NULL,

-- Selector fields which must exactly match a query
source VARCHAR(512) NOT NULL,
environment VARCHAR(128),
query_type VARCHAR(128), -- (reduced from 512)

PRIMARY KEY (environment, source, query_type),
UNIQUE (source, environment, query_type, resource_group_id)
);
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ void setup()

// Setup resource group manager
String jdbcUrl = "jdbc:h2:" + testConfig.h2DbFilePath();
DataStoreConfiguration db = new DataStoreConfiguration(jdbcUrl, "sa", "sa", "org.h2.Driver", 4);
DataStoreConfiguration db = new DataStoreConfiguration(jdbcUrl, "sa", "sa", "org.h2.Driver", 4, false);
Jdbi jdbi = Jdbi.create(jdbcUrl, "sa", "sa");
connectionManager = new JdbcConnectionManager(jdbi, db);
resourceGroupManager = new HaResourceGroupsManager(connectionManager);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public static JdbcConnectionManager createTestingJdbcConnectionManager()
tempH2DbDir.deleteOnExit();
String jdbcUrl = "jdbc:h2:" + tempH2DbDir.getAbsolutePath();
HaGatewayTestUtils.seedRequiredData(new HaGatewayTestUtils.TestConfig("", tempH2DbDir.getAbsolutePath()));
DataStoreConfiguration db = new DataStoreConfiguration(jdbcUrl, "sa", "sa", "org.h2.Driver", 4);
DataStoreConfiguration db = new DataStoreConfiguration(jdbcUrl, "sa", "sa", "org.h2.Driver", 4, false);
Jdbi jdbi = Jdbi.create(jdbcUrl, "sa", "sa");
return new JdbcConnectionManager(jdbi, db);
}
Expand Down
Loading

0 comments on commit 531929a

Please sign in to comment.