a little nicer wrt pep8
[sfa.git] / sfa / util / sfatablesRuntime.py
1 # sfa should not depend on sfatables
2 # if the sfatables.runtime import fails, just define run_sfatables as identity
3
4 try:
5     from sfatables.runtime import SFATablesRules
6
7     def fetch_context(slice_hrn, user_hrn, contexts):
8         """
9         Returns the request context required by sfatables. At some point, this
10         mechanism should be changed to refer to "contexts", which is the
11         information that sfatables is requesting. But for now, we just return
12         the basic information needed in a dict.
13         """
14         base_context = {
15             'sfa': {'user': {'hrn': user_hrn}, 'slice': {'hrn': slice_hrn}}}
16         return base_context
17
18     def run_sfatables(chain, hrn, origin_hrn, rspec, context_callback=None):
19         """
20         Run the rspec through sfatables
21         @param chain Name of rule chain
22         @param hrn Object's hrn
23         @param origin_hrn Original caller's hrn
24         @param rspec Incoming rspec
25         @param context_callback Callback used to generate the request context  
26
27         @return rspec
28         """
29         if not context_callback:
30             context_callback = fetch_context
31
32         chain = chain.upper()
33         rules = SFATablesRules(chain)
34         if rules.sorted_rule_list:
35             contexts = rules.contexts
36             request_context = context_callback(hrn, origin_hrn, contexts)
37             rules.set_context(request_context)
38             newrspec = rules.apply(rspec)
39         else:
40             newrspec = rspec
41         return newrspec
42
43 except:
44
45     from sfa.util.sfalogging import logger
46
47     def run_sfatables(_, __, ___, rspec, ____=None):
48         logger.warning(
49             "Cannot import sfatables.runtime, please install package sfa-sfatables")
50         return rspec