Ejemplo n.º 1
0
 def reload(self):
     Logger.debug("Reloading Config", "config")
     # Check If File Exists
     configPath = os.path.join(SERVERPATH, self.configPath)
     # Load File If File
     if os.path.isfile(configPath):
         Logger.debug("Config File Exists! Loading Config.", "config")
         try:
             with open(configPath, "r") as configFile:
                 self._load(configFile)
             # Save Config After Load (To Update And Fix Any Issues)
             if self.saveAfterConfigLoad:
                 with open(configPath, "w") as configFile:
                     self._save(configFile)
             else:
                 Logger.warn("Skipping Save After Config Load", "config")
         except json.decoder.JSONDecodeError as e:
             Logger.error(
                 f"Failed To Load Json File! - {type(e).__name__}: {e}",
                 "config")
             Logger.askConfirmation(
                 message="Override Old Config With Default Values?")
             with open(configPath, "w") as configFile:
                 self._save(configFile)
     else:
         Logger.debug("Config File Does Not Exist! Creating Config File.",
                      "config")
         with open(configPath, "w") as configFile:
             self._save(configFile)
Ejemplo n.º 2
0
    def register(self, commandClass: Type[AbstractCommand],
                 module: AbstractModule):
        Logger.debug(
            f"Registering Command {commandClass.NAME} From Module {module.NAME}",
            module=f"{module.NAME}-submodule-init")
        command: AbstractCommand = super()._initSubmodule(commandClass, module)

        # Handling Special Cases if OVERRIDE is Set
        if command.OVERRIDE:
            # Check If Override Is Going To Do Anything
            # If Not, Warn
            if command.NAME not in self._command_list.keys():
                Logger.warn(
                    f"Command {command.NAME}  From Module {command.MODULE.NAME} Is Trying To Override A Command That Does Not Exist! If This Is An Accident, Remove The 'override' Flag.",
                    module=f"{module.NAME}-submodule-init")
            else:
                Logger.debug(
                    f"Command {command.NAME} Is Overriding Command {self._command_list[command.NAME].NAME}",
                    module=f"{module.NAME}-submodule-init")
                # Un-registering All Activators for the Command Being Overwritten. Prevents Issues!
                Logger.debug(
                    f"Un-registering Activators for Command {self._command_list[command.NAME].NAME}",
                    module=f"{module.NAME}-submodule-init")
                for activator in list(
                        self._command_list[command.NAME].ACTIVATORS.keys()):
                    # Deleting from Cache
                    del self._activators[activator]

        # Checking If Command Name Is Already In Commands List
        # Ignoring if OVERRIDE is set
        if command.NAME in self._command_list.keys() and not command.OVERRIDE:
            raise InitRegisterError(
                f"Command {command.NAME} Has Already Been Registered! If This Is Intentional, Set the 'override' Flag to True"
            )

        # Setting Activators To Default If None
        if command.ACTIVATORS is None:
            command.ACTIVATORS = []
        if len(command.ACTIVATORS) == 0:
            Logger.warn(
                f"Command {command.NAME} Was Registered Without Any Activators. Using Name As Command Activator.",
                module=f"{module.NAME}-submodule-init")
            command.ACTIVATORS = [command.NAME.lower()]
        # Add Activators To Command Cache
        Logger.debug(
            f"Adding Activators {command.ACTIVATORS} To Activator Cache",
            module=f"{module.NAME}-submodule-init")
        for activator in command.ACTIVATORS:
            Logger.verbose(f"Adding Activator {activator}",
                           module=f"{module.NAME}-submodule-init")
            # If Activator Already Exists, Error
            if activator not in self._activators:
                self._activators[activator] = command
            else:
                raise InitRegisterError(
                    f"Another Command Has Already Registered Command Activator {activator}"
                )

        # Add Command to Commands List
        self._command_list[command.NAME] = command
Ejemplo n.º 3
0
    def register(self, worldFormatClass: Type[AbstractWorldFormat],
                 module: AbstractModule):
        Logger.debug(
            f"Registering World Format {worldFormatClass.NAME} From Module {module.NAME}",
            module=f"{module.NAME}-submodule-init")
        worldFormat: AbstractWorldFormat = super()._initSubmodule(
            worldFormatClass, module)

        # Handling Special Cases if OVERRIDE is Set
        if worldFormat.OVERRIDE:
            # Check If Override Is Going To Do Anything
            # If Not, Warn
            if worldFormat.NAME not in self._format_list.keys():
                Logger.warn(
                    f"World Format {worldFormat.NAME} From Module {worldFormat.MODULE.NAME} Is Trying To Override A World Format That Does Not Exist! If This Is An Accident, Remove The 'override' Flag.",
                    module=f"{module.NAME}-submodule-init")
            else:
                Logger.debug(
                    f"World Format {worldFormat.NAME} Is Overriding World Format {self._format_list[worldFormat.NAME].NAME}",
                    module=f"{module.NAME}-submodule-init")

        # Checking If World Format Name Is Already In Formats List
        # Ignoring if OVERRIDE is set
        if worldFormat.NAME in self._format_list.keys(
        ) and not worldFormat.OVERRIDE:
            raise InitRegisterError(
                f"World Format {worldFormat.NAME} Has Already Been Registered! If This Is Intentional, Set the 'override' Flag to True"
            )

        # Add World Format to World Formats List
        self._format_list[worldFormat.NAME] = worldFormat
