Search in sources :

Example 6 with SystemException

use of com.torodb.core.exceptions.SystemException in project torodb by torodb.

the class MongoClientConfigurationFactory method getMongoClientConfiguration.

public static MongoClientConfiguration getMongoClientConfiguration(AbstractReplication replication) {
    HostAndPort syncSource = HostAndPort.fromString(replication.getSyncSource()).withDefaultPort(27017);
    MongoClientConfiguration.Builder mongoClientConfigurationBuilder = new MongoClientConfiguration.Builder(syncSource);
    Ssl ssl = replication.getSsl();
    mongoClientConfigurationBuilder.setSslEnabled(ssl.getEnabled());
    if (ssl.getEnabled()) {
        try {
            mongoClientConfigurationBuilder.setSslAllowInvalidHostnames(ssl.getAllowInvalidHostnames());
            TrustManager[] tms = getTrustManagers(ssl);
            KeyManager[] kms = getKeyManagers(ssl);
            SSLContext sslContext;
            if (ssl.getFipsMode()) {
                sslContext = SSLContext.getInstance("TLS", "SunPKCS11-NSS");
            } else {
                sslContext = SSLContext.getInstance("TLS");
            }
            sslContext.init(kms, tms, null);
            mongoClientConfigurationBuilder.setSocketFactory(sslContext.getSocketFactory());
        } catch (CertificateException | KeyManagementException | KeyStoreException | UnrecoverableKeyException | NoSuchProviderException | NoSuchAlgorithmException | IOException exception) {
            throw new SystemException(exception);
        }
    }
    Auth auth = replication.getAuth();
    if (auth.getMode().isEnabled()) {
        MongoAuthenticationConfiguration mongoAuthenticationConfiguration = getMongoAuthenticationConfiguration(auth, ssl);
        mongoClientConfigurationBuilder.addAuthenticationConfiguration(mongoAuthenticationConfiguration);
    }
    return mongoClientConfigurationBuilder.build();
}
Also used : MongoAuthenticationConfiguration(com.eightkdata.mongowp.client.wrapper.MongoAuthenticationConfiguration) CertificateException(java.security.cert.CertificateException) SSLContext(javax.net.ssl.SSLContext) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) MongoClientConfiguration(com.eightkdata.mongowp.client.wrapper.MongoClientConfiguration) Ssl(com.torodb.packaging.config.model.protocol.mongo.Ssl) KeyManagementException(java.security.KeyManagementException) TrustManager(javax.net.ssl.TrustManager) HostAndPort(com.google.common.net.HostAndPort) UnrecoverableKeyException(java.security.UnrecoverableKeyException) SystemException(com.torodb.core.exceptions.SystemException) Auth(com.torodb.packaging.config.model.protocol.mongo.Auth) NoSuchProviderException(java.security.NoSuchProviderException) KeyManager(javax.net.ssl.KeyManager)

Example 7 with SystemException

use of com.torodb.core.exceptions.SystemException in project torodb by torodb.

the class Main method main.

