source: main/waeup.sirp/trunk/src/waeup/sirp/app.py @ 6372

Last change on this file since 6372 was 6362, checked in by uli, 14 years ago

Remove BBB imports.

  • Property svn:eol-style set to native
File size: 4.6 KB
Line 
1import grok
2import logging
3import os
4from zope.authentication.interfaces import IAuthentication
5from zope.component import createObject, getUtilitiesFor
6from zope.component.interfaces import ObjectEvent
7from zope.pluggableauth import PluggableAuthentication
8from waeup.sirp.authentication import setup_authentication
9from waeup.sirp.datacenter import DataCenter
10from waeup.sirp.interfaces import (
11    IUniversity, IDataCenter, IWAeUPSIRPPluggable,
12    IDataCenterStorageMovedEvent, IObjectUpgradeEvent, )
13from waeup.sirp.users import UserContainer
14from waeup.sirp.utils.helpers import attrs_to_fields
15
16class University(grok.Application, grok.Container):
17    """A university.
18    """
19    grok.implements(IUniversity)
20
21    # Setup authentication for this app. Note: this is only
22    # initialized, when a new instance of this app is created.
23    grok.local_utility(
24        PluggableAuthentication, provides = IAuthentication,
25        setup = setup_authentication,)
26
27    @property
28    def logger(self):
29        """The application logger.
30
31        Returns a standard logger object as provided by :mod:`logging`
32        module from the standard library.
33
34        Other components can use this logger to perform log entries
35        into the 'main' logfile.
36
37        The logger is initialized the first time, it is called.
38        """
39        sitename = self.__name__
40        loggername = 'waeup.sirp.%s' % sitename
41        logger = logging.getLogger(loggername)
42        if not logger.handlers:
43            logger = self._setupLogger(logger)
44        return logger
45
46    def __init__(self, name=None, skin=None, title=None,
47                 frontpage=None, **kw):
48        super(University, self).__init__(**kw)
49        if name is not None:
50            self.name = name
51        if skin is not None:
52            self.skin = skin
53        if title is not None:
54            self.title = title
55        if frontpage is not None:
56            self.frontpage = frontpage
57        self.setup()
58
59    def setup(self):
60        """Setup some hard-wired components.
61
62        Create local datacenter, containers for users, students and
63        the like.
64        """
65        self['users'] = UserContainer()
66        self['datacenter'] = DataCenter()
67
68        self['students'] = createObject(u'waeup.StudentContainer')
69        self['hostels'] = createObject(u'waeup.HostelContainer')
70        self._createPlugins()
71
72    def _createPlugins(self):
73        """Create instances of all plugins defined somewhere.
74        """
75        for name, plugin in getUtilitiesFor(IWAeUPSIRPPluggable):
76            plugin.setup(self, name, self.logger)
77        return
78
79    def updatePlugins(self):
80        """Lookup all plugins and call their `update()` method.
81        """
82        name = getattr(self, '__name__', '<Unnamed>')
83        self.logger.info('Fire upgrade event for site %s' % name)
84        grok.notify(ObjectUpgradeEvent(self))
85        self.logger.info('Done.')
86        self.logger.info('Now upgrading any plugins.')
87        for name, plugin in getUtilitiesFor(IWAeUPSIRPPluggable):
88            plugin.update(self, name, self.logger)
89        self.logger.info('Plugin update finished.')
90        return
91
92    def _setupLogger(self, logger):
93        """Setup general application logger.
94
95        The logfile will be stored in the datacenter logs/ dir.
96        """
97        logdir = os.path.join(self['datacenter'].storage, 'logs')
98        if not os.path.exists(logdir):
99            os.mkdir(logdir)
100        filename = os.path.join(logdir, 'main.log')
101
102        # Create a rotating file handler logger for application.
103        handler = logging.handlers.RotatingFileHandler(
104            filename, maxBytes=5*1024**1, backupCount=7)
105        formatter = logging.Formatter(
106            '%(asctime)s - %(levelname)s - %(message)s')
107        handler.setFormatter(formatter)
108
109        # Don't send log msgs to ancestors. This stops displaying
110        # logmessages on the commandline.
111        logger.propagate = False
112        logger.addHandler(handler)
113        return logger
114attrs_to_fields(University)
115
116@grok.subscribe(IDataCenter, IDataCenterStorageMovedEvent)
117def handle_storage_move(obj, event):
118    """Event handler, in case datacenter storage moves.
119
120    We initialize the application log again, then.
121    """
122    app = grok.getSite()
123    if app is None:
124        return
125    if obj is not app['datacenter']:
126        return
127    logger = app.logger
128    logger.warn('Log Dir moved. Closing.')
129    handlers = logger.handlers
130    for handler in handlers:
131        logger.removeHandler(handler)
132    app._setupLogger(logger)
133    logger.warn('Log file moved. Opening.')
134
135class ObjectUpgradeEvent(ObjectEvent):
136    """An event fired, when datacenter storage moves.
137    """
138    grok.implements(IObjectUpgradeEvent)
Note: See TracBrowser for help on using the repository browser.