blob: f1ef425880e7b80091c859069827823df3665783 [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 Scandolob6981dc2021-12-02 16:31:44 -0800662 flowRuleService.purgeFlowRules(deviceId);
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700663
664 // removing the status from the cpStatus map
Matteo Scandolo2542e5d2021-12-01 16:53:41 -0800665 if (log.isTraceEnabled()) {
666 log.trace("Clearing cp status from device {}", deviceId);
667 }
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700668 try {
669 cpStatusWriteLock.lock();
670 Iterator<Map.Entry<ServiceKey, OltPortStatus>> iter = cpStatus.entrySet().iterator();
671 while (iter.hasNext()) {
672 Map.Entry<ServiceKey, OltPortStatus> entry = iter.next();
673 if (entry.getKey().getPort().connectPoint().deviceId().equals(deviceId)) {
674 cpStatus.remove(entry.getKey());
675 }
676 }
677 } finally {
678 cpStatusWriteLock.unlock();
679 }
680
681 // removing subscribers from the provisioned map
Matteo Scandolo2542e5d2021-12-01 16:53:41 -0800682 if (log.isTraceEnabled()) {
683 log.trace("Clearing provisioned subscribers from device {}", deviceId);
684 }
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700685 try {
686 provisionedSubscribersWriteLock.lock();
687 Iterator<Map.Entry<ServiceKey, Boolean>> iter = provisionedSubscribers.entrySet().iterator();
688 while (iter.hasNext()) {
689 Map.Entry<ServiceKey, Boolean> entry = iter.next();
690 if (entry.getKey().getPort().connectPoint().deviceId().equals(deviceId)) {
691 provisionedSubscribers.remove(entry.getKey());
692 }
693 }
694 } finally {
695 provisionedSubscribersWriteLock.unlock();
696 }
Matteo Scandolo2542e5d2021-12-01 16:53:41 -0800697 log.debug("Done clearing up device flows and subscribers");
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700698 }
699
700 @Override
701 public boolean isSubscriberServiceProvisioned(AccessDevicePort cp) {
702 // if any service is programmed on this port, returns true
703 AtomicBoolean provisioned = new AtomicBoolean(false);
704 try {
705 provisionedSubscribersReadLock.lock();
706 for (Map.Entry<ServiceKey, Boolean> entry : provisionedSubscribers.entrySet()) {
707 if (entry.getKey().getPort().equals(cp) && entry.getValue()) {
708 provisioned.set(true);
709 break;
710 }
711 }
712 } finally {
713 provisionedSubscribersReadLock.unlock();
714 }
715 return provisioned.get();
716 }
717
718 @Override
719 public boolean isSubscriberServiceProvisioned(ServiceKey sk) {
720 try {
721 provisionedSubscribersReadLock.lock();
722 Boolean provisioned = provisionedSubscribers.get(sk);
723 if (provisioned == null || !provisioned) {
724 return false;
725 }
726 } finally {
727 provisionedSubscribersReadLock.unlock();
728 }
729 return true;
730 }
731
732 @Override
733 public void updateProvisionedSubscriberStatus(ServiceKey sk, Boolean status) {
734 try {
735 provisionedSubscribersWriteLock.lock();
736 provisionedSubscribers.put(sk, status);
737 } finally {
738 provisionedSubscribersWriteLock.unlock();
739 }
740 }
741
742 private boolean handleEapolFlow(DiscoveredSubscriber sub, String bandwidthProfile,
743 String oltBandwidthProfile, FlowOperation action, VlanId vlanId) {
744
745 // create a subscriberKey for the EAPOL flow
746 ServiceKey sk = new ServiceKey(new AccessDevicePort(sub.port), defaultEapolUniTag);
747
748 // NOTE we only need to keep track of the default EAPOL flow in the
749 // connectpoint status map
750 if (vlanId.id().equals(EAPOL_DEFAULT_VLAN)) {
751 OltFlowsStatus status = action == FlowOperation.ADD ?
752 OltFlowsStatus.PENDING_ADD : OltFlowsStatus.PENDING_REMOVE;
753 updateConnectPointStatus(sk, status, OltFlowsStatus.NONE, OltFlowsStatus.NONE);
754
755 }
756
757 DefaultFilteringObjective.Builder filterBuilder = DefaultFilteringObjective.builder();
758 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
759
760 int techProfileId = getDefaultTechProfileId(sub.port);
761 MeterId meterId = oltMeterService.getMeterIdForBandwidthProfile(sub.device.id(), bandwidthProfile);
762
763 // in the delete case the meter should still be there as we remove
764 // the meters only if no flows are pointing to them
765 if (meterId == null) {
766 log.debug("MeterId is null for BandwidthProfile {} on device {}",
767 bandwidthProfile, sub.device.id());
768 return false;
769 }
770
771 MeterId oltMeterId = oltMeterService.getMeterIdForBandwidthProfile(sub.device.id(), oltBandwidthProfile);
772 if (oltMeterId == null) {
773 log.debug("MeterId is null for OltBandwidthProfile {} on device {}",
774 oltBandwidthProfile, sub.device.id());
775 return false;
776 }
777
778 log.info("{} EAPOL flow for {} with vlanId {} and BandwidthProfile {} (meterId {})",
779 flowOpToString(action), portWithName(sub.port), vlanId, bandwidthProfile, meterId);
780
781 FilteringObjective.Builder eapolAction;
782
783 if (action == FlowOperation.ADD) {
784 eapolAction = filterBuilder.permit();
785 } else if (action == FlowOperation.REMOVE) {
786 eapolAction = filterBuilder.deny();
787 } else {
788 log.error("Operation {} not supported", action);
789 return false;
790 }
791
792 FilteringObjective.Builder baseEapol = eapolAction
793 .withKey(Criteria.matchInPort(sub.port.number()))
794 .addCondition(Criteria.matchEthType(EthType.EtherType.EAPOL.ethType()));
795
796 // NOTE we only need to add the treatment to install the flow,
797 // we can remove it based in the match
798 FilteringObjective.Builder eapol;
799
800 TrafficTreatment treatment = treatmentBuilder
801 .meter(meterId)
802 .writeMetadata(createTechProfValueForWriteMetadata(
803 vlanId,
804 techProfileId, oltMeterId), 0)
805 .setOutput(PortNumber.CONTROLLER)
806 .pushVlan()
807 .setVlanId(vlanId)
808 .build();
809 eapol = baseEapol
810 .withMeta(treatment);
811
812 FilteringObjective eapolObjective = eapol
813 .fromApp(appId)
814 .withPriority(MAX_PRIORITY)
815 .add(new ObjectiveContext() {
816 @Override
817 public void onSuccess(Objective objective) {
818 log.info("EAPOL flow objective {} for {}",
819 completeFlowOpToString(action), portWithName(sub.port));
820 if (log.isTraceEnabled()) {
821 log.trace("EAPOL flow details for port {}: {}", portWithName(sub.port), objective);
822 }
823 }
824
825 @Override
826 public void onError(Objective objective, ObjectiveError error) {
827 log.error("Cannot {} eapol flow for {} : {}", action,
828 portWithName(sub.port), error);
829
830 if (vlanId.id().equals(EAPOL_DEFAULT_VLAN)) {
831 updateConnectPointStatus(sk,
832 OltFlowsStatus.ERROR, null, null);
833 }
834 }
835 });
836
837 flowObjectiveService.filter(sub.device.id(), eapolObjective);
838
839 log.info("{} EAPOL filter for {}", completeFlowOpToString(action), portWithName(sub.port));
840 return true;
841 }
842
843 // FIXME it's confusing that si is not necessarily inside the DiscoveredSubscriber
844 private boolean handleSubscriberEapolFlows(DiscoveredSubscriber sub, FlowOperation action,
845 SubscriberAndDeviceInformation si) {
846 if (!enableEapol) {
847 return true;
848 }
849 // TODO verify we need an EAPOL flow for EACH service
850 AtomicBoolean success = new AtomicBoolean(true);
851 si.uniTagList().forEach(u -> {
852 // we assume that if subscriber flows are installed, tagged EAPOL is installed as well
853 boolean hasFlows = hasSubscriberFlows(sub.port, u);
854
855 // if the subscriber flows are present the EAPOL flow is present thus we don't need to install it,
856 // if the subscriber does not have flows the EAPOL flow is not present thus we don't need to remove it
857 if (action == FlowOperation.ADD && hasFlows ||
858 action == FlowOperation.REMOVE && !hasFlows) {
859 log.debug("Not {} EAPOL on {}({}) as subscriber flow status is {}", flowOpToString(action),
860 portWithName(sub.port), u.getServiceName(), hasFlows);
861 return;
862 }
863 log.info("{} EAPOL flows for subscriber {} on {} and service {}",
864 flowOpToString(action), si.id(), portWithName(sub.port), u.getServiceName());
865 if (!handleEapolFlow(sub, u.getUpstreamBandwidthProfile(),
866 u.getUpstreamOltBandwidthProfile(),
867 action, u.getPonCTag())) {
868 //
869 log.error("Failed to {} EAPOL with suscriber tags", action);
870 //TODO this sets it for all services, maybe some services succeeded.
871 success.set(false);
872 }
873 });
874 return success.get();
875 }
876
877 private void handleSubscriberIgmpFlows(DiscoveredSubscriber sub, FlowOperation action) {
878 sub.subscriberAndDeviceInformation.uniTagList().forEach(uti -> {
879 if (uti.getIsIgmpRequired()) {
880 DeviceId deviceId = sub.device.id();
881 // if we reached here a meter already exists
882 MeterId meterId = oltMeterService
883 .getMeterIdForBandwidthProfile(deviceId, uti.getUpstreamBandwidthProfile());
884 MeterId oltMeterId = oltMeterService
885 .getMeterIdForBandwidthProfile(deviceId, uti.getUpstreamOltBandwidthProfile());
886
887 processIgmpFilteringObjectives(deviceId, sub.port,
888 action, FlowDirection.UPSTREAM, meterId, oltMeterId, uti.getTechnologyProfileId(),
889 uti.getPonCTag(), uti.getUniTagMatch(), uti.getUsPonCTagPriority());
890 }
891 });
892 }
893
894 private boolean checkSadisRunning() {
895 if (bpService == null) {
896 log.warn("Sadis is not running");
897 return false;
898 }
899 return true;
900 }
901
902 private int getDefaultTechProfileId(Port port) {
903 if (!checkSadisRunning()) {
904 return defaultTechProfileId;
905 }
906 if (port != null) {
907 SubscriberAndDeviceInformation info = subsService.get(getPortName(port));
908 if (info != null && info.uniTagList().size() == 1) {
909 return info.uniTagList().get(0).getTechnologyProfileId();
910 }
911 }
912 return defaultTechProfileId;
913 }
914
915 protected Long createTechProfValueForWriteMetadata(VlanId cVlan, int techProfileId, MeterId upstreamOltMeterId) {
916 Long writeMetadata;
917
918 if (cVlan == null || VlanId.NONE.equals(cVlan)) {
919 writeMetadata = (long) techProfileId << 32;
920 } else {
921 writeMetadata = ((long) (cVlan.id()) << 48 | (long) techProfileId << 32);
922 }
923 if (upstreamOltMeterId == null) {
924 return writeMetadata;
925 } else {
926 return writeMetadata | upstreamOltMeterId.id();
927 }
928 }
929
930 private void processLldpFilteringObjective(DeviceId deviceId, Port port, FlowOperation action) {
931 DefaultFilteringObjective.Builder builder = DefaultFilteringObjective.builder();
932
933 FilteringObjective lldp = (action == FlowOperation.ADD ? builder.permit() : builder.deny())
934 .withKey(Criteria.matchInPort(port.number()))
935 .addCondition(Criteria.matchEthType(EthType.EtherType.LLDP.ethType()))
936 .withMeta(DefaultTrafficTreatment.builder()
937 .setOutput(PortNumber.CONTROLLER).build())
938 .fromApp(appId)
939 .withPriority(MAX_PRIORITY)
940 .add(new ObjectiveContext() {
941 @Override
942 public void onSuccess(Objective objective) {
943 log.info("{} LLDP filter for {}.", completeFlowOpToString(action), portWithName(port));
944 }
945
946 @Override
947 public void onError(Objective objective, ObjectiveError error) {
948 log.error("Falied to {} LLDP filter on {} because {}", action, portWithName(port),
949 error);
950 }
951 });
952
953 flowObjectiveService.filter(deviceId, lldp);
954 }
955
956 protected void handleSubscriberDhcpFlows(DeviceId deviceId, Port port,
957 FlowOperation action,
958 SubscriberAndDeviceInformation si) {
959 si.uniTagList().forEach(uti -> {
960
961 if (!uti.getIsDhcpRequired()) {
962 return;
963 }
964
965 // if it's an ADD skip if flows are there,
966 // if it's a DELETE skip if flows are not there
967 boolean hasFlows = hasDhcpFlows(port, uti);
968 if (action == FlowOperation.ADD && hasFlows ||
969 action == FlowOperation.REMOVE && !hasFlows) {
970 log.debug("Not dealing with DHCP {} on {} as DHCP flow status is {}", action,
971 uti.getServiceName(), hasFlows);
972 return;
973 }
974
975 log.info("{} DHCP flows for subscriber on {} and service {}",
976 flowOpToString(action), portWithName(port), uti.getServiceName());
977
978 // if we reached here a meter already exists
979 MeterId meterId = oltMeterService
980 .getMeterIdForBandwidthProfile(deviceId, uti.getUpstreamBandwidthProfile());
981 MeterId oltMeterId = oltMeterService
982 .getMeterIdForBandwidthProfile(deviceId, uti.getUpstreamOltBandwidthProfile());
983
984 if (enableDhcpV4) {
985 processDhcpFilteringObjectives(deviceId, port, action, FlowDirection.UPSTREAM, 68, 67,
986 EthType.EtherType.IPV4.ethType(), IPv4.PROTOCOL_UDP, meterId, oltMeterId,
987 uti);
988 }
989 if (enableDhcpV6) {
990 log.error("DHCP V6 not supported for subscribers");
991 }
992 });
993 }
994
995 // FIXME return boolean, if this fails we need to retry
996 protected void handleSubscriberDataFlows(Device device, Port port,
997 FlowOperation action,
998 SubscriberAndDeviceInformation si, String multicastServiceName) {
999
1000 Optional<Port> nniPort = oltDeviceService.getNniPort(device);
1001 if (nniPort.isEmpty()) {
1002 log.error("Cannot configure DP flows as upstream port is not configured for subscriber {} on {}",
1003 si.id(), portWithName(port));
1004 return;
1005 }
1006 si.uniTagList().forEach(uti -> {
1007
1008 boolean hasFlows = hasSubscriberFlows(port, uti);
1009 if (action == FlowOperation.ADD && hasFlows ||
1010 action == FlowOperation.REMOVE && !hasFlows) {
1011 log.debug("Not dealing with DP flows {} on {} as subscriber flow status is {}", action,
1012 uti.getServiceName(), hasFlows);
1013 return;
1014 }
1015
1016 if (multicastServiceName.equals(uti.getServiceName())) {
1017 log.debug("This is the multicast service ({}) for subscriber {} on {}, " +
1018 "dataplane flows are not needed",
1019 uti.getServiceName(), si.id(), portWithName(port));
1020 return;
1021 }
1022
1023 log.info("{} Data plane flows for subscriber {} on {} and service {}",
1024 flowOpToString(action), si.id(), portWithName(port), uti.getServiceName());
Matteo Scandolo80f5e972021-12-02 14:59:15 -08001025 ServiceKey sk = new ServiceKey(new AccessDevicePort(port), uti);
1026 OltFlowsStatus status = action.equals(FlowOperation.ADD) ?
1027 OltFlowsStatus.PENDING_ADD : OltFlowsStatus.PENDING_REMOVE;
1028 updateConnectPointStatus(sk, null, status, null);
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001029
1030 // upstream flows
1031 MeterId usMeterId = oltMeterService
1032 .getMeterIdForBandwidthProfile(device.id(), uti.getUpstreamBandwidthProfile());
1033 MeterId oltUsMeterId = oltMeterService
1034 .getMeterIdForBandwidthProfile(device.id(), uti.getUpstreamOltBandwidthProfile());
1035 processUpstreamDataFilteringObjects(device.id(), port, nniPort.get(), action, usMeterId,
1036 oltUsMeterId, uti);
1037
1038 // downstream flows
1039 MeterId dsMeterId = oltMeterService
1040 .getMeterIdForBandwidthProfile(device.id(), uti.getDownstreamBandwidthProfile());
1041 MeterId oltDsMeterId = oltMeterService
1042 .getMeterIdForBandwidthProfile(device.id(), uti.getDownstreamOltBandwidthProfile());
1043 processDownstreamDataFilteringObjects(device.id(), port, nniPort.get(), action, dsMeterId,
1044 oltDsMeterId, uti, getMacAddress(device.id(), port, uti));
1045 });
1046 }
1047
1048 private void processDhcpFilteringObjectives(DeviceId deviceId, Port port,
1049 FlowOperation action, FlowDirection direction,
1050 int udpSrc, int udpDst, EthType ethType, byte protocol,
1051 MeterId meterId, MeterId oltMeterId, UniTagInformation uti) {
1052 ServiceKey sk = new ServiceKey(new AccessDevicePort(port), uti);
1053 log.debug("{} DHCP filtering objectives on {}", flowOpToString(action), sk);
1054
1055
1056 OltFlowsStatus status = action.equals(FlowOperation.ADD) ?
1057 OltFlowsStatus.PENDING_ADD : OltFlowsStatus.PENDING_REMOVE;
1058 updateConnectPointStatus(sk, null, null, status);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001059
1060 DefaultFilteringObjective.Builder builder = DefaultFilteringObjective.builder();
1061 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
1062
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001063 if (meterId != null) {
1064 treatmentBuilder.meter(meterId);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001065 }
1066
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001067 if (uti.getTechnologyProfileId() != NONE_TP_ID) {
1068 treatmentBuilder.writeMetadata(
1069 createTechProfValueForWriteMetadata(uti.getUniTagMatch(),
1070 uti.getTechnologyProfileId(), oltMeterId), 0);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001071 }
1072
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001073 FilteringObjective.Builder dhcpBuilder = (action == FlowOperation.ADD ? builder.permit() : builder.deny())
Tunahan Sezenf0843b92021-04-30 07:13:16 +00001074 .withKey(Criteria.matchInPort(port.number()))
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001075 .addCondition(Criteria.matchEthType(ethType))
1076 .addCondition(Criteria.matchIPProtocol(protocol))
1077 .addCondition(Criteria.matchUdpSrc(TpPort.tpPort(udpSrc)))
1078 .addCondition(Criteria.matchUdpDst(TpPort.tpPort(udpDst)))
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001079 .fromApp(appId)
1080 .withPriority(MAX_PRIORITY);
1081
Andrea Campanella0e34f562020-06-11 10:47:10 +02001082 //VLAN changes and PCP matching need to happen only in the upstream directions
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001083 if (direction == FlowDirection.UPSTREAM) {
1084 treatmentBuilder.setVlanId(uti.getPonCTag());
1085 if (!VlanId.vlanId(VlanId.NO_VID).equals(uti.getUniTagMatch())) {
1086 dhcpBuilder.addCondition(Criteria.matchVlanId(uti.getUniTagMatch()));
Andrea Campanella0e34f562020-06-11 10:47:10 +02001087 }
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001088 if (uti.getUsPonCTagPriority() != -1) {
1089 treatmentBuilder.setVlanPcp((byte) uti.getUsPonCTagPriority());
Andrea Campanella0e34f562020-06-11 10:47:10 +02001090 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001091 }
1092
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001093 dhcpBuilder.withMeta(treatmentBuilder
1094 .setOutput(PortNumber.CONTROLLER).build());
Andrea Campanella0e34f562020-06-11 10:47:10 +02001095
1096
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001097 FilteringObjective dhcpUpstream = dhcpBuilder.add(new ObjectiveContext() {
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001098 @Override
1099 public void onSuccess(Objective objective) {
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001100 log.info("{} DHCP {} filter for {}.",
1101 completeFlowOpToString(action), (ethType.equals(EthType.EtherType.IPV4.ethType())) ? V4 : V6,
1102 portWithName(port));
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001103 }
1104
1105 @Override
1106 public void onError(Objective objective, ObjectiveError error) {
Tunahan Sezenf0843b92021-04-30 07:13:16 +00001107 log.error("DHCP {} filter for {} failed {} because {}",
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001108 (ethType.equals(EthType.EtherType.IPV4.ethType())) ? V4 : V6,
1109 portWithName(port),
1110 action,
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001111 error);
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001112 updateConnectPointStatus(sk, null, null, OltFlowsStatus.ERROR);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001113 }
1114 });
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001115 flowObjectiveService.filter(deviceId, dhcpUpstream);
1116 }
1117
1118 private void processIgmpFilteringObjectives(DeviceId deviceId, Port port,
1119 FlowOperation action, FlowDirection direction,
1120 MeterId meterId, MeterId oltMeterId, int techProfileId,
1121 VlanId cTag, VlanId unitagMatch, int vlanPcp) {
1122
1123 DefaultFilteringObjective.Builder filterBuilder = DefaultFilteringObjective.builder();
1124 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
1125 if (direction == FlowDirection.UPSTREAM) {
1126
1127 if (techProfileId != NONE_TP_ID) {
1128 treatmentBuilder.writeMetadata(createTechProfValueForWriteMetadata(null,
1129 techProfileId, oltMeterId), 0);
1130 }
1131
1132
1133 if (meterId != null) {
1134 treatmentBuilder.meter(meterId);
1135 }
1136
1137 if (!VlanId.vlanId(VlanId.NO_VID).equals(unitagMatch)) {
1138 filterBuilder.addCondition(Criteria.matchVlanId(unitagMatch));
1139 }
1140
1141 if (!VlanId.vlanId(VlanId.NO_VID).equals(cTag)) {
1142 treatmentBuilder.setVlanId(cTag);
1143 }
1144
1145 if (vlanPcp != -1) {
1146 treatmentBuilder.setVlanPcp((byte) vlanPcp);
1147 }
1148 }
1149
1150 filterBuilder = (action == FlowOperation.ADD) ? filterBuilder.permit() : filterBuilder.deny();
1151
1152 FilteringObjective igmp = filterBuilder
1153 .withKey(Criteria.matchInPort(port.number()))
1154 .addCondition(Criteria.matchEthType(EthType.EtherType.IPV4.ethType()))
1155 .addCondition(Criteria.matchIPProtocol(IPv4.PROTOCOL_IGMP))
1156 .withMeta(treatmentBuilder
1157 .setOutput(PortNumber.CONTROLLER).build())
1158 .fromApp(appId)
1159 .withPriority(MAX_PRIORITY)
1160 .add(new ObjectiveContext() {
1161 @Override
1162 public void onSuccess(Objective objective) {
1163 log.info("Igmp filter for {} {}.", portWithName(port), action);
1164 }
1165
1166 @Override
1167 public void onError(Objective objective, ObjectiveError error) {
1168 log.error("Igmp filter for {} failed {} because {}.", portWithName(port), action,
1169 error);
1170 }
1171 });
1172
1173 flowObjectiveService.filter(deviceId, igmp);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001174
1175 }
1176
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001177 private void processPPPoEDFilteringObjectives(DeviceId deviceId, Port port,
1178 FlowOperation action, FlowDirection direction,
1179 MeterId meterId, MeterId oltMeterId, int techProfileId,
1180 VlanId cTag, VlanId unitagMatch, Byte vlanPcp) {
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001181
1182 DefaultFilteringObjective.Builder builder = DefaultFilteringObjective.builder();
1183 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001184
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001185 if (meterId != null) {
1186 treatmentBuilder.meter(meterId);
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001187 }
1188
1189 if (techProfileId != NONE_TP_ID) {
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001190 treatmentBuilder.writeMetadata(createTechProfValueForWriteMetadata(cTag, techProfileId, oltMeterId), 0);
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001191 }
1192
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001193 DefaultFilteringObjective.Builder pppoedBuilder = ((action == FlowOperation.ADD)
1194 ? builder.permit() : builder.deny())
Tunahan Sezenf0843b92021-04-30 07:13:16 +00001195 .withKey(Criteria.matchInPort(port.number()))
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001196 .addCondition(Criteria.matchEthType(EthType.EtherType.PPPoED.ethType()))
1197 .fromApp(appId)
1198 .withPriority(10000);
1199
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001200 if (direction == FlowDirection.UPSTREAM) {
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001201 treatmentBuilder.setVlanId(cTag);
1202 if (!VlanId.vlanId(VlanId.NO_VID).equals(unitagMatch)) {
1203 pppoedBuilder.addCondition(Criteria.matchVlanId(unitagMatch));
1204 }
1205 if (vlanPcp != null) {
1206 treatmentBuilder.setVlanPcp(vlanPcp);
1207 }
1208 }
1209 pppoedBuilder = pppoedBuilder.withMeta(treatmentBuilder.setOutput(PortNumber.CONTROLLER).build());
1210
1211 FilteringObjective pppoed = pppoedBuilder
1212 .add(new ObjectiveContext() {
1213 @Override
1214 public void onSuccess(Objective objective) {
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001215 log.info("PPPoED filter for {} {}.", portWithName(port), action);
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001216 }
1217
1218 @Override
1219 public void onError(Objective objective, ObjectiveError error) {
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001220 log.info("PPPoED filter for {} failed {} because {}", portWithName(port),
1221 action, error);
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001222 }
1223 });
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001224 flowObjectiveService.filter(deviceId, pppoed);
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001225 }
1226
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001227 private void processUpstreamDataFilteringObjects(DeviceId deviceId, Port port, Port nniPort,
1228 FlowOperation action,
1229 MeterId upstreamMeterId,
1230 MeterId upstreamOltMeterId,
1231 UniTagInformation uti) {
1232 ServiceKey sk = new ServiceKey(new AccessDevicePort(port), uti);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001233 TrafficSelector selector = DefaultTrafficSelector.builder()
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001234 .matchInPort(port.number())
1235 .matchVlanId(uti.getUniTagMatch())
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001236 .build();
1237
Andrea Campanella327c5722020-01-30 11:34:13 +01001238 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
1239 //if the subscriberVlan (cTag) is different than ANY it needs to set.
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001240 if (uti.getPonCTag().toShort() != VlanId.ANY_VALUE) {
Andrea Campanella327c5722020-01-30 11:34:13 +01001241 treatmentBuilder.pushVlan()
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001242 .setVlanId(uti.getPonCTag());
Andrea Campanella327c5722020-01-30 11:34:13 +01001243 }
Maria Carmela Cascino067ee4d2021-11-02 13:14:43 +01001244 if (uti.getPonSTag().toShort() == VlanId.ANY_VALUE) {
1245 treatmentBuilder.popVlan();
1246 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001247
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001248 if (uti.getUsPonCTagPriority() != -1) {
1249 treatmentBuilder.setVlanPcp((byte) uti.getUsPonCTagPriority());
Maria Carmela Cascino067ee4d2021-11-02 13:14:43 +01001250
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001251 }
1252
1253 treatmentBuilder.pushVlan()
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001254 .setVlanId(uti.getPonSTag());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001255
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001256 if (uti.getUsPonSTagPriority() != -1) {
1257 treatmentBuilder.setVlanPcp((byte) uti.getUsPonSTagPriority());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001258 }
1259
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001260 treatmentBuilder.setOutput(nniPort.number())
1261 .writeMetadata(createMetadata(uti.getPonCTag(),
1262 uti.getTechnologyProfileId(), nniPort.number()), 0L);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001263
yasin saplib4b8ee12021-06-13 18:25:20 +00001264 DefaultAnnotations.Builder annotationBuilder = DefaultAnnotations.builder();
1265
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001266 if (upstreamMeterId != null) {
1267 treatmentBuilder.meter(upstreamMeterId);
yasin saplib4b8ee12021-06-13 18:25:20 +00001268 annotationBuilder.set(UPSTREAM_ONU, upstreamMeterId.toString());
1269 }
1270 if (upstreamOltMeterId != null) {
1271 treatmentBuilder.meter(upstreamOltMeterId);
1272 annotationBuilder.set(UPSTREAM_OLT, upstreamOltMeterId.toString());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001273 }
1274
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001275 DefaultForwardingObjective.Builder flowBuilder = createForwardingObjectiveBuilder(selector,
1276 treatmentBuilder.build(), MIN_PRIORITY,
yasin saplib4b8ee12021-06-13 18:25:20 +00001277 annotationBuilder.build());
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001278
1279 ObjectiveContext context = new ObjectiveContext() {
1280 @Override
1281 public void onSuccess(Objective objective) {
1282 log.info("{} Upstream Data plane filter for {}.",
1283 completeFlowOpToString(action), sk);
1284 }
1285
1286 @Override
1287 public void onError(Objective objective, ObjectiveError error) {
1288 log.error("Upstream Data plane filter for {} failed {} because {}.",
1289 sk, action, error);
1290 updateConnectPointStatus(sk, null, OltFlowsStatus.ERROR, null);
1291 }
1292 };
1293
1294 ForwardingObjective flow = null;
1295 if (action == FlowOperation.ADD) {
1296 flow = flowBuilder.add(context);
1297 } else if (action == FlowOperation.REMOVE) {
1298 flow = flowBuilder.remove(context);
1299 } else {
1300 log.error("Flow action not supported: {}", action);
1301 }
1302
1303 if (flow != null) {
1304 flowObjectiveService.forward(deviceId, flow);
1305 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001306 }
1307
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001308 private void processDownstreamDataFilteringObjects(DeviceId deviceId, Port port, Port nniPort,
1309 FlowOperation action,
1310 MeterId downstreamMeterId,
1311 MeterId downstreamOltMeterId,
1312 UniTagInformation uti,
1313 MacAddress macAddress) {
1314 ServiceKey sk = new ServiceKey(new AccessDevicePort(port), uti);
Andrea Campanella327c5722020-01-30 11:34:13 +01001315 //subscriberVlan can be any valid Vlan here including ANY to make sure the packet is tagged
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001316 TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder()
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001317 .matchVlanId(uti.getPonSTag())
1318 .matchInPort(nniPort.number())
1319 .matchInnerVlanId(uti.getPonCTag());
Andrea Campanella090e4a02020-02-05 13:53:55 +01001320
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001321 if (uti.getPonCTag().toShort() != VlanId.ANY_VALUE) {
1322 selectorBuilder.matchMetadata(uti.getPonCTag().toShort());
Andrea Campanella090e4a02020-02-05 13:53:55 +01001323 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001324
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001325 if (uti.getDsPonCTagPriority() != -1) {
1326 selectorBuilder.matchVlanPcp((byte) uti.getDsPonCTagPriority());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001327 }
1328
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001329 if (macAddress != null) {
1330 selectorBuilder.matchEthDst(macAddress);
1331 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001332
1333 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder()
1334 .popVlan()
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001335 .setOutput(port.number());
Andrea Campanella327c5722020-01-30 11:34:13 +01001336
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001337 treatmentBuilder.writeMetadata(createMetadata(uti.getPonCTag(),
1338 uti.getTechnologyProfileId(),
1339 port.number()), 0);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001340
Andrea Campanella981e86c2021-03-12 11:35:33 +01001341 // Upstream pbit is used to remark inner vlan pbit.
1342 // Upstream is used to avoid trusting the BNG to send the packet with correct pbit.
1343 // this is done because ds mode 0 is used because ds mode 3 or 6 that allow for
1344 // all pbit acceptance are not widely supported by vendors even though present in
1345 // the OMCI spec.
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001346 if (uti.getUsPonCTagPriority() != -1) {
1347 treatmentBuilder.setVlanPcp((byte) uti.getUsPonCTagPriority());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001348 }
1349
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001350 if (!VlanId.NONE.equals(uti.getUniTagMatch()) &&
1351 uti.getPonCTag().toShort() != VlanId.ANY_VALUE) {
1352 treatmentBuilder.setVlanId(uti.getUniTagMatch());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001353 }
1354
yasin saplib4b8ee12021-06-13 18:25:20 +00001355 DefaultAnnotations.Builder annotationBuilder = DefaultAnnotations.builder();
1356
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001357 if (downstreamMeterId != null) {
1358 treatmentBuilder.meter(downstreamMeterId);
yasin saplib4b8ee12021-06-13 18:25:20 +00001359 annotationBuilder.set(DOWNSTREAM_ONU, downstreamMeterId.toString());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001360 }
1361
yasin saplib4b8ee12021-06-13 18:25:20 +00001362 if (downstreamOltMeterId != null) {
1363 treatmentBuilder.meter(downstreamOltMeterId);
1364 annotationBuilder.set(DOWNSTREAM_OLT, downstreamOltMeterId.toString());
1365 }
1366
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001367 DefaultForwardingObjective.Builder flowBuilder = createForwardingObjectiveBuilder(selectorBuilder.build(),
1368 treatmentBuilder.build(), MIN_PRIORITY, annotationBuilder.build());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001369
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001370 ObjectiveContext context = new ObjectiveContext() {
1371 @Override
1372 public void onSuccess(Objective objective) {
1373 log.info("{} Downstream Data plane filter for {}.",
1374 completeFlowOpToString(action), sk);
1375 }
1376
1377 @Override
1378 public void onError(Objective objective, ObjectiveError error) {
1379 log.info("Downstream Data plane filter for {} failed {} because {}.",
1380 sk, action, error);
1381 updateConnectPointStatus(sk, null, OltFlowsStatus.ERROR, null);
1382 }
1383 };
1384
1385 ForwardingObjective flow = null;
1386 if (action == FlowOperation.ADD) {
1387 flow = flowBuilder.add(context);
1388 } else if (action == FlowOperation.REMOVE) {
1389 flow = flowBuilder.remove(context);
1390 } else {
1391 log.error("Flow action not supported: {}", action);
1392 }
1393
1394 if (flow != null) {
1395 if (log.isTraceEnabled()) {
1396 log.trace("Forwarding rule {}", flow);
1397 }
1398 flowObjectiveService.forward(deviceId, flow);
1399 }
Andrea Campanella600d2e22020-06-22 11:00:31 +02001400 }
1401
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001402 private DefaultForwardingObjective.Builder createForwardingObjectiveBuilder(TrafficSelector selector,
1403 TrafficTreatment treatment,
yasin saplib4b8ee12021-06-13 18:25:20 +00001404 Integer priority,
1405 Annotations annotations) {
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001406 return DefaultForwardingObjective.builder()
1407 .withFlag(ForwardingObjective.Flag.VERSATILE)
1408 .withPriority(priority)
1409 .makePermanent()
1410 .withSelector(selector)
yasin saplib4b8ee12021-06-13 18:25:20 +00001411 .withAnnotations(annotations)
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001412 .fromApp(appId)
1413 .withTreatment(treatment);
1414 }
1415
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001416 private Long createMetadata(VlanId innerVlan, int techProfileId, PortNumber egressPort) {
1417 if (techProfileId == NONE_TP_ID) {
Andrea Campanella7c49b792020-05-11 11:36:53 +02001418 techProfileId = DEFAULT_TP_ID_DEFAULT;
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001419 }
1420
1421 return ((long) (innerVlan.id()) << 48 | (long) techProfileId << 32) | egressPort.toLong();
1422 }
1423
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001424 private boolean isMacLearningEnabled(SubscriberAndDeviceInformation si) {
1425 AtomicBoolean requiresMacLearning = new AtomicBoolean();
1426 requiresMacLearning.set(false);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001427
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001428 si.uniTagList().forEach(uniTagInfo -> {
1429 if (uniTagInfo.getEnableMacLearning()) {
1430 requiresMacLearning.set(true);
1431 }
1432 });
1433
1434 return requiresMacLearning.get();
1435 }
1436
1437 /**
1438 * Checks whether the subscriber has the MacAddress configured or discovered.
1439 *
1440 * @param deviceId DeviceId for this subscriber
1441 * @param port Port for this subscriber
1442 * @param si SubscriberAndDeviceInformation
1443 * @return boolean
1444 */
1445 protected boolean isMacAddressAvailable(DeviceId deviceId, Port port, SubscriberAndDeviceInformation si) {
1446 AtomicBoolean isConfigured = new AtomicBoolean();
1447 isConfigured.set(true);
1448
1449 si.uniTagList().forEach(uniTagInfo -> {
1450 boolean isMacLearningEnabled = uniTagInfo.getEnableMacLearning();
1451 boolean configureMac = isMacAddressValid(uniTagInfo);
1452 boolean discoveredMac = false;
1453 Optional<Host> optHost = hostService.getConnectedHosts(new ConnectPoint(deviceId, port.number()))
1454 .stream().filter(host -> host.vlan().equals(uniTagInfo.getPonCTag())).findFirst();
1455 if (optHost.isPresent() && optHost.get().mac() != null) {
1456 discoveredMac = true;
1457 }
1458 if (isMacLearningEnabled && !configureMac && !discoveredMac) {
1459 log.debug("Awaiting for macAddress on {} for service {}",
1460 portWithName(port), uniTagInfo.getServiceName());
1461 isConfigured.set(false);
1462 }
1463 });
1464
1465 return isConfigured.get();
1466 }
1467
1468 protected MacAddress getMacAddress(DeviceId deviceId, Port port, UniTagInformation uniTagInfo) {
1469 boolean configuredMac = isMacAddressValid(uniTagInfo);
1470 if (configuredMac) {
1471 return MacAddress.valueOf(uniTagInfo.getConfiguredMacAddress());
1472 } else if (uniTagInfo.getEnableMacLearning()) {
1473 Optional<Host> optHost = hostService.getConnectedHosts(new ConnectPoint(deviceId, port.number()))
1474 .stream().filter(host -> host.vlan().equals(uniTagInfo.getPonCTag())).findFirst();
1475 if (optHost.isPresent() && optHost.get().mac() != null) {
1476 return optHost.get().mac();
1477 }
1478 }
1479 return null;
1480 }
1481
1482 private boolean isMacAddressValid(UniTagInformation tagInformation) {
1483 return tagInformation.getConfiguredMacAddress() != null &&
1484 !tagInformation.getConfiguredMacAddress().trim().equals("") &&
1485 !MacAddress.NONE.equals(MacAddress.valueOf(tagInformation.getConfiguredMacAddress()));
1486 }
1487
1488 protected void updateConnectPointStatus(ServiceKey key, OltFlowsStatus eapolStatus,
1489 OltFlowsStatus subscriberFlowsStatus, OltFlowsStatus dhcpStatus) {
Matteo Scandolo2542e5d2021-12-01 16:53:41 -08001490 if (log.isTraceEnabled()) {
1491 log.trace("Updating cpStatus {} with values: eapolFlow={}, subscriberFlows={}, dhcpFlow={}",
1492 key, eapolStatus, subscriberFlowsStatus, dhcpStatus);
1493 }
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001494 try {
1495 cpStatusWriteLock.lock();
1496 OltPortStatus status = cpStatus.get(key);
1497
Matteo Scandolo2542e5d2021-12-01 16:53:41 -08001498
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001499 if (status == null) {
Matteo Scandolo2542e5d2021-12-01 16:53:41 -08001500 // if we don't have status for the connectPoint
1501 // and we're only updating status to PENDING_REMOVE or ERROR
1502 // do not create it. This is because this case will only happen when a device is removed
1503 // and it's status cleaned
1504 List<OltFlowsStatus> statusesToIgnore = new ArrayList<>();
1505 statusesToIgnore.add(OltFlowsStatus.PENDING_REMOVE);
1506 statusesToIgnore.add(OltFlowsStatus.ERROR);
1507
1508 if (
1509 (statusesToIgnore.contains(subscriberFlowsStatus) && dhcpStatus == null) ||
1510 (subscriberFlowsStatus == null && statusesToIgnore.contains(dhcpStatus))
1511 ) {
1512 if (log.isTraceEnabled()) {
1513 log.trace("Ignoring cpStatus update as status is meaningless");
1514 }
1515 return;
1516 }
1517
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001518 status = new OltPortStatus(
1519 eapolStatus != null ? eapolStatus : OltFlowsStatus.NONE,
1520 subscriberFlowsStatus != null ? subscriberFlowsStatus : OltFlowsStatus.NONE,
1521 dhcpStatus != null ? dhcpStatus : OltFlowsStatus.NONE
1522 );
1523 } else {
1524 if (eapolStatus != null) {
1525 status.defaultEapolStatus = eapolStatus;
1526 }
1527 if (subscriberFlowsStatus != null) {
1528 status.subscriberFlowsStatus = subscriberFlowsStatus;
1529 }
1530 if (dhcpStatus != null) {
1531 status.dhcpStatus = dhcpStatus;
1532 }
1533 }
1534
1535 cpStatus.put(key, status);
1536 } finally {
1537 cpStatusWriteLock.unlock();
1538 }
1539 }
1540
1541 protected class InternalFlowListener implements FlowRuleListener {
1542 @Override
1543 public void event(FlowRuleEvent event) {
1544 if (appId.id() != (event.subject().appId())) {
1545 return;
1546 }
1547
1548 if (!oltDeviceService.isLocalLeader(event.subject().deviceId())) {
1549 if (log.isTraceEnabled()) {
1550 log.trace("ignoring flow event {} " +
1551 "as not leader for {}", event, event.subject().deviceId());
1552 }
1553 return;
1554 }
1555
1556 switch (event.type()) {
1557 case RULE_ADDED:
1558 case RULE_REMOVED:
1559 Port port = getCpFromFlowRule(event.subject());
1560 if (port == null) {
1561 log.error("Can't find port in flow {}", event.subject());
1562 return;
1563 }
1564 if (log.isTraceEnabled()) {
1565 log.trace("flow event {} on cp {}: {}", event.type(),
1566 portWithName(port), event.subject());
1567 }
1568 updateCpStatus(event.type(), port, event.subject());
1569 return;
1570 case RULE_ADD_REQUESTED:
1571 case RULE_REMOVE_REQUESTED:
1572 // NOTE that PENDING_ADD/REMOVE is set when we create the flowObjective
1573 return;
1574 default:
1575 return;
1576 }
1577 }
1578
1579 protected void updateCpStatus(FlowRuleEvent.Type type, Port port, FlowRule flowRule) {
1580 OltFlowsStatus status = flowRuleStatusToOltFlowStatus(type);
1581 if (isDefaultEapolFlow(flowRule)) {
1582 ServiceKey sk = new ServiceKey(new AccessDevicePort(port),
1583 defaultEapolUniTag);
1584 if (log.isTraceEnabled()) {
1585 log.trace("update defaultEapolStatus {} on {}", status, sk);
1586 }
1587 updateConnectPointStatus(sk, status, null, null);
1588 } else if (isDhcpFlow(flowRule)) {
1589 ServiceKey sk = getSubscriberKeyFromFlowRule(flowRule);
1590 if (sk == null) {
1591 return;
1592 }
1593 if (log.isTraceEnabled()) {
1594 log.trace("update dhcpStatus {} on {}", status, sk);
1595 }
1596 updateConnectPointStatus(sk, null, null, status);
1597 } else if (isDataFlow(flowRule)) {
1598
1599 if (oltDeviceService.isNniPort(deviceService.getDevice(flowRule.deviceId()),
1600 getCpFromFlowRule(flowRule).number())) {
1601 // the NNI has data-plane for every subscriber, doesn't make sense to track them
1602 return;
1603 }
1604
1605 ServiceKey sk = getSubscriberKeyFromFlowRule(flowRule);
1606 if (sk == null) {
1607 return;
1608 }
1609 if (log.isTraceEnabled()) {
1610 log.trace("update dataplaneStatus {} on {}", status, sk);
1611 }
1612 updateConnectPointStatus(sk, null, status, null);
1613 }
1614 }
1615
1616 private boolean isDefaultEapolFlow(FlowRule flowRule) {
1617 EthTypeCriterion c = (EthTypeCriterion) flowRule.selector().getCriterion(Criterion.Type.ETH_TYPE);
1618 if (c == null) {
1619 return false;
1620 }
1621 if (c.ethType().equals(EthType.EtherType.EAPOL.ethType())) {
1622 AtomicBoolean isDefault = new AtomicBoolean(false);
1623 flowRule.treatment().allInstructions().forEach(instruction -> {
1624 if (instruction.type() == L2MODIFICATION) {
1625 L2ModificationInstruction modificationInstruction = (L2ModificationInstruction) instruction;
1626 if (modificationInstruction.subtype() == L2ModificationInstruction.L2SubType.VLAN_ID) {
1627 L2ModificationInstruction.ModVlanIdInstruction vlanInstruction =
1628 (L2ModificationInstruction.ModVlanIdInstruction) modificationInstruction;
1629 if (vlanInstruction.vlanId().id().equals(EAPOL_DEFAULT_VLAN)) {
1630 isDefault.set(true);
1631 return;
1632 }
1633 }
1634 }
1635 });
1636 return isDefault.get();
1637 }
1638 return false;
1639 }
1640
1641 /**
1642 * Returns true if the flow is a DHCP flow.
1643 * Matches both upstream and downstream flows.
1644 *
1645 * @param flowRule The FlowRule to evaluate
1646 * @return boolean
1647 */
1648 private boolean isDhcpFlow(FlowRule flowRule) {
1649 IPProtocolCriterion ipCriterion = (IPProtocolCriterion) flowRule.selector()
1650 .getCriterion(Criterion.Type.IP_PROTO);
1651 if (ipCriterion == null) {
1652 return false;
1653 }
1654
1655 UdpPortCriterion src = (UdpPortCriterion) flowRule.selector().getCriterion(Criterion.Type.UDP_SRC);
1656
1657 if (src == null) {
1658 return false;
1659 }
1660 return ipCriterion.protocol() == IPv4.PROTOCOL_UDP &&
1661 (src.udpPort().toInt() == 68 || src.udpPort().toInt() == 67);
1662 }
1663
1664 private boolean isDataFlow(FlowRule flowRule) {
1665 // we consider subscriber flows the one that matches on VLAN_VID
1666 // method is valid only because it's the last check after EAPOL and DHCP.
1667 // this matches mcast flows as well, if we want to avoid that we can
1668 // filter out the elements that have groups in the treatment or
1669 // mcastIp in the selector
1670 // IPV4_DST:224.0.0.22/32
1671 // treatment=[immediate=[GROUP:0x1]]
1672
1673 return flowRule.selector().getCriterion(Criterion.Type.VLAN_VID) != null;
1674 }
1675
1676 private Port getCpFromFlowRule(FlowRule flowRule) {
1677 DeviceId deviceId = flowRule.deviceId();
1678 PortCriterion inPort = (PortCriterion) flowRule.selector().getCriterion(Criterion.Type.IN_PORT);
1679 if (inPort != null) {
1680 PortNumber port = inPort.port();
1681 return deviceService.getPort(deviceId, port);
1682 }
1683 return null;
1684 }
1685
1686 private ServiceKey getSubscriberKeyFromFlowRule(FlowRule flowRule) {
1687 Port flowPort = getCpFromFlowRule(flowRule);
1688 SubscriberAndDeviceInformation si = subsService.get(getPortName(flowPort));
1689
1690 Boolean isNni = oltDeviceService.isNniPort(deviceService.getDevice(flowRule.deviceId()), flowPort.number());
1691 if (si == null && !isNni) {
1692 log.error("Subscriber information not found in sadis for port {}", portWithName(flowPort));
1693 return null;
1694 }
1695
1696 if (isNni) {
1697 return new ServiceKey(new AccessDevicePort(flowPort), nniUniTag);
1698 }
1699
1700 Optional<UniTagInformation> found = Optional.empty();
1701 VlanId flowVlan = null;
1702 if (isDhcpFlow(flowRule)) {
1703 // we need to make a special case for DHCP as in the ATT workflow DHCP flows don't match on tags
1704 L2ModificationInstruction.ModVlanIdInstruction instruction =
1705 (L2ModificationInstruction.ModVlanIdInstruction) flowRule.treatment().immediate().get(1);
1706 flowVlan = instruction.vlanId();
1707 } else {
1708 // for now we assume that if it's not DHCP it's dataplane (or at least tagged)
1709 VlanIdCriterion vlanIdCriterion =
1710 (VlanIdCriterion) flowRule.selector().getCriterion(Criterion.Type.VLAN_VID);
1711 if (vlanIdCriterion == null) {
1712 log.warn("cannot match the flow to a subscriber service as it does not carry vlans");
1713 return null;
1714 }
1715 flowVlan = vlanIdCriterion.vlanId();
1716 }
1717
1718 VlanId finalFlowVlan = flowVlan;
1719 found = si.uniTagList().stream().filter(uti ->
1720 uti.getPonCTag().equals(finalFlowVlan) ||
1721 uti.getPonSTag().equals(finalFlowVlan) ||
1722 uti.getUniTagMatch().equals(finalFlowVlan)
1723 ).findFirst();
1724
1725
1726 if (found.isEmpty()) {
1727 log.warn("Cannot map flow rule {} to Service in {}", flowRule, si);
1728 }
1729
1730 return found.isPresent() ? new ServiceKey(new AccessDevicePort(flowPort), found.get()) : null;
1731
1732 }
1733
1734 private OltFlowsStatus flowRuleStatusToOltFlowStatus(FlowRuleEvent.Type type) {
1735 switch (type) {
1736 case RULE_ADD_REQUESTED:
1737 return OltFlowsStatus.PENDING_ADD;
1738 case RULE_ADDED:
1739 return OltFlowsStatus.ADDED;
1740 case RULE_REMOVE_REQUESTED:
1741 return OltFlowsStatus.PENDING_REMOVE;
1742 case RULE_REMOVED:
1743 return OltFlowsStatus.REMOVED;
1744 default:
1745 return OltFlowsStatus.NONE;
1746 }
1747 }
1748 }
1749
1750 protected void bindSadisService(SadisService service) {
1751 this.subsService = service.getSubscriberInfoService();
1752 this.bpService = service.getBandwidthProfileService();
1753 log.info("Sadis service is loaded");
1754 }
1755
1756 protected void unbindSadisService(SadisService service) {
1757 this.subsService = null;
1758 this.bpService = null;
1759 log.info("Sadis service is unloaded");
1760 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001761}