blob: 6224842985daab5626ce3f33113c6c1dfec480e2 [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;
Brian O'Connorf69e3e32018-05-10 02:25:09 -070031import org.onosproject.net.DeviceId;
32import org.onosproject.net.config.ConfigFactory;
33import org.onosproject.net.config.NetworkConfigRegistry;
34import org.onosproject.net.config.basics.SubjectFactories;
alshabibb452fd72015-04-22 20:46:20 -070035import org.onosproject.net.driver.DriverService;
Brian O'Connorf69e3e32018-05-10 02:25:09 -070036import org.onosproject.openflow.config.OpenFlowDeviceConfig;
Brian O'Connorabafb502014-12-02 22:26:20 -080037import org.onosproject.openflow.controller.DefaultOpenFlowPacketContext;
38import org.onosproject.openflow.controller.Dpid;
39import org.onosproject.openflow.controller.OpenFlowController;
40import org.onosproject.openflow.controller.OpenFlowEventListener;
Jian Lia78cdb22016-04-21 13:03:58 -070041import org.onosproject.openflow.controller.OpenFlowMessageListener;
Brian O'Connorabafb502014-12-02 22:26:20 -080042import org.onosproject.openflow.controller.OpenFlowPacketContext;
43import org.onosproject.openflow.controller.OpenFlowSwitch;
44import org.onosproject.openflow.controller.OpenFlowSwitchListener;
45import org.onosproject.openflow.controller.PacketListener;
46import org.onosproject.openflow.controller.RoleState;
47import org.onosproject.openflow.controller.driver.OpenFlowAgent;
Jonathan Hartbbd91d42015-02-27 11:18:04 -080048import org.osgi.service.component.ComponentContext;
Marc De Leenheerb9311372015-07-09 11:36:49 -070049import org.projectfloodlight.openflow.protocol.OFCalientFlowStatsEntry;
50import org.projectfloodlight.openflow.protocol.OFCalientFlowStatsReply;
Marc De Leenheer631ffce2014-10-28 16:29:07 -070051import org.projectfloodlight.openflow.protocol.OFCircuitPortStatus;
52import org.projectfloodlight.openflow.protocol.OFExperimenter;
alshabib64def642014-12-02 23:27:37 -080053import org.projectfloodlight.openflow.protocol.OFFactories;
Cem Türker3baff672017-10-12 15:09:01 +030054import org.projectfloodlight.openflow.protocol.OFFlowLightweightStatsEntry;
55import org.projectfloodlight.openflow.protocol.OFFlowLightweightStatsReply;
alshabib64def642014-12-02 23:27:37 -080056import org.projectfloodlight.openflow.protocol.OFFlowStatsEntry;
57import org.projectfloodlight.openflow.protocol.OFFlowStatsReply;
sangho6a0bb172015-02-05 12:24:48 -080058import org.projectfloodlight.openflow.protocol.OFGroupDescStatsEntry;
59import org.projectfloodlight.openflow.protocol.OFGroupDescStatsReply;
60import org.projectfloodlight.openflow.protocol.OFGroupStatsEntry;
61import org.projectfloodlight.openflow.protocol.OFGroupStatsReply;
tom7ef8ff92014-09-17 13:08:06 -070062import org.projectfloodlight.openflow.protocol.OFMessage;
63import org.projectfloodlight.openflow.protocol.OFPacketIn;
Marc De Leenheer631ffce2014-10-28 16:29:07 -070064import org.projectfloodlight.openflow.protocol.OFPortDesc;
sangho538108b2015-04-08 14:29:20 -070065import org.projectfloodlight.openflow.protocol.OFPortStatsEntry;
tom7ef8ff92014-09-17 13:08:06 -070066import org.projectfloodlight.openflow.protocol.OFPortStatus;
Cem Türker3baff672017-10-12 15:09:01 +030067import org.projectfloodlight.openflow.protocol.OFQueueStatsEntry;
68import org.projectfloodlight.openflow.protocol.OFQueueStatsReply;
Ayaka Koshibe38594c22014-10-22 13:36:12 -070069import org.projectfloodlight.openflow.protocol.OFStatsReply;
alshabib64def642014-12-02 23:27:37 -080070import org.projectfloodlight.openflow.protocol.OFStatsReplyFlags;
Jian Li2266bff2016-04-21 11:01:25 -070071import org.projectfloodlight.openflow.protocol.OFTableStatsEntry;
72import org.projectfloodlight.openflow.protocol.OFTableStatsReply;
Marc De Leenheerb9311372015-07-09 11:36:49 -070073import org.projectfloodlight.openflow.protocol.action.OFActionOutput;
74import org.projectfloodlight.openflow.protocol.instruction.OFInstruction;
tom7ef8ff92014-09-17 13:08:06 -070075import org.slf4j.Logger;
76import org.slf4j.LoggerFactory;
77
Yuta HIGUCHI7b41dc92017-06-22 19:37:06 -070078import java.util.ArrayList;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -080079import java.util.Collection;
Marc De Leenheerb9311372015-07-09 11:36:49 -070080import java.util.Collections;
Marc De Leenheerb9311372015-07-09 11:36:49 -070081import java.util.List;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -080082import java.util.Set;
Marc De Leenheer8aba62f2017-04-25 14:33:37 -070083import java.util.concurrent.CompletableFuture;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -080084import java.util.concurrent.ConcurrentHashMap;
HIGUCHI Yuta1979f552015-12-28 21:24:26 -080085import java.util.concurrent.ConcurrentMap;
Jonathan Hart6d44d192015-05-11 18:01:19 -070086import java.util.concurrent.CopyOnWriteArraySet;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -080087import java.util.concurrent.ExecutorService;
88import java.util.concurrent.Executors;
89import java.util.concurrent.locks.Lock;
90import java.util.concurrent.locks.ReentrantLock;
Jian Li2266bff2016-04-21 11:01:25 -070091
Thomas Vachuska6f94ded2015-02-21 14:02:38 -080092import static org.onlab.util.Tools.groupedThreads;
Ozge AYAZ60aded22017-06-20 08:35:30 +000093
tom7ef8ff92014-09-17 13:08:06 -070094
95@Component(immediate = true)
96@Service
97public class OpenFlowControllerImpl implements OpenFlowController {
Charles Chanecfdfb72015-11-24 19:05:50 -080098 private static final String APP_ID = "org.onosproject.openflow-base";
Brian O'Connorff278502015-09-22 14:49:52 -070099 private static final String DEFAULT_OFPORT = "6633,6653";
Yuta HIGUCHI8552b172016-07-25 12:10:08 -0700100 private static final int DEFAULT_WORKER_THREADS = 0;
Andrea Campanella86e0c562017-11-23 16:38:24 +0100101 protected static final String SCHEME = "of";
tom7ef8ff92014-09-17 13:08:06 -0700102
103 private static final Logger log =
104 LoggerFactory.getLogger(OpenFlowControllerImpl.class);
105
alshabibb452fd72015-04-22 20:46:20 -0700106 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Charles Chanecfdfb72015-11-24 19:05:50 -0800107 protected CoreService coreService;
108
109 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
alshabibb452fd72015-04-22 20:46:20 -0700110 protected DriverService driverService;
111
Charles Chan3b00e1b2015-08-26 23:12:52 +0800112 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
113 protected ComponentConfigService cfgService;
114
Brian O'Connorf69e3e32018-05-10 02:25:09 -0700115 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
116 protected NetworkConfigRegistry netCfgService;
117
Brian O'Connore2a399e2015-09-22 15:32:50 -0700118 @Property(name = "openflowPorts", value = DEFAULT_OFPORT,
119 label = "Port numbers (comma separated) used by OpenFlow protocol; default is 6633,6653")
120 private String openflowPorts = DEFAULT_OFPORT;
Charles Chan3b00e1b2015-08-26 23:12:52 +0800121
122 @Property(name = "workerThreads", intValue = DEFAULT_WORKER_THREADS,
Yuta HIGUCHI8552b172016-07-25 12:10:08 -0700123 label = "Number of controller worker threads")
Charles Chan3b00e1b2015-08-26 23:12:52 +0800124 private int workerThreads = DEFAULT_WORKER_THREADS;
125
Brian O'Connorf7215b82018-05-10 19:12:44 -0700126 @Property(name = "tlsMode", value = "",
127 label = "TLS mode for OpenFlow channel; options are: disabled [default], enabled, strict")
128 private String tlsModeString;
129
130 @Property(name = "keyStore", value = "",
131 label = "File path to key store for TLS connections")
132 private String keyStore;
133
134 @Property(name = "keyStorePassword", value = "",
135 label = "Key store password")
136 private String keyStorePassword;
137
138 @Property(name = "trustStore", value = "",
139 label = "File path to trust store for TLS connections")
140 private String trustStore;
141
142 @Property(name = "trustStorePassword", value = "",
143 label = "Trust store password")
144 private String trustStorePassword;
145
Ray Milkey7ec0d1b2015-11-13 08:51:35 -0800146 protected ExecutorService executorMsgs =
Andrea Campanelladda93562016-03-02 11:08:12 -0800147 Executors.newFixedThreadPool(32, groupedThreads("onos/of", "event-stats-%d", log));
Pavlin Radoslavov369c6432014-12-03 16:25:14 -0800148
149 private final ExecutorService executorBarrier =
Andrea Campanelladda93562016-03-02 11:08:12 -0800150 Executors.newFixedThreadPool(4, groupedThreads("onos/of", "event-barrier-%d", log));
alshabib8f1cf4a2014-09-17 14:44:48 -0700151
Prince Pereirae7798032016-07-08 16:31:58 +0530152 //Separate executor thread for handling error messages and barrier replies for same failed
153 // transactions to avoid context switching of thread
154 protected ExecutorService executorErrorMsgs =
155 Executors.newSingleThreadExecutor(groupedThreads("onos/of", "event-error-msg-%d", log));
156
157 //concurrent hashmap to track failed transactions
158 protected ConcurrentMap<Long, Boolean> errorMsgs =
159 new ConcurrentHashMap<>();
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800160 protected ConcurrentMap<Dpid, OpenFlowSwitch> connectedSwitches =
Jonathan Hart6d44d192015-05-11 18:01:19 -0700161 new ConcurrentHashMap<>();
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800162 protected ConcurrentMap<Dpid, OpenFlowSwitch> activeMasterSwitches =
Jonathan Hart6d44d192015-05-11 18:01:19 -0700163 new ConcurrentHashMap<>();
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800164 protected ConcurrentMap<Dpid, OpenFlowSwitch> activeEqualSwitches =
Jonathan Hart6d44d192015-05-11 18:01:19 -0700165 new ConcurrentHashMap<>();
tom7ef8ff92014-09-17 13:08:06 -0700166
Marc De Leenheer8aba62f2017-04-25 14:33:37 -0700167 // Key: dpid, value: map with key: long (XID), value: completable future
168 protected ConcurrentMap<Dpid, ConcurrentMap<Long, CompletableFuture<OFMessage>>> responses =
169 new ConcurrentHashMap<>();
170
tom7ef8ff92014-09-17 13:08:06 -0700171 protected OpenFlowSwitchAgent agent = new OpenFlowSwitchAgent();
Jonathan Hart6d44d192015-05-11 18:01:19 -0700172 protected Set<OpenFlowSwitchListener> ofSwitchListener = new CopyOnWriteArraySet<>();
tom7ef8ff92014-09-17 13:08:06 -0700173
174 protected Multimap<Integer, PacketListener> ofPacketListener =
175 ArrayListMultimap.create();
176
Jonathan Hart6d44d192015-05-11 18:01:19 -0700177 protected Set<OpenFlowEventListener> ofEventListener = new CopyOnWriteArraySet<>();
tom7ef8ff92014-09-17 13:08:06 -0700178
Jian Lia78cdb22016-04-21 13:03:58 -0700179 protected Set<OpenFlowMessageListener> ofMessageListener = new CopyOnWriteArraySet<>();
Jian Li28247b52016-01-07 17:24:15 -0800180
sangho6a0bb172015-02-05 12:24:48 -0800181 protected Multimap<Dpid, OFFlowStatsEntry> fullFlowStats =
182 ArrayListMultimap.create();
183
Cem Türker3baff672017-10-12 15:09:01 +0300184 protected Multimap<Dpid, OFFlowLightweightStatsEntry> fullFlowLightweightStats =
185 ArrayListMultimap.create();
186
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700187 protected Multimap<Dpid, OFTableStatsEntry> fullTableStats =
188 ArrayListMultimap.create();
189
sangho6a0bb172015-02-05 12:24:48 -0800190 protected Multimap<Dpid, OFGroupStatsEntry> fullGroupStats =
191 ArrayListMultimap.create();
192
193 protected Multimap<Dpid, OFGroupDescStatsEntry> fullGroupDescStats =
alshabib64def642014-12-02 23:27:37 -0800194 ArrayListMultimap.create();
195
Yuta HIGUCHI7b41dc92017-06-22 19:37:06 -0700196 // deprecated in 1.11.0, no longer referenced from anywhere
197 @Deprecated
sangho538108b2015-04-08 14:29:20 -0700198 protected Multimap<Dpid, OFPortStatsEntry> fullPortStats =
199 ArrayListMultimap.create();
200
Ozge AYAZ60aded22017-06-20 08:35:30 +0000201 protected Multimap<Dpid, OFQueueStatsEntry> fullQueueStats =
202 ArrayListMultimap.create();
203
Brian O'Connorf69e3e32018-05-10 02:25:09 -0700204 protected final ConfigFactory factory =
205 new ConfigFactory<DeviceId, OpenFlowDeviceConfig>(
206 SubjectFactories.DEVICE_SUBJECT_FACTORY,
207 OpenFlowDeviceConfig.class, OpenFlowDeviceConfig.CONFIG_KEY) {
208 @Override
209 public OpenFlowDeviceConfig createConfig() {
210 return new OpenFlowDeviceConfig();
211 }
212 };
213
tom7ef8ff92014-09-17 13:08:06 -0700214 private final Controller ctrl = new Controller();
215
216 @Activate
Jonathan Hartbbd91d42015-02-27 11:18:04 -0800217 public void activate(ComponentContext context) {
Andrea Campanella3556f362016-04-28 15:18:10 -0700218 coreService.registerApplication(APP_ID, this::cleanup);
Charles Chan3b00e1b2015-08-26 23:12:52 +0800219 cfgService.registerProperties(getClass());
Brian O'Connorf69e3e32018-05-10 02:25:09 -0700220 netCfgService.registerConfigFactory(factory);
Brian O'Connorff278502015-09-22 14:49:52 -0700221 ctrl.setConfigParams(context.getProperties());
Brian O'Connorf69e3e32018-05-10 02:25:09 -0700222 ctrl.start(agent, driverService, netCfgService);
Brian O'Connorf7215b82018-05-10 19:12:44 -0700223 // TODO register a netcfg listener that disconnects switches when the keyAlias changes
tom7ef8ff92014-09-17 13:08:06 -0700224 }
225
Andrea Campanella3556f362016-04-28 15:18:10 -0700226 private void cleanup() {
227 // Close listening channel and all OF channels. Clean information about switches
228 // before deactivating
Charles Chanecfdfb72015-11-24 19:05:50 -0800229 ctrl.stop();
230 connectedSwitches.values().forEach(OpenFlowSwitch::disconnectSwitch);
Andrea Campanella3556f362016-04-28 15:18:10 -0700231 connectedSwitches.clear();
232 activeMasterSwitches.clear();
233 activeEqualSwitches.clear();
Charles Chanecfdfb72015-11-24 19:05:50 -0800234 }
235
tom7ef8ff92014-09-17 13:08:06 -0700236 @Deactivate
237 public void deactivate() {
Thiago Santos61725402016-08-05 17:58:56 -0300238 cleanup();
Charles Chan3b00e1b2015-08-26 23:12:52 +0800239 cfgService.unregisterProperties(getClass(), false);
Brian O'Connorf69e3e32018-05-10 02:25:09 -0700240 netCfgService.unregisterConfigFactory(factory);
tom7ef8ff92014-09-17 13:08:06 -0700241 }
242
Jonathan Hartbbd91d42015-02-27 11:18:04 -0800243 @Modified
244 public void modified(ComponentContext context) {
Brian O'Connorf7215b82018-05-10 19:12:44 -0700245 //ctrl.stop();
Brian O'Connorff278502015-09-22 14:49:52 -0700246 ctrl.setConfigParams(context.getProperties());
Brian O'Connorf7215b82018-05-10 19:12:44 -0700247 //ctrl.start(agent, driverService, netCfgService);
Jonathan Hartbbd91d42015-02-27 11:18:04 -0800248 }
249
tom7ef8ff92014-09-17 13:08:06 -0700250 @Override
251 public Iterable<OpenFlowSwitch> getSwitches() {
252 return connectedSwitches.values();
253 }
254
255 @Override
256 public Iterable<OpenFlowSwitch> getMasterSwitches() {
257 return activeMasterSwitches.values();
258 }
259
260 @Override
261 public Iterable<OpenFlowSwitch> getEqualSwitches() {
262 return activeEqualSwitches.values();
263 }
264
265 @Override
266 public OpenFlowSwitch getSwitch(Dpid dpid) {
267 return connectedSwitches.get(dpid);
268 }
269
270 @Override
271 public OpenFlowSwitch getMasterSwitch(Dpid dpid) {
272 return activeMasterSwitches.get(dpid);
273 }
274
275 @Override
276 public OpenFlowSwitch getEqualSwitch(Dpid dpid) {
277 return activeEqualSwitches.get(dpid);
278 }
279
280 @Override
281 public void addListener(OpenFlowSwitchListener listener) {
alshabib8f1cf4a2014-09-17 14:44:48 -0700282 if (!ofSwitchListener.contains(listener)) {
283 this.ofSwitchListener.add(listener);
tom7ef8ff92014-09-17 13:08:06 -0700284 }
285 }
286
287 @Override
288 public void removeListener(OpenFlowSwitchListener listener) {
alshabib8f1cf4a2014-09-17 14:44:48 -0700289 this.ofSwitchListener.remove(listener);
tom7ef8ff92014-09-17 13:08:06 -0700290 }
291
292 @Override
Jian Lia78cdb22016-04-21 13:03:58 -0700293 public void addMessageListener(OpenFlowMessageListener listener) {
294 ofMessageListener.add(listener);
295 }
296
297 @Override
298 public void removeMessageListener(OpenFlowMessageListener listener) {
299 ofMessageListener.remove(listener);
300 }
301
302 @Override
tom7ef8ff92014-09-17 13:08:06 -0700303 public void addPacketListener(int priority, PacketListener listener) {
304 ofPacketListener.put(priority, listener);
305 }
306
307 @Override
308 public void removePacketListener(PacketListener listener) {
309 ofPacketListener.values().remove(listener);
310 }
311
312 @Override
alshabibeec3a062014-09-17 18:01:26 -0700313 public void addEventListener(OpenFlowEventListener listener) {
314 ofEventListener.add(listener);
315 }
316
317 @Override
318 public void removeEventListener(OpenFlowEventListener listener) {
319 ofEventListener.remove(listener);
320 }
321
322 @Override
tom7ef8ff92014-09-17 13:08:06 -0700323 public void write(Dpid dpid, OFMessage msg) {
324 this.getSwitch(dpid).sendMsg(msg);
325 }
326
327 @Override
Marc De Leenheer8aba62f2017-04-25 14:33:37 -0700328 public CompletableFuture<OFMessage> writeResponse(Dpid dpid, OFMessage msg) {
329 write(dpid, msg);
330
331 ConcurrentMap<Long, CompletableFuture<OFMessage>> xids =
Yuta HIGUCHI6ee6b8c2017-05-09 14:44:30 -0700332 responses.computeIfAbsent(dpid, k -> new ConcurrentHashMap<>());
Marc De Leenheer8aba62f2017-04-25 14:33:37 -0700333
Yuta HIGUCHI6ee6b8c2017-05-09 14:44:30 -0700334 CompletableFuture<OFMessage> future = new CompletableFuture<>();
Marc De Leenheer8aba62f2017-04-25 14:33:37 -0700335 xids.put(msg.getXid(), future);
336
337 return future;
338 }
339
340 @Override
tom7ef8ff92014-09-17 13:08:06 -0700341 public void processPacket(Dpid dpid, OFMessage msg) {
sangyun-han69ed4462016-07-27 12:10:12 +0900342 OpenFlowSwitch sw = this.getSwitch(dpid);
Laszlo Pappb68fe7e2017-11-24 17:06:59 +0000343 if (log.isTraceEnabled()) {
344 log.trace("Processing message from switch {} via openflow: {}", dpid, msg);
345 }
sangyun-han69ed4462016-07-27 12:10:12 +0900346
Marc De Leenheer8aba62f2017-04-25 14:33:37 -0700347 // Check if someone is waiting for this message
348 ConcurrentMap<Long, CompletableFuture<OFMessage>> xids = responses.get(dpid);
Yuta HIGUCHI6ee6b8c2017-05-09 14:44:30 -0700349 if (xids != null) {
350 CompletableFuture<OFMessage> future = xids.remove(msg.getXid());
351 if (future != null) {
352 future.complete(msg);
353 }
Marc De Leenheer8aba62f2017-04-25 14:33:37 -0700354 }
355
tom7ef8ff92014-09-17 13:08:06 -0700356 switch (msg.getType()) {
357 case PORT_STATUS:
alshabib8f1cf4a2014-09-17 14:44:48 -0700358 for (OpenFlowSwitchListener l : ofSwitchListener) {
tom7ef8ff92014-09-17 13:08:06 -0700359 l.portChanged(dpid, (OFPortStatus) msg);
360 }
361 break;
Ayaka Koshibe38594c22014-10-22 13:36:12 -0700362 case FEATURES_REPLY:
363 for (OpenFlowSwitchListener l : ofSwitchListener) {
364 l.switchChanged(dpid);
365 }
366 break;
tom7ef8ff92014-09-17 13:08:06 -0700367 case PACKET_IN:
sangyun-han69ed4462016-07-27 12:10:12 +0900368 if (sw == null) {
Yuta HIGUCHI6ee6b8c2017-05-09 14:44:30 -0700369 log.error("Ignoring PACKET_IN, switch {} is not found", dpid);
sangyun-han69ed4462016-07-27 12:10:12 +0900370 break;
371 }
tom7ef8ff92014-09-17 13:08:06 -0700372 OpenFlowPacketContext pktCtx = DefaultOpenFlowPacketContext
Ozge AYAZ60aded22017-06-20 08:35:30 +0000373 .packetContextFromPacketIn(sw, (OFPacketIn) msg);
tom7ef8ff92014-09-17 13:08:06 -0700374 for (PacketListener p : ofPacketListener.values()) {
375 p.handlePacket(pktCtx);
376 }
377 break;
Pavlin Radoslavov369c6432014-12-03 16:25:14 -0800378 // TODO: Consider using separate threadpool for sensitive messages.
379 // ie. Back to back error could cause us to starve.
380 case FLOW_REMOVED:
Andrea Campanelladda93562016-03-02 11:08:12 -0800381 executorMsgs.execute(new OFMessageHandler(dpid, msg));
Pavlin Radoslavov369c6432014-12-03 16:25:14 -0800382 break;
Prince Pereirae7798032016-07-08 16:31:58 +0530383 case ERROR:
384 log.debug("Received error message from {}: {}", dpid, msg);
385 errorMsgs.putIfAbsent(msg.getXid(), true);
386 executorErrorMsgs.execute(new OFMessageHandler(dpid, msg));
387 break;
Ayaka Koshibe38594c22014-10-22 13:36:12 -0700388 case STATS_REPLY:
Yuta HIGUCHI7b41dc92017-06-22 19:37:06 -0700389 processStatsReply(dpid, (OFStatsReply) msg);
alshabib64def642014-12-02 23:27:37 -0800390 break;
alshabib8f1cf4a2014-09-17 14:44:48 -0700391 case BARRIER_REPLY:
Prince Pereirae7798032016-07-08 16:31:58 +0530392 if (errorMsgs.containsKey(msg.getXid())) {
393 //To make oferror msg handling and corresponding barrier reply serialized,
394 // executorErrorMsgs is used for both transaction
395 errorMsgs.remove(msg.getXid());
396 executorErrorMsgs.execute(new OFMessageHandler(dpid, msg));
397 } else {
398 executorBarrier.execute(new OFMessageHandler(dpid, msg));
399 }
alshabib8f1cf4a2014-09-17 14:44:48 -0700400 break;
Marc De Leenheer631ffce2014-10-28 16:29:07 -0700401 case EXPERIMENTER:
sangyun-han69ed4462016-07-27 12:10:12 +0900402 if (sw == null) {
403 log.error("Switch {} is not found", dpid);
404 break;
405 }
Marc De Leenheerb9311372015-07-09 11:36:49 -0700406 long experimenter = ((OFExperimenter) msg).getExperimenter();
407 if (experimenter == 0x748771) {
408 // LINC-OE port stats
Marc De Leenheer631ffce2014-10-28 16:29:07 -0700409 OFCircuitPortStatus circuitPortStatus = (OFCircuitPortStatus) msg;
sangyun-han69ed4462016-07-27 12:10:12 +0900410 OFPortStatus.Builder portStatus = sw.factory().buildPortStatus();
411 OFPortDesc.Builder portDesc = sw.factory().buildPortDesc();
Marc De Leenheer631ffce2014-10-28 16:29:07 -0700412 portDesc.setPortNo(circuitPortStatus.getPortNo())
413 .setHwAddr(circuitPortStatus.getHwAddr())
414 .setName(circuitPortStatus.getName())
415 .setConfig(circuitPortStatus.getConfig())
416 .setState(circuitPortStatus.getState());
417 portStatus.setReason(circuitPortStatus.getReason()).setDesc(portDesc.build());
418 for (OpenFlowSwitchListener l : ofSwitchListener) {
419 l.portChanged(dpid, portStatus.build());
420 }
421 } else {
422 log.warn("Handling experimenter type {} not yet implemented",
423 ((OFExperimenter) msg).getExperimenter(), msg);
424 }
425 break;
tom7ef8ff92014-09-17 13:08:06 -0700426 default:
427 log.warn("Handling message type {} not yet implemented {}",
428 msg.getType(), msg);
429 }
430 }
431
Yuta HIGUCHI7b41dc92017-06-22 19:37:06 -0700432 private void processStatsReply(Dpid dpid, OFStatsReply reply) {
433 switch (reply.getStatsType()) {
434 case QUEUE:
435 Collection<OFQueueStatsEntry> queueStatsEntries = publishQueueStats(dpid, (OFQueueStatsReply) reply);
436 if (queueStatsEntries != null) {
437 OFQueueStatsReply.Builder rep =
438 OFFactories.getFactory(reply.getVersion()).buildQueueStatsReply();
439 rep.setEntries(ImmutableList.copyOf(queueStatsEntries));
440 rep.setXid(reply.getXid());
441 executorMsgs.execute(new OFMessageHandler(dpid, rep.build()));
442 }
443 break;
444
445 case PORT_DESC:
446 for (OpenFlowSwitchListener l : ofSwitchListener) {
447 l.switchChanged(dpid);
448 }
449 break;
450
451 case FLOW:
452 Collection<OFFlowStatsEntry> flowStats = publishFlowStats(dpid, (OFFlowStatsReply) reply);
453 if (flowStats != null) {
454 OFFlowStatsReply.Builder rep =
455 OFFactories.getFactory(reply.getVersion()).buildFlowStatsReply();
456 rep.setEntries(ImmutableList.copyOf(flowStats));
457 rep.setXid(reply.getXid());
458 executorMsgs.execute(new OFMessageHandler(dpid, rep.build()));
459 }
460 break;
Cem Türker3baff672017-10-12 15:09:01 +0300461 case FLOW_LIGHTWEIGHT:
462 Collection<OFFlowLightweightStatsEntry> flowLightweightStats =
463 publishFlowStatsLightweight(dpid, (OFFlowLightweightStatsReply) reply);
464 if (flowLightweightStats != null) {
465 OFFlowLightweightStatsReply.Builder rep =
466 OFFactories.getFactory(reply.getVersion()).buildFlowLightweightStatsReply();
467 rep.setEntries(ImmutableList.copyOf(flowLightweightStats));
468 rep.setXid(reply.getXid());
469 executorMsgs.execute(new OFMessageHandler(dpid, rep.build()));
470 }
471 break;
Yuta HIGUCHI7b41dc92017-06-22 19:37:06 -0700472 case TABLE:
473 Collection<OFTableStatsEntry> tableStats = publishTableStats(dpid, (OFTableStatsReply) reply);
474 if (tableStats != null) {
475 OFTableStatsReply.Builder rep =
476 OFFactories.getFactory(reply.getVersion()).buildTableStatsReply();
477 rep.setEntries(ImmutableList.copyOf(tableStats));
478 executorMsgs.execute(new OFMessageHandler(dpid, rep.build()));
479 }
480 break;
481
482 case GROUP:
483 Collection<OFGroupStatsEntry> groupStats = publishGroupStats(dpid, (OFGroupStatsReply) reply);
484 if (groupStats != null) {
485 OFGroupStatsReply.Builder rep =
486 OFFactories.getFactory(reply.getVersion()).buildGroupStatsReply();
487 rep.setEntries(ImmutableList.copyOf(groupStats));
488 rep.setXid(reply.getXid());
489 executorMsgs.execute(new OFMessageHandler(dpid, rep.build()));
490 }
491 break;
492
493 case GROUP_DESC:
494 Collection<OFGroupDescStatsEntry> groupDescStats = publishGroupDescStats(dpid,
495 (OFGroupDescStatsReply) reply);
496 if (groupDescStats != null) {
497 OFGroupDescStatsReply.Builder rep =
498 OFFactories.getFactory(reply.getVersion()).buildGroupDescStatsReply();
499 rep.setEntries(ImmutableList.copyOf(groupDescStats));
500 rep.setXid(reply.getXid());
501 executorMsgs.execute(new OFMessageHandler(dpid, rep.build()));
502 }
503 break;
504
505 case PORT:
506 executorMsgs.execute(new OFMessageHandler(dpid, reply));
507 break;
508
509 case METER:
510 executorMsgs.execute(new OFMessageHandler(dpid, reply));
511 break;
512
513 case EXPERIMENTER:
514 if (reply instanceof OFCalientFlowStatsReply) {
515 OpenFlowSwitch sw = this.getSwitch(dpid);
516 // Convert Calient flow statistics to regular flow stats
517 // TODO: parse remaining fields such as power levels etc. when we have proper monitoring API
518 if (sw == null) {
519 log.error("Switch {} is not found", dpid);
520 break;
521 }
522 OFFlowStatsReply.Builder fsr = sw.factory().buildFlowStatsReply();
523 List<OFFlowStatsEntry> entries = new ArrayList<>();
524 for (OFCalientFlowStatsEntry entry : ((OFCalientFlowStatsReply) reply).getEntries()) {
525
526 // Single instruction, i.e., output to port
527 OFActionOutput action = sw.factory()
528 .actions()
529 .buildOutput()
530 .setPort(entry.getOutPort())
531 .build();
532 OFInstruction instruction = sw.factory()
533 .instructions()
534 .applyActions(Collections.singletonList(action));
535 OFFlowStatsEntry fs = sw.factory().buildFlowStatsEntry()
536 .setMatch(entry.getMatch())
537 .setTableId(entry.getTableId())
538 .setDurationSec(entry.getDurationSec())
539 .setDurationNsec(entry.getDurationNsec())
540 .setPriority(entry.getPriority())
541 .setIdleTimeout(entry.getIdleTimeout())
542 .setHardTimeout(entry.getHardTimeout())
543 .setFlags(entry.getFlags())
544 .setCookie(entry.getCookie())
545 .setInstructions(Collections.singletonList(instruction))
546 .build();
547 entries.add(fs);
548 }
549 fsr.setEntries(entries);
550
551 flowStats = publishFlowStats(dpid, fsr.build());
552 if (flowStats != null) {
553 OFFlowStatsReply.Builder rep =
554 sw.factory().buildFlowStatsReply();
555 rep.setEntries(ImmutableList.copyOf(flowStats));
556 executorMsgs.execute(new OFMessageHandler(dpid, rep.build()));
557 }
558 } else {
559 executorMsgs.execute(new OFMessageHandler(dpid, reply));
560 }
561 break;
562 default:
563 log.warn("Discarding unknown stats reply type {}", reply.getStatsType());
564 break;
565 }
566 }
567
sangho6a0bb172015-02-05 12:24:48 -0800568 private synchronized Collection<OFFlowStatsEntry> publishFlowStats(Dpid dpid,
569 OFFlowStatsReply reply) {
alshabib64def642014-12-02 23:27:37 -0800570 //TODO: Get rid of synchronized
sangho6a0bb172015-02-05 12:24:48 -0800571 fullFlowStats.putAll(dpid, reply.getEntries());
alshabib64def642014-12-02 23:27:37 -0800572 if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
sangho6a0bb172015-02-05 12:24:48 -0800573 return fullFlowStats.removeAll(dpid);
574 }
575 return null;
576 }
577
Cem Türker3baff672017-10-12 15:09:01 +0300578 private synchronized Collection<OFFlowLightweightStatsEntry> publishFlowStatsLightweight(
579 Dpid dpid,
580 OFFlowLightweightStatsReply reply) {
581 //TODO: Get rid of synchronized
582 fullFlowLightweightStats.putAll(dpid, reply.getEntries());
583 if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
584 return fullFlowLightweightStats.removeAll(dpid);
585 }
586 return null;
587 }
588
Srikanth Vavilapalli95810f52015-09-14 15:49:56 -0700589 private synchronized Collection<OFTableStatsEntry> publishTableStats(Dpid dpid,
590 OFTableStatsReply reply) {
591 //TODO: Get rid of synchronized
592 fullTableStats.putAll(dpid, reply.getEntries());
593 if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
594 return fullTableStats.removeAll(dpid);
595 }
596 return null;
597 }
598
sangho6a0bb172015-02-05 12:24:48 -0800599 private synchronized Collection<OFGroupStatsEntry> publishGroupStats(Dpid dpid,
600 OFGroupStatsReply reply) {
601 //TODO: Get rid of synchronized
602 fullGroupStats.putAll(dpid, reply.getEntries());
603 if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
604 return fullGroupStats.removeAll(dpid);
605 }
606 return null;
607 }
608
609 private synchronized Collection<OFGroupDescStatsEntry> publishGroupDescStats(Dpid dpid,
610 OFGroupDescStatsReply reply) {
611 //TODO: Get rid of synchronized
612 fullGroupDescStats.putAll(dpid, reply.getEntries());
613 if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
614 return fullGroupDescStats.removeAll(dpid);
alshabib64def642014-12-02 23:27:37 -0800615 }
616 return null;
617 }
618
Ozge AYAZ60aded22017-06-20 08:35:30 +0000619 private synchronized Collection<OFQueueStatsEntry> publishQueueStats(Dpid dpid, OFQueueStatsReply reply) {
620 fullQueueStats.putAll(dpid, reply.getEntries());
621 if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
622 return fullQueueStats.removeAll(dpid);
623 }
624 return null;
625 }
626
tom7ef8ff92014-09-17 13:08:06 -0700627 @Override
628 public void setRole(Dpid dpid, RoleState role) {
Yuta HIGUCHI79cbd1c2014-10-02 16:57:57 -0700629 final OpenFlowSwitch sw = getSwitch(dpid);
630 if (sw == null) {
631 log.debug("Switch not connected. Ignoring setRole({}, {})", dpid, role);
632 return;
633 }
634 sw.setRole(role);
tom7ef8ff92014-09-17 13:08:06 -0700635 }
636
637 /**
638 * Implementation of an OpenFlow Agent which is responsible for
639 * keeping track of connected switches and the state in which
640 * they are.
641 */
642 public class OpenFlowSwitchAgent implements OpenFlowAgent {
643
644 private final Logger log = LoggerFactory.getLogger(OpenFlowSwitchAgent.class);
645 private final Lock switchLock = new ReentrantLock();
646
647 @Override
648 public boolean addConnectedSwitch(Dpid dpid, OpenFlowSwitch sw) {
alshabib9eab22f2014-10-20 17:17:31 -0700649
tom7ef8ff92014-09-17 13:08:06 -0700650 if (connectedSwitches.get(dpid) != null) {
651 log.error("Trying to add connectedSwitch but found a previous "
652 + "value for dpid: {}", dpid);
653 return false;
654 } else {
Yuta HIGUCHIeb3f30b2014-10-22 11:34:49 -0700655 log.info("Added switch {}", dpid);
tom7ef8ff92014-09-17 13:08:06 -0700656 connectedSwitches.put(dpid, sw);
alshabib8f1cf4a2014-09-17 14:44:48 -0700657 for (OpenFlowSwitchListener l : ofSwitchListener) {
tom7ef8ff92014-09-17 13:08:06 -0700658 l.switchAdded(dpid);
659 }
660 return true;
661 }
662 }
663
664 @Override
665 public boolean validActivation(Dpid dpid) {
666 if (connectedSwitches.get(dpid) == null) {
667 log.error("Trying to activate switch but is not in "
668 + "connected switches: dpid {}. Aborting ..",
669 dpid);
670 return false;
671 }
672 if (activeMasterSwitches.get(dpid) != null ||
673 activeEqualSwitches.get(dpid) != null) {
674 log.error("Trying to activate switch but it is already "
675 + "activated: dpid {}. Found in activeMaster: {} "
Ray Milkey6bc43c22015-11-06 13:22:38 -0800676 + "Found in activeEqual: {}. Aborting ..",
677 dpid,
678 (activeMasterSwitches.get(dpid) == null) ? 'N' : 'Y',
679 (activeEqualSwitches.get(dpid) == null) ? 'N' : 'Y');
tom7ef8ff92014-09-17 13:08:06 -0700680 return false;
681 }
682 return true;
683 }
684
685
686 @Override
687 public boolean addActivatedMasterSwitch(Dpid dpid, OpenFlowSwitch sw) {
688 switchLock.lock();
689 try {
690 if (!validActivation(dpid)) {
691 return false;
692 }
693 activeMasterSwitches.put(dpid, sw);
694 return true;
695 } finally {
696 switchLock.unlock();
697 }
698 }
699
700 @Override
701 public boolean addActivatedEqualSwitch(Dpid dpid, OpenFlowSwitch sw) {
702 switchLock.lock();
703 try {
704 if (!validActivation(dpid)) {
705 return false;
706 }
707 activeEqualSwitches.put(dpid, sw);
708 log.info("Added Activated EQUAL Switch {}", dpid);
709 return true;
710 } finally {
711 switchLock.unlock();
712 }
713 }
714
715 @Override
716 public void transitionToMasterSwitch(Dpid dpid) {
717 switchLock.lock();
718 try {
719 if (activeMasterSwitches.containsKey(dpid)) {
720 return;
721 }
722 OpenFlowSwitch sw = activeEqualSwitches.remove(dpid);
723 if (sw == null) {
724 sw = getSwitch(dpid);
725 if (sw == null) {
726 log.error("Transition to master called on sw {}, but switch "
727 + "was not found in controller-cache", dpid);
728 return;
729 }
730 }
731 log.info("Transitioned switch {} to MASTER", dpid);
732 activeMasterSwitches.put(dpid, sw);
733 } finally {
734 switchLock.unlock();
735 }
736 }
737
738
739 @Override
740 public void transitionToEqualSwitch(Dpid dpid) {
741 switchLock.lock();
742 try {
743 if (activeEqualSwitches.containsKey(dpid)) {
744 return;
745 }
746 OpenFlowSwitch sw = activeMasterSwitches.remove(dpid);
747 if (sw == null) {
748 sw = getSwitch(dpid);
749 if (sw == null) {
750 log.error("Transition to equal called on sw {}, but switch "
751 + "was not found in controller-cache", dpid);
752 return;
753 }
754 }
755 log.info("Transitioned switch {} to EQUAL", dpid);
756 activeEqualSwitches.put(dpid, sw);
757 } finally {
758 switchLock.unlock();
759 }
760
761 }
762
763 @Override
764 public void removeConnectedSwitch(Dpid dpid) {
765 connectedSwitches.remove(dpid);
766 OpenFlowSwitch sw = activeMasterSwitches.remove(dpid);
767 if (sw == null) {
Thomas Vachuska3358af22015-05-19 18:40:34 -0700768 log.debug("sw was null for {}", dpid);
tom7ef8ff92014-09-17 13:08:06 -0700769 sw = activeEqualSwitches.remove(dpid);
770 }
alshabib8f1cf4a2014-09-17 14:44:48 -0700771 for (OpenFlowSwitchListener l : ofSwitchListener) {
tom7ef8ff92014-09-17 13:08:06 -0700772 l.switchRemoved(dpid);
773 }
774 }
775
776 @Override
Jian Lia78cdb22016-04-21 13:03:58 -0700777 public void processDownstreamMessage(Dpid dpid, List<OFMessage> m) {
778 for (OpenFlowMessageListener listener : ofMessageListener) {
779 listener.handleOutgoingMessage(dpid, m);
780 }
781 }
782
783
784 @Override
tom7ef8ff92014-09-17 13:08:06 -0700785 public void processMessage(Dpid dpid, OFMessage m) {
786 processPacket(dpid, m);
Jian Lia78cdb22016-04-21 13:03:58 -0700787
788 for (OpenFlowMessageListener listener : ofMessageListener) {
789 listener.handleIncomingMessage(dpid, m);
790 }
tom7ef8ff92014-09-17 13:08:06 -0700791 }
Ayaka Koshibeab91cc42014-09-25 10:20:52 -0700792
793 @Override
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700794 public void returnRoleReply(Dpid dpid, RoleState requested, RoleState response) {
Ayaka Koshibeab91cc42014-09-25 10:20:52 -0700795 for (OpenFlowSwitchListener l : ofSwitchListener) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700796 l.receivedRoleReply(dpid, requested, response);
Ayaka Koshibeab91cc42014-09-25 10:20:52 -0700797 }
798 }
tom7ef8ff92014-09-17 13:08:06 -0700799 }
800
Jian Li152b8852015-12-07 14:47:25 -0800801 /**
Jian Li2266bff2016-04-21 11:01:25 -0700802 * OpenFlow message handler.
Jian Li152b8852015-12-07 14:47:25 -0800803 */
Ray Milkey7ec0d1b2015-11-13 08:51:35 -0800804 protected final class OFMessageHandler implements Runnable {
alshabib8f1cf4a2014-09-17 14:44:48 -0700805
Ray Milkey9c9cde42018-01-12 14:22:06 -0800806 final OFMessage msg;
807 final Dpid dpid;
alshabib8f1cf4a2014-09-17 14:44:48 -0700808
809 public OFMessageHandler(Dpid dpid, OFMessage msg) {
810 this.msg = msg;
811 this.dpid = dpid;
812 }
813
814 @Override
815 public void run() {
alshabibeec3a062014-09-17 18:01:26 -0700816 for (OpenFlowEventListener listener : ofEventListener) {
alshabib8f1cf4a2014-09-17 14:44:48 -0700817 listener.handleMessage(dpid, msg);
818 }
819 }
alshabib8f1cf4a2014-09-17 14:44:48 -0700820 }
tom7ef8ff92014-09-17 13:08:06 -0700821}