blob: eed2b3e9ec9b523c3e945da1b8bb518a218b1676 [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;
Matteo Scandolo97449bb2021-12-09 15:33:46 -0800178 protected static final short EAPOL_DEFAULT_VLAN = 4091;
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700179 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
Matteo Scandolod7aa89c2021-12-07 10:21:34 -0800425 log.debug("{} LLDP trap flow on NNI {} for device {}", flowOpToString(action), portWithName(port), device.id());
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700426 processLldpFilteringObjective(device.id(), port, action);
427
428 if (enableDhcpOnNni) {
429 if (enableDhcpV4) {
Matteo Scandolod7aa89c2021-12-07 10:21:34 -0800430 log.debug("{} DHCPv4 trap flow on NNI {} for device {}", flowOpToString(action),
431 portWithName(port), device.id());
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700432 processDhcpFilteringObjectives(device.id(), port, action, FlowDirection.DOWNSTREAM,
433 67, 68, EthType.EtherType.IPV4.ethType(), IPv4.PROTOCOL_UDP,
434 null, null, nniUniTag);
435 }
436 if (enableDhcpV6) {
Matteo Scandolod7aa89c2021-12-07 10:21:34 -0800437 log.debug("{} DHCPv6 trap flow on NNI {} for device {}", flowOpToString(action),
438 portWithName(port), device.id());
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700439 processDhcpFilteringObjectives(device.id(), port, action, FlowDirection.DOWNSTREAM,
440 546, 547, EthType.EtherType.IPV6.ethType(), IPv6.PROTOCOL_UDP,
441 null, null, nniUniTag);
442 }
443 } else {
Matteo Scandolo1f8de332021-12-06 12:18:24 -0800444 log.debug("DHCP is not required on NNI {} for device {}", portWithName(port), device.id());
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700445 }
446
447 if (enableIgmpOnNni) {
Matteo Scandolod7aa89c2021-12-07 10:21:34 -0800448 log.debug("{} IGMP flow on NNI {} for device {}", flowOpToString(action), portWithName(port), device.id());
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700449 processIgmpFilteringObjectives(device.id(), port, action, FlowDirection.DOWNSTREAM,
450 null, null, NONE_TP_ID, VlanId.NONE, VlanId.ANY, -1);
451 }
452
453 if (enablePppoe) {
Matteo Scandolod7aa89c2021-12-07 10:21:34 -0800454 log.debug("{} PPPoE flow on NNI {} for device {}", flowOpToString(action), port.number(), device.id());
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700455 processPPPoEDFilteringObjectives(device.id(), port, action, FlowDirection.DOWNSTREAM,
456 null, null, NONE_TP_ID, VlanId.NONE, VlanId.ANY, null);
457 }
458 }
459
460 @Override
461 public boolean handleBasicPortFlows(DiscoveredSubscriber sub, String bandwidthProfileId,
462 String oltBandwidthProfileId) {
463
464 // we only need to something if EAPOL is enabled
465 if (!enableEapol) {
466 return true;
467 }
468
469 if (sub.status == DiscoveredSubscriber.Status.ADDED) {
470 return addDefaultFlows(sub, bandwidthProfileId, oltBandwidthProfileId);
471 } else if (sub.status == DiscoveredSubscriber.Status.REMOVED) {
472 return removeDefaultFlows(sub, bandwidthProfileId, oltBandwidthProfileId);
473 } else {
474 log.error("Unknown Status {} on DiscoveredSubscriber {}", sub.status, sub);
475 return false;
476 }
477
478 }
479
480 private boolean addDefaultFlows(DiscoveredSubscriber sub, String bandwidthProfileId, String oltBandwidthProfileId) {
481
482 if (!oltMeterService.createMeter(sub.device.id(), bandwidthProfileId)) {
483 if (log.isTraceEnabled()) {
484 log.trace("waiting on meter for bp {} and sub {}", bandwidthProfileId, sub);
485 }
486 return false;
487 }
488 if (hasDefaultEapol(sub.port)) {
489 return true;
490 }
491 return handleEapolFlow(sub, bandwidthProfileId,
492 oltBandwidthProfileId, FlowOperation.ADD, VlanId.vlanId(EAPOL_DEFAULT_VLAN));
493
494 }
495
496 private boolean removeDefaultFlows(DiscoveredSubscriber sub, String bandwidthProfile, String oltBandwidthProfile) {
497 // NOTE that we are not checking for meters as they must have been created to install the flow in first place
498 return handleEapolFlow(sub, bandwidthProfile, oltBandwidthProfile,
499 FlowOperation.REMOVE, VlanId.vlanId(EAPOL_DEFAULT_VLAN));
500 }
501
502 @Override
503 public boolean handleSubscriberFlows(DiscoveredSubscriber sub, String defaultBandwidthProfile,
504 String multicastServiceName) {
505 // NOTE that we are taking defaultBandwithProfile as a parameter as that can be configured in the Olt component
506 if (sub.status == DiscoveredSubscriber.Status.ADDED) {
507 return addSubscriberFlows(sub, defaultBandwidthProfile, multicastServiceName);
508 } else if (sub.status == DiscoveredSubscriber.Status.REMOVED) {
509 return removeSubscriberFlows(sub, defaultBandwidthProfile, multicastServiceName);
510 } else {
511 log.error("don't know how to handle {}", sub);
512 return false;
513 }
514 }
515
516 private boolean addSubscriberFlows(DiscoveredSubscriber sub, String defaultBandwithProfile,
517 String multicastServiceName) {
518 if (log.isTraceEnabled()) {
519 log.trace("Provisioning of subscriber on {} started", portWithName(sub.port));
520 }
521 if (enableEapol) {
522 if (hasDefaultEapol(sub.port)) {
523 // remove EAPOL flow and throw exception so that we'll retry later
524 if (!isDefaultEapolPendingRemoval(sub.port)) {
525 removeDefaultFlows(sub, defaultBandwithProfile, defaultBandwithProfile);
526 }
527
528 if (waitForRemoval) {
529 // NOTE wait for removal is a flag only needed to make sure VOLTHA
530 // does not explode with the flows remove/add in the same batch
531 log.debug("Awaiting for default flows removal for {}", portWithName(sub.port));
532 return false;
533 } else {
534 log.warn("continuing provisioning on {}", portWithName(sub.port));
535 }
536 }
537
538 }
539
540 // NOTE createMeters will return if the meters are not installed
541 if (!oltMeterService.createMeters(sub.device.id(),
Matteo Scandolo88df8ae2021-11-23 13:12:29 -0800542 sub.subscriberAndDeviceInformation, multicastServiceName)) {
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700543 return false;
544 }
545
546 // NOTE we need to add the DHCP flow regardless so that the host can be discovered and the MacAddress added
547 handleSubscriberDhcpFlows(sub.device.id(), sub.port, FlowOperation.ADD,
548 sub.subscriberAndDeviceInformation);
549
550 if (isMacLearningEnabled(sub.subscriberAndDeviceInformation)
551 && !isMacAddressAvailable(sub.device.id(), sub.port,
552 sub.subscriberAndDeviceInformation)) {
553 log.debug("Awaiting for macAddress on {}", portWithName(sub.port));
554 return false;
555 }
556
Matteo Scandolo8a91c0f2021-12-03 10:58:14 -0800557 // NOTE that the EAPOL flows handling is based on the data-plane flows status
558 // always process them before
559 handleSubscriberEapolFlows(sub, FlowOperation.ADD, sub.subscriberAndDeviceInformation);
560
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700561 handleSubscriberDataFlows(sub.device, sub.port, FlowOperation.ADD,
562 sub.subscriberAndDeviceInformation, multicastServiceName);
563
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700564 handleSubscriberIgmpFlows(sub, FlowOperation.ADD);
565
566 log.info("Provisioning of subscriber on {} completed", portWithName(sub.port));
567 return true;
568 }
569
Matteo Scandolo97449bb2021-12-09 15:33:46 -0800570 protected boolean removeSubscriberFlows(DiscoveredSubscriber sub, String defaultBandwithProfile,
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700571 String multicastServiceName) {
572
573 if (log.isTraceEnabled()) {
574 log.trace("Removal of subscriber on {} started",
575 portWithName(sub.port));
576 }
Matteo Scandolo97449bb2021-12-09 15:33:46 -0800577 SubscriberAndDeviceInformation si = sub.subscriberAndDeviceInformation;
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700578
579 handleSubscriberDhcpFlows(sub.device.id(), sub.port, FlowOperation.REMOVE, si);
580
581 if (enableEapol) {
582 // remove the tagged eapol
583 handleSubscriberEapolFlows(sub, FlowOperation.REMOVE, si);
Matteo Scandolo97449bb2021-12-09 15:33:46 -0800584 }
585 handleSubscriberDataFlows(sub.device, sub.port, FlowOperation.REMOVE, si, multicastServiceName);
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700586
Matteo Scandolo97449bb2021-12-09 15:33:46 -0800587 handleSubscriberIgmpFlows(sub, FlowOperation.REMOVE);
588
589 if (enableEapol) {
590
591 // if any of the services still has flows, return false
592 Iterator<UniTagInformation> iter = sub.subscriberAndDeviceInformation.uniTagList().iterator();
593 while (iter.hasNext()) {
594 UniTagInformation entry = iter.next();
595 if (areSubscriberFlowsPendingRemoval(sub.port, entry)) {
596 log.info("Subscriber {} still have flows on service {}, postpone default EAPOL installation.",
597 portWithName(sub.port), entry.getServiceName());
598 return false;
599 }
600 }
601
602 // once the flows are removed add the default one back
603 // (only if the port is ENABLED and still present on the device)
Matteo Scandolo49c42052021-11-23 13:12:29 -0800604 if (sub.port.isEnabled() && deviceService.getPort(sub.device.id(), sub.port.number()) != null) {
605
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700606 // NOTE we remove the subscriber when the port goes down
607 // but in that case we don't need to add default eapol
608 handleEapolFlow(sub, defaultBandwithProfile, defaultBandwithProfile,
609 FlowOperation.ADD, VlanId.vlanId(EAPOL_DEFAULT_VLAN));
610 }
611 }
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700612 // FIXME check the return status of the flow and return accordingly
613 log.info("Removal of subscriber on {} completed", portWithName(sub.port));
614 return true;
615 }
616
617 @Override
618 public boolean hasDefaultEapol(Port port) {
619 OltPortStatus status = getOltPortStatus(port, defaultEapolUniTag);
620 // NOTE we consider ERROR as a present EAPOL flow as ONOS
621 // will keep trying to add it
622 return status != null && (status.defaultEapolStatus == OltFlowsStatus.ADDED ||
623 status.defaultEapolStatus == OltFlowsStatus.PENDING_ADD ||
624 status.defaultEapolStatus == OltFlowsStatus.ERROR);
625 }
626
627 private OltPortStatus getOltPortStatus(Port port, UniTagInformation uniTagInformation) {
628 try {
629 cpStatusReadLock.lock();
630 ServiceKey sk = new ServiceKey(new AccessDevicePort(port), uniTagInformation);
631 OltPortStatus status = cpStatus.get(sk);
632 return status;
633 } finally {
634 cpStatusReadLock.unlock();
635 }
636 }
637
638 public boolean isDefaultEapolPendingRemoval(Port port) {
639 OltPortStatus status = getOltPortStatus(port, defaultEapolUniTag);
640 if (log.isTraceEnabled()) {
641 log.trace("Status during EAPOL flow check {} for port {} and UniTagInformation {}",
642 status, portWithName(port), defaultEapolUniTag);
643 }
644 return status != null && status.defaultEapolStatus == OltFlowsStatus.PENDING_REMOVE;
645 }
646
647 @Override
648 public boolean hasDhcpFlows(Port port, UniTagInformation uti) {
649 OltPortStatus status = getOltPortStatus(port, uti);
650 if (log.isTraceEnabled()) {
651 log.trace("Status during DHCP flow check {} for port {} and service {}",
652 status, portWithName(port), uti.getServiceName());
653 }
654 return status != null &&
655 (status.dhcpStatus == OltFlowsStatus.ADDED ||
656 status.dhcpStatus == OltFlowsStatus.PENDING_ADD);
657 }
658
659 @Override
660 public boolean hasSubscriberFlows(Port port, UniTagInformation uti) {
661
662 OltPortStatus status = getOltPortStatus(port, uti);
663 if (log.isTraceEnabled()) {
664 log.trace("Status during subscriber flow check {} for port {} and service {}",
665 status, portWithName(port), uti.getServiceName());
666 }
667 return status != null && (status.subscriberFlowsStatus == OltFlowsStatus.ADDED ||
668 status.subscriberFlowsStatus == OltFlowsStatus.PENDING_ADD);
669 }
670
Matteo Scandolo97449bb2021-12-09 15:33:46 -0800671 public boolean areSubscriberFlowsPendingRemoval(Port port, UniTagInformation uti) {
672 OltPortStatus status = getOltPortStatus(port, uti);
673 if (log.isTraceEnabled()) {
674 log.trace("Status during pending_remove flow check {} for port {} and UniTagInformation {}",
675 status, portWithName(port), uti);
676 }
677 return status != null && status.subscriberFlowsStatus == OltFlowsStatus.PENDING_REMOVE;
678 }
679
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700680 @Override
681 public void purgeDeviceFlows(DeviceId deviceId) {
682 log.debug("Purging flows on device {}", deviceId);
Matteo Scandolob6981dc2021-12-02 16:31:44 -0800683 flowRuleService.purgeFlowRules(deviceId);
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700684
685 // removing the status from the cpStatus map
Matteo Scandolo2542e5d2021-12-01 16:53:41 -0800686 if (log.isTraceEnabled()) {
687 log.trace("Clearing cp status from device {}", deviceId);
688 }
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700689 try {
690 cpStatusWriteLock.lock();
691 Iterator<Map.Entry<ServiceKey, OltPortStatus>> iter = cpStatus.entrySet().iterator();
692 while (iter.hasNext()) {
693 Map.Entry<ServiceKey, OltPortStatus> entry = iter.next();
694 if (entry.getKey().getPort().connectPoint().deviceId().equals(deviceId)) {
695 cpStatus.remove(entry.getKey());
696 }
697 }
698 } finally {
699 cpStatusWriteLock.unlock();
700 }
701
702 // removing subscribers from the provisioned map
Matteo Scandolo2542e5d2021-12-01 16:53:41 -0800703 if (log.isTraceEnabled()) {
704 log.trace("Clearing provisioned subscribers from device {}", deviceId);
705 }
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700706 try {
707 provisionedSubscribersWriteLock.lock();
708 Iterator<Map.Entry<ServiceKey, Boolean>> iter = provisionedSubscribers.entrySet().iterator();
709 while (iter.hasNext()) {
710 Map.Entry<ServiceKey, Boolean> entry = iter.next();
711 if (entry.getKey().getPort().connectPoint().deviceId().equals(deviceId)) {
712 provisionedSubscribers.remove(entry.getKey());
713 }
714 }
715 } finally {
716 provisionedSubscribersWriteLock.unlock();
717 }
Matteo Scandolo2542e5d2021-12-01 16:53:41 -0800718 log.debug("Done clearing up device flows and subscribers");
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700719 }
720
721 @Override
722 public boolean isSubscriberServiceProvisioned(AccessDevicePort cp) {
723 // if any service is programmed on this port, returns true
724 AtomicBoolean provisioned = new AtomicBoolean(false);
725 try {
726 provisionedSubscribersReadLock.lock();
727 for (Map.Entry<ServiceKey, Boolean> entry : provisionedSubscribers.entrySet()) {
728 if (entry.getKey().getPort().equals(cp) && entry.getValue()) {
729 provisioned.set(true);
730 break;
731 }
732 }
733 } finally {
734 provisionedSubscribersReadLock.unlock();
735 }
736 return provisioned.get();
737 }
738
739 @Override
740 public boolean isSubscriberServiceProvisioned(ServiceKey sk) {
741 try {
742 provisionedSubscribersReadLock.lock();
743 Boolean provisioned = provisionedSubscribers.get(sk);
744 if (provisioned == null || !provisioned) {
745 return false;
746 }
747 } finally {
748 provisionedSubscribersReadLock.unlock();
749 }
750 return true;
751 }
752
753 @Override
754 public void updateProvisionedSubscriberStatus(ServiceKey sk, Boolean status) {
755 try {
756 provisionedSubscribersWriteLock.lock();
757 provisionedSubscribers.put(sk, status);
758 } finally {
759 provisionedSubscribersWriteLock.unlock();
760 }
761 }
762
Matteo Scandolo97449bb2021-12-09 15:33:46 -0800763 protected boolean handleEapolFlow(DiscoveredSubscriber sub, String bandwidthProfile,
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700764 String oltBandwidthProfile, FlowOperation action, VlanId vlanId) {
765
766 // create a subscriberKey for the EAPOL flow
767 ServiceKey sk = new ServiceKey(new AccessDevicePort(sub.port), defaultEapolUniTag);
768
769 // NOTE we only need to keep track of the default EAPOL flow in the
770 // connectpoint status map
771 if (vlanId.id().equals(EAPOL_DEFAULT_VLAN)) {
772 OltFlowsStatus status = action == FlowOperation.ADD ?
773 OltFlowsStatus.PENDING_ADD : OltFlowsStatus.PENDING_REMOVE;
774 updateConnectPointStatus(sk, status, OltFlowsStatus.NONE, OltFlowsStatus.NONE);
775
776 }
777
778 DefaultFilteringObjective.Builder filterBuilder = DefaultFilteringObjective.builder();
779 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
780
781 int techProfileId = getDefaultTechProfileId(sub.port);
782 MeterId meterId = oltMeterService.getMeterIdForBandwidthProfile(sub.device.id(), bandwidthProfile);
783
784 // in the delete case the meter should still be there as we remove
785 // the meters only if no flows are pointing to them
786 if (meterId == null) {
787 log.debug("MeterId is null for BandwidthProfile {} on device {}",
788 bandwidthProfile, sub.device.id());
789 return false;
790 }
791
792 MeterId oltMeterId = oltMeterService.getMeterIdForBandwidthProfile(sub.device.id(), oltBandwidthProfile);
793 if (oltMeterId == null) {
794 log.debug("MeterId is null for OltBandwidthProfile {} on device {}",
795 oltBandwidthProfile, sub.device.id());
796 return false;
797 }
798
799 log.info("{} EAPOL flow for {} with vlanId {} and BandwidthProfile {} (meterId {})",
800 flowOpToString(action), portWithName(sub.port), vlanId, bandwidthProfile, meterId);
801
802 FilteringObjective.Builder eapolAction;
803
804 if (action == FlowOperation.ADD) {
805 eapolAction = filterBuilder.permit();
806 } else if (action == FlowOperation.REMOVE) {
807 eapolAction = filterBuilder.deny();
808 } else {
809 log.error("Operation {} not supported", action);
810 return false;
811 }
812
813 FilteringObjective.Builder baseEapol = eapolAction
814 .withKey(Criteria.matchInPort(sub.port.number()))
815 .addCondition(Criteria.matchEthType(EthType.EtherType.EAPOL.ethType()));
816
817 // NOTE we only need to add the treatment to install the flow,
818 // we can remove it based in the match
819 FilteringObjective.Builder eapol;
820
821 TrafficTreatment treatment = treatmentBuilder
822 .meter(meterId)
823 .writeMetadata(createTechProfValueForWriteMetadata(
824 vlanId,
825 techProfileId, oltMeterId), 0)
826 .setOutput(PortNumber.CONTROLLER)
827 .pushVlan()
828 .setVlanId(vlanId)
829 .build();
830 eapol = baseEapol
831 .withMeta(treatment);
832
833 FilteringObjective eapolObjective = eapol
834 .fromApp(appId)
835 .withPriority(MAX_PRIORITY)
836 .add(new ObjectiveContext() {
837 @Override
838 public void onSuccess(Objective objective) {
839 log.info("EAPOL flow objective {} for {}",
840 completeFlowOpToString(action), portWithName(sub.port));
841 if (log.isTraceEnabled()) {
842 log.trace("EAPOL flow details for port {}: {}", portWithName(sub.port), objective);
843 }
844 }
845
846 @Override
847 public void onError(Objective objective, ObjectiveError error) {
848 log.error("Cannot {} eapol flow for {} : {}", action,
849 portWithName(sub.port), error);
850
851 if (vlanId.id().equals(EAPOL_DEFAULT_VLAN)) {
852 updateConnectPointStatus(sk,
853 OltFlowsStatus.ERROR, null, null);
854 }
855 }
856 });
857
858 flowObjectiveService.filter(sub.device.id(), eapolObjective);
859
860 log.info("{} EAPOL filter for {}", completeFlowOpToString(action), portWithName(sub.port));
861 return true;
862 }
863
864 // FIXME it's confusing that si is not necessarily inside the DiscoveredSubscriber
Matteo Scandolo97449bb2021-12-09 15:33:46 -0800865 protected boolean handleSubscriberEapolFlows(DiscoveredSubscriber sub, FlowOperation action,
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700866 SubscriberAndDeviceInformation si) {
867 if (!enableEapol) {
868 return true;
869 }
870 // TODO verify we need an EAPOL flow for EACH service
871 AtomicBoolean success = new AtomicBoolean(true);
872 si.uniTagList().forEach(u -> {
873 // we assume that if subscriber flows are installed, tagged EAPOL is installed as well
874 boolean hasFlows = hasSubscriberFlows(sub.port, u);
875
876 // if the subscriber flows are present the EAPOL flow is present thus we don't need to install it,
877 // if the subscriber does not have flows the EAPOL flow is not present thus we don't need to remove it
878 if (action == FlowOperation.ADD && hasFlows ||
879 action == FlowOperation.REMOVE && !hasFlows) {
880 log.debug("Not {} EAPOL on {}({}) as subscriber flow status is {}", flowOpToString(action),
881 portWithName(sub.port), u.getServiceName(), hasFlows);
882 return;
883 }
884 log.info("{} EAPOL flows for subscriber {} on {} and service {}",
885 flowOpToString(action), si.id(), portWithName(sub.port), u.getServiceName());
886 if (!handleEapolFlow(sub, u.getUpstreamBandwidthProfile(),
887 u.getUpstreamOltBandwidthProfile(),
888 action, u.getPonCTag())) {
889 //
890 log.error("Failed to {} EAPOL with suscriber tags", action);
891 //TODO this sets it for all services, maybe some services succeeded.
892 success.set(false);
893 }
894 });
895 return success.get();
896 }
897
Matteo Scandolo97449bb2021-12-09 15:33:46 -0800898 protected void handleSubscriberIgmpFlows(DiscoveredSubscriber sub, FlowOperation action) {
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700899 sub.subscriberAndDeviceInformation.uniTagList().forEach(uti -> {
900 if (uti.getIsIgmpRequired()) {
901 DeviceId deviceId = sub.device.id();
902 // if we reached here a meter already exists
903 MeterId meterId = oltMeterService
904 .getMeterIdForBandwidthProfile(deviceId, uti.getUpstreamBandwidthProfile());
905 MeterId oltMeterId = oltMeterService
906 .getMeterIdForBandwidthProfile(deviceId, uti.getUpstreamOltBandwidthProfile());
907
908 processIgmpFilteringObjectives(deviceId, sub.port,
909 action, FlowDirection.UPSTREAM, meterId, oltMeterId, uti.getTechnologyProfileId(),
910 uti.getPonCTag(), uti.getUniTagMatch(), uti.getUsPonCTagPriority());
911 }
912 });
913 }
914
915 private boolean checkSadisRunning() {
916 if (bpService == null) {
917 log.warn("Sadis is not running");
918 return false;
919 }
920 return true;
921 }
922
923 private int getDefaultTechProfileId(Port port) {
924 if (!checkSadisRunning()) {
925 return defaultTechProfileId;
926 }
927 if (port != null) {
928 SubscriberAndDeviceInformation info = subsService.get(getPortName(port));
929 if (info != null && info.uniTagList().size() == 1) {
930 return info.uniTagList().get(0).getTechnologyProfileId();
931 }
932 }
933 return defaultTechProfileId;
934 }
935
936 protected Long createTechProfValueForWriteMetadata(VlanId cVlan, int techProfileId, MeterId upstreamOltMeterId) {
937 Long writeMetadata;
938
939 if (cVlan == null || VlanId.NONE.equals(cVlan)) {
940 writeMetadata = (long) techProfileId << 32;
941 } else {
942 writeMetadata = ((long) (cVlan.id()) << 48 | (long) techProfileId << 32);
943 }
944 if (upstreamOltMeterId == null) {
945 return writeMetadata;
946 } else {
947 return writeMetadata | upstreamOltMeterId.id();
948 }
949 }
950
951 private void processLldpFilteringObjective(DeviceId deviceId, Port port, FlowOperation action) {
952 DefaultFilteringObjective.Builder builder = DefaultFilteringObjective.builder();
953
954 FilteringObjective lldp = (action == FlowOperation.ADD ? builder.permit() : builder.deny())
955 .withKey(Criteria.matchInPort(port.number()))
956 .addCondition(Criteria.matchEthType(EthType.EtherType.LLDP.ethType()))
957 .withMeta(DefaultTrafficTreatment.builder()
958 .setOutput(PortNumber.CONTROLLER).build())
959 .fromApp(appId)
960 .withPriority(MAX_PRIORITY)
961 .add(new ObjectiveContext() {
962 @Override
963 public void onSuccess(Objective objective) {
964 log.info("{} LLDP filter for {}.", completeFlowOpToString(action), portWithName(port));
965 }
966
967 @Override
968 public void onError(Objective objective, ObjectiveError error) {
969 log.error("Falied to {} LLDP filter on {} because {}", action, portWithName(port),
970 error);
971 }
972 });
973
974 flowObjectiveService.filter(deviceId, lldp);
975 }
976
977 protected void handleSubscriberDhcpFlows(DeviceId deviceId, Port port,
978 FlowOperation action,
979 SubscriberAndDeviceInformation si) {
980 si.uniTagList().forEach(uti -> {
981
982 if (!uti.getIsDhcpRequired()) {
983 return;
984 }
985
986 // if it's an ADD skip if flows are there,
987 // if it's a DELETE skip if flows are not there
988 boolean hasFlows = hasDhcpFlows(port, uti);
989 if (action == FlowOperation.ADD && hasFlows ||
990 action == FlowOperation.REMOVE && !hasFlows) {
991 log.debug("Not dealing with DHCP {} on {} as DHCP flow status is {}", action,
992 uti.getServiceName(), hasFlows);
993 return;
994 }
995
996 log.info("{} DHCP flows for subscriber on {} and service {}",
997 flowOpToString(action), portWithName(port), uti.getServiceName());
998
999 // if we reached here a meter already exists
1000 MeterId meterId = oltMeterService
1001 .getMeterIdForBandwidthProfile(deviceId, uti.getUpstreamBandwidthProfile());
1002 MeterId oltMeterId = oltMeterService
1003 .getMeterIdForBandwidthProfile(deviceId, uti.getUpstreamOltBandwidthProfile());
1004
1005 if (enableDhcpV4) {
1006 processDhcpFilteringObjectives(deviceId, port, action, FlowDirection.UPSTREAM, 68, 67,
1007 EthType.EtherType.IPV4.ethType(), IPv4.PROTOCOL_UDP, meterId, oltMeterId,
1008 uti);
1009 }
1010 if (enableDhcpV6) {
1011 log.error("DHCP V6 not supported for subscribers");
1012 }
1013 });
1014 }
1015
1016 // FIXME return boolean, if this fails we need to retry
1017 protected void handleSubscriberDataFlows(Device device, Port port,
1018 FlowOperation action,
1019 SubscriberAndDeviceInformation si, String multicastServiceName) {
1020
1021 Optional<Port> nniPort = oltDeviceService.getNniPort(device);
Matteo Scandolo97449bb2021-12-09 15:33:46 -08001022 if (nniPort == null || nniPort.isEmpty()) {
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001023 log.error("Cannot configure DP flows as upstream port is not configured for subscriber {} on {}",
1024 si.id(), portWithName(port));
1025 return;
1026 }
1027 si.uniTagList().forEach(uti -> {
1028
1029 boolean hasFlows = hasSubscriberFlows(port, uti);
1030 if (action == FlowOperation.ADD && hasFlows ||
1031 action == FlowOperation.REMOVE && !hasFlows) {
1032 log.debug("Not dealing with DP flows {} on {} as subscriber flow status is {}", action,
1033 uti.getServiceName(), hasFlows);
1034 return;
1035 }
1036
1037 if (multicastServiceName.equals(uti.getServiceName())) {
1038 log.debug("This is the multicast service ({}) for subscriber {} on {}, " +
1039 "dataplane flows are not needed",
1040 uti.getServiceName(), si.id(), portWithName(port));
1041 return;
1042 }
1043
1044 log.info("{} Data plane flows for subscriber {} on {} and service {}",
1045 flowOpToString(action), si.id(), portWithName(port), uti.getServiceName());
Matteo Scandolo80f5e972021-12-02 14:59:15 -08001046 ServiceKey sk = new ServiceKey(new AccessDevicePort(port), uti);
1047 OltFlowsStatus status = action.equals(FlowOperation.ADD) ?
1048 OltFlowsStatus.PENDING_ADD : OltFlowsStatus.PENDING_REMOVE;
1049 updateConnectPointStatus(sk, null, status, null);
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001050
1051 // upstream flows
1052 MeterId usMeterId = oltMeterService
1053 .getMeterIdForBandwidthProfile(device.id(), uti.getUpstreamBandwidthProfile());
1054 MeterId oltUsMeterId = oltMeterService
1055 .getMeterIdForBandwidthProfile(device.id(), uti.getUpstreamOltBandwidthProfile());
1056 processUpstreamDataFilteringObjects(device.id(), port, nniPort.get(), action, usMeterId,
1057 oltUsMeterId, uti);
1058
1059 // downstream flows
1060 MeterId dsMeterId = oltMeterService
1061 .getMeterIdForBandwidthProfile(device.id(), uti.getDownstreamBandwidthProfile());
1062 MeterId oltDsMeterId = oltMeterService
1063 .getMeterIdForBandwidthProfile(device.id(), uti.getDownstreamOltBandwidthProfile());
1064 processDownstreamDataFilteringObjects(device.id(), port, nniPort.get(), action, dsMeterId,
1065 oltDsMeterId, uti, getMacAddress(device.id(), port, uti));
1066 });
1067 }
1068
1069 private void processDhcpFilteringObjectives(DeviceId deviceId, Port port,
1070 FlowOperation action, FlowDirection direction,
1071 int udpSrc, int udpDst, EthType ethType, byte protocol,
1072 MeterId meterId, MeterId oltMeterId, UniTagInformation uti) {
1073 ServiceKey sk = new ServiceKey(new AccessDevicePort(port), uti);
1074 log.debug("{} DHCP filtering objectives on {}", flowOpToString(action), sk);
1075
1076
1077 OltFlowsStatus status = action.equals(FlowOperation.ADD) ?
1078 OltFlowsStatus.PENDING_ADD : OltFlowsStatus.PENDING_REMOVE;
1079 updateConnectPointStatus(sk, null, null, status);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001080
1081 DefaultFilteringObjective.Builder builder = DefaultFilteringObjective.builder();
1082 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
1083
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001084 if (meterId != null) {
1085 treatmentBuilder.meter(meterId);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001086 }
1087
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001088 if (uti.getTechnologyProfileId() != NONE_TP_ID) {
1089 treatmentBuilder.writeMetadata(
1090 createTechProfValueForWriteMetadata(uti.getUniTagMatch(),
1091 uti.getTechnologyProfileId(), oltMeterId), 0);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001092 }
1093
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001094 FilteringObjective.Builder dhcpBuilder = (action == FlowOperation.ADD ? builder.permit() : builder.deny())
Tunahan Sezenf0843b92021-04-30 07:13:16 +00001095 .withKey(Criteria.matchInPort(port.number()))
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001096 .addCondition(Criteria.matchEthType(ethType))
1097 .addCondition(Criteria.matchIPProtocol(protocol))
1098 .addCondition(Criteria.matchUdpSrc(TpPort.tpPort(udpSrc)))
1099 .addCondition(Criteria.matchUdpDst(TpPort.tpPort(udpDst)))
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001100 .fromApp(appId)
1101 .withPriority(MAX_PRIORITY);
1102
Andrea Campanella0e34f562020-06-11 10:47:10 +02001103 //VLAN changes and PCP matching need to happen only in the upstream directions
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001104 if (direction == FlowDirection.UPSTREAM) {
1105 treatmentBuilder.setVlanId(uti.getPonCTag());
1106 if (!VlanId.vlanId(VlanId.NO_VID).equals(uti.getUniTagMatch())) {
1107 dhcpBuilder.addCondition(Criteria.matchVlanId(uti.getUniTagMatch()));
Andrea Campanella0e34f562020-06-11 10:47:10 +02001108 }
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001109 if (uti.getUsPonCTagPriority() != -1) {
1110 treatmentBuilder.setVlanPcp((byte) uti.getUsPonCTagPriority());
Andrea Campanella0e34f562020-06-11 10:47:10 +02001111 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001112 }
1113
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001114 dhcpBuilder.withMeta(treatmentBuilder
1115 .setOutput(PortNumber.CONTROLLER).build());
Andrea Campanella0e34f562020-06-11 10:47:10 +02001116
1117
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001118 FilteringObjective dhcpUpstream = dhcpBuilder.add(new ObjectiveContext() {
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001119 @Override
1120 public void onSuccess(Objective objective) {
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001121 log.info("{} DHCP {} filter for {}.",
1122 completeFlowOpToString(action), (ethType.equals(EthType.EtherType.IPV4.ethType())) ? V4 : V6,
1123 portWithName(port));
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001124 }
1125
1126 @Override
1127 public void onError(Objective objective, ObjectiveError error) {
Tunahan Sezenf0843b92021-04-30 07:13:16 +00001128 log.error("DHCP {} filter for {} failed {} because {}",
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001129 (ethType.equals(EthType.EtherType.IPV4.ethType())) ? V4 : V6,
1130 portWithName(port),
1131 action,
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001132 error);
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001133 updateConnectPointStatus(sk, null, null, OltFlowsStatus.ERROR);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001134 }
1135 });
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001136 flowObjectiveService.filter(deviceId, dhcpUpstream);
1137 }
1138
1139 private void processIgmpFilteringObjectives(DeviceId deviceId, Port port,
1140 FlowOperation action, FlowDirection direction,
1141 MeterId meterId, MeterId oltMeterId, int techProfileId,
1142 VlanId cTag, VlanId unitagMatch, int vlanPcp) {
1143
1144 DefaultFilteringObjective.Builder filterBuilder = DefaultFilteringObjective.builder();
1145 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
1146 if (direction == FlowDirection.UPSTREAM) {
1147
1148 if (techProfileId != NONE_TP_ID) {
1149 treatmentBuilder.writeMetadata(createTechProfValueForWriteMetadata(null,
1150 techProfileId, oltMeterId), 0);
1151 }
1152
1153
1154 if (meterId != null) {
1155 treatmentBuilder.meter(meterId);
1156 }
1157
1158 if (!VlanId.vlanId(VlanId.NO_VID).equals(unitagMatch)) {
1159 filterBuilder.addCondition(Criteria.matchVlanId(unitagMatch));
1160 }
1161
1162 if (!VlanId.vlanId(VlanId.NO_VID).equals(cTag)) {
1163 treatmentBuilder.setVlanId(cTag);
1164 }
1165
1166 if (vlanPcp != -1) {
1167 treatmentBuilder.setVlanPcp((byte) vlanPcp);
1168 }
1169 }
1170
1171 filterBuilder = (action == FlowOperation.ADD) ? filterBuilder.permit() : filterBuilder.deny();
1172
1173 FilteringObjective igmp = filterBuilder
1174 .withKey(Criteria.matchInPort(port.number()))
1175 .addCondition(Criteria.matchEthType(EthType.EtherType.IPV4.ethType()))
1176 .addCondition(Criteria.matchIPProtocol(IPv4.PROTOCOL_IGMP))
1177 .withMeta(treatmentBuilder
1178 .setOutput(PortNumber.CONTROLLER).build())
1179 .fromApp(appId)
1180 .withPriority(MAX_PRIORITY)
1181 .add(new ObjectiveContext() {
1182 @Override
1183 public void onSuccess(Objective objective) {
1184 log.info("Igmp filter for {} {}.", portWithName(port), action);
1185 }
1186
1187 @Override
1188 public void onError(Objective objective, ObjectiveError error) {
1189 log.error("Igmp filter for {} failed {} because {}.", portWithName(port), action,
1190 error);
1191 }
1192 });
1193
1194 flowObjectiveService.filter(deviceId, igmp);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001195
1196 }
1197
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001198 private void processPPPoEDFilteringObjectives(DeviceId deviceId, Port port,
1199 FlowOperation action, FlowDirection direction,
1200 MeterId meterId, MeterId oltMeterId, int techProfileId,
1201 VlanId cTag, VlanId unitagMatch, Byte vlanPcp) {
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001202
1203 DefaultFilteringObjective.Builder builder = DefaultFilteringObjective.builder();
1204 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001205
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001206 if (meterId != null) {
1207 treatmentBuilder.meter(meterId);
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001208 }
1209
1210 if (techProfileId != NONE_TP_ID) {
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001211 treatmentBuilder.writeMetadata(createTechProfValueForWriteMetadata(cTag, techProfileId, oltMeterId), 0);
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001212 }
1213
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001214 DefaultFilteringObjective.Builder pppoedBuilder = ((action == FlowOperation.ADD)
1215 ? builder.permit() : builder.deny())
Tunahan Sezenf0843b92021-04-30 07:13:16 +00001216 .withKey(Criteria.matchInPort(port.number()))
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001217 .addCondition(Criteria.matchEthType(EthType.EtherType.PPPoED.ethType()))
1218 .fromApp(appId)
1219 .withPriority(10000);
1220
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001221 if (direction == FlowDirection.UPSTREAM) {
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001222 treatmentBuilder.setVlanId(cTag);
1223 if (!VlanId.vlanId(VlanId.NO_VID).equals(unitagMatch)) {
1224 pppoedBuilder.addCondition(Criteria.matchVlanId(unitagMatch));
1225 }
1226 if (vlanPcp != null) {
1227 treatmentBuilder.setVlanPcp(vlanPcp);
1228 }
1229 }
1230 pppoedBuilder = pppoedBuilder.withMeta(treatmentBuilder.setOutput(PortNumber.CONTROLLER).build());
1231
1232 FilteringObjective pppoed = pppoedBuilder
1233 .add(new ObjectiveContext() {
1234 @Override
1235 public void onSuccess(Objective objective) {
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001236 log.info("PPPoED filter for {} {}.", portWithName(port), action);
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001237 }
1238
1239 @Override
1240 public void onError(Objective objective, ObjectiveError error) {
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001241 log.info("PPPoED filter for {} failed {} because {}", portWithName(port),
1242 action, error);
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001243 }
1244 });
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001245 flowObjectiveService.filter(deviceId, pppoed);
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001246 }
1247
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001248 private void processUpstreamDataFilteringObjects(DeviceId deviceId, Port port, Port nniPort,
1249 FlowOperation action,
1250 MeterId upstreamMeterId,
1251 MeterId upstreamOltMeterId,
1252 UniTagInformation uti) {
1253 ServiceKey sk = new ServiceKey(new AccessDevicePort(port), uti);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001254 TrafficSelector selector = DefaultTrafficSelector.builder()
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001255 .matchInPort(port.number())
1256 .matchVlanId(uti.getUniTagMatch())
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001257 .build();
1258
Andrea Campanella327c5722020-01-30 11:34:13 +01001259 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
1260 //if the subscriberVlan (cTag) is different than ANY it needs to set.
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001261 if (uti.getPonCTag().toShort() != VlanId.ANY_VALUE) {
Andrea Campanella327c5722020-01-30 11:34:13 +01001262 treatmentBuilder.pushVlan()
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001263 .setVlanId(uti.getPonCTag());
Andrea Campanella327c5722020-01-30 11:34:13 +01001264 }
Maria Carmela Cascino067ee4d2021-11-02 13:14:43 +01001265 if (uti.getPonSTag().toShort() == VlanId.ANY_VALUE) {
1266 treatmentBuilder.popVlan();
1267 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001268
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001269 if (uti.getUsPonCTagPriority() != -1) {
1270 treatmentBuilder.setVlanPcp((byte) uti.getUsPonCTagPriority());
Maria Carmela Cascino067ee4d2021-11-02 13:14:43 +01001271
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001272 }
1273
1274 treatmentBuilder.pushVlan()
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001275 .setVlanId(uti.getPonSTag());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001276
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001277 if (uti.getUsPonSTagPriority() != -1) {
1278 treatmentBuilder.setVlanPcp((byte) uti.getUsPonSTagPriority());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001279 }
1280
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001281 treatmentBuilder.setOutput(nniPort.number())
1282 .writeMetadata(createMetadata(uti.getPonCTag(),
1283 uti.getTechnologyProfileId(), nniPort.number()), 0L);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001284
yasin saplib4b8ee12021-06-13 18:25:20 +00001285 DefaultAnnotations.Builder annotationBuilder = DefaultAnnotations.builder();
1286
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001287 if (upstreamMeterId != null) {
1288 treatmentBuilder.meter(upstreamMeterId);
yasin saplib4b8ee12021-06-13 18:25:20 +00001289 annotationBuilder.set(UPSTREAM_ONU, upstreamMeterId.toString());
1290 }
1291 if (upstreamOltMeterId != null) {
1292 treatmentBuilder.meter(upstreamOltMeterId);
1293 annotationBuilder.set(UPSTREAM_OLT, upstreamOltMeterId.toString());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001294 }
1295
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001296 DefaultForwardingObjective.Builder flowBuilder = createForwardingObjectiveBuilder(selector,
1297 treatmentBuilder.build(), MIN_PRIORITY,
yasin saplib4b8ee12021-06-13 18:25:20 +00001298 annotationBuilder.build());
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001299
1300 ObjectiveContext context = new ObjectiveContext() {
1301 @Override
1302 public void onSuccess(Objective objective) {
1303 log.info("{} Upstream Data plane filter for {}.",
1304 completeFlowOpToString(action), sk);
1305 }
1306
1307 @Override
1308 public void onError(Objective objective, ObjectiveError error) {
1309 log.error("Upstream Data plane filter for {} failed {} because {}.",
1310 sk, action, error);
1311 updateConnectPointStatus(sk, null, OltFlowsStatus.ERROR, null);
1312 }
1313 };
1314
1315 ForwardingObjective flow = null;
1316 if (action == FlowOperation.ADD) {
1317 flow = flowBuilder.add(context);
1318 } else if (action == FlowOperation.REMOVE) {
1319 flow = flowBuilder.remove(context);
1320 } else {
1321 log.error("Flow action not supported: {}", action);
1322 }
1323
1324 if (flow != null) {
1325 flowObjectiveService.forward(deviceId, flow);
1326 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001327 }
1328
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001329 private void processDownstreamDataFilteringObjects(DeviceId deviceId, Port port, Port nniPort,
1330 FlowOperation action,
1331 MeterId downstreamMeterId,
1332 MeterId downstreamOltMeterId,
1333 UniTagInformation uti,
1334 MacAddress macAddress) {
1335 ServiceKey sk = new ServiceKey(new AccessDevicePort(port), uti);
Andrea Campanella327c5722020-01-30 11:34:13 +01001336 //subscriberVlan can be any valid Vlan here including ANY to make sure the packet is tagged
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001337 TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder()
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001338 .matchVlanId(uti.getPonSTag())
1339 .matchInPort(nniPort.number())
1340 .matchInnerVlanId(uti.getPonCTag());
Andrea Campanella090e4a02020-02-05 13:53:55 +01001341
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001342 if (uti.getPonCTag().toShort() != VlanId.ANY_VALUE) {
1343 selectorBuilder.matchMetadata(uti.getPonCTag().toShort());
Andrea Campanella090e4a02020-02-05 13:53:55 +01001344 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001345
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001346 if (uti.getDsPonCTagPriority() != -1) {
1347 selectorBuilder.matchVlanPcp((byte) uti.getDsPonCTagPriority());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001348 }
1349
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001350 if (macAddress != null) {
1351 selectorBuilder.matchEthDst(macAddress);
1352 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001353
1354 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder()
1355 .popVlan()
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001356 .setOutput(port.number());
Andrea Campanella327c5722020-01-30 11:34:13 +01001357
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001358 treatmentBuilder.writeMetadata(createMetadata(uti.getPonCTag(),
1359 uti.getTechnologyProfileId(),
1360 port.number()), 0);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001361
Andrea Campanella981e86c2021-03-12 11:35:33 +01001362 // Upstream pbit is used to remark inner vlan pbit.
1363 // Upstream is used to avoid trusting the BNG to send the packet with correct pbit.
1364 // this is done because ds mode 0 is used because ds mode 3 or 6 that allow for
1365 // all pbit acceptance are not widely supported by vendors even though present in
1366 // the OMCI spec.
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001367 if (uti.getUsPonCTagPriority() != -1) {
1368 treatmentBuilder.setVlanPcp((byte) uti.getUsPonCTagPriority());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001369 }
1370
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001371 if (!VlanId.NONE.equals(uti.getUniTagMatch()) &&
1372 uti.getPonCTag().toShort() != VlanId.ANY_VALUE) {
1373 treatmentBuilder.setVlanId(uti.getUniTagMatch());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001374 }
1375
yasin saplib4b8ee12021-06-13 18:25:20 +00001376 DefaultAnnotations.Builder annotationBuilder = DefaultAnnotations.builder();
1377
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001378 if (downstreamMeterId != null) {
1379 treatmentBuilder.meter(downstreamMeterId);
yasin saplib4b8ee12021-06-13 18:25:20 +00001380 annotationBuilder.set(DOWNSTREAM_ONU, downstreamMeterId.toString());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001381 }
1382
yasin saplib4b8ee12021-06-13 18:25:20 +00001383 if (downstreamOltMeterId != null) {
1384 treatmentBuilder.meter(downstreamOltMeterId);
1385 annotationBuilder.set(DOWNSTREAM_OLT, downstreamOltMeterId.toString());
1386 }
1387
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001388 DefaultForwardingObjective.Builder flowBuilder = createForwardingObjectiveBuilder(selectorBuilder.build(),
1389 treatmentBuilder.build(), MIN_PRIORITY, annotationBuilder.build());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001390
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001391 ObjectiveContext context = new ObjectiveContext() {
1392 @Override
1393 public void onSuccess(Objective objective) {
1394 log.info("{} Downstream Data plane filter for {}.",
1395 completeFlowOpToString(action), sk);
1396 }
1397
1398 @Override
1399 public void onError(Objective objective, ObjectiveError error) {
1400 log.info("Downstream Data plane filter for {} failed {} because {}.",
1401 sk, action, error);
1402 updateConnectPointStatus(sk, null, OltFlowsStatus.ERROR, null);
1403 }
1404 };
1405
1406 ForwardingObjective flow = null;
1407 if (action == FlowOperation.ADD) {
1408 flow = flowBuilder.add(context);
1409 } else if (action == FlowOperation.REMOVE) {
1410 flow = flowBuilder.remove(context);
1411 } else {
1412 log.error("Flow action not supported: {}", action);
1413 }
1414
1415 if (flow != null) {
1416 if (log.isTraceEnabled()) {
1417 log.trace("Forwarding rule {}", flow);
1418 }
1419 flowObjectiveService.forward(deviceId, flow);
1420 }
Andrea Campanella600d2e22020-06-22 11:00:31 +02001421 }
1422
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001423 private DefaultForwardingObjective.Builder createForwardingObjectiveBuilder(TrafficSelector selector,
1424 TrafficTreatment treatment,
yasin saplib4b8ee12021-06-13 18:25:20 +00001425 Integer priority,
1426 Annotations annotations) {
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001427 return DefaultForwardingObjective.builder()
1428 .withFlag(ForwardingObjective.Flag.VERSATILE)
1429 .withPriority(priority)
1430 .makePermanent()
1431 .withSelector(selector)
yasin saplib4b8ee12021-06-13 18:25:20 +00001432 .withAnnotations(annotations)
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001433 .fromApp(appId)
1434 .withTreatment(treatment);
1435 }
1436
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001437 private Long createMetadata(VlanId innerVlan, int techProfileId, PortNumber egressPort) {
1438 if (techProfileId == NONE_TP_ID) {
Andrea Campanella7c49b792020-05-11 11:36:53 +02001439 techProfileId = DEFAULT_TP_ID_DEFAULT;
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001440 }
1441
1442 return ((long) (innerVlan.id()) << 48 | (long) techProfileId << 32) | egressPort.toLong();
1443 }
1444
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001445 private boolean isMacLearningEnabled(SubscriberAndDeviceInformation si) {
1446 AtomicBoolean requiresMacLearning = new AtomicBoolean();
1447 requiresMacLearning.set(false);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001448
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001449 si.uniTagList().forEach(uniTagInfo -> {
1450 if (uniTagInfo.getEnableMacLearning()) {
1451 requiresMacLearning.set(true);
1452 }
1453 });
1454
1455 return requiresMacLearning.get();
1456 }
1457
1458 /**
1459 * Checks whether the subscriber has the MacAddress configured or discovered.
1460 *
1461 * @param deviceId DeviceId for this subscriber
1462 * @param port Port for this subscriber
1463 * @param si SubscriberAndDeviceInformation
1464 * @return boolean
1465 */
1466 protected boolean isMacAddressAvailable(DeviceId deviceId, Port port, SubscriberAndDeviceInformation si) {
1467 AtomicBoolean isConfigured = new AtomicBoolean();
1468 isConfigured.set(true);
1469
1470 si.uniTagList().forEach(uniTagInfo -> {
1471 boolean isMacLearningEnabled = uniTagInfo.getEnableMacLearning();
1472 boolean configureMac = isMacAddressValid(uniTagInfo);
1473 boolean discoveredMac = false;
1474 Optional<Host> optHost = hostService.getConnectedHosts(new ConnectPoint(deviceId, port.number()))
1475 .stream().filter(host -> host.vlan().equals(uniTagInfo.getPonCTag())).findFirst();
1476 if (optHost.isPresent() && optHost.get().mac() != null) {
1477 discoveredMac = true;
1478 }
1479 if (isMacLearningEnabled && !configureMac && !discoveredMac) {
1480 log.debug("Awaiting for macAddress on {} for service {}",
1481 portWithName(port), uniTagInfo.getServiceName());
1482 isConfigured.set(false);
1483 }
1484 });
1485
1486 return isConfigured.get();
1487 }
1488
1489 protected MacAddress getMacAddress(DeviceId deviceId, Port port, UniTagInformation uniTagInfo) {
1490 boolean configuredMac = isMacAddressValid(uniTagInfo);
1491 if (configuredMac) {
1492 return MacAddress.valueOf(uniTagInfo.getConfiguredMacAddress());
1493 } else if (uniTagInfo.getEnableMacLearning()) {
1494 Optional<Host> optHost = hostService.getConnectedHosts(new ConnectPoint(deviceId, port.number()))
1495 .stream().filter(host -> host.vlan().equals(uniTagInfo.getPonCTag())).findFirst();
1496 if (optHost.isPresent() && optHost.get().mac() != null) {
1497 return optHost.get().mac();
1498 }
1499 }
1500 return null;
1501 }
1502
1503 private boolean isMacAddressValid(UniTagInformation tagInformation) {
1504 return tagInformation.getConfiguredMacAddress() != null &&
1505 !tagInformation.getConfiguredMacAddress().trim().equals("") &&
1506 !MacAddress.NONE.equals(MacAddress.valueOf(tagInformation.getConfiguredMacAddress()));
1507 }
1508
1509 protected void updateConnectPointStatus(ServiceKey key, OltFlowsStatus eapolStatus,
1510 OltFlowsStatus subscriberFlowsStatus, OltFlowsStatus dhcpStatus) {
Matteo Scandolo2542e5d2021-12-01 16:53:41 -08001511 if (log.isTraceEnabled()) {
1512 log.trace("Updating cpStatus {} with values: eapolFlow={}, subscriberFlows={}, dhcpFlow={}",
1513 key, eapolStatus, subscriberFlowsStatus, dhcpStatus);
1514 }
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001515 try {
1516 cpStatusWriteLock.lock();
1517 OltPortStatus status = cpStatus.get(key);
1518
Matteo Scandolo2542e5d2021-12-01 16:53:41 -08001519
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001520 if (status == null) {
Matteo Scandolo2542e5d2021-12-01 16:53:41 -08001521 // if we don't have status for the connectPoint
1522 // and we're only updating status to PENDING_REMOVE or ERROR
1523 // do not create it. This is because this case will only happen when a device is removed
1524 // and it's status cleaned
1525 List<OltFlowsStatus> statusesToIgnore = new ArrayList<>();
1526 statusesToIgnore.add(OltFlowsStatus.PENDING_REMOVE);
1527 statusesToIgnore.add(OltFlowsStatus.ERROR);
1528
1529 if (
1530 (statusesToIgnore.contains(subscriberFlowsStatus) && dhcpStatus == null) ||
1531 (subscriberFlowsStatus == null && statusesToIgnore.contains(dhcpStatus))
1532 ) {
1533 if (log.isTraceEnabled()) {
1534 log.trace("Ignoring cpStatus update as status is meaningless");
1535 }
1536 return;
1537 }
1538
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001539 status = new OltPortStatus(
1540 eapolStatus != null ? eapolStatus : OltFlowsStatus.NONE,
1541 subscriberFlowsStatus != null ? subscriberFlowsStatus : OltFlowsStatus.NONE,
1542 dhcpStatus != null ? dhcpStatus : OltFlowsStatus.NONE
1543 );
1544 } else {
1545 if (eapolStatus != null) {
1546 status.defaultEapolStatus = eapolStatus;
1547 }
1548 if (subscriberFlowsStatus != null) {
1549 status.subscriberFlowsStatus = subscriberFlowsStatus;
1550 }
1551 if (dhcpStatus != null) {
1552 status.dhcpStatus = dhcpStatus;
1553 }
1554 }
1555
1556 cpStatus.put(key, status);
1557 } finally {
1558 cpStatusWriteLock.unlock();
1559 }
1560 }
1561
1562 protected class InternalFlowListener implements FlowRuleListener {
1563 @Override
1564 public void event(FlowRuleEvent event) {
1565 if (appId.id() != (event.subject().appId())) {
1566 return;
1567 }
1568
1569 if (!oltDeviceService.isLocalLeader(event.subject().deviceId())) {
1570 if (log.isTraceEnabled()) {
1571 log.trace("ignoring flow event {} " +
1572 "as not leader for {}", event, event.subject().deviceId());
1573 }
1574 return;
1575 }
1576
1577 switch (event.type()) {
1578 case RULE_ADDED:
1579 case RULE_REMOVED:
1580 Port port = getCpFromFlowRule(event.subject());
1581 if (port == null) {
1582 log.error("Can't find port in flow {}", event.subject());
1583 return;
1584 }
1585 if (log.isTraceEnabled()) {
1586 log.trace("flow event {} on cp {}: {}", event.type(),
1587 portWithName(port), event.subject());
1588 }
1589 updateCpStatus(event.type(), port, event.subject());
1590 return;
1591 case RULE_ADD_REQUESTED:
1592 case RULE_REMOVE_REQUESTED:
1593 // NOTE that PENDING_ADD/REMOVE is set when we create the flowObjective
1594 return;
1595 default:
1596 return;
1597 }
1598 }
1599
1600 protected void updateCpStatus(FlowRuleEvent.Type type, Port port, FlowRule flowRule) {
1601 OltFlowsStatus status = flowRuleStatusToOltFlowStatus(type);
1602 if (isDefaultEapolFlow(flowRule)) {
1603 ServiceKey sk = new ServiceKey(new AccessDevicePort(port),
1604 defaultEapolUniTag);
1605 if (log.isTraceEnabled()) {
1606 log.trace("update defaultEapolStatus {} on {}", status, sk);
1607 }
1608 updateConnectPointStatus(sk, status, null, null);
1609 } else if (isDhcpFlow(flowRule)) {
1610 ServiceKey sk = getSubscriberKeyFromFlowRule(flowRule);
1611 if (sk == null) {
1612 return;
1613 }
1614 if (log.isTraceEnabled()) {
1615 log.trace("update dhcpStatus {} on {}", status, sk);
1616 }
1617 updateConnectPointStatus(sk, null, null, status);
1618 } else if (isDataFlow(flowRule)) {
1619
1620 if (oltDeviceService.isNniPort(deviceService.getDevice(flowRule.deviceId()),
1621 getCpFromFlowRule(flowRule).number())) {
1622 // the NNI has data-plane for every subscriber, doesn't make sense to track them
1623 return;
1624 }
1625
1626 ServiceKey sk = getSubscriberKeyFromFlowRule(flowRule);
1627 if (sk == null) {
1628 return;
1629 }
1630 if (log.isTraceEnabled()) {
1631 log.trace("update dataplaneStatus {} on {}", status, sk);
1632 }
1633 updateConnectPointStatus(sk, null, status, null);
1634 }
1635 }
1636
1637 private boolean isDefaultEapolFlow(FlowRule flowRule) {
1638 EthTypeCriterion c = (EthTypeCriterion) flowRule.selector().getCriterion(Criterion.Type.ETH_TYPE);
1639 if (c == null) {
1640 return false;
1641 }
1642 if (c.ethType().equals(EthType.EtherType.EAPOL.ethType())) {
1643 AtomicBoolean isDefault = new AtomicBoolean(false);
1644 flowRule.treatment().allInstructions().forEach(instruction -> {
1645 if (instruction.type() == L2MODIFICATION) {
1646 L2ModificationInstruction modificationInstruction = (L2ModificationInstruction) instruction;
1647 if (modificationInstruction.subtype() == L2ModificationInstruction.L2SubType.VLAN_ID) {
1648 L2ModificationInstruction.ModVlanIdInstruction vlanInstruction =
1649 (L2ModificationInstruction.ModVlanIdInstruction) modificationInstruction;
1650 if (vlanInstruction.vlanId().id().equals(EAPOL_DEFAULT_VLAN)) {
1651 isDefault.set(true);
1652 return;
1653 }
1654 }
1655 }
1656 });
1657 return isDefault.get();
1658 }
1659 return false;
1660 }
1661
1662 /**
1663 * Returns true if the flow is a DHCP flow.
1664 * Matches both upstream and downstream flows.
1665 *
1666 * @param flowRule The FlowRule to evaluate
1667 * @return boolean
1668 */
1669 private boolean isDhcpFlow(FlowRule flowRule) {
1670 IPProtocolCriterion ipCriterion = (IPProtocolCriterion) flowRule.selector()
1671 .getCriterion(Criterion.Type.IP_PROTO);
1672 if (ipCriterion == null) {
1673 return false;
1674 }
1675
1676 UdpPortCriterion src = (UdpPortCriterion) flowRule.selector().getCriterion(Criterion.Type.UDP_SRC);
1677
1678 if (src == null) {
1679 return false;
1680 }
1681 return ipCriterion.protocol() == IPv4.PROTOCOL_UDP &&
1682 (src.udpPort().toInt() == 68 || src.udpPort().toInt() == 67);
1683 }
1684
1685 private boolean isDataFlow(FlowRule flowRule) {
1686 // we consider subscriber flows the one that matches on VLAN_VID
1687 // method is valid only because it's the last check after EAPOL and DHCP.
1688 // this matches mcast flows as well, if we want to avoid that we can
1689 // filter out the elements that have groups in the treatment or
1690 // mcastIp in the selector
1691 // IPV4_DST:224.0.0.22/32
1692 // treatment=[immediate=[GROUP:0x1]]
1693
1694 return flowRule.selector().getCriterion(Criterion.Type.VLAN_VID) != null;
1695 }
1696
1697 private Port getCpFromFlowRule(FlowRule flowRule) {
1698 DeviceId deviceId = flowRule.deviceId();
1699 PortCriterion inPort = (PortCriterion) flowRule.selector().getCriterion(Criterion.Type.IN_PORT);
1700 if (inPort != null) {
1701 PortNumber port = inPort.port();
1702 return deviceService.getPort(deviceId, port);
1703 }
1704 return null;
1705 }
1706
1707 private ServiceKey getSubscriberKeyFromFlowRule(FlowRule flowRule) {
1708 Port flowPort = getCpFromFlowRule(flowRule);
1709 SubscriberAndDeviceInformation si = subsService.get(getPortName(flowPort));
1710
1711 Boolean isNni = oltDeviceService.isNniPort(deviceService.getDevice(flowRule.deviceId()), flowPort.number());
1712 if (si == null && !isNni) {
1713 log.error("Subscriber information not found in sadis for port {}", portWithName(flowPort));
1714 return null;
1715 }
1716
1717 if (isNni) {
1718 return new ServiceKey(new AccessDevicePort(flowPort), nniUniTag);
1719 }
1720
1721 Optional<UniTagInformation> found = Optional.empty();
1722 VlanId flowVlan = null;
1723 if (isDhcpFlow(flowRule)) {
1724 // we need to make a special case for DHCP as in the ATT workflow DHCP flows don't match on tags
1725 L2ModificationInstruction.ModVlanIdInstruction instruction =
1726 (L2ModificationInstruction.ModVlanIdInstruction) flowRule.treatment().immediate().get(1);
1727 flowVlan = instruction.vlanId();
1728 } else {
1729 // for now we assume that if it's not DHCP it's dataplane (or at least tagged)
1730 VlanIdCriterion vlanIdCriterion =
1731 (VlanIdCriterion) flowRule.selector().getCriterion(Criterion.Type.VLAN_VID);
1732 if (vlanIdCriterion == null) {
1733 log.warn("cannot match the flow to a subscriber service as it does not carry vlans");
1734 return null;
1735 }
1736 flowVlan = vlanIdCriterion.vlanId();
1737 }
1738
1739 VlanId finalFlowVlan = flowVlan;
1740 found = si.uniTagList().stream().filter(uti ->
1741 uti.getPonCTag().equals(finalFlowVlan) ||
1742 uti.getPonSTag().equals(finalFlowVlan) ||
1743 uti.getUniTagMatch().equals(finalFlowVlan)
1744 ).findFirst();
1745
1746
1747 if (found.isEmpty()) {
1748 log.warn("Cannot map flow rule {} to Service in {}", flowRule, si);
1749 }
1750
1751 return found.isPresent() ? new ServiceKey(new AccessDevicePort(flowPort), found.get()) : null;
1752
1753 }
1754
1755 private OltFlowsStatus flowRuleStatusToOltFlowStatus(FlowRuleEvent.Type type) {
1756 switch (type) {
1757 case RULE_ADD_REQUESTED:
1758 return OltFlowsStatus.PENDING_ADD;
1759 case RULE_ADDED:
1760 return OltFlowsStatus.ADDED;
1761 case RULE_REMOVE_REQUESTED:
1762 return OltFlowsStatus.PENDING_REMOVE;
1763 case RULE_REMOVED:
1764 return OltFlowsStatus.REMOVED;
1765 default:
1766 return OltFlowsStatus.NONE;
1767 }
1768 }
1769 }
1770
1771 protected void bindSadisService(SadisService service) {
1772 this.subsService = service.getSubscriberInfoService();
1773 this.bpService = service.getBandwidthProfileService();
1774 log.info("Sadis service is loaded");
1775 }
1776
1777 protected void unbindSadisService(SadisService service) {
1778 this.subsService = null;
1779 this.bpService = null;
1780 log.info("Sadis service is unloaded");
1781 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001782}