Search in sources :

Example 1 with MainLogger

use of cn.nukkit.utils.MainLogger in project Nukkit by Nukkit.

the class Nukkit method main.

public static void main(String[] args) {
    // prefer IPv4 to stop any weird RakNet issues.
    System.setProperty("java.net.preferIPv4Stack", "true");
    // Shorter title for windows 8/2012
    String osName = System.getProperty("os.name").toLowerCase();
    if (osName.contains("windows")) {
        if (osName.contains("windows 8") || osName.contains("2012")) {
            shortTitle = true;
        }
    }
    LogLevel logLevel = LogLevel.DEFAULT_LEVEL;
    int index = -1;
    boolean skip = false;
    // 启动参数
    for (String arg : args) {
        index++;
        if (skip) {
            skip = false;
            continue;
        }
        switch(arg) {
            case "disable-ansi":
                ANSI = false;
                break;
            case "--verbosity":
            case "-v":
                skip = true;
                try {
                    String levelName = args[index + 1];
                    Set<String> levelNames = Arrays.stream(LogLevel.values()).map(level -> level.name().toLowerCase()).collect(Collectors.toSet());
                    if (!levelNames.contains(levelName.toLowerCase())) {
                        System.out.printf("'%s' is not a valid log level, using the default\n", levelName);
                        continue;
                    }
                    logLevel = Arrays.stream(LogLevel.values()).filter(level -> level.name().equalsIgnoreCase(levelName)).findAny().orElse(LogLevel.DEFAULT_LEVEL);
                } catch (ArrayIndexOutOfBoundsException e) {
                    System.out.println("You must enter the requested log level, using the default\n");
                }
        }
    }
    MainLogger logger = new MainLogger(DATA_PATH + "server.log", logLevel);
    System.out.printf("Using log level '%s'\n", logLevel);
    try {
        if (ANSI) {
            System.out.print((char) 0x1b + "]0;Starting Nukkit Server For Minecraft: PE" + (char) 0x07);
        }
        new Server(logger, PATH, DATA_PATH, PLUGIN_PATH);
    } catch (Exception e) {
        logger.logException(e);
    }
    if (ANSI) {
        System.out.print((char) 0x1b + "]0;Stopping Server..." + (char) 0x07);
    }
    logger.info("Stopping other threads");
    for (Thread thread : java.lang.Thread.getAllStackTraces().keySet()) {
        if (!(thread instanceof InterruptibleThread)) {
            continue;
        }
        logger.debug("Stopping " + thread.getClass().getSimpleName() + " thread");
        if (thread.isAlive()) {
            thread.interrupt();
        }
    }
    ServerKiller killer = new ServerKiller(8);
    killer.start();
    logger.shutdown();
    logger.interrupt();
    CommandReader.getInstance().removePromptLine();
    if (ANSI) {
        System.out.print((char) 0x1b + "]0;Server Stopped" + (char) 0x07);
    }
    System.exit(0);
}
Also used : Arrays(java.util.Arrays) MainLogger(cn.nukkit.utils.MainLogger) LogLevel(cn.nukkit.utils.LogLevel) Set(java.util.Set) ProtocolInfo(cn.nukkit.network.protocol.ProtocolInfo) CommandReader(cn.nukkit.command.CommandReader) Collectors(java.util.stream.Collectors) ServerKiller(cn.nukkit.utils.ServerKiller) MainLogger(cn.nukkit.utils.MainLogger) ServerKiller(cn.nukkit.utils.ServerKiller) LogLevel(cn.nukkit.utils.LogLevel)

Example 2 with MainLogger

use of cn.nukkit.utils.MainLogger in project Nukkit by Nukkit.

the class SimpleCommandMap method dispatch.

@Override
public boolean dispatch(CommandSender sender, String cmdLine) {
    ArrayList<String> parsed = parseArguments(cmdLine);
    if (parsed.size() == 0) {
        return false;
    }
    String sentCommandLabel = parsed.remove(0).toLowerCase();
    String[] args = parsed.toArray(new String[parsed.size()]);
    Command target = this.getCommand(sentCommandLabel);
    if (target == null) {
        return false;
    }
    target.timing.startTiming();
    try {
        target.execute(sender, sentCommandLabel, args);
    } catch (Exception e) {
        sender.sendMessage(new TranslationContainer(TextFormat.RED + "%commands.generic.exception"));
        this.server.getLogger().critical(this.server.getLanguage().translateString("nukkit.command.exception", cmdLine, target.toString(), Utils.getExceptionMessage(e)));
        MainLogger logger = sender.getServer().getLogger();
        if (logger != null) {
            logger.logException(e);
        }
    }
    target.timing.stopTiming();
    return true;
}
Also used : MainLogger(cn.nukkit.utils.MainLogger) SimpleCommand(cn.nukkit.command.simple.SimpleCommand) TranslationContainer(cn.nukkit.lang.TranslationContainer)

Example 3 with MainLogger

