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

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

Embed image storage in universities.

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