blob: 28a0f538d0f03a603245165fac2c11e777c2cbb9 [file] [log] [blame]
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001/*
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07002 * Copyright 2021-present Open Networking Foundation
Andrea Campanellacbbb7952019-11-25 06:38:41 +00003 *
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 */
Matteo Scandoloaa2adde2021-09-13 12:45:32 -070016
Andrea Campanellacbbb7952019-11-25 06:38:41 +000017package org.opencord.olt.impl;
18
Matteo Scandoloaa2adde2021-09-13 12:45:32 -070019import com.google.common.collect.ImmutableMap;
Andrea Campanellacbbb7952019-11-25 06:38:41 +000020import org.onlab.packet.EthType;
21import org.onlab.packet.IPv4;
22import org.onlab.packet.IPv6;
23import org.onlab.packet.MacAddress;
24import org.onlab.packet.TpPort;
25import org.onlab.packet.VlanId;
Ilayda Ozdemir90a93622021-02-25 09:40:58 +000026import org.onlab.util.KryoNamespace;
Andrea Campanellacbbb7952019-11-25 06:38:41 +000027import org.onlab.util.Tools;
28import org.onosproject.cfg.ComponentConfigService;
29import org.onosproject.core.ApplicationId;
30import org.onosproject.core.CoreService;
yasin saplib4b8ee12021-06-13 18:25:20 +000031import org.onosproject.net.Annotations;
Matteo Scandolo3a037a32020-04-01 12:17:50 -070032import org.onosproject.net.ConnectPoint;
yasin saplib4b8ee12021-06-13 18:25:20 +000033import org.onosproject.net.DefaultAnnotations;
Matteo Scandoloaa2adde2021-09-13 12:45:32 -070034import org.onosproject.net.Device;
Andrea Campanellacbbb7952019-11-25 06:38:41 +000035import org.onosproject.net.DeviceId;
Matteo Scandoloaa2adde2021-09-13 12:45:32 -070036import org.onosproject.net.Host;
37import org.onosproject.net.Port;
Andrea Campanellacbbb7952019-11-25 06:38:41 +000038import org.onosproject.net.PortNumber;
39import org.onosproject.net.device.DeviceService;
40import org.onosproject.net.flow.DefaultTrafficSelector;
41import org.onosproject.net.flow.DefaultTrafficTreatment;
Matteo Scandoloaa2adde2021-09-13 12:45:32 -070042import org.onosproject.net.flow.FlowRule;
43import org.onosproject.net.flow.FlowRuleEvent;
44import org.onosproject.net.flow.FlowRuleListener;
45import org.onosproject.net.flow.FlowRuleService;
Andrea Campanellacbbb7952019-11-25 06:38:41 +000046import org.onosproject.net.flow.TrafficSelector;
47import org.onosproject.net.flow.TrafficTreatment;
48import org.onosproject.net.flow.criteria.Criteria;
Matteo Scandoloaa2adde2021-09-13 12:45:32 -070049import org.onosproject.net.flow.criteria.Criterion;
50import org.onosproject.net.flow.criteria.EthTypeCriterion;
51import org.onosproject.net.flow.criteria.IPProtocolCriterion;
52import org.onosproject.net.flow.criteria.PortCriterion;
53import org.onosproject.net.flow.criteria.UdpPortCriterion;
54import org.onosproject.net.flow.criteria.VlanIdCriterion;
55import org.onosproject.net.flow.instructions.L2ModificationInstruction;
Andrea Campanellacbbb7952019-11-25 06:38:41 +000056import org.onosproject.net.flowobjective.DefaultFilteringObjective;
57import org.onosproject.net.flowobjective.DefaultForwardingObjective;
58import org.onosproject.net.flowobjective.FilteringObjective;
59import org.onosproject.net.flowobjective.FlowObjectiveService;
60import org.onosproject.net.flowobjective.ForwardingObjective;
61import org.onosproject.net.flowobjective.Objective;
62import org.onosproject.net.flowobjective.ObjectiveContext;
63import org.onosproject.net.flowobjective.ObjectiveError;
Matteo Scandoloaa2adde2021-09-13 12:45:32 -070064import org.onosproject.net.host.HostService;
Andrea Campanellacbbb7952019-11-25 06:38:41 +000065import org.onosproject.net.meter.MeterId;
Ilayda Ozdemir90a93622021-02-25 09:40:58 +000066import org.onosproject.store.serializers.KryoNamespaces;
67import org.onosproject.store.service.Serializer;
68import org.onosproject.store.service.StorageService;
Andrea Campanellacbbb7952019-11-25 06:38:41 +000069import org.opencord.sadis.BandwidthProfileInformation;
70import org.opencord.sadis.BaseInformationService;
71import org.opencord.sadis.SadisService;
72import org.opencord.sadis.SubscriberAndDeviceInformation;
73import org.opencord.sadis.UniTagInformation;
74import org.osgi.service.component.ComponentContext;
75import org.osgi.service.component.annotations.Activate;
76import org.osgi.service.component.annotations.Component;
77import org.osgi.service.component.annotations.Deactivate;
78import org.osgi.service.component.annotations.Modified;
79import org.osgi.service.component.annotations.Reference;
80import org.osgi.service.component.annotations.ReferenceCardinality;
Ilayda Ozdemir90a93622021-02-25 09:40:58 +000081import org.osgi.service.component.annotations.ReferencePolicy;
Andrea Campanellacbbb7952019-11-25 06:38:41 +000082import org.slf4j.Logger;
Matteo Scandoloaa2adde2021-09-13 12:45:32 -070083import org.slf4j.LoggerFactory;
Andrea Campanellacbbb7952019-11-25 06:38:41 +000084
Andrea Campanella7a1d7e72020-11-05 10:40:10 +010085import java.util.Dictionary;
Matteo Scandoloaa2adde2021-09-13 12:45:32 -070086import java.util.HashMap;
87import java.util.Iterator;
Ilayda Ozdemir90a93622021-02-25 09:40:58 +000088import java.util.Map;
Andrea Campanellabfb47af2021-06-03 11:09:45 +020089import java.util.Optional;
Andrea Campanella7a1d7e72020-11-05 10:40:10 +010090import java.util.Properties;
Matteo Scandoloaa2adde2021-09-13 12:45:32 -070091import java.util.concurrent.atomic.AtomicBoolean;
92import java.util.concurrent.locks.Lock;
93import java.util.concurrent.locks.ReentrantReadWriteLock;
Andrea Campanella7a1d7e72020-11-05 10:40:10 +010094
95import static com.google.common.base.Strings.isNullOrEmpty;
96import static org.onlab.util.Tools.get;
Matteo Scandoloaa2adde2021-09-13 12:45:32 -070097import static org.onosproject.net.flow.instructions.Instruction.Type.L2MODIFICATION;
98import static org.opencord.olt.impl.OltUtils.completeFlowOpToString;
99import static org.opencord.olt.impl.OltUtils.flowOpToString;
100import static org.opencord.olt.impl.OltUtils.getPortName;
101import static org.opencord.olt.impl.OltUtils.portWithName;
102import static org.opencord.olt.impl.OsgiPropertyConstants.DEFAULT_TP_ID;
103import static org.opencord.olt.impl.OsgiPropertyConstants.DEFAULT_TP_ID_DEFAULT;
104import static org.opencord.olt.impl.OsgiPropertyConstants.DOWNSTREAM_OLT;
105import static org.opencord.olt.impl.OsgiPropertyConstants.DOWNSTREAM_ONU;
106import static org.opencord.olt.impl.OsgiPropertyConstants.ENABLE_DHCP_ON_NNI;
107import static org.opencord.olt.impl.OsgiPropertyConstants.ENABLE_DHCP_ON_NNI_DEFAULT;
108import static org.opencord.olt.impl.OsgiPropertyConstants.ENABLE_DHCP_V4;
109import static org.opencord.olt.impl.OsgiPropertyConstants.ENABLE_DHCP_V4_DEFAULT;
110import static org.opencord.olt.impl.OsgiPropertyConstants.ENABLE_DHCP_V6;
111import static org.opencord.olt.impl.OsgiPropertyConstants.ENABLE_DHCP_V6_DEFAULT;
112import static org.opencord.olt.impl.OsgiPropertyConstants.ENABLE_EAPOL;
113import static org.opencord.olt.impl.OsgiPropertyConstants.ENABLE_EAPOL_DEFAULT;
114import static org.opencord.olt.impl.OsgiPropertyConstants.ENABLE_IGMP_ON_NNI;
115import static org.opencord.olt.impl.OsgiPropertyConstants.ENABLE_IGMP_ON_NNI_DEFAULT;
116import static org.opencord.olt.impl.OsgiPropertyConstants.ENABLE_PPPOE;
117import static org.opencord.olt.impl.OsgiPropertyConstants.ENABLE_PPPOE_DEFAULT;
118import static org.opencord.olt.impl.OsgiPropertyConstants.UPSTREAM_OLT;
119import static org.opencord.olt.impl.OsgiPropertyConstants.UPSTREAM_ONU;
120import static org.opencord.olt.impl.OsgiPropertyConstants.WAIT_FOR_REMOVAL;
121import static org.opencord.olt.impl.OsgiPropertyConstants.WAIT_FOR_REMOVAL_DEFAULT;
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000122
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000123@Component(immediate = true, property = {
Saurav Dasf62cea82020-08-26 17:43:04 -0700124 ENABLE_DHCP_ON_NNI + ":Boolean=" + ENABLE_DHCP_ON_NNI_DEFAULT,
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000125 ENABLE_DHCP_V4 + ":Boolean=" + ENABLE_DHCP_V4_DEFAULT,
126 ENABLE_DHCP_V6 + ":Boolean=" + ENABLE_DHCP_V6_DEFAULT,
Saurav Dasf62cea82020-08-26 17:43:04 -0700127 ENABLE_IGMP_ON_NNI + ":Boolean=" + ENABLE_IGMP_ON_NNI_DEFAULT,
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000128 ENABLE_EAPOL + ":Boolean=" + ENABLE_EAPOL_DEFAULT,
Gustavo Silva5c492dd2021-02-12 10:21:11 -0300129 ENABLE_PPPOE + ":Boolean=" + ENABLE_PPPOE_DEFAULT,
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700130 DEFAULT_TP_ID + ":Integer=" + DEFAULT_TP_ID_DEFAULT,
131 // FIXME remove this option as potentially dangerous in production
132 WAIT_FOR_REMOVAL + ":Boolean=" + WAIT_FOR_REMOVAL_DEFAULT
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000133})
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700134public class OltFlowService implements OltFlowServiceInterface {
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000135
136 @Reference(cardinality = ReferenceCardinality.MANDATORY)
137 protected CoreService coreService;
138
139 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700140 protected ComponentConfigService cfgService;
141
142 @Reference(cardinality = ReferenceCardinality.MANDATORY)
143 protected FlowObjectiveService flowObjectiveService;
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000144
Ilayda Ozdemir90a93622021-02-25 09:40:58 +0000145 @Reference(cardinality = ReferenceCardinality.OPTIONAL,
146 bind = "bindSadisService",
147 unbind = "unbindSadisService",
148 policy = ReferencePolicy.DYNAMIC)
149 protected volatile SadisService sadisService;
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000150
151 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700152 protected OltMeterServiceInterface oltMeterService;
153
154 @Reference(cardinality = ReferenceCardinality.MANDATORY)
155 protected OltDeviceServiceInterface oltDeviceService;
156
157 @Reference(cardinality = ReferenceCardinality.MANDATORY)
158 protected FlowRuleService flowRuleService;
159
160 @Reference(cardinality = ReferenceCardinality.MANDATORY)
161 protected HostService hostService;
162
163 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000164 protected DeviceService deviceService;
165
166 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Ilayda Ozdemir90a93622021-02-25 09:40:58 +0000167 protected StorageService storageService;
168
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700169 protected BaseInformationService<SubscriberAndDeviceInformation> subsService;
170 protected BaseInformationService<BandwidthProfileInformation> bpService;
171
172 private static final String APP_NAME = "org.opencord.olt";
173 protected ApplicationId appId;
174 private static final Integer MAX_PRIORITY = 10000;
175 private static final Integer MIN_PRIORITY = 1000;
176 private static final short EAPOL_DEFAULT_VLAN = 4091;
177 private static final int NONE_TP_ID = -1;
178 private static final String V4 = "V4";
179 private static final String V6 = "V6";
180 private final Logger log = LoggerFactory.getLogger(getClass());
181
182 protected UniTagInformation defaultEapolUniTag = new UniTagInformation.Builder()
183 .setServiceName("defaultEapol").build();
184 protected UniTagInformation nniUniTag = new UniTagInformation.Builder()
185 .setServiceName("nni")
186 .setTechnologyProfileId(NONE_TP_ID)
187 .setPonCTag(VlanId.NONE)
188 .setUniTagMatch(VlanId.ANY)
189 .setUsPonCTagPriority(-1)
190 .build();
191
192 /**
193 * Connect Point status map.
194 * Used to keep track of which cp has flows that needs to be removed when the status changes.
195 */
196 protected Map<ServiceKey, OltPortStatus> cpStatus;
197 private final ReentrantReadWriteLock cpStatusLock = new ReentrantReadWriteLock();
198 private final Lock cpStatusWriteLock = cpStatusLock.writeLock();
199 private final Lock cpStatusReadLock = cpStatusLock.readLock();
200
201 /**
202 * This map contains the subscriber that have been provisioned by the operator.
203 * They may or may not have flows, depending on the port status.
204 * The map is used to define whether flows need to be provisioned when a port comes up.
205 */
206 protected Map<ServiceKey, Boolean> provisionedSubscribers;
207 private final ReentrantReadWriteLock provisionedSubscribersLock = new ReentrantReadWriteLock();
208 private final Lock provisionedSubscribersWriteLock = provisionedSubscribersLock.writeLock();
209 private final Lock provisionedSubscribersReadLock = provisionedSubscribersLock.readLock();
210
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000211 /**
Saurav Dasf62cea82020-08-26 17:43:04 -0700212 * Create DHCP trap flow on NNI port(s).
213 */
214 protected boolean enableDhcpOnNni = ENABLE_DHCP_ON_NNI_DEFAULT;
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000215
216 /**
Saurav Dasf62cea82020-08-26 17:43:04 -0700217 * Enable flows for DHCP v4 if dhcp is required in sadis config.
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000218 **/
219 protected boolean enableDhcpV4 = ENABLE_DHCP_V4_DEFAULT;
220
221 /**
Saurav Dasf62cea82020-08-26 17:43:04 -0700222 * Enable flows for DHCP v6 if dhcp is required in sadis config.
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000223 **/
224 protected boolean enableDhcpV6 = ENABLE_DHCP_V6_DEFAULT;
225
226 /**
Saurav Dasf62cea82020-08-26 17:43:04 -0700227 * Create IGMP trap flow on NNI port(s).
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000228 **/
Saurav Dasf62cea82020-08-26 17:43:04 -0700229 protected boolean enableIgmpOnNni = ENABLE_IGMP_ON_NNI_DEFAULT;
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000230
231 /**
232 * Send EAPOL authentication trap flows before subscriber provisioning.
233 **/
234 protected boolean enableEapol = ENABLE_EAPOL_DEFAULT;
235
236 /**
Gustavo Silva5c492dd2021-02-12 10:21:11 -0300237 * Send PPPoED authentication trap flows before subscriber provisioning.
238 **/
239 protected boolean enablePppoe = ENABLE_PPPOE_DEFAULT;
240
241 /**
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000242 * Default technology profile id that is used for authentication trap flows.
243 **/
244 protected int defaultTechProfileId = DEFAULT_TP_ID_DEFAULT;
245
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700246 protected boolean waitForRemoval = WAIT_FOR_REMOVAL_DEFAULT;
247
248 public enum FlowOperation {
249 ADD,
250 REMOVE;
251
252
253 @Override
254 public String toString() {
255 return super.toString().toLowerCase();
256 }
257 }
258
259 public enum FlowDirection {
260 UPSTREAM,
261 DOWNSTREAM,
262 }
263
264 public enum OltFlowsStatus {
265 NONE,
266 PENDING_ADD,
267 ADDED,
268 PENDING_REMOVE,
269 REMOVED,
270 ERROR
271 }
272
273 protected InternalFlowListener internalFlowListener;
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000274
275 @Activate
276 public void activate(ComponentContext context) {
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700277 cfgService.registerProperties(getClass());
278 appId = coreService.registerApplication(APP_NAME);
279 internalFlowListener = new InternalFlowListener();
280
281 modified(context);
282
Ilayda Ozdemir90a93622021-02-25 09:40:58 +0000283 KryoNamespace serializer = KryoNamespace.newBuilder()
284 .register(KryoNamespaces.API)
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700285 .register(OltFlowsStatus.class)
286 .register(FlowDirection.class)
287 .register(OltPortStatus.class)
288 .register(OltFlowsStatus.class)
Tunahan Sezenf0843b92021-04-30 07:13:16 +0000289 .register(AccessDevicePort.class)
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700290 .register(new ServiceKeySerializer(), ServiceKey.class)
291 .register(UniTagInformation.class)
Ilayda Ozdemir90a93622021-02-25 09:40:58 +0000292 .build();
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000293
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700294 cpStatus = storageService.<ServiceKey, OltPortStatus>consistentMapBuilder()
295 .withName("volt-cp-status")
296 .withApplicationId(appId)
297 .withSerializer(Serializer.using(serializer))
298 .build().asJavaMap();
299
300 provisionedSubscribers = storageService.<ServiceKey, Boolean>consistentMapBuilder()
301 .withName("volt-provisioned-subscriber")
302 .withApplicationId(appId)
303 .withSerializer(Serializer.using(serializer))
304 .build().asJavaMap();
305
306 flowRuleService.addListener(internalFlowListener);
307
308 log.info("Started");
309 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000310
311 @Deactivate
312 public void deactivate(ComponentContext context) {
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700313 cfgService.unregisterProperties(getClass(), false);
314 flowRuleService.removeListener(internalFlowListener);
315 log.info("Stopped");
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000316 }
317
318 @Modified
319 public void modified(ComponentContext context) {
320
321 Dictionary<?, ?> properties = context != null ? context.getProperties() : new Properties();
322
Saurav Dasf62cea82020-08-26 17:43:04 -0700323 Boolean o = Tools.isPropertyEnabled(properties, ENABLE_DHCP_ON_NNI);
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000324 if (o != null) {
Saurav Dasf62cea82020-08-26 17:43:04 -0700325 enableDhcpOnNni = o;
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000326 }
327
Andrea Campanella7c49b792020-05-11 11:36:53 +0200328 Boolean v4 = Tools.isPropertyEnabled(properties, ENABLE_DHCP_V4);
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000329 if (v4 != null) {
330 enableDhcpV4 = v4;
331 }
332
Andrea Campanella7c49b792020-05-11 11:36:53 +0200333 Boolean v6 = Tools.isPropertyEnabled(properties, ENABLE_DHCP_V6);
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000334 if (v6 != null) {
335 enableDhcpV6 = v6;
336 }
337
Saurav Dasf62cea82020-08-26 17:43:04 -0700338 Boolean p = Tools.isPropertyEnabled(properties, ENABLE_IGMP_ON_NNI);
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000339 if (p != null) {
Saurav Dasf62cea82020-08-26 17:43:04 -0700340 enableIgmpOnNni = p;
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000341 }
342
Andrea Campanella7c49b792020-05-11 11:36:53 +0200343 Boolean eap = Tools.isPropertyEnabled(properties, ENABLE_EAPOL);
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000344 if (eap != null) {
345 enableEapol = eap;
346 }
347
Gustavo Silva5c492dd2021-02-12 10:21:11 -0300348 Boolean pppoe = Tools.isPropertyEnabled(properties, ENABLE_PPPOE);
349 if (pppoe != null) {
350 enablePppoe = pppoe;
351 }
352
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700353 Boolean wait = Tools.isPropertyEnabled(properties, WAIT_FOR_REMOVAL);
354 if (wait != null) {
355 waitForRemoval = wait;
356 }
357
Andrea Campanella7c49b792020-05-11 11:36:53 +0200358 String tpId = get(properties, DEFAULT_TP_ID);
359 defaultTechProfileId = isNullOrEmpty(tpId) ? DEFAULT_TP_ID_DEFAULT : Integer.parseInt(tpId.trim());
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000360
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700361 log.info("Modified. Values = enableDhcpOnNni: {}, enableDhcpV4: {}, " +
362 "enableDhcpV6:{}, enableIgmpOnNni:{}, " +
363 "enableEapol:{}, enablePppoe:{}, defaultTechProfileId:{}," +
364 "waitForRemoval:{}",
365 enableDhcpOnNni, enableDhcpV4, enableDhcpV6,
366 enableIgmpOnNni, enableEapol, enablePppoe,
367 defaultTechProfileId, waitForRemoval);
Andrea Campanellafee86422020-06-04 16:01:27 +0200368
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000369 }
370
371 @Override
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700372 public ImmutableMap<ServiceKey, OltPortStatus> getConnectPointStatus() {
373 try {
374 cpStatusReadLock.lock();
375 return ImmutableMap.copyOf(cpStatus);
376 } finally {
377 cpStatusReadLock.unlock();
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000378 }
379 }
380
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700381 @Override
382 public ImmutableMap<ServiceKey, UniTagInformation> getProgrammedSubscribers() {
383 // NOTE we might want to remove this conversion and directly use cpStatus as it contains
384 // all the required information about suscribers
385 Map<ServiceKey, UniTagInformation> subscribers =
386 new HashMap<>();
387 try {
388 cpStatusReadLock.lock();
389
390 cpStatus.forEach((sk, status) -> {
391 if (
392 // not NNI Port
393 !oltDeviceService.isNniPort(deviceService.getDevice(sk.getPort().connectPoint().deviceId()),
394 sk.getPort().connectPoint().port()) &&
395 // not EAPOL flow
396 !sk.getService().equals(defaultEapolUniTag)
397 ) {
398 subscribers.put(sk, sk.getService());
399 }
400 });
401
402 return ImmutableMap.copyOf(subscribers);
403 } finally {
404 cpStatusReadLock.unlock();
405 }
406 }
407
408 @Override
409 public Map<ServiceKey, Boolean> getRequestedSubscribers() {
410 try {
411 provisionedSubscribersReadLock.lock();
412 return ImmutableMap.copyOf(provisionedSubscribers);
413 } finally {
414 provisionedSubscribersReadLock.unlock();
415 }
416 }
417
418 @Override
419 public void handleNniFlows(Device device, Port port, FlowOperation action) {
420
421 // always handle the LLDP flow
422 processLldpFilteringObjective(device.id(), port, action);
423
424 if (enableDhcpOnNni) {
425 if (enableDhcpV4) {
426 log.debug("Installing DHCPv4 trap flow on NNI {} for device {}", portWithName(port), device.id());
427 processDhcpFilteringObjectives(device.id(), port, action, FlowDirection.DOWNSTREAM,
428 67, 68, EthType.EtherType.IPV4.ethType(), IPv4.PROTOCOL_UDP,
429 null, null, nniUniTag);
430 }
431 if (enableDhcpV6) {
432 log.debug("Installing DHCPv6 trap flow on NNI {} for device {}", portWithName(port), device.id());
433 processDhcpFilteringObjectives(device.id(), port, action, FlowDirection.DOWNSTREAM,
434 546, 547, EthType.EtherType.IPV6.ethType(), IPv6.PROTOCOL_UDP,
435 null, null, nniUniTag);
436 }
437 } else {
438 log.info("DHCP is not required on NNI {} for device {}", portWithName(port), device.id());
439 }
440
441 if (enableIgmpOnNni) {
442 log.debug("Installing IGMP flow on NNI {} for device {}", portWithName(port), device.id());
443 processIgmpFilteringObjectives(device.id(), port, action, FlowDirection.DOWNSTREAM,
444 null, null, NONE_TP_ID, VlanId.NONE, VlanId.ANY, -1);
445 }
446
447 if (enablePppoe) {
448 log.debug("Installing PPPoE flow on NNI {} for device {}", port.number(), device.id());
449 processPPPoEDFilteringObjectives(device.id(), port, action, FlowDirection.DOWNSTREAM,
450 null, null, NONE_TP_ID, VlanId.NONE, VlanId.ANY, null);
451 }
452 }
453
454 @Override
455 public boolean handleBasicPortFlows(DiscoveredSubscriber sub, String bandwidthProfileId,
456 String oltBandwidthProfileId) {
457
458 // we only need to something if EAPOL is enabled
459 if (!enableEapol) {
460 return true;
461 }
462
463 if (sub.status == DiscoveredSubscriber.Status.ADDED) {
464 return addDefaultFlows(sub, bandwidthProfileId, oltBandwidthProfileId);
465 } else if (sub.status == DiscoveredSubscriber.Status.REMOVED) {
466 return removeDefaultFlows(sub, bandwidthProfileId, oltBandwidthProfileId);
467 } else {
468 log.error("Unknown Status {} on DiscoveredSubscriber {}", sub.status, sub);
469 return false;
470 }
471
472 }
473
474 private boolean addDefaultFlows(DiscoveredSubscriber sub, String bandwidthProfileId, String oltBandwidthProfileId) {
475
476 if (!oltMeterService.createMeter(sub.device.id(), bandwidthProfileId)) {
477 if (log.isTraceEnabled()) {
478 log.trace("waiting on meter for bp {} and sub {}", bandwidthProfileId, sub);
479 }
480 return false;
481 }
482 if (hasDefaultEapol(sub.port)) {
483 return true;
484 }
485 return handleEapolFlow(sub, bandwidthProfileId,
486 oltBandwidthProfileId, FlowOperation.ADD, VlanId.vlanId(EAPOL_DEFAULT_VLAN));
487
488 }
489
490 private boolean removeDefaultFlows(DiscoveredSubscriber sub, String bandwidthProfile, String oltBandwidthProfile) {
491 // NOTE that we are not checking for meters as they must have been created to install the flow in first place
492 return handleEapolFlow(sub, bandwidthProfile, oltBandwidthProfile,
493 FlowOperation.REMOVE, VlanId.vlanId(EAPOL_DEFAULT_VLAN));
494 }
495
496 @Override
497 public boolean handleSubscriberFlows(DiscoveredSubscriber sub, String defaultBandwidthProfile,
498 String multicastServiceName) {
499 // NOTE that we are taking defaultBandwithProfile as a parameter as that can be configured in the Olt component
500 if (sub.status == DiscoveredSubscriber.Status.ADDED) {
501 return addSubscriberFlows(sub, defaultBandwidthProfile, multicastServiceName);
502 } else if (sub.status == DiscoveredSubscriber.Status.REMOVED) {
503 return removeSubscriberFlows(sub, defaultBandwidthProfile, multicastServiceName);
504 } else {
505 log.error("don't know how to handle {}", sub);
506 return false;
507 }
508 }
509
510 private boolean addSubscriberFlows(DiscoveredSubscriber sub, String defaultBandwithProfile,
511 String multicastServiceName) {
512 if (log.isTraceEnabled()) {
513 log.trace("Provisioning of subscriber on {} started", portWithName(sub.port));
514 }
515 if (enableEapol) {
516 if (hasDefaultEapol(sub.port)) {
517 // remove EAPOL flow and throw exception so that we'll retry later
518 if (!isDefaultEapolPendingRemoval(sub.port)) {
519 removeDefaultFlows(sub, defaultBandwithProfile, defaultBandwithProfile);
520 }
521
522 if (waitForRemoval) {
523 // NOTE wait for removal is a flag only needed to make sure VOLTHA
524 // does not explode with the flows remove/add in the same batch
525 log.debug("Awaiting for default flows removal for {}", portWithName(sub.port));
526 return false;
527 } else {
528 log.warn("continuing provisioning on {}", portWithName(sub.port));
529 }
530 }
531
532 }
533
534 // NOTE createMeters will return if the meters are not installed
535 if (!oltMeterService.createMeters(sub.device.id(),
Matteo Scandolo88df8ae2021-11-23 13:12:29 -0800536 sub.subscriberAndDeviceInformation, multicastServiceName)) {
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700537 return false;
538 }
539
540 // NOTE we need to add the DHCP flow regardless so that the host can be discovered and the MacAddress added
541 handleSubscriberDhcpFlows(sub.device.id(), sub.port, FlowOperation.ADD,
542 sub.subscriberAndDeviceInformation);
543
544 if (isMacLearningEnabled(sub.subscriberAndDeviceInformation)
545 && !isMacAddressAvailable(sub.device.id(), sub.port,
546 sub.subscriberAndDeviceInformation)) {
547 log.debug("Awaiting for macAddress on {}", portWithName(sub.port));
548 return false;
549 }
550
551 handleSubscriberDataFlows(sub.device, sub.port, FlowOperation.ADD,
552 sub.subscriberAndDeviceInformation, multicastServiceName);
553
554 handleSubscriberEapolFlows(sub, FlowOperation.ADD, sub.subscriberAndDeviceInformation);
555
556 handleSubscriberIgmpFlows(sub, FlowOperation.ADD);
557
558 log.info("Provisioning of subscriber on {} completed", portWithName(sub.port));
559 return true;
560 }
561
562 private boolean removeSubscriberFlows(DiscoveredSubscriber sub, String defaultBandwithProfile,
563 String multicastServiceName) {
564
565 if (log.isTraceEnabled()) {
566 log.trace("Removal of subscriber on {} started",
567 portWithName(sub.port));
568 }
569 SubscriberAndDeviceInformation si = subsService.get(sub.portName());
570 if (si == null) {
571 log.error("Subscriber information not found in sadis for port {} during subscriber removal",
572 portWithName(sub.port));
573 // NOTE that we are returning true so that the subscriber is removed from the queue
574 // and we can move on provisioning others
575 return true;
576 }
577
578 handleSubscriberDhcpFlows(sub.device.id(), sub.port, FlowOperation.REMOVE, si);
579
580 if (enableEapol) {
581 // remove the tagged eapol
582 handleSubscriberEapolFlows(sub, FlowOperation.REMOVE, si);
583
584 // and add the default one back
585 if (sub.port.isEnabled()) {
586 // NOTE we remove the subscriber when the port goes down
587 // but in that case we don't need to add default eapol
588 handleEapolFlow(sub, defaultBandwithProfile, defaultBandwithProfile,
589 FlowOperation.ADD, VlanId.vlanId(EAPOL_DEFAULT_VLAN));
590 }
591 }
592 handleSubscriberDataFlows(sub.device, sub.port, FlowOperation.REMOVE, si, multicastServiceName);
593
594 handleSubscriberIgmpFlows(sub, FlowOperation.REMOVE);
595
596 // FIXME check the return status of the flow and return accordingly
597 log.info("Removal of subscriber on {} completed", portWithName(sub.port));
598 return true;
599 }
600
601 @Override
602 public boolean hasDefaultEapol(Port port) {
603 OltPortStatus status = getOltPortStatus(port, defaultEapolUniTag);
604 // NOTE we consider ERROR as a present EAPOL flow as ONOS
605 // will keep trying to add it
606 return status != null && (status.defaultEapolStatus == OltFlowsStatus.ADDED ||
607 status.defaultEapolStatus == OltFlowsStatus.PENDING_ADD ||
608 status.defaultEapolStatus == OltFlowsStatus.ERROR);
609 }
610
611 private OltPortStatus getOltPortStatus(Port port, UniTagInformation uniTagInformation) {
612 try {
613 cpStatusReadLock.lock();
614 ServiceKey sk = new ServiceKey(new AccessDevicePort(port), uniTagInformation);
615 OltPortStatus status = cpStatus.get(sk);
616 return status;
617 } finally {
618 cpStatusReadLock.unlock();
619 }
620 }
621
622 public boolean isDefaultEapolPendingRemoval(Port port) {
623 OltPortStatus status = getOltPortStatus(port, defaultEapolUniTag);
624 if (log.isTraceEnabled()) {
625 log.trace("Status during EAPOL flow check {} for port {} and UniTagInformation {}",
626 status, portWithName(port), defaultEapolUniTag);
627 }
628 return status != null && status.defaultEapolStatus == OltFlowsStatus.PENDING_REMOVE;
629 }
630
631 @Override
632 public boolean hasDhcpFlows(Port port, UniTagInformation uti) {
633 OltPortStatus status = getOltPortStatus(port, uti);
634 if (log.isTraceEnabled()) {
635 log.trace("Status during DHCP flow check {} for port {} and service {}",
636 status, portWithName(port), uti.getServiceName());
637 }
638 return status != null &&
639 (status.dhcpStatus == OltFlowsStatus.ADDED ||
640 status.dhcpStatus == OltFlowsStatus.PENDING_ADD);
641 }
642
643 @Override
644 public boolean hasSubscriberFlows(Port port, UniTagInformation uti) {
645
646 OltPortStatus status = getOltPortStatus(port, uti);
647 if (log.isTraceEnabled()) {
648 log.trace("Status during subscriber flow check {} for port {} and service {}",
649 status, portWithName(port), uti.getServiceName());
650 }
651 return status != null && (status.subscriberFlowsStatus == OltFlowsStatus.ADDED ||
652 status.subscriberFlowsStatus == OltFlowsStatus.PENDING_ADD);
653 }
654
655 @Override
656 public void purgeDeviceFlows(DeviceId deviceId) {
657 log.debug("Purging flows on device {}", deviceId);
658 flowRuleService.purgeFlowRules(deviceId);
659
660 // removing the status from the cpStatus map
661 try {
662 cpStatusWriteLock.lock();
663 Iterator<Map.Entry<ServiceKey, OltPortStatus>> iter = cpStatus.entrySet().iterator();
664 while (iter.hasNext()) {
665 Map.Entry<ServiceKey, OltPortStatus> entry = iter.next();
666 if (entry.getKey().getPort().connectPoint().deviceId().equals(deviceId)) {
667 cpStatus.remove(entry.getKey());
668 }
669 }
670 } finally {
671 cpStatusWriteLock.unlock();
672 }
673
674 // removing subscribers from the provisioned map
675 try {
676 provisionedSubscribersWriteLock.lock();
677 Iterator<Map.Entry<ServiceKey, Boolean>> iter = provisionedSubscribers.entrySet().iterator();
678 while (iter.hasNext()) {
679 Map.Entry<ServiceKey, Boolean> entry = iter.next();
680 if (entry.getKey().getPort().connectPoint().deviceId().equals(deviceId)) {
681 provisionedSubscribers.remove(entry.getKey());
682 }
683 }
684 } finally {
685 provisionedSubscribersWriteLock.unlock();
686 }
687 }
688
689 @Override
690 public boolean isSubscriberServiceProvisioned(AccessDevicePort cp) {
691 // if any service is programmed on this port, returns true
692 AtomicBoolean provisioned = new AtomicBoolean(false);
693 try {
694 provisionedSubscribersReadLock.lock();
695 for (Map.Entry<ServiceKey, Boolean> entry : provisionedSubscribers.entrySet()) {
696 if (entry.getKey().getPort().equals(cp) && entry.getValue()) {
697 provisioned.set(true);
698 break;
699 }
700 }
701 } finally {
702 provisionedSubscribersReadLock.unlock();
703 }
704 return provisioned.get();
705 }
706
707 @Override
708 public boolean isSubscriberServiceProvisioned(ServiceKey sk) {
709 try {
710 provisionedSubscribersReadLock.lock();
711 Boolean provisioned = provisionedSubscribers.get(sk);
712 if (provisioned == null || !provisioned) {
713 return false;
714 }
715 } finally {
716 provisionedSubscribersReadLock.unlock();
717 }
718 return true;
719 }
720
721 @Override
722 public void updateProvisionedSubscriberStatus(ServiceKey sk, Boolean status) {
723 try {
724 provisionedSubscribersWriteLock.lock();
725 provisionedSubscribers.put(sk, status);
726 } finally {
727 provisionedSubscribersWriteLock.unlock();
728 }
729 }
730
731 private boolean handleEapolFlow(DiscoveredSubscriber sub, String bandwidthProfile,
732 String oltBandwidthProfile, FlowOperation action, VlanId vlanId) {
733
734 // create a subscriberKey for the EAPOL flow
735 ServiceKey sk = new ServiceKey(new AccessDevicePort(sub.port), defaultEapolUniTag);
736
737 // NOTE we only need to keep track of the default EAPOL flow in the
738 // connectpoint status map
739 if (vlanId.id().equals(EAPOL_DEFAULT_VLAN)) {
740 OltFlowsStatus status = action == FlowOperation.ADD ?
741 OltFlowsStatus.PENDING_ADD : OltFlowsStatus.PENDING_REMOVE;
742 updateConnectPointStatus(sk, status, OltFlowsStatus.NONE, OltFlowsStatus.NONE);
743
744 }
745
746 DefaultFilteringObjective.Builder filterBuilder = DefaultFilteringObjective.builder();
747 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
748
749 int techProfileId = getDefaultTechProfileId(sub.port);
750 MeterId meterId = oltMeterService.getMeterIdForBandwidthProfile(sub.device.id(), bandwidthProfile);
751
752 // in the delete case the meter should still be there as we remove
753 // the meters only if no flows are pointing to them
754 if (meterId == null) {
755 log.debug("MeterId is null for BandwidthProfile {} on device {}",
756 bandwidthProfile, sub.device.id());
757 return false;
758 }
759
760 MeterId oltMeterId = oltMeterService.getMeterIdForBandwidthProfile(sub.device.id(), oltBandwidthProfile);
761 if (oltMeterId == null) {
762 log.debug("MeterId is null for OltBandwidthProfile {} on device {}",
763 oltBandwidthProfile, sub.device.id());
764 return false;
765 }
766
767 log.info("{} EAPOL flow for {} with vlanId {} and BandwidthProfile {} (meterId {})",
768 flowOpToString(action), portWithName(sub.port), vlanId, bandwidthProfile, meterId);
769
770 FilteringObjective.Builder eapolAction;
771
772 if (action == FlowOperation.ADD) {
773 eapolAction = filterBuilder.permit();
774 } else if (action == FlowOperation.REMOVE) {
775 eapolAction = filterBuilder.deny();
776 } else {
777 log.error("Operation {} not supported", action);
778 return false;
779 }
780
781 FilteringObjective.Builder baseEapol = eapolAction
782 .withKey(Criteria.matchInPort(sub.port.number()))
783 .addCondition(Criteria.matchEthType(EthType.EtherType.EAPOL.ethType()));
784
785 // NOTE we only need to add the treatment to install the flow,
786 // we can remove it based in the match
787 FilteringObjective.Builder eapol;
788
789 TrafficTreatment treatment = treatmentBuilder
790 .meter(meterId)
791 .writeMetadata(createTechProfValueForWriteMetadata(
792 vlanId,
793 techProfileId, oltMeterId), 0)
794 .setOutput(PortNumber.CONTROLLER)
795 .pushVlan()
796 .setVlanId(vlanId)
797 .build();
798 eapol = baseEapol
799 .withMeta(treatment);
800
801 FilteringObjective eapolObjective = eapol
802 .fromApp(appId)
803 .withPriority(MAX_PRIORITY)
804 .add(new ObjectiveContext() {
805 @Override
806 public void onSuccess(Objective objective) {
807 log.info("EAPOL flow objective {} for {}",
808 completeFlowOpToString(action), portWithName(sub.port));
809 if (log.isTraceEnabled()) {
810 log.trace("EAPOL flow details for port {}: {}", portWithName(sub.port), objective);
811 }
812 }
813
814 @Override
815 public void onError(Objective objective, ObjectiveError error) {
816 log.error("Cannot {} eapol flow for {} : {}", action,
817 portWithName(sub.port), error);
818
819 if (vlanId.id().equals(EAPOL_DEFAULT_VLAN)) {
820 updateConnectPointStatus(sk,
821 OltFlowsStatus.ERROR, null, null);
822 }
823 }
824 });
825
826 flowObjectiveService.filter(sub.device.id(), eapolObjective);
827
828 log.info("{} EAPOL filter for {}", completeFlowOpToString(action), portWithName(sub.port));
829 return true;
830 }
831
832 // FIXME it's confusing that si is not necessarily inside the DiscoveredSubscriber
833 private boolean handleSubscriberEapolFlows(DiscoveredSubscriber sub, FlowOperation action,
834 SubscriberAndDeviceInformation si) {
835 if (!enableEapol) {
836 return true;
837 }
838 // TODO verify we need an EAPOL flow for EACH service
839 AtomicBoolean success = new AtomicBoolean(true);
840 si.uniTagList().forEach(u -> {
841 // we assume that if subscriber flows are installed, tagged EAPOL is installed as well
842 boolean hasFlows = hasSubscriberFlows(sub.port, u);
843
844 // if the subscriber flows are present the EAPOL flow is present thus we don't need to install it,
845 // if the subscriber does not have flows the EAPOL flow is not present thus we don't need to remove it
846 if (action == FlowOperation.ADD && hasFlows ||
847 action == FlowOperation.REMOVE && !hasFlows) {
848 log.debug("Not {} EAPOL on {}({}) as subscriber flow status is {}", flowOpToString(action),
849 portWithName(sub.port), u.getServiceName(), hasFlows);
850 return;
851 }
852 log.info("{} EAPOL flows for subscriber {} on {} and service {}",
853 flowOpToString(action), si.id(), portWithName(sub.port), u.getServiceName());
854 if (!handleEapolFlow(sub, u.getUpstreamBandwidthProfile(),
855 u.getUpstreamOltBandwidthProfile(),
856 action, u.getPonCTag())) {
857 //
858 log.error("Failed to {} EAPOL with suscriber tags", action);
859 //TODO this sets it for all services, maybe some services succeeded.
860 success.set(false);
861 }
862 });
863 return success.get();
864 }
865
866 private void handleSubscriberIgmpFlows(DiscoveredSubscriber sub, FlowOperation action) {
867 sub.subscriberAndDeviceInformation.uniTagList().forEach(uti -> {
868 if (uti.getIsIgmpRequired()) {
869 DeviceId deviceId = sub.device.id();
870 // if we reached here a meter already exists
871 MeterId meterId = oltMeterService
872 .getMeterIdForBandwidthProfile(deviceId, uti.getUpstreamBandwidthProfile());
873 MeterId oltMeterId = oltMeterService
874 .getMeterIdForBandwidthProfile(deviceId, uti.getUpstreamOltBandwidthProfile());
875
876 processIgmpFilteringObjectives(deviceId, sub.port,
877 action, FlowDirection.UPSTREAM, meterId, oltMeterId, uti.getTechnologyProfileId(),
878 uti.getPonCTag(), uti.getUniTagMatch(), uti.getUsPonCTagPriority());
879 }
880 });
881 }
882
883 private boolean checkSadisRunning() {
884 if (bpService == null) {
885 log.warn("Sadis is not running");
886 return false;
887 }
888 return true;
889 }
890
891 private int getDefaultTechProfileId(Port port) {
892 if (!checkSadisRunning()) {
893 return defaultTechProfileId;
894 }
895 if (port != null) {
896 SubscriberAndDeviceInformation info = subsService.get(getPortName(port));
897 if (info != null && info.uniTagList().size() == 1) {
898 return info.uniTagList().get(0).getTechnologyProfileId();
899 }
900 }
901 return defaultTechProfileId;
902 }
903
904 protected Long createTechProfValueForWriteMetadata(VlanId cVlan, int techProfileId, MeterId upstreamOltMeterId) {
905 Long writeMetadata;
906
907 if (cVlan == null || VlanId.NONE.equals(cVlan)) {
908 writeMetadata = (long) techProfileId << 32;
909 } else {
910 writeMetadata = ((long) (cVlan.id()) << 48 | (long) techProfileId << 32);
911 }
912 if (upstreamOltMeterId == null) {
913 return writeMetadata;
914 } else {
915 return writeMetadata | upstreamOltMeterId.id();
916 }
917 }
918
919 private void processLldpFilteringObjective(DeviceId deviceId, Port port, FlowOperation action) {
920 DefaultFilteringObjective.Builder builder = DefaultFilteringObjective.builder();
921
922 FilteringObjective lldp = (action == FlowOperation.ADD ? builder.permit() : builder.deny())
923 .withKey(Criteria.matchInPort(port.number()))
924 .addCondition(Criteria.matchEthType(EthType.EtherType.LLDP.ethType()))
925 .withMeta(DefaultTrafficTreatment.builder()
926 .setOutput(PortNumber.CONTROLLER).build())
927 .fromApp(appId)
928 .withPriority(MAX_PRIORITY)
929 .add(new ObjectiveContext() {
930 @Override
931 public void onSuccess(Objective objective) {
932 log.info("{} LLDP filter for {}.", completeFlowOpToString(action), portWithName(port));
933 }
934
935 @Override
936 public void onError(Objective objective, ObjectiveError error) {
937 log.error("Falied to {} LLDP filter on {} because {}", action, portWithName(port),
938 error);
939 }
940 });
941
942 flowObjectiveService.filter(deviceId, lldp);
943 }
944
945 protected void handleSubscriberDhcpFlows(DeviceId deviceId, Port port,
946 FlowOperation action,
947 SubscriberAndDeviceInformation si) {
948 si.uniTagList().forEach(uti -> {
949
950 if (!uti.getIsDhcpRequired()) {
951 return;
952 }
953
954 // if it's an ADD skip if flows are there,
955 // if it's a DELETE skip if flows are not there
956 boolean hasFlows = hasDhcpFlows(port, uti);
957 if (action == FlowOperation.ADD && hasFlows ||
958 action == FlowOperation.REMOVE && !hasFlows) {
959 log.debug("Not dealing with DHCP {} on {} as DHCP flow status is {}", action,
960 uti.getServiceName(), hasFlows);
961 return;
962 }
963
964 log.info("{} DHCP flows for subscriber on {} and service {}",
965 flowOpToString(action), portWithName(port), uti.getServiceName());
966
967 // if we reached here a meter already exists
968 MeterId meterId = oltMeterService
969 .getMeterIdForBandwidthProfile(deviceId, uti.getUpstreamBandwidthProfile());
970 MeterId oltMeterId = oltMeterService
971 .getMeterIdForBandwidthProfile(deviceId, uti.getUpstreamOltBandwidthProfile());
972
973 if (enableDhcpV4) {
974 processDhcpFilteringObjectives(deviceId, port, action, FlowDirection.UPSTREAM, 68, 67,
975 EthType.EtherType.IPV4.ethType(), IPv4.PROTOCOL_UDP, meterId, oltMeterId,
976 uti);
977 }
978 if (enableDhcpV6) {
979 log.error("DHCP V6 not supported for subscribers");
980 }
981 });
982 }
983
984 // FIXME return boolean, if this fails we need to retry
985 protected void handleSubscriberDataFlows(Device device, Port port,
986 FlowOperation action,
987 SubscriberAndDeviceInformation si, String multicastServiceName) {
988
989 Optional<Port> nniPort = oltDeviceService.getNniPort(device);
990 if (nniPort.isEmpty()) {
991 log.error("Cannot configure DP flows as upstream port is not configured for subscriber {} on {}",
992 si.id(), portWithName(port));
993 return;
994 }
995 si.uniTagList().forEach(uti -> {
996
997 boolean hasFlows = hasSubscriberFlows(port, uti);
998 if (action == FlowOperation.ADD && hasFlows ||
999 action == FlowOperation.REMOVE && !hasFlows) {
1000 log.debug("Not dealing with DP flows {} on {} as subscriber flow status is {}", action,
1001 uti.getServiceName(), hasFlows);
1002 return;
1003 }
1004
1005 if (multicastServiceName.equals(uti.getServiceName())) {
1006 log.debug("This is the multicast service ({}) for subscriber {} on {}, " +
1007 "dataplane flows are not needed",
1008 uti.getServiceName(), si.id(), portWithName(port));
1009 return;
1010 }
1011
1012 log.info("{} Data plane flows for subscriber {} on {} and service {}",
1013 flowOpToString(action), si.id(), portWithName(port), uti.getServiceName());
1014
1015 // upstream flows
1016 MeterId usMeterId = oltMeterService
1017 .getMeterIdForBandwidthProfile(device.id(), uti.getUpstreamBandwidthProfile());
1018 MeterId oltUsMeterId = oltMeterService
1019 .getMeterIdForBandwidthProfile(device.id(), uti.getUpstreamOltBandwidthProfile());
1020 processUpstreamDataFilteringObjects(device.id(), port, nniPort.get(), action, usMeterId,
1021 oltUsMeterId, uti);
1022
1023 // downstream flows
1024 MeterId dsMeterId = oltMeterService
1025 .getMeterIdForBandwidthProfile(device.id(), uti.getDownstreamBandwidthProfile());
1026 MeterId oltDsMeterId = oltMeterService
1027 .getMeterIdForBandwidthProfile(device.id(), uti.getDownstreamOltBandwidthProfile());
1028 processDownstreamDataFilteringObjects(device.id(), port, nniPort.get(), action, dsMeterId,
1029 oltDsMeterId, uti, getMacAddress(device.id(), port, uti));
1030 });
1031 }
1032
1033 private void processDhcpFilteringObjectives(DeviceId deviceId, Port port,
1034 FlowOperation action, FlowDirection direction,
1035 int udpSrc, int udpDst, EthType ethType, byte protocol,
1036 MeterId meterId, MeterId oltMeterId, UniTagInformation uti) {
1037 ServiceKey sk = new ServiceKey(new AccessDevicePort(port), uti);
1038 log.debug("{} DHCP filtering objectives on {}", flowOpToString(action), sk);
1039
1040
1041 OltFlowsStatus status = action.equals(FlowOperation.ADD) ?
1042 OltFlowsStatus.PENDING_ADD : OltFlowsStatus.PENDING_REMOVE;
1043 updateConnectPointStatus(sk, null, null, status);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001044
1045 DefaultFilteringObjective.Builder builder = DefaultFilteringObjective.builder();
1046 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
1047
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001048 if (meterId != null) {
1049 treatmentBuilder.meter(meterId);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001050 }
1051
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001052 if (uti.getTechnologyProfileId() != NONE_TP_ID) {
1053 treatmentBuilder.writeMetadata(
1054 createTechProfValueForWriteMetadata(uti.getUniTagMatch(),
1055 uti.getTechnologyProfileId(), oltMeterId), 0);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001056 }
1057
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001058 FilteringObjective.Builder dhcpBuilder = (action == FlowOperation.ADD ? builder.permit() : builder.deny())
Tunahan Sezenf0843b92021-04-30 07:13:16 +00001059 .withKey(Criteria.matchInPort(port.number()))
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001060 .addCondition(Criteria.matchEthType(ethType))
1061 .addCondition(Criteria.matchIPProtocol(protocol))
1062 .addCondition(Criteria.matchUdpSrc(TpPort.tpPort(udpSrc)))
1063 .addCondition(Criteria.matchUdpDst(TpPort.tpPort(udpDst)))
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001064 .fromApp(appId)
1065 .withPriority(MAX_PRIORITY);
1066
Andrea Campanella0e34f562020-06-11 10:47:10 +02001067 //VLAN changes and PCP matching need to happen only in the upstream directions
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001068 if (direction == FlowDirection.UPSTREAM) {
1069 treatmentBuilder.setVlanId(uti.getPonCTag());
1070 if (!VlanId.vlanId(VlanId.NO_VID).equals(uti.getUniTagMatch())) {
1071 dhcpBuilder.addCondition(Criteria.matchVlanId(uti.getUniTagMatch()));
Andrea Campanella0e34f562020-06-11 10:47:10 +02001072 }
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001073 if (uti.getUsPonCTagPriority() != -1) {
1074 treatmentBuilder.setVlanPcp((byte) uti.getUsPonCTagPriority());
Andrea Campanella0e34f562020-06-11 10:47:10 +02001075 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001076 }
1077
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001078 dhcpBuilder.withMeta(treatmentBuilder
1079 .setOutput(PortNumber.CONTROLLER).build());
Andrea Campanella0e34f562020-06-11 10:47:10 +02001080
1081
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001082 FilteringObjective dhcpUpstream = dhcpBuilder.add(new ObjectiveContext() {
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001083 @Override
1084 public void onSuccess(Objective objective) {
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001085 log.info("{} DHCP {} filter for {}.",
1086 completeFlowOpToString(action), (ethType.equals(EthType.EtherType.IPV4.ethType())) ? V4 : V6,
1087 portWithName(port));
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001088 }
1089
1090 @Override
1091 public void onError(Objective objective, ObjectiveError error) {
Tunahan Sezenf0843b92021-04-30 07:13:16 +00001092 log.error("DHCP {} filter for {} failed {} because {}",
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001093 (ethType.equals(EthType.EtherType.IPV4.ethType())) ? V4 : V6,
1094 portWithName(port),
1095 action,
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001096 error);
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001097 updateConnectPointStatus(sk, null, null, OltFlowsStatus.ERROR);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001098 }
1099 });
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001100 flowObjectiveService.filter(deviceId, dhcpUpstream);
1101 }
1102
1103 private void processIgmpFilteringObjectives(DeviceId deviceId, Port port,
1104 FlowOperation action, FlowDirection direction,
1105 MeterId meterId, MeterId oltMeterId, int techProfileId,
1106 VlanId cTag, VlanId unitagMatch, int vlanPcp) {
1107
1108 DefaultFilteringObjective.Builder filterBuilder = DefaultFilteringObjective.builder();
1109 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
1110 if (direction == FlowDirection.UPSTREAM) {
1111
1112 if (techProfileId != NONE_TP_ID) {
1113 treatmentBuilder.writeMetadata(createTechProfValueForWriteMetadata(null,
1114 techProfileId, oltMeterId), 0);
1115 }
1116
1117
1118 if (meterId != null) {
1119 treatmentBuilder.meter(meterId);
1120 }
1121
1122 if (!VlanId.vlanId(VlanId.NO_VID).equals(unitagMatch)) {
1123 filterBuilder.addCondition(Criteria.matchVlanId(unitagMatch));
1124 }
1125
1126 if (!VlanId.vlanId(VlanId.NO_VID).equals(cTag)) {
1127 treatmentBuilder.setVlanId(cTag);
1128 }
1129
1130 if (vlanPcp != -1) {
1131 treatmentBuilder.setVlanPcp((byte) vlanPcp);
1132 }
1133 }
1134
1135 filterBuilder = (action == FlowOperation.ADD) ? filterBuilder.permit() : filterBuilder.deny();
1136
1137 FilteringObjective igmp = filterBuilder
1138 .withKey(Criteria.matchInPort(port.number()))
1139 .addCondition(Criteria.matchEthType(EthType.EtherType.IPV4.ethType()))
1140 .addCondition(Criteria.matchIPProtocol(IPv4.PROTOCOL_IGMP))
1141 .withMeta(treatmentBuilder
1142 .setOutput(PortNumber.CONTROLLER).build())
1143 .fromApp(appId)
1144 .withPriority(MAX_PRIORITY)
1145 .add(new ObjectiveContext() {
1146 @Override
1147 public void onSuccess(Objective objective) {
1148 log.info("Igmp filter for {} {}.", portWithName(port), action);
1149 }
1150
1151 @Override
1152 public void onError(Objective objective, ObjectiveError error) {
1153 log.error("Igmp filter for {} failed {} because {}.", portWithName(port), action,
1154 error);
1155 }
1156 });
1157
1158 flowObjectiveService.filter(deviceId, igmp);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001159
1160 }
1161
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001162 private void processPPPoEDFilteringObjectives(DeviceId deviceId, Port port,
1163 FlowOperation action, FlowDirection direction,
1164 MeterId meterId, MeterId oltMeterId, int techProfileId,
1165 VlanId cTag, VlanId unitagMatch, Byte vlanPcp) {
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001166
1167 DefaultFilteringObjective.Builder builder = DefaultFilteringObjective.builder();
1168 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001169
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001170 if (meterId != null) {
1171 treatmentBuilder.meter(meterId);
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001172 }
1173
1174 if (techProfileId != NONE_TP_ID) {
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001175 treatmentBuilder.writeMetadata(createTechProfValueForWriteMetadata(cTag, techProfileId, oltMeterId), 0);
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001176 }
1177
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001178 DefaultFilteringObjective.Builder pppoedBuilder = ((action == FlowOperation.ADD)
1179 ? builder.permit() : builder.deny())
Tunahan Sezenf0843b92021-04-30 07:13:16 +00001180 .withKey(Criteria.matchInPort(port.number()))
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001181 .addCondition(Criteria.matchEthType(EthType.EtherType.PPPoED.ethType()))
1182 .fromApp(appId)
1183 .withPriority(10000);
1184
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001185 if (direction == FlowDirection.UPSTREAM) {
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001186 treatmentBuilder.setVlanId(cTag);
1187 if (!VlanId.vlanId(VlanId.NO_VID).equals(unitagMatch)) {
1188 pppoedBuilder.addCondition(Criteria.matchVlanId(unitagMatch));
1189 }
1190 if (vlanPcp != null) {
1191 treatmentBuilder.setVlanPcp(vlanPcp);
1192 }
1193 }
1194 pppoedBuilder = pppoedBuilder.withMeta(treatmentBuilder.setOutput(PortNumber.CONTROLLER).build());
1195
1196 FilteringObjective pppoed = pppoedBuilder
1197 .add(new ObjectiveContext() {
1198 @Override
1199 public void onSuccess(Objective objective) {
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001200 log.info("PPPoED filter for {} {}.", portWithName(port), action);
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001201 }
1202
1203 @Override
1204 public void onError(Objective objective, ObjectiveError error) {
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001205 log.info("PPPoED filter for {} failed {} because {}", portWithName(port),
1206 action, error);
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001207 }
1208 });
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001209 flowObjectiveService.filter(deviceId, pppoed);
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001210 }
1211
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001212 private void processUpstreamDataFilteringObjects(DeviceId deviceId, Port port, Port nniPort,
1213 FlowOperation action,
1214 MeterId upstreamMeterId,
1215 MeterId upstreamOltMeterId,
1216 UniTagInformation uti) {
1217 ServiceKey sk = new ServiceKey(new AccessDevicePort(port), uti);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001218 TrafficSelector selector = DefaultTrafficSelector.builder()
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001219 .matchInPort(port.number())
1220 .matchVlanId(uti.getUniTagMatch())
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001221 .build();
1222
Andrea Campanella327c5722020-01-30 11:34:13 +01001223 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
1224 //if the subscriberVlan (cTag) is different than ANY it needs to set.
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001225 if (uti.getPonCTag().toShort() != VlanId.ANY_VALUE) {
Andrea Campanella327c5722020-01-30 11:34:13 +01001226 treatmentBuilder.pushVlan()
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001227 .setVlanId(uti.getPonCTag());
Andrea Campanella327c5722020-01-30 11:34:13 +01001228 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001229
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001230 if (uti.getUsPonCTagPriority() != -1) {
1231 treatmentBuilder.setVlanPcp((byte) uti.getUsPonCTagPriority());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001232 }
1233
1234 treatmentBuilder.pushVlan()
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001235 .setVlanId(uti.getPonSTag());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001236
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001237 if (uti.getUsPonSTagPriority() != -1) {
1238 treatmentBuilder.setVlanPcp((byte) uti.getUsPonSTagPriority());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001239 }
1240
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001241 treatmentBuilder.setOutput(nniPort.number())
1242 .writeMetadata(createMetadata(uti.getPonCTag(),
1243 uti.getTechnologyProfileId(), nniPort.number()), 0L);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001244
yasin saplib4b8ee12021-06-13 18:25:20 +00001245 DefaultAnnotations.Builder annotationBuilder = DefaultAnnotations.builder();
1246
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001247 if (upstreamMeterId != null) {
1248 treatmentBuilder.meter(upstreamMeterId);
yasin saplib4b8ee12021-06-13 18:25:20 +00001249 annotationBuilder.set(UPSTREAM_ONU, upstreamMeterId.toString());
1250 }
1251 if (upstreamOltMeterId != null) {
1252 treatmentBuilder.meter(upstreamOltMeterId);
1253 annotationBuilder.set(UPSTREAM_OLT, upstreamOltMeterId.toString());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001254 }
1255
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001256 DefaultForwardingObjective.Builder flowBuilder = createForwardingObjectiveBuilder(selector,
1257 treatmentBuilder.build(), MIN_PRIORITY,
yasin saplib4b8ee12021-06-13 18:25:20 +00001258 annotationBuilder.build());
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001259
1260 ObjectiveContext context = new ObjectiveContext() {
1261 @Override
1262 public void onSuccess(Objective objective) {
1263 log.info("{} Upstream Data plane filter for {}.",
1264 completeFlowOpToString(action), sk);
1265 }
1266
1267 @Override
1268 public void onError(Objective objective, ObjectiveError error) {
1269 log.error("Upstream Data plane filter for {} failed {} because {}.",
1270 sk, action, error);
1271 updateConnectPointStatus(sk, null, OltFlowsStatus.ERROR, null);
1272 }
1273 };
1274
1275 ForwardingObjective flow = null;
1276 if (action == FlowOperation.ADD) {
1277 flow = flowBuilder.add(context);
1278 } else if (action == FlowOperation.REMOVE) {
1279 flow = flowBuilder.remove(context);
1280 } else {
1281 log.error("Flow action not supported: {}", action);
1282 }
1283
1284 if (flow != null) {
1285 flowObjectiveService.forward(deviceId, flow);
1286 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001287 }
1288
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001289 private void processDownstreamDataFilteringObjects(DeviceId deviceId, Port port, Port nniPort,
1290 FlowOperation action,
1291 MeterId downstreamMeterId,
1292 MeterId downstreamOltMeterId,
1293 UniTagInformation uti,
1294 MacAddress macAddress) {
1295 ServiceKey sk = new ServiceKey(new AccessDevicePort(port), uti);
Andrea Campanella327c5722020-01-30 11:34:13 +01001296 //subscriberVlan can be any valid Vlan here including ANY to make sure the packet is tagged
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001297 TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder()
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001298 .matchVlanId(uti.getPonSTag())
1299 .matchInPort(nniPort.number())
1300 .matchInnerVlanId(uti.getPonCTag());
Andrea Campanella090e4a02020-02-05 13:53:55 +01001301
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001302 if (uti.getPonCTag().toShort() != VlanId.ANY_VALUE) {
1303 selectorBuilder.matchMetadata(uti.getPonCTag().toShort());
Andrea Campanella090e4a02020-02-05 13:53:55 +01001304 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001305
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001306 if (uti.getDsPonCTagPriority() != -1) {
1307 selectorBuilder.matchVlanPcp((byte) uti.getDsPonCTagPriority());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001308 }
1309
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001310 if (macAddress != null) {
1311 selectorBuilder.matchEthDst(macAddress);
1312 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001313
1314 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder()
1315 .popVlan()
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001316 .setOutput(port.number());
Andrea Campanella327c5722020-01-30 11:34:13 +01001317
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001318 treatmentBuilder.writeMetadata(createMetadata(uti.getPonCTag(),
1319 uti.getTechnologyProfileId(),
1320 port.number()), 0);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001321
Andrea Campanella981e86c2021-03-12 11:35:33 +01001322 // Upstream pbit is used to remark inner vlan pbit.
1323 // Upstream is used to avoid trusting the BNG to send the packet with correct pbit.
1324 // this is done because ds mode 0 is used because ds mode 3 or 6 that allow for
1325 // all pbit acceptance are not widely supported by vendors even though present in
1326 // the OMCI spec.
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001327 if (uti.getUsPonCTagPriority() != -1) {
1328 treatmentBuilder.setVlanPcp((byte) uti.getUsPonCTagPriority());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001329 }
1330
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001331 if (!VlanId.NONE.equals(uti.getUniTagMatch()) &&
1332 uti.getPonCTag().toShort() != VlanId.ANY_VALUE) {
1333 treatmentBuilder.setVlanId(uti.getUniTagMatch());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001334 }
1335
yasin saplib4b8ee12021-06-13 18:25:20 +00001336 DefaultAnnotations.Builder annotationBuilder = DefaultAnnotations.builder();
1337
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001338 if (downstreamMeterId != null) {
1339 treatmentBuilder.meter(downstreamMeterId);
yasin saplib4b8ee12021-06-13 18:25:20 +00001340 annotationBuilder.set(DOWNSTREAM_ONU, downstreamMeterId.toString());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001341 }
1342
yasin saplib4b8ee12021-06-13 18:25:20 +00001343 if (downstreamOltMeterId != null) {
1344 treatmentBuilder.meter(downstreamOltMeterId);
1345 annotationBuilder.set(DOWNSTREAM_OLT, downstreamOltMeterId.toString());
1346 }
1347
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001348 DefaultForwardingObjective.Builder flowBuilder = createForwardingObjectiveBuilder(selectorBuilder.build(),
1349 treatmentBuilder.build(), MIN_PRIORITY, annotationBuilder.build());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001350
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001351 ObjectiveContext context = new ObjectiveContext() {
1352 @Override
1353 public void onSuccess(Objective objective) {
1354 log.info("{} Downstream Data plane filter for {}.",
1355 completeFlowOpToString(action), sk);
1356 }
1357
1358 @Override
1359 public void onError(Objective objective, ObjectiveError error) {
1360 log.info("Downstream Data plane filter for {} failed {} because {}.",
1361 sk, action, error);
1362 updateConnectPointStatus(sk, null, OltFlowsStatus.ERROR, null);
1363 }
1364 };
1365
1366 ForwardingObjective flow = null;
1367 if (action == FlowOperation.ADD) {
1368 flow = flowBuilder.add(context);
1369 } else if (action == FlowOperation.REMOVE) {
1370 flow = flowBuilder.remove(context);
1371 } else {
1372 log.error("Flow action not supported: {}", action);
1373 }
1374
1375 if (flow != null) {
1376 if (log.isTraceEnabled()) {
1377 log.trace("Forwarding rule {}", flow);
1378 }
1379 flowObjectiveService.forward(deviceId, flow);
1380 }
Andrea Campanella600d2e22020-06-22 11:00:31 +02001381 }
1382
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001383 private DefaultForwardingObjective.Builder createForwardingObjectiveBuilder(TrafficSelector selector,
1384 TrafficTreatment treatment,
yasin saplib4b8ee12021-06-13 18:25:20 +00001385 Integer priority,
1386 Annotations annotations) {
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001387 return DefaultForwardingObjective.builder()
1388 .withFlag(ForwardingObjective.Flag.VERSATILE)
1389 .withPriority(priority)
1390 .makePermanent()
1391 .withSelector(selector)
yasin saplib4b8ee12021-06-13 18:25:20 +00001392 .withAnnotations(annotations)
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001393 .fromApp(appId)
1394 .withTreatment(treatment);
1395 }
1396
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001397 private Long createMetadata(VlanId innerVlan, int techProfileId, PortNumber egressPort) {
1398 if (techProfileId == NONE_TP_ID) {
Andrea Campanella7c49b792020-05-11 11:36:53 +02001399 techProfileId = DEFAULT_TP_ID_DEFAULT;
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001400 }
1401
1402 return ((long) (innerVlan.id()) << 48 | (long) techProfileId << 32) | egressPort.toLong();
1403 }
1404
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001405 private boolean isMacLearningEnabled(SubscriberAndDeviceInformation si) {
1406 AtomicBoolean requiresMacLearning = new AtomicBoolean();
1407 requiresMacLearning.set(false);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001408
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001409 si.uniTagList().forEach(uniTagInfo -> {
1410 if (uniTagInfo.getEnableMacLearning()) {
1411 requiresMacLearning.set(true);
1412 }
1413 });
1414
1415 return requiresMacLearning.get();
1416 }
1417
1418 /**
1419 * Checks whether the subscriber has the MacAddress configured or discovered.
1420 *
1421 * @param deviceId DeviceId for this subscriber
1422 * @param port Port for this subscriber
1423 * @param si SubscriberAndDeviceInformation
1424 * @return boolean
1425 */
1426 protected boolean isMacAddressAvailable(DeviceId deviceId, Port port, SubscriberAndDeviceInformation si) {
1427 AtomicBoolean isConfigured = new AtomicBoolean();
1428 isConfigured.set(true);
1429
1430 si.uniTagList().forEach(uniTagInfo -> {
1431 boolean isMacLearningEnabled = uniTagInfo.getEnableMacLearning();
1432 boolean configureMac = isMacAddressValid(uniTagInfo);
1433 boolean discoveredMac = false;
1434 Optional<Host> optHost = hostService.getConnectedHosts(new ConnectPoint(deviceId, port.number()))
1435 .stream().filter(host -> host.vlan().equals(uniTagInfo.getPonCTag())).findFirst();
1436 if (optHost.isPresent() && optHost.get().mac() != null) {
1437 discoveredMac = true;
1438 }
1439 if (isMacLearningEnabled && !configureMac && !discoveredMac) {
1440 log.debug("Awaiting for macAddress on {} for service {}",
1441 portWithName(port), uniTagInfo.getServiceName());
1442 isConfigured.set(false);
1443 }
1444 });
1445
1446 return isConfigured.get();
1447 }
1448
1449 protected MacAddress getMacAddress(DeviceId deviceId, Port port, UniTagInformation uniTagInfo) {
1450 boolean configuredMac = isMacAddressValid(uniTagInfo);
1451 if (configuredMac) {
1452 return MacAddress.valueOf(uniTagInfo.getConfiguredMacAddress());
1453 } else if (uniTagInfo.getEnableMacLearning()) {
1454 Optional<Host> optHost = hostService.getConnectedHosts(new ConnectPoint(deviceId, port.number()))
1455 .stream().filter(host -> host.vlan().equals(uniTagInfo.getPonCTag())).findFirst();
1456 if (optHost.isPresent() && optHost.get().mac() != null) {
1457 return optHost.get().mac();
1458 }
1459 }
1460 return null;
1461 }
1462
1463 private boolean isMacAddressValid(UniTagInformation tagInformation) {
1464 return tagInformation.getConfiguredMacAddress() != null &&
1465 !tagInformation.getConfiguredMacAddress().trim().equals("") &&
1466 !MacAddress.NONE.equals(MacAddress.valueOf(tagInformation.getConfiguredMacAddress()));
1467 }
1468
1469 protected void updateConnectPointStatus(ServiceKey key, OltFlowsStatus eapolStatus,
1470 OltFlowsStatus subscriberFlowsStatus, OltFlowsStatus dhcpStatus) {
1471 try {
1472 cpStatusWriteLock.lock();
1473 OltPortStatus status = cpStatus.get(key);
1474
1475 if (status == null) {
1476 status = new OltPortStatus(
1477 eapolStatus != null ? eapolStatus : OltFlowsStatus.NONE,
1478 subscriberFlowsStatus != null ? subscriberFlowsStatus : OltFlowsStatus.NONE,
1479 dhcpStatus != null ? dhcpStatus : OltFlowsStatus.NONE
1480 );
1481 } else {
1482 if (eapolStatus != null) {
1483 status.defaultEapolStatus = eapolStatus;
1484 }
1485 if (subscriberFlowsStatus != null) {
1486 status.subscriberFlowsStatus = subscriberFlowsStatus;
1487 }
1488 if (dhcpStatus != null) {
1489 status.dhcpStatus = dhcpStatus;
1490 }
1491 }
1492
1493 cpStatus.put(key, status);
1494 } finally {
1495 cpStatusWriteLock.unlock();
1496 }
1497 }
1498
1499 protected class InternalFlowListener implements FlowRuleListener {
1500 @Override
1501 public void event(FlowRuleEvent event) {
1502 if (appId.id() != (event.subject().appId())) {
1503 return;
1504 }
1505
1506 if (!oltDeviceService.isLocalLeader(event.subject().deviceId())) {
1507 if (log.isTraceEnabled()) {
1508 log.trace("ignoring flow event {} " +
1509 "as not leader for {}", event, event.subject().deviceId());
1510 }
1511 return;
1512 }
1513
1514 switch (event.type()) {
1515 case RULE_ADDED:
1516 case RULE_REMOVED:
1517 Port port = getCpFromFlowRule(event.subject());
1518 if (port == null) {
1519 log.error("Can't find port in flow {}", event.subject());
1520 return;
1521 }
1522 if (log.isTraceEnabled()) {
1523 log.trace("flow event {} on cp {}: {}", event.type(),
1524 portWithName(port), event.subject());
1525 }
1526 updateCpStatus(event.type(), port, event.subject());
1527 return;
1528 case RULE_ADD_REQUESTED:
1529 case RULE_REMOVE_REQUESTED:
1530 // NOTE that PENDING_ADD/REMOVE is set when we create the flowObjective
1531 return;
1532 default:
1533 return;
1534 }
1535 }
1536
1537 protected void updateCpStatus(FlowRuleEvent.Type type, Port port, FlowRule flowRule) {
1538 OltFlowsStatus status = flowRuleStatusToOltFlowStatus(type);
1539 if (isDefaultEapolFlow(flowRule)) {
1540 ServiceKey sk = new ServiceKey(new AccessDevicePort(port),
1541 defaultEapolUniTag);
1542 if (log.isTraceEnabled()) {
1543 log.trace("update defaultEapolStatus {} on {}", status, sk);
1544 }
1545 updateConnectPointStatus(sk, status, null, null);
1546 } else if (isDhcpFlow(flowRule)) {
1547 ServiceKey sk = getSubscriberKeyFromFlowRule(flowRule);
1548 if (sk == null) {
1549 return;
1550 }
1551 if (log.isTraceEnabled()) {
1552 log.trace("update dhcpStatus {} on {}", status, sk);
1553 }
1554 updateConnectPointStatus(sk, null, null, status);
1555 } else if (isDataFlow(flowRule)) {
1556
1557 if (oltDeviceService.isNniPort(deviceService.getDevice(flowRule.deviceId()),
1558 getCpFromFlowRule(flowRule).number())) {
1559 // the NNI has data-plane for every subscriber, doesn't make sense to track them
1560 return;
1561 }
1562
1563 ServiceKey sk = getSubscriberKeyFromFlowRule(flowRule);
1564 if (sk == null) {
1565 return;
1566 }
1567 if (log.isTraceEnabled()) {
1568 log.trace("update dataplaneStatus {} on {}", status, sk);
1569 }
1570 updateConnectPointStatus(sk, null, status, null);
1571 }
1572 }
1573
1574 private boolean isDefaultEapolFlow(FlowRule flowRule) {
1575 EthTypeCriterion c = (EthTypeCriterion) flowRule.selector().getCriterion(Criterion.Type.ETH_TYPE);
1576 if (c == null) {
1577 return false;
1578 }
1579 if (c.ethType().equals(EthType.EtherType.EAPOL.ethType())) {
1580 AtomicBoolean isDefault = new AtomicBoolean(false);
1581 flowRule.treatment().allInstructions().forEach(instruction -> {
1582 if (instruction.type() == L2MODIFICATION) {
1583 L2ModificationInstruction modificationInstruction = (L2ModificationInstruction) instruction;
1584 if (modificationInstruction.subtype() == L2ModificationInstruction.L2SubType.VLAN_ID) {
1585 L2ModificationInstruction.ModVlanIdInstruction vlanInstruction =
1586 (L2ModificationInstruction.ModVlanIdInstruction) modificationInstruction;
1587 if (vlanInstruction.vlanId().id().equals(EAPOL_DEFAULT_VLAN)) {
1588 isDefault.set(true);
1589 return;
1590 }
1591 }
1592 }
1593 });
1594 return isDefault.get();
1595 }
1596 return false;
1597 }
1598
1599 /**
1600 * Returns true if the flow is a DHCP flow.
1601 * Matches both upstream and downstream flows.
1602 *
1603 * @param flowRule The FlowRule to evaluate
1604 * @return boolean
1605 */
1606 private boolean isDhcpFlow(FlowRule flowRule) {
1607 IPProtocolCriterion ipCriterion = (IPProtocolCriterion) flowRule.selector()
1608 .getCriterion(Criterion.Type.IP_PROTO);
1609 if (ipCriterion == null) {
1610 return false;
1611 }
1612
1613 UdpPortCriterion src = (UdpPortCriterion) flowRule.selector().getCriterion(Criterion.Type.UDP_SRC);
1614
1615 if (src == null) {
1616 return false;
1617 }
1618 return ipCriterion.protocol() == IPv4.PROTOCOL_UDP &&
1619 (src.udpPort().toInt() == 68 || src.udpPort().toInt() == 67);
1620 }
1621
1622 private boolean isDataFlow(FlowRule flowRule) {
1623 // we consider subscriber flows the one that matches on VLAN_VID
1624 // method is valid only because it's the last check after EAPOL and DHCP.
1625 // this matches mcast flows as well, if we want to avoid that we can
1626 // filter out the elements that have groups in the treatment or
1627 // mcastIp in the selector
1628 // IPV4_DST:224.0.0.22/32
1629 // treatment=[immediate=[GROUP:0x1]]
1630
1631 return flowRule.selector().getCriterion(Criterion.Type.VLAN_VID) != null;
1632 }
1633
1634 private Port getCpFromFlowRule(FlowRule flowRule) {
1635 DeviceId deviceId = flowRule.deviceId();
1636 PortCriterion inPort = (PortCriterion) flowRule.selector().getCriterion(Criterion.Type.IN_PORT);
1637 if (inPort != null) {
1638 PortNumber port = inPort.port();
1639 return deviceService.getPort(deviceId, port);
1640 }
1641 return null;
1642 }
1643
1644 private ServiceKey getSubscriberKeyFromFlowRule(FlowRule flowRule) {
1645 Port flowPort = getCpFromFlowRule(flowRule);
1646 SubscriberAndDeviceInformation si = subsService.get(getPortName(flowPort));
1647
1648 Boolean isNni = oltDeviceService.isNniPort(deviceService.getDevice(flowRule.deviceId()), flowPort.number());
1649 if (si == null && !isNni) {
1650 log.error("Subscriber information not found in sadis for port {}", portWithName(flowPort));
1651 return null;
1652 }
1653
1654 if (isNni) {
1655 return new ServiceKey(new AccessDevicePort(flowPort), nniUniTag);
1656 }
1657
1658 Optional<UniTagInformation> found = Optional.empty();
1659 VlanId flowVlan = null;
1660 if (isDhcpFlow(flowRule)) {
1661 // we need to make a special case for DHCP as in the ATT workflow DHCP flows don't match on tags
1662 L2ModificationInstruction.ModVlanIdInstruction instruction =
1663 (L2ModificationInstruction.ModVlanIdInstruction) flowRule.treatment().immediate().get(1);
1664 flowVlan = instruction.vlanId();
1665 } else {
1666 // for now we assume that if it's not DHCP it's dataplane (or at least tagged)
1667 VlanIdCriterion vlanIdCriterion =
1668 (VlanIdCriterion) flowRule.selector().getCriterion(Criterion.Type.VLAN_VID);
1669 if (vlanIdCriterion == null) {
1670 log.warn("cannot match the flow to a subscriber service as it does not carry vlans");
1671 return null;
1672 }
1673 flowVlan = vlanIdCriterion.vlanId();
1674 }
1675
1676 VlanId finalFlowVlan = flowVlan;
1677 found = si.uniTagList().stream().filter(uti ->
1678 uti.getPonCTag().equals(finalFlowVlan) ||
1679 uti.getPonSTag().equals(finalFlowVlan) ||
1680 uti.getUniTagMatch().equals(finalFlowVlan)
1681 ).findFirst();
1682
1683
1684 if (found.isEmpty()) {
1685 log.warn("Cannot map flow rule {} to Service in {}", flowRule, si);
1686 }
1687
1688 return found.isPresent() ? new ServiceKey(new AccessDevicePort(flowPort), found.get()) : null;
1689
1690 }
1691
1692 private OltFlowsStatus flowRuleStatusToOltFlowStatus(FlowRuleEvent.Type type) {
1693 switch (type) {
1694 case RULE_ADD_REQUESTED:
1695 return OltFlowsStatus.PENDING_ADD;
1696 case RULE_ADDED:
1697 return OltFlowsStatus.ADDED;
1698 case RULE_REMOVE_REQUESTED:
1699 return OltFlowsStatus.PENDING_REMOVE;
1700 case RULE_REMOVED:
1701 return OltFlowsStatus.REMOVED;
1702 default:
1703 return OltFlowsStatus.NONE;
1704 }
1705 }
1706 }
1707
1708 protected void bindSadisService(SadisService service) {
1709 this.subsService = service.getSubscriberInfoService();
1710 this.bpService = service.getBandwidthProfileService();
1711 log.info("Sadis service is loaded");
1712 }
1713
1714 protected void unbindSadisService(SadisService service) {
1715 this.subsService = null;
1716 this.bpService = null;
1717 log.info("Sadis service is unloaded");
1718 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001719}