blob: 974a71ce944da7f76836329873f5cb5775278ae0 [file] [log] [blame]
Thomas Vachuska781d18b2014-10-27 10:31:25 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
Thomas Vachuska781d18b2014-10-27 10:31:25 -07003 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07004 * 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
Thomas Vachuska781d18b2014-10-27 10:31:25 -07007 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07008 * 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.
Thomas Vachuska781d18b2014-10-27 10:31:25 -070015 */
Brian O'Connorabafb502014-12-02 22:26:20 -080016package org.onosproject.openflow.controller.impl;
tom7ef8ff92014-09-17 13:08:06 -070017
Thomas Vachuska6f94ded2015-02-21 14:02:38 -080018import com.google.common.collect.ArrayListMultimap;
Yuta HIGUCHI7b41dc92017-06-22 19:37:06 -070019import com.google.common.collect.ImmutableList;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -080020import com.google.common.collect.Multimap;
tom7ef8ff92014-09-17 13:08:06 -070021import org.apache.felix.scr.annotations.Activate;
22import org.apache.felix.scr.annotations.Component;
23import org.apache.felix.scr.annotations.Deactivate;
Jonathan Hartbbd91d42015-02-27 11:18:04 -080024import org.apache.felix.scr.annotations.Modified;
Charles Chan3b00e1b2015-08-26 23:12:52 +080025import org.apache.felix.scr.annotations.Property;
alshabibb452fd72015-04-22 20:46:20 -070026import org.apache.felix.scr.annotations.Reference;
27import org.apache.felix.scr.annotations.ReferenceCardinality;
tom7ef8ff92014-09-17 13:08:06 -070028import org.apache.felix.scr.annotations.Service;
Charles Chan3b00e1b2015-08-26 23:12:52 +080029import org.onosproject.cfg.ComponentConfigService;
Charles Chanecfdfb72015-11-24 19:05:50 -080030import org.onosproject.core.CoreService;
Yuta HIGUCHIcedd0df2016-08-23 11:44:13 -070031import org.onosproject.net.device.DeviceEvent;
Yuta HIGUCHIcedd0df2016-08-23 11:44:13 -070032import org.onosproject.net.device.DeviceListener;
33import org.onosproject.net.device.DeviceService;
alshabibb452fd72015-04-22 20:46:20 -070034import org.onosproject.net.driver.DriverService;
Brian O'Connorabafb502014-12-02 22:26:20 -080035import org.onosproject.openflow.controller.DefaultOpenFlowPacketContext;
36import org.onosproject.openflow.controller.Dpid;
37import org.onosproject.openflow.controller.OpenFlowController;
38import org.onosproject.openflow.controller.OpenFlowEventListener;
Jian Lia78cdb22016-04-21 13:03:58 -070039import org.onosproject.openflow.controller.OpenFlowMessageListener;
Brian O'Connorabafb502014-12-02 22:26:20 -080040import org.onosproject.openflow.controller.OpenFlowPacketContext;
41import org.onosproject.openflow.controller.OpenFlowSwitch;
42import org.onosproject.openflow.controller.OpenFlowSwitchListener;
43import org.onosproject.openflow.controller.PacketListener;
44import org.onosproject.openflow.controller.RoleState;
45import org.onosproject.openflow.controller.driver.OpenFlowAgent;
Jonathan Hartbbd91d42015-02-27 11:18:04 -080046import org.osgi.service.component.ComponentContext;
Marc De Leenheerb9311372015-07-09 11:36:49 -070047import org.projectfloodlight.openflow.protocol.OFCalientFlowStatsEntry;
48import org.projectfloodlight.openflow.protocol.OFCalientFlowStatsReply;
Marc De Leenheer631ffce2014-10-28 16:29:07 -070049import org.projectfloodlight.openflow.protocol.OFCircuitPortStatus;
50import org.projectfloodlight.openflow.protocol.OFExperimenter;
alshabib64def642014-12-02 23:27:37 -080051import org.projectfloodlight.openflow.protocol.OFFactories;
Cem Türker3baff672017-10-12 15:09:01 +030052import org.projectfloodlight.openflow.protocol.OFFlowLightweightStatsEntry;
53import org.projectfloodlight.openflow.protocol.OFFlowLightweightStatsReply;
alshabib64def642014-12-02 23:27:37 -080054import org.projectfloodlight.openflow.protocol.OFFlowStatsEntry;
55import org.projectfloodlight.openflow.protocol.OFFlowStatsReply;
sangho6a0bb172015-02-05 12:24:48 -080056import org.projectfloodlight.openflow.protocol.OFGroupDescStatsEntry;
57import org.projectfloodlight.openflow.protocol.OFGroupDescStatsReply;
58import org.projectfloodlight.openflow.protocol.OFGroupStatsEntry;
59import org.projectfloodlight.openflow.protocol.OFGroupStatsReply;
tom7ef8ff92014-09-17 13:08:06 -070060import org.projectfloodlight.openflow.protocol.OFMessage;
61import org.projectfloodlight.openflow.protocol.OFPacketIn;
Marc De Leenheer631ffce2014-10-28 16:29:07 -070062import org.projectfloodlight.openflow.protocol.OFPortDesc;
sangho538108b2015-04-08 14:29:20 -070063import org.projectfloodlight.openflow.protocol.OFPortStatsEntry;
tom7ef8ff92014-09-17 13:08:06 -070064import org.projectfloodlight.openflow.protocol.OFPortStatus;
Cem Türker3baff672017-10-12 15:09:01 +030065import org.projectfloodlight.openflow.protocol.OFQueueStatsEntry;
66import org.projectfloodlight.openflow.protocol.OFQueueStatsReply;
Ayaka Koshibe38594c22014-10-22 13:36:12 -070067import org.projectfloodlight.openflow.protocol.OFStatsReply;
alshabib64def642014-12-02 23:27:37 -080068import org.projectfloodlight.openflow.protocol.OFStatsReplyFlags;
Jian Li2266bff2016-04-21 11:01:25 -070069import org.projectfloodlight.openflow.protocol.OFTableStatsEntry;
70import org.projectfloodlight.openflow.protocol.OFTableStatsReply;
Marc De Leenheerb9311372015-07-09 11:36:49 -070071import org.projectfloodlight.openflow.protocol.action.OFActionOutput;
72import org.projectfloodlight.openflow.protocol.instruction.OFInstruction;
tom7ef8ff92014-09-17 13:08:06 -070073import org.slf4j.Logger;
74import org.slf4j.LoggerFactory;
75
Yuta HIGUCHI7b41dc92017-06-22 19:37:06 -070076import java.util.ArrayList;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -080077import java.util.Collection;
Marc De Leenheerb9311372015-07-09 11:36:49 -070078import java.util.Collections;
Marc De Leenheerb9311372015-07-09 11:36:49 -070079import java.util.List;
Yuta HIGUCHIcedd0df2016-08-23 11:44:13 -070080import java.util.Optional;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -080081import java.util.Set;
Marc De Leenheer8aba62f2017-04-25 14:33:37 -070082import java.util.concurrent.CompletableFuture;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -080083import java.util.concurrent.ConcurrentHashMap;
HIGUCHI Yuta1979f552015-12-28 21:24:26 -080084import java.util.concurrent.ConcurrentMap;
Jonathan Hart6d44d192015-05-11 18:01:19 -070085import java.util.concurrent.CopyOnWriteArraySet;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -080086import java.util.concurrent.ExecutorService;
87import java.util.concurrent.Executors;
88import java.util.concurrent.locks.Lock;
89import java.util.concurrent.locks.ReentrantLock;
Jian Li2266bff2016-04-21 11:01:25 -070090
Thomas Vachuska6f94ded2015-02-21 14:02:38 -080091import static org.onlab.util.Tools.groupedThreads;
Hyunsun Moone71494d2016-11-15 14:45:25 -080092import static org.onosproject.net.Device.Type.CONTROLLER;
93import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_REMOVED;
Yuta HIGUCHIcedd0df2016-08-23 11:44:13 -070094import static org.onosproject.openflow.controller.Dpid.dpid;
Ozge AYAZ60aded22017-06-20 08:35:30 +000095
tom7ef8ff92014-09-17 13:08:06 -070096
97@Component(immediate = true)
98@Service
99public class OpenFlowControllerImpl implements OpenFlowController {
Charles Chanecfdfb72015-11-24 19:05:50 -0800100 private static final String APP_ID = "org.onosproject.openflow-base";
Brian O'Connorff278502015-09-22 14:49:52 -0700101 private static final String DEFAULT_OFPORT = "6633,6653";
Yuta HIGUCHI8552b172016-07-25 12:10:08 -0700102 private static final int DEFAULT_WORKER_THREADS = 0;
Andrea Campanella86e0c562017-11-23 16:38:24 +0100103 protected static final String SCHEME = "of";
tom7ef8ff92014-09-17 13:08:06 -0700104
105 private static final Logger log =
106 LoggerFactory.getLogger(OpenFlowControllerImpl.class);
107
alshabibb452fd72015-04-22 20:46:20 -0700108 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chanecfdfb72015-11-24 19:05:50 -0800109 protected CoreService coreService;
110
111 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
alshabibb452fd72015-04-22 20:46:20 -0700112 protected DriverService driverService;
113
Charles Chan3b00e1b2015-08-26 23:12:52 +0800114 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
115 protected ComponentConfigService cfgService;
116
Yuta HIGUCHIcedd0df2016-08-23 11:44:13 -0700117 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
118 protected DeviceService deviceService;
119
120
Brian O'Connore2a399e2015-09-22 15:32:50 -0700121 @Property(name = "openflowPorts", value = DEFAULT_OFPORT,
122 label = "Port numbers (comma separated) used by OpenFlow protocol; default is 6633,6653")
123 private String openflowPorts = DEFAULT_OFPORT;
Charles Chan3b00e1b2015-08-26 23:12:52 +0800124
125 @Property(name = "workerThreads", intValue = DEFAULT_WORKER_THREADS,
Yuta HIGUCHI8552b172016-07-25 12:10:08 -0700126 label = "Number of controller worker threads")
Charles Chan3b00e1b2015-08-26 23:12:52 +0800127 private int workerThreads = DEFAULT_WORKER_THREADS;
128
Ray Milkey7ec0d1b2015-11-13 08:51:35 -0800129 protected ExecutorService executorMsgs =
Andrea Campanelladda93562016-03-02 11:08:12 -0800130 Executors.newFixedThreadPool(32, groupedThreads("onos/of", "event-stats-%d", log));
Pavlin Radoslavov369c6432014-12-03 16:25:14 -0800131
132 private final ExecutorService executorBarrier =
Andrea Campanelladda93562016-03-02 11:08:12 -0800133 Executors.newFixedThreadPool(4, groupedThreads("onos/of", "event-barrier-%d", log));
alshabib8f1cf4a2014-09-17 14:44:48 -0700134
Prince Pereirae7798032016-07-08 16:31:58 +0530135 //Separate executor thread for handling error messages and barrier replies for same failed
136 // transactions to avoid context switching of thread
137 protected ExecutorService executorErrorMsgs =
138 Executors.newSingleThreadExecutor(groupedThreads("onos/of", "event-error-msg-%d", log));
139
140 //concurrent hashmap to track failed transactions
141 protected ConcurrentMap<Long, Boolean> errorMsgs =
142 new ConcurrentHashMap<>();
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800143 protected ConcurrentMap<Dpid, OpenFlowSwitch> connectedSwitches =
Jonathan Hart6d44d192015-05-11 18:01:19 -0700144 new ConcurrentHashMap<>();
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800145 protected ConcurrentMap<Dpid, OpenFlowSwitch> activeMasterSwitches =
Jonathan Hart6d44d192015-05-11 18:01:19 -0700146 new ConcurrentHashMap<>();
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800147 protected ConcurrentMap<Dpid, OpenFlowSwitch> activeEqualSwitches =
Jonathan Hart6d44d192015-05-11 18:01:19 -0700148 new ConcurrentHashMap<>();
tom7ef8ff92014-09-17 13:08:06 -0700149
Marc De Leenheer8aba62f2017-04-25 14:33:37 -0700150 // Key: dpid, value: map with key: long (XID), value: completable future
151 protected ConcurrentMap<Dpid, ConcurrentMap<Long, CompletableFuture<OFMessage>>> responses =
152 new ConcurrentHashMap<>();
153
tom7ef8ff92014-09-17 13:08:06 -0700154 protected OpenFlowSwitchAgent agent = new OpenFlowSwitchAgent();
Jonathan Hart6d44d192015-05-11 18:01:19 -0700155 protected Set<OpenFlowSwitchListener> ofSwitchListener = new CopyOnWriteArraySet<>();
tom7ef8ff92014-09-17 13:08:06 -0700156
157 protected Multimap<Integer, PacketListener> ofPacketListener =
158 ArrayListMultimap.create();
159
Jonathan Hart6d44d192015-05-11 18:01:19 -0700160 protected Set<OpenFlowEventListener> ofEventListener = new CopyOnWriteArraySet<>();
tom7ef8ff92014-09-17 13:08:06 -0700161
Jian Lia78cdb22016-04-21 13:03:58 -0700162 protected Set<OpenFlowMessageListener> ofMessageListener = new CopyOnWriteArraySet<>();
Jian Li28247b52016-01-07 17:24:15 -0800163
sangho6a0bb172015-02-05 12:24:48 -0800164 protected Multimap<Dpid, OFFlowStatsEntry> fullFlowStats =
165 ArrayListMultimap.create();
166
Cem Türker3baff672017-10-12 15:09:01 +0300167 protected Multimap<Dpid, OFFlowLightweightStatsEntry> fullFlowLightweightStats =
168 ArrayListMultimap.create();
169
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700170 protected Multimap<Dpid, OFTableStatsEntry> fullTableStats =
171 ArrayListMultimap.create();
172
sangho6a0bb172015-02-05 12:24:48 -0800173 protected Multimap<Dpid, OFGroupStatsEntry> fullGroupStats =
174 ArrayListMultimap.create();
175
176 protected Multimap<Dpid, OFGroupDescStatsEntry> fullGroupDescStats =
alshabib64def642014-12-02 23:27:37 -0800177 ArrayListMultimap.create();
178
Yuta HIGUCHI7b41dc92017-06-22 19:37:06 -0700179 // deprecated in 1.11.0, no longer referenced from anywhere
180 @Deprecated
sangho538108b2015-04-08 14:29:20 -0700181 protected Multimap<Dpid, OFPortStatsEntry> fullPortStats =
182 ArrayListMultimap.create();
183
Ozge AYAZ60aded22017-06-20 08:35:30 +0000184 protected Multimap<Dpid, OFQueueStatsEntry> fullQueueStats =
185 ArrayListMultimap.create();
186
tom7ef8ff92014-09-17 13:08:06 -0700187 private final Controller ctrl = new Controller();
Yuta HIGUCHIcedd0df2016-08-23 11:44:13 -0700188 private InternalDeviceListener listener = new InternalDeviceListener();
tom7ef8ff92014-09-17 13:08:06 -0700189
190 @Activate
Jonathan Hartbbd91d42015-02-27 11:18:04 -0800191 public void activate(ComponentContext context) {
Andrea Campanella3556f362016-04-28 15:18:10 -0700192 coreService.registerApplication(APP_ID, this::cleanup);
Charles Chan3b00e1b2015-08-26 23:12:52 +0800193 cfgService.registerProperties(getClass());
Yuta HIGUCHIcedd0df2016-08-23 11:44:13 -0700194 deviceService.addListener(listener);
Brian O'Connorff278502015-09-22 14:49:52 -0700195 ctrl.setConfigParams(context.getProperties());
alshabibb452fd72015-04-22 20:46:20 -0700196 ctrl.start(agent, driverService);
tom7ef8ff92014-09-17 13:08:06 -0700197 }
198
Andrea Campanella3556f362016-04-28 15:18:10 -0700199 private void cleanup() {
200 // Close listening channel and all OF channels. Clean information about switches
201 // before deactivating
Charles Chanecfdfb72015-11-24 19:05:50 -0800202 ctrl.stop();
203 connectedSwitches.values().forEach(OpenFlowSwitch::disconnectSwitch);
Andrea Campanella3556f362016-04-28 15:18:10 -0700204 connectedSwitches.clear();
205 activeMasterSwitches.clear();
206 activeEqualSwitches.clear();
Charles Chanecfdfb72015-11-24 19:05:50 -0800207 }
208
tom7ef8ff92014-09-17 13:08:06 -0700209 @Deactivate
210 public void deactivate() {
Yuta HIGUCHIcedd0df2016-08-23 11:44:13 -0700211 deviceService.removeListener(listener);
Thiago Santos61725402016-08-05 17:58:56 -0300212 cleanup();
Charles Chan3b00e1b2015-08-26 23:12:52 +0800213 cfgService.unregisterProperties(getClass(), false);
tom7ef8ff92014-09-17 13:08:06 -0700214 }
215
Jonathan Hartbbd91d42015-02-27 11:18:04 -0800216 @Modified
217 public void modified(ComponentContext context) {
Charles Chan3b00e1b2015-08-26 23:12:52 +0800218 ctrl.stop();
Brian O'Connorff278502015-09-22 14:49:52 -0700219 ctrl.setConfigParams(context.getProperties());
Charles Chan3b00e1b2015-08-26 23:12:52 +0800220 ctrl.start(agent, driverService);
Jonathan Hartbbd91d42015-02-27 11:18:04 -0800221 }
222
tom7ef8ff92014-09-17 13:08:06 -0700223 @Override
224 public Iterable<OpenFlowSwitch> getSwitches() {
225 return connectedSwitches.values();
226 }
227
228 @Override
229 public Iterable<OpenFlowSwitch> getMasterSwitches() {
230 return activeMasterSwitches.values();
231 }
232
233 @Override
234 public Iterable<OpenFlowSwitch> getEqualSwitches() {
235 return activeEqualSwitches.values();
236 }
237
238 @Override
239 public OpenFlowSwitch getSwitch(Dpid dpid) {
240 return connectedSwitches.get(dpid);
241 }
242
243 @Override
244 public OpenFlowSwitch getMasterSwitch(Dpid dpid) {
245 return activeMasterSwitches.get(dpid);
246 }
247
248 @Override
249 public OpenFlowSwitch getEqualSwitch(Dpid dpid) {
250 return activeEqualSwitches.get(dpid);
251 }
252
253 @Override
254 public void addListener(OpenFlowSwitchListener listener) {
alshabib8f1cf4a2014-09-17 14:44:48 -0700255 if (!ofSwitchListener.contains(listener)) {
256 this.ofSwitchListener.add(listener);
tom7ef8ff92014-09-17 13:08:06 -0700257 }
258 }
259
260 @Override
261 public void removeListener(OpenFlowSwitchListener listener) {
alshabib8f1cf4a2014-09-17 14:44:48 -0700262 this.ofSwitchListener.remove(listener);
tom7ef8ff92014-09-17 13:08:06 -0700263 }
264
265 @Override
Jian Lia78cdb22016-04-21 13:03:58 -0700266 public void addMessageListener(OpenFlowMessageListener listener) {
267 ofMessageListener.add(listener);
268 }
269
270 @Override
271 public void removeMessageListener(OpenFlowMessageListener listener) {
272 ofMessageListener.remove(listener);
273 }
274
275 @Override
tom7ef8ff92014-09-17 13:08:06 -0700276 public void addPacketListener(int priority, PacketListener listener) {
277 ofPacketListener.put(priority, listener);
278 }
279
280 @Override
281 public void removePacketListener(PacketListener listener) {
282 ofPacketListener.values().remove(listener);
283 }
284
285 @Override
alshabibeec3a062014-09-17 18:01:26 -0700286 public void addEventListener(OpenFlowEventListener listener) {
287 ofEventListener.add(listener);
288 }
289
290 @Override
291 public void removeEventListener(OpenFlowEventListener listener) {
292 ofEventListener.remove(listener);
293 }
294
295 @Override
tom7ef8ff92014-09-17 13:08:06 -0700296 public void write(Dpid dpid, OFMessage msg) {
297 this.getSwitch(dpid).sendMsg(msg);
298 }
299
300 @Override
Marc De Leenheer8aba62f2017-04-25 14:33:37 -0700301 public CompletableFuture<OFMessage> writeResponse(Dpid dpid, OFMessage msg) {
302 write(dpid, msg);
303
304 ConcurrentMap<Long, CompletableFuture<OFMessage>> xids =
Yuta HIGUCHI6ee6b8c2017-05-09 14:44:30 -0700305 responses.computeIfAbsent(dpid, k -> new ConcurrentHashMap<>());
Marc De Leenheer8aba62f2017-04-25 14:33:37 -0700306
Yuta HIGUCHI6ee6b8c2017-05-09 14:44:30 -0700307 CompletableFuture<OFMessage> future = new CompletableFuture<>();
Marc De Leenheer8aba62f2017-04-25 14:33:37 -0700308 xids.put(msg.getXid(), future);
309
310 return future;
311 }
312
313 @Override
tom7ef8ff92014-09-17 13:08:06 -0700314 public void processPacket(Dpid dpid, OFMessage msg) {
sangyun-han69ed4462016-07-27 12:10:12 +0900315 OpenFlowSwitch sw = this.getSwitch(dpid);
316
Marc De Leenheer8aba62f2017-04-25 14:33:37 -0700317 // Check if someone is waiting for this message
318 ConcurrentMap<Long, CompletableFuture<OFMessage>> xids = responses.get(dpid);
Yuta HIGUCHI6ee6b8c2017-05-09 14:44:30 -0700319 if (xids != null) {
320 CompletableFuture<OFMessage> future = xids.remove(msg.getXid());
321 if (future != null) {
322 future.complete(msg);
323 }
Marc De Leenheer8aba62f2017-04-25 14:33:37 -0700324 }
325
tom7ef8ff92014-09-17 13:08:06 -0700326 switch (msg.getType()) {
327 case PORT_STATUS:
alshabib8f1cf4a2014-09-17 14:44:48 -0700328 for (OpenFlowSwitchListener l : ofSwitchListener) {
tom7ef8ff92014-09-17 13:08:06 -0700329 l.portChanged(dpid, (OFPortStatus) msg);
330 }
331 break;
Ayaka Koshibe38594c22014-10-22 13:36:12 -0700332 case FEATURES_REPLY:
333 for (OpenFlowSwitchListener l : ofSwitchListener) {
334 l.switchChanged(dpid);
335 }
336 break;
tom7ef8ff92014-09-17 13:08:06 -0700337 case PACKET_IN:
sangyun-han69ed4462016-07-27 12:10:12 +0900338 if (sw == null) {
Yuta HIGUCHI6ee6b8c2017-05-09 14:44:30 -0700339 log.error("Ignoring PACKET_IN, switch {} is not found", dpid);
sangyun-han69ed4462016-07-27 12:10:12 +0900340 break;
341 }
tom7ef8ff92014-09-17 13:08:06 -0700342 OpenFlowPacketContext pktCtx = DefaultOpenFlowPacketContext
Ozge AYAZ60aded22017-06-20 08:35:30 +0000343 .packetContextFromPacketIn(sw, (OFPacketIn) msg);
tom7ef8ff92014-09-17 13:08:06 -0700344 for (PacketListener p : ofPacketListener.values()) {
345 p.handlePacket(pktCtx);
346 }
347 break;
Pavlin Radoslavov369c6432014-12-03 16:25:14 -0800348 // TODO: Consider using separate threadpool for sensitive messages.
349 // ie. Back to back error could cause us to starve.
350 case FLOW_REMOVED:
Andrea Campanelladda93562016-03-02 11:08:12 -0800351 executorMsgs.execute(new OFMessageHandler(dpid, msg));
Pavlin Radoslavov369c6432014-12-03 16:25:14 -0800352 break;
Prince Pereirae7798032016-07-08 16:31:58 +0530353 case ERROR:
354 log.debug("Received error message from {}: {}", dpid, msg);
355 errorMsgs.putIfAbsent(msg.getXid(), true);
356 executorErrorMsgs.execute(new OFMessageHandler(dpid, msg));
357 break;
Ayaka Koshibe38594c22014-10-22 13:36:12 -0700358 case STATS_REPLY:
Yuta HIGUCHI7b41dc92017-06-22 19:37:06 -0700359 processStatsReply(dpid, (OFStatsReply) msg);
alshabib64def642014-12-02 23:27:37 -0800360 break;
alshabib8f1cf4a2014-09-17 14:44:48 -0700361 case BARRIER_REPLY:
Prince Pereirae7798032016-07-08 16:31:58 +0530362 if (errorMsgs.containsKey(msg.getXid())) {
363 //To make oferror msg handling and corresponding barrier reply serialized,
364 // executorErrorMsgs is used for both transaction
365 errorMsgs.remove(msg.getXid());
366 executorErrorMsgs.execute(new OFMessageHandler(dpid, msg));
367 } else {
368 executorBarrier.execute(new OFMessageHandler(dpid, msg));
369 }
alshabib8f1cf4a2014-09-17 14:44:48 -0700370 break;
Marc De Leenheer631ffce2014-10-28 16:29:07 -0700371 case EXPERIMENTER:
sangyun-han69ed4462016-07-27 12:10:12 +0900372 if (sw == null) {
373 log.error("Switch {} is not found", dpid);
374 break;
375 }
Marc De Leenheerb9311372015-07-09 11:36:49 -0700376 long experimenter = ((OFExperimenter) msg).getExperimenter();
377 if (experimenter == 0x748771) {
378 // LINC-OE port stats
Marc De Leenheer631ffce2014-10-28 16:29:07 -0700379 OFCircuitPortStatus circuitPortStatus = (OFCircuitPortStatus) msg;
sangyun-han69ed4462016-07-27 12:10:12 +0900380 OFPortStatus.Builder portStatus = sw.factory().buildPortStatus();
381 OFPortDesc.Builder portDesc = sw.factory().buildPortDesc();
Marc De Leenheer631ffce2014-10-28 16:29:07 -0700382 portDesc.setPortNo(circuitPortStatus.getPortNo())
383 .setHwAddr(circuitPortStatus.getHwAddr())
384 .setName(circuitPortStatus.getName())
385 .setConfig(circuitPortStatus.getConfig())
386 .setState(circuitPortStatus.getState());
387 portStatus.setReason(circuitPortStatus.getReason()).setDesc(portDesc.build());
388 for (OpenFlowSwitchListener l : ofSwitchListener) {
389 l.portChanged(dpid, portStatus.build());
390 }
391 } else {
392 log.warn("Handling experimenter type {} not yet implemented",
393 ((OFExperimenter) msg).getExperimenter(), msg);
394 }
395 break;
tom7ef8ff92014-09-17 13:08:06 -0700396 default:
397 log.warn("Handling message type {} not yet implemented {}",
398 msg.getType(), msg);
399 }
400 }
401
Yuta HIGUCHI7b41dc92017-06-22 19:37:06 -0700402 private void processStatsReply(Dpid dpid, OFStatsReply reply) {
403 switch (reply.getStatsType()) {
404 case QUEUE:
405 Collection<OFQueueStatsEntry> queueStatsEntries = publishQueueStats(dpid, (OFQueueStatsReply) reply);
406 if (queueStatsEntries != null) {
407 OFQueueStatsReply.Builder rep =
408 OFFactories.getFactory(reply.getVersion()).buildQueueStatsReply();
409 rep.setEntries(ImmutableList.copyOf(queueStatsEntries));
410 rep.setXid(reply.getXid());
411 executorMsgs.execute(new OFMessageHandler(dpid, rep.build()));
412 }
413 break;
414
415 case PORT_DESC:
416 for (OpenFlowSwitchListener l : ofSwitchListener) {
417 l.switchChanged(dpid);
418 }
419 break;
420
421 case FLOW:
422 Collection<OFFlowStatsEntry> flowStats = publishFlowStats(dpid, (OFFlowStatsReply) reply);
423 if (flowStats != null) {
424 OFFlowStatsReply.Builder rep =
425 OFFactories.getFactory(reply.getVersion()).buildFlowStatsReply();
426 rep.setEntries(ImmutableList.copyOf(flowStats));
427 rep.setXid(reply.getXid());
428 executorMsgs.execute(new OFMessageHandler(dpid, rep.build()));
429 }
430 break;
Cem Türker3baff672017-10-12 15:09:01 +0300431 case FLOW_LIGHTWEIGHT:
432 Collection<OFFlowLightweightStatsEntry> flowLightweightStats =
433 publishFlowStatsLightweight(dpid, (OFFlowLightweightStatsReply) reply);
434 if (flowLightweightStats != null) {
435 OFFlowLightweightStatsReply.Builder rep =
436 OFFactories.getFactory(reply.getVersion()).buildFlowLightweightStatsReply();
437 rep.setEntries(ImmutableList.copyOf(flowLightweightStats));
438 rep.setXid(reply.getXid());
439 executorMsgs.execute(new OFMessageHandler(dpid, rep.build()));
440 }
441 break;
Yuta HIGUCHI7b41dc92017-06-22 19:37:06 -0700442 case TABLE:
443 Collection<OFTableStatsEntry> tableStats = publishTableStats(dpid, (OFTableStatsReply) reply);
444 if (tableStats != null) {
445 OFTableStatsReply.Builder rep =
446 OFFactories.getFactory(reply.getVersion()).buildTableStatsReply();
447 rep.setEntries(ImmutableList.copyOf(tableStats));
448 executorMsgs.execute(new OFMessageHandler(dpid, rep.build()));
449 }
450 break;
451
452 case GROUP:
453 Collection<OFGroupStatsEntry> groupStats = publishGroupStats(dpid, (OFGroupStatsReply) reply);
454 if (groupStats != null) {
455 OFGroupStatsReply.Builder rep =
456 OFFactories.getFactory(reply.getVersion()).buildGroupStatsReply();
457 rep.setEntries(ImmutableList.copyOf(groupStats));
458 rep.setXid(reply.getXid());
459 executorMsgs.execute(new OFMessageHandler(dpid, rep.build()));
460 }
461 break;
462
463 case GROUP_DESC:
464 Collection<OFGroupDescStatsEntry> groupDescStats = publishGroupDescStats(dpid,
465 (OFGroupDescStatsReply) reply);
466 if (groupDescStats != null) {
467 OFGroupDescStatsReply.Builder rep =
468 OFFactories.getFactory(reply.getVersion()).buildGroupDescStatsReply();
469 rep.setEntries(ImmutableList.copyOf(groupDescStats));
470 rep.setXid(reply.getXid());
471 executorMsgs.execute(new OFMessageHandler(dpid, rep.build()));
472 }
473 break;
474
475 case PORT:
476 executorMsgs.execute(new OFMessageHandler(dpid, reply));
477 break;
478
479 case METER:
480 executorMsgs.execute(new OFMessageHandler(dpid, reply));
481 break;
482
483 case EXPERIMENTER:
484 if (reply instanceof OFCalientFlowStatsReply) {
485 OpenFlowSwitch sw = this.getSwitch(dpid);
486 // Convert Calient flow statistics to regular flow stats
487 // TODO: parse remaining fields such as power levels etc. when we have proper monitoring API
488 if (sw == null) {
489 log.error("Switch {} is not found", dpid);
490 break;
491 }
492 OFFlowStatsReply.Builder fsr = sw.factory().buildFlowStatsReply();
493 List<OFFlowStatsEntry> entries = new ArrayList<>();
494 for (OFCalientFlowStatsEntry entry : ((OFCalientFlowStatsReply) reply).getEntries()) {
495
496 // Single instruction, i.e., output to port
497 OFActionOutput action = sw.factory()
498 .actions()
499 .buildOutput()
500 .setPort(entry.getOutPort())
501 .build();
502 OFInstruction instruction = sw.factory()
503 .instructions()
504 .applyActions(Collections.singletonList(action));
505 OFFlowStatsEntry fs = sw.factory().buildFlowStatsEntry()
506 .setMatch(entry.getMatch())
507 .setTableId(entry.getTableId())
508 .setDurationSec(entry.getDurationSec())
509 .setDurationNsec(entry.getDurationNsec())
510 .setPriority(entry.getPriority())
511 .setIdleTimeout(entry.getIdleTimeout())
512 .setHardTimeout(entry.getHardTimeout())
513 .setFlags(entry.getFlags())
514 .setCookie(entry.getCookie())
515 .setInstructions(Collections.singletonList(instruction))
516 .build();
517 entries.add(fs);
518 }
519 fsr.setEntries(entries);
520
521 flowStats = publishFlowStats(dpid, fsr.build());
522 if (flowStats != null) {
523 OFFlowStatsReply.Builder rep =
524 sw.factory().buildFlowStatsReply();
525 rep.setEntries(ImmutableList.copyOf(flowStats));
526 executorMsgs.execute(new OFMessageHandler(dpid, rep.build()));
527 }
528 } else {
529 executorMsgs.execute(new OFMessageHandler(dpid, reply));
530 }
531 break;
532 default:
533 log.warn("Discarding unknown stats reply type {}", reply.getStatsType());
534 break;
535 }
536 }
537
sangho6a0bb172015-02-05 12:24:48 -0800538 private synchronized Collection<OFFlowStatsEntry> publishFlowStats(Dpid dpid,
539 OFFlowStatsReply reply) {
alshabib64def642014-12-02 23:27:37 -0800540 //TODO: Get rid of synchronized
sangho6a0bb172015-02-05 12:24:48 -0800541 fullFlowStats.putAll(dpid, reply.getEntries());
alshabib64def642014-12-02 23:27:37 -0800542 if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
sangho6a0bb172015-02-05 12:24:48 -0800543 return fullFlowStats.removeAll(dpid);
544 }
545 return null;
546 }
547
Cem Türker3baff672017-10-12 15:09:01 +0300548 private synchronized Collection<OFFlowLightweightStatsEntry> publishFlowStatsLightweight(
549 Dpid dpid,
550 OFFlowLightweightStatsReply reply) {
551 //TODO: Get rid of synchronized
552 fullFlowLightweightStats.putAll(dpid, reply.getEntries());
553 if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
554 return fullFlowLightweightStats.removeAll(dpid);
555 }
556 return null;
557 }
558
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700559 private synchronized Collection<OFTableStatsEntry> publishTableStats(Dpid dpid,
560 OFTableStatsReply reply) {
561 //TODO: Get rid of synchronized
562 fullTableStats.putAll(dpid, reply.getEntries());
563 if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
564 return fullTableStats.removeAll(dpid);
565 }
566 return null;
567 }
568
sangho6a0bb172015-02-05 12:24:48 -0800569 private synchronized Collection<OFGroupStatsEntry> publishGroupStats(Dpid dpid,
570 OFGroupStatsReply reply) {
571 //TODO: Get rid of synchronized
572 fullGroupStats.putAll(dpid, reply.getEntries());
573 if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
574 return fullGroupStats.removeAll(dpid);
575 }
576 return null;
577 }
578
579 private synchronized Collection<OFGroupDescStatsEntry> publishGroupDescStats(Dpid dpid,
580 OFGroupDescStatsReply reply) {
581 //TODO: Get rid of synchronized
582 fullGroupDescStats.putAll(dpid, reply.getEntries());
583 if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
584 return fullGroupDescStats.removeAll(dpid);
alshabib64def642014-12-02 23:27:37 -0800585 }
586 return null;
587 }
588
Ozge AYAZ60aded22017-06-20 08:35:30 +0000589 private synchronized Collection<OFQueueStatsEntry> publishQueueStats(Dpid dpid, OFQueueStatsReply reply) {
590 fullQueueStats.putAll(dpid, reply.getEntries());
591 if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
592 return fullQueueStats.removeAll(dpid);
593 }
594 return null;
595 }
596
tom7ef8ff92014-09-17 13:08:06 -0700597 @Override
598 public void setRole(Dpid dpid, RoleState role) {
Yuta HIGUCHI79cbd1c2014-10-02 16:57:57 -0700599 final OpenFlowSwitch sw = getSwitch(dpid);
600 if (sw == null) {
601 log.debug("Switch not connected. Ignoring setRole({}, {})", dpid, role);
602 return;
603 }
604 sw.setRole(role);
tom7ef8ff92014-09-17 13:08:06 -0700605 }
606
Yuta HIGUCHIcedd0df2016-08-23 11:44:13 -0700607 class InternalDeviceListener implements DeviceListener {
608
609 @Override
610 public boolean isRelevant(DeviceEvent event) {
Andrea Campanella86e0c562017-11-23 16:38:24 +0100611 return event.subject().type() != CONTROLLER && event.type() == DEVICE_REMOVED
612 && event.subject().id().uri().getScheme().equals(SCHEME);
Yuta HIGUCHIcedd0df2016-08-23 11:44:13 -0700613 }
614
615 @Override
616 public void event(DeviceEvent event) {
617 switch (event.type()) {
618 case DEVICE_ADDED:
619 break;
620 case DEVICE_AVAILABILITY_CHANGED:
621 break;
622 case DEVICE_REMOVED:
623 // Device administratively removed, disconnect
624 Optional.ofNullable(getSwitch(dpid(event.subject().id().uri())))
625 .ifPresent(OpenFlowSwitch::disconnectSwitch);
626 break;
627 case DEVICE_SUSPENDED:
628 break;
629 case DEVICE_UPDATED:
630 break;
631 case PORT_ADDED:
632 break;
633 case PORT_REMOVED:
634 break;
635 case PORT_STATS_UPDATED:
636 break;
637 case PORT_UPDATED:
638 break;
639 default:
640 break;
641
642 }
643
644 }
645
646 }
647
tom7ef8ff92014-09-17 13:08:06 -0700648 /**
649 * Implementation of an OpenFlow Agent which is responsible for
650 * keeping track of connected switches and the state in which
651 * they are.
652 */
653 public class OpenFlowSwitchAgent implements OpenFlowAgent {
654
655 private final Logger log = LoggerFactory.getLogger(OpenFlowSwitchAgent.class);
656 private final Lock switchLock = new ReentrantLock();
657
658 @Override
659 public boolean addConnectedSwitch(Dpid dpid, OpenFlowSwitch sw) {
alshabib9eab22f2014-10-20 17:17:31 -0700660
tom7ef8ff92014-09-17 13:08:06 -0700661 if (connectedSwitches.get(dpid) != null) {
662 log.error("Trying to add connectedSwitch but found a previous "
663 + "value for dpid: {}", dpid);
664 return false;
665 } else {
Yuta HIGUCHIeb3f30b2014-10-22 11:34:49 -0700666 log.info("Added switch {}", dpid);
tom7ef8ff92014-09-17 13:08:06 -0700667 connectedSwitches.put(dpid, sw);
alshabib8f1cf4a2014-09-17 14:44:48 -0700668 for (OpenFlowSwitchListener l : ofSwitchListener) {
tom7ef8ff92014-09-17 13:08:06 -0700669 l.switchAdded(dpid);
670 }
671 return true;
672 }
673 }
674
675 @Override
676 public boolean validActivation(Dpid dpid) {
677 if (connectedSwitches.get(dpid) == null) {
678 log.error("Trying to activate switch but is not in "
679 + "connected switches: dpid {}. Aborting ..",
680 dpid);
681 return false;
682 }
683 if (activeMasterSwitches.get(dpid) != null ||
684 activeEqualSwitches.get(dpid) != null) {
685 log.error("Trying to activate switch but it is already "
686 + "activated: dpid {}. Found in activeMaster: {} "
Ray Milkey6bc43c22015-11-06 13:22:38 -0800687 + "Found in activeEqual: {}. Aborting ..",
688 dpid,
689 (activeMasterSwitches.get(dpid) == null) ? 'N' : 'Y',
690 (activeEqualSwitches.get(dpid) == null) ? 'N' : 'Y');
tom7ef8ff92014-09-17 13:08:06 -0700691 return false;
692 }
693 return true;
694 }
695
696
697 @Override
698 public boolean addActivatedMasterSwitch(Dpid dpid, OpenFlowSwitch sw) {
699 switchLock.lock();
700 try {
701 if (!validActivation(dpid)) {
702 return false;
703 }
704 activeMasterSwitches.put(dpid, sw);
705 return true;
706 } finally {
707 switchLock.unlock();
708 }
709 }
710
711 @Override
712 public boolean addActivatedEqualSwitch(Dpid dpid, OpenFlowSwitch sw) {
713 switchLock.lock();
714 try {
715 if (!validActivation(dpid)) {
716 return false;
717 }
718 activeEqualSwitches.put(dpid, sw);
719 log.info("Added Activated EQUAL Switch {}", dpid);
720 return true;
721 } finally {
722 switchLock.unlock();
723 }
724 }
725
726 @Override
727 public void transitionToMasterSwitch(Dpid dpid) {
728 switchLock.lock();
729 try {
730 if (activeMasterSwitches.containsKey(dpid)) {
731 return;
732 }
733 OpenFlowSwitch sw = activeEqualSwitches.remove(dpid);
734 if (sw == null) {
735 sw = getSwitch(dpid);
736 if (sw == null) {
737 log.error("Transition to master called on sw {}, but switch "
738 + "was not found in controller-cache", dpid);
739 return;
740 }
741 }
742 log.info("Transitioned switch {} to MASTER", dpid);
743 activeMasterSwitches.put(dpid, sw);
744 } finally {
745 switchLock.unlock();
746 }
747 }
748
749
750 @Override
751 public void transitionToEqualSwitch(Dpid dpid) {
752 switchLock.lock();
753 try {
754 if (activeEqualSwitches.containsKey(dpid)) {
755 return;
756 }
757 OpenFlowSwitch sw = activeMasterSwitches.remove(dpid);
758 if (sw == null) {
759 sw = getSwitch(dpid);
760 if (sw == null) {
761 log.error("Transition to equal called on sw {}, but switch "
762 + "was not found in controller-cache", dpid);
763 return;
764 }
765 }
766 log.info("Transitioned switch {} to EQUAL", dpid);
767 activeEqualSwitches.put(dpid, sw);
768 } finally {
769 switchLock.unlock();
770 }
771
772 }
773
774 @Override
775 public void removeConnectedSwitch(Dpid dpid) {
776 connectedSwitches.remove(dpid);
777 OpenFlowSwitch sw = activeMasterSwitches.remove(dpid);
778 if (sw == null) {
Thomas Vachuska3358af22015-05-19 18:40:34 -0700779 log.debug("sw was null for {}", dpid);
tom7ef8ff92014-09-17 13:08:06 -0700780 sw = activeEqualSwitches.remove(dpid);
781 }
alshabib8f1cf4a2014-09-17 14:44:48 -0700782 for (OpenFlowSwitchListener l : ofSwitchListener) {
tom7ef8ff92014-09-17 13:08:06 -0700783 l.switchRemoved(dpid);
784 }
785 }
786
787 @Override
Jian Lia78cdb22016-04-21 13:03:58 -0700788 public void processDownstreamMessage(Dpid dpid, List<OFMessage> m) {
789 for (OpenFlowMessageListener listener : ofMessageListener) {
790 listener.handleOutgoingMessage(dpid, m);
791 }
792 }
793
794
795 @Override
tom7ef8ff92014-09-17 13:08:06 -0700796 public void processMessage(Dpid dpid, OFMessage m) {
797 processPacket(dpid, m);
Jian Lia78cdb22016-04-21 13:03:58 -0700798
799 for (OpenFlowMessageListener listener : ofMessageListener) {
800 listener.handleIncomingMessage(dpid, m);
801 }
tom7ef8ff92014-09-17 13:08:06 -0700802 }
Ayaka Koshibeab91cc42014-09-25 10:20:52 -0700803
804 @Override
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700805 public void returnRoleReply(Dpid dpid, RoleState requested, RoleState response) {
Ayaka Koshibeab91cc42014-09-25 10:20:52 -0700806 for (OpenFlowSwitchListener l : ofSwitchListener) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700807 l.receivedRoleReply(dpid, requested, response);
Ayaka Koshibeab91cc42014-09-25 10:20:52 -0700808 }
809 }
tom7ef8ff92014-09-17 13:08:06 -0700810 }
811
Jian Li152b8852015-12-07 14:47:25 -0800812 /**
Jian Li2266bff2016-04-21 11:01:25 -0700813 * OpenFlow message handler.
Jian Li152b8852015-12-07 14:47:25 -0800814 */
Ray Milkey7ec0d1b2015-11-13 08:51:35 -0800815 protected final class OFMessageHandler implements Runnable {
alshabib8f1cf4a2014-09-17 14:44:48 -0700816
Ray Milkey7ec0d1b2015-11-13 08:51:35 -0800817 protected final OFMessage msg;
818 protected final Dpid dpid;
alshabib8f1cf4a2014-09-17 14:44:48 -0700819
820 public OFMessageHandler(Dpid dpid, OFMessage msg) {
821 this.msg = msg;
822 this.dpid = dpid;
823 }
824
825 @Override
826 public void run() {
alshabibeec3a062014-09-17 18:01:26 -0700827 for (OpenFlowEventListener listener : ofEventListener) {
alshabib8f1cf4a2014-09-17 14:44:48 -0700828 listener.handleMessage(dpid, msg);
829 }
830 }
alshabib8f1cf4a2014-09-17 14:44:48 -0700831 }
tom7ef8ff92014-09-17 13:08:06 -0700832}