Search in sources :

Example 1 with LogLevel

use of org.aion.log.LogLevel in project aion by aionnetwork.

the class EditCliTest method paramsForTestConverter.

public Object paramsForTestConverter() {
    List<Object> params = new ArrayList<>();
    EditCli.EnabledConverter enabledConverter = new EditCli.EnabledConverter();
    EditCli.DBVendorConverter dbVendorConverter = new EditCli.DBVendorConverter();
    EditCli.DBPruneOptionConverter dbPruneOptionConverter = new EditCli.DBPruneOptionConverter();
    EditCli.PortNumberConverter portNumberConverter = new EditCli.PortNumberConverter();
    EditCli.LogConverter logConverter = new EditCli.LogConverter();
    params.add(new Object[] { "on", enabledConverter, true });
    params.add(new Object[] { "off", enabledConverter, false });
    for (DBVendor vendor : DBVendor.values()) {
        if (!vendor.equals(DBVendor.UNKNOWN)) {
            params.add(new Object[] { vendor.toString().toUpperCase(), dbVendorConverter, vendor });
            params.add(new Object[] { vendor.toString().toLowerCase(), dbVendorConverter, vendor });
        }
    }
    for (CfgDb.PruneOption pruneOption : CfgDb.PruneOption.values()) {
        params.add(new Object[] { pruneOption.toString().toUpperCase(), dbPruneOptionConverter, pruneOption });
        params.add(new Object[] { pruneOption.toString().toLowerCase(), dbPruneOptionConverter, pruneOption });
    }
    for (LogEnum logEnum : LogEnum.values()) {
        for (LogLevel logLevel : LogLevel.values()) {
            params.add(new Object[] { logEnum.toString() + "=" + logLevel.toString(), logConverter, new Object[] { logEnum, logLevel } });
        }
    }
    int[] ports = { 0x1, 0xF, 0xFF, 0xFFF, 0xFFFF };
    for (Integer port : ports) {
        params.add(new Object[] { port.toString(), portNumberConverter, port });
    }
    return params;
}
Also used : PruneOption(org.aion.zero.impl.config.CfgDb.PruneOption) CfgDb(org.aion.zero.impl.config.CfgDb) ArrayList(java.util.ArrayList) DBVendor(org.aion.db.impl.DBVendor) LogLevel(org.aion.log.LogLevel) LogEnum(org.aion.log.LogEnum)

Example 2 with LogLevel

use of org.aion.log.LogLevel in project aion by aionnetwork.

the class Cli method call.

