blob: f798e252e57ebdddf26aae8b22aa44f04da3c2cc [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
Matteo Scandolo2542e5d2021-12-01 16:53:41 -080085import java.util.ArrayList;
Andrea Campanella7a1d7e72020-11-05 10:40:10 +010086import java.util.Dictionary;
Matteo Scandoloaa2adde2021-09-13 12:45:32 -070087import java.util.HashMap;
88import java.util.Iterator;
Matteo Scandolo2542e5d2021-12-01 16:53:41 -080089import java.util.List;
Ilayda Ozdemir90a93622021-02-25 09:40:58 +000090import java.util.Map;
Andrea Campanellabfb47af2021-06-03 11:09:45 +020091import java.util.Optional;
Andrea Campanella7a1d7e72020-11-05 10:40:10 +010092import java.util.Properties;
Matteo Scandoloaa2adde2021-09-13 12:45:32 -070093import java.util.concurrent.atomic.AtomicBoolean;
94import java.util.concurrent.locks.Lock;
95import java.util.concurrent.locks.ReentrantReadWriteLock;
Andrea Campanella7a1d7e72020-11-05 10:40:10 +010096
97import static com.google.common.base.Strings.isNullOrEmpty;
98import static org.onlab.util.Tools.get;
Matteo Scandoloaa2adde2021-09-13 12:45:32 -070099import static org.onosproject.net.flow.instructions.Instruction.Type.L2MODIFICATION;
100import static org.opencord.olt.impl.OltUtils.completeFlowOpToString;
101import static org.opencord.olt.impl.OltUtils.flowOpToString;
102import static org.opencord.olt.impl.OltUtils.getPortName;
103import static org.opencord.olt.impl.OltUtils.portWithName;
104import static org.opencord.olt.impl.OsgiPropertyConstants.DEFAULT_TP_ID;
105import static org.opencord.olt.impl.OsgiPropertyConstants.DEFAULT_TP_ID_DEFAULT;
106import static org.opencord.olt.impl.OsgiPropertyConstants.DOWNSTREAM_OLT;
107import static org.opencord.olt.impl.OsgiPropertyConstants.DOWNSTREAM_ONU;
108import static org.opencord.olt.impl.OsgiPropertyConstants.ENABLE_DHCP_ON_NNI;
109import static org.opencord.olt.impl.OsgiPropertyConstants.ENABLE_DHCP_ON_NNI_DEFAULT;
110import static org.opencord.olt.impl.OsgiPropertyConstants.ENABLE_DHCP_V4;
111import static org.opencord.olt.impl.OsgiPropertyConstants.ENABLE_DHCP_V4_DEFAULT;
112import static org.opencord.olt.impl.OsgiPropertyConstants.ENABLE_DHCP_V6;
113import static org.opencord.olt.impl.OsgiPropertyConstants.ENABLE_DHCP_V6_DEFAULT;
114import static org.opencord.olt.impl.OsgiPropertyConstants.ENABLE_EAPOL;
115import static org.opencord.olt.impl.OsgiPropertyConstants.ENABLE_EAPOL_DEFAULT;
116import static org.opencord.olt.impl.OsgiPropertyConstants.ENABLE_IGMP_ON_NNI;
117import static org.opencord.olt.impl.OsgiPropertyConstants.ENABLE_IGMP_ON_NNI_DEFAULT;
118import static org.opencord.olt.impl.OsgiPropertyConstants.ENABLE_PPPOE;
119import static org.opencord.olt.impl.OsgiPropertyConstants.ENABLE_PPPOE_DEFAULT;
120import static org.opencord.olt.impl.OsgiPropertyConstants.UPSTREAM_OLT;
121import static org.opencord.olt.impl.OsgiPropertyConstants.UPSTREAM_ONU;
122import static org.opencord.olt.impl.OsgiPropertyConstants.WAIT_FOR_REMOVAL;
123import static org.opencord.olt.impl.OsgiPropertyConstants.WAIT_FOR_REMOVAL_DEFAULT;
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000124
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000125@Component(immediate = true, property = {
Saurav Dasf62cea82020-08-26 17:43:04 -0700126 ENABLE_DHCP_ON_NNI + ":Boolean=" + ENABLE_DHCP_ON_NNI_DEFAULT,
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000127 ENABLE_DHCP_V4 + ":Boolean=" + ENABLE_DHCP_V4_DEFAULT,
128 ENABLE_DHCP_V6 + ":Boolean=" + ENABLE_DHCP_V6_DEFAULT,
Saurav Dasf62cea82020-08-26 17:43:04 -0700129 ENABLE_IGMP_ON_NNI + ":Boolean=" + ENABLE_IGMP_ON_NNI_DEFAULT,
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000130 ENABLE_EAPOL + ":Boolean=" + ENABLE_EAPOL_DEFAULT,
Gustavo Silva5c492dd2021-02-12 10:21:11 -0300131 ENABLE_PPPOE + ":Boolean=" + ENABLE_PPPOE_DEFAULT,
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700132 DEFAULT_TP_ID + ":Integer=" + DEFAULT_TP_ID_DEFAULT,
133 // FIXME remove this option as potentially dangerous in production
134 WAIT_FOR_REMOVAL + ":Boolean=" + WAIT_FOR_REMOVAL_DEFAULT
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000135})
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700136public class OltFlowService implements OltFlowServiceInterface {
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000137
138 @Reference(cardinality = ReferenceCardinality.MANDATORY)
139 protected CoreService coreService;
140
141 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700142 protected ComponentConfigService cfgService;
143
144 @Reference(cardinality = ReferenceCardinality.MANDATORY)
145 protected FlowObjectiveService flowObjectiveService;
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000146
Ilayda Ozdemir90a93622021-02-25 09:40:58 +0000147 @Reference(cardinality = ReferenceCardinality.OPTIONAL,
148 bind = "bindSadisService",
149 unbind = "unbindSadisService",
150 policy = ReferencePolicy.DYNAMIC)
151 protected volatile SadisService sadisService;
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000152
153 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700154 protected OltMeterServiceInterface oltMeterService;
155
156 @Reference(cardinality = ReferenceCardinality.MANDATORY)
157 protected OltDeviceServiceInterface oltDeviceService;
158
159 @Reference(cardinality = ReferenceCardinality.MANDATORY)
160 protected FlowRuleService flowRuleService;
161
162 @Reference(cardinality = ReferenceCardinality.MANDATORY)
163 protected HostService hostService;
164
165 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000166 protected DeviceService deviceService;
167
168 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Ilayda Ozdemir90a93622021-02-25 09:40:58 +0000169 protected StorageService storageService;
170
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700171 protected BaseInformationService<SubscriberAndDeviceInformation> subsService;
172 protected BaseInformationService<BandwidthProfileInformation> bpService;
173
174 private static final String APP_NAME = "org.opencord.olt";
175 protected ApplicationId appId;
176 private static final Integer MAX_PRIORITY = 10000;
177 private static final Integer MIN_PRIORITY = 1000;
178 private static final short EAPOL_DEFAULT_VLAN = 4091;
179 private static final int NONE_TP_ID = -1;
180 private static final String V4 = "V4";
181 private static final String V6 = "V6";
182 private final Logger log = LoggerFactory.getLogger(getClass());
183
184 protected UniTagInformation defaultEapolUniTag = new UniTagInformation.Builder()
185 .setServiceName("defaultEapol").build();
186 protected UniTagInformation nniUniTag = new UniTagInformation.Builder()
187 .setServiceName("nni")
188 .setTechnologyProfileId(NONE_TP_ID)
189 .setPonCTag(VlanId.NONE)
190 .setUniTagMatch(VlanId.ANY)
191 .setUsPonCTagPriority(-1)
192 .build();
193
194 /**
195 * Connect Point status map.
196 * Used to keep track of which cp has flows that needs to be removed when the status changes.
197 */
198 protected Map<ServiceKey, OltPortStatus> cpStatus;
199 private final ReentrantReadWriteLock cpStatusLock = new ReentrantReadWriteLock();
200 private final Lock cpStatusWriteLock = cpStatusLock.writeLock();
201 private final Lock cpStatusReadLock = cpStatusLock.readLock();
202
203 /**
204 * This map contains the subscriber that have been provisioned by the operator.
205 * They may or may not have flows, depending on the port status.
206 * The map is used to define whether flows need to be provisioned when a port comes up.
207 */
208 protected Map<ServiceKey, Boolean> provisionedSubscribers;
209 private final ReentrantReadWriteLock provisionedSubscribersLock = new ReentrantReadWriteLock();
210 private final Lock provisionedSubscribersWriteLock = provisionedSubscribersLock.writeLock();
211 private final Lock provisionedSubscribersReadLock = provisionedSubscribersLock.readLock();
212
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000213 /**
Saurav Dasf62cea82020-08-26 17:43:04 -0700214 * Create DHCP trap flow on NNI port(s).
215 */
216 protected boolean enableDhcpOnNni = ENABLE_DHCP_ON_NNI_DEFAULT;
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000217
218 /**
Saurav Dasf62cea82020-08-26 17:43:04 -0700219 * Enable flows for DHCP v4 if dhcp is required in sadis config.
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000220 **/
221 protected boolean enableDhcpV4 = ENABLE_DHCP_V4_DEFAULT;
222
223 /**
Saurav Dasf62cea82020-08-26 17:43:04 -0700224 * Enable flows for DHCP v6 if dhcp is required in sadis config.
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000225 **/
226 protected boolean enableDhcpV6 = ENABLE_DHCP_V6_DEFAULT;
227
228 /**
Saurav Dasf62cea82020-08-26 17:43:04 -0700229 * Create IGMP trap flow on NNI port(s).
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000230 **/
Saurav Dasf62cea82020-08-26 17:43:04 -0700231 protected boolean enableIgmpOnNni = ENABLE_IGMP_ON_NNI_DEFAULT;
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000232
233 /**
234 * Send EAPOL authentication trap flows before subscriber provisioning.
235 **/
236 protected boolean enableEapol = ENABLE_EAPOL_DEFAULT;
237
238 /**
Gustavo Silva5c492dd2021-02-12 10:21:11 -0300239 * Send PPPoED authentication trap flows before subscriber provisioning.
240 **/
241 protected boolean enablePppoe = ENABLE_PPPOE_DEFAULT;
242
243 /**
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000244 * Default technology profile id that is used for authentication trap flows.
245 **/
246 protected int defaultTechProfileId = DEFAULT_TP_ID_DEFAULT;
247
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700248 protected boolean waitForRemoval = WAIT_FOR_REMOVAL_DEFAULT;
249
250 public enum FlowOperation {
251 ADD,
252 REMOVE;
253
254
255 @Override
256 public String toString() {
257 return super.toString().toLowerCase();
258 }
259 }
260
261 public enum FlowDirection {
262 UPSTREAM,
263 DOWNSTREAM,
264 }
265
266 public enum OltFlowsStatus {
267 NONE,
268 PENDING_ADD,
269 ADDED,
270 PENDING_REMOVE,
271 REMOVED,
272 ERROR
273 }
274
275 protected InternalFlowListener internalFlowListener;
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000276
277 @Activate
278 public void activate(ComponentContext context) {
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700279 cfgService.registerProperties(getClass());
280 appId = coreService.registerApplication(APP_NAME);
281 internalFlowListener = new InternalFlowListener();
282
283 modified(context);
284
Ilayda Ozdemir90a93622021-02-25 09:40:58 +0000285 KryoNamespace serializer = KryoNamespace.newBuilder()
286 .register(KryoNamespaces.API)
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700287 .register(OltFlowsStatus.class)
288 .register(FlowDirection.class)
289 .register(OltPortStatus.class)
290 .register(OltFlowsStatus.class)
Tunahan Sezenf0843b92021-04-30 07:13:16 +0000291 .register(AccessDevicePort.class)
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700292 .register(new ServiceKeySerializer(), ServiceKey.class)
293 .register(UniTagInformation.class)
Ilayda Ozdemir90a93622021-02-25 09:40:58 +0000294 .build();
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000295
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700296 cpStatus = storageService.<ServiceKey, OltPortStatus>consistentMapBuilder()
297 .withName("volt-cp-status")
298 .withApplicationId(appId)
299 .withSerializer(Serializer.using(serializer))
300 .build().asJavaMap();
301
302 provisionedSubscribers = storageService.<ServiceKey, Boolean>consistentMapBuilder()
303 .withName("volt-provisioned-subscriber")
304 .withApplicationId(appId)
305 .withSerializer(Serializer.using(serializer))
306 .build().asJavaMap();
307
308 flowRuleService.addListener(internalFlowListener);
309
310 log.info("Started");
311 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000312
313 @Deactivate
314 public void deactivate(ComponentContext context) {
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700315 cfgService.unregisterProperties(getClass(), false);
316 flowRuleService.removeListener(internalFlowListener);
317 log.info("Stopped");
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000318 }
319
320 @Modified
321 public void modified(ComponentContext context) {
322
323 Dictionary<?, ?> properties = context != null ? context.getProperties() : new Properties();
324
Saurav Dasf62cea82020-08-26 17:43:04 -0700325 Boolean o = Tools.isPropertyEnabled(properties, ENABLE_DHCP_ON_NNI);
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000326 if (o != null) {
Saurav Dasf62cea82020-08-26 17:43:04 -0700327 enableDhcpOnNni = o;
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000328 }
329
Andrea Campanella7c49b792020-05-11 11:36:53 +0200330 Boolean v4 = Tools.isPropertyEnabled(properties, ENABLE_DHCP_V4);
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000331 if (v4 != null) {
332 enableDhcpV4 = v4;
333 }
334
Andrea Campanella7c49b792020-05-11 11:36:53 +0200335 Boolean v6 = Tools.isPropertyEnabled(properties, ENABLE_DHCP_V6);
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000336 if (v6 != null) {
337 enableDhcpV6 = v6;
338 }
339
Saurav Dasf62cea82020-08-26 17:43:04 -0700340 Boolean p = Tools.isPropertyEnabled(properties, ENABLE_IGMP_ON_NNI);
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000341 if (p != null) {
Saurav Dasf62cea82020-08-26 17:43:04 -0700342 enableIgmpOnNni = p;
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000343 }
344
Andrea Campanella7c49b792020-05-11 11:36:53 +0200345 Boolean eap = Tools.isPropertyEnabled(properties, ENABLE_EAPOL);
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000346 if (eap != null) {
347 enableEapol = eap;
348 }
349
Gustavo Silva5c492dd2021-02-12 10:21:11 -0300350 Boolean pppoe = Tools.isPropertyEnabled(properties, ENABLE_PPPOE);
351 if (pppoe != null) {
352 enablePppoe = pppoe;
353 }
354
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700355 Boolean wait = Tools.isPropertyEnabled(properties, WAIT_FOR_REMOVAL);
356 if (wait != null) {
357 waitForRemoval = wait;
358 }
359
Andrea Campanella7c49b792020-05-11 11:36:53 +0200360 String tpId = get(properties, DEFAULT_TP_ID);
361 defaultTechProfileId = isNullOrEmpty(tpId) ? DEFAULT_TP_ID_DEFAULT : Integer.parseInt(tpId.trim());
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000362
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700363 log.info("Modified. Values = enableDhcpOnNni: {}, enableDhcpV4: {}, " +
364 "enableDhcpV6:{}, enableIgmpOnNni:{}, " +
365 "enableEapol:{}, enablePppoe:{}, defaultTechProfileId:{}," +
366 "waitForRemoval:{}",
367 enableDhcpOnNni, enableDhcpV4, enableDhcpV6,
368 enableIgmpOnNni, enableEapol, enablePppoe,
369 defaultTechProfileId, waitForRemoval);
Andrea Campanellafee86422020-06-04 16:01:27 +0200370
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000371 }
372
373 @Override
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700374 public ImmutableMap<ServiceKey, OltPortStatus> getConnectPointStatus() {
375 try {
376 cpStatusReadLock.lock();
377 return ImmutableMap.copyOf(cpStatus);
378 } finally {
379 cpStatusReadLock.unlock();
Andrea Campanellacbbb7952019-11-25 06:38:41 +0000380 }
381 }
382
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700383 @Override
384 public ImmutableMap<ServiceKey, UniTagInformation> getProgrammedSubscribers() {
385 // NOTE we might want to remove this conversion and directly use cpStatus as it contains
Matteo Scandolo2542e5d2021-12-01 16:53:41 -0800386 // all the required information about subscribers
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700387 Map<ServiceKey, UniTagInformation> subscribers =
388 new HashMap<>();
389 try {
390 cpStatusReadLock.lock();
391
392 cpStatus.forEach((sk, status) -> {
393 if (
394 // not NNI Port
395 !oltDeviceService.isNniPort(deviceService.getDevice(sk.getPort().connectPoint().deviceId()),
396 sk.getPort().connectPoint().port()) &&
397 // not EAPOL flow
398 !sk.getService().equals(defaultEapolUniTag)
Matteo Scandolo2542e5d2021-12-01 16:53:41 -0800399
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700400 ) {
401 subscribers.put(sk, sk.getService());
402 }
403 });
404
405 return ImmutableMap.copyOf(subscribers);
406 } finally {
407 cpStatusReadLock.unlock();
408 }
409 }
410
411 @Override
412 public Map<ServiceKey, Boolean> getRequestedSubscribers() {
413 try {
414 provisionedSubscribersReadLock.lock();
415 return ImmutableMap.copyOf(provisionedSubscribers);
416 } finally {
417 provisionedSubscribersReadLock.unlock();
418 }
419 }
420
421 @Override
422 public void handleNniFlows(Device device, Port port, FlowOperation action) {
423
424 // always handle the LLDP flow
425 processLldpFilteringObjective(device.id(), port, action);
426
427 if (enableDhcpOnNni) {
428 if (enableDhcpV4) {
429 log.debug("Installing DHCPv4 trap flow on NNI {} for device {}", portWithName(port), device.id());
430 processDhcpFilteringObjectives(device.id(), port, action, FlowDirection.DOWNSTREAM,
431 67, 68, EthType.EtherType.IPV4.ethType(), IPv4.PROTOCOL_UDP,
432 null, null, nniUniTag);
433 }
434 if (enableDhcpV6) {
435 log.debug("Installing DHCPv6 trap flow on NNI {} for device {}", portWithName(port), device.id());
436 processDhcpFilteringObjectives(device.id(), port, action, FlowDirection.DOWNSTREAM,
437 546, 547, EthType.EtherType.IPV6.ethType(), IPv6.PROTOCOL_UDP,
438 null, null, nniUniTag);
439 }
440 } else {
441 log.info("DHCP is not required on NNI {} for device {}", portWithName(port), device.id());
442 }
443
444 if (enableIgmpOnNni) {
445 log.debug("Installing IGMP flow on NNI {} for device {}", portWithName(port), device.id());
446 processIgmpFilteringObjectives(device.id(), port, action, FlowDirection.DOWNSTREAM,
447 null, null, NONE_TP_ID, VlanId.NONE, VlanId.ANY, -1);
448 }
449
450 if (enablePppoe) {
451 log.debug("Installing PPPoE flow on NNI {} for device {}", port.number(), device.id());
452 processPPPoEDFilteringObjectives(device.id(), port, action, FlowDirection.DOWNSTREAM,
453 null, null, NONE_TP_ID, VlanId.NONE, VlanId.ANY, null);
454 }
455 }
456
457 @Override
458 public boolean handleBasicPortFlows(DiscoveredSubscriber sub, String bandwidthProfileId,
459 String oltBandwidthProfileId) {
460
461 // we only need to something if EAPOL is enabled
462 if (!enableEapol) {
463 return true;
464 }
465
466 if (sub.status == DiscoveredSubscriber.Status.ADDED) {
467 return addDefaultFlows(sub, bandwidthProfileId, oltBandwidthProfileId);
468 } else if (sub.status == DiscoveredSubscriber.Status.REMOVED) {
469 return removeDefaultFlows(sub, bandwidthProfileId, oltBandwidthProfileId);
470 } else {
471 log.error("Unknown Status {} on DiscoveredSubscriber {}", sub.status, sub);
472 return false;
473 }
474
475 }
476
477 private boolean addDefaultFlows(DiscoveredSubscriber sub, String bandwidthProfileId, String oltBandwidthProfileId) {
478
479 if (!oltMeterService.createMeter(sub.device.id(), bandwidthProfileId)) {
480 if (log.isTraceEnabled()) {
481 log.trace("waiting on meter for bp {} and sub {}", bandwidthProfileId, sub);
482 }
483 return false;
484 }
485 if (hasDefaultEapol(sub.port)) {
486 return true;
487 }
488 return handleEapolFlow(sub, bandwidthProfileId,
489 oltBandwidthProfileId, FlowOperation.ADD, VlanId.vlanId(EAPOL_DEFAULT_VLAN));
490
491 }
492
493 private boolean removeDefaultFlows(DiscoveredSubscriber sub, String bandwidthProfile, String oltBandwidthProfile) {
494 // NOTE that we are not checking for meters as they must have been created to install the flow in first place
495 return handleEapolFlow(sub, bandwidthProfile, oltBandwidthProfile,
496 FlowOperation.REMOVE, VlanId.vlanId(EAPOL_DEFAULT_VLAN));
497 }
498
499 @Override
500 public boolean handleSubscriberFlows(DiscoveredSubscriber sub, String defaultBandwidthProfile,
501 String multicastServiceName) {
502 // NOTE that we are taking defaultBandwithProfile as a parameter as that can be configured in the Olt component
503 if (sub.status == DiscoveredSubscriber.Status.ADDED) {
504 return addSubscriberFlows(sub, defaultBandwidthProfile, multicastServiceName);
505 } else if (sub.status == DiscoveredSubscriber.Status.REMOVED) {
506 return removeSubscriberFlows(sub, defaultBandwidthProfile, multicastServiceName);
507 } else {
508 log.error("don't know how to handle {}", sub);
509 return false;
510 }
511 }
512
513 private boolean addSubscriberFlows(DiscoveredSubscriber sub, String defaultBandwithProfile,
514 String multicastServiceName) {
515 if (log.isTraceEnabled()) {
516 log.trace("Provisioning of subscriber on {} started", portWithName(sub.port));
517 }
518 if (enableEapol) {
519 if (hasDefaultEapol(sub.port)) {
520 // remove EAPOL flow and throw exception so that we'll retry later
521 if (!isDefaultEapolPendingRemoval(sub.port)) {
522 removeDefaultFlows(sub, defaultBandwithProfile, defaultBandwithProfile);
523 }
524
525 if (waitForRemoval) {
526 // NOTE wait for removal is a flag only needed to make sure VOLTHA
527 // does not explode with the flows remove/add in the same batch
528 log.debug("Awaiting for default flows removal for {}", portWithName(sub.port));
529 return false;
530 } else {
531 log.warn("continuing provisioning on {}", portWithName(sub.port));
532 }
533 }
534
535 }
536
537 // NOTE createMeters will return if the meters are not installed
538 if (!oltMeterService.createMeters(sub.device.id(),
Matteo Scandolo88df8ae2021-11-23 13:12:29 -0800539 sub.subscriberAndDeviceInformation, multicastServiceName)) {
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700540 return false;
541 }
542
543 // NOTE we need to add the DHCP flow regardless so that the host can be discovered and the MacAddress added
544 handleSubscriberDhcpFlows(sub.device.id(), sub.port, FlowOperation.ADD,
545 sub.subscriberAndDeviceInformation);
546
547 if (isMacLearningEnabled(sub.subscriberAndDeviceInformation)
548 && !isMacAddressAvailable(sub.device.id(), sub.port,
549 sub.subscriberAndDeviceInformation)) {
550 log.debug("Awaiting for macAddress on {}", portWithName(sub.port));
551 return false;
552 }
553
554 handleSubscriberDataFlows(sub.device, sub.port, FlowOperation.ADD,
555 sub.subscriberAndDeviceInformation, multicastServiceName);
556
557 handleSubscriberEapolFlows(sub, FlowOperation.ADD, sub.subscriberAndDeviceInformation);
558
559 handleSubscriberIgmpFlows(sub, FlowOperation.ADD);
560
561 log.info("Provisioning of subscriber on {} completed", portWithName(sub.port));
562 return true;
563 }
564
565 private boolean removeSubscriberFlows(DiscoveredSubscriber sub, String defaultBandwithProfile,
566 String multicastServiceName) {
567
568 if (log.isTraceEnabled()) {
569 log.trace("Removal of subscriber on {} started",
570 portWithName(sub.port));
571 }
572 SubscriberAndDeviceInformation si = subsService.get(sub.portName());
573 if (si == null) {
574 log.error("Subscriber information not found in sadis for port {} during subscriber removal",
575 portWithName(sub.port));
576 // NOTE that we are returning true so that the subscriber is removed from the queue
577 // and we can move on provisioning others
578 return true;
579 }
580
581 handleSubscriberDhcpFlows(sub.device.id(), sub.port, FlowOperation.REMOVE, si);
582
583 if (enableEapol) {
584 // remove the tagged eapol
585 handleSubscriberEapolFlows(sub, FlowOperation.REMOVE, si);
586
Matteo Scandolo49c42052021-11-23 13:12:29 -0800587 // and add the default one back (only if the port is ENABLED and still present on the device)
588 if (sub.port.isEnabled() && deviceService.getPort(sub.device.id(), sub.port.number()) != null) {
589
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700590 // NOTE we remove the subscriber when the port goes down
591 // but in that case we don't need to add default eapol
592 handleEapolFlow(sub, defaultBandwithProfile, defaultBandwithProfile,
593 FlowOperation.ADD, VlanId.vlanId(EAPOL_DEFAULT_VLAN));
594 }
595 }
596 handleSubscriberDataFlows(sub.device, sub.port, FlowOperation.REMOVE, si, multicastServiceName);
597
598 handleSubscriberIgmpFlows(sub, FlowOperation.REMOVE);
599
600 // FIXME check the return status of the flow and return accordingly
601 log.info("Removal of subscriber on {} completed", portWithName(sub.port));
602 return true;
603 }
604
605 @Override
606 public boolean hasDefaultEapol(Port port) {
607 OltPortStatus status = getOltPortStatus(port, defaultEapolUniTag);
608 // NOTE we consider ERROR as a present EAPOL flow as ONOS
609 // will keep trying to add it
610 return status != null && (status.defaultEapolStatus == OltFlowsStatus.ADDED ||
611 status.defaultEapolStatus == OltFlowsStatus.PENDING_ADD ||
612 status.defaultEapolStatus == OltFlowsStatus.ERROR);
613 }
614
615 private OltPortStatus getOltPortStatus(Port port, UniTagInformation uniTagInformation) {
616 try {
617 cpStatusReadLock.lock();
618 ServiceKey sk = new ServiceKey(new AccessDevicePort(port), uniTagInformation);
619 OltPortStatus status = cpStatus.get(sk);
620 return status;
621 } finally {
622 cpStatusReadLock.unlock();
623 }
624 }
625
626 public boolean isDefaultEapolPendingRemoval(Port port) {
627 OltPortStatus status = getOltPortStatus(port, defaultEapolUniTag);
628 if (log.isTraceEnabled()) {
629 log.trace("Status during EAPOL flow check {} for port {} and UniTagInformation {}",
630 status, portWithName(port), defaultEapolUniTag);
631 }
632 return status != null && status.defaultEapolStatus == OltFlowsStatus.PENDING_REMOVE;
633 }
634
635 @Override
636 public boolean hasDhcpFlows(Port port, UniTagInformation uti) {
637 OltPortStatus status = getOltPortStatus(port, uti);
638 if (log.isTraceEnabled()) {
639 log.trace("Status during DHCP flow check {} for port {} and service {}",
640 status, portWithName(port), uti.getServiceName());
641 }
642 return status != null &&
643 (status.dhcpStatus == OltFlowsStatus.ADDED ||
644 status.dhcpStatus == OltFlowsStatus.PENDING_ADD);
645 }
646
647 @Override
648 public boolean hasSubscriberFlows(Port port, UniTagInformation uti) {
649
650 OltPortStatus status = getOltPortStatus(port, uti);
651 if (log.isTraceEnabled()) {
652 log.trace("Status during subscriber flow check {} for port {} and service {}",
653 status, portWithName(port), uti.getServiceName());
654 }
655 return status != null && (status.subscriberFlowsStatus == OltFlowsStatus.ADDED ||
656 status.subscriberFlowsStatus == OltFlowsStatus.PENDING_ADD);
657 }
658
659 @Override
660 public void purgeDeviceFlows(DeviceId deviceId) {
661 log.debug("Purging flows on device {}", deviceId);
Matteo Scandolo2542e5d2021-12-01 16:53:41 -0800662 try {
663 flowRuleService.purgeFlowRules(deviceId);
664 } catch (Exception e) {
665 log.error("Cannot purge flow rules", e);
666 }
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700667
668 // removing the status from the cpStatus map
Matteo Scandolo2542e5d2021-12-01 16:53:41 -0800669 if (log.isTraceEnabled()) {
670 log.trace("Clearing cp status from device {}", deviceId);
671 }
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700672 try {
673 cpStatusWriteLock.lock();
674 Iterator<Map.Entry<ServiceKey, OltPortStatus>> iter = cpStatus.entrySet().iterator();
675 while (iter.hasNext()) {
676 Map.Entry<ServiceKey, OltPortStatus> entry = iter.next();
677 if (entry.getKey().getPort().connectPoint().deviceId().equals(deviceId)) {
678 cpStatus.remove(entry.getKey());
679 }
680 }
Matteo Scandolo2542e5d2021-12-01 16:53:41 -0800681 } catch (Exception e) {
682 log.error("Cannot wipe out cpStatus", e);
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700683 } finally {
684 cpStatusWriteLock.unlock();
685 }
686
687 // removing subscribers from the provisioned map
Matteo Scandolo2542e5d2021-12-01 16:53:41 -0800688 if (log.isTraceEnabled()) {
689 log.trace("Clearing provisioned subscribers from device {}", deviceId);
690 }
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700691 try {
692 provisionedSubscribersWriteLock.lock();
693 Iterator<Map.Entry<ServiceKey, Boolean>> iter = provisionedSubscribers.entrySet().iterator();
694 while (iter.hasNext()) {
695 Map.Entry<ServiceKey, Boolean> entry = iter.next();
696 if (entry.getKey().getPort().connectPoint().deviceId().equals(deviceId)) {
697 provisionedSubscribers.remove(entry.getKey());
698 }
699 }
Matteo Scandolo2542e5d2021-12-01 16:53:41 -0800700 } catch (Exception e) {
701 log.error("Cannot wipe out subscribers", e);
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700702 } finally {
703 provisionedSubscribersWriteLock.unlock();
704 }
Matteo Scandolo2542e5d2021-12-01 16:53:41 -0800705 log.debug("Done clearing up device flows and subscribers");
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700706 }
707
708 @Override
709 public boolean isSubscriberServiceProvisioned(AccessDevicePort cp) {
710 // if any service is programmed on this port, returns true
711 AtomicBoolean provisioned = new AtomicBoolean(false);
712 try {
713 provisionedSubscribersReadLock.lock();
714 for (Map.Entry<ServiceKey, Boolean> entry : provisionedSubscribers.entrySet()) {
715 if (entry.getKey().getPort().equals(cp) && entry.getValue()) {
716 provisioned.set(true);
717 break;
718 }
719 }
720 } finally {
721 provisionedSubscribersReadLock.unlock();
722 }
723 return provisioned.get();
724 }
725
726 @Override
727 public boolean isSubscriberServiceProvisioned(ServiceKey sk) {
728 try {
729 provisionedSubscribersReadLock.lock();
730 Boolean provisioned = provisionedSubscribers.get(sk);
731 if (provisioned == null || !provisioned) {
732 return false;
733 }
734 } finally {
735 provisionedSubscribersReadLock.unlock();
736 }
737 return true;
738 }
739
740 @Override
741 public void updateProvisionedSubscriberStatus(ServiceKey sk, Boolean status) {
742 try {
743 provisionedSubscribersWriteLock.lock();
744 provisionedSubscribers.put(sk, status);
745 } finally {
746 provisionedSubscribersWriteLock.unlock();
747 }
748 }
749
750 private boolean handleEapolFlow(DiscoveredSubscriber sub, String bandwidthProfile,
751 String oltBandwidthProfile, FlowOperation action, VlanId vlanId) {
752
753 // create a subscriberKey for the EAPOL flow
754 ServiceKey sk = new ServiceKey(new AccessDevicePort(sub.port), defaultEapolUniTag);
755
756 // NOTE we only need to keep track of the default EAPOL flow in the
757 // connectpoint status map
758 if (vlanId.id().equals(EAPOL_DEFAULT_VLAN)) {
759 OltFlowsStatus status = action == FlowOperation.ADD ?
760 OltFlowsStatus.PENDING_ADD : OltFlowsStatus.PENDING_REMOVE;
761 updateConnectPointStatus(sk, status, OltFlowsStatus.NONE, OltFlowsStatus.NONE);
762
763 }
764
765 DefaultFilteringObjective.Builder filterBuilder = DefaultFilteringObjective.builder();
766 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
767
768 int techProfileId = getDefaultTechProfileId(sub.port);
769 MeterId meterId = oltMeterService.getMeterIdForBandwidthProfile(sub.device.id(), bandwidthProfile);
770
771 // in the delete case the meter should still be there as we remove
772 // the meters only if no flows are pointing to them
773 if (meterId == null) {
774 log.debug("MeterId is null for BandwidthProfile {} on device {}",
775 bandwidthProfile, sub.device.id());
776 return false;
777 }
778
779 MeterId oltMeterId = oltMeterService.getMeterIdForBandwidthProfile(sub.device.id(), oltBandwidthProfile);
780 if (oltMeterId == null) {
781 log.debug("MeterId is null for OltBandwidthProfile {} on device {}",
782 oltBandwidthProfile, sub.device.id());
783 return false;
784 }
785
786 log.info("{} EAPOL flow for {} with vlanId {} and BandwidthProfile {} (meterId {})",
787 flowOpToString(action), portWithName(sub.port), vlanId, bandwidthProfile, meterId);
788
789 FilteringObjective.Builder eapolAction;
790
791 if (action == FlowOperation.ADD) {
792 eapolAction = filterBuilder.permit();
793 } else if (action == FlowOperation.REMOVE) {
794 eapolAction = filterBuilder.deny();
795 } else {
796 log.error("Operation {} not supported", action);
797 return false;
798 }
799
800 FilteringObjective.Builder baseEapol = eapolAction
801 .withKey(Criteria.matchInPort(sub.port.number()))
802 .addCondition(Criteria.matchEthType(EthType.EtherType.EAPOL.ethType()));
803
804 // NOTE we only need to add the treatment to install the flow,
805 // we can remove it based in the match
806 FilteringObjective.Builder eapol;
807
808 TrafficTreatment treatment = treatmentBuilder
809 .meter(meterId)
810 .writeMetadata(createTechProfValueForWriteMetadata(
811 vlanId,
812 techProfileId, oltMeterId), 0)
813 .setOutput(PortNumber.CONTROLLER)
814 .pushVlan()
815 .setVlanId(vlanId)
816 .build();
817 eapol = baseEapol
818 .withMeta(treatment);
819
820 FilteringObjective eapolObjective = eapol
821 .fromApp(appId)
822 .withPriority(MAX_PRIORITY)
823 .add(new ObjectiveContext() {
824 @Override
825 public void onSuccess(Objective objective) {
826 log.info("EAPOL flow objective {} for {}",
827 completeFlowOpToString(action), portWithName(sub.port));
828 if (log.isTraceEnabled()) {
829 log.trace("EAPOL flow details for port {}: {}", portWithName(sub.port), objective);
830 }
831 }
832
833 @Override
834 public void onError(Objective objective, ObjectiveError error) {
835 log.error("Cannot {} eapol flow for {} : {}", action,
836 portWithName(sub.port), error);
837
838 if (vlanId.id().equals(EAPOL_DEFAULT_VLAN)) {
839 updateConnectPointStatus(sk,
840 OltFlowsStatus.ERROR, null, null);
841 }
842 }
843 });
844
845 flowObjectiveService.filter(sub.device.id(), eapolObjective);
846
847 log.info("{} EAPOL filter for {}", completeFlowOpToString(action), portWithName(sub.port));
848 return true;
849 }
850
851 // FIXME it's confusing that si is not necessarily inside the DiscoveredSubscriber
852 private boolean handleSubscriberEapolFlows(DiscoveredSubscriber sub, FlowOperation action,
853 SubscriberAndDeviceInformation si) {
854 if (!enableEapol) {
855 return true;
856 }
857 // TODO verify we need an EAPOL flow for EACH service
858 AtomicBoolean success = new AtomicBoolean(true);
859 si.uniTagList().forEach(u -> {
860 // we assume that if subscriber flows are installed, tagged EAPOL is installed as well
861 boolean hasFlows = hasSubscriberFlows(sub.port, u);
862
863 // if the subscriber flows are present the EAPOL flow is present thus we don't need to install it,
864 // if the subscriber does not have flows the EAPOL flow is not present thus we don't need to remove it
865 if (action == FlowOperation.ADD && hasFlows ||
866 action == FlowOperation.REMOVE && !hasFlows) {
867 log.debug("Not {} EAPOL on {}({}) as subscriber flow status is {}", flowOpToString(action),
868 portWithName(sub.port), u.getServiceName(), hasFlows);
869 return;
870 }
871 log.info("{} EAPOL flows for subscriber {} on {} and service {}",
872 flowOpToString(action), si.id(), portWithName(sub.port), u.getServiceName());
873 if (!handleEapolFlow(sub, u.getUpstreamBandwidthProfile(),
874 u.getUpstreamOltBandwidthProfile(),
875 action, u.getPonCTag())) {
876 //
877 log.error("Failed to {} EAPOL with suscriber tags", action);
878 //TODO this sets it for all services, maybe some services succeeded.
879 success.set(false);
880 }
881 });
882 return success.get();
883 }
884
885 private void handleSubscriberIgmpFlows(DiscoveredSubscriber sub, FlowOperation action) {
886 sub.subscriberAndDeviceInformation.uniTagList().forEach(uti -> {
887 if (uti.getIsIgmpRequired()) {
888 DeviceId deviceId = sub.device.id();
889 // if we reached here a meter already exists
890 MeterId meterId = oltMeterService
891 .getMeterIdForBandwidthProfile(deviceId, uti.getUpstreamBandwidthProfile());
892 MeterId oltMeterId = oltMeterService
893 .getMeterIdForBandwidthProfile(deviceId, uti.getUpstreamOltBandwidthProfile());
894
895 processIgmpFilteringObjectives(deviceId, sub.port,
896 action, FlowDirection.UPSTREAM, meterId, oltMeterId, uti.getTechnologyProfileId(),
897 uti.getPonCTag(), uti.getUniTagMatch(), uti.getUsPonCTagPriority());
898 }
899 });
900 }
901
902 private boolean checkSadisRunning() {
903 if (bpService == null) {
904 log.warn("Sadis is not running");
905 return false;
906 }
907 return true;
908 }
909
910 private int getDefaultTechProfileId(Port port) {
911 if (!checkSadisRunning()) {
912 return defaultTechProfileId;
913 }
914 if (port != null) {
915 SubscriberAndDeviceInformation info = subsService.get(getPortName(port));
916 if (info != null && info.uniTagList().size() == 1) {
917 return info.uniTagList().get(0).getTechnologyProfileId();
918 }
919 }
920 return defaultTechProfileId;
921 }
922
923 protected Long createTechProfValueForWriteMetadata(VlanId cVlan, int techProfileId, MeterId upstreamOltMeterId) {
924 Long writeMetadata;
925
926 if (cVlan == null || VlanId.NONE.equals(cVlan)) {
927 writeMetadata = (long) techProfileId << 32;
928 } else {
929 writeMetadata = ((long) (cVlan.id()) << 48 | (long) techProfileId << 32);
930 }
931 if (upstreamOltMeterId == null) {
932 return writeMetadata;
933 } else {
934 return writeMetadata | upstreamOltMeterId.id();
935 }
936 }
937
938 private void processLldpFilteringObjective(DeviceId deviceId, Port port, FlowOperation action) {
939 DefaultFilteringObjective.Builder builder = DefaultFilteringObjective.builder();
940
941 FilteringObjective lldp = (action == FlowOperation.ADD ? builder.permit() : builder.deny())
942 .withKey(Criteria.matchInPort(port.number()))
943 .addCondition(Criteria.matchEthType(EthType.EtherType.LLDP.ethType()))
944 .withMeta(DefaultTrafficTreatment.builder()
945 .setOutput(PortNumber.CONTROLLER).build())
946 .fromApp(appId)
947 .withPriority(MAX_PRIORITY)
948 .add(new ObjectiveContext() {
949 @Override
950 public void onSuccess(Objective objective) {
951 log.info("{} LLDP filter for {}.", completeFlowOpToString(action), portWithName(port));
952 }
953
954 @Override
955 public void onError(Objective objective, ObjectiveError error) {
956 log.error("Falied to {} LLDP filter on {} because {}", action, portWithName(port),
957 error);
958 }
959 });
960
961 flowObjectiveService.filter(deviceId, lldp);
962 }
963
964 protected void handleSubscriberDhcpFlows(DeviceId deviceId, Port port,
965 FlowOperation action,
966 SubscriberAndDeviceInformation si) {
967 si.uniTagList().forEach(uti -> {
968
969 if (!uti.getIsDhcpRequired()) {
970 return;
971 }
972
973 // if it's an ADD skip if flows are there,
974 // if it's a DELETE skip if flows are not there
975 boolean hasFlows = hasDhcpFlows(port, uti);
976 if (action == FlowOperation.ADD && hasFlows ||
977 action == FlowOperation.REMOVE && !hasFlows) {
978 log.debug("Not dealing with DHCP {} on {} as DHCP flow status is {}", action,
979 uti.getServiceName(), hasFlows);
980 return;
981 }
982
983 log.info("{} DHCP flows for subscriber on {} and service {}",
984 flowOpToString(action), portWithName(port), uti.getServiceName());
985
986 // if we reached here a meter already exists
987 MeterId meterId = oltMeterService
988 .getMeterIdForBandwidthProfile(deviceId, uti.getUpstreamBandwidthProfile());
989 MeterId oltMeterId = oltMeterService
990 .getMeterIdForBandwidthProfile(deviceId, uti.getUpstreamOltBandwidthProfile());
991
992 if (enableDhcpV4) {
993 processDhcpFilteringObjectives(deviceId, port, action, FlowDirection.UPSTREAM, 68, 67,
994 EthType.EtherType.IPV4.ethType(), IPv4.PROTOCOL_UDP, meterId, oltMeterId,
995 uti);
996 }
997 if (enableDhcpV6) {
998 log.error("DHCP V6 not supported for subscribers");
999 }
1000 });
1001 }
1002
1003 // FIXME return boolean, if this fails we need to retry
1004 protected void handleSubscriberDataFlows(Device device, Port port,
1005 FlowOperation action,
1006 SubscriberAndDeviceInformation si, String multicastServiceName) {
1007
1008 Optional<Port> nniPort = oltDeviceService.getNniPort(device);
1009 if (nniPort.isEmpty()) {
1010 log.error("Cannot configure DP flows as upstream port is not configured for subscriber {} on {}",
1011 si.id(), portWithName(port));
1012 return;
1013 }
1014 si.uniTagList().forEach(uti -> {
1015
1016 boolean hasFlows = hasSubscriberFlows(port, uti);
1017 if (action == FlowOperation.ADD && hasFlows ||
1018 action == FlowOperation.REMOVE && !hasFlows) {
1019 log.debug("Not dealing with DP flows {} on {} as subscriber flow status is {}", action,
1020 uti.getServiceName(), hasFlows);
1021 return;
1022 }
1023
1024 if (multicastServiceName.equals(uti.getServiceName())) {
1025 log.debug("This is the multicast service ({}) for subscriber {} on {}, " +
1026 "dataplane flows are not needed",
1027 uti.getServiceName(), si.id(), portWithName(port));
1028 return;
1029 }
1030
1031 log.info("{} Data plane flows for subscriber {} on {} and service {}",
1032 flowOpToString(action), si.id(), portWithName(port), uti.getServiceName());
Matteo Scandolo80f5e972021-12-02 14:59:15 -08001033 ServiceKey sk = new ServiceKey(new AccessDevicePort(port), uti);
1034 OltFlowsStatus status = action.equals(FlowOperation.ADD) ?
1035 OltFlowsStatus.PENDING_ADD : OltFlowsStatus.PENDING_REMOVE;
1036 updateConnectPointStatus(sk, null, status, null);
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001037
1038 // upstream flows
1039 MeterId usMeterId = oltMeterService
1040 .getMeterIdForBandwidthProfile(device.id(), uti.getUpstreamBandwidthProfile());
1041 MeterId oltUsMeterId = oltMeterService
1042 .getMeterIdForBandwidthProfile(device.id(), uti.getUpstreamOltBandwidthProfile());
1043 processUpstreamDataFilteringObjects(device.id(), port, nniPort.get(), action, usMeterId,
1044 oltUsMeterId, uti);
1045
1046 // downstream flows
1047 MeterId dsMeterId = oltMeterService
1048 .getMeterIdForBandwidthProfile(device.id(), uti.getDownstreamBandwidthProfile());
1049 MeterId oltDsMeterId = oltMeterService
1050 .getMeterIdForBandwidthProfile(device.id(), uti.getDownstreamOltBandwidthProfile());
1051 processDownstreamDataFilteringObjects(device.id(), port, nniPort.get(), action, dsMeterId,
1052 oltDsMeterId, uti, getMacAddress(device.id(), port, uti));
1053 });
1054 }
1055
1056 private void processDhcpFilteringObjectives(DeviceId deviceId, Port port,
1057 FlowOperation action, FlowDirection direction,
1058 int udpSrc, int udpDst, EthType ethType, byte protocol,
1059 MeterId meterId, MeterId oltMeterId, UniTagInformation uti) {
1060 ServiceKey sk = new ServiceKey(new AccessDevicePort(port), uti);
1061 log.debug("{} DHCP filtering objectives on {}", flowOpToString(action), sk);
1062
1063
1064 OltFlowsStatus status = action.equals(FlowOperation.ADD) ?
1065 OltFlowsStatus.PENDING_ADD : OltFlowsStatus.PENDING_REMOVE;
1066 updateConnectPointStatus(sk, null, null, status);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001067
1068 DefaultFilteringObjective.Builder builder = DefaultFilteringObjective.builder();
1069 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
1070
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001071 if (meterId != null) {
1072 treatmentBuilder.meter(meterId);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001073 }
1074
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001075 if (uti.getTechnologyProfileId() != NONE_TP_ID) {
1076 treatmentBuilder.writeMetadata(
1077 createTechProfValueForWriteMetadata(uti.getUniTagMatch(),
1078 uti.getTechnologyProfileId(), oltMeterId), 0);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001079 }
1080
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001081 FilteringObjective.Builder dhcpBuilder = (action == FlowOperation.ADD ? builder.permit() : builder.deny())
Tunahan Sezenf0843b92021-04-30 07:13:16 +00001082 .withKey(Criteria.matchInPort(port.number()))
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001083 .addCondition(Criteria.matchEthType(ethType))
1084 .addCondition(Criteria.matchIPProtocol(protocol))
1085 .addCondition(Criteria.matchUdpSrc(TpPort.tpPort(udpSrc)))
1086 .addCondition(Criteria.matchUdpDst(TpPort.tpPort(udpDst)))
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001087 .fromApp(appId)
1088 .withPriority(MAX_PRIORITY);
1089
Andrea Campanella0e34f562020-06-11 10:47:10 +02001090 //VLAN changes and PCP matching need to happen only in the upstream directions
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001091 if (direction == FlowDirection.UPSTREAM) {
1092 treatmentBuilder.setVlanId(uti.getPonCTag());
1093 if (!VlanId.vlanId(VlanId.NO_VID).equals(uti.getUniTagMatch())) {
1094 dhcpBuilder.addCondition(Criteria.matchVlanId(uti.getUniTagMatch()));
Andrea Campanella0e34f562020-06-11 10:47:10 +02001095 }
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001096 if (uti.getUsPonCTagPriority() != -1) {
1097 treatmentBuilder.setVlanPcp((byte) uti.getUsPonCTagPriority());
Andrea Campanella0e34f562020-06-11 10:47:10 +02001098 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001099 }
1100
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001101 dhcpBuilder.withMeta(treatmentBuilder
1102 .setOutput(PortNumber.CONTROLLER).build());
Andrea Campanella0e34f562020-06-11 10:47:10 +02001103
1104
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001105 FilteringObjective dhcpUpstream = dhcpBuilder.add(new ObjectiveContext() {
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001106 @Override
1107 public void onSuccess(Objective objective) {
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001108 log.info("{} DHCP {} filter for {}.",
1109 completeFlowOpToString(action), (ethType.equals(EthType.EtherType.IPV4.ethType())) ? V4 : V6,
1110 portWithName(port));
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001111 }
1112
1113 @Override
1114 public void onError(Objective objective, ObjectiveError error) {
Tunahan Sezenf0843b92021-04-30 07:13:16 +00001115 log.error("DHCP {} filter for {} failed {} because {}",
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001116 (ethType.equals(EthType.EtherType.IPV4.ethType())) ? V4 : V6,
1117 portWithName(port),
1118 action,
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001119 error);
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001120 updateConnectPointStatus(sk, null, null, OltFlowsStatus.ERROR);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001121 }
1122 });
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001123 flowObjectiveService.filter(deviceId, dhcpUpstream);
1124 }
1125
1126 private void processIgmpFilteringObjectives(DeviceId deviceId, Port port,
1127 FlowOperation action, FlowDirection direction,
1128 MeterId meterId, MeterId oltMeterId, int techProfileId,
1129 VlanId cTag, VlanId unitagMatch, int vlanPcp) {
1130
1131 DefaultFilteringObjective.Builder filterBuilder = DefaultFilteringObjective.builder();
1132 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
1133 if (direction == FlowDirection.UPSTREAM) {
1134
1135 if (techProfileId != NONE_TP_ID) {
1136 treatmentBuilder.writeMetadata(createTechProfValueForWriteMetadata(null,
1137 techProfileId, oltMeterId), 0);
1138 }
1139
1140
1141 if (meterId != null) {
1142 treatmentBuilder.meter(meterId);
1143 }
1144
1145 if (!VlanId.vlanId(VlanId.NO_VID).equals(unitagMatch)) {
1146 filterBuilder.addCondition(Criteria.matchVlanId(unitagMatch));
1147 }
1148
1149 if (!VlanId.vlanId(VlanId.NO_VID).equals(cTag)) {
1150 treatmentBuilder.setVlanId(cTag);
1151 }
1152
1153 if (vlanPcp != -1) {
1154 treatmentBuilder.setVlanPcp((byte) vlanPcp);
1155 }
1156 }
1157
1158 filterBuilder = (action == FlowOperation.ADD) ? filterBuilder.permit() : filterBuilder.deny();
1159
1160 FilteringObjective igmp = filterBuilder
1161 .withKey(Criteria.matchInPort(port.number()))
1162 .addCondition(Criteria.matchEthType(EthType.EtherType.IPV4.ethType()))
1163 .addCondition(Criteria.matchIPProtocol(IPv4.PROTOCOL_IGMP))
1164 .withMeta(treatmentBuilder
1165 .setOutput(PortNumber.CONTROLLER).build())
1166 .fromApp(appId)
1167 .withPriority(MAX_PRIORITY)
1168 .add(new ObjectiveContext() {
1169 @Override
1170 public void onSuccess(Objective objective) {
1171 log.info("Igmp filter for {} {}.", portWithName(port), action);
1172 }
1173
1174 @Override
1175 public void onError(Objective objective, ObjectiveError error) {
1176 log.error("Igmp filter for {} failed {} because {}.", portWithName(port), action,
1177 error);
1178 }
1179 });
1180
1181 flowObjectiveService.filter(deviceId, igmp);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001182
1183 }
1184
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001185 private void processPPPoEDFilteringObjectives(DeviceId deviceId, Port port,
1186 FlowOperation action, FlowDirection direction,
1187 MeterId meterId, MeterId oltMeterId, int techProfileId,
1188 VlanId cTag, VlanId unitagMatch, Byte vlanPcp) {
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001189
1190 DefaultFilteringObjective.Builder builder = DefaultFilteringObjective.builder();
1191 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001192
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001193 if (meterId != null) {
1194 treatmentBuilder.meter(meterId);
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001195 }
1196
1197 if (techProfileId != NONE_TP_ID) {
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001198 treatmentBuilder.writeMetadata(createTechProfValueForWriteMetadata(cTag, techProfileId, oltMeterId), 0);
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001199 }
1200
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001201 DefaultFilteringObjective.Builder pppoedBuilder = ((action == FlowOperation.ADD)
1202 ? builder.permit() : builder.deny())
Tunahan Sezenf0843b92021-04-30 07:13:16 +00001203 .withKey(Criteria.matchInPort(port.number()))
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001204 .addCondition(Criteria.matchEthType(EthType.EtherType.PPPoED.ethType()))
1205 .fromApp(appId)
1206 .withPriority(10000);
1207
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001208 if (direction == FlowDirection.UPSTREAM) {
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001209 treatmentBuilder.setVlanId(cTag);
1210 if (!VlanId.vlanId(VlanId.NO_VID).equals(unitagMatch)) {
1211 pppoedBuilder.addCondition(Criteria.matchVlanId(unitagMatch));
1212 }
1213 if (vlanPcp != null) {
1214 treatmentBuilder.setVlanPcp(vlanPcp);
1215 }
1216 }
1217 pppoedBuilder = pppoedBuilder.withMeta(treatmentBuilder.setOutput(PortNumber.CONTROLLER).build());
1218
1219 FilteringObjective pppoed = pppoedBuilder
1220 .add(new ObjectiveContext() {
1221 @Override
1222 public void onSuccess(Objective objective) {
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001223 log.info("PPPoED filter for {} {}.", portWithName(port), action);
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001224 }
1225
1226 @Override
1227 public void onError(Objective objective, ObjectiveError error) {
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001228 log.info("PPPoED filter for {} failed {} because {}", portWithName(port),
1229 action, error);
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001230 }
1231 });
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001232 flowObjectiveService.filter(deviceId, pppoed);
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001233 }
1234
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001235 private void processUpstreamDataFilteringObjects(DeviceId deviceId, Port port, Port nniPort,
1236 FlowOperation action,
1237 MeterId upstreamMeterId,
1238 MeterId upstreamOltMeterId,
1239 UniTagInformation uti) {
1240 ServiceKey sk = new ServiceKey(new AccessDevicePort(port), uti);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001241 TrafficSelector selector = DefaultTrafficSelector.builder()
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001242 .matchInPort(port.number())
1243 .matchVlanId(uti.getUniTagMatch())
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001244 .build();
1245
Andrea Campanella327c5722020-01-30 11:34:13 +01001246 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
1247 //if the subscriberVlan (cTag) is different than ANY it needs to set.
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001248 if (uti.getPonCTag().toShort() != VlanId.ANY_VALUE) {
Andrea Campanella327c5722020-01-30 11:34:13 +01001249 treatmentBuilder.pushVlan()
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001250 .setVlanId(uti.getPonCTag());
Andrea Campanella327c5722020-01-30 11:34:13 +01001251 }
Maria Carmela Cascino067ee4d2021-11-02 13:14:43 +01001252 if (uti.getPonSTag().toShort() == VlanId.ANY_VALUE) {
1253 treatmentBuilder.popVlan();
1254 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001255
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001256 if (uti.getUsPonCTagPriority() != -1) {
1257 treatmentBuilder.setVlanPcp((byte) uti.getUsPonCTagPriority());
Maria Carmela Cascino067ee4d2021-11-02 13:14:43 +01001258
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001259 }
1260
1261 treatmentBuilder.pushVlan()
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001262 .setVlanId(uti.getPonSTag());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001263
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001264 if (uti.getUsPonSTagPriority() != -1) {
1265 treatmentBuilder.setVlanPcp((byte) uti.getUsPonSTagPriority());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001266 }
1267
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001268 treatmentBuilder.setOutput(nniPort.number())
1269 .writeMetadata(createMetadata(uti.getPonCTag(),
1270 uti.getTechnologyProfileId(), nniPort.number()), 0L);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001271
yasin saplib4b8ee12021-06-13 18:25:20 +00001272 DefaultAnnotations.Builder annotationBuilder = DefaultAnnotations.builder();
1273
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001274 if (upstreamMeterId != null) {
1275 treatmentBuilder.meter(upstreamMeterId);
yasin saplib4b8ee12021-06-13 18:25:20 +00001276 annotationBuilder.set(UPSTREAM_ONU, upstreamMeterId.toString());
1277 }
1278 if (upstreamOltMeterId != null) {
1279 treatmentBuilder.meter(upstreamOltMeterId);
1280 annotationBuilder.set(UPSTREAM_OLT, upstreamOltMeterId.toString());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001281 }
1282
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001283 DefaultForwardingObjective.Builder flowBuilder = createForwardingObjectiveBuilder(selector,
1284 treatmentBuilder.build(), MIN_PRIORITY,
yasin saplib4b8ee12021-06-13 18:25:20 +00001285 annotationBuilder.build());
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001286
1287 ObjectiveContext context = new ObjectiveContext() {
1288 @Override
1289 public void onSuccess(Objective objective) {
1290 log.info("{} Upstream Data plane filter for {}.",
1291 completeFlowOpToString(action), sk);
1292 }
1293
1294 @Override
1295 public void onError(Objective objective, ObjectiveError error) {
1296 log.error("Upstream Data plane filter for {} failed {} because {}.",
1297 sk, action, error);
1298 updateConnectPointStatus(sk, null, OltFlowsStatus.ERROR, null);
1299 }
1300 };
1301
1302 ForwardingObjective flow = null;
1303 if (action == FlowOperation.ADD) {
1304 flow = flowBuilder.add(context);
1305 } else if (action == FlowOperation.REMOVE) {
1306 flow = flowBuilder.remove(context);
1307 } else {
1308 log.error("Flow action not supported: {}", action);
1309 }
1310
1311 if (flow != null) {
1312 flowObjectiveService.forward(deviceId, flow);
1313 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001314 }
1315
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001316 private void processDownstreamDataFilteringObjects(DeviceId deviceId, Port port, Port nniPort,
1317 FlowOperation action,
1318 MeterId downstreamMeterId,
1319 MeterId downstreamOltMeterId,
1320 UniTagInformation uti,
1321 MacAddress macAddress) {
1322 ServiceKey sk = new ServiceKey(new AccessDevicePort(port), uti);
Andrea Campanella327c5722020-01-30 11:34:13 +01001323 //subscriberVlan can be any valid Vlan here including ANY to make sure the packet is tagged
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001324 TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder()
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001325 .matchVlanId(uti.getPonSTag())
1326 .matchInPort(nniPort.number())
1327 .matchInnerVlanId(uti.getPonCTag());
Andrea Campanella090e4a02020-02-05 13:53:55 +01001328
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001329 if (uti.getPonCTag().toShort() != VlanId.ANY_VALUE) {
1330 selectorBuilder.matchMetadata(uti.getPonCTag().toShort());
Andrea Campanella090e4a02020-02-05 13:53:55 +01001331 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001332
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001333 if (uti.getDsPonCTagPriority() != -1) {
1334 selectorBuilder.matchVlanPcp((byte) uti.getDsPonCTagPriority());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001335 }
1336
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001337 if (macAddress != null) {
1338 selectorBuilder.matchEthDst(macAddress);
1339 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001340
1341 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder()
1342 .popVlan()
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001343 .setOutput(port.number());
Andrea Campanella327c5722020-01-30 11:34:13 +01001344
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001345 treatmentBuilder.writeMetadata(createMetadata(uti.getPonCTag(),
1346 uti.getTechnologyProfileId(),
1347 port.number()), 0);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001348
Andrea Campanella981e86c2021-03-12 11:35:33 +01001349 // Upstream pbit is used to remark inner vlan pbit.
1350 // Upstream is used to avoid trusting the BNG to send the packet with correct pbit.
1351 // this is done because ds mode 0 is used because ds mode 3 or 6 that allow for
1352 // all pbit acceptance are not widely supported by vendors even though present in
1353 // the OMCI spec.
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001354 if (uti.getUsPonCTagPriority() != -1) {
1355 treatmentBuilder.setVlanPcp((byte) uti.getUsPonCTagPriority());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001356 }
1357
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001358 if (!VlanId.NONE.equals(uti.getUniTagMatch()) &&
1359 uti.getPonCTag().toShort() != VlanId.ANY_VALUE) {
1360 treatmentBuilder.setVlanId(uti.getUniTagMatch());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001361 }
1362
yasin saplib4b8ee12021-06-13 18:25:20 +00001363 DefaultAnnotations.Builder annotationBuilder = DefaultAnnotations.builder();
1364
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001365 if (downstreamMeterId != null) {
1366 treatmentBuilder.meter(downstreamMeterId);
yasin saplib4b8ee12021-06-13 18:25:20 +00001367 annotationBuilder.set(DOWNSTREAM_ONU, downstreamMeterId.toString());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001368 }
1369
yasin saplib4b8ee12021-06-13 18:25:20 +00001370 if (downstreamOltMeterId != null) {
1371 treatmentBuilder.meter(downstreamOltMeterId);
1372 annotationBuilder.set(DOWNSTREAM_OLT, downstreamOltMeterId.toString());
1373 }
1374
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001375 DefaultForwardingObjective.Builder flowBuilder = createForwardingObjectiveBuilder(selectorBuilder.build(),
1376 treatmentBuilder.build(), MIN_PRIORITY, annotationBuilder.build());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001377
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001378 ObjectiveContext context = new ObjectiveContext() {
1379 @Override
1380 public void onSuccess(Objective objective) {
1381 log.info("{} Downstream Data plane filter for {}.",
1382 completeFlowOpToString(action), sk);
1383 }
1384
1385 @Override
1386 public void onError(Objective objective, ObjectiveError error) {
1387 log.info("Downstream Data plane filter for {} failed {} because {}.",
1388 sk, action, error);
1389 updateConnectPointStatus(sk, null, OltFlowsStatus.ERROR, null);
1390 }
1391 };
1392
1393 ForwardingObjective flow = null;
1394 if (action == FlowOperation.ADD) {
1395 flow = flowBuilder.add(context);
1396 } else if (action == FlowOperation.REMOVE) {
1397 flow = flowBuilder.remove(context);
1398 } else {
1399 log.error("Flow action not supported: {}", action);
1400 }
1401
1402 if (flow != null) {
1403 if (log.isTraceEnabled()) {
1404 log.trace("Forwarding rule {}", flow);
1405 }
1406 flowObjectiveService.forward(deviceId, flow);
1407 }
Andrea Campanella600d2e22020-06-22 11:00:31 +02001408 }
1409
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001410 private DefaultForwardingObjective.Builder createForwardingObjectiveBuilder(TrafficSelector selector,
1411 TrafficTreatment treatment,
yasin saplib4b8ee12021-06-13 18:25:20 +00001412 Integer priority,
1413 Annotations annotations) {
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001414 return DefaultForwardingObjective.builder()
1415 .withFlag(ForwardingObjective.Flag.VERSATILE)
1416 .withPriority(priority)
1417 .makePermanent()
1418 .withSelector(selector)
yasin saplib4b8ee12021-06-13 18:25:20 +00001419 .withAnnotations(annotations)
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001420 .fromApp(appId)
1421 .withTreatment(treatment);
1422 }
1423
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001424 private Long createMetadata(VlanId innerVlan, int techProfileId, PortNumber egressPort) {
1425 if (techProfileId == NONE_TP_ID) {
Andrea Campanella7c49b792020-05-11 11:36:53 +02001426 techProfileId = DEFAULT_TP_ID_DEFAULT;
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001427 }
1428
1429 return ((long) (innerVlan.id()) << 48 | (long) techProfileId << 32) | egressPort.toLong();
1430 }
1431
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001432 private boolean isMacLearningEnabled(SubscriberAndDeviceInformation si) {
1433 AtomicBoolean requiresMacLearning = new AtomicBoolean();
1434 requiresMacLearning.set(false);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001435
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001436 si.uniTagList().forEach(uniTagInfo -> {
1437 if (uniTagInfo.getEnableMacLearning()) {
1438 requiresMacLearning.set(true);
1439 }
1440 });
1441
1442 return requiresMacLearning.get();
1443 }
1444
1445 /**
1446 * Checks whether the subscriber has the MacAddress configured or discovered.
1447 *
1448 * @param deviceId DeviceId for this subscriber
1449 * @param port Port for this subscriber
1450 * @param si SubscriberAndDeviceInformation
1451 * @return boolean
1452 */
1453 protected boolean isMacAddressAvailable(DeviceId deviceId, Port port, SubscriberAndDeviceInformation si) {
1454 AtomicBoolean isConfigured = new AtomicBoolean();
1455 isConfigured.set(true);
1456
1457 si.uniTagList().forEach(uniTagInfo -> {
1458 boolean isMacLearningEnabled = uniTagInfo.getEnableMacLearning();
1459 boolean configureMac = isMacAddressValid(uniTagInfo);
1460 boolean discoveredMac = false;
1461 Optional<Host> optHost = hostService.getConnectedHosts(new ConnectPoint(deviceId, port.number()))
1462 .stream().filter(host -> host.vlan().equals(uniTagInfo.getPonCTag())).findFirst();
1463 if (optHost.isPresent() && optHost.get().mac() != null) {
1464 discoveredMac = true;
1465 }
1466 if (isMacLearningEnabled && !configureMac && !discoveredMac) {
1467 log.debug("Awaiting for macAddress on {} for service {}",
1468 portWithName(port), uniTagInfo.getServiceName());
1469 isConfigured.set(false);
1470 }
1471 });
1472
1473 return isConfigured.get();
1474 }
1475
1476 protected MacAddress getMacAddress(DeviceId deviceId, Port port, UniTagInformation uniTagInfo) {
1477 boolean configuredMac = isMacAddressValid(uniTagInfo);
1478 if (configuredMac) {
1479 return MacAddress.valueOf(uniTagInfo.getConfiguredMacAddress());
1480 } else if (uniTagInfo.getEnableMacLearning()) {
1481 Optional<Host> optHost = hostService.getConnectedHosts(new ConnectPoint(deviceId, port.number()))
1482 .stream().filter(host -> host.vlan().equals(uniTagInfo.getPonCTag())).findFirst();
1483 if (optHost.isPresent() && optHost.get().mac() != null) {
1484 return optHost.get().mac();
1485 }
1486 }
1487 return null;
1488 }
1489
1490 private boolean isMacAddressValid(UniTagInformation tagInformation) {
1491 return tagInformation.getConfiguredMacAddress() != null &&
1492 !tagInformation.getConfiguredMacAddress().trim().equals("") &&
1493 !MacAddress.NONE.equals(MacAddress.valueOf(tagInformation.getConfiguredMacAddress()));
1494 }
1495
1496 protected void updateConnectPointStatus(ServiceKey key, OltFlowsStatus eapolStatus,
1497 OltFlowsStatus subscriberFlowsStatus, OltFlowsStatus dhcpStatus) {
Matteo Scandolo2542e5d2021-12-01 16:53:41 -08001498 if (log.isTraceEnabled()) {
1499 log.trace("Updating cpStatus {} with values: eapolFlow={}, subscriberFlows={}, dhcpFlow={}",
1500 key, eapolStatus, subscriberFlowsStatus, dhcpStatus);
1501 }
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001502 try {
1503 cpStatusWriteLock.lock();
1504 OltPortStatus status = cpStatus.get(key);
1505
Matteo Scandolo2542e5d2021-12-01 16:53:41 -08001506
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001507 if (status == null) {
Matteo Scandolo2542e5d2021-12-01 16:53:41 -08001508 // if we don't have status for the connectPoint
1509 // and we're only updating status to PENDING_REMOVE or ERROR
1510 // do not create it. This is because this case will only happen when a device is removed
1511 // and it's status cleaned
1512 List<OltFlowsStatus> statusesToIgnore = new ArrayList<>();
1513 statusesToIgnore.add(OltFlowsStatus.PENDING_REMOVE);
1514 statusesToIgnore.add(OltFlowsStatus.ERROR);
1515
1516 if (
1517 (statusesToIgnore.contains(subscriberFlowsStatus) && dhcpStatus == null) ||
1518 (subscriberFlowsStatus == null && statusesToIgnore.contains(dhcpStatus))
1519 ) {
1520 if (log.isTraceEnabled()) {
1521 log.trace("Ignoring cpStatus update as status is meaningless");
1522 }
1523 return;
1524 }
1525
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001526 status = new OltPortStatus(
1527 eapolStatus != null ? eapolStatus : OltFlowsStatus.NONE,
1528 subscriberFlowsStatus != null ? subscriberFlowsStatus : OltFlowsStatus.NONE,
1529 dhcpStatus != null ? dhcpStatus : OltFlowsStatus.NONE
1530 );
1531 } else {
1532 if (eapolStatus != null) {
1533 status.defaultEapolStatus = eapolStatus;
1534 }
1535 if (subscriberFlowsStatus != null) {
1536 status.subscriberFlowsStatus = subscriberFlowsStatus;
1537 }
1538 if (dhcpStatus != null) {
1539 status.dhcpStatus = dhcpStatus;
1540 }
1541 }
1542
1543 cpStatus.put(key, status);
1544 } finally {
1545 cpStatusWriteLock.unlock();
1546 }
1547 }
1548
1549 protected class InternalFlowListener implements FlowRuleListener {
1550 @Override
1551 public void event(FlowRuleEvent event) {
1552 if (appId.id() != (event.subject().appId())) {
1553 return;
1554 }
1555
1556 if (!oltDeviceService.isLocalLeader(event.subject().deviceId())) {
1557 if (log.isTraceEnabled()) {
1558 log.trace("ignoring flow event {} " +
1559 "as not leader for {}", event, event.subject().deviceId());
1560 }
1561 return;
1562 }
1563
1564 switch (event.type()) {
1565 case RULE_ADDED:
1566 case RULE_REMOVED:
1567 Port port = getCpFromFlowRule(event.subject());
1568 if (port == null) {
1569 log.error("Can't find port in flow {}", event.subject());
1570 return;
1571 }
1572 if (log.isTraceEnabled()) {
1573 log.trace("flow event {} on cp {}: {}", event.type(),
1574 portWithName(port), event.subject());
1575 }
1576 updateCpStatus(event.type(), port, event.subject());
1577 return;
1578 case RULE_ADD_REQUESTED:
1579 case RULE_REMOVE_REQUESTED:
1580 // NOTE that PENDING_ADD/REMOVE is set when we create the flowObjective
1581 return;
1582 default:
1583 return;
1584 }
1585 }
1586
1587 protected void updateCpStatus(FlowRuleEvent.Type type, Port port, FlowRule flowRule) {
1588 OltFlowsStatus status = flowRuleStatusToOltFlowStatus(type);
1589 if (isDefaultEapolFlow(flowRule)) {
1590 ServiceKey sk = new ServiceKey(new AccessDevicePort(port),
1591 defaultEapolUniTag);
1592 if (log.isTraceEnabled()) {
1593 log.trace("update defaultEapolStatus {} on {}", status, sk);
1594 }
1595 updateConnectPointStatus(sk, status, null, null);
1596 } else if (isDhcpFlow(flowRule)) {
1597 ServiceKey sk = getSubscriberKeyFromFlowRule(flowRule);
1598 if (sk == null) {
1599 return;
1600 }
1601 if (log.isTraceEnabled()) {
1602 log.trace("update dhcpStatus {} on {}", status, sk);
1603 }
1604 updateConnectPointStatus(sk, null, null, status);
1605 } else if (isDataFlow(flowRule)) {
1606
1607 if (oltDeviceService.isNniPort(deviceService.getDevice(flowRule.deviceId()),
1608 getCpFromFlowRule(flowRule).number())) {
1609 // the NNI has data-plane for every subscriber, doesn't make sense to track them
1610 return;
1611 }
1612
1613 ServiceKey sk = getSubscriberKeyFromFlowRule(flowRule);
1614 if (sk == null) {
1615 return;
1616 }
1617 if (log.isTraceEnabled()) {
1618 log.trace("update dataplaneStatus {} on {}", status, sk);
1619 }
1620 updateConnectPointStatus(sk, null, status, null);
1621 }
1622 }
1623
1624 private boolean isDefaultEapolFlow(FlowRule flowRule) {
1625 EthTypeCriterion c = (EthTypeCriterion) flowRule.selector().getCriterion(Criterion.Type.ETH_TYPE);
1626 if (c == null) {
1627 return false;
1628 }
1629 if (c.ethType().equals(EthType.EtherType.EAPOL.ethType())) {
1630 AtomicBoolean isDefault = new AtomicBoolean(false);
1631 flowRule.treatment().allInstructions().forEach(instruction -> {
1632 if (instruction.type() == L2MODIFICATION) {
1633 L2ModificationInstruction modificationInstruction = (L2ModificationInstruction) instruction;
1634 if (modificationInstruction.subtype() == L2ModificationInstruction.L2SubType.VLAN_ID) {
1635 L2ModificationInstruction.ModVlanIdInstruction vlanInstruction =
1636 (L2ModificationInstruction.ModVlanIdInstruction) modificationInstruction;
1637 if (vlanInstruction.vlanId().id().equals(EAPOL_DEFAULT_VLAN)) {
1638 isDefault.set(true);
1639 return;
1640 }
1641 }
1642 }
1643 });
1644 return isDefault.get();
1645 }
1646 return false;
1647 }
1648
1649 /**
1650 * Returns true if the flow is a DHCP flow.
1651 * Matches both upstream and downstream flows.
1652 *
1653 * @param flowRule The FlowRule to evaluate
1654 * @return boolean
1655 */
1656 private boolean isDhcpFlow(FlowRule flowRule) {
1657 IPProtocolCriterion ipCriterion = (IPProtocolCriterion) flowRule.selector()
1658 .getCriterion(Criterion.Type.IP_PROTO);
1659 if (ipCriterion == null) {
1660 return false;
1661 }
1662
1663 UdpPortCriterion src = (UdpPortCriterion) flowRule.selector().getCriterion(Criterion.Type.UDP_SRC);
1664
1665 if (src == null) {
1666 return false;
1667 }
1668 return ipCriterion.protocol() == IPv4.PROTOCOL_UDP &&
1669 (src.udpPort().toInt() == 68 || src.udpPort().toInt() == 67);
1670 }
1671
1672 private boolean isDataFlow(FlowRule flowRule) {
1673 // we consider subscriber flows the one that matches on VLAN_VID
1674 // method is valid only because it's the last check after EAPOL and DHCP.
1675 // this matches mcast flows as well, if we want to avoid that we can
1676 // filter out the elements that have groups in the treatment or
1677 // mcastIp in the selector
1678 // IPV4_DST:224.0.0.22/32
1679 // treatment=[immediate=[GROUP:0x1]]
1680
1681 return flowRule.selector().getCriterion(Criterion.Type.VLAN_VID) != null;
1682 }
1683
1684 private Port getCpFromFlowRule(FlowRule flowRule) {
1685 DeviceId deviceId = flowRule.deviceId();
1686 PortCriterion inPort = (PortCriterion) flowRule.selector().getCriterion(Criterion.Type.IN_PORT);
1687 if (inPort != null) {
1688 PortNumber port = inPort.port();
1689 return deviceService.getPort(deviceId, port);
1690 }
1691 return null;
1692 }
1693
1694 private ServiceKey getSubscriberKeyFromFlowRule(FlowRule flowRule) {
1695 Port flowPort = getCpFromFlowRule(flowRule);
1696 SubscriberAndDeviceInformation si = subsService.get(getPortName(flowPort));
1697
1698 Boolean isNni = oltDeviceService.isNniPort(deviceService.getDevice(flowRule.deviceId()), flowPort.number());
1699 if (si == null && !isNni) {
1700 log.error("Subscriber information not found in sadis for port {}", portWithName(flowPort));
1701 return null;
1702 }
1703
1704 if (isNni) {
1705 return new ServiceKey(new AccessDevicePort(flowPort), nniUniTag);
1706 }
1707
1708 Optional<UniTagInformation> found = Optional.empty();
1709 VlanId flowVlan = null;
1710 if (isDhcpFlow(flowRule)) {
1711 // we need to make a special case for DHCP as in the ATT workflow DHCP flows don't match on tags
1712 L2ModificationInstruction.ModVlanIdInstruction instruction =
1713 (L2ModificationInstruction.ModVlanIdInstruction) flowRule.treatment().immediate().get(1);
1714 flowVlan = instruction.vlanId();
1715 } else {
1716 // for now we assume that if it's not DHCP it's dataplane (or at least tagged)
1717 VlanIdCriterion vlanIdCriterion =
1718 (VlanIdCriterion) flowRule.selector().getCriterion(Criterion.Type.VLAN_VID);
1719 if (vlanIdCriterion == null) {
1720 log.warn("cannot match the flow to a subscriber service as it does not carry vlans");
1721 return null;
1722 }
1723 flowVlan = vlanIdCriterion.vlanId();
1724 }
1725
1726 VlanId finalFlowVlan = flowVlan;
1727 found = si.uniTagList().stream().filter(uti ->
1728 uti.getPonCTag().equals(finalFlowVlan) ||
1729 uti.getPonSTag().equals(finalFlowVlan) ||
1730 uti.getUniTagMatch().equals(finalFlowVlan)
1731 ).findFirst();
1732
1733
1734 if (found.isEmpty()) {
1735 log.warn("Cannot map flow rule {} to Service in {}", flowRule, si);
1736 }
1737
1738 return found.isPresent() ? new ServiceKey(new AccessDevicePort(flowPort), found.get()) : null;
1739
1740 }
1741
1742 private OltFlowsStatus flowRuleStatusToOltFlowStatus(FlowRuleEvent.Type type) {
1743 switch (type) {
1744 case RULE_ADD_REQUESTED:
1745 return OltFlowsStatus.PENDING_ADD;
1746 case RULE_ADDED:
1747 return OltFlowsStatus.ADDED;
1748 case RULE_REMOVE_REQUESTED:
1749 return OltFlowsStatus.PENDING_REMOVE;
1750 case RULE_REMOVED:
1751 return OltFlowsStatus.REMOVED;
1752 default:
1753 return OltFlowsStatus.NONE;
1754 }
1755 }
1756 }
1757
1758 protected void bindSadisService(SadisService service) {
1759 this.subsService = service.getSubscriberInfoService();
1760 this.bpService = service.getBandwidthProfileService();
1761 log.info("Sadis service is loaded");
1762 }
1763
1764 protected void unbindSadisService(SadisService service) {
1765 this.subsService = null;
1766 this.bpService = null;
1767 log.info("Sadis service is unloaded");
1768 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001769}