4 # S.Çağlar Onur <caglar@cs.princeton.edu>
6 from PLC.Config import Config
7 from PLC.Faults import PLCPermissionDenied
9 from datetime import datetime, timedelta
11 from pyaspects.meta import MetaAspect
15 class BaseRateLimit(object):
18 self.config = Config("/etc/planetlab/plc_config")
20 # FIXME: change with Config values
21 self.prefix = "ratelimit"
22 self.minutes = 5 # The time period
23 self.requests = 50 # Number of allowed requests in that time period
24 self.expire_after = (self.minutes + 1) * 60
28 def before(self, wobj, data, *args, **kwargs):
29 # ratelimit_128.112.139.115_201011091532 = 1
30 # ratelimit_128.112.139.115_201011091533 = 14
31 # ratelimit_128.112.139.115_201011091534 = 11
32 # Now, on every request we work out the keys for the past five minutes and use get_multi to retrieve them.
33 # If the sum of those counters exceeds the maximum allowed for that time period, we block the request.
35 api_method_name = wobj.name
36 api_method_source = wobj.source
38 if api_method_source == None or api_method_source[0] == self.config.PLC_API_IP or api_method_source[0] in self.whitelist:
41 mc = memcache.Client(["%s:11211" % self.config.PLC_API_HOST])
43 current_key = "%s_%s_%s" % (self.prefix, api_method_source[0], now.strftime("%Y%m%d%H%M"))
45 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)]
48 value = mc.incr(current_key)
53 mc.set(current_key, 1, time=self.expire_after)
55 result = mc.get_multi(keys_to_check)
58 total_requests += result[i]
60 if total_requests > self.requests:
61 log = open("/var/log/plc_api_ratelimit.log", "a")
62 date = datetime.now().strftime("%d/%m/%y %H:%M")
63 log.write("%s - %s\n" % (date, api_method_source[0]))
65 raise PLCPermissionDenied, "Maximum allowed number of API calls exceeded"
67 def after(self, wobj, data, *args, **kwargs):
70 class RateLimitAspect_class(BaseRateLimit):
71 __metaclass__ = MetaAspect
72 name = "ratelimitaspect_class"
75 BaseRateLimit.__init__(self)
77 def before(self, wobj, data, *args, **kwargs):
78 BaseRateLimit.before(self, wobj, data, *args, **kwargs)
80 def after(self, wobj, data, *args, **kwargs):
81 BaseRateLimit.after(self, wobj, data, *args, **kwargs)
83 RateLimitAspect = RateLimitAspect_class