Demo script enables waypoint now. Fixed original analytics script so that it can...
[affinity.git] / scripts / demo.py
1 #!/usr/local/bin/python
2
3 import httplib2
4 import json
5 import signal
6 import sys
7 import time
8
9 from threading import Thread
10
11 from affinity_control import AffinityControl
12 from subnet import SubnetControl
13 from stats import Stats
14
15 # If True, SIG_INT has been captured
16 global sigint
17 sigint = False
18
19 # Handle SIG_INT
20 def signal_handler(signal, frame):
21     global sigint
22     sigint = True
23
24 # Monitors statistics
25 class WaypointMonitor(Thread):
26
27     def __init__(self, monitor_type, **kwargs):
28         Thread.__init__(self)
29         self.stat = Stats(monitor_type, **kwargs)
30         self.stat_type = monitor_type
31         self.waypoint_address = None
32
33     def set_waypoint(self, waypoint_ip):
34         self.waypoint_address = waypoint_ip
35         print "Registered waypoint for %s.  Any large flows will be redirected to %s." % (self.stat, waypoint_ip)
36
37     def run(self):
38         global sigint
39         did_waypoint = False
40         while not sigint:
41             _, is_big = self.stat.refresh()
42             if is_big and not did_waypoint:
43                 print "Large flow detected"
44                 ac = AffinityControl()
45                 # First AG: Sources sending data into this subnet
46                 src_ag_name = "sources"
47                 src_ips = self.stat.get_incoming_hosts()
48                 ac.add_affinity_group(src_ag_name, ips=src_ips)
49                 # Second AG: This entity
50                 dst_ag_name = "client"
51                 if (self.stat_type == Stats.TYPE_PREFIX):
52                     ac.add_affinity_group(dst_ag_name, subnet=self.stat.subnet)
53                 elif (self.stat_type == Stats.TYPE_HOST):
54                     pass
55                 else:
56                     print "type", self.stat_type, "not supported for redirection"
57                 # AL: Between them
58                 link_name = "inflows"
59                 ac.add_affinity_link(link_name, src_ag_name, dst_ag_name)
60                 ac.add_waypoint(link_name, self.waypoint_address)
61                 ac.enable_waypoint(link_name)
62                 did_waypoint = True
63             time.sleep(1)
64
65 def main():
66
67     # Default subnet is required for the host tracker to work.
68     subnet_control = SubnetControl()
69     subnet_control.add_subnet("defaultSubnet", "10.0.0.254/8")
70
71     m = WaypointMonitor(Stats.TYPE_PREFIX, subnet="10.0.0.0/31")
72     m.set_waypoint("10.0.0.2")
73     m.start()
74
75     # Register signal-handler to catch SIG_INT
76     signal.signal(signal.SIGINT, signal_handler)
77     signal.pause()
78
79     # join() won't return until SIG_INT has been captured
80     m.join()
81
82 if __name__ == "__main__":
83     main()