blob: afe05f093c1d9d78683298a7f6d66b6768406ca6 [file] [log] [blame]
Yi Tseng51301292017-07-28 13:02:59 -07001/*
2 * Copyright 2017-present Open Networking Foundation
3 *
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 *
16 */
Yi Tseng51301292017-07-28 13:02:59 -070017package org.onosproject.dhcprelay;
18
Yi Tseng525ff402017-10-23 19:39:39 -070019import com.google.common.collect.HashMultimap;
Yi Tseng919b2df2017-09-07 16:22:51 -070020import com.google.common.collect.Lists;
Yi Tseng525ff402017-10-23 19:39:39 -070021import com.google.common.collect.Multimap;
Charles Chan70fdd492018-03-07 17:36:06 -080022import com.google.common.collect.Multimaps;
Kalhee Kim45fede42017-09-05 19:05:06 +000023import com.google.common.collect.Sets;
24import com.google.common.collect.ImmutableSet;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070025import org.osgi.service.component.annotations.Activate;
26import org.osgi.service.component.annotations.Component;
27import org.osgi.service.component.annotations.Deactivate;
28import org.osgi.service.component.annotations.Modified;
29import org.osgi.service.component.annotations.Reference;
30import org.osgi.service.component.annotations.ReferenceCardinality;
Yi Tseng51301292017-07-28 13:02:59 -070031import org.onlab.packet.BasePacket;
Kalhee Kim45fede42017-09-05 19:05:06 +000032import org.onlab.packet.DHCP6;
33import org.onlab.packet.IPv6;
34import org.onlab.packet.Ethernet;
35import org.onlab.packet.Ip6Address;
Yi Tseng51301292017-07-28 13:02:59 -070036import org.onlab.packet.IpAddress;
Kalhee Kim45fede42017-09-05 19:05:06 +000037import org.onlab.packet.IpPrefix;
Yi Tseng51301292017-07-28 13:02:59 -070038import org.onlab.packet.MacAddress;
Yi Tseng525ff402017-10-23 19:39:39 -070039import org.onlab.packet.TpPort;
Kalhee Kim45fede42017-09-05 19:05:06 +000040import org.onlab.packet.UDP;
Yi Tseng51301292017-07-28 13:02:59 -070041import org.onlab.packet.VlanId;
Lior Assoulinea21c0ca2018-01-28 16:18:48 -080042import org.onlab.packet.dhcp.Dhcp6ClientDataOption;
43import org.onlab.packet.dhcp.Dhcp6LeaseQueryOption;
Kalhee Kim45fede42017-09-05 19:05:06 +000044import org.onlab.packet.dhcp.Dhcp6RelayOption;
45import org.onlab.packet.dhcp.Dhcp6InterfaceIdOption;
Lior Assoulinea21c0ca2018-01-28 16:18:48 -080046import org.onlab.packet.dhcp.Dhcp6Option;
Kalhee Kim45fede42017-09-05 19:05:06 +000047import org.onlab.packet.dhcp.Dhcp6IaNaOption;
48import org.onlab.packet.dhcp.Dhcp6IaTaOption;
49import org.onlab.packet.dhcp.Dhcp6IaPdOption;
50import org.onlab.packet.dhcp.Dhcp6IaAddressOption;
51import org.onlab.packet.dhcp.Dhcp6IaPrefixOption;
Kalhee Kimea4b6c22017-11-09 14:38:37 +000052import org.onlab.packet.dhcp.Dhcp6ClientIdOption;
53import org.onlab.packet.dhcp.Dhcp6Duid;
Kalhee Kim495c9b22017-11-07 16:32:09 +000054import org.onlab.packet.DHCP6.MsgType;
Kalhee Kim45fede42017-09-05 19:05:06 +000055import org.onlab.util.HexString;
Taras Lemkin96a0d342018-03-26 14:52:58 +000056import org.onlab.util.Tools;
57import org.onosproject.cfg.ComponentConfigService;
Yi Tseng525ff402017-10-23 19:39:39 -070058import org.onosproject.core.ApplicationId;
59import org.onosproject.core.CoreService;
Yi Tseng51301292017-07-28 13:02:59 -070060import org.onosproject.dhcprelay.api.DhcpHandler;
Yi Tseng919b2df2017-09-07 16:22:51 -070061import org.onosproject.dhcprelay.api.DhcpServerInfo;
Yi Tseng525ff402017-10-23 19:39:39 -070062import org.onosproject.dhcprelay.config.IgnoreDhcpConfig;
Kalhee Kim45fede42017-09-05 19:05:06 +000063import org.onosproject.dhcprelay.store.DhcpRelayStore;
Kalhee Kimea4b6c22017-11-09 14:38:37 +000064import org.onosproject.dhcprelay.store.DhcpRecord;
Kalhee Kimba366062017-11-07 16:32:09 +000065import org.onosproject.dhcprelay.store.DhcpFpmPrefixStore;
Kalhee Kimd94ceea2017-11-29 19:03:02 +000066import org.onosproject.dhcprelay.store.DhcpRelayCountersStore;
Yi Tseng525ff402017-10-23 19:39:39 -070067import org.onosproject.net.Device;
68import org.onosproject.net.DeviceId;
Kalhee Kimba366062017-11-07 16:32:09 +000069import org.onosproject.routing.fpm.api.FpmRecord;
Yi Tseng525ff402017-10-23 19:39:39 -070070import org.onosproject.net.behaviour.Pipeliner;
71import org.onosproject.net.device.DeviceService;
72import org.onosproject.net.flow.DefaultTrafficSelector;
73import org.onosproject.net.flow.TrafficSelector;
74import org.onosproject.net.flowobjective.DefaultForwardingObjective;
75import org.onosproject.net.flowobjective.FlowObjectiveService;
76import org.onosproject.net.flowobjective.ForwardingObjective;
77import org.onosproject.net.flowobjective.Objective;
78import org.onosproject.net.flowobjective.ObjectiveContext;
79import org.onosproject.net.flowobjective.ObjectiveError;
Yi Tsengaa417a62017-09-08 17:22:51 -070080import org.onosproject.net.host.HostProvider;
81import org.onosproject.net.host.HostProviderRegistry;
82import org.onosproject.net.host.HostProviderService;
Kalhee Kim45fede42017-09-05 19:05:06 +000083import org.onosproject.net.host.HostService;
84import org.onosproject.net.host.DefaultHostDescription;
85import org.onosproject.net.host.HostDescription;
Kalhee Kim45fede42017-09-05 19:05:06 +000086import org.onosproject.net.host.HostListener;
87import org.onosproject.net.host.HostEvent;
88import org.onosproject.net.intf.Interface;
89import org.onosproject.net.intf.InterfaceService;
Yi Tseng525ff402017-10-23 19:39:39 -070090import org.onosproject.net.packet.PacketPriority;
Yi Tsengaa417a62017-09-08 17:22:51 -070091import org.onosproject.net.provider.ProviderId;
Kalhee Kim45fede42017-09-05 19:05:06 +000092import org.onosproject.routeservice.Route;
93import org.onosproject.routeservice.RouteStore;
Yi Tseng483ac6f2017-08-02 15:03:31 -070094import org.onosproject.dhcprelay.config.DhcpServerConfig;
Yi Tseng51301292017-07-28 13:02:59 -070095import org.onosproject.net.ConnectPoint;
Kalhee Kim45fede42017-09-05 19:05:06 +000096import org.onosproject.net.Host;
97import org.onosproject.net.HostId;
98import org.onosproject.net.HostLocation;
99import org.onosproject.net.packet.DefaultOutboundPacket;
100import org.onosproject.net.packet.OutboundPacket;
Yi Tseng51301292017-07-28 13:02:59 -0700101import org.onosproject.net.packet.PacketContext;
Kalhee Kim45fede42017-09-05 19:05:06 +0000102import org.onosproject.net.packet.PacketService;
Taras Lemkin96a0d342018-03-26 14:52:58 +0000103import org.osgi.service.component.ComponentContext;
Kalhee Kim45fede42017-09-05 19:05:06 +0000104import org.slf4j.Logger;
105import org.slf4j.LoggerFactory;
106import org.onosproject.net.flow.DefaultTrafficTreatment;
107import org.onosproject.net.flow.TrafficTreatment;
Kalhee Kim45fede42017-09-05 19:05:06 +0000108import java.nio.ByteBuffer;
Taras Lemkin96a0d342018-03-26 14:52:58 +0000109import java.util.ArrayList;
Yi Tseng483ac6f2017-08-02 15:03:31 -0700110import java.util.Collection;
Taras Lemkin96a0d342018-03-26 14:52:58 +0000111import java.util.Dictionary;
112import java.util.List;
Yi Tseng51301292017-07-28 13:02:59 -0700113import java.util.Optional;
Kalhee Kim45fede42017-09-05 19:05:06 +0000114import java.util.Set;
Charles Chan909cff82018-03-05 13:14:02 -0800115import java.util.concurrent.CopyOnWriteArrayList;
Jordan Halterman6328db72018-04-10 13:34:50 -0400116import java.util.concurrent.Executor;
Yi Tseng525ff402017-10-23 19:39:39 -0700117import java.util.concurrent.atomic.AtomicInteger;
Kalhee Kim45fede42017-09-05 19:05:06 +0000118import static com.google.common.base.Preconditions.checkNotNull;
119import static com.google.common.base.Preconditions.checkState;
Jordan Halterman6328db72018-04-10 13:34:50 -0400120import static java.util.concurrent.Executors.newSingleThreadExecutor;
121import static org.onlab.util.Tools.groupedThreads;
Ray Milkey687c00c2018-10-31 10:18:41 -0700122import static org.onosproject.dhcprelay.OsgiPropertyConstants.LEARN_ROUTE_FROM_LEASE_QUERY;
123import static org.onosproject.dhcprelay.OsgiPropertyConstants.LEARN_ROUTE_FROM_LEASE_QUERY_DEFAULT;
Yi Tseng525ff402017-10-23 19:39:39 -0700124import static org.onosproject.net.flowobjective.Objective.Operation.ADD;
125import static org.onosproject.net.flowobjective.Objective.Operation.REMOVE;
Kalhee Kimd94ceea2017-11-29 19:03:02 +0000126import java.util.concurrent.Semaphore;
Yi Tseng51301292017-07-28 13:02:59 -0700127
Ray Milkey687c00c2018-10-31 10:18:41 -0700128@Component(
129 service = { DhcpHandler.class, HostProvider.class },
130 property = {
Ray Milkey5504bd22019-03-22 16:24:38 -0700131 "_version:Integer = 6",
Ray Milkey687c00c2018-10-31 10:18:41 -0700132 LEARN_ROUTE_FROM_LEASE_QUERY + ":Boolean=" + LEARN_ROUTE_FROM_LEASE_QUERY_DEFAULT
133 }
134)
135
Yi Tsengaa417a62017-09-08 17:22:51 -0700136public class Dhcp6HandlerImpl implements DhcpHandler, HostProvider {
Charles Chand988c282017-09-12 17:09:32 -0700137 public static final String DHCP_V6_RELAY_APP = "org.onosproject.Dhcp6HandlerImpl";
Saurav Das7c6dec12017-09-13 14:35:56 -0700138 public static final ProviderId PROVIDER_ID = new ProviderId("dhcp6", DHCP_V6_RELAY_APP);
Yi Tseng525ff402017-10-23 19:39:39 -0700139 private static final int IGNORE_CONTROL_PRIORITY = PacketPriority.CONTROL.priorityValue() + 1000;
Kalhee Kimd94ceea2017-11-29 19:03:02 +0000140 private String gCount = "global";
Yi Tseng525ff402017-10-23 19:39:39 -0700141 private static final TrafficSelector CLIENT_SERVER_SELECTOR = DefaultTrafficSelector.builder()
142 .matchEthType(Ethernet.TYPE_IPV6)
143 .matchIPProtocol(IPv6.PROTOCOL_UDP)
144 .matchIPv6Src(IpPrefix.IPV6_LINK_LOCAL_PREFIX)
145 .matchIPv6Dst(Ip6Address.ALL_DHCP_RELAY_AGENTS_AND_SERVERS.toIpPrefix())
146 .matchUdpSrc(TpPort.tpPort(UDP.DHCP_V6_CLIENT_PORT))
147 .matchUdpDst(TpPort.tpPort(UDP.DHCP_V6_SERVER_PORT))
148 .build();
149 private static final TrafficSelector SERVER_RELAY_SELECTOR = DefaultTrafficSelector.builder()
150 .matchEthType(Ethernet.TYPE_IPV6)
151 .matchIPProtocol(IPv6.PROTOCOL_UDP)
152 .matchUdpSrc(TpPort.tpPort(UDP.DHCP_V6_SERVER_PORT))
153 .matchUdpDst(TpPort.tpPort(UDP.DHCP_V6_SERVER_PORT))
154 .build();
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800155 // lease query reply is from server to client (no relay in between) - so we need to
156 // catch that scenario also ..
157 private static final TrafficSelector LEASE_QUERY_RESPONSE_SELECTOR = DefaultTrafficSelector.builder()
158 .matchEthType(Ethernet.TYPE_IPV6)
159 .matchIPProtocol(IPv6.PROTOCOL_UDP)
160 .matchUdpSrc(TpPort.tpPort(UDP.DHCP_V6_SERVER_PORT))
161 .matchUdpDst(TpPort.tpPort(UDP.DHCP_V6_CLIENT_PORT))
162 .build();
Yi Tseng525ff402017-10-23 19:39:39 -0700163 static final Set<TrafficSelector> DHCP_SELECTORS = ImmutableSet.of(
164 CLIENT_SERVER_SELECTOR,
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800165 SERVER_RELAY_SELECTOR,
166 LEASE_QUERY_RESPONSE_SELECTOR
Yi Tseng525ff402017-10-23 19:39:39 -0700167 );
Kalhee Kim45fede42017-09-05 19:05:06 +0000168 private static Logger log = LoggerFactory.getLogger(Dhcp6HandlerImpl.class);
Yi Tseng51301292017-07-28 13:02:59 -0700169
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700170 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Kalhee Kim45fede42017-09-05 19:05:06 +0000171 protected DhcpRelayStore dhcpRelayStore;
Yi Tseng51301292017-07-28 13:02:59 -0700172
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700173 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Kalhee Kimd94ceea2017-11-29 19:03:02 +0000174 protected DhcpRelayCountersStore dhcpRelayCountersStore;
175
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700176 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Kalhee Kim45fede42017-09-05 19:05:06 +0000177 protected PacketService packetService;
178
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700179 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Kalhee Kim45fede42017-09-05 19:05:06 +0000180 protected RouteStore routeStore;
181
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700182 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Kalhee Kim45fede42017-09-05 19:05:06 +0000183 protected InterfaceService interfaceService;
184
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700185 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Kalhee Kim45fede42017-09-05 19:05:06 +0000186 protected HostService hostService;
187
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700188 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Yi Tsengaa417a62017-09-08 17:22:51 -0700189 protected HostProviderRegistry providerRegistry;
Kalhee Kim45fede42017-09-05 19:05:06 +0000190
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700191 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Yi Tseng525ff402017-10-23 19:39:39 -0700192 protected CoreService coreService;
193
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700194 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Kalhee Kimba366062017-11-07 16:32:09 +0000195 protected DhcpFpmPrefixStore dhcpFpmPrefixStore;
196
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700197 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Yi Tseng525ff402017-10-23 19:39:39 -0700198 protected DeviceService deviceService;
199
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700200 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Yi Tseng525ff402017-10-23 19:39:39 -0700201 protected FlowObjectiveService flowObjectiveService;
202
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700203 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Taras Lemkin96a0d342018-03-26 14:52:58 +0000204 protected ComponentConfigService cfgService;
205
Ray Milkey687c00c2018-10-31 10:18:41 -0700206 /** Enable learning routing information from LQ. */
207 private Boolean learnRouteFromLeasequery = LEARN_ROUTE_FROM_LEASE_QUERY_DEFAULT;
Taras Lemkin96a0d342018-03-26 14:52:58 +0000208
Yi Tsengaa417a62017-09-08 17:22:51 -0700209 protected HostProviderService providerService;
Yi Tseng525ff402017-10-23 19:39:39 -0700210 protected ApplicationId appId;
Charles Chan70fdd492018-03-07 17:36:06 -0800211 protected Multimap<DeviceId, VlanId> ignoredVlans = Multimaps.synchronizedMultimap(HashMultimap.create());
Yi Tseng525ff402017-10-23 19:39:39 -0700212 private InternalHostListener hostListener = new InternalHostListener();
Kalhee Kimba366062017-11-07 16:32:09 +0000213 private Boolean dhcpFpmEnabled = false;
Charles Chan909cff82018-03-05 13:14:02 -0800214 private List<DhcpServerInfo> defaultServerInfoList = new CopyOnWriteArrayList<>();
215 private List<DhcpServerInfo> indirectServerInfoList = new CopyOnWriteArrayList<>();
Jordan Halterman6328db72018-04-10 13:34:50 -0400216
217 private Executor hostEventExecutor = newSingleThreadExecutor(
218 groupedThreads("dhcp6-event-host", "%d", log));
219
Kalhee Kim495c9b22017-11-07 16:32:09 +0000220 private class IpAddressInfo {
221 Ip6Address ip6Address;
222 long prefTime;
223 }
224 private class PdPrefixInfo {
225 IpPrefix pdPrefix;
226 long prefTime;
227 }
228 protected int dhcp6PollInterval = 24 * 3600; // 24 hr period
229
Kalhee Kimd94ceea2017-11-29 19:03:02 +0000230 // max 1 thread
231 static Semaphore recordSemaphore = new Semaphore(1);
Kalhee Kim45fede42017-09-05 19:05:06 +0000232
233 // CLIENT message types
234 public static final Set<Byte> MSG_TYPE_FROM_CLIENT =
235 ImmutableSet.of(DHCP6.MsgType.SOLICIT.value(),
236 DHCP6.MsgType.REQUEST.value(),
237 DHCP6.MsgType.REBIND.value(),
238 DHCP6.MsgType.RENEW.value(),
239 DHCP6.MsgType.RELEASE.value(),
240 DHCP6.MsgType.DECLINE.value(),
241 DHCP6.MsgType.CONFIRM.value(),
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800242 DHCP6.MsgType.RELAY_FORW.value(),
243 DHCP6.MsgType.LEASEQUERY.value());
Kalhee Kim45fede42017-09-05 19:05:06 +0000244 // SERVER message types
245 public static final Set<Byte> MSG_TYPE_FROM_SERVER =
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800246 ImmutableSet.of(DHCP6.MsgType.RELAY_REPL.value(),
247 DHCP6.MsgType.LEASEQUERY_REPLY.value());
Kalhee Kim45fede42017-09-05 19:05:06 +0000248
249 @Activate
Taras Lemkin96a0d342018-03-26 14:52:58 +0000250 protected void activate(ComponentContext context) {
251 cfgService.registerProperties(getClass());
252 modified(context);
Yi Tseng525ff402017-10-23 19:39:39 -0700253 appId = coreService.registerApplication(DHCP_V6_RELAY_APP);
Yi Tsengaa417a62017-09-08 17:22:51 -0700254 providerService = providerRegistry.register(this);
Kalhee Kim45fede42017-09-05 19:05:06 +0000255 hostService.addListener(hostListener);
Yi Tseng51301292017-07-28 13:02:59 -0700256 }
257
Kalhee Kim45fede42017-09-05 19:05:06 +0000258 @Deactivate
259 protected void deactivate() {
Taras Lemkin96a0d342018-03-26 14:52:58 +0000260 cfgService.unregisterProperties(getClass(), false);
Yi Tsengaa417a62017-09-08 17:22:51 -0700261 providerRegistry.unregister(this);
Kalhee Kim45fede42017-09-05 19:05:06 +0000262 hostService.removeListener(hostListener);
Yi Tseng919b2df2017-09-07 16:22:51 -0700263 defaultServerInfoList.forEach(this::stopMonitoringIps);
Charles Chanfc1c22e2018-07-19 09:52:01 -0700264 defaultServerInfoList.forEach(info -> info.getDhcpServerIp6().ifPresent(this::cancelDhcpPacket));
Yi Tseng919b2df2017-09-07 16:22:51 -0700265 defaultServerInfoList.clear();
266 indirectServerInfoList.forEach(this::stopMonitoringIps);
Charles Chanfc1c22e2018-07-19 09:52:01 -0700267 indirectServerInfoList.forEach(info -> info.getDhcpServerIp6().ifPresent(this::cancelDhcpPacket));
Yi Tseng919b2df2017-09-07 16:22:51 -0700268 indirectServerInfoList.clear();
269 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000270
Taras Lemkin96a0d342018-03-26 14:52:58 +0000271 @Modified
272 protected void modified(ComponentContext context) {
273 Dictionary<?, ?> properties = context.getProperties();
274 Boolean flag;
Ray Milkey687c00c2018-10-31 10:18:41 -0700275 flag = Tools.isPropertyEnabled(properties, LEARN_ROUTE_FROM_LEASE_QUERY);
Taras Lemkin96a0d342018-03-26 14:52:58 +0000276 if (flag != null) {
277 learnRouteFromLeasequery = flag;
278 log.info("Learning routes from DHCP leasequery is {}",
279 learnRouteFromLeasequery ? "enabled" : "disabled");
280 }
281 }
282
Yi Tseng919b2df2017-09-07 16:22:51 -0700283 private void stopMonitoringIps(DhcpServerInfo serverInfo) {
284 serverInfo.getDhcpGatewayIp6().ifPresent(gatewayIp -> {
285 hostService.stopMonitoringIp(gatewayIp);
286 });
287 serverInfo.getDhcpServerIp6().ifPresent(serverIp -> {
288 hostService.stopMonitoringIp(serverIp);
289 });
Yi Tseng51301292017-07-28 13:02:59 -0700290 }
291
Yi Tseng51301292017-07-28 13:02:59 -0700292 @Override
Yi Tseng919b2df2017-09-07 16:22:51 -0700293 public List<DhcpServerInfo> getDefaultDhcpServerInfoList() {
294 return defaultServerInfoList;
Yi Tseng51301292017-07-28 13:02:59 -0700295 }
296
297 @Override
Yi Tseng919b2df2017-09-07 16:22:51 -0700298 public List<DhcpServerInfo> getIndirectDhcpServerInfoList() {
299 return indirectServerInfoList;
Yi Tseng51301292017-07-28 13:02:59 -0700300 }
301
302 @Override
Yi Tseng525ff402017-10-23 19:39:39 -0700303 public void updateIgnoreVlanConfig(IgnoreDhcpConfig config) {
304 if (config == null) {
305 ignoredVlans.forEach(((deviceId, vlanId) -> {
306 processIgnoreVlanRule(deviceId, vlanId, REMOVE);
307 }));
308 return;
309 }
310 config.ignoredVlans().forEach((deviceId, vlanId) -> {
311 if (ignoredVlans.get(deviceId).contains(vlanId)) {
312 // don't need to process if it already ignored
313 return;
314 }
315 processIgnoreVlanRule(deviceId, vlanId, ADD);
316 });
Yi Tseng525ff402017-10-23 19:39:39 -0700317 ignoredVlans.forEach((deviceId, vlanId) -> {
318 if (!config.ignoredVlans().get(deviceId).contains(vlanId)) {
319 // not contains in new config, remove it
320 processIgnoreVlanRule(deviceId, vlanId, REMOVE);
321 }
322 });
323 }
324
325 @Override
Saurav Dasb805f1a2017-12-13 16:19:35 -0800326 public void removeIgnoreVlanState(IgnoreDhcpConfig config) {
327 if (config == null) {
328 ignoredVlans.clear();
329 return;
330 }
331 config.ignoredVlans().forEach((deviceId, vlanId) -> {
332 ignoredVlans.remove(deviceId, vlanId);
333 });
334 }
335
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800336 public DhcpRecord getDhcpRelayRecordFor(Ip6Address clientAddress) {
337
Taras Lemkin96a0d342018-03-26 14:52:58 +0000338 Collection<DhcpRecord> records = dhcpRelayStore.getDhcpRecords();
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800339 DhcpRecord dr = null;
340 for (DhcpRecord e:records) {
341 if (e.ip6Address().isPresent()) {
342 if (e.ip6Address().get().equals(clientAddress)) {
343 dr = e;
344 break;
345 }
346 }
347 }
348 return dr;
349 }
350
351 public MacAddress findNextHopMacForIp6FromRelayStore(Ip6Address clientAddress,
352 MacAddress clientMacAddress, VlanId vlanID) {
353
354 DhcpRecord dr = getDhcpRelayRecordFor(clientAddress);
355
356 if (dr != null) {
357 Optional<MacAddress> nextHopTempMac = dr.nextHopTemp();
358 if (nextHopTempMac.isPresent()) {
359 log.info("findNextHopForIp6FromRelayStore " + clientAddress + " got mac " + nextHopTempMac.toString());
360 return nextHopTempMac.get();
361 }
362 } else {
363 log.warn("findNextHopMacForIp6FromRelayStore could NOT find next hop for " + clientAddress);
364 return null;
365 }
366 return null;
367 }
368
369 public Ip6Address findNextHopIp6FromRelayStore(Ip6Address clientAddress) {
370
371 DhcpRecord dr = getDhcpRelayRecordFor(clientAddress);
372 if (dr != null) {
373 Optional<MacAddress> nextHopMac = dr.nextHop();
374 if (nextHopMac.isPresent()) {
375 // find the local ip6 from the host store
376 HostId gwHostId = HostId.hostId(nextHopMac.get(), dr.vlanId());
377 Host gwHost = hostService.getHost(gwHostId);
378 if (gwHost == null) {
379 log.warn("Can't find next hop host ID {}", gwHostId);
380 return null;
381 }
382 Ip6Address nextHopIp = gwHost.ipAddresses()
383 .stream()
384 .filter(IpAddress::isIp6)
385 .filter(IpAddress::isLinkLocal)
386 .map(IpAddress::getIp6Address)
387 .findFirst()
388 .orElse(null);
389
390 log.info("findNextHopIp6FromRelayStore " + clientAddress + " got mac " +
391 nextHopMac.toString() + " ip6 " + nextHopIp);
392 return nextHopIp;
393 }
394 } else {
395 log.warn("findNextHopIp6FromRelayStore could NOT find next hop for " + clientAddress);
396 return null;
397 }
398 return null;
399 }
400
401 private void setPotentialNextHopForIp6InRelayStore(Ip6Address clientAddress,
402 VlanId vlanId, MacAddress nh) {
403 DhcpRecord dr = getDhcpRelayRecordFor(clientAddress);
404 if (dr != null) {
405 dr.nextHopTemp(nh);
406 log.debug("LQ6 potential NH mac " + nh.toString() + " UPDATED in RelayRecord client " + clientAddress);
407 } else {
408 log.warn("LQ6 potential NH mac" + nh.toString() +
409 " NOT FOUND in RelayRecord for client - LQ rejected" + clientAddress);
410 }
411 }
412
413 public void handleLeaseQuery6ReplyMsg(PacketContext context, DHCP6 dhcp6Payload) {
414 ConnectPoint inPort = context.inPacket().receivedFrom();
415 log.info("Got LQV6-REPLY on port {}", inPort);
416 List<Dhcp6Option> lopt = dhcp6Payload.getOptions();
417 log.info("Options list: {}", lopt);
418 // find out if this lease is known is
419 Dhcp6ClientDataOption clientDataOption = dhcp6Payload.getOptions()
420 .stream()
421 .filter(opt -> opt instanceof Dhcp6ClientDataOption)
422 .map(pld -> (Dhcp6ClientDataOption) pld)
423 .findFirst()
424 .orElse(null);
425
426 if (clientDataOption == null) {
427 log.warn("clientDataOption option is not present, " +
428 "lease is UNKNOWN - not adding any new route...");
429 } else {
430 Dhcp6IaAddressOption aiAddressOption = clientDataOption.getOptions()
431 .stream()
432 .filter(opt -> opt instanceof Dhcp6IaAddressOption)
433 .map(pld -> (Dhcp6IaAddressOption) pld)
434 .findFirst()
435 .orElse(null);
436
437 Dhcp6ClientIdOption clientIdOption = clientDataOption.getOptions()
438 .stream()
439 .filter(opt -> opt instanceof Dhcp6ClientIdOption)
440 .map(pld -> (Dhcp6ClientIdOption) pld)
441 .findFirst()
442 .orElse(null);
443
444 if (aiAddressOption == null) {
445 log.warn("clientDataOption from DHCP server does not " +
446 "contains Dhcp6IaAddressOption for the client - giving up...");
447 } else {
448 Ip6Address clientAddress = aiAddressOption.getIp6Address();
449 MacAddress clientMacAddress = MacAddress.valueOf(clientIdOption.getDuid().getLinkLayerAddress());
450 Ethernet packet = context.inPacket().parsed();
451 VlanId vlanId = VlanId.vlanId(packet.getVlanID());
452 MacAddress potentialNextHopMac =
453 findNextHopMacForIp6FromRelayStore(clientAddress, clientMacAddress, vlanId);
454
455 if (potentialNextHopMac == null) {
456 log.warn("Can't find next hop host mac for client {} mac:{}/{}",
457 clientAddress, clientMacAddress, vlanId);
458 return;
459 } else {
460 log.info("Next hop mac for {}/{}/{} is {}", clientAddress,
461 clientMacAddress, vlanId, potentialNextHopMac.toString());
462 }
463 // search the next hop in the hosts store
464 HostId gwHostId = HostId.hostId(potentialNextHopMac, vlanId);
465 Host gwHost = hostService.getHost(gwHostId);
466 if (gwHost == null) {
467 log.warn("Can't find next hop host ID {}", gwHostId);
468 return;
469 }
470 Ip6Address nextHopIp = gwHost.ipAddresses()
471 .stream()
472 .filter(IpAddress::isIp6)
473 .filter(IpAddress::isLinkLocal)
474 .map(IpAddress::getIp6Address)
475 .findFirst()
476 .orElse(null);
477 if (nextHopIp == null) {
478 log.warn("Can't find IP6 address of next hop {}", gwHost);
479 return;
480 }
481 log.info("client " + clientAddress + " is known !");
Kalhee Kim54a97c92018-04-02 21:23:46 +0000482 Route routeForIP6 = new Route(Route.Source.DHCP, clientAddress.toIpPrefix(), nextHopIp);
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800483 log.debug("updating route of Client for indirectly connected.");
484 log.debug("client ip: " + clientAddress + ", next hop ip6: " + nextHopIp);
485 routeStore.updateRoute(routeForIP6);
486 }
487 }
488 }
489
Saurav Dasb805f1a2017-12-13 16:19:35 -0800490 @Override
Kalhee Kim45fede42017-09-05 19:05:06 +0000491 public void processDhcpPacket(PacketContext context, BasePacket payload) {
492 checkNotNull(payload, "DHCP6 payload can't be null");
493 checkState(payload instanceof DHCP6, "Payload is not a DHCP6");
494 DHCP6 dhcp6Payload = (DHCP6) payload;
495 Ethernet receivedPacket = context.inPacket().parsed();
496
497 if (!configured()) {
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800498 log.warn("Missing DHCP6 relay server config. " +
499 "Abort packet processing dhcp6 payload {}", dhcp6Payload);
Kalhee Kim45fede42017-09-05 19:05:06 +0000500 return;
501 }
Kalhee Kim495c9b22017-11-07 16:32:09 +0000502 byte msgTypeVal = dhcp6Payload.getMsgType();
503 MsgType msgType = DHCP6.MsgType.getType(msgTypeVal);
504 log.debug("msgType is {}", msgType);
Kalhee Kim45fede42017-09-05 19:05:06 +0000505
Kalhee Kim45fede42017-09-05 19:05:06 +0000506 ConnectPoint inPort = context.inPacket().receivedFrom();
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800507
Kalhee Kim495c9b22017-11-07 16:32:09 +0000508 if (inPort == null) {
Taras Lemkin96a0d342018-03-26 14:52:58 +0000509 log.warn("incoming ConnectPoint is null");
Kalhee Kim495c9b22017-11-07 16:32:09 +0000510 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000511 Set<Interface> receivingInterfaces = interfaceService.getInterfacesByPort(inPort);
512 //ignore the packets if dhcp client interface is not configured on onos.
513 if (receivingInterfaces.isEmpty()) {
514 log.warn("Virtual interface is not configured on {}", inPort);
515 return;
516 }
517
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800518 if (msgTypeVal == DHCP6.MsgType.LEASEQUERY.value()) {
Taras Lemkin96a0d342018-03-26 14:52:58 +0000519 List<InternalPacket> ethernetClientPackets =
520 learnRouteFromLeasequery ?
521 processLQ6PacketFromClient(context, receivedPacket, receivingInterfaces, dhcp6Payload) :
522 processDhcp6ForwardOnly(context, receivedPacket, receivingInterfaces, dhcp6Payload);
523 for (InternalPacket internalPacket : ethernetClientPackets) {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000524 forwardPacket(internalPacket);
Kalhee Kim45fede42017-09-05 19:05:06 +0000525 }
Taras Lemkin96a0d342018-03-26 14:52:58 +0000526 } else if (msgTypeVal == DHCP6.MsgType.LEASEQUERY_REPLY.value() && learnRouteFromLeasequery) {
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800527 IPv6 clientIpv6 = (IPv6) receivedPacket.getPayload();
528 UDP clientUdp = (UDP) clientIpv6.getPayload();
529 DHCP6 clientDhcp6 = (DHCP6) clientUdp.getPayload();
Taras Lemkin96a0d342018-03-26 14:52:58 +0000530 Interface serverInterface = Dhcp6HandlerUtil.directlyConnected(clientDhcp6) ?
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800531 getServerInterface() : getIndirectServerInterface();
Kalhee Kim45fede42017-09-05 19:05:06 +0000532 InternalPacket ethernetPacketReply =
Taras Lemkin96a0d342018-03-26 14:52:58 +0000533 Dhcp6HandlerUtil.processLQ6PacketFromServer(
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800534 defaultServerInfoList, indirectServerInfoList,
535 serverInterface, interfaceService,
536 hostService,
537 context, receivedPacket, receivingInterfaces);
Kalhee Kim45fede42017-09-05 19:05:06 +0000538 if (ethernetPacketReply != null) {
539 forwardPacket(ethernetPacketReply);
540 }
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800541 handleLeaseQuery6ReplyMsg(context, dhcp6Payload);
Taras Lemkin96a0d342018-03-26 14:52:58 +0000542 } else if (MSG_TYPE_FROM_CLIENT.contains(msgTypeVal)) {
543 List<InternalPacket> ethernetClientPacket =
544 processDhcp6PacketFromClient(context, receivedPacket, receivingInterfaces);
545 for (InternalPacket internalPacket : ethernetClientPacket) {
546 forwardPacket(internalPacket);
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800547 }
Taras Lemkin96a0d342018-03-26 14:52:58 +0000548 } else if (MSG_TYPE_FROM_SERVER.contains(msgTypeVal)) {
549 log.debug("calling processDhcp6PacketFromServer with RELAY_REPL {}, {}", receivedPacket, dhcp6Payload);
550 InternalPacket ethernetPacketReply =
551 processDhcp6PacketFromServer(context, receivedPacket, receivingInterfaces);
552 if (ethernetPacketReply != null) {
553 forwardPacket(ethernetPacketReply);
554 }
555 } else {
556 log.warn("Not so fast, packet type {} not supported yet", msgTypeVal);
Kalhee Kim45fede42017-09-05 19:05:06 +0000557 }
558 }
559
Kalhee Kim45fede42017-09-05 19:05:06 +0000560 /**
561 * Checks if this app has been configured.
562 *
563 * @return true if all information we need have been initialized
564 */
565 public boolean configured() {
Yi Tseng919b2df2017-09-07 16:22:51 -0700566 return !defaultServerInfoList.isEmpty();
Kalhee Kim45fede42017-09-05 19:05:06 +0000567 }
568
Yi Tsengaa417a62017-09-08 17:22:51 -0700569 @Override
570 public ProviderId id() {
Charles Chand988c282017-09-12 17:09:32 -0700571 return PROVIDER_ID;
Yi Tsengaa417a62017-09-08 17:22:51 -0700572 }
573
574 @Override
575 public void triggerProbe(Host host) {
576 // Do nothing here
577 }
578
Kalhee Kim45fede42017-09-05 19:05:06 +0000579 //forward the packet to ConnectPoint where the DHCP server is attached.
580 private void forwardPacket(InternalPacket packet) {
581 //send Packetout to dhcp server connectpoint.
Taras Lemkin96a0d342018-03-26 14:52:58 +0000582 if (packet.getDestLocation() != null) {
Kalhee Kim45fede42017-09-05 19:05:06 +0000583 TrafficTreatment t = DefaultTrafficTreatment.builder()
Taras Lemkin96a0d342018-03-26 14:52:58 +0000584 .setOutput(packet.getDestLocation().port()).build();
Kalhee Kim45fede42017-09-05 19:05:06 +0000585 OutboundPacket o = new DefaultOutboundPacket(
Taras Lemkin96a0d342018-03-26 14:52:58 +0000586 packet.getDestLocation().deviceId(), t, ByteBuffer.wrap(packet.getPacket().serialize()));
Kalhee Kim45fede42017-09-05 19:05:06 +0000587 packetService.emit(o);
Taras Lemkin96a0d342018-03-26 14:52:58 +0000588 if (log.isTraceEnabled()) {
589 IPv6 ip6 = (IPv6) packet.getPacket().getPayload();
590 UDP udp = (UDP) ip6.getPayload();
591 DHCP6 dhcp6 = (DHCP6) udp.getPayload();
592 log.trace("Relaying packet to destination {} eth: {} dhcp: {}",
593 packet.getDestLocation(), packet.getPacket(), dhcp6);
594 }
595
596 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000597 }
598
Kalhee Kim45fede42017-09-05 19:05:06 +0000599 /**
600 * extract from dhcp6 packet client ipv6 address of given by dhcp server.
601 *
602 * @param dhcp6 the dhcp6 packet
Kalhee Kim495c9b22017-11-07 16:32:09 +0000603 * @return IpAddressInfo IpAddressInfo given by dhcp server, or null if not exists
Kalhee Kim45fede42017-09-05 19:05:06 +0000604 */
Kalhee Kim495c9b22017-11-07 16:32:09 +0000605 private IpAddressInfo extractIpAddress(DHCP6 dhcp6) {
606 IpAddressInfo ipInfo = new IpAddressInfo();
Kalhee Kim45fede42017-09-05 19:05:06 +0000607
608 log.debug("extractIpAddress enters dhcp6 {}.", dhcp6);
609 // Extract IPv6 address from IA NA ot IA TA option
610 Optional<Dhcp6IaNaOption> iaNaOption = dhcp6.getOptions()
611 .stream()
612 .filter(opt -> opt instanceof Dhcp6IaNaOption)
613 .map(opt -> (Dhcp6IaNaOption) opt)
614 .findFirst();
615 Optional<Dhcp6IaTaOption> iaTaOption = dhcp6.getOptions()
616 .stream()
617 .filter(opt -> opt instanceof Dhcp6IaTaOption)
618 .map(opt -> (Dhcp6IaTaOption) opt)
619 .findFirst();
620 Optional<Dhcp6IaAddressOption> iaAddressOption;
621 if (iaNaOption.isPresent()) {
622 log.debug("Found IPv6 address from iaNaOption {}", iaNaOption);
623
624 iaAddressOption = iaNaOption.get().getOptions().stream()
625 .filter(opt -> opt instanceof Dhcp6IaAddressOption)
626 .map(opt -> (Dhcp6IaAddressOption) opt)
627 .findFirst();
628 } else if (iaTaOption.isPresent()) {
629 log.debug("Found IPv6 address from iaTaOption {}", iaTaOption);
630
631 iaAddressOption = iaTaOption.get().getOptions().stream()
632 .filter(opt -> opt instanceof Dhcp6IaAddressOption)
633 .map(opt -> (Dhcp6IaAddressOption) opt)
634 .findFirst();
635 } else {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000636 log.info("No IPv6 address found from iaTaOption {}", iaTaOption);
Kalhee Kim45fede42017-09-05 19:05:06 +0000637 iaAddressOption = Optional.empty();
638 }
639 if (iaAddressOption.isPresent()) {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000640 ipInfo.ip6Address = iaAddressOption.get().getIp6Address();
641 ipInfo.prefTime = iaAddressOption.get().getPreferredLifetime();
Kalhee Kim45fede42017-09-05 19:05:06 +0000642 log.debug("Found IPv6 address from iaAddressOption {}", iaAddressOption);
Kalhee Kim45fede42017-09-05 19:05:06 +0000643 } else {
644 log.debug("Can't find IPv6 address from DHCPv6 {}", dhcp6);
Kalhee Kim495c9b22017-11-07 16:32:09 +0000645 return null;
Kalhee Kim45fede42017-09-05 19:05:06 +0000646 }
Kalhee Kim495c9b22017-11-07 16:32:09 +0000647 return ipInfo;
Kalhee Kim45fede42017-09-05 19:05:06 +0000648 }
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800649
Kalhee Kim45fede42017-09-05 19:05:06 +0000650 /**
651 * extract from dhcp6 packet Prefix prefix provided by dhcp server.
652 *
653 * @param dhcp6 the dhcp6 payload
654 * @return IpPrefix Prefix Delegation prefix, or null if not exists.
655 */
Kalhee Kim495c9b22017-11-07 16:32:09 +0000656 private PdPrefixInfo extractPrefix(DHCP6 dhcp6) {
657 log.debug("extractPrefix enters {}", dhcp6);
Kalhee Kim45fede42017-09-05 19:05:06 +0000658
659 // extract prefix
Kalhee Kim495c9b22017-11-07 16:32:09 +0000660 PdPrefixInfo pdPrefixInfo = new PdPrefixInfo();
Kalhee Kim45fede42017-09-05 19:05:06 +0000661
662 Ip6Address prefixAddress = null;
663
664 // Extract IPv6 prefix from IA PD option
665 Optional<Dhcp6IaPdOption> iaPdOption = dhcp6.getOptions()
666 .stream()
667 .filter(opt -> opt instanceof Dhcp6IaPdOption)
668 .map(opt -> (Dhcp6IaPdOption) opt)
669 .findFirst();
670
671 Optional<Dhcp6IaPrefixOption> iaPrefixOption;
672 if (iaPdOption.isPresent()) {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000673 log.debug("IA_PD option found {}", iaPdOption);
Kalhee Kim45fede42017-09-05 19:05:06 +0000674
675 iaPrefixOption = iaPdOption.get().getOptions().stream()
676 .filter(opt -> opt instanceof Dhcp6IaPrefixOption)
677 .map(opt -> (Dhcp6IaPrefixOption) opt)
678 .findFirst();
679 } else {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000680 log.debug("IA_PD option NOT found");
Kalhee Kim45fede42017-09-05 19:05:06 +0000681
682 iaPrefixOption = Optional.empty();
683 }
684 if (iaPrefixOption.isPresent()) {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000685 log.debug("IAPrefix Option within IA_PD option found {}", iaPrefixOption);
Kalhee Kim45fede42017-09-05 19:05:06 +0000686
687 prefixAddress = iaPrefixOption.get().getIp6Prefix();
688 int prefixLen = (int) iaPrefixOption.get().getPrefixLength();
Kalhee Kim495c9b22017-11-07 16:32:09 +0000689 log.debug("Prefix length is {} bits", prefixLen);
690 pdPrefixInfo.pdPrefix = IpPrefix.valueOf(prefixAddress, prefixLen);
691 pdPrefixInfo.prefTime = iaPrefixOption.get().getPreferredLifetime();
Kalhee Kim45fede42017-09-05 19:05:06 +0000692 } else {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000693 log.debug("Can't find IPv6 prefix from DHCPv6 {}", dhcp6);
694 return null;
Kalhee Kim45fede42017-09-05 19:05:06 +0000695 }
Kalhee Kim495c9b22017-11-07 16:32:09 +0000696 return pdPrefixInfo;
Kalhee Kim45fede42017-09-05 19:05:06 +0000697 }
698
699 /**
Kalhee Kim495c9b22017-11-07 16:32:09 +0000700 * remove host or route and update dhcp relay record attributes.
Kalhee Kim45fede42017-09-05 19:05:06 +0000701 *
702 * @param directConnFlag flag to show that packet is from directly connected client
Kalhee Kim495c9b22017-11-07 16:32:09 +0000703 * @param location client side connect point
Kalhee Kim45fede42017-09-05 19:05:06 +0000704 * @param dhcp6Packet the dhcp6 payload
705 * @param clientPacket client's ethernet packet
706 * @param clientIpv6 client's Ipv6 packet
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000707 * @param clientInterface client interfaces
Kalhee Kim45fede42017-09-05 19:05:06 +0000708 */
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000709 private void removeHostOrRoute(boolean directConnFlag, ConnectPoint location,
710 DHCP6 dhcp6Packet,
Kalhee Kim45fede42017-09-05 19:05:06 +0000711 Ethernet clientPacket, IPv6 clientIpv6,
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000712 Interface clientInterface) {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000713 log.debug("removeHostOrRoute enters {}", dhcp6Packet);
Kalhee Kim121ba922017-11-01 17:56:44 +0000714 VlanId vlanId = clientInterface.vlan();
Kalhee Kim495c9b22017-11-07 16:32:09 +0000715 MacAddress srcMac = clientPacket.getSourceMAC(); // could be gw or host
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000716 MacAddress leafClientMac;
717 byte leafMsgType;
Kalhee Kim495c9b22017-11-07 16:32:09 +0000718 log.debug("client mac {} client vlan {}", HexString.toHexString(srcMac.toBytes(), ":"), vlanId);
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000719
Charles Chan24a96ff2018-08-13 10:32:03 -0700720 Dhcp6ClientIdOption clientIdOption = Dhcp6HandlerUtil.extractClientId(directConnFlag, dhcp6Packet);
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000721 if (clientIdOption != null) {
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000722 if ((clientIdOption.getDuid().getDuidType() == Dhcp6Duid.DuidType.DUID_LLT) ||
723 (clientIdOption.getDuid().getDuidType() == Dhcp6Duid.DuidType.DUID_LL)) {
724 leafClientMac = MacAddress.valueOf(clientIdOption.getDuid().getLinkLayerAddress());
725 } else {
726 log.warn("Link-Layer Address not supported in CLIENTID option. No DhcpRelay Record created.");
Charles Chanb87495c2019-02-01 11:31:50 -0800727 //dhcpRelayCountersStore.incrementCounter(gCount, DhcpRelayCounters.NO_LINKLOCAL_FAIL);
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000728 return;
729 }
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000730 } else {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000731 log.warn("CLIENTID option NOT found. Don't create DhcpRelay Record.");
Charles Chanb87495c2019-02-01 11:31:50 -0800732 //dhcpRelayCountersStore.incrementCounter(gCount, DhcpRelayCounters.NO_CLIENTID_FAIL);
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000733 return;
734 }
735
Kalhee Kim495c9b22017-11-07 16:32:09 +0000736 HostId leafHostId = HostId.hostId(leafClientMac, vlanId);
737 DhcpRecord record = dhcpRelayStore.getDhcpRecord(leafHostId).orElse(null);
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000738 if (record == null) {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000739 record = new DhcpRecord(leafHostId);
Kalhee Kimd94ceea2017-11-29 19:03:02 +0000740 } else {
741 record = record.clone();
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000742 }
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000743
Taras Lemkin96a0d342018-03-26 14:52:58 +0000744 Boolean isMsgRelease = Dhcp6HandlerUtil.isDhcp6Release(dhcp6Packet);
Kalhee Kim495c9b22017-11-07 16:32:09 +0000745 IpAddressInfo ipInfo;
746 PdPrefixInfo pdInfo = null;
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000747 if (directConnFlag) {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000748 // Add to host store if it is connected to network directly
749 ipInfo = extractIpAddress(dhcp6Packet);
750 if (ipInfo != null) {
751 if (isMsgRelease) {
752 HostId hostId = HostId.hostId(srcMac, vlanId);
753 log.debug("remove Host {} ip for directly connected.", hostId.toString());
754 providerService.removeIpFromHost(hostId, ipInfo.ip6Address);
Kalhee Kim45fede42017-09-05 19:05:06 +0000755 }
756 } else {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000757 log.debug("ipAddress not found. Do not remove Host {} for directly connected.",
758 HostId.hostId(srcMac, vlanId).toString());
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000759 }
Kalhee Kim495c9b22017-11-07 16:32:09 +0000760 leafMsgType = dhcp6Packet.getMsgType();
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000761 } else {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000762 // Remove from route store if it is not connected to network directly
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000763 // pick out the first link-local ip address
Kalhee Kim495c9b22017-11-07 16:32:09 +0000764 IpAddress nextHopIp = getFirstIpByHost(directConnFlag, srcMac, vlanId);
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000765 if (nextHopIp == null) {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000766 log.warn("Can't find link-local IP address of gateway mac {} vlanId {}", srcMac, vlanId);
Charles Chanb87495c2019-02-01 11:31:50 -0800767 //dhcpRelayCountersStore.incrementCounter(gCount, DhcpRelayCounters.NO_LINKLOCAL_GW);
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000768 return;
769 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000770
Taras Lemkin96a0d342018-03-26 14:52:58 +0000771 DHCP6 leafDhcp = Dhcp6HandlerUtil.getDhcp6Leaf(dhcp6Packet);
Kalhee Kim495c9b22017-11-07 16:32:09 +0000772 ipInfo = extractIpAddress(leafDhcp);
773 if (ipInfo == null) {
774 log.debug("ip is null");
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000775 } else {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000776 if (isMsgRelease) {
Kalhee Kim54a97c92018-04-02 21:23:46 +0000777 Route routeForIP = new Route(Route.Source.DHCP, ipInfo.ip6Address.toIpPrefix(), nextHopIp);
Kalhee Kim495c9b22017-11-07 16:32:09 +0000778 log.debug("removing route of 128 address for indirectly connected.");
779 log.debug("128 ip {}, nexthop {}",
780 HexString.toHexString(ipInfo.ip6Address.toOctets(), ":"),
781 HexString.toHexString(nextHopIp.toOctets(), ":"));
782 routeStore.removeRoute(routeForIP);
Kalhee Kim45fede42017-09-05 19:05:06 +0000783 }
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000784 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000785
Kalhee Kim495c9b22017-11-07 16:32:09 +0000786 pdInfo = extractPrefix(leafDhcp);
787 if (pdInfo == null) {
788 log.debug("ipPrefix is null ");
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000789 } else {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000790 if (isMsgRelease) {
Kalhee Kim54a97c92018-04-02 21:23:46 +0000791 Route routeForPrefix = new Route(Route.Source.DHCP, pdInfo.pdPrefix, nextHopIp);
Kalhee Kim495c9b22017-11-07 16:32:09 +0000792 log.debug("removing route of PD for indirectly connected.");
793 log.debug("pd ip {}, nexthop {}",
794 HexString.toHexString(pdInfo.pdPrefix.address().toOctets(), ":"),
795 HexString.toHexString(nextHopIp.toOctets(), ":"));
796
797 routeStore.removeRoute(routeForPrefix);
Kalhee Kimba366062017-11-07 16:32:09 +0000798 if (this.dhcpFpmEnabled) {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000799 dhcpFpmPrefixStore.removeFpmRecord(pdInfo.pdPrefix);
Kalhee Kimba366062017-11-07 16:32:09 +0000800 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000801 }
802 }
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000803 leafMsgType = leafDhcp.getMsgType();
Kalhee Kimd94ceea2017-11-29 19:03:02 +0000804 }
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000805
Kalhee Kim495c9b22017-11-07 16:32:09 +0000806 if (isMsgRelease) {
807 log.debug("DHCP6 RELEASE msg.");
808 if (record != null) {
809 if (ipInfo != null) {
810 log.debug("DhcpRelay Record ip6Address is set to null.");
811 record.ip6Address(null);
812 }
813 if (pdInfo != null) {
814 log.debug("DhcpRelay Record pdPrefix is set to null.");
815 }
816
817 if (!record.ip6Address().isPresent() && !record.pdPrefix().isPresent()) {
818 log.warn("IP6 address and IP6 PD both are null. Remove record.");
819 // do not remove a record. Let timer task handler it.
820 //dhcpRelayStore.removeDhcpRecord(HostId.hostId(leafClientMac, vlanId));
821 }
822 }
823 }
824
Ray Milkeyffe1a332018-01-24 10:41:14 -0800825 if (record != null) {
Taras Lemkin96a0d342018-03-26 14:52:58 +0000826 record.getV6Counters().incrementCounter(Dhcp6HandlerUtil.getMsgTypeStr(leafMsgType));
Ray Milkeyffe1a332018-01-24 10:41:14 -0800827 record.addLocation(new HostLocation(location, System.currentTimeMillis()));
828 record.ip6Status(DHCP6.MsgType.getType(leafMsgType));
829 record.setDirectlyConnected(directConnFlag);
830 if (!directConnFlag) {
831 // Update gateway mac address if the host is not directly connected
832 record.nextHop(srcMac);
833 }
834 record.updateLastSeen();
Kalhee Kim495c9b22017-11-07 16:32:09 +0000835 }
Kalhee Kim495c9b22017-11-07 16:32:09 +0000836 dhcpRelayStore.updateDhcpRecord(leafHostId, record);
Charles Chanb87495c2019-02-01 11:31:50 -0800837 /*
Kalhee Kimd94ceea2017-11-29 19:03:02 +0000838 // TODO Use AtomicInteger for the counters
839 try {
840 recordSemaphore.acquire();
841 try {
Taras Lemkin96a0d342018-03-26 14:52:58 +0000842 dhcpRelayCountersStore.incrementCounter(gCount, Dhcp6HandlerUtil.getMsgTypeStr(leafMsgType));
Kalhee Kimd94ceea2017-11-29 19:03:02 +0000843 } finally {
844 // calling release() after a successful acquire()
845 recordSemaphore.release();
846 }
847 } catch (InterruptedException e) {
Ray Milkeyba547f92018-02-01 15:22:31 -0800848 Thread.currentThread().interrupt();
Kalhee Kimd94ceea2017-11-29 19:03:02 +0000849 }
Charles Chanb87495c2019-02-01 11:31:50 -0800850 */
Kalhee Kim495c9b22017-11-07 16:32:09 +0000851 }
852
853 /**
854 * add host or route and update dhcp relay record.
855 *
856 * @param directConnFlag flag to show that packet is from directly connected client
857 * @param location client side connect point
858 * @param dhcp6Relay the dhcp6 payload
859 * @param embeddedDhcp6 the dhcp6 payload within relay
860 * @param srcMac client gw/host macAddress
861 * @param clientInterface client interface
862 */
863 private void addHostOrRoute(boolean directConnFlag, ConnectPoint location, DHCP6 dhcp6Relay,
864 DHCP6 embeddedDhcp6, MacAddress srcMac, Interface clientInterface) {
865 log.debug("addHostOrRoute entered.");
866 VlanId vlanId = clientInterface.vlan();
Taras Lemkin96a0d342018-03-26 14:52:58 +0000867 Boolean isMsgReply = Dhcp6HandlerUtil.isDhcp6Reply(dhcp6Relay);
Kalhee Kim495c9b22017-11-07 16:32:09 +0000868 MacAddress leafClientMac;
869 Byte leafMsgType;
870
Charles Chan24a96ff2018-08-13 10:32:03 -0700871 Dhcp6ClientIdOption clientIdOption = Dhcp6HandlerUtil.extractClientId(directConnFlag, embeddedDhcp6);
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000872 if (clientIdOption != null) {
873 log.debug("CLIENTID option found {}", clientIdOption);
874 if ((clientIdOption.getDuid().getDuidType() == Dhcp6Duid.DuidType.DUID_LLT) ||
875 (clientIdOption.getDuid().getDuidType() == Dhcp6Duid.DuidType.DUID_LL)) {
876 leafClientMac = MacAddress.valueOf(clientIdOption.getDuid().getLinkLayerAddress());
877 } else {
878 log.warn("Link-Layer Address not supported in CLIENTID option. No DhcpRelay Record created.");
Charles Chanb87495c2019-02-01 11:31:50 -0800879 //dhcpRelayCountersStore.incrementCounter(gCount, DhcpRelayCounters.NO_LINKLOCAL_FAIL);
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000880 return;
881 }
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000882 } else {
883 log.warn("CLIENTID option NOT found. No DhcpRelay Record created.");
Charles Chanb87495c2019-02-01 11:31:50 -0800884 //dhcpRelayCountersStore.incrementCounter(gCount, DhcpRelayCounters.NO_CLIENTID_FAIL);
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000885 return;
886 }
Kalhee Kim495c9b22017-11-07 16:32:09 +0000887 HostId leafHostId = HostId.hostId(leafClientMac, vlanId);
888 DhcpRecord record = dhcpRelayStore.getDhcpRecord(leafHostId).orElse(null);
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000889 if (record == null) {
890 record = new DhcpRecord(HostId.hostId(leafClientMac, vlanId));
Kalhee Kimd94ceea2017-11-29 19:03:02 +0000891 } else {
892 record = record.clone();
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000893 }
Kalhee Kim495c9b22017-11-07 16:32:09 +0000894
895 IpAddressInfo ipInfo;
896 PdPrefixInfo pdInfo = null;
897 if (directConnFlag) {
898 // Add to host store if it connect to network directly
899 ipInfo = extractIpAddress(embeddedDhcp6);
900 if (ipInfo != null) {
901 if (isMsgReply) {
902 Set<IpAddress> ips = Sets.newHashSet(ipInfo.ip6Address);
903 HostId hostId = HostId.hostId(srcMac, vlanId);
904 Host host = hostService.getHost(hostId);
905 HostLocation hostLocation = new HostLocation(clientInterface.connectPoint(),
906 System.currentTimeMillis());
907 Set<HostLocation> hostLocations = Sets.newHashSet(hostLocation);
908 if (host != null) {
909 // Dual homing support:
910 // if host exists, use old locations and new location
911 hostLocations.addAll(host.locations());
912 }
913 HostDescription desc = new DefaultHostDescription(srcMac, vlanId, hostLocations, ips,
914 false);
915 log.debug("adding Host for directly connected.");
916 log.debug("client mac {} client vlan {} hostlocation {}",
917 HexString.toHexString(srcMac.toBytes(), ":"), vlanId, hostLocation.toString());
918 // Replace the ip when dhcp server give the host new ip address
919 providerService.hostDetected(hostId, desc, false);
920 }
921 } else {
922 log.warn("ipAddress not found. Do not add Host {} for directly connected.",
923 HostId.hostId(srcMac, vlanId).toString());
924 }
925 leafMsgType = embeddedDhcp6.getMsgType();
926 } else {
927 // Add to route store if it does not connect to network directly
928 // pick out the first link-local ip address
929 IpAddress nextHopIp = getFirstIpByHost(directConnFlag, srcMac, vlanId);
930 if (nextHopIp == null) {
931 log.warn("Can't find link-local IP address of gateway mac {} vlanId {}", srcMac, vlanId);
Charles Chanb87495c2019-02-01 11:31:50 -0800932 //dhcpRelayCountersStore.incrementCounter(gCount, DhcpRelayCounters.NO_LINKLOCAL_GW);
Kalhee Kim495c9b22017-11-07 16:32:09 +0000933 return;
934 }
935
Taras Lemkin96a0d342018-03-26 14:52:58 +0000936 DHCP6 leafDhcp = Dhcp6HandlerUtil.getDhcp6Leaf(embeddedDhcp6);
Kalhee Kim495c9b22017-11-07 16:32:09 +0000937 ipInfo = extractIpAddress(leafDhcp);
938 if (ipInfo == null) {
939 log.debug("ip is null");
940 } else {
941 if (isMsgReply) {
Kalhee Kim54a97c92018-04-02 21:23:46 +0000942 Route routeForIP = new Route(Route.Source.DHCP, ipInfo.ip6Address.toIpPrefix(), nextHopIp);
Kalhee Kim495c9b22017-11-07 16:32:09 +0000943 log.debug("adding Route of 128 address for indirectly connected.");
Daniel Ginsburg83b76452018-06-09 01:43:59 +0300944 routeStore.replaceRoute(routeForIP);
Kalhee Kim495c9b22017-11-07 16:32:09 +0000945 }
946 }
947
948 pdInfo = extractPrefix(leafDhcp);
949 if (pdInfo == null) {
950 log.debug("ipPrefix is null ");
951 } else {
952 if (isMsgReply) {
Kalhee Kim54a97c92018-04-02 21:23:46 +0000953 Route routeForPrefix = new Route(Route.Source.DHCP, pdInfo.pdPrefix, nextHopIp);
Kalhee Kim495c9b22017-11-07 16:32:09 +0000954 log.debug("adding Route of PD for indirectly connected.");
Daniel Ginsburg83b76452018-06-09 01:43:59 +0300955 routeStore.replaceRoute(routeForPrefix);
Kalhee Kim495c9b22017-11-07 16:32:09 +0000956 if (this.dhcpFpmEnabled) {
957 FpmRecord fpmRecord = new FpmRecord(pdInfo.pdPrefix, nextHopIp, FpmRecord.Type.DHCP_RELAY);
958 dhcpFpmPrefixStore.addFpmRecord(pdInfo.pdPrefix, fpmRecord);
959 }
960 }
961 }
962 leafMsgType = leafDhcp.getMsgType();
963 }
964 if (leafMsgType == DHCP6.MsgType.RELEASE.value() ||
965 (leafMsgType == DHCP6.MsgType.REPLY.value()) && ipInfo == null) {
966 log.warn("DHCP6 RELEASE/REPLY(null ip) from Server. MsgType {}", leafMsgType);
967 //return;
968 }
969
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000970 record.addLocation(new HostLocation(location, System.currentTimeMillis()));
Kalhee Kim2f07c602017-11-15 18:57:53 +0000971
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000972 if (leafMsgType == DHCP6.MsgType.REPLY.value()) {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000973 if (ipInfo != null) {
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000974 log.debug("IP6 address is being stored into dhcp-relay store.");
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800975 log.debug("Client IP6 address {}", HexString.toHexString(ipInfo.ip6Address.toOctets(), ":"));
Kalhee Kim495c9b22017-11-07 16:32:09 +0000976 record.ip6Address(ipInfo.ip6Address);
Kalhee Kim2f07c602017-11-15 18:57:53 +0000977 record.updateAddrPrefTime(ipInfo.prefTime);
978 record.updateLastIp6Update();
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800979 } else {
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000980 log.debug("IP6 address is not returned from server. Maybe only PD is returned.");
981 }
Kalhee Kim495c9b22017-11-07 16:32:09 +0000982 if (pdInfo != null) {
983 log.debug("IP6 PD address {}",
984 HexString.toHexString(pdInfo.pdPrefix.address().toOctets(), ":"));
Kalhee Kim2f07c602017-11-15 18:57:53 +0000985 record.pdPrefix(pdInfo.pdPrefix);
986 record.updatePdPrefTime(pdInfo.prefTime);
987 record.updateLastPdUpdate();
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000988 } else {
989 log.debug("IP6 PD address is not returned from server. Maybe only IPAddress is returned.");
990 }
991 }
Kalhee Kim2f07c602017-11-15 18:57:53 +0000992
Taras Lemkin96a0d342018-03-26 14:52:58 +0000993 record.getV6Counters().incrementCounter(Dhcp6HandlerUtil.getMsgTypeStr(leafMsgType));
Kalhee Kim495c9b22017-11-07 16:32:09 +0000994 record.ip6Status(DHCP6.MsgType.getType(leafMsgType));
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000995 record.setDirectlyConnected(directConnFlag);
996 record.updateLastSeen();
Kalhee Kim495c9b22017-11-07 16:32:09 +0000997 dhcpRelayStore.updateDhcpRecord(leafHostId, record);
Charles Chanb87495c2019-02-01 11:31:50 -0800998 /*
Kalhee Kimd94ceea2017-11-29 19:03:02 +0000999 // TODO Use AtomicInteger for the counters
1000 try {
1001 recordSemaphore.acquire();
1002 try {
Taras Lemkin96a0d342018-03-26 14:52:58 +00001003 dhcpRelayCountersStore.incrementCounter(gCount, Dhcp6HandlerUtil.getMsgTypeStr(leafMsgType));
Kalhee Kimd94ceea2017-11-29 19:03:02 +00001004 } finally {
1005 // calling release() after a successful acquire()
1006 recordSemaphore.release();
1007 }
1008 } catch (InterruptedException e) {
Ray Milkeyba547f92018-02-01 15:22:31 -08001009 Thread.currentThread().interrupt();
Kalhee Kimd94ceea2017-11-29 19:03:02 +00001010 }
Charles Chanb87495c2019-02-01 11:31:50 -08001011 */
Kalhee Kim45fede42017-09-05 19:05:06 +00001012 }
1013
Taras Lemkin96a0d342018-03-26 14:52:58 +00001014 private List<InternalPacket> processDhcp6ForwardOnly(PacketContext context,
1015 Ethernet clientPacket,
1016 Set<Interface> clientInterfaces,
1017 DHCP6 dhcpPacket) {
1018 ConnectPoint inPort = context.inPacket().receivedFrom();
1019 log.trace("Got DHCPv6 on port {}", inPort);
1020 boolean directConnFlag = Dhcp6HandlerUtil.directlyConnected(dhcpPacket);
1021
1022 List<InternalPacket> internalPackets = new ArrayList<>();
1023 List<DhcpServerInfo> serverInfoList = findValidServerInfo(directConnFlag);
1024
1025 for (DhcpServerInfo dhcpServer : serverInfoList) {
Charles Chan24a96ff2018-08-13 10:32:03 -07001026 Interface serverInterface = getServerInterface(dhcpServer);
1027 if (serverInterface == null) {
1028 log.warn("Can't get server interface, ignore");
1029 continue;
1030 }
1031
Taras Lemkin96a0d342018-03-26 14:52:58 +00001032 Ethernet newPacket = Dhcp6HandlerUtil.buildDhcp6PacketFromClient(context,
Charles Chan24a96ff2018-08-13 10:32:03 -07001033 clientPacket, clientInterfaces, dhcpServer, serverInterface);
Taras Lemkin96a0d342018-03-26 14:52:58 +00001034 log.trace("Built packet for server {} : {}", dhcpServer, newPacket);
1035 internalPackets.add(InternalPacket.internalPacket(newPacket,
1036 dhcpServer.getDhcpServerConnectPoint().get()));
1037 }
1038
1039 return internalPackets;
1040 }
1041
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001042 private List<InternalPacket> processLQ6PacketFromClient(PacketContext context,
1043 Ethernet clientPacket,
1044 Set<Interface> clientInterfaces,
1045 DHCP6 dhcp6Payload) {
1046 ConnectPoint inPort = context.inPacket().receivedFrom();
1047 log.info("Got LQ-REQUEST V6 on port {}", inPort);
1048 List<Dhcp6Option> lopt = dhcp6Payload.getOptions();
1049 log.info("Options list: {}", lopt);
1050 Dhcp6LeaseQueryOption lqoption = dhcp6Payload.getOptions()
1051 .stream()
1052 .filter(opt -> opt instanceof Dhcp6LeaseQueryOption)
1053 .map(pld -> (Dhcp6LeaseQueryOption) pld)
1054 .findFirst()
1055 .orElse(null);
1056
1057 if (lqoption == null) {
1058 // Can't find dhcp payload
1059 log.warn("Can't find dhcp6 lease query message - aborting");
1060 return null;
1061 } else {
1062 log.info("dhcp6 lqv6 options found: {}", lqoption);
1063 }
1064 log.warn("LQv6 for " + lqoption.linkAddress.toString() + " comes from " + inPort.toString());
1065 Ethernet packet = context.inPacket().parsed();
1066 Ip6Address clientAddress = lqoption.linkAddress;
1067 IPv6 ipv6Packet = (IPv6) packet.getPayload();
1068 Ip6Address nextHopIp = findNextHopIp6FromRelayStore(clientAddress);
1069
1070 // 1. only if there is a route to remove - remove it
1071 if (nextHopIp != null) {
Kalhee Kim54a97c92018-04-02 21:23:46 +00001072 Route routeForIP6 = new Route(Route.Source.DHCP, clientAddress.toIpPrefix(), nextHopIp);
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001073 log.debug("Removing route of Client " + clientAddress +
1074 " for indirectly connected - next hop ip6 " + nextHopIp);
1075 routeStore.removeRoute(routeForIP6);
1076 }
1077
1078 // 2. note the potential NH this packet came from in case it's a known lease
1079 // this NH will then be used to build the route
1080 MacAddress potentialNH = packet.getSourceMAC();
1081 VlanId vlanId = VlanId.vlanId(packet.getVlanID());
1082 setPotentialNextHopForIp6InRelayStore(clientAddress, vlanId, potentialNH);
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001083 // 3. route this LQ6 to all relevant servers
1084 IPv6 clientIpv6 = (IPv6) clientPacket.getPayload();
1085 UDP clientUdp = (UDP) clientIpv6.getPayload();
1086 DHCP6 clientDhcp6 = (DHCP6) clientUdp.getPayload();
1087
Taras Lemkin96a0d342018-03-26 14:52:58 +00001088 boolean directConnFlag = Dhcp6HandlerUtil.directlyConnected(clientDhcp6);
Harshada Chaundkarf0780fe2019-05-06 20:16:13 +00001089 boolean serverFound = false;
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001090 List<InternalPacket> internalPackets = new ArrayList<>();
1091 List<DhcpServerInfo> serverInfoList = findValidServerInfo(directConnFlag);
1092 List<DhcpServerInfo> copyServerInfoList = new ArrayList<DhcpServerInfo>(serverInfoList);
1093
1094 for (DhcpServerInfo serverInfo : copyServerInfoList) {
Taras Lemkin96a0d342018-03-26 14:52:58 +00001095 if (!Dhcp6HandlerUtil.checkDhcpServerConnPt(directConnFlag, serverInfo)) {
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001096 log.warn("Can't get server connect point, ignore");
1097 continue;
1098 }
1099 DhcpServerInfo newServerInfo = getHostInfoForServerInfo(serverInfo, serverInfoList);
1100 if (newServerInfo == null) {
Harshada Chaundkarf0780fe2019-05-06 20:16:13 +00001101 log.debug("Can't get server interface with host info resolved, ignore serverInfo {} serverInfoList {}",
1102 serverInfo, serverInfoList);
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001103 continue;
1104 }
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001105 Interface serverInterface = getServerInterface(newServerInfo);
1106 if (serverInterface == null) {
Harshada Chaundkarf0780fe2019-05-06 20:16:13 +00001107 log.debug("Can't get server interface, ignore for serverInfo {}, serverInfoList {}",
1108 serverInfo, serverInfoList);
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001109 continue;
1110 }
Harshada Chaundkarf0780fe2019-05-06 20:16:13 +00001111
1112 serverFound = true;
1113 log.debug("Server Info Found {}", serverInfo.getDhcpConnectMac());
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001114 Ethernet etherRouted = (Ethernet) clientPacket.clone();
1115 MacAddress macFacingServer = serverInterface.mac();
1116 if (macFacingServer == null) {
1117 log.warn("No MAC address for server Interface {}", serverInterface);
1118 return null;
1119 }
1120 etherRouted.setSourceMACAddress(macFacingServer);
1121 etherRouted.setDestinationMACAddress(newServerInfo.getDhcpConnectMac().get());
1122 InternalPacket internalPacket =
Taras Lemkin96a0d342018-03-26 14:52:58 +00001123 InternalPacket.internalPacket(etherRouted,
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001124 serverInfo.getDhcpServerConnectPoint().get());
1125 internalPackets.add(internalPacket);
1126 log.debug("Sending LQ to DHCP server {}", newServerInfo.getDhcpServerIp6());
1127 }
Harshada Chaundkarf0780fe2019-05-06 20:16:13 +00001128 if (!serverFound) {
1129 log.warn("ProcessDhcp6PacketFromClient No Server Found");
1130 }
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001131 log.debug("num of client packets to send is{}", internalPackets.size());
1132
1133 return internalPackets;
1134 }
1135
Kalhee Kim45fede42017-09-05 19:05:06 +00001136 /**
Kalhee Kim495c9b22017-11-07 16:32:09 +00001137 * build the DHCP6 solicit/request packet with gatewayip.
Kalhee Kim45fede42017-09-05 19:05:06 +00001138 *
1139 * @param context packet context
1140 * @param clientPacket client ethernet packet
1141 * @param clientInterfaces set of client side interfaces
1142 */
Kalhee Kim495c9b22017-11-07 16:32:09 +00001143 private List<InternalPacket> processDhcp6PacketFromClient(PacketContext context,
1144 Ethernet clientPacket,
1145 Set<Interface> clientInterfaces) {
Yi Tseng3bd57ac2017-11-29 14:39:18 -08001146 ConnectPoint receivedFrom = context.inPacket().receivedFrom();
Taras Lemkin96a0d342018-03-26 14:52:58 +00001147 Ip6Address relayAgentIp = Dhcp6HandlerUtil.getRelayAgentIPv6Address(clientInterfaces);
Yi Tseng3bd57ac2017-11-29 14:39:18 -08001148 MacAddress relayAgentMac = clientInterfaces.iterator().next().mac();
1149 if (relayAgentIp == null || relayAgentMac == null) {
1150 log.warn("Missing DHCP relay agent interface Ipv6 addr config for "
Kalhee Kim495c9b22017-11-07 16:32:09 +00001151 + "packet from client on port: {}. Aborting packet processing",
1152 clientInterfaces.iterator().next().connectPoint());
Charles Chanb87495c2019-02-01 11:31:50 -08001153 //dhcpRelayCountersStore.incrementCounter(gCount, DhcpRelayCounters.NO_CLIENT_INTF_MAC);
Charles Chan239492c2018-01-22 13:27:28 -08001154 return Lists.newArrayList();
Kalhee Kim121ba922017-11-01 17:56:44 +00001155 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001156
Kalhee Kim495c9b22017-11-07 16:32:09 +00001157 IPv6 clientIpv6 = (IPv6) clientPacket.getPayload();
1158 UDP clientUdp = (UDP) clientIpv6.getPayload();
1159 DHCP6 clientDhcp6 = (DHCP6) clientUdp.getPayload();
1160
Taras Lemkin96a0d342018-03-26 14:52:58 +00001161 boolean directConnFlag = Dhcp6HandlerUtil.directlyConnected(clientDhcp6);
Charles Chana990ce92017-10-30 10:22:50 -07001162
Kalhee Kim121ba922017-11-01 17:56:44 +00001163 ConnectPoint clientConnectionPoint = context.inPacket().receivedFrom();
1164 VlanId vlanIdInUse = VlanId.vlanId(clientPacket.getVlanID());
1165 Interface clientInterface = interfaceService.getInterfacesByPort(clientConnectionPoint)
Taras Lemkin96a0d342018-03-26 14:52:58 +00001166 .stream().filter(iface -> Dhcp6HandlerUtil.interfaceContainsVlan(iface, vlanIdInUse))
Kalhee Kim495c9b22017-11-07 16:32:09 +00001167 .findFirst()
1168 .orElse(null);
Kalhee Kim45fede42017-09-05 19:05:06 +00001169
Kalhee Kim495c9b22017-11-07 16:32:09 +00001170 List<InternalPacket> internalPackets = new ArrayList<>();
1171 List<DhcpServerInfo> serverInfoList = findValidServerInfo(directConnFlag);
1172 List<DhcpServerInfo> copyServerInfoList = new ArrayList<DhcpServerInfo>(serverInfoList);
Kalhee Kim45b24182017-10-18 18:30:23 +00001173
Kalhee Kim495c9b22017-11-07 16:32:09 +00001174 for (DhcpServerInfo serverInfo : copyServerInfoList) {
Taras Lemkin96a0d342018-03-26 14:52:58 +00001175 if (!Dhcp6HandlerUtil.checkDhcpServerConnPt(directConnFlag, serverInfo)) {
Kalhee Kim495c9b22017-11-07 16:32:09 +00001176 log.warn("Can't get server connect point, ignore");
1177 continue;
1178 }
1179 DhcpServerInfo newServerInfo = getHostInfoForServerInfo(serverInfo, serverInfoList);
1180 if (newServerInfo == null) {
1181 log.warn("Can't get server interface with host info resolved, ignore");
1182 continue;
1183 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001184
Kalhee Kim495c9b22017-11-07 16:32:09 +00001185 Interface serverInterface = getServerInterface(newServerInfo);
1186 if (serverInterface == null) {
1187 log.warn("Can't get server interface, ignore");
1188 continue;
1189 }
Kalhee Kimea4b6c22017-11-09 14:38:37 +00001190
Taras Lemkin96a0d342018-03-26 14:52:58 +00001191 Ethernet etherReply = Dhcp6HandlerUtil.buildDhcp6PacketFromClient(context, clientPacket,
Kalhee Kim495c9b22017-11-07 16:32:09 +00001192 clientInterfaces, newServerInfo, serverInterface);
1193 removeHostOrRoute(directConnFlag, clientConnectionPoint, clientDhcp6, clientPacket,
1194 clientIpv6, clientInterface);
Kalhee Kimea4b6c22017-11-09 14:38:37 +00001195
Taras Lemkin96a0d342018-03-26 14:52:58 +00001196 InternalPacket internalPacket = InternalPacket.internalPacket(etherReply,
Kalhee Kim495c9b22017-11-07 16:32:09 +00001197 serverInfo.getDhcpServerConnectPoint().get());
1198 internalPackets.add(internalPacket);
1199 }
1200 log.debug("num of client packets to send is{}", internalPackets.size());
Kalhee Kimea4b6c22017-11-09 14:38:37 +00001201
Kalhee Kim495c9b22017-11-07 16:32:09 +00001202 return internalPackets;
1203 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001204
1205 /**
Kalhee Kim45fede42017-09-05 19:05:06 +00001206 * process the DHCP6 relay-reply packet from dhcp server.
1207 *
1208 * @param context packet context
1209 * @param receivedPacket server ethernet packet
1210 * @param recevingInterfaces set of server side interfaces
Kalhee Kim495c9b22017-11-07 16:32:09 +00001211 * @return internalPacket toward client
Kalhee Kim45fede42017-09-05 19:05:06 +00001212 */
1213 private InternalPacket processDhcp6PacketFromServer(PacketContext context,
1214 Ethernet receivedPacket, Set<Interface> recevingInterfaces) {
Kalhee Kim45fede42017-09-05 19:05:06 +00001215 // get dhcp6 header.
Ray Milkeyf0c47612017-09-28 11:29:38 -07001216 Ethernet etherReply = receivedPacket.duplicate();
Kalhee Kim45fede42017-09-05 19:05:06 +00001217 IPv6 ipv6Packet = (IPv6) etherReply.getPayload();
1218 UDP udpPacket = (UDP) ipv6Packet.getPayload();
1219 DHCP6 dhcp6Relay = (DHCP6) udpPacket.getPayload();
Taras Lemkin96a0d342018-03-26 14:52:58 +00001220 Boolean directConnFlag = Dhcp6HandlerUtil.directlyConnected(dhcp6Relay);
Kalhee Kim45fede42017-09-05 19:05:06 +00001221
Kalhee Kim495c9b22017-11-07 16:32:09 +00001222 DHCP6 embeddedDhcp6 = dhcp6Relay.getOptions().stream()
1223 .filter(opt -> opt instanceof Dhcp6RelayOption)
1224 .map(BasePacket::getPayload)
1225 .map(pld -> (DHCP6) pld)
1226 .findFirst()
1227 .orElse(null);
Kalhee Kimd21029f2017-09-26 20:21:53 +00001228 ConnectPoint inPort = context.inPacket().receivedFrom();
Kalhee Kim495c9b22017-11-07 16:32:09 +00001229 DhcpServerInfo foundServerInfo = findServerInfoFromServer(directConnFlag, inPort);
Kalhee Kimd21029f2017-09-26 20:21:53 +00001230
Kalhee Kim495c9b22017-11-07 16:32:09 +00001231 if (foundServerInfo == null) {
jayakumarthazhathed5f05d2018-09-25 15:56:51 -04001232 log.warn("Cannot find server info for {} server, inPort {}",
1233 directConnFlag ? "direct" : "indirect", inPort);
Charles Chanb87495c2019-02-01 11:31:50 -08001234 //dhcpRelayCountersStore.incrementCounter(gCount, DhcpRelayCounters.NO_SERVER_INFO);
Kalhee Kimd21029f2017-09-26 20:21:53 +00001235 return null;
Kalhee Kim495c9b22017-11-07 16:32:09 +00001236 } else {
Taras Lemkin96a0d342018-03-26 14:52:58 +00001237 if (Dhcp6HandlerUtil.isServerIpEmpty(foundServerInfo)) {
Kalhee Kim495c9b22017-11-07 16:32:09 +00001238 log.warn("Cannot find server info's ipaddress");
Charles Chanb87495c2019-02-01 11:31:50 -08001239 //dhcpRelayCountersStore.incrementCounter(gCount, DhcpRelayCounters.NO_SERVER_IP6ADDR);
Kalhee Kim495c9b22017-11-07 16:32:09 +00001240 return null;
1241 }
Kalhee Kimd21029f2017-09-26 20:21:53 +00001242 }
1243
Kalhee Kim45fede42017-09-05 19:05:06 +00001244 Dhcp6InterfaceIdOption interfaceIdOption = dhcp6Relay.getOptions().stream()
1245 .filter(opt -> opt instanceof Dhcp6InterfaceIdOption)
1246 .map(opt -> (Dhcp6InterfaceIdOption) opt)
1247 .findFirst()
1248 .orElse(null);
Kalhee Kim45fede42017-09-05 19:05:06 +00001249 if (interfaceIdOption == null) {
1250 log.warn("Interface Id option is not present, abort packet...");
Charles Chanb87495c2019-02-01 11:31:50 -08001251 //dhcpRelayCountersStore.incrementCounter(gCount, DhcpRelayCounters.OPTION_MISSING_FAIL);
Kalhee Kim45fede42017-09-05 19:05:06 +00001252 return null;
1253 }
1254
1255 MacAddress peerMac = interfaceIdOption.getMacAddress();
1256 String clientConnectionPointStr = new String(interfaceIdOption.getInPort());
Kalhee Kim45fede42017-09-05 19:05:06 +00001257 ConnectPoint clientConnectionPoint = ConnectPoint.deviceConnectPoint(clientConnectionPointStr);
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +00001258 VlanId vlanIdInUse = VlanId.vlanId(interfaceIdOption.getVlanId());
Harshada Chaundkarf0780fe2019-05-06 20:16:13 +00001259
1260 log.debug("processDhcp6PacketFromServer Interface Id Mac {}, port{}, vlan {}",
1261 peerMac, clientConnectionPointStr, vlanIdInUse);
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +00001262 Interface clientInterface = interfaceService.getInterfacesByPort(clientConnectionPoint)
Taras Lemkin96a0d342018-03-26 14:52:58 +00001263 .stream().filter(iface -> Dhcp6HandlerUtil.interfaceContainsVlan(iface, vlanIdInUse))
Kalhee Kim495c9b22017-11-07 16:32:09 +00001264 .findFirst().orElse(null);
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +00001265 if (clientInterface == null) {
1266 log.warn("Cannot get client interface for from packet, abort... vlan {}", vlanIdInUse.toString());
Charles Chanb87495c2019-02-01 11:31:50 -08001267 //dhcpRelayCountersStore.incrementCounter(gCount, DhcpRelayCounters.NO_MATCHING_INTF);
Kalhee Kim45fede42017-09-05 19:05:06 +00001268 return null;
1269 }
Kalhee Kim44fbda12018-04-03 21:08:18 +00001270 etherReply.setVlanID(vlanIdInUse.toShort());
1271
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +00001272 MacAddress relayAgentMac = clientInterface.mac();
Kalhee Kim45fede42017-09-05 19:05:06 +00001273 if (relayAgentMac == null) {
Yi Tseng68ef26b2017-12-18 17:10:00 -08001274 log.warn("Can not get client interface mac, abort packet..");
Charles Chanb87495c2019-02-01 11:31:50 -08001275 //dhcpRelayCountersStore.incrementCounter(gCount, DhcpRelayCounters.NO_CLIENT_INTF_MAC);
Kalhee Kim45fede42017-09-05 19:05:06 +00001276 return null;
1277 }
1278 etherReply.setSourceMACAddress(relayAgentMac);
1279
1280 // find destMac
Yi Tseng68ef26b2017-12-18 17:10:00 -08001281 MacAddress clientMac;
Yi Tsengaa417a62017-09-08 17:22:51 -07001282 Ip6Address peerAddress = Ip6Address.valueOf(dhcp6Relay.getPeerAddress());
1283 Set<Host> clients = hostService.getHostsByIp(peerAddress);
Kalhee Kim45fede42017-09-05 19:05:06 +00001284 if (clients.isEmpty()) {
Yi Tseng68ef26b2017-12-18 17:10:00 -08001285 log.trace("There's no host found for this address {}",
Kalhee Kim45fede42017-09-05 19:05:06 +00001286 HexString.toHexString(dhcp6Relay.getPeerAddress(), ":"));
Yi Tseng68ef26b2017-12-18 17:10:00 -08001287 log.trace("Let's look up interfaceId {}", HexString.toHexString(peerMac.toBytes(), ":"));
Kalhee Kim45fede42017-09-05 19:05:06 +00001288 clientMac = peerMac;
1289 } else {
1290 clientMac = clients.iterator().next().mac();
1291 if (clientMac == null) {
1292 log.warn("No client mac address found, abort packet...");
Charles Chanb87495c2019-02-01 11:31:50 -08001293 //dhcpRelayCountersStore.incrementCounter(gCount, DhcpRelayCounters.NO_CLIENT_INTF_MAC);
Kalhee Kim45fede42017-09-05 19:05:06 +00001294 return null;
1295 }
Yi Tseng68ef26b2017-12-18 17:10:00 -08001296 log.trace("Client mac address found from getHostByIp");
Kalhee Kim45fede42017-09-05 19:05:06 +00001297 }
1298 etherReply.setDestinationMACAddress(clientMac);
Kalhee Kim45fede42017-09-05 19:05:06 +00001299 // ip header
1300 ipv6Packet.setSourceAddress(dhcp6Relay.getLinkAddress());
1301 ipv6Packet.setDestinationAddress(dhcp6Relay.getPeerAddress());
1302 // udp header
1303 udpPacket.setSourcePort(UDP.DHCP_V6_SERVER_PORT);
1304 if (directConnFlag) {
1305 udpPacket.setDestinationPort(UDP.DHCP_V6_CLIENT_PORT);
1306 } else {
1307 udpPacket.setDestinationPort(UDP.DHCP_V6_SERVER_PORT);
1308 }
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001309
Kalhee Kim45fede42017-09-05 19:05:06 +00001310
Taras Lemkin96a0d342018-03-26 14:52:58 +00001311 boolean hostOrRouteAllowed = learnRouteFromLeasequery ||
1312 Dhcp6HandlerUtil.getDhcp6LeafMessageType(dhcp6Relay) != MsgType.LEASEQUERY_REPLY;
1313 log.debug("Can add host or route: {}", hostOrRouteAllowed);
1314
1315 if (hostOrRouteAllowed) {
1316 // add host or route
1317 addHostOrRoute(directConnFlag, clientConnectionPoint, dhcp6Relay, embeddedDhcp6,
1318 clientMac, clientInterface);
1319 }
1320
Kalhee Kim45fede42017-09-05 19:05:06 +00001321 udpPacket.setPayload(embeddedDhcp6);
1322 udpPacket.resetChecksum();
1323 ipv6Packet.setPayload(udpPacket);
1324 etherReply.setPayload(ipv6Packet);
Taras Lemkin96a0d342018-03-26 14:52:58 +00001325 return InternalPacket.internalPacket(etherReply, clientConnectionPoint);
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001326 }
Yi Tseng483ac6f2017-08-02 15:03:31 -07001327
1328 @Override
Kalhee Kimba366062017-11-07 16:32:09 +00001329 public void setDhcpFpmEnabled(Boolean enabled) {
1330 dhcpFpmEnabled = enabled;
1331 }
1332
1333 @Override
Yi Tseng483ac6f2017-08-02 15:03:31 -07001334 public void setDefaultDhcpServerConfigs(Collection<DhcpServerConfig> configs) {
Kalhee Kim495c9b22017-11-07 16:32:09 +00001335 log.debug("setDefaultDhcpServerConfigs is called.");
Yi Tseng919b2df2017-09-07 16:22:51 -07001336 setDhcpServerConfigs(configs, defaultServerInfoList);
Yi Tseng919b2df2017-09-07 16:22:51 -07001337 }
1338
1339 @Override
1340 public void setIndirectDhcpServerConfigs(Collection<DhcpServerConfig> configs) {
Kalhee Kim495c9b22017-11-07 16:32:09 +00001341 log.debug("setIndirectDhcpServerConfigs is called.");
Yi Tseng919b2df2017-09-07 16:22:51 -07001342 setDhcpServerConfigs(configs, indirectServerInfoList);
Yi Tseng919b2df2017-09-07 16:22:51 -07001343 }
1344
1345 public void setDhcpServerConfigs(Collection<DhcpServerConfig> configs, List<DhcpServerInfo> serverInfoList) {
Kalhee Kim495c9b22017-11-07 16:32:09 +00001346 log.debug("config size {}.", configs.size());
1347
Kalhee Kim45fede42017-09-05 19:05:06 +00001348 if (configs.size() == 0) {
1349 // no config to update
1350 return;
1351 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001352 // TODO: currently we pick up first DHCP server config.
1353 // Will use other server configs in the future for HA.
Kalhee Kim495c9b22017-11-07 16:32:09 +00001354 Boolean isConfigValid = false;
1355 for (DhcpServerConfig serverConfig : configs) {
1356 if (serverConfig.getDhcpServerIp6().isPresent()) {
1357 isConfigValid = true;
1358 break;
1359 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001360 }
Kalhee Kim495c9b22017-11-07 16:32:09 +00001361 if (!isConfigValid) {
1362 log.warn("No IP V6 server address found.");
1363 return; // No IP V6 address found
1364 }
1365 for (DhcpServerInfo oldServerInfo : serverInfoList) {
Yi Tseng919b2df2017-09-07 16:22:51 -07001366 // stop monitoring gateway or server
1367 oldServerInfo.getDhcpGatewayIp6().ifPresent(gatewayIp -> {
1368 hostService.stopMonitoringIp(gatewayIp);
1369 });
1370 oldServerInfo.getDhcpServerIp6().ifPresent(serverIp -> {
1371 hostService.stopMonitoringIp(serverIp);
Yi Tseng525ff402017-10-23 19:39:39 -07001372 cancelDhcpPacket(serverIp);
Yi Tseng919b2df2017-09-07 16:22:51 -07001373 });
1374 }
Kalhee Kim495c9b22017-11-07 16:32:09 +00001375 serverInfoList.clear();
1376 for (DhcpServerConfig serverConfig : configs) {
1377 // Create new server info according to the config
1378 DhcpServerInfo newServerInfo = new DhcpServerInfo(serverConfig,
1379 DhcpServerInfo.Version.DHCP_V6);
1380 checkState(newServerInfo.getDhcpServerConnectPoint().isPresent(),
1381 "Connect point not exists");
1382 checkState(newServerInfo.getDhcpServerIp6().isPresent(),
1383 "IP of DHCP server not exists");
Yi Tseng919b2df2017-09-07 16:22:51 -07001384
Kalhee Kim495c9b22017-11-07 16:32:09 +00001385 log.debug("DHCP server connect point: {}", newServerInfo.getDhcpServerConnectPoint().orElse(null));
1386 log.debug("DHCP server IP: {}", newServerInfo.getDhcpServerIp6().orElse(null));
Yi Tseng919b2df2017-09-07 16:22:51 -07001387
Kalhee Kim495c9b22017-11-07 16:32:09 +00001388 Ip6Address serverIp = newServerInfo.getDhcpServerIp6().get();
1389 Ip6Address ipToProbe;
1390 if (newServerInfo.getDhcpGatewayIp6().isPresent()) {
1391 ipToProbe = newServerInfo.getDhcpGatewayIp6().get();
1392 } else {
1393 ipToProbe = newServerInfo.getDhcpServerIp6().orElse(null);
1394 }
1395 String hostToProbe = newServerInfo.getDhcpGatewayIp6()
1396 .map(ip -> "gateway").orElse("server");
Yi Tseng919b2df2017-09-07 16:22:51 -07001397
Kalhee Kim495c9b22017-11-07 16:32:09 +00001398 log.warn("Probing to resolve {} IP {}", hostToProbe, ipToProbe);
1399 hostService.startMonitoringIp(ipToProbe);
1400
1401 Set<Host> hosts = hostService.getHostsByIp(ipToProbe);
1402 if (!hosts.isEmpty()) {
1403 Host host = hosts.iterator().next();
1404 newServerInfo.setDhcpConnectVlan(host.vlan());
1405 newServerInfo.setDhcpConnectMac(host.mac());
1406 log.warn("Host found host {}", host);
1407
1408 } else {
1409 log.warn("No host found host ip {}", ipToProbe);
1410 }
1411 // Add new server info
1412 synchronized (this) {
1413 serverInfoList.add(newServerInfo);
1414 }
1415 if (!hosts.isEmpty()) {
1416 requestDhcpPacket(serverIp);
1417 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001418 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001419 }
1420
1421 class InternalHostListener implements HostListener {
1422 @Override
1423 public void event(HostEvent event) {
1424 switch (event.type()) {
1425 case HOST_ADDED:
1426 case HOST_UPDATED:
Charles Chan24a96ff2018-08-13 10:32:03 -07001427 case HOST_MOVED:
Jordan Halterman6328db72018-04-10 13:34:50 -04001428 log.trace("Scheduled host event {}", event);
1429 hostEventExecutor.execute(() -> hostUpdated(event.subject()));
Kalhee Kim45fede42017-09-05 19:05:06 +00001430 break;
1431 case HOST_REMOVED:
Jordan Halterman6328db72018-04-10 13:34:50 -04001432 log.trace("Scheduled host event {}", event);
1433 hostEventExecutor.execute(() -> hostRemoved(event.subject()));
Kalhee Kim45fede42017-09-05 19:05:06 +00001434 break;
Kalhee Kim45fede42017-09-05 19:05:06 +00001435 default:
1436 break;
1437 }
1438 }
1439 }
1440
1441 /**
Kalhee Kim45fede42017-09-05 19:05:06 +00001442 * Handle host updated.
1443 * If the host is DHCP server or gateway, update connect mac and vlan.
1444 *
1445 * @param host the host
1446 */
1447 private void hostUpdated(Host host) {
Yi Tseng525ff402017-10-23 19:39:39 -07001448 hostUpdated(host, defaultServerInfoList);
1449 hostUpdated(host, indirectServerInfoList);
Kalhee Kim45fede42017-09-05 19:05:06 +00001450 }
1451
Yi Tseng525ff402017-10-23 19:39:39 -07001452 private void hostUpdated(Host host, List<DhcpServerInfo> serverInfoList) {
jjosep004c05f55ab2018-08-21 09:01:10 -04001453 serverInfoList.stream().forEach(serverInfo -> {
Yi Tseng525ff402017-10-23 19:39:39 -07001454 Ip6Address serverIp = serverInfo.getDhcpServerIp6().orElse(null);
jjosep004c05f55ab2018-08-21 09:01:10 -04001455 Ip6Address targetIp = serverInfo.getDhcpGatewayIp6().orElse(null);
Yi Tseng525ff402017-10-23 19:39:39 -07001456
1457 if (targetIp == null) {
1458 targetIp = serverIp;
1459 }
Yi Tseng525ff402017-10-23 19:39:39 -07001460 if (targetIp != null) {
1461 if (host.ipAddresses().contains(targetIp)) {
1462 serverInfo.setDhcpConnectMac(host.mac());
1463 serverInfo.setDhcpConnectVlan(host.vlan());
1464 requestDhcpPacket(serverIp);
1465 }
1466 }
jjosep004c05f55ab2018-08-21 09:01:10 -04001467 });
Yi Tseng525ff402017-10-23 19:39:39 -07001468 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001469 /**
1470 * Handle host removed.
1471 * If the host is DHCP server or gateway, unset connect mac and vlan.
1472 *
1473 * @param host the host
1474 */
1475 private void hostRemoved(Host host) {
Yi Tseng525ff402017-10-23 19:39:39 -07001476 hostRemoved(host, defaultServerInfoList);
1477 hostRemoved(host, indirectServerInfoList);
Yi Tseng919b2df2017-09-07 16:22:51 -07001478 }
1479
Yi Tseng525ff402017-10-23 19:39:39 -07001480 private void hostRemoved(Host host, List<DhcpServerInfo> serverInfoList) {
jjosep004c05f55ab2018-08-21 09:01:10 -04001481 serverInfoList.stream().forEach(serverInfo -> {
Yi Tseng525ff402017-10-23 19:39:39 -07001482 Ip6Address serverIp = serverInfo.getDhcpServerIp6().orElse(null);
jjosep004c05f55ab2018-08-21 09:01:10 -04001483 Ip6Address targetIp = serverInfo.getDhcpGatewayIp6().orElse(null);
Yi Tseng525ff402017-10-23 19:39:39 -07001484
1485 if (targetIp == null) {
1486 targetIp = serverIp;
1487 }
Yi Tseng525ff402017-10-23 19:39:39 -07001488 if (targetIp != null) {
1489 if (host.ipAddresses().contains(targetIp)) {
1490 serverInfo.setDhcpConnectVlan(null);
1491 serverInfo.setDhcpConnectMac(null);
1492 cancelDhcpPacket(serverIp);
1493 }
1494 }
jjosep004c05f55ab2018-08-21 09:01:10 -04001495 });
Yi Tseng525ff402017-10-23 19:39:39 -07001496 }
1497
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001498 /**
1499 * Gets Interface facing to the server for default host.
1500 *
1501 * @return the Interface facing to the server; null if not found
1502 */
1503 private Interface getServerInterface() {
1504 DhcpServerInfo serverInfo;
1505 ConnectPoint dhcpServerConnectPoint;
1506 VlanId dhcpConnectVlan;
1507
1508 if (!defaultServerInfoList.isEmpty()) {
1509 serverInfo = defaultServerInfoList.get(0);
1510 dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1511 dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
1512 } else {
1513 return null;
1514 }
1515 if (dhcpServerConnectPoint == null || dhcpConnectVlan == null) {
1516 log.info("Default DHCP server {} not resolve yet", serverInfo.getDhcpGatewayIp6());
1517 return null;
1518 }
1519 return interfaceService.getInterfacesByPort(dhcpServerConnectPoint)
1520 .stream()
Taras Lemkin96a0d342018-03-26 14:52:58 +00001521 .filter(iface -> Dhcp6HandlerUtil.interfaceContainsVlan(iface, dhcpConnectVlan))
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001522 .findFirst()
1523 .orElse(null);
1524 }
1525
1526 /**
1527 * Gets Interface facing to the server for indirect hosts.
1528 * Use default server Interface if indirect server not configured.
1529 *
1530 * @return the Interface facing to the server; null if not found
1531 */
1532 private Interface getIndirectServerInterface() {
1533 DhcpServerInfo serverInfo;
1534
1535 ConnectPoint indirectDhcpServerConnectPoint;
1536 VlanId indirectDhcpConnectVlan;
1537
1538 if (!indirectServerInfoList.isEmpty()) {
1539 serverInfo = indirectServerInfoList.get(0);
1540 indirectDhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1541 indirectDhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
1542 } else {
1543 return getServerInterface();
1544 }
1545 if (indirectDhcpServerConnectPoint == null || indirectDhcpConnectVlan == null) {
1546 log.info("Indirect DHCP server {} not resolve yet", serverInfo.getDhcpGatewayIp6());
1547 return null;
1548 }
1549 return interfaceService.getInterfacesByPort(indirectDhcpServerConnectPoint)
1550 .stream()
Taras Lemkin96a0d342018-03-26 14:52:58 +00001551 .filter(iface -> Dhcp6HandlerUtil.interfaceContainsVlan(iface, indirectDhcpConnectVlan))
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001552 .findFirst()
1553 .orElse(null);
1554 }
1555
Kalhee Kim45b24182017-10-18 18:30:23 +00001556 /**
Kalhee Kim495c9b22017-11-07 16:32:09 +00001557 * Checks if serverInfo's host info (mac and vlan) is filled in; if not, fills in.
1558 *
1559 * @param serverInfo server information
1560 * @return newServerInfo if host info can be either found or filled in.
1561 */
1562 private DhcpServerInfo getHostInfoForServerInfo(DhcpServerInfo serverInfo, List<DhcpServerInfo> sererInfoList) {
1563 DhcpServerInfo newServerInfo = null;
1564 MacAddress dhcpServerConnectMac = serverInfo.getDhcpConnectMac().orElse(null);
1565 VlanId dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
1566 ConnectPoint dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1567
1568 if (dhcpServerConnectMac != null && dhcpConnectVlan != null) {
1569 newServerInfo = serverInfo;
Charles Chan750c9992018-02-26 10:44:49 -08001570 log.debug("DHCP server {} host info found. ConnectPt{} Mac {} vlan {}", serverInfo.getDhcpServerIp6(),
Kalhee Kim495c9b22017-11-07 16:32:09 +00001571 dhcpServerConnectPoint, dhcpServerConnectMac, dhcpConnectVlan);
1572 } else {
Harshada Chaundkarf0780fe2019-05-06 20:16:13 +00001573 log.debug("DHCP server {} not resolve yet connectPt {} mac {} vlan {}", serverInfo.getDhcpServerIp6(),
Kalhee Kim495c9b22017-11-07 16:32:09 +00001574 dhcpServerConnectPoint, dhcpServerConnectMac, dhcpConnectVlan);
1575
1576 Ip6Address ipToProbe;
1577 if (serverInfo.getDhcpGatewayIp6().isPresent()) {
1578 ipToProbe = serverInfo.getDhcpGatewayIp6().get();
1579 } else {
1580 ipToProbe = serverInfo.getDhcpServerIp6().orElse(null);
1581 }
1582 String hostToProbe = serverInfo.getDhcpGatewayIp6()
1583 .map(ip -> "gateway").orElse("server");
1584
Harshada Chaundkarf0780fe2019-05-06 20:16:13 +00001585 log.debug("Dynamically probing to resolve {} IP {}", hostToProbe, ipToProbe);
Kalhee Kim495c9b22017-11-07 16:32:09 +00001586 hostService.startMonitoringIp(ipToProbe);
1587
1588 Set<Host> hosts = hostService.getHostsByIp(ipToProbe);
1589 if (!hosts.isEmpty()) {
1590 int serverInfoIndex = sererInfoList.indexOf(serverInfo);
1591 Host host = hosts.iterator().next();
1592 serverInfo.setDhcpConnectVlan(host.vlan());
1593 serverInfo.setDhcpConnectMac(host.mac());
1594 // replace the serverInfo in the list
1595 sererInfoList.set(serverInfoIndex, serverInfo);
1596 newServerInfo = serverInfo;
1597 log.warn("Dynamically host found host {}", host);
1598 } else {
Harshada Chaundkarf0780fe2019-05-06 20:16:13 +00001599 log.debug("No host found host ip {} dynamically", ipToProbe);
Kalhee Kim495c9b22017-11-07 16:32:09 +00001600 }
1601 }
1602 return newServerInfo;
1603 }
1604
1605 /**
Kalhee Kim45b24182017-10-18 18:30:23 +00001606 * Gets Interface facing to the server for default host.
1607 *
Kalhee Kim495c9b22017-11-07 16:32:09 +00001608 * @param serverInfo server information
Kalhee Kim45b24182017-10-18 18:30:23 +00001609 * @return the Interface facing to the server; null if not found
1610 */
Kalhee Kim495c9b22017-11-07 16:32:09 +00001611 private Interface getServerInterface(DhcpServerInfo serverInfo) {
1612 Interface serverInterface = null;
Yi Tseng25bfe372017-11-03 16:27:32 -07001613
Kalhee Kim495c9b22017-11-07 16:32:09 +00001614 ConnectPoint dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1615 VlanId dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
1616
1617 if (dhcpServerConnectPoint != null && dhcpConnectVlan != null) {
1618 serverInterface = interfaceService.getInterfacesByPort(dhcpServerConnectPoint)
1619 .stream()
Taras Lemkin96a0d342018-03-26 14:52:58 +00001620 .filter(iface -> Dhcp6HandlerUtil.interfaceContainsVlan(iface, dhcpConnectVlan))
Kalhee Kim495c9b22017-11-07 16:32:09 +00001621 .findFirst()
1622 .orElse(null);
Yi Tseng25bfe372017-11-03 16:27:32 -07001623 } else {
Kalhee Kim495c9b22017-11-07 16:32:09 +00001624 log.warn("DHCP server {} not resolve yet connectPoint {} vlan {}", serverInfo.getDhcpServerIp6(),
1625 dhcpServerConnectPoint, dhcpConnectVlan);
Kalhee Kim45b24182017-10-18 18:30:23 +00001626 }
Kalhee Kim495c9b22017-11-07 16:32:09 +00001627
1628 return serverInterface;
Kalhee Kim45b24182017-10-18 18:30:23 +00001629 }
1630
Yi Tseng525ff402017-10-23 19:39:39 -07001631 private void requestDhcpPacket(Ip6Address serverIp) {
1632 requestServerDhcpPacket(serverIp);
1633 requestClientDhcpPacket(serverIp);
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001634 requestServerLQPacket(serverIp);
Yi Tseng525ff402017-10-23 19:39:39 -07001635 }
1636
1637 private void cancelDhcpPacket(Ip6Address serverIp) {
1638 cancelServerDhcpPacket(serverIp);
1639 cancelClientDhcpPacket(serverIp);
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001640 cancelServerLQPacket(serverIp);
Yi Tseng525ff402017-10-23 19:39:39 -07001641 }
1642
1643 private void cancelServerDhcpPacket(Ip6Address serverIp) {
1644 TrafficSelector serverSelector =
1645 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1646 .matchIPv6Src(serverIp.toIpPrefix())
1647 .build();
1648 packetService.cancelPackets(serverSelector,
1649 PacketPriority.CONTROL,
1650 appId);
1651 }
1652
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001653 private void cancelServerLQPacket(Ip6Address serverIp) {
1654 TrafficSelector serverSelector =
1655 DefaultTrafficSelector.builder(LEASE_QUERY_RESPONSE_SELECTOR)
1656 .matchIPv6Src(serverIp.toIpPrefix())
1657 .build();
1658 packetService.cancelPackets(serverSelector,
1659 PacketPriority.CONTROL,
1660 appId);
1661 }
1662
Yi Tseng525ff402017-10-23 19:39:39 -07001663 private void requestServerDhcpPacket(Ip6Address serverIp) {
1664 TrafficSelector serverSelector =
1665 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1666 .matchIPv6Src(serverIp.toIpPrefix())
1667 .build();
1668 packetService.requestPackets(serverSelector,
1669 PacketPriority.CONTROL,
1670 appId);
1671 }
1672
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001673 private void requestServerLQPacket(Ip6Address serverIp) {
1674 TrafficSelector serverSelector =
1675 DefaultTrafficSelector.builder(LEASE_QUERY_RESPONSE_SELECTOR)
1676 .matchIPv6Src(serverIp.toIpPrefix())
1677 .build();
1678 packetService.requestPackets(serverSelector,
1679 PacketPriority.CONTROL,
1680 appId);
1681 }
1682
Yi Tseng525ff402017-10-23 19:39:39 -07001683 private void cancelClientDhcpPacket(Ip6Address serverIp) {
1684 // Packet comes from relay
1685 TrafficSelector indirectClientSelector =
1686 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1687 .matchIPv6Dst(serverIp.toIpPrefix())
1688 .build();
1689 packetService.cancelPackets(indirectClientSelector,
1690 PacketPriority.CONTROL,
1691 appId);
Yi Tseng41dde702017-11-02 15:21:10 -07001692 indirectClientSelector =
1693 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1694 .matchIPv6Dst(Ip6Address.ALL_DHCP_RELAY_AGENTS_AND_SERVERS.toIpPrefix())
1695 .build();
1696 packetService.cancelPackets(indirectClientSelector,
1697 PacketPriority.CONTROL,
1698 appId);
1699 indirectClientSelector =
1700 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1701 .matchIPv6Dst(Ip6Address.ALL_DHCP_SERVERS.toIpPrefix())
1702 .build();
1703 packetService.cancelPackets(indirectClientSelector,
1704 PacketPriority.CONTROL,
1705 appId);
Yi Tseng525ff402017-10-23 19:39:39 -07001706
1707 // Packet comes from client
1708 packetService.cancelPackets(CLIENT_SERVER_SELECTOR,
1709 PacketPriority.CONTROL,
1710 appId);
1711 }
1712
1713 private void requestClientDhcpPacket(Ip6Address serverIp) {
1714 // Packet comes from relay
1715 TrafficSelector indirectClientSelector =
1716 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1717 .matchIPv6Dst(serverIp.toIpPrefix())
1718 .build();
1719 packetService.requestPackets(indirectClientSelector,
1720 PacketPriority.CONTROL,
1721 appId);
Yi Tseng41dde702017-11-02 15:21:10 -07001722 indirectClientSelector =
1723 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1724 .matchIPv6Dst(Ip6Address.ALL_DHCP_RELAY_AGENTS_AND_SERVERS.toIpPrefix())
1725 .build();
1726 packetService.requestPackets(indirectClientSelector,
1727 PacketPriority.CONTROL,
1728 appId);
1729 indirectClientSelector =
1730 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1731 .matchIPv6Dst(Ip6Address.ALL_DHCP_SERVERS.toIpPrefix())
1732 .build();
1733 packetService.requestPackets(indirectClientSelector,
1734 PacketPriority.CONTROL,
1735 appId);
Yi Tseng525ff402017-10-23 19:39:39 -07001736
1737 // Packet comes from client
1738 packetService.requestPackets(CLIENT_SERVER_SELECTOR,
1739 PacketPriority.CONTROL,
1740 appId);
1741 }
1742
1743 /**
1744 * Process the ignore rules.
1745 *
1746 * @param deviceId the device id
1747 * @param vlanId the vlan to be ignored
1748 * @param op the operation, ADD to install; REMOVE to uninstall rules
1749 */
1750 private void processIgnoreVlanRule(DeviceId deviceId, VlanId vlanId, Objective.Operation op) {
Yi Tseng525ff402017-10-23 19:39:39 -07001751 AtomicInteger installedCount = new AtomicInteger(DHCP_SELECTORS.size());
1752 DHCP_SELECTORS.forEach(trafficSelector -> {
1753 TrafficSelector selector = DefaultTrafficSelector.builder(trafficSelector)
1754 .matchVlanId(vlanId)
1755 .build();
1756
1757 ForwardingObjective.Builder builder = DefaultForwardingObjective.builder()
1758 .withFlag(ForwardingObjective.Flag.VERSATILE)
1759 .withSelector(selector)
1760 .withPriority(IGNORE_CONTROL_PRIORITY)
Yi Tsengdbabeed2017-11-29 10:49:20 -08001761 .withTreatment(DefaultTrafficTreatment.emptyTreatment())
Yi Tseng525ff402017-10-23 19:39:39 -07001762 .fromApp(appId);
1763
1764
1765 ObjectiveContext objectiveContext = new ObjectiveContext() {
1766 @Override
1767 public void onSuccess(Objective objective) {
1768 log.info("Ignore rule {} (Vlan id {}, device {}, selector {})",
1769 op, vlanId, deviceId, selector);
1770 int countDown = installedCount.decrementAndGet();
1771 if (countDown != 0) {
1772 return;
1773 }
1774 switch (op) {
1775 case ADD:
1776 ignoredVlans.put(deviceId, vlanId);
1777 break;
1778 case REMOVE:
1779 ignoredVlans.remove(deviceId, vlanId);
1780 break;
1781 default:
1782 log.warn("Unsupported objective operation {}", op);
1783 break;
1784 }
1785 }
1786
1787 @Override
1788 public void onError(Objective objective, ObjectiveError error) {
1789 log.warn("Can't {} ignore rule (vlan id {}, selector {}, device {}) due to {}",
1790 op, vlanId, selector, deviceId, error);
1791 }
1792 };
1793
1794 ForwardingObjective fwd;
1795 switch (op) {
1796 case ADD:
1797 fwd = builder.add(objectiveContext);
1798 break;
1799 case REMOVE:
1800 fwd = builder.remove(objectiveContext);
1801 break;
1802 default:
1803 log.warn("Unsupported objective operation {}", op);
1804 return;
1805 }
1806
1807 Device device = deviceService.getDevice(deviceId);
1808 if (device == null || !device.is(Pipeliner.class)) {
1809 log.warn("Device {} is not available now, wait until device is available", deviceId);
1810 return;
1811 }
1812 flowObjectiveService.apply(deviceId, fwd);
1813 });
1814 }
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001815
Kalhee Kim121ba922017-11-01 17:56:44 +00001816 /**
1817 * Find first ipaddress for a given Host info i.e. mac and vlan.
1818 *
1819 * @param clientMac client mac
1820 * @param vlanId packet's vlan
1821 * @return next-hop link-local ipaddress for a given host
1822 */
Kalhee Kim495c9b22017-11-07 16:32:09 +00001823 private IpAddress getFirstIpByHost(Boolean directConnFlag, MacAddress clientMac, VlanId vlanId) {
Kalhee Kim121ba922017-11-01 17:56:44 +00001824 IpAddress nextHopIp;
1825 // pick out the first link-local ip address
1826 HostId gwHostId = HostId.hostId(clientMac, vlanId);
1827 Host gwHost = hostService.getHost(gwHostId);
1828 if (gwHost == null) {
1829 log.warn("Can't find gateway host for hostId {}", gwHostId);
1830 return null;
1831 }
Kalhee Kim495c9b22017-11-07 16:32:09 +00001832 if (directConnFlag) {
1833 nextHopIp = gwHost.ipAddresses()
1834 .stream()
1835 .filter(IpAddress::isIp6)
1836 .map(IpAddress::getIp6Address)
1837 .findFirst()
1838 .orElse(null);
1839 } else {
1840 nextHopIp = gwHost.ipAddresses()
1841 .stream()
1842 .filter(IpAddress::isIp6)
1843 .filter(ip6 -> ip6.isLinkLocal())
1844 .map(IpAddress::getIp6Address)
1845 .findFirst()
1846 .orElse(null);
1847 }
Kalhee Kim121ba922017-11-01 17:56:44 +00001848 return nextHopIp;
1849 }
Kalhee Kimea4b6c22017-11-09 14:38:37 +00001850
Kalhee Kim495c9b22017-11-07 16:32:09 +00001851 private List<DhcpServerInfo> findValidServerInfo(boolean directConnFlag) {
1852 List<DhcpServerInfo> validServerInfo;
1853
1854 if (directConnFlag || indirectServerInfoList.isEmpty()) {
1855 validServerInfo = new ArrayList<DhcpServerInfo>(defaultServerInfoList);
1856 } else {
1857 validServerInfo = new ArrayList<DhcpServerInfo>(indirectServerInfoList);
1858 }
1859 return validServerInfo;
1860 }
1861
1862 private DhcpServerInfo findServerInfoFromServer(boolean directConnFlag, ConnectPoint inPort) {
1863 List<DhcpServerInfo> validServerInfoList = findValidServerInfo(directConnFlag);
1864 DhcpServerInfo foundServerInfo = null;
1865 for (DhcpServerInfo serverInfo : validServerInfoList) {
1866 if (inPort.equals(serverInfo.getDhcpServerConnectPoint().get())) {
1867 foundServerInfo = serverInfo;
Charles Chan750c9992018-02-26 10:44:49 -08001868 log.debug("ServerInfo found for Rcv port {} Server Connect Point {} for {}",
Kalhee Kim495c9b22017-11-07 16:32:09 +00001869 inPort, serverInfo.getDhcpServerConnectPoint(), directConnFlag ? "direct" : "indirect");
1870 break;
Kalhee Kim495c9b22017-11-07 16:32:09 +00001871 }
1872 }
1873 return foundServerInfo;
1874 }
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001875
Kalhee Kim495c9b22017-11-07 16:32:09 +00001876 /**
1877 * Set the dhcp6 lease expiry poll interval value.
1878 *
1879 * @param val poll interval value in seconds
1880 */
Kalhee Kim2f07c602017-11-15 18:57:53 +00001881 @Override
Kalhee Kim495c9b22017-11-07 16:32:09 +00001882 public void setDhcp6PollInterval(int val) {
1883 dhcp6PollInterval = val;
1884 }
1885
Kalhee Kim2f07c602017-11-15 18:57:53 +00001886 /**
1887 * get the dhcp6 lease expiry poll interval value.
1888 * This is a private function
1889 * @return poll interval value in seconds
1890 */
1891 private int getDhcp6PollInterval() {
1892 return dhcp6PollInterval;
1893 }
1894
1895 /**
1896 * Find lease-expired ipaddresses and pd prefixes.
1897 * Removing host/route/fpm entries.
1898 */
1899 public void timeTick() {
1900 long currentTime = System.currentTimeMillis();
1901 Collection<DhcpRecord> records = dhcpRelayStore.getDhcpRecords();
1902
1903 log.debug("timeTick called currenttime {} records num {} ", currentTime, records.size());
1904
1905 records.forEach(record -> {
1906 boolean addrOrPdRemoved = false;
1907 DHCP6.MsgType ip6Status = record.ip6Status().orElse(null);
1908 if (ip6Status == null) {
1909 log.debug("record is not valid v6 record.");
1910 return;
1911 }
1912
1913 if ((currentTime - record.getLastIp6Update()) >
1914 ((record.addrPrefTime() + getDhcp6PollInterval() / 2) * 1000)) {
1915 // remove ipaddress from host/route table
1916 IpAddress ip = record.ip6Address().orElse(null);
1917 if (ip != null) {
1918 if (record.directlyConnected()) {
1919 providerService.removeIpFromHost(HostId.hostId(record.macAddress(),
1920 record.vlanId()), ip);
1921 } else {
1922 MacAddress gwMac = record.nextHop().orElse(null);
1923 if (gwMac == null) {
1924 log.warn("Can't find gateway mac address from record {} for ip6Addr", record);
1925 return;
1926 }
1927 IpAddress nextHopIp = getFirstIpByHost(record.directlyConnected(),
1928 gwMac,
1929 record.vlanId());
Kalhee Kim54a97c92018-04-02 21:23:46 +00001930 Route route = new Route(Route.Source.DHCP, ip.toIpPrefix(), nextHopIp);
Kalhee Kim2f07c602017-11-15 18:57:53 +00001931 routeStore.removeRoute(route);
1932 }
1933 record.updateAddrPrefTime(0);
1934 record.ip6Address(null);
1935 addrOrPdRemoved = true;
1936 dhcpRelayStore.updateDhcpRecord(HostId.hostId(record.macAddress(),
1937 record.vlanId()), record);
1938 log.warn("IP6 address is set to null. delta {} lastUpdate {} addrPrefTime {}",
1939 (currentTime - record.getLastIp6Update()), record.getLastIp6Update(),
1940 record.addrPrefTime());
1941 }
1942 }
1943 if ((currentTime - record.getLastPdUpdate()) >
1944 ((record.pdPrefTime() + getDhcp6PollInterval() / 2) * 1000)) {
1945 // remove PD from route/fpm table
1946 IpPrefix pdIpPrefix = record.pdPrefix().orElse(null);
1947 if (pdIpPrefix != null) {
1948 if (record.directlyConnected()) {
1949 providerService.removeIpFromHost(HostId.hostId(record.macAddress(), record.vlanId()),
1950 pdIpPrefix.address().getIp6Address());
1951 } else {
1952 MacAddress gwMac = record.nextHop().orElse(null);
1953 if (gwMac == null) {
1954 log.warn("Can't find gateway mac address from record {} for PD prefix", record);
1955 return;
1956 }
1957 IpAddress nextHopIp = getFirstIpByHost(record.directlyConnected(),
1958 gwMac,
1959 record.vlanId());
Kalhee Kim54a97c92018-04-02 21:23:46 +00001960 Route route = new Route(Route.Source.DHCP, pdIpPrefix, nextHopIp);
Kalhee Kim2f07c602017-11-15 18:57:53 +00001961 routeStore.removeRoute(route);
1962 if (this.dhcpFpmEnabled) {
1963 dhcpFpmPrefixStore.removeFpmRecord(pdIpPrefix);
1964 }
1965 }
1966 record.updatePdPrefTime(0);
1967 record.pdPrefix(null);
1968 addrOrPdRemoved = true;
1969 dhcpRelayStore.updateDhcpRecord(HostId.hostId(record.macAddress(),
1970 record.vlanId()), record);
1971 log.warn("PD prefix is set to null.delta {} pdPrefTime {}",
1972 (currentTime - record.getLastPdUpdate()), record.pdPrefTime());
1973 }
1974 }
1975 if (addrOrPdRemoved &&
1976 !record.ip6Address().isPresent() && !record.pdPrefix().isPresent()) {
1977 log.warn("ip6Status {} IP6 address and IP6 PD both are null. Remove record.", ip6Status);
1978 dhcpRelayStore.removeDhcpRecord(HostId.hostId(record.macAddress(), record.vlanId()));
1979 }
1980 }
1981 );
1982 }
1983}