blob: c73316c5c5c7429a6d9853cdcfcec08fc80e9386 [file] [log] [blame]
Brian O'Connor7cbbbb72016-04-09 02:13:23 -07001/*
2 * Copyright 2016-present Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Charles Chan188ebf52015-12-23 00:15:11 -080016package org.onosproject.driver.pipeline;
17
18import com.google.common.cache.Cache;
19import com.google.common.cache.CacheBuilder;
20import com.google.common.cache.RemovalCause;
21import com.google.common.cache.RemovalNotification;
Charles Chan5b9df8d2016-03-28 22:21:40 -070022import com.google.common.collect.ImmutableList;
23import com.google.common.collect.Lists;
Yi Tseng78f51f42017-02-02 13:54:58 -080024import com.google.common.collect.Sets;
Charles Chan188ebf52015-12-23 00:15:11 -080025import org.onlab.osgi.ServiceDirectory;
Charles Chan5b9df8d2016-03-28 22:21:40 -070026import org.onlab.packet.IpPrefix;
Charles Chan5270ed02016-01-30 23:22:37 -080027import org.onlab.packet.MacAddress;
Charles Chan188ebf52015-12-23 00:15:11 -080028import org.onlab.packet.MplsLabel;
29import org.onlab.packet.VlanId;
30import org.onosproject.core.ApplicationId;
Yi Tseng78f51f42017-02-02 13:54:58 -080031import org.onosproject.core.GroupId;
Charles Chan32562522016-04-07 14:37:14 -070032import org.onosproject.driver.extensions.OfdpaSetVlanVid;
Charles Chan188ebf52015-12-23 00:15:11 -080033import org.onosproject.net.DeviceId;
34import org.onosproject.net.PortNumber;
35import org.onosproject.net.behaviour.NextGroup;
36import org.onosproject.net.behaviour.PipelinerContext;
37import org.onosproject.net.flow.DefaultTrafficTreatment;
38import org.onosproject.net.flow.TrafficSelector;
39import org.onosproject.net.flow.TrafficTreatment;
40import org.onosproject.net.flow.criteria.Criterion;
Pier Ventre42287df2016-11-09 14:17:26 -080041import org.onosproject.net.flow.criteria.TunnelIdCriterion;
Charles Chan188ebf52015-12-23 00:15:11 -080042import org.onosproject.net.flow.criteria.VlanIdCriterion;
43import org.onosproject.net.flow.instructions.Instruction;
44import org.onosproject.net.flow.instructions.Instructions;
45import org.onosproject.net.flow.instructions.L2ModificationInstruction;
Yi Tseng47f82dc2017-03-05 22:48:39 -080046import org.onosproject.net.flowobjective.DefaultNextObjective;
Charles Chan188ebf52015-12-23 00:15:11 -080047import org.onosproject.net.flowobjective.FlowObjectiveStore;
48import org.onosproject.net.flowobjective.NextObjective;
Yi Tseng47f82dc2017-03-05 22:48:39 -080049import org.onosproject.net.flowobjective.ObjectiveContext;
Charles Chan188ebf52015-12-23 00:15:11 -080050import org.onosproject.net.flowobjective.ObjectiveError;
51import org.onosproject.net.group.DefaultGroupBucket;
52import org.onosproject.net.group.DefaultGroupDescription;
53import org.onosproject.net.group.DefaultGroupKey;
54import org.onosproject.net.group.Group;
55import org.onosproject.net.group.GroupBucket;
56import org.onosproject.net.group.GroupBuckets;
57import org.onosproject.net.group.GroupDescription;
58import org.onosproject.net.group.GroupEvent;
59import org.onosproject.net.group.GroupKey;
60import org.onosproject.net.group.GroupListener;
61import org.onosproject.net.group.GroupService;
Saurav Das8be4e3a2016-03-11 17:19:07 -080062import org.onosproject.store.service.AtomicCounter;
63import org.onosproject.store.service.StorageService;
Charles Chan188ebf52015-12-23 00:15:11 -080064import org.slf4j.Logger;
65
66import java.util.ArrayDeque;
67import java.util.ArrayList;
68import java.util.Collection;
69import java.util.Collections;
70import java.util.Deque;
71import java.util.List;
Charles Chand0fd5dc2016-02-16 23:14:49 -080072import java.util.Objects;
Charles Chan188ebf52015-12-23 00:15:11 -080073import java.util.Set;
74import java.util.concurrent.ConcurrentHashMap;
75import java.util.concurrent.CopyOnWriteArrayList;
76import java.util.concurrent.Executors;
77import java.util.concurrent.ScheduledExecutorService;
78import java.util.concurrent.TimeUnit;
79import java.util.concurrent.atomic.AtomicInteger;
80import java.util.stream.Collectors;
81
82import static org.onlab.util.Tools.groupedThreads;
Pier Ventre140a8942016-11-02 07:26:38 -070083import static org.onosproject.driver.pipeline.Ofdpa2GroupHandler.OfdpaMplsGroupSubType.OFDPA_GROUP_TYPE_SHIFT;
84import static org.onosproject.driver.pipeline.Ofdpa2GroupHandler.OfdpaMplsGroupSubType.OFDPA_MPLS_SUBTYPE_SHIFT;
85import static org.onosproject.driver.pipeline.Ofdpa2Pipeline.isNotMplsBos;
Pier Ventre42287df2016-11-09 14:17:26 -080086import static org.onosproject.net.flow.criteria.Criterion.Type.TUNNEL_ID;
Pier Ventre140a8942016-11-02 07:26:38 -070087import static org.onosproject.net.flow.criteria.Criterion.Type.VLAN_VID;
88import static org.onosproject.net.flowobjective.NextObjective.Type.HASHED;
Yi Tseng78f51f42017-02-02 13:54:58 -080089import static org.onosproject.net.group.GroupDescription.Type.ALL;
90import static org.onosproject.net.group.GroupDescription.Type.SELECT;
Charles Chan188ebf52015-12-23 00:15:11 -080091import static org.slf4j.LoggerFactory.getLogger;
92
93/**
Saurav Das961beb22017-03-29 19:09:17 -070094 * Group handler that emulates Broadcom OF-DPA TTP.
Charles Chan188ebf52015-12-23 00:15:11 -080095 */
Charles Chan361154b2016-03-24 10:23:39 -070096public class Ofdpa2GroupHandler {
Charles Chan188ebf52015-12-23 00:15:11 -080097 /*
98 * OFDPA requires group-id's to have a certain form.
99 * L2 Interface Groups have <4bits-0><12bits-vlanid><16bits-portid>
100 * L3 Unicast Groups have <4bits-2><28bits-index>
101 * MPLS Interface Groups have <4bits-9><4bits:0><24bits-index>
102 * L3 ECMP Groups have <4bits-7><28bits-index>
103 * L2 Flood Groups have <4bits-4><12bits-vlanid><16bits-index>
104 * L3 VPN Groups have <4bits-9><4bits-2><24bits-index>
105 */
Charles Chan425854b2016-04-11 15:32:12 -0700106 protected static final int L2_INTERFACE_TYPE = 0x00000000;
107 protected static final int L3_INTERFACE_TYPE = 0x50000000;
108 protected static final int L3_UNICAST_TYPE = 0x20000000;
109 protected static final int L3_MULTICAST_TYPE = 0x60000000;
110 protected static final int MPLS_INTERFACE_TYPE = 0x90000000;
111 protected static final int MPLS_L3VPN_SUBTYPE = 0x92000000;
112 protected static final int L3_ECMP_TYPE = 0x70000000;
113 protected static final int L2_FLOOD_TYPE = 0x40000000;
Charles Chane849c192016-01-11 18:28:54 -0800114
Charles Chan425854b2016-04-11 15:32:12 -0700115 protected static final int TYPE_MASK = 0x0fffffff;
116 protected static final int SUBTYPE_MASK = 0x00ffffff;
117 protected static final int TYPE_VLAN_MASK = 0x0000ffff;
Charles Chane849c192016-01-11 18:28:54 -0800118
Charles Chan372b63e2017-02-07 12:10:53 -0800119 protected static final int THREE_BIT_MASK = 0x0fff;
120 protected static final int FOUR_BIT_MASK = 0xffff;
121 protected static final int PORT_LEN = 16;
122
Charles Chan425854b2016-04-11 15:32:12 -0700123 protected static final int PORT_LOWER_BITS_MASK = 0x3f;
124 protected static final long PORT_HIGHER_BITS_MASK = ~PORT_LOWER_BITS_MASK;
Charles Chan188ebf52015-12-23 00:15:11 -0800125
Yi Tseng78f51f42017-02-02 13:54:58 -0800126 protected static final String HEX_PREFIX = "0x";
127
Charles Chan188ebf52015-12-23 00:15:11 -0800128 private final Logger log = getLogger(getClass());
129 private ServiceDirectory serviceDirectory;
130 protected GroupService groupService;
Saurav Das8be4e3a2016-03-11 17:19:07 -0800131 protected StorageService storageService;
Charles Chan188ebf52015-12-23 00:15:11 -0800132
Charles Chan425854b2016-04-11 15:32:12 -0700133 protected DeviceId deviceId;
Charles Chan188ebf52015-12-23 00:15:11 -0800134 private FlowObjectiveStore flowObjectiveStore;
Charles Chanfc5c7802016-05-17 13:13:55 -0700135 private Cache<GroupKey, List<OfdpaNextGroup>> pendingAddNextObjectives;
136 private Cache<NextObjective, List<GroupKey>> pendingRemoveNextObjectives;
Saurav Das961beb22017-03-29 19:09:17 -0700137 private Cache<GroupKey, Set<GroupChainElem>> pendingGroups;
Yi Tseng78f51f42017-02-02 13:54:58 -0800138 private ConcurrentHashMap<GroupKey, Set<NextObjective>> pendingUpdateNextObjectives;
Charles Chan188ebf52015-12-23 00:15:11 -0800139 private ScheduledExecutorService groupChecker =
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700140 Executors.newScheduledThreadPool(2, groupedThreads("onos/pipeliner", "ofdpa2-%d", log));
Charles Chan188ebf52015-12-23 00:15:11 -0800141
142 // index number for group creation
Saurav Das8be4e3a2016-03-11 17:19:07 -0800143 private AtomicCounter nextIndex;
Charles Chan188ebf52015-12-23 00:15:11 -0800144
Yi Tseng47f82dc2017-03-05 22:48:39 -0800145 // local store for pending bucketAdds - by design there can be multiple
Charles Chan188ebf52015-12-23 00:15:11 -0800146 // pending bucket for a group
Yi Tseng47f82dc2017-03-05 22:48:39 -0800147 protected ConcurrentHashMap<Integer, Set<NextObjective>> pendingBuckets =
Saurav Das1ce0a7b2016-10-21 14:06:29 -0700148 new ConcurrentHashMap<>();
Charles Chan188ebf52015-12-23 00:15:11 -0800149
Charles Chan40132b32017-01-22 00:19:37 -0800150 /**
151 * Determines whether this pipeline support copy ttl instructions or not.
152 *
153 * @return true if copy ttl instructions are supported
154 */
155 protected boolean supportCopyTtl() {
156 return true;
157 }
158
159 /**
160 * Determines whether this pipeline support set mpls bos instruction or not.
161 *
162 * @return true if set mpls bos instruction is supported
163 */
164 protected boolean supportSetMplsBos() {
165 return true;
166 }
167
Charles Chan0f43e472017-02-14 14:00:16 -0800168 /**
169 * Determines whether this pipeline requires popping VLAN before pushing MPLS.
170 * <p>
171 * If required, pop vlan before push mpls and add an arbitrary vlan back afterward.
172 * MPLS interface group will substitute the arbitrary VLAN with expected VLAN later on.
173 *
174 * @return true if this pipeline requires popping VLAN before pushing MPLS
175 */
176 protected boolean requireVlanPopBeforeMplsPush() {
177 return false;
178 }
179
Charles Chan188ebf52015-12-23 00:15:11 -0800180 protected void init(DeviceId deviceId, PipelinerContext context) {
181 this.deviceId = deviceId;
182 this.flowObjectiveStore = context.store();
183 this.serviceDirectory = context.directory();
184 this.groupService = serviceDirectory.get(GroupService.class);
Saurav Das8be4e3a2016-03-11 17:19:07 -0800185 this.storageService = serviceDirectory.get(StorageService.class);
Madan Jampanid5714e02016-04-19 14:15:20 -0700186 this.nextIndex = storageService.getAtomicCounter("group-id-index-counter");
Charles Chan188ebf52015-12-23 00:15:11 -0800187
Charles Chanfc5c7802016-05-17 13:13:55 -0700188 pendingAddNextObjectives = CacheBuilder.newBuilder()
Charles Chan188ebf52015-12-23 00:15:11 -0800189 .expireAfterWrite(20, TimeUnit.SECONDS)
190 .removalListener((
191 RemovalNotification<GroupKey, List<OfdpaNextGroup>> notification) -> {
192 if (notification.getCause() == RemovalCause.EXPIRED) {
193 notification.getValue().forEach(ofdpaNextGrp ->
Charles Chan361154b2016-03-24 10:23:39 -0700194 Ofdpa2Pipeline.fail(ofdpaNextGrp.nextObj,
Charles Chan188ebf52015-12-23 00:15:11 -0800195 ObjectiveError.GROUPINSTALLATIONFAILED));
Charles Chanfc5c7802016-05-17 13:13:55 -0700196 }
197 }).build();
Charles Chan188ebf52015-12-23 00:15:11 -0800198
Charles Chanfc5c7802016-05-17 13:13:55 -0700199 pendingRemoveNextObjectives = CacheBuilder.newBuilder()
200 .expireAfterWrite(20, TimeUnit.SECONDS)
201 .removalListener((
202 RemovalNotification<NextObjective, List<GroupKey>> notification) -> {
203 if (notification.getCause() == RemovalCause.EXPIRED) {
204 Ofdpa2Pipeline.fail(notification.getKey(),
205 ObjectiveError.GROUPREMOVALFAILED);
Charles Chan188ebf52015-12-23 00:15:11 -0800206 }
207 }).build();
Saurav Das961beb22017-03-29 19:09:17 -0700208 pendingGroups = CacheBuilder.newBuilder()
209 .expireAfterWrite(20, TimeUnit.SECONDS)
210 .removalListener((
211 RemovalNotification<GroupKey, Set<GroupChainElem>> notification) -> {
212 if (notification.getCause() == RemovalCause.EXPIRED) {
213 log.error("Unable to install group with key {} and pending GCEs: {}",
214 notification.getKey(), notification.getValue());
215 }
216 }).build();
Yi Tseng78f51f42017-02-02 13:54:58 -0800217 pendingUpdateNextObjectives = new ConcurrentHashMap<>();
Charles Chan188ebf52015-12-23 00:15:11 -0800218 groupChecker.scheduleAtFixedRate(new GroupChecker(), 0, 500, TimeUnit.MILLISECONDS);
219
220 groupService.addListener(new InnerGroupListener());
221 }
222
Pier Ventre140a8942016-11-02 07:26:38 -0700223 /**
224 * The purpose of this function is to verify if the hashed next
225 * objective is supported by the current pipeline.
226 *
227 * @param nextObjective the hashed objective to verify
228 * @return true if the hashed objective is supported. Otherwise false.
229 */
230 public boolean verifyHashedNextObjective(NextObjective nextObjective) {
231 // if it is not hashed, there is something wrong;
232 if (nextObjective.type() != HASHED) {
233 return false;
234 }
235 // The case non supported is the MPLS-ECMP. For now, we try
236 // to create a MPLS-ECMP for the transport of a VPWS. The
237 // necessary info are contained in the meta selector. In particular
238 // we are looking for the case of BoS==False;
239 TrafficSelector metaSelector = nextObjective.meta();
240 if (metaSelector != null && isNotMplsBos(metaSelector)) {
241 return false;
242 }
243
244 return true;
245 }
246
Saurav Das8be4e3a2016-03-11 17:19:07 -0800247 //////////////////////////////////////
248 // Group Creation
249 //////////////////////////////////////
250
Charles Chan188ebf52015-12-23 00:15:11 -0800251 protected void addGroup(NextObjective nextObjective) {
252 switch (nextObjective.type()) {
253 case SIMPLE:
254 Collection<TrafficTreatment> treatments = nextObjective.next();
255 if (treatments.size() != 1) {
256 log.error("Next Objectives of type Simple should only have a "
257 + "single Traffic Treatment. Next Objective Id:{}",
258 nextObjective.id());
Charles Chan361154b2016-03-24 10:23:39 -0700259 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.BADPARAMS);
Charles Chan188ebf52015-12-23 00:15:11 -0800260 return;
261 }
262 processSimpleNextObjective(nextObjective);
263 break;
264 case BROADCAST:
265 processBroadcastNextObjective(nextObjective);
266 break;
267 case HASHED:
Pier Ventre140a8942016-11-02 07:26:38 -0700268 if (!verifyHashedNextObjective(nextObjective)) {
269 log.error("Next Objectives of type hashed not supported. Next Objective Id:{}",
270 nextObjective.id());
271 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.BADPARAMS);
272 return;
273 }
Charles Chan188ebf52015-12-23 00:15:11 -0800274 processHashedNextObjective(nextObjective);
275 break;
276 case FAILOVER:
Charles Chan361154b2016-03-24 10:23:39 -0700277 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.UNSUPPORTED);
Charles Chan188ebf52015-12-23 00:15:11 -0800278 log.warn("Unsupported next objective type {}", nextObjective.type());
279 break;
280 default:
Charles Chan361154b2016-03-24 10:23:39 -0700281 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.UNKNOWN);
Charles Chan188ebf52015-12-23 00:15:11 -0800282 log.warn("Unknown next objective type {}", nextObjective.type());
283 }
284 }
285
286 /**
287 * As per the OFDPA 2.0 TTP, packets are sent out of ports by using
288 * a chain of groups. The simple Next Objective passed
289 * in by the application has to be broken up into a group chain
290 * comprising of an L3 Unicast Group that points to an L2 Interface
291 * Group which in-turn points to an output port. In some cases, the simple
292 * next Objective can just be an L2 interface without the need for chaining.
293 *
294 * @param nextObj the nextObjective of type SIMPLE
295 */
296 private void processSimpleNextObjective(NextObjective nextObj) {
297 TrafficTreatment treatment = nextObj.next().iterator().next();
298 // determine if plain L2 or L3->L2
299 boolean plainL2 = true;
300 for (Instruction ins : treatment.allInstructions()) {
301 if (ins.type() == Instruction.Type.L2MODIFICATION) {
302 L2ModificationInstruction l2ins = (L2ModificationInstruction) ins;
303 if (l2ins.subtype() == L2ModificationInstruction.L2SubType.ETH_DST ||
304 l2ins.subtype() == L2ModificationInstruction.L2SubType.ETH_SRC) {
305 plainL2 = false;
306 break;
307 }
308 }
309 }
310
311 if (plainL2) {
312 createL2InterfaceGroup(nextObj);
313 return;
314 }
315
Pier Ventre140a8942016-11-02 07:26:38 -0700316 boolean isMpls = false;
Pier Ventre42287df2016-11-09 14:17:26 -0800317 // In order to understand if it is a pseudo wire related
318 // next objective we look for the tunnel id in the meta.
319 boolean isPw = false;
Pier Ventre140a8942016-11-02 07:26:38 -0700320 if (nextObj.meta() != null) {
321 isMpls = isNotMplsBos(nextObj.meta());
Pier Ventre42287df2016-11-09 14:17:26 -0800322
323 TunnelIdCriterion tunnelIdCriterion = (TunnelIdCriterion) nextObj
324 .meta()
325 .getCriterion(TUNNEL_ID);
326 if (tunnelIdCriterion != null) {
327 isPw = true;
328 }
329
Pier Ventre140a8942016-11-02 07:26:38 -0700330 }
331
Pier Ventre42287df2016-11-09 14:17:26 -0800332 if (!isPw) {
333 // break up simple next objective to GroupChain objects
334 GroupInfo groupInfo = createL2L3Chain(treatment, nextObj.id(),
335 nextObj.appId(), isMpls,
336 nextObj.meta());
337 if (groupInfo == null) {
338 log.error("Could not process nextObj={} in dev:{}", nextObj.id(), deviceId);
339 return;
340 }
341 // create object for local and distributed storage
342 Deque<GroupKey> gkeyChain = new ArrayDeque<>();
343 gkeyChain.addFirst(groupInfo.innerMostGroupDesc.appCookie());
344 gkeyChain.addFirst(groupInfo.nextGroupDesc.appCookie());
345 OfdpaNextGroup ofdpaGrp =
346 new OfdpaNextGroup(Collections.singletonList(gkeyChain), nextObj);
347
348 // store l3groupkey with the ofdpaNextGroup for the nextObjective that depends on it
349 updatePendingNextObjective(groupInfo.nextGroupDesc.appCookie(), ofdpaGrp);
350
351 // now we are ready to send the l2 groupDescription (inner), as all the stores
352 // that will get async replies have been updated. By waiting to update
353 // the stores, we prevent nasty race conditions.
354 groupService.addGroup(groupInfo.innerMostGroupDesc);
355 } else {
356 // We handle the pseudo wire with a different a procedure.
357 // This procedure is meant to handle both initiation and
358 // termination of the pseudo wire.
359 processPwNextObjective(nextObj);
Charles Chan188ebf52015-12-23 00:15:11 -0800360 }
Charles Chan188ebf52015-12-23 00:15:11 -0800361 }
362
Charles Chan188ebf52015-12-23 00:15:11 -0800363 /**
364 * Creates a simple L2 Interface Group.
365 *
366 * @param nextObj the next Objective
367 */
368 private void createL2InterfaceGroup(NextObjective nextObj) {
Charles Chan5b9df8d2016-03-28 22:21:40 -0700369 VlanId assignedVlan = Ofdpa2Pipeline.readVlanFromSelector(nextObj.meta());
370 if (assignedVlan == null) {
371 log.warn("VLAN ID required by simple next obj is missing. Abort.");
372 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.BADPARAMS);
Charles Chan188ebf52015-12-23 00:15:11 -0800373 return;
374 }
375
Charles Chan5b9df8d2016-03-28 22:21:40 -0700376 List<GroupInfo> groupInfos = prepareL2InterfaceGroup(nextObj, assignedVlan);
Charles Chan188ebf52015-12-23 00:15:11 -0800377
Charles Chan5b9df8d2016-03-28 22:21:40 -0700378 // There is only one L2 interface group in this case
379 GroupDescription l2InterfaceGroupDesc = groupInfos.get(0).innerMostGroupDesc;
Charles Chan188ebf52015-12-23 00:15:11 -0800380
Charles Chan5b9df8d2016-03-28 22:21:40 -0700381 // Put all dependency information into allGroupKeys
382 List<Deque<GroupKey>> allGroupKeys = Lists.newArrayList();
383 Deque<GroupKey> gkeyChain = new ArrayDeque<>();
384 gkeyChain.addFirst(l2InterfaceGroupDesc.appCookie());
385 allGroupKeys.add(gkeyChain);
Charles Chan188ebf52015-12-23 00:15:11 -0800386
Charles Chan5b9df8d2016-03-28 22:21:40 -0700387 // Point the next objective to this group
388 OfdpaNextGroup ofdpaGrp = new OfdpaNextGroup(allGroupKeys, nextObj);
389 updatePendingNextObjective(l2InterfaceGroupDesc.appCookie(), ofdpaGrp);
390
391 // Start installing the inner-most group
392 groupService.addGroup(l2InterfaceGroupDesc);
Charles Chan188ebf52015-12-23 00:15:11 -0800393 }
394
395 /**
396 * Creates one of two possible group-chains from the treatment
397 * passed in. Depending on the MPLS boolean, this method either creates
Charles Chan425854b2016-04-11 15:32:12 -0700398 * an L3Unicast Group --&gt; L2Interface Group, if mpls is false;
399 * or MPLSInterface Group --&gt; L2Interface Group, if mpls is true;
Charles Chan188ebf52015-12-23 00:15:11 -0800400 * The returned 'inner' group description is always the L2 Interface group.
401 *
402 * @param treatment that needs to be broken up to create the group chain
403 * @param nextId of the next objective that needs this group chain
404 * @param appId of the application that sent this next objective
405 * @param mpls determines if L3Unicast or MPLSInterface group is created
406 * @param meta metadata passed in by the application as part of the nextObjective
407 * @return GroupInfo containing the GroupDescription of the
408 * L2Interface group(inner) and the GroupDescription of the (outer)
409 * L3Unicast/MPLSInterface group. May return null if there is an
410 * error in processing the chain
411 */
Charles Chan425854b2016-04-11 15:32:12 -0700412 protected GroupInfo createL2L3Chain(TrafficTreatment treatment, int nextId,
Charles Chanf9e98652016-09-07 16:54:23 -0700413 ApplicationId appId, boolean mpls,
414 TrafficSelector meta) {
415 return createL2L3ChainInternal(treatment, nextId, appId, mpls, meta, true);
416 }
417
418 /**
419 * Internal implementation of createL2L3Chain.
420 * <p>
421 * The is_present bit in set_vlan_vid action is required to be 0 in OFDPA i12.
422 * Since it is non-OF spec, we need an extension treatment for that.
423 * The useSetVlanExtension must be set to false for OFDPA i12.
424 * </p>
425 *
426 * @param treatment that needs to be broken up to create the group chain
427 * @param nextId of the next objective that needs this group chain
428 * @param appId of the application that sent this next objective
429 * @param mpls determines if L3Unicast or MPLSInterface group is created
430 * @param meta metadata passed in by the application as part of the nextObjective
431 * @param useSetVlanExtension use the setVlanVid extension that has is_present bit set to 0.
432 * @return GroupInfo containing the GroupDescription of the
433 * L2Interface group(inner) and the GroupDescription of the (outer)
434 * L3Unicast/MPLSInterface group. May return null if there is an
435 * error in processing the chain
436 */
437 protected GroupInfo createL2L3ChainInternal(TrafficTreatment treatment, int nextId,
Pier Ventre42287df2016-11-09 14:17:26 -0800438 ApplicationId appId, boolean mpls,
439 TrafficSelector meta, boolean useSetVlanExtension) {
Charles Chan188ebf52015-12-23 00:15:11 -0800440 // for the l2interface group, get vlan and port info
441 // for the outer group, get the src/dst mac, and vlan info
442 TrafficTreatment.Builder outerTtb = DefaultTrafficTreatment.builder();
443 TrafficTreatment.Builder innerTtb = DefaultTrafficTreatment.builder();
444 VlanId vlanid = null;
445 long portNum = 0;
446 boolean setVlan = false, popVlan = false;
Yi Tseng78f51f42017-02-02 13:54:58 -0800447 MacAddress srcMac;
448 MacAddress dstMac;
Charles Chan188ebf52015-12-23 00:15:11 -0800449 for (Instruction ins : treatment.allInstructions()) {
450 if (ins.type() == Instruction.Type.L2MODIFICATION) {
451 L2ModificationInstruction l2ins = (L2ModificationInstruction) ins;
452 switch (l2ins.subtype()) {
453 case ETH_DST:
Charles Chan5270ed02016-01-30 23:22:37 -0800454 dstMac = ((L2ModificationInstruction.ModEtherInstruction) l2ins).mac();
455 outerTtb.setEthDst(dstMac);
Charles Chan188ebf52015-12-23 00:15:11 -0800456 break;
457 case ETH_SRC:
Charles Chand0fd5dc2016-02-16 23:14:49 -0800458 srcMac = ((L2ModificationInstruction.ModEtherInstruction) l2ins).mac();
459 outerTtb.setEthSrc(srcMac);
Charles Chan188ebf52015-12-23 00:15:11 -0800460 break;
461 case VLAN_ID:
462 vlanid = ((L2ModificationInstruction.ModVlanIdInstruction) l2ins).vlanId();
Charles Chanf9e98652016-09-07 16:54:23 -0700463 if (useSetVlanExtension) {
464 OfdpaSetVlanVid ofdpaSetVlanVid = new OfdpaSetVlanVid(vlanid);
465 outerTtb.extension(ofdpaSetVlanVid, deviceId);
466 } else {
467 outerTtb.setVlanId(vlanid);
468 }
Charles Chan188ebf52015-12-23 00:15:11 -0800469 setVlan = true;
470 break;
471 case VLAN_POP:
472 innerTtb.popVlan();
473 popVlan = true;
474 break;
475 case DEC_MPLS_TTL:
476 case MPLS_LABEL:
477 case MPLS_POP:
478 case MPLS_PUSH:
479 case VLAN_PCP:
480 case VLAN_PUSH:
481 default:
482 break;
483 }
484 } else if (ins.type() == Instruction.Type.OUTPUT) {
485 portNum = ((Instructions.OutputInstruction) ins).port().toLong();
486 innerTtb.add(ins);
487 } else {
488 log.warn("Driver does not handle this type of TrafficTreatment"
489 + " instruction in nextObjectives: {}", ins.type());
490 }
491 }
492
493 if (vlanid == null && meta != null) {
494 // use metadata if available
Pier Ventre140a8942016-11-02 07:26:38 -0700495 Criterion vidCriterion = meta.getCriterion(VLAN_VID);
Charles Chan188ebf52015-12-23 00:15:11 -0800496 if (vidCriterion != null) {
497 vlanid = ((VlanIdCriterion) vidCriterion).vlanId();
498 }
499 // if vlan is not set, use the vlan in metadata for outerTtb
500 if (vlanid != null && !setVlan) {
Charles Chanf9e98652016-09-07 16:54:23 -0700501 if (useSetVlanExtension) {
502 OfdpaSetVlanVid ofdpaSetVlanVid = new OfdpaSetVlanVid(vlanid);
503 outerTtb.extension(ofdpaSetVlanVid, deviceId);
504 } else {
505 outerTtb.setVlanId(vlanid);
506 }
Charles Chan188ebf52015-12-23 00:15:11 -0800507 }
508 }
509
510 if (vlanid == null) {
511 log.error("Driver cannot process an L2/L3 group chain without "
512 + "egress vlan information for dev: {} port:{}",
513 deviceId, portNum);
514 return null;
515 }
516
517 if (!setVlan && !popVlan) {
518 // untagged outgoing port
519 TrafficTreatment.Builder temp = DefaultTrafficTreatment.builder();
520 temp.popVlan();
521 innerTtb.build().allInstructions().forEach(i -> temp.add(i));
522 innerTtb = temp;
523 }
524
525 // assemble information for ofdpa l2interface group
Charles Chane849c192016-01-11 18:28:54 -0800526 int l2groupId = L2_INTERFACE_TYPE | (vlanid.toShort() << 16) | (int) portNum;
Saurav Das8be4e3a2016-03-11 17:19:07 -0800527 // a globally unique groupkey that is different for ports in the same device,
Charles Chan188ebf52015-12-23 00:15:11 -0800528 // but different for the same portnumber on different devices. Also different
529 // for the various group-types created out of the same next objective.
Charles Chane849c192016-01-11 18:28:54 -0800530 int l2gk = l2InterfaceGroupKey(deviceId, vlanid, portNum);
Charles Chan361154b2016-03-24 10:23:39 -0700531 final GroupKey l2groupkey = new DefaultGroupKey(Ofdpa2Pipeline.appKryo.serialize(l2gk));
Charles Chan188ebf52015-12-23 00:15:11 -0800532
533 // assemble information for outer group
534 GroupDescription outerGrpDesc = null;
535 if (mpls) {
536 // outer group is MPLSInteface
Saurav Das8be4e3a2016-03-11 17:19:07 -0800537 int mplsInterfaceIndex = getNextAvailableIndex();
538 int mplsgroupId = MPLS_INTERFACE_TYPE | (SUBTYPE_MASK & mplsInterfaceIndex);
539 final GroupKey mplsgroupkey = new DefaultGroupKey(
Charles Chan361154b2016-03-24 10:23:39 -0700540 Ofdpa2Pipeline.appKryo.serialize(mplsInterfaceIndex));
Yi Tsengfa394de2017-02-01 11:26:40 -0800541 outerTtb.group(new GroupId(l2groupId));
Charles Chan188ebf52015-12-23 00:15:11 -0800542 // create the mpls-interface group description to wait for the
543 // l2 interface group to be processed
544 GroupBucket mplsinterfaceGroupBucket =
545 DefaultGroupBucket.createIndirectGroupBucket(outerTtb.build());
546 outerGrpDesc = new DefaultGroupDescription(
547 deviceId,
548 GroupDescription.Type.INDIRECT,
549 new GroupBuckets(Collections.singletonList(
550 mplsinterfaceGroupBucket)),
551 mplsgroupkey,
552 mplsgroupId,
553 appId);
554 log.debug("Trying MPLS-Interface: device:{} gid:{} gkey:{} nextid:{}",
555 deviceId, Integer.toHexString(mplsgroupId),
556 mplsgroupkey, nextId);
557 } else {
558 // outer group is L3Unicast
Saurav Das8be4e3a2016-03-11 17:19:07 -0800559 int l3unicastIndex = getNextAvailableIndex();
560 int l3groupId = L3_UNICAST_TYPE | (TYPE_MASK & l3unicastIndex);
561 final GroupKey l3groupkey = new DefaultGroupKey(
Charles Chan361154b2016-03-24 10:23:39 -0700562 Ofdpa2Pipeline.appKryo.serialize(l3unicastIndex));
Yi Tsengfa394de2017-02-01 11:26:40 -0800563 outerTtb.group(new GroupId(l2groupId));
Charles Chan188ebf52015-12-23 00:15:11 -0800564 // create the l3unicast group description to wait for the
565 // l2 interface group to be processed
566 GroupBucket l3unicastGroupBucket =
567 DefaultGroupBucket.createIndirectGroupBucket(outerTtb.build());
568 outerGrpDesc = new DefaultGroupDescription(
569 deviceId,
570 GroupDescription.Type.INDIRECT,
571 new GroupBuckets(Collections.singletonList(
572 l3unicastGroupBucket)),
573 l3groupkey,
574 l3groupId,
575 appId);
576 log.debug("Trying L3Unicast: device:{} gid:{} gkey:{} nextid:{}",
577 deviceId, Integer.toHexString(l3groupId),
578 l3groupkey, nextId);
579 }
580
581 // store l2groupkey with the groupChainElem for the outer-group that depends on it
582 GroupChainElem gce = new GroupChainElem(outerGrpDesc, 1, false);
583 updatePendingGroups(l2groupkey, gce);
584
585 // create group description for the inner l2interfacegroup
Charles Chan5b9df8d2016-03-28 22:21:40 -0700586 GroupBucket l2InterfaceGroupBucket =
Charles Chan188ebf52015-12-23 00:15:11 -0800587 DefaultGroupBucket.createIndirectGroupBucket(innerTtb.build());
588 GroupDescription l2groupDescription =
589 new DefaultGroupDescription(
590 deviceId,
591 GroupDescription.Type.INDIRECT,
592 new GroupBuckets(Collections.singletonList(
Charles Chan5b9df8d2016-03-28 22:21:40 -0700593 l2InterfaceGroupBucket)),
Charles Chan188ebf52015-12-23 00:15:11 -0800594 l2groupkey,
595 l2groupId,
596 appId);
597 log.debug("Trying L2Interface: device:{} gid:{} gkey:{} nextId:{}",
598 deviceId, Integer.toHexString(l2groupId),
599 l2groupkey, nextId);
600 return new GroupInfo(l2groupDescription, outerGrpDesc);
601
602 }
603
604 /**
605 * As per the OFDPA 2.0 TTP, packets are sent out of ports by using
606 * a chain of groups. The broadcast Next Objective passed in by the application
607 * has to be broken up into a group chain comprising of an
Saurav Das1a129a02016-11-18 15:21:57 -0800608 * L2 Flood group or L3 Multicast group, whose buckets point to L2 Interface groups.
Charles Chan188ebf52015-12-23 00:15:11 -0800609 *
610 * @param nextObj the nextObjective of type BROADCAST
611 */
612 private void processBroadcastNextObjective(NextObjective nextObj) {
Charles Chan5b9df8d2016-03-28 22:21:40 -0700613 VlanId assignedVlan = Ofdpa2Pipeline.readVlanFromSelector(nextObj.meta());
614 if (assignedVlan == null) {
615 log.warn("VLAN ID required by broadcast next obj is missing. Abort.");
616 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.BADPARAMS);
Charles Chan188ebf52015-12-23 00:15:11 -0800617 return;
618 }
Charles Chan188ebf52015-12-23 00:15:11 -0800619
Charles Chan5b9df8d2016-03-28 22:21:40 -0700620 List<GroupInfo> groupInfos = prepareL2InterfaceGroup(nextObj, assignedVlan);
621
622 IpPrefix ipDst = Ofdpa2Pipeline.readIpDstFromSelector(nextObj.meta());
623 if (ipDst != null) {
624 if (ipDst.isMulticast()) {
625 createL3MulticastGroup(nextObj, assignedVlan, groupInfos);
626 } else {
627 log.warn("Broadcast NextObj with non-multicast IP address {}", nextObj);
628 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.BADPARAMS);
629 return;
630 }
631 } else {
632 createL2FloodGroup(nextObj, assignedVlan, groupInfos);
633 }
634 }
635
Saurav Das1ce0a7b2016-10-21 14:06:29 -0700636 private List<GroupInfo> prepareL2InterfaceGroup(NextObjective nextObj,
637 VlanId assignedVlan) {
Charles Chan5b9df8d2016-03-28 22:21:40 -0700638 ImmutableList.Builder<GroupInfo> groupInfoBuilder = ImmutableList.builder();
639
640 // break up broadcast next objective to multiple groups
641 Collection<TrafficTreatment> buckets = nextObj.next();
642
Charles Chan188ebf52015-12-23 00:15:11 -0800643 // each treatment is converted to an L2 interface group
Charles Chan188ebf52015-12-23 00:15:11 -0800644 for (TrafficTreatment treatment : buckets) {
645 TrafficTreatment.Builder newTreatment = DefaultTrafficTreatment.builder();
646 PortNumber portNum = null;
Charles Chan5b9df8d2016-03-28 22:21:40 -0700647 VlanId egressVlan = null;
Charles Chan188ebf52015-12-23 00:15:11 -0800648 // ensure that the only allowed treatments are pop-vlan and output
649 for (Instruction ins : treatment.allInstructions()) {
650 if (ins.type() == Instruction.Type.L2MODIFICATION) {
651 L2ModificationInstruction l2ins = (L2ModificationInstruction) ins;
652 switch (l2ins.subtype()) {
653 case VLAN_POP:
654 newTreatment.add(l2ins);
655 break;
Charles Chan5b9df8d2016-03-28 22:21:40 -0700656 case VLAN_ID:
657 egressVlan = ((L2ModificationInstruction.ModVlanIdInstruction) l2ins).vlanId();
658 break;
Charles Chan188ebf52015-12-23 00:15:11 -0800659 default:
660 log.debug("action {} not permitted for broadcast nextObj",
661 l2ins.subtype());
662 break;
663 }
664 } else if (ins.type() == Instruction.Type.OUTPUT) {
665 portNum = ((Instructions.OutputInstruction) ins).port();
666 newTreatment.add(ins);
667 } else {
Charles Chane849c192016-01-11 18:28:54 -0800668 log.debug("TrafficTreatment of type {} not permitted in " +
669 " broadcast nextObjective", ins.type());
Charles Chan188ebf52015-12-23 00:15:11 -0800670 }
671 }
672
Charles Chan188ebf52015-12-23 00:15:11 -0800673 // assemble info for l2 interface group
Charles Chan5b9df8d2016-03-28 22:21:40 -0700674 VlanId l2InterfaceGroupVlan =
675 (egressVlan != null && !assignedVlan.equals(egressVlan)) ?
676 egressVlan : assignedVlan;
677 int l2gk = l2InterfaceGroupKey(deviceId, l2InterfaceGroupVlan, portNum.toLong());
678 final GroupKey l2InterfaceGroupKey =
679 new DefaultGroupKey(Ofdpa2Pipeline.appKryo.serialize(l2gk));
Charles Chan372b63e2017-02-07 12:10:53 -0800680 int l2InterfaceGroupId = L2_INTERFACE_TYPE |
681 ((l2InterfaceGroupVlan.toShort() & THREE_BIT_MASK) << PORT_LEN) |
682 ((int) portNum.toLong() & FOUR_BIT_MASK);
Charles Chan5b9df8d2016-03-28 22:21:40 -0700683 GroupBucket l2InterfaceGroupBucket =
Charles Chan188ebf52015-12-23 00:15:11 -0800684 DefaultGroupBucket.createIndirectGroupBucket(newTreatment.build());
Charles Chan5b9df8d2016-03-28 22:21:40 -0700685 GroupDescription l2InterfaceGroupDescription =
Charles Chan188ebf52015-12-23 00:15:11 -0800686 new DefaultGroupDescription(
687 deviceId,
688 GroupDescription.Type.INDIRECT,
689 new GroupBuckets(Collections.singletonList(
Charles Chan5b9df8d2016-03-28 22:21:40 -0700690 l2InterfaceGroupBucket)),
691 l2InterfaceGroupKey,
692 l2InterfaceGroupId,
Charles Chan188ebf52015-12-23 00:15:11 -0800693 nextObj.appId());
694 log.debug("Trying L2-Interface: device:{} gid:{} gkey:{} nextid:{}",
Charles Chan5b9df8d2016-03-28 22:21:40 -0700695 deviceId, Integer.toHexString(l2InterfaceGroupId),
696 l2InterfaceGroupKey, nextObj.id());
Charles Chan188ebf52015-12-23 00:15:11 -0800697
Charles Chan5b9df8d2016-03-28 22:21:40 -0700698 groupInfoBuilder.add(new GroupInfo(l2InterfaceGroupDescription,
699 l2InterfaceGroupDescription));
Charles Chan188ebf52015-12-23 00:15:11 -0800700 }
Charles Chan5b9df8d2016-03-28 22:21:40 -0700701 return groupInfoBuilder.build();
702 }
Charles Chan188ebf52015-12-23 00:15:11 -0800703
Saurav Das1ce0a7b2016-10-21 14:06:29 -0700704 private void createL2FloodGroup(NextObjective nextObj, VlanId vlanId,
705 List<GroupInfo> groupInfos) {
706 // assemble info for l2 flood group. Since there can be only one flood
707 // group for a vlan, its index is always the same - 0
Saurav Das0fd79d92016-03-07 10:58:36 -0800708 Integer l2floodgroupId = L2_FLOOD_TYPE | (vlanId.toShort() << 16);
Yi Tseng117952d2017-02-28 10:58:23 -0800709 int l2floodgk = l2FloodGroupKey(vlanId);
Saurav Das1ce0a7b2016-10-21 14:06:29 -0700710 final GroupKey l2floodgroupkey =
711 new DefaultGroupKey(Ofdpa2Pipeline.appKryo.serialize(l2floodgk));
Charles Chan5b9df8d2016-03-28 22:21:40 -0700712
Charles Chan188ebf52015-12-23 00:15:11 -0800713 // collection of group buckets pointing to all the l2 interface groups
Yi Tseng78f51f42017-02-02 13:54:58 -0800714 List<GroupBucket> l2floodBuckets =
715 generateNextGroupBuckets(groupInfos, ALL);
Charles Chan188ebf52015-12-23 00:15:11 -0800716 // create the l2flood group-description to wait for all the
717 // l2interface groups to be processed
718 GroupDescription l2floodGroupDescription =
719 new DefaultGroupDescription(
720 deviceId,
Yi Tseng78f51f42017-02-02 13:54:58 -0800721 ALL,
Charles Chan188ebf52015-12-23 00:15:11 -0800722 new GroupBuckets(l2floodBuckets),
723 l2floodgroupkey,
724 l2floodgroupId,
725 nextObj.appId());
Charles Chan188ebf52015-12-23 00:15:11 -0800726 log.debug("Trying L2-Flood: device:{} gid:{} gkey:{} nextid:{}",
727 deviceId, Integer.toHexString(l2floodgroupId),
728 l2floodgroupkey, nextObj.id());
729
Charles Chan5b9df8d2016-03-28 22:21:40 -0700730 // Put all dependency information into allGroupKeys
731 List<Deque<GroupKey>> allGroupKeys = Lists.newArrayList();
732 groupInfos.forEach(groupInfo -> {
733 Deque<GroupKey> gkeyChain = new ArrayDeque<>();
734 // In this case we should have L2 interface group only
735 gkeyChain.addFirst(groupInfo.nextGroupDesc.appCookie());
736 gkeyChain.addFirst(l2floodgroupkey);
737 allGroupKeys.add(gkeyChain);
738 });
Charles Chan188ebf52015-12-23 00:15:11 -0800739
Charles Chan5b9df8d2016-03-28 22:21:40 -0700740 // Point the next objective to this group
741 OfdpaNextGroup ofdpaGrp = new OfdpaNextGroup(allGroupKeys, nextObj);
Charles Chan188ebf52015-12-23 00:15:11 -0800742 updatePendingNextObjective(l2floodgroupkey, ofdpaGrp);
743
Charles Chan5b9df8d2016-03-28 22:21:40 -0700744 GroupChainElem gce = new GroupChainElem(l2floodGroupDescription,
745 groupInfos.size(), false);
746 groupInfos.forEach(groupInfo -> {
747 // Point this group to the next group
748 updatePendingGroups(groupInfo.nextGroupDesc.appCookie(), gce);
749 // Start installing the inner-most group
750 groupService.addGroup(groupInfo.innerMostGroupDesc);
751 });
752 }
753
Yi Tseng117952d2017-02-28 10:58:23 -0800754 private int l2FloodGroupKey(VlanId vlanId) {
755 int hash = Objects.hash(deviceId, vlanId);
756 return L2_FLOOD_TYPE | TYPE_MASK & hash;
757 }
758
Saurav Das1ce0a7b2016-10-21 14:06:29 -0700759 private void createL3MulticastGroup(NextObjective nextObj, VlanId vlanId,
760 List<GroupInfo> groupInfos) {
Charles Chan5b9df8d2016-03-28 22:21:40 -0700761 List<GroupBucket> l3McastBuckets = new ArrayList<>();
762 groupInfos.forEach(groupInfo -> {
763 // Points to L3 interface group if there is one.
764 // Otherwise points to L2 interface group directly.
765 GroupDescription nextGroupDesc = (groupInfo.nextGroupDesc != null) ?
766 groupInfo.nextGroupDesc : groupInfo.innerMostGroupDesc;
767 TrafficTreatment.Builder ttb = DefaultTrafficTreatment.builder();
Yi Tsengfa394de2017-02-01 11:26:40 -0800768 ttb.group(new GroupId(nextGroupDesc.givenGroupId()));
Charles Chan5b9df8d2016-03-28 22:21:40 -0700769 GroupBucket abucket = DefaultGroupBucket.createAllGroupBucket(ttb.build());
770 l3McastBuckets.add(abucket);
771 });
772
773 int l3MulticastIndex = getNextAvailableIndex();
Saurav Das1ce0a7b2016-10-21 14:06:29 -0700774 int l3MulticastGroupId = L3_MULTICAST_TYPE |
775 vlanId.toShort() << 16 | (TYPE_VLAN_MASK & l3MulticastIndex);
776 final GroupKey l3MulticastGroupKey =
777 new DefaultGroupKey(Ofdpa2Pipeline.appKryo.serialize(l3MulticastIndex));
Charles Chan5b9df8d2016-03-28 22:21:40 -0700778
779 GroupDescription l3MulticastGroupDesc = new DefaultGroupDescription(deviceId,
Yi Tseng78f51f42017-02-02 13:54:58 -0800780 ALL,
Charles Chan5b9df8d2016-03-28 22:21:40 -0700781 new GroupBuckets(l3McastBuckets),
782 l3MulticastGroupKey,
783 l3MulticastGroupId,
784 nextObj.appId());
785
786 // Put all dependency information into allGroupKeys
787 List<Deque<GroupKey>> allGroupKeys = Lists.newArrayList();
788 groupInfos.forEach(groupInfo -> {
789 Deque<GroupKey> gkeyChain = new ArrayDeque<>();
790 gkeyChain.addFirst(groupInfo.innerMostGroupDesc.appCookie());
791 // Add L3 interface group to the chain if there is one.
792 if (!groupInfo.nextGroupDesc.equals(groupInfo.innerMostGroupDesc)) {
793 gkeyChain.addFirst(groupInfo.nextGroupDesc.appCookie());
794 }
795 gkeyChain.addFirst(l3MulticastGroupKey);
796 allGroupKeys.add(gkeyChain);
797 });
798
799 // Point the next objective to this group
800 OfdpaNextGroup ofdpaGrp = new OfdpaNextGroup(allGroupKeys, nextObj);
801 updatePendingNextObjective(l3MulticastGroupKey, ofdpaGrp);
802
803 GroupChainElem outerGce = new GroupChainElem(l3MulticastGroupDesc,
804 groupInfos.size(), false);
805 groupInfos.forEach(groupInfo -> {
806 // Point this group (L3 multicast) to the next group
807 updatePendingGroups(groupInfo.nextGroupDesc.appCookie(), outerGce);
808
809 // Point next group to inner-most group, if any
810 if (!groupInfo.nextGroupDesc.equals(groupInfo.innerMostGroupDesc)) {
811 GroupChainElem innerGce = new GroupChainElem(groupInfo.nextGroupDesc,
812 1, false);
813 updatePendingGroups(groupInfo.innerMostGroupDesc.appCookie(), innerGce);
814 }
815
816 // Start installing the inner-most group
817 groupService.addGroup(groupInfo.innerMostGroupDesc);
818 });
Charles Chan188ebf52015-12-23 00:15:11 -0800819 }
820
Charles Chan188ebf52015-12-23 00:15:11 -0800821 /**
822 * As per the OFDPA 2.0 TTP, packets are sent out of ports by using
823 * a chain of groups. The hashed Next Objective passed in by the application
824 * has to be broken up into a group chain comprising of an
825 * L3 ECMP group as the top level group. Buckets of this group can point
826 * to a variety of groups in a group chain, depending on the whether
827 * MPLS labels are being pushed or not.
828 * <p>
829 * NOTE: We do not create MPLS ECMP groups as they are unimplemented in
830 * OF-DPA 2.0 (even though it is in the spec). Therefore we do not
831 * check the nextObjective meta to see what is matching before being
832 * sent to this nextObjective.
833 *
834 * @param nextObj the nextObjective of type HASHED
835 */
Pier Ventre140a8942016-11-02 07:26:38 -0700836 protected void processHashedNextObjective(NextObjective nextObj) {
Charles Chan188ebf52015-12-23 00:15:11 -0800837 // storage for all group keys in the chain of groups created
838 List<Deque<GroupKey>> allGroupKeys = new ArrayList<>();
839 List<GroupInfo> unsentGroups = new ArrayList<>();
840 createHashBucketChains(nextObj, allGroupKeys, unsentGroups);
841
842 // now we can create the outermost L3 ECMP group
843 List<GroupBucket> l3ecmpGroupBuckets = new ArrayList<>();
844 for (GroupInfo gi : unsentGroups) {
845 // create ECMP bucket to point to the outer group
846 TrafficTreatment.Builder ttb = DefaultTrafficTreatment.builder();
Yi Tsengfa394de2017-02-01 11:26:40 -0800847 ttb.group(new GroupId(gi.nextGroupDesc.givenGroupId()));
Charles Chan188ebf52015-12-23 00:15:11 -0800848 GroupBucket sbucket = DefaultGroupBucket
849 .createSelectGroupBucket(ttb.build());
850 l3ecmpGroupBuckets.add(sbucket);
851 }
Saurav Das8be4e3a2016-03-11 17:19:07 -0800852 int l3ecmpIndex = getNextAvailableIndex();
853 int l3ecmpGroupId = L3_ECMP_TYPE | (TYPE_MASK & l3ecmpIndex);
854 GroupKey l3ecmpGroupKey = new DefaultGroupKey(
Charles Chan361154b2016-03-24 10:23:39 -0700855 Ofdpa2Pipeline.appKryo.serialize(l3ecmpIndex));
Charles Chan188ebf52015-12-23 00:15:11 -0800856 GroupDescription l3ecmpGroupDesc =
857 new DefaultGroupDescription(
858 deviceId,
Yi Tseng78f51f42017-02-02 13:54:58 -0800859 SELECT,
Charles Chan188ebf52015-12-23 00:15:11 -0800860 new GroupBuckets(l3ecmpGroupBuckets),
861 l3ecmpGroupKey,
862 l3ecmpGroupId,
863 nextObj.appId());
864 GroupChainElem l3ecmpGce = new GroupChainElem(l3ecmpGroupDesc,
865 l3ecmpGroupBuckets.size(),
866 false);
867
868 // create objects for local and distributed storage
869 allGroupKeys.forEach(gkeyChain -> gkeyChain.addFirst(l3ecmpGroupKey));
870 OfdpaNextGroup ofdpaGrp = new OfdpaNextGroup(allGroupKeys, nextObj);
871
872 // store l3ecmpGroupKey with the ofdpaGroupChain for the nextObjective
873 // that depends on it
874 updatePendingNextObjective(l3ecmpGroupKey, ofdpaGrp);
875
876 log.debug("Trying L3ECMP: device:{} gid:{} gkey:{} nextId:{}",
877 deviceId, Integer.toHexString(l3ecmpGroupId),
878 l3ecmpGroupKey, nextObj.id());
879 // finally we are ready to send the innermost groups
880 for (GroupInfo gi : unsentGroups) {
881 log.debug("Sending innermost group {} in group chain on device {} ",
Charles Chan5b9df8d2016-03-28 22:21:40 -0700882 Integer.toHexString(gi.innerMostGroupDesc.givenGroupId()), deviceId);
883 updatePendingGroups(gi.nextGroupDesc.appCookie(), l3ecmpGce);
884 groupService.addGroup(gi.innerMostGroupDesc);
Charles Chan188ebf52015-12-23 00:15:11 -0800885 }
Charles Chan188ebf52015-12-23 00:15:11 -0800886 }
887
888 /**
889 * Creates group chains for all buckets in a hashed group, and stores the
890 * GroupInfos and GroupKeys for all the groups in the lists passed in, which
891 * should be empty.
892 * <p>
893 * Does not create the top level ECMP group. Does not actually send the
894 * groups to the groupService.
895 *
896 * @param nextObj the Next Objective with buckets that need to be converted
897 * to group chains
898 * @param allGroupKeys a list to store groupKey for each bucket-group-chain
899 * @param unsentGroups a list to store GroupInfo for each bucket-group-chain
900 */
Pier Ventre140a8942016-11-02 07:26:38 -0700901 protected void createHashBucketChains(NextObjective nextObj,
Saurav Das8be4e3a2016-03-11 17:19:07 -0800902 List<Deque<GroupKey>> allGroupKeys,
903 List<GroupInfo> unsentGroups) {
Charles Chan188ebf52015-12-23 00:15:11 -0800904 // break up hashed next objective to multiple groups
905 Collection<TrafficTreatment> buckets = nextObj.next();
906
907 for (TrafficTreatment bucket : buckets) {
908 //figure out how many labels are pushed in each bucket
909 int labelsPushed = 0;
910 MplsLabel innermostLabel = null;
911 for (Instruction ins : bucket.allInstructions()) {
912 if (ins.type() == Instruction.Type.L2MODIFICATION) {
913 L2ModificationInstruction l2ins = (L2ModificationInstruction) ins;
914 if (l2ins.subtype() == L2ModificationInstruction.L2SubType.MPLS_PUSH) {
915 labelsPushed++;
916 }
917 if (l2ins.subtype() == L2ModificationInstruction.L2SubType.MPLS_LABEL) {
918 if (innermostLabel == null) {
Ray Milkey125572b2016-02-22 16:48:17 -0800919 innermostLabel = ((L2ModificationInstruction.ModMplsLabelInstruction) l2ins).label();
Charles Chan188ebf52015-12-23 00:15:11 -0800920 }
921 }
922 }
923 }
924
925 Deque<GroupKey> gkeyChain = new ArrayDeque<>();
926 // XXX we only deal with 0 and 1 label push right now
927 if (labelsPushed == 0) {
Pier Ventre140a8942016-11-02 07:26:38 -0700928 GroupInfo nolabelGroupInfo;
929 TrafficSelector metaSelector = nextObj.meta();
930 if (metaSelector != null) {
931 if (isNotMplsBos(metaSelector)) {
932 nolabelGroupInfo = createL2L3Chain(bucket, nextObj.id(),
933 nextObj.appId(), true,
934 nextObj.meta());
935 } else {
936 nolabelGroupInfo = createL2L3Chain(bucket, nextObj.id(),
937 nextObj.appId(), false,
938 nextObj.meta());
939 }
940 } else {
941 nolabelGroupInfo = createL2L3Chain(bucket, nextObj.id(),
942 nextObj.appId(), false,
943 nextObj.meta());
944 }
Charles Chan188ebf52015-12-23 00:15:11 -0800945 if (nolabelGroupInfo == null) {
946 log.error("Could not process nextObj={} in dev:{}",
947 nextObj.id(), deviceId);
948 return;
949 }
Charles Chan5b9df8d2016-03-28 22:21:40 -0700950 gkeyChain.addFirst(nolabelGroupInfo.innerMostGroupDesc.appCookie());
951 gkeyChain.addFirst(nolabelGroupInfo.nextGroupDesc.appCookie());
Charles Chan188ebf52015-12-23 00:15:11 -0800952
953 // we can't send the inner group description yet, as we have to
954 // create the dependent ECMP group first. So we store..
955 unsentGroups.add(nolabelGroupInfo);
956
957 } else if (labelsPushed == 1) {
958 GroupInfo onelabelGroupInfo = createL2L3Chain(bucket, nextObj.id(),
959 nextObj.appId(), true,
960 nextObj.meta());
961 if (onelabelGroupInfo == null) {
962 log.error("Could not process nextObj={} in dev:{}",
963 nextObj.id(), deviceId);
964 return;
965 }
966 // we need to add another group to this chain - the L3VPN group
967 TrafficTreatment.Builder l3vpnTtb = DefaultTrafficTreatment.builder();
Charles Chan0f43e472017-02-14 14:00:16 -0800968 if (requireVlanPopBeforeMplsPush()) {
969 l3vpnTtb.popVlan();
970 }
Charles Chan188ebf52015-12-23 00:15:11 -0800971 l3vpnTtb.pushMpls()
972 .setMpls(innermostLabel)
Yi Tsengfa394de2017-02-01 11:26:40 -0800973 .group(new GroupId(onelabelGroupInfo.nextGroupDesc.givenGroupId()));
Charles Chan40132b32017-01-22 00:19:37 -0800974 if (supportCopyTtl()) {
975 l3vpnTtb.copyTtlOut();
976 }
977 if (supportSetMplsBos()) {
978 l3vpnTtb.setMplsBos(true);
979 }
Charles Chan0f43e472017-02-14 14:00:16 -0800980 if (requireVlanPopBeforeMplsPush()) {
981 l3vpnTtb.pushVlan().setVlanId(VlanId.vlanId(VlanId.RESERVED));
982 }
Charles Chan40132b32017-01-22 00:19:37 -0800983
Charles Chan188ebf52015-12-23 00:15:11 -0800984 GroupBucket l3vpnGrpBkt =
985 DefaultGroupBucket.createIndirectGroupBucket(l3vpnTtb.build());
Saurav Das8be4e3a2016-03-11 17:19:07 -0800986 int l3vpnIndex = getNextAvailableIndex();
987 int l3vpngroupId = MPLS_L3VPN_SUBTYPE | (SUBTYPE_MASK & l3vpnIndex);
988 GroupKey l3vpngroupkey = new DefaultGroupKey(
Charles Chan361154b2016-03-24 10:23:39 -0700989 Ofdpa2Pipeline.appKryo.serialize(l3vpnIndex));
Charles Chan188ebf52015-12-23 00:15:11 -0800990 GroupDescription l3vpnGroupDesc =
991 new DefaultGroupDescription(
992 deviceId,
993 GroupDescription.Type.INDIRECT,
994 new GroupBuckets(Collections.singletonList(
995 l3vpnGrpBkt)),
996 l3vpngroupkey,
997 l3vpngroupId,
998 nextObj.appId());
999 GroupChainElem l3vpnGce = new GroupChainElem(l3vpnGroupDesc, 1, false);
Charles Chan5b9df8d2016-03-28 22:21:40 -07001000 updatePendingGroups(onelabelGroupInfo.nextGroupDesc.appCookie(), l3vpnGce);
Charles Chan188ebf52015-12-23 00:15:11 -08001001
Charles Chan5b9df8d2016-03-28 22:21:40 -07001002 gkeyChain.addFirst(onelabelGroupInfo.innerMostGroupDesc.appCookie());
1003 gkeyChain.addFirst(onelabelGroupInfo.nextGroupDesc.appCookie());
Charles Chan188ebf52015-12-23 00:15:11 -08001004 gkeyChain.addFirst(l3vpngroupkey);
1005
1006 //now we can replace the outerGrpDesc with the one we just created
Charles Chan5b9df8d2016-03-28 22:21:40 -07001007 onelabelGroupInfo.nextGroupDesc = l3vpnGroupDesc;
Charles Chan188ebf52015-12-23 00:15:11 -08001008
1009 // we can't send the innermost group yet, as we have to create
1010 // the dependent ECMP group first. So we store ...
1011 unsentGroups.add(onelabelGroupInfo);
1012
1013 log.debug("Trying L3VPN: device:{} gid:{} gkey:{} nextId:{}",
1014 deviceId, Integer.toHexString(l3vpngroupId),
1015 l3vpngroupkey, nextObj.id());
1016
1017 } else {
1018 log.warn("Driver currently does not handle more than 1 MPLS "
1019 + "labels. Not processing nextObjective {}", nextObj.id());
1020 return;
1021 }
1022
1023 // all groups in this chain
1024 allGroupKeys.add(gkeyChain);
1025 }
1026 }
1027
Pier Ventre42287df2016-11-09 14:17:26 -08001028 /**
1029 * Processes the pseudo wire related next objective.
1030 * This procedure try to reuse the mpls label groups,
1031 * the mpls interface group and the l2 interface group.
1032 *
1033 * @param nextObjective the objective to process.
1034 */
1035 protected void processPwNextObjective(NextObjective nextObjective) {
1036 log.warn("Pseudo wire extensions are not support for the OFDPA 2.0 {}", nextObjective.id());
1037 return;
1038 }
1039
Saurav Das8be4e3a2016-03-11 17:19:07 -08001040 //////////////////////////////////////
1041 // Group Editing
1042 //////////////////////////////////////
1043
Charles Chan188ebf52015-12-23 00:15:11 -08001044 /**
1045 * Adds a bucket to the top level group of a group-chain, and creates the chain.
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001046 * Ensures that bucket being added is not a duplicate, by checking existing
1047 * buckets for the same outport.
Charles Chan188ebf52015-12-23 00:15:11 -08001048 *
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001049 * @param nextObjective the bucket information for a next group
Charles Chan188ebf52015-12-23 00:15:11 -08001050 * @param next the representation of the existing group-chain for this next objective
1051 */
1052 protected void addBucketToGroup(NextObjective nextObjective, NextGroup next) {
Saurav Das1a129a02016-11-18 15:21:57 -08001053 if (nextObjective.type() != NextObjective.Type.HASHED &&
1054 nextObjective.type() != NextObjective.Type.BROADCAST) {
Charles Chan188ebf52015-12-23 00:15:11 -08001055 log.warn("AddBuckets not applied to nextType:{} in dev:{} for next:{}",
Yi Tseng78f51f42017-02-02 13:54:58 -08001056 nextObjective.type(), deviceId, nextObjective.id());
Saurav Das1a129a02016-11-18 15:21:57 -08001057 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.UNSUPPORTED);
Charles Chan188ebf52015-12-23 00:15:11 -08001058 return;
1059 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001060
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001061 // first check to see if bucket being added is not a duplicate of an
1062 // existing bucket. If it is for an existing outport, then its a duplicate.
Yi Tseng78f51f42017-02-02 13:54:58 -08001063 Set<TrafficTreatment> duplicateBuckets = Sets.newHashSet();
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001064 List<Deque<GroupKey>> allActiveKeys = Ofdpa2Pipeline.appKryo.deserialize(next.data());
Yi Tseng78f51f42017-02-02 13:54:58 -08001065 Set<PortNumber> existingPorts = getExistingOutputPorts(allActiveKeys);
Yi Tseng47f82dc2017-03-05 22:48:39 -08001066 Set<TrafficTreatment> nonDuplicateBuckets = Sets.newHashSet();
1067 NextObjective objectiveToAdd;
Yi Tseng78f51f42017-02-02 13:54:58 -08001068
1069 nextObjective.next().forEach(trafficTreatment -> {
1070 PortNumber portNumber = readOutPortFromTreatment(trafficTreatment);
Yi Tseng78f51f42017-02-02 13:54:58 -08001071 if (portNumber == null) {
1072 return;
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001073 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001074 if (existingPorts.contains(portNumber)) {
1075 duplicateBuckets.add(trafficTreatment);
Yi Tseng47f82dc2017-03-05 22:48:39 -08001076 } else {
1077 nonDuplicateBuckets.add(trafficTreatment);
Yi Tseng78f51f42017-02-02 13:54:58 -08001078 }
1079 });
1080
Saurav Dasb28d5dd2017-03-24 19:03:58 -07001081 if (duplicateBuckets.isEmpty()) {
1082 // use the original objective
1083 objectiveToAdd = nextObjective;
1084 } else if (!nonDuplicateBuckets.isEmpty()) {
1085 // only use the non-duplicate buckets if there are any
1086 log.debug("Some buckets {} already exist in next id {}, duplicate "
1087 + "buckets will be ignored.", duplicateBuckets, nextObjective.id());
1088 // new next objective with non duplicate treatments
Yi Tseng47f82dc2017-03-05 22:48:39 -08001089 NextObjective.Builder builder = DefaultNextObjective.builder()
1090 .withType(nextObjective.type())
1091 .withId(nextObjective.id())
1092 .withMeta(nextObjective.meta())
1093 .fromApp(nextObjective.appId());
1094 nonDuplicateBuckets.forEach(builder::addTreatment);
1095
1096 ObjectiveContext context = nextObjective.context().orElse(null);
1097 objectiveToAdd = builder.addToExisting(context);
1098 } else {
Saurav Dasb28d5dd2017-03-24 19:03:58 -07001099 // buckets to add are already there - nothing to do
1100 return;
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001101 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001102
Saurav Das1a129a02016-11-18 15:21:57 -08001103 if (nextObjective.type() == NextObjective.Type.HASHED) {
Yi Tseng47f82dc2017-03-05 22:48:39 -08001104 addBucketToHashGroup(objectiveToAdd, allActiveKeys);
Saurav Das1a129a02016-11-18 15:21:57 -08001105 } else if (nextObjective.type() == NextObjective.Type.BROADCAST) {
Yi Tseng47f82dc2017-03-05 22:48:39 -08001106 addBucketToBroadcastGroup(objectiveToAdd, allActiveKeys);
Saurav Das1a129a02016-11-18 15:21:57 -08001107 }
1108 }
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001109
Yi Tseng78f51f42017-02-02 13:54:58 -08001110 private Set<PortNumber> getExistingOutputPorts(List<Deque<GroupKey>> allActiveKeys) {
1111 Set<PortNumber> existingPorts = Sets.newHashSet();
1112
1113 allActiveKeys.forEach(keyChain -> {
1114 GroupKey ifaceGroupKey = keyChain.peekLast();
1115 Group ifaceGroup = groupService.getGroup(deviceId, ifaceGroupKey);
1116 if (ifaceGroup != null && !ifaceGroup.buckets().buckets().isEmpty()) {
1117 ifaceGroup.buckets().buckets().forEach(bucket -> {
1118 PortNumber portNumber = readOutPortFromTreatment(bucket.treatment());
1119
1120 if (portNumber != null) {
1121 existingPorts.add(portNumber);
1122 }
1123 });
1124 }
1125 });
Yi Tseng78f51f42017-02-02 13:54:58 -08001126 return existingPorts;
1127 }
1128
Saurav Das1a129a02016-11-18 15:21:57 -08001129 private void addBucketToHashGroup(NextObjective nextObjective,
Yi Tseng78f51f42017-02-02 13:54:58 -08001130 List<Deque<GroupKey>> allActiveKeys) {
Charles Chan188ebf52015-12-23 00:15:11 -08001131 // storage for all group keys in the chain of groups created
1132 List<Deque<GroupKey>> allGroupKeys = new ArrayList<>();
1133 List<GroupInfo> unsentGroups = new ArrayList<>();
Yi Tseng78f51f42017-02-02 13:54:58 -08001134 List<GroupBucket> newBuckets = Lists.newArrayList();
Charles Chan188ebf52015-12-23 00:15:11 -08001135 createHashBucketChains(nextObjective, allGroupKeys, unsentGroups);
1136
Yi Tseng78f51f42017-02-02 13:54:58 -08001137 // now we can create the buckets to add to the outermost L3 ECMP group
1138 newBuckets = generateNextGroupBuckets(unsentGroups, SELECT);
Charles Chan188ebf52015-12-23 00:15:11 -08001139
Saurav Das1a129a02016-11-18 15:21:57 -08001140 // retrieve the original L3 ECMP group
1141 Group l3ecmpGroup = retrieveTopLevelGroup(allActiveKeys, nextObjective.id());
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001142 if (l3ecmpGroup == null) {
Saurav Das1a129a02016-11-18 15:21:57 -08001143 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.GROUPMISSING);
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001144 return;
1145 }
Saurav Das1a129a02016-11-18 15:21:57 -08001146 GroupKey l3ecmpGroupKey = l3ecmpGroup.appCookie();
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001147 int l3ecmpGroupId = l3ecmpGroup.id().id();
Charles Chan188ebf52015-12-23 00:15:11 -08001148
1149 // Although GroupDescriptions are not necessary for adding buckets to
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001150 // existing groups, we still use one in the GroupChainElem. When the latter is
Charles Chan188ebf52015-12-23 00:15:11 -08001151 // processed, the info will be extracted for the bucketAdd call to groupService
1152 GroupDescription l3ecmpGroupDesc =
1153 new DefaultGroupDescription(
1154 deviceId,
Yi Tseng78f51f42017-02-02 13:54:58 -08001155 SELECT,
1156 new GroupBuckets(newBuckets),
Charles Chan188ebf52015-12-23 00:15:11 -08001157 l3ecmpGroupKey,
1158 l3ecmpGroupId,
1159 nextObjective.appId());
Yi Tseng78f51f42017-02-02 13:54:58 -08001160 GroupChainElem l3ecmpGce = new GroupChainElem(l3ecmpGroupDesc,
1161 unsentGroups.size(),
1162 true);
Charles Chan188ebf52015-12-23 00:15:11 -08001163
1164 // update original NextGroup with new bucket-chain
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001165 // If active keys shows only the top-level group without a chain of groups,
1166 // then it represents an empty group. Update by replacing empty chain.
Charles Chan188ebf52015-12-23 00:15:11 -08001167 Deque<GroupKey> newBucketChain = allGroupKeys.get(0);
1168 newBucketChain.addFirst(l3ecmpGroupKey);
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001169 if (allActiveKeys.size() == 1 && allActiveKeys.get(0).size() == 1) {
1170 allActiveKeys.clear();
1171 }
1172 allActiveKeys.add(newBucketChain);
1173 updatePendingNextObjective(l3ecmpGroupKey,
1174 new OfdpaNextGroup(allActiveKeys, nextObjective));
Yi Tseng78f51f42017-02-02 13:54:58 -08001175
Charles Chan188ebf52015-12-23 00:15:11 -08001176 log.debug("Adding to L3ECMP: device:{} gid:{} gkey:{} nextId:{}",
1177 deviceId, Integer.toHexString(l3ecmpGroupId),
1178 l3ecmpGroupKey, nextObjective.id());
Yi Tseng78f51f42017-02-02 13:54:58 -08001179
1180 unsentGroups.forEach(groupInfo -> {
1181 // send the innermost group
1182 log.debug("Sending innermost group {} in group chain on device {} ",
1183 Integer.toHexString(groupInfo.innerMostGroupDesc.givenGroupId()), deviceId);
1184 updatePendingGroups(groupInfo.nextGroupDesc.appCookie(), l3ecmpGce);
1185 groupService.addGroup(groupInfo.innerMostGroupDesc);
1186 });
Saurav Das1a129a02016-11-18 15:21:57 -08001187 }
Charles Chan188ebf52015-12-23 00:15:11 -08001188
Saurav Das1a129a02016-11-18 15:21:57 -08001189 private void addBucketToBroadcastGroup(NextObjective nextObj,
Yi Tseng78f51f42017-02-02 13:54:58 -08001190 List<Deque<GroupKey>> allActiveKeys) {
Saurav Das1a129a02016-11-18 15:21:57 -08001191 VlanId assignedVlan = Ofdpa2Pipeline.readVlanFromSelector(nextObj.meta());
1192 if (assignedVlan == null) {
1193 log.warn("VLAN ID required by broadcast next obj is missing. "
1194 + "Aborting add bucket to broadcast group for next:{} in dev:{}",
1195 nextObj.id(), deviceId);
1196 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.BADPARAMS);
1197 return;
1198 }
1199
1200 List<GroupInfo> groupInfos = prepareL2InterfaceGroup(nextObj, assignedVlan);
1201
1202 IpPrefix ipDst = Ofdpa2Pipeline.readIpDstFromSelector(nextObj.meta());
1203 if (ipDst != null) {
1204 if (ipDst.isMulticast()) {
1205 addBucketToL3MulticastGroup(nextObj, allActiveKeys,
Yi Tseng78f51f42017-02-02 13:54:58 -08001206 groupInfos, assignedVlan);
Saurav Das1a129a02016-11-18 15:21:57 -08001207 } else {
1208 log.warn("Broadcast NextObj with non-multicast IP address {}", nextObj);
1209 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.BADPARAMS);
1210 return;
1211 }
1212 } else {
1213 addBucketToL2FloodGroup(nextObj, allActiveKeys,
Yi Tseng78f51f42017-02-02 13:54:58 -08001214 groupInfos, assignedVlan);
Saurav Das1a129a02016-11-18 15:21:57 -08001215 }
1216 }
1217
1218 private void addBucketToL2FloodGroup(NextObjective nextObj,
1219 List<Deque<GroupKey>> allActiveKeys,
1220 List<GroupInfo> groupInfos,
Yi Tseng78f51f42017-02-02 13:54:58 -08001221 VlanId assignedVlan) {
1222 Group l2FloodGroup = retrieveTopLevelGroup(allActiveKeys, nextObj.id());
1223
1224 if (l2FloodGroup == null) {
1225 log.warn("Can't find L2 flood group while adding bucket to it. NextObj = {}",
1226 nextObj);
Saurav Das1a129a02016-11-18 15:21:57 -08001227 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.GROUPMISSING);
1228 return;
1229 }
Saurav Das1a129a02016-11-18 15:21:57 -08001230
Yi Tseng78f51f42017-02-02 13:54:58 -08001231 GroupKey l2floodGroupKey = l2FloodGroup.appCookie();
1232 int l2floodGroupId = l2FloodGroup.id().id();
1233 List<GroupBucket> newBuckets = generateNextGroupBuckets(groupInfos, ALL);
1234
1235 GroupDescription l2FloodGroupDescription =
Saurav Das1a129a02016-11-18 15:21:57 -08001236 new DefaultGroupDescription(
1237 deviceId,
Yi Tseng78f51f42017-02-02 13:54:58 -08001238 ALL,
1239 new GroupBuckets(newBuckets),
Saurav Das1a129a02016-11-18 15:21:57 -08001240 l2floodGroupKey,
1241 l2floodGroupId,
1242 nextObj.appId());
Saurav Das1a129a02016-11-18 15:21:57 -08001243
Yi Tseng78f51f42017-02-02 13:54:58 -08001244 GroupChainElem l2FloodGroupChainElement =
1245 new GroupChainElem(l2FloodGroupDescription,
1246 groupInfos.size(),
1247 true);
1248
Saurav Das1a129a02016-11-18 15:21:57 -08001249 updatePendingNextObjective(l2floodGroupKey,
1250 new OfdpaNextGroup(allActiveKeys, nextObj));
Yi Tseng78f51f42017-02-02 13:54:58 -08001251
1252 //ensure assignedVlan applies to the chosen group
1253 VlanId floodGroupVlan = extractVlanIdFromGroupId(l2floodGroupId);
1254
1255 if (!floodGroupVlan.equals(assignedVlan)) {
1256 log.warn("VLAN ID {} does not match Flood group {} to which bucket is "
1257 + "being added, for next:{} in dev:{}. Abort.", assignedVlan,
1258 Integer.toHexString(l2floodGroupId), nextObj.id(), deviceId);
1259 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.BADPARAMS);
1260 return;
1261 }
1262
1263 groupInfos.forEach(groupInfo -> {
1264 // update original NextGroup with new bucket-chain
1265 // If active keys shows only the top-level group without a chain of groups,
1266 // then it represents an empty group. Update by replacing empty chain.
1267 Deque<GroupKey> newBucketChain = new ArrayDeque<>();
1268 newBucketChain.addFirst(groupInfo.nextGroupDesc.appCookie());
1269 newBucketChain.addFirst(l2floodGroupKey);
1270 if (allActiveKeys.size() == 1 && allActiveKeys.get(0).size() == 1) {
1271 allActiveKeys.clear();
1272 }
1273 allActiveKeys.add(newBucketChain);
1274
1275 log.debug("Adding to L2FLOOD: device:{} gid:{} gkey:{} nextId:{}",
1276 deviceId, Integer.toHexString(l2floodGroupId),
1277 l2floodGroupKey, nextObj.id());
1278 // send the innermost group
1279 log.debug("Sending innermost group {} in group chain on device {} ",
1280 Integer.toHexString(groupInfo.innerMostGroupDesc.givenGroupId()),
1281 deviceId);
1282
1283 updatePendingGroups(groupInfo.nextGroupDesc.appCookie(), l2FloodGroupChainElement);
1284
1285 DeviceId innerMostGroupDevice = groupInfo.innerMostGroupDesc.deviceId();
1286 GroupKey innerMostGroupKey = groupInfo.innerMostGroupDesc.appCookie();
1287 Group existsL2IGroup = groupService.getGroup(innerMostGroupDevice, innerMostGroupKey);
1288
1289 if (existsL2IGroup != null) {
1290 // group already exist
1291 processPendingAddGroupsOrNextObjs(innerMostGroupKey, true);
1292 } else {
1293 groupService.addGroup(groupInfo.innerMostGroupDesc);
1294 }
1295
1296 });
1297 }
1298
1299 private VlanId extractVlanIdFromGroupId(int groupId) {
1300 // Extract the 9th to 20th bit from group id as vlan id.
1301 short vlanId = (short) ((groupId & 0x0fff0000) >> 16);
1302 return VlanId.vlanId(vlanId);
1303 }
1304
Saurav Dasb0ae6ee2017-03-04 16:08:47 -08001305 private List<GroupBucket> generateNextGroupBuckets(List<GroupInfo> groupInfos,
1306 GroupDescription.Type bucketType) {
Yi Tseng78f51f42017-02-02 13:54:58 -08001307 List<GroupBucket> newBuckets = Lists.newArrayList();
1308
1309 groupInfos.forEach(groupInfo -> {
1310 GroupDescription groupDesc = groupInfo.nextGroupDesc;
1311 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
Yi Tsengfa394de2017-02-01 11:26:40 -08001312 treatmentBuilder.group(new GroupId(groupDesc.givenGroupId()));
Yi Tseng78f51f42017-02-02 13:54:58 -08001313 GroupBucket newBucket = null;
1314 switch (bucketType) {
1315 case ALL:
1316 newBucket =
1317 DefaultGroupBucket.createAllGroupBucket(treatmentBuilder.build());
1318 break;
1319 case INDIRECT:
1320 newBucket =
1321 DefaultGroupBucket.createIndirectGroupBucket(treatmentBuilder.build());
1322 break;
1323 case SELECT:
1324 newBucket =
1325 DefaultGroupBucket.createSelectGroupBucket(treatmentBuilder.build());
1326 break;
1327 case FAILOVER:
1328 // TODO support failover bucket type
1329 default:
1330 log.warn("Unknown bucket type: {}", bucketType);
1331 break;
1332 }
1333
1334 if (newBucket != null) {
1335 newBuckets.add(newBucket);
1336 }
1337
1338 });
1339
1340 return ImmutableList.copyOf(newBuckets);
Saurav Das1a129a02016-11-18 15:21:57 -08001341 }
1342
1343 private void addBucketToL3MulticastGroup(NextObjective nextObj,
1344 List<Deque<GroupKey>> allActiveKeys,
1345 List<GroupInfo> groupInfos,
Yi Tseng78f51f42017-02-02 13:54:58 -08001346 VlanId assignedVlan) {
1347 // create the buckets to add to the outermost L3 Multicast group
1348 List<GroupBucket> newBuckets = Lists.newArrayList();
1349 groupInfos.forEach(groupInfo -> {
1350 // Points to L3 interface group if there is one.
1351 // Otherwise points to L2 interface group directly.
1352 GroupDescription nextGroupDesc = (groupInfo.nextGroupDesc != null) ?
1353 groupInfo.nextGroupDesc : groupInfo.innerMostGroupDesc;
1354 TrafficTreatment.Builder treatmentBuidler = DefaultTrafficTreatment.builder();
Yi Tsengfa394de2017-02-01 11:26:40 -08001355 treatmentBuidler.group(new GroupId(nextGroupDesc.givenGroupId()));
Yi Tseng78f51f42017-02-02 13:54:58 -08001356 GroupBucket newBucket = DefaultGroupBucket.createAllGroupBucket(treatmentBuidler.build());
1357 newBuckets.add(newBucket);
1358 });
Saurav Das1a129a02016-11-18 15:21:57 -08001359
1360 // get the group being edited
1361 Group l3mcastGroup = retrieveTopLevelGroup(allActiveKeys, nextObj.id());
1362 if (l3mcastGroup == null) {
1363 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.GROUPMISSING);
1364 return;
1365 }
1366 GroupKey l3mcastGroupKey = l3mcastGroup.appCookie();
1367 int l3mcastGroupId = l3mcastGroup.id().id();
1368
1369 //ensure assignedVlan applies to the chosen group
Yi Tseng78f51f42017-02-02 13:54:58 -08001370 VlanId expectedVlan = extractVlanIdFromGroupId(l3mcastGroupId);
Saurav Das1a129a02016-11-18 15:21:57 -08001371 if (!expectedVlan.equals(assignedVlan)) {
1372 log.warn("VLAN ID {} does not match L3 Mcast group {} to which bucket is "
1373 + "being added, for next:{} in dev:{}. Abort.", assignedVlan,
1374 Integer.toHexString(l3mcastGroupId), nextObj.id(), deviceId);
1375 Ofdpa2Pipeline.fail(nextObj, ObjectiveError.BADPARAMS);
1376 }
1377 GroupDescription l3mcastGroupDescription =
1378 new DefaultGroupDescription(
1379 deviceId,
Yi Tseng78f51f42017-02-02 13:54:58 -08001380 ALL,
1381 new GroupBuckets(newBuckets),
Saurav Das1a129a02016-11-18 15:21:57 -08001382 l3mcastGroupKey,
1383 l3mcastGroupId,
1384 nextObj.appId());
1385 GroupChainElem l3mcastGce = new GroupChainElem(l3mcastGroupDescription,
Yi Tseng78f51f42017-02-02 13:54:58 -08001386 groupInfos.size(), true);
Yi Tseng78f51f42017-02-02 13:54:58 -08001387 groupInfos.forEach(groupInfo -> {
1388 // update original NextGroup with new bucket-chain
1389 Deque<GroupKey> newBucketChain = new ArrayDeque<>();
1390 newBucketChain.addFirst(groupInfo.innerMostGroupDesc.appCookie());
1391 // Add L3 interface group to the chain if there is one.
1392 if (!groupInfo.nextGroupDesc.equals(groupInfo.innerMostGroupDesc)) {
1393 newBucketChain.addFirst(groupInfo.nextGroupDesc.appCookie());
1394 }
1395 newBucketChain.addFirst(l3mcastGroupKey);
1396 // If active keys shows only the top-level group without a chain of groups,
1397 // then it represents an empty group. Update by replacing empty chain.
1398 if (allActiveKeys.size() == 1 && allActiveKeys.get(0).size() == 1) {
1399 allActiveKeys.clear();
1400 }
1401 allActiveKeys.add(newBucketChain);
1402
1403 updatePendingGroups(groupInfo.nextGroupDesc.appCookie(), l3mcastGce);
1404 // Point next group to inner-most group, if any
1405 if (!groupInfo.nextGroupDesc.equals(groupInfo.innerMostGroupDesc)) {
1406 GroupChainElem innerGce = new GroupChainElem(groupInfo.nextGroupDesc,
1407 1, false);
1408 updatePendingGroups(groupInfo.innerMostGroupDesc.appCookie(), innerGce);
1409 }
1410 log.debug("Adding to L3MCAST: device:{} gid:{} gkey:{} nextId:{}",
1411 deviceId, Integer.toHexString(l3mcastGroupId),
1412 l3mcastGroupKey, nextObj.id());
1413 // send the innermost group
1414 log.debug("Sending innermost group {} in group chain on device {} ",
1415 Integer.toHexString(groupInfo.innerMostGroupDesc.givenGroupId()),
1416 deviceId);
1417 groupService.addGroup(groupInfo.innerMostGroupDesc);
1418
1419 });
1420
Saurav Das1a129a02016-11-18 15:21:57 -08001421 updatePendingNextObjective(l3mcastGroupKey,
1422 new OfdpaNextGroup(allActiveKeys, nextObj));
Charles Chan188ebf52015-12-23 00:15:11 -08001423 }
1424
1425 /**
1426 * Removes the bucket in the top level group of a possible group-chain. Does
Saurav Das1a129a02016-11-18 15:21:57 -08001427 * not remove the groups in the group-chain pointed to by this bucket, as they
Charles Chan188ebf52015-12-23 00:15:11 -08001428 * may be in use (referenced by other groups) elsewhere.
1429 *
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001430 * @param nextObjective the bucket information for a next group
Charles Chan188ebf52015-12-23 00:15:11 -08001431 * @param next the representation of the existing group-chain for this next objective
1432 */
1433 protected void removeBucketFromGroup(NextObjective nextObjective, NextGroup next) {
Saurav Das1a129a02016-11-18 15:21:57 -08001434 if (nextObjective.type() != NextObjective.Type.HASHED &&
1435 nextObjective.type() != NextObjective.Type.BROADCAST) {
Charles Chan188ebf52015-12-23 00:15:11 -08001436 log.warn("RemoveBuckets not applied to nextType:{} in dev:{} for next:{}",
1437 nextObjective.type(), deviceId, nextObjective.id());
Saurav Das1a129a02016-11-18 15:21:57 -08001438 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.UNSUPPORTED);
Charles Chan188ebf52015-12-23 00:15:11 -08001439 return;
1440 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001441 Set<PortNumber> portsToRemove = Sets.newHashSet();
Charles Chan188ebf52015-12-23 00:15:11 -08001442 Collection<TrafficTreatment> treatments = nextObjective.next();
Yi Tseng78f51f42017-02-02 13:54:58 -08001443 for (TrafficTreatment treatment : treatments) {
1444 // find the bucket to remove by noting the outport, and figuring out the
1445 // top-level group in the group-chain that indirectly references the port
1446 PortNumber portToRemove = readOutPortFromTreatment(treatment);
1447 if (portToRemove == null) {
1448 log.warn("treatment {} of next objective {} has no outport.. cannot remove bucket"
1449 + "from group in dev: {}", treatment, nextObjective.id(), deviceId);
1450 } else {
1451 portsToRemove.add(portToRemove);
1452 }
1453 }
1454
1455 if (portsToRemove.isEmpty()) {
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001456 log.warn("next objective {} has no outport.. cannot remove bucket"
Yi Tseng78f51f42017-02-02 13:54:58 -08001457 + "from group in dev: {}", nextObjective.id(), deviceId);
Saurav Das1a129a02016-11-18 15:21:57 -08001458 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.BADPARAMS);
Charles Chan188ebf52015-12-23 00:15:11 -08001459 }
1460
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001461 List<Deque<GroupKey>> allActiveKeys = Ofdpa2Pipeline.appKryo.deserialize(next.data());
Yi Tseng78f51f42017-02-02 13:54:58 -08001462 List<Deque<GroupKey>> chainsToRemove = Lists.newArrayList();
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001463 for (Deque<GroupKey> gkeys : allActiveKeys) {
1464 // last group in group chain should have a single bucket pointing to port
Yi Tseng78f51f42017-02-02 13:54:58 -08001465
Charles Chan188ebf52015-12-23 00:15:11 -08001466 GroupKey groupWithPort = gkeys.peekLast();
1467 Group group = groupService.getGroup(deviceId, groupWithPort);
1468 if (group == null) {
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001469 log.warn("Inconsistent group chain found when removing bucket"
1470 + "for next:{} in dev:{}", nextObjective.id(), deviceId);
Charles Chan188ebf52015-12-23 00:15:11 -08001471 continue;
1472 }
Yi Tseng91cf2d42017-04-10 17:05:37 -07001473 if (group.buckets().buckets().isEmpty()) {
1474 log.warn("Can't get output port information from group {} " +
1475 "because there is no bucket in the group.",
1476 group.id().toString());
1477 continue;
1478 }
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001479 PortNumber pout = readOutPortFromTreatment(
1480 group.buckets().buckets().get(0).treatment());
Yi Tseng78f51f42017-02-02 13:54:58 -08001481 if (portsToRemove.contains(pout)) {
1482 chainsToRemove.add(gkeys);
Charles Chan188ebf52015-12-23 00:15:11 -08001483 }
Charles Chan188ebf52015-12-23 00:15:11 -08001484 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001485 if (chainsToRemove.isEmpty()) {
Charles Chan188ebf52015-12-23 00:15:11 -08001486 log.warn("Could not find appropriate group-chain for removing bucket"
1487 + " for next id {} in dev:{}", nextObjective.id(), deviceId);
Saurav Das1a129a02016-11-18 15:21:57 -08001488 Ofdpa2Pipeline.fail(nextObjective, ObjectiveError.BADPARAMS);
1489 return;
Charles Chan188ebf52015-12-23 00:15:11 -08001490 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001491 List<GroupBucket> bucketsToRemove = Lists.newArrayList();
1492 //first group key is the one we want to modify
1493 GroupKey modGroupKey = chainsToRemove.get(0).peekFirst();
Saurav Das1a129a02016-11-18 15:21:57 -08001494 Group modGroup = groupService.getGroup(deviceId, modGroupKey);
Yi Tseng78f51f42017-02-02 13:54:58 -08001495 for (Deque<GroupKey> foundChain : chainsToRemove) {
1496 //second group key is the one we wish to remove the reference to
1497 if (foundChain.size() < 2) {
1498 // additional check to make sure second group key exist in
1499 // the chain.
1500 log.warn("Can't find second group key from chain {}",
1501 foundChain);
1502 continue;
Saurav Das1a129a02016-11-18 15:21:57 -08001503 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001504 GroupKey pointedGroupKey = foundChain.stream().collect(Collectors.toList()).get(1);
Yi Tseng78f51f42017-02-02 13:54:58 -08001505 Group pointedGroup = groupService.getGroup(deviceId, pointedGroupKey);
1506
1507 if (pointedGroup == null) {
1508 continue;
1509 }
1510
1511 GroupBucket bucket;
1512 if (nextObjective.type() == NextObjective.Type.HASHED) {
1513 bucket = DefaultGroupBucket.createSelectGroupBucket(
1514 DefaultTrafficTreatment.builder()
1515 .group(pointedGroup.id())
1516 .build());
1517 } else {
1518 bucket = DefaultGroupBucket.createAllGroupBucket(
1519 DefaultTrafficTreatment.builder()
1520 .group(pointedGroup.id())
1521 .build());
1522 }
1523
1524 bucketsToRemove.add(bucket);
Saurav Das1a129a02016-11-18 15:21:57 -08001525 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001526
1527 GroupBuckets removeBuckets = new GroupBuckets(bucketsToRemove);
1528 List<String> pointedGroupIds; // for debug log
1529 pointedGroupIds = bucketsToRemove.stream()
1530 .map(GroupBucket::treatment)
1531 .map(TrafficTreatment::allInstructions)
1532 .flatMap(List::stream)
1533 .filter(inst -> inst instanceof Instructions.GroupInstruction)
1534 .map(inst -> (Instructions.GroupInstruction) inst)
1535 .map(Instructions.GroupInstruction::groupId)
1536 .map(GroupId::id)
1537 .map(Integer::toHexString)
1538 .map(id -> HEX_PREFIX + id)
1539 .collect(Collectors.toList());
1540
Yi Tseng78f51f42017-02-02 13:54:58 -08001541 log.debug("Removing buckets from group id 0x{} pointing to group id(s) {} "
Saurav Das1a129a02016-11-18 15:21:57 -08001542 + "for next id {} in device {}", Integer.toHexString(modGroup.id().id()),
Yi Tseng78f51f42017-02-02 13:54:58 -08001543 pointedGroupIds, nextObjective.id(), deviceId);
1544 addPendingUpdateNextObjective(modGroupKey, nextObjective);
Saurav Das1a129a02016-11-18 15:21:57 -08001545 groupService.removeBucketsFromGroup(deviceId, modGroupKey,
1546 removeBuckets, modGroupKey,
1547 nextObjective.appId());
1548 // update store
Yi Tsengeeb3dc12017-03-15 10:55:50 -07001549 allActiveKeys.removeAll(chainsToRemove);
1550 // If no buckets in the group, then retain an entry for the
1551 // top level group which still exists.
1552 if (allActiveKeys.isEmpty()) {
Saurav Das1a129a02016-11-18 15:21:57 -08001553 ArrayDeque<GroupKey> top = new ArrayDeque<>();
1554 top.add(modGroupKey);
1555 allActiveKeys.add(top);
1556 }
Saurav Das1a129a02016-11-18 15:21:57 -08001557 flowObjectiveStore.putNextGroup(nextObjective.id(),
1558 new OfdpaNextGroup(allActiveKeys,
1559 nextObjective));
Charles Chan188ebf52015-12-23 00:15:11 -08001560 }
1561
1562 /**
Saurav Das961beb22017-03-29 19:09:17 -07001563 * Removes all groups in multiple possible group-chains that represent the next-obj.
Charles Chan188ebf52015-12-23 00:15:11 -08001564 *
1565 * @param nextObjective the next objective to remove
1566 * @param next the NextGroup that represents the existing group-chain for
1567 * this next objective
1568 */
1569 protected void removeGroup(NextObjective nextObjective, NextGroup next) {
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001570 List<Deque<GroupKey>> allActiveKeys = Ofdpa2Pipeline.appKryo.deserialize(next.data());
Charles Chanfc5c7802016-05-17 13:13:55 -07001571
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001572 List<GroupKey> groupKeys = allActiveKeys.stream()
Charles Chanfc5c7802016-05-17 13:13:55 -07001573 .map(Deque::getFirst).collect(Collectors.toList());
1574 pendingRemoveNextObjectives.put(nextObjective, groupKeys);
1575
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001576 allActiveKeys.forEach(groupChain -> groupChain.forEach(groupKey ->
Charles Chan188ebf52015-12-23 00:15:11 -08001577 groupService.removeGroup(deviceId, groupKey, nextObjective.appId())));
1578 flowObjectiveStore.removeNextGroup(nextObjective.id());
1579 }
1580
Saurav Das8be4e3a2016-03-11 17:19:07 -08001581 //////////////////////////////////////
1582 // Helper Methods and Classes
1583 //////////////////////////////////////
1584
Saurav Das961beb22017-03-29 19:09:17 -07001585 protected void updatePendingNextObjective(GroupKey gkey, OfdpaNextGroup value) {
1586 pendingAddNextObjectives.asMap().compute(gkey, (k, val) -> {
1587 if (val == null) {
1588 val = new CopyOnWriteArrayList<OfdpaNextGroup>();
1589 }
1590 val.add(value);
1591 return val;
1592 });
Saurav Das8be4e3a2016-03-11 17:19:07 -08001593 }
1594
Charles Chan425854b2016-04-11 15:32:12 -07001595 protected void updatePendingGroups(GroupKey gkey, GroupChainElem gce) {
Saurav Das961beb22017-03-29 19:09:17 -07001596 pendingGroups.asMap().compute(gkey, (k, val) -> {
1597 if (val == null) {
1598 val = Sets.newConcurrentHashSet();
1599 }
1600 val.add(gce);
1601 return val;
1602 });
Saurav Das8be4e3a2016-03-11 17:19:07 -08001603 }
1604
Yi Tseng78f51f42017-02-02 13:54:58 -08001605 private void addPendingUpdateNextObjective(GroupKey groupKey, NextObjective nextObjective) {
1606 pendingUpdateNextObjectives.compute(groupKey, (gKey, nextObjs) -> {
1607 if (nextObjs != null) {
1608 nextObjs.add(nextObjective);
1609 } else {
1610 nextObjs = Sets.newHashSet(nextObjective);
1611 }
1612 return nextObjs;
1613 });
1614 }
1615
Charles Chan188ebf52015-12-23 00:15:11 -08001616 /**
1617 * Processes next element of a group chain. Assumption is that if this
1618 * group points to another group, the latter has already been created
1619 * and this driver has received notification for it. A second assumption is
1620 * that if there is another group waiting for this group then the appropriate
1621 * stores already have the information to act upon the notification for the
1622 * creation of this group.
1623 * <p>
1624 * The processing of the GroupChainElement depends on the number of groups
1625 * this element is waiting on. For all group types other than SIMPLE, a
1626 * GroupChainElement could be waiting on multiple groups.
1627 *
1628 * @param gce the group chain element to be processed next
1629 */
1630 private void processGroupChain(GroupChainElem gce) {
1631 int waitOnGroups = gce.decrementAndGetGroupsWaitedOn();
1632 if (waitOnGroups != 0) {
1633 log.debug("GCE: {} not ready to be processed", gce);
1634 return;
1635 }
1636 log.debug("GCE: {} ready to be processed", gce);
1637 if (gce.addBucketToGroup) {
1638 groupService.addBucketsToGroup(gce.groupDescription.deviceId(),
1639 gce.groupDescription.appCookie(),
1640 gce.groupDescription.buckets(),
1641 gce.groupDescription.appCookie(),
1642 gce.groupDescription.appId());
1643 } else {
1644 groupService.addGroup(gce.groupDescription);
1645 }
1646 }
1647
1648 private class GroupChecker implements Runnable {
1649 @Override
1650 public void run() {
Saurav Das961beb22017-03-29 19:09:17 -07001651 if (pendingGroups.size() != 0) {
1652 log.debug("pending groups being checked: {}", pendingGroups.asMap().keySet());
1653 }
1654 if (pendingAddNextObjectives.size() != 0) {
1655 log.debug("pending add-next-obj being checked: {}",
1656 pendingAddNextObjectives.asMap().keySet());
1657 }
1658 Set<GroupKey> keys = pendingGroups.asMap().keySet().stream()
Charles Chan188ebf52015-12-23 00:15:11 -08001659 .filter(key -> groupService.getGroup(deviceId, key) != null)
1660 .collect(Collectors.toSet());
Charles Chanfc5c7802016-05-17 13:13:55 -07001661 Set<GroupKey> otherkeys = pendingAddNextObjectives.asMap().keySet().stream()
Charles Chan188ebf52015-12-23 00:15:11 -08001662 .filter(otherkey -> groupService.getGroup(deviceId, otherkey) != null)
1663 .collect(Collectors.toSet());
1664 keys.addAll(otherkeys);
1665
Sho SHIMIZUa09e1bb2016-08-01 14:25:25 -07001666 keys.forEach(key ->
Charles Chanfc5c7802016-05-17 13:13:55 -07001667 processPendingAddGroupsOrNextObjs(key, false));
Charles Chan188ebf52015-12-23 00:15:11 -08001668 }
1669 }
1670
Saurav Das8be4e3a2016-03-11 17:19:07 -08001671 private class InnerGroupListener implements GroupListener {
1672 @Override
1673 public void event(GroupEvent event) {
1674 log.trace("received group event of type {}", event.type());
Charles Chanfc5c7802016-05-17 13:13:55 -07001675 switch (event.type()) {
1676 case GROUP_ADDED:
1677 processPendingAddGroupsOrNextObjs(event.subject().appCookie(), true);
1678 break;
1679 case GROUP_REMOVED:
1680 processPendingRemoveNextObjs(event.subject().appCookie());
1681 break;
Yi Tseng78f51f42017-02-02 13:54:58 -08001682 case GROUP_UPDATED:
1683 processPendingUpdateNextObjs(event.subject().appCookie());
1684 break;
Charles Chanfc5c7802016-05-17 13:13:55 -07001685 default:
1686 break;
Saurav Das8be4e3a2016-03-11 17:19:07 -08001687 }
1688 }
1689 }
1690
Yi Tseng78f51f42017-02-02 13:54:58 -08001691 private void processPendingUpdateNextObjs(GroupKey groupKey) {
Yi Tseng78f51f42017-02-02 13:54:58 -08001692 pendingUpdateNextObjectives.compute(groupKey, (gKey, nextObjs) -> {
1693 if (nextObjs != null) {
1694
1695 nextObjs.forEach(nextObj -> {
1696 log.debug("Group {} updated, update pending next objective {}.",
1697 groupKey, nextObj);
1698
1699 Ofdpa2Pipeline.pass(nextObj);
1700 });
1701 }
Yi Tseng78f51f42017-02-02 13:54:58 -08001702 return Sets.newHashSet();
1703 });
1704 }
1705
Charles Chanfc5c7802016-05-17 13:13:55 -07001706 private void processPendingAddGroupsOrNextObjs(GroupKey key, boolean added) {
Charles Chan188ebf52015-12-23 00:15:11 -08001707 //first check for group chain
Saurav Das961beb22017-03-29 19:09:17 -07001708 Set<GroupChainElem> gceSet = pendingGroups.asMap().remove(key);
Charles Chan188ebf52015-12-23 00:15:11 -08001709 if (gceSet != null) {
1710 for (GroupChainElem gce : gceSet) {
Charles Chan216e3c82016-04-23 14:48:16 -07001711 log.debug("Group service {} group key {} in device {}. "
Saurav Das0fd79d92016-03-07 10:58:36 -08001712 + "Processing next group in group chain with group id 0x{}",
Charles Chan188ebf52015-12-23 00:15:11 -08001713 (added) ? "ADDED" : "processed",
1714 key, deviceId,
1715 Integer.toHexString(gce.groupDescription.givenGroupId()));
1716 processGroupChain(gce);
1717 }
1718 } else {
1719 // otherwise chain complete - check for waiting nextObjectives
Charles Chanfc5c7802016-05-17 13:13:55 -07001720 List<OfdpaNextGroup> nextGrpList = pendingAddNextObjectives.getIfPresent(key);
Charles Chan188ebf52015-12-23 00:15:11 -08001721 if (nextGrpList != null) {
Charles Chanfc5c7802016-05-17 13:13:55 -07001722 pendingAddNextObjectives.invalidate(key);
Charles Chan188ebf52015-12-23 00:15:11 -08001723 nextGrpList.forEach(nextGrp -> {
Charles Chan216e3c82016-04-23 14:48:16 -07001724 log.debug("Group service {} group key {} in device:{}. "
Saurav Das0fd79d92016-03-07 10:58:36 -08001725 + "Done implementing next objective: {} <<-->> gid:0x{}",
Charles Chan188ebf52015-12-23 00:15:11 -08001726 (added) ? "ADDED" : "processed",
1727 key, deviceId, nextGrp.nextObjective().id(),
1728 Integer.toHexString(groupService.getGroup(deviceId, key)
1729 .givenGroupId()));
Charles Chan361154b2016-03-24 10:23:39 -07001730 Ofdpa2Pipeline.pass(nextGrp.nextObjective());
Charles Chan188ebf52015-12-23 00:15:11 -08001731 flowObjectiveStore.putNextGroup(nextGrp.nextObjective().id(), nextGrp);
Yi Tseng47f82dc2017-03-05 22:48:39 -08001732
Charles Chan188ebf52015-12-23 00:15:11 -08001733 // check if addBuckets waiting for this completion
Yi Tseng47f82dc2017-03-05 22:48:39 -08001734 pendingBuckets.compute(nextGrp.nextObjective().id(), (nextId, pendBkts) -> {
1735 if (pendBkts != null) {
1736 pendBkts.forEach(pendBkt -> addBucketToGroup(pendBkt, nextGrp));
1737 }
1738 return null;
1739 });
Charles Chan188ebf52015-12-23 00:15:11 -08001740 });
1741 }
1742 }
1743 }
1744
Charles Chanfc5c7802016-05-17 13:13:55 -07001745 private void processPendingRemoveNextObjs(GroupKey key) {
1746 pendingRemoveNextObjectives.asMap().forEach((nextObjective, groupKeys) -> {
1747 if (groupKeys.isEmpty()) {
1748 pendingRemoveNextObjectives.invalidate(nextObjective);
1749 Ofdpa2Pipeline.pass(nextObjective);
1750 } else {
1751 groupKeys.remove(key);
1752 }
1753 });
1754 }
1755
Charles Chan425854b2016-04-11 15:32:12 -07001756 protected int getNextAvailableIndex() {
Saurav Das8be4e3a2016-03-11 17:19:07 -08001757 return (int) nextIndex.incrementAndGet();
1758 }
1759
Charles Chane849c192016-01-11 18:28:54 -08001760 /**
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001761 * Returns the outport in a traffic treatment.
1762 *
1763 * @param tt the treatment
1764 * @return the PortNumber for the outport or null
1765 */
1766 protected static PortNumber readOutPortFromTreatment(TrafficTreatment tt) {
1767 for (Instruction ins : tt.allInstructions()) {
1768 if (ins.type() == Instruction.Type.OUTPUT) {
1769 return ((Instructions.OutputInstruction) ins).port();
1770 }
1771 }
1772 return null;
1773 }
1774
1775 /**
Charles Chane849c192016-01-11 18:28:54 -08001776 * Returns a hash as the L2 Interface Group Key.
1777 *
1778 * Keep the lower 6-bit for port since port number usually smaller than 64.
1779 * Hash other information into remaining 28 bits.
1780 *
1781 * @param deviceId Device ID
1782 * @param vlanId VLAN ID
1783 * @param portNumber Port number
1784 * @return L2 interface group key
1785 */
Pier Ventre140a8942016-11-02 07:26:38 -07001786 protected int l2InterfaceGroupKey(DeviceId deviceId, VlanId vlanId, long portNumber) {
Charles Chane849c192016-01-11 18:28:54 -08001787 int portLowerBits = (int) portNumber & PORT_LOWER_BITS_MASK;
1788 long portHigherBits = portNumber & PORT_HIGHER_BITS_MASK;
Charles Chand0fd5dc2016-02-16 23:14:49 -08001789 int hash = Objects.hash(deviceId, vlanId, portHigherBits);
Charles Chane849c192016-01-11 18:28:54 -08001790 return L2_INTERFACE_TYPE | (TYPE_MASK & hash << 6) | portLowerBits;
1791 }
1792
Saurav Das1a129a02016-11-18 15:21:57 -08001793 private Group retrieveTopLevelGroup(List<Deque<GroupKey>> allActiveKeys,
1794 int nextid) {
Yi Tseng78f51f42017-02-02 13:54:58 -08001795 GroupKey topLevelGroupKey;
Saurav Das1a129a02016-11-18 15:21:57 -08001796 if (!allActiveKeys.isEmpty()) {
1797 topLevelGroupKey = allActiveKeys.get(0).peekFirst();
1798 } else {
1799 log.warn("Could not determine top level group while processing"
1800 + "next:{} in dev:{}", nextid, deviceId);
1801 return null;
1802 }
1803 Group topGroup = groupService.getGroup(deviceId, topLevelGroupKey);
1804 if (topGroup == null) {
1805 log.warn("Could not find top level group while processing "
1806 + "next:{} in dev:{}", nextid, deviceId);
1807 }
1808 return topGroup;
1809 }
1810
Charles Chan188ebf52015-12-23 00:15:11 -08001811 /**
1812 * Utility class for moving group information around.
Saurav Das1a129a02016-11-18 15:21:57 -08001813 *
1814 * Example: Suppose we are trying to create a group-chain A-B-C-D, where
1815 * A is the top level group, and D is the inner-most group, typically L2 Interface.
1816 * The innerMostGroupDesc is always D. At various stages of the creation
1817 * process the nextGroupDesc may be C or B. The nextGroupDesc exists to
1818 * inform the referencing group about which group it needs to point to,
1819 * and wait for. In some cases the group chain may simply be A-B. In this case,
1820 * both innerMostGroupDesc and nextGroupDesc will be B.
Charles Chan188ebf52015-12-23 00:15:11 -08001821 */
Charles Chan425854b2016-04-11 15:32:12 -07001822 protected class GroupInfo {
Charles Chan5b9df8d2016-03-28 22:21:40 -07001823 /**
1824 * Description of the inner-most group of the group chain.
1825 * It is always an L2 interface group.
1826 */
1827 private GroupDescription innerMostGroupDesc;
Charles Chan188ebf52015-12-23 00:15:11 -08001828
Charles Chan5b9df8d2016-03-28 22:21:40 -07001829 /**
1830 * Description of the next group in the group chain.
1831 * It can be L2 interface, L3 interface, L3 unicast, L3 VPN group.
Saurav Das1a129a02016-11-18 15:21:57 -08001832 * It is possible that nextGroupDesc is the same as the innerMostGroup.
Charles Chan5b9df8d2016-03-28 22:21:40 -07001833 */
1834 private GroupDescription nextGroupDesc;
1835
1836 GroupInfo(GroupDescription innerMostGroupDesc, GroupDescription nextGroupDesc) {
1837 this.innerMostGroupDesc = innerMostGroupDesc;
1838 this.nextGroupDesc = nextGroupDesc;
Charles Chan188ebf52015-12-23 00:15:11 -08001839 }
Pier Ventre140a8942016-11-02 07:26:38 -07001840
1841 /**
1842 * Getter for innerMostGroupDesc.
1843 *
1844 * @return the inner most group description
1845 */
1846 public GroupDescription getInnerMostGroupDesc() {
1847 return innerMostGroupDesc;
1848 }
1849
1850 /**
1851 * Getter for the next group description.
1852 *
1853 * @return the next group description
1854 */
1855 public GroupDescription getNextGroupDesc() {
1856 return nextGroupDesc;
1857 }
Charles Chan188ebf52015-12-23 00:15:11 -08001858 }
1859
1860 /**
1861 * Represents an entire group-chain that implements a Next-Objective from
1862 * the application. The objective is represented as a list of deques, where
1863 * each deque is a separate chain of groups.
1864 * <p>
1865 * For example, an ECMP group with 3 buckets, where each bucket points to
1866 * a group chain of L3 Unicast and L2 interface groups will look like this:
1867 * <ul>
1868 * <li>List[0] is a Deque of GroupKeyECMP(first)-GroupKeyL3(middle)-GroupKeyL2(last)
1869 * <li>List[1] is a Deque of GroupKeyECMP(first)-GroupKeyL3(middle)-GroupKeyL2(last)
1870 * <li>List[2] is a Deque of GroupKeyECMP(first)-GroupKeyL3(middle)-GroupKeyL2(last)
1871 * </ul>
1872 * where the first element of each deque is the same, representing the
1873 * top level ECMP group, while every other element represents a unique groupKey.
1874 * <p>
1875 * Also includes information about the next objective that
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001876 * resulted in these group-chains.
Charles Chan188ebf52015-12-23 00:15:11 -08001877 *
1878 */
1879 protected class OfdpaNextGroup implements NextGroup {
1880 private final NextObjective nextObj;
1881 private final List<Deque<GroupKey>> gkeys;
1882
1883 public OfdpaNextGroup(List<Deque<GroupKey>> gkeys, NextObjective nextObj) {
Charles Chan188ebf52015-12-23 00:15:11 -08001884 this.nextObj = nextObj;
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001885 this.gkeys = gkeys;
Charles Chan188ebf52015-12-23 00:15:11 -08001886 }
1887
1888 public NextObjective nextObjective() {
1889 return nextObj;
1890 }
1891
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001892 public List<Deque<GroupKey>> groupKeys() {
1893 return gkeys;
1894 }
1895
Charles Chan188ebf52015-12-23 00:15:11 -08001896 @Override
1897 public byte[] data() {
Charles Chan361154b2016-03-24 10:23:39 -07001898 return Ofdpa2Pipeline.appKryo.serialize(gkeys);
Charles Chan188ebf52015-12-23 00:15:11 -08001899 }
1900 }
1901
1902 /**
1903 * Represents a group element that is part of a chain of groups.
1904 * Stores enough information to create a Group Description to add the group
1905 * to the switch by requesting the Group Service. Objects instantiating this
1906 * class are meant to be temporary and live as long as it is needed to wait for
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001907 * referenced groups in the group chain to be created.
Charles Chan188ebf52015-12-23 00:15:11 -08001908 */
Charles Chan425854b2016-04-11 15:32:12 -07001909 protected class GroupChainElem {
Charles Chan188ebf52015-12-23 00:15:11 -08001910 private GroupDescription groupDescription;
1911 private AtomicInteger waitOnGroups;
1912 private boolean addBucketToGroup;
1913
1914 GroupChainElem(GroupDescription groupDescription, int waitOnGroups,
1915 boolean addBucketToGroup) {
1916 this.groupDescription = groupDescription;
1917 this.waitOnGroups = new AtomicInteger(waitOnGroups);
1918 this.addBucketToGroup = addBucketToGroup;
1919 }
1920
1921 /**
Saurav Das1ce0a7b2016-10-21 14:06:29 -07001922 * This method atomically decrements the counter for the number of
Charles Chan188ebf52015-12-23 00:15:11 -08001923 * groups this GroupChainElement is waiting on, for notifications from
1924 * the Group Service. When this method returns a value of 0, this
1925 * GroupChainElement is ready to be processed.
1926 *
1927 * @return integer indication of the number of notifications being waited on
1928 */
1929 int decrementAndGetGroupsWaitedOn() {
1930 return waitOnGroups.decrementAndGet();
1931 }
1932
1933 @Override
1934 public String toString() {
1935 return (Integer.toHexString(groupDescription.givenGroupId()) +
1936 " groupKey: " + groupDescription.appCookie() +
1937 " waiting-on-groups: " + waitOnGroups.get() +
1938 " addBucketToGroup: " + addBucketToGroup +
1939 " device: " + deviceId);
1940 }
1941 }
Pier Ventre140a8942016-11-02 07:26:38 -07001942
1943 /**
1944 * Helper enum to handle the different MPLS group
1945 * types.
1946 */
1947 protected enum OfdpaMplsGroupSubType {
Pier Ventre140a8942016-11-02 07:26:38 -07001948 MPLS_INTF((short) 0),
Pier Ventre140a8942016-11-02 07:26:38 -07001949 L2_VPN((short) 1),
Pier Ventre140a8942016-11-02 07:26:38 -07001950 L3_VPN((short) 2),
Pier Ventre140a8942016-11-02 07:26:38 -07001951 MPLS_TUNNEL_LABEL_1((short) 3),
Pier Ventre140a8942016-11-02 07:26:38 -07001952 MPLS_TUNNEL_LABEL_2((short) 4),
Pier Ventre140a8942016-11-02 07:26:38 -07001953 MPLS_SWAP_LABEL((short) 5),
Pier Ventre140a8942016-11-02 07:26:38 -07001954 MPLS_ECMP((short) 8);
1955
1956 private short value;
Pier Ventre140a8942016-11-02 07:26:38 -07001957 public static final int OFDPA_GROUP_TYPE_SHIFT = 28;
1958 public static final int OFDPA_MPLS_SUBTYPE_SHIFT = 24;
1959
1960 OfdpaMplsGroupSubType(short value) {
1961 this.value = value;
1962 }
1963
1964 /**
1965 * Gets the value as an short.
1966 *
1967 * @return the value as an short
1968 */
1969 public short getValue() {
1970 return this.value;
1971 }
1972
1973 }
1974
1975 /**
1976 * Creates MPLS Label group id given a sub type and
1977 * the index.
1978 *
1979 * @param subType the MPLS Label group sub type
1980 * @param index the index of the group
1981 * @return the OFDPA group id
1982 */
1983 public Integer makeMplsLabelGroupId(OfdpaMplsGroupSubType subType, int index) {
1984 index = index & 0x00FFFFFF;
1985 return index | (9 << OFDPA_GROUP_TYPE_SHIFT) | (subType.value << OFDPA_MPLS_SUBTYPE_SHIFT);
1986 }
1987
1988 /**
1989 * Creates MPLS Forwarding group id given a sub type and
1990 * the index.
1991 *
1992 * @param subType the MPLS forwarding group sub type
1993 * @param index the index of the group
1994 * @return the OFDPA group id
1995 */
1996 public Integer makeMplsForwardingGroupId(OfdpaMplsGroupSubType subType, int index) {
1997 index = index & 0x00FFFFFF;
1998 return index | (10 << OFDPA_GROUP_TYPE_SHIFT) | (subType.value << OFDPA_MPLS_SUBTYPE_SHIFT);
1999 }
Charles Chan188ebf52015-12-23 00:15:11 -08002000}