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