Ejemplo n.º 4
0
 def saveWorlds(self):
     Logger.debug("Starting Attempt to Save All Worlds",
                  module="world-save")
     if self.persistant and (self.server.config.worldSaveLocation
                             is not None):
         Logger.info("Saving All Worlds...", module="world-save")
         # Loop through all worlds and attempt to save!
         for worldName, world in self.worlds.items():
             Logger.debug(f"Trying To Save World {worldName}",
                          module="world-save")
             # Check persistance
             if world.persistant:
                 try:
                     # Saving World
                     Logger.info(f"Saving World {worldName}",
                                 module="world-save")
                     world.saveMap()
                 except Exception as e:
                     Logger.error(
                         f"Error While Saving World {worldName} - {type(e).__name__}: {e}",
                         module="world-save")
             else:
                 Logger.warn(
                     f"World {worldName} Is Non Persistant! Skipping World Save!",
                     module="world-save")
     else:
         Logger.warn(
             "World Manager Is Non Persistant! Skipping World Save!",
             module="world-save")
Ejemplo n.º 5
0
    def __init__(self, server: Server, blacklist: List[str] = []):
        self.server = server
        self.worlds = dict()
        self.blacklist = blacklist
        self.persistant = True
        self.worldFormat = None

        # Get worldFormat Using Given World Format Key
        # Loop Through All World Formats
        for worldFormat in WorldFormats._format_list.values():
            # Check If key Matches With Config Key List
            if self.server.config.defaultSaveFormat.lower(
            ) in worldFormat.KEYS:
                # Set World Format
                self.worldFormat = worldFormat

        # Check If World Format Was Set
        if self.worldFormat is None:
            raise FatalError(
                f"Unknown World Format Key {self.server.config.defaultSaveFormat} Given In Server Config!"
            )
        Logger.info(f"Using World Format {self.worldFormat.NAME}",
                    module="init-world")

        # If World Location Was Not Given, Disable Persistance
        # (Don't Save / Load)
        if self.server.config.worldSaveLocation is None:
            Logger.warn(
                "World Save Location Was Not Defined. Creating Non-Persistant World!!!",
                module="init-world")
            self.persistant = False
Ejemplo n.º 6
0
    def getHighestBlock(self,
                        blockX: int,
                        blockZ: int,
                        start: Optional[int] = None):
        # Returns the highest block
        # Set and Verify Scan Start Value
        if start is None:
            scanY = self.sizeY - 1
        else:
            if start > self.sizeY:
                Logger.warn(
                    f"Trying To Get Heighest Block From Location Greater Than Map Size (MapHeight: {self.sizeY}, Given: {start})"
                )
                scanY = self.sizeY - 1
            else:
                scanY = start

        # Scan Downwards To Get Heighest Block
        while self.getBlock(blockX, scanY, blockZ) is Blocks.Air:
            if scanY == 0:
                break
            # Scan Downwards
            scanY -= 1

        return scanY
Ejemplo n.º 7
0
    def register(self, mapGenClass: Type[AbstractMapGenerator],
                 module: AbstractModule):
        Logger.debug(
            f"Registering Map Generator {mapGenClass.NAME} From Module {module.NAME}",
            module=f"{module.NAME}-submodule-init")
        mapGen: AbstractMapGenerator = super()._initSubmodule(
            mapGenClass, module)

        # Handling Special Cases if OVERRIDE is Set
        if mapGen.OVERRIDE:
            # Check If Override Is Going To Do Anything
            # If Not, Warn
            if mapGen.NAME not in self._generator_list.keys():
                Logger.warn(
                    f"Map Generator {mapGen.NAME} From Module {mapGen.MODULE.NAME} Is Trying To Override A Map Generator That Does Not Exist! If This Is An Accident, Remove The 'override' Flag.",
                    module=f"{module.NAME}-submodule-init")
            else:
                Logger.debug(
                    f"Map Generator {mapGen.NAME} Is Overriding Map Generator {self._generator_list[mapGen.NAME].NAME}",
                    module=f"{module.NAME}-submodule-init")

        # Checking If Map Generator Name Is Already In Generators List
        # Ignoring if OVERRIDE is set
        if mapGen.NAME in self._generator_list.keys() and not mapGen.OVERRIDE:
            raise InitRegisterError(
                f"Map Generator {mapGen.NAME} Has Already Been Registered! If This Is Intentional, Set the 'override' Flag to True"
            )

        # Add Map Generator to Map Generators List
        self._generator_list[mapGen.NAME] = mapGen
