Search in sources :

Example 21 with CliResult

use of com.quorum.tessera.cli.CliResult in project tessera by ConsenSys.

the class EnclaveCliAdapterTest method missingConfigurationOutputsErrorMessageAndUsage.

@Test
public void missingConfigurationOutputsErrorMessageAndUsage() {
    commandLine.execute();
    final CliResult result = commandLine.getExecutionResult();
    final String output = systemErrOutput.getLog();
    // assertThat(result).isEqualToComparingFieldByField(new CliResult(1, true, null));
    // assertThat(output).contains("Missing required option: '--configfile <config>'");
    assertThat(output).contains("Usage:", "Run a standalone enclave to perform encryption/decryption operations", "enclave -configfile <config> [-pidfile <pidFilePath>] [COMMAND]");
    assertThat(output).contains("Description:", "Run a standalone enclave, which will perform encryption/decryption operations", "for a transaction manager. This means that the transaction manager does not", "perform any of the operations inside its own process, shielding the user from");
    assertThat(output).contains("Options:", "      -configfile, --configfile <config>", "         Path to enclave configuration file", "      -pidfile, --pidfile <pidFilePath>", "         Create a file at the specified path containing the process' ID (PID)");
    assertThat(output).contains("Commands:", " help  Displays help information about the specified command");
}
Also used : CliResult(com.quorum.tessera.cli.CliResult) Test(org.junit.Test)

Example 22 with CliResult

use of com.quorum.tessera.cli.CliResult in project tessera by ConsenSys.

the class EnclaveCliAdapterTest method helpOptionOutputsUsageMessage.

@Test
public void helpOptionOutputsUsageMessage() {
    commandLine.execute("help");
    final CliResult result = commandLine.getExecutionResult();
    final String output = systemOutOutput.getLog();
    // assertThat(result).isEqualToComparingFieldByField(new CliResult(0, true, null));
    assertThat(result).isNull();
    assertThat(output).contains("Usage:", "Run a standalone enclave to perform encryption/decryption operations", "enclave -configfile <config> [-pidfile <pidFilePath>] [COMMAND]");
    assertThat(output).contains("Description:", "Run a standalone enclave, which will perform encryption/decryption operations", "for a transaction manager. This means that the transaction manager does not", "perform any of the operations inside its own process, shielding the user from");
    assertThat(output).contains("Options:", "      -configfile, --configfile <config>", "         Path to enclave configuration file", "      -pidfile, --pidfile <pidFilePath>", "         Create a file at the specified path containing the process' ID (PID)");
    assertThat(output).contains("Commands:", " help  Displays help information about the specified command");
}
Also used : CliResult(com.quorum.tessera.cli.CliResult) Test(org.junit.Test)

Example 23 with CliResult

use of com.quorum.tessera.cli.CliResult in project tessera by ConsenSys.

the class Main method main.

