blob: 4691d9c541764c27f3b42c648a55a4f9e2e1d693 [file] [log] [blame]
Zsolt Haraszti656ecc62016-12-28 15:08:23 -08001#
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#
16import structlog
17from scapy.layers.l2 import Ether
18from scapy.packet import Packet
19from twisted.internet.defer import inlineCallbacks, returnValue
20
21from common.frameio.frameio import FrameIOManager, hexify
22
23log = structlog.get_logger()
24
25
26class RealIo(object):
27
28 def __init__(self, iface_map):
29 self.port_to_iface_name = iface_map
30 self.iface_name_to_port = dict((n, p) for p, n in iface_map.items())
31 self.frame_io = FrameIOManager()
32 self.ponsim = None
33 self.io_ports = dict()
34
35 @inlineCallbacks
36 def start(self):
37 log.debug('starting')
38 yield self.frame_io.start()
39 for port, iface_name in self.port_to_iface_name.items():
Zsolt Haraszti3e6f0892017-01-19 11:51:40 -080040 io_port = self.frame_io.open_port(iface_name, self.ingress)
Zsolt Haraszti656ecc62016-12-28 15:08:23 -080041 self.io_ports[port] = io_port
42 log.info('started')
43 returnValue(self)
44
Rouzbahan Rashidi-Tabrizic35866b2017-02-23 14:57:58 -050045 @inlineCallbacks
Zsolt Haraszti656ecc62016-12-28 15:08:23 -080046 def stop(self):
47 log.debug('stopping')
Rouzbahan Rashidi-Tabrizic35866b2017-02-23 14:57:58 -050048 try:
49 for port in self.io_ports.values():
50 yield self.frame_io.del_interface(port.iface_name)
51 yield self.frame_io.stop()
52 log.info('stopped')
53 except Exception, e:
Rouzbahan Rashidi-Tabrizi66aa41d2017-02-24 09:30:30 -050054 log.exception('exception', e=e)
Zsolt Haraszti656ecc62016-12-28 15:08:23 -080055
56 def register_ponsim(self, ponsim):
57 self.ponsim = ponsim
58
59 def ingress(self, io_port, frame):
60 port = self.iface_name_to_port.get(io_port.iface_name)
61 log.debug('ingress', port=port, iface_name=io_port.iface_name,
62 frame=hexify(frame))
63 decoded_frame = Ether(frame)
64 if self.ponsim is not None:
65 self.ponsim.ingress(port, decoded_frame)
66
67 def egress(self, port, frame):
68 if isinstance(frame, Packet):
69 frame = str(frame)
70 io_port = self.io_ports[port]
71 log.debug('sending', port=port, frame=hexify(frame))
72 io_port.send(frame)