Ejemplo n.º 8
0
 def saveMap(self):
     if self.persistant:
         Logger.info(f"Attempting To Save World {self.name}",
                     module="world-save")
         self.worldManager.worldFormat.saveWorld(self, self.fileIO,
                                                 self.worldManager)
     else:
         Logger.warn(f"World {self.name} Is Not Persistant! Not Saving.",
                     module="world-save")
Ejemplo n.º 9
0
 def _importModules(self):
     # Initialize Temporary List of Files Imported
     _module_files = []
     # Walk Through All Packages And Import Library
     for _, module_name, _ in pkgutil.walk_packages(
         [os.path.join(SERVERPATH, MODULESFOLDER)]):
         # Load Modules
         Logger.debug(f"Detected Module {module_name}",
                      module="module-import")
         if module_name not in self._module_blacklist:
             try:
                 Logger.verbose(
                     f"Module {module_name} Not In Blacklist. Adding!",
                     module="module-import")
                 # Import Module
                 _module = importlib.import_module(MODULESIMPORT +
                                                   module_name)
                 # Appending To A List of Module Files to be Used Later
                 _module_files.append(module_name)
                 # Set the Imported Module into the Global Scope
                 globals()[module_name] = _module
             except FatalError as e:
                 # Pass Down Fatal Error To Base Server
                 raise e
             except Exception as e:
                 # Handle Exception if Error Occurs
                 self._error_list.append(
                     (module_name,
                      "PreInit-Import"))  # Module Loaded WITH Errors
                 # If the Error is a Register Error (raised on purpose), Don't print out TB
                 if type(e) is InitRegisterError:
                     printTb = False
                 else:
                     printTb = True
                 Logger.error(
                     f"Error While Importing Module {module_name} - {type(e).__name__}: {e}\n",
                     module="module-import",
                     printTb=printTb)
                 Logger.warn(
                     "!!! Fatal Module Errors May Cause Compatibility Issues And/Or Data Corruption !!!\n",
                     module="module-import")
                 Logger.askConfirmation()
         else:
             Logger.verbose(
                 f"Skipping Module {module_name} Due To Blacklist",
                 module="module-import")
     Logger.verbose(f"Detected and Imported Module Files {_module_files}",
                    module="module-import")
     # Check If Core Was Loaded
     if self._ensure_core:
         if "core" not in self._module_list.keys():
             self._error_list.append(
                 ("core",
                  "PreInit-EnsureCore"))  # Module Loaded WITH Errors
             raise FatalError(
                 "Error While Loading Module core - Critical Module Not Found"
             )
Ejemplo n.º 10
0
 async def serialize(self, message: str, playerId: int = 0):
     # <Player Message Packet>
     # (Byte) Packet ID
     # (Byte) Player ID (Seems to be unused?)
     # (64String) Message
     if len(message) > 64:
         Logger.warn(
             f"Trying to send message '{message}' over the 64 character limit!",
             module="packet-serializer")
     msg = struct.pack(self.FORMAT, self.ID, int(playerId),
                       bytearray(packageString(message)))
     return msg
Ejemplo n.º 11
0
 async def initConnection(self, *args, **kwargs):
     try:
         return await self._initConnection(*args, **kwargs)
     except ClientError as e:
         Logger.warn(
             f"Client Error, Disconnecting Ip {self.ip} - {type(e).__name__}: {e}",
             module="network")
         await self.closeConnection(reason=str(e), notifyPlayer=True)
     except BrokenPipeError:
         Logger.warn(f"Ip {self.ip} Broken Pipe. Closing Connection.",
                     module="network")
         await self.closeConnection(reason="Broken Pipe")
     except ConnectionResetError:
         Logger.warn(f"Ip {self.ip} Connection Reset. Closing Connection.",
                     module="network")
         await self.closeConnection(reason="Connection Reset")
     except asyncio.IncompleteReadError:
         Logger.warn(
             f"Ip {self.ip} Incomplete Read Error. Closing Connection.",
             module="network")
         await self.closeConnection(reason="Incomplete Read Error")
     except Exception as e:
         Logger.error(
             f"Error While Handling Connection {self.ip} - {type(e).__name__}: {e}",
             module="network")
         try:
             await self.closeConnection(reason="Internal Server Error",
                                        notifyPlayer=True)
         except Exception as e:
             Logger.error(
                 f"Close Connected Failed To Complete Successfully - {type(e).__name__}: {e}",
                 module="network")
