The first of many re-arrangements. Eliminated gameconf in favor of using the manager on ConfigValue. Moved some commands while I was at it. There are going to be crash bugs that need to be found and worked out.

This commit is contained in:
Greg Taylor 2008-06-15 17:21:02 +00:00
parent 8a1204ce76
commit d620f3b1f0
17 changed files with 216 additions and 200 deletions

View file

@ -1,8 +1,32 @@
"""
Custom manager for ConfigValue objects.
"""
from traceback import format_exc
from django.db import models
import functions_log
class ConfigValueManager(models.Manager):
pass
def get_configvalue(self, configname):
"""
Retrieve a configuration value.
"""
try:
return self.get(conf_key__iexact=configname).conf_value
except self.model.DoesNotExist:
functions_log.log_errmsg("Unable to get config value for %s (does not exist):\n%s" % (
configname, (format_exc())))
def set_configvalue(self, configname, newvalue):
"""
Sets a configuration value with the specified name.
Returns the new value for the directive.
"""
try:
conf = self.get(conf_key=configname)
conf.conf_value = newvalue
conf.save()
# We'll do this instead of conf.conf_value, might save a DB query.
return newvalue
except self.model.DoesNotExist:
functions_log.log_errmsg("Unable to set config value for %s (does not exist):\n%s" % (
configname, (format_exc())))

View file

