blob: 109995610e4ccaa0d8792d5dbe46d9fb65bff286 [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;
Taras Lemkin41785912018-03-26 14:52:58 +000025import org.apache.felix.scr.annotations.Activate;
Yi Tseng51301292017-07-28 13:02:59 -070026import org.apache.felix.scr.annotations.Component;
Taras Lemkin41785912018-03-26 14:52:58 +000027import org.apache.felix.scr.annotations.Deactivate;
28import org.apache.felix.scr.annotations.Modified;
Yi Tseng51301292017-07-28 13:02:59 -070029import org.apache.felix.scr.annotations.Property;
Kalhee Kim45fede42017-09-05 19:05:06 +000030import org.apache.felix.scr.annotations.Reference;
31import org.apache.felix.scr.annotations.ReferenceCardinality;
Yi Tseng51301292017-07-28 13:02:59 -070032import org.apache.felix.scr.annotations.Service;
33import org.onlab.packet.BasePacket;
Kalhee Kim45fede42017-09-05 19:05:06 +000034import org.onlab.packet.DHCP6;
35import org.onlab.packet.IPv6;
36import org.onlab.packet.Ethernet;
37import org.onlab.packet.Ip6Address;
Yi Tseng51301292017-07-28 13:02:59 -070038import org.onlab.packet.IpAddress;
Kalhee Kim45fede42017-09-05 19:05:06 +000039import org.onlab.packet.IpPrefix;
Yi Tseng51301292017-07-28 13:02:59 -070040import org.onlab.packet.MacAddress;
Yi Tseng525ff402017-10-23 19:39:39 -070041import org.onlab.packet.TpPort;
Kalhee Kim45fede42017-09-05 19:05:06 +000042import org.onlab.packet.UDP;
Yi Tseng51301292017-07-28 13:02:59 -070043import org.onlab.packet.VlanId;
Lior Assoulinea21c0ca2018-01-28 16:18:48 -080044import org.onlab.packet.dhcp.Dhcp6ClientDataOption;
45import org.onlab.packet.dhcp.Dhcp6LeaseQueryOption;
Kalhee Kim45fede42017-09-05 19:05:06 +000046import org.onlab.packet.dhcp.Dhcp6RelayOption;
47import org.onlab.packet.dhcp.Dhcp6InterfaceIdOption;
Lior Assoulinea21c0ca2018-01-28 16:18:48 -080048import org.onlab.packet.dhcp.Dhcp6Option;
Kalhee Kim45fede42017-09-05 19:05:06 +000049import org.onlab.packet.dhcp.Dhcp6IaNaOption;
50import org.onlab.packet.dhcp.Dhcp6IaTaOption;
51import org.onlab.packet.dhcp.Dhcp6IaPdOption;
52import org.onlab.packet.dhcp.Dhcp6IaAddressOption;
53import org.onlab.packet.dhcp.Dhcp6IaPrefixOption;
Kalhee Kimea4b6c22017-11-09 14:38:37 +000054import org.onlab.packet.dhcp.Dhcp6ClientIdOption;
55import org.onlab.packet.dhcp.Dhcp6Duid;
Kalhee Kim495c9b22017-11-07 16:32:09 +000056import org.onlab.packet.DHCP6.MsgType;
Kalhee Kim45fede42017-09-05 19:05:06 +000057import org.onlab.util.HexString;
Taras Lemkin41785912018-03-26 14:52:58 +000058import org.onlab.util.Tools;
59import org.onosproject.cfg.ComponentConfigService;
Yi Tseng525ff402017-10-23 19:39:39 -070060import org.onosproject.core.ApplicationId;
61import org.onosproject.core.CoreService;
Yi Tseng51301292017-07-28 13:02:59 -070062import org.onosproject.dhcprelay.api.DhcpHandler;
Yi Tseng919b2df2017-09-07 16:22:51 -070063import org.onosproject.dhcprelay.api.DhcpServerInfo;
Yi Tseng525ff402017-10-23 19:39:39 -070064import org.onosproject.dhcprelay.config.IgnoreDhcpConfig;
Kalhee Kim45fede42017-09-05 19:05:06 +000065import org.onosproject.dhcprelay.store.DhcpRelayStore;
Kalhee Kimea4b6c22017-11-09 14:38:37 +000066import org.onosproject.dhcprelay.store.DhcpRecord;
Kalhee Kimba366062017-11-07 16:32:09 +000067import org.onosproject.dhcprelay.store.DhcpFpmPrefixStore;
Kalhee Kimd94ceea2017-11-29 19:03:02 +000068import org.onosproject.dhcprelay.store.DhcpRelayCountersStore;
Yi Tseng525ff402017-10-23 19:39:39 -070069import org.onosproject.net.Device;
70import org.onosproject.net.DeviceId;
Kalhee Kimba366062017-11-07 16:32:09 +000071import org.onosproject.routing.fpm.api.FpmRecord;
Yi Tseng525ff402017-10-23 19:39:39 -070072import org.onosproject.net.behaviour.Pipeliner;
73import org.onosproject.net.device.DeviceService;
74import org.onosproject.net.flow.DefaultTrafficSelector;
75import org.onosproject.net.flow.TrafficSelector;
76import org.onosproject.net.flowobjective.DefaultForwardingObjective;
77import org.onosproject.net.flowobjective.FlowObjectiveService;
78import org.onosproject.net.flowobjective.ForwardingObjective;
79import org.onosproject.net.flowobjective.Objective;
80import org.onosproject.net.flowobjective.ObjectiveContext;
81import org.onosproject.net.flowobjective.ObjectiveError;
Yi Tsengaa417a62017-09-08 17:22:51 -070082import org.onosproject.net.host.HostProvider;
83import org.onosproject.net.host.HostProviderRegistry;
84import org.onosproject.net.host.HostProviderService;
Kalhee Kim45fede42017-09-05 19:05:06 +000085import org.onosproject.net.host.HostService;
86import org.onosproject.net.host.DefaultHostDescription;
87import org.onosproject.net.host.HostDescription;
Kalhee Kim45fede42017-09-05 19:05:06 +000088import org.onosproject.net.host.HostListener;
89import org.onosproject.net.host.HostEvent;
90import org.onosproject.net.intf.Interface;
91import org.onosproject.net.intf.InterfaceService;
Yi Tseng525ff402017-10-23 19:39:39 -070092import org.onosproject.net.packet.PacketPriority;
Yi Tsengaa417a62017-09-08 17:22:51 -070093import org.onosproject.net.provider.ProviderId;
Kalhee Kim45fede42017-09-05 19:05:06 +000094import org.onosproject.routeservice.Route;
95import org.onosproject.routeservice.RouteStore;
Yi Tseng483ac6f2017-08-02 15:03:31 -070096import org.onosproject.dhcprelay.config.DhcpServerConfig;
Yi Tseng51301292017-07-28 13:02:59 -070097import org.onosproject.net.ConnectPoint;
Kalhee Kim45fede42017-09-05 19:05:06 +000098import org.onosproject.net.Host;
99import org.onosproject.net.HostId;
100import org.onosproject.net.HostLocation;
101import org.onosproject.net.packet.DefaultOutboundPacket;
102import org.onosproject.net.packet.OutboundPacket;
Yi Tseng51301292017-07-28 13:02:59 -0700103import org.onosproject.net.packet.PacketContext;
Kalhee Kim45fede42017-09-05 19:05:06 +0000104import org.onosproject.net.packet.PacketService;
Taras Lemkin41785912018-03-26 14:52:58 +0000105import org.osgi.service.component.ComponentContext;
Kalhee Kim45fede42017-09-05 19:05:06 +0000106import org.slf4j.Logger;
107import org.slf4j.LoggerFactory;
108import org.onosproject.net.flow.DefaultTrafficTreatment;
109import org.onosproject.net.flow.TrafficTreatment;
Kalhee Kim45fede42017-09-05 19:05:06 +0000110import java.nio.ByteBuffer;
Taras Lemkin41785912018-03-26 14:52:58 +0000111import java.util.ArrayList;
Yi Tseng483ac6f2017-08-02 15:03:31 -0700112import java.util.Collection;
Taras Lemkin41785912018-03-26 14:52:58 +0000113import java.util.Dictionary;
114import java.util.List;
Yi Tseng51301292017-07-28 13:02:59 -0700115import java.util.Optional;
Kalhee Kim45fede42017-09-05 19:05:06 +0000116import java.util.Set;
Charles Chan909cff82018-03-05 13:14:02 -0800117import java.util.concurrent.CopyOnWriteArrayList;
Jordan Halterman6328db72018-04-10 13:34:50 -0400118import java.util.concurrent.Executor;
Yi Tseng525ff402017-10-23 19:39:39 -0700119import java.util.concurrent.atomic.AtomicInteger;
Kalhee Kim45fede42017-09-05 19:05:06 +0000120import static com.google.common.base.Preconditions.checkNotNull;
121import static com.google.common.base.Preconditions.checkState;
Jordan Halterman6328db72018-04-10 13:34:50 -0400122import static java.util.concurrent.Executors.newSingleThreadExecutor;
123import static org.onlab.util.Tools.groupedThreads;
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
128@Component
129@Service
130@Property(name = "version", value = "6")
Yi Tsengaa417a62017-09-08 17:22:51 -0700131public class Dhcp6HandlerImpl implements DhcpHandler, HostProvider {
Charles Chand988c282017-09-12 17:09:32 -0700132 public static final String DHCP_V6_RELAY_APP = "org.onosproject.Dhcp6HandlerImpl";
Saurav Das7c6dec12017-09-13 14:35:56 -0700133 public static final ProviderId PROVIDER_ID = new ProviderId("dhcp6", DHCP_V6_RELAY_APP);
Yi Tseng525ff402017-10-23 19:39:39 -0700134 private static final int IGNORE_CONTROL_PRIORITY = PacketPriority.CONTROL.priorityValue() + 1000;
Kalhee Kimd94ceea2017-11-29 19:03:02 +0000135 private String gCount = "global";
Taras Lemkin41785912018-03-26 14:52:58 +0000136 private static final String LQ_ROUTE_PROPERTY_NAME = "learnRouteFromLeasequery";
Yi Tseng525ff402017-10-23 19:39:39 -0700137 private static final TrafficSelector CLIENT_SERVER_SELECTOR = DefaultTrafficSelector.builder()
138 .matchEthType(Ethernet.TYPE_IPV6)
139 .matchIPProtocol(IPv6.PROTOCOL_UDP)
140 .matchIPv6Src(IpPrefix.IPV6_LINK_LOCAL_PREFIX)
141 .matchIPv6Dst(Ip6Address.ALL_DHCP_RELAY_AGENTS_AND_SERVERS.toIpPrefix())
142 .matchUdpSrc(TpPort.tpPort(UDP.DHCP_V6_CLIENT_PORT))
143 .matchUdpDst(TpPort.tpPort(UDP.DHCP_V6_SERVER_PORT))
144 .build();
145 private static final TrafficSelector SERVER_RELAY_SELECTOR = DefaultTrafficSelector.builder()
146 .matchEthType(Ethernet.TYPE_IPV6)
147 .matchIPProtocol(IPv6.PROTOCOL_UDP)
148 .matchUdpSrc(TpPort.tpPort(UDP.DHCP_V6_SERVER_PORT))
149 .matchUdpDst(TpPort.tpPort(UDP.DHCP_V6_SERVER_PORT))
150 .build();
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800151 // lease query reply is from server to client (no relay in between) - so we need to
152 // catch that scenario also ..
153 private static final TrafficSelector LEASE_QUERY_RESPONSE_SELECTOR = DefaultTrafficSelector.builder()
154 .matchEthType(Ethernet.TYPE_IPV6)
155 .matchIPProtocol(IPv6.PROTOCOL_UDP)
156 .matchUdpSrc(TpPort.tpPort(UDP.DHCP_V6_SERVER_PORT))
157 .matchUdpDst(TpPort.tpPort(UDP.DHCP_V6_CLIENT_PORT))
158 .build();
Yi Tseng525ff402017-10-23 19:39:39 -0700159 static final Set<TrafficSelector> DHCP_SELECTORS = ImmutableSet.of(
160 CLIENT_SERVER_SELECTOR,
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800161 SERVER_RELAY_SELECTOR,
162 LEASE_QUERY_RESPONSE_SELECTOR
Yi Tseng525ff402017-10-23 19:39:39 -0700163 );
Kalhee Kim45fede42017-09-05 19:05:06 +0000164 private static Logger log = LoggerFactory.getLogger(Dhcp6HandlerImpl.class);
Yi Tseng51301292017-07-28 13:02:59 -0700165
Kalhee Kim45fede42017-09-05 19:05:06 +0000166 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
167 protected DhcpRelayStore dhcpRelayStore;
Yi Tseng51301292017-07-28 13:02:59 -0700168
Kalhee Kim45fede42017-09-05 19:05:06 +0000169 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Kalhee Kimd94ceea2017-11-29 19:03:02 +0000170 protected DhcpRelayCountersStore dhcpRelayCountersStore;
171
172 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Kalhee Kim45fede42017-09-05 19:05:06 +0000173 protected PacketService packetService;
174
175 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Kalhee Kim45fede42017-09-05 19:05:06 +0000176 protected RouteStore routeStore;
177
178 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
179 protected InterfaceService interfaceService;
180
181 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
182 protected HostService hostService;
183
Yi Tsengaa417a62017-09-08 17:22:51 -0700184 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
185 protected HostProviderRegistry providerRegistry;
Kalhee Kim45fede42017-09-05 19:05:06 +0000186
Yi Tseng525ff402017-10-23 19:39:39 -0700187 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
188 protected CoreService coreService;
189
190 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Kalhee Kimba366062017-11-07 16:32:09 +0000191 protected DhcpFpmPrefixStore dhcpFpmPrefixStore;
192
193 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yi Tseng525ff402017-10-23 19:39:39 -0700194 protected DeviceService deviceService;
195
196 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
197 protected FlowObjectiveService flowObjectiveService;
198
Taras Lemkin41785912018-03-26 14:52:58 +0000199 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
200 protected ComponentConfigService cfgService;
201
202 @Property(name = Dhcp6HandlerImpl.LQ_ROUTE_PROPERTY_NAME, boolValue = false,
203 label = "Enable learning routing information from LQ")
204 private Boolean learnRouteFromLeasequery = Boolean.TRUE;
205
Yi Tsengaa417a62017-09-08 17:22:51 -0700206 protected HostProviderService providerService;
Yi Tseng525ff402017-10-23 19:39:39 -0700207 protected ApplicationId appId;
Charles Chan70fdd492018-03-07 17:36:06 -0800208 protected Multimap<DeviceId, VlanId> ignoredVlans = Multimaps.synchronizedMultimap(HashMultimap.create());
Yi Tseng525ff402017-10-23 19:39:39 -0700209 private InternalHostListener hostListener = new InternalHostListener();
Kalhee Kimba366062017-11-07 16:32:09 +0000210 private Boolean dhcpFpmEnabled = false;
Charles Chan909cff82018-03-05 13:14:02 -0800211 private List<DhcpServerInfo> defaultServerInfoList = new CopyOnWriteArrayList<>();
212 private List<DhcpServerInfo> indirectServerInfoList = new CopyOnWriteArrayList<>();
Jordan Halterman6328db72018-04-10 13:34:50 -0400213
214 private Executor hostEventExecutor = newSingleThreadExecutor(
215 groupedThreads("dhcp6-event-host", "%d", log));
216
Kalhee Kim495c9b22017-11-07 16:32:09 +0000217 private class IpAddressInfo {
218 Ip6Address ip6Address;
219 long prefTime;
220 }
221 private class PdPrefixInfo {
222 IpPrefix pdPrefix;
223 long prefTime;
224 }
225 protected int dhcp6PollInterval = 24 * 3600; // 24 hr period
226
Kalhee Kimd94ceea2017-11-29 19:03:02 +0000227 // max 1 thread
228 static Semaphore recordSemaphore = new Semaphore(1);
Kalhee Kim45fede42017-09-05 19:05:06 +0000229
230 // CLIENT message types
231 public static final Set<Byte> MSG_TYPE_FROM_CLIENT =
232 ImmutableSet.of(DHCP6.MsgType.SOLICIT.value(),
233 DHCP6.MsgType.REQUEST.value(),
234 DHCP6.MsgType.REBIND.value(),
235 DHCP6.MsgType.RENEW.value(),
236 DHCP6.MsgType.RELEASE.value(),
237 DHCP6.MsgType.DECLINE.value(),
238 DHCP6.MsgType.CONFIRM.value(),
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800239 DHCP6.MsgType.RELAY_FORW.value(),
240 DHCP6.MsgType.LEASEQUERY.value());
Kalhee Kim45fede42017-09-05 19:05:06 +0000241 // SERVER message types
242 public static final Set<Byte> MSG_TYPE_FROM_SERVER =
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800243 ImmutableSet.of(DHCP6.MsgType.RELAY_REPL.value(),
244 DHCP6.MsgType.LEASEQUERY_REPLY.value());
Kalhee Kim45fede42017-09-05 19:05:06 +0000245
246 @Activate
Taras Lemkin41785912018-03-26 14:52:58 +0000247 protected void activate(ComponentContext context) {
248 cfgService.registerProperties(getClass());
249 modified(context);
Yi Tseng525ff402017-10-23 19:39:39 -0700250 appId = coreService.registerApplication(DHCP_V6_RELAY_APP);
Yi Tsengaa417a62017-09-08 17:22:51 -0700251 providerService = providerRegistry.register(this);
Kalhee Kim45fede42017-09-05 19:05:06 +0000252 hostService.addListener(hostListener);
Yi Tseng51301292017-07-28 13:02:59 -0700253 }
254
Kalhee Kim45fede42017-09-05 19:05:06 +0000255 @Deactivate
256 protected void deactivate() {
Taras Lemkin41785912018-03-26 14:52:58 +0000257 cfgService.unregisterProperties(getClass(), false);
Yi Tsengaa417a62017-09-08 17:22:51 -0700258 providerRegistry.unregister(this);
Kalhee Kim45fede42017-09-05 19:05:06 +0000259 hostService.removeListener(hostListener);
Yi Tseng919b2df2017-09-07 16:22:51 -0700260 defaultServerInfoList.forEach(this::stopMonitoringIps);
Charles Chana134ee32018-07-19 09:52:01 -0700261 defaultServerInfoList.forEach(info -> info.getDhcpServerIp6().ifPresent(this::cancelDhcpPacket));
Yi Tseng919b2df2017-09-07 16:22:51 -0700262 defaultServerInfoList.clear();
263 indirectServerInfoList.forEach(this::stopMonitoringIps);
Charles Chana134ee32018-07-19 09:52:01 -0700264 indirectServerInfoList.forEach(info -> info.getDhcpServerIp6().ifPresent(this::cancelDhcpPacket));
Yi Tseng919b2df2017-09-07 16:22:51 -0700265 indirectServerInfoList.clear();
266 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000267
Taras Lemkin41785912018-03-26 14:52:58 +0000268 @Modified
269 protected void modified(ComponentContext context) {
270 Dictionary<?, ?> properties = context.getProperties();
271 Boolean flag;
272 flag = Tools.isPropertyEnabled(properties, Dhcp6HandlerImpl.LQ_ROUTE_PROPERTY_NAME);
273 if (flag != null) {
274 learnRouteFromLeasequery = flag;
275 log.info("Learning routes from DHCP leasequery is {}",
276 learnRouteFromLeasequery ? "enabled" : "disabled");
277 }
278 }
279
Yi Tseng919b2df2017-09-07 16:22:51 -0700280 private void stopMonitoringIps(DhcpServerInfo serverInfo) {
281 serverInfo.getDhcpGatewayIp6().ifPresent(gatewayIp -> {
282 hostService.stopMonitoringIp(gatewayIp);
283 });
284 serverInfo.getDhcpServerIp6().ifPresent(serverIp -> {
285 hostService.stopMonitoringIp(serverIp);
286 });
Yi Tseng51301292017-07-28 13:02:59 -0700287 }
288
Yi Tseng51301292017-07-28 13:02:59 -0700289 @Override
Yi Tseng919b2df2017-09-07 16:22:51 -0700290 public List<DhcpServerInfo> getDefaultDhcpServerInfoList() {
291 return defaultServerInfoList;
Yi Tseng51301292017-07-28 13:02:59 -0700292 }
293
294 @Override
Yi Tseng919b2df2017-09-07 16:22:51 -0700295 public List<DhcpServerInfo> getIndirectDhcpServerInfoList() {
296 return indirectServerInfoList;
Yi Tseng51301292017-07-28 13:02:59 -0700297 }
298
299 @Override
Yi Tseng525ff402017-10-23 19:39:39 -0700300 public void updateIgnoreVlanConfig(IgnoreDhcpConfig config) {
301 if (config == null) {
302 ignoredVlans.forEach(((deviceId, vlanId) -> {
303 processIgnoreVlanRule(deviceId, vlanId, REMOVE);
304 }));
305 return;
306 }
307 config.ignoredVlans().forEach((deviceId, vlanId) -> {
308 if (ignoredVlans.get(deviceId).contains(vlanId)) {
309 // don't need to process if it already ignored
310 return;
311 }
312 processIgnoreVlanRule(deviceId, vlanId, ADD);
313 });
Yi Tseng525ff402017-10-23 19:39:39 -0700314 ignoredVlans.forEach((deviceId, vlanId) -> {
315 if (!config.ignoredVlans().get(deviceId).contains(vlanId)) {
316 // not contains in new config, remove it
317 processIgnoreVlanRule(deviceId, vlanId, REMOVE);
318 }
319 });
320 }
321
322 @Override
Saurav Dasb805f1a2017-12-13 16:19:35 -0800323 public void removeIgnoreVlanState(IgnoreDhcpConfig config) {
324 if (config == null) {
325 ignoredVlans.clear();
326 return;
327 }
328 config.ignoredVlans().forEach((deviceId, vlanId) -> {
329 ignoredVlans.remove(deviceId, vlanId);
330 });
331 }
332
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800333 public DhcpRecord getDhcpRelayRecordFor(Ip6Address clientAddress) {
334
Taras Lemkin41785912018-03-26 14:52:58 +0000335 Collection<DhcpRecord> records = dhcpRelayStore.getDhcpRecords();
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800336 DhcpRecord dr = null;
337 for (DhcpRecord e:records) {
338 if (e.ip6Address().isPresent()) {
339 if (e.ip6Address().get().equals(clientAddress)) {
340 dr = e;
341 break;
342 }
343 }
344 }
345 return dr;
346 }
347
348 public MacAddress findNextHopMacForIp6FromRelayStore(Ip6Address clientAddress,
349 MacAddress clientMacAddress, VlanId vlanID) {
350
351 DhcpRecord dr = getDhcpRelayRecordFor(clientAddress);
352
353 if (dr != null) {
354 Optional<MacAddress> nextHopTempMac = dr.nextHopTemp();
355 if (nextHopTempMac.isPresent()) {
356 log.info("findNextHopForIp6FromRelayStore " + clientAddress + " got mac " + nextHopTempMac.toString());
357 return nextHopTempMac.get();
358 }
359 } else {
360 log.warn("findNextHopMacForIp6FromRelayStore could NOT find next hop for " + clientAddress);
361 return null;
362 }
363 return null;
364 }
365
366 public Ip6Address findNextHopIp6FromRelayStore(Ip6Address clientAddress) {
367
368 DhcpRecord dr = getDhcpRelayRecordFor(clientAddress);
369 if (dr != null) {
370 Optional<MacAddress> nextHopMac = dr.nextHop();
371 if (nextHopMac.isPresent()) {
372 // find the local ip6 from the host store
373 HostId gwHostId = HostId.hostId(nextHopMac.get(), dr.vlanId());
374 Host gwHost = hostService.getHost(gwHostId);
375 if (gwHost == null) {
376 log.warn("Can't find next hop host ID {}", gwHostId);
377 return null;
378 }
379 Ip6Address nextHopIp = gwHost.ipAddresses()
380 .stream()
381 .filter(IpAddress::isIp6)
382 .filter(IpAddress::isLinkLocal)
383 .map(IpAddress::getIp6Address)
384 .findFirst()
385 .orElse(null);
386
387 log.info("findNextHopIp6FromRelayStore " + clientAddress + " got mac " +
388 nextHopMac.toString() + " ip6 " + nextHopIp);
389 return nextHopIp;
390 }
391 } else {
392 log.warn("findNextHopIp6FromRelayStore could NOT find next hop for " + clientAddress);
393 return null;
394 }
395 return null;
396 }
397
398 private void setPotentialNextHopForIp6InRelayStore(Ip6Address clientAddress,
399 VlanId vlanId, MacAddress nh) {
400 DhcpRecord dr = getDhcpRelayRecordFor(clientAddress);
401 if (dr != null) {
402 dr.nextHopTemp(nh);
403 log.debug("LQ6 potential NH mac " + nh.toString() + " UPDATED in RelayRecord client " + clientAddress);
404 } else {
405 log.warn("LQ6 potential NH mac" + nh.toString() +
406 " NOT FOUND in RelayRecord for client - LQ rejected" + clientAddress);
407 }
408 }
409
410 public void handleLeaseQuery6ReplyMsg(PacketContext context, DHCP6 dhcp6Payload) {
411 ConnectPoint inPort = context.inPacket().receivedFrom();
412 log.info("Got LQV6-REPLY on port {}", inPort);
413 List<Dhcp6Option> lopt = dhcp6Payload.getOptions();
414 log.info("Options list: {}", lopt);
415 // find out if this lease is known is
416 Dhcp6ClientDataOption clientDataOption = dhcp6Payload.getOptions()
417 .stream()
418 .filter(opt -> opt instanceof Dhcp6ClientDataOption)
419 .map(pld -> (Dhcp6ClientDataOption) pld)
420 .findFirst()
421 .orElse(null);
422
423 if (clientDataOption == null) {
424 log.warn("clientDataOption option is not present, " +
425 "lease is UNKNOWN - not adding any new route...");
426 } else {
427 Dhcp6IaAddressOption aiAddressOption = clientDataOption.getOptions()
428 .stream()
429 .filter(opt -> opt instanceof Dhcp6IaAddressOption)
430 .map(pld -> (Dhcp6IaAddressOption) pld)
431 .findFirst()
432 .orElse(null);
433
434 Dhcp6ClientIdOption clientIdOption = clientDataOption.getOptions()
435 .stream()
436 .filter(opt -> opt instanceof Dhcp6ClientIdOption)
437 .map(pld -> (Dhcp6ClientIdOption) pld)
438 .findFirst()
439 .orElse(null);
440
441 if (aiAddressOption == null) {
442 log.warn("clientDataOption from DHCP server does not " +
443 "contains Dhcp6IaAddressOption for the client - giving up...");
444 } else {
445 Ip6Address clientAddress = aiAddressOption.getIp6Address();
446 MacAddress clientMacAddress = MacAddress.valueOf(clientIdOption.getDuid().getLinkLayerAddress());
447 Ethernet packet = context.inPacket().parsed();
448 VlanId vlanId = VlanId.vlanId(packet.getVlanID());
449 MacAddress potentialNextHopMac =
450 findNextHopMacForIp6FromRelayStore(clientAddress, clientMacAddress, vlanId);
451
452 if (potentialNextHopMac == null) {
453 log.warn("Can't find next hop host mac for client {} mac:{}/{}",
454 clientAddress, clientMacAddress, vlanId);
455 return;
456 } else {
457 log.info("Next hop mac for {}/{}/{} is {}", clientAddress,
458 clientMacAddress, vlanId, potentialNextHopMac.toString());
459 }
460 // search the next hop in the hosts store
461 HostId gwHostId = HostId.hostId(potentialNextHopMac, vlanId);
462 Host gwHost = hostService.getHost(gwHostId);
463 if (gwHost == null) {
464 log.warn("Can't find next hop host ID {}", gwHostId);
465 return;
466 }
467 Ip6Address nextHopIp = gwHost.ipAddresses()
468 .stream()
469 .filter(IpAddress::isIp6)
470 .filter(IpAddress::isLinkLocal)
471 .map(IpAddress::getIp6Address)
472 .findFirst()
473 .orElse(null);
474 if (nextHopIp == null) {
475 log.warn("Can't find IP6 address of next hop {}", gwHost);
476 return;
477 }
478 log.info("client " + clientAddress + " is known !");
Kalhee Kim54a97c92018-04-02 21:23:46 +0000479 Route routeForIP6 = new Route(Route.Source.DHCP, clientAddress.toIpPrefix(), nextHopIp);
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800480 log.debug("updating route of Client for indirectly connected.");
481 log.debug("client ip: " + clientAddress + ", next hop ip6: " + nextHopIp);
482 routeStore.updateRoute(routeForIP6);
483 }
484 }
485 }
486
Saurav Dasb805f1a2017-12-13 16:19:35 -0800487 @Override
Kalhee Kim45fede42017-09-05 19:05:06 +0000488 public void processDhcpPacket(PacketContext context, BasePacket payload) {
489 checkNotNull(payload, "DHCP6 payload can't be null");
490 checkState(payload instanceof DHCP6, "Payload is not a DHCP6");
491 DHCP6 dhcp6Payload = (DHCP6) payload;
492 Ethernet receivedPacket = context.inPacket().parsed();
493
494 if (!configured()) {
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800495 log.warn("Missing DHCP6 relay server config. " +
496 "Abort packet processing dhcp6 payload {}", dhcp6Payload);
Kalhee Kim45fede42017-09-05 19:05:06 +0000497 return;
498 }
Kalhee Kim495c9b22017-11-07 16:32:09 +0000499 byte msgTypeVal = dhcp6Payload.getMsgType();
500 MsgType msgType = DHCP6.MsgType.getType(msgTypeVal);
501 log.debug("msgType is {}", msgType);
Kalhee Kim45fede42017-09-05 19:05:06 +0000502
Kalhee Kim45fede42017-09-05 19:05:06 +0000503 ConnectPoint inPort = context.inPacket().receivedFrom();
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800504
Kalhee Kim495c9b22017-11-07 16:32:09 +0000505 if (inPort == null) {
Taras Lemkin41785912018-03-26 14:52:58 +0000506 log.warn("incoming ConnectPoint is null");
Kalhee Kim495c9b22017-11-07 16:32:09 +0000507 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000508 Set<Interface> receivingInterfaces = interfaceService.getInterfacesByPort(inPort);
509 //ignore the packets if dhcp client interface is not configured on onos.
510 if (receivingInterfaces.isEmpty()) {
511 log.warn("Virtual interface is not configured on {}", inPort);
512 return;
513 }
514
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800515 if (msgTypeVal == DHCP6.MsgType.LEASEQUERY.value()) {
Taras Lemkin41785912018-03-26 14:52:58 +0000516 List<InternalPacket> ethernetClientPackets =
517 learnRouteFromLeasequery ?
518 processLQ6PacketFromClient(context, receivedPacket, receivingInterfaces, dhcp6Payload) :
519 processDhcp6ForwardOnly(context, receivedPacket, receivingInterfaces, dhcp6Payload);
520 for (InternalPacket internalPacket : ethernetClientPackets) {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000521 forwardPacket(internalPacket);
Kalhee Kim45fede42017-09-05 19:05:06 +0000522 }
Taras Lemkin41785912018-03-26 14:52:58 +0000523 } else if (msgTypeVal == DHCP6.MsgType.LEASEQUERY_REPLY.value() && learnRouteFromLeasequery) {
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800524 IPv6 clientIpv6 = (IPv6) receivedPacket.getPayload();
525 UDP clientUdp = (UDP) clientIpv6.getPayload();
526 DHCP6 clientDhcp6 = (DHCP6) clientUdp.getPayload();
Taras Lemkin41785912018-03-26 14:52:58 +0000527 Interface serverInterface = Dhcp6HandlerUtil.directlyConnected(clientDhcp6) ?
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800528 getServerInterface() : getIndirectServerInterface();
Kalhee Kim45fede42017-09-05 19:05:06 +0000529 InternalPacket ethernetPacketReply =
Taras Lemkin41785912018-03-26 14:52:58 +0000530 Dhcp6HandlerUtil.processLQ6PacketFromServer(
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800531 defaultServerInfoList, indirectServerInfoList,
532 serverInterface, interfaceService,
533 hostService,
534 context, receivedPacket, receivingInterfaces);
Kalhee Kim45fede42017-09-05 19:05:06 +0000535 if (ethernetPacketReply != null) {
536 forwardPacket(ethernetPacketReply);
537 }
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800538 handleLeaseQuery6ReplyMsg(context, dhcp6Payload);
Taras Lemkin41785912018-03-26 14:52:58 +0000539 } else if (MSG_TYPE_FROM_CLIENT.contains(msgTypeVal)) {
540 List<InternalPacket> ethernetClientPacket =
541 processDhcp6PacketFromClient(context, receivedPacket, receivingInterfaces);
542 for (InternalPacket internalPacket : ethernetClientPacket) {
543 forwardPacket(internalPacket);
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800544 }
Taras Lemkin41785912018-03-26 14:52:58 +0000545 } else if (MSG_TYPE_FROM_SERVER.contains(msgTypeVal)) {
546 log.debug("calling processDhcp6PacketFromServer with RELAY_REPL {}, {}", receivedPacket, dhcp6Payload);
547 InternalPacket ethernetPacketReply =
548 processDhcp6PacketFromServer(context, receivedPacket, receivingInterfaces);
549 if (ethernetPacketReply != null) {
550 forwardPacket(ethernetPacketReply);
551 }
552 } else {
553 log.warn("Not so fast, packet type {} not supported yet", msgTypeVal);
Kalhee Kim45fede42017-09-05 19:05:06 +0000554 }
555 }
556
Kalhee Kim45fede42017-09-05 19:05:06 +0000557 /**
558 * Checks if this app has been configured.
559 *
560 * @return true if all information we need have been initialized
561 */
562 public boolean configured() {
Yi Tseng919b2df2017-09-07 16:22:51 -0700563 return !defaultServerInfoList.isEmpty();
Kalhee Kim45fede42017-09-05 19:05:06 +0000564 }
565
Yi Tsengaa417a62017-09-08 17:22:51 -0700566 @Override
567 public ProviderId id() {
Charles Chand988c282017-09-12 17:09:32 -0700568 return PROVIDER_ID;
Yi Tsengaa417a62017-09-08 17:22:51 -0700569 }
570
571 @Override
572 public void triggerProbe(Host host) {
573 // Do nothing here
574 }
575
Kalhee Kim45fede42017-09-05 19:05:06 +0000576 //forward the packet to ConnectPoint where the DHCP server is attached.
577 private void forwardPacket(InternalPacket packet) {
578 //send Packetout to dhcp server connectpoint.
Taras Lemkin41785912018-03-26 14:52:58 +0000579 if (packet.getDestLocation() != null) {
Kalhee Kim45fede42017-09-05 19:05:06 +0000580 TrafficTreatment t = DefaultTrafficTreatment.builder()
Taras Lemkin41785912018-03-26 14:52:58 +0000581 .setOutput(packet.getDestLocation().port()).build();
Kalhee Kim45fede42017-09-05 19:05:06 +0000582 OutboundPacket o = new DefaultOutboundPacket(
Taras Lemkin41785912018-03-26 14:52:58 +0000583 packet.getDestLocation().deviceId(), t, ByteBuffer.wrap(packet.getPacket().serialize()));
Kalhee Kim45fede42017-09-05 19:05:06 +0000584 packetService.emit(o);
Taras Lemkin41785912018-03-26 14:52:58 +0000585 if (log.isTraceEnabled()) {
586 IPv6 ip6 = (IPv6) packet.getPacket().getPayload();
587 UDP udp = (UDP) ip6.getPayload();
588 DHCP6 dhcp6 = (DHCP6) udp.getPayload();
589 log.trace("Relaying packet to destination {} eth: {} dhcp: {}",
590 packet.getDestLocation(), packet.getPacket(), dhcp6);
591 }
592
593 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000594 }
595
Kalhee Kim45fede42017-09-05 19:05:06 +0000596 /**
597 * extract from dhcp6 packet client ipv6 address of given by dhcp server.
598 *
599 * @param dhcp6 the dhcp6 packet
Kalhee Kim495c9b22017-11-07 16:32:09 +0000600 * @return IpAddressInfo IpAddressInfo given by dhcp server, or null if not exists
Kalhee Kim45fede42017-09-05 19:05:06 +0000601 */
Kalhee Kim495c9b22017-11-07 16:32:09 +0000602 private IpAddressInfo extractIpAddress(DHCP6 dhcp6) {
603 IpAddressInfo ipInfo = new IpAddressInfo();
Kalhee Kim45fede42017-09-05 19:05:06 +0000604
605 log.debug("extractIpAddress enters dhcp6 {}.", dhcp6);
606 // Extract IPv6 address from IA NA ot IA TA option
607 Optional<Dhcp6IaNaOption> iaNaOption = dhcp6.getOptions()
608 .stream()
609 .filter(opt -> opt instanceof Dhcp6IaNaOption)
610 .map(opt -> (Dhcp6IaNaOption) opt)
611 .findFirst();
612 Optional<Dhcp6IaTaOption> iaTaOption = dhcp6.getOptions()
613 .stream()
614 .filter(opt -> opt instanceof Dhcp6IaTaOption)
615 .map(opt -> (Dhcp6IaTaOption) opt)
616 .findFirst();
617 Optional<Dhcp6IaAddressOption> iaAddressOption;
618 if (iaNaOption.isPresent()) {
619 log.debug("Found IPv6 address from iaNaOption {}", iaNaOption);
620
621 iaAddressOption = iaNaOption.get().getOptions().stream()
622 .filter(opt -> opt instanceof Dhcp6IaAddressOption)
623 .map(opt -> (Dhcp6IaAddressOption) opt)
624 .findFirst();
625 } else if (iaTaOption.isPresent()) {
626 log.debug("Found IPv6 address from iaTaOption {}", iaTaOption);
627
628 iaAddressOption = iaTaOption.get().getOptions().stream()
629 .filter(opt -> opt instanceof Dhcp6IaAddressOption)
630 .map(opt -> (Dhcp6IaAddressOption) opt)
631 .findFirst();
632 } else {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000633 log.info("No IPv6 address found from iaTaOption {}", iaTaOption);
Kalhee Kim45fede42017-09-05 19:05:06 +0000634 iaAddressOption = Optional.empty();
635 }
636 if (iaAddressOption.isPresent()) {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000637 ipInfo.ip6Address = iaAddressOption.get().getIp6Address();
638 ipInfo.prefTime = iaAddressOption.get().getPreferredLifetime();
Kalhee Kim45fede42017-09-05 19:05:06 +0000639 log.debug("Found IPv6 address from iaAddressOption {}", iaAddressOption);
Kalhee Kim45fede42017-09-05 19:05:06 +0000640 } else {
641 log.debug("Can't find IPv6 address from DHCPv6 {}", dhcp6);
Kalhee Kim495c9b22017-11-07 16:32:09 +0000642 return null;
Kalhee Kim45fede42017-09-05 19:05:06 +0000643 }
Kalhee Kim495c9b22017-11-07 16:32:09 +0000644 return ipInfo;
Kalhee Kim45fede42017-09-05 19:05:06 +0000645 }
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800646
Kalhee Kim45fede42017-09-05 19:05:06 +0000647 /**
648 * extract from dhcp6 packet Prefix prefix provided by dhcp server.
649 *
650 * @param dhcp6 the dhcp6 payload
651 * @return IpPrefix Prefix Delegation prefix, or null if not exists.
652 */
Kalhee Kim495c9b22017-11-07 16:32:09 +0000653 private PdPrefixInfo extractPrefix(DHCP6 dhcp6) {
654 log.debug("extractPrefix enters {}", dhcp6);
Kalhee Kim45fede42017-09-05 19:05:06 +0000655
656 // extract prefix
Kalhee Kim495c9b22017-11-07 16:32:09 +0000657 PdPrefixInfo pdPrefixInfo = new PdPrefixInfo();
Kalhee Kim45fede42017-09-05 19:05:06 +0000658
659 Ip6Address prefixAddress = null;
660
661 // Extract IPv6 prefix from IA PD option
662 Optional<Dhcp6IaPdOption> iaPdOption = dhcp6.getOptions()
663 .stream()
664 .filter(opt -> opt instanceof Dhcp6IaPdOption)
665 .map(opt -> (Dhcp6IaPdOption) opt)
666 .findFirst();
667
668 Optional<Dhcp6IaPrefixOption> iaPrefixOption;
669 if (iaPdOption.isPresent()) {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000670 log.debug("IA_PD option found {}", iaPdOption);
Kalhee Kim45fede42017-09-05 19:05:06 +0000671
672 iaPrefixOption = iaPdOption.get().getOptions().stream()
673 .filter(opt -> opt instanceof Dhcp6IaPrefixOption)
674 .map(opt -> (Dhcp6IaPrefixOption) opt)
675 .findFirst();
676 } else {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000677 log.debug("IA_PD option NOT found");
Kalhee Kim45fede42017-09-05 19:05:06 +0000678
679 iaPrefixOption = Optional.empty();
680 }
681 if (iaPrefixOption.isPresent()) {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000682 log.debug("IAPrefix Option within IA_PD option found {}", iaPrefixOption);
Kalhee Kim45fede42017-09-05 19:05:06 +0000683
684 prefixAddress = iaPrefixOption.get().getIp6Prefix();
685 int prefixLen = (int) iaPrefixOption.get().getPrefixLength();
Kalhee Kim495c9b22017-11-07 16:32:09 +0000686 log.debug("Prefix length is {} bits", prefixLen);
687 pdPrefixInfo.pdPrefix = IpPrefix.valueOf(prefixAddress, prefixLen);
688 pdPrefixInfo.prefTime = iaPrefixOption.get().getPreferredLifetime();
Kalhee Kim45fede42017-09-05 19:05:06 +0000689 } else {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000690 log.debug("Can't find IPv6 prefix from DHCPv6 {}", dhcp6);
691 return null;
Kalhee Kim45fede42017-09-05 19:05:06 +0000692 }
Kalhee Kim495c9b22017-11-07 16:32:09 +0000693 return pdPrefixInfo;
Kalhee Kim45fede42017-09-05 19:05:06 +0000694 }
695
696 /**
Kalhee Kim495c9b22017-11-07 16:32:09 +0000697 * remove host or route and update dhcp relay record attributes.
Kalhee Kim45fede42017-09-05 19:05:06 +0000698 *
699 * @param directConnFlag flag to show that packet is from directly connected client
Kalhee Kim495c9b22017-11-07 16:32:09 +0000700 * @param location client side connect point
Kalhee Kim45fede42017-09-05 19:05:06 +0000701 * @param dhcp6Packet the dhcp6 payload
702 * @param clientPacket client's ethernet packet
703 * @param clientIpv6 client's Ipv6 packet
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000704 * @param clientInterface client interfaces
Kalhee Kim45fede42017-09-05 19:05:06 +0000705 */
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000706 private void removeHostOrRoute(boolean directConnFlag, ConnectPoint location,
707 DHCP6 dhcp6Packet,
Kalhee Kim45fede42017-09-05 19:05:06 +0000708 Ethernet clientPacket, IPv6 clientIpv6,
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +0000709 Interface clientInterface) {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000710 log.debug("removeHostOrRoute enters {}", dhcp6Packet);
Kalhee Kim121ba922017-11-01 17:56:44 +0000711 VlanId vlanId = clientInterface.vlan();
Kalhee Kim495c9b22017-11-07 16:32:09 +0000712 MacAddress srcMac = clientPacket.getSourceMAC(); // could be gw or host
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000713 MacAddress leafClientMac;
714 byte leafMsgType;
Kalhee Kim495c9b22017-11-07 16:32:09 +0000715 log.debug("client mac {} client vlan {}", HexString.toHexString(srcMac.toBytes(), ":"), vlanId);
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000716
Charles Chanc7f63b62018-08-13 10:32:03 -0700717 Dhcp6ClientIdOption clientIdOption = Dhcp6HandlerUtil.extractClientId(directConnFlag, dhcp6Packet);
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000718 if (clientIdOption != null) {
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000719 if ((clientIdOption.getDuid().getDuidType() == Dhcp6Duid.DuidType.DUID_LLT) ||
720 (clientIdOption.getDuid().getDuidType() == Dhcp6Duid.DuidType.DUID_LL)) {
721 leafClientMac = MacAddress.valueOf(clientIdOption.getDuid().getLinkLayerAddress());
722 } else {
723 log.warn("Link-Layer Address not supported in CLIENTID option. No DhcpRelay Record created.");
Charles Chancd1783f2019-02-01 11:31:50 -0800724 //dhcpRelayCountersStore.incrementCounter(gCount, DhcpRelayCounters.NO_LINKLOCAL_FAIL);
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000725 return;
726 }
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000727 } else {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000728 log.warn("CLIENTID option NOT found. Don't create DhcpRelay Record.");
Charles Chancd1783f2019-02-01 11:31:50 -0800729 //dhcpRelayCountersStore.incrementCounter(gCount, DhcpRelayCounters.NO_CLIENTID_FAIL);
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000730 return;
731 }
732
Kalhee Kim495c9b22017-11-07 16:32:09 +0000733 HostId leafHostId = HostId.hostId(leafClientMac, vlanId);
734 DhcpRecord record = dhcpRelayStore.getDhcpRecord(leafHostId).orElse(null);
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000735 if (record == null) {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000736 record = new DhcpRecord(leafHostId);
Kalhee Kimd94ceea2017-11-29 19:03:02 +0000737 } else {
738 record = record.clone();
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000739 }
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000740
Taras Lemkin41785912018-03-26 14:52:58 +0000741 Boolean isMsgRelease = Dhcp6HandlerUtil.isDhcp6Release(dhcp6Packet);
Kalhee Kim495c9b22017-11-07 16:32:09 +0000742 IpAddressInfo ipInfo;
743 PdPrefixInfo pdInfo = null;
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000744 if (directConnFlag) {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000745 // Add to host store if it is connected to network directly
746 ipInfo = extractIpAddress(dhcp6Packet);
747 if (ipInfo != null) {
748 if (isMsgRelease) {
749 HostId hostId = HostId.hostId(srcMac, vlanId);
750 log.debug("remove Host {} ip for directly connected.", hostId.toString());
751 providerService.removeIpFromHost(hostId, ipInfo.ip6Address);
Kalhee Kim45fede42017-09-05 19:05:06 +0000752 }
753 } else {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000754 log.debug("ipAddress not found. Do not remove Host {} for directly connected.",
755 HostId.hostId(srcMac, vlanId).toString());
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000756 }
Kalhee Kim495c9b22017-11-07 16:32:09 +0000757 leafMsgType = dhcp6Packet.getMsgType();
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000758 } else {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000759 // Remove from route store if it is not connected to network directly
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000760 // pick out the first link-local ip address
Kalhee Kim495c9b22017-11-07 16:32:09 +0000761 IpAddress nextHopIp = getFirstIpByHost(directConnFlag, srcMac, vlanId);
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000762 if (nextHopIp == null) {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000763 log.warn("Can't find link-local IP address of gateway mac {} vlanId {}", srcMac, vlanId);
Charles Chancd1783f2019-02-01 11:31:50 -0800764 //dhcpRelayCountersStore.incrementCounter(gCount, DhcpRelayCounters.NO_LINKLOCAL_GW);
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000765 return;
766 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000767
Taras Lemkin41785912018-03-26 14:52:58 +0000768 DHCP6 leafDhcp = Dhcp6HandlerUtil.getDhcp6Leaf(dhcp6Packet);
Kalhee Kim495c9b22017-11-07 16:32:09 +0000769 ipInfo = extractIpAddress(leafDhcp);
770 if (ipInfo == null) {
771 log.debug("ip is null");
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000772 } else {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000773 if (isMsgRelease) {
Kalhee Kim54a97c92018-04-02 21:23:46 +0000774 Route routeForIP = new Route(Route.Source.DHCP, ipInfo.ip6Address.toIpPrefix(), nextHopIp);
Kalhee Kim495c9b22017-11-07 16:32:09 +0000775 log.debug("removing route of 128 address for indirectly connected.");
776 log.debug("128 ip {}, nexthop {}",
777 HexString.toHexString(ipInfo.ip6Address.toOctets(), ":"),
778 HexString.toHexString(nextHopIp.toOctets(), ":"));
779 routeStore.removeRoute(routeForIP);
Kalhee Kim45fede42017-09-05 19:05:06 +0000780 }
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000781 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000782
Kalhee Kim495c9b22017-11-07 16:32:09 +0000783 pdInfo = extractPrefix(leafDhcp);
784 if (pdInfo == null) {
785 log.debug("ipPrefix is null ");
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000786 } else {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000787 if (isMsgRelease) {
Kalhee Kim54a97c92018-04-02 21:23:46 +0000788 Route routeForPrefix = new Route(Route.Source.DHCP, pdInfo.pdPrefix, nextHopIp);
Kalhee Kim495c9b22017-11-07 16:32:09 +0000789 log.debug("removing route of PD for indirectly connected.");
790 log.debug("pd ip {}, nexthop {}",
791 HexString.toHexString(pdInfo.pdPrefix.address().toOctets(), ":"),
792 HexString.toHexString(nextHopIp.toOctets(), ":"));
793
794 routeStore.removeRoute(routeForPrefix);
Kalhee Kimba366062017-11-07 16:32:09 +0000795 if (this.dhcpFpmEnabled) {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000796 dhcpFpmPrefixStore.removeFpmRecord(pdInfo.pdPrefix);
Kalhee Kimba366062017-11-07 16:32:09 +0000797 }
Kalhee Kim45fede42017-09-05 19:05:06 +0000798 }
799 }
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000800 leafMsgType = leafDhcp.getMsgType();
Kalhee Kimd94ceea2017-11-29 19:03:02 +0000801 }
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000802
Kalhee Kim495c9b22017-11-07 16:32:09 +0000803 if (isMsgRelease) {
804 log.debug("DHCP6 RELEASE msg.");
805 if (record != null) {
806 if (ipInfo != null) {
807 log.debug("DhcpRelay Record ip6Address is set to null.");
808 record.ip6Address(null);
809 }
810 if (pdInfo != null) {
811 log.debug("DhcpRelay Record pdPrefix is set to null.");
812 }
813
814 if (!record.ip6Address().isPresent() && !record.pdPrefix().isPresent()) {
815 log.warn("IP6 address and IP6 PD both are null. Remove record.");
816 // do not remove a record. Let timer task handler it.
817 //dhcpRelayStore.removeDhcpRecord(HostId.hostId(leafClientMac, vlanId));
818 }
819 }
820 }
821
Ray Milkeyffe1a332018-01-24 10:41:14 -0800822 if (record != null) {
Taras Lemkin41785912018-03-26 14:52:58 +0000823 record.getV6Counters().incrementCounter(Dhcp6HandlerUtil.getMsgTypeStr(leafMsgType));
Ray Milkeyffe1a332018-01-24 10:41:14 -0800824 record.addLocation(new HostLocation(location, System.currentTimeMillis()));
825 record.ip6Status(DHCP6.MsgType.getType(leafMsgType));
826 record.setDirectlyConnected(directConnFlag);
827 if (!directConnFlag) {
828 // Update gateway mac address if the host is not directly connected
829 record.nextHop(srcMac);
830 }
831 record.updateLastSeen();
Kalhee Kim495c9b22017-11-07 16:32:09 +0000832 }
Kalhee Kim495c9b22017-11-07 16:32:09 +0000833 dhcpRelayStore.updateDhcpRecord(leafHostId, record);
Charles Chancd1783f2019-02-01 11:31:50 -0800834 /*
Kalhee Kimd94ceea2017-11-29 19:03:02 +0000835 // TODO Use AtomicInteger for the counters
836 try {
837 recordSemaphore.acquire();
838 try {
Taras Lemkin41785912018-03-26 14:52:58 +0000839 dhcpRelayCountersStore.incrementCounter(gCount, Dhcp6HandlerUtil.getMsgTypeStr(leafMsgType));
Kalhee Kimd94ceea2017-11-29 19:03:02 +0000840 } finally {
841 // calling release() after a successful acquire()
842 recordSemaphore.release();
843 }
844 } catch (InterruptedException e) {
Ray Milkeyba547f92018-02-01 15:22:31 -0800845 Thread.currentThread().interrupt();
Kalhee Kimd94ceea2017-11-29 19:03:02 +0000846 }
Charles Chancd1783f2019-02-01 11:31:50 -0800847 */
Kalhee Kim495c9b22017-11-07 16:32:09 +0000848 }
849
850 /**
851 * add host or route and update dhcp relay record.
852 *
853 * @param directConnFlag flag to show that packet is from directly connected client
854 * @param location client side connect point
855 * @param dhcp6Relay the dhcp6 payload
856 * @param embeddedDhcp6 the dhcp6 payload within relay
857 * @param srcMac client gw/host macAddress
858 * @param clientInterface client interface
859 */
860 private void addHostOrRoute(boolean directConnFlag, ConnectPoint location, DHCP6 dhcp6Relay,
861 DHCP6 embeddedDhcp6, MacAddress srcMac, Interface clientInterface) {
862 log.debug("addHostOrRoute entered.");
863 VlanId vlanId = clientInterface.vlan();
Taras Lemkin41785912018-03-26 14:52:58 +0000864 Boolean isMsgReply = Dhcp6HandlerUtil.isDhcp6Reply(dhcp6Relay);
Kalhee Kim495c9b22017-11-07 16:32:09 +0000865 MacAddress leafClientMac;
866 Byte leafMsgType;
867
Charles Chanc7f63b62018-08-13 10:32:03 -0700868 Dhcp6ClientIdOption clientIdOption = Dhcp6HandlerUtil.extractClientId(directConnFlag, embeddedDhcp6);
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000869 if (clientIdOption != null) {
870 log.debug("CLIENTID option found {}", clientIdOption);
871 if ((clientIdOption.getDuid().getDuidType() == Dhcp6Duid.DuidType.DUID_LLT) ||
872 (clientIdOption.getDuid().getDuidType() == Dhcp6Duid.DuidType.DUID_LL)) {
873 leafClientMac = MacAddress.valueOf(clientIdOption.getDuid().getLinkLayerAddress());
874 } else {
875 log.warn("Link-Layer Address not supported in CLIENTID option. No DhcpRelay Record created.");
Charles Chancd1783f2019-02-01 11:31:50 -0800876 //dhcpRelayCountersStore.incrementCounter(gCount, DhcpRelayCounters.NO_LINKLOCAL_FAIL);
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000877 return;
878 }
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000879 } else {
880 log.warn("CLIENTID option NOT found. No DhcpRelay Record created.");
Charles Chancd1783f2019-02-01 11:31:50 -0800881 //dhcpRelayCountersStore.incrementCounter(gCount, DhcpRelayCounters.NO_CLIENTID_FAIL);
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000882 return;
883 }
Kalhee Kim495c9b22017-11-07 16:32:09 +0000884 HostId leafHostId = HostId.hostId(leafClientMac, vlanId);
885 DhcpRecord record = dhcpRelayStore.getDhcpRecord(leafHostId).orElse(null);
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000886 if (record == null) {
887 record = new DhcpRecord(HostId.hostId(leafClientMac, vlanId));
Kalhee Kimd94ceea2017-11-29 19:03:02 +0000888 } else {
889 record = record.clone();
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000890 }
Kalhee Kim495c9b22017-11-07 16:32:09 +0000891
892 IpAddressInfo ipInfo;
893 PdPrefixInfo pdInfo = null;
894 if (directConnFlag) {
895 // Add to host store if it connect to network directly
896 ipInfo = extractIpAddress(embeddedDhcp6);
897 if (ipInfo != null) {
898 if (isMsgReply) {
899 Set<IpAddress> ips = Sets.newHashSet(ipInfo.ip6Address);
900 HostId hostId = HostId.hostId(srcMac, vlanId);
901 Host host = hostService.getHost(hostId);
902 HostLocation hostLocation = new HostLocation(clientInterface.connectPoint(),
903 System.currentTimeMillis());
904 Set<HostLocation> hostLocations = Sets.newHashSet(hostLocation);
905 if (host != null) {
906 // Dual homing support:
907 // if host exists, use old locations and new location
908 hostLocations.addAll(host.locations());
909 }
910 HostDescription desc = new DefaultHostDescription(srcMac, vlanId, hostLocations, ips,
911 false);
912 log.debug("adding Host for directly connected.");
913 log.debug("client mac {} client vlan {} hostlocation {}",
914 HexString.toHexString(srcMac.toBytes(), ":"), vlanId, hostLocation.toString());
915 // Replace the ip when dhcp server give the host new ip address
916 providerService.hostDetected(hostId, desc, false);
917 }
918 } else {
919 log.warn("ipAddress not found. Do not add Host {} for directly connected.",
920 HostId.hostId(srcMac, vlanId).toString());
921 }
922 leafMsgType = embeddedDhcp6.getMsgType();
923 } else {
924 // Add to route store if it does not connect to network directly
925 // pick out the first link-local ip address
926 IpAddress nextHopIp = getFirstIpByHost(directConnFlag, srcMac, vlanId);
927 if (nextHopIp == null) {
928 log.warn("Can't find link-local IP address of gateway mac {} vlanId {}", srcMac, vlanId);
Charles Chancd1783f2019-02-01 11:31:50 -0800929 //dhcpRelayCountersStore.incrementCounter(gCount, DhcpRelayCounters.NO_LINKLOCAL_GW);
Kalhee Kim495c9b22017-11-07 16:32:09 +0000930 return;
931 }
932
Taras Lemkin41785912018-03-26 14:52:58 +0000933 DHCP6 leafDhcp = Dhcp6HandlerUtil.getDhcp6Leaf(embeddedDhcp6);
Kalhee Kim495c9b22017-11-07 16:32:09 +0000934 ipInfo = extractIpAddress(leafDhcp);
935 if (ipInfo == null) {
936 log.debug("ip is null");
937 } else {
938 if (isMsgReply) {
Kalhee Kim54a97c92018-04-02 21:23:46 +0000939 Route routeForIP = new Route(Route.Source.DHCP, ipInfo.ip6Address.toIpPrefix(), nextHopIp);
Kalhee Kim495c9b22017-11-07 16:32:09 +0000940 log.debug("adding Route of 128 address for indirectly connected.");
Daniel Ginsburgc1d6aaf2018-06-09 01:43:59 +0300941 routeStore.replaceRoute(routeForIP);
Kalhee Kim495c9b22017-11-07 16:32:09 +0000942 }
943 }
944
945 pdInfo = extractPrefix(leafDhcp);
946 if (pdInfo == null) {
947 log.debug("ipPrefix is null ");
948 } else {
949 if (isMsgReply) {
Kalhee Kim54a97c92018-04-02 21:23:46 +0000950 Route routeForPrefix = new Route(Route.Source.DHCP, pdInfo.pdPrefix, nextHopIp);
Kalhee Kim495c9b22017-11-07 16:32:09 +0000951 log.debug("adding Route of PD for indirectly connected.");
Daniel Ginsburgc1d6aaf2018-06-09 01:43:59 +0300952 routeStore.replaceRoute(routeForPrefix);
Kalhee Kim495c9b22017-11-07 16:32:09 +0000953 if (this.dhcpFpmEnabled) {
954 FpmRecord fpmRecord = new FpmRecord(pdInfo.pdPrefix, nextHopIp, FpmRecord.Type.DHCP_RELAY);
955 dhcpFpmPrefixStore.addFpmRecord(pdInfo.pdPrefix, fpmRecord);
956 }
957 }
958 }
959 leafMsgType = leafDhcp.getMsgType();
960 }
961 if (leafMsgType == DHCP6.MsgType.RELEASE.value() ||
962 (leafMsgType == DHCP6.MsgType.REPLY.value()) && ipInfo == null) {
963 log.warn("DHCP6 RELEASE/REPLY(null ip) from Server. MsgType {}", leafMsgType);
964 //return;
965 }
966
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000967 record.addLocation(new HostLocation(location, System.currentTimeMillis()));
Kalhee Kim2f07c602017-11-15 18:57:53 +0000968
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000969 if (leafMsgType == DHCP6.MsgType.REPLY.value()) {
Kalhee Kim495c9b22017-11-07 16:32:09 +0000970 if (ipInfo != null) {
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000971 log.debug("IP6 address is being stored into dhcp-relay store.");
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800972 log.debug("Client IP6 address {}", HexString.toHexString(ipInfo.ip6Address.toOctets(), ":"));
Kalhee Kim495c9b22017-11-07 16:32:09 +0000973 record.ip6Address(ipInfo.ip6Address);
Kalhee Kim2f07c602017-11-15 18:57:53 +0000974 record.updateAddrPrefTime(ipInfo.prefTime);
975 record.updateLastIp6Update();
Lior Assoulinea21c0ca2018-01-28 16:18:48 -0800976 } else {
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000977 log.debug("IP6 address is not returned from server. Maybe only PD is returned.");
978 }
Kalhee Kim495c9b22017-11-07 16:32:09 +0000979 if (pdInfo != null) {
980 log.debug("IP6 PD address {}",
981 HexString.toHexString(pdInfo.pdPrefix.address().toOctets(), ":"));
Kalhee Kim2f07c602017-11-15 18:57:53 +0000982 record.pdPrefix(pdInfo.pdPrefix);
983 record.updatePdPrefTime(pdInfo.prefTime);
984 record.updateLastPdUpdate();
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000985 } else {
986 log.debug("IP6 PD address is not returned from server. Maybe only IPAddress is returned.");
987 }
988 }
Kalhee Kim2f07c602017-11-15 18:57:53 +0000989
Taras Lemkin41785912018-03-26 14:52:58 +0000990 record.getV6Counters().incrementCounter(Dhcp6HandlerUtil.getMsgTypeStr(leafMsgType));
Kalhee Kim495c9b22017-11-07 16:32:09 +0000991 record.ip6Status(DHCP6.MsgType.getType(leafMsgType));
Kalhee Kimea4b6c22017-11-09 14:38:37 +0000992 record.setDirectlyConnected(directConnFlag);
993 record.updateLastSeen();
Kalhee Kim495c9b22017-11-07 16:32:09 +0000994 dhcpRelayStore.updateDhcpRecord(leafHostId, record);
Charles Chancd1783f2019-02-01 11:31:50 -0800995 /*
Kalhee Kimd94ceea2017-11-29 19:03:02 +0000996 // TODO Use AtomicInteger for the counters
997 try {
998 recordSemaphore.acquire();
999 try {
Taras Lemkin41785912018-03-26 14:52:58 +00001000 dhcpRelayCountersStore.incrementCounter(gCount, Dhcp6HandlerUtil.getMsgTypeStr(leafMsgType));
Kalhee Kimd94ceea2017-11-29 19:03:02 +00001001 } finally {
1002 // calling release() after a successful acquire()
1003 recordSemaphore.release();
1004 }
1005 } catch (InterruptedException e) {
Ray Milkeyba547f92018-02-01 15:22:31 -08001006 Thread.currentThread().interrupt();
Kalhee Kimd94ceea2017-11-29 19:03:02 +00001007 }
Charles Chancd1783f2019-02-01 11:31:50 -08001008 */
Kalhee Kim45fede42017-09-05 19:05:06 +00001009 }
1010
Taras Lemkin41785912018-03-26 14:52:58 +00001011 private List<InternalPacket> processDhcp6ForwardOnly(PacketContext context,
1012 Ethernet clientPacket,
1013 Set<Interface> clientInterfaces,
1014 DHCP6 dhcpPacket) {
1015 ConnectPoint inPort = context.inPacket().receivedFrom();
1016 log.trace("Got DHCPv6 on port {}", inPort);
1017 boolean directConnFlag = Dhcp6HandlerUtil.directlyConnected(dhcpPacket);
1018
1019 List<InternalPacket> internalPackets = new ArrayList<>();
1020 List<DhcpServerInfo> serverInfoList = findValidServerInfo(directConnFlag);
1021
1022 for (DhcpServerInfo dhcpServer : serverInfoList) {
Charles Chanc7f63b62018-08-13 10:32:03 -07001023 Interface serverInterface = getServerInterface(dhcpServer);
1024 if (serverInterface == null) {
1025 log.warn("Can't get server interface, ignore");
1026 continue;
1027 }
1028
Taras Lemkin41785912018-03-26 14:52:58 +00001029 Ethernet newPacket = Dhcp6HandlerUtil.buildDhcp6PacketFromClient(context,
Charles Chanc7f63b62018-08-13 10:32:03 -07001030 clientPacket, clientInterfaces, dhcpServer, serverInterface);
Taras Lemkin41785912018-03-26 14:52:58 +00001031 log.trace("Built packet for server {} : {}", dhcpServer, newPacket);
1032 internalPackets.add(InternalPacket.internalPacket(newPacket,
1033 dhcpServer.getDhcpServerConnectPoint().get()));
1034 }
1035
1036 return internalPackets;
1037 }
1038
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001039 private List<InternalPacket> processLQ6PacketFromClient(PacketContext context,
1040 Ethernet clientPacket,
1041 Set<Interface> clientInterfaces,
1042 DHCP6 dhcp6Payload) {
1043 ConnectPoint inPort = context.inPacket().receivedFrom();
1044 log.info("Got LQ-REQUEST V6 on port {}", inPort);
1045 List<Dhcp6Option> lopt = dhcp6Payload.getOptions();
1046 log.info("Options list: {}", lopt);
1047 Dhcp6LeaseQueryOption lqoption = dhcp6Payload.getOptions()
1048 .stream()
1049 .filter(opt -> opt instanceof Dhcp6LeaseQueryOption)
1050 .map(pld -> (Dhcp6LeaseQueryOption) pld)
1051 .findFirst()
1052 .orElse(null);
1053
1054 if (lqoption == null) {
1055 // Can't find dhcp payload
1056 log.warn("Can't find dhcp6 lease query message - aborting");
1057 return null;
1058 } else {
1059 log.info("dhcp6 lqv6 options found: {}", lqoption);
1060 }
1061 log.warn("LQv6 for " + lqoption.linkAddress.toString() + " comes from " + inPort.toString());
1062 Ethernet packet = context.inPacket().parsed();
1063 Ip6Address clientAddress = lqoption.linkAddress;
1064 IPv6 ipv6Packet = (IPv6) packet.getPayload();
1065 Ip6Address nextHopIp = findNextHopIp6FromRelayStore(clientAddress);
1066
1067 // 1. only if there is a route to remove - remove it
1068 if (nextHopIp != null) {
Kalhee Kim54a97c92018-04-02 21:23:46 +00001069 Route routeForIP6 = new Route(Route.Source.DHCP, clientAddress.toIpPrefix(), nextHopIp);
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001070 log.debug("Removing route of Client " + clientAddress +
1071 " for indirectly connected - next hop ip6 " + nextHopIp);
1072 routeStore.removeRoute(routeForIP6);
1073 }
1074
1075 // 2. note the potential NH this packet came from in case it's a known lease
1076 // this NH will then be used to build the route
1077 MacAddress potentialNH = packet.getSourceMAC();
1078 VlanId vlanId = VlanId.vlanId(packet.getVlanID());
1079 setPotentialNextHopForIp6InRelayStore(clientAddress, vlanId, potentialNH);
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001080 // 3. route this LQ6 to all relevant servers
1081 IPv6 clientIpv6 = (IPv6) clientPacket.getPayload();
1082 UDP clientUdp = (UDP) clientIpv6.getPayload();
1083 DHCP6 clientDhcp6 = (DHCP6) clientUdp.getPayload();
1084
Taras Lemkin41785912018-03-26 14:52:58 +00001085 boolean directConnFlag = Dhcp6HandlerUtil.directlyConnected(clientDhcp6);
Harshada Chaundkar6c54f202019-05-06 20:16:13 +00001086 boolean serverFound = false;
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001087 List<InternalPacket> internalPackets = new ArrayList<>();
1088 List<DhcpServerInfo> serverInfoList = findValidServerInfo(directConnFlag);
1089 List<DhcpServerInfo> copyServerInfoList = new ArrayList<DhcpServerInfo>(serverInfoList);
1090
1091 for (DhcpServerInfo serverInfo : copyServerInfoList) {
Taras Lemkin41785912018-03-26 14:52:58 +00001092 if (!Dhcp6HandlerUtil.checkDhcpServerConnPt(directConnFlag, serverInfo)) {
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001093 log.warn("Can't get server connect point, ignore");
1094 continue;
1095 }
1096 DhcpServerInfo newServerInfo = getHostInfoForServerInfo(serverInfo, serverInfoList);
1097 if (newServerInfo == null) {
Harshada Chaundkar6c54f202019-05-06 20:16:13 +00001098 log.debug("Can't get server interface with host info resolved, ignore serverInfo {} serverInfoList {}",
1099 serverInfo, serverInfoList);
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001100 continue;
1101 }
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001102 Interface serverInterface = getServerInterface(newServerInfo);
1103 if (serverInterface == null) {
Harshada Chaundkar6c54f202019-05-06 20:16:13 +00001104 log.debug("Can't get server interface, ignore for serverInfo {}, serverInfoList {}",
1105 serverInfo, serverInfoList);
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001106 continue;
1107 }
Harshada Chaundkar6c54f202019-05-06 20:16:13 +00001108
1109 serverFound = true;
1110 log.debug("Server Info Found {}", serverInfo.getDhcpConnectMac());
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001111 Ethernet etherRouted = (Ethernet) clientPacket.clone();
1112 MacAddress macFacingServer = serverInterface.mac();
1113 if (macFacingServer == null) {
1114 log.warn("No MAC address for server Interface {}", serverInterface);
1115 return null;
1116 }
1117 etherRouted.setSourceMACAddress(macFacingServer);
1118 etherRouted.setDestinationMACAddress(newServerInfo.getDhcpConnectMac().get());
1119 InternalPacket internalPacket =
Taras Lemkin41785912018-03-26 14:52:58 +00001120 InternalPacket.internalPacket(etherRouted,
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001121 serverInfo.getDhcpServerConnectPoint().get());
1122 internalPackets.add(internalPacket);
1123 log.debug("Sending LQ to DHCP server {}", newServerInfo.getDhcpServerIp6());
1124 }
Harshada Chaundkar6c54f202019-05-06 20:16:13 +00001125 if (!serverFound) {
1126 log.warn("ProcessDhcp6PacketFromClient No Server Found");
1127 }
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001128 log.debug("num of client packets to send is{}", internalPackets.size());
1129
1130 return internalPackets;
1131 }
1132
Kalhee Kim45fede42017-09-05 19:05:06 +00001133 /**
Kalhee Kim495c9b22017-11-07 16:32:09 +00001134 * build the DHCP6 solicit/request packet with gatewayip.
Kalhee Kim45fede42017-09-05 19:05:06 +00001135 *
1136 * @param context packet context
1137 * @param clientPacket client ethernet packet
1138 * @param clientInterfaces set of client side interfaces
1139 */
Kalhee Kim495c9b22017-11-07 16:32:09 +00001140 private List<InternalPacket> processDhcp6PacketFromClient(PacketContext context,
1141 Ethernet clientPacket,
1142 Set<Interface> clientInterfaces) {
Yi Tseng3bd57ac2017-11-29 14:39:18 -08001143 ConnectPoint receivedFrom = context.inPacket().receivedFrom();
Taras Lemkin41785912018-03-26 14:52:58 +00001144 Ip6Address relayAgentIp = Dhcp6HandlerUtil.getRelayAgentIPv6Address(clientInterfaces);
Yi Tseng3bd57ac2017-11-29 14:39:18 -08001145 MacAddress relayAgentMac = clientInterfaces.iterator().next().mac();
1146 if (relayAgentIp == null || relayAgentMac == null) {
1147 log.warn("Missing DHCP relay agent interface Ipv6 addr config for "
Kalhee Kim495c9b22017-11-07 16:32:09 +00001148 + "packet from client on port: {}. Aborting packet processing",
1149 clientInterfaces.iterator().next().connectPoint());
Charles Chancd1783f2019-02-01 11:31:50 -08001150 //dhcpRelayCountersStore.incrementCounter(gCount, DhcpRelayCounters.NO_CLIENT_INTF_MAC);
Charles Chan239492c2018-01-22 13:27:28 -08001151 return Lists.newArrayList();
Kalhee Kim121ba922017-11-01 17:56:44 +00001152 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001153
Kalhee Kim495c9b22017-11-07 16:32:09 +00001154 IPv6 clientIpv6 = (IPv6) clientPacket.getPayload();
1155 UDP clientUdp = (UDP) clientIpv6.getPayload();
1156 DHCP6 clientDhcp6 = (DHCP6) clientUdp.getPayload();
1157
Taras Lemkin41785912018-03-26 14:52:58 +00001158 boolean directConnFlag = Dhcp6HandlerUtil.directlyConnected(clientDhcp6);
Charles Chana990ce92017-10-30 10:22:50 -07001159
Kalhee Kim121ba922017-11-01 17:56:44 +00001160 ConnectPoint clientConnectionPoint = context.inPacket().receivedFrom();
1161 VlanId vlanIdInUse = VlanId.vlanId(clientPacket.getVlanID());
1162 Interface clientInterface = interfaceService.getInterfacesByPort(clientConnectionPoint)
Taras Lemkin41785912018-03-26 14:52:58 +00001163 .stream().filter(iface -> Dhcp6HandlerUtil.interfaceContainsVlan(iface, vlanIdInUse))
Kalhee Kim495c9b22017-11-07 16:32:09 +00001164 .findFirst()
1165 .orElse(null);
Kalhee Kim45fede42017-09-05 19:05:06 +00001166
Kalhee Kim495c9b22017-11-07 16:32:09 +00001167 List<InternalPacket> internalPackets = new ArrayList<>();
1168 List<DhcpServerInfo> serverInfoList = findValidServerInfo(directConnFlag);
1169 List<DhcpServerInfo> copyServerInfoList = new ArrayList<DhcpServerInfo>(serverInfoList);
Kalhee Kim45b24182017-10-18 18:30:23 +00001170
Kalhee Kim495c9b22017-11-07 16:32:09 +00001171 for (DhcpServerInfo serverInfo : copyServerInfoList) {
Taras Lemkin41785912018-03-26 14:52:58 +00001172 if (!Dhcp6HandlerUtil.checkDhcpServerConnPt(directConnFlag, serverInfo)) {
Kalhee Kim495c9b22017-11-07 16:32:09 +00001173 log.warn("Can't get server connect point, ignore");
1174 continue;
1175 }
1176 DhcpServerInfo newServerInfo = getHostInfoForServerInfo(serverInfo, serverInfoList);
1177 if (newServerInfo == null) {
1178 log.warn("Can't get server interface with host info resolved, ignore");
1179 continue;
1180 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001181
Kalhee Kim495c9b22017-11-07 16:32:09 +00001182 Interface serverInterface = getServerInterface(newServerInfo);
1183 if (serverInterface == null) {
1184 log.warn("Can't get server interface, ignore");
1185 continue;
1186 }
Kalhee Kimea4b6c22017-11-09 14:38:37 +00001187
Taras Lemkin41785912018-03-26 14:52:58 +00001188 Ethernet etherReply = Dhcp6HandlerUtil.buildDhcp6PacketFromClient(context, clientPacket,
Kalhee Kim495c9b22017-11-07 16:32:09 +00001189 clientInterfaces, newServerInfo, serverInterface);
1190 removeHostOrRoute(directConnFlag, clientConnectionPoint, clientDhcp6, clientPacket,
1191 clientIpv6, clientInterface);
Kalhee Kimea4b6c22017-11-09 14:38:37 +00001192
Taras Lemkin41785912018-03-26 14:52:58 +00001193 InternalPacket internalPacket = InternalPacket.internalPacket(etherReply,
Kalhee Kim495c9b22017-11-07 16:32:09 +00001194 serverInfo.getDhcpServerConnectPoint().get());
1195 internalPackets.add(internalPacket);
1196 }
1197 log.debug("num of client packets to send is{}", internalPackets.size());
Kalhee Kimea4b6c22017-11-09 14:38:37 +00001198
Kalhee Kim495c9b22017-11-07 16:32:09 +00001199 return internalPackets;
1200 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001201
1202 /**
Kalhee Kim45fede42017-09-05 19:05:06 +00001203 * process the DHCP6 relay-reply packet from dhcp server.
1204 *
1205 * @param context packet context
1206 * @param receivedPacket server ethernet packet
1207 * @param recevingInterfaces set of server side interfaces
Kalhee Kim495c9b22017-11-07 16:32:09 +00001208 * @return internalPacket toward client
Kalhee Kim45fede42017-09-05 19:05:06 +00001209 */
1210 private InternalPacket processDhcp6PacketFromServer(PacketContext context,
1211 Ethernet receivedPacket, Set<Interface> recevingInterfaces) {
Kalhee Kim45fede42017-09-05 19:05:06 +00001212 // get dhcp6 header.
Ray Milkeyf0c47612017-09-28 11:29:38 -07001213 Ethernet etherReply = receivedPacket.duplicate();
Kalhee Kim45fede42017-09-05 19:05:06 +00001214 IPv6 ipv6Packet = (IPv6) etherReply.getPayload();
1215 UDP udpPacket = (UDP) ipv6Packet.getPayload();
1216 DHCP6 dhcp6Relay = (DHCP6) udpPacket.getPayload();
Taras Lemkin41785912018-03-26 14:52:58 +00001217 Boolean directConnFlag = Dhcp6HandlerUtil.directlyConnected(dhcp6Relay);
Kalhee Kim45fede42017-09-05 19:05:06 +00001218
Kalhee Kim495c9b22017-11-07 16:32:09 +00001219 DHCP6 embeddedDhcp6 = dhcp6Relay.getOptions().stream()
1220 .filter(opt -> opt instanceof Dhcp6RelayOption)
1221 .map(BasePacket::getPayload)
1222 .map(pld -> (DHCP6) pld)
1223 .findFirst()
1224 .orElse(null);
Kalhee Kimd21029f2017-09-26 20:21:53 +00001225 ConnectPoint inPort = context.inPacket().receivedFrom();
Kalhee Kim495c9b22017-11-07 16:32:09 +00001226 DhcpServerInfo foundServerInfo = findServerInfoFromServer(directConnFlag, inPort);
Kalhee Kimd21029f2017-09-26 20:21:53 +00001227
Kalhee Kim495c9b22017-11-07 16:32:09 +00001228 if (foundServerInfo == null) {
jayakumarthazhath27aa7722018-09-25 15:56:51 -04001229 log.warn("Cannot find server info for {} server, inPort {}",
1230 directConnFlag ? "direct" : "indirect", inPort);
Charles Chancd1783f2019-02-01 11:31:50 -08001231 //dhcpRelayCountersStore.incrementCounter(gCount, DhcpRelayCounters.NO_SERVER_INFO);
Kalhee Kimd21029f2017-09-26 20:21:53 +00001232 return null;
Kalhee Kim495c9b22017-11-07 16:32:09 +00001233 } else {
Taras Lemkin41785912018-03-26 14:52:58 +00001234 if (Dhcp6HandlerUtil.isServerIpEmpty(foundServerInfo)) {
Kalhee Kim495c9b22017-11-07 16:32:09 +00001235 log.warn("Cannot find server info's ipaddress");
Charles Chancd1783f2019-02-01 11:31:50 -08001236 //dhcpRelayCountersStore.incrementCounter(gCount, DhcpRelayCounters.NO_SERVER_IP6ADDR);
Kalhee Kim495c9b22017-11-07 16:32:09 +00001237 return null;
1238 }
Kalhee Kimd21029f2017-09-26 20:21:53 +00001239 }
1240
Kalhee Kim45fede42017-09-05 19:05:06 +00001241 Dhcp6InterfaceIdOption interfaceIdOption = dhcp6Relay.getOptions().stream()
1242 .filter(opt -> opt instanceof Dhcp6InterfaceIdOption)
1243 .map(opt -> (Dhcp6InterfaceIdOption) opt)
1244 .findFirst()
1245 .orElse(null);
Kalhee Kim45fede42017-09-05 19:05:06 +00001246 if (interfaceIdOption == null) {
1247 log.warn("Interface Id option is not present, abort packet...");
Charles Chancd1783f2019-02-01 11:31:50 -08001248 //dhcpRelayCountersStore.incrementCounter(gCount, DhcpRelayCounters.OPTION_MISSING_FAIL);
Kalhee Kim45fede42017-09-05 19:05:06 +00001249 return null;
1250 }
1251
1252 MacAddress peerMac = interfaceIdOption.getMacAddress();
1253 String clientConnectionPointStr = new String(interfaceIdOption.getInPort());
Kalhee Kim45fede42017-09-05 19:05:06 +00001254 ConnectPoint clientConnectionPoint = ConnectPoint.deviceConnectPoint(clientConnectionPointStr);
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +00001255 VlanId vlanIdInUse = VlanId.vlanId(interfaceIdOption.getVlanId());
Harshada Chaundkar6c54f202019-05-06 20:16:13 +00001256
1257 log.debug("processDhcp6PacketFromServer Interface Id Mac {}, port{}, vlan {}",
1258 peerMac, clientConnectionPointStr, vlanIdInUse);
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +00001259 Interface clientInterface = interfaceService.getInterfacesByPort(clientConnectionPoint)
Taras Lemkin41785912018-03-26 14:52:58 +00001260 .stream().filter(iface -> Dhcp6HandlerUtil.interfaceContainsVlan(iface, vlanIdInUse))
Kalhee Kim495c9b22017-11-07 16:32:09 +00001261 .findFirst().orElse(null);
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +00001262 if (clientInterface == null) {
1263 log.warn("Cannot get client interface for from packet, abort... vlan {}", vlanIdInUse.toString());
Charles Chancd1783f2019-02-01 11:31:50 -08001264 //dhcpRelayCountersStore.incrementCounter(gCount, DhcpRelayCounters.NO_MATCHING_INTF);
Kalhee Kim45fede42017-09-05 19:05:06 +00001265 return null;
1266 }
Kalhee Kim44fbda12018-04-03 21:08:18 +00001267 etherReply.setVlanID(vlanIdInUse.toShort());
1268
Kalhee Kim0c0cb0b2017-09-15 17:43:27 +00001269 MacAddress relayAgentMac = clientInterface.mac();
Kalhee Kim45fede42017-09-05 19:05:06 +00001270 if (relayAgentMac == null) {
Yi Tseng68ef26b2017-12-18 17:10:00 -08001271 log.warn("Can not get client interface mac, abort packet..");
Charles Chancd1783f2019-02-01 11:31:50 -08001272 //dhcpRelayCountersStore.incrementCounter(gCount, DhcpRelayCounters.NO_CLIENT_INTF_MAC);
Kalhee Kim45fede42017-09-05 19:05:06 +00001273 return null;
1274 }
1275 etherReply.setSourceMACAddress(relayAgentMac);
1276
1277 // find destMac
Yi Tseng68ef26b2017-12-18 17:10:00 -08001278 MacAddress clientMac;
Yi Tsengaa417a62017-09-08 17:22:51 -07001279 Ip6Address peerAddress = Ip6Address.valueOf(dhcp6Relay.getPeerAddress());
1280 Set<Host> clients = hostService.getHostsByIp(peerAddress);
Kalhee Kim45fede42017-09-05 19:05:06 +00001281 if (clients.isEmpty()) {
Yi Tseng68ef26b2017-12-18 17:10:00 -08001282 log.trace("There's no host found for this address {}",
Kalhee Kim45fede42017-09-05 19:05:06 +00001283 HexString.toHexString(dhcp6Relay.getPeerAddress(), ":"));
Yi Tseng68ef26b2017-12-18 17:10:00 -08001284 log.trace("Let's look up interfaceId {}", HexString.toHexString(peerMac.toBytes(), ":"));
Kalhee Kim45fede42017-09-05 19:05:06 +00001285 clientMac = peerMac;
1286 } else {
1287 clientMac = clients.iterator().next().mac();
1288 if (clientMac == null) {
1289 log.warn("No client mac address found, abort packet...");
Charles Chancd1783f2019-02-01 11:31:50 -08001290 //dhcpRelayCountersStore.incrementCounter(gCount, DhcpRelayCounters.NO_CLIENT_INTF_MAC);
Kalhee Kim45fede42017-09-05 19:05:06 +00001291 return null;
1292 }
Yi Tseng68ef26b2017-12-18 17:10:00 -08001293 log.trace("Client mac address found from getHostByIp");
Kalhee Kim45fede42017-09-05 19:05:06 +00001294 }
1295 etherReply.setDestinationMACAddress(clientMac);
Kalhee Kim45fede42017-09-05 19:05:06 +00001296 // ip header
1297 ipv6Packet.setSourceAddress(dhcp6Relay.getLinkAddress());
1298 ipv6Packet.setDestinationAddress(dhcp6Relay.getPeerAddress());
1299 // udp header
1300 udpPacket.setSourcePort(UDP.DHCP_V6_SERVER_PORT);
1301 if (directConnFlag) {
1302 udpPacket.setDestinationPort(UDP.DHCP_V6_CLIENT_PORT);
1303 } else {
1304 udpPacket.setDestinationPort(UDP.DHCP_V6_SERVER_PORT);
1305 }
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001306
Kalhee Kim45fede42017-09-05 19:05:06 +00001307
Taras Lemkin41785912018-03-26 14:52:58 +00001308 boolean hostOrRouteAllowed = learnRouteFromLeasequery ||
1309 Dhcp6HandlerUtil.getDhcp6LeafMessageType(dhcp6Relay) != MsgType.LEASEQUERY_REPLY;
1310 log.debug("Can add host or route: {}", hostOrRouteAllowed);
1311
1312 if (hostOrRouteAllowed) {
1313 // add host or route
1314 addHostOrRoute(directConnFlag, clientConnectionPoint, dhcp6Relay, embeddedDhcp6,
1315 clientMac, clientInterface);
1316 }
1317
Kalhee Kim45fede42017-09-05 19:05:06 +00001318 udpPacket.setPayload(embeddedDhcp6);
1319 udpPacket.resetChecksum();
1320 ipv6Packet.setPayload(udpPacket);
1321 etherReply.setPayload(ipv6Packet);
Taras Lemkin41785912018-03-26 14:52:58 +00001322 return InternalPacket.internalPacket(etherReply, clientConnectionPoint);
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001323 }
Yi Tseng483ac6f2017-08-02 15:03:31 -07001324
1325 @Override
Kalhee Kimba366062017-11-07 16:32:09 +00001326 public void setDhcpFpmEnabled(Boolean enabled) {
1327 dhcpFpmEnabled = enabled;
1328 }
1329
1330 @Override
Yi Tseng483ac6f2017-08-02 15:03:31 -07001331 public void setDefaultDhcpServerConfigs(Collection<DhcpServerConfig> configs) {
Kalhee Kim495c9b22017-11-07 16:32:09 +00001332 log.debug("setDefaultDhcpServerConfigs is called.");
Yi Tseng919b2df2017-09-07 16:22:51 -07001333 setDhcpServerConfigs(configs, defaultServerInfoList);
Yi Tseng919b2df2017-09-07 16:22:51 -07001334 }
1335
1336 @Override
1337 public void setIndirectDhcpServerConfigs(Collection<DhcpServerConfig> configs) {
Kalhee Kim495c9b22017-11-07 16:32:09 +00001338 log.debug("setIndirectDhcpServerConfigs is called.");
Yi Tseng919b2df2017-09-07 16:22:51 -07001339 setDhcpServerConfigs(configs, indirectServerInfoList);
Yi Tseng919b2df2017-09-07 16:22:51 -07001340 }
1341
1342 public void setDhcpServerConfigs(Collection<DhcpServerConfig> configs, List<DhcpServerInfo> serverInfoList) {
Kalhee Kim495c9b22017-11-07 16:32:09 +00001343 log.debug("config size {}.", configs.size());
1344
Kalhee Kim45fede42017-09-05 19:05:06 +00001345 if (configs.size() == 0) {
1346 // no config to update
1347 return;
1348 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001349 // TODO: currently we pick up first DHCP server config.
1350 // Will use other server configs in the future for HA.
Kalhee Kim495c9b22017-11-07 16:32:09 +00001351 Boolean isConfigValid = false;
1352 for (DhcpServerConfig serverConfig : configs) {
1353 if (serverConfig.getDhcpServerIp6().isPresent()) {
1354 isConfigValid = true;
1355 break;
1356 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001357 }
Kalhee Kim495c9b22017-11-07 16:32:09 +00001358 if (!isConfigValid) {
1359 log.warn("No IP V6 server address found.");
1360 return; // No IP V6 address found
1361 }
1362 for (DhcpServerInfo oldServerInfo : serverInfoList) {
Yi Tseng919b2df2017-09-07 16:22:51 -07001363 // stop monitoring gateway or server
1364 oldServerInfo.getDhcpGatewayIp6().ifPresent(gatewayIp -> {
1365 hostService.stopMonitoringIp(gatewayIp);
1366 });
1367 oldServerInfo.getDhcpServerIp6().ifPresent(serverIp -> {
1368 hostService.stopMonitoringIp(serverIp);
Yi Tseng525ff402017-10-23 19:39:39 -07001369 cancelDhcpPacket(serverIp);
Yi Tseng919b2df2017-09-07 16:22:51 -07001370 });
1371 }
Kalhee Kim495c9b22017-11-07 16:32:09 +00001372 serverInfoList.clear();
1373 for (DhcpServerConfig serverConfig : configs) {
1374 // Create new server info according to the config
1375 DhcpServerInfo newServerInfo = new DhcpServerInfo(serverConfig,
1376 DhcpServerInfo.Version.DHCP_V6);
1377 checkState(newServerInfo.getDhcpServerConnectPoint().isPresent(),
1378 "Connect point not exists");
1379 checkState(newServerInfo.getDhcpServerIp6().isPresent(),
1380 "IP of DHCP server not exists");
Yi Tseng919b2df2017-09-07 16:22:51 -07001381
Kalhee Kim495c9b22017-11-07 16:32:09 +00001382 log.debug("DHCP server connect point: {}", newServerInfo.getDhcpServerConnectPoint().orElse(null));
1383 log.debug("DHCP server IP: {}", newServerInfo.getDhcpServerIp6().orElse(null));
Yi Tseng919b2df2017-09-07 16:22:51 -07001384
Kalhee Kim495c9b22017-11-07 16:32:09 +00001385 Ip6Address serverIp = newServerInfo.getDhcpServerIp6().get();
1386 Ip6Address ipToProbe;
1387 if (newServerInfo.getDhcpGatewayIp6().isPresent()) {
1388 ipToProbe = newServerInfo.getDhcpGatewayIp6().get();
1389 } else {
1390 ipToProbe = newServerInfo.getDhcpServerIp6().orElse(null);
1391 }
1392 String hostToProbe = newServerInfo.getDhcpGatewayIp6()
1393 .map(ip -> "gateway").orElse("server");
Yi Tseng919b2df2017-09-07 16:22:51 -07001394
Kalhee Kim495c9b22017-11-07 16:32:09 +00001395 log.warn("Probing to resolve {} IP {}", hostToProbe, ipToProbe);
1396 hostService.startMonitoringIp(ipToProbe);
1397
1398 Set<Host> hosts = hostService.getHostsByIp(ipToProbe);
1399 if (!hosts.isEmpty()) {
1400 Host host = hosts.iterator().next();
1401 newServerInfo.setDhcpConnectVlan(host.vlan());
1402 newServerInfo.setDhcpConnectMac(host.mac());
1403 log.warn("Host found host {}", host);
1404
1405 } else {
1406 log.warn("No host found host ip {}", ipToProbe);
1407 }
1408 // Add new server info
1409 synchronized (this) {
1410 serverInfoList.add(newServerInfo);
1411 }
1412 if (!hosts.isEmpty()) {
1413 requestDhcpPacket(serverIp);
1414 }
Yi Tseng919b2df2017-09-07 16:22:51 -07001415 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001416 }
1417
1418 class InternalHostListener implements HostListener {
1419 @Override
1420 public void event(HostEvent event) {
1421 switch (event.type()) {
1422 case HOST_ADDED:
1423 case HOST_UPDATED:
Charles Chanc7f63b62018-08-13 10:32:03 -07001424 case HOST_MOVED:
Jordan Halterman6328db72018-04-10 13:34:50 -04001425 log.trace("Scheduled host event {}", event);
1426 hostEventExecutor.execute(() -> hostUpdated(event.subject()));
Kalhee Kim45fede42017-09-05 19:05:06 +00001427 break;
1428 case HOST_REMOVED:
Jordan Halterman6328db72018-04-10 13:34:50 -04001429 log.trace("Scheduled host event {}", event);
1430 hostEventExecutor.execute(() -> hostRemoved(event.subject()));
Kalhee Kim45fede42017-09-05 19:05:06 +00001431 break;
Kalhee Kim45fede42017-09-05 19:05:06 +00001432 default:
1433 break;
1434 }
1435 }
1436 }
1437
1438 /**
Kalhee Kim45fede42017-09-05 19:05:06 +00001439 * Handle host updated.
1440 * If the host is DHCP server or gateway, update connect mac and vlan.
1441 *
1442 * @param host the host
1443 */
1444 private void hostUpdated(Host host) {
Yi Tseng525ff402017-10-23 19:39:39 -07001445 hostUpdated(host, defaultServerInfoList);
1446 hostUpdated(host, indirectServerInfoList);
Kalhee Kim45fede42017-09-05 19:05:06 +00001447 }
1448
Yi Tseng525ff402017-10-23 19:39:39 -07001449 private void hostUpdated(Host host, List<DhcpServerInfo> serverInfoList) {
jjosep004c41357882018-08-21 09:01:10 -04001450 serverInfoList.stream().forEach(serverInfo -> {
Yi Tseng525ff402017-10-23 19:39:39 -07001451 Ip6Address serverIp = serverInfo.getDhcpServerIp6().orElse(null);
jjosep004c41357882018-08-21 09:01:10 -04001452 Ip6Address targetIp = serverInfo.getDhcpGatewayIp6().orElse(null);
Yi Tseng525ff402017-10-23 19:39:39 -07001453
1454 if (targetIp == null) {
1455 targetIp = serverIp;
1456 }
Yi Tseng525ff402017-10-23 19:39:39 -07001457 if (targetIp != null) {
1458 if (host.ipAddresses().contains(targetIp)) {
1459 serverInfo.setDhcpConnectMac(host.mac());
1460 serverInfo.setDhcpConnectVlan(host.vlan());
1461 requestDhcpPacket(serverIp);
1462 }
1463 }
jjosep004c41357882018-08-21 09:01:10 -04001464 });
Yi Tseng525ff402017-10-23 19:39:39 -07001465 }
Kalhee Kim45fede42017-09-05 19:05:06 +00001466 /**
1467 * Handle host removed.
1468 * If the host is DHCP server or gateway, unset connect mac and vlan.
1469 *
1470 * @param host the host
1471 */
1472 private void hostRemoved(Host host) {
Yi Tseng525ff402017-10-23 19:39:39 -07001473 hostRemoved(host, defaultServerInfoList);
1474 hostRemoved(host, indirectServerInfoList);
Yi Tseng919b2df2017-09-07 16:22:51 -07001475 }
1476
Yi Tseng525ff402017-10-23 19:39:39 -07001477 private void hostRemoved(Host host, List<DhcpServerInfo> serverInfoList) {
jjosep004c41357882018-08-21 09:01:10 -04001478 serverInfoList.stream().forEach(serverInfo -> {
Yi Tseng525ff402017-10-23 19:39:39 -07001479 Ip6Address serverIp = serverInfo.getDhcpServerIp6().orElse(null);
jjosep004c41357882018-08-21 09:01:10 -04001480 Ip6Address targetIp = serverInfo.getDhcpGatewayIp6().orElse(null);
Yi Tseng525ff402017-10-23 19:39:39 -07001481
1482 if (targetIp == null) {
1483 targetIp = serverIp;
1484 }
Yi Tseng525ff402017-10-23 19:39:39 -07001485 if (targetIp != null) {
1486 if (host.ipAddresses().contains(targetIp)) {
1487 serverInfo.setDhcpConnectVlan(null);
1488 serverInfo.setDhcpConnectMac(null);
1489 cancelDhcpPacket(serverIp);
1490 }
1491 }
jjosep004c41357882018-08-21 09:01:10 -04001492 });
Yi Tseng525ff402017-10-23 19:39:39 -07001493 }
1494
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001495 /**
1496 * Gets Interface facing to the server for default host.
1497 *
1498 * @return the Interface facing to the server; null if not found
1499 */
1500 private Interface getServerInterface() {
1501 DhcpServerInfo serverInfo;
1502 ConnectPoint dhcpServerConnectPoint;
1503 VlanId dhcpConnectVlan;
1504
1505 if (!defaultServerInfoList.isEmpty()) {
1506 serverInfo = defaultServerInfoList.get(0);
1507 dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1508 dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
1509 } else {
1510 return null;
1511 }
1512 if (dhcpServerConnectPoint == null || dhcpConnectVlan == null) {
1513 log.info("Default DHCP server {} not resolve yet", serverInfo.getDhcpGatewayIp6());
1514 return null;
1515 }
1516 return interfaceService.getInterfacesByPort(dhcpServerConnectPoint)
1517 .stream()
Taras Lemkin41785912018-03-26 14:52:58 +00001518 .filter(iface -> Dhcp6HandlerUtil.interfaceContainsVlan(iface, dhcpConnectVlan))
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001519 .findFirst()
1520 .orElse(null);
1521 }
1522
1523 /**
1524 * Gets Interface facing to the server for indirect hosts.
1525 * Use default server Interface if indirect server not configured.
1526 *
1527 * @return the Interface facing to the server; null if not found
1528 */
1529 private Interface getIndirectServerInterface() {
1530 DhcpServerInfo serverInfo;
1531
1532 ConnectPoint indirectDhcpServerConnectPoint;
1533 VlanId indirectDhcpConnectVlan;
1534
1535 if (!indirectServerInfoList.isEmpty()) {
1536 serverInfo = indirectServerInfoList.get(0);
1537 indirectDhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1538 indirectDhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
1539 } else {
1540 return getServerInterface();
1541 }
1542 if (indirectDhcpServerConnectPoint == null || indirectDhcpConnectVlan == null) {
1543 log.info("Indirect DHCP server {} not resolve yet", serverInfo.getDhcpGatewayIp6());
1544 return null;
1545 }
1546 return interfaceService.getInterfacesByPort(indirectDhcpServerConnectPoint)
1547 .stream()
Taras Lemkin41785912018-03-26 14:52:58 +00001548 .filter(iface -> Dhcp6HandlerUtil.interfaceContainsVlan(iface, indirectDhcpConnectVlan))
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001549 .findFirst()
1550 .orElse(null);
1551 }
1552
Kalhee Kim45b24182017-10-18 18:30:23 +00001553 /**
Kalhee Kim495c9b22017-11-07 16:32:09 +00001554 * Checks if serverInfo's host info (mac and vlan) is filled in; if not, fills in.
1555 *
1556 * @param serverInfo server information
1557 * @return newServerInfo if host info can be either found or filled in.
1558 */
1559 private DhcpServerInfo getHostInfoForServerInfo(DhcpServerInfo serverInfo, List<DhcpServerInfo> sererInfoList) {
1560 DhcpServerInfo newServerInfo = null;
1561 MacAddress dhcpServerConnectMac = serverInfo.getDhcpConnectMac().orElse(null);
1562 VlanId dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
1563 ConnectPoint dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1564
1565 if (dhcpServerConnectMac != null && dhcpConnectVlan != null) {
1566 newServerInfo = serverInfo;
Charles Chan750c9992018-02-26 10:44:49 -08001567 log.debug("DHCP server {} host info found. ConnectPt{} Mac {} vlan {}", serverInfo.getDhcpServerIp6(),
Kalhee Kim495c9b22017-11-07 16:32:09 +00001568 dhcpServerConnectPoint, dhcpServerConnectMac, dhcpConnectVlan);
1569 } else {
Harshada Chaundkar6c54f202019-05-06 20:16:13 +00001570 log.debug("DHCP server {} not resolve yet connectPt {} mac {} vlan {}", serverInfo.getDhcpServerIp6(),
Kalhee Kim495c9b22017-11-07 16:32:09 +00001571 dhcpServerConnectPoint, dhcpServerConnectMac, dhcpConnectVlan);
1572
1573 Ip6Address ipToProbe;
1574 if (serverInfo.getDhcpGatewayIp6().isPresent()) {
1575 ipToProbe = serverInfo.getDhcpGatewayIp6().get();
1576 } else {
1577 ipToProbe = serverInfo.getDhcpServerIp6().orElse(null);
1578 }
1579 String hostToProbe = serverInfo.getDhcpGatewayIp6()
1580 .map(ip -> "gateway").orElse("server");
1581
Harshada Chaundkar6c54f202019-05-06 20:16:13 +00001582 log.debug("Dynamically probing to resolve {} IP {}", hostToProbe, ipToProbe);
Kalhee Kim495c9b22017-11-07 16:32:09 +00001583 hostService.startMonitoringIp(ipToProbe);
1584
1585 Set<Host> hosts = hostService.getHostsByIp(ipToProbe);
1586 if (!hosts.isEmpty()) {
1587 int serverInfoIndex = sererInfoList.indexOf(serverInfo);
1588 Host host = hosts.iterator().next();
1589 serverInfo.setDhcpConnectVlan(host.vlan());
1590 serverInfo.setDhcpConnectMac(host.mac());
1591 // replace the serverInfo in the list
1592 sererInfoList.set(serverInfoIndex, serverInfo);
1593 newServerInfo = serverInfo;
1594 log.warn("Dynamically host found host {}", host);
1595 } else {
Harshada Chaundkar6c54f202019-05-06 20:16:13 +00001596 log.debug("No host found host ip {} dynamically", ipToProbe);
Kalhee Kim495c9b22017-11-07 16:32:09 +00001597 }
1598 }
1599 return newServerInfo;
1600 }
1601
1602 /**
Kalhee Kim45b24182017-10-18 18:30:23 +00001603 * Gets Interface facing to the server for default host.
1604 *
Kalhee Kim495c9b22017-11-07 16:32:09 +00001605 * @param serverInfo server information
Kalhee Kim45b24182017-10-18 18:30:23 +00001606 * @return the Interface facing to the server; null if not found
1607 */
Kalhee Kim495c9b22017-11-07 16:32:09 +00001608 private Interface getServerInterface(DhcpServerInfo serverInfo) {
1609 Interface serverInterface = null;
Yi Tseng25bfe372017-11-03 16:27:32 -07001610
Kalhee Kim495c9b22017-11-07 16:32:09 +00001611 ConnectPoint dhcpServerConnectPoint = serverInfo.getDhcpServerConnectPoint().orElse(null);
1612 VlanId dhcpConnectVlan = serverInfo.getDhcpConnectVlan().orElse(null);
1613
1614 if (dhcpServerConnectPoint != null && dhcpConnectVlan != null) {
1615 serverInterface = interfaceService.getInterfacesByPort(dhcpServerConnectPoint)
1616 .stream()
Taras Lemkin41785912018-03-26 14:52:58 +00001617 .filter(iface -> Dhcp6HandlerUtil.interfaceContainsVlan(iface, dhcpConnectVlan))
Kalhee Kim495c9b22017-11-07 16:32:09 +00001618 .findFirst()
1619 .orElse(null);
Yi Tseng25bfe372017-11-03 16:27:32 -07001620 } else {
Kalhee Kim495c9b22017-11-07 16:32:09 +00001621 log.warn("DHCP server {} not resolve yet connectPoint {} vlan {}", serverInfo.getDhcpServerIp6(),
1622 dhcpServerConnectPoint, dhcpConnectVlan);
Kalhee Kim45b24182017-10-18 18:30:23 +00001623 }
Kalhee Kim495c9b22017-11-07 16:32:09 +00001624
1625 return serverInterface;
Kalhee Kim45b24182017-10-18 18:30:23 +00001626 }
1627
Yi Tseng525ff402017-10-23 19:39:39 -07001628 private void requestDhcpPacket(Ip6Address serverIp) {
1629 requestServerDhcpPacket(serverIp);
1630 requestClientDhcpPacket(serverIp);
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001631 requestServerLQPacket(serverIp);
Yi Tseng525ff402017-10-23 19:39:39 -07001632 }
1633
1634 private void cancelDhcpPacket(Ip6Address serverIp) {
1635 cancelServerDhcpPacket(serverIp);
1636 cancelClientDhcpPacket(serverIp);
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001637 cancelServerLQPacket(serverIp);
Yi Tseng525ff402017-10-23 19:39:39 -07001638 }
1639
1640 private void cancelServerDhcpPacket(Ip6Address serverIp) {
1641 TrafficSelector serverSelector =
1642 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1643 .matchIPv6Src(serverIp.toIpPrefix())
1644 .build();
1645 packetService.cancelPackets(serverSelector,
1646 PacketPriority.CONTROL,
1647 appId);
1648 }
1649
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001650 private void cancelServerLQPacket(Ip6Address serverIp) {
1651 TrafficSelector serverSelector =
1652 DefaultTrafficSelector.builder(LEASE_QUERY_RESPONSE_SELECTOR)
1653 .matchIPv6Src(serverIp.toIpPrefix())
1654 .build();
1655 packetService.cancelPackets(serverSelector,
1656 PacketPriority.CONTROL,
1657 appId);
1658 }
1659
Yi Tseng525ff402017-10-23 19:39:39 -07001660 private void requestServerDhcpPacket(Ip6Address serverIp) {
1661 TrafficSelector serverSelector =
1662 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1663 .matchIPv6Src(serverIp.toIpPrefix())
1664 .build();
1665 packetService.requestPackets(serverSelector,
1666 PacketPriority.CONTROL,
1667 appId);
1668 }
1669
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001670 private void requestServerLQPacket(Ip6Address serverIp) {
1671 TrafficSelector serverSelector =
1672 DefaultTrafficSelector.builder(LEASE_QUERY_RESPONSE_SELECTOR)
1673 .matchIPv6Src(serverIp.toIpPrefix())
1674 .build();
1675 packetService.requestPackets(serverSelector,
1676 PacketPriority.CONTROL,
1677 appId);
1678 }
1679
Yi Tseng525ff402017-10-23 19:39:39 -07001680 private void cancelClientDhcpPacket(Ip6Address serverIp) {
1681 // Packet comes from relay
1682 TrafficSelector indirectClientSelector =
1683 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1684 .matchIPv6Dst(serverIp.toIpPrefix())
1685 .build();
1686 packetService.cancelPackets(indirectClientSelector,
1687 PacketPriority.CONTROL,
1688 appId);
Yi Tseng41dde702017-11-02 15:21:10 -07001689 indirectClientSelector =
1690 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1691 .matchIPv6Dst(Ip6Address.ALL_DHCP_RELAY_AGENTS_AND_SERVERS.toIpPrefix())
1692 .build();
1693 packetService.cancelPackets(indirectClientSelector,
1694 PacketPriority.CONTROL,
1695 appId);
1696 indirectClientSelector =
1697 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1698 .matchIPv6Dst(Ip6Address.ALL_DHCP_SERVERS.toIpPrefix())
1699 .build();
1700 packetService.cancelPackets(indirectClientSelector,
1701 PacketPriority.CONTROL,
1702 appId);
Yi Tseng525ff402017-10-23 19:39:39 -07001703
1704 // Packet comes from client
1705 packetService.cancelPackets(CLIENT_SERVER_SELECTOR,
1706 PacketPriority.CONTROL,
1707 appId);
1708 }
1709
1710 private void requestClientDhcpPacket(Ip6Address serverIp) {
1711 // Packet comes from relay
1712 TrafficSelector indirectClientSelector =
1713 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1714 .matchIPv6Dst(serverIp.toIpPrefix())
1715 .build();
1716 packetService.requestPackets(indirectClientSelector,
1717 PacketPriority.CONTROL,
1718 appId);
Yi Tseng41dde702017-11-02 15:21:10 -07001719 indirectClientSelector =
1720 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1721 .matchIPv6Dst(Ip6Address.ALL_DHCP_RELAY_AGENTS_AND_SERVERS.toIpPrefix())
1722 .build();
1723 packetService.requestPackets(indirectClientSelector,
1724 PacketPriority.CONTROL,
1725 appId);
1726 indirectClientSelector =
1727 DefaultTrafficSelector.builder(SERVER_RELAY_SELECTOR)
1728 .matchIPv6Dst(Ip6Address.ALL_DHCP_SERVERS.toIpPrefix())
1729 .build();
1730 packetService.requestPackets(indirectClientSelector,
1731 PacketPriority.CONTROL,
1732 appId);
Yi Tseng525ff402017-10-23 19:39:39 -07001733
1734 // Packet comes from client
1735 packetService.requestPackets(CLIENT_SERVER_SELECTOR,
1736 PacketPriority.CONTROL,
1737 appId);
1738 }
1739
1740 /**
1741 * Process the ignore rules.
1742 *
1743 * @param deviceId the device id
1744 * @param vlanId the vlan to be ignored
1745 * @param op the operation, ADD to install; REMOVE to uninstall rules
1746 */
1747 private void processIgnoreVlanRule(DeviceId deviceId, VlanId vlanId, Objective.Operation op) {
Yi Tseng525ff402017-10-23 19:39:39 -07001748 AtomicInteger installedCount = new AtomicInteger(DHCP_SELECTORS.size());
1749 DHCP_SELECTORS.forEach(trafficSelector -> {
1750 TrafficSelector selector = DefaultTrafficSelector.builder(trafficSelector)
1751 .matchVlanId(vlanId)
1752 .build();
1753
1754 ForwardingObjective.Builder builder = DefaultForwardingObjective.builder()
1755 .withFlag(ForwardingObjective.Flag.VERSATILE)
1756 .withSelector(selector)
1757 .withPriority(IGNORE_CONTROL_PRIORITY)
Yi Tsengdbabeed2017-11-29 10:49:20 -08001758 .withTreatment(DefaultTrafficTreatment.emptyTreatment())
Yi Tseng525ff402017-10-23 19:39:39 -07001759 .fromApp(appId);
1760
1761
1762 ObjectiveContext objectiveContext = new ObjectiveContext() {
1763 @Override
1764 public void onSuccess(Objective objective) {
1765 log.info("Ignore rule {} (Vlan id {}, device {}, selector {})",
1766 op, vlanId, deviceId, selector);
1767 int countDown = installedCount.decrementAndGet();
1768 if (countDown != 0) {
1769 return;
1770 }
1771 switch (op) {
1772 case ADD:
1773 ignoredVlans.put(deviceId, vlanId);
1774 break;
1775 case REMOVE:
1776 ignoredVlans.remove(deviceId, vlanId);
1777 break;
1778 default:
1779 log.warn("Unsupported objective operation {}", op);
1780 break;
1781 }
1782 }
1783
1784 @Override
1785 public void onError(Objective objective, ObjectiveError error) {
1786 log.warn("Can't {} ignore rule (vlan id {}, selector {}, device {}) due to {}",
1787 op, vlanId, selector, deviceId, error);
1788 }
1789 };
1790
1791 ForwardingObjective fwd;
1792 switch (op) {
1793 case ADD:
1794 fwd = builder.add(objectiveContext);
1795 break;
1796 case REMOVE:
1797 fwd = builder.remove(objectiveContext);
1798 break;
1799 default:
1800 log.warn("Unsupported objective operation {}", op);
1801 return;
1802 }
1803
1804 Device device = deviceService.getDevice(deviceId);
1805 if (device == null || !device.is(Pipeliner.class)) {
1806 log.warn("Device {} is not available now, wait until device is available", deviceId);
1807 return;
1808 }
1809 flowObjectiveService.apply(deviceId, fwd);
1810 });
1811 }
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001812
Kalhee Kim121ba922017-11-01 17:56:44 +00001813 /**
1814 * Find first ipaddress for a given Host info i.e. mac and vlan.
1815 *
1816 * @param clientMac client mac
1817 * @param vlanId packet's vlan
1818 * @return next-hop link-local ipaddress for a given host
1819 */
Kalhee Kim495c9b22017-11-07 16:32:09 +00001820 private IpAddress getFirstIpByHost(Boolean directConnFlag, MacAddress clientMac, VlanId vlanId) {
Kalhee Kim121ba922017-11-01 17:56:44 +00001821 IpAddress nextHopIp;
1822 // pick out the first link-local ip address
1823 HostId gwHostId = HostId.hostId(clientMac, vlanId);
1824 Host gwHost = hostService.getHost(gwHostId);
1825 if (gwHost == null) {
1826 log.warn("Can't find gateway host for hostId {}", gwHostId);
1827 return null;
1828 }
Kalhee Kim495c9b22017-11-07 16:32:09 +00001829 if (directConnFlag) {
1830 nextHopIp = gwHost.ipAddresses()
1831 .stream()
1832 .filter(IpAddress::isIp6)
1833 .map(IpAddress::getIp6Address)
1834 .findFirst()
1835 .orElse(null);
1836 } else {
1837 nextHopIp = gwHost.ipAddresses()
1838 .stream()
1839 .filter(IpAddress::isIp6)
1840 .filter(ip6 -> ip6.isLinkLocal())
1841 .map(IpAddress::getIp6Address)
1842 .findFirst()
1843 .orElse(null);
1844 }
Kalhee Kim121ba922017-11-01 17:56:44 +00001845 return nextHopIp;
1846 }
Kalhee Kimea4b6c22017-11-09 14:38:37 +00001847
Kalhee Kim495c9b22017-11-07 16:32:09 +00001848 private List<DhcpServerInfo> findValidServerInfo(boolean directConnFlag) {
1849 List<DhcpServerInfo> validServerInfo;
1850
1851 if (directConnFlag || indirectServerInfoList.isEmpty()) {
1852 validServerInfo = new ArrayList<DhcpServerInfo>(defaultServerInfoList);
1853 } else {
1854 validServerInfo = new ArrayList<DhcpServerInfo>(indirectServerInfoList);
1855 }
1856 return validServerInfo;
1857 }
1858
1859 private DhcpServerInfo findServerInfoFromServer(boolean directConnFlag, ConnectPoint inPort) {
1860 List<DhcpServerInfo> validServerInfoList = findValidServerInfo(directConnFlag);
1861 DhcpServerInfo foundServerInfo = null;
1862 for (DhcpServerInfo serverInfo : validServerInfoList) {
1863 if (inPort.equals(serverInfo.getDhcpServerConnectPoint().get())) {
1864 foundServerInfo = serverInfo;
Charles Chan750c9992018-02-26 10:44:49 -08001865 log.debug("ServerInfo found for Rcv port {} Server Connect Point {} for {}",
Kalhee Kim495c9b22017-11-07 16:32:09 +00001866 inPort, serverInfo.getDhcpServerConnectPoint(), directConnFlag ? "direct" : "indirect");
1867 break;
Kalhee Kim495c9b22017-11-07 16:32:09 +00001868 }
1869 }
1870 return foundServerInfo;
1871 }
Lior Assoulinea21c0ca2018-01-28 16:18:48 -08001872
Kalhee Kim495c9b22017-11-07 16:32:09 +00001873 /**
1874 * Set the dhcp6 lease expiry poll interval value.
1875 *
1876 * @param val poll interval value in seconds
1877 */
Kalhee Kim2f07c602017-11-15 18:57:53 +00001878 @Override
Kalhee Kim495c9b22017-11-07 16:32:09 +00001879 public void setDhcp6PollInterval(int val) {
1880 dhcp6PollInterval = val;
1881 }
1882
Kalhee Kim2f07c602017-11-15 18:57:53 +00001883 /**
1884 * get the dhcp6 lease expiry poll interval value.
1885 * This is a private function
1886 * @return poll interval value in seconds
1887 */
1888 private int getDhcp6PollInterval() {
1889 return dhcp6PollInterval;
1890 }
1891
1892 /**
1893 * Find lease-expired ipaddresses and pd prefixes.
1894 * Removing host/route/fpm entries.
1895 */
1896 public void timeTick() {
1897 long currentTime = System.currentTimeMillis();
1898 Collection<DhcpRecord> records = dhcpRelayStore.getDhcpRecords();
1899
1900 log.debug("timeTick called currenttime {} records num {} ", currentTime, records.size());
1901
1902 records.forEach(record -> {
1903 boolean addrOrPdRemoved = false;
1904 DHCP6.MsgType ip6Status = record.ip6Status().orElse(null);
1905 if (ip6Status == null) {
1906 log.debug("record is not valid v6 record.");
1907 return;
1908 }
1909
1910 if ((currentTime - record.getLastIp6Update()) >
1911 ((record.addrPrefTime() + getDhcp6PollInterval() / 2) * 1000)) {
1912 // remove ipaddress from host/route table
1913 IpAddress ip = record.ip6Address().orElse(null);
1914 if (ip != null) {
1915 if (record.directlyConnected()) {
1916 providerService.removeIpFromHost(HostId.hostId(record.macAddress(),
1917 record.vlanId()), ip);
1918 } else {
1919 MacAddress gwMac = record.nextHop().orElse(null);
1920 if (gwMac == null) {
1921 log.warn("Can't find gateway mac address from record {} for ip6Addr", record);
1922 return;
1923 }
1924 IpAddress nextHopIp = getFirstIpByHost(record.directlyConnected(),
1925 gwMac,
1926 record.vlanId());
Kalhee Kim54a97c92018-04-02 21:23:46 +00001927 Route route = new Route(Route.Source.DHCP, ip.toIpPrefix(), nextHopIp);
Kalhee Kim2f07c602017-11-15 18:57:53 +00001928 routeStore.removeRoute(route);
1929 }
1930 record.updateAddrPrefTime(0);
1931 record.ip6Address(null);
1932 addrOrPdRemoved = true;
1933 dhcpRelayStore.updateDhcpRecord(HostId.hostId(record.macAddress(),
1934 record.vlanId()), record);
1935 log.warn("IP6 address is set to null. delta {} lastUpdate {} addrPrefTime {}",
1936 (currentTime - record.getLastIp6Update()), record.getLastIp6Update(),
1937 record.addrPrefTime());
1938 }
1939 }
1940 if ((currentTime - record.getLastPdUpdate()) >
1941 ((record.pdPrefTime() + getDhcp6PollInterval() / 2) * 1000)) {
1942 // remove PD from route/fpm table
1943 IpPrefix pdIpPrefix = record.pdPrefix().orElse(null);
1944 if (pdIpPrefix != null) {
1945 if (record.directlyConnected()) {
1946 providerService.removeIpFromHost(HostId.hostId(record.macAddress(), record.vlanId()),
1947 pdIpPrefix.address().getIp6Address());
1948 } else {
1949 MacAddress gwMac = record.nextHop().orElse(null);
1950 if (gwMac == null) {
1951 log.warn("Can't find gateway mac address from record {} for PD prefix", record);
1952 return;
1953 }
1954 IpAddress nextHopIp = getFirstIpByHost(record.directlyConnected(),
1955 gwMac,
1956 record.vlanId());
Kalhee Kim54a97c92018-04-02 21:23:46 +00001957 Route route = new Route(Route.Source.DHCP, pdIpPrefix, nextHopIp);
Kalhee Kim2f07c602017-11-15 18:57:53 +00001958 routeStore.removeRoute(route);
1959 if (this.dhcpFpmEnabled) {
1960 dhcpFpmPrefixStore.removeFpmRecord(pdIpPrefix);
1961 }
1962 }
1963 record.updatePdPrefTime(0);
1964 record.pdPrefix(null);
1965 addrOrPdRemoved = true;
1966 dhcpRelayStore.updateDhcpRecord(HostId.hostId(record.macAddress(),
1967 record.vlanId()), record);
1968 log.warn("PD prefix is set to null.delta {} pdPrefTime {}",
1969 (currentTime - record.getLastPdUpdate()), record.pdPrefTime());
1970 }
1971 }
1972 if (addrOrPdRemoved &&
1973 !record.ip6Address().isPresent() && !record.pdPrefix().isPresent()) {
1974 log.warn("ip6Status {} IP6 address and IP6 PD both are null. Remove record.", ip6Status);
1975 dhcpRelayStore.removeDhcpRecord(HostId.hostId(record.macAddress(), record.vlanId()));
1976 }
1977 }
1978 );
1979 }
1980}