Ejemplo n.º 12
0
    def register(self, packetClass: Type[AbstractPacket],
                 module: AbstractModule):
        Logger.debug(
            f"Registering Packet {packetClass.NAME} From Module {module.NAME}",
            module=f"{module.NAME}-submodule-init")
        packet: AbstractPacket = super()._initSubmodule(packetClass, module)

        # Handling Special Cases if OVERRIDE is Set
        if packet.OVERRIDE:
            # Check If Override Is Going To Do Anything
            # If Not, Warn
            if (packet.ID not in self._packet_list.keys()) and (
                    packet.NAME not in self.getAllPacketIds()):
                Logger.warn(
                    f"Packet {packet.NAME} (ID: {packet.ID}) From Module {packet.MODULE.NAME} Is Trying To Override A Packet That Does Not Exist! If This Is An Accident, Remove The 'override' Flag.",
                    module=f"{module.NAME}-submodule-init")
            else:
                Logger.debug(
                    f"Packet {packet.NAME} Is Overriding Packet {self._packet_list[packet.NAME].NAME} (ID: {packet.ID})",
                    module=f"{module.NAME}-submodule-init")

        # Checking If Packet And PacketId Is Already In Packets List
        # Ignoring if OVERRIDE is set
        if packet.NAME in self._packet_list.keys() and not packet.OVERRIDE:
            raise InitRegisterError(
                f"Packet {packet.NAME} Has Already Been Registered! If This Is Intentional, Set the 'override' Flag to True"
            )
        if packet.ID in self.getAllPacketIds() and not packet.OVERRIDE:
            raise InitRegisterError(
                f"Packet Id {packet.ID} Has Already Been Registered! If This Is Intentional, Set the 'override' Flag to True"
            )

        # Only Used If Request
        if self.direction is PacketDirections.REQUEST:
            # Cast Packet into Request Packet Type
            requestPacket: AbstractRequestPacket = packet  # type: ignore
            # Add To Packet Cache If Packet Is Used In Main Player Loop
            if requestPacket.PLAYERLOOP:
                Logger.verbose(
                    f"Adding Packet {requestPacket.ID} To Main Player Loop Request Packet Cache",
                    module=f"{module.NAME}-submodule-init")
                self.loopPackets[requestPacket.ID] = requestPacket

        # Add Packet to Packets List
        self._packet_list[packet.NAME] = packet
Ejemplo n.º 13
0
 def _load(self, fileIO: io.TextIOWrapper):
     Logger.debug(f"Loading Config With FileIO {fileIO}", "config-load")
     # Set Internal Attributes If It Exists
     configData = json.load(fileIO)
     Logger.verbose(f"Config data Is {configData}", "config-load")
     for configKey, configValue in configData.items():
         Logger.verbose(f"Checking Config Attribute {configKey}",
                        "config-load")
         # Checking If Key Exists In Config AND If Its Not Part Of The Overrides
         if hasattr(self,
                    configKey) and configKey not in self.configOverrides:
             Logger.verbose(
                 f"Setting Config Attribute {configKey} to {configValue}",
                 "config-load")
             setattr(self, configKey, configValue)
         else:
             Logger.warn(f"Ignoring Unknown Config Attribute {configKey}",
                         "config-load")
Ejemplo n.º 14
0
    def gzipMap(self,
                compressionLevel: int = -1,
                includeSizeHeader: bool = False):
        # If Gzip Compression Level Is -1, Use Default!
        # includeSizeHeader Dictates If Output Should Include Map Size Header Used For Level Init

        # Check If Compression Is -1 (Use Server gzipCompressionLevel)
        if compressionLevel == -1:
            compressionLevel = self.worldManager.server.config.gzipCompressionLevel
        # Check If Compression Level Is Valid
        elif compressionLevel >= 0 and compressionLevel <= 9:
            pass
        # Invalid Compression Level!
        else:
            Logger.error(
                f"Invalid GZIP Compression Level Of {compressionLevel}!!!",
                module="world")
            Logger.askConfirmation()
            Logger.warn("Using Fallback Compression Level Of 0",
                        module="world")
            compressionLevel = 0

        Logger.debug(
            f"Compressing Map {self.name} With Compression Level {compressionLevel}",
            module="world")
        # Create File Buffer
        buf = io.BytesIO()
        # Check If Size Header Is Needed (Using Bytes For '+' Capabilities)
        header = bytes()
        if includeSizeHeader:
            Logger.debug("Packing Size Header", module="world")
            header = header + bytes(struct.pack('!I', len(self.mapArray)))
        # Gzip World
        with gzip.GzipFile(fileobj=buf,
                           mode='wb',
                           compresslevel=compressionLevel) as f:
            f.write(header + bytes(self.mapArray))

        # Extract and Return Gzip Data
        gzipData = buf.getvalue()
        Logger.debug(f"GZipped Map! GZ SIZE: {len(gzipData)}", module="world")
        return gzipData
