blob: 477e3a3222898370e36e172d921c3a0de6cdb515 [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
Matteo Scandolo8a91c0f2021-12-03 10:58:14 -0800554 // NOTE that the EAPOL flows handling is based on the data-plane flows status
555 // always process them before
556 handleSubscriberEapolFlows(sub, FlowOperation.ADD, sub.subscriberAndDeviceInformation);
557
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700558 handleSubscriberDataFlows(sub.device, sub.port, FlowOperation.ADD,
559 sub.subscriberAndDeviceInformation, multicastServiceName);
560
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700561 handleSubscriberIgmpFlows(sub, FlowOperation.ADD);
562
563 log.info("Provisioning of subscriber on {} completed", portWithName(sub.port));
564 return true;
565 }
566
567 private boolean removeSubscriberFlows(DiscoveredSubscriber sub, String defaultBandwithProfile,
568 String multicastServiceName) {
569
570 if (log.isTraceEnabled()) {
571 log.trace("Removal of subscriber on {} started",
572 portWithName(sub.port));
573 }
574 SubscriberAndDeviceInformation si = subsService.get(sub.portName());
575 if (si == null) {
576 log.error("Subscriber information not found in sadis for port {} during subscriber removal",
577 portWithName(sub.port));
578 // NOTE that we are returning true so that the subscriber is removed from the queue
579 // and we can move on provisioning others
580 return true;
581 }
582
583 handleSubscriberDhcpFlows(sub.device.id(), sub.port, FlowOperation.REMOVE, si);
584
585 if (enableEapol) {
586 // remove the tagged eapol
587 handleSubscriberEapolFlows(sub, FlowOperation.REMOVE, si);
588
Matteo Scandolo49c42052021-11-23 13:12:29 -0800589 // and add the default one back (only if the port is ENABLED and still present on the device)
590 if (sub.port.isEnabled() && deviceService.getPort(sub.device.id(), sub.port.number()) != null) {
591
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700592 // NOTE we remove the subscriber when the port goes down
593 // but in that case we don't need to add default eapol
594 handleEapolFlow(sub, defaultBandwithProfile, defaultBandwithProfile,
595 FlowOperation.ADD, VlanId.vlanId(EAPOL_DEFAULT_VLAN));
596 }
597 }
598 handleSubscriberDataFlows(sub.device, sub.port, FlowOperation.REMOVE, si, multicastServiceName);
599
600 handleSubscriberIgmpFlows(sub, FlowOperation.REMOVE);
601
602 // FIXME check the return status of the flow and return accordingly
603 log.info("Removal of subscriber on {} completed", portWithName(sub.port));
604 return true;
605 }
606
607 @Override
608 public boolean hasDefaultEapol(Port port) {
609 OltPortStatus status = getOltPortStatus(port, defaultEapolUniTag);
610 // NOTE we consider ERROR as a present EAPOL flow as ONOS
611 // will keep trying to add it
612 return status != null && (status.defaultEapolStatus == OltFlowsStatus.ADDED ||
613 status.defaultEapolStatus == OltFlowsStatus.PENDING_ADD ||
614 status.defaultEapolStatus == OltFlowsStatus.ERROR);
615 }
616
617 private OltPortStatus getOltPortStatus(Port port, UniTagInformation uniTagInformation) {
618 try {
619 cpStatusReadLock.lock();
620 ServiceKey sk = new ServiceKey(new AccessDevicePort(port), uniTagInformation);
621 OltPortStatus status = cpStatus.get(sk);
622 return status;
623 } finally {
624 cpStatusReadLock.unlock();
625 }
626 }
627
628 public boolean isDefaultEapolPendingRemoval(Port port) {
629 OltPortStatus status = getOltPortStatus(port, defaultEapolUniTag);
630 if (log.isTraceEnabled()) {
631 log.trace("Status during EAPOL flow check {} for port {} and UniTagInformation {}",
632 status, portWithName(port), defaultEapolUniTag);
633 }
634 return status != null && status.defaultEapolStatus == OltFlowsStatus.PENDING_REMOVE;
635 }
636
637 @Override
638 public boolean hasDhcpFlows(Port port, UniTagInformation uti) {
639 OltPortStatus status = getOltPortStatus(port, uti);
640 if (log.isTraceEnabled()) {
641 log.trace("Status during DHCP flow check {} for port {} and service {}",
642 status, portWithName(port), uti.getServiceName());
643 }
644 return status != null &&
645 (status.dhcpStatus == OltFlowsStatus.ADDED ||
646 status.dhcpStatus == OltFlowsStatus.PENDING_ADD);
647 }
648
649 @Override
650 public boolean hasSubscriberFlows(Port port, UniTagInformation uti) {
651
652 OltPortStatus status = getOltPortStatus(port, uti);
653 if (log.isTraceEnabled()) {
654 log.trace("Status during subscriber flow check {} for port {} and service {}",
655 status, portWithName(port), uti.getServiceName());
656 }
657 return status != null && (status.subscriberFlowsStatus == OltFlowsStatus.ADDED ||
658 status.subscriberFlowsStatus == OltFlowsStatus.PENDING_ADD);
659 }
660
661 @Override
662 public void purgeDeviceFlows(DeviceId deviceId) {
663 log.debug("Purging flows on device {}", deviceId);
Matteo Scandolob6981dc2021-12-02 16:31:44 -0800664 flowRuleService.purgeFlowRules(deviceId);
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700665
666 // removing the status from the cpStatus map
Matteo Scandolo2542e5d2021-12-01 16:53:41 -0800667 if (log.isTraceEnabled()) {
668 log.trace("Clearing cp status from device {}", deviceId);
669 }
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700670 try {
671 cpStatusWriteLock.lock();
672 Iterator<Map.Entry<ServiceKey, OltPortStatus>> iter = cpStatus.entrySet().iterator();
673 while (iter.hasNext()) {
674 Map.Entry<ServiceKey, OltPortStatus> entry = iter.next();
675 if (entry.getKey().getPort().connectPoint().deviceId().equals(deviceId)) {
676 cpStatus.remove(entry.getKey());
677 }
678 }
679 } finally {
680 cpStatusWriteLock.unlock();
681 }
682
683 // removing subscribers from the provisioned map
Matteo Scandolo2542e5d2021-12-01 16:53:41 -0800684 if (log.isTraceEnabled()) {
685 log.trace("Clearing provisioned subscribers from device {}", deviceId);
686 }
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700687 try {
688 provisionedSubscribersWriteLock.lock();
689 Iterator<Map.Entry<ServiceKey, Boolean>> iter = provisionedSubscribers.entrySet().iterator();
690 while (iter.hasNext()) {
691 Map.Entry<ServiceKey, Boolean> entry = iter.next();
692 if (entry.getKey().getPort().connectPoint().deviceId().equals(deviceId)) {
693 provisionedSubscribers.remove(entry.getKey());
694 }
695 }
696 } finally {
697 provisionedSubscribersWriteLock.unlock();
698 }
Matteo Scandolo2542e5d2021-12-01 16:53:41 -0800699 log.debug("Done clearing up device flows and subscribers");
Matteo Scandoloaa2adde2021-09-13 12:45:32 -0700700 }
701
702 @Override
703 public boolean isSubscriberServiceProvisioned(AccessDevicePort cp) {
704 // if any service is programmed on this port, returns true
705 AtomicBoolean provisioned = new AtomicBoolean(false);
706 try {
707 provisionedSubscribersReadLock.lock();
708 for (Map.Entry<ServiceKey, Boolean> entry : provisionedSubscribers.entrySet()) {
709 if (entry.getKey().getPort().equals(cp) && entry.getValue()) {
710 provisioned.set(true);
711 break;
712 }
713 }
714 } finally {
715 provisionedSubscribersReadLock.unlock();
716 }
717 return provisioned.get();
718 }
719
720 @Override
721 public boolean isSubscriberServiceProvisioned(ServiceKey sk) {
722 try {
723 provisionedSubscribersReadLock.lock();
724 Boolean provisioned = provisionedSubscribers.get(sk);
725 if (provisioned == null || !provisioned) {
726 return false;
727 }
728 } finally {
729 provisionedSubscribersReadLock.unlock();
730 }
731 return true;
732 }
733
734 @Override
735 public void updateProvisionedSubscriberStatus(ServiceKey sk, Boolean status) {
736 try {
737 provisionedSubscribersWriteLock.lock();
738 provisionedSubscribers.put(sk, status);
739 } finally {
740 provisionedSubscribersWriteLock.unlock();
741 }
742 }
743
744 private boolean handleEapolFlow(DiscoveredSubscriber sub, String bandwidthProfile,
745 String oltBandwidthProfile, FlowOperation action, VlanId vlanId) {
746
747 // create a subscriberKey for the EAPOL flow
748 ServiceKey sk = new ServiceKey(new AccessDevicePort(sub.port), defaultEapolUniTag);
749
750 // NOTE we only need to keep track of the default EAPOL flow in the
751 // connectpoint status map
752 if (vlanId.id().equals(EAPOL_DEFAULT_VLAN)) {
753 OltFlowsStatus status = action == FlowOperation.ADD ?
754 OltFlowsStatus.PENDING_ADD : OltFlowsStatus.PENDING_REMOVE;
755 updateConnectPointStatus(sk, status, OltFlowsStatus.NONE, OltFlowsStatus.NONE);
756
757 }
758
759 DefaultFilteringObjective.Builder filterBuilder = DefaultFilteringObjective.builder();
760 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
761
762 int techProfileId = getDefaultTechProfileId(sub.port);
763 MeterId meterId = oltMeterService.getMeterIdForBandwidthProfile(sub.device.id(), bandwidthProfile);
764
765 // in the delete case the meter should still be there as we remove
766 // the meters only if no flows are pointing to them
767 if (meterId == null) {
768 log.debug("MeterId is null for BandwidthProfile {} on device {}",
769 bandwidthProfile, sub.device.id());
770 return false;
771 }
772
773 MeterId oltMeterId = oltMeterService.getMeterIdForBandwidthProfile(sub.device.id(), oltBandwidthProfile);
774 if (oltMeterId == null) {
775 log.debug("MeterId is null for OltBandwidthProfile {} on device {}",
776 oltBandwidthProfile, sub.device.id());
777 return false;
778 }
779
780 log.info("{} EAPOL flow for {} with vlanId {} and BandwidthProfile {} (meterId {})",
781 flowOpToString(action), portWithName(sub.port), vlanId, bandwidthProfile, meterId);
782
783 FilteringObjective.Builder eapolAction;
784
785 if (action == FlowOperation.ADD) {
786 eapolAction = filterBuilder.permit();
787 } else if (action == FlowOperation.REMOVE) {
788 eapolAction = filterBuilder.deny();
789 } else {
790 log.error("Operation {} not supported", action);
791 return false;
792 }
793
794 FilteringObjective.Builder baseEapol = eapolAction
795 .withKey(Criteria.matchInPort(sub.port.number()))
796 .addCondition(Criteria.matchEthType(EthType.EtherType.EAPOL.ethType()));
797
798 // NOTE we only need to add the treatment to install the flow,
799 // we can remove it based in the match
800 FilteringObjective.Builder eapol;
801
802 TrafficTreatment treatment = treatmentBuilder
803 .meter(meterId)
804 .writeMetadata(createTechProfValueForWriteMetadata(
805 vlanId,
806 techProfileId, oltMeterId), 0)
807 .setOutput(PortNumber.CONTROLLER)
808 .pushVlan()
809 .setVlanId(vlanId)
810 .build();
811 eapol = baseEapol
812 .withMeta(treatment);
813
814 FilteringObjective eapolObjective = eapol
815 .fromApp(appId)
816 .withPriority(MAX_PRIORITY)
817 .add(new ObjectiveContext() {
818 @Override
819 public void onSuccess(Objective objective) {
820 log.info("EAPOL flow objective {} for {}",
821 completeFlowOpToString(action), portWithName(sub.port));
822 if (log.isTraceEnabled()) {
823 log.trace("EAPOL flow details for port {}: {}", portWithName(sub.port), objective);
824 }
825 }
826
827 @Override
828 public void onError(Objective objective, ObjectiveError error) {
829 log.error("Cannot {} eapol flow for {} : {}", action,
830 portWithName(sub.port), error);
831
832 if (vlanId.id().equals(EAPOL_DEFAULT_VLAN)) {
833 updateConnectPointStatus(sk,
834 OltFlowsStatus.ERROR, null, null);
835 }
836 }
837 });
838
839 flowObjectiveService.filter(sub.device.id(), eapolObjective);
840
841 log.info("{} EAPOL filter for {}", completeFlowOpToString(action), portWithName(sub.port));
842 return true;
843 }
844
845 // FIXME it's confusing that si is not necessarily inside the DiscoveredSubscriber
846 private boolean handleSubscriberEapolFlows(DiscoveredSubscriber sub, FlowOperation action,
847 SubscriberAndDeviceInformation si) {
848 if (!enableEapol) {
849 return true;
850 }
851 // TODO verify we need an EAPOL flow for EACH service
852 AtomicBoolean success = new AtomicBoolean(true);
853 si.uniTagList().forEach(u -> {
854 // we assume that if subscriber flows are installed, tagged EAPOL is installed as well
855 boolean hasFlows = hasSubscriberFlows(sub.port, u);
856
857 // if the subscriber flows are present the EAPOL flow is present thus we don't need to install it,
858 // if the subscriber does not have flows the EAPOL flow is not present thus we don't need to remove it
859 if (action == FlowOperation.ADD && hasFlows ||
860 action == FlowOperation.REMOVE && !hasFlows) {
861 log.debug("Not {} EAPOL on {}({}) as subscriber flow status is {}", flowOpToString(action),
862 portWithName(sub.port), u.getServiceName(), hasFlows);
863 return;
864 }
865 log.info("{} EAPOL flows for subscriber {} on {} and service {}",
866 flowOpToString(action), si.id(), portWithName(sub.port), u.getServiceName());
867 if (!handleEapolFlow(sub, u.getUpstreamBandwidthProfile(),
868 u.getUpstreamOltBandwidthProfile(),
869 action, u.getPonCTag())) {
870 //
871 log.error("Failed to {} EAPOL with suscriber tags", action);
872 //TODO this sets it for all services, maybe some services succeeded.
873 success.set(false);
874 }
875 });
876 return success.get();
877 }
878
879 private void handleSubscriberIgmpFlows(DiscoveredSubscriber sub, FlowOperation action) {
880 sub.subscriberAndDeviceInformation.uniTagList().forEach(uti -> {
881 if (uti.getIsIgmpRequired()) {
882 DeviceId deviceId = sub.device.id();
883 // if we reached here a meter already exists
884 MeterId meterId = oltMeterService
885 .getMeterIdForBandwidthProfile(deviceId, uti.getUpstreamBandwidthProfile());
886 MeterId oltMeterId = oltMeterService
887 .getMeterIdForBandwidthProfile(deviceId, uti.getUpstreamOltBandwidthProfile());
888
889 processIgmpFilteringObjectives(deviceId, sub.port,
890 action, FlowDirection.UPSTREAM, meterId, oltMeterId, uti.getTechnologyProfileId(),
891 uti.getPonCTag(), uti.getUniTagMatch(), uti.getUsPonCTagPriority());
892 }
893 });
894 }
895
896 private boolean checkSadisRunning() {
897 if (bpService == null) {
898 log.warn("Sadis is not running");
899 return false;
900 }
901 return true;
902 }
903
904 private int getDefaultTechProfileId(Port port) {
905 if (!checkSadisRunning()) {
906 return defaultTechProfileId;
907 }
908 if (port != null) {
909 SubscriberAndDeviceInformation info = subsService.get(getPortName(port));
910 if (info != null && info.uniTagList().size() == 1) {
911 return info.uniTagList().get(0).getTechnologyProfileId();
912 }
913 }
914 return defaultTechProfileId;
915 }
916
917 protected Long createTechProfValueForWriteMetadata(VlanId cVlan, int techProfileId, MeterId upstreamOltMeterId) {
918 Long writeMetadata;
919
920 if (cVlan == null || VlanId.NONE.equals(cVlan)) {
921 writeMetadata = (long) techProfileId << 32;
922 } else {
923 writeMetadata = ((long) (cVlan.id()) << 48 | (long) techProfileId << 32);
924 }
925 if (upstreamOltMeterId == null) {
926 return writeMetadata;
927 } else {
928 return writeMetadata | upstreamOltMeterId.id();
929 }
930 }
931
932 private void processLldpFilteringObjective(DeviceId deviceId, Port port, FlowOperation action) {
933 DefaultFilteringObjective.Builder builder = DefaultFilteringObjective.builder();
934
935 FilteringObjective lldp = (action == FlowOperation.ADD ? builder.permit() : builder.deny())
936 .withKey(Criteria.matchInPort(port.number()))
937 .addCondition(Criteria.matchEthType(EthType.EtherType.LLDP.ethType()))
938 .withMeta(DefaultTrafficTreatment.builder()
939 .setOutput(PortNumber.CONTROLLER).build())
940 .fromApp(appId)
941 .withPriority(MAX_PRIORITY)
942 .add(new ObjectiveContext() {
943 @Override
944 public void onSuccess(Objective objective) {
945 log.info("{} LLDP filter for {}.", completeFlowOpToString(action), portWithName(port));
946 }
947
948 @Override
949 public void onError(Objective objective, ObjectiveError error) {
950 log.error("Falied to {} LLDP filter on {} because {}", action, portWithName(port),
951 error);
952 }
953 });
954
955 flowObjectiveService.filter(deviceId, lldp);
956 }
957
958 protected void handleSubscriberDhcpFlows(DeviceId deviceId, Port port,
959 FlowOperation action,
960 SubscriberAndDeviceInformation si) {
961 si.uniTagList().forEach(uti -> {
962
963 if (!uti.getIsDhcpRequired()) {
964 return;
965 }
966
967 // if it's an ADD skip if flows are there,
968 // if it's a DELETE skip if flows are not there
969 boolean hasFlows = hasDhcpFlows(port, uti);
970 if (action == FlowOperation.ADD && hasFlows ||
971 action == FlowOperation.REMOVE && !hasFlows) {
972 log.debug("Not dealing with DHCP {} on {} as DHCP flow status is {}", action,
973 uti.getServiceName(), hasFlows);
974 return;
975 }
976
977 log.info("{} DHCP flows for subscriber on {} and service {}",
978 flowOpToString(action), portWithName(port), uti.getServiceName());
979
980 // if we reached here a meter already exists
981 MeterId meterId = oltMeterService
982 .getMeterIdForBandwidthProfile(deviceId, uti.getUpstreamBandwidthProfile());
983 MeterId oltMeterId = oltMeterService
984 .getMeterIdForBandwidthProfile(deviceId, uti.getUpstreamOltBandwidthProfile());
985
986 if (enableDhcpV4) {
987 processDhcpFilteringObjectives(deviceId, port, action, FlowDirection.UPSTREAM, 68, 67,
988 EthType.EtherType.IPV4.ethType(), IPv4.PROTOCOL_UDP, meterId, oltMeterId,
989 uti);
990 }
991 if (enableDhcpV6) {
992 log.error("DHCP V6 not supported for subscribers");
993 }
994 });
995 }
996
997 // FIXME return boolean, if this fails we need to retry
998 protected void handleSubscriberDataFlows(Device device, Port port,
999 FlowOperation action,
1000 SubscriberAndDeviceInformation si, String multicastServiceName) {
1001
1002 Optional<Port> nniPort = oltDeviceService.getNniPort(device);
1003 if (nniPort.isEmpty()) {
1004 log.error("Cannot configure DP flows as upstream port is not configured for subscriber {} on {}",
1005 si.id(), portWithName(port));
1006 return;
1007 }
1008 si.uniTagList().forEach(uti -> {
1009
1010 boolean hasFlows = hasSubscriberFlows(port, uti);
1011 if (action == FlowOperation.ADD && hasFlows ||
1012 action == FlowOperation.REMOVE && !hasFlows) {
1013 log.debug("Not dealing with DP flows {} on {} as subscriber flow status is {}", action,
1014 uti.getServiceName(), hasFlows);
1015 return;
1016 }
1017
1018 if (multicastServiceName.equals(uti.getServiceName())) {
1019 log.debug("This is the multicast service ({}) for subscriber {} on {}, " +
1020 "dataplane flows are not needed",
1021 uti.getServiceName(), si.id(), portWithName(port));
1022 return;
1023 }
1024
1025 log.info("{} Data plane flows for subscriber {} on {} and service {}",
1026 flowOpToString(action), si.id(), portWithName(port), uti.getServiceName());
Matteo Scandolo80f5e972021-12-02 14:59:15 -08001027 ServiceKey sk = new ServiceKey(new AccessDevicePort(port), uti);
1028 OltFlowsStatus status = action.equals(FlowOperation.ADD) ?
1029 OltFlowsStatus.PENDING_ADD : OltFlowsStatus.PENDING_REMOVE;
1030 updateConnectPointStatus(sk, null, status, null);
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001031
1032 // upstream flows
1033 MeterId usMeterId = oltMeterService
1034 .getMeterIdForBandwidthProfile(device.id(), uti.getUpstreamBandwidthProfile());
1035 MeterId oltUsMeterId = oltMeterService
1036 .getMeterIdForBandwidthProfile(device.id(), uti.getUpstreamOltBandwidthProfile());
1037 processUpstreamDataFilteringObjects(device.id(), port, nniPort.get(), action, usMeterId,
1038 oltUsMeterId, uti);
1039
1040 // downstream flows
1041 MeterId dsMeterId = oltMeterService
1042 .getMeterIdForBandwidthProfile(device.id(), uti.getDownstreamBandwidthProfile());
1043 MeterId oltDsMeterId = oltMeterService
1044 .getMeterIdForBandwidthProfile(device.id(), uti.getDownstreamOltBandwidthProfile());
1045 processDownstreamDataFilteringObjects(device.id(), port, nniPort.get(), action, dsMeterId,
1046 oltDsMeterId, uti, getMacAddress(device.id(), port, uti));
1047 });
1048 }
1049
1050 private void processDhcpFilteringObjectives(DeviceId deviceId, Port port,
1051 FlowOperation action, FlowDirection direction,
1052 int udpSrc, int udpDst, EthType ethType, byte protocol,
1053 MeterId meterId, MeterId oltMeterId, UniTagInformation uti) {
1054 ServiceKey sk = new ServiceKey(new AccessDevicePort(port), uti);
1055 log.debug("{} DHCP filtering objectives on {}", flowOpToString(action), sk);
1056
1057
1058 OltFlowsStatus status = action.equals(FlowOperation.ADD) ?
1059 OltFlowsStatus.PENDING_ADD : OltFlowsStatus.PENDING_REMOVE;
1060 updateConnectPointStatus(sk, null, null, status);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001061
1062 DefaultFilteringObjective.Builder builder = DefaultFilteringObjective.builder();
1063 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
1064
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001065 if (meterId != null) {
1066 treatmentBuilder.meter(meterId);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001067 }
1068
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001069 if (uti.getTechnologyProfileId() != NONE_TP_ID) {
1070 treatmentBuilder.writeMetadata(
1071 createTechProfValueForWriteMetadata(uti.getUniTagMatch(),
1072 uti.getTechnologyProfileId(), oltMeterId), 0);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001073 }
1074
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001075 FilteringObjective.Builder dhcpBuilder = (action == FlowOperation.ADD ? builder.permit() : builder.deny())
Tunahan Sezenf0843b92021-04-30 07:13:16 +00001076 .withKey(Criteria.matchInPort(port.number()))
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001077 .addCondition(Criteria.matchEthType(ethType))
1078 .addCondition(Criteria.matchIPProtocol(protocol))
1079 .addCondition(Criteria.matchUdpSrc(TpPort.tpPort(udpSrc)))
1080 .addCondition(Criteria.matchUdpDst(TpPort.tpPort(udpDst)))
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001081 .fromApp(appId)
1082 .withPriority(MAX_PRIORITY);
1083
Andrea Campanella0e34f562020-06-11 10:47:10 +02001084 //VLAN changes and PCP matching need to happen only in the upstream directions
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001085 if (direction == FlowDirection.UPSTREAM) {
1086 treatmentBuilder.setVlanId(uti.getPonCTag());
1087 if (!VlanId.vlanId(VlanId.NO_VID).equals(uti.getUniTagMatch())) {
1088 dhcpBuilder.addCondition(Criteria.matchVlanId(uti.getUniTagMatch()));
Andrea Campanella0e34f562020-06-11 10:47:10 +02001089 }
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001090 if (uti.getUsPonCTagPriority() != -1) {
1091 treatmentBuilder.setVlanPcp((byte) uti.getUsPonCTagPriority());
Andrea Campanella0e34f562020-06-11 10:47:10 +02001092 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001093 }
1094
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001095 dhcpBuilder.withMeta(treatmentBuilder
1096 .setOutput(PortNumber.CONTROLLER).build());
Andrea Campanella0e34f562020-06-11 10:47:10 +02001097
1098
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001099 FilteringObjective dhcpUpstream = dhcpBuilder.add(new ObjectiveContext() {
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001100 @Override
1101 public void onSuccess(Objective objective) {
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001102 log.info("{} DHCP {} filter for {}.",
1103 completeFlowOpToString(action), (ethType.equals(EthType.EtherType.IPV4.ethType())) ? V4 : V6,
1104 portWithName(port));
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001105 }
1106
1107 @Override
1108 public void onError(Objective objective, ObjectiveError error) {
Tunahan Sezenf0843b92021-04-30 07:13:16 +00001109 log.error("DHCP {} filter for {} failed {} because {}",
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001110 (ethType.equals(EthType.EtherType.IPV4.ethType())) ? V4 : V6,
1111 portWithName(port),
1112 action,
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001113 error);
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001114 updateConnectPointStatus(sk, null, null, OltFlowsStatus.ERROR);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001115 }
1116 });
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001117 flowObjectiveService.filter(deviceId, dhcpUpstream);
1118 }
1119
1120 private void processIgmpFilteringObjectives(DeviceId deviceId, Port port,
1121 FlowOperation action, FlowDirection direction,
1122 MeterId meterId, MeterId oltMeterId, int techProfileId,
1123 VlanId cTag, VlanId unitagMatch, int vlanPcp) {
1124
1125 DefaultFilteringObjective.Builder filterBuilder = DefaultFilteringObjective.builder();
1126 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
1127 if (direction == FlowDirection.UPSTREAM) {
1128
1129 if (techProfileId != NONE_TP_ID) {
1130 treatmentBuilder.writeMetadata(createTechProfValueForWriteMetadata(null,
1131 techProfileId, oltMeterId), 0);
1132 }
1133
1134
1135 if (meterId != null) {
1136 treatmentBuilder.meter(meterId);
1137 }
1138
1139 if (!VlanId.vlanId(VlanId.NO_VID).equals(unitagMatch)) {
1140 filterBuilder.addCondition(Criteria.matchVlanId(unitagMatch));
1141 }
1142
1143 if (!VlanId.vlanId(VlanId.NO_VID).equals(cTag)) {
1144 treatmentBuilder.setVlanId(cTag);
1145 }
1146
1147 if (vlanPcp != -1) {
1148 treatmentBuilder.setVlanPcp((byte) vlanPcp);
1149 }
1150 }
1151
1152 filterBuilder = (action == FlowOperation.ADD) ? filterBuilder.permit() : filterBuilder.deny();
1153
1154 FilteringObjective igmp = filterBuilder
1155 .withKey(Criteria.matchInPort(port.number()))
1156 .addCondition(Criteria.matchEthType(EthType.EtherType.IPV4.ethType()))
1157 .addCondition(Criteria.matchIPProtocol(IPv4.PROTOCOL_IGMP))
1158 .withMeta(treatmentBuilder
1159 .setOutput(PortNumber.CONTROLLER).build())
1160 .fromApp(appId)
1161 .withPriority(MAX_PRIORITY)
1162 .add(new ObjectiveContext() {
1163 @Override
1164 public void onSuccess(Objective objective) {
1165 log.info("Igmp filter for {} {}.", portWithName(port), action);
1166 }
1167
1168 @Override
1169 public void onError(Objective objective, ObjectiveError error) {
1170 log.error("Igmp filter for {} failed {} because {}.", portWithName(port), action,
1171 error);
1172 }
1173 });
1174
1175 flowObjectiveService.filter(deviceId, igmp);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001176
1177 }
1178
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001179 private void processPPPoEDFilteringObjectives(DeviceId deviceId, Port port,
1180 FlowOperation action, FlowDirection direction,
1181 MeterId meterId, MeterId oltMeterId, int techProfileId,
1182 VlanId cTag, VlanId unitagMatch, Byte vlanPcp) {
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001183
1184 DefaultFilteringObjective.Builder builder = DefaultFilteringObjective.builder();
1185 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001186
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001187 if (meterId != null) {
1188 treatmentBuilder.meter(meterId);
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001189 }
1190
1191 if (techProfileId != NONE_TP_ID) {
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001192 treatmentBuilder.writeMetadata(createTechProfValueForWriteMetadata(cTag, techProfileId, oltMeterId), 0);
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001193 }
1194
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001195 DefaultFilteringObjective.Builder pppoedBuilder = ((action == FlowOperation.ADD)
1196 ? builder.permit() : builder.deny())
Tunahan Sezenf0843b92021-04-30 07:13:16 +00001197 .withKey(Criteria.matchInPort(port.number()))
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001198 .addCondition(Criteria.matchEthType(EthType.EtherType.PPPoED.ethType()))
1199 .fromApp(appId)
1200 .withPriority(10000);
1201
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001202 if (direction == FlowDirection.UPSTREAM) {
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001203 treatmentBuilder.setVlanId(cTag);
1204 if (!VlanId.vlanId(VlanId.NO_VID).equals(unitagMatch)) {
1205 pppoedBuilder.addCondition(Criteria.matchVlanId(unitagMatch));
1206 }
1207 if (vlanPcp != null) {
1208 treatmentBuilder.setVlanPcp(vlanPcp);
1209 }
1210 }
1211 pppoedBuilder = pppoedBuilder.withMeta(treatmentBuilder.setOutput(PortNumber.CONTROLLER).build());
1212
1213 FilteringObjective pppoed = pppoedBuilder
1214 .add(new ObjectiveContext() {
1215 @Override
1216 public void onSuccess(Objective objective) {
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001217 log.info("PPPoED filter for {} {}.", portWithName(port), action);
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001218 }
1219
1220 @Override
1221 public void onError(Objective objective, ObjectiveError error) {
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001222 log.info("PPPoED filter for {} failed {} because {}", portWithName(port),
1223 action, error);
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001224 }
1225 });
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001226 flowObjectiveService.filter(deviceId, pppoed);
Gustavo Silva5c492dd2021-02-12 10:21:11 -03001227 }
1228
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001229 private void processUpstreamDataFilteringObjects(DeviceId deviceId, Port port, Port nniPort,
1230 FlowOperation action,
1231 MeterId upstreamMeterId,
1232 MeterId upstreamOltMeterId,
1233 UniTagInformation uti) {
1234 ServiceKey sk = new ServiceKey(new AccessDevicePort(port), uti);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001235 TrafficSelector selector = DefaultTrafficSelector.builder()
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001236 .matchInPort(port.number())
1237 .matchVlanId(uti.getUniTagMatch())
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001238 .build();
1239
Andrea Campanella327c5722020-01-30 11:34:13 +01001240 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
1241 //if the subscriberVlan (cTag) is different than ANY it needs to set.
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001242 if (uti.getPonCTag().toShort() != VlanId.ANY_VALUE) {
Andrea Campanella327c5722020-01-30 11:34:13 +01001243 treatmentBuilder.pushVlan()
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001244 .setVlanId(uti.getPonCTag());
Andrea Campanella327c5722020-01-30 11:34:13 +01001245 }
Maria Carmela Cascino067ee4d2021-11-02 13:14:43 +01001246 if (uti.getPonSTag().toShort() == VlanId.ANY_VALUE) {
1247 treatmentBuilder.popVlan();
1248 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001249
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001250 if (uti.getUsPonCTagPriority() != -1) {
1251 treatmentBuilder.setVlanPcp((byte) uti.getUsPonCTagPriority());
Maria Carmela Cascino067ee4d2021-11-02 13:14:43 +01001252
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001253 }
1254
1255 treatmentBuilder.pushVlan()
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001256 .setVlanId(uti.getPonSTag());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001257
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001258 if (uti.getUsPonSTagPriority() != -1) {
1259 treatmentBuilder.setVlanPcp((byte) uti.getUsPonSTagPriority());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001260 }
1261
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001262 treatmentBuilder.setOutput(nniPort.number())
1263 .writeMetadata(createMetadata(uti.getPonCTag(),
1264 uti.getTechnologyProfileId(), nniPort.number()), 0L);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001265
yasin saplib4b8ee12021-06-13 18:25:20 +00001266 DefaultAnnotations.Builder annotationBuilder = DefaultAnnotations.builder();
1267
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001268 if (upstreamMeterId != null) {
1269 treatmentBuilder.meter(upstreamMeterId);
yasin saplib4b8ee12021-06-13 18:25:20 +00001270 annotationBuilder.set(UPSTREAM_ONU, upstreamMeterId.toString());
1271 }
1272 if (upstreamOltMeterId != null) {
1273 treatmentBuilder.meter(upstreamOltMeterId);
1274 annotationBuilder.set(UPSTREAM_OLT, upstreamOltMeterId.toString());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001275 }
1276
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001277 DefaultForwardingObjective.Builder flowBuilder = createForwardingObjectiveBuilder(selector,
1278 treatmentBuilder.build(), MIN_PRIORITY,
yasin saplib4b8ee12021-06-13 18:25:20 +00001279 annotationBuilder.build());
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001280
1281 ObjectiveContext context = new ObjectiveContext() {
1282 @Override
1283 public void onSuccess(Objective objective) {
1284 log.info("{} Upstream Data plane filter for {}.",
1285 completeFlowOpToString(action), sk);
1286 }
1287
1288 @Override
1289 public void onError(Objective objective, ObjectiveError error) {
1290 log.error("Upstream Data plane filter for {} failed {} because {}.",
1291 sk, action, error);
1292 updateConnectPointStatus(sk, null, OltFlowsStatus.ERROR, null);
1293 }
1294 };
1295
1296 ForwardingObjective flow = null;
1297 if (action == FlowOperation.ADD) {
1298 flow = flowBuilder.add(context);
1299 } else if (action == FlowOperation.REMOVE) {
1300 flow = flowBuilder.remove(context);
1301 } else {
1302 log.error("Flow action not supported: {}", action);
1303 }
1304
1305 if (flow != null) {
1306 flowObjectiveService.forward(deviceId, flow);
1307 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001308 }
1309
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001310 private void processDownstreamDataFilteringObjects(DeviceId deviceId, Port port, Port nniPort,
1311 FlowOperation action,
1312 MeterId downstreamMeterId,
1313 MeterId downstreamOltMeterId,
1314 UniTagInformation uti,
1315 MacAddress macAddress) {
1316 ServiceKey sk = new ServiceKey(new AccessDevicePort(port), uti);
Andrea Campanella327c5722020-01-30 11:34:13 +01001317 //subscriberVlan can be any valid Vlan here including ANY to make sure the packet is tagged
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001318 TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder()
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001319 .matchVlanId(uti.getPonSTag())
1320 .matchInPort(nniPort.number())
1321 .matchInnerVlanId(uti.getPonCTag());
Andrea Campanella090e4a02020-02-05 13:53:55 +01001322
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001323 if (uti.getPonCTag().toShort() != VlanId.ANY_VALUE) {
1324 selectorBuilder.matchMetadata(uti.getPonCTag().toShort());
Andrea Campanella090e4a02020-02-05 13:53:55 +01001325 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001326
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001327 if (uti.getDsPonCTagPriority() != -1) {
1328 selectorBuilder.matchVlanPcp((byte) uti.getDsPonCTagPriority());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001329 }
1330
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001331 if (macAddress != null) {
1332 selectorBuilder.matchEthDst(macAddress);
1333 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001334
1335 TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder()
1336 .popVlan()
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001337 .setOutput(port.number());
Andrea Campanella327c5722020-01-30 11:34:13 +01001338
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001339 treatmentBuilder.writeMetadata(createMetadata(uti.getPonCTag(),
1340 uti.getTechnologyProfileId(),
1341 port.number()), 0);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001342
Andrea Campanella981e86c2021-03-12 11:35:33 +01001343 // Upstream pbit is used to remark inner vlan pbit.
1344 // Upstream is used to avoid trusting the BNG to send the packet with correct pbit.
1345 // this is done because ds mode 0 is used because ds mode 3 or 6 that allow for
1346 // all pbit acceptance are not widely supported by vendors even though present in
1347 // the OMCI spec.
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001348 if (uti.getUsPonCTagPriority() != -1) {
1349 treatmentBuilder.setVlanPcp((byte) uti.getUsPonCTagPriority());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001350 }
1351
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001352 if (!VlanId.NONE.equals(uti.getUniTagMatch()) &&
1353 uti.getPonCTag().toShort() != VlanId.ANY_VALUE) {
1354 treatmentBuilder.setVlanId(uti.getUniTagMatch());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001355 }
1356
yasin saplib4b8ee12021-06-13 18:25:20 +00001357 DefaultAnnotations.Builder annotationBuilder = DefaultAnnotations.builder();
1358
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001359 if (downstreamMeterId != null) {
1360 treatmentBuilder.meter(downstreamMeterId);
yasin saplib4b8ee12021-06-13 18:25:20 +00001361 annotationBuilder.set(DOWNSTREAM_ONU, downstreamMeterId.toString());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001362 }
1363
yasin saplib4b8ee12021-06-13 18:25:20 +00001364 if (downstreamOltMeterId != null) {
1365 treatmentBuilder.meter(downstreamOltMeterId);
1366 annotationBuilder.set(DOWNSTREAM_OLT, downstreamOltMeterId.toString());
1367 }
1368
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001369 DefaultForwardingObjective.Builder flowBuilder = createForwardingObjectiveBuilder(selectorBuilder.build(),
1370 treatmentBuilder.build(), MIN_PRIORITY, annotationBuilder.build());
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001371
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001372 ObjectiveContext context = new ObjectiveContext() {
1373 @Override
1374 public void onSuccess(Objective objective) {
1375 log.info("{} Downstream Data plane filter for {}.",
1376 completeFlowOpToString(action), sk);
1377 }
1378
1379 @Override
1380 public void onError(Objective objective, ObjectiveError error) {
1381 log.info("Downstream Data plane filter for {} failed {} because {}.",
1382 sk, action, error);
1383 updateConnectPointStatus(sk, null, OltFlowsStatus.ERROR, null);
1384 }
1385 };
1386
1387 ForwardingObjective flow = null;
1388 if (action == FlowOperation.ADD) {
1389 flow = flowBuilder.add(context);
1390 } else if (action == FlowOperation.REMOVE) {
1391 flow = flowBuilder.remove(context);
1392 } else {
1393 log.error("Flow action not supported: {}", action);
1394 }
1395
1396 if (flow != null) {
1397 if (log.isTraceEnabled()) {
1398 log.trace("Forwarding rule {}", flow);
1399 }
1400 flowObjectiveService.forward(deviceId, flow);
1401 }
Andrea Campanella600d2e22020-06-22 11:00:31 +02001402 }
1403
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001404 private DefaultForwardingObjective.Builder createForwardingObjectiveBuilder(TrafficSelector selector,
1405 TrafficTreatment treatment,
yasin saplib4b8ee12021-06-13 18:25:20 +00001406 Integer priority,
1407 Annotations annotations) {
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001408 return DefaultForwardingObjective.builder()
1409 .withFlag(ForwardingObjective.Flag.VERSATILE)
1410 .withPriority(priority)
1411 .makePermanent()
1412 .withSelector(selector)
yasin saplib4b8ee12021-06-13 18:25:20 +00001413 .withAnnotations(annotations)
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001414 .fromApp(appId)
1415 .withTreatment(treatment);
1416 }
1417
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001418 private Long createMetadata(VlanId innerVlan, int techProfileId, PortNumber egressPort) {
1419 if (techProfileId == NONE_TP_ID) {
Andrea Campanella7c49b792020-05-11 11:36:53 +02001420 techProfileId = DEFAULT_TP_ID_DEFAULT;
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001421 }
1422
1423 return ((long) (innerVlan.id()) << 48 | (long) techProfileId << 32) | egressPort.toLong();
1424 }
1425
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001426 private boolean isMacLearningEnabled(SubscriberAndDeviceInformation si) {
1427 AtomicBoolean requiresMacLearning = new AtomicBoolean();
1428 requiresMacLearning.set(false);
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001429
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001430 si.uniTagList().forEach(uniTagInfo -> {
1431 if (uniTagInfo.getEnableMacLearning()) {
1432 requiresMacLearning.set(true);
1433 }
1434 });
1435
1436 return requiresMacLearning.get();
1437 }
1438
1439 /**
1440 * Checks whether the subscriber has the MacAddress configured or discovered.
1441 *
1442 * @param deviceId DeviceId for this subscriber
1443 * @param port Port for this subscriber
1444 * @param si SubscriberAndDeviceInformation
1445 * @return boolean
1446 */
1447 protected boolean isMacAddressAvailable(DeviceId deviceId, Port port, SubscriberAndDeviceInformation si) {
1448 AtomicBoolean isConfigured = new AtomicBoolean();
1449 isConfigured.set(true);
1450
1451 si.uniTagList().forEach(uniTagInfo -> {
1452 boolean isMacLearningEnabled = uniTagInfo.getEnableMacLearning();
1453 boolean configureMac = isMacAddressValid(uniTagInfo);
1454 boolean discoveredMac = false;
1455 Optional<Host> optHost = hostService.getConnectedHosts(new ConnectPoint(deviceId, port.number()))
1456 .stream().filter(host -> host.vlan().equals(uniTagInfo.getPonCTag())).findFirst();
1457 if (optHost.isPresent() && optHost.get().mac() != null) {
1458 discoveredMac = true;
1459 }
1460 if (isMacLearningEnabled && !configureMac && !discoveredMac) {
1461 log.debug("Awaiting for macAddress on {} for service {}",
1462 portWithName(port), uniTagInfo.getServiceName());
1463 isConfigured.set(false);
1464 }
1465 });
1466
1467 return isConfigured.get();
1468 }
1469
1470 protected MacAddress getMacAddress(DeviceId deviceId, Port port, UniTagInformation uniTagInfo) {
1471 boolean configuredMac = isMacAddressValid(uniTagInfo);
1472 if (configuredMac) {
1473 return MacAddress.valueOf(uniTagInfo.getConfiguredMacAddress());
1474 } else if (uniTagInfo.getEnableMacLearning()) {
1475 Optional<Host> optHost = hostService.getConnectedHosts(new ConnectPoint(deviceId, port.number()))
1476 .stream().filter(host -> host.vlan().equals(uniTagInfo.getPonCTag())).findFirst();
1477 if (optHost.isPresent() && optHost.get().mac() != null) {
1478 return optHost.get().mac();
1479 }
1480 }
1481 return null;
1482 }
1483
1484 private boolean isMacAddressValid(UniTagInformation tagInformation) {
1485 return tagInformation.getConfiguredMacAddress() != null &&
1486 !tagInformation.getConfiguredMacAddress().trim().equals("") &&
1487 !MacAddress.NONE.equals(MacAddress.valueOf(tagInformation.getConfiguredMacAddress()));
1488 }
1489
1490 protected void updateConnectPointStatus(ServiceKey key, OltFlowsStatus eapolStatus,
1491 OltFlowsStatus subscriberFlowsStatus, OltFlowsStatus dhcpStatus) {
Matteo Scandolo2542e5d2021-12-01 16:53:41 -08001492 if (log.isTraceEnabled()) {
1493 log.trace("Updating cpStatus {} with values: eapolFlow={}, subscriberFlows={}, dhcpFlow={}",
1494 key, eapolStatus, subscriberFlowsStatus, dhcpStatus);
1495 }
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001496 try {
1497 cpStatusWriteLock.lock();
1498 OltPortStatus status = cpStatus.get(key);
1499
Matteo Scandolo2542e5d2021-12-01 16:53:41 -08001500
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001501 if (status == null) {
Matteo Scandolo2542e5d2021-12-01 16:53:41 -08001502 // if we don't have status for the connectPoint
1503 // and we're only updating status to PENDING_REMOVE or ERROR
1504 // do not create it. This is because this case will only happen when a device is removed
1505 // and it's status cleaned
1506 List<OltFlowsStatus> statusesToIgnore = new ArrayList<>();
1507 statusesToIgnore.add(OltFlowsStatus.PENDING_REMOVE);
1508 statusesToIgnore.add(OltFlowsStatus.ERROR);
1509
1510 if (
1511 (statusesToIgnore.contains(subscriberFlowsStatus) && dhcpStatus == null) ||
1512 (subscriberFlowsStatus == null && statusesToIgnore.contains(dhcpStatus))
1513 ) {
1514 if (log.isTraceEnabled()) {
1515 log.trace("Ignoring cpStatus update as status is meaningless");
1516 }
1517 return;
1518 }
1519
Matteo Scandoloaa2adde2021-09-13 12:45:32 -07001520 status = new OltPortStatus(
1521 eapolStatus != null ? eapolStatus : OltFlowsStatus.NONE,
1522 subscriberFlowsStatus != null ? subscriberFlowsStatus : OltFlowsStatus.NONE,
1523 dhcpStatus != null ? dhcpStatus : OltFlowsStatus.NONE
1524 );
1525 } else {
1526 if (eapolStatus != null) {
1527 status.defaultEapolStatus = eapolStatus;
1528 }
1529 if (subscriberFlowsStatus != null) {
1530 status.subscriberFlowsStatus = subscriberFlowsStatus;
1531 }
1532 if (dhcpStatus != null) {
1533 status.dhcpStatus = dhcpStatus;
1534 }
1535 }
1536
1537 cpStatus.put(key, status);
1538 } finally {
1539 cpStatusWriteLock.unlock();
1540 }
1541 }
1542
1543 protected class InternalFlowListener implements FlowRuleListener {
1544 @Override
1545 public void event(FlowRuleEvent event) {
1546 if (appId.id() != (event.subject().appId())) {
1547 return;
1548 }
1549
1550 if (!oltDeviceService.isLocalLeader(event.subject().deviceId())) {
1551 if (log.isTraceEnabled()) {
1552 log.trace("ignoring flow event {} " +
1553 "as not leader for {}", event, event.subject().deviceId());
1554 }
1555 return;
1556 }
1557
1558 switch (event.type()) {
1559 case RULE_ADDED:
1560 case RULE_REMOVED:
1561 Port port = getCpFromFlowRule(event.subject());
1562 if (port == null) {
1563 log.error("Can't find port in flow {}", event.subject());
1564 return;
1565 }
1566 if (log.isTraceEnabled()) {
1567 log.trace("flow event {} on cp {}: {}", event.type(),
1568 portWithName(port), event.subject());
1569 }
1570 updateCpStatus(event.type(), port, event.subject());
1571 return;
1572 case RULE_ADD_REQUESTED:
1573 case RULE_REMOVE_REQUESTED:
1574 // NOTE that PENDING_ADD/REMOVE is set when we create the flowObjective
1575 return;
1576 default:
1577 return;
1578 }
1579 }
1580
1581 protected void updateCpStatus(FlowRuleEvent.Type type, Port port, FlowRule flowRule) {
1582 OltFlowsStatus status = flowRuleStatusToOltFlowStatus(type);
1583 if (isDefaultEapolFlow(flowRule)) {
1584 ServiceKey sk = new ServiceKey(new AccessDevicePort(port),
1585 defaultEapolUniTag);
1586 if (log.isTraceEnabled()) {
1587 log.trace("update defaultEapolStatus {} on {}", status, sk);
1588 }
1589 updateConnectPointStatus(sk, status, null, null);
1590 } else if (isDhcpFlow(flowRule)) {
1591 ServiceKey sk = getSubscriberKeyFromFlowRule(flowRule);
1592 if (sk == null) {
1593 return;
1594 }
1595 if (log.isTraceEnabled()) {
1596 log.trace("update dhcpStatus {} on {}", status, sk);
1597 }
1598 updateConnectPointStatus(sk, null, null, status);
1599 } else if (isDataFlow(flowRule)) {
1600
1601 if (oltDeviceService.isNniPort(deviceService.getDevice(flowRule.deviceId()),
1602 getCpFromFlowRule(flowRule).number())) {
1603 // the NNI has data-plane for every subscriber, doesn't make sense to track them
1604 return;
1605 }
1606
1607 ServiceKey sk = getSubscriberKeyFromFlowRule(flowRule);
1608 if (sk == null) {
1609 return;
1610 }
1611 if (log.isTraceEnabled()) {
1612 log.trace("update dataplaneStatus {} on {}", status, sk);
1613 }
1614 updateConnectPointStatus(sk, null, status, null);
1615 }
1616 }
1617
1618 private boolean isDefaultEapolFlow(FlowRule flowRule) {
1619 EthTypeCriterion c = (EthTypeCriterion) flowRule.selector().getCriterion(Criterion.Type.ETH_TYPE);
1620 if (c == null) {
1621 return false;
1622 }
1623 if (c.ethType().equals(EthType.EtherType.EAPOL.ethType())) {
1624 AtomicBoolean isDefault = new AtomicBoolean(false);
1625 flowRule.treatment().allInstructions().forEach(instruction -> {
1626 if (instruction.type() == L2MODIFICATION) {
1627 L2ModificationInstruction modificationInstruction = (L2ModificationInstruction) instruction;
1628 if (modificationInstruction.subtype() == L2ModificationInstruction.L2SubType.VLAN_ID) {
1629 L2ModificationInstruction.ModVlanIdInstruction vlanInstruction =
1630 (L2ModificationInstruction.ModVlanIdInstruction) modificationInstruction;
1631 if (vlanInstruction.vlanId().id().equals(EAPOL_DEFAULT_VLAN)) {
1632 isDefault.set(true);
1633 return;
1634 }
1635 }
1636 }
1637 });
1638 return isDefault.get();
1639 }
1640 return false;
1641 }
1642
1643 /**
1644 * Returns true if the flow is a DHCP flow.
1645 * Matches both upstream and downstream flows.
1646 *
1647 * @param flowRule The FlowRule to evaluate
1648 * @return boolean
1649 */
1650 private boolean isDhcpFlow(FlowRule flowRule) {
1651 IPProtocolCriterion ipCriterion = (IPProtocolCriterion) flowRule.selector()
1652 .getCriterion(Criterion.Type.IP_PROTO);
1653 if (ipCriterion == null) {
1654 return false;
1655 }
1656
1657 UdpPortCriterion src = (UdpPortCriterion) flowRule.selector().getCriterion(Criterion.Type.UDP_SRC);
1658
1659 if (src == null) {
1660 return false;
1661 }
1662 return ipCriterion.protocol() == IPv4.PROTOCOL_UDP &&
1663 (src.udpPort().toInt() == 68 || src.udpPort().toInt() == 67);
1664 }
1665
1666 private boolean isDataFlow(FlowRule flowRule) {
1667 // we consider subscriber flows the one that matches on VLAN_VID
1668 // method is valid only because it's the last check after EAPOL and DHCP.
1669 // this matches mcast flows as well, if we want to avoid that we can
1670 // filter out the elements that have groups in the treatment or
1671 // mcastIp in the selector
1672 // IPV4_DST:224.0.0.22/32
1673 // treatment=[immediate=[GROUP:0x1]]
1674
1675 return flowRule.selector().getCriterion(Criterion.Type.VLAN_VID) != null;
1676 }
1677
1678 private Port getCpFromFlowRule(FlowRule flowRule) {
1679 DeviceId deviceId = flowRule.deviceId();
1680 PortCriterion inPort = (PortCriterion) flowRule.selector().getCriterion(Criterion.Type.IN_PORT);
1681 if (inPort != null) {
1682 PortNumber port = inPort.port();
1683 return deviceService.getPort(deviceId, port);
1684 }
1685 return null;
1686 }
1687
1688 private ServiceKey getSubscriberKeyFromFlowRule(FlowRule flowRule) {
1689 Port flowPort = getCpFromFlowRule(flowRule);
1690 SubscriberAndDeviceInformation si = subsService.get(getPortName(flowPort));
1691
1692 Boolean isNni = oltDeviceService.isNniPort(deviceService.getDevice(flowRule.deviceId()), flowPort.number());
1693 if (si == null && !isNni) {
1694 log.error("Subscriber information not found in sadis for port {}", portWithName(flowPort));
1695 return null;
1696 }
1697
1698 if (isNni) {
1699 return new ServiceKey(new AccessDevicePort(flowPort), nniUniTag);
1700 }
1701
1702 Optional<UniTagInformation> found = Optional.empty();
1703 VlanId flowVlan = null;
1704 if (isDhcpFlow(flowRule)) {
1705 // we need to make a special case for DHCP as in the ATT workflow DHCP flows don't match on tags
1706 L2ModificationInstruction.ModVlanIdInstruction instruction =
1707 (L2ModificationInstruction.ModVlanIdInstruction) flowRule.treatment().immediate().get(1);
1708 flowVlan = instruction.vlanId();
1709 } else {
1710 // for now we assume that if it's not DHCP it's dataplane (or at least tagged)
1711 VlanIdCriterion vlanIdCriterion =
1712 (VlanIdCriterion) flowRule.selector().getCriterion(Criterion.Type.VLAN_VID);
1713 if (vlanIdCriterion == null) {
1714 log.warn("cannot match the flow to a subscriber service as it does not carry vlans");
1715 return null;
1716 }
1717 flowVlan = vlanIdCriterion.vlanId();
1718 }
1719
1720 VlanId finalFlowVlan = flowVlan;
1721 found = si.uniTagList().stream().filter(uti ->
1722 uti.getPonCTag().equals(finalFlowVlan) ||
1723 uti.getPonSTag().equals(finalFlowVlan) ||
1724 uti.getUniTagMatch().equals(finalFlowVlan)
1725 ).findFirst();
1726
1727
1728 if (found.isEmpty()) {
1729 log.warn("Cannot map flow rule {} to Service in {}", flowRule, si);
1730 }
1731
1732 return found.isPresent() ? new ServiceKey(new AccessDevicePort(flowPort), found.get()) : null;
1733
1734 }
1735
1736 private OltFlowsStatus flowRuleStatusToOltFlowStatus(FlowRuleEvent.Type type) {
1737 switch (type) {
1738 case RULE_ADD_REQUESTED:
1739 return OltFlowsStatus.PENDING_ADD;
1740 case RULE_ADDED:
1741 return OltFlowsStatus.ADDED;
1742 case RULE_REMOVE_REQUESTED:
1743 return OltFlowsStatus.PENDING_REMOVE;
1744 case RULE_REMOVED:
1745 return OltFlowsStatus.REMOVED;
1746 default:
1747 return OltFlowsStatus.NONE;
1748 }
1749 }
1750 }
1751
1752 protected void bindSadisService(SadisService service) {
1753 this.subsService = service.getSubscriberInfoService();
1754 this.bpService = service.getBandwidthProfileService();
1755 log.info("Sadis service is loaded");
1756 }
1757
1758 protected void unbindSadisService(SadisService service) {
1759 this.subsService = null;
1760 this.bpService = null;
1761 log.info("Sadis service is unloaded");
1762 }
Andrea Campanellacbbb7952019-11-25 06:38:41 +00001763}