1 from PLC.Config import Config
2 from PLC.Faults import *
4 from datetime import datetime, timedelta
5 from pyaspects.meta import MetaAspect
8 class BaseRateLimit(object):
11 self.config = Config("/etc/planetlab/plc_config")
13 # FIXME: change with Config values
14 self.prefix = "ratelimit"
15 self.minutes = 5 # The time period
16 self.requests = 50 # Number of allowed requests in that time period
17 self.expire_after = (self.minutes + 1) * 60
19 def before(self, wobj, data, *args, **kwargs):
20 # ratelimit_128.112.139.115_201011091532 = 1
21 # ratelimit_128.112.139.115_201011091533 = 14
22 # ratelimit_128.112.139.115_201011091534 = 11
23 # Now, on every request we work out the keys for the past five minutes and use get_multi to retrieve them.
24 # If the sum of those counters exceeds the maximum allowed for that time period, we block the request.
26 api_method_name = wobj.name
27 api_method_source = wobj.source
29 if api_method_source == None or api_method_source[0] == self.config.PLC_API_IP:
32 mc = memcache.Client(["%s:11211" % self.config.PLC_API_HOST])
34 current_key = "%s_%s_%s" % (self.prefix, api_method_source[0], now.strftime("%Y%m%d%H%M"))
36 keys_to_check = ["%s_%s_%s" % (self.prefix, api_method_source[0], (now - timedelta(minutes = minute)).strftime("%Y%m%d%H%M")) for minute in range(self.minutes + 1)]
41 mc.set(current_key, 1, time=self.expire_after)
43 result = mc.get_multi(keys_to_check)
46 total_requests += result[i]
48 if total_requests > self.requests:
49 log = open("/var/log/api_ratelimit.log", "a")
50 date = datetime.now().strftime("%d/%m/%y %H:%M")
51 log.write("%s - %s\n" % (date, api_method_source[0]))
53 raise PLCPermissionDenied, "Maximum allowed number of API calls exceeded"
55 def after(self, wobj, data, *args, **kwargs):
58 class RateLimitAspect_class(BaseRateLimit):
59 __metaclass__ = MetaAspect
60 name = "ratelimitaspect_class"
63 BaseRateLimit.__init__(self)
65 def before(self, wobj, data, *args, **kwargs):
66 BaseRateLimit.before(self, wobj, data, *args, **kwargs)
68 def after(self, wobj, data, *args, **kwargs):
69 BaseRateLimit.after(self, wobj, data, *args, **kwargs)
71 RateLimitAspect = RateLimitAspect_class