private ReturnType call(final String[] args, CfgAion cfg, boolean initializeAvm) {
    final CommandLine.ParseResult parseResult;
    try {
        // the pre-process method handles arguments that are separated by space
        // parsing populates the options object
        parseResult = parser.parseArgs(Arguments.preProcess(args));
    } catch (Exception e) {
        System.out.println("Unable to parse the input arguments due to: ");
        if (e.getMessage() != null) {
            System.out.println(e.getMessage());
        } else {
            e.printStackTrace();
        }
        System.out.println();
        printHelp();
        return ERROR;
    }
    // make sure that there is no conflicting arguments; otherwise send warning
    checkArguments(options, parseResult);
    try {
        if (options.isHelp()) {
            printHelp();
            return EXIT;
        }
        if (options.isVersion() || options.isVersionTag()) {
            if (options.isVersion()) {
                System.out.println("\nVersion");
                System.out.println("--------------------------------------------");
            }
            System.out.println(Version.KERNEL_VERSION);
            return EXIT;
        }
        if (options.getNetwork() != null || (options.getConfig() != null && !options.getConfig().isEmpty())) {
            String strNet = options.getNetwork();
            // the network given in config overwrites the -n option
            if (options.getConfig() != null && !options.getConfig().isEmpty()) {
                strNet = options.getConfig();
            }
            setNetwork(strNet, cfg);
        // no return -> allow for other parameters combined with -n
        }
        if (options.getDirectory() != null) {
            if (!setDirectory(options.getDirectory(), cfg)) {
                return ERROR;
            }
        // no return -> allow for other parameters combined with -d
        }
        // reading from correct config file
        File configFile = cfg.getExecConfigFile();
        if (!configFile.exists()) {
            configFile = cfg.getInitialConfigFile();
        } else {
            cfg.setReadConfigFile(configFile);
        }
        // reading from correct fork file
        File forkFile = cfg.getForkFile();
        if (forkFile != null && forkFile.exists()) {
            cfg.setForkProperties(cfg.getNetwork(), forkFile);
        }
        // true means the UUID must be set
        boolean overwrite = cfg.fromXML(configFile);
        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ initialize the avm ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        if (initializeAvm) {
            try {
                // Grab the project root directory.
                String projectRootDirectory = System.getProperty("user.dir") + File.separator;
                // Create the multi-version schedule. Note that avm version 1 is always enabled, from block zero
                // because it handles balance transfers. The kernel is responsible for ensuring it is not called
                // with anything else.
                Properties forkProperties = CfgAion.inst().getFork().getProperties();
                String fork2 = forkProperties.getProperty("fork1.0");
                AvmVersionSchedule schedule;
                if (fork2 != null) {
                    schedule = AvmVersionSchedule.newScheduleForBothVersions(0, Long.valueOf(fork2), 100);
                } else {
                    schedule = AvmVersionSchedule.newScheduleForOnlySingleVersionSupport(0, 100);
                }
                AvmConfigurations.initializeConfigurationsAsReadOnly(schedule, projectRootDirectory);
            } catch (Exception e) {
                System.out.println("A fatal error occurred attempting to configure the AVM: " + e.getMessage());
                System.exit(SystemExitCodes.INITIALIZATION_ERROR);
            }
        }
        // determine the port configuration, can be combined with the -n, -d, -c, -i arguments
        if (parseResult.subcommand() != null && parseResult.subcommand().commandSpec().userObject().getClass() == EditCli.class && editCli.runCommand(cfg)) {
            overwrite = true;
        }
        if (editCli.help) {
            return ReturnType.EXIT;
        }
        if (options.getPort() != null) {
            int currentPort = cfg.getNet().getP2p().getPort();
            int portNumber = currentPort;
            boolean validPort = true;
            try {
                portNumber = Integer.parseInt(options.getPort());
            } catch (NumberFormatException e) {
                validPort = false;
                System.out.println("Port must be a positive integer value");
            }
            if (portNumber < 0 || portNumber > 0xFFFF) {
                validPort = false;
                System.out.println("Port out of range: " + portNumber);
            }
            if (validPort && portNumber != currentPort) {
                // update port in config
                cfg.getNet().getP2p().setPort(portNumber);
                overwrite = true;
                System.out.println("Port set to: " + portNumber);
            } else {
                System.out.println("Using the current port configuration: " + currentPort);
            }
        // no return, allow for other parameters combined with -p
        }
        if (options.getConfig() != null) {
            // if the directory was set we generate a new file
            if (options.getDirectory() != null) {
                configFile = cfg.getExecConfigFile();
                // ensure path exists
                File dir = cfg.getExecConfigDirectory();
                if (!dir.exists()) {
                    if (!dir.mkdirs()) {
                        System.out.println("ERROR: Unable to create directory: " + getRelativePath(dir.getAbsolutePath()));
                        return ERROR;
                    }
                }
                try {
                    configFile.createNewFile();
                } catch (IOException e) {
                    System.out.println("ERROR: Unable to create file: " + getRelativePath(configFile.getAbsolutePath()));
                    return ERROR;
                }
            }
            // save to disk
            cfg.toXML(null, configFile);
            System.out.println("\nNew config generated at: " + getRelativePath(configFile.getAbsolutePath()));
            return ReturnType.EXIT;
        }
        if (options.isInfo()) {
            System.out.println("Reading config file from: " + getRelativePath(configFile.getAbsolutePath()));
            if (overwrite) {
                // updating the file in case the user id was not set; overwrite port
                cfg.toXML(null, configFile);
            }
            printInfo(cfg);
            return ReturnType.EXIT;
        }
        // make directories for kernel execution
        makeDirs(configFile, forkFile, cfg);
        if (overwrite) {
            // updating the file in case the user id was not set; overwrite port
            cfg.toXML(null, cfg.getExecConfigFile());
        }
        // set correct keystore directory
        Keystore.setKeystorePath(cfg.getKeystoreDir().getAbsolutePath());
        CommandSpec commandSpec = findCommandSpec(parseResult, AccountCli.class);
        if (commandSpec != null) {
            return ((AccountCli) commandSpec.userObject()).runCommand(passwordReader);
        }
        if (options.getSsl() != null) {
            String[] parameters = options.getSsl();
            if (parameters.length == 0 || parameters.length == 2) {
                createKeystoreDirIfMissing();
                Console console = System.console();
                checkConsoleExists(console);
                List<String> scriptArgs = new ArrayList<>();
                scriptArgs.add("/bin/bash");
                scriptArgs.add("script/generateSslCert.sh");
                scriptArgs.add(getCertName(console));
                scriptArgs.add(getCertPass(console));
                // add the hostname and ip optionally passed in as cli args
                scriptArgs.addAll(Arrays.asList(parameters));
                new ProcessBuilder(scriptArgs).inheritIO().start().waitFor();
                return EXIT;
            } else {
                System.out.println("Incorrect usage of -s create command.\n" + "Command must enter both hostname AND ip or else neither one.");
                return ERROR;
            }
        }
        if (options.isRebuildBlockInfo()) {
            System.out.println("Starting database clean-up.");
            CfgAion.inst().dbFromXML();
            Map<LogEnum, LogLevel> cfgLog = new HashMap<>();
            cfgLog.put(LogEnum.GEN, LogLevel.INFO);
            AionLoggerFactory.initAll(cfgLog);
            // get the current blockchain
            AionRepositoryImpl repository = AionRepositoryImpl.inst();
            repository.pruneAndCorrectBlockStore(AionLoggerFactory.getLogger(LogEnum.GEN.name()));
            repository.close();
            System.out.println("Finished database clean-up.");
            return EXIT;
        }
        if (options.getRevertToBlock() != null) {
            String block = options.getRevertToBlock();
            if (revertTo(block)) {
                System.out.println("Blockchain successfully reverted to block number " + block + ".");
                return EXIT;
            } else {
                System.out.println("Unable to revert to block number " + block + ".");
                return ERROR;
            }
        }
        if (options.getPruneStateOption() != null) {
            String pruning_type = options.getPruneStateOption();
            try {
                // ensure mining is disabled
                CfgAion localCfg = CfgAion.inst();
                localCfg.fromXML();
                localCfg.getConsensus().setMining(false);
                // setting pruning to the version requested
                CfgDb.PruneOption option = CfgDb.PruneOption.fromValue(pruning_type);
                localCfg.getDb().setPrune(option.toString());
                AionLoggerFactory.initAll(Map.of(LogEnum.GEN, LogLevel.INFO));
                final Logger log = AionLoggerFactory.getLogger(LogEnum.GEN.name());
                log.info("Reorganizing the state storage to " + option + " mode ...");
                AionBlockchainImpl chain = new AionBlockchainImpl(localCfg, null, false);
                chain.pruneOrRecoverState(pruning_type.equals("spread"), localCfg.getGenesis(), log);
                chain.close();
                return EXIT;
            } catch (Exception e) {
                System.out.println("Reorganizing the state storage FAILED due to:");
                e.printStackTrace();
                return ERROR;
            }
        }
        CommandLine.Model.CommandSpec spec = findCommandSpec(parseResult, DevCLI.class);
        if (spec != null) {
            ReturnType returnType = ((DevCLI) spec.userObject()).runCommand();
            if (returnType != RUN) {
                return returnType;
            }
        }
        if (options.isDbCompact()) {
            // read database configuration
            CfgAion.inst().dbFromXML();
            AionLoggerFactory.initAll(Map.of(LogEnum.DB, LogLevel.INFO));
            // get the current blockchain
            AionRepositoryImpl repository = AionRepositoryImpl.inst();
            // compact database after the changes were applied
            repository.compact();
            repository.close();
            return EXIT;
        }
        if (options.isRedoImport() != null) {
            long height = 0L;
            String parameter = options.isRedoImport();
            // ensure mining is disabled
            CfgAion localCfg = CfgAion.inst();
            localCfg.dbFromXML();
            localCfg.getConsensus().setMining(false);
            AionLoggerFactory.initAll(Map.of(LogEnum.GEN, LogLevel.INFO));
            final Logger log = AionLoggerFactory.getLogger(LogEnum.GEN.name());
            if (height < 0) {
                log.error("Negative values are not valid as starting height. Nothing to do.");
                return ERROR;
            }
            log.info("Importing stored blocks INITIATED...");
            AionBlockchainImpl chain = new AionBlockchainImpl(localCfg, null, false);
            if (parameter.isEmpty()) {
                chain.redoMainChainImport(height, localCfg.getGenesis(), log);
                chain.close();
                return EXIT;
            } else {
                try {
                    height = Long.parseLong(parameter);
                } catch (NumberFormatException e) {
                    log.error("The given argument «" + parameter + "» cannot be converted to a number.");
                    chain.close();
                    return ERROR;
                }
                chain.redoMainChainImport(height, localCfg.getGenesis(), log);
                chain.close();
                return EXIT;
            }
        }
        // if no return happened earlier, run the kernel
        return RUN;
    } catch (Exception e) {
        // TODO: should be moved to individual procedures
        System.out.println();
        e.printStackTrace();
        return ERROR;
    }
}
Also used : CfgDb(org.aion.zero.impl.config.CfgDb) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) AionRepositoryImpl(org.aion.zero.impl.db.AionRepositoryImpl) Properties(java.util.Properties) Logger(org.slf4j.Logger) LogLevel(org.aion.log.LogLevel) LogEnum(org.aion.log.LogEnum) CommandSpec(picocli.CommandLine.Model.CommandSpec) Console(java.io.Console) CommandSpec(picocli.CommandLine.Model.CommandSpec) AvmVersionSchedule(org.aion.zero.impl.vm.avm.schedule.AvmVersionSchedule) IOException(java.io.IOException) IOException(java.io.IOException) CfgAion(org.aion.zero.impl.config.CfgAion) CommandLine(picocli.CommandLine) AionBlockchainImpl(org.aion.zero.impl.blockchain.AionBlockchainImpl) File(java.io.File)

Example 3 with LogLevel

use of org.aion.log.LogLevel in project aion by aionnetwork.

the class Cli method revertTo.

/**
 * @return {@code true} if successful and {@code false} in case of any failure
 */
private boolean revertTo(String blockNumber) {
    // try to convert to long
    long block;
    try {
        block = Long.parseLong(blockNumber);
    } catch (NumberFormatException e) {
        System.out.println("The given argument «" + blockNumber + "» cannot be converted to a number.");
        return false;
    }
    // ensure mining is disabled
    CfgAion cfg = CfgAion.inst();
    cfg.dbFromXML();
    cfg.getConsensus().setMining(false);
    Map<LogEnum, LogLevel> cfgLog = new HashMap<>();
    cfgLog.put(LogEnum.GEN, LogLevel.INFO);
    AionLoggerFactory.initAll(cfgLog);
    final Logger log = AionLoggerFactory.getLogger(LogEnum.GEN.name());
    // get the current blockchain
    AionRepositoryImpl repository = AionRepositoryImpl.inst();
    boolean isSuccessful = repository.revertTo(block, log);
    repository.close();
    // ok if we managed to get down to the expected block
    return isSuccessful;
}
Also used : CfgAion(org.aion.zero.impl.config.CfgAion) LogEnum(org.aion.log.LogEnum) HashMap(java.util.HashMap) AionRepositoryImpl(org.aion.zero.impl.db.AionRepositoryImpl) Logger(org.slf4j.Logger) LogLevel(org.aion.log.LogLevel)