public static void main(String[] args) throws Exception {
    Console console = JCommander.getConsole();
    ResourceBundle cliBundle = PropertyResourceBundle.getBundle("CliMessages");
    final CliConfig cliConfig = new CliConfig();
    JCommander jCommander = new JCommander(cliConfig, cliBundle, args);
    jCommander.setColumnSize(Integer.MAX_VALUE);
    if (cliConfig.isHelp()) {
        jCommander.usage();
        System.exit(0);
    }
    if (cliConfig.isHelpParam()) {
        console.println(cliBundle.getString("help-param-header"));
        ResourceBundle configBundle = PropertyResourceBundle.getBundle("ConfigMessages");
        ConfigUtils.printParamDescriptionFromConfigSchema(Config.class, configBundle, console, 0);
        System.exit(0);
    }
    final Config config = CliConfigUtils.readConfig(cliConfig);
    if (cliConfig.isPrintConfig()) {
        ConfigUtils.printYamlConfig(config, console);
        System.exit(0);
    }
    if (cliConfig.isPrintXmlConfig()) {
        ConfigUtils.printXmlConfig(config, console);
        System.exit(0);
    }
    configureLogger(cliConfig, config);
    config.getBackend().getBackendImplementation().accept(new BackendImplementationVisitor() {

        @Override
        public void visit(AbstractDerby value) {
            parseToropassFile(value);
        }

        @Override
        public void visit(AbstractPostgres value) {
            parseToropassFile(value);
        }

        public void parseToropassFile(BackendPasswordConfig value) {
            try {
                ConfigUtils.parseToropassFile(value);
            } catch (Exception ex) {
                throw new SystemException(ex);
            }
        }
    });
    if (config.getProtocol().getMongo().getReplication() != null) {
        for (AbstractReplication replication : config.getProtocol().getMongo().getReplication()) {
            if (replication.getAuth().getUser() != null) {
                HostAndPort syncSource = HostAndPort.fromString(replication.getSyncSource()).withDefaultPort(27017);
                ConfigUtils.parseMongopassFile(new MongoPasswordConfig() {

                    @Override
                    public void setPassword(String password) {
                        replication.getAuth().setPassword(password);
                    }

                    @Override
                    public String getUser() {
                        return replication.getAuth().getUser();
                    }

                    @Override
                    public Integer getPort() {
                        return syncSource.getPort();
                    }

                    @Override
                    public String getPassword() {
                        return replication.getAuth().getPassword();
                    }

                    @Override
                    public String getMongopassFile() {
                        return config.getProtocol().getMongo().getMongopassFile();
                    }

                    @Override
                    public String getHost() {
                        return syncSource.getHostText();
                    }

                    @Override
                    public String getDatabase() {
                        return replication.getAuth().getSource();
                    }
                });
            }
        }
    }
    if (config.getBackend().isLike(AbstractPostgres.class)) {
        AbstractPostgres postgres = config.getBackend().as(AbstractPostgres.class);
        if (cliConfig.isAskForPassword()) {
            console.print("Database user " + postgres.getUser() + " password:");
            postgres.setPassword(readPwd());
        }
    } else if (config.getBackend().isLike(AbstractDerby.class)) {
        AbstractDerby derby = config.getBackend().as(AbstractDerby.class);
        if (cliConfig.isAskForPassword()) {
            console.print("Database user " + derby.getUser() + " password:");
            derby.setPassword(readPwd());
        }
    }
    try {
        Clock clock = Clock.systemDefaultZone();
        Service server;
        if (config.getProtocol().getMongo().getReplication() == null || config.getProtocol().getMongo().getReplication().isEmpty()) {
            Service toroDbServer = ToroDbBootstrap.createStandaloneService(config, clock);
            toroDbServer.startAsync();
            toroDbServer.awaitRunning();
            server = toroDbServer;
        } else {
            throw new UnsupportedOperationException("Replication not supported yet!");
        }
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            server.stopAsync();
            server.awaitTerminated();
        }));
    } catch (CreationException ex) {
        ex.getErrorMessages().stream().forEach(m -> {
            if (m.getCause() != null) {
                LOGGER.error(m.getCause().getMessage());
            } else {
                LOGGER.error(m.getMessage());
            }
        });
        System.exit(1);
    } catch (Throwable ex) {
        LOGGER.error("Fatal error on initialization", ex);
        Throwable rootCause = Throwables.getRootCause(ex);
        String causeMessage = rootCause.getMessage();
        JCommander.getConsole().println("Fatal error while ToroDB was starting: " + causeMessage);
        System.exit(1);
    }
}
Also used : Charsets(com.google.common.base.Charsets) BackendPasswordConfig(com.torodb.packaging.config.model.backend.BackendPasswordConfig) Config(com.torodb.standalone.config.model.Config) JCommander(com.beust.jcommander.JCommander) Throwables(com.google.common.base.Throwables) PropertyResourceBundle(java.util.PropertyResourceBundle) IOException(java.io.IOException) Console(com.beust.jcommander.internal.Console) AbstractPostgres(com.torodb.packaging.config.model.backend.postgres.AbstractPostgres) HostAndPort(com.google.common.net.HostAndPort) Service(com.google.common.util.concurrent.Service) SystemException(com.torodb.core.exceptions.SystemException) BackendImplementationVisitor(com.torodb.packaging.config.visitor.BackendImplementationVisitor) ConfigUtils(com.torodb.packaging.config.util.ConfigUtils) CreationException(com.google.inject.CreationException) Logger(org.apache.logging.log4j.Logger) ResourceBundle(java.util.ResourceBundle) AbstractDerby(com.torodb.packaging.config.model.backend.derby.AbstractDerby) AbstractReplication(com.torodb.packaging.config.model.protocol.mongo.AbstractReplication) Clock(java.time.Clock) Log4jUtils(com.torodb.packaging.util.Log4jUtils) LogManager(org.apache.logging.log4j.LogManager) MongoPasswordConfig(com.torodb.packaging.config.model.protocol.mongo.MongoPasswordConfig) InputStream(java.io.InputStream) BackendPasswordConfig(com.torodb.packaging.config.model.backend.BackendPasswordConfig) Config(com.torodb.standalone.config.model.Config) MongoPasswordConfig(com.torodb.packaging.config.model.protocol.mongo.MongoPasswordConfig) BackendImplementationVisitor(com.torodb.packaging.config.visitor.BackendImplementationVisitor) MongoPasswordConfig(com.torodb.packaging.config.model.protocol.mongo.MongoPasswordConfig) Service(com.google.common.util.concurrent.Service) CreationException(com.google.inject.CreationException) AbstractReplication(com.torodb.packaging.config.model.protocol.mongo.AbstractReplication) AbstractPostgres(com.torodb.packaging.config.model.backend.postgres.AbstractPostgres) Clock(java.time.Clock) IOException(java.io.IOException) SystemException(com.torodb.core.exceptions.SystemException) CreationException(com.google.inject.CreationException) HostAndPort(com.google.common.net.HostAndPort) SystemException(com.torodb.core.exceptions.SystemException) JCommander(com.beust.jcommander.JCommander) Console(com.beust.jcommander.internal.Console) PropertyResourceBundle(java.util.PropertyResourceBundle) ResourceBundle(java.util.ResourceBundle) AbstractDerby(com.torodb.packaging.config.model.backend.derby.AbstractDerby) BackendPasswordConfig(com.torodb.packaging.config.model.backend.BackendPasswordConfig)