@ -32,6 +32,9 @@ class ConfigValue(models.Model):
class Admin:
list_display = ('conf_key', 'conf_value',)
def __str__(self):
return "%s" % self.conf_key
class ConnectScreen(models.Model):
"""
Stores connect screens. The admins may have only one or multiple, which

View file

@ -5,8 +5,8 @@ from django.contrib.auth.models import User, Group
import scripthandler
import defines_global
import gameconf
import ansi
from apps.config.models import ConfigValue
from apps.objects.managers.commchannel import CommChannelManager
from apps.objects.managers.object import ObjectManager
@ -439,7 +439,7 @@ class Object(models.Model):
# Gather up everything, other than exits and going/garbage, that is under
# the belief this is its location.
objs = self.obj_location.filter(type__in=[1,2,3])
default_home_id = gameconf.get_configvalue('default_home')
default_home_id = ConfigValue.objects.get_configvalue('default_home')
try:
default_home = Object.objects.get(id=default_home_id)
except:

View file

@ -1,3 +1,8 @@
"""
This is the command processing module. It is instanced once in the main
server module and the handle() function is hit every time a player sends
something.
"""
from traceback import format_exc
import time
@ -5,14 +10,9 @@ import defines_global
import cmdtable
import functions_db
import functions_general
import functions_log
import functions_comsys
"""
This is the command processing module. It is instanced once in the main
server module and the handle() function is hit every time a player sends
something.
"""
class UnknownCommand(Exception):
"""
Throw this when a user enters an an invalid command.
@ -225,7 +225,7 @@ def handle(cdat):
cmd(cdat)
except:
session.msg("Untrapped error, please file a bug report:\n%s" % (format_exc(),))
functions_general.log_errmsg("Untrapped error, evoker %s: %s" %
functions_log.log_errmsg("Untrapped error, evoker %s: %s" %
(session, format_exc()))
return

View file

@ -18,64 +18,64 @@ permissions tuple.
"""
# -- Unlogged-in Command Table --
# Command Name Command Function Privilege Tuple
# Command Name Command Function Privilege Tuple
uncon_ctable = {
"connect": (commands.unloggedin.cmd_connect, None),
"create": (commands.unloggedin.cmd_create, None),
"quit": (commands.unloggedin.cmd_quit, None),
"connect": (commands.unloggedin.cmd_connect, None),
"create": (commands.unloggedin.cmd_create, None),
"quit": (commands.unloggedin.cmd_quit, None),
}
# -- Command Table --
# Command Name Command Function Privilege Tuple
# Command Name Command Function Privilege Tuple
ctable = {
"addcom": (commands.comsys.cmd_addcom, None),
"comlist": (commands.comsys.cmd_comlist, None),
"delcom": (commands.comsys.cmd_delcom, None),
"drop": (commands.general.cmd_drop, None),
"examine": (commands.general.cmd_examine, None),
"get": (commands.general.cmd_get, None),
"help": (commands.general.cmd_help, None),
"idle": (commands.general.cmd_idle, None),
"inventory": (commands.general.cmd_inventory, None),
"look": (commands.general.cmd_look, None),
"page": (commands.general.cmd_page, None),
"pose": (commands.general.cmd_pose, None),
"quit": (commands.general.cmd_quit, None),
"say": (commands.general.cmd_say, None),
"time": (commands.general.cmd_time, None),
"uptime": (commands.general.cmd_uptime, None),
"version": (commands.general.cmd_version, None),
"who": (commands.general.cmd_who, None),
"@alias": (commands.objmanip.cmd_alias, None),
"@boot": (commands.privileged.cmd_boot, ("genperms.manage_players")),
"@ccreate": (commands.comsys.cmd_ccreate, ("objects.add_commchannel")),
"@cdestroy": (commands.comsys.cmd_cdestroy, ("objects.delete_commchannel")),
"@cemit": (commands.comsys.cmd_cemit, None),
"@clist": (commands.comsys.cmd_clist, None),
"@create": (commands.objmanip.cmd_create, ("genperms.builder")),
"@describe": (commands.objmanip.cmd_description, None),
"@destroy": (commands.objmanip.cmd_destroy, ("genperms.builder")),
"@dig": (commands.objmanip.cmd_dig, ("genperms.builder")),
"@emit": (commands.general.cmd_emit, ("genperms.announce")),
# "@pemit": (commands.general.cmd_pemit, None),
"@find": (commands.objmanip.cmd_find, ("genperms.builder")),
"@link": (commands.objmanip.cmd_link, ("genperms.builder")),
"@list": (commands.info.cmd_list, ("genperms.process_control")),
"@name": (commands.objmanip.cmd_name, None),
"@nextfree": (commands.objmanip.cmd_nextfree, ("genperms.builder")),
"@newpassword": (commands.privileged.cmd_newpassword, ("genperms.manage_players")),
"@open": (commands.objmanip.cmd_open, ("genperms.builder")),
"@password": (commands.general.cmd_password, None),
"@ps": (commands.info.cmd_ps, ("genperms.process_control")),
"@reload": (commands.privileged.cmd_reload, ("genperms.process_control")),
"@set": (commands.objmanip.cmd_set, None),
"@shutdown": (commands.privileged.cmd_shutdown, ("genperms.process_control")),
"@stats": (commands.info.cmd_stats, None),
"@teleport": (commands.objmanip.cmd_teleport, ("genperms.builder")),
"@unlink": (commands.objmanip.cmd_unlink, ("genperms.builder")),
"@wall": (commands.general.cmd_wall, ("genperms.announce")),
"@wipe": (commands.objmanip.cmd_wipe, None),
"addcom": (commands.comsys.cmd_addcom, None),
"comlist": (commands.comsys.cmd_comlist, None),
"delcom": (commands.comsys.cmd_delcom, None),
"drop": (commands.general.cmd_drop, None),
"examine": (commands.general.cmd_examine, None),
"get": (commands.general.cmd_get, None),
"help": (commands.general.cmd_help, None),
"idle": (commands.general.cmd_idle, None),
"inventory": (commands.general.cmd_inventory, None),
"look": (commands.general.cmd_look, None),
"page": (commands.general.cmd_page, None),
"pose": (commands.general.cmd_pose, None),
"quit": (commands.general.cmd_quit, None),
"say": (commands.general.cmd_say, None),
"time": (commands.info.cmd_time, None),
"uptime": (commands.info.cmd_uptime, None),
"version": (commands.info.cmd_version, None),
"who": (commands.general.cmd_who, None),
"@alias": (commands.objmanip.cmd_alias, None),
"@boot": (commands.privileged.cmd_boot, ("genperms.manage_players")),
"@ccreate": (commands.comsys.cmd_ccreate, ("objects.add_commchannel")),
"@cdestroy": (commands.comsys.cmd_cdestroy, ("objects.delete_commchannel")),
"@cemit": (commands.comsys.cmd_cemit, None),
"@clist": (commands.comsys.cmd_clist, None),
"@create": (commands.objmanip.cmd_create, ("genperms.builder")),
"@describe": (commands.objmanip.cmd_description, None),
"@destroy": (commands.objmanip.cmd_destroy, ("genperms.builder")),
"@dig": (commands.objmanip.cmd_dig, ("genperms.builder")),
"@emit": (commands.general.cmd_emit, ("genperms.announce")),
# "@pemit": (commands.general.cmd_pemit, None),
"@find": (commands.objmanip.cmd_find, ("genperms.builder")),
"@link": (commands.objmanip.cmd_link, ("genperms.builder")),
"@list": (commands.info.cmd_list, ("genperms.process_control")),
"@name": (commands.objmanip.cmd_name, None),
"@nextfree": (commands.objmanip.cmd_nextfree, ("genperms.builder")),
"@newpassword": (commands.privileged.cmd_newpassword, ("genperms.manage_players")),
"@open": (commands.objmanip.cmd_open, ("genperms.builder")),
"@password": (commands.general.cmd_password, None),
"@ps": (commands.info.cmd_ps, ("genperms.process_control")),
"@reload": (commands.privileged.cmd_reload, ("genperms.process_control")),
"@set": (commands.objmanip.cmd_set, None),
"@shutdown": (commands.privileged.cmd_shutdown, ("genperms.process_control")),
"@stats": (commands.info.cmd_stats, None),
"@teleport": (commands.objmanip.cmd_teleport, ("genperms.builder")),
"@unlink": (commands.objmanip.cmd_unlink, ("genperms.builder")),
"@wall": (commands.general.cmd_wall, ("genperms.announce")),
"@wipe": (commands.objmanip.cmd_wipe, None),
}
def return_cmdtuple(func_name, unlogged_cmd=False):

View file

@ -1,6 +1,8 @@
import os, time
import gameconf
import settings
import time
from django.conf import settings
from apps.config.models import ConfigValue
import functions_general
import functions_db
import functions_help
@ -90,9 +92,9 @@ def cmd_inventory(cdat):
money = int(pobject.get_attribute_value("MONEY", default=0))
if money == 1:
money_name = gameconf.get_configvalue("MONEY_NAME_SINGULAR")
money_name = ConfigValue.objects.get_configvalue("MONEY_NAME_SINGULAR")
else:
money_name = gameconf.get_configvalue("MONEY_NAME_PLURAL")
money_name = ConfigValue.objects.get_configvalue("MONEY_NAME_PLURAL")
session.msg("You have %d %s." % (money,money_name))
@ -532,33 +534,3 @@ def cmd_help(cdat):
topic = topics[0]
session.msg("\r\n%s%s%s" % (ansi.ansi["hilite"], topic.get_topicname(), ansi.ansi["normal"]))
session.msg(topic.get_entrytext_ingame())
def cmd_version(cdat):
"""
Version info command.
"""
session = cdat['session']
retval = "-"*50 +"\n\r"
retval += "Evennia %s\n\r" % (defines_global.EVENNIA_VERSION,)
retval += "-"*50
session.msg(retval)
def cmd_time(cdat):
"""
Server local time.
"""
session = cdat['session']
session.msg('Current server time : %s' % (time.strftime('%a %b %d %H:%M %Y (%Z)', time.localtime(),)))
def cmd_uptime(cdat):
"""
Server uptime and stats.
"""
session = cdat['session']
server = cdat['server']
start_delta = time.time() - server.start_time
loadavg = os.getloadavg()
session.msg('Current server time : %s' % (time.strftime('%a %b %d %H:%M %Y (%Z)', time.localtime(),)))
session.msg('Server start time : %s' % (time.strftime('%a %b %d %H:%M %Y', time.localtime(server.start_time),)))
session.msg('Server uptime : %s' % functions_general.time_format(start_delta, style=2))
session.msg('Server load (1 min) : %.2f' % loadavg[0])

View file

@ -1,11 +1,49 @@
import gameconf
if not gameconf.host_os_is('nt'):
"""
Commands that are generally staff-oriented that show information regarding
the server instance.
"""
import os
import time
import functions_general
if not functions_general.host_os_is('nt'):
# Don't import the resource module if the host OS is Windows.
import resource
import os
import functions_db
import scheduler
import defines_global
def cmd_version(cdat):
"""
Version info command.
"""
session = cdat['session']
retval = "-"*50 +"\n\r"
retval += "Evennia %s\n\r" % (defines_global.EVENNIA_VERSION,)
retval += "-"*50
session.msg(retval)
def cmd_time(cdat):
"""
Server local time.
"""
session = cdat['session']
session.msg('Current server time : %s' % (time.strftime('%a %b %d %H:%M %Y (%Z)', time.localtime(),)))
def cmd_uptime(cdat):
"""
Server uptime and stats.
"""
session = cdat['session']
server = cdat['server']
start_delta = time.time() - server.start_time
loadavg = os.getloadavg()
session.msg('Current server time : %s' % (time.strftime('%a %b %d %H:%M %Y (%Z)', time.localtime(),)))
session.msg('Server start time : %s' % (time.strftime('%a %b %d %H:%M %Y', time.localtime(server.start_time),)))
session.msg('Server uptime : %s' % functions_general.time_format(start_delta, style=2))
session.msg('Server load (1 min) : %.2f' % loadavg[0])
def cmd_list(cdat):
"""
@ -23,7 +61,7 @@ def cmd_list(cdat):
elif argstr == "commands":
session.msg('Commands: '+ ' '.join(session.server.command_list()))
elif argstr == "process":
if not gameconf.host_os_is('nt'):
if not functions_general.host_os_is('nt'):
loadvg = os.getloadavg()
psize = resource.getpagesize()
rusage = resource.getrusage(resource.RUSAGE_SELF)

View file

@ -3,11 +3,12 @@ from datetime import datetime, timedelta
from django.db import connection
from django.contrib.auth.models import User
from apps.objects.models import Object, Attribute
import defines_global
import gameconf
from django.db.models import Q
from apps.objects.models import Object, Attribute
from apps.config.models import ConfigValue
import defines_global
"""
Common database functions.
"""
@ -336,7 +337,7 @@ def create_user(cdat, uname, email, password):
"""
session = cdat['session']
server = cdat['server']
start_room = int(gameconf.get_configvalue('player_dbnum_start'))
start_room = int(ConfigValue.objects.get_configvalue('player_dbnum_start'))
start_room_obj = get_object_from_dbref(start_room)
# The user's entry in the User table must match up to an object
@ -372,4 +373,6 @@ def create_user(cdat, uname, email, password):
# Activate the player's session and set them loose.
session.login(user)
print 'Registration: %s' % (session,)
session.msg("Welcome to %s, %s.\n\r" % (gameconf.get_configvalue('site_name'), session.get_pobject().get_name(show_dbref=False),))
session.msg("Welcome to %s, %s.\n\r" % (
ConfigValue.objects.get_configvalue('site_name'),
session.get_pobject().get_name(show_dbref=False)))

View file

@ -1,10 +1,9 @@
"""
General functions that don't fit neatly under any given category.
"""
import os
import textwrap
from twisted.python import log
import session_mgr
"""
General commonly used functions.
"""
def wildcard_to_regexp(instring):
"""
@ -39,24 +38,6 @@ def cmd_check_num_args(session, arg_list, min_args, errortext="Missing arguments
session.msg(errortext)
return False
return True
def log_errmsg(errormsg):
"""
Prints/logs an error message to the server log.
errormsg: (string) The message to be logged.
"""
log.err('ERROR: %s' % (errormsg,))
#functions_comsys.send_cmessage("Errors", "[Errors] "+ errormsg)
def log_infomsg(infomsg):
"""
Prints any generic debugging/informative info that should appear in the log.
debugmsg: (string) The message to be logged.
"""
log.msg('%s' % (infomsg,))
#functions_comsys.send_cmessage("Info", "[Info] "+ infomsg)
def time_format(seconds, style=0):
"""
@ -138,3 +119,11 @@ def word_wrap(text, width=78):
width: (int) The number of characters to wrap to.
"""
return '\r\n'.join(textwrap.wrap(text, width))
def host_os_is(osname):
"""
Check to see if the host OS matches the query.
"""
if os.name == osname:
return True
return False

24
functions_log.py Normal file
View file

@ -0,0 +1,24 @@
"""
Logging facilities
This file should have an absolute minimum in imports. If you'd like to layer
additional functionality on top of some of the methods below, wrap them in
a higher layer module.
"""
from twisted.python import log
def log_errmsg(errormsg):
"""
Prints/logs an error message to the server log.
errormsg: (string) The message to be logged.
"""
log.err('ERROR: %s' % (errormsg,))
def log_infomsg(infomsg):
"""
Prints any generic debugging/informative info that should appear in the log.
debugmsg: (string) The message to be logged.
"""
log.msg('%s' % (infomsg,))

View file

@ -1,34 +0,0 @@
import os
from traceback import format_exc
from apps.config.models import ConfigValue
import functions_general
"""
Handle the setting/retrieving of server config directives.
"""
def host_os_is(osname):
"""
Check to see if the host OS matches the query.
"""
if os.name == osname:
return True
return False
def get_configvalue(configname):
"""
Retrieve a configuration value.
"""
try:
return ConfigValue.objects.get(conf_key__iexact=configname).conf_value
except:
functions_general.log_errmsg("Unable to get config value for %s:\n%s" % (configname, (format_exc())))
def set_configvalue(configname, newvalue):
"""
Sets a configuration value with the specified name.
"""
conf = ConfigValue.objects.get(conf_key=configname)
conf.conf_value = newvalue
conf.save()

View file

@ -1,6 +1,6 @@
from django.contrib.auth.models import User, Group
from apps.objects.models import Object
import gameconf
from apps.config.models import ConfigValue
def handle_setup():
# Set the initial user's username on the #1 object.
@ -15,4 +15,4 @@ def handle_setup():
newgroup.save()
# We don't want to do initial setup tasks every startup, only the first.
gameconf.set_configvalue('game_firstrun', '0')
ConfigValue.objects.set_configvalue('game_firstrun', '0')

View file

@ -1,14 +1,14 @@
import os
from traceback import format_exc
import settings
import functions_general
"""
This module is responsible for managing scripts and their connection to the
Object class model. It is important to keep this as independent from the
codebase as possible in order to allow for drop-in replacements. All
interaction with actual script methods should happen via calls to Objects.
"""
import os
from traceback import format_exc
import settings
import functions_log
# A dictionary with keys equivalent to the script's name and values that
# contain references to the associated module for each key.
@ -48,16 +48,16 @@ def scriptlink(source_obj, scriptname):
try:
# Change the working directory to the location of the script and import.
os.chdir('%s/%s/' % (settings.SCRIPT_ROOT, newpath_str))
functions_general.log_infomsg("SCRIPT: Caching and importing %s." % (modname))
functions_log.log_infomsg("SCRIPT: Caching and importing %s." % (modname))
modreference = __import__(modname)
# Store the module reference for later fast retrieval.
cached_scripts[scriptname] = modreference
except ImportError:
functions_general.log_infomsg('Error importing %s: %s' % (modname, format_exc()))
functions_log.log_infomsg('Error importing %s: %s' % (modname, format_exc()))
os.chdir(settings.BASE_PATH)
return
except OSError:
functions_general.log_infomsg('Invalid module path: %s' % (format_exc()))
functions_log.log_infomsg('Invalid module path: %s' % (format_exc()))
os.chdir(settings.BASE_PATH)
return

View file

@ -7,15 +7,14 @@ from twisted.python import log
from django.db import models
from django.db import connection
from django.conf import settings
from apps.config.models import CommandAlias
from apps.config.models import CommandAlias, ConfigValue
from session import SessionProtocol
import settings
import scheduler
import functions_general
import session_mgr
import gameconf
import settings
import cmdtable
import initial_setup
@ -38,13 +37,13 @@ class EvenniaService(service.Service):
# Load command aliases into memory for easy/quick access.
self.load_cmd_aliases()
if gameconf.get_configvalue('game_firstrun') == '1':
if ConfigValue.objects.get_configvalue('game_firstrun') == '1':
print ' Game started for the first time, setting defaults.'
initial_setup.handle_setup()
self.start_time = time.time()
print ' %s started on port(s):' % (gameconf.get_configvalue('site_name'),)
print ' %s started on port(s):' % (ConfigValue.objects.get_configvalue('site_name'),)
for port in settings.GAMEPORTS:
print ' * %s' % (port)
print '-'*50
@ -96,11 +95,7 @@ class EvenniaService(service.Service):
For changes to the scheduler, server, or session_mgr modules, a cold
restart is needed.
"""
reload_list = ['ansi', 'cmdhandler', 'commands.comsys', 'commands.general',
'commands.privileged', 'commands.unloggedin', 'defines_global',
'events', 'functions_db', 'functions_general', 'functions_comsys',
'functions_help', 'gameconf', 'session', 'apps.objects.models',
'apps.helpsys.models', 'apps.config.models']
reload_list = []
for mod in reload_list:
reload(sys.modules[mod])

View file

@ -7,13 +7,13 @@ from twisted.conch.telnet import StatefulTelnetProtocol
from django.contrib.auth.models import User
from apps.objects.models import Object
from apps.config.models import ConnectScreen
from apps.config.models import ConnectScreen, ConfigValue
import cmdhandler
import functions_db
import functions_general
import functions_log
import session_mgr
import ansi
import gameconf
class SessionProtocol(StatefulTelnetProtocol):
"""
@ -26,7 +26,7 @@ class SessionProtocol(StatefulTelnetProtocol):
What to do when we get a connection.
"""
self.prep_session()
functions_general.log_infomsg('Connection: %s' % (self,))
functions_log.log_infomsg('Connection: %s' % (self,))
session_mgr.add_session(self)
self.game_connect_screen()
@ -63,7 +63,7 @@ class SessionProtocol(StatefulTelnetProtocol):
"""
Execute this when a client abruplty loses their connection.
"""
functions_general.log_infomsg('Disconnect: %s' % (self,))
functions_log.log_infomsg('Disconnect: %s' % (self,))
self.handle_close()
def load_user_channels(self):
@ -151,7 +151,7 @@ class SessionProtocol(StatefulTelnetProtocol):
self.msg("You are now logged in as %s." % (self.name,))
pobject.get_location().emit_to_contents("%s has connected." % (pobject.get_name(show_dbref=False),), exclude=pobject)
self.execute_cmd("look")
functions_general.log_infomsg("Login: %s" % (self,))
functions_log.log_infomsg("Login: %s" % (self,))
# Update their account's last login time.
user.last_login = datetime.now()

View file

@ -1,10 +1,12 @@
import time
import gameconf
import functions_general
"""
Session manager, handles connected players.
"""
import time
from apps.config.models import ConfigValue
import functions_general
import functions_log
# Our list of connected sessions.
session_list = []
@ -13,7 +15,7 @@ def add_session(session):
Adds a session to the session list.
"""
session_list.insert(0, session)
functions_general.log_infomsg('Sessions active: %d' % (len(get_session_list(return_unlogged=True),)))
functions_log.log_infomsg('Sessions active: %d' % (len(get_session_list(return_unlogged=True),)))
def get_session_list(return_unlogged=False):
"""
@ -50,7 +52,7 @@ def check_all_sessions():
"""
Check all currently connected sessions and see if any are dead.
"""
idle_timeout = int(gameconf.get_configvalue('idle_timeout'))
idle_timeout = int(ConfigValue.objects.get_configvalue('idle_timeout'))
if len(session_list) <= 0:
return
@ -69,9 +71,9 @@ def remove_session(session):
"""
try:
session_list.remove(session)
functions_general.log_infomsg('Sessions active: %d' % (len(get_session_list()),))
except:
#functions_general.log_errmsg("Unable to remove session: %s" % (session,))
functions_log.log_infomsg('Sessions active: %d' % (len(get_session_list()),))
except ValueError:
#functions_log.log_errmsg("Unable to remove session: %s" % (session,))
pass

View file

@ -11,6 +11,6 @@ mv -f $BASE_PATH/logs/evennia.log $BASE_PATH/logs/evennia.logs.old
## mode instead of having to uncomment crap.
## Interactive mode. Good for development and debugging.
#twistd -n --logfile=logs/evennia.log --python=server.py
twistd -n --logfile=logs/evennia.log --python=server.py
## Stand-alone mode. Good for running games.
twistd --logfile=logs/evennia.log --python=server.py
#twistd --logfile=logs/evennia.log --python=server.py