Example 4 with LogLevel

use of org.aion.log.LogLevel in project aion by aionnetwork.

the class CfgLog method toXML.

public String toXML() {
    final XMLOutputFactory output = XMLOutputFactory.newInstance();
    XMLStreamWriter xmlWriter;
    String xml;
    try {
        Writer strWriter = new StringWriter();
        xmlWriter = output.createXMLStreamWriter(strWriter);
        xmlWriter.writeCharacters("\r\n\t");
        xmlWriter.writeStartElement("log");
        xmlWriter.writeCharacters("\r\n");
        /*
             * XML - Displays tag/entry in the config.xml
             * Boolean value to allow logger to be toggled ON and OFF
             */
        xmlWriter.writeCharacters("\t\t");
        xmlWriter.writeComment("Enable/Disable logback service; if disabled, output will not be logged.");
        xmlWriter.writeCharacters("\r\n\t\t");
        xmlWriter.writeStartElement("log-file");
        xmlWriter.writeCharacters(this.logFile + "");
        xmlWriter.writeEndElement();
        xmlWriter.writeCharacters("\r\n");
        /*
             * XML - Displays log-path in the config.xml
             * String value to determine the folder path for log files
             */
        xmlWriter.writeCharacters("\t\t");
        xmlWriter.writeComment("Sets the physical location on disk where log files will be stored.");
        xmlWriter.writeCharacters("\r\n\t\t");
        xmlWriter.writeStartElement("log-path");
        xmlWriter.writeCharacters(this.logPath + "");
        xmlWriter.writeEndElement();
        xmlWriter.writeCharacters("\r\n");
        for (Map.Entry<LogEnum, LogLevel> module : this.modules.entrySet()) {
            xmlWriter.writeCharacters("\t\t");
            xmlWriter.writeStartElement(module.getKey().name());
            xmlWriter.writeCharacters(module.getValue().name());
            xmlWriter.writeEndElement();
            xmlWriter.writeCharacters("\r\n");
        }
        xmlWriter.writeCharacters("\t");
        xmlWriter.writeEndElement();
        xml = strWriter.toString();
        strWriter.flush();
        strWriter.close();
        xmlWriter.flush();
        xmlWriter.close();
        return xml;
    } catch (IOException | XMLStreamException e) {
        return "";
    }
}
Also used : XMLOutputFactory(javax.xml.stream.XMLOutputFactory) StringWriter(java.io.StringWriter) XMLStreamException(javax.xml.stream.XMLStreamException) LogEnum(org.aion.log.LogEnum) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) IOException(java.io.IOException) Map(java.util.Map) HashMap(java.util.HashMap) StringWriter(java.io.StringWriter) Writer(java.io.Writer) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) LogLevel(org.aion.log.LogLevel)

