def InitGamePaths(source=None, root=None): if root == None: root = Configure.CurrentPath() if source == None: source = os.getcwd() gamepath = os.path.join(Configure.CurrentPath(), "cyberwar_edu") # .playground/cyberwar_edu if not os.path.exists(gamepath): os.mkdir(gamepath) templatesPath = os.path.join(gamepath, "templates") if not os.path.exists(templatesPath): os.mkdir(templatesPath) brainTemplatesPath = os.path.join(templatesPath, "brains") if not os.path.exists(brainTemplatesPath): os.mkdir(brainTemplatesPath) brainsPath = os.path.join(gamepath, "brains") if not os.path.exists(brainsPath): os.mkdir(brainsPath) shutil.copy(os.path.join(source, "object_types.ini"), gamepath) for fileName in os.listdir(source): if fileName.endswith("_brain.py"): shutil.copy(os.path.join(source, fileName), brainTemplatesPath) for fileName in BRAIN_REQUIRED_FILES: shutil.copy(os.path.join(source, fileName), brainTemplatesPath)
def reloadConnectors(self, force=False): if self._loaded and not force: return configPath = Configure.CurrentPath() connectorsLocation = os.path.join(configPath, "connectors") connectorsInitPath = os.path.join(connectorsLocation, "__init__.py") oldPath = sys.path if configPath not in sys.path: sys.path.insert(0, configPath) if not os.path.exists(connectorsInitPath): with open(connectorsInitPath, "w+") as f: f.write("#dummy init for connectors module") for pathName in os.listdir(connectorsLocation): pathName = os.path.join(connectorsLocation, pathName) moduleName = os.path.basename(pathName) if os.path.exists(os.path.join(pathName, "__init__.py")): dottedName = "connectors.{}".format(moduleName) with PacketDefinitionSilo(): if dottedName in sys.modules: #TODO: Test if this even works. importlib.reload(sys.module[dottedName]) else: importlib.import_module(dottedName) sys.path = oldPath self._loaded = True
def _reloadConfiguration(self): if self._gameGenerating: raise Exception("Cannot reload config until game generation is complete") self._gamepath = os.path.join(Configure.CurrentPath(), "cyberwar_edu") # .playground/cyberwar_edu self._objectTypesFile = os.path.join(self._gamepath, "object_types.ini") self._templatesPath = os.path.join(self._gamepath, "templates") self._brainTemplatesPath = os.path.join(self._templatesPath, "brains") self._brainsPath = os.path.join(self._gamepath, "brains") self._dbFile = os.path.join(self._gamepath, "board.db") loadGame = os.path.exists(self._dbFile) self._db = sqlite3.connect(self._dbFile, isolation_level=None) self._objectStore = None #self._db.execute("PRAGMA synchronous = OFF") #self._db.execute("PRAGMA journal_mode = OFF") if loadGame: try: self._loadGame() except Exception as e: print("Could not load game", e) self._game = None not os.path.exists(self._gamepath) and os.mkdir(self._gamepath) not os.path.exists(self._templatesPath) and os.mkdir(self._templatesPath) not os.path.exists(self._brainTemplatesPath) and os.mkdir(self._brainTemplatesPath) not os.path.exists(self._brainsPath) and os.mkdir(self._brainsPath) self._playerObjectTypes = configparser.ConfigParser() if os.path.exists(self._objectTypesFile): self._playerObjectTypes.read(self._objectTypesFile) self._initialObjects = configparser.ConfigParser()
def main(): import sys kargs = {} args = [] for arg in sys.argv[1:]: if arg.startswith("--"): if "=" in arg: k,v = arg.split("=") else: k,v = arg,True kargs[k]=v elif arg.startswith("-"): kargs[k]=True else: args.append(arg) if "--init" in kargs: switchHost, switchPort, address = kargs["--init"].split(",") switchPort = int(switchPort) InitPlayground(switchHost, switchPort, address) expectedPlayground = os.path.join(os.getcwd(), ".playground") if Configure.CurrentPath() != expectedPlayground: raise Exception("Init didn't work") InitGamePaths() return if "--pypy" in kargs: from cyberwar.braininterface.Loader import Loader Loader.PYPY_PATH = os.path.expanduser(kargs["--pypy"]) else: raise Exception("--pypy argument is required.") #asyncio.get_event_loop().set_debug(True) import logging root = logging.getLogger() root.addHandler(logging.StreamHandler()) root.setLevel(logging.NOTSET) root.debug("Creating Game") gameshell = GameConsole() asyncio.get_event_loop().call_soon(gameshell.start) try: asyncio.get_event_loop().run_forever() finally: print("Shutdown. Cleanup all game-related stuff.") gameshell.stop()
def __init__(self, stdoutFunction=print, stderrFunction=print, failFunction=sys.exit): self._write = stdoutFunction self._error = stderrFunction self._fail = failFunction try: self._currentPath = Configure.CurrentPath() self._manager = NetworkManager() self._manager.loadConfiguration() except Exception as e: print(e) print("no path") self._currentPath = None self._manager = None self.init_argument_handler() self._subcmd_help = self.initialize_subcommand_help()
def __init__(self, create=True, view=None): if view != None and create: raise Exception("View has no file access and does not create") self._view = view if not self._view: playgroundPath = Configure.CurrentPath() self._path = os.path.join(playgroundPath, "bank") self._config_file = os.path.join(self._path, "config.ini") if not os.path.exists(self._path): if create: os.mkdir(self._path) else: raise Exception("No path for bank config") self.reloadConfig() else: self._path = view.path() self._config = configparser.ConfigParser() self._config.update(self._view._config)
def execute(self, args): self._currentPath = Configure.CurrentPath() args = self._topargs.parse_args(args) if not self._currentPath and args.func not in self._preinit_functions: return self._fail( "Pnetworking cannot find playground path. Try 'pnetworking help'" ) if self._currentPath: self._loadNetworkManager() try: args.func(args) except Exception as e: self._error("Error executing pnetworking") self._error("\t{}".format(e)) response = input("See stack trace [y/N]? ") if response.lower().startswith('y'): writer = io.StringIO() traceback.print_tb(e.__traceback__, file=writer) self._error(writer.getvalue() + "\n") self._fail()
def reloadConnectors(self, force=False): if self._loaded and not force: return self._connectors = {} # self._connectors.update(self._default_connectors) #{"default":PlaygroundConnector()} configPath = Configure.CurrentPath() connectorsLocation = os.path.join(configPath, "connectors") connectorsInitPath = os.path.join(connectorsLocation, "__init__.py") oldPath = sys.path if configPath not in sys.path: sys.path.insert(0, configPath) if not os.path.exists(connectorsInitPath): with open(connectorsInitPath, "w+") as f: f.write("#dummy init for connectors module") self._autoLoading = True for pathName in os.listdir(connectorsLocation): try: pathName = os.path.join(connectorsLocation, pathName) moduleName = os.path.basename(pathName) if os.path.exists(os.path.join( pathName, "__init__.py")) or os.path.exists( os.path.join(pathName, "__init__.pyc")): dottedName = "connectors.{}".format(moduleName) with PacketDefinitionSilo(): if dottedName in sys.modules: #TODO: Test if this even works. importlib.reload(sys.modules[dottedName]) else: importlib.import_module(dottedName) except Exception as e: print("WARNING: could not load auto connector", pathName, "because", e) self._autoLoading = False sys.path = oldPath self._loaded = True
def _findConfig(self): path = Configure.CurrentPath() filepath = os.path.join(path, self.CONFIG_FILE) if os.path.exists(filepath): return path, filepath return None, None
def init_argument_handler(self): self._topargs = argparse.ArgumentParser(add_help=False) self._topargs.set_defaults(func=self.help_handler) commands = self._topargs.add_subparsers(dest="subcommand") self._commands = commands sub_formatter = SimplifiedUsageFormatter help_parser = commands.add_parser("help", add_help=False, formatter_class=sub_formatter) help_parser.add_argument("subcommand", nargs="?") help_parser.set_defaults(func=self.help_handler) initialize_parser = commands.add_parser("initialize", add_help=False, formatter_class=sub_formatter) initialize_parser.add_argument("location", choices=['instance', 'local', 'global']) initialize_parser.add_argument("overwrite", nargs="?", default=False) initialize_parser.set_defaults(func=lambda args: Configure.Initialize( args.location.upper(), overwrite=args.overwrite)) on_parser = commands.add_parser("on", add_help=False, formatter_class=sub_formatter) on_parser.set_defaults(func=lambda args: self._manager.on()) off_parser = commands.add_parser("off", add_help=False, formatter_class=sub_formatter) off_parser.set_defaults(func=lambda args: self._manager.off()) add_parser = commands.add_parser("add", add_help=False, formatter_class=sub_formatter) add_parser.add_argument("device", type=str) add_parser.add_argument("device_type", type=str) add_parser.add_argument("args", nargs=argparse.REMAINDER) add_parser.set_defaults(func=lambda args: self._manager.addDevice( args.device, args.device_type, args.args)) remove_parser = commands.add_parser('remove', add_help=False, formatter_class=sub_formatter) remove_parser.add_argument("device", type=str) remove_parser.set_defaults( func=lambda args: self._manager.removeDevice(args.device)) enable_parser = commands.add_parser('enable', add_help=False, formatter_class=sub_formatter) enable_parser.add_argument("device", type=str) enable_parser.set_defaults( func=lambda args: self.initialize_device(args.device).enable()) disable_parser = commands.add_parser('disable', add_help=False, formatter_class=sub_formatter) disable_parser.add_argument("device", type=str) disable_parser.set_defaults( func=lambda args: self.initialize_device(args.device).disable()) config_parser = commands.add_parser('config', add_help=False, formatter_class=sub_formatter) config_parser.add_argument('device', type=str) config_parser.add_argument('verb', type=str) config_parser.add_argument('args', nargs=argparse.REMAINDER) config_parser.set_defaults(func=lambda args: self.initialize_device( args.device).config(args.verb, args.args)) query_parser = commands.add_parser('query', add_help=False, formatter_class=sub_formatter) query_parser.add_argument('device', type=str) query_parser.add_argument('verb', type=str) query_parser.add_argument('args', nargs=argparse.REMAINDER) query_parser.set_defaults( func=lambda args: self._write("\t{} Response: {}".format( args.device, self.initialize_device(args.device).query( args.verb, args.args)))) routes_parser = commands.add_parser('routes', add_help=False, formatter_class=sub_formatter) routes_parser.set_defaults(func=lambda args: self._write( RoutesStatusOutputProcessor().process)(initialize_manager())) status_parser = commands.add_parser('status', add_help=False, formatter_class=sub_formatter) status_parser.add_argument('device', nargs='?', default=None) status_parser.set_defaults(func=self.status_handler)
def processCommand(command, args): if command == "initialize": pathId = Configure.INSTANCE_CONFIG_KEY overwrite = False while args: nextArg = args.pop(0) if nextArg.upper() in Configure.SEARCH_PATHS.keys(): pathId = nextArg.upper() elif nextArg == "overwrite": overwrite = True else: failExit("Initialize got unknown option {}.".format(nextArg)) Configure.Initialize(pathId, overwrite=overwrite) return 0 manager = NetworkManager() manager.loadConfiguration() if command == "add": if not args: failExit("USAGE: add device_name device_type device_args") deviceName = args.pop(0) if not args: failExit("USAGE: add device_name device_type device_args") deviceType = args.pop(0) manager.addDevice(deviceName, deviceType, args) elif command == "remove": if not args: failExit("USAGE: remove device_name") deviceName = args.pop(0) manager.removeDevice(deviceName) elif command == "enable": if not args: failExit("USAGE: enable device_name") deviceName = args.pop(0) deviceManager = manager.getDevice(deviceName) if not deviceManager: failExit("Unknown device {}".format(deviceName)) deviceManager.enable() elif command == "disable": if not args: failExit("USAGE: disable device_name") deviceName = args.pop(0) deviceManager = manager.getDevice(deviceName) if not deviceManager: failExit("Unknown device {}".format(deviceName)) deviceManager.disable() elif command == "config": if not args: failExit("USAGE: config device_name verb args") deviceName = args.pop(0) if not args: failExit("USAGE: config device_name verb args") verb = args.pop(0) deviceManager = manager.getDevice(deviceName) if not deviceManager: failExit("Unknown device {}".format(deviceName)) deviceManager.config(verb, args) elif command == "query": if not args: failExit("USAGE: config device_name verb args") deviceName = args.pop(0) if not args: failExit("USAGE: config device_name verb args") verb = args.pop(0) deviceManager = manager.getDevice(deviceName) if not deviceManager: failExit("Unknown device {}".format(deviceName)) result = deviceManager.query(verb, args) if result != None: print("\tResponse: {}".format(result)) elif command == "on": manager.on() elif command == "off": manager.off() elif command == "status": if args: deviceName = args.pop(0) statusProcessor = DeviceStatusOutputProcessor.DeviceProcessorFactory( manager, deviceName) print(statusProcessor.process(manager.getDevice(deviceName))) else: statusProcessor = DeviceStatusOutputProcessor() print(statusProcessor.process(manager)) elif command == "routes": statusProcessor = RoutesStatusOutputProcessor() print(statusProcessor.process(manager)) else: failExit("Unknown command '{}'.".format(command))