Ejemplo n.º 15
0
 def _postInit(self):
     for module_name, module_obj in list(self._module_list.items()):
         try:
             Logger.debug(
                 f"Running Post-Initialization for Module {module_name}",
                 module=f"{module_name}-postinit")
             # Calling the Final Init function
             module_obj.postInit()
         except FatalError as e:
             # Pass Down Fatal Error To Base Server
             raise e
         except Exception as e:
             # Handle Exception if Error Occurs
             self._error_list.append(
                 (module_name, "Init-Final"))  # Module Loaded WITH Errors
             # If the Error is an Postinit Error (raised on purpose), Don't print out TB
             if type(e) is PostInitError:
                 printTb = False
             else:
                 printTb = True
             Logger.error(
                 f"Error While Running Post-Initialization For {module_name} - {type(e).__name__}: {e}\n",
                 module="postinit",
                 printTb=printTb)
             Logger.warn(
                 "!!! Module Errors May Cause Compatibility Issues And/Or Data Corruption !!!\n",
                 module="postinit")
             Logger.warn(f"Skipping Module {module_name}?",
                         module="postinit")
             Logger.askConfirmation()
             # Remove Module
             Logger.warn(f"Removing Module {module_name} From Loader!",
                         module="postinit")
             del self._module_list[module_name]
Ejemplo n.º 16
0
    def _save(self, fileIO: io.TextIOWrapper):
        Logger.debug(f"Saving Config With FileIO {fileIO}", "config-save")
        # Write Config Values To File (Except ConfigOverrides)
        # Create A Shallow Copy Dict Version Of Dataclass
        configData = copy.copy(asdict(self))

        # Remove All configOverrides Values
        Logger.debug("Applying Config Overrides", "config-save")
        configOverrides = copy.copy(configData["configOverrides"])
        for overrideKey in configOverrides:
            Logger.debug(f"Applying Config Override {overrideKey}",
                         "config-save")
            if overrideKey in configData.keys():
                del configData[overrideKey]
            else:
                Logger.warn(
                    f"Trying To Apply Non-Existant Config Override Key {overrideKey}",
                    "config-save")

        # Writing Dict (as JSON) To File
        Logger.debug("Writing Formatted Config To File", "config-save")
        Logger.verbose(f"Formatted Config Is {configData}", "config-save")
        json.dump(configData, fileIO, indent=4)
Ejemplo n.º 17
0
    def _resolveDependencyCycles(self):
        # Helper Function To Run Down Module Dependency Tree To Check For Cycles
        def _ensureNoCycles(current: Type[AbstractModule],
                            previous: List[str]):
            Logger.verbose(
                f"Travelling Down Dependency Tree. CUR: {current} PREV: {previous}",
                module="cycle-check")
            # If Current Name Appears In Any Previous Dependency, There Is An Infinite Cycle
            if current.NAME in previous:
                raise DependencyError(
                    f"Circular dependency Detected: {' -> '.join([*previous, current.NAME])}"
                )

            Logger.verbose(
                f"Current Modules Has Dependencies {current.DEPENDENCIES}",
                module="cycle-check")
            # Run DFS through All Dependencies
            for dependency in current.DEPENDENCIES:
                _ensureNoCycles(dependency.MODULE, [*previous, current.NAME])

        for module_name, module_obj in list(self._module_list.items()):
            try:
                Logger.debug(
                    f"Ensuring No Circular Dependencies For Module {module_name}",
                    module="module-verify")
                # Run DFS Through All Decencies To Check If Cycle Exists
                _ensureNoCycles(module_obj, [])
            except FatalError as e:
                # Pass Down Fatal Error To Base Server
                raise e
            except Exception as e:
                # Handle Exception if Error Occurs
                self._error_list.append(
                    (module_name,
                     "PreInit-Dependency"))  # Module Loaded WITH Errors
                # If the Error is a Dependency Error (raised on purpose), Don't print out TB
                if type(e) is DependencyError:
                    printTb = False
                else:
                    printTb = True
                Logger.error(
                    f"Error While Resolving Dependency Cycles For {module_name} - {type(e).__name__}: {e}\n",
                    module="module-verify",
                    printTb=printTb)
                Logger.warn(
                    "!!! Module Errors May Cause Compatibility Issues And/Or Data Corruption !!!\n",
                    module="module-verify")
                Logger.warn(f"Skipping Module {module_name}?",
                            module="module-verify")
                Logger.askConfirmation()
                # Remove Module
                Logger.warn(f"Removing Module {module_name} From Loader!",
                            module="module-verify")
                del self._module_list[module_name]
