blob: bb335919839638a4506af341a8d61f152933f30f [file] [log] [blame]
Srikanth Vavilapalli8a661e72014-10-27 15:40:22 -07001package net.onrc.onos.core.drivermanager;
2
3import java.io.IOException;
4import java.util.ArrayList;
5import java.util.Collection;
6import java.util.Collections;
7import java.util.HashMap;
8import java.util.HashSet;
9import java.util.Iterator;
10import java.util.List;
11import java.util.Map;
12import java.util.Set;
13import java.util.concurrent.ConcurrentHashMap;
14import java.util.concurrent.ConcurrentMap;
15import java.util.concurrent.atomic.AtomicBoolean;
16import java.util.concurrent.atomic.AtomicInteger;
17
18import net.floodlightcontroller.core.IFloodlightProviderService.Role;
19import net.floodlightcontroller.core.IOF13Switch;
20import net.floodlightcontroller.core.IOFSwitch;
21import net.floodlightcontroller.core.SwitchDriverSubHandshakeAlreadyStarted;
22import net.floodlightcontroller.core.SwitchDriverSubHandshakeCompleted;
23import net.floodlightcontroller.core.SwitchDriverSubHandshakeNotStarted;
24import net.floodlightcontroller.core.internal.OFSwitchImplBase;
25import net.floodlightcontroller.util.MACAddress;
26import net.floodlightcontroller.util.OrderedCollection;
27import net.onrc.onos.core.configmanager.INetworkConfigService;
28import net.onrc.onos.core.configmanager.INetworkConfigService.NetworkConfigState;
29import net.onrc.onos.core.configmanager.INetworkConfigService.SwitchConfigStatus;
30import net.onrc.onos.core.configmanager.NetworkConfig.LinkConfig;
31import net.onrc.onos.core.configmanager.NetworkConfig.SwitchConfig;
32import net.onrc.onos.core.configmanager.NetworkConfigManager;
33import net.onrc.onos.core.configmanager.PktLinkConfig;
34import net.onrc.onos.core.configmanager.SegmentRouterConfig;
35import net.onrc.onos.core.configmanager.SegmentRouterConfig.AdjacencySid;
36import net.onrc.onos.core.matchaction.MatchAction;
37import net.onrc.onos.core.matchaction.MatchActionOperationEntry;
38import net.onrc.onos.core.matchaction.MatchActionOperations;
39import net.onrc.onos.core.matchaction.MatchActionOperations.Operator;
40import net.onrc.onos.core.matchaction.action.Action;
41import net.onrc.onos.core.matchaction.action.CopyTtlInAction;
42import net.onrc.onos.core.matchaction.action.CopyTtlOutAction;
43import net.onrc.onos.core.matchaction.action.DecMplsTtlAction;
44import net.onrc.onos.core.matchaction.action.DecNwTtlAction;
45import net.onrc.onos.core.matchaction.action.GroupAction;
46import net.onrc.onos.core.matchaction.action.ModifyDstMacAction;
47import net.onrc.onos.core.matchaction.action.ModifySrcMacAction;
48import net.onrc.onos.core.matchaction.action.OutputAction;
49import net.onrc.onos.core.matchaction.action.PopMplsAction;
50import net.onrc.onos.core.matchaction.action.PushMplsAction;
51import net.onrc.onos.core.matchaction.action.SetDAAction;
52import net.onrc.onos.core.matchaction.action.SetMplsBosAction;
53import net.onrc.onos.core.matchaction.action.SetMplsIdAction;
54import net.onrc.onos.core.matchaction.action.SetSAAction;
55import net.onrc.onos.core.matchaction.match.Ipv4Match;
56import net.onrc.onos.core.matchaction.match.Match;
57import net.onrc.onos.core.matchaction.match.MplsMatch;
58import net.onrc.onos.core.matchaction.match.PacketMatch;
59import net.onrc.onos.core.util.Dpid;
60import net.onrc.onos.core.util.IPv4Net;
61import net.onrc.onos.core.util.PortNumber;
62
63import org.codehaus.jackson.map.ObjectMapper;
64import org.projectfloodlight.openflow.protocol.OFAsyncGetReply;
65import org.projectfloodlight.openflow.protocol.OFBarrierRequest;
66import org.projectfloodlight.openflow.protocol.OFBucket;
67import org.projectfloodlight.openflow.protocol.OFDescStatsReply;
68import org.projectfloodlight.openflow.protocol.OFErrorMsg;
69import org.projectfloodlight.openflow.protocol.OFFactory;
70import org.projectfloodlight.openflow.protocol.OFFlowMod;
71import org.projectfloodlight.openflow.protocol.OFGroupDescStatsReply;
72import org.projectfloodlight.openflow.protocol.OFGroupFeaturesStatsReply;
73import org.projectfloodlight.openflow.protocol.OFGroupType;
74import org.projectfloodlight.openflow.protocol.OFMatchV3;
75import org.projectfloodlight.openflow.protocol.OFMessage;
76import org.projectfloodlight.openflow.protocol.OFOxmList;
77import org.projectfloodlight.openflow.protocol.OFPortDesc;
78import org.projectfloodlight.openflow.protocol.OFPortStatus;
79import org.projectfloodlight.openflow.protocol.OFStatsReply;
80import org.projectfloodlight.openflow.protocol.action.OFAction;
81import org.projectfloodlight.openflow.protocol.instruction.OFInstruction;
82import org.projectfloodlight.openflow.protocol.match.Match.Builder;
83import org.projectfloodlight.openflow.protocol.match.MatchField;
84import org.projectfloodlight.openflow.protocol.oxm.OFOxmEthDst;
85import org.projectfloodlight.openflow.protocol.oxm.OFOxmEthSrc;
86import org.projectfloodlight.openflow.protocol.oxm.OFOxmEthType;
87import org.projectfloodlight.openflow.protocol.oxm.OFOxmInPort;
88import org.projectfloodlight.openflow.protocol.oxm.OFOxmIpv4DstMasked;
89import org.projectfloodlight.openflow.protocol.oxm.OFOxmMplsBos;
90import org.projectfloodlight.openflow.protocol.oxm.OFOxmMplsLabel;
91import org.projectfloodlight.openflow.protocol.oxm.OFOxmVlanVid;
92import org.projectfloodlight.openflow.types.EthType;
93import org.projectfloodlight.openflow.types.IPv4Address;
94import org.projectfloodlight.openflow.types.IpProtocol;
95import org.projectfloodlight.openflow.types.MacAddress;
96import org.projectfloodlight.openflow.types.OFBooleanValue;
97import org.projectfloodlight.openflow.types.OFBufferId;
98import org.projectfloodlight.openflow.types.OFGroup;
99import org.projectfloodlight.openflow.types.OFPort;
100import org.projectfloodlight.openflow.types.OFVlanVidMatch;
101import org.projectfloodlight.openflow.types.TableId;
102import org.projectfloodlight.openflow.types.TransportPort;
103import org.projectfloodlight.openflow.types.U32;
104import org.projectfloodlight.openflow.util.HexString;
105
106/**
107 * OFDescriptionStatistics Vendor (Manufacturer Desc.): Stanford University,
108 * Ericsson Research and CPqD Research. Make (Hardware Desc.) : OpenFlow 1.3
109 * Reference Userspace Switch Model (Datapath Desc.) : None Software : Serial :
110 * None
111 */
112public class OFSwitchImplSpringOpenTTP extends OFSwitchImplBase implements IOF13Switch {
113 private AtomicBoolean driverHandshakeComplete;
114 private AtomicBoolean haltStateMachine;
115 private OFFactory factory;
116 private static final int OFPCML_NO_BUFFER = 0xffff;
117 // Configuration of asynch messages to controller. We need different
118 // asynch messages depending on role-equal or role-master.
119 // We don't want to get anything if we are slave.
120 private static final long SET_FLOW_REMOVED_MASK_MASTER = 0xf;
121 private static final long SET_PACKET_IN_MASK_MASTER = 0x7;
122 private static final long SET_PORT_STATUS_MASK_MASTER = 0x7;
123 private static final long SET_FLOW_REMOVED_MASK_EQUAL = 0x0;
124 private static final long SET_PACKET_IN_MASK_EQUAL = 0x0;
125 private static final long SET_PORT_STATUS_MASK_EQUAL = 0x7;
126 private static final long SET_ALL_SLAVE = 0x0;
127
128 private static final long TEST_FLOW_REMOVED_MASK = 0xf;
129 private static final long TEST_PACKET_IN_MASK = 0x7;
130 private static final long TEST_PORT_STATUS_MASK = 0x7;
131
132 private static final int TABLE_VLAN = 0;
133 private static final int TABLE_TMAC = 1;
134 private static final int TABLE_IPv4_UNICAST = 2;
135 private static final int TABLE_MPLS = 3;
136 private static final int TABLE_ACL = 5;
137
138 private static final short MAX_PRIORITY = (short) 0xffff;
139 private static final short PRIORITY_MULTIPLIER = (short) 2046;
140 private static final short MIN_PRIORITY = 0x0;
141
142 private long barrierXidToWaitFor = -1;
143 private DriverState driverState;
144 private final boolean usePipeline13;
145 private SegmentRouterConfig srConfig;
146 private ConcurrentMap<Dpid, Set<PortNumber>> neighbors;
147 private ConcurrentMap<PortNumber, Dpid> portToNeighbors;
148 private List<Integer> segmentIds;
149 private boolean isEdgeRouter;
150 private ConcurrentMap<NeighborSet, EcmpInfo> ecmpGroups;
151 private ConcurrentMap<Integer, EcmpInfo> userDefinedGroups;
152 private ConcurrentMap<PortNumber, ArrayList<NeighborSet>> portNeighborSetMap;
153 private AtomicInteger groupid;
154 private Map<String, String> publishAttributes;
155
156 public OFSwitchImplSpringOpenTTP(OFDescStatsReply desc, boolean usePipeline13) {
157 super();
158 haltStateMachine = new AtomicBoolean(false);
159 driverState = DriverState.INIT;
160 driverHandshakeComplete = new AtomicBoolean(false);
161 setSwitchDescription(desc);
162 neighbors = new ConcurrentHashMap<Dpid, Set<PortNumber>>();
163 portToNeighbors = new ConcurrentHashMap<PortNumber, Dpid>();
164 ecmpGroups = new ConcurrentHashMap<NeighborSet, EcmpInfo>();
165 userDefinedGroups = new ConcurrentHashMap<Integer, EcmpInfo>();
166 portNeighborSetMap =
167 new ConcurrentHashMap<PortNumber, ArrayList<NeighborSet>>();
168 segmentIds = new ArrayList<Integer>();
169 isEdgeRouter = false;
170 groupid = new AtomicInteger(0);
171 this.usePipeline13 = usePipeline13;
172 }
173
174 // *****************************
175 // OFSwitchImplBase
176 // *****************************
177
178
179 /* (non-Javadoc)
180 * @see java.lang.Object#toString()
181 */
182 @Override
183 public String toString() {
184 return "OFSwitchImplCPqD13 [" + ((channel != null)
185 ? channel.getRemoteAddress() : "?")
186 + " DPID[" + ((stringId != null) ? stringId : "?") + "]]";
187 }
188
189 @Override
190 public void startDriverHandshake() throws IOException {
191 log.debug("Starting driver handshake for sw {}", getStringId());
192 if (startDriverHandshakeCalled) {
193 throw new SwitchDriverSubHandshakeAlreadyStarted();
194 }
195 startDriverHandshakeCalled = true;
196 factory = getFactory();
197 if (!usePipeline13) {
198 // Send packet-in to controller if a packet misses the first table
199 populateTableMissEntry(0, true, false, false, 0);
200 driverHandshakeComplete.set(true);
201 } else {
202 nextDriverState();
203 }
204 }
205
206 @Override
207 public boolean isDriverHandshakeComplete() {
208 if (!startDriverHandshakeCalled)
209 throw new SwitchDriverSubHandshakeNotStarted();
210 return driverHandshakeComplete.get();
211 }
212
213 @Override
214 public void processDriverHandshakeMessage(OFMessage m) {
215 if (!startDriverHandshakeCalled)
216 throw new SwitchDriverSubHandshakeNotStarted();
217 if (isDriverHandshakeComplete())
218 throw new SwitchDriverSubHandshakeCompleted(m);
219 try {
220 processOFMessage(this, m);
221 } catch (IOException e) {
222 log.error("Error generated when processing OFMessage", e.getCause());
223 }
224 }
225
226 @Override
227 public String getSwitchDriverState() {
228 return driverState.toString();
229 }
230
231 public void removePortFromGroups(PortNumber port) {
232 log.debug("removePortFromGroups: Remove port {} from Switch {}",
233 port, getStringId());
234 ArrayList<NeighborSet> portNSSet = portNeighborSetMap.get(port);
235 if (portNSSet == null)
236 {
237 /* No Groups are created with this port yet */
238 log.warn("removePortFromGroups: No groups exist with Switch {} port {}",
239 getStringId(), port);
240 return;
241 }
242 log.debug("removePortFromGroups: Neighborsets that the port {} is part"
243 + "of on Switch {} are {}",
244 port, getStringId(), portNSSet);
245
246 for (NeighborSet ns : portNSSet) {
247 /* Delete the first matched bucket */
248 EcmpInfo portEcmpInfo = ecmpGroups.get(ns);
249 Iterator<BucketInfo> it = portEcmpInfo.buckets.iterator();
250 log.debug("removePortFromGroups: Group {} on Switch {} has {} buckets",
251 portEcmpInfo.groupId, getStringId(),
252 portEcmpInfo.buckets.size());
253 while (it.hasNext()) {
254 BucketInfo bucket = it.next();
255 if (bucket.outport.equals(port)) {
256 it.remove();
257 }
258 }
259 log.debug("removePortFromGroups: Modifying Group on Switch {} "
260 + "and Neighborset {} with {}",
261 getStringId(), ns, portEcmpInfo);
262 modifyEcmpGroup(portEcmpInfo);
263 }
264 /* Don't delete the entry from portNeighborSetMap because
265 * when the port is up again this info is needed
266 */
267 return;
268 }
269
270 public void addPortToGroups(PortNumber port) {
271 log.debug("addPortToGroups: Add port {} to Switch {}",
272 port, getStringId());
273 ArrayList<NeighborSet> portNSSet = portNeighborSetMap.get(port);
274 if (portNSSet == null) {
275 /* Unknown Port */
276 log.warn("addPortToGroups: Switch {} port {} is unknown",
277 getStringId(), port);
278 return;
279 }
280 log.debug("addPortToGroups: Neighborsets that the port {} is part"
281 + "of on Switch {} are {}",
282 port, getStringId(), portNSSet);
283
284 Dpid neighborDpid = portToNeighbors.get(port);
285 for (NeighborSet ns : portNSSet) {
286 EcmpInfo portEcmpInfo = ecmpGroups.get(ns);
287 /* Find if this port is already part of any bucket
288 * in this group
289 * NOTE: This is needed because in some cases
290 * (such as for configured network nodes), both driver and
291 * application detect the network elements and creates the
292 * buckets in the same group. This check is to avoid
293 * duplicate bucket creation in such scenarios
294 */
295 List<BucketInfo> buckets = portEcmpInfo.buckets;
296 if (buckets == null) {
297 buckets = new ArrayList<BucketInfo>();
298 portEcmpInfo.buckets = buckets;
299 } else {
300 Iterator<BucketInfo> it = buckets.iterator();
301 boolean matchingBucketExist = false;
302 while (it.hasNext()) {
303 BucketInfo bucket = it.next();
304 if (bucket.outport.equals(port)) {
305 matchingBucketExist = true;
306 break;
307 }
308 }
309 if (matchingBucketExist) {
310 log.warn("addPortToGroups: On Switch {} duplicate "
311 + "portAdd is called for port {} with buckets {}",
312 getStringId(), port, buckets);
313 continue;
314 }
315 }
316 BucketInfo b = new BucketInfo(neighborDpid,
317 MacAddress.of(srConfig.getRouterMac()),
318 getNeighborRouterMacAddress(neighborDpid),
319 port,
320 ns.getEdgeLabel(), true, -1);
321 buckets.add(b);
322 log.debug("addPortToGroups: Modifying Group on Switch {} "
323 + "and Neighborset {} with {}",
324 getStringId(), ns, portEcmpInfo);
325 modifyEcmpGroup(portEcmpInfo);
326 }
327 return;
328 }
329
330 @Override
331 public OrderedCollection<PortChangeEvent> processOFPortStatus(OFPortStatus ps) {
332 OrderedCollection<PortChangeEvent> events = super.processOFPortStatus(ps);
333 for (PortChangeEvent e : events) {
334 switch (e.type) {
335 case DELETE:
336 case DOWN:
337 log.debug("processOFPortStatus: sw {} Port {} DOWN",
338 getStringId(), e.port.getPortNo().getPortNumber());
339 removePortFromGroups(PortNumber.uint32(
340 e.port.getPortNo().getPortNumber()));
341 break;
342 case UP:
343 log.debug("processOFPortStatus: sw {} Port {} UP",
344 getStringId(), e.port.getPortNo().getPortNumber());
345 addPortToGroups(PortNumber.uint32(
346 e.port.getPortNo().getPortNumber()));
347 }
348 }
349 return events;
350 }
351
352 // *****************************
353 // Driver handshake state-machine
354 // *****************************
355
356 enum DriverState {
357 INIT,
358 SET_TABLE_MISS_ENTRIES,
359 SET_TABLE_VLAN_TMAC,
360 SET_GROUPS,
361 VERIFY_GROUPS,
362 SET_ADJACENCY_LABELS,
363 EXIT
364 }
365
366 protected void nextDriverState() throws IOException {
367 DriverState currentState = driverState;
368 if (haltStateMachine.get()) {
369 return;
370 }
371 switch (currentState) {
372 case INIT:
373 driverState = DriverState.SET_TABLE_MISS_ENTRIES;
374 setTableMissEntries();
375 sendHandshakeBarrier();
376 break;
377 case SET_TABLE_MISS_ENTRIES:
378 driverState = DriverState.SET_TABLE_VLAN_TMAC;
379 getNetworkConfig();
380 populateTableVlan();
381 populateTableTMac();
382 sendHandshakeBarrier();
383 break;
384 case SET_TABLE_VLAN_TMAC:
385 driverState = DriverState.SET_GROUPS;
386 createGroups();
387 sendHandshakeBarrier();
388 break;
389 case SET_GROUPS:
390 driverState = DriverState.VERIFY_GROUPS;
391 verifyGroups();
392 break;
393 case VERIFY_GROUPS:
394 driverState = DriverState.SET_ADJACENCY_LABELS;
395 assignAdjacencyLabels();
396 break;
397 case SET_ADJACENCY_LABELS:
398 driverState = DriverState.EXIT;
399 driverHandshakeComplete.set(true);
400 break;
401 case EXIT:
402 default:
403 driverState = DriverState.EXIT;
404 log.error("Driver handshake has exited for sw: {}", getStringId());
405 }
406 }
407
408 void processOFMessage(IOFSwitch sw, OFMessage m) throws IOException {
409 switch (m.getType()) {
410 case BARRIER_REPLY:
411 processBarrierReply(m);
412 break;
413
414 case ERROR:
415 processErrorMessage(m);
416 break;
417
418 case GET_ASYNC_REPLY:
419 OFAsyncGetReply asrep = (OFAsyncGetReply) m;
420 decodeAsyncGetReply(asrep);
421 break;
422
423 case PACKET_IN:
424 // not ready to handle packet-ins
425 break;
426
427 case QUEUE_GET_CONFIG_REPLY:
428 // not doing queue config yet
429 break;
430
431 case STATS_REPLY:
432 processStatsReply((OFStatsReply) m);
433 break;
434
435 case ROLE_REPLY: // channelHandler should handle this
436 case PORT_STATUS: // channelHandler should handle this
437 case FEATURES_REPLY: // don't care
438 case FLOW_REMOVED: // don't care
439 default:
440 log.debug("Received message {} during switch-driver subhandshake "
441 + "from switch {} ... Ignoring message", m, sw.getStringId());
442 }
443 }
444
445 private void processStatsReply(OFStatsReply sr) {
446 switch (sr.getStatsType()) {
447 case AGGREGATE:
448 break;
449 case DESC:
450 break;
451 case EXPERIMENTER:
452 break;
453 case FLOW:
454 break;
455 case GROUP_DESC:
456 processGroupDesc((OFGroupDescStatsReply) sr);
457 break;
458 case GROUP_FEATURES:
459 processGroupFeatures((OFGroupFeaturesStatsReply) sr);
460 break;
461 case METER_CONFIG:
462 break;
463 case METER_FEATURES:
464 break;
465 case PORT_DESC:
466 break;
467 case TABLE_FEATURES:
468 break;
469 default:
470 break;
471
472 }
473 }
474
475 private void processErrorMessage(OFMessage m) {
476 log.error("Switch {} Error {} in DriverState", getStringId(),
477 (OFErrorMsg) m, driverState);
478 }
479
480 private void processBarrierReply(OFMessage m) throws IOException {
481 if (m.getXid() == barrierXidToWaitFor) {
482 // Driver state-machine progresses to the next state.
483 // If Barrier messages is not received, then eventually
484 // the ChannelHandler state machine will timeout, and the switch
485 // will be disconnected.
486 nextDriverState();
487 } else {
488 log.error("Received incorrect barrier-message xid {} (expected: {}) in "
489 + "switch-driver state {} for switch {}", m, barrierXidToWaitFor,
490 driverState, getStringId());
491 }
492 }
493
494 private void processGroupDesc(OFGroupDescStatsReply gdsr) {
495 log.info("Sw: {} Group Desc {}", getStringId(), gdsr);
496 // TODO -- actually do verification
497 try {
498 nextDriverState();
499 } catch (IOException e) {
500 // TODO Auto-generated catch block
501 e.printStackTrace();
502 }
503 }
504
505 // *****************************
506 // Utility methods
507 // *****************************
508
509 void setTableMissEntries() throws IOException {
510 // set all table-miss-entries
511 populateTableMissEntry(TABLE_VLAN, true, false, false, -1);
512 populateTableMissEntry(TABLE_TMAC, true, false, false, -1);
513 populateTableMissEntry(TABLE_IPv4_UNICAST, false, true, true,
514 TABLE_ACL);
515 populateTableMissEntry(TABLE_MPLS, false, true, true,
516 TABLE_ACL);
517 populateTableMissEntry(TABLE_ACL, false, false, false, -1);
518 }
519
520 private void sendHandshakeBarrier() throws IOException {
521 long xid = getNextTransactionId();
522 barrierXidToWaitFor = xid;
523 OFBarrierRequest br = getFactory()
524 .buildBarrierRequest()
525 .setXid(xid)
526 .build();
527 write(br, null);
528 }
529
530 /**
531 * Adds a table-miss-entry to a pipeline table.
532 * <p>
533 * The table-miss-entry can be added with 'write-actions' or
534 * 'apply-actions'. It can also add a 'goto-table' instruction. By default
535 * if none of the booleans in the call are set, then the table-miss entry is
536 * added with no instructions, which means that if a packet hits the
537 * table-miss-entry, pipeline execution will stop, and the action set
538 * associated with the packet will be executed.
539 *
540 * @param tableToAdd the table to where the table-miss-entry will be added
541 * @param toControllerNow as an APPLY_ACTION instruction
542 * @param toControllerWrite as a WRITE_ACTION instruction
543 * @param toTable as a GOTO_TABLE instruction
544 * @param tableToSend the table to send as per the GOTO_TABLE instruction it
545 * needs to be set if 'toTable' is true. Ignored of 'toTable' is
546 * false.
547 * @throws IOException
548 */
549 @SuppressWarnings("unchecked")
550 private void populateTableMissEntry(int tableToAdd, boolean toControllerNow,
551 boolean toControllerWrite,
552 boolean toTable, int tableToSend) throws IOException {
553 OFOxmList oxmList = OFOxmList.EMPTY;
554 OFMatchV3 match = factory.buildMatchV3()
555 .setOxmList(oxmList)
556 .build();
557 OFAction outc = factory.actions()
558 .buildOutput()
559 .setPort(OFPort.CONTROLLER)
560 .setMaxLen(OFPCML_NO_BUFFER)
561 .build();
562 List<OFInstruction> instructions = new ArrayList<OFInstruction>();
563 if (toControllerNow) {
564 // table-miss instruction to send to controller immediately
565 OFInstruction instr = factory.instructions()
566 .buildApplyActions()
567 .setActions(Collections.singletonList(outc))
568 .build();
569 instructions.add(instr);
570 }
571
572 if (toControllerWrite) {
573 // table-miss instruction to write-action to send to controller
574 // this will be executed whenever the action-set gets executed
575 OFInstruction instr = factory.instructions()
576 .buildWriteActions()
577 .setActions(Collections.singletonList(outc))
578 .build();
579 instructions.add(instr);
580 }
581
582 if (toTable) {
583 // table-miss instruction to goto-table x
584 OFInstruction instr = factory.instructions()
585 .gotoTable(TableId.of(tableToSend));
586 instructions.add(instr);
587 }
588
589 if (!toControllerNow && !toControllerWrite && !toTable) {
590 // table-miss has no instruction - at which point action-set will be
591 // executed - if there is an action to output/group in the action
592 // set
593 // the packet will be sent there, otherwise it will be dropped.
594 instructions = (List<OFInstruction>) Collections.EMPTY_LIST;
595 }
596
597 OFMessage tableMissEntry = factory.buildFlowAdd()
598 .setTableId(TableId.of(tableToAdd))
599 .setMatch(match) // match everything
600 .setInstructions(instructions)
601 .setPriority(MIN_PRIORITY)
602 .setBufferId(OFBufferId.NO_BUFFER)
603 .setIdleTimeout(0)
604 .setHardTimeout(0)
605 .setXid(getNextTransactionId())
606 .build();
607 write(tableMissEntry, null);
608 }
609
610 private void getNetworkConfig() {
611 INetworkConfigService ncs = floodlightProvider.getNetworkConfigService();
612 SwitchConfigStatus scs = ncs.checkSwitchConfig(new Dpid(getId()));
613 if (scs.getConfigState() == NetworkConfigState.ACCEPT_ADD) {
614 srConfig = (SegmentRouterConfig) scs.getSwitchConfig();
615 isEdgeRouter = srConfig.isEdgeRouter();
616 } else {
617 log.error("Switch not configured as Segment-Router");
618 }
619
620 List<LinkConfig> linkConfigList = ncs.getConfiguredAllowedLinks();
621 setNeighbors(linkConfigList);
622
623 if (isEdgeRouter) {
624 List<SwitchConfig> switchList = ncs.getConfiguredAllowedSwitches();
625 getAllNodeSegmentIds(switchList);
626 }
627 }
628
629 private void populateTableVlan() throws IOException {
630 List<OFMessage> msglist = new ArrayList<OFMessage>();
631 for (OFPortDesc p : getPorts()) {
632 int pnum = p.getPortNo().getPortNumber();
633 if (U32.of(pnum).compareTo(U32.of(OFPort.MAX.getPortNumber())) < 1) {
634 OFOxmInPort oxp = factory.oxms().inPort(p.getPortNo());
635 OFOxmVlanVid oxv = factory.oxms()
636 .vlanVid(OFVlanVidMatch.UNTAGGED);
637 OFOxmList oxmList = OFOxmList.of(oxp, oxv);
638 OFMatchV3 match = factory.buildMatchV3()
639 .setOxmList(oxmList).build();
640
641 // TODO: match on vlan-tagged packets for vlans configured on
642 // subnet ports and strip-vlan
643
644 // Do not need to add vlans
645 /*int vlanid = getVlanConfig(pnum);
646 OFOxmVlanVid vidToSet = factory.oxms()
647 .vlanVid(OFVlanVidMatch.ofVlan(vlanid));
648 OFAction pushVlan = factory.actions().pushVlan(EthType.VLAN_FRAME);
649 OFAction setVlan = factory.actions().setField(vidToSet);
650 List<OFAction> actionlist = new ArrayList<OFAction>();
651 actionlist.add(pushVlan);
652 actionlist.add(setVlan);
653 OFInstruction appAction = factory.instructions().buildApplyActions()
654 .setActions(actionlist).build();*/
655
656 OFInstruction gotoTbl = factory.instructions().buildGotoTable()
657 .setTableId(TableId.of(TABLE_TMAC)).build();
658 List<OFInstruction> instructions = new ArrayList<OFInstruction>();
659 // instructions.add(appAction);
660 instructions.add(gotoTbl);
661 OFMessage flowEntry = factory.buildFlowAdd()
662 .setTableId(TableId.of(TABLE_VLAN))
663 .setMatch(match)
664 .setInstructions(instructions)
665 .setPriority(1000) // does not matter - all rules
666 // exclusive
667 .setBufferId(OFBufferId.NO_BUFFER)
668 .setIdleTimeout(0)
669 .setHardTimeout(0)
670 .setXid(getNextTransactionId())
671 .build();
672 msglist.add(flowEntry);
673 }
674 }
675 write(msglist);
676 log.debug("Adding {} port/vlan-rules in sw {}", msglist.size(), getStringId());
677 }
678
679 private void populateTableTMac() throws IOException {
680 // match for router-mac and ip-packets
681 OFOxmEthType oxe = factory.oxms().ethType(EthType.IPv4);
682 OFOxmEthDst dmac = factory.oxms().ethDst(getRouterMacAddr());
683 OFOxmList oxmListIp = OFOxmList.of(dmac, oxe);
684 OFMatchV3 matchIp = factory.buildMatchV3()
685 .setOxmList(oxmListIp).build();
686 OFInstruction gotoTblIp = factory.instructions().buildGotoTable()
687 .setTableId(TableId.of(TABLE_IPv4_UNICAST)).build();
688 List<OFInstruction> instructionsIp = Collections.singletonList(gotoTblIp);
689 OFMessage ipEntry = factory.buildFlowAdd()
690 .setTableId(TableId.of(TABLE_TMAC))
691 .setMatch(matchIp)
692 .setInstructions(instructionsIp)
693 .setPriority(1000) // strict priority required lower than
694 // multicastMac
695 .setBufferId(OFBufferId.NO_BUFFER)
696 .setIdleTimeout(0)
697 .setHardTimeout(0)
698 .setXid(getNextTransactionId())
699 .build();
700
701 // match for router-mac and mpls packets
702 OFOxmEthType oxmpls = factory.oxms().ethType(EthType.MPLS_UNICAST);
703 OFOxmList oxmListMpls = OFOxmList.of(dmac, oxmpls);
704 OFMatchV3 matchMpls = factory.buildMatchV3()
705 .setOxmList(oxmListMpls).build();
706 OFInstruction gotoTblMpls = factory.instructions().buildGotoTable()
707 .setTableId(TableId.of(TABLE_MPLS)).build();
708 List<OFInstruction> instructionsMpls = Collections.singletonList(gotoTblMpls);
709 OFMessage mplsEntry = factory.buildFlowAdd()
710 .setTableId(TableId.of(TABLE_TMAC))
711 .setMatch(matchMpls)
712 .setInstructions(instructionsMpls)
713 .setPriority(1001) // strict priority required lower than
714 // multicastMac
715 .setBufferId(OFBufferId.NO_BUFFER)
716 .setIdleTimeout(0)
717 .setHardTimeout(0)
718 .setXid(getNextTransactionId())
719 .build();
720
721 log.debug("Adding termination-mac-rules in sw {}", getStringId());
722 List<OFMessage> msglist = new ArrayList<OFMessage>(2);
723 msglist.add(ipEntry);
724 msglist.add(mplsEntry);
725 write(msglist);
726 }
727
728 private MacAddress getRouterMacAddr() {
729 if (srConfig != null) {
730 return MacAddress.of(srConfig.getRouterMac());
731 } else {
732 // return a dummy mac address - it will not be used
733 return MacAddress.of("00:00:00:00:00:00");
734 }
735 }
736
737 private boolean isEdgeRouter(Dpid ndpid) {
738 INetworkConfigService ncs = floodlightProvider.getNetworkConfigService();
739 SwitchConfigStatus scs = ncs.checkSwitchConfig(ndpid);
740 if (scs.getConfigState() == NetworkConfigState.ACCEPT_ADD) {
741 return ((SegmentRouterConfig) scs.getSwitchConfig()).isEdgeRouter();
742 } else {
743 // TODO: return false if router not allowed
744 return false;
745 }
746 }
747
748 private MacAddress getNeighborRouterMacAddress(Dpid ndpid) {
749 INetworkConfigService ncs = floodlightProvider.getNetworkConfigService();
750 SwitchConfigStatus scs = ncs.checkSwitchConfig(ndpid);
751 if (scs.getConfigState() == NetworkConfigState.ACCEPT_ADD) {
752 return MacAddress.of(((SegmentRouterConfig) scs.getSwitchConfig())
753 .getRouterMac());
754 } else {
755 // return a dummy mac address - it will not be used
756 return MacAddress.of("00:00:00:00:00:00");
757 }
758 }
759
760 private void setNeighbors(List<LinkConfig> linkConfigList) {
761 for (LinkConfig lg : linkConfigList) {
762 if (!lg.getType().equals(NetworkConfigManager.PKT_LINK)) {
763 continue;
764 }
765 PktLinkConfig plg = (PktLinkConfig) lg;
766 if (plg.getDpid1() == getId()) {
767 addNeighborAtPort(new Dpid(plg.getDpid2()),
768 PortNumber.uint32(plg.getPort1()));
769 } else if (plg.getDpid2() == getId()) {
770 addNeighborAtPort(new Dpid(plg.getDpid1()),
771 PortNumber.uint32(plg.getPort2()));
772 }
773 }
774 }
775
776 private void addNeighborAtPort(Dpid neighborDpid, PortNumber portToNeighbor) {
777 /* Update NeighborToPort database */
778 if (neighbors.get(neighborDpid) != null) {
779 neighbors.get(neighborDpid).add(portToNeighbor);
780 } else {
781 Set<PortNumber> ports = new HashSet<PortNumber>();
782 ports.add(portToNeighbor);
783 neighbors.put(neighborDpid, ports);
784 }
785
786 /* Update portToNeighbors database */
787 if (portToNeighbors.get(portToNeighbor) == null)
788 portToNeighbors.put(portToNeighbor, neighborDpid);
789 }
790
791 private void getAllNodeSegmentIds(List<SwitchConfig> switchList) {
792 for (SwitchConfig sc : switchList) {
793 /* TODO: Do we need to check if the SwitchConfig is of
794 * type SegmentRouter?
795 */
796 if (sc.getDpid() == getId()) {
797 continue;
798 }
799 segmentIds.add(((SegmentRouterConfig) sc).getNodeSid());
800 }
801 log.debug("getAllNodeSegmentIds: at sw {} are {}",
802 getStringId(), segmentIds);
803 }
804
805 private boolean isSegmentIdSameAsNodeSegmentId(Dpid dpid, int sId) {
806 INetworkConfigService ncs = floodlightProvider.getNetworkConfigService();
807 SwitchConfigStatus scs = ncs.checkSwitchConfig(dpid);
808 if (scs.getConfigState() == NetworkConfigState.ACCEPT_ADD) {
809 return (((SegmentRouterConfig) scs.getSwitchConfig()).
810 getNodeSid() == sId);
811 } else {
812 // TODO: return false if router not allowed
813 return false;
814 }
815 }
816
817 private Set<Set<Dpid>> getAllNeighborSets(Set<Dpid> neighbors) {
818 List<Dpid> list = new ArrayList<Dpid>(neighbors);
819 Set<Set<Dpid>> sets = new HashSet<Set<Dpid>>();
820 /* get the number of elements in the neighbors */
821 int elements = list.size();
822 /* the number of members of a power set is 2^n
823 * including the empty set
824 */
825 int powerElements = (1 << elements);
826
827 /* run a binary counter for the number of power elements */
828 for (long i = 1; i < powerElements; i++) {
829 Set<Dpid> dpidSubSet = new HashSet<Dpid>();
830 for (int j = 0; j < elements; j++) {
831 if ((i >> j) % 2 == 1) {
832 dpidSubSet.add(list.get(j));
833 }
834 }
835 /* NOTE: Avoid any pairings of edge routers only
836 * at a backbone router */
837 boolean avoidEdgeRouterPairing = true;
838 if ((!isEdgeRouter) && (dpidSubSet.size() > 1)) {
839 for (Dpid dpid : dpidSubSet) {
840 if (!isEdgeRouter(dpid)) {
841 avoidEdgeRouterPairing = false;
842 break;
843 }
844 }
845 }
846 else
847 avoidEdgeRouterPairing = false;
848
849 if (!avoidEdgeRouterPairing)
850 sets.add(dpidSubSet);
851 }
852 return sets;
853 }
854
855 private void createGroupForANeighborSet(NeighborSet ns, int groupId) {
856 List<BucketInfo> buckets = new ArrayList<BucketInfo>();
857 for (Dpid d : ns.getDpids()) {
858 for (PortNumber sp : neighbors.get(d)) {
859 BucketInfo b = new BucketInfo(d,
860 MacAddress.of(srConfig.getRouterMac()),
861 getNeighborRouterMacAddress(d), sp,
862 ns.getEdgeLabel(), true, -1);
863 buckets.add(b);
864
865 /* Update Port Neighborset map */
866 ArrayList<NeighborSet> portNeighborSets =
867 portNeighborSetMap.get(sp);
868 if (portNeighborSets == null) {
869 portNeighborSets = new ArrayList<NeighborSet>();
870 portNeighborSets.add(ns);
871 portNeighborSetMap.put(sp, portNeighborSets);
872 }
873 else
874 portNeighborSets.add(ns);
875 }
876 }
877 EcmpInfo ecmpInfo = new EcmpInfo(groupId, OFGroupType.SELECT, buckets);
878 setEcmpGroup(ecmpInfo);
879 ecmpGroups.put(ns, ecmpInfo);
880 log.debug(
881 "createGroupForANeighborSet: Creating ecmp group {} in sw {} "
882 + "for neighbor set {} with: {}",
883 groupId, getStringId(), ns, ecmpInfo);
884 return;
885 }
886
887 /**
888 * createGroups creates ECMP groups for all ports on this router connected
889 * to other routers (in the OF network). The information for ports is
890 * gleaned from the configured links. If no links are configured no groups
891 * will be created, and it is up to the caller of the IOF13Switch API to
892 * create groups.
893 * <p>
894 * By default all ports connected to the same neighbor router will be part
895 * of the same ECMP group. In addition, groups will be created for all
896 * possible combinations of neighbor routers.
897 * <p>
898 * For example, consider this router (R0) connected to 3 neighbors (R1, R2,
899 * and R3). The following groups will be created in R0:
900 * <li>1) all ports to R1,
901 * <li>2) all ports to R2,
902 * <li>3) all ports to R3,
903 * <li>4) all ports to R1 and R2
904 * <li>5) all ports to R1 and R3
905 * <li>6) all ports to R2 and R3
906 * <li>7) all ports to R1, R2, and R3
907 */
908 private void createGroups() {
909
910 Set<Dpid> dpids = neighbors.keySet();
911 if (dpids == null || dpids.isEmpty()) {
912 return;
913 }
914 /* Create all possible Neighbor sets from this router
915 * NOTE: Avoid any pairings of edge routers only
916 */
917 Set<Set<Dpid>> powerSet = getAllNeighborSets(dpids);
918 log.debug("createGroups: The size of neighbor powerset for sw {} is {}",
919 getStringId(), powerSet.size());
920 Set<NeighborSet> nsSet = new HashSet<NeighborSet>();
921 for (Set<Dpid> combo : powerSet) {
922 if (combo.isEmpty())
923 continue;
924 if (isEdgeRouter && !segmentIds.isEmpty()) {
925 for (Integer sId : segmentIds) {
926 NeighborSet ns = new NeighborSet();
927 ns.addDpids(combo);
928 /* Check if the edge label being set is of the
929 * same node in the Neighbor set
930 */
931 if ((combo.size() != 1) ||
932 (!isSegmentIdSameAsNodeSegmentId(
933 combo.iterator().next(), sId))) {
934 ns.setEdgeLabel(sId);
935 }
936 nsSet.add(ns);
937 }
938 } else {
939 NeighborSet ns = new NeighborSet();
940 ns.addDpids(combo);
941 nsSet.add(ns);
942 }
943 }
944 log.debug("createGroups: The neighborset with label for sw {} is {}",
945 getStringId(), nsSet);
946
947 for (NeighborSet ns : nsSet) {
948 createGroupForANeighborSet(ns, groupid.incrementAndGet());
949 }
950 }
951
952 private class EcmpInfo {
953 int groupId;
954 OFGroupType groupType;
955 List<BucketInfo> buckets;
956
957 EcmpInfo(int gid, OFGroupType gType, List<BucketInfo> bucketInfos) {
958 groupId = gid;
959 groupType = gType;
960 buckets = bucketInfos;
961 }
962
963 @Override
964 public String toString() {
965 return "groupId: " + groupId + ", buckets: " + buckets;
966 }
967 }
968
969 private class BucketInfo {
970 Dpid neighborDpid;
971 MacAddress srcMac;
972 MacAddress dstMac;
973 PortNumber outport;
974 int groupNo;
975 int mplsLabel;
976 boolean bos;
977
978 BucketInfo(Dpid nDpid, MacAddress smac, MacAddress dmac,
979 PortNumber p, int label, boolean bos, int gotoGroupNo) {
980 neighborDpid = nDpid;
981 srcMac = smac;
982 dstMac = dmac;
983 outport = p;
984 mplsLabel = label;
985 this.bos = bos;
986 groupNo = gotoGroupNo;
987 }
988
989
990 @Override
991 public String toString() {
992 return " {neighborDpid: " + neighborDpid + ", dstMac: " + dstMac +
993 ", srcMac: " + srcMac + ", outport: " + outport +
994 ", groupNo: " + groupNo +
995 ", mplsLabel: " + mplsLabel + "}";
996 }
997 }
998
999 private void setEcmpGroup(EcmpInfo ecmpInfo) {
1000 List<OFMessage> msglist = new ArrayList<OFMessage>();
1001 OFGroup group = OFGroup.of(ecmpInfo.groupId);
1002
1003 List<OFBucket> buckets = new ArrayList<OFBucket>();
1004 for (BucketInfo b : ecmpInfo.buckets) {
1005 List<OFAction> actions = new ArrayList<OFAction>();
1006 if (b.dstMac != null) {
1007 OFOxmEthDst dmac = factory.oxms()
1008 .ethDst(b.dstMac);
1009 OFAction setDA = factory.actions().buildSetField()
1010 .setField(dmac).build();
1011 actions.add(setDA);
1012 }
1013 if (b.srcMac != null) {
1014 OFOxmEthSrc smac = factory.oxms()
1015 .ethSrc(b.srcMac);
1016 OFAction setSA = factory.actions().buildSetField()
1017 .setField(smac).build();
1018 actions.add(setSA);
1019 }
1020 if (b.outport != null) {
1021 OFAction outp = factory.actions().buildOutput()
1022 .setPort(OFPort.of(b.outport.shortValue()))
1023 .build();
1024 actions.add(outp);
1025 }
1026 if (b.mplsLabel != -1) {
1027 OFAction pushLabel = factory.actions().buildPushMpls()
1028 .setEthertype(EthType.MPLS_UNICAST).build();
1029 OFBooleanValue bosValue = null;
1030 if (b.bos)
1031 bosValue = OFBooleanValue.TRUE;
1032 else
1033 bosValue = OFBooleanValue.FALSE;
1034 OFOxmMplsBos bosX = factory.oxms()
1035 .mplsBos(bosValue);
1036 OFAction setBX = factory.actions().buildSetField()
1037 .setField(bosX).build();
1038 OFOxmMplsLabel lid = factory.oxms()
1039 .mplsLabel(U32.of(b.mplsLabel));
1040 OFAction setLabel = factory.actions().buildSetField()
1041 .setField(lid).build();
1042 OFAction copyTtl = factory.actions().copyTtlOut();
1043 OFAction decrTtl = factory.actions().decMplsTtl();
1044 actions.add(pushLabel);
1045 actions.add(setLabel);
1046 actions.add(setBX);
1047 actions.add(copyTtl);
1048 // decrement TTL only when the first MPLS label is pushed
1049 if (b.bos)
1050 actions.add(decrTtl);
1051 }
1052 if (b.groupNo > 0) {
1053 OFAction groupTo = factory.actions().buildGroup()
1054 .setGroup(OFGroup.of(b.groupNo))
1055 .build();
1056 actions.add(groupTo);
1057 }
1058 OFBucket.Builder bldr = factory.buildBucket();
1059 bldr.setActions(actions);
1060 if (ecmpInfo.groupType == OFGroupType.SELECT)
1061 bldr.setWeight(1);
1062 OFBucket ofb = bldr.build();
1063 buckets.add(ofb);
1064 }
1065
1066 OFMessage gm = factory.buildGroupAdd()
1067 .setGroup(group)
1068 .setBuckets(buckets)
1069 .setGroupType(ecmpInfo.groupType)
1070 .setXid(getNextTransactionId())
1071 .build();
1072 msglist.add(gm);
1073 try {
1074 write(msglist);
1075 } catch (IOException e) {
1076 // TODO Auto-generated catch block
1077 e.printStackTrace();
1078 }
1079 }
1080
1081 private void deleteGroup(EcmpInfo groupInfo) {
1082
1083 List<OFMessage> msglist = new ArrayList<OFMessage>();
1084 OFGroup group = OFGroup.of(groupInfo.groupId);
1085
1086 OFMessage gm = factory.buildGroupDelete()
1087 .setGroup(group)
1088 // .setGroupType(groupInfo.groupType) /* Due to a bug in CPqD
1089 // switch */
1090 .setGroupType(OFGroupType.SELECT)
1091 .setXid(getNextTransactionId())
1092 .build();
1093 msglist.add(gm);
1094 try {
1095 write(msglist);
1096 } catch (IOException e) {
1097 // TODO Auto-generated catch block
1098 e.printStackTrace();
1099 }
1100 }
1101
1102 private void modifyEcmpGroup(EcmpInfo ecmpInfo) {
1103 List<OFMessage> msglist = new ArrayList<OFMessage>();
1104 OFGroup group = OFGroup.of(ecmpInfo.groupId);
1105
1106 List<OFBucket> buckets = new ArrayList<OFBucket>();
1107 for (BucketInfo b : ecmpInfo.buckets) {
1108 OFOxmEthDst dmac = factory.oxms()
1109 .ethDst(b.dstMac);
1110 OFAction setDA = factory.actions().buildSetField()
1111 .setField(dmac).build();
1112 OFOxmEthSrc smac = factory.oxms()
1113 .ethSrc(b.srcMac);
1114 OFAction setSA = factory.actions().buildSetField()
1115 .setField(smac).build();
1116 OFAction outp = factory.actions().buildOutput()
1117 .setPort(OFPort.of(b.outport.shortValue()))
1118 .build();
1119 List<OFAction> actions = new ArrayList<OFAction>();
1120 actions.add(setSA);
1121 actions.add(setDA);
1122 actions.add(outp);
1123 if (b.mplsLabel != -1) {
1124 OFAction pushLabel = factory.actions().buildPushMpls()
1125 .setEthertype(EthType.MPLS_UNICAST).build();
1126 OFOxmMplsBos bosX = factory.oxms()
1127 .mplsBos(OFBooleanValue.TRUE);
1128 OFAction setBX = factory.actions().buildSetField()
1129 .setField(bosX).build();
1130 OFOxmMplsLabel lid = factory.oxms()
1131 .mplsLabel(U32.of(b.mplsLabel));
1132 OFAction setLabel = factory.actions().buildSetField()
1133 .setField(lid).build();
1134 OFAction copyTtl = factory.actions().copyTtlOut();
1135 OFAction decrTtl = factory.actions().decMplsTtl();
1136 actions.add(pushLabel);
1137 actions.add(setLabel);
1138 actions.add(setBX);
1139 actions.add(copyTtl);
1140 actions.add(decrTtl);
1141 }
1142 OFBucket ofb = factory.buildBucket()
1143 .setWeight(1)
1144 .setActions(actions)
1145 .build();
1146 buckets.add(ofb);
1147 }
1148
1149 OFMessage gm = factory.buildGroupModify()
1150 .setGroup(group)
1151 .setBuckets(buckets)
1152 .setGroupType(OFGroupType.SELECT)
1153 .setXid(getNextTransactionId())
1154 .build();
1155 msglist.add(gm);
1156 try {
1157 write(msglist);
1158 } catch (IOException e) {
1159 // TODO Auto-generated catch block
1160 e.printStackTrace();
1161 }
1162 }
1163
1164 private void verifyGroups() throws IOException {
1165 sendGroupDescRequest();
1166 }
1167
1168 private void sendGroupDescRequest() throws IOException {
1169 OFMessage gdr = factory.buildGroupDescStatsRequest()
1170 .setXid(getNextTransactionId())
1171 .build();
1172 write(gdr, null);
1173 }
1174
1175 private void assignAdjacencyLabels() {
1176 List<AdjacencySid> autogenAdjSids = new ArrayList<AdjacencySid>();
1177 publishAttributes = new HashMap<String, String>();
1178 for (OFPortDesc p : getPorts()) {
1179 int pnum = p.getPortNo().getPortNumber();
1180
1181 if (U32.ofRaw(pnum).compareTo(U32.ofRaw(OFPort.MAX.getPortNumber())) >= 1) {
1182 continue;
1183 }
1184 // create unique adj-sid assuming that operator only
1185 // enters adjSids for multiple-ports and only in the range
1186 // 1-10k XXX make sure that happens
1187 int adjSid = srConfig.getNodeSid() * 1000 + pnum;
1188 AdjacencySid as = new AdjacencySid(adjSid,
1189 Collections.singletonList(pnum));
1190 autogenAdjSids.add(as);
1191 }
1192 ObjectMapper mapper = new ObjectMapper();
1193 try {
1194 publishAttributes.put("autogenAdjSids",
1195 mapper.writeValueAsString(autogenAdjSids));
1196 } catch (IOException e1) {
1197 log.error("Error while writing adjacency labels: {}", e1.getCause());
1198 }
1199
1200 try {
1201 nextDriverState();
1202 } catch (IOException e) {
1203 // TODO Auto-generated catch block
1204 e.printStackTrace();
1205 }
1206 }
1207
1208 private OFAction getOFAction(Action action) {
1209 OFAction ofAction = null;
1210 if (action instanceof OutputAction) {
1211 OutputAction outputAction = (OutputAction) action;
1212 OFPort port = OFPort.of((int) outputAction.getPortNumber().value());
1213 ofAction = factory.actions().output(port, Short.MAX_VALUE);
1214 } else if (action instanceof ModifyDstMacAction) {
1215 long dstMac = ((ModifyDstMacAction) action).getDstMac().toLong();
1216 OFOxmEthDst dmac = factory.oxms()
1217 .ethDst(MacAddress.of(dstMac));
1218 ofAction = factory.actions().buildSetField()
1219 .setField(dmac).build();
1220 } else if (action instanceof ModifySrcMacAction) {
1221 long srcMac = ((ModifySrcMacAction) action).getSrcMac().toLong();
1222 OFOxmEthSrc smac = factory.oxms()
1223 .ethSrc(MacAddress.of(srcMac));
1224 ofAction = factory.actions().buildSetField()
1225 .setField(smac).build();
1226 } else if (action instanceof PushMplsAction) {
1227 ofAction = factory.actions().pushMpls(EthType.MPLS_UNICAST);
1228 } else if (action instanceof SetMplsIdAction) {
1229 int labelid = ((SetMplsIdAction) action).getMplsId();
1230 OFOxmMplsLabel lid = factory.oxms()
1231 .mplsLabel(U32.of(labelid));
1232 ofAction = factory.actions().buildSetField()
1233 .setField(lid).build();
1234 } else if (action instanceof SetMplsBosAction) {
1235 OFBooleanValue val = OFBooleanValue.of(
1236 ((SetMplsBosAction) action).isSet());
1237 OFOxmMplsBos bos = factory.oxms().mplsBos(val);
1238 OFAction setBos = factory.actions().buildSetField()
1239 .setField(bos).build();
1240 } else if (action instanceof PopMplsAction) {
1241 EthType ethertype = ((PopMplsAction) action).getEthType();
1242 ofAction = factory.actions().popMpls(ethertype);
1243 } else if (action instanceof GroupAction) {
1244 int gid = -1;
1245 GroupAction ga = (GroupAction)action;
1246 if (ga.getGroupId() > 0) {
1247 gid = ga.getGroupId();
1248 }
1249 else {
1250 NeighborSet ns = ((GroupAction) action).getDpids();
1251 EcmpInfo ei = ecmpGroups.get(ns);
1252 if (ei == null) {
1253 log.debug("Unable to find ecmp group for neighbors {} at "
1254 + "switch {} and hence creating it", ns, getStringId());
1255 createGroupForANeighborSet(ns, groupid.incrementAndGet());
1256 ei = ecmpGroups.get(ns);
1257 }
1258 gid = ei.groupId;
1259 }
1260 ofAction = factory.actions().buildGroup()
1261 .setGroup(OFGroup.of(gid))
1262 .build();
1263 } else if (action instanceof DecNwTtlAction) {
1264 ofAction = factory.actions().decNwTtl();
1265 } else if (action instanceof DecMplsTtlAction) {
1266 ofAction = factory.actions().decMplsTtl();
1267 } else if (action instanceof CopyTtlInAction) {
1268 ofAction = factory.actions().copyTtlIn();
1269 } else if (action instanceof CopyTtlOutAction) {
1270 ofAction = factory.actions().copyTtlOut();
1271 } else if (action instanceof SetDAAction) {
1272 OFOxmEthDst dmac = factory.oxms()
1273 .ethDst(((SetDAAction)action).getAddress());
1274 ofAction = factory.actions().buildSetField()
1275 .setField(dmac).build();
1276 } else if (action instanceof SetSAAction) {
1277 OFOxmEthSrc smac = factory.oxms()
1278 .ethSrc(((SetSAAction)action).getAddress());
1279 ofAction = factory.actions().buildSetField()
1280 .setField(smac).build();
1281 } else {
1282 log.warn("Unsupported Action type: {}", action.getClass().getName());
1283 return null;
1284 }
1285
1286 return ofAction;
1287 }
1288
1289 private OFMessage getIpEntry(MatchActionOperationEntry mao) {
1290 MatchAction ma = mao.getTarget();
1291 Operator op = mao.getOperator();
1292 Ipv4Match ipm = (Ipv4Match) ma.getMatch();
1293
1294 // set match
1295 IPv4Net ipdst = ipm.getDestination();
1296 OFOxmEthType ethTypeIp = factory.oxms()
1297 .ethType(EthType.IPv4);
1298 OFOxmIpv4DstMasked ipPrefix = factory.oxms()
1299 .ipv4DstMasked(
1300 IPv4Address.of(ipdst.address().value()),
1301 IPv4Address.ofCidrMaskLength(ipdst.prefixLen())
1302 );
1303 OFOxmList oxmList = OFOxmList.of(ethTypeIp, ipPrefix);
1304 OFMatchV3 match = factory.buildMatchV3()
1305 .setOxmList(oxmList).build();
1306
1307 // set actions
1308 List<OFAction> writeActions = new ArrayList<OFAction>();
1309 for (Action action : ma.getActions()) {
1310 OFAction ofAction = getOFAction(action);
1311 if (ofAction != null) {
1312 writeActions.add(ofAction);
1313 }
1314 }
1315
1316 // set instructions
1317 OFInstruction writeInstr = factory.instructions().buildWriteActions()
1318 .setActions(writeActions).build();
1319 OFInstruction gotoInstr = factory.instructions().buildGotoTable()
1320 .setTableId(TableId.of(TABLE_ACL)).build();
1321 List<OFInstruction> instructions = new ArrayList<OFInstruction>();
1322 instructions.add(writeInstr);
1323 instructions.add(gotoInstr);
1324
1325 // set flow priority to emulate longest prefix match
1326 int priority = ipdst.prefixLen() * PRIORITY_MULTIPLIER;
1327 if (ipdst.prefixLen() == (short) 32) {
1328 priority = MAX_PRIORITY;
1329 }
1330
1331 // set flow-mod
1332 OFFlowMod.Builder fmBuilder = null;
1333 switch (op) {
1334 case ADD:
1335 fmBuilder = factory.buildFlowAdd();
1336 break;
1337 case REMOVE:
1338 fmBuilder = factory.buildFlowDeleteStrict();
1339 break;
1340 case MODIFY: // TODO
1341 fmBuilder = factory.buildFlowModifyStrict();
1342 break;
1343 default:
1344 log.warn("Unsupported MatchAction Operator: {}", op);
1345 return null;
1346 }
1347 OFMessage ipFlow = fmBuilder
1348 .setTableId(TableId.of(TABLE_IPv4_UNICAST))
1349 .setMatch(match)
1350 .setInstructions(instructions)
1351 .setPriority(priority)
1352 .setBufferId(OFBufferId.NO_BUFFER)
1353 .setIdleTimeout(0)
1354 .setHardTimeout(0)
1355 .setXid(getNextTransactionId())
1356 .build();
1357 log.debug("{} ip-rule {}-{} in sw {}",
1358 (op == MatchActionOperations.Operator.ADD) ? "Adding" : "Deleting",
1359 match, writeActions,
1360 getStringId());
1361 return ipFlow;
1362 }
1363
1364 private OFMessage getMplsEntry(MatchActionOperationEntry mao) {
1365 MatchAction ma = mao.getTarget();
1366 Operator op = mao.getOperator();
1367 MplsMatch mplsm = (MplsMatch) ma.getMatch();
1368
1369 // set match
1370 OFOxmEthType ethTypeMpls = factory.oxms()
1371 .ethType(EthType.MPLS_UNICAST);
1372 OFOxmMplsLabel labelid = factory.oxms()
1373 .mplsLabel(U32.of(mplsm.getMplsLabel()));
1374 OFOxmMplsBos bos = factory.oxms()
1375 .mplsBos(OFBooleanValue.of(mplsm.isBos()));
1376 OFOxmList oxmList = OFOxmList.of(ethTypeMpls, labelid, bos);
1377 OFMatchV3 matchlabel = factory.buildMatchV3()
1378 .setOxmList(oxmList).build();
1379
1380 // set actions
1381 List<OFAction> writeActions = new ArrayList<OFAction>();
1382 for (Action action : ma.getActions()) {
1383 OFAction ofAction = getOFAction(action);
1384 if (ofAction != null) {
1385 writeActions.add(ofAction);
1386 }
1387 }
1388
1389 // set instructions
1390 OFInstruction writeInstr = factory.instructions().buildWriteActions()
1391 .setActions(writeActions).build();
1392 OFInstruction gotoInstr = factory.instructions().buildGotoTable()
1393 .setTableId(TableId.of(TABLE_ACL)).build();
1394 List<OFInstruction> instructions = new ArrayList<OFInstruction>();
1395 instructions.add(writeInstr);
1396 instructions.add(gotoInstr);
1397
1398 // set flow-mod
1399 OFFlowMod.Builder fmBuilder = null;
1400 switch (op) {
1401 case ADD:
1402 fmBuilder = factory.buildFlowAdd();
1403 break;
1404 case REMOVE:
1405 fmBuilder = factory.buildFlowDeleteStrict();
1406 break;
1407 case MODIFY: // TODO
1408 fmBuilder = factory.buildFlowModifyStrict();
1409 break;
1410 default:
1411 log.warn("Unsupported MatchAction Operator: {}", op);
1412 return null;
1413 }
1414
1415 OFMessage mplsFlow = fmBuilder
1416 .setTableId(TableId.of(TABLE_MPLS))
1417 .setMatch(matchlabel)
1418 .setInstructions(instructions)
1419 .setPriority(MAX_PRIORITY) // exact match and exclusive
1420 .setBufferId(OFBufferId.NO_BUFFER)
1421 .setIdleTimeout(0)
1422 .setHardTimeout(0)
1423 .setXid(getNextTransactionId())
1424 .build();
1425 log.debug("{} mpls-rule {}-{} in sw {}",
1426 (op == MatchActionOperations.Operator.ADD) ? "Adding" : "Deleting",
1427 matchlabel, writeActions,
1428 getStringId());
1429 return mplsFlow;
1430 }
1431
1432 private OFMessage getAclEntry(MatchActionOperationEntry mao) {
1433 MatchAction ma = mao.getTarget();
1434 Operator op = mao.getOperator();
1435 PacketMatch packetMatch = (PacketMatch) ma.getMatch();
1436 Builder matchBuilder = factory.buildMatch();
1437
1438 // set match
1439 int inport = 0;
1440 if (ma.getSwitchPort() != null) {
1441 inport = (int) ma.getSwitchPort().getPortNumber().value();
1442 }
1443 final MACAddress srcMac = packetMatch.getSrcMacAddress();
1444 final MACAddress dstMac = packetMatch.getDstMacAddress();
1445 final Short etherType = packetMatch.getEtherType();
1446 final IPv4Net srcIp = packetMatch.getSrcIpAddress();
1447 final IPv4Net dstIp = packetMatch.getDstIpAddress();
1448 final Byte ipProto = packetMatch.getIpProtocolNumber();
1449 final Short srcTcpPort = packetMatch.getSrcTcpPortNumber();
1450 final Short dstTcpPort = packetMatch.getDstTcpPortNumber();
1451 if (inport > 0) {
1452 matchBuilder.setExact(MatchField.IN_PORT,
1453 OFPort.of(inport));
1454 }
1455 if (srcMac != null) {
1456 matchBuilder.setExact(MatchField.ETH_SRC, MacAddress.of(srcMac.toLong()));
1457 }
1458 if (dstMac != null) {
1459 matchBuilder.setExact(MatchField.ETH_DST, MacAddress.of(dstMac.toLong()));
1460 }
1461 if (etherType != null) {
1462 matchBuilder.setExact(MatchField.ETH_TYPE, EthType.of(etherType));
1463 }
1464 if (srcIp != null) {
1465 matchBuilder.setMasked(MatchField.IPV4_SRC,
1466 IPv4Address.of(srcIp.address().value())
1467 .withMaskOfLength(srcIp.prefixLen()));
1468 }
1469 if (dstIp != null) {
1470 matchBuilder.setMasked(MatchField.IPV4_DST,
1471 IPv4Address.of(dstIp.address().value())
1472 .withMaskOfLength(dstIp.prefixLen()));
1473 }
1474 if (ipProto != null) {
1475 matchBuilder.setExact(MatchField.IP_PROTO, IpProtocol.of(ipProto));
1476 }
1477 if (srcTcpPort != null) {
1478 matchBuilder.setExact(MatchField.TCP_SRC, TransportPort.of(srcTcpPort));
1479 }
1480 if (dstTcpPort != null) {
1481 matchBuilder.setExact(MatchField.TCP_DST, TransportPort.of(dstTcpPort));
1482 }
1483
1484 // set actions
1485 List<OFAction> writeActions = new ArrayList<OFAction>();
1486 for (Action action : ma.getActions()) {
1487 OFAction ofAction = getOFAction(action);
1488 if (ofAction != null) {
1489 writeActions.add(ofAction);
1490 }
1491 }
1492
1493 // set instructions
1494 OFInstruction clearInstr = factory.instructions().clearActions();
1495 OFInstruction writeInstr = factory.instructions().buildWriteActions()
1496 .setActions(writeActions).build();
1497 List<OFInstruction> instructions = new ArrayList<OFInstruction>();
1498 instructions.add(clearInstr);
1499 instructions.add(writeInstr);
1500
1501 // set flow-mod
1502 OFFlowMod.Builder fmBuilder = null;
1503 switch (op) {
1504 case ADD:
1505 fmBuilder = factory.buildFlowAdd();
1506 break;
1507 case REMOVE:
1508 fmBuilder = factory.buildFlowDeleteStrict();
1509 break;
1510 case MODIFY: // TODO
1511 fmBuilder = factory.buildFlowModifyStrict();
1512 break;
1513 default:
1514 log.warn("Unsupported MatchAction Operator: {}", op);
1515 return null;
1516 }
1517
1518 OFMessage aclFlow = fmBuilder
1519 .setTableId(TableId.of(TABLE_ACL))
1520 .setMatch(matchBuilder.build())
1521 .setInstructions(instructions)
1522 .setPriority(ma.getPriority()) // exact match and exclusive
1523 .setBufferId(OFBufferId.NO_BUFFER)
1524 .setIdleTimeout(0)
1525 .setHardTimeout(0)
1526 .setXid(getNextTransactionId())
1527 .build();
1528
1529 return aclFlow;
1530 }
1531
1532 // *****************************
1533 // IOF13Switch
1534 // *****************************
1535
1536 @Override
1537 public void pushFlow(MatchActionOperationEntry matchActionOp) throws IOException {
1538 OFMessage ofm = getFlow(matchActionOp);
1539 if (ofm != null) {
1540 write(Collections.singletonList(ofm));
1541 }
1542 }
1543
1544 private OFMessage getFlow(MatchActionOperationEntry matchActionOp) {
1545 final MatchAction matchAction = matchActionOp.getTarget();
1546 final Match match = matchAction.getMatch();
1547 if (match instanceof Ipv4Match) {
1548 return getIpEntry(matchActionOp);
1549 } else if (match instanceof MplsMatch) {
1550 return getMplsEntry(matchActionOp);
1551 } else if (match instanceof PacketMatch) {
1552 return getAclEntry(matchActionOp);
1553 } else {
1554 log.error("Unknown match type {} pushed to switch {}", match,
1555 getStringId());
1556 }
1557 return null;
1558 }
1559
1560 @Override
1561 public void pushFlows(Collection<MatchActionOperationEntry> matchActionOps)
1562 throws IOException {
1563 List<OFMessage> flowMods = new ArrayList<OFMessage>();
1564 for (MatchActionOperationEntry matchActionOp : matchActionOps) {
1565 OFMessage ofm = getFlow(matchActionOp);
1566 if (ofm != null) {
1567 flowMods.add(ofm);
1568 }
1569 }
1570 write(flowMods);
1571 }
1572
1573 @Override
1574 public int getEcmpGroupId(NeighborSet ns) {
1575 EcmpInfo ei = ecmpGroups.get(ns);
1576 if (ei == null) {
1577 return -1;
1578 } else {
1579 return ei.groupId;
1580 }
1581 }
1582
1583 @Override
1584 public TableId getTableId(String tableType) {
1585 tableType = tableType.toLowerCase();
1586 if (tableType.contentEquals("ip")) {
1587 return TableId.of(OFSwitchImplSpringOpenTTP.TABLE_IPv4_UNICAST);
1588 }
1589 else if (tableType.contentEquals("mpls")) {
1590 return TableId.of(OFSwitchImplSpringOpenTTP.TABLE_MPLS);
1591 }
1592 else if (tableType.contentEquals("acl")) {
1593 return TableId.of(OFSwitchImplSpringOpenTTP.TABLE_ACL);
1594 }
1595 else {
1596 log.warn("Invalid tableType: {}", tableType);
1597 return null;
1598 }
1599 }
1600
1601 private EcmpInfo createIndirectGroup(int groupId, MacAddress srcMac,
1602 MacAddress dstMac, PortNumber outPort, int gotoGroupNo,
1603 int mplsLabel, boolean bos) {
1604 List<BucketInfo> buckets = new ArrayList<BucketInfo>();
1605 BucketInfo b = new BucketInfo(null, srcMac, dstMac, outPort,
1606 mplsLabel, bos, gotoGroupNo);
1607 buckets.add(b);
1608
1609 EcmpInfo ecmpInfo = new EcmpInfo(groupId, OFGroupType.INDIRECT, buckets);
1610 setEcmpGroup(ecmpInfo);
1611 log.debug(
1612 "createIndirectGroup: Creating indirect group {} in sw {} "
1613 + "with: {}", groupId, getStringId(), ecmpInfo);
1614 return ecmpInfo;
1615 }
1616
1617 private EcmpInfo createInnermostLabelGroup(int innermostGroupId,
1618 List<PortNumber> ports, int mplsLabel, boolean bos,
1619 HashMap<PortNumber, Integer> lastSetOfGroupIds) {
1620 List<BucketInfo> buckets = new ArrayList<BucketInfo>();
1621 for (PortNumber sp : ports) {
1622 Dpid neighborDpid = portToNeighbors.get(sp);
1623 BucketInfo b = new BucketInfo(neighborDpid,
1624 MacAddress.of(srConfig.getRouterMac()),
1625 getNeighborRouterMacAddress(neighborDpid), null,
1626 mplsLabel, bos,
1627 lastSetOfGroupIds.get(sp));
1628 buckets.add(b);
1629 }
1630 EcmpInfo ecmpInfo = new EcmpInfo(innermostGroupId,
1631 OFGroupType.SELECT, buckets);
1632 setEcmpGroup(ecmpInfo);
1633 log.debug(
1634 "createInnermostLabelGroup: Creating select group {} in sw {} "
1635 + "with: {}", innermostGroupId, getStringId(), ecmpInfo);
1636 return ecmpInfo;
1637 }
1638 @Override
1639 /**
1640 * Create a group chain with the specified label stack for a given set of
1641 * ports. This API can be used by user to create groups for a tunnel based
1642 * policy routing scenario. NOTE: This API can not be used if a group to be
1643 * created with different label stacks for each port in the given set of
1644 * ports. Use XXX API for this purpose
1645 *
1646 * @param labelStack list of router segment Ids to be pushed. Can be empty.
1647 * labelStack is processed from left to right with leftmost
1648 * representing the outermost label and rightmost representing
1649 * innermost label to be pushed
1650 * @param ports List of ports on this switch to get to the first router in
1651 * the labelStack
1652 * @return group identifier
1653 */
1654 public int createGroup(List<Integer> labelStack, List<PortNumber> ports) {
1655
1656 if ((ports == null) ||
1657 ((labelStack != null) && (labelStack.size() > 3))) {
1658 log.warn("createGroup in sw {} with wrong input parameters", getStringId());
1659 }
1660 log.debug("createGroup in sw {} with labelStack {} and ports {}",
1661 getStringId(), labelStack, ports);
1662
1663 HashMap<PortNumber, Integer> lastSetOfGroupIds =
1664 new HashMap<PortNumber, Integer>();
1665 int innermostGroupId = -1;
1666 /* If it is empty label stack or label stack with only one label,
1667 * Create a single select group with buckets for each port in the list
1668 * of specified ports and specified label if any and return the
1669 * created group id
1670 */
1671 if (labelStack.size() < 2) {
1672 int curLabel = -1;
1673 boolean bos = false;
1674 if (labelStack.size()==1) {
1675 curLabel = labelStack.get(0).intValue();
1676 bos = true;
1677 }
1678
1679 List<BucketInfo> buckets = new ArrayList<BucketInfo>();
1680 for (PortNumber sp : ports) {
1681 Dpid neighborDpid = portToNeighbors.get(sp);
1682 BucketInfo b = new BucketInfo(neighborDpid,
1683 MacAddress.of(srConfig.getRouterMac()),
1684 getNeighborRouterMacAddress(neighborDpid),
1685 sp, curLabel, bos, -1);
1686 buckets.add(b);
1687 }
1688 innermostGroupId = groupid.incrementAndGet();
1689 EcmpInfo ecmpInfo = new EcmpInfo(innermostGroupId,
1690 OFGroupType.SELECT, buckets);
1691 setEcmpGroup(ecmpInfo);
1692 userDefinedGroups.put(innermostGroupId, ecmpInfo);
1693 return innermostGroupId;
1694 }
1695
1696 /* If the label stack has two or more labels, then a chain of groups
1697 * to be created.
1698 * Step1: Create for each port in the list of specified ports,
1699 * an indirect group with the outermost label. These groups are the
1700 * end of the chain and hence don't reference to any other groups
1701 * Step2: Create for each port in the list of specified ports, an
1702 * indirect group with middle labels (if any). These groups will
1703 * have references to group ids that are created in the previous
1704 * iteration for the same ports
1705 * Step3: Create a select group with all ports and innermost label.
1706 * This group will have references to indirect group ids that are
1707 * created in the previous iteration for the same ports
1708 */
1709 for (int i = 0; i < labelStack.size(); i++) {
1710 for (PortNumber sp : ports) {
1711 if (i == 0) {
1712 /* Outermost label processing */
1713 int currGroupId = groupid.incrementAndGet();
1714 EcmpInfo indirectGroup = createIndirectGroup(currGroupId,
1715 null, null, sp, -1,
1716 labelStack.get(i).intValue(), false);
1717 lastSetOfGroupIds.put(sp, currGroupId);
1718 userDefinedGroups.put(currGroupId, indirectGroup);
1719 }
1720 else if (i == (labelStack.size() - 1)) {
1721 /* Innermost label processing */
1722 innermostGroupId = groupid.incrementAndGet();
1723 EcmpInfo topLevelGroup = createInnermostLabelGroup(
1724 innermostGroupId,
1725 ports,
1726 labelStack.get(i).intValue(), true,
1727 lastSetOfGroupIds);
1728 userDefinedGroups.put(
1729 innermostGroupId, topLevelGroup);
1730 break;
1731 }
1732 else {
1733 /* Middle label processing */
1734 int currGroupId = groupid.incrementAndGet();
1735 EcmpInfo indirectGroup = createIndirectGroup(currGroupId,
1736 null, null, null,
1737 lastSetOfGroupIds.get(sp),
1738 labelStack.get(i).intValue(), false);
1739 /* Overwrite with this iteration's group IDs */
1740 lastSetOfGroupIds.put(sp, currGroupId);
1741 userDefinedGroups.put(currGroupId, indirectGroup);
1742 }
1743 }
1744 }
1745 log.debug("createGroup in sw{}: group created with innermost group id {}",
1746 getStringId(), innermostGroupId);
1747 return innermostGroupId;
1748 }
1749
1750 /**
1751 * Remove the specified group
1752 *
1753 * @param groupId group identifier
1754 * @return success/fail
1755 */
1756 public boolean removeGroup(int groupId) {
1757 EcmpInfo group = userDefinedGroups.get(groupId);
1758 if (group == null) {
1759 log.warn("removeGroup in sw {}: with invalid group id", getStringId());
1760 return false;
1761 }
1762 deleteGroup(group);
1763 for (BucketInfo bucket : group.buckets) {
1764 int currGroupIdToBeDeleted = bucket.groupNo;
1765 while (currGroupIdToBeDeleted != -1) {
1766 /* Assuming indirect groups with single buckets */
1767 int nextGroupIdToBeDeleted =
1768 userDefinedGroups.get(currGroupIdToBeDeleted).
1769 buckets.get(0).groupNo;
1770 EcmpInfo groupToBeDeleted =
1771 userDefinedGroups.get(currGroupIdToBeDeleted);
1772 deleteGroup(groupToBeDeleted);
1773 userDefinedGroups.remove(currGroupIdToBeDeleted);
1774 currGroupIdToBeDeleted = nextGroupIdToBeDeleted;
1775 }
1776 }
1777
1778 userDefinedGroups.remove(groupId);
1779 log.debug("removeGroup in sw {}: removed group with group id {}",
1780 getStringId(), groupId);
1781 return true;
1782 }
1783
1784 @Override
1785 public Map<String, String> getPublishAttributes() {
1786 return publishAttributes;
1787 }
1788
1789 // *****************************
1790 // Unused
1791 // *****************************
1792
1793 @SuppressWarnings("unused")
1794 private void setAsyncConfig() throws IOException {
1795 List<OFMessage> msglist = new ArrayList<OFMessage>(3);
1796 OFMessage setAC = null;
1797
1798 if (role == Role.MASTER) {
1799 setAC = factory.buildAsyncSet()
1800 .setFlowRemovedMaskEqualMaster(SET_FLOW_REMOVED_MASK_MASTER)
1801 .setPacketInMaskEqualMaster(SET_PACKET_IN_MASK_MASTER)
1802 .setPortStatusMaskEqualMaster(SET_PORT_STATUS_MASK_MASTER)
1803 .setFlowRemovedMaskSlave(SET_ALL_SLAVE)
1804 .setPacketInMaskSlave(SET_ALL_SLAVE)
1805 .setPortStatusMaskSlave(SET_ALL_SLAVE)
1806 .setXid(getNextTransactionId())
1807 .build();
1808 } else if (role == Role.EQUAL) {
1809 setAC = factory.buildAsyncSet()
1810 .setFlowRemovedMaskEqualMaster(SET_FLOW_REMOVED_MASK_EQUAL)
1811 .setPacketInMaskEqualMaster(SET_PACKET_IN_MASK_EQUAL)
1812 .setPortStatusMaskEqualMaster(SET_PORT_STATUS_MASK_EQUAL)
1813 .setFlowRemovedMaskSlave(SET_ALL_SLAVE)
1814 .setPacketInMaskSlave(SET_ALL_SLAVE)
1815 .setPortStatusMaskSlave(SET_ALL_SLAVE)
1816 .setXid(getNextTransactionId())
1817 .build();
1818 }
1819 msglist.add(setAC);
1820
1821 OFMessage br = factory.buildBarrierRequest()
1822 .setXid(getNextTransactionId())
1823 .build();
1824 msglist.add(br);
1825
1826 OFMessage getAC = factory.buildAsyncGetRequest()
1827 .setXid(getNextTransactionId())
1828 .build();
1829 msglist.add(getAC);
1830
1831 write(msglist);
1832 }
1833
1834 @SuppressWarnings("unused")
1835 private void decodeAsyncGetReply(OFAsyncGetReply rep) {
1836 long frm = rep.getFlowRemovedMaskEqualMaster();
1837 long frs = rep.getFlowRemovedMaskSlave();
1838 long pim = rep.getPacketInMaskEqualMaster();
1839 long pis = rep.getPacketInMaskSlave();
1840 long psm = rep.getPortStatusMaskEqualMaster();
1841 long pss = rep.getPortStatusMaskSlave();
1842
1843 if (role == Role.MASTER || role == Role.EQUAL) { // should separate
1844 log.info("FRM:{}", HexString.toHexString((frm & TEST_FLOW_REMOVED_MASK)));
1845 log.info("PIM:{}", HexString.toHexString((pim & TEST_PACKET_IN_MASK)));
1846 log.info("PSM:{}", HexString.toHexString((psm & TEST_PORT_STATUS_MASK)));
1847 }
1848
1849 }
1850
1851 @SuppressWarnings("unused")
1852 private void getTableFeatures() throws IOException {
1853 OFMessage gtf = factory.buildTableFeaturesStatsRequest()
1854 .setXid(getNextTransactionId())
1855 .build();
1856 write(gtf, null);
1857 }
1858
1859 @SuppressWarnings("unused")
1860 private void sendGroupFeaturesRequest() throws IOException {
1861 OFMessage gfr = factory.buildGroupFeaturesStatsRequest()
1862 .setXid(getNextTransactionId())
1863 .build();
1864 write(gfr, null);
1865 }
1866
1867 private void processGroupFeatures(OFGroupFeaturesStatsReply gfsr) {
1868 log.info("Sw: {} Group Features {}", getStringId(), gfsr);
1869 }
1870
1871 @SuppressWarnings("unused")
1872 private void testMultipleLabels() {
1873 if (getId() == 1) {
1874 List<OFMessage> msglist = new ArrayList<OFMessage>();
1875
1876 // first all the indirect groups
1877
1878 // the group to switch 2 with outer label
1879 OFGroup g1 = OFGroup.of(201);
1880 OFOxmEthDst dmac1 = factory.oxms().ethDst(MacAddress.of("00:00:02:02:02:80"));
1881 OFAction push1 = factory.actions().pushMpls(EthType.MPLS_UNICAST);
1882 OFOxmMplsLabel lid1 = factory.oxms()
1883 .mplsLabel(U32.of(105)); // outer label
1884 OFAction setMpls1 = factory.actions().buildSetField()
1885 .setField(lid1).build();
1886 OFOxmMplsBos bos1 = factory.oxms()
1887 .mplsBos(OFBooleanValue.FALSE);
1888 OFAction setB1 = factory.actions().buildSetField()
1889 .setField(bos1).build();
1890 OFAction setDA1 = factory.actions().buildSetField()
1891 .setField(dmac1).build();
1892 OFAction outp1 = factory.actions().buildOutput()
1893 .setPort(OFPort.of(2))
1894 .build();
1895 List<OFAction> a1 = new ArrayList<OFAction>();
1896 a1.add(push1);
1897 a1.add(setMpls1);
1898 a1.add(setB1);
1899 a1.add(setDA1);
1900 a1.add(outp1);
1901 OFBucket b1 = factory.buildBucket()
1902 .setActions(a1)
1903 .build();
1904 OFMessage gm1 = factory.buildGroupAdd()
1905 .setGroup(g1)
1906 .setBuckets(Collections.singletonList(b1))
1907 .setGroupType(OFGroupType.INDIRECT)
1908 .setXid(getNextTransactionId())
1909 .build();
1910 msglist.add(gm1);
1911
1912 // the group to switch 3 with outer label
1913 OFGroup g2 = OFGroup.of(301);
1914 OFOxmEthDst dmac2 = factory.oxms().ethDst(MacAddress.of("00:00:03:03:03:80"));
1915 OFAction push2 = factory.actions().pushMpls(EthType.MPLS_UNICAST);
1916 OFOxmMplsLabel lid2 = factory.oxms()
1917 .mplsLabel(U32.of(104)); // outer label
1918 OFAction setMpls2 = factory.actions().buildSetField()
1919 .setField(lid2).build();
1920 OFOxmMplsBos bos2 = factory.oxms()
1921 .mplsBos(OFBooleanValue.FALSE);
1922 OFAction setB2 = factory.actions().buildSetField()
1923 .setField(bos2).build();
1924 OFAction setDA2 = factory.actions().buildSetField()
1925 .setField(dmac2).build();
1926 OFAction outp2 = factory.actions().buildOutput()
1927 .setPort(OFPort.of(3))
1928 .build();
1929 List<OFAction> a2 = new ArrayList<OFAction>();
1930 a2.add(push2);
1931 a2.add(setMpls2);
1932 a2.add(setB2);
1933 a2.add(setDA2);
1934 a2.add(outp2);
1935 OFBucket b2 = factory.buildBucket()
1936 .setActions(a2)
1937 .build();
1938 OFMessage gm2 = factory.buildGroupAdd()
1939 .setGroup(g2)
1940 .setBuckets(Collections.singletonList(b2))
1941 .setGroupType(OFGroupType.INDIRECT)
1942 .setXid(getNextTransactionId())
1943 .build();
1944 msglist.add(gm2);
1945
1946 // now add main ECMP group with inner labels
1947 OFGroup group = OFGroup.of(786);
1948 List<OFBucket> buckets = new ArrayList<OFBucket>();
1949 for (int i = 0; i < 2; i++) { // 2 buckets
1950
1951 List<OFAction> actions = new ArrayList<OFAction>();
1952 OFOxmEthSrc smac = factory.oxms()
1953 .ethSrc(MacAddress.of("00:00:01:01:01:80"));
1954 OFAction setSA = factory.actions().buildSetField()
1955 .setField(smac).build();
1956 actions.add(setSA);
1957
1958 if (i == 0) {
1959 // send to switch 2
1960 OFAction pushX = factory.actions().pushMpls(EthType.MPLS_UNICAST);
1961 OFOxmMplsLabel lidX = factory.oxms()
1962 .mplsLabel(U32.of(106)); // inner label
1963 OFAction setX = factory.actions().buildSetField()
1964 .setField(lidX).build();
1965 OFOxmMplsBos bosX = factory.oxms()
1966 .mplsBos(OFBooleanValue.TRUE);
1967 OFAction setBX = factory.actions().buildSetField()
1968 .setField(bosX).build();
1969 OFAction ogX = factory.actions().buildGroup()
1970 .setGroup(g1).build();
1971 actions.add(pushX);
1972 actions.add(setX);
1973 actions.add(setBX);
1974 actions.add(ogX);
1975
1976 } else {
1977 // send to switch 3
1978 OFAction pushY = factory.actions().pushMpls(EthType.MPLS_UNICAST);
1979 OFOxmMplsLabel lidY = factory.oxms()
1980 .mplsLabel(U32.of(106)); // inner label
1981 OFAction setY = factory.actions().buildSetField()
1982 .setField(lidY).build();
1983 OFOxmMplsBos bosY = factory.oxms()
1984 .mplsBos(OFBooleanValue.TRUE);
1985 OFAction setBY = factory.actions().buildSetField()
1986 .setField(bosY).build();
1987 OFAction ogY = factory.actions().buildGroup()
1988 .setGroup(g2).build();
1989 actions.add(pushY);
1990 actions.add(setY);
1991 actions.add(setBY);
1992 actions.add(ogY);
1993 }
1994
1995 OFBucket ofb = factory.buildBucket()
1996 .setWeight(1)
1997 .setActions(actions)
1998 .build();
1999 buckets.add(ofb);
2000 }
2001
2002 OFMessage gm = factory.buildGroupAdd()
2003 .setGroup(group)
2004 .setBuckets(buckets)
2005 .setGroupType(OFGroupType.SELECT)
2006 .setXid(getNextTransactionId())
2007 .build();
2008 msglist.add(gm);
2009
2010 // create an ACL entry to use this ecmp group
2011 Builder matchBuilder = factory.buildMatch();
2012 matchBuilder.setExact(MatchField.ETH_TYPE, EthType.of(0x800));
2013 matchBuilder.setMasked(MatchField.IPV4_DST,
2014 IPv4Address.of("7.7.7.0")
2015 .withMaskOfLength(24));
2016
2017 OFAction grp = factory.actions().buildGroup()
2018 .setGroup(OFGroup.of(786))
2019 .build();
2020 List<OFAction> writeActions = Collections.singletonList(grp);
2021
2022 OFInstruction clearInstr = factory.instructions().clearActions();
2023 OFInstruction writeInstr = factory.instructions().buildWriteActions()
2024 .setActions(writeActions).build();
2025 List<OFInstruction> instructions = new ArrayList<OFInstruction>();
2026 instructions.add(clearInstr);
2027 instructions.add(writeInstr);
2028
2029 OFFlowMod.Builder fmBuilder = factory.buildFlowAdd();
2030
2031 OFMessage aclFlow = fmBuilder
2032 .setTableId(TableId.of(TABLE_ACL))
2033 .setMatch(matchBuilder.build())
2034 .setInstructions(instructions)
2035 .setPriority(10) // TODO: wrong - should be MA
2036 // priority
2037 .setBufferId(OFBufferId.NO_BUFFER)
2038 .setIdleTimeout(0)
2039 .setHardTimeout(0)
2040 .setXid(getNextTransactionId())
2041 .build();
2042 msglist.add(aclFlow);
2043
2044 try {
2045 write(msglist);
2046 } catch (IOException e) {
2047 // TODO Auto-generated catch block
2048 e.printStackTrace();
2049 }
2050 }
2051 }
2052
2053
2054
2055}