Example 8 with SystemException

use of com.torodb.core.exceptions.SystemException in project torodb by torodb.

the class DefaultIdentifierFactory method generateUniqueIdentifier.

private String generateUniqueIdentifier(NameChain nameChain, IdentifierChecker identifierChecker, String extraImmutableName) {
    final Instant beginInstant = Instant.now();
    final int maxSize = identifierConstraints.identifierMaxSize();
    String lastCollision = null;
    ChainConverterFactory straightConverterFactory = ChainConverterFactory.straight;
    Counter counter = new Counter();
    String identifier = buildIdentifier(nameChain, straightConverterFactory.getConverters(), maxSize, counter, identifierChecker, extraImmutableName);
    if (identifier.length() <= maxSize && identifierChecker.isUnique(identifier)) {
        return identifier;
    }
    if (identifier.length() <= maxSize) {
        lastCollision = identifier;
    }
    ChainConverterFactory counterChainConverterFactory = ChainConverterFactory.counter;
    NameConverter[] counterConverters = counterChainConverterFactory.getConverters();
    while (ChronoUnit.SECONDS.between(beginInstant, Instant.now()) < MAX_GENERATION_TIME) {
        identifier = buildIdentifier(nameChain, counterConverters, maxSize, counter, identifierChecker, extraImmutableName);
        if (identifier.length() > maxSize) {
            throw new SystemException("Counter generator did not fit in maxSize!");
        }
        if (identifierChecker.isUnique(identifier)) {
            return identifier;
        }
        lastCollision = identifier;
        counter.increment();
    }
    if (lastCollision != null) {
        throw new SystemException("Identifier collision(s) does not allow to generate a valid identifier. Last " + "collisioned identifier: " + lastCollision + ". Name chain: " + nameChain);
    }
    throw new SystemException("Can not generate a valid identifier. Name chain: " + nameChain);
}
Also used : SystemException(com.torodb.core.exceptions.SystemException) Instant(java.time.Instant)

Example 9 with SystemException

use of com.torodb.core.exceptions.SystemException in project torodb by torodb.

the class SchemaValidator method checkDatabaseSchema.

