backing up
[vsorcdistro/.git] / ryu / build / lib.linux-armv7l-2.7 / ryu / app / ws_topology.py
1 # Copyright (C) 2014 Stratosphere Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #    http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12 # implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 """
17 Usage example
18
19 1. Run this application:
20 $ ryu-manager --verbose --observe-links ryu.app.ws_topology
21
22 2. Connect to this application by WebSocket (use your favorite client):
23 $ wscat -c ws://localhost:8080/v1.0/topology/ws
24
25 3. Join switches (use your favorite method):
26 $ sudo mn --controller=remote --topo linear,2
27
28 4. Topology change is notified:
29 < {"params": [{"ports": [{"hw_addr": "56:c7:08:12:bb:36", "name": "s1-eth1", "port_no": "00000001", "dpid": "0000000000000001"}, {"hw_addr": "de:b9:49:24:74:3f", "name": "s1-eth2", "port_no": "00000002", "dpid": "0000000000000001"}], "dpid": "0000000000000001"}], "jsonrpc": "2.0", "method": "event_switch_enter", "id": 1}
30 > {"id": 1, "jsonrpc": "2.0", "result": ""}
31
32 < {"params": [{"ports": [{"hw_addr": "56:c7:08:12:bb:36", "name": "s1-eth1", "port_no": "00000001", "dpid": "0000000000000001"}, {"hw_addr": "de:b9:49:24:74:3f", "name": "s1-eth2", "port_no": "00000002", "dpid": "0000000000000001"}], "dpid": "0000000000000001"}], "jsonrpc": "2.0", "method": "event_switch_leave", "id": 2}
33 > {"id": 2, "jsonrpc": "2.0", "result": ""}
34 ...
35 """  # noqa
36
37 from socket import error as SocketError
38 from tinyrpc.exc import InvalidReplyError
39
40
41 from ryu.app.wsgi import (
42     ControllerBase,
43     WSGIApplication,
44     websocket,
45     WebSocketRPCClient
46 )
47 from ryu.base import app_manager
48 from ryu.topology import event, switches
49 from ryu.controller.handler import set_ev_cls
50
51
52 class WebSocketTopology(app_manager.RyuApp):
53     _CONTEXTS = {
54         'wsgi': WSGIApplication,
55         'switches': switches.Switches,
56     }
57
58     def __init__(self, *args, **kwargs):
59         super(WebSocketTopology, self).__init__(*args, **kwargs)
60
61         self.rpc_clients = []
62
63         wsgi = kwargs['wsgi']
64         wsgi.register(WebSocketTopologyController, {'app': self})
65
66     @set_ev_cls(event.EventSwitchEnter)
67     def _event_switch_enter_handler(self, ev):
68         msg = ev.switch.to_dict()
69         self._rpc_broadcall('event_switch_enter', msg)
70
71     @set_ev_cls(event.EventSwitchLeave)
72     def _event_switch_leave_handler(self, ev):
73         msg = ev.switch.to_dict()
74         self._rpc_broadcall('event_switch_leave', msg)
75
76     @set_ev_cls(event.EventLinkAdd)
77     def _event_link_add_handler(self, ev):
78         msg = ev.link.to_dict()
79         self._rpc_broadcall('event_link_add', msg)
80
81     @set_ev_cls(event.EventLinkDelete)
82     def _event_link_delete_handler(self, ev):
83         msg = ev.link.to_dict()
84         self._rpc_broadcall('event_link_delete', msg)
85
86     @set_ev_cls(event.EventHostAdd)
87     def _event_host_add_handler(self, ev):
88         msg = ev.host.to_dict()
89         self._rpc_broadcall('event_host_add', msg)
90
91     def _rpc_broadcall(self, func_name, msg):
92         disconnected_clients = []
93         for rpc_client in self.rpc_clients:
94             # NOTE: Although broadcasting is desired,
95             #       RPCClient#get_proxy(one_way=True) does not work well
96             rpc_server = rpc_client.get_proxy()
97             try:
98                 getattr(rpc_server, func_name)(msg)
99             except SocketError:
100                 self.logger.debug('WebSocket disconnected: %s', rpc_client.ws)
101                 disconnected_clients.append(rpc_client)
102             except InvalidReplyError as e:
103                 self.logger.error(e)
104
105         for client in disconnected_clients:
106             self.rpc_clients.remove(client)
107
108
109 class WebSocketTopologyController(ControllerBase):
110
111     def __init__(self, req, link, data, **config):
112         super(WebSocketTopologyController, self).__init__(
113             req, link, data, **config)
114         self.app = data['app']
115
116     @websocket('topology', '/v1.0/topology/ws')
117     def _websocket_handler(self, ws):
118         rpc_client = WebSocketRPCClient(ws)
119         self.app.rpc_clients.append(rpc_client)
120         rpc_client.serve_forever()