cosmetic
[plcapi.git] / aspects / ratelimitaspects.py
1 #!/usr/bin/python
2 #-*- coding: utf-8 -*-
3 #
4 # S.Çağlar Onur <caglar@cs.princeton.edu>
5
6 from PLC.Config import Config
7 from PLC.Faults import PLCPermissionDenied
8
9 from datetime import datetime, timedelta
10
11 from pyaspects.meta import MetaAspect
12
13 import memcache
14
15 class BaseRateLimit(object):
16
17     def __init__(self):
18         self.config = Config("/etc/planetlab/plc_config")
19
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
25
26     def before(self, wobj, data, *args, **kwargs):
27         # ratelimit_128.112.139.115_201011091532 = 1
28         # ratelimit_128.112.139.115_201011091533 = 14
29         # ratelimit_128.112.139.115_201011091534 = 11
30         # Now, on every request we work out the keys for the past five minutes and use get_multi to retrieve them. 
31         # If the sum of those counters exceeds the maximum allowed for that time period, we block the request.
32
33         api_method_name = wobj.name
34         api_method_source = wobj.source
35
36         if api_method_source == None or api_method_source[0] == self.config.PLC_API_IP:
37             return
38
39         mc = memcache.Client(["%s:11211" % self.config.PLC_API_HOST])
40         now = datetime.now()
41         current_key = "%s_%s_%s" % (self.prefix, api_method_source[0], now.strftime("%Y%m%d%H%M"))
42
43         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)]
44
45         try:
46             mc.incr(current_key)
47         except ValueError:
48             mc.set(current_key, 1, time=self.expire_after)
49
50         result = mc.get_multi(keys_to_check)
51         total_requests = 0
52         for i in result:
53             total_requests += result[i]
54
55         if total_requests > self.requests:
56             log = open("/var/log/plc_api_ratelimit.log", "a")
57             date = datetime.now().strftime("%d/%m/%y %H:%M")
58             log.write("%s - %s\n" % (date, api_method_source[0]))
59             log.flush()
60             raise PLCPermissionDenied, "Maximum allowed number of API calls exceeded"
61
62     def after(self, wobj, data, *args, **kwargs):
63         return
64
65 class RateLimitAspect_class(BaseRateLimit):
66     __metaclass__ = MetaAspect
67     name = "ratelimitaspect_class"
68
69     def __init__(self):
70         BaseRateLimit.__init__(self)
71
72     def before(self, wobj, data, *args, **kwargs):
73         BaseRateLimit.before(self, wobj, data, *args, **kwargs)
74
75     def after(self, wobj, data, *args, **kwargs):
76         BaseRateLimit.after(self, wobj, data, *args, **kwargs)
77
78 RateLimitAspect = RateLimitAspect_class