use of cn.nukkit.utils.MainLogger in project Nukkit by Nukkit.

the class RakNetInterface method handleEncapsulated.

@Override
public void handleEncapsulated(String identifier, EncapsulatedPacket packet, int flags) {
    if (this.players.containsKey(identifier)) {
        DataPacket pk = null;
        try {
            if (packet.buffer.length > 0) {
                if (packet.buffer[0] == PING_DataPacket.ID) {
                    PING_DataPacket pingPacket = new PING_DataPacket();
                    pingPacket.buffer = packet.buffer;
                    pingPacket.decode();
                    this.networkLatency.put(identifier, (int) pingPacket.pingID);
                    return;
                }
                pk = this.getPacket(packet.buffer);
                if (pk != null) {
                    pk.decode();
                    this.players.get(identifier).handleDataPacket(pk);
                }
            }
        } catch (Exception e) {
            this.server.getLogger().logException(e);
            if (Nukkit.DEBUG > 1 && pk != null) {
                MainLogger logger = this.server.getLogger();
                // if (logger != null) {
                logger.debug("Packet " + pk.getClass().getName() + " 0x" + Binary.bytesToHexString(packet.buffer));
            // logger.logException(e);
            // }
            }
            if (this.players.containsKey(identifier)) {
                this.handler.blockAddress(this.players.get(identifier).getAddress(), 5);
            }
        }
    }
}
Also used : PING_DataPacket(cn.nukkit.raknet.protocol.packet.PING_DataPacket) MainLogger(cn.nukkit.utils.MainLogger) PING_DataPacket(cn.nukkit.raknet.protocol.packet.PING_DataPacket) DataPacket(cn.nukkit.network.protocol.DataPacket) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 4 with MainLogger

use of cn.nukkit.utils.MainLogger in project Nukkit by Nukkit.

the class PluginManager method loadPlugins.