Example 5 with LogLevel

use of org.aion.log.LogLevel in project aion by aionnetwork.

the class EditCliTest method paramsForTestConverterValidation.

public Object paramsForTestConverterValidation() {
    List<Object[]> params = new ArrayList<>();
    EditCli.EnabledConverter enabledConverter = new EditCli.EnabledConverter();
    EditCli.DBVendorConverter dbVendorConverter = new EditCli.DBVendorConverter();
    EditCli.DBPruneOptionConverter dbPruneOptionConverter = new EditCli.DBPruneOptionConverter();
    EditCli.PortNumberConverter portNumberConverter = new EditCli.PortNumberConverter();
    EditCli.LogConverter logConverter = new EditCli.LogConverter();
    params.add(new Object[] { "onn", enabledConverter });
    params.add(new Object[] { "offf", enabledConverter });
    params.add(new Object[] { "on".toUpperCase(), enabledConverter });
    params.add(new Object[] { "off".toUpperCase(), enabledConverter });
    params.add(new Object[] { "".toUpperCase(), enabledConverter });
    for (DBVendor vendor : DBVendor.values()) {
        params.add(new Object[] { vendor + "1", dbVendorConverter });
    }
    params.add(new Object[] { "", dbVendorConverter });
    for (CfgDb.PruneOption pruneOption : CfgDb.PruneOption.values()) {
        params.add(new Object[] { pruneOption.toString().toUpperCase() + "1", dbPruneOptionConverter });
        params.add(new Object[] { pruneOption.toString().toLowerCase() + "1", dbPruneOptionConverter });
    }
    params.add(new Object[] { "", dbPruneOptionConverter });
    for (LogEnum logEnum : LogEnum.values()) {
        for (LogLevel logLevel : LogLevel.values()) {
            params.add(new Object[] { logEnum.toString() + "-" + logLevel.toString(), logConverter });
            params.add(new Object[] { logEnum.toString() + "=" + logLevel.toString() + "1", logConverter });
            params.add(new Object[] { logEnum.toString() + "1" + "=" + logLevel.toString() + "1", logConverter });
            params.add(new Object[] { logEnum.toString() + "1" + "=" + logLevel.toString(), logConverter });
        }
    }
    params.add(new Object[] { "", logConverter });
    int[] ports = { 0x0, 0xFFFF + 1 };
    for (Integer port : ports) {
        params.add(new Object[] { port.toString(), portNumberConverter });
    }
    params.add(new Object[] { "", portNumberConverter });
    return params;
}
Also used : PruneOption(org.aion.zero.impl.config.CfgDb.PruneOption) CfgDb(org.aion.zero.impl.config.CfgDb) ArrayList(java.util.ArrayList) DBVendor(org.aion.db.impl.DBVendor) LogLevel(org.aion.log.LogLevel) LogEnum(org.aion.log.LogEnum)

Aggregations

LogEnum (org.aion.log.LogEnum)5 LogLevel (org.aion.log.LogLevel)5 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 CfgDb (org.aion.zero.impl.config.CfgDb)3 IOException (java.io.IOException)2 DBVendor (org.aion.db.impl.DBVendor)2 CfgAion (org.aion.zero.impl.config.CfgAion)2 PruneOption (org.aion.zero.impl.config.CfgDb.PruneOption)2 AionRepositoryImpl (org.aion.zero.impl.db.AionRepositoryImpl)2 Logger (org.slf4j.Logger)2 Console (java.io.Console)1 File (java.io.File)1 StringWriter (java.io.StringWriter)1 Writer (java.io.Writer)1 Map (java.util.Map)1 Properties (java.util.Properties)1 XMLOutputFactory (javax.xml.stream.XMLOutputFactory)1 XMLStreamException (javax.xml.stream.XMLStreamException)1 XMLStreamWriter (javax.xml.stream.XMLStreamWriter)1