blob: fedfc208666f79ace438c553b5c8d8fb6bbce344 [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;
31import org.onosproject.core.DefaultGroupId;
Yi Tseng78f51f42017-02-02 13:54:58 -080032import org.onosproject.core.GroupId;
Charles Chan32562522016-04-07 14:37:14 -070033import org.onosproject.driver.extensions.OfdpaSetVlanVid;
Charles Chan188ebf52015-12-23 00:15:11 -080034import org.onosproject.net.DeviceId;
35import org.onosproject.net.PortNumber;
36import org.onosproject.net.behaviour.NextGroup;
37import org.onosproject.net.behaviour.PipelinerContext;
38import org.onosproject.net.flow.DefaultTrafficTreatment;
39import org.onosproject.net.flow.TrafficSelector;
40import org.onosproject.net.flow.TrafficTreatment;
41import org.onosproject.net.flow.criteria.Criterion;
Pier Ventre42287df2016-11-09 14:17:26 -080042import org.onosproject.net.flow.criteria.TunnelIdCriterion;
Charles Chan188ebf52015-12-23 00:15:11 -080043import org.onosproject.net.flow.criteria.VlanIdCriterion;
44import org.onosproject.net.flow.instructions.Instruction;
45import org.onosproject.net.flow.instructions.Instructions;
46import org.onosproject.net.flow.instructions.L2ModificationInstruction;
47import org.onosproject.net.flowobjective.FlowObjectiveStore;
48import org.onosproject.net.flowobjective.NextObjective;
49import org.onosproject.net.flowobjective.ObjectiveError;
50import org.onosproject.net.group.DefaultGroupBucket;
51import org.onosproject.net.group.DefaultGroupDescription;
52import org.onosproject.net.group.DefaultGroupKey;
53import org.onosproject.net.group.Group;
54import org.onosproject.net.group.GroupBucket;
55import org.onosproject.net.group.GroupBuckets;
56import org.onosproject.net.group.GroupDescription;
57import org.onosproject.net.group.GroupEvent;
58import org.onosproject.net.group.GroupKey;
59import org.onosproject.net.group.GroupListener;
60import org.onosproject.net.group.GroupService;
Saurav Das8be4e3a2016-03-11 17:19:07 -080061import org.onosproject.store.service.AtomicCounter;
62import org.onosproject.store.service.StorageService;
Charles Chan188ebf52015-12-23 00:15:11 -080063import org.slf4j.Logger;
64
65import java.util.ArrayDeque;
66import java.util.ArrayList;
67import java.util.Collection;
68import java.util.Collections;
69import java.util.Deque;
70import java.util.List;
Charles Chand0fd5dc2016-02-16 23:14:49 -080071import java.util.Objects;
Charles Chan188ebf52015-12-23 00:15:11 -080072import java.util.Set;
73import java.util.concurrent.ConcurrentHashMap;
74import java.util.concurrent.CopyOnWriteArrayList;
75import java.util.concurrent.Executors;
76import java.util.concurrent.ScheduledExecutorService;
77import java.util.concurrent.TimeUnit;
78import java.util.concurrent.atomic.AtomicInteger;
79import java.util.stream.Collectors;
80
81import static org.onlab.util.Tools.groupedThreads;
Pier Ventre140a8942016-11-02 07:26:38 -070082import static org.onosproject.driver.pipeline.Ofdpa2GroupHandler.OfdpaMplsGroupSubType.OFDPA_GROUP_TYPE_SHIFT;
83import static org.onosproject.driver.pipeline.Ofdpa2GroupHandler.OfdpaMplsGroupSubType.OFDPA_MPLS_SUBTYPE_SHIFT;
84import static org.onosproject.driver.pipeline.Ofdpa2Pipeline.isNotMplsBos;
Pier Ventre42287df2016-11-09 14:17:26 -080085import static org.onosproject.net.flow.criteria.Criterion.Type.TUNNEL_ID;
Pier Ventre140a8942016-11-02 07:26:38 -070086import static org.onosproject.net.flow.criteria.Criterion.Type.VLAN_VID;
87import static org.onosproject.net.flowobjective.NextObjective.Type.HASHED;
Yi Tseng78f51f42017-02-02 13:54:58 -080088import static org.onosproject.net.group.GroupDescription.Type.ALL;
89import static org.onosproject.net.group.GroupDescription.Type.SELECT;
Charles Chan188ebf52015-12-23 00:15:11 -080090import static org.slf4j.LoggerFactory.getLogger;
91
92/**
Charles Chan40132b32017-01-22 00:19:37 -080093 * Group handler that emulates Broadcom OF-DPA TTP on CpqD.
Charles Chan188ebf52015-12-23 00:15:11 -080094 */
Charles Chan361154b2016-03-24 10:23:39 -070095public class Ofdpa2GroupHandler {
Charles Chan188ebf52015-12-23 00:15:11 -080096 /*
97 * OFDPA requires group-id's to have a certain form.
98 * L2 Interface Groups have <4bits-0><12bits-vlanid><16bits-portid>
99 * L3 Unicast Groups have <4bits-2><28bits-index>
100 * MPLS Interface Groups have <4bits-9><4bits:0><24bits-index>
101 * L3 ECMP Groups have <4bits-7><28bits-index>
102 * L2 Flood Groups have <4bits-4><12bits-vlanid><16bits-index>
103 * L3 VPN Groups have <4bits-9><4bits-2><24bits-index>
104 */
Charles Chan425854b2016-04-11 15:32:12 -0700105 protected static final int L2_INTERFACE_TYPE = 0x00000000;
106 protected static final int L3_INTERFACE_TYPE = 0x50000000;
107 protected static final int L3_UNICAST_TYPE = 0x20000000;
108 protected static final int L3_MULTICAST_TYPE = 0x60000000;
109 protected static final int MPLS_INTERFACE_TYPE = 0x90000000;
110 protected static final int MPLS_L3VPN_SUBTYPE = 0x92000000;
111 protected static final int L3_ECMP_TYPE = 0x70000000;
112 protected static final int L2_FLOOD_TYPE = 0x40000000;
Charles Chane849c192016-01-11 18:28:54 -0800113
Charles Chan425854b2016-04-11 15:32:12 -0700114 protected static final int TYPE_MASK = 0x0fffffff;
115 protected static final int SUBTYPE_MASK = 0x00ffffff;
116 protected static final int TYPE_VLAN_MASK = 0x0000ffff;
Charles Chane849c192016-01-11 18:28:54 -0800117
Charles Chan372b63e2017-02-07 12:10:53 -0800118 protected static final int THREE_BIT_MASK = 0x0fff;
119 protected static final int FOUR_BIT_MASK = 0xffff;
120 protected static final int PORT_LEN = 16;
121
Charles Chan425854b2016-04-11 15:32:12 -0700122 protected static final int PORT_LOWER_BITS_MASK = 0x3f;
123 protected static final long PORT_HIGHER_BITS_MASK = ~PORT_LOWER_BITS_MASK;
Charles Chan188ebf52015-12-23 00:15:11 -0800124
Yi Tseng78f51f42017-02-02 13:54:58 -0800125 protected static final String HEX_PREFIX = "0x";
126
Charles Chan188ebf52015-12-23 00:15:11 -0800127 private final Logger log = getLogger(getClass());
128 private ServiceDirectory serviceDirectory;
129 protected GroupService groupService;
Saurav Das8be4e3a2016-03-11 17:19:07 -0800130 protected StorageService storageService;
Charles Chan188ebf52015-12-23 00:15:11 -0800131
Charles Chan425854b2016-04-11 15:32:12 -0700132 protected DeviceId deviceId;
Charles Chan188ebf52015-12-23 00:15:11 -0800133 private FlowObjectiveStore flowObjectiveStore;
Charles Chanfc5c7802016-05-17 13:13:55 -0700134 private Cache<GroupKey, List<OfdpaNextGroup>> pendingAddNextObjectives;
135 private Cache<NextObjective, List<GroupKey>> pendingRemoveNextObjectives;
Charles Chan188ebf52015-12-23 00:15:11 -0800136 private ConcurrentHashMap<GroupKey, Set<GroupChainElem>> pendingGroups;
Yi Tseng78f51f42017-02-02 13:54:58 -0800137 private ConcurrentHashMap<GroupKey, Set<NextObjective>> pendingUpdateNextObjectives;
Charles Chan188ebf52015-12-23 00:15:11 -0800138 private ScheduledExecutorService groupChecker =
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700139 Executors.newScheduledThreadPool(2, groupedThreads("onos/pipeliner", "ofdpa2-%d", log));
Charles Chan188ebf52015-12-23 00:15:11 -0800140
141 // index number for group creation
Saurav Das8be4e3a2016-03-11 17:19:07 -0800142 private AtomicCounter nextIndex;
Charles Chan188ebf52015-12-23 00:15:11 -0800143
Charles Chan188ebf52015-12-23 00:15:11 -0800144 // local store for pending bucketAdds - by design there can only be one
145 // pending bucket for a group
Saurav Das1ce0a7b2016-10-21 14:06:29 -0700146 protected ConcurrentHashMap<Integer, NextObjective> pendingBuckets =
147 new ConcurrentHashMap<>();
Charles Chan188ebf52015-12-23 00:15:11 -0800148
Charles Chan40132b32017-01-22 00:19:37 -0800149 /**
150 * Determines whether this pipeline support copy ttl instructions or not.
151 *
152 * @return true if copy ttl instructions are supported
153 */
154 protected boolean supportCopyTtl() {
155 return true;
156 }
157
158 /**
159 * Determines whether this pipeline support set mpls bos instruction or not.
160 *
161 * @return true if set mpls bos instruction is supported
162 */
163 protected boolean supportSetMplsBos() {
164 return true;
165 }
166
Charles Chan0f43e472017-02-14 14:00:16 -0800167 /**
168 * Determines whether this pipeline requires popping VLAN before pushing MPLS.
169 * <p>
170 * If required, pop vlan before push mpls and add an arbitrary vlan back afterward.
171 * MPLS interface group will substitute the arbitrary VLAN with expected VLAN later on.
172 *
173 * @return true if this pipeline requires popping VLAN before pushing MPLS
174 */
175 protected boolean requireVlanPopBeforeMplsPush() {
176 return false;
177 }
178
Charles Chan188ebf52015-12-23 00:15:11 -0800179 protected void init(DeviceId deviceId, PipelinerContext context) {
180 this.deviceId = deviceId;
181 this.flowObjectiveStore = context.store();
182 this.serviceDirectory = context.directory();
183 this.groupService = serviceDirectory.get(GroupService.class);
Saurav Das8be4e3a2016-03-11 17:19:07 -0800184 this.storageService = serviceDirectory.get(StorageService.class);
Madan Jampanid5714e02016-04-19 14:15:20 -0700185 this.nextIndex = storageService.getAtomicCounter("group-id-index-counter");
Charles Chan188ebf52015-12-23 00:15:11 -0800186
Charles Chanfc5c7802016-05-17 13:13:55 -0700187 pendingAddNextObjectives = CacheBuilder.newBuilder()
Charles Chan188ebf52015-12-23 00:15:11 -0800188 .expireAfterWrite(20, TimeUnit.SECONDS)
189 .removalListener((
190 RemovalNotification<GroupKey, List<OfdpaNextGroup>> notification) -> {
191 if (notification.getCause() == RemovalCause.EXPIRED) {
192 notification.getValue().forEach(ofdpaNextGrp ->
Charles Chan361154b2016-03-24 10:23:39 -0700193 Ofdpa2Pipeline.fail(ofdpaNextGrp.nextObj,
Charles Chan188ebf52015-12-23 00:15:11 -0800194 ObjectiveError.GROUPINSTALLATIONFAILED));
Charles Chanfc5c7802016-05-17 13:13:55 -0700195 }
196 }).build();
Charles Chan188ebf52015-12-23 00:15:11 -0800197
Charles Chanfc5c7802016-05-17 13:13:55 -0700198 pendingRemoveNextObjectives = CacheBuilder.newBuilder()
199 .expireAfterWrite(20, TimeUnit.SECONDS)
200 .removalListener((
201 RemovalNotification<NextObjective, List<GroupKey>> notification) -> {
202 if (notification.getCause() == RemovalCause.EXPIRED) {
203 Ofdpa2Pipeline.fail(notification.getKey(),
204 ObjectiveError.GROUPREMOVALFAILED);
Charles Chan188ebf52015-12-23 00:15:11 -0800205 }
206 }).build();
207 pendingGroups = new ConcurrentHashMap<>();
Yi Tseng78f51f42017-02-02 13:54:58 -0800208 pendingUpdateNextObjectives = new ConcurrentHashMap<>();
Charles Chan188ebf52015-12-23 00:15:11 -0800209 groupChecker.scheduleAtFixedRate(new GroupChecker(), 0, 500, TimeUnit.MILLISECONDS);
210
211 groupService.addListener(new InnerGroupListener());
212 }
213
Pier Ventre140a8942016-11-02 07:26:38 -0700214 /**
215 * The purpose of this function is to verify if the hashed next
216 * objective is supported by the current pipeline.
217 *
218 * @param nextObjective the hashed objective to verify
219 * @return true if the hashed objective is supported. Otherwise false.
220 */
221 public boolean verifyHashedNextObjective(NextObjective nextObjective) {
222 // if it is not hashed, there is something wrong;
223 if (nextObjective.type() != HASHED) {
224 return false;
225 }
226 // The case non supported is the MPLS-ECMP. For now, we try
227 // to create a MPLS-ECMP for the transport of a VPWS. The
228 // necessary info are contained in the meta selector. In particular
229 // we are looking for the case of BoS==False;
230 TrafficSelector metaSelector = nextObjective.meta();
231 if (metaSelector != null && isNotMplsBos(metaSelector)) {
232 return false;
233 }
234
235 return true;
236 }
237
Saurav Das8be4e3a2016-03-11 17:19:07 -0800238 //////////////////////////////////////
239 // Group Creation
240 //////////////////////////////////////
241
Charles Chan188ebf52015-12-23 00:15:11 -0800242 protected void addGroup(NextObjective nextObjective) {
243 switch (nextObjective.type()) {
244 case SIMPLE:
245 Collection<TrafficTreatment> treatments = nextObjective.next();
246 if (treatments.size() != 1) {
247 log.error("Next Objectives of type Simple should only have a "
248 + "single Traffic Treatment. Next Objective Id:{}",
249 nextObjective.id());
Charles Chan361154b2016-03-24 10:23:39 -0700250 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.BADPARAMS);
Charles Chan188ebf52015-12-23 00:15:11 -0800251 return;
252 }
253 processSimpleNextObjective(nextObjective);
254 break;
255 case BROADCAST:
256 processBroadcastNextObjective(nextObjective);
257 break;
258 case HASHED:
Pier Ventre140a8942016-11-02 07:26:38 -0700259 if (!verifyHashedNextObjective(nextObjective)) {
260 log.error("Next Objectives of type hashed not supported. Next Objective Id:{}",
261 nextObjective.id());
262 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.BADPARAMS);
263 return;
264 }
Charles Chan188ebf52015-12-23 00:15:11 -0800265 processHashedNextObjective(nextObjective);
266 break;
267 case FAILOVER:
Charles Chan361154b2016-03-24 10:23:39 -0700268 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.UNSUPPORTED);
Charles Chan188ebf52015-12-23 00:15:11 -0800269 log.warn("Unsupported next objective type {}", nextObjective.type());
270 break;
271 default:
Charles Chan361154b2016-03-24 10:23:39 -0700272 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.UNKNOWN);
Charles Chan188ebf52015-12-23 00:15:11 -0800273 log.warn("Unknown next objective type {}", nextObjective.type());
274 }
275 }
276
277 /**
278 * As per the OFDPA 2.0 TTP, packets are sent out of ports by using
279 * a chain of groups. The simple Next Objective passed
280 * in by the application has to be broken up into a group chain
281 * comprising of an L3 Unicast Group that points to an L2 Interface
282 * Group which in-turn points to an output port. In some cases, the simple
283 * next Objective can just be an L2 interface without the need for chaining.
284 *
285 * @param nextObj the nextObjective of type SIMPLE
286 */
287 private void processSimpleNextObjective(NextObjective nextObj) {
288 TrafficTreatment treatment = nextObj.next().iterator().next();
289 // determine if plain L2 or L3->L2
290 boolean plainL2 = true;
291 for (Instruction ins : treatment.allInstructions()) {
292 if (ins.type() == Instruction.Type.L2MODIFICATION) {
293 L2ModificationInstruction l2ins = (L2ModificationInstruction) ins;
294 if (l2ins.subtype() == L2ModificationInstruction.L2SubType.ETH_DST ||
295 l2ins.subtype() == L2ModificationInstruction.L2SubType.ETH_SRC) {
296 plainL2 = false;
297 break;
298 }
299 }
300 }
301
302 if (plainL2) {
303 createL2InterfaceGroup(nextObj);
304 return;
305 }
306
Pier Ventre140a8942016-11-02 07:26:38 -0700307 boolean isMpls = false;
Pier Ventre42287df2016-11-09 14:17:26 -0800308 // In order to understand if it is a pseudo wire related
309 // next objective we look for the tunnel id in the meta.
310 boolean isPw = false;
Pier Ventre140a8942016-11-02 07:26:38 -0700311 if (nextObj.meta() != null) {
312 isMpls = isNotMplsBos(nextObj.meta());
Pier Ventre42287df2016-11-09 14:17:26 -0800313
314 TunnelIdCriterion tunnelIdCriterion = (TunnelIdCriterion) nextObj
315 .meta()
316 .getCriterion(TUNNEL_ID);
317 if (tunnelIdCriterion != null) {
318 isPw = true;
319 }
320
Pier Ventre140a8942016-11-02 07:26:38 -0700321 }
322
Pier Ventre42287df2016-11-09 14:17:26 -0800323 if (!isPw) {
324 // break up simple next objective to GroupChain objects
325 GroupInfo groupInfo = createL2L3Chain(treatment, nextObj.id(),
326 nextObj.appId(), isMpls,
327 nextObj.meta());
328 if (groupInfo == null) {
329 log.error("Could not process nextObj={} in dev:{}", nextObj.id(), deviceId);
330 return;
331 }
332 // create object for local and distributed storage
333 Deque<GroupKey> gkeyChain = new ArrayDeque<>();
334 gkeyChain.addFirst(groupInfo.innerMostGroupDesc.appCookie());
335 gkeyChain.addFirst(groupInfo.nextGroupDesc.appCookie());
336 OfdpaNextGroup ofdpaGrp =
337 new OfdpaNextGroup(Collections.singletonList(gkeyChain), nextObj);
338
339 // store l3groupkey with the ofdpaNextGroup for the nextObjective that depends on it
340 updatePendingNextObjective(groupInfo.nextGroupDesc.appCookie(), ofdpaGrp);
341
342 // now we are ready to send the l2 groupDescription (inner), as all the stores
343 // that will get async replies have been updated. By waiting to update
344 // the stores, we prevent nasty race conditions.
345 groupService.addGroup(groupInfo.innerMostGroupDesc);
346 } else {
347 // We handle the pseudo wire with a different a procedure.
348 // This procedure is meant to handle both initiation and
349 // termination of the pseudo wire.
350 processPwNextObjective(nextObj);
Charles Chan188ebf52015-12-23 00:15:11 -0800351 }
Charles Chan188ebf52015-12-23 00:15:11 -0800352 }
353
Charles Chan188ebf52015-12-23 00:15:11 -0800354 /**
355 * Creates a simple L2 Interface Group.
356 *
357 * @param nextObj the next Objective
358 */
359 private void createL2InterfaceGroup(NextObjective nextObj) {
Charles Chan5b9df8d2016-03-28 22:21:40 -0700360 VlanId assignedVlan = Ofdpa2Pipeline.readVlanFromSelector(nextObj.meta());
361 if (assignedVlan == null) {
362 log.warn("VLAN ID required by simple next obj is missing. Abort.");
363 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.BADPARAMS);
Charles Chan188ebf52015-12-23 00:15:11 -0800364 return;
365 }
366
Charles Chan5b9df8d2016-03-28 22:21:40 -0700367 List<GroupInfo> groupInfos = prepareL2InterfaceGroup(nextObj, assignedVlan);
Charles Chan188ebf52015-12-23 00:15:11 -0800368
Charles Chan5b9df8d2016-03-28 22:21:40 -0700369 // There is only one L2 interface group in this case
370 GroupDescription l2InterfaceGroupDesc = groupInfos.get(0).innerMostGroupDesc;
Charles Chan188ebf52015-12-23 00:15:11 -0800371
Charles Chan5b9df8d2016-03-28 22:21:40 -0700372 // Put all dependency information into allGroupKeys
373 List<Deque<GroupKey>> allGroupKeys = Lists.newArrayList();
374 Deque<GroupKey> gkeyChain = new ArrayDeque<>();
375 gkeyChain.addFirst(l2InterfaceGroupDesc.appCookie());
376 allGroupKeys.add(gkeyChain);
Charles Chan188ebf52015-12-23 00:15:11 -0800377
Charles Chan5b9df8d2016-03-28 22:21:40 -0700378 // Point the next objective to this group
379 OfdpaNextGroup ofdpaGrp = new OfdpaNextGroup(allGroupKeys, nextObj);
380 updatePendingNextObjective(l2InterfaceGroupDesc.appCookie(), ofdpaGrp);
381
382 // Start installing the inner-most group
383 groupService.addGroup(l2InterfaceGroupDesc);
Charles Chan188ebf52015-12-23 00:15:11 -0800384 }
385
386 /**
387 * Creates one of two possible group-chains from the treatment
388 * passed in. Depending on the MPLS boolean, this method either creates
Charles Chan425854b2016-04-11 15:32:12 -0700389 * an L3Unicast Group --&gt; L2Interface Group, if mpls is false;
390 * or MPLSInterface Group --&gt; L2Interface Group, if mpls is true;
Charles Chan188ebf52015-12-23 00:15:11 -0800391 * The returned 'inner' group description is always the L2 Interface group.
392 *
393 * @param treatment that needs to be broken up to create the group chain
394 * @param nextId of the next objective that needs this group chain
395 * @param appId of the application that sent this next objective
396 * @param mpls determines if L3Unicast or MPLSInterface group is created
397 * @param meta metadata passed in by the application as part of the nextObjective
398 * @return GroupInfo containing the GroupDescription of the
399 * L2Interface group(inner) and the GroupDescription of the (outer)
400 * L3Unicast/MPLSInterface group. May return null if there is an
401 * error in processing the chain
402 */
Charles Chan425854b2016-04-11 15:32:12 -0700403 protected GroupInfo createL2L3Chain(TrafficTreatment treatment, int nextId,
Charles Chanf9e98652016-09-07 16:54:23 -0700404 ApplicationId appId, boolean mpls,
405 TrafficSelector meta) {
406 return createL2L3ChainInternal(treatment, nextId, appId, mpls, meta, true);
407 }
408
409 /**
410 * Internal implementation of createL2L3Chain.
411 * <p>
412 * The is_present bit in set_vlan_vid action is required to be 0 in OFDPA i12.
413 * Since it is non-OF spec, we need an extension treatment for that.
414 * The useSetVlanExtension must be set to false for OFDPA i12.
415 * </p>
416 *
417 * @param treatment that needs to be broken up to create the group chain
418 * @param nextId of the next objective that needs this group chain
419 * @param appId of the application that sent this next objective
420 * @param mpls determines if L3Unicast or MPLSInterface group is created
421 * @param meta metadata passed in by the application as part of the nextObjective
422 * @param useSetVlanExtension use the setVlanVid extension that has is_present bit set to 0.
423 * @return GroupInfo containing the GroupDescription of the
424 * L2Interface group(inner) and the GroupDescription of the (outer)
425 * L3Unicast/MPLSInterface group. May return null if there is an
426 * error in processing the chain
427 */
428 protected GroupInfo createL2L3ChainInternal(TrafficTreatment treatment, int nextId,
Pier Ventre42287df2016-11-09 14:17:26 -0800429 ApplicationId appId, boolean mpls,
430 TrafficSelector meta, boolean useSetVlanExtension) {
Charles Chan188ebf52015-12-23 00:15:11 -0800431 // for the l2interface group, get vlan and port info
432 // for the outer group, get the src/dst mac, and vlan info
433 TrafficTreatment.Builder outerTtb = DefaultTrafficTreatment.builder();
434 TrafficTreatment.Builder innerTtb = DefaultTrafficTreatment.builder();
435 VlanId vlanid = null;
436 long portNum = 0;
437 boolean setVlan = false, popVlan = false;
Yi Tseng78f51f42017-02-02 13:54:58 -0800438 MacAddress srcMac;
439 MacAddress dstMac;
Charles Chan188ebf52015-12-23 00:15:11 -0800440 for (Instruction ins : treatment.allInstructions()) {
441 if (ins.type() == Instruction.Type.L2MODIFICATION) {
442 L2ModificationInstruction l2ins = (L2ModificationInstruction) ins;
443 switch (l2ins.subtype()) {
444 case ETH_DST:
Charles Chan5270ed02016-01-30 23:22:37 -0800445 dstMac = ((L2ModificationInstruction.ModEtherInstruction) l2ins).mac();
446 outerTtb.setEthDst(dstMac);
Charles Chan188ebf52015-12-23 00:15:11 -0800447 break;
448 case ETH_SRC:
Charles Chand0fd5dc2016-02-16 23:14:49 -0800449 srcMac = ((L2ModificationInstruction.ModEtherInstruction) l2ins).mac();
450 outerTtb.setEthSrc(srcMac);
Charles Chan188ebf52015-12-23 00:15:11 -0800451 break;
452 case VLAN_ID:
453 vlanid = ((L2ModificationInstruction.ModVlanIdInstruction) l2ins).vlanId();
Charles Chanf9e98652016-09-07 16:54:23 -0700454 if (useSetVlanExtension) {
455 OfdpaSetVlanVid ofdpaSetVlanVid = new OfdpaSetVlanVid(vlanid);
456 outerTtb.extension(ofdpaSetVlanVid, deviceId);
457 } else {
458 outerTtb.setVlanId(vlanid);
459 }
Charles Chan188ebf52015-12-23 00:15:11 -0800460 setVlan = true;
461 break;
462 case VLAN_POP:
463 innerTtb.popVlan();
464 popVlan = true;
465 break;
466 case DEC_MPLS_TTL:
467 case MPLS_LABEL:
468 case MPLS_POP:
469 case MPLS_PUSH:
470 case VLAN_PCP:
471 case VLAN_PUSH:
472 default:
473 break;
474 }
475 } else if (ins.type() == Instruction.Type.OUTPUT) {
476 portNum = ((Instructions.OutputInstruction) ins).port().toLong();
477 innerTtb.add(ins);
478 } else {
479 log.warn("Driver does not handle this type of TrafficTreatment"
480 + " instruction in nextObjectives: {}", ins.type());
481 }
482 }
483
484 if (vlanid == null && meta != null) {
485 // use metadata if available
Pier Ventre140a8942016-11-02 07:26:38 -0700486 Criterion vidCriterion = meta.getCriterion(VLAN_VID);
Charles Chan188ebf52015-12-23 00:15:11 -0800487 if (vidCriterion != null) {
488 vlanid = ((VlanIdCriterion) vidCriterion).vlanId();
489 }
490 // if vlan is not set, use the vlan in metadata for outerTtb
491 if (vlanid != null && !setVlan) {
Charles Chanf9e98652016-09-07 16:54:23 -0700492 if (useSetVlanExtension) {
493 OfdpaSetVlanVid ofdpaSetVlanVid = new OfdpaSetVlanVid(vlanid);
494 outerTtb.extension(ofdpaSetVlanVid, deviceId);
495 } else {
496 outerTtb.setVlanId(vlanid);
497 }
Charles Chan188ebf52015-12-23 00:15:11 -0800498 }
499 }
500
501 if (vlanid == null) {
502 log.error("Driver cannot process an L2/L3 group chain without "
503 + "egress vlan information for dev: {} port:{}",
504 deviceId, portNum);
505 return null;
506 }
507
508 if (!setVlan && !popVlan) {
509 // untagged outgoing port
510 TrafficTreatment.Builder temp = DefaultTrafficTreatment.builder();
511 temp.popVlan();
512 innerTtb.build().allInstructions().forEach(i -> temp.add(i));
513 innerTtb = temp;
514 }
515
516 // assemble information for ofdpa l2interface group
Charles Chane849c192016-01-11 18:28:54 -0800517 int l2groupId = L2_INTERFACE_TYPE | (vlanid.toShort() << 16) | (int) portNum;
Saurav Das8be4e3a2016-03-11 17:19:07 -0800518 // a globally unique groupkey that is different for ports in the same device,
Charles Chan188ebf52015-12-23 00:15:11 -0800519 // but different for the same portnumber on different devices. Also different
520 // for the various group-types created out of the same next objective.
Charles Chane849c192016-01-11 18:28:54 -0800521 int l2gk = l2InterfaceGroupKey(deviceId, vlanid, portNum);
Charles Chan361154b2016-03-24 10:23:39 -0700522 final GroupKey l2groupkey = new DefaultGroupKey(Ofdpa2Pipeline.appKryo.serialize(l2gk));
Charles Chan188ebf52015-12-23 00:15:11 -0800523
524 // assemble information for outer group
525 GroupDescription outerGrpDesc = null;
526 if (mpls) {
527 // outer group is MPLSInteface
Saurav Das8be4e3a2016-03-11 17:19:07 -0800528 int mplsInterfaceIndex = getNextAvailableIndex();
529 int mplsgroupId = MPLS_INTERFACE_TYPE | (SUBTYPE_MASK & mplsInterfaceIndex);
530 final GroupKey mplsgroupkey = new DefaultGroupKey(
Charles Chan361154b2016-03-24 10:23:39 -0700531 Ofdpa2Pipeline.appKryo.serialize(mplsInterfaceIndex));
Charles Chan188ebf52015-12-23 00:15:11 -0800532 outerTtb.group(new DefaultGroupId(l2groupId));
533 // create the mpls-interface group description to wait for the
534 // l2 interface group to be processed
535 GroupBucket mplsinterfaceGroupBucket =
536 DefaultGroupBucket.createIndirectGroupBucket(outerTtb.build());
537 outerGrpDesc = new DefaultGroupDescription(
538 deviceId,
539 GroupDescription.Type.INDIRECT,
540 new GroupBuckets(Collections.singletonList(
541 mplsinterfaceGroupBucket)),
542 mplsgroupkey,
543 mplsgroupId,
544 appId);
545 log.debug("Trying MPLS-Interface: device:{} gid:{} gkey:{} nextid:{}",
546 deviceId, Integer.toHexString(mplsgroupId),
547 mplsgroupkey, nextId);
548 } else {
549 // outer group is L3Unicast
Saurav Das8be4e3a2016-03-11 17:19:07 -0800550 int l3unicastIndex = getNextAvailableIndex();
551 int l3groupId = L3_UNICAST_TYPE | (TYPE_MASK & l3unicastIndex);
552 final GroupKey l3groupkey = new DefaultGroupKey(
Charles Chan361154b2016-03-24 10:23:39 -0700553 Ofdpa2Pipeline.appKryo.serialize(l3unicastIndex));
Charles Chan188ebf52015-12-23 00:15:11 -0800554 outerTtb.group(new DefaultGroupId(l2groupId));
555 // create the l3unicast group description to wait for the
556 // l2 interface group to be processed
557 GroupBucket l3unicastGroupBucket =
558 DefaultGroupBucket.createIndirectGroupBucket(outerTtb.build());
559 outerGrpDesc = new DefaultGroupDescription(
560 deviceId,
561 GroupDescription.Type.INDIRECT,
562 new GroupBuckets(Collections.singletonList(
563 l3unicastGroupBucket)),
564 l3groupkey,
565 l3groupId,
566 appId);
567 log.debug("Trying L3Unicast: device:{} gid:{} gkey:{} nextid:{}",
568 deviceId, Integer.toHexString(l3groupId),
569 l3groupkey, nextId);
570 }
571
572 // store l2groupkey with the groupChainElem for the outer-group that depends on it
573 GroupChainElem gce = new GroupChainElem(outerGrpDesc, 1, false);
574 updatePendingGroups(l2groupkey, gce);
575
576 // create group description for the inner l2interfacegroup
Charles Chan5b9df8d2016-03-28 22:21:40 -0700577 GroupBucket l2InterfaceGroupBucket =
Charles Chan188ebf52015-12-23 00:15:11 -0800578 DefaultGroupBucket.createIndirectGroupBucket(innerTtb.build());
579 GroupDescription l2groupDescription =
580 new DefaultGroupDescription(
581 deviceId,
582 GroupDescription.Type.INDIRECT,
583 new GroupBuckets(Collections.singletonList(
Charles Chan5b9df8d2016-03-28 22:21:40 -0700584 l2InterfaceGroupBucket)),
Charles Chan188ebf52015-12-23 00:15:11 -0800585 l2groupkey,
586 l2groupId,
587 appId);
588 log.debug("Trying L2Interface: device:{} gid:{} gkey:{} nextId:{}",
589 deviceId, Integer.toHexString(l2groupId),
590 l2groupkey, nextId);
591 return new GroupInfo(l2groupDescription, outerGrpDesc);
592
593 }
594
595 /**
596 * As per the OFDPA 2.0 TTP, packets are sent out of ports by using
597 * a chain of groups. The broadcast Next Objective passed in by the application
598 * has to be broken up into a group chain comprising of an
Saurav Das1a129a02016-11-18 15:21:57 -0800599 * L2 Flood group or L3 Multicast group, whose buckets point to L2 Interface groups.
Charles Chan188ebf52015-12-23 00:15:11 -0800600 *
601 * @param nextObj the nextObjective of type BROADCAST
602 */
603 private void processBroadcastNextObjective(NextObjective nextObj) {
Charles Chan5b9df8d2016-03-28 22:21:40 -0700604 VlanId assignedVlan = Ofdpa2Pipeline.readVlanFromSelector(nextObj.meta());
605 if (assignedVlan == null) {
606 log.warn("VLAN ID required by broadcast next obj is missing. Abort.");
607 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.BADPARAMS);
Charles Chan188ebf52015-12-23 00:15:11 -0800608 return;
609 }
Charles Chan188ebf52015-12-23 00:15:11 -0800610
Charles Chan5b9df8d2016-03-28 22:21:40 -0700611 List<GroupInfo> groupInfos = prepareL2InterfaceGroup(nextObj, assignedVlan);
612
613 IpPrefix ipDst = Ofdpa2Pipeline.readIpDstFromSelector(nextObj.meta());
614 if (ipDst != null) {
615 if (ipDst.isMulticast()) {
616 createL3MulticastGroup(nextObj, assignedVlan, groupInfos);
617 } else {
618 log.warn("Broadcast NextObj with non-multicast IP address {}", nextObj);
619 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.BADPARAMS);
620 return;
621 }
622 } else {
623 createL2FloodGroup(nextObj, assignedVlan, groupInfos);
624 }
625 }
626
Saurav Das1ce0a7b2016-10-21 14:06:29 -0700627 private List<GroupInfo> prepareL2InterfaceGroup(NextObjective nextObj,
628 VlanId assignedVlan) {
Charles Chan5b9df8d2016-03-28 22:21:40 -0700629 ImmutableList.Builder<GroupInfo> groupInfoBuilder = ImmutableList.builder();
630
631 // break up broadcast next objective to multiple groups
632 Collection<TrafficTreatment> buckets = nextObj.next();
633
Charles Chan188ebf52015-12-23 00:15:11 -0800634 // each treatment is converted to an L2 interface group
Charles Chan188ebf52015-12-23 00:15:11 -0800635 for (TrafficTreatment treatment : buckets) {
636 TrafficTreatment.Builder newTreatment = DefaultTrafficTreatment.builder();
637 PortNumber portNum = null;
Charles Chan5b9df8d2016-03-28 22:21:40 -0700638 VlanId egressVlan = null;
Charles Chan188ebf52015-12-23 00:15:11 -0800639 // ensure that the only allowed treatments are pop-vlan and output
640 for (Instruction ins : treatment.allInstructions()) {
641 if (ins.type() == Instruction.Type.L2MODIFICATION) {
642 L2ModificationInstruction l2ins = (L2ModificationInstruction) ins;
643 switch (l2ins.subtype()) {
644 case VLAN_POP:
645 newTreatment.add(l2ins);
646 break;
Charles Chan5b9df8d2016-03-28 22:21:40 -0700647 case VLAN_ID:
648 egressVlan = ((L2ModificationInstruction.ModVlanIdInstruction) l2ins).vlanId();
649 break;
Charles Chan188ebf52015-12-23 00:15:11 -0800650 default:
651 log.debug("action {} not permitted for broadcast nextObj",
652 l2ins.subtype());
653 break;
654 }
655 } else if (ins.type() == Instruction.Type.OUTPUT) {
656 portNum = ((Instructions.OutputInstruction) ins).port();
657 newTreatment.add(ins);
658 } else {
Charles Chane849c192016-01-11 18:28:54 -0800659 log.debug("TrafficTreatment of type {} not permitted in " +
660 " broadcast nextObjective", ins.type());
Charles Chan188ebf52015-12-23 00:15:11 -0800661 }
662 }
663
Charles Chan188ebf52015-12-23 00:15:11 -0800664 // assemble info for l2 interface group
Charles Chan5b9df8d2016-03-28 22:21:40 -0700665 VlanId l2InterfaceGroupVlan =
666 (egressVlan != null && !assignedVlan.equals(egressVlan)) ?
667 egressVlan : assignedVlan;
668 int l2gk = l2InterfaceGroupKey(deviceId, l2InterfaceGroupVlan, portNum.toLong());
669 final GroupKey l2InterfaceGroupKey =
670 new DefaultGroupKey(Ofdpa2Pipeline.appKryo.serialize(l2gk));
Charles Chan372b63e2017-02-07 12:10:53 -0800671 int l2InterfaceGroupId = L2_INTERFACE_TYPE |
672 ((l2InterfaceGroupVlan.toShort() & THREE_BIT_MASK) << PORT_LEN) |
673 ((int) portNum.toLong() & FOUR_BIT_MASK);
Charles Chan5b9df8d2016-03-28 22:21:40 -0700674 GroupBucket l2InterfaceGroupBucket =
Charles Chan188ebf52015-12-23 00:15:11 -0800675 DefaultGroupBucket.createIndirectGroupBucket(newTreatment.build());
Charles Chan5b9df8d2016-03-28 22:21:40 -0700676 GroupDescription l2InterfaceGroupDescription =
Charles Chan188ebf52015-12-23 00:15:11 -0800677 new DefaultGroupDescription(
678 deviceId,
679 GroupDescription.Type.INDIRECT,
680 new GroupBuckets(Collections.singletonList(
Charles Chan5b9df8d2016-03-28 22:21:40 -0700681 l2InterfaceGroupBucket)),
682 l2InterfaceGroupKey,
683 l2InterfaceGroupId,
Charles Chan188ebf52015-12-23 00:15:11 -0800684 nextObj.appId());
685 log.debug("Trying L2-Interface: device:{} gid:{} gkey:{} nextid:{}",
Charles Chan5b9df8d2016-03-28 22:21:40 -0700686 deviceId, Integer.toHexString(l2InterfaceGroupId),
687 l2InterfaceGroupKey, nextObj.id());
Charles Chan188ebf52015-12-23 00:15:11 -0800688
Charles Chan5b9df8d2016-03-28 22:21:40 -0700689 groupInfoBuilder.add(new GroupInfo(l2InterfaceGroupDescription,
690 l2InterfaceGroupDescription));
Charles Chan188ebf52015-12-23 00:15:11 -0800691 }
Charles Chan5b9df8d2016-03-28 22:21:40 -0700692 return groupInfoBuilder.build();
693 }
Charles Chan188ebf52015-12-23 00:15:11 -0800694
Saurav Das1ce0a7b2016-10-21 14:06:29 -0700695 private void createL2FloodGroup(NextObjective nextObj, VlanId vlanId,
696 List<GroupInfo> groupInfos) {
697 // assemble info for l2 flood group. Since there can be only one flood
698 // group for a vlan, its index is always the same - 0
Saurav Das0fd79d92016-03-07 10:58:36 -0800699 Integer l2floodgroupId = L2_FLOOD_TYPE | (vlanId.toShort() << 16);
Saurav Das8be4e3a2016-03-11 17:19:07 -0800700 int l2floodgk = getNextAvailableIndex();
Saurav Das1ce0a7b2016-10-21 14:06:29 -0700701 final GroupKey l2floodgroupkey =
702 new DefaultGroupKey(Ofdpa2Pipeline.appKryo.serialize(l2floodgk));
Charles Chan5b9df8d2016-03-28 22:21:40 -0700703
Charles Chan188ebf52015-12-23 00:15:11 -0800704 // collection of group buckets pointing to all the l2 interface groups
Yi Tseng78f51f42017-02-02 13:54:58 -0800705 List<GroupBucket> l2floodBuckets =
706 generateNextGroupBuckets(groupInfos, ALL);
Charles Chan188ebf52015-12-23 00:15:11 -0800707 // create the l2flood group-description to wait for all the
708 // l2interface groups to be processed
709 GroupDescription l2floodGroupDescription =
710 new DefaultGroupDescription(
711 deviceId,
Yi Tseng78f51f42017-02-02 13:54:58 -0800712 ALL,
Charles Chan188ebf52015-12-23 00:15:11 -0800713 new GroupBuckets(l2floodBuckets),
714 l2floodgroupkey,
715 l2floodgroupId,
716 nextObj.appId());
Charles Chan188ebf52015-12-23 00:15:11 -0800717 log.debug("Trying L2-Flood: device:{} gid:{} gkey:{} nextid:{}",
718 deviceId, Integer.toHexString(l2floodgroupId),
719 l2floodgroupkey, nextObj.id());
720
Charles Chan5b9df8d2016-03-28 22:21:40 -0700721 // Put all dependency information into allGroupKeys
722 List<Deque<GroupKey>> allGroupKeys = Lists.newArrayList();
723 groupInfos.forEach(groupInfo -> {
724 Deque<GroupKey> gkeyChain = new ArrayDeque<>();
725 // In this case we should have L2 interface group only
726 gkeyChain.addFirst(groupInfo.nextGroupDesc.appCookie());
727 gkeyChain.addFirst(l2floodgroupkey);
728 allGroupKeys.add(gkeyChain);
729 });
Charles Chan188ebf52015-12-23 00:15:11 -0800730
Charles Chan5b9df8d2016-03-28 22:21:40 -0700731 // Point the next objective to this group
732 OfdpaNextGroup ofdpaGrp = new OfdpaNextGroup(allGroupKeys, nextObj);
Charles Chan188ebf52015-12-23 00:15:11 -0800733 updatePendingNextObjective(l2floodgroupkey, ofdpaGrp);
734
Charles Chan5b9df8d2016-03-28 22:21:40 -0700735 GroupChainElem gce = new GroupChainElem(l2floodGroupDescription,
736 groupInfos.size(), false);
737 groupInfos.forEach(groupInfo -> {
738 // Point this group to the next group
739 updatePendingGroups(groupInfo.nextGroupDesc.appCookie(), gce);
740 // Start installing the inner-most group
741 groupService.addGroup(groupInfo.innerMostGroupDesc);
742 });
743 }
744
Saurav Das1ce0a7b2016-10-21 14:06:29 -0700745 private void createL3MulticastGroup(NextObjective nextObj, VlanId vlanId,
746 List<GroupInfo> groupInfos) {
Charles Chan5b9df8d2016-03-28 22:21:40 -0700747 List<GroupBucket> l3McastBuckets = new ArrayList<>();
748 groupInfos.forEach(groupInfo -> {
749 // Points to L3 interface group if there is one.
750 // Otherwise points to L2 interface group directly.
751 GroupDescription nextGroupDesc = (groupInfo.nextGroupDesc != null) ?
752 groupInfo.nextGroupDesc : groupInfo.innerMostGroupDesc;
753 TrafficTreatment.Builder ttb = DefaultTrafficTreatment.builder();
754 ttb.group(new DefaultGroupId(nextGroupDesc.givenGroupId()));
755 GroupBucket abucket = DefaultGroupBucket.createAllGroupBucket(ttb.build());
756 l3McastBuckets.add(abucket);
757 });
758
759 int l3MulticastIndex = getNextAvailableIndex();
Saurav Das1ce0a7b2016-10-21 14:06:29 -0700760 int l3MulticastGroupId = L3_MULTICAST_TYPE |
761 vlanId.toShort() << 16 | (TYPE_VLAN_MASK & l3MulticastIndex);
762 final GroupKey l3MulticastGroupKey =
763 new DefaultGroupKey(Ofdpa2Pipeline.appKryo.serialize(l3MulticastIndex));
Charles Chan5b9df8d2016-03-28 22:21:40 -0700764
765 GroupDescription l3MulticastGroupDesc = new DefaultGroupDescription(deviceId,
Yi Tseng78f51f42017-02-02 13:54:58 -0800766 ALL,
Charles Chan5b9df8d2016-03-28 22:21:40 -0700767 new GroupBuckets(l3McastBuckets),
768 l3MulticastGroupKey,
769 l3MulticastGroupId,
770 nextObj.appId());
771
772 // Put all dependency information into allGroupKeys
773 List<Deque<GroupKey>> allGroupKeys = Lists.newArrayList();
774 groupInfos.forEach(groupInfo -> {
775 Deque<GroupKey> gkeyChain = new ArrayDeque<>();
776 gkeyChain.addFirst(groupInfo.innerMostGroupDesc.appCookie());
777 // Add L3 interface group to the chain if there is one.
778 if (!groupInfo.nextGroupDesc.equals(groupInfo.innerMostGroupDesc)) {
779 gkeyChain.addFirst(groupInfo.nextGroupDesc.appCookie());
780 }
781 gkeyChain.addFirst(l3MulticastGroupKey);
782 allGroupKeys.add(gkeyChain);
783 });
784
785 // Point the next objective to this group
786 OfdpaNextGroup ofdpaGrp = new OfdpaNextGroup(allGroupKeys, nextObj);
787 updatePendingNextObjective(l3MulticastGroupKey, ofdpaGrp);
788
789 GroupChainElem outerGce = new GroupChainElem(l3MulticastGroupDesc,
790 groupInfos.size(), false);
791 groupInfos.forEach(groupInfo -> {
792 // Point this group (L3 multicast) to the next group
793 updatePendingGroups(groupInfo.nextGroupDesc.appCookie(), outerGce);
794
795 // Point next group to inner-most group, if any
796 if (!groupInfo.nextGroupDesc.equals(groupInfo.innerMostGroupDesc)) {
797 GroupChainElem innerGce = new GroupChainElem(groupInfo.nextGroupDesc,
798 1, false);
799 updatePendingGroups(groupInfo.innerMostGroupDesc.appCookie(), innerGce);
800 }
801
802 // Start installing the inner-most group
803 groupService.addGroup(groupInfo.innerMostGroupDesc);
804 });
Charles Chan188ebf52015-12-23 00:15:11 -0800805 }
806
Charles Chan188ebf52015-12-23 00:15:11 -0800807 /**
808 * As per the OFDPA 2.0 TTP, packets are sent out of ports by using
809 * a chain of groups. The hashed Next Objective passed in by the application
810 * has to be broken up into a group chain comprising of an
811 * L3 ECMP group as the top level group. Buckets of this group can point
812 * to a variety of groups in a group chain, depending on the whether
813 * MPLS labels are being pushed or not.
814 * <p>
815 * NOTE: We do not create MPLS ECMP groups as they are unimplemented in
816 * OF-DPA 2.0 (even though it is in the spec). Therefore we do not
817 * check the nextObjective meta to see what is matching before being
818 * sent to this nextObjective.
819 *
820 * @param nextObj the nextObjective of type HASHED
821 */
Pier Ventre140a8942016-11-02 07:26:38 -0700822 protected void processHashedNextObjective(NextObjective nextObj) {
Charles Chan188ebf52015-12-23 00:15:11 -0800823 // storage for all group keys in the chain of groups created
824 List<Deque<GroupKey>> allGroupKeys = new ArrayList<>();
825 List<GroupInfo> unsentGroups = new ArrayList<>();
826 createHashBucketChains(nextObj, allGroupKeys, unsentGroups);
827
828 // now we can create the outermost L3 ECMP group
829 List<GroupBucket> l3ecmpGroupBuckets = new ArrayList<>();
830 for (GroupInfo gi : unsentGroups) {
831 // create ECMP bucket to point to the outer group
832 TrafficTreatment.Builder ttb = DefaultTrafficTreatment.builder();
Charles Chan5b9df8d2016-03-28 22:21:40 -0700833 ttb.group(new DefaultGroupId(gi.nextGroupDesc.givenGroupId()));
Charles Chan188ebf52015-12-23 00:15:11 -0800834 GroupBucket sbucket = DefaultGroupBucket
835 .createSelectGroupBucket(ttb.build());
836 l3ecmpGroupBuckets.add(sbucket);
837 }
Saurav Das8be4e3a2016-03-11 17:19:07 -0800838 int l3ecmpIndex = getNextAvailableIndex();
839 int l3ecmpGroupId = L3_ECMP_TYPE | (TYPE_MASK & l3ecmpIndex);
840 GroupKey l3ecmpGroupKey = new DefaultGroupKey(
Charles Chan361154b2016-03-24 10:23:39 -0700841 Ofdpa2Pipeline.appKryo.serialize(l3ecmpIndex));
Charles Chan188ebf52015-12-23 00:15:11 -0800842 GroupDescription l3ecmpGroupDesc =
843 new DefaultGroupDescription(
844 deviceId,
Yi Tseng78f51f42017-02-02 13:54:58 -0800845 SELECT,
Charles Chan188ebf52015-12-23 00:15:11 -0800846 new GroupBuckets(l3ecmpGroupBuckets),
847 l3ecmpGroupKey,
848 l3ecmpGroupId,
849 nextObj.appId());
850 GroupChainElem l3ecmpGce = new GroupChainElem(l3ecmpGroupDesc,
851 l3ecmpGroupBuckets.size(),
852 false);
853
854 // create objects for local and distributed storage
855 allGroupKeys.forEach(gkeyChain -> gkeyChain.addFirst(l3ecmpGroupKey));
856 OfdpaNextGroup ofdpaGrp = new OfdpaNextGroup(allGroupKeys, nextObj);
857
858 // store l3ecmpGroupKey with the ofdpaGroupChain for the nextObjective
859 // that depends on it
860 updatePendingNextObjective(l3ecmpGroupKey, ofdpaGrp);
861
862 log.debug("Trying L3ECMP: device:{} gid:{} gkey:{} nextId:{}",
863 deviceId, Integer.toHexString(l3ecmpGroupId),
864 l3ecmpGroupKey, nextObj.id());
865 // finally we are ready to send the innermost groups
866 for (GroupInfo gi : unsentGroups) {
867 log.debug("Sending innermost group {} in group chain on device {} ",
Charles Chan5b9df8d2016-03-28 22:21:40 -0700868 Integer.toHexString(gi.innerMostGroupDesc.givenGroupId()), deviceId);
869 updatePendingGroups(gi.nextGroupDesc.appCookie(), l3ecmpGce);
870 groupService.addGroup(gi.innerMostGroupDesc);
Charles Chan188ebf52015-12-23 00:15:11 -0800871 }
872
873 }
874
875 /**
876 * Creates group chains for all buckets in a hashed group, and stores the
877 * GroupInfos and GroupKeys for all the groups in the lists passed in, which
878 * should be empty.
879 * <p>
880 * Does not create the top level ECMP group. Does not actually send the
881 * groups to the groupService.
882 *
883 * @param nextObj the Next Objective with buckets that need to be converted
884 * to group chains
885 * @param allGroupKeys a list to store groupKey for each bucket-group-chain
886 * @param unsentGroups a list to store GroupInfo for each bucket-group-chain
887 */
Pier Ventre140a8942016-11-02 07:26:38 -0700888 protected void createHashBucketChains(NextObjective nextObj,
Saurav Das8be4e3a2016-03-11 17:19:07 -0800889 List<Deque<GroupKey>> allGroupKeys,
890 List<GroupInfo> unsentGroups) {
Charles Chan188ebf52015-12-23 00:15:11 -0800891 // break up hashed next objective to multiple groups
892 Collection<TrafficTreatment> buckets = nextObj.next();
893
894 for (TrafficTreatment bucket : buckets) {
895 //figure out how many labels are pushed in each bucket
896 int labelsPushed = 0;
897 MplsLabel innermostLabel = null;
898 for (Instruction ins : bucket.allInstructions()) {
899 if (ins.type() == Instruction.Type.L2MODIFICATION) {
900 L2ModificationInstruction l2ins = (L2ModificationInstruction) ins;
901 if (l2ins.subtype() == L2ModificationInstruction.L2SubType.MPLS_PUSH) {
902 labelsPushed++;
903 }
904 if (l2ins.subtype() == L2ModificationInstruction.L2SubType.MPLS_LABEL) {
905 if (innermostLabel == null) {
Ray Milkey125572b2016-02-22 16:48:17 -0800906 innermostLabel = ((L2ModificationInstruction.ModMplsLabelInstruction) l2ins).label();
Charles Chan188ebf52015-12-23 00:15:11 -0800907 }
908 }
909 }
910 }
911
912 Deque<GroupKey> gkeyChain = new ArrayDeque<>();
913 // XXX we only deal with 0 and 1 label push right now
914 if (labelsPushed == 0) {
Pier Ventre140a8942016-11-02 07:26:38 -0700915 GroupInfo nolabelGroupInfo;
916 TrafficSelector metaSelector = nextObj.meta();
917 if (metaSelector != null) {
918 if (isNotMplsBos(metaSelector)) {
919 nolabelGroupInfo = createL2L3Chain(bucket, nextObj.id(),
920 nextObj.appId(), true,
921 nextObj.meta());
922 } else {
923 nolabelGroupInfo = createL2L3Chain(bucket, nextObj.id(),
924 nextObj.appId(), false,
925 nextObj.meta());
926 }
927 } else {
928 nolabelGroupInfo = createL2L3Chain(bucket, nextObj.id(),
929 nextObj.appId(), false,
930 nextObj.meta());
931 }
Charles Chan188ebf52015-12-23 00:15:11 -0800932 if (nolabelGroupInfo == null) {
933 log.error("Could not process nextObj={} in dev:{}",
934 nextObj.id(), deviceId);
935 return;
936 }
Charles Chan5b9df8d2016-03-28 22:21:40 -0700937 gkeyChain.addFirst(nolabelGroupInfo.innerMostGroupDesc.appCookie());
938 gkeyChain.addFirst(nolabelGroupInfo.nextGroupDesc.appCookie());
Charles Chan188ebf52015-12-23 00:15:11 -0800939
940 // we can't send the inner group description yet, as we have to
941 // create the dependent ECMP group first. So we store..
942 unsentGroups.add(nolabelGroupInfo);
943
944 } else if (labelsPushed == 1) {
945 GroupInfo onelabelGroupInfo = createL2L3Chain(bucket, nextObj.id(),
946 nextObj.appId(), true,
947 nextObj.meta());
948 if (onelabelGroupInfo == null) {
949 log.error("Could not process nextObj={} in dev:{}",
950 nextObj.id(), deviceId);
951 return;
952 }
953 // we need to add another group to this chain - the L3VPN group
954 TrafficTreatment.Builder l3vpnTtb = DefaultTrafficTreatment.builder();
Charles Chan0f43e472017-02-14 14:00:16 -0800955 if (requireVlanPopBeforeMplsPush()) {
956 l3vpnTtb.popVlan();
957 }
Charles Chan188ebf52015-12-23 00:15:11 -0800958 l3vpnTtb.pushMpls()
959 .setMpls(innermostLabel)
Charles Chan40132b32017-01-22 00:19:37 -0800960 .group(new DefaultGroupId(onelabelGroupInfo.nextGroupDesc.givenGroupId()));
961 if (supportCopyTtl()) {
962 l3vpnTtb.copyTtlOut();
963 }
964 if (supportSetMplsBos()) {
965 l3vpnTtb.setMplsBos(true);
966 }
Charles Chan0f43e472017-02-14 14:00:16 -0800967 if (requireVlanPopBeforeMplsPush()) {
968 l3vpnTtb.pushVlan().setVlanId(VlanId.vlanId(VlanId.RESERVED));
969 }
Charles Chan40132b32017-01-22 00:19:37 -0800970
Charles Chan188ebf52015-12-23 00:15:11 -0800971 GroupBucket l3vpnGrpBkt =
972 DefaultGroupBucket.createIndirectGroupBucket(l3vpnTtb.build());
Saurav Das8be4e3a2016-03-11 17:19:07 -0800973 int l3vpnIndex = getNextAvailableIndex();
974 int l3vpngroupId = MPLS_L3VPN_SUBTYPE | (SUBTYPE_MASK & l3vpnIndex);
975 GroupKey l3vpngroupkey = new DefaultGroupKey(
Charles Chan361154b2016-03-24 10:23:39 -0700976 Ofdpa2Pipeline.appKryo.serialize(l3vpnIndex));
Charles Chan188ebf52015-12-23 00:15:11 -0800977 GroupDescription l3vpnGroupDesc =
978 new DefaultGroupDescription(
979 deviceId,
980 GroupDescription.Type.INDIRECT,
981 new GroupBuckets(Collections.singletonList(
982 l3vpnGrpBkt)),
983 l3vpngroupkey,
984 l3vpngroupId,
985 nextObj.appId());
986 GroupChainElem l3vpnGce = new GroupChainElem(l3vpnGroupDesc, 1, false);
Charles Chan5b9df8d2016-03-28 22:21:40 -0700987 updatePendingGroups(onelabelGroupInfo.nextGroupDesc.appCookie(), l3vpnGce);
Charles Chan188ebf52015-12-23 00:15:11 -0800988
Charles Chan5b9df8d2016-03-28 22:21:40 -0700989 gkeyChain.addFirst(onelabelGroupInfo.innerMostGroupDesc.appCookie());
990 gkeyChain.addFirst(onelabelGroupInfo.nextGroupDesc.appCookie());
Charles Chan188ebf52015-12-23 00:15:11 -0800991 gkeyChain.addFirst(l3vpngroupkey);
992
993 //now we can replace the outerGrpDesc with the one we just created
Charles Chan5b9df8d2016-03-28 22:21:40 -0700994 onelabelGroupInfo.nextGroupDesc = l3vpnGroupDesc;
Charles Chan188ebf52015-12-23 00:15:11 -0800995
996 // we can't send the innermost group yet, as we have to create
997 // the dependent ECMP group first. So we store ...
998 unsentGroups.add(onelabelGroupInfo);
999
1000 log.debug("Trying L3VPN: device:{} gid:{} gkey:{} nextId:{}",
1001 deviceId, Integer.toHexString(l3vpngroupId),
1002 l3vpngroupkey, nextObj.id());
1003
1004 } else {
1005 log.warn("Driver currently does not handle more than 1 MPLS "
1006 + "labels. Not processing nextObjective {}", nextObj.id());
1007 return;
1008 }
1009
1010 // all groups in this chain
1011 allGroupKeys.add(gkeyChain);
1012 }
1013 }
1014
Pier Ventre42287df2016-11-09 14:17:26 -08001015 /**
1016 * Processes the pseudo wire related next objective.
1017 * This procedure try to reuse the mpls label groups,
1018 * the mpls interface group and the l2 interface group.
1019 *
1020 * @param nextObjective the objective to process.
1021 */
1022 protected void processPwNextObjective(NextObjective nextObjective) {
1023 log.warn("Pseudo wire extensions are not support for the OFDPA 2.0 {}", nextObjective.id());
1024 return;
1025 }
1026
Saurav Das8be4e3a2016-03-11 17:19:07 -08001027 //////////////////////////////////////
1028 // Group Editing
1029 //////////////////////////////////////
1030
Charles Chan188ebf52015-12-23 00:15:11 -08001031 /**
1032 * Adds a bucket to the top level group of a group-chain, and creates the chain.
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001033 * Ensures that bucket being added is not a duplicate, by checking existing
1034 * buckets for the same outport.
Charles Chan188ebf52015-12-23 00:15:11 -08001035 *
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001036 * @param nextObjective the bucket information for a next group
Charles Chan188ebf52015-12-23 00:15:11 -08001037 * @param next the representation of the existing group-chain for this next objective
1038 */
1039 protected void addBucketToGroup(NextObjective nextObjective, NextGroup next) {
Saurav Das1a129a02016-11-18 15:21:57 -08001040 if (nextObjective.type() != NextObjective.Type.HASHED &&
1041 nextObjective.type() != NextObjective.Type.BROADCAST) {
Charles Chan188ebf52015-12-23 00:15:11 -08001042 log.warn("AddBuckets not applied to nextType:{} in dev:{} for next:{}",
Yi Tseng78f51f42017-02-02 13:54:58 -08001043 nextObjective.type(), deviceId, nextObjective.id());
Saurav Das1a129a02016-11-18 15:21:57 -08001044 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.UNSUPPORTED);
Charles Chan188ebf52015-12-23 00:15:11 -08001045 return;
1046 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001047
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001048 // first check to see if bucket being added is not a duplicate of an
1049 // existing bucket. If it is for an existing outport, then its a duplicate.
Yi Tseng78f51f42017-02-02 13:54:58 -08001050 Set<TrafficTreatment> duplicateBuckets = Sets.newHashSet();
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001051 List<Deque<GroupKey>> allActiveKeys = Ofdpa2Pipeline.appKryo.deserialize(next.data());
Yi Tseng78f51f42017-02-02 13:54:58 -08001052 Set<PortNumber> existingPorts = getExistingOutputPorts(allActiveKeys);
1053
1054 nextObjective.next().forEach(trafficTreatment -> {
1055 PortNumber portNumber = readOutPortFromTreatment(trafficTreatment);
1056
1057 if (portNumber == null) {
1058 return;
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001059 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001060
1061 if (existingPorts.contains(portNumber)) {
1062 duplicateBuckets.add(trafficTreatment);
1063 }
1064 });
1065
1066 if (!duplicateBuckets.isEmpty()) {
1067 log.warn("Some buckets {} already exists in next id {}, abort.",
1068 duplicateBuckets, nextObjective.id());
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001069 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001070
Saurav Das1a129a02016-11-18 15:21:57 -08001071 if (nextObjective.type() == NextObjective.Type.HASHED) {
Yi Tseng78f51f42017-02-02 13:54:58 -08001072 addBucketToHashGroup(nextObjective, allActiveKeys);
Saurav Das1a129a02016-11-18 15:21:57 -08001073 } else if (nextObjective.type() == NextObjective.Type.BROADCAST) {
Yi Tseng78f51f42017-02-02 13:54:58 -08001074 addBucketToBroadcastGroup(nextObjective, allActiveKeys);
Saurav Das1a129a02016-11-18 15:21:57 -08001075 }
1076 }
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001077
Yi Tseng78f51f42017-02-02 13:54:58 -08001078 private Set<PortNumber> getExistingOutputPorts(List<Deque<GroupKey>> allActiveKeys) {
1079 Set<PortNumber> existingPorts = Sets.newHashSet();
1080
1081 allActiveKeys.forEach(keyChain -> {
1082 GroupKey ifaceGroupKey = keyChain.peekLast();
1083 Group ifaceGroup = groupService.getGroup(deviceId, ifaceGroupKey);
1084 if (ifaceGroup != null && !ifaceGroup.buckets().buckets().isEmpty()) {
1085 ifaceGroup.buckets().buckets().forEach(bucket -> {
1086 PortNumber portNumber = readOutPortFromTreatment(bucket.treatment());
1087
1088 if (portNumber != null) {
1089 existingPorts.add(portNumber);
1090 }
1091 });
1092 }
1093 });
1094
1095 return existingPorts;
1096 }
1097
Saurav Das1a129a02016-11-18 15:21:57 -08001098 private void addBucketToHashGroup(NextObjective nextObjective,
Yi Tseng78f51f42017-02-02 13:54:58 -08001099 List<Deque<GroupKey>> allActiveKeys) {
Charles Chan188ebf52015-12-23 00:15:11 -08001100 // storage for all group keys in the chain of groups created
1101 List<Deque<GroupKey>> allGroupKeys = new ArrayList<>();
1102 List<GroupInfo> unsentGroups = new ArrayList<>();
Yi Tseng78f51f42017-02-02 13:54:58 -08001103 List<GroupBucket> newBuckets = Lists.newArrayList();
Charles Chan188ebf52015-12-23 00:15:11 -08001104 createHashBucketChains(nextObjective, allGroupKeys, unsentGroups);
1105
Yi Tseng78f51f42017-02-02 13:54:58 -08001106 // now we can create the buckets to add to the outermost L3 ECMP group
1107 newBuckets = generateNextGroupBuckets(unsentGroups, SELECT);
Charles Chan188ebf52015-12-23 00:15:11 -08001108
Saurav Das1a129a02016-11-18 15:21:57 -08001109 // retrieve the original L3 ECMP group
1110 Group l3ecmpGroup = retrieveTopLevelGroup(allActiveKeys, nextObjective.id());
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001111 if (l3ecmpGroup == null) {
Saurav Das1a129a02016-11-18 15:21:57 -08001112 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.GROUPMISSING);
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001113 return;
1114 }
Saurav Das1a129a02016-11-18 15:21:57 -08001115 GroupKey l3ecmpGroupKey = l3ecmpGroup.appCookie();
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001116 int l3ecmpGroupId = l3ecmpGroup.id().id();
Charles Chan188ebf52015-12-23 00:15:11 -08001117
1118 // Although GroupDescriptions are not necessary for adding buckets to
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001119 // existing groups, we still use one in the GroupChainElem. When the latter is
Charles Chan188ebf52015-12-23 00:15:11 -08001120 // processed, the info will be extracted for the bucketAdd call to groupService
1121 GroupDescription l3ecmpGroupDesc =
1122 new DefaultGroupDescription(
1123 deviceId,
Yi Tseng78f51f42017-02-02 13:54:58 -08001124 SELECT,
1125 new GroupBuckets(newBuckets),
Charles Chan188ebf52015-12-23 00:15:11 -08001126 l3ecmpGroupKey,
1127 l3ecmpGroupId,
1128 nextObjective.appId());
Yi Tseng78f51f42017-02-02 13:54:58 -08001129 GroupChainElem l3ecmpGce = new GroupChainElem(l3ecmpGroupDesc,
1130 unsentGroups.size(),
1131 true);
Charles Chan188ebf52015-12-23 00:15:11 -08001132
1133 // update original NextGroup with new bucket-chain
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001134 // If active keys shows only the top-level group without a chain of groups,
1135 // then it represents an empty group. Update by replacing empty chain.
Charles Chan188ebf52015-12-23 00:15:11 -08001136 Deque<GroupKey> newBucketChain = allGroupKeys.get(0);
1137 newBucketChain.addFirst(l3ecmpGroupKey);
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001138 if (allActiveKeys.size() == 1 && allActiveKeys.get(0).size() == 1) {
1139 allActiveKeys.clear();
1140 }
1141 allActiveKeys.add(newBucketChain);
1142 updatePendingNextObjective(l3ecmpGroupKey,
1143 new OfdpaNextGroup(allActiveKeys, nextObjective));
Yi Tseng78f51f42017-02-02 13:54:58 -08001144
Charles Chan188ebf52015-12-23 00:15:11 -08001145 log.debug("Adding to L3ECMP: device:{} gid:{} gkey:{} nextId:{}",
1146 deviceId, Integer.toHexString(l3ecmpGroupId),
1147 l3ecmpGroupKey, nextObjective.id());
Yi Tseng78f51f42017-02-02 13:54:58 -08001148
1149 unsentGroups.forEach(groupInfo -> {
1150 // send the innermost group
1151 log.debug("Sending innermost group {} in group chain on device {} ",
1152 Integer.toHexString(groupInfo.innerMostGroupDesc.givenGroupId()), deviceId);
1153 updatePendingGroups(groupInfo.nextGroupDesc.appCookie(), l3ecmpGce);
1154 groupService.addGroup(groupInfo.innerMostGroupDesc);
1155 });
1156
Saurav Das1a129a02016-11-18 15:21:57 -08001157 }
Charles Chan188ebf52015-12-23 00:15:11 -08001158
Saurav Das1a129a02016-11-18 15:21:57 -08001159 private void addBucketToBroadcastGroup(NextObjective nextObj,
Yi Tseng78f51f42017-02-02 13:54:58 -08001160 List<Deque<GroupKey>> allActiveKeys) {
Saurav Das1a129a02016-11-18 15:21:57 -08001161 VlanId assignedVlan = Ofdpa2Pipeline.readVlanFromSelector(nextObj.meta());
1162 if (assignedVlan == null) {
1163 log.warn("VLAN ID required by broadcast next obj is missing. "
1164 + "Aborting add bucket to broadcast group for next:{} in dev:{}",
1165 nextObj.id(), deviceId);
1166 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.BADPARAMS);
1167 return;
1168 }
1169
1170 List<GroupInfo> groupInfos = prepareL2InterfaceGroup(nextObj, assignedVlan);
1171
1172 IpPrefix ipDst = Ofdpa2Pipeline.readIpDstFromSelector(nextObj.meta());
1173 if (ipDst != null) {
1174 if (ipDst.isMulticast()) {
1175 addBucketToL3MulticastGroup(nextObj, allActiveKeys,
Yi Tseng78f51f42017-02-02 13:54:58 -08001176 groupInfos, assignedVlan);
Saurav Das1a129a02016-11-18 15:21:57 -08001177 } else {
1178 log.warn("Broadcast NextObj with non-multicast IP address {}", nextObj);
1179 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.BADPARAMS);
1180 return;
1181 }
1182 } else {
1183 addBucketToL2FloodGroup(nextObj, allActiveKeys,
Yi Tseng78f51f42017-02-02 13:54:58 -08001184 groupInfos, assignedVlan);
Saurav Das1a129a02016-11-18 15:21:57 -08001185 }
1186 }
1187
1188 private void addBucketToL2FloodGroup(NextObjective nextObj,
1189 List<Deque<GroupKey>> allActiveKeys,
1190 List<GroupInfo> groupInfos,
Yi Tseng78f51f42017-02-02 13:54:58 -08001191 VlanId assignedVlan) {
1192 Group l2FloodGroup = retrieveTopLevelGroup(allActiveKeys, nextObj.id());
1193
1194 if (l2FloodGroup == null) {
1195 log.warn("Can't find L2 flood group while adding bucket to it. NextObj = {}",
1196 nextObj);
Saurav Das1a129a02016-11-18 15:21:57 -08001197 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.GROUPMISSING);
1198 return;
1199 }
Saurav Das1a129a02016-11-18 15:21:57 -08001200
Yi Tseng78f51f42017-02-02 13:54:58 -08001201 GroupKey l2floodGroupKey = l2FloodGroup.appCookie();
1202 int l2floodGroupId = l2FloodGroup.id().id();
1203 List<GroupBucket> newBuckets = generateNextGroupBuckets(groupInfos, ALL);
1204
1205 GroupDescription l2FloodGroupDescription =
Saurav Das1a129a02016-11-18 15:21:57 -08001206 new DefaultGroupDescription(
1207 deviceId,
Yi Tseng78f51f42017-02-02 13:54:58 -08001208 ALL,
1209 new GroupBuckets(newBuckets),
Saurav Das1a129a02016-11-18 15:21:57 -08001210 l2floodGroupKey,
1211 l2floodGroupId,
1212 nextObj.appId());
Saurav Das1a129a02016-11-18 15:21:57 -08001213
Yi Tseng78f51f42017-02-02 13:54:58 -08001214 GroupChainElem l2FloodGroupChainElement =
1215 new GroupChainElem(l2FloodGroupDescription,
1216 groupInfos.size(),
1217 true);
1218
Saurav Das1a129a02016-11-18 15:21:57 -08001219 updatePendingNextObjective(l2floodGroupKey,
1220 new OfdpaNextGroup(allActiveKeys, nextObj));
Yi Tseng78f51f42017-02-02 13:54:58 -08001221
1222 //ensure assignedVlan applies to the chosen group
1223 VlanId floodGroupVlan = extractVlanIdFromGroupId(l2floodGroupId);
1224
1225 if (!floodGroupVlan.equals(assignedVlan)) {
1226 log.warn("VLAN ID {} does not match Flood group {} to which bucket is "
1227 + "being added, for next:{} in dev:{}. Abort.", assignedVlan,
1228 Integer.toHexString(l2floodGroupId), nextObj.id(), deviceId);
1229 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.BADPARAMS);
1230 return;
1231 }
1232
1233 groupInfos.forEach(groupInfo -> {
1234 // update original NextGroup with new bucket-chain
1235 // If active keys shows only the top-level group without a chain of groups,
1236 // then it represents an empty group. Update by replacing empty chain.
1237 Deque<GroupKey> newBucketChain = new ArrayDeque<>();
1238 newBucketChain.addFirst(groupInfo.nextGroupDesc.appCookie());
1239 newBucketChain.addFirst(l2floodGroupKey);
1240 if (allActiveKeys.size() == 1 && allActiveKeys.get(0).size() == 1) {
1241 allActiveKeys.clear();
1242 }
1243 allActiveKeys.add(newBucketChain);
1244
1245 log.debug("Adding to L2FLOOD: device:{} gid:{} gkey:{} nextId:{}",
1246 deviceId, Integer.toHexString(l2floodGroupId),
1247 l2floodGroupKey, nextObj.id());
1248 // send the innermost group
1249 log.debug("Sending innermost group {} in group chain on device {} ",
1250 Integer.toHexString(groupInfo.innerMostGroupDesc.givenGroupId()),
1251 deviceId);
1252
1253 updatePendingGroups(groupInfo.nextGroupDesc.appCookie(), l2FloodGroupChainElement);
1254
1255 DeviceId innerMostGroupDevice = groupInfo.innerMostGroupDesc.deviceId();
1256 GroupKey innerMostGroupKey = groupInfo.innerMostGroupDesc.appCookie();
1257 Group existsL2IGroup = groupService.getGroup(innerMostGroupDevice, innerMostGroupKey);
1258
1259 if (existsL2IGroup != null) {
1260 // group already exist
1261 processPendingAddGroupsOrNextObjs(innerMostGroupKey, true);
1262 } else {
1263 groupService.addGroup(groupInfo.innerMostGroupDesc);
1264 }
1265
1266 });
1267 }
1268
1269 private VlanId extractVlanIdFromGroupId(int groupId) {
1270 // Extract the 9th to 20th bit from group id as vlan id.
1271 short vlanId = (short) ((groupId & 0x0fff0000) >> 16);
1272 return VlanId.vlanId(vlanId);
1273 }
1274
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001275 private List<GroupBucket> generateNextGroupBuckets(List<GroupInfo> groupInfos,
1276 GroupDescription.Type bucketType) {
Yi Tseng78f51f42017-02-02 13:54:58 -08001277 List<GroupBucket> newBuckets = Lists.newArrayList();
1278
1279 groupInfos.forEach(groupInfo -> {
1280 GroupDescription groupDesc = groupInfo.nextGroupDesc;
1281 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
1282 treatmentBuilder.group(new DefaultGroupId(groupDesc.givenGroupId()));
1283 GroupBucket newBucket = null;
1284 switch (bucketType) {
1285 case ALL:
1286 newBucket =
1287 DefaultGroupBucket.createAllGroupBucket(treatmentBuilder.build());
1288 break;
1289 case INDIRECT:
1290 newBucket =
1291 DefaultGroupBucket.createIndirectGroupBucket(treatmentBuilder.build());
1292 break;
1293 case SELECT:
1294 newBucket =
1295 DefaultGroupBucket.createSelectGroupBucket(treatmentBuilder.build());
1296 break;
1297 case FAILOVER:
1298 // TODO support failover bucket type
1299 default:
1300 log.warn("Unknown bucket type: {}", bucketType);
1301 break;
1302 }
1303
1304 if (newBucket != null) {
1305 newBuckets.add(newBucket);
1306 }
1307
1308 });
1309
1310 return ImmutableList.copyOf(newBuckets);
Saurav Das1a129a02016-11-18 15:21:57 -08001311 }
1312
1313 private void addBucketToL3MulticastGroup(NextObjective nextObj,
1314 List<Deque<GroupKey>> allActiveKeys,
1315 List<GroupInfo> groupInfos,
Yi Tseng78f51f42017-02-02 13:54:58 -08001316 VlanId assignedVlan) {
1317 // create the buckets to add to the outermost L3 Multicast group
1318 List<GroupBucket> newBuckets = Lists.newArrayList();
1319 groupInfos.forEach(groupInfo -> {
1320 // Points to L3 interface group if there is one.
1321 // Otherwise points to L2 interface group directly.
1322 GroupDescription nextGroupDesc = (groupInfo.nextGroupDesc != null) ?
1323 groupInfo.nextGroupDesc : groupInfo.innerMostGroupDesc;
1324 TrafficTreatment.Builder treatmentBuidler = DefaultTrafficTreatment.builder();
1325 treatmentBuidler.group(new DefaultGroupId(nextGroupDesc.givenGroupId()));
1326 GroupBucket newBucket = DefaultGroupBucket.createAllGroupBucket(treatmentBuidler.build());
1327 newBuckets.add(newBucket);
1328 });
Saurav Das1a129a02016-11-18 15:21:57 -08001329
1330 // get the group being edited
1331 Group l3mcastGroup = retrieveTopLevelGroup(allActiveKeys, nextObj.id());
1332 if (l3mcastGroup == null) {
1333 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.GROUPMISSING);
1334 return;
1335 }
1336 GroupKey l3mcastGroupKey = l3mcastGroup.appCookie();
1337 int l3mcastGroupId = l3mcastGroup.id().id();
1338
1339 //ensure assignedVlan applies to the chosen group
Yi Tseng78f51f42017-02-02 13:54:58 -08001340 VlanId expectedVlan = extractVlanIdFromGroupId(l3mcastGroupId);
Saurav Das1a129a02016-11-18 15:21:57 -08001341 if (!expectedVlan.equals(assignedVlan)) {
1342 log.warn("VLAN ID {} does not match L3 Mcast group {} to which bucket is "
1343 + "being added, for next:{} in dev:{}. Abort.", assignedVlan,
1344 Integer.toHexString(l3mcastGroupId), nextObj.id(), deviceId);
1345 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.BADPARAMS);
1346 }
1347 GroupDescription l3mcastGroupDescription =
1348 new DefaultGroupDescription(
1349 deviceId,
Yi Tseng78f51f42017-02-02 13:54:58 -08001350 ALL,
1351 new GroupBuckets(newBuckets),
Saurav Das1a129a02016-11-18 15:21:57 -08001352 l3mcastGroupKey,
1353 l3mcastGroupId,
1354 nextObj.appId());
1355 GroupChainElem l3mcastGce = new GroupChainElem(l3mcastGroupDescription,
Yi Tseng78f51f42017-02-02 13:54:58 -08001356 groupInfos.size(), true);
Saurav Das1a129a02016-11-18 15:21:57 -08001357
Yi Tseng78f51f42017-02-02 13:54:58 -08001358 groupInfos.forEach(groupInfo -> {
1359 // update original NextGroup with new bucket-chain
1360 Deque<GroupKey> newBucketChain = new ArrayDeque<>();
1361 newBucketChain.addFirst(groupInfo.innerMostGroupDesc.appCookie());
1362 // Add L3 interface group to the chain if there is one.
1363 if (!groupInfo.nextGroupDesc.equals(groupInfo.innerMostGroupDesc)) {
1364 newBucketChain.addFirst(groupInfo.nextGroupDesc.appCookie());
1365 }
1366 newBucketChain.addFirst(l3mcastGroupKey);
1367 // If active keys shows only the top-level group without a chain of groups,
1368 // then it represents an empty group. Update by replacing empty chain.
1369 if (allActiveKeys.size() == 1 && allActiveKeys.get(0).size() == 1) {
1370 allActiveKeys.clear();
1371 }
1372 allActiveKeys.add(newBucketChain);
1373
1374 updatePendingGroups(groupInfo.nextGroupDesc.appCookie(), l3mcastGce);
1375 // Point next group to inner-most group, if any
1376 if (!groupInfo.nextGroupDesc.equals(groupInfo.innerMostGroupDesc)) {
1377 GroupChainElem innerGce = new GroupChainElem(groupInfo.nextGroupDesc,
1378 1, false);
1379 updatePendingGroups(groupInfo.innerMostGroupDesc.appCookie(), innerGce);
1380 }
1381 log.debug("Adding to L3MCAST: device:{} gid:{} gkey:{} nextId:{}",
1382 deviceId, Integer.toHexString(l3mcastGroupId),
1383 l3mcastGroupKey, nextObj.id());
1384 // send the innermost group
1385 log.debug("Sending innermost group {} in group chain on device {} ",
1386 Integer.toHexString(groupInfo.innerMostGroupDesc.givenGroupId()),
1387 deviceId);
1388 groupService.addGroup(groupInfo.innerMostGroupDesc);
1389
1390 });
1391
Saurav Das1a129a02016-11-18 15:21:57 -08001392 updatePendingNextObjective(l3mcastGroupKey,
1393 new OfdpaNextGroup(allActiveKeys, nextObj));
1394
Yi Tseng78f51f42017-02-02 13:54:58 -08001395
1396
Charles Chan188ebf52015-12-23 00:15:11 -08001397 }
1398
1399 /**
1400 * Removes the bucket in the top level group of a possible group-chain. Does
Saurav Das1a129a02016-11-18 15:21:57 -08001401 * not remove the groups in the group-chain pointed to by this bucket, as they
Charles Chan188ebf52015-12-23 00:15:11 -08001402 * may be in use (referenced by other groups) elsewhere.
1403 *
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001404 * @param nextObjective the bucket information for a next group
Charles Chan188ebf52015-12-23 00:15:11 -08001405 * @param next the representation of the existing group-chain for this next objective
1406 */
1407 protected void removeBucketFromGroup(NextObjective nextObjective, NextGroup next) {
Saurav Das1a129a02016-11-18 15:21:57 -08001408 if (nextObjective.type() != NextObjective.Type.HASHED &&
1409 nextObjective.type() != NextObjective.Type.BROADCAST) {
Charles Chan188ebf52015-12-23 00:15:11 -08001410 log.warn("RemoveBuckets not applied to nextType:{} in dev:{} for next:{}",
1411 nextObjective.type(), deviceId, nextObjective.id());
Saurav Das1a129a02016-11-18 15:21:57 -08001412 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.UNSUPPORTED);
Charles Chan188ebf52015-12-23 00:15:11 -08001413 return;
1414 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001415 Set<PortNumber> portsToRemove = Sets.newHashSet();
Charles Chan188ebf52015-12-23 00:15:11 -08001416 Collection<TrafficTreatment> treatments = nextObjective.next();
Yi Tseng78f51f42017-02-02 13:54:58 -08001417 for (TrafficTreatment treatment : treatments) {
1418 // find the bucket to remove by noting the outport, and figuring out the
1419 // top-level group in the group-chain that indirectly references the port
1420 PortNumber portToRemove = readOutPortFromTreatment(treatment);
1421 if (portToRemove == null) {
1422 log.warn("treatment {} of next objective {} has no outport.. cannot remove bucket"
1423 + "from group in dev: {}", treatment, nextObjective.id(), deviceId);
1424 } else {
1425 portsToRemove.add(portToRemove);
1426 }
1427 }
1428
1429 if (portsToRemove.isEmpty()) {
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001430 log.warn("next objective {} has no outport.. cannot remove bucket"
Yi Tseng78f51f42017-02-02 13:54:58 -08001431 + "from group in dev: {}", nextObjective.id(), deviceId);
Saurav Das1a129a02016-11-18 15:21:57 -08001432 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.BADPARAMS);
Charles Chan188ebf52015-12-23 00:15:11 -08001433 }
1434
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001435 List<Deque<GroupKey>> allActiveKeys = Ofdpa2Pipeline.appKryo.deserialize(next.data());
Yi Tseng78f51f42017-02-02 13:54:58 -08001436 List<Deque<GroupKey>> chainsToRemove = Lists.newArrayList();
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001437 for (Deque<GroupKey> gkeys : allActiveKeys) {
1438 // last group in group chain should have a single bucket pointing to port
Yi Tseng78f51f42017-02-02 13:54:58 -08001439
Charles Chan188ebf52015-12-23 00:15:11 -08001440 GroupKey groupWithPort = gkeys.peekLast();
1441 Group group = groupService.getGroup(deviceId, groupWithPort);
1442 if (group == null) {
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001443 log.warn("Inconsistent group chain found when removing bucket"
1444 + "for next:{} in dev:{}", nextObjective.id(), deviceId);
Charles Chan188ebf52015-12-23 00:15:11 -08001445 continue;
1446 }
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001447 PortNumber pout = readOutPortFromTreatment(
1448 group.buckets().buckets().get(0).treatment());
Yi Tseng78f51f42017-02-02 13:54:58 -08001449 if (portsToRemove.contains(pout)) {
1450 chainsToRemove.add(gkeys);
Charles Chan188ebf52015-12-23 00:15:11 -08001451 }
Charles Chan188ebf52015-12-23 00:15:11 -08001452 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001453
1454 if (chainsToRemove.isEmpty()) {
Charles Chan188ebf52015-12-23 00:15:11 -08001455 log.warn("Could not find appropriate group-chain for removing bucket"
1456 + " for next id {} in dev:{}", nextObjective.id(), deviceId);
Saurav Das1a129a02016-11-18 15:21:57 -08001457 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.BADPARAMS);
1458 return;
Charles Chan188ebf52015-12-23 00:15:11 -08001459 }
Saurav Das1a129a02016-11-18 15:21:57 -08001460
Yi Tseng78f51f42017-02-02 13:54:58 -08001461
1462 List<GroupBucket> bucketsToRemove = Lists.newArrayList();
1463 //first group key is the one we want to modify
1464 GroupKey modGroupKey = chainsToRemove.get(0).peekFirst();
Saurav Das1a129a02016-11-18 15:21:57 -08001465 Group modGroup = groupService.getGroup(deviceId, modGroupKey);
Yi Tseng78f51f42017-02-02 13:54:58 -08001466
1467 for (Deque<GroupKey> foundChain : chainsToRemove) {
1468 //second group key is the one we wish to remove the reference to
1469 if (foundChain.size() < 2) {
1470 // additional check to make sure second group key exist in
1471 // the chain.
1472 log.warn("Can't find second group key from chain {}",
1473 foundChain);
1474 continue;
Saurav Das1a129a02016-11-18 15:21:57 -08001475 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001476 GroupKey pointedGroupKey = foundChain.stream().collect(Collectors.toList()).get(1);
1477
1478 Group pointedGroup = groupService.getGroup(deviceId, pointedGroupKey);
1479
1480 if (pointedGroup == null) {
1481 continue;
1482 }
1483
1484 GroupBucket bucket;
1485 if (nextObjective.type() == NextObjective.Type.HASHED) {
1486 bucket = DefaultGroupBucket.createSelectGroupBucket(
1487 DefaultTrafficTreatment.builder()
1488 .group(pointedGroup.id())
1489 .build());
1490 } else {
1491 bucket = DefaultGroupBucket.createAllGroupBucket(
1492 DefaultTrafficTreatment.builder()
1493 .group(pointedGroup.id())
1494 .build());
1495 }
1496
1497 bucketsToRemove.add(bucket);
Saurav Das1a129a02016-11-18 15:21:57 -08001498 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001499
1500 GroupBuckets removeBuckets = new GroupBuckets(bucketsToRemove);
1501 List<String> pointedGroupIds; // for debug log
1502 pointedGroupIds = bucketsToRemove.stream()
1503 .map(GroupBucket::treatment)
1504 .map(TrafficTreatment::allInstructions)
1505 .flatMap(List::stream)
1506 .filter(inst -> inst instanceof Instructions.GroupInstruction)
1507 .map(inst -> (Instructions.GroupInstruction) inst)
1508 .map(Instructions.GroupInstruction::groupId)
1509 .map(GroupId::id)
1510 .map(Integer::toHexString)
1511 .map(id -> HEX_PREFIX + id)
1512 .collect(Collectors.toList());
1513
1514
1515
1516 log.debug("Removing buckets from group id 0x{} pointing to group id(s) {} "
Saurav Das1a129a02016-11-18 15:21:57 -08001517 + "for next id {} in device {}", Integer.toHexString(modGroup.id().id()),
Yi Tseng78f51f42017-02-02 13:54:58 -08001518 pointedGroupIds, nextObjective.id(), deviceId);
1519 addPendingUpdateNextObjective(modGroupKey, nextObjective);
Saurav Das1a129a02016-11-18 15:21:57 -08001520 groupService.removeBucketsFromGroup(deviceId, modGroupKey,
1521 removeBuckets, modGroupKey,
1522 nextObjective.appId());
1523 // update store
1524 // If the bucket removed was the last bucket in the group, then
1525 // retain an entry for the top level group which still exists.
1526 if (allActiveKeys.size() == 1) {
1527 ArrayDeque<GroupKey> top = new ArrayDeque<>();
1528 top.add(modGroupKey);
1529 allActiveKeys.add(top);
1530 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001531
1532 allActiveKeys.removeAll(chainsToRemove);
Saurav Das1a129a02016-11-18 15:21:57 -08001533 flowObjectiveStore.putNextGroup(nextObjective.id(),
1534 new OfdpaNextGroup(allActiveKeys,
1535 nextObjective));
Charles Chan188ebf52015-12-23 00:15:11 -08001536 }
1537
1538 /**
1539 * Removes all groups in multiple possible group-chains that represent the next
1540 * objective.
1541 *
1542 * @param nextObjective the next objective to remove
1543 * @param next the NextGroup that represents the existing group-chain for
1544 * this next objective
1545 */
1546 protected void removeGroup(NextObjective nextObjective, NextGroup next) {
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001547 List<Deque<GroupKey>> allActiveKeys = Ofdpa2Pipeline.appKryo.deserialize(next.data());
Charles Chanfc5c7802016-05-17 13:13:55 -07001548
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001549 List<GroupKey> groupKeys = allActiveKeys.stream()
Charles Chanfc5c7802016-05-17 13:13:55 -07001550 .map(Deque::getFirst).collect(Collectors.toList());
1551 pendingRemoveNextObjectives.put(nextObjective, groupKeys);
1552
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001553 allActiveKeys.forEach(groupChain -> groupChain.forEach(groupKey ->
Charles Chan188ebf52015-12-23 00:15:11 -08001554 groupService.removeGroup(deviceId, groupKey, nextObjective.appId())));
1555 flowObjectiveStore.removeNextGroup(nextObjective.id());
1556 }
1557
Saurav Das8be4e3a2016-03-11 17:19:07 -08001558 //////////////////////////////////////
1559 // Helper Methods and Classes
1560 //////////////////////////////////////
1561
Pier Ventre140a8942016-11-02 07:26:38 -07001562 protected void updatePendingNextObjective(GroupKey key, OfdpaNextGroup value) {
Saurav Das8be4e3a2016-03-11 17:19:07 -08001563 List<OfdpaNextGroup> nextList = new CopyOnWriteArrayList<OfdpaNextGroup>();
1564 nextList.add(value);
Charles Chanfc5c7802016-05-17 13:13:55 -07001565 List<OfdpaNextGroup> ret = pendingAddNextObjectives.asMap()
Saurav Das8be4e3a2016-03-11 17:19:07 -08001566 .putIfAbsent(key, nextList);
1567 if (ret != null) {
1568 ret.add(value);
1569 }
1570 }
1571
Charles Chan425854b2016-04-11 15:32:12 -07001572 protected void updatePendingGroups(GroupKey gkey, GroupChainElem gce) {
Saurav Das8be4e3a2016-03-11 17:19:07 -08001573 Set<GroupChainElem> gceSet = Collections.newSetFromMap(
1574 new ConcurrentHashMap<GroupChainElem, Boolean>());
1575 gceSet.add(gce);
1576 Set<GroupChainElem> retval = pendingGroups.putIfAbsent(gkey, gceSet);
1577 if (retval != null) {
1578 retval.add(gce);
1579 }
1580 }
1581
Yi Tseng78f51f42017-02-02 13:54:58 -08001582 private void addPendingUpdateNextObjective(GroupKey groupKey, NextObjective nextObjective) {
1583 pendingUpdateNextObjectives.compute(groupKey, (gKey, nextObjs) -> {
1584 if (nextObjs != null) {
1585 nextObjs.add(nextObjective);
1586 } else {
1587 nextObjs = Sets.newHashSet(nextObjective);
1588 }
1589 return nextObjs;
1590 });
1591 }
1592
Charles Chan188ebf52015-12-23 00:15:11 -08001593 /**
1594 * Processes next element of a group chain. Assumption is that if this
1595 * group points to another group, the latter has already been created
1596 * and this driver has received notification for it. A second assumption is
1597 * that if there is another group waiting for this group then the appropriate
1598 * stores already have the information to act upon the notification for the
1599 * creation of this group.
1600 * <p>
1601 * The processing of the GroupChainElement depends on the number of groups
1602 * this element is waiting on. For all group types other than SIMPLE, a
1603 * GroupChainElement could be waiting on multiple groups.
1604 *
1605 * @param gce the group chain element to be processed next
1606 */
1607 private void processGroupChain(GroupChainElem gce) {
1608 int waitOnGroups = gce.decrementAndGetGroupsWaitedOn();
1609 if (waitOnGroups != 0) {
1610 log.debug("GCE: {} not ready to be processed", gce);
1611 return;
1612 }
1613 log.debug("GCE: {} ready to be processed", gce);
1614 if (gce.addBucketToGroup) {
1615 groupService.addBucketsToGroup(gce.groupDescription.deviceId(),
1616 gce.groupDescription.appCookie(),
1617 gce.groupDescription.buckets(),
1618 gce.groupDescription.appCookie(),
1619 gce.groupDescription.appId());
1620 } else {
1621 groupService.addGroup(gce.groupDescription);
1622 }
1623 }
1624
1625 private class GroupChecker implements Runnable {
1626 @Override
1627 public void run() {
1628 Set<GroupKey> keys = pendingGroups.keySet().stream()
1629 .filter(key -> groupService.getGroup(deviceId, key) != null)
1630 .collect(Collectors.toSet());
Charles Chanfc5c7802016-05-17 13:13:55 -07001631 Set<GroupKey> otherkeys = pendingAddNextObjectives.asMap().keySet().stream()
Charles Chan188ebf52015-12-23 00:15:11 -08001632 .filter(otherkey -> groupService.getGroup(deviceId, otherkey) != null)
1633 .collect(Collectors.toSet());
1634 keys.addAll(otherkeys);
1635
Sho SHIMIZUa09e1bb2016-08-01 14:25:25 -07001636 keys.forEach(key ->
Charles Chanfc5c7802016-05-17 13:13:55 -07001637 processPendingAddGroupsOrNextObjs(key, false));
Charles Chan188ebf52015-12-23 00:15:11 -08001638 }
1639 }
1640
Saurav Das8be4e3a2016-03-11 17:19:07 -08001641 private class InnerGroupListener implements GroupListener {
1642 @Override
1643 public void event(GroupEvent event) {
1644 log.trace("received group event of type {}", event.type());
Charles Chanfc5c7802016-05-17 13:13:55 -07001645 switch (event.type()) {
1646 case GROUP_ADDED:
1647 processPendingAddGroupsOrNextObjs(event.subject().appCookie(), true);
1648 break;
1649 case GROUP_REMOVED:
1650 processPendingRemoveNextObjs(event.subject().appCookie());
1651 break;
Yi Tseng78f51f42017-02-02 13:54:58 -08001652 case GROUP_UPDATED:
1653 processPendingUpdateNextObjs(event.subject().appCookie());
1654 break;
Charles Chanfc5c7802016-05-17 13:13:55 -07001655 default:
1656 break;
Saurav Das8be4e3a2016-03-11 17:19:07 -08001657 }
1658 }
1659 }
1660
Yi Tseng78f51f42017-02-02 13:54:58 -08001661 private void processPendingUpdateNextObjs(GroupKey groupKey) {
1662
1663 pendingUpdateNextObjectives.compute(groupKey, (gKey, nextObjs) -> {
1664 if (nextObjs != null) {
1665
1666 nextObjs.forEach(nextObj -> {
1667 log.debug("Group {} updated, update pending next objective {}.",
1668 groupKey, nextObj);
1669
1670 Ofdpa2Pipeline.pass(nextObj);
1671 });
1672 }
1673
1674 return Sets.newHashSet();
1675 });
1676 }
1677
Charles Chanfc5c7802016-05-17 13:13:55 -07001678 private void processPendingAddGroupsOrNextObjs(GroupKey key, boolean added) {
Charles Chan188ebf52015-12-23 00:15:11 -08001679 //first check for group chain
1680 Set<GroupChainElem> gceSet = pendingGroups.remove(key);
1681 if (gceSet != null) {
1682 for (GroupChainElem gce : gceSet) {
Charles Chan216e3c82016-04-23 14:48:16 -07001683 log.debug("Group service {} group key {} in device {}. "
Saurav Das0fd79d92016-03-07 10:58:36 -08001684 + "Processing next group in group chain with group id 0x{}",
Charles Chan188ebf52015-12-23 00:15:11 -08001685 (added) ? "ADDED" : "processed",
1686 key, deviceId,
1687 Integer.toHexString(gce.groupDescription.givenGroupId()));
1688 processGroupChain(gce);
1689 }
1690 } else {
1691 // otherwise chain complete - check for waiting nextObjectives
Charles Chanfc5c7802016-05-17 13:13:55 -07001692 List<OfdpaNextGroup> nextGrpList = pendingAddNextObjectives.getIfPresent(key);
Charles Chan188ebf52015-12-23 00:15:11 -08001693 if (nextGrpList != null) {
Charles Chanfc5c7802016-05-17 13:13:55 -07001694 pendingAddNextObjectives.invalidate(key);
Charles Chan188ebf52015-12-23 00:15:11 -08001695 nextGrpList.forEach(nextGrp -> {
Charles Chan216e3c82016-04-23 14:48:16 -07001696 log.debug("Group service {} group key {} in device:{}. "
Saurav Das0fd79d92016-03-07 10:58:36 -08001697 + "Done implementing next objective: {} <<-->> gid:0x{}",
Charles Chan188ebf52015-12-23 00:15:11 -08001698 (added) ? "ADDED" : "processed",
1699 key, deviceId, nextGrp.nextObjective().id(),
1700 Integer.toHexString(groupService.getGroup(deviceId, key)
1701 .givenGroupId()));
Charles Chan361154b2016-03-24 10:23:39 -07001702 Ofdpa2Pipeline.pass(nextGrp.nextObjective());
Charles Chan188ebf52015-12-23 00:15:11 -08001703 flowObjectiveStore.putNextGroup(nextGrp.nextObjective().id(), nextGrp);
1704 // check if addBuckets waiting for this completion
1705 NextObjective pendBkt = pendingBuckets
1706 .remove(nextGrp.nextObjective().id());
1707 if (pendBkt != null) {
1708 addBucketToGroup(pendBkt, nextGrp);
1709 }
1710 });
1711 }
1712 }
1713 }
1714
Charles Chanfc5c7802016-05-17 13:13:55 -07001715 private void processPendingRemoveNextObjs(GroupKey key) {
1716 pendingRemoveNextObjectives.asMap().forEach((nextObjective, groupKeys) -> {
1717 if (groupKeys.isEmpty()) {
1718 pendingRemoveNextObjectives.invalidate(nextObjective);
1719 Ofdpa2Pipeline.pass(nextObjective);
1720 } else {
1721 groupKeys.remove(key);
1722 }
1723 });
1724 }
1725
Charles Chan425854b2016-04-11 15:32:12 -07001726 protected int getNextAvailableIndex() {
Saurav Das8be4e3a2016-03-11 17:19:07 -08001727 return (int) nextIndex.incrementAndGet();
1728 }
1729
Charles Chane849c192016-01-11 18:28:54 -08001730 /**
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001731 * Returns the outport in a traffic treatment.
1732 *
1733 * @param tt the treatment
1734 * @return the PortNumber for the outport or null
1735 */
1736 protected static PortNumber readOutPortFromTreatment(TrafficTreatment tt) {
1737 for (Instruction ins : tt.allInstructions()) {
1738 if (ins.type() == Instruction.Type.OUTPUT) {
1739 return ((Instructions.OutputInstruction) ins).port();
1740 }
1741 }
1742 return null;
1743 }
1744
1745 /**
Charles Chane849c192016-01-11 18:28:54 -08001746 * Returns a hash as the L2 Interface Group Key.
1747 *
1748 * Keep the lower 6-bit for port since port number usually smaller than 64.
1749 * Hash other information into remaining 28 bits.
1750 *
1751 * @param deviceId Device ID
1752 * @param vlanId VLAN ID
1753 * @param portNumber Port number
1754 * @return L2 interface group key
1755 */
Pier Ventre140a8942016-11-02 07:26:38 -07001756 protected int l2InterfaceGroupKey(DeviceId deviceId, VlanId vlanId, long portNumber) {
Charles Chane849c192016-01-11 18:28:54 -08001757 int portLowerBits = (int) portNumber & PORT_LOWER_BITS_MASK;
1758 long portHigherBits = portNumber & PORT_HIGHER_BITS_MASK;
Charles Chand0fd5dc2016-02-16 23:14:49 -08001759 int hash = Objects.hash(deviceId, vlanId, portHigherBits);
Charles Chane849c192016-01-11 18:28:54 -08001760 return L2_INTERFACE_TYPE | (TYPE_MASK & hash << 6) | portLowerBits;
1761 }
1762
Saurav Das1a129a02016-11-18 15:21:57 -08001763 private Group retrieveTopLevelGroup(List<Deque<GroupKey>> allActiveKeys,
1764 int nextid) {
Yi Tseng78f51f42017-02-02 13:54:58 -08001765 GroupKey topLevelGroupKey;
Saurav Das1a129a02016-11-18 15:21:57 -08001766 if (!allActiveKeys.isEmpty()) {
1767 topLevelGroupKey = allActiveKeys.get(0).peekFirst();
1768 } else {
1769 log.warn("Could not determine top level group while processing"
1770 + "next:{} in dev:{}", nextid, deviceId);
1771 return null;
1772 }
1773 Group topGroup = groupService.getGroup(deviceId, topLevelGroupKey);
1774 if (topGroup == null) {
1775 log.warn("Could not find top level group while processing "
1776 + "next:{} in dev:{}", nextid, deviceId);
1777 }
1778 return topGroup;
1779 }
1780
Charles Chan188ebf52015-12-23 00:15:11 -08001781 /**
1782 * Utility class for moving group information around.
Saurav Das1a129a02016-11-18 15:21:57 -08001783 *
1784 * Example: Suppose we are trying to create a group-chain A-B-C-D, where
1785 * A is the top level group, and D is the inner-most group, typically L2 Interface.
1786 * The innerMostGroupDesc is always D. At various stages of the creation
1787 * process the nextGroupDesc may be C or B. The nextGroupDesc exists to
1788 * inform the referencing group about which group it needs to point to,
1789 * and wait for. In some cases the group chain may simply be A-B. In this case,
1790 * both innerMostGroupDesc and nextGroupDesc will be B.
Charles Chan188ebf52015-12-23 00:15:11 -08001791 */
Charles Chan425854b2016-04-11 15:32:12 -07001792 protected class GroupInfo {
Charles Chan5b9df8d2016-03-28 22:21:40 -07001793 /**
1794 * Description of the inner-most group of the group chain.
1795 * It is always an L2 interface group.
1796 */
1797 private GroupDescription innerMostGroupDesc;
Charles Chan188ebf52015-12-23 00:15:11 -08001798
Charles Chan5b9df8d2016-03-28 22:21:40 -07001799 /**
1800 * Description of the next group in the group chain.
1801 * It can be L2 interface, L3 interface, L3 unicast, L3 VPN group.
Saurav Das1a129a02016-11-18 15:21:57 -08001802 * It is possible that nextGroupDesc is the same as the innerMostGroup.
Charles Chan5b9df8d2016-03-28 22:21:40 -07001803 */
1804 private GroupDescription nextGroupDesc;
1805
1806 GroupInfo(GroupDescription innerMostGroupDesc, GroupDescription nextGroupDesc) {
1807 this.innerMostGroupDesc = innerMostGroupDesc;
1808 this.nextGroupDesc = nextGroupDesc;
Charles Chan188ebf52015-12-23 00:15:11 -08001809 }
Pier Ventre140a8942016-11-02 07:26:38 -07001810
1811 /**
1812 * Getter for innerMostGroupDesc.
1813 *
1814 * @return the inner most group description
1815 */
1816 public GroupDescription getInnerMostGroupDesc() {
1817 return innerMostGroupDesc;
1818 }
1819
1820 /**
1821 * Getter for the next group description.
1822 *
1823 * @return the next group description
1824 */
1825 public GroupDescription getNextGroupDesc() {
1826 return nextGroupDesc;
1827 }
Charles Chan188ebf52015-12-23 00:15:11 -08001828 }
1829
1830 /**
1831 * Represents an entire group-chain that implements a Next-Objective from
1832 * the application. The objective is represented as a list of deques, where
1833 * each deque is a separate chain of groups.
1834 * <p>
1835 * For example, an ECMP group with 3 buckets, where each bucket points to
1836 * a group chain of L3 Unicast and L2 interface groups will look like this:
1837 * <ul>
1838 * <li>List[0] is a Deque of GroupKeyECMP(first)-GroupKeyL3(middle)-GroupKeyL2(last)
1839 * <li>List[1] is a Deque of GroupKeyECMP(first)-GroupKeyL3(middle)-GroupKeyL2(last)
1840 * <li>List[2] is a Deque of GroupKeyECMP(first)-GroupKeyL3(middle)-GroupKeyL2(last)
1841 * </ul>
1842 * where the first element of each deque is the same, representing the
1843 * top level ECMP group, while every other element represents a unique groupKey.
1844 * <p>
1845 * Also includes information about the next objective that
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001846 * resulted in these group-chains.
Charles Chan188ebf52015-12-23 00:15:11 -08001847 *
1848 */
1849 protected class OfdpaNextGroup implements NextGroup {
1850 private final NextObjective nextObj;
1851 private final List<Deque<GroupKey>> gkeys;
1852
1853 public OfdpaNextGroup(List<Deque<GroupKey>> gkeys, NextObjective nextObj) {
Charles Chan188ebf52015-12-23 00:15:11 -08001854 this.nextObj = nextObj;
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001855 this.gkeys = gkeys;
Charles Chan188ebf52015-12-23 00:15:11 -08001856 }
1857
1858 public NextObjective nextObjective() {
1859 return nextObj;
1860 }
1861
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001862 public List<Deque<GroupKey>> groupKeys() {
1863 return gkeys;
1864 }
1865
Charles Chan188ebf52015-12-23 00:15:11 -08001866 @Override
1867 public byte[] data() {
Charles Chan361154b2016-03-24 10:23:39 -07001868 return Ofdpa2Pipeline.appKryo.serialize(gkeys);
Charles Chan188ebf52015-12-23 00:15:11 -08001869 }
1870 }
1871
1872 /**
1873 * Represents a group element that is part of a chain of groups.
1874 * Stores enough information to create a Group Description to add the group
1875 * to the switch by requesting the Group Service. Objects instantiating this
1876 * class are meant to be temporary and live as long as it is needed to wait for
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001877 * referenced groups in the group chain to be created.
Charles Chan188ebf52015-12-23 00:15:11 -08001878 */
Charles Chan425854b2016-04-11 15:32:12 -07001879 protected class GroupChainElem {
Charles Chan188ebf52015-12-23 00:15:11 -08001880 private GroupDescription groupDescription;
1881 private AtomicInteger waitOnGroups;
1882 private boolean addBucketToGroup;
1883
1884 GroupChainElem(GroupDescription groupDescription, int waitOnGroups,
1885 boolean addBucketToGroup) {
1886 this.groupDescription = groupDescription;
1887 this.waitOnGroups = new AtomicInteger(waitOnGroups);
1888 this.addBucketToGroup = addBucketToGroup;
1889 }
1890
1891 /**
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001892 * This method atomically decrements the counter for the number of
Charles Chan188ebf52015-12-23 00:15:11 -08001893 * groups this GroupChainElement is waiting on, for notifications from
1894 * the Group Service. When this method returns a value of 0, this
1895 * GroupChainElement is ready to be processed.
1896 *
1897 * @return integer indication of the number of notifications being waited on
1898 */
1899 int decrementAndGetGroupsWaitedOn() {
1900 return waitOnGroups.decrementAndGet();
1901 }
1902
1903 @Override
1904 public String toString() {
1905 return (Integer.toHexString(groupDescription.givenGroupId()) +
1906 " groupKey: " + groupDescription.appCookie() +
1907 " waiting-on-groups: " + waitOnGroups.get() +
1908 " addBucketToGroup: " + addBucketToGroup +
1909 " device: " + deviceId);
1910 }
1911 }
Pier Ventre140a8942016-11-02 07:26:38 -07001912
1913 /**
1914 * Helper enum to handle the different MPLS group
1915 * types.
1916 */
1917 protected enum OfdpaMplsGroupSubType {
1918
1919 MPLS_INTF((short) 0),
1920
1921 L2_VPN((short) 1),
1922
1923 L3_VPN((short) 2),
1924
1925 MPLS_TUNNEL_LABEL_1((short) 3),
1926
1927 MPLS_TUNNEL_LABEL_2((short) 4),
1928
1929 MPLS_SWAP_LABEL((short) 5),
1930
1931 MPLS_ECMP((short) 8);
1932
1933 private short value;
1934
1935 public static final int OFDPA_GROUP_TYPE_SHIFT = 28;
1936 public static final int OFDPA_MPLS_SUBTYPE_SHIFT = 24;
1937
1938 OfdpaMplsGroupSubType(short value) {
1939 this.value = value;
1940 }
1941
1942 /**
1943 * Gets the value as an short.
1944 *
1945 * @return the value as an short
1946 */
1947 public short getValue() {
1948 return this.value;
1949 }
1950
1951 }
1952
1953 /**
1954 * Creates MPLS Label group id given a sub type and
1955 * the index.
1956 *
1957 * @param subType the MPLS Label group sub type
1958 * @param index the index of the group
1959 * @return the OFDPA group id
1960 */
1961 public Integer makeMplsLabelGroupId(OfdpaMplsGroupSubType subType, int index) {
1962 index = index & 0x00FFFFFF;
1963 return index | (9 << OFDPA_GROUP_TYPE_SHIFT) | (subType.value << OFDPA_MPLS_SUBTYPE_SHIFT);
1964 }
1965
1966 /**
1967 * Creates MPLS Forwarding group id given a sub type and
1968 * the index.
1969 *
1970 * @param subType the MPLS forwarding group sub type
1971 * @param index the index of the group
1972 * @return the OFDPA group id
1973 */
1974 public Integer makeMplsForwardingGroupId(OfdpaMplsGroupSubType subType, int index) {
1975 index = index & 0x00FFFFFF;
1976 return index | (10 << OFDPA_GROUP_TYPE_SHIFT) | (subType.value << OFDPA_MPLS_SUBTYPE_SHIFT);
1977 }
Charles Chan188ebf52015-12-23 00:15:11 -08001978}