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

Last change on this file since 6361 was 6361, checked in by uli, 13 years ago

Clean up app.

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