Search in sources :

Example 16 with CommandFailedException

use of org.neo4j.cli.CommandFailedException in project neo4j by neo4j.

the class LoadCommand method loadDump.

protected void loadDump() throws IOException {
    Config config = buildConfig();
    DatabaseLayout databaseLayout = Neo4jLayout.of(config).databaseLayout(database.name());
    ctx.fs().mkdirs(databaseLayout.databaseDirectory());
    ctx.fs().mkdirs(databaseLayout.getNeo4jLayout().transactionLogsRootDirectory());
    try (Closeable ignore = LockChecker.checkDatabaseLock(databaseLayout)) {
        deleteIfNecessary(databaseLayout, force);
        load(from, databaseLayout);
    } catch (FileLockException e) {
        throw new CommandFailedException("The database is in use. Stop database '" + database.name() + "' and try again.", e);
    } catch (IOException e) {
        wrapIOException(e);
    } catch (CannotWriteException e) {
        throw new CommandFailedException("You do not have permission to load the database.", e);
    }
    StoreVersionLoader.Result result = loader.getStoreVersion(ctx.fs(), config, databaseLayout);
    if (!result.isLatest) {
        ctx.err().printf("The loaded database is not on the latest format (current:%s, latest:%s). Set %s=true to enable migration.%n", result.currentFormatName, result.latestFormatName, GraphDatabaseSettings.allow_upgrade.name());
    }
}
Also used : FileLockException(org.neo4j.kernel.internal.locker.FileLockException) Config(org.neo4j.configuration.Config) Closeable(java.io.Closeable) DatabaseLayout(org.neo4j.io.layout.DatabaseLayout) Util.wrapIOException(org.neo4j.commandline.Util.wrapIOException) IOException(java.io.IOException) CommandFailedException(org.neo4j.cli.CommandFailedException)

Example 17 with CommandFailedException

use of org.neo4j.cli.CommandFailedException in project neo4j by neo4j.

the class HttpCopier method copy.

/**
 * Do the actual transfer of the source (a Neo4j database dump) to the target.
 */
@Override
public void copy(boolean verbose, String consoleURL, String boltUri, PushToCloudCommand.Source source, boolean deleteSourceAfterImport, String bearerToken) {
    try {
        String bearerTokenHeader = "Bearer " + bearerToken;
        long crc32Sum = source.crc32Sum();
        URL signedURL = retryOnUnavailable(() -> initiateCopy(verbose, safeUrl(consoleURL + "/import"), crc32Sum, source.size(), bearerTokenHeader));
        URL uploadLocation = retryOnUnavailable(() -> initiateResumableUpload(verbose, signedURL));
        long sourceLength = ctx.fs().getFileSize(source.path());
        // Enter the resume:able upload loop
        long position = 0;
        int resumeUploadRetries = 0;
        ThreadLocalRandom random = ThreadLocalRandom.current();
        ProgressTrackingOutputStream.Progress uploadProgress = new ProgressTrackingOutputStream.Progress(progressListenerFactory.create("Upload", sourceLength), position);
        while (!resumeUpload(verbose, source.path(), boltUri, sourceLength, position, uploadLocation, uploadProgress)) {
            position = getResumablePosition(verbose, sourceLength, uploadLocation);
            if (position == POSITION_UPLOAD_COMPLETED) {
                // got it responded that it was fully uploaded. I'd guess we're fine here.
                break;
            }
            // Truncated exponential backoff
            if (resumeUploadRetries > maxResumeUploadRetries) {
                throw new CommandFailedException("Upload failed after numerous attempts.");
            }
            long backoffFromRetryCount = SECONDS.toMillis(1 << resumeUploadRetries++) + random.nextInt(1_000);
            sleeper.sleep(min(backoffFromRetryCount, maximumBackoff));
        }
        uploadProgress.done();
        triggerImportProtocol(verbose, safeUrl(consoleURL + "/import/upload-complete"), boltUri, source.path(), crc32Sum, bearerTokenHeader);
        doStatusPolling(verbose, consoleURL, bearerToken, sourceLength);
        if (deleteSourceAfterImport) {
            Files.delete(source.path());
        } else {
            ctx.out().printf("It is safe to delete the dump file now: %s%n", source.path().toAbsolutePath());
        }
    } catch (InterruptedException | IOException e) {
        throw new CommandFailedException(e.getMessage(), e);
    }
}
Also used : ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) IOException(java.io.IOException) URL(java.net.URL) CommandFailedException(org.neo4j.cli.CommandFailedException)

Example 18 with CommandFailedException

use of org.neo4j.cli.CommandFailedException in project neo4j by neo4j.

the class PushToCloudCommand method execute.