Ejemplo n.º 18
0
 def _initSubmodules(self):
     # Loop through all the submodules in the order of the sorted graph
     for module in self._sorted_module_graph:
         try:
             # Loop Through All Items within Module
             Logger.debug(f"Checking All Items in {module.NAME}",
                          module=f"{module.NAME}-submodule-init")
             # Loop Through All Items In Class
             for _, item in module.__dict__.items():
                 # Check If Item Has "obsidian_submodule" Flag
                 if hasattr(item, "obsidian_submodule"):
                     Logger.verbose(
                         f"{item} Is A Submodule! Adding As {module.NAME} Submodule.",
                         module=f"{module.NAME}-submodule-init")
                     # Register Submodule Using information Provided by Submodule Class
                     item.MANAGER.register(item, module)
         except FatalError as e:
             # Pass Down Fatal Error To Base Server
             raise e
         except Exception as e:
             # Handle Exception if Error Occurs
             self._error_list.append(
                 (module.NAME,
                  "Init-Submodule"))  # Module Loaded WITH Errors
             # If the Error is an Init Error (raised on purpose), Don't print out TB
             if type(e) is InitError:
                 printTb = False
             else:
                 printTb = True
             Logger.error(
                 f"Error While Initializing Submodules For {module.NAME} - {type(e).__name__}: {e}\n",
                 module="submodule-init",
                 printTb=printTb)
             Logger.warn(
                 "!!! Module Errors May Cause Compatibility Issues And/Or Data Corruption !!!\n",
                 module="submodule-init")
             Logger.warn(f"Skipping Module {module.NAME}?",
                         module="submodule-init")
             Logger.askConfirmation()
             # Remove Module
             Logger.warn(f"Removing Module {module.NAME} From Loader!",
                         module="submodule-init")
             del self._module_list[module.NAME]
Ejemplo n.º 19
0
 def _initModules(self):
     for module in self._sorted_module_graph:
         try:
             Logger.debug(f"Initializing Module {module.NAME}",
                          module=f"{module.NAME}-init")
             # Initialize Module
             initializedModule = module()
             # Initialize and Transfer Module Variables
             initializedModule.NAME = module.NAME
             initializedModule.DESCRIPTION = module.DESCRIPTION
             initializedModule.AUTHOR = module.AUTHOR
             initializedModule.VERSION = module.VERSION
             initializedModule.DEPENDENCIES = module.DEPENDENCIES
             # Replacing Item in _module_list with the Initialized Version!
             self._module_list[module.NAME] = initializedModule
         except FatalError as e:
             # Pass Down Fatal Error To Base Server
             raise e
         except Exception as e:
             # Handle Exception if Error Occurs
             self._error_list.append(
                 (module.NAME, "Init-Module"))  # Module Loaded WITH Errors
             # If the Error is an Init Error (raised on purpose), Don't print out TB
             if type(e) is InitError:
                 printTb = False
             else:
                 printTb = True
             Logger.error(
                 f"Error While Initializing Modules For {module.NAME} - {type(e).__name__}: {e}\n",
                 module="module-init",
                 printTb=printTb)
             Logger.warn(
                 "!!! Module Errors May Cause Compatibility Issues And/Or Data Corruption !!!\n",
                 module="module-init")
             Logger.warn(f"Skipping Module {module.NAME}?",
                         module="module-init")
             Logger.askConfirmation()
             # Remove Module
             Logger.warn(f"Removing Module {module.NAME} From Loader!",
                         module="module-init")
             del self._module_list[module.NAME]