public static void main(final String... args) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    LOGGER.debug("args [{}]", String.join(",", args));
    try {
        PicoCliDelegate picoCliDelegate = new PicoCliDelegate();
        LOGGER.debug("Execute PicoCliDelegate with args [{}]", String.join(",", args));
        final CliResult cliResult = picoCliDelegate.execute(args);
        LOGGER.debug("Executed PicoCliDelegate with args [{}].", String.join(",", args));
        if (cliResult.isSuppressStartup()) {
            System.exit(0);
        }
        if (cliResult.getStatus() != 0) {
            System.exit(cliResult.getStatus());
        }
        final Config config = cliResult.getConfig().orElseThrow(() -> new NoSuchElementException("No config found. Tessera will not run."));
        // Start legacy spring profile stuff
        final String springProfileWarning = "Warn: Spring profiles will not be supported in future. To start in recover mode use 'tessera recover'";
        if (System.getProperties().containsKey("spring.profiles.active")) {
            System.out.println(springProfileWarning);
            config.setRecoveryMode(System.getProperty("spring.profiles.active").contains("enable-sync-poller"));
        } else if (System.getenv().containsKey("SPRING_PROFILES_ACTIVE")) {
            System.out.println(springProfileWarning);
            config.setRecoveryMode(System.getenv("SPRING_PROFILES_ACTIVE").contains("enable-sync-poller"));
        }
        // end spring profile stuff
        LOGGER.debug("Storing config {}", config);
        ConfigFactory.create().store(config);
        LOGGER.debug("Stored config {}", config);
        LOGGER.debug("Creating enclave");
        final Enclave enclave = Enclave.create();
        LOGGER.debug("Created enclave {}", enclave);
        LOGGER.debug("Creating RuntimeContext");
        final RuntimeContext runtimeContext = RuntimeContext.getInstance();
        LOGGER.debug("Created RuntimeContext {}", runtimeContext);
        LOGGER.debug("Creating Discovery");
        Discovery discovery = Discovery.create();
        discovery.onCreate();
        LOGGER.debug("Created Discovery {}", discovery);
        if (runtimeContext.isMultiplePrivateStates()) {
            LOGGER.debug("Creating ResidentGroupHandler");
            ResidentGroupHandler residentGroupHandler = ResidentGroupHandler.create();
            residentGroupHandler.onCreate(config);
            LOGGER.debug("Created ResidentGroupHandler {}", residentGroupHandler);
        }
        LOGGER.debug("Creating EncodedPayloadManager");
        EncodedPayloadManager.create();
        LOGGER.debug("Created EncodedPayloadManager");
        LOGGER.debug("Creating BatchResendManager");
        BatchResendManager.create();
        LOGGER.debug("Created BatchResendManager");
        LOGGER.debug("Creating txn manager");
        TransactionManager transactionManager = TransactionManager.create();
        LOGGER.debug("Created txn manager");
        LOGGER.debug("Validating if transaction table exists");
        if (!transactionManager.upcheck()) {
            throw new RuntimeException("The database has not been setup correctly. Please ensure transaction tables " + "are present and correct");
        }
        LOGGER.debug("Creating ScheduledServiceFactory");
        ScheduledServiceFactory scheduledServiceFactory = ScheduledServiceFactory.fromConfig(config);
        scheduledServiceFactory.build();
        LOGGER.debug("Created ScheduledServiceFactory");
        LOGGER.debug("Creating Launcher");
        final List<TesseraServer> tesseraServers = Launcher.create(runtimeContext.isRecoveryMode()).launchServer(config);
        LOGGER.debug("Created Launcher");
        if (config.getOutputServerURIPath() != null) {
            ServerURIFileWriter.writeURIFile(config.getOutputServerURIPath(), tesseraServers);
        }
    } catch (final ConstraintViolationException ex) {
        for (final ConstraintViolation<?> violation : ex.getConstraintViolations()) {
            System.err.println("ERROR: Config validation issue: " + violation.getPropertyPath() + " " + violation.getMessage());
        }
        System.exit(1);
    } catch (final ConfigException ex) {
        LOGGER.debug("", ex);
        final Throwable cause = ExceptionUtils.getRootCause(ex);
        if (JsonException.class.isInstance(cause)) {
            System.err.println("ERROR: Invalid json, cause is " + cause.getMessage());
        } else {
            System.err.println("ERROR: Configuration exception, cause is " + Objects.toString(cause));
        }
        System.exit(3);
    } catch (final CliException ex) {
        LOGGER.debug("", ex);
        System.err.println("ERROR: CLI exception, cause is " + ex.getMessage());
        System.exit(4);
    } catch (final ServiceConfigurationError ex) {
        LOGGER.debug("", ex);
        Optional<Throwable> e = Optional.of(ex);
        e.map(Throwable::getMessage).ifPresent(System.err::println);
        // get root cause
        while (e.map(Throwable::getCause).isPresent()) {
            e = e.map(Throwable::getCause);
        }
        e.map(Throwable::toString).ifPresent(System.err::println);
        System.exit(5);
    } catch (final Throwable ex) {
        LOGGER.debug(null, ex);
        if (Arrays.asList(args).contains("--debug")) {
            ex.printStackTrace();
        } else {
            if (Optional.ofNullable(ex.getMessage()).isPresent()) {
                System.err.println("ERROR: Cause is " + ex.getMessage());
            } else {
                System.err.println("ERROR: In class " + ex.getClass().getSimpleName());
            }
        }
        System.exit(2);
    }
}
Also used : JsonException(jakarta.json.JsonException) Config(com.quorum.tessera.config.Config) ResidentGroupHandler(com.quorum.tessera.privacygroup.ResidentGroupHandler) Discovery(com.quorum.tessera.discovery.Discovery) ConfigException(com.quorum.tessera.config.ConfigException) TesseraServer(com.quorum.tessera.server.TesseraServer) PicoCliDelegate(com.quorum.tessera.config.cli.PicoCliDelegate) CliException(com.quorum.tessera.cli.CliException) CliResult(com.quorum.tessera.cli.CliResult) Enclave(com.quorum.tessera.enclave.Enclave) TransactionManager(com.quorum.tessera.transaction.TransactionManager) ConstraintViolation(jakarta.validation.ConstraintViolation) ConstraintViolationException(jakarta.validation.ConstraintViolationException) RuntimeContext(com.quorum.tessera.context.RuntimeContext) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 24 with CliResult

use of com.quorum.tessera.cli.CliResult in project tessera by ConsenSys.

the class PicoCliDelegateTest method withRecoverMode.