@Override
public void execute() {
    try {
        if ((database == null || isBlank(database.name())) && (dump == null || isBlank(dump.toString()))) {
            database = new NormalizedDatabaseName(DEFAULT_DATABASE_NAME);
        }
        if (isBlank(username)) {
            if (isBlank(username = cons.readLine("%s", "Neo4j aura username (default: neo4j):"))) {
                username = "neo4j";
            }
        }
        char[] pass;
        if (isBlank(password)) {
            if ((pass = cons.readPassword("Neo4j aura password for %s:", username)).length == 0) {
                throw new CommandFailedException("Please supply a password, either by '--password' parameter, 'NEO4J_PASSWORD' environment variable, or prompt");
            }
        } else {
            pass = password.toCharArray();
        }
        String consoleURL = buildConsoleURI(boltURI);
        String bearerToken = copier.authenticate(verbose, consoleURL, username, pass, overwrite);
        Uploader uploader = prepareUploader(dump, database, tmpDumpFile);
        uploader.process(consoleURL, bearerToken);
    } catch (Exception e) {
        if (verbose) {
            e.printStackTrace(ctx.out());
        }
        throw e;
    }
}
Also used : NormalizedDatabaseName(org.neo4j.configuration.helpers.NormalizedDatabaseName) CommandFailedException(org.neo4j.cli.CommandFailedException) IOException(java.io.IOException) CommandFailedException(org.neo4j.cli.CommandFailedException)

Example 19 with CommandFailedException

use of org.neo4j.cli.CommandFailedException in project neo4j by neo4j.

the class PushToCloudCommand method buildConsoleURI.

private String buildConsoleURI(String boltURI) throws CommandFailedException {
    // A boltURI looks something like this:
    // 
    // bolt+routing://mydbid-myenvironment.databases.neo4j.io
    // <─┬──><──────┬─────>
    // │          └──────── environment
    // └─────────────────── database id
    // 
    // Constructing a console URI takes elements from the bolt URI and places them inside this URI:
    // 
    // https://console<environment>.neo4j.io/v1/databases/<database id>
    // 
    // Examples:
    // 
    // bolt+routing://rogue.databases.neo4j.io  --> https://console.neo4j.io/v1/databases/rogue
    // bolt+routing://rogue-mattias.databases.neo4j.io  --> https://console-mattias.neo4j.io/v1/databases/rogue
    Pattern pattern = Pattern.compile("(?:bolt(?:\\+routing)?|neo4j(?:\\+s|\\+ssc)?)://([^-]+)(-(.+))?.databases.neo4j.io$");
    Matcher matcher = pattern.matcher(boltURI);
    if (!matcher.matches()) {
        throw new CommandFailedException("Invalid Bolt URI '" + boltURI + "'");
    }
    String databaseId = matcher.group(1);
    String environment = matcher.group(2);
    return String.format("https://console%s.neo4j.io/v1/databases/%s", environment == null ? "" : environment, databaseId);
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) CommandFailedException(org.neo4j.cli.CommandFailedException)

Example 20 with CommandFailedException

use of org.neo4j.cli.CommandFailedException in project neo4j by neo4j.

the class HttpCopier method retryOnUnavailable.

<T> T retryOnUnavailable(IOExceptionSupplier<T> runnableCommand) {
    int attempt = 0;
    RetryableHttpException lastException = null;
    while (true) {
        try {
            return runnableCommand.get();
        } catch (RetryableHttpException e) {
            if (// Will retry one more, so in the end we have 1 + (n+1) retries
            attempt >= maxResumeUploadRetries) {
                break;
            }
            // Truncated exponential backoff
            ThreadLocalRandom random = ThreadLocalRandom.current();
            long backoffFromRetryCount = SECONDS.toMillis(1 << attempt++) + random.nextInt(1_000);
            try {
                sleeper.sleep(min(backoffFromRetryCount, maximumBackoff));
            } catch (InterruptedException ex) {
                throw new CommandFailedException(e.getMessage(), e);
            }
            lastException = e;
        } catch (IOException e) {
            throw new CommandFailedException(e.getMessage(), e);
        }
    }
    throw (RuntimeException) lastException.getCause();
}
Also used : ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) IOException(java.io.IOException) CommandFailedException(org.neo4j.cli.CommandFailedException)

Aggregations

CommandFailedException (org.neo4j.cli.CommandFailedException)34 Test (org.junit.jupiter.api.Test)20 IOException (java.io.IOException)10 Path (java.nio.file.Path)10 Config (org.neo4j.configuration.Config)9 DatabaseLayout (org.neo4j.io.layout.DatabaseLayout)9 FileSystemAbstraction (org.neo4j.io.fs.FileSystemAbstraction)8 DefaultFileSystemAbstraction (org.neo4j.io.fs.DefaultFileSystemAbstraction)6 Closeable (java.io.Closeable)5 ExecutionContext (org.neo4j.cli.ExecutionContext)5 FileLockException (org.neo4j.kernel.internal.locker.FileLockException)5 NoSuchFileException (java.nio.file.NoSuchFileException)3 CheckConsistencyCommand (org.neo4j.consistency.CheckConsistencyCommand)3 ConsistencyCheckService (org.neo4j.consistency.ConsistencyCheckService)3 FileAlreadyExistsException (java.nio.file.FileAlreadyExistsException)2 ThreadLocalRandom (java.util.concurrent.ThreadLocalRandom)2 ConsistencyFlags (org.neo4j.consistency.checking.full.ConsistencyFlags)2 ProgressMonitorFactory (org.neo4j.internal.helpers.progress.ProgressMonitorFactory)2 DatabaseLocker (org.neo4j.kernel.internal.locker.DatabaseLocker)2 Locker (org.neo4j.kernel.internal.locker.Locker)2