private void checkDatabaseSchema(Connection connection) throws InvalidDatabaseSchemaException {
    try {
        DatabaseMetaData metaData = connection.getMetaData();
        ResultSet resultSet = metaData.getSchemas();
        while (resultSet.next()) {
            if (resultSet.getString("TABLE_SCHEM").equals(schemaName)) {
                return;
            }
        }
        throw new IllegalStateException("The database " + database + " is associated with schema " + schemaName + " but there is no schema with that name");
    } catch (SQLException sqlException) {
        throw new SystemException(sqlException);
    }
}
Also used : SystemException(com.torodb.core.exceptions.SystemException) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) DatabaseMetaData(java.sql.DatabaseMetaData)

Example 10 with SystemException

use of com.torodb.core.exceptions.SystemException in project torodb by torodb.

the class OfficialDerbyDriver method getConfiguredDataSource.

@Override
public DataSource getConfiguredDataSource(DerbyDbBackendConfiguration configuration, String poolName) {
    DataSource dataSource;
    if (configuration.embedded()) {
        EmbeddedDataSource embeddedDataSource = new EmbeddedDataSource();
        embeddedDataSource.setCreateDatabase("create");
        if (configuration.inMemory()) {
            embeddedDataSource.setDatabaseName("memory:" + configuration.getDbName());
        } else {
            embeddedDataSource.setDatabaseName(configuration.getDbName());
        }
        try (Connection connection = embeddedDataSource.getConnection()) {
            LOGGER.debug("Derby test connection has been successfully created.");
        } catch (SQLException ex) {
            throw new SystemException(ex);
        }
        embeddedDataSource.setCreateDatabase(null);
        dataSource = embeddedDataSource;
    } else {
        ClientDataSource clientDataSource = new ClientDataSource();
        clientDataSource.setServerName(configuration.getDbHost());
        clientDataSource.setPortNumber(configuration.getDbPort());
        clientDataSource.setUser(configuration.getUsername());
        clientDataSource.setPassword(configuration.getPassword());
        if (configuration.inMemory()) {
            clientDataSource.setDatabaseName("memory:" + configuration.getDbName());
        } else {
            clientDataSource.setDatabaseName(configuration.getDbName());
        }
        dataSource = clientDataSource;
    }
    if (LOGGER.isTraceEnabled()) {
        try {
            dataSource.setLogWriter(LOGGER_WRITER);
        } catch (SQLException sqlException) {
            throw new SystemException(sqlException);
        }
    }
    //TODO
    try (Connection conn = dataSource.getConnection();
        Statement stat = conn.createStatement();
        ResultSet rs = stat.executeQuery("SELECT 1 FROM SYSIBM.SYSDUMMY1")) {
        rs.next();
    } catch (SQLException ex) {
        throw new SystemException(ex);
    }
    return dataSource;
}
Also used : SystemException(com.torodb.core.exceptions.SystemException) SQLException(java.sql.SQLException) Statement(java.sql.Statement) ClientDataSource(org.apache.derby.jdbc.ClientDataSource) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) EmbeddedDataSource(org.apache.derby.jdbc.EmbeddedDataSource) EmbeddedDataSource(org.apache.derby.jdbc.EmbeddedDataSource) DataSource(javax.sql.DataSource) ClientDataSource(org.apache.derby.jdbc.ClientDataSource)

Aggregations

SystemException (com.torodb.core.exceptions.SystemException)13 IOException (java.io.IOException)6 SQLException (java.sql.SQLException)4 HostAndPort (com.google.common.net.HostAndPort)3 InputStream (java.io.InputStream)3 Connection (java.sql.Connection)3 ResultSet (java.sql.ResultSet)3 JCommander (com.beust.jcommander.JCommander)2 Console (com.beust.jcommander.internal.Console)2 MongoAuthenticationConfiguration (com.eightkdata.mongowp.client.wrapper.MongoAuthenticationConfiguration)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 Charsets (com.google.common.base.Charsets)2 Throwables (com.google.common.base.Throwables)2 Service (com.google.common.util.concurrent.Service)2 CreationException (com.google.inject.CreationException)2 BackendPasswordConfig (com.torodb.packaging.config.model.backend.BackendPasswordConfig)2 AbstractDerby (com.torodb.packaging.config.model.backend.derby.AbstractDerby)2 AbstractPostgres (com.torodb.packaging.config.model.backend.postgres.AbstractPostgres)2 AbstractReplication (com.torodb.packaging.config.model.protocol.mongo.AbstractReplication)2 MongoPasswordConfig (com.torodb.packaging.config.model.protocol.mongo.MongoPasswordConfig)2