@Test
public void withRecoverMode() throws Exception {
    Path configFile = Paths.get(getClass().getResource("/sample-config.json").toURI());
    CliResult result = cliDelegate.execute("-configfile", configFile.toString(), "-r");
    assertThat(result).isNotNull();
    assertThat(result.getConfig()).isPresent();
    assertThat(result.getStatus()).isEqualTo(0);
    Config config = result.getConfig().get();
    assertThat(config.isRecoveryMode()).isTrue();
}
Also used : Path(java.nio.file.Path) CliResult(com.quorum.tessera.cli.CliResult) KeyDataConfig(com.quorum.tessera.config.KeyDataConfig) Config(com.quorum.tessera.config.Config) Test(org.junit.Test)

Example 25 with CliResult

use of com.quorum.tessera.cli.CliResult in project tessera by ConsenSys.

the class PicoCliDelegateTest method keygenUpdateConfig.

@Test
public void keygenUpdateConfig() throws Exception {
    Path publicKeyPath = Files.createTempFile(UUID.randomUUID().toString(), "");
    Path privateKeyPath = Files.createTempFile(UUID.randomUUID().toString(), "");
    Files.write(privateKeyPath, Arrays.asList("SOMEDATA"));
    Files.write(publicKeyPath, Arrays.asList("SOMEDATA"));
    KeyEncryptor keyEncryptor = mock(KeyEncryptor.class);
    FilesystemKeyPair keypair = new FilesystemKeyPair(publicKeyPath, privateKeyPath, keyEncryptor);
    when(keyGenerator.generate(anyString(), eq(null), eq(null))).thenReturn(keypair);
    Path unixSocketPath = Files.createTempFile(UUID.randomUUID().toString(), ".ipc");
    Map<String, Object> params = new HashMap<>();
    params.put("unixSocketPath", unixSocketPath.toString());
    Path configFile = Paths.get(getClass().getResource("/keygen-sample.json").toURI());
    Path keyOutputPath = configFile.resolveSibling(UUID.randomUUID().toString());
    Path configOutputPath = configFile.resolveSibling(UUID.randomUUID().toString() + ".json");
    assertThat(Files.exists(configOutputPath)).isFalse();
    CliResult result = cliDelegate.execute("-keygen", "-filename", keyOutputPath.toString(), "-output", configOutputPath.toString(), "-configfile", configFile.toString());
    assertThat(result).isNotNull();
    assertThat(result.getStatus()).isEqualTo(0);
    assertThat(result.getConfig()).isNotNull();
    assertThat(result.isSuppressStartup()).isTrue();
    assertThat(Files.exists(configOutputPath)).isTrue();
    configOutputPath.toFile().deleteOnExit();
    verify(keyGenerator).generate(anyString(), eq(null), eq(null));
    verifyNoMoreInteractions(keyGenerator);
    try {
        cliDelegate.execute("-keygen", "-filename", UUID.randomUUID().toString(), "-output", configOutputPath.toString(), "-configfile", configFile.toString());
        failBecauseExceptionWasNotThrown(Exception.class);
    } catch (Exception ex) {
        assertThat(ex).isInstanceOf(UncheckedIOException.class);
        assertThat(ex.getCause()).isExactlyInstanceOf(FileAlreadyExistsException.class);
    }
}
Also used : Path(java.nio.file.Path) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) FilesystemKeyPair(com.quorum.tessera.config.keypairs.FilesystemKeyPair) HashMap(java.util.HashMap) CliResult(com.quorum.tessera.cli.CliResult) KeyEncryptor(com.quorum.tessera.config.keys.KeyEncryptor) UncheckedIOException(java.io.UncheckedIOException) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) CliException(com.quorum.tessera.cli.CliException) ConstraintViolationException(jakarta.validation.ConstraintViolationException) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) UncheckedIOException(java.io.UncheckedIOException) Test(org.junit.Test)

Aggregations

CliResult (com.quorum.tessera.cli.CliResult)38 Test (org.junit.Test)29 Path (java.nio.file.Path)15 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)10 CommandLine (picocli.CommandLine)9 CliException (com.quorum.tessera.cli.CliException)7 ConstraintViolationException (jakarta.validation.ConstraintViolationException)7 FilesystemKeyPair (com.quorum.tessera.config.keypairs.FilesystemKeyPair)6 Config (com.quorum.tessera.config.Config)5 ConfigConverter (com.quorum.tessera.cli.parsers.ConfigConverter)4 ConfigKeyPair (com.quorum.tessera.config.keypairs.ConfigKeyPair)4 KeyDataConfig (com.quorum.tessera.config.KeyDataConfig)3 KeyEncryptor (com.quorum.tessera.config.keys.KeyEncryptor)3 ConstraintViolation (jakarta.validation.ConstraintViolation)3 UncheckedIOException (java.io.UncheckedIOException)3 FileAlreadyExistsException (java.nio.file.FileAlreadyExistsException)3 HashMap (java.util.HashMap)3 Enclave (com.quorum.tessera.enclave.Enclave)2 EnclaveCliAdapter (com.quorum.tessera.enclave.server.EnclaveCliAdapter)2 TesseraServer (com.quorum.tessera.server.TesseraServer)2