Run black reformatter on code
This commit is contained in:
parent
4582eb4085
commit
bd3e31bf3c
178 changed files with 4511 additions and 3385 deletions
|
|
@ -6,6 +6,7 @@ These all print to the terminal.
|
|||
"""
|
||||
import os
|
||||
|
||||
|
||||
def check_errors(settings):
|
||||
"""
|
||||
Check for deprecations that are critical errors and should stop
|
||||
|
|
@ -61,19 +62,26 @@ def check_errors(settings):
|
|||
)
|
||||
depstring = (
|
||||
"settings.{} was renamed to {}. Update your settings file (the FuncParser "
|
||||
"replaces and generalizes that which inlinefuncs used to do).")
|
||||
"replaces and generalizes that which inlinefuncs used to do)."
|
||||
)
|
||||
if hasattr(settings, "INLINEFUNC_ENABLED"):
|
||||
raise DeprecationWarning(depstring.format(
|
||||
"settings.INLINEFUNC_ENABLED", "FUNCPARSER_PARSE_OUTGOING_MESSAGES_ENABLED"))
|
||||
raise DeprecationWarning(
|
||||
depstring.format(
|
||||
"settings.INLINEFUNC_ENABLED", "FUNCPARSER_PARSE_OUTGOING_MESSAGES_ENABLED"
|
||||
)
|
||||
)
|
||||
if hasattr(settings, "INLINEFUNC_STACK_MAXSIZE"):
|
||||
raise DeprecationWarning(depstring.format(
|
||||
"settings.INLINEFUNC_STACK_MAXSIZE", "FUNCPARSER_MAX_NESTING"))
|
||||
raise DeprecationWarning(
|
||||
depstring.format("settings.INLINEFUNC_STACK_MAXSIZE", "FUNCPARSER_MAX_NESTING")
|
||||
)
|
||||
if hasattr(settings, "INLINEFUNC_MODULES"):
|
||||
raise DeprecationWarning(depstring.format(
|
||||
"settings.INLINEFUNC_MODULES", "FUNCPARSER_OUTGOING_MESSAGES_MODULES"))
|
||||
raise DeprecationWarning(
|
||||
depstring.format("settings.INLINEFUNC_MODULES", "FUNCPARSER_OUTGOING_MESSAGES_MODULES")
|
||||
)
|
||||
if hasattr(settings, "PROTFUNC_MODULES"):
|
||||
raise DeprecationWarning(depstring.format(
|
||||
"settings.PROTFUNC_MODULES", "FUNCPARSER_PROTOTYPE_VALUE_MODULES"))
|
||||
raise DeprecationWarning(
|
||||
depstring.format("settings.PROTFUNC_MODULES", "FUNCPARSER_PROTOTYPE_VALUE_MODULES")
|
||||
)
|
||||
|
||||
gametime_deprecation = (
|
||||
"The settings TIME_SEC_PER_MIN, TIME_MIN_PER_HOUR,"
|
||||
|
|
@ -121,7 +129,8 @@ def check_errors(settings):
|
|||
raise DeprecationWarning(
|
||||
"settings.CHANNEL_HANDLER_CLASS and CHANNEL COMMAND_CLASS are "
|
||||
"unused and should be removed. The ChannelHandler is no more; "
|
||||
"channels are now handled by aliasing the default 'channel' command.")
|
||||
"channels are now handled by aliasing the default 'channel' command."
|
||||
)
|
||||
|
||||
template_overrides_dir = os.path.join(settings.GAME_DIR, "web", "template_overrides")
|
||||
static_overrides_dir = os.path.join(settings.GAME_DIR, "web", "static_overrides")
|
||||
|
|
@ -151,8 +160,10 @@ def check_warnings(settings):
|
|||
if settings.ALLOWED_HOSTS == ["*"]:
|
||||
print(" [Devel: settings.ALLOWED_HOSTS set to '*' (all). Limit in production.]")
|
||||
if settings.SERVER_HOSTNAME == "localhost":
|
||||
print(" [Devel: settings.SERVER_HOSTNAME is set to 'localhost'. "
|
||||
"Update to the actual hostname in production.]")
|
||||
print(
|
||||
" [Devel: settings.SERVER_HOSTNAME is set to 'localhost'. "
|
||||
"Update to the actual hostname in production.]"
|
||||
)
|
||||
|
||||
for dbentry in settings.DATABASES.values():
|
||||
if "psycopg" in dbentry.get("ENGINE", ""):
|
||||
|
|
|
|||
|
|
@ -1431,6 +1431,7 @@ def create_superuser():
|
|||
|
||||
if (username is not None) and (password is not None) and len(password) > 0:
|
||||
from evennia.accounts.models import AccountDB
|
||||
|
||||
superuser = AccountDB.objects.create_superuser(username, email, password)
|
||||
superuser.save()
|
||||
else:
|
||||
|
|
@ -1947,7 +1948,7 @@ def run_custom_commands(option, *args):
|
|||
return False
|
||||
cmdpath = custom_commands.get(option)
|
||||
if cmdpath:
|
||||
modpath, *cmdname = cmdpath.rsplit('.', 1)
|
||||
modpath, *cmdname = cmdpath.rsplit(".", 1)
|
||||
if cmdname:
|
||||
cmdname = cmdname[0]
|
||||
mod = importlib.import_module(modpath)
|
||||
|
|
|
|||
|
|
@ -25,14 +25,16 @@ ERROR_NO_SUPERUSER = """
|
|||
"""
|
||||
|
||||
|
||||
LIMBO_DESC = _("""
|
||||
LIMBO_DESC = _(
|
||||
"""
|
||||
Welcome to your new |wEvennia|n-based game! Visit https://www.evennia.com if you need
|
||||
help, want to contribute, report issues or just join the community.
|
||||
|
||||
As a privileged user, write |wbatchcommand tutorial_world.build|n to build
|
||||
tutorial content. Once built, try |wintro|n for starting help and |wtutorial|n to
|
||||
play the demo game.
|
||||
""")
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
WARNING_POSTGRESQL_FIX = """
|
||||
|
|
@ -99,7 +101,8 @@ def create_objects():
|
|||
superuser_character = ObjectDB.objects.get(id=1)
|
||||
except ObjectDB.DoesNotExist:
|
||||
superuser_character = create.create_object(
|
||||
character_typeclass, key=superuser.username, nohome=True)
|
||||
character_typeclass, key=superuser.username, nohome=True
|
||||
)
|
||||
|
||||
superuser_character.db_typeclass_path = character_typeclass
|
||||
superuser_character.db.desc = _("This is User #1.")
|
||||
|
|
@ -135,6 +138,7 @@ def create_objects():
|
|||
if not superuser_character.home:
|
||||
superuser_character.home = limbo_obj
|
||||
|
||||
|
||||
def at_initial_setup():
|
||||
"""
|
||||
Custom hook for users to overload some or all parts of the initial
|
||||
|
|
@ -192,7 +196,7 @@ def handle_setup(last_step=None):
|
|||
the function will exit immediately.
|
||||
|
||||
"""
|
||||
if last_step in('done', -1):
|
||||
if last_step in ("done", -1):
|
||||
# this means we don't need to handle setup since
|
||||
# it already ran sucessfully once. -1 is the legacy
|
||||
# value for existing databases.
|
||||
|
|
@ -200,15 +204,15 @@ def handle_setup(last_step=None):
|
|||
|
||||
# setup sequence
|
||||
setup_sequence = {
|
||||
'create_objects': create_objects,
|
||||
'at_initial_setup': at_initial_setup,
|
||||
'collectstatic': collectstatic,
|
||||
'done': reset_server,
|
||||
"create_objects": create_objects,
|
||||
"at_initial_setup": at_initial_setup,
|
||||
"collectstatic": collectstatic,
|
||||
"done": reset_server,
|
||||
}
|
||||
|
||||
# determine the sequence so we can skip ahead
|
||||
steps = list(setup_sequence)
|
||||
steps = steps[steps.index(last_step) + 1 if last_step is not None else 0:]
|
||||
steps = steps[steps.index(last_step) + 1 if last_step is not None else 0 :]
|
||||
|
||||
# step through queue from last completed function. Once completed,
|
||||
# the 'done' key should be set.
|
||||
|
|
@ -221,6 +225,6 @@ def handle_setup(last_step=None):
|
|||
else:
|
||||
# save the step
|
||||
ServerConfig.objects.conf("last_initial_setup_step", stepname)
|
||||
if stepname == 'done':
|
||||
if stepname == "done":
|
||||
# always exit on 'done'
|
||||
break
|
||||
|
|
|
|||
|
|
@ -42,7 +42,6 @@ _STRIP_INCOMING_MXP = settings.MXP_ENABLED and settings.MXP_OUTGOING_ONLY
|
|||
_STRIP_MXP = None
|
||||
|
||||
|
||||
|
||||
def _NA(o):
|
||||
return "N/A"
|
||||
|
||||
|
|
@ -95,9 +94,7 @@ def text(session, *args, **kwargs):
|
|||
# nick replacement
|
||||
puppet = session.puppet
|
||||
if puppet:
|
||||
txt = puppet.nicks.nickreplace(
|
||||
txt, categories=("inputline"), include_account=True
|
||||
)
|
||||
txt = puppet.nicks.nickreplace(txt, categories=("inputline"), include_account=True)
|
||||
else:
|
||||
txt = session.account.nicks.nickreplace(
|
||||
txt, categories=("inputline"), include_account=False
|
||||
|
|
|
|||
|
|
@ -47,12 +47,12 @@ NULNUL = b"\x00\x00"
|
|||
AMP_MAXLEN = amp.MAX_VALUE_LENGTH # max allowed data length in AMP protocol (cannot be changed)
|
||||
|
||||
# amp internal
|
||||
ASK = b'_ask'
|
||||
ANSWER = b'_answer'
|
||||
ERROR = b'_error'
|
||||
ERROR_CODE = b'_error_code'
|
||||
ERROR_DESCRIPTION = b'_error_description'
|
||||
UNKNOWN_ERROR_CODE = b'UNKNOWN'
|
||||
ASK = b"_ask"
|
||||
ANSWER = b"_answer"
|
||||
ERROR = b"_error"
|
||||
ERROR_CODE = b"_error_code"
|
||||
ERROR_DESCRIPTION = b"_error_description"
|
||||
UNKNOWN_ERROR_CODE = b"UNKNOWN"
|
||||
|
||||
# buffers
|
||||
_SENDBATCH = defaultdict(list)
|
||||
|
|
@ -322,6 +322,7 @@ class AMPMultiConnectionProtocol(amp.AMP):
|
|||
add a specific log of the problem on the erroring side.
|
||||
|
||||
"""
|
||||
|
||||
def formatAnswer(answerBox):
|
||||
answerBox[ANSWER] = box[ASK]
|
||||
return answerBox
|
||||
|
|
@ -350,6 +351,7 @@ class AMPMultiConnectionProtocol(amp.AMP):
|
|||
errorBox[ERROR_DESCRIPTION] = desc
|
||||
errorBox[ERROR_CODE] = code
|
||||
return errorBox
|
||||
|
||||
deferred = self.dispatchCommand(box)
|
||||
if ASK in box:
|
||||
deferred.addCallbacks(formatAnswer, formatError)
|
||||
|
|
|
|||
|
|
@ -244,7 +244,7 @@ class IRCBot(irc.IRCClient, Session):
|
|||
self.sendLine("NAMES %s" % self.channel)
|
||||
|
||||
def irc_RPL_NAMREPLY(self, prefix, params):
|
||||
""""Handles IRC NAME request returns (nicklist)"""
|
||||
""" "Handles IRC NAME request returns (nicklist)"""
|
||||
channel = params[2].lower()
|
||||
if channel != self.channel.lower():
|
||||
return
|
||||
|
|
|
|||
|
|
@ -358,8 +358,7 @@ if SSH_ENABLED:
|
|||
for port in SSH_PORTS:
|
||||
pstring = "%s:%s" % (ifacestr, port)
|
||||
factory = ssh.makeFactory(
|
||||
{"protocolFactory": _ssh_protocol,
|
||||
"protocolArgs": (), "sessions": PORTAL_SESSIONS}
|
||||
{"protocolFactory": _ssh_protocol, "protocolArgs": (), "sessions": PORTAL_SESSIONS}
|
||||
)
|
||||
factory.noisy = False
|
||||
ssh_service = internet.TCPServer(port, factory, interface=interface)
|
||||
|
|
|
|||
|
|
@ -37,8 +37,9 @@ DUMMYSESSION = namedtuple("DummySession", ["sessid"])(0)
|
|||
# Portal-SessionHandler class
|
||||
# -------------------------------------------------------------
|
||||
|
||||
DOS_PROTECTION_MSG = _("{servername} DoS protection is active."
|
||||
"You are queued to connect in {num} seconds ...")
|
||||
DOS_PROTECTION_MSG = _(
|
||||
"{servername} DoS protection is active." "You are queued to connect in {num} seconds ..."
|
||||
)
|
||||
|
||||
|
||||
class PortalSessionHandler(SessionHandler):
|
||||
|
|
@ -117,9 +118,12 @@ class PortalSessionHandler(SessionHandler):
|
|||
if len(_CONNECTION_QUEUE) > 1:
|
||||
session.data_out(
|
||||
text=(
|
||||
(DOS_PROTECTION_MSG.format(
|
||||
servername=settings.SERVERNAME,
|
||||
num=len(_CONNECTION_QUEUE) * _MIN_TIME_BETWEEN_CONNECTS),),
|
||||
(
|
||||
DOS_PROTECTION_MSG.format(
|
||||
servername=settings.SERVERNAME,
|
||||
num=len(_CONNECTION_QUEUE) * _MIN_TIME_BETWEEN_CONNECTS,
|
||||
),
|
||||
),
|
||||
{},
|
||||
)
|
||||
)
|
||||
|
|
@ -442,8 +446,8 @@ class PortalSessionHandler(SessionHandler):
|
|||
self.portal.amp_protocol.send_MsgPortal2Server(session, **kwargs)
|
||||
|
||||
# eventual local echo (text input only)
|
||||
if 'text' in kwargs and session.protocol_flags.get('LOCALECHO', False):
|
||||
self.data_out(session, text=kwargs['text'])
|
||||
if "text" in kwargs and session.protocol_flags.get("LOCALECHO", False):
|
||||
self.data_out(session, text=kwargs["text"])
|
||||
|
||||
def data_out(self, session, **kwargs):
|
||||
"""
|
||||
|
|
|
|||
|
|
@ -80,6 +80,7 @@ class SSHServerFactory(protocol.ServerFactory):
|
|||
This is only to name this better in logs
|
||||
|
||||
"""
|
||||
|
||||
noisy = False
|
||||
|
||||
def logPrefix(self):
|
||||
|
|
|
|||
|
|
@ -32,8 +32,8 @@ from evennia.utils import ansi
|
|||
from evennia.utils.utils import to_bytes, class_from_module
|
||||
|
||||
_RE_N = re.compile(r"\|n$")
|
||||
_RE_LEND = re.compile(br"\n$|\r$|\r\n$|\r\x00$|", re.MULTILINE)
|
||||
_RE_LINEBREAK = re.compile(br"\n\r|\r\n|\n|\r", re.DOTALL + re.MULTILINE)
|
||||
_RE_LEND = re.compile(rb"\n$|\r$|\r\n$|\r\x00$|", re.MULTILINE)
|
||||
_RE_LINEBREAK = re.compile(rb"\n\r|\r\n|\n|\r", re.DOTALL + re.MULTILINE)
|
||||
_RE_SCREENREADER_REGEX = re.compile(
|
||||
r"%s" % settings.SCREENREADER_REGEX_STRIP, re.DOTALL + re.MULTILINE
|
||||
)
|
||||
|
|
@ -63,6 +63,7 @@ class TelnetServerFactory(protocol.ServerFactory):
|
|||
This exists only to name this better in logs.
|
||||
|
||||
"""
|
||||
|
||||
noisy = False
|
||||
|
||||
def logPrefix(self):
|
||||
|
|
@ -92,6 +93,7 @@ class TelnetProtocol(Telnet, StatefulTelnetProtocol, _BASE_SESSION_CLASS):
|
|||
super().dataReceived(data)
|
||||
except ValueError as err:
|
||||
from evennia.utils import logger
|
||||
|
||||
logger.log_err(f"Malformed telnet input: {err}")
|
||||
|
||||
def connectionMade(self):
|
||||
|
|
@ -458,8 +460,9 @@ class TelnetProtocol(Telnet, StatefulTelnetProtocol, _BASE_SESSION_CLASS):
|
|||
prompt = mxp_parse(prompt)
|
||||
prompt = to_bytes(prompt, self)
|
||||
prompt = prompt.replace(IAC, IAC + IAC).replace(b"\n", b"\r\n")
|
||||
if not self.protocol_flags.get("NOPROMPTGOAHEAD",
|
||||
self.protocol_flags.get("NOGOAHEAD", True)):
|
||||
if not self.protocol_flags.get(
|
||||
"NOPROMPTGOAHEAD", self.protocol_flags.get("NOGOAHEAD", True)
|
||||
):
|
||||
prompt += IAC + GA
|
||||
self.transport.write(mccp_compress(self, prompt))
|
||||
else:
|
||||
|
|
|
|||
|
|
@ -47,14 +47,14 @@ GMCP = bytes([201])
|
|||
# pre-compiled regexes
|
||||
# returns 2-tuple
|
||||
msdp_regex_table = re.compile(
|
||||
br"%s\s*(\w*?)\s*%s\s*%s(.*?)%s" % (MSDP_VAR, MSDP_VAL, MSDP_TABLE_OPEN, MSDP_TABLE_CLOSE)
|
||||
rb"%s\s*(\w*?)\s*%s\s*%s(.*?)%s" % (MSDP_VAR, MSDP_VAL, MSDP_TABLE_OPEN, MSDP_TABLE_CLOSE)
|
||||
)
|
||||
# returns 2-tuple
|
||||
msdp_regex_array = re.compile(
|
||||
br"%s\s*(\w*?)\s*%s\s*%s(.*?)%s" % (MSDP_VAR, MSDP_VAL, MSDP_ARRAY_OPEN, MSDP_ARRAY_CLOSE)
|
||||
rb"%s\s*(\w*?)\s*%s\s*%s(.*?)%s" % (MSDP_VAR, MSDP_VAL, MSDP_ARRAY_OPEN, MSDP_ARRAY_CLOSE)
|
||||
)
|
||||
msdp_regex_var = re.compile(br"%s" % MSDP_VAR)
|
||||
msdp_regex_val = re.compile(br"%s" % MSDP_VAL)
|
||||
msdp_regex_var = re.compile(rb"%s" % MSDP_VAR)
|
||||
msdp_regex_val = re.compile(rb"%s" % MSDP_VAL)
|
||||
|
||||
EVENNIA_TO_GMCP = {
|
||||
"client_options": "Core.Supports.Get",
|
||||
|
|
|
|||
|
|
@ -41,8 +41,10 @@ from twisted.internet import reactor, protocol
|
|||
from twisted.internet.task import LoopingCall
|
||||
|
||||
import django
|
||||
|
||||
django.setup()
|
||||
import evennia # noqa
|
||||
|
||||
evennia._init()
|
||||
|
||||
from django.conf import settings # noqa
|
||||
|
|
@ -214,6 +216,7 @@ class CmdDummyRunnerEchoResponse(Command):
|
|||
with the receive time on both ends.
|
||||
|
||||
"""
|
||||
|
||||
key = "dummyrunner_echo_response"
|
||||
|
||||
def func(self):
|
||||
|
|
@ -228,9 +231,11 @@ class DummyRunnerCmdSet(CmdSet):
|
|||
Dummyrunner injected cmdset.
|
||||
|
||||
"""
|
||||
|
||||
def at_cmdset_creation(self):
|
||||
self.add(CmdDummyRunnerEchoResponse())
|
||||
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# Helper functions
|
||||
# ------------------------------------------------------------
|
||||
|
|
@ -285,6 +290,7 @@ def makeiter(obj):
|
|||
# Client classes
|
||||
# ------------------------------------------------------------
|
||||
|
||||
|
||||
class DummyClient(telnet.StatefulTelnetProtocol):
|
||||
"""
|
||||
Handles connection to a running Evennia server,
|
||||
|
|
@ -296,11 +302,13 @@ class DummyClient(telnet.StatefulTelnetProtocol):
|
|||
def report(self, text, clientkey):
|
||||
pad = " " * (25 - len(text))
|
||||
tim = round(time.time() - self.connection_timestamp)
|
||||
print(f"{text} {clientkey}{pad}\t"
|
||||
f"conn: {NCONNECTED} -> "
|
||||
f"welcome screen: {NLOGIN_SCREEN} -> "
|
||||
f"authing: {NLOGGING_IN} -> "
|
||||
f"loggedin/tot: {NLOGGED_IN}/{NCLIENTS} (after {tim}s)")
|
||||
print(
|
||||
f"{text} {clientkey}{pad}\t"
|
||||
f"conn: {NCONNECTED} -> "
|
||||
f"welcome screen: {NLOGIN_SCREEN} -> "
|
||||
f"authing: {NLOGGING_IN} -> "
|
||||
f"loggedin/tot: {NLOGGED_IN}/{NCLIENTS} (after {tim}s)"
|
||||
)
|
||||
|
||||
def connectionMade(self):
|
||||
"""
|
||||
|
|
@ -342,7 +350,7 @@ class DummyClient(telnet.StatefulTelnetProtocol):
|
|||
# (unclear why this would be - overload?)
|
||||
# try sending a look to get something to start with
|
||||
self.report("?? retrying welcome screen", self.key)
|
||||
self.sendLine(bytes("look", 'utf-8'))
|
||||
self.sendLine(bytes("look", "utf-8"))
|
||||
# make sure to check again later
|
||||
reactor.callLater(30, self._retry_welcome_screen)
|
||||
|
||||
|
|
@ -363,8 +371,10 @@ class DummyClient(telnet.StatefulTelnetProtocol):
|
|||
TOTAL_LAG_MEASURES = 0
|
||||
TIME_ALL_LOGIN = time.time()
|
||||
|
||||
print(f".. running 30s average: ~{avgrate} actions/s "
|
||||
f"lag: {lag:.2}s (in: {lag_in:.2}s, out: {lag_out:.2}s)")
|
||||
print(
|
||||
f".. running 30s average: ~{avgrate} actions/s "
|
||||
f"lag: {lag:.2}s (in: {lag_in:.2}s, out: {lag_out:.2}s)"
|
||||
)
|
||||
|
||||
reactor.callLater(30, self._print_statistics)
|
||||
|
||||
|
|
@ -393,7 +403,7 @@ class DummyClient(telnet.StatefulTelnetProtocol):
|
|||
# negotiation)
|
||||
# start client tick
|
||||
d = LoopingCall(self.step)
|
||||
df = max(abs(TIMESTEP * 0.001), min(TIMESTEP/10, 0.5))
|
||||
df = max(abs(TIMESTEP * 0.001), min(TIMESTEP / 10, 0.5))
|
||||
# dither next attempt with random time
|
||||
timestep = TIMESTEP + (-df + (random.random() * df))
|
||||
d.start(timestep, now=True).addErrback(self.error)
|
||||
|
|
@ -477,7 +487,7 @@ class DummyClient(telnet.StatefulTelnetProtocol):
|
|||
self._logging_out = True
|
||||
cmd = self._logout(self)[0]
|
||||
self.report(f"-> logout/disconnect ({self.istep} actions)", self.key)
|
||||
self.sendLine(bytes(cmd, 'utf-8'))
|
||||
self.sendLine(bytes(cmd, "utf-8"))
|
||||
|
||||
def step(self):
|
||||
"""
|
||||
|
|
@ -521,7 +531,7 @@ class DummyClient(telnet.StatefulTelnetProtocol):
|
|||
# the send as possible
|
||||
cmd = cmd.format(timestamp=time.time())
|
||||
|
||||
self.sendLine(bytes(cmd, 'utf-8'))
|
||||
self.sendLine(bytes(cmd, "utf-8"))
|
||||
self.action_started = time.time()
|
||||
self.istep += 1
|
||||
|
||||
|
|
@ -605,17 +615,19 @@ if __name__ == "__main__":
|
|||
args = parser.parse_args()
|
||||
nclients = int(args.nclients[0])
|
||||
|
||||
print(INFO_STARTING.format(
|
||||
nclients=nclients,
|
||||
port=TELNET_PORT,
|
||||
idmapper_cache_size=IDMAPPER_CACHE_MAXSIZE,
|
||||
timestep=TIMESTEP,
|
||||
rate=1/TIMESTEP,
|
||||
chance_of_login=CHANCE_OF_LOGIN * 100,
|
||||
chance_of_action=CHANCE_OF_ACTION * 100,
|
||||
avg_rate=(1 / TIMESTEP) * CHANCE_OF_ACTION,
|
||||
avg_rate_total=(1 / TIMESTEP) * CHANCE_OF_ACTION * nclients
|
||||
))
|
||||
print(
|
||||
INFO_STARTING.format(
|
||||
nclients=nclients,
|
||||
port=TELNET_PORT,
|
||||
idmapper_cache_size=IDMAPPER_CACHE_MAXSIZE,
|
||||
timestep=TIMESTEP,
|
||||
rate=1 / TIMESTEP,
|
||||
chance_of_login=CHANCE_OF_LOGIN * 100,
|
||||
chance_of_action=CHANCE_OF_ACTION * 100,
|
||||
avg_rate=(1 / TIMESTEP) * CHANCE_OF_ACTION,
|
||||
avg_rate_total=(1 / TIMESTEP) * CHANCE_OF_ACTION * nclients,
|
||||
)
|
||||
)
|
||||
|
||||
# run the dummyrunner
|
||||
TIME_START = t0 = time.time()
|
||||
|
|
|
|||
|
|
@ -86,8 +86,9 @@ TELNET_PORT = None
|
|||
# some convenient templates
|
||||
|
||||
DUMMY_NAME = "Dummy_{gid}"
|
||||
DUMMY_PWD = (''.join(random.choice(string.ascii_letters + string.digits)
|
||||
for _ in range(20)) + "-{gid}")
|
||||
DUMMY_PWD = (
|
||||
"".join(random.choice(string.ascii_letters + string.digits) for _ in range(20)) + "-{gid}"
|
||||
)
|
||||
START_ROOM = "testing_room_start_{gid}"
|
||||
ROOM_TEMPLATE = "testing_room_%s"
|
||||
EXIT_TEMPLATE = "exit_%s"
|
||||
|
|
@ -101,6 +102,7 @@ TOBJ_TYPECLASS = "contrib.tutorial_examples.red_button.RedButton"
|
|||
|
||||
# login/logout
|
||||
|
||||
|
||||
def c_login(client):
|
||||
"logins to the game"
|
||||
# we always use a new client name
|
||||
|
|
@ -131,10 +133,7 @@ def c_login_nodig(client):
|
|||
"logins, don't dig its own room"
|
||||
cname = DUMMY_NAME.format(gid=client.gid)
|
||||
cpwd = DUMMY_PWD.format(gid=client.gid)
|
||||
cmds = (
|
||||
f"create {cname} {cpwd}",
|
||||
f"connect {cname} {cpwd}"
|
||||
)
|
||||
cmds = (f"create {cname} {cpwd}", f"connect {cname} {cpwd}")
|
||||
return cmds
|
||||
|
||||
|
||||
|
|
@ -174,7 +173,10 @@ def c_idles(client):
|
|||
|
||||
def c_help(client):
|
||||
"reads help files"
|
||||
cmds = ("help", "dummyrunner_echo_response",)
|
||||
cmds = (
|
||||
"help",
|
||||
"dummyrunner_echo_response",
|
||||
)
|
||||
return cmds
|
||||
|
||||
|
||||
|
|
@ -262,21 +264,16 @@ def c_measure_lag(client):
|
|||
PROFILE = "looker"
|
||||
|
||||
|
||||
if PROFILE == 'idler':
|
||||
if PROFILE == "idler":
|
||||
ACTIONS = (
|
||||
c_login,
|
||||
c_logout,
|
||||
(0.9, c_idles),
|
||||
(0.1, c_measure_lag),
|
||||
)
|
||||
elif PROFILE == 'looker':
|
||||
ACTIONS = (
|
||||
c_login,
|
||||
c_logout,
|
||||
(0.8, c_looks),
|
||||
(0.2, c_measure_lag)
|
||||
)
|
||||
elif PROFILE == 'normal_player':
|
||||
elif PROFILE == "looker":
|
||||
ACTIONS = (c_login, c_logout, (0.8, c_looks), (0.2, c_measure_lag))
|
||||
elif PROFILE == "normal_player":
|
||||
ACTIONS = (
|
||||
c_login,
|
||||
c_logout,
|
||||
|
|
@ -285,9 +282,9 @@ elif PROFILE == 'normal_player':
|
|||
(0.2, c_help),
|
||||
(0.3, c_moves),
|
||||
(0.05, c_socialize),
|
||||
(0.1, c_measure_lag)
|
||||
(0.1, c_measure_lag),
|
||||
)
|
||||
elif PROFILE == 'normal_builder':
|
||||
elif PROFILE == "normal_builder":
|
||||
ACTIONS = (
|
||||
c_login,
|
||||
c_logout,
|
||||
|
|
@ -297,9 +294,9 @@ elif PROFILE == 'normal_builder':
|
|||
(0.01, c_digs),
|
||||
(0.01, c_creates_obj),
|
||||
(0.2, c_moves),
|
||||
(0.1, c_measure_lag)
|
||||
(0.1, c_measure_lag),
|
||||
)
|
||||
elif PROFILE == 'heavy_builder':
|
||||
elif PROFILE == "heavy_builder":
|
||||
ACTIONS = (
|
||||
c_login,
|
||||
c_logout,
|
||||
|
|
@ -309,9 +306,9 @@ elif PROFILE == 'heavy_builder':
|
|||
(0.1, c_digs),
|
||||
(0.1, c_creates_obj),
|
||||
(0.2, c_moves),
|
||||
(0.1, c_measure_lag)
|
||||
(0.1, c_measure_lag),
|
||||
)
|
||||
elif PROFILE == 'socializing_builder':
|
||||
elif PROFILE == "socializing_builder":
|
||||
ACTIONS = (
|
||||
c_login,
|
||||
c_logout,
|
||||
|
|
@ -321,17 +318,13 @@ elif PROFILE == 'socializing_builder':
|
|||
(0.1, c_creates_obj),
|
||||
(0.2, c_digs),
|
||||
(0.3, c_moves),
|
||||
(0.1, c_measure_lag)
|
||||
)
|
||||
elif PROFILE == 'only_digger':
|
||||
ACTIONS = (
|
||||
c_login,
|
||||
c_logout,
|
||||
(0.9, c_digs),
|
||||
(0.1, c_measure_lag)
|
||||
(0.1, c_measure_lag),
|
||||
)
|
||||
elif PROFILE == "only_digger":
|
||||
ACTIONS = (c_login, c_logout, (0.9, c_digs), (0.1, c_measure_lag))
|
||||
|
||||
else:
|
||||
print("No dummyrunner ACTION profile defined.")
|
||||
import sys
|
||||
|
||||
sys.exit()
|
||||
|
|
|
|||
|
|
@ -27,7 +27,8 @@ MAX_COMMAND_RATE = 100000
|
|||
MAX_CONNECTION_RATE = 100000
|
||||
MAX_CHAR_LIMIT = 100000
|
||||
|
||||
print("""
|
||||
print(
|
||||
"""
|
||||
Dummyrunner settings_mixin added (ONLY FOR PROFILING, NOT FOR PRODUCTION!)
|
||||
|
||||
PASSWORD_HASHERS = ("django.contrib.auth.hashers.MD5PasswordHasher",)
|
||||
|
|
@ -39,4 +40,5 @@ print("""
|
|||
MAX_COMMAND_RATE = 100000
|
||||
MAX_CONNECTION_RATE = 100000
|
||||
MAX_CHAR_LIMIT = 100000
|
||||
""")
|
||||
"""
|
||||
)
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ class TestDummyrunnerSettings(TestCase):
|
|||
self.client.counter = Mock(return_value=1)
|
||||
self.client.gid = "20171025161153-1"
|
||||
self.client.name = "Dummy_%s" % self.client.gid
|
||||
self.client.password = Something,
|
||||
self.client.password = (Something,)
|
||||
self.client.start_room = "testing_room_start_%s" % self.client.gid
|
||||
self.client.objs = []
|
||||
self.client.exits = []
|
||||
|
|
@ -45,12 +45,12 @@ class TestDummyrunnerSettings(TestCase):
|
|||
c_login(self.client),
|
||||
(
|
||||
Something, # create
|
||||
'yes', # confirm creation
|
||||
"yes", # confirm creation
|
||||
Something, # connect
|
||||
"dig %s" % self.client.start_room,
|
||||
"teleport %s" % self.client.start_room,
|
||||
"py from evennia.server.profiling.dummyrunner import DummyRunnerCmdSet;"
|
||||
"self.cmdset.add(DummyRunnerCmdSet, persistent=False)"
|
||||
"self.cmdset.add(DummyRunnerCmdSet, persistent=False)",
|
||||
),
|
||||
)
|
||||
|
||||
|
|
@ -86,7 +86,7 @@ class TestDummyrunnerSettings(TestCase):
|
|||
)
|
||||
|
||||
def test_c_digs(self):
|
||||
self.assertEqual(c_digs(self.client), ("dig/tel testing_room_1 = exit_1, exit_1", ))
|
||||
self.assertEqual(c_digs(self.client), ("dig/tel testing_room_1 = exit_1, exit_1",))
|
||||
self.assertEqual(self.client.exits, ["exit_1", "exit_1"])
|
||||
self.clear_client_lists()
|
||||
|
||||
|
|
|
|||
|
|
@ -284,9 +284,12 @@ class Evennia:
|
|||
(i, tup[0], tup[1]) for i, tup in enumerate(settings_compare) if i in mismatches
|
||||
):
|
||||
# update the database
|
||||
INFO_DICT["info"] = (
|
||||
" %s:\n '%s' changed to '%s'. Updating unchanged entries in database ..."
|
||||
% (settings_names[i], prev, curr)
|
||||
INFO_DICT[
|
||||
"info"
|
||||
] = " %s:\n '%s' changed to '%s'. Updating unchanged entries in database ..." % (
|
||||
settings_names[i],
|
||||
prev,
|
||||
curr,
|
||||
)
|
||||
if i == 0:
|
||||
ObjectDB.objects.filter(db_cmdset_storage__exact=prev).update(
|
||||
|
|
@ -344,7 +347,7 @@ class Evennia:
|
|||
# i.e. this is an empty DB that needs populating.
|
||||
INFO_DICT["info"] = " Server started for the first time. Setting defaults."
|
||||
initial_setup.handle_setup()
|
||||
elif last_initial_setup_step not in ('done', -1):
|
||||
elif last_initial_setup_step not in ("done", -1):
|
||||
# last step crashed, so we weill resume from this step.
|
||||
# modules and setup will resume from this step, retrying
|
||||
# the last failed module. When all are finished, the step
|
||||
|
|
@ -405,9 +408,10 @@ class Evennia:
|
|||
self.update_defaults()
|
||||
|
||||
# run at_init() on all cached entities on reconnect
|
||||
[[entity.at_init()
|
||||
for entity in typeclass_db.get_all_cached_instances()]
|
||||
for typeclass_db in TypedObject.__subclasses__()]
|
||||
[
|
||||
[entity.at_init() for entity in typeclass_db.get_all_cached_instances()]
|
||||
for typeclass_db in TypedObject.__subclasses__()
|
||||
]
|
||||
|
||||
# call correct server hook based on start file value
|
||||
if mode == "reload":
|
||||
|
|
@ -418,6 +422,7 @@ class Evennia:
|
|||
self.at_server_cold_start()
|
||||
logger.log_msg("Evennia Server successfully restarted in 'reset' mode.")
|
||||
elif mode == "shutdown":
|
||||
from evennia.objects.models import ObjectDB
|
||||
self.at_server_cold_start()
|
||||
# clear eventual lingering session storages
|
||||
ObjectDB.objects.clear_all_sessids()
|
||||
|
|
|
|||
|
|
@ -185,8 +185,10 @@ class SessionHandler(dict):
|
|||
global _FUNCPARSER
|
||||
if not _FUNCPARSER:
|
||||
from evennia.utils.funcparser import FuncParser
|
||||
_FUNCPARSER = FuncParser(settings.FUNCPARSER_OUTGOING_MESSAGES_MODULES,
|
||||
raise_errors=True)
|
||||
|
||||
_FUNCPARSER = FuncParser(
|
||||
settings.FUNCPARSER_OUTGOING_MESSAGES_MODULES, raise_errors=True
|
||||
)
|
||||
|
||||
options = kwargs.pop("options", None) or {}
|
||||
raw = options.get("raw", False)
|
||||
|
|
@ -222,8 +224,11 @@ class SessionHandler(dict):
|
|||
elif isinstance(data, (str, bytes)):
|
||||
data = _utf8(data)
|
||||
|
||||
if (_FUNCPARSER_PARSE_OUTGOING_MESSAGES_ENABLED
|
||||
and not raw and isinstance(self, ServerSessionHandler)):
|
||||
if (
|
||||
_FUNCPARSER_PARSE_OUTGOING_MESSAGES_ENABLED
|
||||
and not raw
|
||||
and isinstance(self, ServerSessionHandler)
|
||||
):
|
||||
# only apply funcparser on the outgoing path (sessionhandler->)
|
||||
# data = parse_inlinefunc(data, strip=strip_inlinefunc, session=session)
|
||||
data = _FUNCPARSER.parse(data, strip=strip_inlinefunc, session=session)
|
||||
|
|
@ -638,8 +643,7 @@ class ServerSessionHandler(SessionHandler):
|
|||
# mean connecting from the same host would not catch duplicates
|
||||
sid = id(curr_session)
|
||||
doublet_sessions = [
|
||||
sess for sess in self.values()
|
||||
if sess.logged_in and sess.uid == uid and id(sess) != sid
|
||||
sess for sess in self.values() if sess.logged_in and sess.uid == uid and id(sess) != sid
|
||||
]
|
||||
|
||||
for session in doublet_sessions:
|
||||
|
|
|
|||
|
|
@ -124,14 +124,14 @@ class ThrottleTest(BaseEvenniaTest):
|
|||
|
||||
# There should only be (cache_size * num_ips) total in the Throttle cache
|
||||
self.assertEqual(sum([len(cache[x]) for x in cache.keys()]), throttle.cache_size * len(ips))
|
||||
|
||||
|
||||
# Make sure the cache is populated
|
||||
self.assertTrue(throttle.get())
|
||||
|
||||
# Remove the test IPs from the throttle cache
|
||||
|
||||
# Remove the test IPs from the throttle cache
|
||||
# (in case persistent storage was configured by the user)
|
||||
for ip in ips:
|
||||
self.assertTrue(throttle.remove(ip))
|
||||
|
||||
|
||||
# Make sure the cache is empty
|
||||
self.assertFalse(throttle.get())
|
||||
self.assertFalse(throttle.get())
|
||||
|
|
|
|||
|
|
@ -32,6 +32,4 @@ class EvenniaTestSuiteRunner(DiscoverRunner):
|
|||
import evennia
|
||||
|
||||
evennia._init()
|
||||
return super().build_suite(
|
||||
test_labels, extra_tests=extra_tests, **kwargs
|
||||
)
|
||||
return super().build_suite(test_labels, extra_tests=extra_tests, **kwargs)
|
||||
|
|
|
|||
|
|
@ -35,14 +35,14 @@ class Throttle:
|
|||
the throttle is imposed!
|
||||
"""
|
||||
try:
|
||||
self.storage = caches['throttle']
|
||||
self.storage = caches["throttle"]
|
||||
except Exception:
|
||||
logger.log_trace("Throttle: Errors encountered; using default cache.")
|
||||
self.storage = caches['default']
|
||||
self.storage = caches["default"]
|
||||
|
||||
self.name = kwargs.get('name', 'undefined-throttle')
|
||||
self.name = kwargs.get("name", "undefined-throttle")
|
||||
self.limit = kwargs.get("limit", 5)
|
||||
self.cache_size = kwargs.get('cache_size', self.limit)
|
||||
self.cache_size = kwargs.get("cache_size", self.limit)
|
||||
self.timeout = kwargs.get("timeout", 5 * 60)
|
||||
|
||||
def get_cache_key(self, *args, **kwargs):
|
||||
|
|
@ -51,7 +51,7 @@ class Throttle:
|
|||
collisions in the same namespace.
|
||||
|
||||
"""
|
||||
return '-'.join((self.name, *args))
|
||||
return "-".join((self.name, *args))
|
||||
|
||||
def touch(self, key, *args, **kwargs):
|
||||
"""
|
||||
|
|
@ -85,7 +85,7 @@ class Throttle:
|
|||
cache_key = self.get_cache_key(str(ip))
|
||||
return self.storage.get(cache_key, deque(maxlen=self.cache_size))
|
||||
else:
|
||||
keys_key = self.get_cache_key('keys')
|
||||
keys_key = self.get_cache_key("keys")
|
||||
keys = self.storage.get_or_set(keys_key, set(), self.timeout)
|
||||
data = self.storage.get_many((self.get_cache_key(x) for x in keys))
|
||||
|
||||
|
|
@ -161,7 +161,7 @@ class Throttle:
|
|||
IP, not the cache-prefixed key.
|
||||
|
||||
"""
|
||||
keys_key = self.get_cache_key('keys')
|
||||
keys_key = self.get_cache_key("keys")
|
||||
keys = self.storage.get(keys_key, set())
|
||||
keys.add(ip)
|
||||
self.storage.set(keys_key, keys, self.timeout)
|
||||
|
|
@ -175,7 +175,7 @@ class Throttle:
|
|||
ip(str): IP to remove from list of keys.
|
||||
|
||||
"""
|
||||
keys_key = self.get_cache_key('keys')
|
||||
keys_key = self.get_cache_key("keys")
|
||||
keys = self.storage.get(keys_key, set())
|
||||
try:
|
||||
keys.remove(ip)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue