View Javadoc
1   package de.dlr.shepard.common.neo4j;
2   
3   import ac.simons.neo4j.migrations.core.Migrations;
4   import ac.simons.neo4j.migrations.core.MigrationsConfig;
5   import ac.simons.neo4j.migrations.core.MigrationsConfig.VersionSortOrder;
6   import ac.simons.neo4j.migrations.core.MigrationsException;
7   import io.quarkus.logging.Log;
8   import java.nio.file.Paths;
9   import org.eclipse.microprofile.config.ConfigProvider;
10  import org.neo4j.driver.AuthTokens;
11  import org.neo4j.driver.Driver;
12  import org.neo4j.driver.GraphDatabase;
13  import org.neo4j.driver.exceptions.ServiceUnavailableException;
14  
15  public class MigrationsRunner {
16  
17    private Migrations migrations;
18    private Driver driver;
19  
20    public MigrationsRunner() {
21      String username = ConfigProvider.getConfig().getValue("neo4j.username", String.class);
22      String password = ConfigProvider.getConfig().getValue("neo4j.password", String.class);
23      String host = "neo4j://" + ConfigProvider.getConfig().getValue("neo4j.host", String.class);
24      driver = GraphDatabase.driver(host, AuthTokens.basic(username, password));
25  
26      // This is a workaround to make all migrations available in a dockerized quarkus jar.
27      // See https://gitlab.com/dlr-shepard/shepard/-/issues/146 for more information
28      var localPath = this.getClass().getClassLoader().getResource("neo4j/migrations").toString();
29      var dockerPath = Paths.get("/deployments/neo4j/migrations").toAbsolutePath().toString();
30      var isDocker = localPath.startsWith("jar");
31      var locationsToScan = isDocker ? dockerPath : localPath;
32  
33      var config = MigrationsConfig.builder()
34        .withTransactionMode(MigrationsConfig.TransactionMode.PER_STATEMENT)
35        .withPackagesToScan("de.dlr.shepard.common.neo4j.migrations")
36        .withLocationsToScan("file://" + locationsToScan)
37        .withVersionSortOrder(VersionSortOrder.SEMANTIC)
38        .build();
39  
40      migrations = new Migrations(config, driver);
41    }
42  
43    public void waitForConnection() {
44      while (true) {
45        try {
46          driver.verifyConnectivity();
47          break;
48        } catch (Exception e) {
49          Log.warn("Cannot connect to neo4j database. Retrying...");
50        }
51        try {
52          Thread.sleep(1000);
53        } catch (InterruptedException e) {
54          Log.error("Cannot sleep while waiting for neo4j Connection");
55          Thread.currentThread().interrupt();
56        }
57      }
58    }
59  
60    public void apply() {
61      try {
62        migrations.apply();
63      } catch (ServiceUnavailableException e) {
64        Log.error("Migrations cannot be executed because the neo4j database is not available");
65      } catch (MigrationsException e) {
66        Log.error("An error occurred during the execution of the migrations: ", e);
67      }
68    }
69  }