source: products/vendor/Products.CacheSetup/current/Products/CacheSetup/enabler.py @ 3296

Last change on this file since 3296 was 3296, checked in by fenix, 13 years ago

Load Products.CacheSetup?-1.2.1 into vendor/Products.CacheSetup?/current.

  • Property svn:eol-style set to native
File size: 6.6 KB
Line 
1from zope.component import getSiteManager
2from Products.CMFCore.utils import getToolByName
3from Products.CMFCore import CachingPolicyManager
4from Products.CMFCore.interfaces import ICachingPolicyManager
5from Products.CacheSetup.config import PROJECT_NAME, GLOBALS, \
6     CACHE_TOOL_ID, PAGE_CACHE_MANAGER_ID, OFS_CACHE_ID, RR_CACHE_ID, CPM_ID
7
8try:
9    from Products.PageCacheManager import PageCacheManager
10except ImportError:
11    PageCacheManager = None
12try:
13    from Products.PolicyHTTPCacheManager import PolicyHTTPCacheManager
14except ImportError:
15    PolicyHTTPCacheManager = None
16from Products.StandardCacheManagers import RAMCacheManager, AcceleratedHTTPCacheManager
17from Products.CacheSetup.utils import base_hasattr
18
19try:
20    import five.localsitemanager
21    HAS_LSM = True
22except ImportError, err:
23    HAS_LSM = False
24
25def enableCacheFu(self, enabled):
26    portal = getToolByName(self, 'portal_url').getPortalObject()
27    if enabled:
28        installPageCacheManager(portal)
29        removeCachingPolicyManager(portal)
30        setupPolicyHTTPCaches(portal)
31        setupResourceRegistry(portal)
32    else:
33        removePageCacheManager(portal)
34        restoreCachingPolicyManager(portal)
35        restoreResourceRegistry(portal)
36        removePolicyHTTPCaches(portal)
37
38
39def installPageCacheManager(portal):
40    if PageCacheManager is None:
41        raise ValueError, 'Please add PageCacheManager to your Products directory'
42    id = PAGE_CACHE_MANAGER_ID
43    if not id in portal.objectIds():
44        PageCacheManager.manage_addPageCacheManager(portal, id)
45        pcm = getattr(portal, id)
46        pcm.setTitle('Page Cache Manager')
47
48def removePageCacheManager(portal):
49    id = PAGE_CACHE_MANAGER_ID
50    if hasattr(portal, id):
51        portal.manage_delObjects([id])
52
53
54def removeCachingPolicyManager(portal):
55    cpm = getattr(portal, CPM_ID, None)
56    if not cpm.__class__ == CachingPolicyManager.CachingPolicyManager:
57        return
58   
59    old_policies = []
60    if cpm:
61        for id, p in cpm.listPolicies():
62            # crude check for right version of CMF
63            if getattr(p, 'getSMaxAgeSecs', None):
64                old_policies.append(
65                    {'policy_id': id,
66                     'predicate': p.getPredicate(),
67                     'mtime_func': p.getMTimeFunc(),
68                     'max_age_secs': p.getMaxAgeSecs(),
69                     'no_cache': p.getNoCache(),
70                     'no_store': p.getNoStore(),
71                     'must_revalidate': p.getMustRevalidate(),
72                     'vary': p.getVary(),
73                     'etag_func': p.getETagFunc(),
74                     's_max_age_secs': p.getSMaxAgeSecs(),
75                     'proxy_revalidate': p.getProxyRevalidate(),
76                     'public': p.getPublic(),
77                     'private': p.getPrivate(),
78                     'no_transform': p.getNoTransform(),
79                     'enable_304s': p.getEnable304s(),
80                     'last_modified': p.getLastModified(),
81                     'pre_check': p.getPreCheck(),
82                     'post_check': p.getPostCheck(),
83                     })
84        portal.manage_delObjects([CPM_ID])
85    pcs = getattr(portal, CACHE_TOOL_ID)
86    pcs.old_policies = old_policies
87    portal.manage_addProduct['CacheSetup'].manage_addTool('CacheFu Caching Policy Manager')
88    # for Plone 3.0 we need to register this as a local utility
89    sm = getSiteManager(portal)
90    if HAS_LSM and getattr(sm, 'registerUtility', None) is not None:
91        sm.registerUtility(component=getattr(portal, CPM_ID), provided=ICachingPolicyManager)
92
93def restoreCachingPolicyManager(portal):
94    # for Plone 3.0 we need to unregister the cachefu cpm
95    sm = getSiteManager(portal)
96    if HAS_LSM and getattr(sm, 'unregisterUtility', None) is not None:
97        sm.unregisterUtility(component=getattr(portal, CPM_ID), provided=ICachingPolicyManager)
98   
99    # now let's restore the old cpm
100    portal.manage_delObjects([CPM_ID])
101    pcs = getattr(portal, CACHE_TOOL_ID, None)
102    if pcs:
103        old_policies = getattr(pcs, 'old_policies', [])
104    else:
105        old_policies = []
106    CachingPolicyManager.manage_addCachingPolicyManager(portal)
107    cpm = getattr(portal, CPM_ID)
108    for p in old_policies:
109        cpm.addPolicy(p['policy_id'], p['predicate'], p['mtime_func'], p['max_age_secs'],
110                      p['no_cache'], p['no_store'], p['must_revalidate'], p['vary'],
111                      p['etag_func'], None, p['s_max_age_secs'], p['proxy_revalidate'], 
112                      p['public'], p['private'], p['no_transform'], p['enable_304s'],
113                      p['last_modified'], p['pre_check'], p['post_check'])
114
115
116def setupResourceRegistry(portal):
117    ram_cache_id = RR_CACHE_ID
118    if not ram_cache_id in portal.objectIds():
119        RAMCacheManager.manage_addRAMCacheManager(portal, ram_cache_id)
120        cache = getattr(portal, ram_cache_id)
121        settings = cache.getSettings()
122        settings['max_age'] = 24*3600 # keep for up to 24 hours
123        settings['request_vars'] = ('URL',)
124        cache.manage_editProps('Cache for saved ResourceRegistry files', settings)
125    registries = ['portal_css','portal_javascripts','portal_kss']
126    for regId in registries:
127        reg = getToolByName(portal, regId, None)
128        if reg is not None and base_hasattr(reg, 'ZCacheable_setManagerId'):
129            reg.ZCacheable_setManagerId(ram_cache_id)
130            reg.ZCacheable_setEnabled(1)
131
132def restoreResourceRegistry(portal):
133    registries = ['portal_css','portal_javascripts','portal_kss']
134    for regId in registries:
135        reg = getToolByName(portal, regId, None)
136        if reg is not None and base_hasattr(reg, 'ZCacheable_setManagerId'):
137            reg.ZCacheable_setManagerId(None)
138            reg.ZCacheable_setEnabled(0)
139    ram_cache_id = RR_CACHE_ID
140    if hasattr(portal, ram_cache_id):
141        portal.manage_delObjects([ram_cache_id])
142
143
144def setupPolicyHTTPCaches(portal):
145    if PolicyHTTPCacheManager is None:
146        raise ValueError, 'Please add PolicyHTTPCacheManager to your Products directory'
147    meta_type = PolicyHTTPCacheManager.PolicyHTTPCacheManager.meta_type
148    for cache_id in ('HTTPCache', OFS_CACHE_ID):
149        if cache_id not in portal.objectIds(spec=meta_type):
150            if cache_id in portal.objectIds():
151                portal.manage_delObjects([cache_id])
152            PolicyHTTPCacheManager.manage_addPolicyHTTPCacheManager(portal, cache_id)
153
154def removePolicyHTTPCaches(portal):
155    for obj in ['HTTPCache', OFS_CACHE_ID]:
156        if hasattr(portal, obj):
157            portal.manage_delObjects([obj])
158    AcceleratedHTTPCacheManager.manage_addAcceleratedHTTPCacheManager(portal, 'HTTPCache')
159
160
161
162
163
Note: See TracBrowser for help on using the repository browser.