Ejemplo n.º 20
0
    async def _init(self):
        Logger.info(f"=== Initializing Server '{self.name}' ===", module="init")

        # Testing If Debug Is Enabled
        Logger.debug("Debug Is Enabled", module="init")
        Logger.verbose("Verbose Is Enabled", module="init")
        Logger.info("Use '-d' and/or '-v' To Enable Debug Mode Or Verbose Mode", module="init")

        # Initializing Config
        Logger.info("Initializing Server Config", module="init")
        # Ensuring Config Path
        self._ensureFileStructure(os.path.dirname(self.config.configPath))
        # Initing Config
        self.config.init()

        # Setting Up File Structure
        Logger.info("Setting Up File Structure", module="init")
        if self.config.worldSaveLocation is not None:
            self.ensureFiles.append(MODULESFOLDER)
            self.ensureFiles.append(self.config.worldSaveLocation)
        self._ensureFileStructure(self.ensureFiles)

        # Load and Log Modules
        Logger.info("Starting Module Initialization", module="init")
        ModuleManager.initModules(blacklist=self.config.moduleBlacklist, ensureCore=True)
        Logger.info("All Modules Initialized!!!", module="init")

        Logger.info(f"{ModuleManager.numModules} Modules Initialized", module="init")
        Logger.info(f"{PacketManager.numPackets} Packets Initialized", module="init")
        Logger.info(f"{BlockManager.numBlocks} Blocks Initialized", module="init")
        Logger.info(f"{CommandManager.numCommands} Commands Initialized", module="init")
        Logger.info(f"{MapGeneratorManager.numMapGenerators} Map Generators Initialized", module="init")

        # Print Pretty List of All Modules
        Logger.info(f"Module List:\n{ModuleManager.generateTable()}", module="init")
        # Only Print Packet And World Generators List If Debug Enabled
        if Logger.DEBUG:
            Logger.debug(f"Packets List:\n{PacketManager.generateTable()}", module="init")
            Logger.debug(f"World Formats List:\n{WorldFormatManager.generateTable()}", module="init")
            Logger.debug(f"Map Generators List:\n{MapGeneratorManager.generateTable()}", module="init")
            Logger.debug(f"Commands List:\n{CommandManager.generateTable()}", module="init")

        # Only Print Block List If Verbose Enabled (Very Big)
        if Logger.VERBOSE:
            Logger.verbose(f"Blocks List:\n{BlockManager.generateTable()}", module="init")

        # Printing Error If Error Occurs During Init
        if len(ModuleManager._error_list) != 0:
            Logger.warn("Some Modules Files Failed To Load!\n", module="init")
            Logger.warn("!!! Failed Modules May Cause Compatibility Issues And/Or Data Corruption !!!\n", module="init-module")
            Logger.warn(f"Failed: {ModuleManager._error_list}\n", module="init")
            Logger.askConfirmation()

        # Initialize WorldManager
        Logger.info("Initializing World Manager", module="init")
        self.worldManager = WorldManager(self, blacklist=self.config.worldBlacklist)
        Logger.info("Loading Worlds", module="init")
        self.worldManager.loadWorlds()

        # Initialize PlayerManager
        Logger.info("Initializing Player Manager", module="init")
        self.playerManager = PlayerManager(self, maxSize=self.config.serverMaxPlayers)

        # Create Asyncio Socket Server
        # When new connection occurs, run callback _getConnHandler
        Logger.info(f"Setting Up Server {self.name}", module="init")
        self.server = await asyncio.start_server(self._getConnHandler(), self.address, self.port)

        self.initialized = True
Ejemplo n.º 21
0
 def _initDependencies(self):
     for module_name, module_obj in list(self._module_list.items()):
         try:
             Logger.debug(f"Checking Dependencies for Module {module_name}",
                          module="module-resolve")
             # Loop through all dependencies, check type, then check if exists
             for dependency in module_obj.DEPENDENCIES:
                 # Get Variables
                 dep_name = dependency.NAME
                 dep_ver = dependency.VERSION
                 Logger.verbose(f"Checking if Dependency {dep_name} Exists",
                                module="module-resolve")
                 # Check if Dependency is "Loaded"
                 if dep_name in self._module_list.keys():
                     # Check if Version should be checked
                     if dep_ver is None:
                         Logger.verbose(
                             f"Skipping Version Check For Dependency {dependency}",
                             module="module-resolve")
                         pass  # No Version Check Needed
                     elif dep_ver == self._module_list[
                             dependency.NAME].VERSION:
                         Logger.verbose(
                             f"Dependencies {dependency} Statisfied!",
                             module="module-resolve")
                         pass
                     else:
                         raise DependencyError(
                             f"Dependency '{dependency}' Has Unmatched Version! (Requirement: {dep_ver} | Has: {self._module_list[dependency.NAME].VERSION})"
                         )
                     # If All Passes, Link Module Class
                     dependency.MODULE = self._module_list[dependency.NAME]
                 else:
                     raise DependencyError(
                         f"Dependency '{dependency}' Not Found!")
         except FatalError as e:
             # Pass Down Fatal Error To Base Server
             raise e
         except Exception as e:
             # Handle Exception if Error Occurs
             self._error_list.append(
                 (module_name,
                  "PreInit-Dependency"))  # Module Loaded WITH Errors
             # If the Error is a Dependency Error (raised on purpose), Don't print out TB
             if type(e) is DependencyError:
                 printTb = False
             else:
                 printTb = True
             Logger.error(
                 f"Error While Initializing Dependencies For {module_name} - {type(e).__name__}: {e}\n",
                 module="module-resolve",
                 printTb=printTb)
             Logger.warn(
                 "!!! Module Errors May Cause Compatibility Issues And/Or Data Corruption !!!\n",
                 module="module-resolve")
             Logger.warn(f"Skipping Module {module_name}?",
                         module="module-resolve")
             Logger.askConfirmation()
             # Remove Module
             Logger.warn(f"Removing Module {module_name} From Loader!",
                         module="module-resolve")
             del self._module_list[module_name]