public Map<String, Plugin> loadPlugins(File dictionary, List<String> newLoaders, boolean includeDir) {
    if (dictionary.isDirectory()) {
        Map<String, File> plugins = new LinkedHashMap<>();
        Map<String, Plugin> loadedPlugins = new LinkedHashMap<>();
        Map<String, List<String>> dependencies = new LinkedHashMap<>();
        Map<String, List<String>> softDependencies = new LinkedHashMap<>();
        Map<String, PluginLoader> loaders = new LinkedHashMap<>();
        if (newLoaders != null) {
            for (String key : newLoaders) {
                if (this.fileAssociations.containsKey(key)) {
                    loaders.put(key, this.fileAssociations.get(key));
                }
            }
        } else {
            loaders = this.fileAssociations;
        }
        for (final PluginLoader loader : loaders.values()) {
            for (File file : dictionary.listFiles((dir, name) -> {
                for (Pattern pattern : loader.getPluginFilters()) {
                    if (pattern.matcher(name).matches()) {
                        return true;
                    }
                }
                return false;
            })) {
                if (file.isDirectory() && !includeDir) {
                    continue;
                }
                try {
                    PluginDescription description = loader.getPluginDescription(file);
                    if (description != null) {
                        String name = description.getName();
                        if (plugins.containsKey(name) || this.getPlugin(name) != null) {
                            this.server.getLogger().error(this.server.getLanguage().translateString("nukkit.plugin.duplicateError", name));
                            continue;
                        }
                        boolean compatible = false;
                        for (String version : description.getCompatibleAPIs()) {
                            // Check the format: majorVersion.minorVersion.patch
                            if (!Pattern.matches("[0-9]\\.[0-9]\\.[0-9]", version)) {
                                this.server.getLogger().error(this.server.getLanguage().translateString("nukkit.plugin.loadError", new String[] { name, "Wrong API format" }));
                                continue;
                            }
                            String[] versionArray = version.split("\\.");
                            String[] apiVersion = this.server.getApiVersion().split("\\.");
                            // Completely different API version
                            if (!Objects.equals(Integer.valueOf(versionArray[0]), Integer.valueOf(apiVersion[0]))) {
                                continue;
                            }
                            // If the plugin requires new API features, being backwards compatible
                            if (Integer.valueOf(versionArray[1]) > Integer.valueOf(apiVersion[1])) {
                                continue;
                            }
                            compatible = true;
                            break;
                        }
                        if (!compatible) {
                            this.server.getLogger().error(this.server.getLanguage().translateString("nukkit.plugin.loadError", new String[] { name, "%nukkit.plugin.incompatibleAPI" }));
                        }
                        plugins.put(name, file);
                        softDependencies.put(name, description.getSoftDepend());
                        dependencies.put(name, description.getDepend());
                        for (String before : description.getLoadBefore()) {
                            if (softDependencies.containsKey(before)) {
                                softDependencies.get(before).add(name);
                            } else {
                                List<String> list = new ArrayList<>();
                                list.add(name);
                                softDependencies.put(before, list);
                            }
                        }
                    }
                } catch (Exception e) {
                    this.server.getLogger().error(this.server.getLanguage().translateString("nukkit.plugin" + ".fileError", file.getName(), dictionary.toString(), Utils.getExceptionMessage(e)));
                    MainLogger logger = this.server.getLogger();
                    if (logger != null) {
                        logger.logException(e);
                    }
                }
            }
        }
        while (!plugins.isEmpty()) {
            boolean missingDependency = true;
            for (String name : new ArrayList<>(plugins.keySet())) {
                File file = plugins.get(name);
                if (dependencies.containsKey(name)) {
                    for (String dependency : new ArrayList<>(dependencies.get(name))) {
                        if (loadedPlugins.containsKey(dependency) || this.getPlugin(dependency) != null) {
                            dependencies.get(name).remove(dependency);
                        } else if (!plugins.containsKey(dependency)) {
                            this.server.getLogger().critical(this.server.getLanguage().translateString("nukkit" + ".plugin.loadError", new String[] { name, "%nukkit.plugin.unknownDependency" }));
                            break;
                        }
                    }
                    if (dependencies.get(name).isEmpty()) {
                        dependencies.remove(name);
                    }
                }
                if (softDependencies.containsKey(name)) {
                    for (String dependency : new ArrayList<>(softDependencies.get(name))) {
                        if (loadedPlugins.containsKey(dependency) || this.getPlugin(dependency) != null) {
                            softDependencies.get(name).remove(dependency);
                        }
                    }
                    if (softDependencies.get(name).isEmpty()) {
                        softDependencies.remove(name);
                    }
                }
                if (!dependencies.containsKey(name) && !softDependencies.containsKey(name)) {
                    plugins.remove(name);
                    missingDependency = false;
                    Plugin plugin = this.loadPlugin(file, loaders);
                    if (plugin != null) {
                        loadedPlugins.put(name, plugin);
                    } else {
                        this.server.getLogger().critical(this.server.getLanguage().translateString("nukkit.plugin.genericLoadError", name));
                    }
                }
            }
            if (missingDependency) {
                for (String name : new ArrayList<>(plugins.keySet())) {
                    File file = plugins.get(name);
                    if (!dependencies.containsKey(name)) {
                        softDependencies.remove(name);
                        plugins.remove(name);
                        missingDependency = false;
                        Plugin plugin = this.loadPlugin(file, loaders);
                        if (plugin != null) {
                            loadedPlugins.put(name, plugin);
                        } else {
                            this.server.getLogger().critical(this.server.getLanguage().translateString("nukkit.plugin.genericLoadError", name));
                        }
                    }
                }
                if (missingDependency) {
                    for (String name : plugins.keySet()) {
                        this.server.getLogger().critical(this.server.getLanguage().translateString("nukkit.plugin.loadError", new String[] { name, "%nukkit.plugin.circularDependency" }));
                    }
                    plugins.clear();
                }
            }
        }
        return loadedPlugins;
    } else {
        return new HashMap<>();
    }
}
Also used : Pattern(java.util.regex.Pattern) MainLogger(cn.nukkit.utils.MainLogger) PluginException(cn.nukkit.utils.PluginException) File(java.io.File)

Example 5 with MainLogger

use of cn.nukkit.utils.MainLogger in project Nukkit by Nukkit.

the class PluginManager method disablePlugin.

public void disablePlugin(Plugin plugin) {
    if (plugin.isEnabled()) {
        try {
            plugin.getPluginLoader().disablePlugin(plugin);
        } catch (Exception e) {
            MainLogger logger = this.server.getLogger();
            if (logger != null) {
                logger.logException(e);
            }
        }
        this.server.getScheduler().cancelTask(plugin);
        HandlerList.unregisterAll(plugin);
        for (Permission permission : plugin.getDescription().getPermissions()) {
            this.removePermission(permission);
        }
    }
}
Also used : MainLogger(cn.nukkit.utils.MainLogger) Permission(cn.nukkit.permission.Permission) PluginException(cn.nukkit.utils.PluginException)

Aggregations

MainLogger (cn.nukkit.utils.MainLogger)5 PluginException (cn.nukkit.utils.PluginException)2 CommandReader (cn.nukkit.command.CommandReader)1 SimpleCommand (cn.nukkit.command.simple.SimpleCommand)1 TranslationContainer (cn.nukkit.lang.TranslationContainer)1 DataPacket (cn.nukkit.network.protocol.DataPacket)1 ProtocolInfo (cn.nukkit.network.protocol.ProtocolInfo)1 Permission (cn.nukkit.permission.Permission)1 PING_DataPacket (cn.nukkit.raknet.protocol.packet.PING_DataPacket)1 LogLevel (cn.nukkit.utils.LogLevel)1 ServerKiller (cn.nukkit.utils.ServerKiller)1 File (java.io.File)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Arrays (java.util.Arrays)1 Set (java.util.Set)1 Pattern (java.util.regex.Pattern)1 Collectors (java.util.stream.Collectors)1