blob: c93ad9b0e47ff50778fe93c4b04381b67f6252b1 [file] [log] [blame]
Brian O'Connor7cbbbb72016-04-09 02:13:23 -07001/*
2 * Copyright 2016-present Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Charles Chan188ebf52015-12-23 00:15:11 -080016package org.onosproject.driver.pipeline;
17
18import com.google.common.cache.Cache;
19import com.google.common.cache.CacheBuilder;
20import com.google.common.cache.RemovalCause;
21import com.google.common.cache.RemovalNotification;
Charles Chan5b9df8d2016-03-28 22:21:40 -070022import com.google.common.collect.ImmutableList;
23import com.google.common.collect.Lists;
Yi Tseng78f51f42017-02-02 13:54:58 -080024import com.google.common.collect.Sets;
Charles Chan188ebf52015-12-23 00:15:11 -080025import org.onlab.osgi.ServiceDirectory;
Charles Chan5b9df8d2016-03-28 22:21:40 -070026import org.onlab.packet.IpPrefix;
Charles Chan5270ed02016-01-30 23:22:37 -080027import org.onlab.packet.MacAddress;
Charles Chan188ebf52015-12-23 00:15:11 -080028import org.onlab.packet.MplsLabel;
29import org.onlab.packet.VlanId;
30import org.onosproject.core.ApplicationId;
Yi Tseng78f51f42017-02-02 13:54:58 -080031import org.onosproject.core.GroupId;
Charles Chan32562522016-04-07 14:37:14 -070032import org.onosproject.driver.extensions.OfdpaSetVlanVid;
Charles Chan188ebf52015-12-23 00:15:11 -080033import org.onosproject.net.DeviceId;
34import org.onosproject.net.PortNumber;
35import org.onosproject.net.behaviour.NextGroup;
36import org.onosproject.net.behaviour.PipelinerContext;
37import org.onosproject.net.flow.DefaultTrafficTreatment;
38import org.onosproject.net.flow.TrafficSelector;
39import org.onosproject.net.flow.TrafficTreatment;
40import org.onosproject.net.flow.criteria.Criterion;
Pier Ventre42287df2016-11-09 14:17:26 -080041import org.onosproject.net.flow.criteria.TunnelIdCriterion;
Charles Chan188ebf52015-12-23 00:15:11 -080042import org.onosproject.net.flow.criteria.VlanIdCriterion;
43import org.onosproject.net.flow.instructions.Instruction;
44import org.onosproject.net.flow.instructions.Instructions;
45import org.onosproject.net.flow.instructions.L2ModificationInstruction;
Yi Tseng47f82dc2017-03-05 22:48:39 -080046import org.onosproject.net.flowobjective.DefaultNextObjective;
Charles Chan188ebf52015-12-23 00:15:11 -080047import org.onosproject.net.flowobjective.FlowObjectiveStore;
48import org.onosproject.net.flowobjective.NextObjective;
Yi Tseng47f82dc2017-03-05 22:48:39 -080049import org.onosproject.net.flowobjective.ObjectiveContext;
Charles Chan188ebf52015-12-23 00:15:11 -080050import org.onosproject.net.flowobjective.ObjectiveError;
51import org.onosproject.net.group.DefaultGroupBucket;
52import org.onosproject.net.group.DefaultGroupDescription;
53import org.onosproject.net.group.DefaultGroupKey;
54import org.onosproject.net.group.Group;
55import org.onosproject.net.group.GroupBucket;
56import org.onosproject.net.group.GroupBuckets;
57import org.onosproject.net.group.GroupDescription;
58import org.onosproject.net.group.GroupEvent;
59import org.onosproject.net.group.GroupKey;
60import org.onosproject.net.group.GroupListener;
61import org.onosproject.net.group.GroupService;
Saurav Das8be4e3a2016-03-11 17:19:07 -080062import org.onosproject.store.service.AtomicCounter;
63import org.onosproject.store.service.StorageService;
Charles Chan188ebf52015-12-23 00:15:11 -080064import org.slf4j.Logger;
65
66import java.util.ArrayDeque;
67import java.util.ArrayList;
68import java.util.Collection;
69import java.util.Collections;
70import java.util.Deque;
71import java.util.List;
Charles Chand0fd5dc2016-02-16 23:14:49 -080072import java.util.Objects;
Charles Chan188ebf52015-12-23 00:15:11 -080073import java.util.Set;
74import java.util.concurrent.ConcurrentHashMap;
75import java.util.concurrent.CopyOnWriteArrayList;
76import java.util.concurrent.Executors;
77import java.util.concurrent.ScheduledExecutorService;
78import java.util.concurrent.TimeUnit;
79import java.util.concurrent.atomic.AtomicInteger;
80import java.util.stream.Collectors;
81
82import static org.onlab.util.Tools.groupedThreads;
Pier Ventre140a8942016-11-02 07:26:38 -070083import static org.onosproject.driver.pipeline.Ofdpa2GroupHandler.OfdpaMplsGroupSubType.OFDPA_GROUP_TYPE_SHIFT;
84import static org.onosproject.driver.pipeline.Ofdpa2GroupHandler.OfdpaMplsGroupSubType.OFDPA_MPLS_SUBTYPE_SHIFT;
85import static org.onosproject.driver.pipeline.Ofdpa2Pipeline.isNotMplsBos;
Pier Ventre42287df2016-11-09 14:17:26 -080086import static org.onosproject.net.flow.criteria.Criterion.Type.TUNNEL_ID;
Pier Ventre140a8942016-11-02 07:26:38 -070087import static org.onosproject.net.flow.criteria.Criterion.Type.VLAN_VID;
88import static org.onosproject.net.flowobjective.NextObjective.Type.HASHED;
Yi Tseng78f51f42017-02-02 13:54:58 -080089import static org.onosproject.net.group.GroupDescription.Type.ALL;
90import static org.onosproject.net.group.GroupDescription.Type.SELECT;
Charles Chan188ebf52015-12-23 00:15:11 -080091import static org.slf4j.LoggerFactory.getLogger;
92
93/**
Charles Chan40132b32017-01-22 00:19:37 -080094 * Group handler that emulates Broadcom OF-DPA TTP on CpqD.
Charles Chan188ebf52015-12-23 00:15:11 -080095 */
Charles Chan361154b2016-03-24 10:23:39 -070096public class Ofdpa2GroupHandler {
Charles Chan188ebf52015-12-23 00:15:11 -080097 /*
98 * OFDPA requires group-id's to have a certain form.
99 * L2 Interface Groups have <4bits-0><12bits-vlanid><16bits-portid>
100 * L3 Unicast Groups have <4bits-2><28bits-index>
101 * MPLS Interface Groups have <4bits-9><4bits:0><24bits-index>
102 * L3 ECMP Groups have <4bits-7><28bits-index>
103 * L2 Flood Groups have <4bits-4><12bits-vlanid><16bits-index>
104 * L3 VPN Groups have <4bits-9><4bits-2><24bits-index>
105 */
Charles Chan425854b2016-04-11 15:32:12 -0700106 protected static final int L2_INTERFACE_TYPE = 0x00000000;
107 protected static final int L3_INTERFACE_TYPE = 0x50000000;
108 protected static final int L3_UNICAST_TYPE = 0x20000000;
109 protected static final int L3_MULTICAST_TYPE = 0x60000000;
110 protected static final int MPLS_INTERFACE_TYPE = 0x90000000;
111 protected static final int MPLS_L3VPN_SUBTYPE = 0x92000000;
112 protected static final int L3_ECMP_TYPE = 0x70000000;
113 protected static final int L2_FLOOD_TYPE = 0x40000000;
Charles Chane849c192016-01-11 18:28:54 -0800114
Charles Chan425854b2016-04-11 15:32:12 -0700115 protected static final int TYPE_MASK = 0x0fffffff;
116 protected static final int SUBTYPE_MASK = 0x00ffffff;
117 protected static final int TYPE_VLAN_MASK = 0x0000ffff;
Charles Chane849c192016-01-11 18:28:54 -0800118
Charles Chan372b63e2017-02-07 12:10:53 -0800119 protected static final int THREE_BIT_MASK = 0x0fff;
120 protected static final int FOUR_BIT_MASK = 0xffff;
121 protected static final int PORT_LEN = 16;
122
Charles Chan425854b2016-04-11 15:32:12 -0700123 protected static final int PORT_LOWER_BITS_MASK = 0x3f;
124 protected static final long PORT_HIGHER_BITS_MASK = ~PORT_LOWER_BITS_MASK;
Charles Chan188ebf52015-12-23 00:15:11 -0800125
Yi Tseng78f51f42017-02-02 13:54:58 -0800126 protected static final String HEX_PREFIX = "0x";
127
Charles Chan188ebf52015-12-23 00:15:11 -0800128 private final Logger log = getLogger(getClass());
129 private ServiceDirectory serviceDirectory;
130 protected GroupService groupService;
Saurav Das8be4e3a2016-03-11 17:19:07 -0800131 protected StorageService storageService;
Charles Chan188ebf52015-12-23 00:15:11 -0800132
Charles Chan425854b2016-04-11 15:32:12 -0700133 protected DeviceId deviceId;
Charles Chan188ebf52015-12-23 00:15:11 -0800134 private FlowObjectiveStore flowObjectiveStore;
Charles Chanfc5c7802016-05-17 13:13:55 -0700135 private Cache<GroupKey, List<OfdpaNextGroup>> pendingAddNextObjectives;
136 private Cache<NextObjective, List<GroupKey>> pendingRemoveNextObjectives;
Charles Chan188ebf52015-12-23 00:15:11 -0800137 private ConcurrentHashMap<GroupKey, Set<GroupChainElem>> pendingGroups;
Yi Tseng78f51f42017-02-02 13:54:58 -0800138 private ConcurrentHashMap<GroupKey, Set<NextObjective>> pendingUpdateNextObjectives;
Charles Chan188ebf52015-12-23 00:15:11 -0800139 private ScheduledExecutorService groupChecker =
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700140 Executors.newScheduledThreadPool(2, groupedThreads("onos/pipeliner", "ofdpa2-%d", log));
Charles Chan188ebf52015-12-23 00:15:11 -0800141
142 // index number for group creation
Saurav Das8be4e3a2016-03-11 17:19:07 -0800143 private AtomicCounter nextIndex;
Charles Chan188ebf52015-12-23 00:15:11 -0800144
Yi Tseng47f82dc2017-03-05 22:48:39 -0800145 // local store for pending bucketAdds - by design there can be multiple
Charles Chan188ebf52015-12-23 00:15:11 -0800146 // pending bucket for a group
Yi Tseng47f82dc2017-03-05 22:48:39 -0800147 protected ConcurrentHashMap<Integer, Set<NextObjective>> pendingBuckets =
Saurav Das1ce0a7b2016-10-21 14:06:29 -0700148 new ConcurrentHashMap<>();
Charles Chan188ebf52015-12-23 00:15:11 -0800149
Charles Chan40132b32017-01-22 00:19:37 -0800150 /**
151 * Determines whether this pipeline support copy ttl instructions or not.
152 *
153 * @return true if copy ttl instructions are supported
154 */
155 protected boolean supportCopyTtl() {
156 return true;
157 }
158
159 /**
160 * Determines whether this pipeline support set mpls bos instruction or not.
161 *
162 * @return true if set mpls bos instruction is supported
163 */
164 protected boolean supportSetMplsBos() {
165 return true;
166 }
167
Charles Chan0f43e472017-02-14 14:00:16 -0800168 /**
169 * Determines whether this pipeline requires popping VLAN before pushing MPLS.
170 * <p>
171 * If required, pop vlan before push mpls and add an arbitrary vlan back afterward.
172 * MPLS interface group will substitute the arbitrary VLAN with expected VLAN later on.
173 *
174 * @return true if this pipeline requires popping VLAN before pushing MPLS
175 */
176 protected boolean requireVlanPopBeforeMplsPush() {
177 return false;
178 }
179
Charles Chan188ebf52015-12-23 00:15:11 -0800180 protected void init(DeviceId deviceId, PipelinerContext context) {
181 this.deviceId = deviceId;
182 this.flowObjectiveStore = context.store();
183 this.serviceDirectory = context.directory();
184 this.groupService = serviceDirectory.get(GroupService.class);
Saurav Das8be4e3a2016-03-11 17:19:07 -0800185 this.storageService = serviceDirectory.get(StorageService.class);
Madan Jampanid5714e02016-04-19 14:15:20 -0700186 this.nextIndex = storageService.getAtomicCounter("group-id-index-counter");
Charles Chan188ebf52015-12-23 00:15:11 -0800187
Charles Chanfc5c7802016-05-17 13:13:55 -0700188 pendingAddNextObjectives = CacheBuilder.newBuilder()
Charles Chan188ebf52015-12-23 00:15:11 -0800189 .expireAfterWrite(20, TimeUnit.SECONDS)
190 .removalListener((
191 RemovalNotification<GroupKey, List<OfdpaNextGroup>> notification) -> {
192 if (notification.getCause() == RemovalCause.EXPIRED) {
193 notification.getValue().forEach(ofdpaNextGrp ->
Charles Chan361154b2016-03-24 10:23:39 -0700194 Ofdpa2Pipeline.fail(ofdpaNextGrp.nextObj,
Charles Chan188ebf52015-12-23 00:15:11 -0800195 ObjectiveError.GROUPINSTALLATIONFAILED));
Charles Chanfc5c7802016-05-17 13:13:55 -0700196 }
197 }).build();
Charles Chan188ebf52015-12-23 00:15:11 -0800198
Charles Chanfc5c7802016-05-17 13:13:55 -0700199 pendingRemoveNextObjectives = CacheBuilder.newBuilder()
200 .expireAfterWrite(20, TimeUnit.SECONDS)
201 .removalListener((
202 RemovalNotification<NextObjective, List<GroupKey>> notification) -> {
203 if (notification.getCause() == RemovalCause.EXPIRED) {
204 Ofdpa2Pipeline.fail(notification.getKey(),
205 ObjectiveError.GROUPREMOVALFAILED);
Charles Chan188ebf52015-12-23 00:15:11 -0800206 }
207 }).build();
208 pendingGroups = new ConcurrentHashMap<>();
Yi Tseng78f51f42017-02-02 13:54:58 -0800209 pendingUpdateNextObjectives = new ConcurrentHashMap<>();
Charles Chan188ebf52015-12-23 00:15:11 -0800210 groupChecker.scheduleAtFixedRate(new GroupChecker(), 0, 500, TimeUnit.MILLISECONDS);
211
212 groupService.addListener(new InnerGroupListener());
213 }
214
Pier Ventre140a8942016-11-02 07:26:38 -0700215 /**
216 * The purpose of this function is to verify if the hashed next
217 * objective is supported by the current pipeline.
218 *
219 * @param nextObjective the hashed objective to verify
220 * @return true if the hashed objective is supported. Otherwise false.
221 */
222 public boolean verifyHashedNextObjective(NextObjective nextObjective) {
223 // if it is not hashed, there is something wrong;
224 if (nextObjective.type() != HASHED) {
225 return false;
226 }
227 // The case non supported is the MPLS-ECMP. For now, we try
228 // to create a MPLS-ECMP for the transport of a VPWS. The
229 // necessary info are contained in the meta selector. In particular
230 // we are looking for the case of BoS==False;
231 TrafficSelector metaSelector = nextObjective.meta();
232 if (metaSelector != null && isNotMplsBos(metaSelector)) {
233 return false;
234 }
235
236 return true;
237 }
238
Saurav Das8be4e3a2016-03-11 17:19:07 -0800239 //////////////////////////////////////
240 // Group Creation
241 //////////////////////////////////////
242
Charles Chan188ebf52015-12-23 00:15:11 -0800243 protected void addGroup(NextObjective nextObjective) {
244 switch (nextObjective.type()) {
245 case SIMPLE:
246 Collection<TrafficTreatment> treatments = nextObjective.next();
247 if (treatments.size() != 1) {
248 log.error("Next Objectives of type Simple should only have a "
249 + "single Traffic Treatment. Next Objective Id:{}",
250 nextObjective.id());
Charles Chan361154b2016-03-24 10:23:39 -0700251 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.BADPARAMS);
Charles Chan188ebf52015-12-23 00:15:11 -0800252 return;
253 }
254 processSimpleNextObjective(nextObjective);
255 break;
256 case BROADCAST:
257 processBroadcastNextObjective(nextObjective);
258 break;
259 case HASHED:
Pier Ventre140a8942016-11-02 07:26:38 -0700260 if (!verifyHashedNextObjective(nextObjective)) {
261 log.error("Next Objectives of type hashed not supported. Next Objective Id:{}",
262 nextObjective.id());
263 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.BADPARAMS);
264 return;
265 }
Charles Chan188ebf52015-12-23 00:15:11 -0800266 processHashedNextObjective(nextObjective);
267 break;
268 case FAILOVER:
Charles Chan361154b2016-03-24 10:23:39 -0700269 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.UNSUPPORTED);
Charles Chan188ebf52015-12-23 00:15:11 -0800270 log.warn("Unsupported next objective type {}", nextObjective.type());
271 break;
272 default:
Charles Chan361154b2016-03-24 10:23:39 -0700273 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.UNKNOWN);
Charles Chan188ebf52015-12-23 00:15:11 -0800274 log.warn("Unknown next objective type {}", nextObjective.type());
275 }
276 }
277
278 /**
279 * As per the OFDPA 2.0 TTP, packets are sent out of ports by using
280 * a chain of groups. The simple Next Objective passed
281 * in by the application has to be broken up into a group chain
282 * comprising of an L3 Unicast Group that points to an L2 Interface
283 * Group which in-turn points to an output port. In some cases, the simple
284 * next Objective can just be an L2 interface without the need for chaining.
285 *
286 * @param nextObj the nextObjective of type SIMPLE
287 */
288 private void processSimpleNextObjective(NextObjective nextObj) {
289 TrafficTreatment treatment = nextObj.next().iterator().next();
290 // determine if plain L2 or L3->L2
291 boolean plainL2 = true;
292 for (Instruction ins : treatment.allInstructions()) {
293 if (ins.type() == Instruction.Type.L2MODIFICATION) {
294 L2ModificationInstruction l2ins = (L2ModificationInstruction) ins;
295 if (l2ins.subtype() == L2ModificationInstruction.L2SubType.ETH_DST ||
296 l2ins.subtype() == L2ModificationInstruction.L2SubType.ETH_SRC) {
297 plainL2 = false;
298 break;
299 }
300 }
301 }
302
303 if (plainL2) {
304 createL2InterfaceGroup(nextObj);
305 return;
306 }
307
Pier Ventre140a8942016-11-02 07:26:38 -0700308 boolean isMpls = false;
Pier Ventre42287df2016-11-09 14:17:26 -0800309 // In order to understand if it is a pseudo wire related
310 // next objective we look for the tunnel id in the meta.
311 boolean isPw = false;
Pier Ventre140a8942016-11-02 07:26:38 -0700312 if (nextObj.meta() != null) {
313 isMpls = isNotMplsBos(nextObj.meta());
Pier Ventre42287df2016-11-09 14:17:26 -0800314
315 TunnelIdCriterion tunnelIdCriterion = (TunnelIdCriterion) nextObj
316 .meta()
317 .getCriterion(TUNNEL_ID);
318 if (tunnelIdCriterion != null) {
319 isPw = true;
320 }
321
Pier Ventre140a8942016-11-02 07:26:38 -0700322 }
323
Pier Ventre42287df2016-11-09 14:17:26 -0800324 if (!isPw) {
325 // break up simple next objective to GroupChain objects
326 GroupInfo groupInfo = createL2L3Chain(treatment, nextObj.id(),
327 nextObj.appId(), isMpls,
328 nextObj.meta());
329 if (groupInfo == null) {
330 log.error("Could not process nextObj={} in dev:{}", nextObj.id(), deviceId);
331 return;
332 }
333 // create object for local and distributed storage
334 Deque<GroupKey> gkeyChain = new ArrayDeque<>();
335 gkeyChain.addFirst(groupInfo.innerMostGroupDesc.appCookie());
336 gkeyChain.addFirst(groupInfo.nextGroupDesc.appCookie());
337 OfdpaNextGroup ofdpaGrp =
338 new OfdpaNextGroup(Collections.singletonList(gkeyChain), nextObj);
339
340 // store l3groupkey with the ofdpaNextGroup for the nextObjective that depends on it
341 updatePendingNextObjective(groupInfo.nextGroupDesc.appCookie(), ofdpaGrp);
342
343 // now we are ready to send the l2 groupDescription (inner), as all the stores
344 // that will get async replies have been updated. By waiting to update
345 // the stores, we prevent nasty race conditions.
346 groupService.addGroup(groupInfo.innerMostGroupDesc);
347 } else {
348 // We handle the pseudo wire with a different a procedure.
349 // This procedure is meant to handle both initiation and
350 // termination of the pseudo wire.
351 processPwNextObjective(nextObj);
Charles Chan188ebf52015-12-23 00:15:11 -0800352 }
Charles Chan188ebf52015-12-23 00:15:11 -0800353 }
354
Charles Chan188ebf52015-12-23 00:15:11 -0800355 /**
356 * Creates a simple L2 Interface Group.
357 *
358 * @param nextObj the next Objective
359 */
360 private void createL2InterfaceGroup(NextObjective nextObj) {
Charles Chan5b9df8d2016-03-28 22:21:40 -0700361 VlanId assignedVlan = Ofdpa2Pipeline.readVlanFromSelector(nextObj.meta());
362 if (assignedVlan == null) {
363 log.warn("VLAN ID required by simple next obj is missing. Abort.");
364 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.BADPARAMS);
Charles Chan188ebf52015-12-23 00:15:11 -0800365 return;
366 }
367
Charles Chan5b9df8d2016-03-28 22:21:40 -0700368 List<GroupInfo> groupInfos = prepareL2InterfaceGroup(nextObj, assignedVlan);
Charles Chan188ebf52015-12-23 00:15:11 -0800369
Charles Chan5b9df8d2016-03-28 22:21:40 -0700370 // There is only one L2 interface group in this case
371 GroupDescription l2InterfaceGroupDesc = groupInfos.get(0).innerMostGroupDesc;
Charles Chan188ebf52015-12-23 00:15:11 -0800372
Charles Chan5b9df8d2016-03-28 22:21:40 -0700373 // Put all dependency information into allGroupKeys
374 List<Deque<GroupKey>> allGroupKeys = Lists.newArrayList();
375 Deque<GroupKey> gkeyChain = new ArrayDeque<>();
376 gkeyChain.addFirst(l2InterfaceGroupDesc.appCookie());
377 allGroupKeys.add(gkeyChain);
Charles Chan188ebf52015-12-23 00:15:11 -0800378
Charles Chan5b9df8d2016-03-28 22:21:40 -0700379 // Point the next objective to this group
380 OfdpaNextGroup ofdpaGrp = new OfdpaNextGroup(allGroupKeys, nextObj);
381 updatePendingNextObjective(l2InterfaceGroupDesc.appCookie(), ofdpaGrp);
382
383 // Start installing the inner-most group
384 groupService.addGroup(l2InterfaceGroupDesc);
Charles Chan188ebf52015-12-23 00:15:11 -0800385 }
386
387 /**
388 * Creates one of two possible group-chains from the treatment
389 * passed in. Depending on the MPLS boolean, this method either creates
Charles Chan425854b2016-04-11 15:32:12 -0700390 * an L3Unicast Group --&gt; L2Interface Group, if mpls is false;
391 * or MPLSInterface Group --&gt; L2Interface Group, if mpls is true;
Charles Chan188ebf52015-12-23 00:15:11 -0800392 * The returned 'inner' group description is always the L2 Interface group.
393 *
394 * @param treatment that needs to be broken up to create the group chain
395 * @param nextId of the next objective that needs this group chain
396 * @param appId of the application that sent this next objective
397 * @param mpls determines if L3Unicast or MPLSInterface group is created
398 * @param meta metadata passed in by the application as part of the nextObjective
399 * @return GroupInfo containing the GroupDescription of the
400 * L2Interface group(inner) and the GroupDescription of the (outer)
401 * L3Unicast/MPLSInterface group. May return null if there is an
402 * error in processing the chain
403 */
Charles Chan425854b2016-04-11 15:32:12 -0700404 protected GroupInfo createL2L3Chain(TrafficTreatment treatment, int nextId,
Charles Chanf9e98652016-09-07 16:54:23 -0700405 ApplicationId appId, boolean mpls,
406 TrafficSelector meta) {
407 return createL2L3ChainInternal(treatment, nextId, appId, mpls, meta, true);
408 }
409
410 /**
411 * Internal implementation of createL2L3Chain.
412 * <p>
413 * The is_present bit in set_vlan_vid action is required to be 0 in OFDPA i12.
414 * Since it is non-OF spec, we need an extension treatment for that.
415 * The useSetVlanExtension must be set to false for OFDPA i12.
416 * </p>
417 *
418 * @param treatment that needs to be broken up to create the group chain
419 * @param nextId of the next objective that needs this group chain
420 * @param appId of the application that sent this next objective
421 * @param mpls determines if L3Unicast or MPLSInterface group is created
422 * @param meta metadata passed in by the application as part of the nextObjective
423 * @param useSetVlanExtension use the setVlanVid extension that has is_present bit set to 0.
424 * @return GroupInfo containing the GroupDescription of the
425 * L2Interface group(inner) and the GroupDescription of the (outer)
426 * L3Unicast/MPLSInterface group. May return null if there is an
427 * error in processing the chain
428 */
429 protected GroupInfo createL2L3ChainInternal(TrafficTreatment treatment, int nextId,
Pier Ventre42287df2016-11-09 14:17:26 -0800430 ApplicationId appId, boolean mpls,
431 TrafficSelector meta, boolean useSetVlanExtension) {
Charles Chan188ebf52015-12-23 00:15:11 -0800432 // for the l2interface group, get vlan and port info
433 // for the outer group, get the src/dst mac, and vlan info
434 TrafficTreatment.Builder outerTtb = DefaultTrafficTreatment.builder();
435 TrafficTreatment.Builder innerTtb = DefaultTrafficTreatment.builder();
436 VlanId vlanid = null;
437 long portNum = 0;
438 boolean setVlan = false, popVlan = false;
Yi Tseng78f51f42017-02-02 13:54:58 -0800439 MacAddress srcMac;
440 MacAddress dstMac;
Charles Chan188ebf52015-12-23 00:15:11 -0800441 for (Instruction ins : treatment.allInstructions()) {
442 if (ins.type() == Instruction.Type.L2MODIFICATION) {
443 L2ModificationInstruction l2ins = (L2ModificationInstruction) ins;
444 switch (l2ins.subtype()) {
445 case ETH_DST:
Charles Chan5270ed02016-01-30 23:22:37 -0800446 dstMac = ((L2ModificationInstruction.ModEtherInstruction) l2ins).mac();
447 outerTtb.setEthDst(dstMac);
Charles Chan188ebf52015-12-23 00:15:11 -0800448 break;
449 case ETH_SRC:
Charles Chand0fd5dc2016-02-16 23:14:49 -0800450 srcMac = ((L2ModificationInstruction.ModEtherInstruction) l2ins).mac();
451 outerTtb.setEthSrc(srcMac);
Charles Chan188ebf52015-12-23 00:15:11 -0800452 break;
453 case VLAN_ID:
454 vlanid = ((L2ModificationInstruction.ModVlanIdInstruction) l2ins).vlanId();
Charles Chanf9e98652016-09-07 16:54:23 -0700455 if (useSetVlanExtension) {
456 OfdpaSetVlanVid ofdpaSetVlanVid = new OfdpaSetVlanVid(vlanid);
457 outerTtb.extension(ofdpaSetVlanVid, deviceId);
458 } else {
459 outerTtb.setVlanId(vlanid);
460 }
Charles Chan188ebf52015-12-23 00:15:11 -0800461 setVlan = true;
462 break;
463 case VLAN_POP:
464 innerTtb.popVlan();
465 popVlan = true;
466 break;
467 case DEC_MPLS_TTL:
468 case MPLS_LABEL:
469 case MPLS_POP:
470 case MPLS_PUSH:
471 case VLAN_PCP:
472 case VLAN_PUSH:
473 default:
474 break;
475 }
476 } else if (ins.type() == Instruction.Type.OUTPUT) {
477 portNum = ((Instructions.OutputInstruction) ins).port().toLong();
478 innerTtb.add(ins);
479 } else {
480 log.warn("Driver does not handle this type of TrafficTreatment"
481 + " instruction in nextObjectives: {}", ins.type());
482 }
483 }
484
485 if (vlanid == null && meta != null) {
486 // use metadata if available
Pier Ventre140a8942016-11-02 07:26:38 -0700487 Criterion vidCriterion = meta.getCriterion(VLAN_VID);
Charles Chan188ebf52015-12-23 00:15:11 -0800488 if (vidCriterion != null) {
489 vlanid = ((VlanIdCriterion) vidCriterion).vlanId();
490 }
491 // if vlan is not set, use the vlan in metadata for outerTtb
492 if (vlanid != null && !setVlan) {
Charles Chanf9e98652016-09-07 16:54:23 -0700493 if (useSetVlanExtension) {
494 OfdpaSetVlanVid ofdpaSetVlanVid = new OfdpaSetVlanVid(vlanid);
495 outerTtb.extension(ofdpaSetVlanVid, deviceId);
496 } else {
497 outerTtb.setVlanId(vlanid);
498 }
Charles Chan188ebf52015-12-23 00:15:11 -0800499 }
500 }
501
502 if (vlanid == null) {
503 log.error("Driver cannot process an L2/L3 group chain without "
504 + "egress vlan information for dev: {} port:{}",
505 deviceId, portNum);
506 return null;
507 }
508
509 if (!setVlan && !popVlan) {
510 // untagged outgoing port
511 TrafficTreatment.Builder temp = DefaultTrafficTreatment.builder();
512 temp.popVlan();
513 innerTtb.build().allInstructions().forEach(i -> temp.add(i));
514 innerTtb = temp;
515 }
516
517 // assemble information for ofdpa l2interface group
Charles Chane849c192016-01-11 18:28:54 -0800518 int l2groupId = L2_INTERFACE_TYPE | (vlanid.toShort() << 16) | (int) portNum;
Saurav Das8be4e3a2016-03-11 17:19:07 -0800519 // a globally unique groupkey that is different for ports in the same device,
Charles Chan188ebf52015-12-23 00:15:11 -0800520 // but different for the same portnumber on different devices. Also different
521 // for the various group-types created out of the same next objective.
Charles Chane849c192016-01-11 18:28:54 -0800522 int l2gk = l2InterfaceGroupKey(deviceId, vlanid, portNum);
Charles Chan361154b2016-03-24 10:23:39 -0700523 final GroupKey l2groupkey = new DefaultGroupKey(Ofdpa2Pipeline.appKryo.serialize(l2gk));
Charles Chan188ebf52015-12-23 00:15:11 -0800524
525 // assemble information for outer group
526 GroupDescription outerGrpDesc = null;
527 if (mpls) {
528 // outer group is MPLSInteface
Saurav Das8be4e3a2016-03-11 17:19:07 -0800529 int mplsInterfaceIndex = getNextAvailableIndex();
530 int mplsgroupId = MPLS_INTERFACE_TYPE | (SUBTYPE_MASK & mplsInterfaceIndex);
531 final GroupKey mplsgroupkey = new DefaultGroupKey(
Charles Chan361154b2016-03-24 10:23:39 -0700532 Ofdpa2Pipeline.appKryo.serialize(mplsInterfaceIndex));
Yi Tsengfa394de2017-02-01 11:26:40 -0800533 outerTtb.group(new GroupId(l2groupId));
Charles Chan188ebf52015-12-23 00:15:11 -0800534 // create the mpls-interface group description to wait for the
535 // l2 interface group to be processed
536 GroupBucket mplsinterfaceGroupBucket =
537 DefaultGroupBucket.createIndirectGroupBucket(outerTtb.build());
538 outerGrpDesc = new DefaultGroupDescription(
539 deviceId,
540 GroupDescription.Type.INDIRECT,
541 new GroupBuckets(Collections.singletonList(
542 mplsinterfaceGroupBucket)),
543 mplsgroupkey,
544 mplsgroupId,
545 appId);
546 log.debug("Trying MPLS-Interface: device:{} gid:{} gkey:{} nextid:{}",
547 deviceId, Integer.toHexString(mplsgroupId),
548 mplsgroupkey, nextId);
549 } else {
550 // outer group is L3Unicast
Saurav Das8be4e3a2016-03-11 17:19:07 -0800551 int l3unicastIndex = getNextAvailableIndex();
552 int l3groupId = L3_UNICAST_TYPE | (TYPE_MASK & l3unicastIndex);
553 final GroupKey l3groupkey = new DefaultGroupKey(
Charles Chan361154b2016-03-24 10:23:39 -0700554 Ofdpa2Pipeline.appKryo.serialize(l3unicastIndex));
Yi Tsengfa394de2017-02-01 11:26:40 -0800555 outerTtb.group(new GroupId(l2groupId));
Charles Chan188ebf52015-12-23 00:15:11 -0800556 // create the l3unicast group description to wait for the
557 // l2 interface group to be processed
558 GroupBucket l3unicastGroupBucket =
559 DefaultGroupBucket.createIndirectGroupBucket(outerTtb.build());
560 outerGrpDesc = new DefaultGroupDescription(
561 deviceId,
562 GroupDescription.Type.INDIRECT,
563 new GroupBuckets(Collections.singletonList(
564 l3unicastGroupBucket)),
565 l3groupkey,
566 l3groupId,
567 appId);
568 log.debug("Trying L3Unicast: device:{} gid:{} gkey:{} nextid:{}",
569 deviceId, Integer.toHexString(l3groupId),
570 l3groupkey, nextId);
571 }
572
573 // store l2groupkey with the groupChainElem for the outer-group that depends on it
574 GroupChainElem gce = new GroupChainElem(outerGrpDesc, 1, false);
575 updatePendingGroups(l2groupkey, gce);
576
577 // create group description for the inner l2interfacegroup
Charles Chan5b9df8d2016-03-28 22:21:40 -0700578 GroupBucket l2InterfaceGroupBucket =
Charles Chan188ebf52015-12-23 00:15:11 -0800579 DefaultGroupBucket.createIndirectGroupBucket(innerTtb.build());
580 GroupDescription l2groupDescription =
581 new DefaultGroupDescription(
582 deviceId,
583 GroupDescription.Type.INDIRECT,
584 new GroupBuckets(Collections.singletonList(
Charles Chan5b9df8d2016-03-28 22:21:40 -0700585 l2InterfaceGroupBucket)),
Charles Chan188ebf52015-12-23 00:15:11 -0800586 l2groupkey,
587 l2groupId,
588 appId);
589 log.debug("Trying L2Interface: device:{} gid:{} gkey:{} nextId:{}",
590 deviceId, Integer.toHexString(l2groupId),
591 l2groupkey, nextId);
592 return new GroupInfo(l2groupDescription, outerGrpDesc);
593
594 }
595
596 /**
597 * As per the OFDPA 2.0 TTP, packets are sent out of ports by using
598 * a chain of groups. The broadcast Next Objective passed in by the application
599 * has to be broken up into a group chain comprising of an
Saurav Das1a129a02016-11-18 15:21:57 -0800600 * L2 Flood group or L3 Multicast group, whose buckets point to L2 Interface groups.
Charles Chan188ebf52015-12-23 00:15:11 -0800601 *
602 * @param nextObj the nextObjective of type BROADCAST
603 */
604 private void processBroadcastNextObjective(NextObjective nextObj) {
Charles Chan5b9df8d2016-03-28 22:21:40 -0700605 VlanId assignedVlan = Ofdpa2Pipeline.readVlanFromSelector(nextObj.meta());
606 if (assignedVlan == null) {
607 log.warn("VLAN ID required by broadcast next obj is missing. Abort.");
608 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.BADPARAMS);
Charles Chan188ebf52015-12-23 00:15:11 -0800609 return;
610 }
Charles Chan188ebf52015-12-23 00:15:11 -0800611
Charles Chan5b9df8d2016-03-28 22:21:40 -0700612 List<GroupInfo> groupInfos = prepareL2InterfaceGroup(nextObj, assignedVlan);
613
614 IpPrefix ipDst = Ofdpa2Pipeline.readIpDstFromSelector(nextObj.meta());
615 if (ipDst != null) {
616 if (ipDst.isMulticast()) {
617 createL3MulticastGroup(nextObj, assignedVlan, groupInfos);
618 } else {
619 log.warn("Broadcast NextObj with non-multicast IP address {}", nextObj);
620 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.BADPARAMS);
621 return;
622 }
623 } else {
624 createL2FloodGroup(nextObj, assignedVlan, groupInfos);
625 }
626 }
627
Saurav Das1ce0a7b2016-10-21 14:06:29 -0700628 private List<GroupInfo> prepareL2InterfaceGroup(NextObjective nextObj,
629 VlanId assignedVlan) {
Charles Chan5b9df8d2016-03-28 22:21:40 -0700630 ImmutableList.Builder<GroupInfo> groupInfoBuilder = ImmutableList.builder();
631
632 // break up broadcast next objective to multiple groups
633 Collection<TrafficTreatment> buckets = nextObj.next();
634
Charles Chan188ebf52015-12-23 00:15:11 -0800635 // each treatment is converted to an L2 interface group
Charles Chan188ebf52015-12-23 00:15:11 -0800636 for (TrafficTreatment treatment : buckets) {
637 TrafficTreatment.Builder newTreatment = DefaultTrafficTreatment.builder();
638 PortNumber portNum = null;
Charles Chan5b9df8d2016-03-28 22:21:40 -0700639 VlanId egressVlan = null;
Charles Chan188ebf52015-12-23 00:15:11 -0800640 // ensure that the only allowed treatments are pop-vlan and output
641 for (Instruction ins : treatment.allInstructions()) {
642 if (ins.type() == Instruction.Type.L2MODIFICATION) {
643 L2ModificationInstruction l2ins = (L2ModificationInstruction) ins;
644 switch (l2ins.subtype()) {
645 case VLAN_POP:
646 newTreatment.add(l2ins);
647 break;
Charles Chan5b9df8d2016-03-28 22:21:40 -0700648 case VLAN_ID:
649 egressVlan = ((L2ModificationInstruction.ModVlanIdInstruction) l2ins).vlanId();
650 break;
Charles Chan188ebf52015-12-23 00:15:11 -0800651 default:
652 log.debug("action {} not permitted for broadcast nextObj",
653 l2ins.subtype());
654 break;
655 }
656 } else if (ins.type() == Instruction.Type.OUTPUT) {
657 portNum = ((Instructions.OutputInstruction) ins).port();
658 newTreatment.add(ins);
659 } else {
Charles Chane849c192016-01-11 18:28:54 -0800660 log.debug("TrafficTreatment of type {} not permitted in " +
661 " broadcast nextObjective", ins.type());
Charles Chan188ebf52015-12-23 00:15:11 -0800662 }
663 }
664
Charles Chan188ebf52015-12-23 00:15:11 -0800665 // assemble info for l2 interface group
Charles Chan5b9df8d2016-03-28 22:21:40 -0700666 VlanId l2InterfaceGroupVlan =
667 (egressVlan != null && !assignedVlan.equals(egressVlan)) ?
668 egressVlan : assignedVlan;
669 int l2gk = l2InterfaceGroupKey(deviceId, l2InterfaceGroupVlan, portNum.toLong());
670 final GroupKey l2InterfaceGroupKey =
671 new DefaultGroupKey(Ofdpa2Pipeline.appKryo.serialize(l2gk));
Charles Chan372b63e2017-02-07 12:10:53 -0800672 int l2InterfaceGroupId = L2_INTERFACE_TYPE |
673 ((l2InterfaceGroupVlan.toShort() & THREE_BIT_MASK) << PORT_LEN) |
674 ((int) portNum.toLong() & FOUR_BIT_MASK);
Charles Chan5b9df8d2016-03-28 22:21:40 -0700675 GroupBucket l2InterfaceGroupBucket =
Charles Chan188ebf52015-12-23 00:15:11 -0800676 DefaultGroupBucket.createIndirectGroupBucket(newTreatment.build());
Charles Chan5b9df8d2016-03-28 22:21:40 -0700677 GroupDescription l2InterfaceGroupDescription =
Charles Chan188ebf52015-12-23 00:15:11 -0800678 new DefaultGroupDescription(
679 deviceId,
680 GroupDescription.Type.INDIRECT,
681 new GroupBuckets(Collections.singletonList(
Charles Chan5b9df8d2016-03-28 22:21:40 -0700682 l2InterfaceGroupBucket)),
683 l2InterfaceGroupKey,
684 l2InterfaceGroupId,
Charles Chan188ebf52015-12-23 00:15:11 -0800685 nextObj.appId());
686 log.debug("Trying L2-Interface: device:{} gid:{} gkey:{} nextid:{}",
Charles Chan5b9df8d2016-03-28 22:21:40 -0700687 deviceId, Integer.toHexString(l2InterfaceGroupId),
688 l2InterfaceGroupKey, nextObj.id());
Charles Chan188ebf52015-12-23 00:15:11 -0800689
Charles Chan5b9df8d2016-03-28 22:21:40 -0700690 groupInfoBuilder.add(new GroupInfo(l2InterfaceGroupDescription,
691 l2InterfaceGroupDescription));
Charles Chan188ebf52015-12-23 00:15:11 -0800692 }
Charles Chan5b9df8d2016-03-28 22:21:40 -0700693 return groupInfoBuilder.build();
694 }
Charles Chan188ebf52015-12-23 00:15:11 -0800695
Saurav Das1ce0a7b2016-10-21 14:06:29 -0700696 private void createL2FloodGroup(NextObjective nextObj, VlanId vlanId,
697 List<GroupInfo> groupInfos) {
698 // assemble info for l2 flood group. Since there can be only one flood
699 // group for a vlan, its index is always the same - 0
Saurav Das0fd79d92016-03-07 10:58:36 -0800700 Integer l2floodgroupId = L2_FLOOD_TYPE | (vlanId.toShort() << 16);
Yi Tseng117952d2017-02-28 10:58:23 -0800701 int l2floodgk = l2FloodGroupKey(vlanId);
Saurav Das1ce0a7b2016-10-21 14:06:29 -0700702 final GroupKey l2floodgroupkey =
703 new DefaultGroupKey(Ofdpa2Pipeline.appKryo.serialize(l2floodgk));
Charles Chan5b9df8d2016-03-28 22:21:40 -0700704
Charles Chan188ebf52015-12-23 00:15:11 -0800705 // collection of group buckets pointing to all the l2 interface groups
Yi Tseng78f51f42017-02-02 13:54:58 -0800706 List<GroupBucket> l2floodBuckets =
707 generateNextGroupBuckets(groupInfos, ALL);
Charles Chan188ebf52015-12-23 00:15:11 -0800708 // create the l2flood group-description to wait for all the
709 // l2interface groups to be processed
710 GroupDescription l2floodGroupDescription =
711 new DefaultGroupDescription(
712 deviceId,
Yi Tseng78f51f42017-02-02 13:54:58 -0800713 ALL,
Charles Chan188ebf52015-12-23 00:15:11 -0800714 new GroupBuckets(l2floodBuckets),
715 l2floodgroupkey,
716 l2floodgroupId,
717 nextObj.appId());
Charles Chan188ebf52015-12-23 00:15:11 -0800718 log.debug("Trying L2-Flood: device:{} gid:{} gkey:{} nextid:{}",
719 deviceId, Integer.toHexString(l2floodgroupId),
720 l2floodgroupkey, nextObj.id());
721
Charles Chan5b9df8d2016-03-28 22:21:40 -0700722 // Put all dependency information into allGroupKeys
723 List<Deque<GroupKey>> allGroupKeys = Lists.newArrayList();
724 groupInfos.forEach(groupInfo -> {
725 Deque<GroupKey> gkeyChain = new ArrayDeque<>();
726 // In this case we should have L2 interface group only
727 gkeyChain.addFirst(groupInfo.nextGroupDesc.appCookie());
728 gkeyChain.addFirst(l2floodgroupkey);
729 allGroupKeys.add(gkeyChain);
730 });
Charles Chan188ebf52015-12-23 00:15:11 -0800731
Charles Chan5b9df8d2016-03-28 22:21:40 -0700732 // Point the next objective to this group
733 OfdpaNextGroup ofdpaGrp = new OfdpaNextGroup(allGroupKeys, nextObj);
Charles Chan188ebf52015-12-23 00:15:11 -0800734 updatePendingNextObjective(l2floodgroupkey, ofdpaGrp);
735
Charles Chan5b9df8d2016-03-28 22:21:40 -0700736 GroupChainElem gce = new GroupChainElem(l2floodGroupDescription,
737 groupInfos.size(), false);
738 groupInfos.forEach(groupInfo -> {
739 // Point this group to the next group
740 updatePendingGroups(groupInfo.nextGroupDesc.appCookie(), gce);
741 // Start installing the inner-most group
742 groupService.addGroup(groupInfo.innerMostGroupDesc);
743 });
744 }
745
Yi Tseng117952d2017-02-28 10:58:23 -0800746 private int l2FloodGroupKey(VlanId vlanId) {
747 int hash = Objects.hash(deviceId, vlanId);
748 return L2_FLOOD_TYPE | TYPE_MASK & hash;
749 }
750
Saurav Das1ce0a7b2016-10-21 14:06:29 -0700751 private void createL3MulticastGroup(NextObjective nextObj, VlanId vlanId,
752 List<GroupInfo> groupInfos) {
Charles Chan5b9df8d2016-03-28 22:21:40 -0700753 List<GroupBucket> l3McastBuckets = new ArrayList<>();
754 groupInfos.forEach(groupInfo -> {
755 // Points to L3 interface group if there is one.
756 // Otherwise points to L2 interface group directly.
757 GroupDescription nextGroupDesc = (groupInfo.nextGroupDesc != null) ?
758 groupInfo.nextGroupDesc : groupInfo.innerMostGroupDesc;
759 TrafficTreatment.Builder ttb = DefaultTrafficTreatment.builder();
Yi Tsengfa394de2017-02-01 11:26:40 -0800760 ttb.group(new GroupId(nextGroupDesc.givenGroupId()));
Charles Chan5b9df8d2016-03-28 22:21:40 -0700761 GroupBucket abucket = DefaultGroupBucket.createAllGroupBucket(ttb.build());
762 l3McastBuckets.add(abucket);
763 });
764
765 int l3MulticastIndex = getNextAvailableIndex();
Saurav Das1ce0a7b2016-10-21 14:06:29 -0700766 int l3MulticastGroupId = L3_MULTICAST_TYPE |
767 vlanId.toShort() << 16 | (TYPE_VLAN_MASK & l3MulticastIndex);
768 final GroupKey l3MulticastGroupKey =
769 new DefaultGroupKey(Ofdpa2Pipeline.appKryo.serialize(l3MulticastIndex));
Charles Chan5b9df8d2016-03-28 22:21:40 -0700770
771 GroupDescription l3MulticastGroupDesc = new DefaultGroupDescription(deviceId,
Yi Tseng78f51f42017-02-02 13:54:58 -0800772 ALL,
Charles Chan5b9df8d2016-03-28 22:21:40 -0700773 new GroupBuckets(l3McastBuckets),
774 l3MulticastGroupKey,
775 l3MulticastGroupId,
776 nextObj.appId());
777
778 // Put all dependency information into allGroupKeys
779 List<Deque<GroupKey>> allGroupKeys = Lists.newArrayList();
780 groupInfos.forEach(groupInfo -> {
781 Deque<GroupKey> gkeyChain = new ArrayDeque<>();
782 gkeyChain.addFirst(groupInfo.innerMostGroupDesc.appCookie());
783 // Add L3 interface group to the chain if there is one.
784 if (!groupInfo.nextGroupDesc.equals(groupInfo.innerMostGroupDesc)) {
785 gkeyChain.addFirst(groupInfo.nextGroupDesc.appCookie());
786 }
787 gkeyChain.addFirst(l3MulticastGroupKey);
788 allGroupKeys.add(gkeyChain);
789 });
790
791 // Point the next objective to this group
792 OfdpaNextGroup ofdpaGrp = new OfdpaNextGroup(allGroupKeys, nextObj);
793 updatePendingNextObjective(l3MulticastGroupKey, ofdpaGrp);
794
795 GroupChainElem outerGce = new GroupChainElem(l3MulticastGroupDesc,
796 groupInfos.size(), false);
797 groupInfos.forEach(groupInfo -> {
798 // Point this group (L3 multicast) to the next group
799 updatePendingGroups(groupInfo.nextGroupDesc.appCookie(), outerGce);
800
801 // Point next group to inner-most group, if any
802 if (!groupInfo.nextGroupDesc.equals(groupInfo.innerMostGroupDesc)) {
803 GroupChainElem innerGce = new GroupChainElem(groupInfo.nextGroupDesc,
804 1, false);
805 updatePendingGroups(groupInfo.innerMostGroupDesc.appCookie(), innerGce);
806 }
807
808 // Start installing the inner-most group
809 groupService.addGroup(groupInfo.innerMostGroupDesc);
810 });
Charles Chan188ebf52015-12-23 00:15:11 -0800811 }
812
Charles Chan188ebf52015-12-23 00:15:11 -0800813 /**
814 * As per the OFDPA 2.0 TTP, packets are sent out of ports by using
815 * a chain of groups. The hashed Next Objective passed in by the application
816 * has to be broken up into a group chain comprising of an
817 * L3 ECMP group as the top level group. Buckets of this group can point
818 * to a variety of groups in a group chain, depending on the whether
819 * MPLS labels are being pushed or not.
820 * <p>
821 * NOTE: We do not create MPLS ECMP groups as they are unimplemented in
822 * OF-DPA 2.0 (even though it is in the spec). Therefore we do not
823 * check the nextObjective meta to see what is matching before being
824 * sent to this nextObjective.
825 *
826 * @param nextObj the nextObjective of type HASHED
827 */
Pier Ventre140a8942016-11-02 07:26:38 -0700828 protected void processHashedNextObjective(NextObjective nextObj) {
Charles Chan188ebf52015-12-23 00:15:11 -0800829 // storage for all group keys in the chain of groups created
830 List<Deque<GroupKey>> allGroupKeys = new ArrayList<>();
831 List<GroupInfo> unsentGroups = new ArrayList<>();
832 createHashBucketChains(nextObj, allGroupKeys, unsentGroups);
833
834 // now we can create the outermost L3 ECMP group
835 List<GroupBucket> l3ecmpGroupBuckets = new ArrayList<>();
836 for (GroupInfo gi : unsentGroups) {
837 // create ECMP bucket to point to the outer group
838 TrafficTreatment.Builder ttb = DefaultTrafficTreatment.builder();
Yi Tsengfa394de2017-02-01 11:26:40 -0800839 ttb.group(new GroupId(gi.nextGroupDesc.givenGroupId()));
Charles Chan188ebf52015-12-23 00:15:11 -0800840 GroupBucket sbucket = DefaultGroupBucket
841 .createSelectGroupBucket(ttb.build());
842 l3ecmpGroupBuckets.add(sbucket);
843 }
Saurav Das8be4e3a2016-03-11 17:19:07 -0800844 int l3ecmpIndex = getNextAvailableIndex();
845 int l3ecmpGroupId = L3_ECMP_TYPE | (TYPE_MASK & l3ecmpIndex);
846 GroupKey l3ecmpGroupKey = new DefaultGroupKey(
Charles Chan361154b2016-03-24 10:23:39 -0700847 Ofdpa2Pipeline.appKryo.serialize(l3ecmpIndex));
Charles Chan188ebf52015-12-23 00:15:11 -0800848 GroupDescription l3ecmpGroupDesc =
849 new DefaultGroupDescription(
850 deviceId,
Yi Tseng78f51f42017-02-02 13:54:58 -0800851 SELECT,
Charles Chan188ebf52015-12-23 00:15:11 -0800852 new GroupBuckets(l3ecmpGroupBuckets),
853 l3ecmpGroupKey,
854 l3ecmpGroupId,
855 nextObj.appId());
856 GroupChainElem l3ecmpGce = new GroupChainElem(l3ecmpGroupDesc,
857 l3ecmpGroupBuckets.size(),
858 false);
859
860 // create objects for local and distributed storage
861 allGroupKeys.forEach(gkeyChain -> gkeyChain.addFirst(l3ecmpGroupKey));
862 OfdpaNextGroup ofdpaGrp = new OfdpaNextGroup(allGroupKeys, nextObj);
863
864 // store l3ecmpGroupKey with the ofdpaGroupChain for the nextObjective
865 // that depends on it
866 updatePendingNextObjective(l3ecmpGroupKey, ofdpaGrp);
867
868 log.debug("Trying L3ECMP: device:{} gid:{} gkey:{} nextId:{}",
869 deviceId, Integer.toHexString(l3ecmpGroupId),
870 l3ecmpGroupKey, nextObj.id());
871 // finally we are ready to send the innermost groups
872 for (GroupInfo gi : unsentGroups) {
873 log.debug("Sending innermost group {} in group chain on device {} ",
Charles Chan5b9df8d2016-03-28 22:21:40 -0700874 Integer.toHexString(gi.innerMostGroupDesc.givenGroupId()), deviceId);
875 updatePendingGroups(gi.nextGroupDesc.appCookie(), l3ecmpGce);
876 groupService.addGroup(gi.innerMostGroupDesc);
Charles Chan188ebf52015-12-23 00:15:11 -0800877 }
878
879 }
880
881 /**
882 * Creates group chains for all buckets in a hashed group, and stores the
883 * GroupInfos and GroupKeys for all the groups in the lists passed in, which
884 * should be empty.
885 * <p>
886 * Does not create the top level ECMP group. Does not actually send the
887 * groups to the groupService.
888 *
889 * @param nextObj the Next Objective with buckets that need to be converted
890 * to group chains
891 * @param allGroupKeys a list to store groupKey for each bucket-group-chain
892 * @param unsentGroups a list to store GroupInfo for each bucket-group-chain
893 */
Pier Ventre140a8942016-11-02 07:26:38 -0700894 protected void createHashBucketChains(NextObjective nextObj,
Saurav Das8be4e3a2016-03-11 17:19:07 -0800895 List<Deque<GroupKey>> allGroupKeys,
896 List<GroupInfo> unsentGroups) {
Charles Chan188ebf52015-12-23 00:15:11 -0800897 // break up hashed next objective to multiple groups
898 Collection<TrafficTreatment> buckets = nextObj.next();
899
900 for (TrafficTreatment bucket : buckets) {
901 //figure out how many labels are pushed in each bucket
902 int labelsPushed = 0;
903 MplsLabel innermostLabel = null;
904 for (Instruction ins : bucket.allInstructions()) {
905 if (ins.type() == Instruction.Type.L2MODIFICATION) {
906 L2ModificationInstruction l2ins = (L2ModificationInstruction) ins;
907 if (l2ins.subtype() == L2ModificationInstruction.L2SubType.MPLS_PUSH) {
908 labelsPushed++;
909 }
910 if (l2ins.subtype() == L2ModificationInstruction.L2SubType.MPLS_LABEL) {
911 if (innermostLabel == null) {
Ray Milkey125572b2016-02-22 16:48:17 -0800912 innermostLabel = ((L2ModificationInstruction.ModMplsLabelInstruction) l2ins).label();
Charles Chan188ebf52015-12-23 00:15:11 -0800913 }
914 }
915 }
916 }
917
918 Deque<GroupKey> gkeyChain = new ArrayDeque<>();
919 // XXX we only deal with 0 and 1 label push right now
920 if (labelsPushed == 0) {
Pier Ventre140a8942016-11-02 07:26:38 -0700921 GroupInfo nolabelGroupInfo;
922 TrafficSelector metaSelector = nextObj.meta();
923 if (metaSelector != null) {
924 if (isNotMplsBos(metaSelector)) {
925 nolabelGroupInfo = createL2L3Chain(bucket, nextObj.id(),
926 nextObj.appId(), true,
927 nextObj.meta());
928 } else {
929 nolabelGroupInfo = createL2L3Chain(bucket, nextObj.id(),
930 nextObj.appId(), false,
931 nextObj.meta());
932 }
933 } else {
934 nolabelGroupInfo = createL2L3Chain(bucket, nextObj.id(),
935 nextObj.appId(), false,
936 nextObj.meta());
937 }
Charles Chan188ebf52015-12-23 00:15:11 -0800938 if (nolabelGroupInfo == null) {
939 log.error("Could not process nextObj={} in dev:{}",
940 nextObj.id(), deviceId);
941 return;
942 }
Charles Chan5b9df8d2016-03-28 22:21:40 -0700943 gkeyChain.addFirst(nolabelGroupInfo.innerMostGroupDesc.appCookie());
944 gkeyChain.addFirst(nolabelGroupInfo.nextGroupDesc.appCookie());
Charles Chan188ebf52015-12-23 00:15:11 -0800945
946 // we can't send the inner group description yet, as we have to
947 // create the dependent ECMP group first. So we store..
948 unsentGroups.add(nolabelGroupInfo);
949
950 } else if (labelsPushed == 1) {
951 GroupInfo onelabelGroupInfo = createL2L3Chain(bucket, nextObj.id(),
952 nextObj.appId(), true,
953 nextObj.meta());
954 if (onelabelGroupInfo == null) {
955 log.error("Could not process nextObj={} in dev:{}",
956 nextObj.id(), deviceId);
957 return;
958 }
959 // we need to add another group to this chain - the L3VPN group
960 TrafficTreatment.Builder l3vpnTtb = DefaultTrafficTreatment.builder();
Charles Chan0f43e472017-02-14 14:00:16 -0800961 if (requireVlanPopBeforeMplsPush()) {
962 l3vpnTtb.popVlan();
963 }
Charles Chan188ebf52015-12-23 00:15:11 -0800964 l3vpnTtb.pushMpls()
965 .setMpls(innermostLabel)
Yi Tsengfa394de2017-02-01 11:26:40 -0800966 .group(new GroupId(onelabelGroupInfo.nextGroupDesc.givenGroupId()));
Charles Chan40132b32017-01-22 00:19:37 -0800967 if (supportCopyTtl()) {
968 l3vpnTtb.copyTtlOut();
969 }
970 if (supportSetMplsBos()) {
971 l3vpnTtb.setMplsBos(true);
972 }
Charles Chan0f43e472017-02-14 14:00:16 -0800973 if (requireVlanPopBeforeMplsPush()) {
974 l3vpnTtb.pushVlan().setVlanId(VlanId.vlanId(VlanId.RESERVED));
975 }
Charles Chan40132b32017-01-22 00:19:37 -0800976
Charles Chan188ebf52015-12-23 00:15:11 -0800977 GroupBucket l3vpnGrpBkt =
978 DefaultGroupBucket.createIndirectGroupBucket(l3vpnTtb.build());
Saurav Das8be4e3a2016-03-11 17:19:07 -0800979 int l3vpnIndex = getNextAvailableIndex();
980 int l3vpngroupId = MPLS_L3VPN_SUBTYPE | (SUBTYPE_MASK & l3vpnIndex);
981 GroupKey l3vpngroupkey = new DefaultGroupKey(
Charles Chan361154b2016-03-24 10:23:39 -0700982 Ofdpa2Pipeline.appKryo.serialize(l3vpnIndex));
Charles Chan188ebf52015-12-23 00:15:11 -0800983 GroupDescription l3vpnGroupDesc =
984 new DefaultGroupDescription(
985 deviceId,
986 GroupDescription.Type.INDIRECT,
987 new GroupBuckets(Collections.singletonList(
988 l3vpnGrpBkt)),
989 l3vpngroupkey,
990 l3vpngroupId,
991 nextObj.appId());
992 GroupChainElem l3vpnGce = new GroupChainElem(l3vpnGroupDesc, 1, false);
Charles Chan5b9df8d2016-03-28 22:21:40 -0700993 updatePendingGroups(onelabelGroupInfo.nextGroupDesc.appCookie(), l3vpnGce);
Charles Chan188ebf52015-12-23 00:15:11 -0800994
Charles Chan5b9df8d2016-03-28 22:21:40 -0700995 gkeyChain.addFirst(onelabelGroupInfo.innerMostGroupDesc.appCookie());
996 gkeyChain.addFirst(onelabelGroupInfo.nextGroupDesc.appCookie());
Charles Chan188ebf52015-12-23 00:15:11 -0800997 gkeyChain.addFirst(l3vpngroupkey);
998
999 //now we can replace the outerGrpDesc with the one we just created
Charles Chan5b9df8d2016-03-28 22:21:40 -07001000 onelabelGroupInfo.nextGroupDesc = l3vpnGroupDesc;
Charles Chan188ebf52015-12-23 00:15:11 -08001001
1002 // we can't send the innermost group yet, as we have to create
1003 // the dependent ECMP group first. So we store ...
1004 unsentGroups.add(onelabelGroupInfo);
1005
1006 log.debug("Trying L3VPN: device:{} gid:{} gkey:{} nextId:{}",
1007 deviceId, Integer.toHexString(l3vpngroupId),
1008 l3vpngroupkey, nextObj.id());
1009
1010 } else {
1011 log.warn("Driver currently does not handle more than 1 MPLS "
1012 + "labels. Not processing nextObjective {}", nextObj.id());
1013 return;
1014 }
1015
1016 // all groups in this chain
1017 allGroupKeys.add(gkeyChain);
1018 }
1019 }
1020
Pier Ventre42287df2016-11-09 14:17:26 -08001021 /**
1022 * Processes the pseudo wire related next objective.
1023 * This procedure try to reuse the mpls label groups,
1024 * the mpls interface group and the l2 interface group.
1025 *
1026 * @param nextObjective the objective to process.
1027 */
1028 protected void processPwNextObjective(NextObjective nextObjective) {
1029 log.warn("Pseudo wire extensions are not support for the OFDPA 2.0 {}", nextObjective.id());
1030 return;
1031 }
1032
Saurav Das8be4e3a2016-03-11 17:19:07 -08001033 //////////////////////////////////////
1034 // Group Editing
1035 //////////////////////////////////////
1036
Charles Chan188ebf52015-12-23 00:15:11 -08001037 /**
1038 * Adds a bucket to the top level group of a group-chain, and creates the chain.
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001039 * Ensures that bucket being added is not a duplicate, by checking existing
1040 * buckets for the same outport.
Charles Chan188ebf52015-12-23 00:15:11 -08001041 *
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001042 * @param nextObjective the bucket information for a next group
Charles Chan188ebf52015-12-23 00:15:11 -08001043 * @param next the representation of the existing group-chain for this next objective
1044 */
1045 protected void addBucketToGroup(NextObjective nextObjective, NextGroup next) {
Saurav Das1a129a02016-11-18 15:21:57 -08001046 if (nextObjective.type() != NextObjective.Type.HASHED &&
1047 nextObjective.type() != NextObjective.Type.BROADCAST) {
Charles Chan188ebf52015-12-23 00:15:11 -08001048 log.warn("AddBuckets not applied to nextType:{} in dev:{} for next:{}",
Yi Tseng78f51f42017-02-02 13:54:58 -08001049 nextObjective.type(), deviceId, nextObjective.id());
Saurav Das1a129a02016-11-18 15:21:57 -08001050 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.UNSUPPORTED);
Charles Chan188ebf52015-12-23 00:15:11 -08001051 return;
1052 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001053
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001054 // first check to see if bucket being added is not a duplicate of an
1055 // existing bucket. If it is for an existing outport, then its a duplicate.
Yi Tseng78f51f42017-02-02 13:54:58 -08001056 Set<TrafficTreatment> duplicateBuckets = Sets.newHashSet();
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001057 List<Deque<GroupKey>> allActiveKeys = Ofdpa2Pipeline.appKryo.deserialize(next.data());
Yi Tseng78f51f42017-02-02 13:54:58 -08001058 Set<PortNumber> existingPorts = getExistingOutputPorts(allActiveKeys);
Yi Tseng47f82dc2017-03-05 22:48:39 -08001059 Set<TrafficTreatment> nonDuplicateBuckets = Sets.newHashSet();
1060 NextObjective objectiveToAdd;
Yi Tseng78f51f42017-02-02 13:54:58 -08001061
1062 nextObjective.next().forEach(trafficTreatment -> {
1063 PortNumber portNumber = readOutPortFromTreatment(trafficTreatment);
1064
1065 if (portNumber == null) {
1066 return;
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001067 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001068
1069 if (existingPorts.contains(portNumber)) {
1070 duplicateBuckets.add(trafficTreatment);
Yi Tseng47f82dc2017-03-05 22:48:39 -08001071 } else {
1072 nonDuplicateBuckets.add(trafficTreatment);
Yi Tseng78f51f42017-02-02 13:54:58 -08001073 }
1074 });
1075
Saurav Dasb28d5dd2017-03-24 19:03:58 -07001076 if (duplicateBuckets.isEmpty()) {
1077 // use the original objective
1078 objectiveToAdd = nextObjective;
1079 } else if (!nonDuplicateBuckets.isEmpty()) {
1080 // only use the non-duplicate buckets if there are any
1081 log.debug("Some buckets {} already exist in next id {}, duplicate "
1082 + "buckets will be ignored.", duplicateBuckets, nextObjective.id());
1083 // new next objective with non duplicate treatments
Yi Tseng47f82dc2017-03-05 22:48:39 -08001084 NextObjective.Builder builder = DefaultNextObjective.builder()
1085 .withType(nextObjective.type())
1086 .withId(nextObjective.id())
1087 .withMeta(nextObjective.meta())
1088 .fromApp(nextObjective.appId());
1089 nonDuplicateBuckets.forEach(builder::addTreatment);
1090
1091 ObjectiveContext context = nextObjective.context().orElse(null);
1092 objectiveToAdd = builder.addToExisting(context);
1093 } else {
Saurav Dasb28d5dd2017-03-24 19:03:58 -07001094 // buckets to add are already there - nothing to do
1095 return;
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001096 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001097
Saurav Das1a129a02016-11-18 15:21:57 -08001098 if (nextObjective.type() == NextObjective.Type.HASHED) {
Yi Tseng47f82dc2017-03-05 22:48:39 -08001099 addBucketToHashGroup(objectiveToAdd, allActiveKeys);
Saurav Das1a129a02016-11-18 15:21:57 -08001100 } else if (nextObjective.type() == NextObjective.Type.BROADCAST) {
Yi Tseng47f82dc2017-03-05 22:48:39 -08001101 addBucketToBroadcastGroup(objectiveToAdd, allActiveKeys);
Saurav Das1a129a02016-11-18 15:21:57 -08001102 }
1103 }
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001104
Yi Tseng78f51f42017-02-02 13:54:58 -08001105 private Set<PortNumber> getExistingOutputPorts(List<Deque<GroupKey>> allActiveKeys) {
1106 Set<PortNumber> existingPorts = Sets.newHashSet();
1107
1108 allActiveKeys.forEach(keyChain -> {
1109 GroupKey ifaceGroupKey = keyChain.peekLast();
1110 Group ifaceGroup = groupService.getGroup(deviceId, ifaceGroupKey);
1111 if (ifaceGroup != null && !ifaceGroup.buckets().buckets().isEmpty()) {
1112 ifaceGroup.buckets().buckets().forEach(bucket -> {
1113 PortNumber portNumber = readOutPortFromTreatment(bucket.treatment());
1114
1115 if (portNumber != null) {
1116 existingPorts.add(portNumber);
1117 }
1118 });
1119 }
1120 });
1121
1122 return existingPorts;
1123 }
1124
Saurav Das1a129a02016-11-18 15:21:57 -08001125 private void addBucketToHashGroup(NextObjective nextObjective,
Yi Tseng78f51f42017-02-02 13:54:58 -08001126 List<Deque<GroupKey>> allActiveKeys) {
Charles Chan188ebf52015-12-23 00:15:11 -08001127 // storage for all group keys in the chain of groups created
1128 List<Deque<GroupKey>> allGroupKeys = new ArrayList<>();
1129 List<GroupInfo> unsentGroups = new ArrayList<>();
Yi Tseng78f51f42017-02-02 13:54:58 -08001130 List<GroupBucket> newBuckets = Lists.newArrayList();
Charles Chan188ebf52015-12-23 00:15:11 -08001131 createHashBucketChains(nextObjective, allGroupKeys, unsentGroups);
1132
Yi Tseng78f51f42017-02-02 13:54:58 -08001133 // now we can create the buckets to add to the outermost L3 ECMP group
1134 newBuckets = generateNextGroupBuckets(unsentGroups, SELECT);
Charles Chan188ebf52015-12-23 00:15:11 -08001135
Saurav Das1a129a02016-11-18 15:21:57 -08001136 // retrieve the original L3 ECMP group
1137 Group l3ecmpGroup = retrieveTopLevelGroup(allActiveKeys, nextObjective.id());
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001138 if (l3ecmpGroup == null) {
Saurav Das1a129a02016-11-18 15:21:57 -08001139 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.GROUPMISSING);
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001140 return;
1141 }
Saurav Das1a129a02016-11-18 15:21:57 -08001142 GroupKey l3ecmpGroupKey = l3ecmpGroup.appCookie();
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001143 int l3ecmpGroupId = l3ecmpGroup.id().id();
Charles Chan188ebf52015-12-23 00:15:11 -08001144
1145 // Although GroupDescriptions are not necessary for adding buckets to
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001146 // existing groups, we still use one in the GroupChainElem. When the latter is
Charles Chan188ebf52015-12-23 00:15:11 -08001147 // processed, the info will be extracted for the bucketAdd call to groupService
1148 GroupDescription l3ecmpGroupDesc =
1149 new DefaultGroupDescription(
1150 deviceId,
Yi Tseng78f51f42017-02-02 13:54:58 -08001151 SELECT,
1152 new GroupBuckets(newBuckets),
Charles Chan188ebf52015-12-23 00:15:11 -08001153 l3ecmpGroupKey,
1154 l3ecmpGroupId,
1155 nextObjective.appId());
Yi Tseng78f51f42017-02-02 13:54:58 -08001156 GroupChainElem l3ecmpGce = new GroupChainElem(l3ecmpGroupDesc,
1157 unsentGroups.size(),
1158 true);
Charles Chan188ebf52015-12-23 00:15:11 -08001159
1160 // update original NextGroup with new bucket-chain
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001161 // If active keys shows only the top-level group without a chain of groups,
1162 // then it represents an empty group. Update by replacing empty chain.
Charles Chan188ebf52015-12-23 00:15:11 -08001163 Deque<GroupKey> newBucketChain = allGroupKeys.get(0);
1164 newBucketChain.addFirst(l3ecmpGroupKey);
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001165 if (allActiveKeys.size() == 1 && allActiveKeys.get(0).size() == 1) {
1166 allActiveKeys.clear();
1167 }
1168 allActiveKeys.add(newBucketChain);
1169 updatePendingNextObjective(l3ecmpGroupKey,
1170 new OfdpaNextGroup(allActiveKeys, nextObjective));
Yi Tseng78f51f42017-02-02 13:54:58 -08001171
Charles Chan188ebf52015-12-23 00:15:11 -08001172 log.debug("Adding to L3ECMP: device:{} gid:{} gkey:{} nextId:{}",
1173 deviceId, Integer.toHexString(l3ecmpGroupId),
1174 l3ecmpGroupKey, nextObjective.id());
Yi Tseng78f51f42017-02-02 13:54:58 -08001175
1176 unsentGroups.forEach(groupInfo -> {
1177 // send the innermost group
1178 log.debug("Sending innermost group {} in group chain on device {} ",
1179 Integer.toHexString(groupInfo.innerMostGroupDesc.givenGroupId()), deviceId);
1180 updatePendingGroups(groupInfo.nextGroupDesc.appCookie(), l3ecmpGce);
1181 groupService.addGroup(groupInfo.innerMostGroupDesc);
1182 });
1183
Saurav Das1a129a02016-11-18 15:21:57 -08001184 }
Charles Chan188ebf52015-12-23 00:15:11 -08001185
Saurav Das1a129a02016-11-18 15:21:57 -08001186 private void addBucketToBroadcastGroup(NextObjective nextObj,
Yi Tseng78f51f42017-02-02 13:54:58 -08001187 List<Deque<GroupKey>> allActiveKeys) {
Saurav Das1a129a02016-11-18 15:21:57 -08001188 VlanId assignedVlan = Ofdpa2Pipeline.readVlanFromSelector(nextObj.meta());
1189 if (assignedVlan == null) {
1190 log.warn("VLAN ID required by broadcast next obj is missing. "
1191 + "Aborting add bucket to broadcast group for next:{} in dev:{}",
1192 nextObj.id(), deviceId);
1193 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.BADPARAMS);
1194 return;
1195 }
1196
1197 List<GroupInfo> groupInfos = prepareL2InterfaceGroup(nextObj, assignedVlan);
1198
1199 IpPrefix ipDst = Ofdpa2Pipeline.readIpDstFromSelector(nextObj.meta());
1200 if (ipDst != null) {
1201 if (ipDst.isMulticast()) {
1202 addBucketToL3MulticastGroup(nextObj, allActiveKeys,
Yi Tseng78f51f42017-02-02 13:54:58 -08001203 groupInfos, assignedVlan);
Saurav Das1a129a02016-11-18 15:21:57 -08001204 } else {
1205 log.warn("Broadcast NextObj with non-multicast IP address {}", nextObj);
1206 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.BADPARAMS);
1207 return;
1208 }
1209 } else {
1210 addBucketToL2FloodGroup(nextObj, allActiveKeys,
Yi Tseng78f51f42017-02-02 13:54:58 -08001211 groupInfos, assignedVlan);
Saurav Das1a129a02016-11-18 15:21:57 -08001212 }
1213 }
1214
1215 private void addBucketToL2FloodGroup(NextObjective nextObj,
1216 List<Deque<GroupKey>> allActiveKeys,
1217 List<GroupInfo> groupInfos,
Yi Tseng78f51f42017-02-02 13:54:58 -08001218 VlanId assignedVlan) {
1219 Group l2FloodGroup = retrieveTopLevelGroup(allActiveKeys, nextObj.id());
1220
1221 if (l2FloodGroup == null) {
1222 log.warn("Can't find L2 flood group while adding bucket to it. NextObj = {}",
1223 nextObj);
Saurav Das1a129a02016-11-18 15:21:57 -08001224 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.GROUPMISSING);
1225 return;
1226 }
Saurav Das1a129a02016-11-18 15:21:57 -08001227
Yi Tseng78f51f42017-02-02 13:54:58 -08001228 GroupKey l2floodGroupKey = l2FloodGroup.appCookie();
1229 int l2floodGroupId = l2FloodGroup.id().id();
1230 List<GroupBucket> newBuckets = generateNextGroupBuckets(groupInfos, ALL);
1231
1232 GroupDescription l2FloodGroupDescription =
Saurav Das1a129a02016-11-18 15:21:57 -08001233 new DefaultGroupDescription(
1234 deviceId,
Yi Tseng78f51f42017-02-02 13:54:58 -08001235 ALL,
1236 new GroupBuckets(newBuckets),
Saurav Das1a129a02016-11-18 15:21:57 -08001237 l2floodGroupKey,
1238 l2floodGroupId,
1239 nextObj.appId());
Saurav Das1a129a02016-11-18 15:21:57 -08001240
Yi Tseng78f51f42017-02-02 13:54:58 -08001241 GroupChainElem l2FloodGroupChainElement =
1242 new GroupChainElem(l2FloodGroupDescription,
1243 groupInfos.size(),
1244 true);
1245
Saurav Das1a129a02016-11-18 15:21:57 -08001246 updatePendingNextObjective(l2floodGroupKey,
1247 new OfdpaNextGroup(allActiveKeys, nextObj));
Yi Tseng78f51f42017-02-02 13:54:58 -08001248
1249 //ensure assignedVlan applies to the chosen group
1250 VlanId floodGroupVlan = extractVlanIdFromGroupId(l2floodGroupId);
1251
1252 if (!floodGroupVlan.equals(assignedVlan)) {
1253 log.warn("VLAN ID {} does not match Flood group {} to which bucket is "
1254 + "being added, for next:{} in dev:{}. Abort.", assignedVlan,
1255 Integer.toHexString(l2floodGroupId), nextObj.id(), deviceId);
1256 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.BADPARAMS);
1257 return;
1258 }
1259
1260 groupInfos.forEach(groupInfo -> {
1261 // update original NextGroup with new bucket-chain
1262 // If active keys shows only the top-level group without a chain of groups,
1263 // then it represents an empty group. Update by replacing empty chain.
1264 Deque<GroupKey> newBucketChain = new ArrayDeque<>();
1265 newBucketChain.addFirst(groupInfo.nextGroupDesc.appCookie());
1266 newBucketChain.addFirst(l2floodGroupKey);
1267 if (allActiveKeys.size() == 1 && allActiveKeys.get(0).size() == 1) {
1268 allActiveKeys.clear();
1269 }
1270 allActiveKeys.add(newBucketChain);
1271
1272 log.debug("Adding to L2FLOOD: device:{} gid:{} gkey:{} nextId:{}",
1273 deviceId, Integer.toHexString(l2floodGroupId),
1274 l2floodGroupKey, nextObj.id());
1275 // send the innermost group
1276 log.debug("Sending innermost group {} in group chain on device {} ",
1277 Integer.toHexString(groupInfo.innerMostGroupDesc.givenGroupId()),
1278 deviceId);
1279
1280 updatePendingGroups(groupInfo.nextGroupDesc.appCookie(), l2FloodGroupChainElement);
1281
1282 DeviceId innerMostGroupDevice = groupInfo.innerMostGroupDesc.deviceId();
1283 GroupKey innerMostGroupKey = groupInfo.innerMostGroupDesc.appCookie();
1284 Group existsL2IGroup = groupService.getGroup(innerMostGroupDevice, innerMostGroupKey);
1285
1286 if (existsL2IGroup != null) {
1287 // group already exist
1288 processPendingAddGroupsOrNextObjs(innerMostGroupKey, true);
1289 } else {
1290 groupService.addGroup(groupInfo.innerMostGroupDesc);
1291 }
1292
1293 });
1294 }
1295
1296 private VlanId extractVlanIdFromGroupId(int groupId) {
1297 // Extract the 9th to 20th bit from group id as vlan id.
1298 short vlanId = (short) ((groupId & 0x0fff0000) >> 16);
1299 return VlanId.vlanId(vlanId);
1300 }
1301
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001302 private List<GroupBucket> generateNextGroupBuckets(List<GroupInfo> groupInfos,
1303 GroupDescription.Type bucketType) {
Yi Tseng78f51f42017-02-02 13:54:58 -08001304 List<GroupBucket> newBuckets = Lists.newArrayList();
1305
1306 groupInfos.forEach(groupInfo -> {
1307 GroupDescription groupDesc = groupInfo.nextGroupDesc;
1308 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
Yi Tsengfa394de2017-02-01 11:26:40 -08001309 treatmentBuilder.group(new GroupId(groupDesc.givenGroupId()));
Yi Tseng78f51f42017-02-02 13:54:58 -08001310 GroupBucket newBucket = null;
1311 switch (bucketType) {
1312 case ALL:
1313 newBucket =
1314 DefaultGroupBucket.createAllGroupBucket(treatmentBuilder.build());
1315 break;
1316 case INDIRECT:
1317 newBucket =
1318 DefaultGroupBucket.createIndirectGroupBucket(treatmentBuilder.build());
1319 break;
1320 case SELECT:
1321 newBucket =
1322 DefaultGroupBucket.createSelectGroupBucket(treatmentBuilder.build());
1323 break;
1324 case FAILOVER:
1325 // TODO support failover bucket type
1326 default:
1327 log.warn("Unknown bucket type: {}", bucketType);
1328 break;
1329 }
1330
1331 if (newBucket != null) {
1332 newBuckets.add(newBucket);
1333 }
1334
1335 });
1336
1337 return ImmutableList.copyOf(newBuckets);
Saurav Das1a129a02016-11-18 15:21:57 -08001338 }
1339
1340 private void addBucketToL3MulticastGroup(NextObjective nextObj,
1341 List<Deque<GroupKey>> allActiveKeys,
1342 List<GroupInfo> groupInfos,
Yi Tseng78f51f42017-02-02 13:54:58 -08001343 VlanId assignedVlan) {
1344 // create the buckets to add to the outermost L3 Multicast group
1345 List<GroupBucket> newBuckets = Lists.newArrayList();
1346 groupInfos.forEach(groupInfo -> {
1347 // Points to L3 interface group if there is one.
1348 // Otherwise points to L2 interface group directly.
1349 GroupDescription nextGroupDesc = (groupInfo.nextGroupDesc != null) ?
1350 groupInfo.nextGroupDesc : groupInfo.innerMostGroupDesc;
1351 TrafficTreatment.Builder treatmentBuidler = DefaultTrafficTreatment.builder();
Yi Tsengfa394de2017-02-01 11:26:40 -08001352 treatmentBuidler.group(new GroupId(nextGroupDesc.givenGroupId()));
Yi Tseng78f51f42017-02-02 13:54:58 -08001353 GroupBucket newBucket = DefaultGroupBucket.createAllGroupBucket(treatmentBuidler.build());
1354 newBuckets.add(newBucket);
1355 });
Saurav Das1a129a02016-11-18 15:21:57 -08001356
1357 // get the group being edited
1358 Group l3mcastGroup = retrieveTopLevelGroup(allActiveKeys, nextObj.id());
1359 if (l3mcastGroup == null) {
1360 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.GROUPMISSING);
1361 return;
1362 }
1363 GroupKey l3mcastGroupKey = l3mcastGroup.appCookie();
1364 int l3mcastGroupId = l3mcastGroup.id().id();
1365
1366 //ensure assignedVlan applies to the chosen group
Yi Tseng78f51f42017-02-02 13:54:58 -08001367 VlanId expectedVlan = extractVlanIdFromGroupId(l3mcastGroupId);
Saurav Das1a129a02016-11-18 15:21:57 -08001368 if (!expectedVlan.equals(assignedVlan)) {
1369 log.warn("VLAN ID {} does not match L3 Mcast group {} to which bucket is "
1370 + "being added, for next:{} in dev:{}. Abort.", assignedVlan,
1371 Integer.toHexString(l3mcastGroupId), nextObj.id(), deviceId);
1372 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.BADPARAMS);
1373 }
1374 GroupDescription l3mcastGroupDescription =
1375 new DefaultGroupDescription(
1376 deviceId,
Yi Tseng78f51f42017-02-02 13:54:58 -08001377 ALL,
1378 new GroupBuckets(newBuckets),
Saurav Das1a129a02016-11-18 15:21:57 -08001379 l3mcastGroupKey,
1380 l3mcastGroupId,
1381 nextObj.appId());
1382 GroupChainElem l3mcastGce = new GroupChainElem(l3mcastGroupDescription,
Yi Tseng78f51f42017-02-02 13:54:58 -08001383 groupInfos.size(), true);
Saurav Das1a129a02016-11-18 15:21:57 -08001384
Yi Tseng78f51f42017-02-02 13:54:58 -08001385 groupInfos.forEach(groupInfo -> {
1386 // update original NextGroup with new bucket-chain
1387 Deque<GroupKey> newBucketChain = new ArrayDeque<>();
1388 newBucketChain.addFirst(groupInfo.innerMostGroupDesc.appCookie());
1389 // Add L3 interface group to the chain if there is one.
1390 if (!groupInfo.nextGroupDesc.equals(groupInfo.innerMostGroupDesc)) {
1391 newBucketChain.addFirst(groupInfo.nextGroupDesc.appCookie());
1392 }
1393 newBucketChain.addFirst(l3mcastGroupKey);
1394 // If active keys shows only the top-level group without a chain of groups,
1395 // then it represents an empty group. Update by replacing empty chain.
1396 if (allActiveKeys.size() == 1 && allActiveKeys.get(0).size() == 1) {
1397 allActiveKeys.clear();
1398 }
1399 allActiveKeys.add(newBucketChain);
1400
1401 updatePendingGroups(groupInfo.nextGroupDesc.appCookie(), l3mcastGce);
1402 // Point next group to inner-most group, if any
1403 if (!groupInfo.nextGroupDesc.equals(groupInfo.innerMostGroupDesc)) {
1404 GroupChainElem innerGce = new GroupChainElem(groupInfo.nextGroupDesc,
1405 1, false);
1406 updatePendingGroups(groupInfo.innerMostGroupDesc.appCookie(), innerGce);
1407 }
1408 log.debug("Adding to L3MCAST: device:{} gid:{} gkey:{} nextId:{}",
1409 deviceId, Integer.toHexString(l3mcastGroupId),
1410 l3mcastGroupKey, nextObj.id());
1411 // send the innermost group
1412 log.debug("Sending innermost group {} in group chain on device {} ",
1413 Integer.toHexString(groupInfo.innerMostGroupDesc.givenGroupId()),
1414 deviceId);
1415 groupService.addGroup(groupInfo.innerMostGroupDesc);
1416
1417 });
1418
Saurav Das1a129a02016-11-18 15:21:57 -08001419 updatePendingNextObjective(l3mcastGroupKey,
1420 new OfdpaNextGroup(allActiveKeys, nextObj));
1421
Yi Tseng78f51f42017-02-02 13:54:58 -08001422
1423
Charles Chan188ebf52015-12-23 00:15:11 -08001424 }
1425
1426 /**
1427 * Removes the bucket in the top level group of a possible group-chain. Does
Saurav Das1a129a02016-11-18 15:21:57 -08001428 * not remove the groups in the group-chain pointed to by this bucket, as they
Charles Chan188ebf52015-12-23 00:15:11 -08001429 * may be in use (referenced by other groups) elsewhere.
1430 *
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001431 * @param nextObjective the bucket information for a next group
Charles Chan188ebf52015-12-23 00:15:11 -08001432 * @param next the representation of the existing group-chain for this next objective
1433 */
1434 protected void removeBucketFromGroup(NextObjective nextObjective, NextGroup next) {
Saurav Das1a129a02016-11-18 15:21:57 -08001435 if (nextObjective.type() != NextObjective.Type.HASHED &&
1436 nextObjective.type() != NextObjective.Type.BROADCAST) {
Charles Chan188ebf52015-12-23 00:15:11 -08001437 log.warn("RemoveBuckets not applied to nextType:{} in dev:{} for next:{}",
1438 nextObjective.type(), deviceId, nextObjective.id());
Saurav Das1a129a02016-11-18 15:21:57 -08001439 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.UNSUPPORTED);
Charles Chan188ebf52015-12-23 00:15:11 -08001440 return;
1441 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001442 Set<PortNumber> portsToRemove = Sets.newHashSet();
Charles Chan188ebf52015-12-23 00:15:11 -08001443 Collection<TrafficTreatment> treatments = nextObjective.next();
Yi Tseng78f51f42017-02-02 13:54:58 -08001444 for (TrafficTreatment treatment : treatments) {
1445 // find the bucket to remove by noting the outport, and figuring out the
1446 // top-level group in the group-chain that indirectly references the port
1447 PortNumber portToRemove = readOutPortFromTreatment(treatment);
1448 if (portToRemove == null) {
1449 log.warn("treatment {} of next objective {} has no outport.. cannot remove bucket"
1450 + "from group in dev: {}", treatment, nextObjective.id(), deviceId);
1451 } else {
1452 portsToRemove.add(portToRemove);
1453 }
1454 }
1455
1456 if (portsToRemove.isEmpty()) {
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001457 log.warn("next objective {} has no outport.. cannot remove bucket"
Yi Tseng78f51f42017-02-02 13:54:58 -08001458 + "from group in dev: {}", nextObjective.id(), deviceId);
Saurav Das1a129a02016-11-18 15:21:57 -08001459 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.BADPARAMS);
Charles Chan188ebf52015-12-23 00:15:11 -08001460 }
1461
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001462 List<Deque<GroupKey>> allActiveKeys = Ofdpa2Pipeline.appKryo.deserialize(next.data());
Yi Tseng78f51f42017-02-02 13:54:58 -08001463 List<Deque<GroupKey>> chainsToRemove = Lists.newArrayList();
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001464 for (Deque<GroupKey> gkeys : allActiveKeys) {
1465 // last group in group chain should have a single bucket pointing to port
Yi Tseng78f51f42017-02-02 13:54:58 -08001466
Charles Chan188ebf52015-12-23 00:15:11 -08001467 GroupKey groupWithPort = gkeys.peekLast();
1468 Group group = groupService.getGroup(deviceId, groupWithPort);
1469 if (group == null) {
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001470 log.warn("Inconsistent group chain found when removing bucket"
1471 + "for next:{} in dev:{}", nextObjective.id(), deviceId);
Charles Chan188ebf52015-12-23 00:15:11 -08001472 continue;
1473 }
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001474 PortNumber pout = readOutPortFromTreatment(
1475 group.buckets().buckets().get(0).treatment());
Yi Tseng78f51f42017-02-02 13:54:58 -08001476 if (portsToRemove.contains(pout)) {
1477 chainsToRemove.add(gkeys);
Charles Chan188ebf52015-12-23 00:15:11 -08001478 }
Charles Chan188ebf52015-12-23 00:15:11 -08001479 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001480
1481 if (chainsToRemove.isEmpty()) {
Charles Chan188ebf52015-12-23 00:15:11 -08001482 log.warn("Could not find appropriate group-chain for removing bucket"
1483 + " for next id {} in dev:{}", nextObjective.id(), deviceId);
Saurav Das1a129a02016-11-18 15:21:57 -08001484 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.BADPARAMS);
1485 return;
Charles Chan188ebf52015-12-23 00:15:11 -08001486 }
Saurav Das1a129a02016-11-18 15:21:57 -08001487
Yi Tseng78f51f42017-02-02 13:54:58 -08001488 List<GroupBucket> bucketsToRemove = Lists.newArrayList();
1489 //first group key is the one we want to modify
1490 GroupKey modGroupKey = chainsToRemove.get(0).peekFirst();
Saurav Das1a129a02016-11-18 15:21:57 -08001491 Group modGroup = groupService.getGroup(deviceId, modGroupKey);
Yi Tseng78f51f42017-02-02 13:54:58 -08001492
1493 for (Deque<GroupKey> foundChain : chainsToRemove) {
1494 //second group key is the one we wish to remove the reference to
1495 if (foundChain.size() < 2) {
1496 // additional check to make sure second group key exist in
1497 // the chain.
1498 log.warn("Can't find second group key from chain {}",
1499 foundChain);
1500 continue;
Saurav Das1a129a02016-11-18 15:21:57 -08001501 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001502 GroupKey pointedGroupKey = foundChain.stream().collect(Collectors.toList()).get(1);
1503
1504 Group pointedGroup = groupService.getGroup(deviceId, pointedGroupKey);
1505
1506 if (pointedGroup == null) {
1507 continue;
1508 }
1509
1510 GroupBucket bucket;
1511 if (nextObjective.type() == NextObjective.Type.HASHED) {
1512 bucket = DefaultGroupBucket.createSelectGroupBucket(
1513 DefaultTrafficTreatment.builder()
1514 .group(pointedGroup.id())
1515 .build());
1516 } else {
1517 bucket = DefaultGroupBucket.createAllGroupBucket(
1518 DefaultTrafficTreatment.builder()
1519 .group(pointedGroup.id())
1520 .build());
1521 }
1522
1523 bucketsToRemove.add(bucket);
Saurav Das1a129a02016-11-18 15:21:57 -08001524 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001525
1526 GroupBuckets removeBuckets = new GroupBuckets(bucketsToRemove);
1527 List<String> pointedGroupIds; // for debug log
1528 pointedGroupIds = bucketsToRemove.stream()
1529 .map(GroupBucket::treatment)
1530 .map(TrafficTreatment::allInstructions)
1531 .flatMap(List::stream)
1532 .filter(inst -> inst instanceof Instructions.GroupInstruction)
1533 .map(inst -> (Instructions.GroupInstruction) inst)
1534 .map(Instructions.GroupInstruction::groupId)
1535 .map(GroupId::id)
1536 .map(Integer::toHexString)
1537 .map(id -> HEX_PREFIX + id)
1538 .collect(Collectors.toList());
1539
1540
1541
1542 log.debug("Removing buckets from group id 0x{} pointing to group id(s) {} "
Saurav Das1a129a02016-11-18 15:21:57 -08001543 + "for next id {} in device {}", Integer.toHexString(modGroup.id().id()),
Yi Tseng78f51f42017-02-02 13:54:58 -08001544 pointedGroupIds, nextObjective.id(), deviceId);
1545 addPendingUpdateNextObjective(modGroupKey, nextObjective);
Saurav Das1a129a02016-11-18 15:21:57 -08001546 groupService.removeBucketsFromGroup(deviceId, modGroupKey,
1547 removeBuckets, modGroupKey,
1548 nextObjective.appId());
1549 // update store
Yi Tsengeeb3dc12017-03-15 10:55:50 -07001550 allActiveKeys.removeAll(chainsToRemove);
1551 // If no buckets in the group, then retain an entry for the
1552 // top level group which still exists.
1553 if (allActiveKeys.isEmpty()) {
Saurav Das1a129a02016-11-18 15:21:57 -08001554 ArrayDeque<GroupKey> top = new ArrayDeque<>();
1555 top.add(modGroupKey);
1556 allActiveKeys.add(top);
1557 }
Saurav Das1a129a02016-11-18 15:21:57 -08001558 flowObjectiveStore.putNextGroup(nextObjective.id(),
1559 new OfdpaNextGroup(allActiveKeys,
1560 nextObjective));
Charles Chan188ebf52015-12-23 00:15:11 -08001561 }
1562
1563 /**
1564 * Removes all groups in multiple possible group-chains that represent the next
1565 * objective.
1566 *
1567 * @param nextObjective the next objective to remove
1568 * @param next the NextGroup that represents the existing group-chain for
1569 * this next objective
1570 */
1571 protected void removeGroup(NextObjective nextObjective, NextGroup next) {
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001572 List<Deque<GroupKey>> allActiveKeys = Ofdpa2Pipeline.appKryo.deserialize(next.data());
Charles Chanfc5c7802016-05-17 13:13:55 -07001573
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001574 List<GroupKey> groupKeys = allActiveKeys.stream()
Charles Chanfc5c7802016-05-17 13:13:55 -07001575 .map(Deque::getFirst).collect(Collectors.toList());
1576 pendingRemoveNextObjectives.put(nextObjective, groupKeys);
1577
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001578 allActiveKeys.forEach(groupChain -> groupChain.forEach(groupKey ->
Charles Chan188ebf52015-12-23 00:15:11 -08001579 groupService.removeGroup(deviceId, groupKey, nextObjective.appId())));
1580 flowObjectiveStore.removeNextGroup(nextObjective.id());
1581 }
1582
Saurav Das8be4e3a2016-03-11 17:19:07 -08001583 //////////////////////////////////////
1584 // Helper Methods and Classes
1585 //////////////////////////////////////
1586
Pier Ventre140a8942016-11-02 07:26:38 -07001587 protected void updatePendingNextObjective(GroupKey key, OfdpaNextGroup value) {
Saurav Das8be4e3a2016-03-11 17:19:07 -08001588 List<OfdpaNextGroup> nextList = new CopyOnWriteArrayList<OfdpaNextGroup>();
1589 nextList.add(value);
Charles Chanfc5c7802016-05-17 13:13:55 -07001590 List<OfdpaNextGroup> ret = pendingAddNextObjectives.asMap()
Saurav Das8be4e3a2016-03-11 17:19:07 -08001591 .putIfAbsent(key, nextList);
1592 if (ret != null) {
1593 ret.add(value);
1594 }
1595 }
1596
Charles Chan425854b2016-04-11 15:32:12 -07001597 protected void updatePendingGroups(GroupKey gkey, GroupChainElem gce) {
Saurav Das8be4e3a2016-03-11 17:19:07 -08001598 Set<GroupChainElem> gceSet = Collections.newSetFromMap(
1599 new ConcurrentHashMap<GroupChainElem, Boolean>());
1600 gceSet.add(gce);
1601 Set<GroupChainElem> retval = pendingGroups.putIfAbsent(gkey, gceSet);
1602 if (retval != null) {
1603 retval.add(gce);
1604 }
1605 }
1606
Yi Tseng78f51f42017-02-02 13:54:58 -08001607 private void addPendingUpdateNextObjective(GroupKey groupKey, NextObjective nextObjective) {
1608 pendingUpdateNextObjectives.compute(groupKey, (gKey, nextObjs) -> {
1609 if (nextObjs != null) {
1610 nextObjs.add(nextObjective);
1611 } else {
1612 nextObjs = Sets.newHashSet(nextObjective);
1613 }
1614 return nextObjs;
1615 });
1616 }
1617
Charles Chan188ebf52015-12-23 00:15:11 -08001618 /**
1619 * Processes next element of a group chain. Assumption is that if this
1620 * group points to another group, the latter has already been created
1621 * and this driver has received notification for it. A second assumption is
1622 * that if there is another group waiting for this group then the appropriate
1623 * stores already have the information to act upon the notification for the
1624 * creation of this group.
1625 * <p>
1626 * The processing of the GroupChainElement depends on the number of groups
1627 * this element is waiting on. For all group types other than SIMPLE, a
1628 * GroupChainElement could be waiting on multiple groups.
1629 *
1630 * @param gce the group chain element to be processed next
1631 */
1632 private void processGroupChain(GroupChainElem gce) {
1633 int waitOnGroups = gce.decrementAndGetGroupsWaitedOn();
1634 if (waitOnGroups != 0) {
1635 log.debug("GCE: {} not ready to be processed", gce);
1636 return;
1637 }
1638 log.debug("GCE: {} ready to be processed", gce);
1639 if (gce.addBucketToGroup) {
1640 groupService.addBucketsToGroup(gce.groupDescription.deviceId(),
1641 gce.groupDescription.appCookie(),
1642 gce.groupDescription.buckets(),
1643 gce.groupDescription.appCookie(),
1644 gce.groupDescription.appId());
1645 } else {
1646 groupService.addGroup(gce.groupDescription);
1647 }
1648 }
1649
1650 private class GroupChecker implements Runnable {
1651 @Override
1652 public void run() {
1653 Set<GroupKey> keys = pendingGroups.keySet().stream()
1654 .filter(key -> groupService.getGroup(deviceId, key) != null)
1655 .collect(Collectors.toSet());
Charles Chanfc5c7802016-05-17 13:13:55 -07001656 Set<GroupKey> otherkeys = pendingAddNextObjectives.asMap().keySet().stream()
Charles Chan188ebf52015-12-23 00:15:11 -08001657 .filter(otherkey -> groupService.getGroup(deviceId, otherkey) != null)
1658 .collect(Collectors.toSet());
1659 keys.addAll(otherkeys);
1660
Sho SHIMIZUa09e1bb2016-08-01 14:25:25 -07001661 keys.forEach(key ->
Charles Chanfc5c7802016-05-17 13:13:55 -07001662 processPendingAddGroupsOrNextObjs(key, false));
Charles Chan188ebf52015-12-23 00:15:11 -08001663 }
1664 }
1665
Saurav Das8be4e3a2016-03-11 17:19:07 -08001666 private class InnerGroupListener implements GroupListener {
1667 @Override
1668 public void event(GroupEvent event) {
1669 log.trace("received group event of type {}", event.type());
Charles Chanfc5c7802016-05-17 13:13:55 -07001670 switch (event.type()) {
1671 case GROUP_ADDED:
1672 processPendingAddGroupsOrNextObjs(event.subject().appCookie(), true);
1673 break;
1674 case GROUP_REMOVED:
1675 processPendingRemoveNextObjs(event.subject().appCookie());
1676 break;
Yi Tseng78f51f42017-02-02 13:54:58 -08001677 case GROUP_UPDATED:
1678 processPendingUpdateNextObjs(event.subject().appCookie());
1679 break;
Charles Chanfc5c7802016-05-17 13:13:55 -07001680 default:
1681 break;
Saurav Das8be4e3a2016-03-11 17:19:07 -08001682 }
1683 }
1684 }
1685
Yi Tseng78f51f42017-02-02 13:54:58 -08001686 private void processPendingUpdateNextObjs(GroupKey groupKey) {
1687
1688 pendingUpdateNextObjectives.compute(groupKey, (gKey, nextObjs) -> {
1689 if (nextObjs != null) {
1690
1691 nextObjs.forEach(nextObj -> {
1692 log.debug("Group {} updated, update pending next objective {}.",
1693 groupKey, nextObj);
1694
1695 Ofdpa2Pipeline.pass(nextObj);
1696 });
1697 }
1698
1699 return Sets.newHashSet();
1700 });
1701 }
1702
Charles Chanfc5c7802016-05-17 13:13:55 -07001703 private void processPendingAddGroupsOrNextObjs(GroupKey key, boolean added) {
Charles Chan188ebf52015-12-23 00:15:11 -08001704 //first check for group chain
1705 Set<GroupChainElem> gceSet = pendingGroups.remove(key);
1706 if (gceSet != null) {
1707 for (GroupChainElem gce : gceSet) {
Charles Chan216e3c82016-04-23 14:48:16 -07001708 log.debug("Group service {} group key {} in device {}. "
Saurav Das0fd79d92016-03-07 10:58:36 -08001709 + "Processing next group in group chain with group id 0x{}",
Charles Chan188ebf52015-12-23 00:15:11 -08001710 (added) ? "ADDED" : "processed",
1711 key, deviceId,
1712 Integer.toHexString(gce.groupDescription.givenGroupId()));
1713 processGroupChain(gce);
1714 }
1715 } else {
1716 // otherwise chain complete - check for waiting nextObjectives
Charles Chanfc5c7802016-05-17 13:13:55 -07001717 List<OfdpaNextGroup> nextGrpList = pendingAddNextObjectives.getIfPresent(key);
Charles Chan188ebf52015-12-23 00:15:11 -08001718 if (nextGrpList != null) {
Charles Chanfc5c7802016-05-17 13:13:55 -07001719 pendingAddNextObjectives.invalidate(key);
Charles Chan188ebf52015-12-23 00:15:11 -08001720 nextGrpList.forEach(nextGrp -> {
Charles Chan216e3c82016-04-23 14:48:16 -07001721 log.debug("Group service {} group key {} in device:{}. "
Saurav Das0fd79d92016-03-07 10:58:36 -08001722 + "Done implementing next objective: {} <<-->> gid:0x{}",
Charles Chan188ebf52015-12-23 00:15:11 -08001723 (added) ? "ADDED" : "processed",
1724 key, deviceId, nextGrp.nextObjective().id(),
1725 Integer.toHexString(groupService.getGroup(deviceId, key)
1726 .givenGroupId()));
Charles Chan361154b2016-03-24 10:23:39 -07001727 Ofdpa2Pipeline.pass(nextGrp.nextObjective());
Charles Chan188ebf52015-12-23 00:15:11 -08001728 flowObjectiveStore.putNextGroup(nextGrp.nextObjective().id(), nextGrp);
Yi Tseng47f82dc2017-03-05 22:48:39 -08001729
Charles Chan188ebf52015-12-23 00:15:11 -08001730 // check if addBuckets waiting for this completion
Yi Tseng47f82dc2017-03-05 22:48:39 -08001731 pendingBuckets.compute(nextGrp.nextObjective().id(), (nextId, pendBkts) -> {
1732 if (pendBkts != null) {
1733 pendBkts.forEach(pendBkt -> addBucketToGroup(pendBkt, nextGrp));
1734 }
1735 return null;
1736 });
Charles Chan188ebf52015-12-23 00:15:11 -08001737 });
1738 }
1739 }
1740 }
1741
Charles Chanfc5c7802016-05-17 13:13:55 -07001742 private void processPendingRemoveNextObjs(GroupKey key) {
1743 pendingRemoveNextObjectives.asMap().forEach((nextObjective, groupKeys) -> {
1744 if (groupKeys.isEmpty()) {
1745 pendingRemoveNextObjectives.invalidate(nextObjective);
1746 Ofdpa2Pipeline.pass(nextObjective);
1747 } else {
1748 groupKeys.remove(key);
1749 }
1750 });
1751 }
1752
Charles Chan425854b2016-04-11 15:32:12 -07001753 protected int getNextAvailableIndex() {
Saurav Das8be4e3a2016-03-11 17:19:07 -08001754 return (int) nextIndex.incrementAndGet();
1755 }
1756
Charles Chane849c192016-01-11 18:28:54 -08001757 /**
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001758 * Returns the outport in a traffic treatment.
1759 *
1760 * @param tt the treatment
1761 * @return the PortNumber for the outport or null
1762 */
1763 protected static PortNumber readOutPortFromTreatment(TrafficTreatment tt) {
1764 for (Instruction ins : tt.allInstructions()) {
1765 if (ins.type() == Instruction.Type.OUTPUT) {
1766 return ((Instructions.OutputInstruction) ins).port();
1767 }
1768 }
1769 return null;
1770 }
1771
1772 /**
Charles Chane849c192016-01-11 18:28:54 -08001773 * Returns a hash as the L2 Interface Group Key.
1774 *
1775 * Keep the lower 6-bit for port since port number usually smaller than 64.
1776 * Hash other information into remaining 28 bits.
1777 *
1778 * @param deviceId Device ID
1779 * @param vlanId VLAN ID
1780 * @param portNumber Port number
1781 * @return L2 interface group key
1782 */
Pier Ventre140a8942016-11-02 07:26:38 -07001783 protected int l2InterfaceGroupKey(DeviceId deviceId, VlanId vlanId, long portNumber) {
Charles Chane849c192016-01-11 18:28:54 -08001784 int portLowerBits = (int) portNumber & PORT_LOWER_BITS_MASK;
1785 long portHigherBits = portNumber & PORT_HIGHER_BITS_MASK;
Charles Chand0fd5dc2016-02-16 23:14:49 -08001786 int hash = Objects.hash(deviceId, vlanId, portHigherBits);
Charles Chane849c192016-01-11 18:28:54 -08001787 return L2_INTERFACE_TYPE | (TYPE_MASK & hash << 6) | portLowerBits;
1788 }
1789
Saurav Das1a129a02016-11-18 15:21:57 -08001790 private Group retrieveTopLevelGroup(List<Deque<GroupKey>> allActiveKeys,
1791 int nextid) {
Yi Tseng78f51f42017-02-02 13:54:58 -08001792 GroupKey topLevelGroupKey;
Saurav Das1a129a02016-11-18 15:21:57 -08001793 if (!allActiveKeys.isEmpty()) {
1794 topLevelGroupKey = allActiveKeys.get(0).peekFirst();
1795 } else {
1796 log.warn("Could not determine top level group while processing"
1797 + "next:{} in dev:{}", nextid, deviceId);
1798 return null;
1799 }
1800 Group topGroup = groupService.getGroup(deviceId, topLevelGroupKey);
1801 if (topGroup == null) {
1802 log.warn("Could not find top level group while processing "
1803 + "next:{} in dev:{}", nextid, deviceId);
1804 }
1805 return topGroup;
1806 }
1807
Charles Chan188ebf52015-12-23 00:15:11 -08001808 /**
1809 * Utility class for moving group information around.
Saurav Das1a129a02016-11-18 15:21:57 -08001810 *
1811 * Example: Suppose we are trying to create a group-chain A-B-C-D, where
1812 * A is the top level group, and D is the inner-most group, typically L2 Interface.
1813 * The innerMostGroupDesc is always D. At various stages of the creation
1814 * process the nextGroupDesc may be C or B. The nextGroupDesc exists to
1815 * inform the referencing group about which group it needs to point to,
1816 * and wait for. In some cases the group chain may simply be A-B. In this case,
1817 * both innerMostGroupDesc and nextGroupDesc will be B.
Charles Chan188ebf52015-12-23 00:15:11 -08001818 */
Charles Chan425854b2016-04-11 15:32:12 -07001819 protected class GroupInfo {
Charles Chan5b9df8d2016-03-28 22:21:40 -07001820 /**
1821 * Description of the inner-most group of the group chain.
1822 * It is always an L2 interface group.
1823 */
1824 private GroupDescription innerMostGroupDesc;
Charles Chan188ebf52015-12-23 00:15:11 -08001825
Charles Chan5b9df8d2016-03-28 22:21:40 -07001826 /**
1827 * Description of the next group in the group chain.
1828 * It can be L2 interface, L3 interface, L3 unicast, L3 VPN group.
Saurav Das1a129a02016-11-18 15:21:57 -08001829 * It is possible that nextGroupDesc is the same as the innerMostGroup.
Charles Chan5b9df8d2016-03-28 22:21:40 -07001830 */
1831 private GroupDescription nextGroupDesc;
1832
1833 GroupInfo(GroupDescription innerMostGroupDesc, GroupDescription nextGroupDesc) {
1834 this.innerMostGroupDesc = innerMostGroupDesc;
1835 this.nextGroupDesc = nextGroupDesc;
Charles Chan188ebf52015-12-23 00:15:11 -08001836 }
Pier Ventre140a8942016-11-02 07:26:38 -07001837
1838 /**
1839 * Getter for innerMostGroupDesc.
1840 *
1841 * @return the inner most group description
1842 */
1843 public GroupDescription getInnerMostGroupDesc() {
1844 return innerMostGroupDesc;
1845 }
1846
1847 /**
1848 * Getter for the next group description.
1849 *
1850 * @return the next group description
1851 */
1852 public GroupDescription getNextGroupDesc() {
1853 return nextGroupDesc;
1854 }
Charles Chan188ebf52015-12-23 00:15:11 -08001855 }
1856
1857 /**
1858 * Represents an entire group-chain that implements a Next-Objective from
1859 * the application. The objective is represented as a list of deques, where
1860 * each deque is a separate chain of groups.
1861 * <p>
1862 * For example, an ECMP group with 3 buckets, where each bucket points to
1863 * a group chain of L3 Unicast and L2 interface groups will look like this:
1864 * <ul>
1865 * <li>List[0] is a Deque of GroupKeyECMP(first)-GroupKeyL3(middle)-GroupKeyL2(last)
1866 * <li>List[1] is a Deque of GroupKeyECMP(first)-GroupKeyL3(middle)-GroupKeyL2(last)
1867 * <li>List[2] is a Deque of GroupKeyECMP(first)-GroupKeyL3(middle)-GroupKeyL2(last)
1868 * </ul>
1869 * where the first element of each deque is the same, representing the
1870 * top level ECMP group, while every other element represents a unique groupKey.
1871 * <p>
1872 * Also includes information about the next objective that
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001873 * resulted in these group-chains.
Charles Chan188ebf52015-12-23 00:15:11 -08001874 *
1875 */
1876 protected class OfdpaNextGroup implements NextGroup {
1877 private final NextObjective nextObj;
1878 private final List<Deque<GroupKey>> gkeys;
1879
1880 public OfdpaNextGroup(List<Deque<GroupKey>> gkeys, NextObjective nextObj) {
Charles Chan188ebf52015-12-23 00:15:11 -08001881 this.nextObj = nextObj;
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001882 this.gkeys = gkeys;
Charles Chan188ebf52015-12-23 00:15:11 -08001883 }
1884
1885 public NextObjective nextObjective() {
1886 return nextObj;
1887 }
1888
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001889 public List<Deque<GroupKey>> groupKeys() {
1890 return gkeys;
1891 }
1892
Charles Chan188ebf52015-12-23 00:15:11 -08001893 @Override
1894 public byte[] data() {
Charles Chan361154b2016-03-24 10:23:39 -07001895 return Ofdpa2Pipeline.appKryo.serialize(gkeys);
Charles Chan188ebf52015-12-23 00:15:11 -08001896 }
1897 }
1898
1899 /**
1900 * Represents a group element that is part of a chain of groups.
1901 * Stores enough information to create a Group Description to add the group
1902 * to the switch by requesting the Group Service. Objects instantiating this
1903 * class are meant to be temporary and live as long as it is needed to wait for
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001904 * referenced groups in the group chain to be created.
Charles Chan188ebf52015-12-23 00:15:11 -08001905 */
Charles Chan425854b2016-04-11 15:32:12 -07001906 protected class GroupChainElem {
Charles Chan188ebf52015-12-23 00:15:11 -08001907 private GroupDescription groupDescription;
1908 private AtomicInteger waitOnGroups;
1909 private boolean addBucketToGroup;
1910
1911 GroupChainElem(GroupDescription groupDescription, int waitOnGroups,
1912 boolean addBucketToGroup) {
1913 this.groupDescription = groupDescription;
1914 this.waitOnGroups = new AtomicInteger(waitOnGroups);
1915 this.addBucketToGroup = addBucketToGroup;
1916 }
1917
1918 /**
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001919 * This method atomically decrements the counter for the number of
Charles Chan188ebf52015-12-23 00:15:11 -08001920 * groups this GroupChainElement is waiting on, for notifications from
1921 * the Group Service. When this method returns a value of 0, this
1922 * GroupChainElement is ready to be processed.
1923 *
1924 * @return integer indication of the number of notifications being waited on
1925 */
1926 int decrementAndGetGroupsWaitedOn() {
1927 return waitOnGroups.decrementAndGet();
1928 }
1929
1930 @Override
1931 public String toString() {
1932 return (Integer.toHexString(groupDescription.givenGroupId()) +
1933 " groupKey: " + groupDescription.appCookie() +
1934 " waiting-on-groups: " + waitOnGroups.get() +
1935 " addBucketToGroup: " + addBucketToGroup +
1936 " device: " + deviceId);
1937 }
1938 }
Pier Ventre140a8942016-11-02 07:26:38 -07001939
1940 /**
1941 * Helper enum to handle the different MPLS group
1942 * types.
1943 */
1944 protected enum OfdpaMplsGroupSubType {
Pier Ventre140a8942016-11-02 07:26:38 -07001945 MPLS_INTF((short) 0),
Pier Ventre140a8942016-11-02 07:26:38 -07001946 L2_VPN((short) 1),
Pier Ventre140a8942016-11-02 07:26:38 -07001947 L3_VPN((short) 2),
Pier Ventre140a8942016-11-02 07:26:38 -07001948 MPLS_TUNNEL_LABEL_1((short) 3),
Pier Ventre140a8942016-11-02 07:26:38 -07001949 MPLS_TUNNEL_LABEL_2((short) 4),
Pier Ventre140a8942016-11-02 07:26:38 -07001950 MPLS_SWAP_LABEL((short) 5),
Pier Ventre140a8942016-11-02 07:26:38 -07001951 MPLS_ECMP((short) 8);
1952
1953 private short value;
Pier Ventre140a8942016-11-02 07:26:38 -07001954 public static final int OFDPA_GROUP_TYPE_SHIFT = 28;
1955 public static final int OFDPA_MPLS_SUBTYPE_SHIFT = 24;
1956
1957 OfdpaMplsGroupSubType(short value) {
1958 this.value = value;
1959 }
1960
1961 /**
1962 * Gets the value as an short.
1963 *
1964 * @return the value as an short
1965 */
1966 public short getValue() {
1967 return this.value;
1968 }
1969
1970 }
1971
1972 /**
1973 * Creates MPLS Label group id given a sub type and
1974 * the index.
1975 *
1976 * @param subType the MPLS Label group sub type
1977 * @param index the index of the group
1978 * @return the OFDPA group id
1979 */
1980 public Integer makeMplsLabelGroupId(OfdpaMplsGroupSubType subType, int index) {
1981 index = index & 0x00FFFFFF;
1982 return index | (9 << OFDPA_GROUP_TYPE_SHIFT) | (subType.value << OFDPA_MPLS_SUBTYPE_SHIFT);
1983 }
1984
1985 /**
1986 * Creates MPLS Forwarding group id given a sub type and
1987 * the index.
1988 *
1989 * @param subType the MPLS forwarding group sub type
1990 * @param index the index of the group
1991 * @return the OFDPA group id
1992 */
1993 public Integer makeMplsForwardingGroupId(OfdpaMplsGroupSubType subType, int index) {
1994 index = index & 0x00FFFFFF;
1995 return index | (10 << OFDPA_GROUP_TYPE_SHIFT) | (subType.value << OFDPA_MPLS_SUBTYPE_SHIFT);
1996 }
Charles Chan188ebf52015-12-23 00:15:11 -08001997}