Ejemplo n.º 22
0
 def loadWorlds(self):
     Logger.debug("Starting Attempt to Load All Worlds",
                  module="world-load")
     if self.persistant and (self.server.config.worldSaveLocation
                             is not None):
         Logger.debug(
             f"Beginning To Scan Through {self.server.config.worldSaveLocation} Dir",
             module="world-load")
         # Loop Through All Files Given In World Folder
         for filename in os.listdir(
                 os.path.join(SERVERPATH,
                              self.server.config.worldSaveLocation)):
             # Get Pure File Name (No Extentions)
             saveName = os.path.splitext(os.path.basename(filename))[0]
             Logger.verbose(
                 f"Checking Extention and Status of World File {filename}",
                 module="world-load")
             # Check If File Type Matches With The Extentions Provided By worldFormat
             if not any([
                     filename.endswith(ext)
                     for ext in self.worldFormat.EXTENTIONS
             ]):
                 Logger.debug(
                     f"Ignoring World File {filename}. File Extention Not Known!",
                     module="world-load")
             # Also Check If World Is Blacklisted
             elif saveName in self.server.config.worldBlacklist:
                 Logger.info(
                     f"Ignoring World File {filename}. World Name Is Blacklisted!",
                     module="world-load")
             # Also Check If World Name Is Already Loaded (Same File Names with Different Extentions)
             elif saveName in self.worlds.keys():
                 Logger.warn(
                     f"Ignoring World File {filename}. World With Similar Name Has Already Been Registered!",
                     module="world-load")
                 Logger.warn(
                     f"World File {os.path.basename(self.worlds[saveName].fileIO.name)} Conflicts With World File {filename}!",
                     module="world-load")
                 Logger.askConfirmation()
             else:
                 Logger.debug(
                     f"Detected World File {filename}. Attempting To Load World",
                     module="world-load")
                 # (Attempt) To Load Up World
                 try:
                     Logger.info(f"Loading World {saveName}",
                                 module="world-load")
                     fileIO = open(
                         os.path.join(SERVERPATH,
                                      self.server.config.worldSaveLocation,
                                      filename), "rb+")
                     self.worlds[saveName] = self.worldFormat.loadWorld(
                         fileIO, self, persistant=self.persistant)
                 except Exception as e:
                     Logger.error(
                         f"Error While Loading World {filename} - {type(e).__name__}: {e}",
                         module="world-load")
                     Logger.askConfirmation()
         # Check If Default World Is Loaded
         if self.server.config.defaultWorld not in self.worlds.keys():
             # Check if other worlds were loaded as well
             if len(self.worlds.keys()) > 0:
                 Logger.warn(
                     f"Default World {self.server.config.defaultWorld} Not Loaded.",
                     module="world-load")
                 Logger.warn(
                     "Consider Checking If World Exists. Consider Changing The Default World and/or File Format In Config.",
                     module="world-load")
                 # Ask User If They Want To Continue With World Generation
                 Logger.warn(
                     f"Other Worlds Were Detected. Generate New World With Name {self.server.config.defaultWorld}?",
                     module="world-load")
                 Logger.askConfirmation(message="Generate New World?")
             else:
                 Logger.warn(
                     "No Existing Worlds Were Detected. Generating New World!",
                     module="world-load")
             # Generate New World
             defaultWorldName = self.server.config.defaultWorld
             defaultGenerator = MapGenerators[
                 self.server.config.defaultGenerator]
             Logger.debug(f"Creating World {defaultWorldName}",
                          module="world-load")
             self.createWorld(
                 defaultWorldName,
                 self.server.config.defaultWorldSizeX,
                 self.server.config.defaultWorldSizeY,
                 self.server.config.defaultWorldSizeZ,
                 defaultGenerator,
                 persistant=self.persistant,
                 grassHeight=self.server.config.defaultWorldSizeY // 2)
     else:
         Logger.debug("World Manager Is Non Persistant!",
                      module="world-load")
         # Create Non-Persistant Temporary World
         defaultWorldName = self.server.config.defaultWorld
         defaultGenerator = MapGenerators[
             self.server.config.defaultGenerator]
         Logger.debug(f"Creating Temporary World {defaultWorldName}",
                      module="world-load")
         self.createWorld(
             defaultWorldName,
             self.server.config.defaultWorldSizeX,
             self.server.config.defaultWorldSizeY,
             self.server.config.defaultWorldSizeZ,
             defaultGenerator,
             persistant=False,
             maxPlayers=self.server.config.worldMaxPlayers,
             grassHeight=self.server.config.defaultWorldSizeY // 2)