blob: fe605e96989c164d467f0b0fd3890cae37e592d2 [file] [log] [blame]
Brian O'Connor7cbbbb72016-04-09 02:13:23 -07001/*
2 * Copyright 2016-present Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Charles Chan188ebf52015-12-23 00:15:11 -080016package org.onosproject.driver.pipeline;
17
18import com.google.common.cache.Cache;
19import com.google.common.cache.CacheBuilder;
20import com.google.common.cache.RemovalCause;
21import com.google.common.cache.RemovalNotification;
Charles Chan5b9df8d2016-03-28 22:21:40 -070022import com.google.common.collect.ImmutableList;
23import com.google.common.collect.Lists;
Yi Tseng78f51f42017-02-02 13:54:58 -080024import com.google.common.collect.Sets;
Charles Chan188ebf52015-12-23 00:15:11 -080025import org.onlab.osgi.ServiceDirectory;
Charles Chan5b9df8d2016-03-28 22:21:40 -070026import org.onlab.packet.IpPrefix;
Charles Chan5270ed02016-01-30 23:22:37 -080027import org.onlab.packet.MacAddress;
Charles Chan188ebf52015-12-23 00:15:11 -080028import org.onlab.packet.MplsLabel;
29import org.onlab.packet.VlanId;
30import org.onosproject.core.ApplicationId;
Yi Tseng78f51f42017-02-02 13:54:58 -080031import org.onosproject.core.GroupId;
Charles Chan32562522016-04-07 14:37:14 -070032import org.onosproject.driver.extensions.OfdpaSetVlanVid;
Charles Chan188ebf52015-12-23 00:15:11 -080033import org.onosproject.net.DeviceId;
34import org.onosproject.net.PortNumber;
35import org.onosproject.net.behaviour.NextGroup;
36import org.onosproject.net.behaviour.PipelinerContext;
37import org.onosproject.net.flow.DefaultTrafficTreatment;
38import org.onosproject.net.flow.TrafficSelector;
39import org.onosproject.net.flow.TrafficTreatment;
40import org.onosproject.net.flow.criteria.Criterion;
Pier Ventre42287df2016-11-09 14:17:26 -080041import org.onosproject.net.flow.criteria.TunnelIdCriterion;
Charles Chan188ebf52015-12-23 00:15:11 -080042import org.onosproject.net.flow.criteria.VlanIdCriterion;
43import org.onosproject.net.flow.instructions.Instruction;
44import org.onosproject.net.flow.instructions.Instructions;
45import org.onosproject.net.flow.instructions.L2ModificationInstruction;
46import org.onosproject.net.flowobjective.FlowObjectiveStore;
47import org.onosproject.net.flowobjective.NextObjective;
48import org.onosproject.net.flowobjective.ObjectiveError;
49import org.onosproject.net.group.DefaultGroupBucket;
50import org.onosproject.net.group.DefaultGroupDescription;
51import org.onosproject.net.group.DefaultGroupKey;
52import org.onosproject.net.group.Group;
53import org.onosproject.net.group.GroupBucket;
54import org.onosproject.net.group.GroupBuckets;
55import org.onosproject.net.group.GroupDescription;
56import org.onosproject.net.group.GroupEvent;
57import org.onosproject.net.group.GroupKey;
58import org.onosproject.net.group.GroupListener;
59import org.onosproject.net.group.GroupService;
Saurav Das8be4e3a2016-03-11 17:19:07 -080060import org.onosproject.store.service.AtomicCounter;
61import org.onosproject.store.service.StorageService;
Charles Chan188ebf52015-12-23 00:15:11 -080062import org.slf4j.Logger;
63
64import java.util.ArrayDeque;
65import java.util.ArrayList;
66import java.util.Collection;
67import java.util.Collections;
68import java.util.Deque;
69import java.util.List;
Charles Chand0fd5dc2016-02-16 23:14:49 -080070import java.util.Objects;
Charles Chan188ebf52015-12-23 00:15:11 -080071import java.util.Set;
72import java.util.concurrent.ConcurrentHashMap;
73import java.util.concurrent.CopyOnWriteArrayList;
74import java.util.concurrent.Executors;
75import java.util.concurrent.ScheduledExecutorService;
76import java.util.concurrent.TimeUnit;
77import java.util.concurrent.atomic.AtomicInteger;
78import java.util.stream.Collectors;
79
80import static org.onlab.util.Tools.groupedThreads;
Pier Ventre140a8942016-11-02 07:26:38 -070081import static org.onosproject.driver.pipeline.Ofdpa2GroupHandler.OfdpaMplsGroupSubType.OFDPA_GROUP_TYPE_SHIFT;
82import static org.onosproject.driver.pipeline.Ofdpa2GroupHandler.OfdpaMplsGroupSubType.OFDPA_MPLS_SUBTYPE_SHIFT;
83import static org.onosproject.driver.pipeline.Ofdpa2Pipeline.isNotMplsBos;
Pier Ventre42287df2016-11-09 14:17:26 -080084import static org.onosproject.net.flow.criteria.Criterion.Type.TUNNEL_ID;
Pier Ventre140a8942016-11-02 07:26:38 -070085import static org.onosproject.net.flow.criteria.Criterion.Type.VLAN_VID;
86import static org.onosproject.net.flowobjective.NextObjective.Type.HASHED;
Yi Tseng78f51f42017-02-02 13:54:58 -080087import static org.onosproject.net.group.GroupDescription.Type.ALL;
88import static org.onosproject.net.group.GroupDescription.Type.SELECT;
Charles Chan188ebf52015-12-23 00:15:11 -080089import static org.slf4j.LoggerFactory.getLogger;
90
91/**
Charles Chan40132b32017-01-22 00:19:37 -080092 * Group handler that emulates Broadcom OF-DPA TTP on CpqD.
Charles Chan188ebf52015-12-23 00:15:11 -080093 */
Charles Chan361154b2016-03-24 10:23:39 -070094public class Ofdpa2GroupHandler {
Charles Chan188ebf52015-12-23 00:15:11 -080095 /*
96 * OFDPA requires group-id's to have a certain form.
97 * L2 Interface Groups have <4bits-0><12bits-vlanid><16bits-portid>
98 * L3 Unicast Groups have <4bits-2><28bits-index>
99 * MPLS Interface Groups have <4bits-9><4bits:0><24bits-index>
100 * L3 ECMP Groups have <4bits-7><28bits-index>
101 * L2 Flood Groups have <4bits-4><12bits-vlanid><16bits-index>
102 * L3 VPN Groups have <4bits-9><4bits-2><24bits-index>
103 */
Charles Chan425854b2016-04-11 15:32:12 -0700104 protected static final int L2_INTERFACE_TYPE = 0x00000000;
105 protected static final int L3_INTERFACE_TYPE = 0x50000000;
106 protected static final int L3_UNICAST_TYPE = 0x20000000;
107 protected static final int L3_MULTICAST_TYPE = 0x60000000;
108 protected static final int MPLS_INTERFACE_TYPE = 0x90000000;
109 protected static final int MPLS_L3VPN_SUBTYPE = 0x92000000;
110 protected static final int L3_ECMP_TYPE = 0x70000000;
111 protected static final int L2_FLOOD_TYPE = 0x40000000;
Charles Chane849c192016-01-11 18:28:54 -0800112
Charles Chan425854b2016-04-11 15:32:12 -0700113 protected static final int TYPE_MASK = 0x0fffffff;
114 protected static final int SUBTYPE_MASK = 0x00ffffff;
115 protected static final int TYPE_VLAN_MASK = 0x0000ffff;
Charles Chane849c192016-01-11 18:28:54 -0800116
Charles Chan372b63e2017-02-07 12:10:53 -0800117 protected static final int THREE_BIT_MASK = 0x0fff;
118 protected static final int FOUR_BIT_MASK = 0xffff;
119 protected static final int PORT_LEN = 16;
120
Charles Chan425854b2016-04-11 15:32:12 -0700121 protected static final int PORT_LOWER_BITS_MASK = 0x3f;
122 protected static final long PORT_HIGHER_BITS_MASK = ~PORT_LOWER_BITS_MASK;
Charles Chan188ebf52015-12-23 00:15:11 -0800123
Yi Tseng78f51f42017-02-02 13:54:58 -0800124 protected static final String HEX_PREFIX = "0x";
125
Charles Chan188ebf52015-12-23 00:15:11 -0800126 private final Logger log = getLogger(getClass());
127 private ServiceDirectory serviceDirectory;
128 protected GroupService groupService;
Saurav Das8be4e3a2016-03-11 17:19:07 -0800129 protected StorageService storageService;
Charles Chan188ebf52015-12-23 00:15:11 -0800130
Charles Chan425854b2016-04-11 15:32:12 -0700131 protected DeviceId deviceId;
Charles Chan188ebf52015-12-23 00:15:11 -0800132 private FlowObjectiveStore flowObjectiveStore;
Charles Chanfc5c7802016-05-17 13:13:55 -0700133 private Cache<GroupKey, List<OfdpaNextGroup>> pendingAddNextObjectives;
134 private Cache<NextObjective, List<GroupKey>> pendingRemoveNextObjectives;
Charles Chan188ebf52015-12-23 00:15:11 -0800135 private ConcurrentHashMap<GroupKey, Set<GroupChainElem>> pendingGroups;
Yi Tseng78f51f42017-02-02 13:54:58 -0800136 private ConcurrentHashMap<GroupKey, Set<NextObjective>> pendingUpdateNextObjectives;
Charles Chan188ebf52015-12-23 00:15:11 -0800137 private ScheduledExecutorService groupChecker =
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700138 Executors.newScheduledThreadPool(2, groupedThreads("onos/pipeliner", "ofdpa2-%d", log));
Charles Chan188ebf52015-12-23 00:15:11 -0800139
140 // index number for group creation
Saurav Das8be4e3a2016-03-11 17:19:07 -0800141 private AtomicCounter nextIndex;
Charles Chan188ebf52015-12-23 00:15:11 -0800142
Charles Chan188ebf52015-12-23 00:15:11 -0800143 // local store for pending bucketAdds - by design there can only be one
144 // pending bucket for a group
Saurav Das1ce0a7b2016-10-21 14:06:29 -0700145 protected ConcurrentHashMap<Integer, NextObjective> pendingBuckets =
146 new ConcurrentHashMap<>();
Charles Chan188ebf52015-12-23 00:15:11 -0800147
Charles Chan40132b32017-01-22 00:19:37 -0800148 /**
149 * Determines whether this pipeline support copy ttl instructions or not.
150 *
151 * @return true if copy ttl instructions are supported
152 */
153 protected boolean supportCopyTtl() {
154 return true;
155 }
156
157 /**
158 * Determines whether this pipeline support set mpls bos instruction or not.
159 *
160 * @return true if set mpls bos instruction is supported
161 */
162 protected boolean supportSetMplsBos() {
163 return true;
164 }
165
Charles Chan0f43e472017-02-14 14:00:16 -0800166 /**
167 * Determines whether this pipeline requires popping VLAN before pushing MPLS.
168 * <p>
169 * If required, pop vlan before push mpls and add an arbitrary vlan back afterward.
170 * MPLS interface group will substitute the arbitrary VLAN with expected VLAN later on.
171 *
172 * @return true if this pipeline requires popping VLAN before pushing MPLS
173 */
174 protected boolean requireVlanPopBeforeMplsPush() {
175 return false;
176 }
177
Charles Chan188ebf52015-12-23 00:15:11 -0800178 protected void init(DeviceId deviceId, PipelinerContext context) {
179 this.deviceId = deviceId;
180 this.flowObjectiveStore = context.store();
181 this.serviceDirectory = context.directory();
182 this.groupService = serviceDirectory.get(GroupService.class);
Saurav Das8be4e3a2016-03-11 17:19:07 -0800183 this.storageService = serviceDirectory.get(StorageService.class);
Madan Jampanid5714e02016-04-19 14:15:20 -0700184 this.nextIndex = storageService.getAtomicCounter("group-id-index-counter");
Charles Chan188ebf52015-12-23 00:15:11 -0800185
Charles Chanfc5c7802016-05-17 13:13:55 -0700186 pendingAddNextObjectives = CacheBuilder.newBuilder()
Charles Chan188ebf52015-12-23 00:15:11 -0800187 .expireAfterWrite(20, TimeUnit.SECONDS)
188 .removalListener((
189 RemovalNotification<GroupKey, List<OfdpaNextGroup>> notification) -> {
190 if (notification.getCause() == RemovalCause.EXPIRED) {
191 notification.getValue().forEach(ofdpaNextGrp ->
Charles Chan361154b2016-03-24 10:23:39 -0700192 Ofdpa2Pipeline.fail(ofdpaNextGrp.nextObj,
Charles Chan188ebf52015-12-23 00:15:11 -0800193 ObjectiveError.GROUPINSTALLATIONFAILED));
Charles Chanfc5c7802016-05-17 13:13:55 -0700194 }
195 }).build();
Charles Chan188ebf52015-12-23 00:15:11 -0800196
Charles Chanfc5c7802016-05-17 13:13:55 -0700197 pendingRemoveNextObjectives = CacheBuilder.newBuilder()
198 .expireAfterWrite(20, TimeUnit.SECONDS)
199 .removalListener((
200 RemovalNotification<NextObjective, List<GroupKey>> notification) -> {
201 if (notification.getCause() == RemovalCause.EXPIRED) {
202 Ofdpa2Pipeline.fail(notification.getKey(),
203 ObjectiveError.GROUPREMOVALFAILED);
Charles Chan188ebf52015-12-23 00:15:11 -0800204 }
205 }).build();
206 pendingGroups = new ConcurrentHashMap<>();
Yi Tseng78f51f42017-02-02 13:54:58 -0800207 pendingUpdateNextObjectives = new ConcurrentHashMap<>();
Charles Chan188ebf52015-12-23 00:15:11 -0800208 groupChecker.scheduleAtFixedRate(new GroupChecker(), 0, 500, TimeUnit.MILLISECONDS);
209
210 groupService.addListener(new InnerGroupListener());
211 }
212
Pier Ventre140a8942016-11-02 07:26:38 -0700213 /**
214 * The purpose of this function is to verify if the hashed next
215 * objective is supported by the current pipeline.
216 *
217 * @param nextObjective the hashed objective to verify
218 * @return true if the hashed objective is supported. Otherwise false.
219 */
220 public boolean verifyHashedNextObjective(NextObjective nextObjective) {
221 // if it is not hashed, there is something wrong;
222 if (nextObjective.type() != HASHED) {
223 return false;
224 }
225 // The case non supported is the MPLS-ECMP. For now, we try
226 // to create a MPLS-ECMP for the transport of a VPWS. The
227 // necessary info are contained in the meta selector. In particular
228 // we are looking for the case of BoS==False;
229 TrafficSelector metaSelector = nextObjective.meta();
230 if (metaSelector != null && isNotMplsBos(metaSelector)) {
231 return false;
232 }
233
234 return true;
235 }
236
Saurav Das8be4e3a2016-03-11 17:19:07 -0800237 //////////////////////////////////////
238 // Group Creation
239 //////////////////////////////////////
240
Charles Chan188ebf52015-12-23 00:15:11 -0800241 protected void addGroup(NextObjective nextObjective) {
242 switch (nextObjective.type()) {
243 case SIMPLE:
244 Collection<TrafficTreatment> treatments = nextObjective.next();
245 if (treatments.size() != 1) {
246 log.error("Next Objectives of type Simple should only have a "
247 + "single Traffic Treatment. Next Objective Id:{}",
248 nextObjective.id());
Charles Chan361154b2016-03-24 10:23:39 -0700249 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.BADPARAMS);
Charles Chan188ebf52015-12-23 00:15:11 -0800250 return;
251 }
252 processSimpleNextObjective(nextObjective);
253 break;
254 case BROADCAST:
255 processBroadcastNextObjective(nextObjective);
256 break;
257 case HASHED:
Pier Ventre140a8942016-11-02 07:26:38 -0700258 if (!verifyHashedNextObjective(nextObjective)) {
259 log.error("Next Objectives of type hashed not supported. Next Objective Id:{}",
260 nextObjective.id());
261 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.BADPARAMS);
262 return;
263 }
Charles Chan188ebf52015-12-23 00:15:11 -0800264 processHashedNextObjective(nextObjective);
265 break;
266 case FAILOVER:
Charles Chan361154b2016-03-24 10:23:39 -0700267 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.UNSUPPORTED);
Charles Chan188ebf52015-12-23 00:15:11 -0800268 log.warn("Unsupported next objective type {}", nextObjective.type());
269 break;
270 default:
Charles Chan361154b2016-03-24 10:23:39 -0700271 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.UNKNOWN);
Charles Chan188ebf52015-12-23 00:15:11 -0800272 log.warn("Unknown next objective type {}", nextObjective.type());
273 }
274 }
275
276 /**
277 * As per the OFDPA 2.0 TTP, packets are sent out of ports by using
278 * a chain of groups. The simple Next Objective passed
279 * in by the application has to be broken up into a group chain
280 * comprising of an L3 Unicast Group that points to an L2 Interface
281 * Group which in-turn points to an output port. In some cases, the simple
282 * next Objective can just be an L2 interface without the need for chaining.
283 *
284 * @param nextObj the nextObjective of type SIMPLE
285 */
286 private void processSimpleNextObjective(NextObjective nextObj) {
287 TrafficTreatment treatment = nextObj.next().iterator().next();
288 // determine if plain L2 or L3->L2
289 boolean plainL2 = true;
290 for (Instruction ins : treatment.allInstructions()) {
291 if (ins.type() == Instruction.Type.L2MODIFICATION) {
292 L2ModificationInstruction l2ins = (L2ModificationInstruction) ins;
293 if (l2ins.subtype() == L2ModificationInstruction.L2SubType.ETH_DST ||
294 l2ins.subtype() == L2ModificationInstruction.L2SubType.ETH_SRC) {
295 plainL2 = false;
296 break;
297 }
298 }
299 }
300
301 if (plainL2) {
302 createL2InterfaceGroup(nextObj);
303 return;
304 }
305
Pier Ventre140a8942016-11-02 07:26:38 -0700306 boolean isMpls = false;
Pier Ventre42287df2016-11-09 14:17:26 -0800307 // In order to understand if it is a pseudo wire related
308 // next objective we look for the tunnel id in the meta.
309 boolean isPw = false;
Pier Ventre140a8942016-11-02 07:26:38 -0700310 if (nextObj.meta() != null) {
311 isMpls = isNotMplsBos(nextObj.meta());
Pier Ventre42287df2016-11-09 14:17:26 -0800312
313 TunnelIdCriterion tunnelIdCriterion = (TunnelIdCriterion) nextObj
314 .meta()
315 .getCriterion(TUNNEL_ID);
316 if (tunnelIdCriterion != null) {
317 isPw = true;
318 }
319
Pier Ventre140a8942016-11-02 07:26:38 -0700320 }
321
Pier Ventre42287df2016-11-09 14:17:26 -0800322 if (!isPw) {
323 // break up simple next objective to GroupChain objects
324 GroupInfo groupInfo = createL2L3Chain(treatment, nextObj.id(),
325 nextObj.appId(), isMpls,
326 nextObj.meta());
327 if (groupInfo == null) {
328 log.error("Could not process nextObj={} in dev:{}", nextObj.id(), deviceId);
329 return;
330 }
331 // create object for local and distributed storage
332 Deque<GroupKey> gkeyChain = new ArrayDeque<>();
333 gkeyChain.addFirst(groupInfo.innerMostGroupDesc.appCookie());
334 gkeyChain.addFirst(groupInfo.nextGroupDesc.appCookie());
335 OfdpaNextGroup ofdpaGrp =
336 new OfdpaNextGroup(Collections.singletonList(gkeyChain), nextObj);
337
338 // store l3groupkey with the ofdpaNextGroup for the nextObjective that depends on it
339 updatePendingNextObjective(groupInfo.nextGroupDesc.appCookie(), ofdpaGrp);
340
341 // now we are ready to send the l2 groupDescription (inner), as all the stores
342 // that will get async replies have been updated. By waiting to update
343 // the stores, we prevent nasty race conditions.
344 groupService.addGroup(groupInfo.innerMostGroupDesc);
345 } else {
346 // We handle the pseudo wire with a different a procedure.
347 // This procedure is meant to handle both initiation and
348 // termination of the pseudo wire.
349 processPwNextObjective(nextObj);
Charles Chan188ebf52015-12-23 00:15:11 -0800350 }
Charles Chan188ebf52015-12-23 00:15:11 -0800351 }
352
Charles Chan188ebf52015-12-23 00:15:11 -0800353 /**
354 * Creates a simple L2 Interface Group.
355 *
356 * @param nextObj the next Objective
357 */
358 private void createL2InterfaceGroup(NextObjective nextObj) {
Charles Chan5b9df8d2016-03-28 22:21:40 -0700359 VlanId assignedVlan = Ofdpa2Pipeline.readVlanFromSelector(nextObj.meta());
360 if (assignedVlan == null) {
361 log.warn("VLAN ID required by simple next obj is missing. Abort.");
362 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.BADPARAMS);
Charles Chan188ebf52015-12-23 00:15:11 -0800363 return;
364 }
365
Charles Chan5b9df8d2016-03-28 22:21:40 -0700366 List<GroupInfo> groupInfos = prepareL2InterfaceGroup(nextObj, assignedVlan);
Charles Chan188ebf52015-12-23 00:15:11 -0800367
Charles Chan5b9df8d2016-03-28 22:21:40 -0700368 // There is only one L2 interface group in this case
369 GroupDescription l2InterfaceGroupDesc = groupInfos.get(0).innerMostGroupDesc;
Charles Chan188ebf52015-12-23 00:15:11 -0800370
Charles Chan5b9df8d2016-03-28 22:21:40 -0700371 // Put all dependency information into allGroupKeys
372 List<Deque<GroupKey>> allGroupKeys = Lists.newArrayList();
373 Deque<GroupKey> gkeyChain = new ArrayDeque<>();
374 gkeyChain.addFirst(l2InterfaceGroupDesc.appCookie());
375 allGroupKeys.add(gkeyChain);
Charles Chan188ebf52015-12-23 00:15:11 -0800376
Charles Chan5b9df8d2016-03-28 22:21:40 -0700377 // Point the next objective to this group
378 OfdpaNextGroup ofdpaGrp = new OfdpaNextGroup(allGroupKeys, nextObj);
379 updatePendingNextObjective(l2InterfaceGroupDesc.appCookie(), ofdpaGrp);
380
381 // Start installing the inner-most group
382 groupService.addGroup(l2InterfaceGroupDesc);
Charles Chan188ebf52015-12-23 00:15:11 -0800383 }
384
385 /**
386 * Creates one of two possible group-chains from the treatment
387 * passed in. Depending on the MPLS boolean, this method either creates
Charles Chan425854b2016-04-11 15:32:12 -0700388 * an L3Unicast Group --&gt; L2Interface Group, if mpls is false;
389 * or MPLSInterface Group --&gt; L2Interface Group, if mpls is true;
Charles Chan188ebf52015-12-23 00:15:11 -0800390 * The returned 'inner' group description is always the L2 Interface group.
391 *
392 * @param treatment that needs to be broken up to create the group chain
393 * @param nextId of the next objective that needs this group chain
394 * @param appId of the application that sent this next objective
395 * @param mpls determines if L3Unicast or MPLSInterface group is created
396 * @param meta metadata passed in by the application as part of the nextObjective
397 * @return GroupInfo containing the GroupDescription of the
398 * L2Interface group(inner) and the GroupDescription of the (outer)
399 * L3Unicast/MPLSInterface group. May return null if there is an
400 * error in processing the chain
401 */
Charles Chan425854b2016-04-11 15:32:12 -0700402 protected GroupInfo createL2L3Chain(TrafficTreatment treatment, int nextId,
Charles Chanf9e98652016-09-07 16:54:23 -0700403 ApplicationId appId, boolean mpls,
404 TrafficSelector meta) {
405 return createL2L3ChainInternal(treatment, nextId, appId, mpls, meta, true);
406 }
407
408 /**
409 * Internal implementation of createL2L3Chain.
410 * <p>
411 * The is_present bit in set_vlan_vid action is required to be 0 in OFDPA i12.
412 * Since it is non-OF spec, we need an extension treatment for that.
413 * The useSetVlanExtension must be set to false for OFDPA i12.
414 * </p>
415 *
416 * @param treatment that needs to be broken up to create the group chain
417 * @param nextId of the next objective that needs this group chain
418 * @param appId of the application that sent this next objective
419 * @param mpls determines if L3Unicast or MPLSInterface group is created
420 * @param meta metadata passed in by the application as part of the nextObjective
421 * @param useSetVlanExtension use the setVlanVid extension that has is_present bit set to 0.
422 * @return GroupInfo containing the GroupDescription of the
423 * L2Interface group(inner) and the GroupDescription of the (outer)
424 * L3Unicast/MPLSInterface group. May return null if there is an
425 * error in processing the chain
426 */
427 protected GroupInfo createL2L3ChainInternal(TrafficTreatment treatment, int nextId,
Pier Ventre42287df2016-11-09 14:17:26 -0800428 ApplicationId appId, boolean mpls,
429 TrafficSelector meta, boolean useSetVlanExtension) {
Charles Chan188ebf52015-12-23 00:15:11 -0800430 // for the l2interface group, get vlan and port info
431 // for the outer group, get the src/dst mac, and vlan info
432 TrafficTreatment.Builder outerTtb = DefaultTrafficTreatment.builder();
433 TrafficTreatment.Builder innerTtb = DefaultTrafficTreatment.builder();
434 VlanId vlanid = null;
435 long portNum = 0;
436 boolean setVlan = false, popVlan = false;
Yi Tseng78f51f42017-02-02 13:54:58 -0800437 MacAddress srcMac;
438 MacAddress dstMac;
Charles Chan188ebf52015-12-23 00:15:11 -0800439 for (Instruction ins : treatment.allInstructions()) {
440 if (ins.type() == Instruction.Type.L2MODIFICATION) {
441 L2ModificationInstruction l2ins = (L2ModificationInstruction) ins;
442 switch (l2ins.subtype()) {
443 case ETH_DST:
Charles Chan5270ed02016-01-30 23:22:37 -0800444 dstMac = ((L2ModificationInstruction.ModEtherInstruction) l2ins).mac();
445 outerTtb.setEthDst(dstMac);
Charles Chan188ebf52015-12-23 00:15:11 -0800446 break;
447 case ETH_SRC:
Charles Chand0fd5dc2016-02-16 23:14:49 -0800448 srcMac = ((L2ModificationInstruction.ModEtherInstruction) l2ins).mac();
449 outerTtb.setEthSrc(srcMac);
Charles Chan188ebf52015-12-23 00:15:11 -0800450 break;
451 case VLAN_ID:
452 vlanid = ((L2ModificationInstruction.ModVlanIdInstruction) l2ins).vlanId();
Charles Chanf9e98652016-09-07 16:54:23 -0700453 if (useSetVlanExtension) {
454 OfdpaSetVlanVid ofdpaSetVlanVid = new OfdpaSetVlanVid(vlanid);
455 outerTtb.extension(ofdpaSetVlanVid, deviceId);
456 } else {
457 outerTtb.setVlanId(vlanid);
458 }
Charles Chan188ebf52015-12-23 00:15:11 -0800459 setVlan = true;
460 break;
461 case VLAN_POP:
462 innerTtb.popVlan();
463 popVlan = true;
464 break;
465 case DEC_MPLS_TTL:
466 case MPLS_LABEL:
467 case MPLS_POP:
468 case MPLS_PUSH:
469 case VLAN_PCP:
470 case VLAN_PUSH:
471 default:
472 break;
473 }
474 } else if (ins.type() == Instruction.Type.OUTPUT) {
475 portNum = ((Instructions.OutputInstruction) ins).port().toLong();
476 innerTtb.add(ins);
477 } else {
478 log.warn("Driver does not handle this type of TrafficTreatment"
479 + " instruction in nextObjectives: {}", ins.type());
480 }
481 }
482
483 if (vlanid == null && meta != null) {
484 // use metadata if available
Pier Ventre140a8942016-11-02 07:26:38 -0700485 Criterion vidCriterion = meta.getCriterion(VLAN_VID);
Charles Chan188ebf52015-12-23 00:15:11 -0800486 if (vidCriterion != null) {
487 vlanid = ((VlanIdCriterion) vidCriterion).vlanId();
488 }
489 // if vlan is not set, use the vlan in metadata for outerTtb
490 if (vlanid != null && !setVlan) {
Charles Chanf9e98652016-09-07 16:54:23 -0700491 if (useSetVlanExtension) {
492 OfdpaSetVlanVid ofdpaSetVlanVid = new OfdpaSetVlanVid(vlanid);
493 outerTtb.extension(ofdpaSetVlanVid, deviceId);
494 } else {
495 outerTtb.setVlanId(vlanid);
496 }
Charles Chan188ebf52015-12-23 00:15:11 -0800497 }
498 }
499
500 if (vlanid == null) {
501 log.error("Driver cannot process an L2/L3 group chain without "
502 + "egress vlan information for dev: {} port:{}",
503 deviceId, portNum);
504 return null;
505 }
506
507 if (!setVlan && !popVlan) {
508 // untagged outgoing port
509 TrafficTreatment.Builder temp = DefaultTrafficTreatment.builder();
510 temp.popVlan();
511 innerTtb.build().allInstructions().forEach(i -> temp.add(i));
512 innerTtb = temp;
513 }
514
515 // assemble information for ofdpa l2interface group
Charles Chane849c192016-01-11 18:28:54 -0800516 int l2groupId = L2_INTERFACE_TYPE | (vlanid.toShort() << 16) | (int) portNum;
Saurav Das8be4e3a2016-03-11 17:19:07 -0800517 // a globally unique groupkey that is different for ports in the same device,
Charles Chan188ebf52015-12-23 00:15:11 -0800518 // but different for the same portnumber on different devices. Also different
519 // for the various group-types created out of the same next objective.
Charles Chane849c192016-01-11 18:28:54 -0800520 int l2gk = l2InterfaceGroupKey(deviceId, vlanid, portNum);
Charles Chan361154b2016-03-24 10:23:39 -0700521 final GroupKey l2groupkey = new DefaultGroupKey(Ofdpa2Pipeline.appKryo.serialize(l2gk));
Charles Chan188ebf52015-12-23 00:15:11 -0800522
523 // assemble information for outer group
524 GroupDescription outerGrpDesc = null;
525 if (mpls) {
526 // outer group is MPLSInteface
Saurav Das8be4e3a2016-03-11 17:19:07 -0800527 int mplsInterfaceIndex = getNextAvailableIndex();
528 int mplsgroupId = MPLS_INTERFACE_TYPE | (SUBTYPE_MASK & mplsInterfaceIndex);
529 final GroupKey mplsgroupkey = new DefaultGroupKey(
Charles Chan361154b2016-03-24 10:23:39 -0700530 Ofdpa2Pipeline.appKryo.serialize(mplsInterfaceIndex));
Yi Tsengfa394de2017-02-01 11:26:40 -0800531 outerTtb.group(new GroupId(l2groupId));
Charles Chan188ebf52015-12-23 00:15:11 -0800532 // create the mpls-interface group description to wait for the
533 // l2 interface group to be processed
534 GroupBucket mplsinterfaceGroupBucket =
535 DefaultGroupBucket.createIndirectGroupBucket(outerTtb.build());
536 outerGrpDesc = new DefaultGroupDescription(
537 deviceId,
538 GroupDescription.Type.INDIRECT,
539 new GroupBuckets(Collections.singletonList(
540 mplsinterfaceGroupBucket)),
541 mplsgroupkey,
542 mplsgroupId,
543 appId);
544 log.debug("Trying MPLS-Interface: device:{} gid:{} gkey:{} nextid:{}",
545 deviceId, Integer.toHexString(mplsgroupId),
546 mplsgroupkey, nextId);
547 } else {
548 // outer group is L3Unicast
Saurav Das8be4e3a2016-03-11 17:19:07 -0800549 int l3unicastIndex = getNextAvailableIndex();
550 int l3groupId = L3_UNICAST_TYPE | (TYPE_MASK & l3unicastIndex);
551 final GroupKey l3groupkey = new DefaultGroupKey(
Charles Chan361154b2016-03-24 10:23:39 -0700552 Ofdpa2Pipeline.appKryo.serialize(l3unicastIndex));
Yi Tsengfa394de2017-02-01 11:26:40 -0800553 outerTtb.group(new GroupId(l2groupId));
Charles Chan188ebf52015-12-23 00:15:11 -0800554 // create the l3unicast group description to wait for the
555 // l2 interface group to be processed
556 GroupBucket l3unicastGroupBucket =
557 DefaultGroupBucket.createIndirectGroupBucket(outerTtb.build());
558 outerGrpDesc = new DefaultGroupDescription(
559 deviceId,
560 GroupDescription.Type.INDIRECT,
561 new GroupBuckets(Collections.singletonList(
562 l3unicastGroupBucket)),
563 l3groupkey,
564 l3groupId,
565 appId);
566 log.debug("Trying L3Unicast: device:{} gid:{} gkey:{} nextid:{}",
567 deviceId, Integer.toHexString(l3groupId),
568 l3groupkey, nextId);
569 }
570
571 // store l2groupkey with the groupChainElem for the outer-group that depends on it
572 GroupChainElem gce = new GroupChainElem(outerGrpDesc, 1, false);
573 updatePendingGroups(l2groupkey, gce);
574
575 // create group description for the inner l2interfacegroup
Charles Chan5b9df8d2016-03-28 22:21:40 -0700576 GroupBucket l2InterfaceGroupBucket =
Charles Chan188ebf52015-12-23 00:15:11 -0800577 DefaultGroupBucket.createIndirectGroupBucket(innerTtb.build());
578 GroupDescription l2groupDescription =
579 new DefaultGroupDescription(
580 deviceId,
581 GroupDescription.Type.INDIRECT,
582 new GroupBuckets(Collections.singletonList(
Charles Chan5b9df8d2016-03-28 22:21:40 -0700583 l2InterfaceGroupBucket)),
Charles Chan188ebf52015-12-23 00:15:11 -0800584 l2groupkey,
585 l2groupId,
586 appId);
587 log.debug("Trying L2Interface: device:{} gid:{} gkey:{} nextId:{}",
588 deviceId, Integer.toHexString(l2groupId),
589 l2groupkey, nextId);
590 return new GroupInfo(l2groupDescription, outerGrpDesc);
591
592 }
593
594 /**
595 * As per the OFDPA 2.0 TTP, packets are sent out of ports by using
596 * a chain of groups. The broadcast Next Objective passed in by the application
597 * has to be broken up into a group chain comprising of an
Saurav Das1a129a02016-11-18 15:21:57 -0800598 * L2 Flood group or L3 Multicast group, whose buckets point to L2 Interface groups.
Charles Chan188ebf52015-12-23 00:15:11 -0800599 *
600 * @param nextObj the nextObjective of type BROADCAST
601 */
602 private void processBroadcastNextObjective(NextObjective nextObj) {
Charles Chan5b9df8d2016-03-28 22:21:40 -0700603 VlanId assignedVlan = Ofdpa2Pipeline.readVlanFromSelector(nextObj.meta());
604 if (assignedVlan == null) {
605 log.warn("VLAN ID required by broadcast next obj is missing. Abort.");
606 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.BADPARAMS);
Charles Chan188ebf52015-12-23 00:15:11 -0800607 return;
608 }
Charles Chan188ebf52015-12-23 00:15:11 -0800609
Charles Chan5b9df8d2016-03-28 22:21:40 -0700610 List<GroupInfo> groupInfos = prepareL2InterfaceGroup(nextObj, assignedVlan);
611
612 IpPrefix ipDst = Ofdpa2Pipeline.readIpDstFromSelector(nextObj.meta());
613 if (ipDst != null) {
614 if (ipDst.isMulticast()) {
615 createL3MulticastGroup(nextObj, assignedVlan, groupInfos);
616 } else {
617 log.warn("Broadcast NextObj with non-multicast IP address {}", nextObj);
618 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.BADPARAMS);
619 return;
620 }
621 } else {
622 createL2FloodGroup(nextObj, assignedVlan, groupInfos);
623 }
624 }
625
Saurav Das1ce0a7b2016-10-21 14:06:29 -0700626 private List<GroupInfo> prepareL2InterfaceGroup(NextObjective nextObj,
627 VlanId assignedVlan) {
Charles Chan5b9df8d2016-03-28 22:21:40 -0700628 ImmutableList.Builder<GroupInfo> groupInfoBuilder = ImmutableList.builder();
629
630 // break up broadcast next objective to multiple groups
631 Collection<TrafficTreatment> buckets = nextObj.next();
632
Charles Chan188ebf52015-12-23 00:15:11 -0800633 // each treatment is converted to an L2 interface group
Charles Chan188ebf52015-12-23 00:15:11 -0800634 for (TrafficTreatment treatment : buckets) {
635 TrafficTreatment.Builder newTreatment = DefaultTrafficTreatment.builder();
636 PortNumber portNum = null;
Charles Chan5b9df8d2016-03-28 22:21:40 -0700637 VlanId egressVlan = null;
Charles Chan188ebf52015-12-23 00:15:11 -0800638 // ensure that the only allowed treatments are pop-vlan and output
639 for (Instruction ins : treatment.allInstructions()) {
640 if (ins.type() == Instruction.Type.L2MODIFICATION) {
641 L2ModificationInstruction l2ins = (L2ModificationInstruction) ins;
642 switch (l2ins.subtype()) {
643 case VLAN_POP:
644 newTreatment.add(l2ins);
645 break;
Charles Chan5b9df8d2016-03-28 22:21:40 -0700646 case VLAN_ID:
647 egressVlan = ((L2ModificationInstruction.ModVlanIdInstruction) l2ins).vlanId();
648 break;
Charles Chan188ebf52015-12-23 00:15:11 -0800649 default:
650 log.debug("action {} not permitted for broadcast nextObj",
651 l2ins.subtype());
652 break;
653 }
654 } else if (ins.type() == Instruction.Type.OUTPUT) {
655 portNum = ((Instructions.OutputInstruction) ins).port();
656 newTreatment.add(ins);
657 } else {
Charles Chane849c192016-01-11 18:28:54 -0800658 log.debug("TrafficTreatment of type {} not permitted in " +
659 " broadcast nextObjective", ins.type());
Charles Chan188ebf52015-12-23 00:15:11 -0800660 }
661 }
662
Charles Chan188ebf52015-12-23 00:15:11 -0800663 // assemble info for l2 interface group
Charles Chan5b9df8d2016-03-28 22:21:40 -0700664 VlanId l2InterfaceGroupVlan =
665 (egressVlan != null && !assignedVlan.equals(egressVlan)) ?
666 egressVlan : assignedVlan;
667 int l2gk = l2InterfaceGroupKey(deviceId, l2InterfaceGroupVlan, portNum.toLong());
668 final GroupKey l2InterfaceGroupKey =
669 new DefaultGroupKey(Ofdpa2Pipeline.appKryo.serialize(l2gk));
Charles Chan372b63e2017-02-07 12:10:53 -0800670 int l2InterfaceGroupId = L2_INTERFACE_TYPE |
671 ((l2InterfaceGroupVlan.toShort() & THREE_BIT_MASK) << PORT_LEN) |
672 ((int) portNum.toLong() & FOUR_BIT_MASK);
Charles Chan5b9df8d2016-03-28 22:21:40 -0700673 GroupBucket l2InterfaceGroupBucket =
Charles Chan188ebf52015-12-23 00:15:11 -0800674 DefaultGroupBucket.createIndirectGroupBucket(newTreatment.build());
Charles Chan5b9df8d2016-03-28 22:21:40 -0700675 GroupDescription l2InterfaceGroupDescription =
Charles Chan188ebf52015-12-23 00:15:11 -0800676 new DefaultGroupDescription(
677 deviceId,
678 GroupDescription.Type.INDIRECT,
679 new GroupBuckets(Collections.singletonList(
Charles Chan5b9df8d2016-03-28 22:21:40 -0700680 l2InterfaceGroupBucket)),
681 l2InterfaceGroupKey,
682 l2InterfaceGroupId,
Charles Chan188ebf52015-12-23 00:15:11 -0800683 nextObj.appId());
684 log.debug("Trying L2-Interface: device:{} gid:{} gkey:{} nextid:{}",
Charles Chan5b9df8d2016-03-28 22:21:40 -0700685 deviceId, Integer.toHexString(l2InterfaceGroupId),
686 l2InterfaceGroupKey, nextObj.id());
Charles Chan188ebf52015-12-23 00:15:11 -0800687
Charles Chan5b9df8d2016-03-28 22:21:40 -0700688 groupInfoBuilder.add(new GroupInfo(l2InterfaceGroupDescription,
689 l2InterfaceGroupDescription));
Charles Chan188ebf52015-12-23 00:15:11 -0800690 }
Charles Chan5b9df8d2016-03-28 22:21:40 -0700691 return groupInfoBuilder.build();
692 }
Charles Chan188ebf52015-12-23 00:15:11 -0800693
Saurav Das1ce0a7b2016-10-21 14:06:29 -0700694 private void createL2FloodGroup(NextObjective nextObj, VlanId vlanId,
695 List<GroupInfo> groupInfos) {
696 // assemble info for l2 flood group. Since there can be only one flood
697 // group for a vlan, its index is always the same - 0
Saurav Das0fd79d92016-03-07 10:58:36 -0800698 Integer l2floodgroupId = L2_FLOOD_TYPE | (vlanId.toShort() << 16);
Yi Tseng117952d2017-02-28 10:58:23 -0800699 int l2floodgk = l2FloodGroupKey(vlanId);
Saurav Das1ce0a7b2016-10-21 14:06:29 -0700700 final GroupKey l2floodgroupkey =
701 new DefaultGroupKey(Ofdpa2Pipeline.appKryo.serialize(l2floodgk));
Charles Chan5b9df8d2016-03-28 22:21:40 -0700702
Charles Chan188ebf52015-12-23 00:15:11 -0800703 // collection of group buckets pointing to all the l2 interface groups
Yi Tseng78f51f42017-02-02 13:54:58 -0800704 List<GroupBucket> l2floodBuckets =
705 generateNextGroupBuckets(groupInfos, ALL);
Charles Chan188ebf52015-12-23 00:15:11 -0800706 // create the l2flood group-description to wait for all the
707 // l2interface groups to be processed
708 GroupDescription l2floodGroupDescription =
709 new DefaultGroupDescription(
710 deviceId,
Yi Tseng78f51f42017-02-02 13:54:58 -0800711 ALL,
Charles Chan188ebf52015-12-23 00:15:11 -0800712 new GroupBuckets(l2floodBuckets),
713 l2floodgroupkey,
714 l2floodgroupId,
715 nextObj.appId());
Charles Chan188ebf52015-12-23 00:15:11 -0800716 log.debug("Trying L2-Flood: device:{} gid:{} gkey:{} nextid:{}",
717 deviceId, Integer.toHexString(l2floodgroupId),
718 l2floodgroupkey, nextObj.id());
719
Charles Chan5b9df8d2016-03-28 22:21:40 -0700720 // Put all dependency information into allGroupKeys
721 List<Deque<GroupKey>> allGroupKeys = Lists.newArrayList();
722 groupInfos.forEach(groupInfo -> {
723 Deque<GroupKey> gkeyChain = new ArrayDeque<>();
724 // In this case we should have L2 interface group only
725 gkeyChain.addFirst(groupInfo.nextGroupDesc.appCookie());
726 gkeyChain.addFirst(l2floodgroupkey);
727 allGroupKeys.add(gkeyChain);
728 });
Charles Chan188ebf52015-12-23 00:15:11 -0800729
Charles Chan5b9df8d2016-03-28 22:21:40 -0700730 // Point the next objective to this group
731 OfdpaNextGroup ofdpaGrp = new OfdpaNextGroup(allGroupKeys, nextObj);
Charles Chan188ebf52015-12-23 00:15:11 -0800732 updatePendingNextObjective(l2floodgroupkey, ofdpaGrp);
733
Charles Chan5b9df8d2016-03-28 22:21:40 -0700734 GroupChainElem gce = new GroupChainElem(l2floodGroupDescription,
735 groupInfos.size(), false);
736 groupInfos.forEach(groupInfo -> {
737 // Point this group to the next group
738 updatePendingGroups(groupInfo.nextGroupDesc.appCookie(), gce);
739 // Start installing the inner-most group
740 groupService.addGroup(groupInfo.innerMostGroupDesc);
741 });
742 }
743
Yi Tseng117952d2017-02-28 10:58:23 -0800744 private int l2FloodGroupKey(VlanId vlanId) {
745 int hash = Objects.hash(deviceId, vlanId);
746 return L2_FLOOD_TYPE | TYPE_MASK & hash;
747 }
748
Saurav Das1ce0a7b2016-10-21 14:06:29 -0700749 private void createL3MulticastGroup(NextObjective nextObj, VlanId vlanId,
750 List<GroupInfo> groupInfos) {
Charles Chan5b9df8d2016-03-28 22:21:40 -0700751 List<GroupBucket> l3McastBuckets = new ArrayList<>();
752 groupInfos.forEach(groupInfo -> {
753 // Points to L3 interface group if there is one.
754 // Otherwise points to L2 interface group directly.
755 GroupDescription nextGroupDesc = (groupInfo.nextGroupDesc != null) ?
756 groupInfo.nextGroupDesc : groupInfo.innerMostGroupDesc;
757 TrafficTreatment.Builder ttb = DefaultTrafficTreatment.builder();
Yi Tsengfa394de2017-02-01 11:26:40 -0800758 ttb.group(new GroupId(nextGroupDesc.givenGroupId()));
Charles Chan5b9df8d2016-03-28 22:21:40 -0700759 GroupBucket abucket = DefaultGroupBucket.createAllGroupBucket(ttb.build());
760 l3McastBuckets.add(abucket);
761 });
762
763 int l3MulticastIndex = getNextAvailableIndex();
Saurav Das1ce0a7b2016-10-21 14:06:29 -0700764 int l3MulticastGroupId = L3_MULTICAST_TYPE |
765 vlanId.toShort() << 16 | (TYPE_VLAN_MASK & l3MulticastIndex);
766 final GroupKey l3MulticastGroupKey =
767 new DefaultGroupKey(Ofdpa2Pipeline.appKryo.serialize(l3MulticastIndex));
Charles Chan5b9df8d2016-03-28 22:21:40 -0700768
769 GroupDescription l3MulticastGroupDesc = new DefaultGroupDescription(deviceId,
Yi Tseng78f51f42017-02-02 13:54:58 -0800770 ALL,
Charles Chan5b9df8d2016-03-28 22:21:40 -0700771 new GroupBuckets(l3McastBuckets),
772 l3MulticastGroupKey,
773 l3MulticastGroupId,
774 nextObj.appId());
775
776 // Put all dependency information into allGroupKeys
777 List<Deque<GroupKey>> allGroupKeys = Lists.newArrayList();
778 groupInfos.forEach(groupInfo -> {
779 Deque<GroupKey> gkeyChain = new ArrayDeque<>();
780 gkeyChain.addFirst(groupInfo.innerMostGroupDesc.appCookie());
781 // Add L3 interface group to the chain if there is one.
782 if (!groupInfo.nextGroupDesc.equals(groupInfo.innerMostGroupDesc)) {
783 gkeyChain.addFirst(groupInfo.nextGroupDesc.appCookie());
784 }
785 gkeyChain.addFirst(l3MulticastGroupKey);
786 allGroupKeys.add(gkeyChain);
787 });
788
789 // Point the next objective to this group
790 OfdpaNextGroup ofdpaGrp = new OfdpaNextGroup(allGroupKeys, nextObj);
791 updatePendingNextObjective(l3MulticastGroupKey, ofdpaGrp);
792
793 GroupChainElem outerGce = new GroupChainElem(l3MulticastGroupDesc,
794 groupInfos.size(), false);
795 groupInfos.forEach(groupInfo -> {
796 // Point this group (L3 multicast) to the next group
797 updatePendingGroups(groupInfo.nextGroupDesc.appCookie(), outerGce);
798
799 // Point next group to inner-most group, if any
800 if (!groupInfo.nextGroupDesc.equals(groupInfo.innerMostGroupDesc)) {
801 GroupChainElem innerGce = new GroupChainElem(groupInfo.nextGroupDesc,
802 1, false);
803 updatePendingGroups(groupInfo.innerMostGroupDesc.appCookie(), innerGce);
804 }
805
806 // Start installing the inner-most group
807 groupService.addGroup(groupInfo.innerMostGroupDesc);
808 });
Charles Chan188ebf52015-12-23 00:15:11 -0800809 }
810
Charles Chan188ebf52015-12-23 00:15:11 -0800811 /**
812 * As per the OFDPA 2.0 TTP, packets are sent out of ports by using
813 * a chain of groups. The hashed Next Objective passed in by the application
814 * has to be broken up into a group chain comprising of an
815 * L3 ECMP group as the top level group. Buckets of this group can point
816 * to a variety of groups in a group chain, depending on the whether
817 * MPLS labels are being pushed or not.
818 * <p>
819 * NOTE: We do not create MPLS ECMP groups as they are unimplemented in
820 * OF-DPA 2.0 (even though it is in the spec). Therefore we do not
821 * check the nextObjective meta to see what is matching before being
822 * sent to this nextObjective.
823 *
824 * @param nextObj the nextObjective of type HASHED
825 */
Pier Ventre140a8942016-11-02 07:26:38 -0700826 protected void processHashedNextObjective(NextObjective nextObj) {
Charles Chan188ebf52015-12-23 00:15:11 -0800827 // storage for all group keys in the chain of groups created
828 List<Deque<GroupKey>> allGroupKeys = new ArrayList<>();
829 List<GroupInfo> unsentGroups = new ArrayList<>();
830 createHashBucketChains(nextObj, allGroupKeys, unsentGroups);
831
832 // now we can create the outermost L3 ECMP group
833 List<GroupBucket> l3ecmpGroupBuckets = new ArrayList<>();
834 for (GroupInfo gi : unsentGroups) {
835 // create ECMP bucket to point to the outer group
836 TrafficTreatment.Builder ttb = DefaultTrafficTreatment.builder();
Yi Tsengfa394de2017-02-01 11:26:40 -0800837 ttb.group(new GroupId(gi.nextGroupDesc.givenGroupId()));
Charles Chan188ebf52015-12-23 00:15:11 -0800838 GroupBucket sbucket = DefaultGroupBucket
839 .createSelectGroupBucket(ttb.build());
840 l3ecmpGroupBuckets.add(sbucket);
841 }
Saurav Das8be4e3a2016-03-11 17:19:07 -0800842 int l3ecmpIndex = getNextAvailableIndex();
843 int l3ecmpGroupId = L3_ECMP_TYPE | (TYPE_MASK & l3ecmpIndex);
844 GroupKey l3ecmpGroupKey = new DefaultGroupKey(
Charles Chan361154b2016-03-24 10:23:39 -0700845 Ofdpa2Pipeline.appKryo.serialize(l3ecmpIndex));
Charles Chan188ebf52015-12-23 00:15:11 -0800846 GroupDescription l3ecmpGroupDesc =
847 new DefaultGroupDescription(
848 deviceId,
Yi Tseng78f51f42017-02-02 13:54:58 -0800849 SELECT,
Charles Chan188ebf52015-12-23 00:15:11 -0800850 new GroupBuckets(l3ecmpGroupBuckets),
851 l3ecmpGroupKey,
852 l3ecmpGroupId,
853 nextObj.appId());
854 GroupChainElem l3ecmpGce = new GroupChainElem(l3ecmpGroupDesc,
855 l3ecmpGroupBuckets.size(),
856 false);
857
858 // create objects for local and distributed storage
859 allGroupKeys.forEach(gkeyChain -> gkeyChain.addFirst(l3ecmpGroupKey));
860 OfdpaNextGroup ofdpaGrp = new OfdpaNextGroup(allGroupKeys, nextObj);
861
862 // store l3ecmpGroupKey with the ofdpaGroupChain for the nextObjective
863 // that depends on it
864 updatePendingNextObjective(l3ecmpGroupKey, ofdpaGrp);
865
866 log.debug("Trying L3ECMP: device:{} gid:{} gkey:{} nextId:{}",
867 deviceId, Integer.toHexString(l3ecmpGroupId),
868 l3ecmpGroupKey, nextObj.id());
869 // finally we are ready to send the innermost groups
870 for (GroupInfo gi : unsentGroups) {
871 log.debug("Sending innermost group {} in group chain on device {} ",
Charles Chan5b9df8d2016-03-28 22:21:40 -0700872 Integer.toHexString(gi.innerMostGroupDesc.givenGroupId()), deviceId);
873 updatePendingGroups(gi.nextGroupDesc.appCookie(), l3ecmpGce);
874 groupService.addGroup(gi.innerMostGroupDesc);
Charles Chan188ebf52015-12-23 00:15:11 -0800875 }
876
877 }
878
879 /**
880 * Creates group chains for all buckets in a hashed group, and stores the
881 * GroupInfos and GroupKeys for all the groups in the lists passed in, which
882 * should be empty.
883 * <p>
884 * Does not create the top level ECMP group. Does not actually send the
885 * groups to the groupService.
886 *
887 * @param nextObj the Next Objective with buckets that need to be converted
888 * to group chains
889 * @param allGroupKeys a list to store groupKey for each bucket-group-chain
890 * @param unsentGroups a list to store GroupInfo for each bucket-group-chain
891 */
Pier Ventre140a8942016-11-02 07:26:38 -0700892 protected void createHashBucketChains(NextObjective nextObj,
Saurav Das8be4e3a2016-03-11 17:19:07 -0800893 List<Deque<GroupKey>> allGroupKeys,
894 List<GroupInfo> unsentGroups) {
Charles Chan188ebf52015-12-23 00:15:11 -0800895 // break up hashed next objective to multiple groups
896 Collection<TrafficTreatment> buckets = nextObj.next();
897
898 for (TrafficTreatment bucket : buckets) {
899 //figure out how many labels are pushed in each bucket
900 int labelsPushed = 0;
901 MplsLabel innermostLabel = null;
902 for (Instruction ins : bucket.allInstructions()) {
903 if (ins.type() == Instruction.Type.L2MODIFICATION) {
904 L2ModificationInstruction l2ins = (L2ModificationInstruction) ins;
905 if (l2ins.subtype() == L2ModificationInstruction.L2SubType.MPLS_PUSH) {
906 labelsPushed++;
907 }
908 if (l2ins.subtype() == L2ModificationInstruction.L2SubType.MPLS_LABEL) {
909 if (innermostLabel == null) {
Ray Milkey125572b2016-02-22 16:48:17 -0800910 innermostLabel = ((L2ModificationInstruction.ModMplsLabelInstruction) l2ins).label();
Charles Chan188ebf52015-12-23 00:15:11 -0800911 }
912 }
913 }
914 }
915
916 Deque<GroupKey> gkeyChain = new ArrayDeque<>();
917 // XXX we only deal with 0 and 1 label push right now
918 if (labelsPushed == 0) {
Pier Ventre140a8942016-11-02 07:26:38 -0700919 GroupInfo nolabelGroupInfo;
920 TrafficSelector metaSelector = nextObj.meta();
921 if (metaSelector != null) {
922 if (isNotMplsBos(metaSelector)) {
923 nolabelGroupInfo = createL2L3Chain(bucket, nextObj.id(),
924 nextObj.appId(), true,
925 nextObj.meta());
926 } else {
927 nolabelGroupInfo = createL2L3Chain(bucket, nextObj.id(),
928 nextObj.appId(), false,
929 nextObj.meta());
930 }
931 } else {
932 nolabelGroupInfo = createL2L3Chain(bucket, nextObj.id(),
933 nextObj.appId(), false,
934 nextObj.meta());
935 }
Charles Chan188ebf52015-12-23 00:15:11 -0800936 if (nolabelGroupInfo == null) {
937 log.error("Could not process nextObj={} in dev:{}",
938 nextObj.id(), deviceId);
939 return;
940 }
Charles Chan5b9df8d2016-03-28 22:21:40 -0700941 gkeyChain.addFirst(nolabelGroupInfo.innerMostGroupDesc.appCookie());
942 gkeyChain.addFirst(nolabelGroupInfo.nextGroupDesc.appCookie());
Charles Chan188ebf52015-12-23 00:15:11 -0800943
944 // we can't send the inner group description yet, as we have to
945 // create the dependent ECMP group first. So we store..
946 unsentGroups.add(nolabelGroupInfo);
947
948 } else if (labelsPushed == 1) {
949 GroupInfo onelabelGroupInfo = createL2L3Chain(bucket, nextObj.id(),
950 nextObj.appId(), true,
951 nextObj.meta());
952 if (onelabelGroupInfo == null) {
953 log.error("Could not process nextObj={} in dev:{}",
954 nextObj.id(), deviceId);
955 return;
956 }
957 // we need to add another group to this chain - the L3VPN group
958 TrafficTreatment.Builder l3vpnTtb = DefaultTrafficTreatment.builder();
Charles Chan0f43e472017-02-14 14:00:16 -0800959 if (requireVlanPopBeforeMplsPush()) {
960 l3vpnTtb.popVlan();
961 }
Charles Chan188ebf52015-12-23 00:15:11 -0800962 l3vpnTtb.pushMpls()
963 .setMpls(innermostLabel)
Yi Tsengfa394de2017-02-01 11:26:40 -0800964 .group(new GroupId(onelabelGroupInfo.nextGroupDesc.givenGroupId()));
Charles Chan40132b32017-01-22 00:19:37 -0800965 if (supportCopyTtl()) {
966 l3vpnTtb.copyTtlOut();
967 }
968 if (supportSetMplsBos()) {
969 l3vpnTtb.setMplsBos(true);
970 }
Charles Chan0f43e472017-02-14 14:00:16 -0800971 if (requireVlanPopBeforeMplsPush()) {
972 l3vpnTtb.pushVlan().setVlanId(VlanId.vlanId(VlanId.RESERVED));
973 }
Charles Chan40132b32017-01-22 00:19:37 -0800974
Charles Chan188ebf52015-12-23 00:15:11 -0800975 GroupBucket l3vpnGrpBkt =
976 DefaultGroupBucket.createIndirectGroupBucket(l3vpnTtb.build());
Saurav Das8be4e3a2016-03-11 17:19:07 -0800977 int l3vpnIndex = getNextAvailableIndex();
978 int l3vpngroupId = MPLS_L3VPN_SUBTYPE | (SUBTYPE_MASK & l3vpnIndex);
979 GroupKey l3vpngroupkey = new DefaultGroupKey(
Charles Chan361154b2016-03-24 10:23:39 -0700980 Ofdpa2Pipeline.appKryo.serialize(l3vpnIndex));
Charles Chan188ebf52015-12-23 00:15:11 -0800981 GroupDescription l3vpnGroupDesc =
982 new DefaultGroupDescription(
983 deviceId,
984 GroupDescription.Type.INDIRECT,
985 new GroupBuckets(Collections.singletonList(
986 l3vpnGrpBkt)),
987 l3vpngroupkey,
988 l3vpngroupId,
989 nextObj.appId());
990 GroupChainElem l3vpnGce = new GroupChainElem(l3vpnGroupDesc, 1, false);
Charles Chan5b9df8d2016-03-28 22:21:40 -0700991 updatePendingGroups(onelabelGroupInfo.nextGroupDesc.appCookie(), l3vpnGce);
Charles Chan188ebf52015-12-23 00:15:11 -0800992
Charles Chan5b9df8d2016-03-28 22:21:40 -0700993 gkeyChain.addFirst(onelabelGroupInfo.innerMostGroupDesc.appCookie());
994 gkeyChain.addFirst(onelabelGroupInfo.nextGroupDesc.appCookie());
Charles Chan188ebf52015-12-23 00:15:11 -0800995 gkeyChain.addFirst(l3vpngroupkey);
996
997 //now we can replace the outerGrpDesc with the one we just created
Charles Chan5b9df8d2016-03-28 22:21:40 -0700998 onelabelGroupInfo.nextGroupDesc = l3vpnGroupDesc;
Charles Chan188ebf52015-12-23 00:15:11 -0800999
1000 // we can't send the innermost group yet, as we have to create
1001 // the dependent ECMP group first. So we store ...
1002 unsentGroups.add(onelabelGroupInfo);
1003
1004 log.debug("Trying L3VPN: device:{} gid:{} gkey:{} nextId:{}",
1005 deviceId, Integer.toHexString(l3vpngroupId),
1006 l3vpngroupkey, nextObj.id());
1007
1008 } else {
1009 log.warn("Driver currently does not handle more than 1 MPLS "
1010 + "labels. Not processing nextObjective {}", nextObj.id());
1011 return;
1012 }
1013
1014 // all groups in this chain
1015 allGroupKeys.add(gkeyChain);
1016 }
1017 }
1018
Pier Ventre42287df2016-11-09 14:17:26 -08001019 /**
1020 * Processes the pseudo wire related next objective.
1021 * This procedure try to reuse the mpls label groups,
1022 * the mpls interface group and the l2 interface group.
1023 *
1024 * @param nextObjective the objective to process.
1025 */
1026 protected void processPwNextObjective(NextObjective nextObjective) {
1027 log.warn("Pseudo wire extensions are not support for the OFDPA 2.0 {}", nextObjective.id());
1028 return;
1029 }
1030
Saurav Das8be4e3a2016-03-11 17:19:07 -08001031 //////////////////////////////////////
1032 // Group Editing
1033 //////////////////////////////////////
1034
Charles Chan188ebf52015-12-23 00:15:11 -08001035 /**
1036 * Adds a bucket to the top level group of a group-chain, and creates the chain.
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001037 * Ensures that bucket being added is not a duplicate, by checking existing
1038 * buckets for the same outport.
Charles Chan188ebf52015-12-23 00:15:11 -08001039 *
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001040 * @param nextObjective the bucket information for a next group
Charles Chan188ebf52015-12-23 00:15:11 -08001041 * @param next the representation of the existing group-chain for this next objective
1042 */
1043 protected void addBucketToGroup(NextObjective nextObjective, NextGroup next) {
Saurav Das1a129a02016-11-18 15:21:57 -08001044 if (nextObjective.type() != NextObjective.Type.HASHED &&
1045 nextObjective.type() != NextObjective.Type.BROADCAST) {
Charles Chan188ebf52015-12-23 00:15:11 -08001046 log.warn("AddBuckets not applied to nextType:{} in dev:{} for next:{}",
Yi Tseng78f51f42017-02-02 13:54:58 -08001047 nextObjective.type(), deviceId, nextObjective.id());
Saurav Das1a129a02016-11-18 15:21:57 -08001048 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.UNSUPPORTED);
Charles Chan188ebf52015-12-23 00:15:11 -08001049 return;
1050 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001051
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001052 // first check to see if bucket being added is not a duplicate of an
1053 // existing bucket. If it is for an existing outport, then its a duplicate.
Yi Tseng78f51f42017-02-02 13:54:58 -08001054 Set<TrafficTreatment> duplicateBuckets = Sets.newHashSet();
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001055 List<Deque<GroupKey>> allActiveKeys = Ofdpa2Pipeline.appKryo.deserialize(next.data());
Yi Tseng78f51f42017-02-02 13:54:58 -08001056 Set<PortNumber> existingPorts = getExistingOutputPorts(allActiveKeys);
1057
1058 nextObjective.next().forEach(trafficTreatment -> {
1059 PortNumber portNumber = readOutPortFromTreatment(trafficTreatment);
1060
1061 if (portNumber == null) {
1062 return;
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001063 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001064
1065 if (existingPorts.contains(portNumber)) {
1066 duplicateBuckets.add(trafficTreatment);
1067 }
1068 });
1069
1070 if (!duplicateBuckets.isEmpty()) {
1071 log.warn("Some buckets {} already exists in next id {}, abort.",
1072 duplicateBuckets, nextObjective.id());
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001073 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001074
Saurav Das1a129a02016-11-18 15:21:57 -08001075 if (nextObjective.type() == NextObjective.Type.HASHED) {
Yi Tseng78f51f42017-02-02 13:54:58 -08001076 addBucketToHashGroup(nextObjective, allActiveKeys);
Saurav Das1a129a02016-11-18 15:21:57 -08001077 } else if (nextObjective.type() == NextObjective.Type.BROADCAST) {
Yi Tseng78f51f42017-02-02 13:54:58 -08001078 addBucketToBroadcastGroup(nextObjective, allActiveKeys);
Saurav Das1a129a02016-11-18 15:21:57 -08001079 }
1080 }
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001081
Yi Tseng78f51f42017-02-02 13:54:58 -08001082 private Set<PortNumber> getExistingOutputPorts(List<Deque<GroupKey>> allActiveKeys) {
1083 Set<PortNumber> existingPorts = Sets.newHashSet();
1084
1085 allActiveKeys.forEach(keyChain -> {
1086 GroupKey ifaceGroupKey = keyChain.peekLast();
1087 Group ifaceGroup = groupService.getGroup(deviceId, ifaceGroupKey);
1088 if (ifaceGroup != null && !ifaceGroup.buckets().buckets().isEmpty()) {
1089 ifaceGroup.buckets().buckets().forEach(bucket -> {
1090 PortNumber portNumber = readOutPortFromTreatment(bucket.treatment());
1091
1092 if (portNumber != null) {
1093 existingPorts.add(portNumber);
1094 }
1095 });
1096 }
1097 });
1098
1099 return existingPorts;
1100 }
1101
Saurav Das1a129a02016-11-18 15:21:57 -08001102 private void addBucketToHashGroup(NextObjective nextObjective,
Yi Tseng78f51f42017-02-02 13:54:58 -08001103 List<Deque<GroupKey>> allActiveKeys) {
Charles Chan188ebf52015-12-23 00:15:11 -08001104 // storage for all group keys in the chain of groups created
1105 List<Deque<GroupKey>> allGroupKeys = new ArrayList<>();
1106 List<GroupInfo> unsentGroups = new ArrayList<>();
Yi Tseng78f51f42017-02-02 13:54:58 -08001107 List<GroupBucket> newBuckets = Lists.newArrayList();
Charles Chan188ebf52015-12-23 00:15:11 -08001108 createHashBucketChains(nextObjective, allGroupKeys, unsentGroups);
1109
Yi Tseng78f51f42017-02-02 13:54:58 -08001110 // now we can create the buckets to add to the outermost L3 ECMP group
1111 newBuckets = generateNextGroupBuckets(unsentGroups, SELECT);
Charles Chan188ebf52015-12-23 00:15:11 -08001112
Saurav Das1a129a02016-11-18 15:21:57 -08001113 // retrieve the original L3 ECMP group
1114 Group l3ecmpGroup = retrieveTopLevelGroup(allActiveKeys, nextObjective.id());
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001115 if (l3ecmpGroup == null) {
Saurav Das1a129a02016-11-18 15:21:57 -08001116 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.GROUPMISSING);
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001117 return;
1118 }
Saurav Das1a129a02016-11-18 15:21:57 -08001119 GroupKey l3ecmpGroupKey = l3ecmpGroup.appCookie();
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001120 int l3ecmpGroupId = l3ecmpGroup.id().id();
Charles Chan188ebf52015-12-23 00:15:11 -08001121
1122 // Although GroupDescriptions are not necessary for adding buckets to
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001123 // existing groups, we still use one in the GroupChainElem. When the latter is
Charles Chan188ebf52015-12-23 00:15:11 -08001124 // processed, the info will be extracted for the bucketAdd call to groupService
1125 GroupDescription l3ecmpGroupDesc =
1126 new DefaultGroupDescription(
1127 deviceId,
Yi Tseng78f51f42017-02-02 13:54:58 -08001128 SELECT,
1129 new GroupBuckets(newBuckets),
Charles Chan188ebf52015-12-23 00:15:11 -08001130 l3ecmpGroupKey,
1131 l3ecmpGroupId,
1132 nextObjective.appId());
Yi Tseng78f51f42017-02-02 13:54:58 -08001133 GroupChainElem l3ecmpGce = new GroupChainElem(l3ecmpGroupDesc,
1134 unsentGroups.size(),
1135 true);
Charles Chan188ebf52015-12-23 00:15:11 -08001136
1137 // update original NextGroup with new bucket-chain
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001138 // If active keys shows only the top-level group without a chain of groups,
1139 // then it represents an empty group. Update by replacing empty chain.
Charles Chan188ebf52015-12-23 00:15:11 -08001140 Deque<GroupKey> newBucketChain = allGroupKeys.get(0);
1141 newBucketChain.addFirst(l3ecmpGroupKey);
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001142 if (allActiveKeys.size() == 1 && allActiveKeys.get(0).size() == 1) {
1143 allActiveKeys.clear();
1144 }
1145 allActiveKeys.add(newBucketChain);
1146 updatePendingNextObjective(l3ecmpGroupKey,
1147 new OfdpaNextGroup(allActiveKeys, nextObjective));
Yi Tseng78f51f42017-02-02 13:54:58 -08001148
Charles Chan188ebf52015-12-23 00:15:11 -08001149 log.debug("Adding to L3ECMP: device:{} gid:{} gkey:{} nextId:{}",
1150 deviceId, Integer.toHexString(l3ecmpGroupId),
1151 l3ecmpGroupKey, nextObjective.id());
Yi Tseng78f51f42017-02-02 13:54:58 -08001152
1153 unsentGroups.forEach(groupInfo -> {
1154 // send the innermost group
1155 log.debug("Sending innermost group {} in group chain on device {} ",
1156 Integer.toHexString(groupInfo.innerMostGroupDesc.givenGroupId()), deviceId);
1157 updatePendingGroups(groupInfo.nextGroupDesc.appCookie(), l3ecmpGce);
1158 groupService.addGroup(groupInfo.innerMostGroupDesc);
1159 });
1160
Saurav Das1a129a02016-11-18 15:21:57 -08001161 }
Charles Chan188ebf52015-12-23 00:15:11 -08001162
Saurav Das1a129a02016-11-18 15:21:57 -08001163 private void addBucketToBroadcastGroup(NextObjective nextObj,
Yi Tseng78f51f42017-02-02 13:54:58 -08001164 List<Deque<GroupKey>> allActiveKeys) {
Saurav Das1a129a02016-11-18 15:21:57 -08001165 VlanId assignedVlan = Ofdpa2Pipeline.readVlanFromSelector(nextObj.meta());
1166 if (assignedVlan == null) {
1167 log.warn("VLAN ID required by broadcast next obj is missing. "
1168 + "Aborting add bucket to broadcast group for next:{} in dev:{}",
1169 nextObj.id(), deviceId);
1170 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.BADPARAMS);
1171 return;
1172 }
1173
1174 List<GroupInfo> groupInfos = prepareL2InterfaceGroup(nextObj, assignedVlan);
1175
1176 IpPrefix ipDst = Ofdpa2Pipeline.readIpDstFromSelector(nextObj.meta());
1177 if (ipDst != null) {
1178 if (ipDst.isMulticast()) {
1179 addBucketToL3MulticastGroup(nextObj, allActiveKeys,
Yi Tseng78f51f42017-02-02 13:54:58 -08001180 groupInfos, assignedVlan);
Saurav Das1a129a02016-11-18 15:21:57 -08001181 } else {
1182 log.warn("Broadcast NextObj with non-multicast IP address {}", nextObj);
1183 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.BADPARAMS);
1184 return;
1185 }
1186 } else {
1187 addBucketToL2FloodGroup(nextObj, allActiveKeys,
Yi Tseng78f51f42017-02-02 13:54:58 -08001188 groupInfos, assignedVlan);
Saurav Das1a129a02016-11-18 15:21:57 -08001189 }
1190 }
1191
1192 private void addBucketToL2FloodGroup(NextObjective nextObj,
1193 List<Deque<GroupKey>> allActiveKeys,
1194 List<GroupInfo> groupInfos,
Yi Tseng78f51f42017-02-02 13:54:58 -08001195 VlanId assignedVlan) {
1196 Group l2FloodGroup = retrieveTopLevelGroup(allActiveKeys, nextObj.id());
1197
1198 if (l2FloodGroup == null) {
1199 log.warn("Can't find L2 flood group while adding bucket to it. NextObj = {}",
1200 nextObj);
Saurav Das1a129a02016-11-18 15:21:57 -08001201 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.GROUPMISSING);
1202 return;
1203 }
Saurav Das1a129a02016-11-18 15:21:57 -08001204
Yi Tseng78f51f42017-02-02 13:54:58 -08001205 GroupKey l2floodGroupKey = l2FloodGroup.appCookie();
1206 int l2floodGroupId = l2FloodGroup.id().id();
1207 List<GroupBucket> newBuckets = generateNextGroupBuckets(groupInfos, ALL);
1208
1209 GroupDescription l2FloodGroupDescription =
Saurav Das1a129a02016-11-18 15:21:57 -08001210 new DefaultGroupDescription(
1211 deviceId,
Yi Tseng78f51f42017-02-02 13:54:58 -08001212 ALL,
1213 new GroupBuckets(newBuckets),
Saurav Das1a129a02016-11-18 15:21:57 -08001214 l2floodGroupKey,
1215 l2floodGroupId,
1216 nextObj.appId());
Saurav Das1a129a02016-11-18 15:21:57 -08001217
Yi Tseng78f51f42017-02-02 13:54:58 -08001218 GroupChainElem l2FloodGroupChainElement =
1219 new GroupChainElem(l2FloodGroupDescription,
1220 groupInfos.size(),
1221 true);
1222
Saurav Das1a129a02016-11-18 15:21:57 -08001223 updatePendingNextObjective(l2floodGroupKey,
1224 new OfdpaNextGroup(allActiveKeys, nextObj));
Yi Tseng78f51f42017-02-02 13:54:58 -08001225
1226 //ensure assignedVlan applies to the chosen group
1227 VlanId floodGroupVlan = extractVlanIdFromGroupId(l2floodGroupId);
1228
1229 if (!floodGroupVlan.equals(assignedVlan)) {
1230 log.warn("VLAN ID {} does not match Flood group {} to which bucket is "
1231 + "being added, for next:{} in dev:{}. Abort.", assignedVlan,
1232 Integer.toHexString(l2floodGroupId), nextObj.id(), deviceId);
1233 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.BADPARAMS);
1234 return;
1235 }
1236
1237 groupInfos.forEach(groupInfo -> {
1238 // update original NextGroup with new bucket-chain
1239 // If active keys shows only the top-level group without a chain of groups,
1240 // then it represents an empty group. Update by replacing empty chain.
1241 Deque<GroupKey> newBucketChain = new ArrayDeque<>();
1242 newBucketChain.addFirst(groupInfo.nextGroupDesc.appCookie());
1243 newBucketChain.addFirst(l2floodGroupKey);
1244 if (allActiveKeys.size() == 1 && allActiveKeys.get(0).size() == 1) {
1245 allActiveKeys.clear();
1246 }
1247 allActiveKeys.add(newBucketChain);
1248
1249 log.debug("Adding to L2FLOOD: device:{} gid:{} gkey:{} nextId:{}",
1250 deviceId, Integer.toHexString(l2floodGroupId),
1251 l2floodGroupKey, nextObj.id());
1252 // send the innermost group
1253 log.debug("Sending innermost group {} in group chain on device {} ",
1254 Integer.toHexString(groupInfo.innerMostGroupDesc.givenGroupId()),
1255 deviceId);
1256
1257 updatePendingGroups(groupInfo.nextGroupDesc.appCookie(), l2FloodGroupChainElement);
1258
1259 DeviceId innerMostGroupDevice = groupInfo.innerMostGroupDesc.deviceId();
1260 GroupKey innerMostGroupKey = groupInfo.innerMostGroupDesc.appCookie();
1261 Group existsL2IGroup = groupService.getGroup(innerMostGroupDevice, innerMostGroupKey);
1262
1263 if (existsL2IGroup != null) {
1264 // group already exist
1265 processPendingAddGroupsOrNextObjs(innerMostGroupKey, true);
1266 } else {
1267 groupService.addGroup(groupInfo.innerMostGroupDesc);
1268 }
1269
1270 });
1271 }
1272
1273 private VlanId extractVlanIdFromGroupId(int groupId) {
1274 // Extract the 9th to 20th bit from group id as vlan id.
1275 short vlanId = (short) ((groupId & 0x0fff0000) >> 16);
1276 return VlanId.vlanId(vlanId);
1277 }
1278
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001279 private List<GroupBucket> generateNextGroupBuckets(List<GroupInfo> groupInfos,
1280 GroupDescription.Type bucketType) {
Yi Tseng78f51f42017-02-02 13:54:58 -08001281 List<GroupBucket> newBuckets = Lists.newArrayList();
1282
1283 groupInfos.forEach(groupInfo -> {
1284 GroupDescription groupDesc = groupInfo.nextGroupDesc;
1285 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
Yi Tsengfa394de2017-02-01 11:26:40 -08001286 treatmentBuilder.group(new GroupId(groupDesc.givenGroupId()));
Yi Tseng78f51f42017-02-02 13:54:58 -08001287 GroupBucket newBucket = null;
1288 switch (bucketType) {
1289 case ALL:
1290 newBucket =
1291 DefaultGroupBucket.createAllGroupBucket(treatmentBuilder.build());
1292 break;
1293 case INDIRECT:
1294 newBucket =
1295 DefaultGroupBucket.createIndirectGroupBucket(treatmentBuilder.build());
1296 break;
1297 case SELECT:
1298 newBucket =
1299 DefaultGroupBucket.createSelectGroupBucket(treatmentBuilder.build());
1300 break;
1301 case FAILOVER:
1302 // TODO support failover bucket type
1303 default:
1304 log.warn("Unknown bucket type: {}", bucketType);
1305 break;
1306 }
1307
1308 if (newBucket != null) {
1309 newBuckets.add(newBucket);
1310 }
1311
1312 });
1313
1314 return ImmutableList.copyOf(newBuckets);
Saurav Das1a129a02016-11-18 15:21:57 -08001315 }
1316
1317 private void addBucketToL3MulticastGroup(NextObjective nextObj,
1318 List<Deque<GroupKey>> allActiveKeys,
1319 List<GroupInfo> groupInfos,
Yi Tseng78f51f42017-02-02 13:54:58 -08001320 VlanId assignedVlan) {
1321 // create the buckets to add to the outermost L3 Multicast group
1322 List<GroupBucket> newBuckets = Lists.newArrayList();
1323 groupInfos.forEach(groupInfo -> {
1324 // Points to L3 interface group if there is one.
1325 // Otherwise points to L2 interface group directly.
1326 GroupDescription nextGroupDesc = (groupInfo.nextGroupDesc != null) ?
1327 groupInfo.nextGroupDesc : groupInfo.innerMostGroupDesc;
1328 TrafficTreatment.Builder treatmentBuidler = DefaultTrafficTreatment.builder();
Yi Tsengfa394de2017-02-01 11:26:40 -08001329 treatmentBuidler.group(new GroupId(nextGroupDesc.givenGroupId()));
Yi Tseng78f51f42017-02-02 13:54:58 -08001330 GroupBucket newBucket = DefaultGroupBucket.createAllGroupBucket(treatmentBuidler.build());
1331 newBuckets.add(newBucket);
1332 });
Saurav Das1a129a02016-11-18 15:21:57 -08001333
1334 // get the group being edited
1335 Group l3mcastGroup = retrieveTopLevelGroup(allActiveKeys, nextObj.id());
1336 if (l3mcastGroup == null) {
1337 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.GROUPMISSING);
1338 return;
1339 }
1340 GroupKey l3mcastGroupKey = l3mcastGroup.appCookie();
1341 int l3mcastGroupId = l3mcastGroup.id().id();
1342
1343 //ensure assignedVlan applies to the chosen group
Yi Tseng78f51f42017-02-02 13:54:58 -08001344 VlanId expectedVlan = extractVlanIdFromGroupId(l3mcastGroupId);
Saurav Das1a129a02016-11-18 15:21:57 -08001345 if (!expectedVlan.equals(assignedVlan)) {
1346 log.warn("VLAN ID {} does not match L3 Mcast group {} to which bucket is "
1347 + "being added, for next:{} in dev:{}. Abort.", assignedVlan,
1348 Integer.toHexString(l3mcastGroupId), nextObj.id(), deviceId);
1349 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.BADPARAMS);
1350 }
1351 GroupDescription l3mcastGroupDescription =
1352 new DefaultGroupDescription(
1353 deviceId,
Yi Tseng78f51f42017-02-02 13:54:58 -08001354 ALL,
1355 new GroupBuckets(newBuckets),
Saurav Das1a129a02016-11-18 15:21:57 -08001356 l3mcastGroupKey,
1357 l3mcastGroupId,
1358 nextObj.appId());
1359 GroupChainElem l3mcastGce = new GroupChainElem(l3mcastGroupDescription,
Yi Tseng78f51f42017-02-02 13:54:58 -08001360 groupInfos.size(), true);
Saurav Das1a129a02016-11-18 15:21:57 -08001361
Yi Tseng78f51f42017-02-02 13:54:58 -08001362 groupInfos.forEach(groupInfo -> {
1363 // update original NextGroup with new bucket-chain
1364 Deque<GroupKey> newBucketChain = new ArrayDeque<>();
1365 newBucketChain.addFirst(groupInfo.innerMostGroupDesc.appCookie());
1366 // Add L3 interface group to the chain if there is one.
1367 if (!groupInfo.nextGroupDesc.equals(groupInfo.innerMostGroupDesc)) {
1368 newBucketChain.addFirst(groupInfo.nextGroupDesc.appCookie());
1369 }
1370 newBucketChain.addFirst(l3mcastGroupKey);
1371 // If active keys shows only the top-level group without a chain of groups,
1372 // then it represents an empty group. Update by replacing empty chain.
1373 if (allActiveKeys.size() == 1 && allActiveKeys.get(0).size() == 1) {
1374 allActiveKeys.clear();
1375 }
1376 allActiveKeys.add(newBucketChain);
1377
1378 updatePendingGroups(groupInfo.nextGroupDesc.appCookie(), l3mcastGce);
1379 // Point next group to inner-most group, if any
1380 if (!groupInfo.nextGroupDesc.equals(groupInfo.innerMostGroupDesc)) {
1381 GroupChainElem innerGce = new GroupChainElem(groupInfo.nextGroupDesc,
1382 1, false);
1383 updatePendingGroups(groupInfo.innerMostGroupDesc.appCookie(), innerGce);
1384 }
1385 log.debug("Adding to L3MCAST: device:{} gid:{} gkey:{} nextId:{}",
1386 deviceId, Integer.toHexString(l3mcastGroupId),
1387 l3mcastGroupKey, nextObj.id());
1388 // send the innermost group
1389 log.debug("Sending innermost group {} in group chain on device {} ",
1390 Integer.toHexString(groupInfo.innerMostGroupDesc.givenGroupId()),
1391 deviceId);
1392 groupService.addGroup(groupInfo.innerMostGroupDesc);
1393
1394 });
1395
Saurav Das1a129a02016-11-18 15:21:57 -08001396 updatePendingNextObjective(l3mcastGroupKey,
1397 new OfdpaNextGroup(allActiveKeys, nextObj));
1398
Yi Tseng78f51f42017-02-02 13:54:58 -08001399
1400
Charles Chan188ebf52015-12-23 00:15:11 -08001401 }
1402
1403 /**
1404 * Removes the bucket in the top level group of a possible group-chain. Does
Saurav Das1a129a02016-11-18 15:21:57 -08001405 * not remove the groups in the group-chain pointed to by this bucket, as they
Charles Chan188ebf52015-12-23 00:15:11 -08001406 * may be in use (referenced by other groups) elsewhere.
1407 *
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001408 * @param nextObjective the bucket information for a next group
Charles Chan188ebf52015-12-23 00:15:11 -08001409 * @param next the representation of the existing group-chain for this next objective
1410 */
1411 protected void removeBucketFromGroup(NextObjective nextObjective, NextGroup next) {
Saurav Das1a129a02016-11-18 15:21:57 -08001412 if (nextObjective.type() != NextObjective.Type.HASHED &&
1413 nextObjective.type() != NextObjective.Type.BROADCAST) {
Charles Chan188ebf52015-12-23 00:15:11 -08001414 log.warn("RemoveBuckets not applied to nextType:{} in dev:{} for next:{}",
1415 nextObjective.type(), deviceId, nextObjective.id());
Saurav Das1a129a02016-11-18 15:21:57 -08001416 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.UNSUPPORTED);
Charles Chan188ebf52015-12-23 00:15:11 -08001417 return;
1418 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001419 Set<PortNumber> portsToRemove = Sets.newHashSet();
Charles Chan188ebf52015-12-23 00:15:11 -08001420 Collection<TrafficTreatment> treatments = nextObjective.next();
Yi Tseng78f51f42017-02-02 13:54:58 -08001421 for (TrafficTreatment treatment : treatments) {
1422 // find the bucket to remove by noting the outport, and figuring out the
1423 // top-level group in the group-chain that indirectly references the port
1424 PortNumber portToRemove = readOutPortFromTreatment(treatment);
1425 if (portToRemove == null) {
1426 log.warn("treatment {} of next objective {} has no outport.. cannot remove bucket"
1427 + "from group in dev: {}", treatment, nextObjective.id(), deviceId);
1428 } else {
1429 portsToRemove.add(portToRemove);
1430 }
1431 }
1432
1433 if (portsToRemove.isEmpty()) {
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001434 log.warn("next objective {} has no outport.. cannot remove bucket"
Yi Tseng78f51f42017-02-02 13:54:58 -08001435 + "from group in dev: {}", nextObjective.id(), deviceId);
Saurav Das1a129a02016-11-18 15:21:57 -08001436 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.BADPARAMS);
Charles Chan188ebf52015-12-23 00:15:11 -08001437 }
1438
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001439 List<Deque<GroupKey>> allActiveKeys = Ofdpa2Pipeline.appKryo.deserialize(next.data());
Yi Tseng78f51f42017-02-02 13:54:58 -08001440 List<Deque<GroupKey>> chainsToRemove = Lists.newArrayList();
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001441 for (Deque<GroupKey> gkeys : allActiveKeys) {
1442 // last group in group chain should have a single bucket pointing to port
Yi Tseng78f51f42017-02-02 13:54:58 -08001443
Charles Chan188ebf52015-12-23 00:15:11 -08001444 GroupKey groupWithPort = gkeys.peekLast();
1445 Group group = groupService.getGroup(deviceId, groupWithPort);
1446 if (group == null) {
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001447 log.warn("Inconsistent group chain found when removing bucket"
1448 + "for next:{} in dev:{}", nextObjective.id(), deviceId);
Charles Chan188ebf52015-12-23 00:15:11 -08001449 continue;
1450 }
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001451 PortNumber pout = readOutPortFromTreatment(
1452 group.buckets().buckets().get(0).treatment());
Yi Tseng78f51f42017-02-02 13:54:58 -08001453 if (portsToRemove.contains(pout)) {
1454 chainsToRemove.add(gkeys);
Charles Chan188ebf52015-12-23 00:15:11 -08001455 }
Charles Chan188ebf52015-12-23 00:15:11 -08001456 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001457
1458 if (chainsToRemove.isEmpty()) {
Charles Chan188ebf52015-12-23 00:15:11 -08001459 log.warn("Could not find appropriate group-chain for removing bucket"
1460 + " for next id {} in dev:{}", nextObjective.id(), deviceId);
Saurav Das1a129a02016-11-18 15:21:57 -08001461 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.BADPARAMS);
1462 return;
Charles Chan188ebf52015-12-23 00:15:11 -08001463 }
Saurav Das1a129a02016-11-18 15:21:57 -08001464
Yi Tseng78f51f42017-02-02 13:54:58 -08001465 List<GroupBucket> bucketsToRemove = Lists.newArrayList();
1466 //first group key is the one we want to modify
1467 GroupKey modGroupKey = chainsToRemove.get(0).peekFirst();
Saurav Das1a129a02016-11-18 15:21:57 -08001468 Group modGroup = groupService.getGroup(deviceId, modGroupKey);
Yi Tseng78f51f42017-02-02 13:54:58 -08001469
1470 for (Deque<GroupKey> foundChain : chainsToRemove) {
1471 //second group key is the one we wish to remove the reference to
1472 if (foundChain.size() < 2) {
1473 // additional check to make sure second group key exist in
1474 // the chain.
1475 log.warn("Can't find second group key from chain {}",
1476 foundChain);
1477 continue;
Saurav Das1a129a02016-11-18 15:21:57 -08001478 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001479 GroupKey pointedGroupKey = foundChain.stream().collect(Collectors.toList()).get(1);
1480
1481 Group pointedGroup = groupService.getGroup(deviceId, pointedGroupKey);
1482
1483 if (pointedGroup == null) {
1484 continue;
1485 }
1486
1487 GroupBucket bucket;
1488 if (nextObjective.type() == NextObjective.Type.HASHED) {
1489 bucket = DefaultGroupBucket.createSelectGroupBucket(
1490 DefaultTrafficTreatment.builder()
1491 .group(pointedGroup.id())
1492 .build());
1493 } else {
1494 bucket = DefaultGroupBucket.createAllGroupBucket(
1495 DefaultTrafficTreatment.builder()
1496 .group(pointedGroup.id())
1497 .build());
1498 }
1499
1500 bucketsToRemove.add(bucket);
Saurav Das1a129a02016-11-18 15:21:57 -08001501 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001502
1503 GroupBuckets removeBuckets = new GroupBuckets(bucketsToRemove);
1504 List<String> pointedGroupIds; // for debug log
1505 pointedGroupIds = bucketsToRemove.stream()
1506 .map(GroupBucket::treatment)
1507 .map(TrafficTreatment::allInstructions)
1508 .flatMap(List::stream)
1509 .filter(inst -> inst instanceof Instructions.GroupInstruction)
1510 .map(inst -> (Instructions.GroupInstruction) inst)
1511 .map(Instructions.GroupInstruction::groupId)
1512 .map(GroupId::id)
1513 .map(Integer::toHexString)
1514 .map(id -> HEX_PREFIX + id)
1515 .collect(Collectors.toList());
1516
1517
1518
1519 log.debug("Removing buckets from group id 0x{} pointing to group id(s) {} "
Saurav Das1a129a02016-11-18 15:21:57 -08001520 + "for next id {} in device {}", Integer.toHexString(modGroup.id().id()),
Yi Tseng78f51f42017-02-02 13:54:58 -08001521 pointedGroupIds, nextObjective.id(), deviceId);
1522 addPendingUpdateNextObjective(modGroupKey, nextObjective);
Saurav Das1a129a02016-11-18 15:21:57 -08001523 groupService.removeBucketsFromGroup(deviceId, modGroupKey,
1524 removeBuckets, modGroupKey,
1525 nextObjective.appId());
1526 // update store
Yi Tsengeeb3dc12017-03-15 10:55:50 -07001527 allActiveKeys.removeAll(chainsToRemove);
1528 // If no buckets in the group, then retain an entry for the
1529 // top level group which still exists.
1530 if (allActiveKeys.isEmpty()) {
Saurav Das1a129a02016-11-18 15:21:57 -08001531 ArrayDeque<GroupKey> top = new ArrayDeque<>();
1532 top.add(modGroupKey);
1533 allActiveKeys.add(top);
1534 }
Saurav Das1a129a02016-11-18 15:21:57 -08001535 flowObjectiveStore.putNextGroup(nextObjective.id(),
1536 new OfdpaNextGroup(allActiveKeys,
1537 nextObjective));
Charles Chan188ebf52015-12-23 00:15:11 -08001538 }
1539
1540 /**
1541 * Removes all groups in multiple possible group-chains that represent the next
1542 * objective.
1543 *
1544 * @param nextObjective the next objective to remove
1545 * @param next the NextGroup that represents the existing group-chain for
1546 * this next objective
1547 */
1548 protected void removeGroup(NextObjective nextObjective, NextGroup next) {
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001549 List<Deque<GroupKey>> allActiveKeys = Ofdpa2Pipeline.appKryo.deserialize(next.data());
Charles Chanfc5c7802016-05-17 13:13:55 -07001550
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001551 List<GroupKey> groupKeys = allActiveKeys.stream()
Charles Chanfc5c7802016-05-17 13:13:55 -07001552 .map(Deque::getFirst).collect(Collectors.toList());
1553 pendingRemoveNextObjectives.put(nextObjective, groupKeys);
1554
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001555 allActiveKeys.forEach(groupChain -> groupChain.forEach(groupKey ->
Charles Chan188ebf52015-12-23 00:15:11 -08001556 groupService.removeGroup(deviceId, groupKey, nextObjective.appId())));
1557 flowObjectiveStore.removeNextGroup(nextObjective.id());
1558 }
1559
Saurav Das8be4e3a2016-03-11 17:19:07 -08001560 //////////////////////////////////////
1561 // Helper Methods and Classes
1562 //////////////////////////////////////
1563
Pier Ventre140a8942016-11-02 07:26:38 -07001564 protected void updatePendingNextObjective(GroupKey key, OfdpaNextGroup value) {
Saurav Das8be4e3a2016-03-11 17:19:07 -08001565 List<OfdpaNextGroup> nextList = new CopyOnWriteArrayList<OfdpaNextGroup>();
1566 nextList.add(value);
Charles Chanfc5c7802016-05-17 13:13:55 -07001567 List<OfdpaNextGroup> ret = pendingAddNextObjectives.asMap()
Saurav Das8be4e3a2016-03-11 17:19:07 -08001568 .putIfAbsent(key, nextList);
1569 if (ret != null) {
1570 ret.add(value);
1571 }
1572 }
1573
Charles Chan425854b2016-04-11 15:32:12 -07001574 protected void updatePendingGroups(GroupKey gkey, GroupChainElem gce) {
Saurav Das8be4e3a2016-03-11 17:19:07 -08001575 Set<GroupChainElem> gceSet = Collections.newSetFromMap(
1576 new ConcurrentHashMap<GroupChainElem, Boolean>());
1577 gceSet.add(gce);
1578 Set<GroupChainElem> retval = pendingGroups.putIfAbsent(gkey, gceSet);
1579 if (retval != null) {
1580 retval.add(gce);
1581 }
1582 }
1583
Yi Tseng78f51f42017-02-02 13:54:58 -08001584 private void addPendingUpdateNextObjective(GroupKey groupKey, NextObjective nextObjective) {
1585 pendingUpdateNextObjectives.compute(groupKey, (gKey, nextObjs) -> {
1586 if (nextObjs != null) {
1587 nextObjs.add(nextObjective);
1588 } else {
1589 nextObjs = Sets.newHashSet(nextObjective);
1590 }
1591 return nextObjs;
1592 });
1593 }
1594
Charles Chan188ebf52015-12-23 00:15:11 -08001595 /**
1596 * Processes next element of a group chain. Assumption is that if this
1597 * group points to another group, the latter has already been created
1598 * and this driver has received notification for it. A second assumption is
1599 * that if there is another group waiting for this group then the appropriate
1600 * stores already have the information to act upon the notification for the
1601 * creation of this group.
1602 * <p>
1603 * The processing of the GroupChainElement depends on the number of groups
1604 * this element is waiting on. For all group types other than SIMPLE, a
1605 * GroupChainElement could be waiting on multiple groups.
1606 *
1607 * @param gce the group chain element to be processed next
1608 */
1609 private void processGroupChain(GroupChainElem gce) {
1610 int waitOnGroups = gce.decrementAndGetGroupsWaitedOn();
1611 if (waitOnGroups != 0) {
1612 log.debug("GCE: {} not ready to be processed", gce);
1613 return;
1614 }
1615 log.debug("GCE: {} ready to be processed", gce);
1616 if (gce.addBucketToGroup) {
1617 groupService.addBucketsToGroup(gce.groupDescription.deviceId(),
1618 gce.groupDescription.appCookie(),
1619 gce.groupDescription.buckets(),
1620 gce.groupDescription.appCookie(),
1621 gce.groupDescription.appId());
1622 } else {
1623 groupService.addGroup(gce.groupDescription);
1624 }
1625 }
1626
1627 private class GroupChecker implements Runnable {
1628 @Override
1629 public void run() {
1630 Set<GroupKey> keys = pendingGroups.keySet().stream()
1631 .filter(key -> groupService.getGroup(deviceId, key) != null)
1632 .collect(Collectors.toSet());
Charles Chanfc5c7802016-05-17 13:13:55 -07001633 Set<GroupKey> otherkeys = pendingAddNextObjectives.asMap().keySet().stream()
Charles Chan188ebf52015-12-23 00:15:11 -08001634 .filter(otherkey -> groupService.getGroup(deviceId, otherkey) != null)
1635 .collect(Collectors.toSet());
1636 keys.addAll(otherkeys);
1637
Sho SHIMIZUa09e1bb2016-08-01 14:25:25 -07001638 keys.forEach(key ->
Charles Chanfc5c7802016-05-17 13:13:55 -07001639 processPendingAddGroupsOrNextObjs(key, false));
Charles Chan188ebf52015-12-23 00:15:11 -08001640 }
1641 }
1642
Saurav Das8be4e3a2016-03-11 17:19:07 -08001643 private class InnerGroupListener implements GroupListener {
1644 @Override
1645 public void event(GroupEvent event) {
1646 log.trace("received group event of type {}", event.type());
Charles Chanfc5c7802016-05-17 13:13:55 -07001647 switch (event.type()) {
1648 case GROUP_ADDED:
1649 processPendingAddGroupsOrNextObjs(event.subject().appCookie(), true);
1650 break;
1651 case GROUP_REMOVED:
1652 processPendingRemoveNextObjs(event.subject().appCookie());
1653 break;
Yi Tseng78f51f42017-02-02 13:54:58 -08001654 case GROUP_UPDATED:
1655 processPendingUpdateNextObjs(event.subject().appCookie());
1656 break;
Charles Chanfc5c7802016-05-17 13:13:55 -07001657 default:
1658 break;
Saurav Das8be4e3a2016-03-11 17:19:07 -08001659 }
1660 }
1661 }
1662
Yi Tseng78f51f42017-02-02 13:54:58 -08001663 private void processPendingUpdateNextObjs(GroupKey groupKey) {
1664
1665 pendingUpdateNextObjectives.compute(groupKey, (gKey, nextObjs) -> {
1666 if (nextObjs != null) {
1667
1668 nextObjs.forEach(nextObj -> {
1669 log.debug("Group {} updated, update pending next objective {}.",
1670 groupKey, nextObj);
1671
1672 Ofdpa2Pipeline.pass(nextObj);
1673 });
1674 }
1675
1676 return Sets.newHashSet();
1677 });
1678 }
1679
Charles Chanfc5c7802016-05-17 13:13:55 -07001680 private void processPendingAddGroupsOrNextObjs(GroupKey key, boolean added) {
Charles Chan188ebf52015-12-23 00:15:11 -08001681 //first check for group chain
1682 Set<GroupChainElem> gceSet = pendingGroups.remove(key);
1683 if (gceSet != null) {
1684 for (GroupChainElem gce : gceSet) {
Charles Chan216e3c82016-04-23 14:48:16 -07001685 log.debug("Group service {} group key {} in device {}. "
Saurav Das0fd79d92016-03-07 10:58:36 -08001686 + "Processing next group in group chain with group id 0x{}",
Charles Chan188ebf52015-12-23 00:15:11 -08001687 (added) ? "ADDED" : "processed",
1688 key, deviceId,
1689 Integer.toHexString(gce.groupDescription.givenGroupId()));
1690 processGroupChain(gce);
1691 }
1692 } else {
1693 // otherwise chain complete - check for waiting nextObjectives
Charles Chanfc5c7802016-05-17 13:13:55 -07001694 List<OfdpaNextGroup> nextGrpList = pendingAddNextObjectives.getIfPresent(key);
Charles Chan188ebf52015-12-23 00:15:11 -08001695 if (nextGrpList != null) {
Charles Chanfc5c7802016-05-17 13:13:55 -07001696 pendingAddNextObjectives.invalidate(key);
Charles Chan188ebf52015-12-23 00:15:11 -08001697 nextGrpList.forEach(nextGrp -> {
Charles Chan216e3c82016-04-23 14:48:16 -07001698 log.debug("Group service {} group key {} in device:{}. "
Saurav Das0fd79d92016-03-07 10:58:36 -08001699 + "Done implementing next objective: {} <<-->> gid:0x{}",
Charles Chan188ebf52015-12-23 00:15:11 -08001700 (added) ? "ADDED" : "processed",
1701 key, deviceId, nextGrp.nextObjective().id(),
1702 Integer.toHexString(groupService.getGroup(deviceId, key)
1703 .givenGroupId()));
Charles Chan361154b2016-03-24 10:23:39 -07001704 Ofdpa2Pipeline.pass(nextGrp.nextObjective());
Charles Chan188ebf52015-12-23 00:15:11 -08001705 flowObjectiveStore.putNextGroup(nextGrp.nextObjective().id(), nextGrp);
1706 // check if addBuckets waiting for this completion
1707 NextObjective pendBkt = pendingBuckets
1708 .remove(nextGrp.nextObjective().id());
1709 if (pendBkt != null) {
1710 addBucketToGroup(pendBkt, nextGrp);
1711 }
1712 });
1713 }
1714 }
1715 }
1716
Charles Chanfc5c7802016-05-17 13:13:55 -07001717 private void processPendingRemoveNextObjs(GroupKey key) {
1718 pendingRemoveNextObjectives.asMap().forEach((nextObjective, groupKeys) -> {
1719 if (groupKeys.isEmpty()) {
1720 pendingRemoveNextObjectives.invalidate(nextObjective);
1721 Ofdpa2Pipeline.pass(nextObjective);
1722 } else {
1723 groupKeys.remove(key);
1724 }
1725 });
1726 }
1727
Charles Chan425854b2016-04-11 15:32:12 -07001728 protected int getNextAvailableIndex() {
Saurav Das8be4e3a2016-03-11 17:19:07 -08001729 return (int) nextIndex.incrementAndGet();
1730 }
1731
Charles Chane849c192016-01-11 18:28:54 -08001732 /**
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001733 * Returns the outport in a traffic treatment.
1734 *
1735 * @param tt the treatment
1736 * @return the PortNumber for the outport or null
1737 */
1738 protected static PortNumber readOutPortFromTreatment(TrafficTreatment tt) {
1739 for (Instruction ins : tt.allInstructions()) {
1740 if (ins.type() == Instruction.Type.OUTPUT) {
1741 return ((Instructions.OutputInstruction) ins).port();
1742 }
1743 }
1744 return null;
1745 }
1746
1747 /**
Charles Chane849c192016-01-11 18:28:54 -08001748 * Returns a hash as the L2 Interface Group Key.
1749 *
1750 * Keep the lower 6-bit for port since port number usually smaller than 64.
1751 * Hash other information into remaining 28 bits.
1752 *
1753 * @param deviceId Device ID
1754 * @param vlanId VLAN ID
1755 * @param portNumber Port number
1756 * @return L2 interface group key
1757 */
Pier Ventre140a8942016-11-02 07:26:38 -07001758 protected int l2InterfaceGroupKey(DeviceId deviceId, VlanId vlanId, long portNumber) {
Charles Chane849c192016-01-11 18:28:54 -08001759 int portLowerBits = (int) portNumber & PORT_LOWER_BITS_MASK;
1760 long portHigherBits = portNumber & PORT_HIGHER_BITS_MASK;
Charles Chand0fd5dc2016-02-16 23:14:49 -08001761 int hash = Objects.hash(deviceId, vlanId, portHigherBits);
Charles Chane849c192016-01-11 18:28:54 -08001762 return L2_INTERFACE_TYPE | (TYPE_MASK & hash << 6) | portLowerBits;
1763 }
1764
Saurav Das1a129a02016-11-18 15:21:57 -08001765 private Group retrieveTopLevelGroup(List<Deque<GroupKey>> allActiveKeys,
1766 int nextid) {
Yi Tseng78f51f42017-02-02 13:54:58 -08001767 GroupKey topLevelGroupKey;
Saurav Das1a129a02016-11-18 15:21:57 -08001768 if (!allActiveKeys.isEmpty()) {
1769 topLevelGroupKey = allActiveKeys.get(0).peekFirst();
1770 } else {
1771 log.warn("Could not determine top level group while processing"
1772 + "next:{} in dev:{}", nextid, deviceId);
1773 return null;
1774 }
1775 Group topGroup = groupService.getGroup(deviceId, topLevelGroupKey);
1776 if (topGroup == null) {
1777 log.warn("Could not find top level group while processing "
1778 + "next:{} in dev:{}", nextid, deviceId);
1779 }
1780 return topGroup;
1781 }
1782
Charles Chan188ebf52015-12-23 00:15:11 -08001783 /**
1784 * Utility class for moving group information around.
Saurav Das1a129a02016-11-18 15:21:57 -08001785 *
1786 * Example: Suppose we are trying to create a group-chain A-B-C-D, where
1787 * A is the top level group, and D is the inner-most group, typically L2 Interface.
1788 * The innerMostGroupDesc is always D. At various stages of the creation
1789 * process the nextGroupDesc may be C or B. The nextGroupDesc exists to
1790 * inform the referencing group about which group it needs to point to,
1791 * and wait for. In some cases the group chain may simply be A-B. In this case,
1792 * both innerMostGroupDesc and nextGroupDesc will be B.
Charles Chan188ebf52015-12-23 00:15:11 -08001793 */
Charles Chan425854b2016-04-11 15:32:12 -07001794 protected class GroupInfo {
Charles Chan5b9df8d2016-03-28 22:21:40 -07001795 /**
1796 * Description of the inner-most group of the group chain.
1797 * It is always an L2 interface group.
1798 */
1799 private GroupDescription innerMostGroupDesc;
Charles Chan188ebf52015-12-23 00:15:11 -08001800
Charles Chan5b9df8d2016-03-28 22:21:40 -07001801 /**
1802 * Description of the next group in the group chain.
1803 * It can be L2 interface, L3 interface, L3 unicast, L3 VPN group.
Saurav Das1a129a02016-11-18 15:21:57 -08001804 * It is possible that nextGroupDesc is the same as the innerMostGroup.
Charles Chan5b9df8d2016-03-28 22:21:40 -07001805 */
1806 private GroupDescription nextGroupDesc;
1807
1808 GroupInfo(GroupDescription innerMostGroupDesc, GroupDescription nextGroupDesc) {
1809 this.innerMostGroupDesc = innerMostGroupDesc;
1810 this.nextGroupDesc = nextGroupDesc;
Charles Chan188ebf52015-12-23 00:15:11 -08001811 }
Pier Ventre140a8942016-11-02 07:26:38 -07001812
1813 /**
1814 * Getter for innerMostGroupDesc.
1815 *
1816 * @return the inner most group description
1817 */
1818 public GroupDescription getInnerMostGroupDesc() {
1819 return innerMostGroupDesc;
1820 }
1821
1822 /**
1823 * Getter for the next group description.
1824 *
1825 * @return the next group description
1826 */
1827 public GroupDescription getNextGroupDesc() {
1828 return nextGroupDesc;
1829 }
Charles Chan188ebf52015-12-23 00:15:11 -08001830 }
1831
1832 /**
1833 * Represents an entire group-chain that implements a Next-Objective from
1834 * the application. The objective is represented as a list of deques, where
1835 * each deque is a separate chain of groups.
1836 * <p>
1837 * For example, an ECMP group with 3 buckets, where each bucket points to
1838 * a group chain of L3 Unicast and L2 interface groups will look like this:
1839 * <ul>
1840 * <li>List[0] is a Deque of GroupKeyECMP(first)-GroupKeyL3(middle)-GroupKeyL2(last)
1841 * <li>List[1] is a Deque of GroupKeyECMP(first)-GroupKeyL3(middle)-GroupKeyL2(last)
1842 * <li>List[2] is a Deque of GroupKeyECMP(first)-GroupKeyL3(middle)-GroupKeyL2(last)
1843 * </ul>
1844 * where the first element of each deque is the same, representing the
1845 * top level ECMP group, while every other element represents a unique groupKey.
1846 * <p>
1847 * Also includes information about the next objective that
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001848 * resulted in these group-chains.
Charles Chan188ebf52015-12-23 00:15:11 -08001849 *
1850 */
1851 protected class OfdpaNextGroup implements NextGroup {
1852 private final NextObjective nextObj;
1853 private final List<Deque<GroupKey>> gkeys;
1854
1855 public OfdpaNextGroup(List<Deque<GroupKey>> gkeys, NextObjective nextObj) {
Charles Chan188ebf52015-12-23 00:15:11 -08001856 this.nextObj = nextObj;
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001857 this.gkeys = gkeys;
Charles Chan188ebf52015-12-23 00:15:11 -08001858 }
1859
1860 public NextObjective nextObjective() {
1861 return nextObj;
1862 }
1863
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001864 public List<Deque<GroupKey>> groupKeys() {
1865 return gkeys;
1866 }
1867
Charles Chan188ebf52015-12-23 00:15:11 -08001868 @Override
1869 public byte[] data() {
Charles Chan361154b2016-03-24 10:23:39 -07001870 return Ofdpa2Pipeline.appKryo.serialize(gkeys);
Charles Chan188ebf52015-12-23 00:15:11 -08001871 }
1872 }
1873
1874 /**
1875 * Represents a group element that is part of a chain of groups.
1876 * Stores enough information to create a Group Description to add the group
1877 * to the switch by requesting the Group Service. Objects instantiating this
1878 * class are meant to be temporary and live as long as it is needed to wait for
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001879 * referenced groups in the group chain to be created.
Charles Chan188ebf52015-12-23 00:15:11 -08001880 */
Charles Chan425854b2016-04-11 15:32:12 -07001881 protected class GroupChainElem {
Charles Chan188ebf52015-12-23 00:15:11 -08001882 private GroupDescription groupDescription;
1883 private AtomicInteger waitOnGroups;
1884 private boolean addBucketToGroup;
1885
1886 GroupChainElem(GroupDescription groupDescription, int waitOnGroups,
1887 boolean addBucketToGroup) {
1888 this.groupDescription = groupDescription;
1889 this.waitOnGroups = new AtomicInteger(waitOnGroups);
1890 this.addBucketToGroup = addBucketToGroup;
1891 }
1892
1893 /**
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001894 * This method atomically decrements the counter for the number of
Charles Chan188ebf52015-12-23 00:15:11 -08001895 * groups this GroupChainElement is waiting on, for notifications from
1896 * the Group Service. When this method returns a value of 0, this
1897 * GroupChainElement is ready to be processed.
1898 *
1899 * @return integer indication of the number of notifications being waited on
1900 */
1901 int decrementAndGetGroupsWaitedOn() {
1902 return waitOnGroups.decrementAndGet();
1903 }
1904
1905 @Override
1906 public String toString() {
1907 return (Integer.toHexString(groupDescription.givenGroupId()) +
1908 " groupKey: " + groupDescription.appCookie() +
1909 " waiting-on-groups: " + waitOnGroups.get() +
1910 " addBucketToGroup: " + addBucketToGroup +
1911 " device: " + deviceId);
1912 }
1913 }
Pier Ventre140a8942016-11-02 07:26:38 -07001914
1915 /**
1916 * Helper enum to handle the different MPLS group
1917 * types.
1918 */
1919 protected enum OfdpaMplsGroupSubType {
1920
1921 MPLS_INTF((short) 0),
1922
1923 L2_VPN((short) 1),
1924
1925 L3_VPN((short) 2),
1926
1927 MPLS_TUNNEL_LABEL_1((short) 3),
1928
1929 MPLS_TUNNEL_LABEL_2((short) 4),
1930
1931 MPLS_SWAP_LABEL((short) 5),
1932
1933 MPLS_ECMP((short) 8);
1934
1935 private short value;
1936
1937 public static final int OFDPA_GROUP_TYPE_SHIFT = 28;
1938 public static final int OFDPA_MPLS_SUBTYPE_SHIFT = 24;
1939
1940 OfdpaMplsGroupSubType(short value) {
1941 this.value = value;
1942 }
1943
1944 /**
1945 * Gets the value as an short.
1946 *
1947 * @return the value as an short
1948 */
1949 public short getValue() {
1950 return this.value;
1951 }
1952
1953 }
1954
1955 /**
1956 * Creates MPLS Label group id given a sub type and
1957 * the index.
1958 *
1959 * @param subType the MPLS Label group sub type
1960 * @param index the index of the group
1961 * @return the OFDPA group id
1962 */
1963 public Integer makeMplsLabelGroupId(OfdpaMplsGroupSubType subType, int index) {
1964 index = index & 0x00FFFFFF;
1965 return index | (9 << OFDPA_GROUP_TYPE_SHIFT) | (subType.value << OFDPA_MPLS_SUBTYPE_SHIFT);
1966 }
1967
1968 /**
1969 * Creates MPLS Forwarding group id given a sub type and
1970 * the index.
1971 *
1972 * @param subType the MPLS forwarding group sub type
1973 * @param index the index of the group
1974 * @return the OFDPA group id
1975 */
1976 public Integer makeMplsForwardingGroupId(OfdpaMplsGroupSubType subType, int index) {
1977 index = index & 0x00FFFFFF;
1978 return index | (10 << OFDPA_GROUP_TYPE_SHIFT) | (subType.value << OFDPA_MPLS_SUBTYPE_SHIFT);
1979 }
Charles Chan188ebf52015-12-23 00:15:11 -08001980}