blob: ab1b868484ac124e8366a6572ece8e816a52ed50 [file] [log] [blame]
Zsolt Haraszti023ea7c2016-10-16 19:30:34 -07001#
2# Copyright 2016 the original author or authors.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16
17import sys
18
19import structlog
20from twisted.internet import protocol
21from twisted.internet import reactor
22from twisted.internet.defer import Deferred, inlineCallbacks
23
24import loxi.of13 as of13
25from common.utils.asleep import asleep
26from of_connection import OpenFlowConnection
27from of_protocol_handler import OpenFlowProtocolHandler
28
29
30log = structlog.get_logger()
31
32
33class Agent(protocol.ClientFactory):
34
Zsolt Haraszticd22adc2016-10-25 00:13:06 -070035 def __init__(self,
36 controller_endpoint,
37 datapath_id,
38 device_id,
39 rpc_stub,
Zsolt Haraszti023ea7c2016-10-16 19:30:34 -070040 conn_retry_interval=1):
Zsolt Haraszticd22adc2016-10-25 00:13:06 -070041
Zsolt Haraszti023ea7c2016-10-16 19:30:34 -070042 self.controller_endpoint = controller_endpoint
43 self.datapath_id = datapath_id
Zsolt Haraszticd22adc2016-10-25 00:13:06 -070044 self.device_id = device_id
Zsolt Haraszti023ea7c2016-10-16 19:30:34 -070045 self.rpc_stub = rpc_stub
46 self.retry_interval = conn_retry_interval
47
48 self.running = False
49 self.connector = None # will be a Connector instance once connected
50 self.d_disconnected = None # a deferred to signal reconnect loop when
51 # TCP connection is lost
52 self.connected = False
53 self.exiting = False
54
Zsolt Haraszticd22adc2016-10-25 00:13:06 -070055 def get_device_id(self):
56 return self.device_id
57
Zsolt Haraszti023ea7c2016-10-16 19:30:34 -070058 def run(self):
59 if self.running:
60 return
61 self.running = True
62 reactor.callLater(0, self.keep_connected)
63 return self
64
65 def resolve_endpoint(self, endpoint):
66 # TODO allow resolution via consul
67 host, port = endpoint.split(':', 2)
68 return host, int(port)
69
70 @inlineCallbacks
71 def keep_connected(self):
72 """Keep reconnecting to the controller"""
73 while not self.exiting:
74 host, port = self.resolve_endpoint(self.controller_endpoint)
75 log.info('connecting', host=host, port=port)
76 self.connector = reactor.connectTCP(host, port, self)
77 self.d_disconnected = Deferred()
78 yield self.d_disconnected
79 log.debug('reconnect', after_delay=self.retry_interval)
80 yield asleep(self.retry_interval)
81
82 def stop(self):
83 self.connected = False
84 self.exiting = True
85 self.connector.disconnect()
86 log.info('stopped')
87
88 def enter_disconnected(self, event, reason):
89 """Internally signal entering disconnected state"""
90 log.error(event, reason=reason)
91 self.connected = False
92 self.d_disconnected.callback(None)
93
94 def enter_connected(self):
95 """Handle transitioning from disconnected to connected state"""
96 log.info('connected')
97 self.connected = True
98 self.read_buffer = None
99 reactor.callLater(0, self.proto_handler.run)
100
101 # protocol.ClientFactory methods
102
103 def protocol(self):
104 cxn = OpenFlowConnection(self) # Low level message handler
105 self.proto_handler = OpenFlowProtocolHandler(
Zsolt Haraszticd22adc2016-10-25 00:13:06 -0700106 self.datapath_id, self.device_id, self, cxn, self.rpc_stub)
Zsolt Haraszti023ea7c2016-10-16 19:30:34 -0700107 return cxn
108
109 def clientConnectionFailed(self, connector, reason):
110 self.enter_disconnected('connection-failed', reason)
111
112 def clientConnectionLost(self, connector, reason):
113 log.error('client-connection-lost',
114 reason=reason, connector=connector)
115
Zsolt Haraszticd22adc2016-10-25 00:13:06 -0700116 def forward_packet_in(self, ofp_packet_in):
117 self.proto_handler.forward_packet_in(ofp_packet_in)
118
Zsolt Haraszti023ea7c2016-10-16 19:30:34 -0700119
120if __name__ == '__main__':
121 """Run this to test the agent for N concurrent sessions:
122 python agent [<number-of-desired-instances>]
123 """
124
125 n = 1 if len(sys.argv) < 2 else int(sys.argv[1])
126
127 from utils import mac_str_to_tuple
128
129 class MockRpc(object):
130 @staticmethod
131 def get_port_list(_):
132 ports = []
133 cap = of13.OFPPF_1GB_FD | of13.OFPPF_FIBER
134 for pno, mac, nam, cur, adv, sup, spe in (
135 (1, '00:00:00:00:00:01', 'onu1', cap, cap, cap,
136 of13.OFPPF_1GB_FD),
137 (2, '00:00:00:00:00:02', 'onu2', cap, cap, cap,
138 of13.OFPPF_1GB_FD),
139 (129, '00:00:00:00:00:81', 'olt', cap, cap, cap,
140 of13.OFPPF_1GB_FD)
141 ):
142 port = of13.common.port_desc(pno, mac_str_to_tuple(mac), nam,
143 curr=cur, advertised=adv,
144 supported=sup,
145 curr_speed=spe, max_speed=spe)
146 ports.append(port)
147 return ports
148
149 stub = MockRpc()
150 agents = [Agent('localhost:6633', 256 + i, stub).run() for i in range(n)]
151
152 def shutdown():
153 [a.stop() for a in agents]
154
155 reactor.addSystemEventTrigger('before', 'shutdown', shutdown)
156 reactor.run()
157