Bug 3460 removed ip prefix from DHCP/DNS flows
[groupbasedpolicy.git] / neutron-mapper / src / main / java / org / opendaylight / groupbasedpolicy / neutron / mapper / mapping / NeutronPortAware.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping;
9
10 import static com.google.common.base.Preconditions.checkNotNull;
11
12 import java.util.ArrayList;
13 import java.util.Collection;
14 import java.util.HashMap;
15 import java.util.HashSet;
16 import java.util.List;
17 import java.util.Map;
18 import java.util.Set;
19 import java.util.concurrent.ExecutionException;
20
21 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
22 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
23 import org.opendaylight.controller.md.sal.binding.api.ReadTransaction;
24 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
25 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
26 import org.opendaylight.groupbasedpolicy.neutron.gbp.util.NeutronGbpIidFactory;
27 import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils;
28 import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils.ForwardingCtx;
29 import org.opendaylight.groupbasedpolicy.neutron.mapper.util.NeutronUtils;
30 import org.opendaylight.groupbasedpolicy.neutron.mapper.util.Utils;
31 import org.opendaylight.groupbasedpolicy.util.DataStoreHelper;
32 import org.opendaylight.groupbasedpolicy.util.IidFactory;
33 import org.opendaylight.neutron.spi.INeutronPortAware;
34 import org.opendaylight.neutron.spi.NeutronPort;
35 import org.opendaylight.neutron.spi.NeutronSecurityGroup;
36 import org.opendaylight.neutron.spi.NeutronSecurityRule;
37 import org.opendaylight.neutron.spi.Neutron_IPs;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2FloodDomainId;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L3ContextId;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.Name;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.NetworkDomainId;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubnetId;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.UniqueId;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.EndpointService;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterEndpointInput;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterEndpointInputBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterL3PrefixEndpointInput;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterL3PrefixEndpointInputBuilder;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.UnregisterEndpointInput;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.UnregisterEndpointInputBuilder;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoint.fields.L3Address;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoint.fields.L3AddressBuilder;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoint.l3.prefix.fields.EndpointL3Gateways;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoint.l3.prefix.fields.EndpointL3GatewaysBuilder;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.Endpoint;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointKey;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3Builder;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3Key;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3PrefixKey;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.unregister.endpoint.input.L2;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.unregister.endpoint.input.L2Builder;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.unregister.endpoint.input.L3;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.unregister.endpoint.input.L3Builder;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.mappings.gbp.by.neutron.mappings.endpoints.by.floating.ip.ports.EndpointByFloatingIpPort;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.mappings.gbp.by.neutron.mappings.endpoints.by.ports.EndpointByPort;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.mappings.gbp.by.neutron.mappings.endpoints.by.router._interface.ports.EndpointByRouterInterfacePort;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.mappings.gbp.by.neutron.mappings.endpoints.by.router.gateway.ports.EndpointByRouterGatewayPort;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.mappings.neutron.by.gbp.mappings.external.gateways.as.l3.endpoints.ExternalGatewayAsL3Endpoint;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.mappings.neutron.by.gbp.mappings.floating.ip.ports.by.endpoints.FloatingIpPortByEndpoint;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.mappings.neutron.by.gbp.mappings.ports.by.endpoints.PortByEndpoint;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.mappings.neutron.by.gbp.mappings.router._interface.ports.by.endpoints.RouterInterfacePortByEndpoint;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.mappings.neutron.by.gbp.mappings.router.gateway.ports.by.endpoints.RouterGatewayPortByEndpoint;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.ofoverlay.rev140528.EndpointLocation.LocationType;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.ofoverlay.rev140528.OfOverlayContextInput;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.ofoverlay.rev140528.OfOverlayContextInputBuilder;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.EndpointGroup;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.Subnet;
84 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
85 import org.opendaylight.yangtools.yang.common.RpcResult;
86 import org.slf4j.Logger;
87 import org.slf4j.LoggerFactory;
88
89 import com.google.common.base.Function;
90 import com.google.common.base.Optional;
91 import com.google.common.base.Strings;
92 import com.google.common.collect.Collections2;
93 import com.google.common.collect.ImmutableList;
94
95 public class NeutronPortAware implements INeutronPortAware {
96
97     public static final Logger LOG = LoggerFactory.getLogger(NeutronPortAware.class);
98     private static final String DEVICE_OWNER_DHCP = "network:dhcp";
99     private static final String DEVICE_OWNER_ROUTER_IFACE = "network:router_interface";
100     private static final String DEVICE_OWNER_ROUTER_GATEWAY = "network:router_gateway";
101     private static final String DEVICE_OWNER_FLOATING_IP = "network:floatingip";
102     private static final int DHCP_SERVER_PORT = 67;
103     private static final int DNS_SERVER_PORT = 53;
104     private final DataBroker dataProvider;
105     private final EndpointService epService;
106     private final static Map<String, UniqueId> floatingIpPortByDeviceId = new HashMap<>();
107
108     public NeutronPortAware(DataBroker dataProvider, EndpointService epService) {
109         this.dataProvider = checkNotNull(dataProvider);
110         this.epService = checkNotNull(epService);
111     }
112
113     /**
114      * @see org.opendaylight.neutron.spi.INeutronPortAware#canCreatePort(org.opendaylight.neutron.spi.NeutronPort)
115      */
116     @Override
117     public int canCreatePort(NeutronPort port) {
118         LOG.trace("canCreatePort - {}", port);
119         // TODO Li msunal this has to be rewrite when OFOverlay renderer will support l3-endpoints.
120         List<Neutron_IPs> fixedIPs = port.getFixedIPs();
121         if (fixedIPs != null && fixedIPs.size() > 1) {
122             LOG.warn("Neutron mapper does not support multiple IPs on the same port.");
123             return StatusCode.BAD_REQUEST;
124         }
125         return StatusCode.OK;
126     }
127
128     /**
129      * @see org.opendaylight.neutron.spi.INeutronPortAware#neutronPortCreated(org.opendaylight.neutron.spi.NeutronPort)
130      */
131     @Override
132     public void neutronPortCreated(NeutronPort port) {
133         LOG.trace("neutronPortCreated - {}", port);
134         if (isRouterInterfacePort(port)) {
135             LOG.trace("Port is router interface - {} does nothing. {} handles router iface.",
136                     NeutronPortAware.class.getSimpleName(), NeutronRouterAware.class.getSimpleName());
137             return;
138         }
139         if (isRouterGatewayPort(port)) {
140             LOG.trace("Port is router gateway - {} does nothing. {} handles router iface.",
141                     NeutronPortAware.class.getSimpleName(), NeutronRouterAware.class.getSimpleName());
142             return;
143         }
144         if (isFloatingIpPort(port)) {
145             LOG.trace("Port is floating ip - {} device id - {}", port.getID(), port.getDeviceID());
146             floatingIpPortByDeviceId.put(port.getDeviceID(), new UniqueId(port.getID()));
147             return;
148         }
149         ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction();
150         TenantId tenantId = new TenantId(Utils.normalizeUuid(port.getTenantID()));
151         if (isDhcpPort(port)) {
152             LOG.trace("Port is DHCP port. - {}", port.getID());
153             List<NeutronSecurityRule> dhcpSecRules = createDhcpSecRules(port, null, rwTx);
154             if (dhcpSecRules == null) {
155                 rwTx.cancel();
156                 return;
157             }
158
159             for (NeutronSecurityRule dhcpSecRule : dhcpSecRules) {
160                 boolean isDhcpSecRuleAdded = NeutronSecurityRuleAware.addNeutronSecurityRule(dhcpSecRule, rwTx);
161                 if (!isDhcpSecRuleAdded) {
162                     rwTx.cancel();
163                     return;
164                 }
165             }
166         } else {
167             List<NeutronSecurityGroup> secGroups = port.getSecurityGroups();
168             if (secGroups != null) {
169                 for (NeutronSecurityGroup secGroup : secGroups) {
170                     EndpointGroupId epgId = new EndpointGroupId(secGroup.getSecurityGroupUUID());
171                     Optional<EndpointGroup> potentialEpg = DataStoreHelper.readFromDs(LogicalDatastoreType.CONFIGURATION,
172                             IidFactory.endpointGroupIid(tenantId, epgId), rwTx);
173                     if (!potentialEpg.isPresent()) {
174                         boolean isSecGroupCreated = NeutronSecurityGroupAware.addNeutronSecurityGroup(secGroup, rwTx);
175                         if (!isSecGroupCreated) {
176                             rwTx.cancel();
177                             return;
178                         }
179                         if (containsSecRuleWithRemoteSecGroup(secGroup)) {
180                             List<NeutronSecurityRule> dhcpSecRules = createDhcpSecRules(port, epgId, rwTx);
181                             if (dhcpSecRules == null) {
182                                 rwTx.cancel();
183                                 return;
184                             }
185                             List<NeutronSecurityRule> routerSecRules = NeutronRouterAware.createRouterSecRules(port, epgId, rwTx);
186                             if (routerSecRules == null) {
187                                 rwTx.cancel();
188                                 return;
189                             }
190                         }
191                     } else {
192                         List<NeutronSecurityRule> secRules = secGroup.getSecurityRules();
193                         if (secRules != null) {
194                             for (NeutronSecurityRule secRule : secRules) {
195                                 NeutronSecurityRuleAware.addNeutronSecurityRule(secRule, rwTx);
196                             }
197                         }
198                     }
199                 }
200             }
201         }
202         boolean isNeutronPortCreated = addNeutronPort(port, rwTx, epService);
203         if (!isNeutronPortCreated) {
204             rwTx.cancel();
205             return;
206         }
207
208         DataStoreHelper.submitToDs(rwTx);
209     }
210
211     public static boolean addNeutronPort(NeutronPort port, ReadWriteTransaction rwTx, EndpointService epService) {
212         TenantId tenantId = new TenantId(Utils.normalizeUuid(port.getTenantID()));
213         L2FloodDomainId l2FdId = new L2FloodDomainId(port.getNetworkUUID());
214         ForwardingCtx fwCtx = MappingUtils.createForwardingContext(tenantId, l2FdId, rwTx);
215         boolean isFwCtxValid = validateForwardingCtx(fwCtx);
216         if (!isFwCtxValid) {
217             return false;
218         }
219         EndpointKey epKey = new EndpointKey(fwCtx.getL2BridgeDomain().getId(), new MacAddress(port.getMacAddress()));
220         addNeutronGbpMapping(port, epKey, rwTx);
221
222         try {
223             RegisterEndpointInput registerEpRpcInput = createRegisterEndpointInput(port, fwCtx);
224             RpcResult<Void> rpcResult = epService.registerEndpoint(registerEpRpcInput).get();
225             if (!rpcResult.isSuccessful()) {
226                 LOG.warn("Illegal state - RPC registerEndpoint failed. Input of RPC: {}", registerEpRpcInput);
227                 return false;
228             }
229         } catch (InterruptedException | ExecutionException e) {
230             LOG.error("addNeutronPort failed. {}", port, e);
231             return false;
232         }
233         return true;
234     }
235
236     public static boolean addL3EndpointForExternalGateway(TenantId tenantId, L3ContextId l3ContextId,
237             IpAddress ipAddress, NetworkDomainId networkContainment, ReadWriteTransaction rwTx) {
238
239         EndpointL3Key epL3Key = new EndpointL3Key(ipAddress, l3ContextId);
240         addNeutronExtGwGbpMapping(epL3Key, rwTx);
241         List<EndpointGroupId> epgIds = new ArrayList<>();
242         // each EP has to be in EPG ANY, except dhcp and router
243         epgIds.add(MappingUtils.EPG_EXTERNAL_ID);
244         epgIds.add(MappingUtils.EPG_ROUTER_ID);
245         EndpointL3 epL3 = createL3Endpoint(tenantId, epL3Key, epgIds, networkContainment);
246         InstanceIdentifier<EndpointL3> iid_l3 = IidFactory.l3EndpointIid(l3ContextId, ipAddress);
247         rwTx.put(LogicalDatastoreType.OPERATIONAL, iid_l3, epL3, true);
248         return true;
249     }
250
251     private static void addNeutronExtGwGbpMapping(EndpointL3Key epL3Key, ReadWriteTransaction rwTx) {
252             ExternalGatewayAsL3Endpoint externalGatewayL3Endpoint = MappingFactory.createExternalGatewayByL3Endpoint(epL3Key);
253             rwTx.put(LogicalDatastoreType.OPERATIONAL, NeutronGbpIidFactory.externalGatewayAsL3Endpoint(epL3Key.getL3Context(), epL3Key.getIpAddress()),
254                     externalGatewayL3Endpoint, true);
255     }
256
257     private static void addNeutronGbpMapping(NeutronPort port, EndpointKey epKey, ReadWriteTransaction rwTx) {
258         UniqueId portId = new UniqueId(port.getID());
259         if (isRouterInterfacePort(port)) {
260             LOG.trace("Adding RouterInterfacePort-Endpoint mapping for port {} and endpoint {}", port.getID(), epKey);
261             EndpointByRouterInterfacePort endpointByPort = MappingFactory.createEndpointByRouterInterfacePort(epKey,
262                     portId);
263             rwTx.put(LogicalDatastoreType.OPERATIONAL, NeutronGbpIidFactory.endpointByRouterInterfacePortIid(portId),
264                     endpointByPort, true);
265             RouterInterfacePortByEndpoint portByEndpoint = MappingFactory.createRouterInterfacePortByEndpoint(portId,
266                     epKey);
267             rwTx.put(LogicalDatastoreType.OPERATIONAL,
268                     NeutronGbpIidFactory.routerInterfacePortByEndpointIid(epKey.getL2Context(), epKey.getMacAddress()),
269                     portByEndpoint, true);
270         } else if (isRouterGatewayPort(port)) {
271             LOG.trace("Adding RouterGatewayPort-Endpoint mapping for port {} and endpoint {}", port.getID(), epKey);
272             EndpointByRouterGatewayPort endpointByPort = MappingFactory.createEndpointByRouterGatewayPort(epKey, portId);
273             rwTx.put(LogicalDatastoreType.OPERATIONAL, NeutronGbpIidFactory.endpointByRouterGatewayPortIid(portId),
274                     endpointByPort, true);
275             RouterGatewayPortByEndpoint portByEndpoint = MappingFactory.createRouterGatewayPortByEndpoint(portId, epKey);
276             rwTx.put(LogicalDatastoreType.OPERATIONAL,
277                     NeutronGbpIidFactory.routerGatewayPortByEndpointIid(epKey.getL2Context(), epKey.getMacAddress()),
278                     portByEndpoint, true);
279         } else if (isFloatingIpPort(port)) {
280             LOG.trace("Adding FloatingIpPort-Endpoint mapping for port {} and endpoint {}", port.getID(), epKey);
281             EndpointByFloatingIpPort endpointByPort = MappingFactory.createEndpointByFloatingIpPort(epKey, portId);
282             rwTx.put(LogicalDatastoreType.OPERATIONAL, NeutronGbpIidFactory.endpointByFloatingIpPortIid(portId),
283                     endpointByPort, true);
284             FloatingIpPortByEndpoint portByEndpoint = MappingFactory.createFloatingIpPortByEndpoint(portId, epKey);
285             rwTx.put(LogicalDatastoreType.OPERATIONAL,
286                     NeutronGbpIidFactory.floatingIpPortByEndpointIid(epKey.getL2Context(), epKey.getMacAddress()),
287                     portByEndpoint, true);
288         } else {
289             LOG.trace("Adding Port-Endpoint mapping for port {} (device owner {}) and endpoint {}", port.getID(),
290                     port.getDeviceOwner(), epKey);
291             EndpointByPort endpointByPort = MappingFactory.createEndpointByPort(epKey, portId);
292             rwTx.put(LogicalDatastoreType.OPERATIONAL, NeutronGbpIidFactory.endpointByPortIid(portId), endpointByPort, true);
293             PortByEndpoint portByEndpoint = MappingFactory.createPortByEndpoint(portId, epKey);
294             rwTx.put(LogicalDatastoreType.OPERATIONAL,
295                     NeutronGbpIidFactory.portByEndpointIid(epKey.getL2Context(), epKey.getMacAddress()), portByEndpoint, true);
296         }
297     }
298
299     public static boolean addL3PrefixEndpoint(L3ContextId l3ContextId, IpPrefix ipPrefix, IpAddress ipAddress, TenantId tenantId,
300             ReadWriteTransaction rwTx, EndpointService epService) {
301
302         EndpointL3PrefixKey epL3PrefixKey = new EndpointL3PrefixKey( ipPrefix, l3ContextId);
303
304         EndpointL3Key epL3Key = null;
305         List<EndpointL3Key> l3Gateways = new ArrayList<>();
306         if (ipAddress != null) {
307             epL3Key = new EndpointL3Key(ipAddress, l3ContextId);
308             l3Gateways.add(epL3Key);
309         }
310
311
312         try {
313             RegisterL3PrefixEndpointInput registerL3PrefixEpRpcInput = createRegisterL3PrefixEndpointInput(epL3PrefixKey, l3Gateways,tenantId);
314
315             RpcResult<Void> rpcResult = epService.registerL3PrefixEndpoint(registerL3PrefixEpRpcInput).get();
316             if (!rpcResult.isSuccessful()) {
317                 LOG.warn("Illegal state - RPC registerEndpoint failed. Input of RPC: {}", registerL3PrefixEpRpcInput);
318                 return false;
319             }
320         } catch (InterruptedException | ExecutionException e) {
321             LOG.error("addPort - RPC invocation failed.", e);
322             return false;
323         }
324         return true;
325
326     }
327
328     private static boolean validateForwardingCtx(ForwardingCtx fwCtx) {
329         if (fwCtx.getL2FloodDomain() == null) {
330             LOG.warn("Illegal state - l2-flood-domain does not exist.");
331             return false;
332         }
333         if (fwCtx.getL2BridgeDomain() == null) {
334             LOG.warn("Illegal state - l2-bridge-domain does not exist.");
335             return false;
336         }
337         if (fwCtx.getL3Context() == null) {
338             LOG.warn("Illegal state - l3-context does not exist.");
339             return false;
340         }
341         return true;
342     }
343
344     private List<NeutronSecurityRule> createDhcpSecRules(NeutronPort port, EndpointGroupId consumerEpgId, ReadTransaction rTx) {
345         TenantId tenantId = new TenantId(Utils.normalizeUuid(port.getTenantID()));
346         Neutron_IPs firstIp = MappingUtils.getFirstIp(port.getFixedIPs());
347         if (firstIp == null) {
348             LOG.warn("Illegal state - DHCP port does not have an IP address.");
349             return null;
350         }
351         SubnetId dhcpSubnetId = new SubnetId(firstIp.getSubnetUUID());
352         Optional<Subnet> potentialSubnet = DataStoreHelper.readFromDs(LogicalDatastoreType.CONFIGURATION,
353                 IidFactory.subnetIid(tenantId, dhcpSubnetId), rTx);
354         if (!potentialSubnet.isPresent()) {
355             LOG.warn("Illegal state - Subnet {} where is DHCP port does not exist.", dhcpSubnetId.getValue());
356             return null;
357         }
358         IpPrefix ipSubnet = potentialSubnet.get().getIpPrefix();
359         List<NeutronSecurityRule> rules = new ArrayList<>();
360         rules.add(createDhcpIngressSecRule(port.getID(), tenantId, ipSubnet, consumerEpgId));
361         rules.add(createDnsSecRule(port.getID(), tenantId, ipSubnet, consumerEpgId));
362         rules.add(createUdpEgressSecRule(port.getID(), tenantId, ipSubnet, consumerEpgId));
363         rules.add(createIcmpSecRule(port.getID(), tenantId, ipSubnet, consumerEpgId, true));
364         rules.add(createIcmpSecRule(port.getID(), tenantId, ipSubnet, consumerEpgId, false));
365         return rules;
366     }
367
368     private NeutronSecurityRule createDhcpIngressSecRule(String ruleUuid, TenantId tenantId, IpPrefix ipSubnet, EndpointGroupId consumerEpgId) {
369         NeutronSecurityRule dhcpSecRule = new NeutronSecurityRule();
370         dhcpSecRule.setSecurityRuleGroupID(MappingUtils.EPG_DHCP_ID.getValue());
371         dhcpSecRule.setSecurityRuleTenantID(tenantId.getValue());
372         if (consumerEpgId != null) {
373             dhcpSecRule.setSecurityRemoteGroupID(consumerEpgId.getValue());
374         }
375         dhcpSecRule.setSecurityRuleUUID(NeutronUtils.INGRESS + "_dhcp__" + ruleUuid);
376         dhcpSecRule.setSecurityRuleDirection(NeutronUtils.INGRESS);
377         dhcpSecRule.setSecurityRulePortMin(DHCP_SERVER_PORT);
378         dhcpSecRule.setSecurityRulePortMax(DHCP_SERVER_PORT);
379         dhcpSecRule.setSecurityRuleProtocol(NeutronUtils.UDP);
380         if (ipSubnet.getIpv4Prefix() != null) {
381             dhcpSecRule.setSecurityRuleEthertype(NeutronUtils.IPv4);
382         } else {
383             dhcpSecRule.setSecurityRuleEthertype(NeutronUtils.IPv6);
384         }
385         return dhcpSecRule;
386     }
387
388     private NeutronSecurityRule createUdpEgressSecRule(String ruleUuid, TenantId tenantId, IpPrefix ipSubnet, EndpointGroupId consumerEpgId) {
389         NeutronSecurityRule dhcpSecRule = new NeutronSecurityRule();
390         dhcpSecRule.setSecurityRuleGroupID(MappingUtils.EPG_DHCP_ID.getValue());
391         dhcpSecRule.setSecurityRuleTenantID(tenantId.getValue());
392         if (consumerEpgId != null) {
393             dhcpSecRule.setSecurityRemoteGroupID(consumerEpgId.getValue());
394         }
395         dhcpSecRule.setSecurityRuleUUID(NeutronUtils.EGRESS + "_udp__" + ruleUuid);
396         dhcpSecRule.setSecurityRuleDirection(NeutronUtils.EGRESS);
397         dhcpSecRule.setSecurityRuleProtocol(NeutronUtils.UDP);
398         if (ipSubnet.getIpv4Prefix() != null) {
399             dhcpSecRule.setSecurityRuleEthertype(NeutronUtils.IPv4);
400         } else {
401             dhcpSecRule.setSecurityRuleEthertype(NeutronUtils.IPv6);
402         }
403         return dhcpSecRule;
404     }
405
406     private NeutronSecurityRule createDnsSecRule(String ruleUuid, TenantId tenantId, IpPrefix ipSubnet, EndpointGroupId consumerEpgId) {
407         NeutronSecurityRule dnsSecRule = new NeutronSecurityRule();
408         dnsSecRule.setSecurityRuleGroupID(MappingUtils.EPG_DHCP_ID.getValue());
409         dnsSecRule.setSecurityRuleTenantID(tenantId.getValue());
410         if (consumerEpgId != null) {
411             dnsSecRule.setSecurityRemoteGroupID(consumerEpgId.getValue());
412         }
413         dnsSecRule.setSecurityRuleUUID(NeutronUtils.INGRESS + "_dns__" + ruleUuid);
414         dnsSecRule.setSecurityRuleDirection(NeutronUtils.INGRESS);
415         dnsSecRule.setSecurityRulePortMin(DNS_SERVER_PORT);
416         dnsSecRule.setSecurityRulePortMax(DNS_SERVER_PORT);
417         dnsSecRule.setSecurityRuleProtocol(NeutronUtils.UDP);
418         if (ipSubnet.getIpv4Prefix() != null) {
419             dnsSecRule.setSecurityRuleEthertype(NeutronUtils.IPv4);
420         } else {
421             dnsSecRule.setSecurityRuleEthertype(NeutronUtils.IPv6);
422         }
423         return dnsSecRule;
424     }
425
426     private NeutronSecurityRule createIcmpSecRule(String ruleUuid, TenantId tenantId, IpPrefix ipSubnet, EndpointGroupId consumerEpgId,
427             boolean isEgress) {
428         NeutronSecurityRule icmpSecRule = new NeutronSecurityRule();
429         icmpSecRule.setSecurityRuleGroupID(MappingUtils.EPG_DHCP_ID.getValue());
430         icmpSecRule.setSecurityRuleTenantID(tenantId.getValue());
431         icmpSecRule.setSecurityRuleRemoteIpPrefix(Utils.getStringIpPrefix(ipSubnet));
432         if (consumerEpgId != null) {
433             icmpSecRule.setSecurityRemoteGroupID(consumerEpgId.getValue());
434         }
435         if (isEgress) {
436             icmpSecRule.setSecurityRuleUUID(NeutronUtils.EGRESS + "_icmp__" + ruleUuid);
437             icmpSecRule.setSecurityRuleDirection(NeutronUtils.EGRESS);
438         } else {
439             icmpSecRule.setSecurityRuleUUID(NeutronUtils.INGRESS + "_icmp__" + ruleUuid);
440             icmpSecRule.setSecurityRuleDirection(NeutronUtils.INGRESS);
441         }
442         icmpSecRule.setSecurityRuleProtocol(NeutronUtils.ICMP);
443         if (ipSubnet.getIpv4Prefix() != null) {
444             icmpSecRule.setSecurityRuleEthertype(NeutronUtils.IPv4);
445         } else {
446             icmpSecRule.setSecurityRuleEthertype(NeutronUtils.IPv6);
447         }
448         return icmpSecRule;
449     }
450
451     /**
452      * @see org.opendaylight.neutron.spi.INeutronPortAware#canUpdatePort(org.opendaylight.neutron.spi.NeutronPort,
453      *      org.opendaylight.neutron.spi.NeutronPort)
454      */
455     @Override
456     public int canUpdatePort(NeutronPort delta, NeutronPort original) {
457         LOG.trace("canUpdatePort - delta: {} original: {}", delta, original);
458         if (delta.getFixedIPs() == null || delta.getFixedIPs().isEmpty()) {
459             return StatusCode.OK;
460         }
461         // TODO Li msunal this has to be rewrite when OFOverlay renderer will support l3-endpoints.
462         List<Neutron_IPs> fixedIPs = delta.getFixedIPs();
463         if (fixedIPs != null && fixedIPs.size() > 1) {
464             LOG.warn("Neutron mapper does not support multiple IPs on the same port.");
465             return StatusCode.BAD_REQUEST;
466         }
467         return StatusCode.OK;
468     }
469
470     /**
471      * @see org.opendaylight.neutron.spi.INeutronPortAware#neutronPortUpdated(org.opendaylight.neutron.spi.NeutronPort)
472      */
473     @Override
474     public void neutronPortUpdated(NeutronPort port) {
475         LOG.trace("neutronPortUpdated - {}", port);
476         if (isRouterInterfacePort(port)) {
477             LOG.trace("Port is router interface - {} does nothing. {} handles router iface.",
478                     NeutronPortAware.class.getSimpleName(), NeutronRouterAware.class.getSimpleName());
479             return;
480         }
481         if (isRouterGatewayPort(port)) {
482             LOG.trace("Port is router gateway - {}", port.getID());
483             return;
484         }
485         if (isFloatingIpPort(port)) {
486             LOG.trace("Port is floating ip - {}", port.getID());
487             return;
488         }
489         if (Strings.isNullOrEmpty(port.getTenantID())) {
490             LOG.trace("REMOVE ME: Tenant is null - {}", port.getID());
491             return;
492         }
493
494         ReadOnlyTransaction rTx = dataProvider.newReadOnlyTransaction();
495         TenantId tenantId = new TenantId(Utils.normalizeUuid(port.getTenantID()));
496         MacAddress macAddress = new MacAddress(port.getMacAddress());
497         L2FloodDomainId l2FdId = new L2FloodDomainId(port.getNetworkUUID());
498         ForwardingCtx fwCtx = MappingUtils.createForwardingContext(tenantId, l2FdId, rTx);
499         boolean isFwCtxValid = validateForwardingCtx(fwCtx);
500         if (!isFwCtxValid) {
501             rTx.close();
502             return;
503         }
504
505         Optional<Endpoint> potentionalEp = DataStoreHelper.readFromDs(LogicalDatastoreType.OPERATIONAL,
506                 IidFactory.endpointIid(fwCtx.getL2BridgeDomain().getId(), macAddress), rTx);
507         if (!potentionalEp.isPresent()) {
508             LOG.warn("Illegal state - endpoint {} does not exist.", new EndpointKey(fwCtx.getL2BridgeDomain().getId(),
509                     macAddress));
510             rTx.close();
511             return;
512         }
513
514         Endpoint ep = potentionalEp.get();
515         if (isEpIpDifferentThanPortFixedIp(ep, port) || isEpgDifferentThanSecGrp(ep, port)) {
516             UnregisterEndpointInput unregisterEpRpcInput = createUnregisterEndpointInput(ep);
517             RegisterEndpointInput registerEpRpcInput = createRegisterEndpointInput(port, fwCtx);
518             try {
519                 RpcResult<Void> rpcResult = epService.unregisterEndpoint(unregisterEpRpcInput).get();
520                 if (!rpcResult.isSuccessful()) {
521                     LOG.warn("Illegal state - RPC unregisterEndpoint failed. Input of RPC: {}", unregisterEpRpcInput);
522                     rTx.close();
523                     return;
524                 }
525                 rpcResult = epService.registerEndpoint(registerEpRpcInput).get();
526                 if (!rpcResult.isSuccessful()) {
527                     LOG.warn("Illegal state - RPC registerEndpoint failed. Input of RPC: {}", registerEpRpcInput);
528                     rTx.close();
529                     return;
530                 }
531             } catch (InterruptedException | ExecutionException e) {
532                 LOG.error("addPort - RPC invocation failed.", e);
533                 rTx.close();
534                 return;
535             }
536         }
537         rTx.close();
538     }
539
540     private boolean isEpIpDifferentThanPortFixedIp(Endpoint ep, NeutronPort port) {
541         List<L3Address> l3Addresses = ep.getL3Address();
542         List<Neutron_IPs> fixedIPs = port.getFixedIPs();
543         if ((l3Addresses == null || l3Addresses.isEmpty()) && (fixedIPs == null || fixedIPs.isEmpty())) {
544             return false;
545         }
546         if (l3Addresses != null && !l3Addresses.isEmpty() && fixedIPs != null && !fixedIPs.isEmpty()) {
547             if (fixedIPs.get(0).getIpAddress().equals(Utils.getStringIpAddress(l3Addresses.get(0).getIpAddress()))) {
548                 return false;
549             }
550         }
551         return true;
552     }
553
554     private boolean isEpgDifferentThanSecGrp(Endpoint ep, NeutronPort port) {
555         List<EndpointGroupId> epgIds = ep.getEndpointGroups();
556         List<NeutronSecurityGroup> secGroups = port.getSecurityGroups();
557         if ((epgIds == null || epgIds.isEmpty()) && (secGroups == null || secGroups.isEmpty())) {
558             return false;
559         }
560         if (epgIds != null && !epgIds.isEmpty() && secGroups != null && !secGroups.isEmpty()) {
561             if (epgIds.size() != secGroups.size()) {
562                 return true;
563             }
564             Collection<EndpointGroupId> epgIdsFromSecGroups = Collections2.transform(secGroups,
565                     new Function<NeutronSecurityGroup, EndpointGroupId>() {
566
567                         @Override
568                         public EndpointGroupId apply(NeutronSecurityGroup input) {
569                             return new EndpointGroupId(input.getSecurityGroupUUID());
570                         }
571                     });
572             // order independent equals
573             Set<EndpointGroupId> one = new HashSet<>(epgIds);
574             Set<EndpointGroupId> two = new HashSet<>(epgIdsFromSecGroups);
575             if (one.equals(two)) {
576                 return false;
577             }
578         }
579         return true;
580     }
581
582     /**
583      * @see org.opendaylight.neutron.spi.INeutronPortAware#canDeletePort(org.opendaylight.neutron.spi.NeutronPort)
584      */
585     @Override
586     public int canDeletePort(NeutronPort port) {
587         LOG.trace("canDeletePort - {}", port);
588         // nothing to consider
589         return StatusCode.OK;
590     }
591
592     /**
593      * @see org.opendaylight.neutron.spi.INeutronPortAware#neutronPortDeleted(org.opendaylight.neutron.spi.NeutronPort)
594      */
595     @Override
596     public void neutronPortDeleted(NeutronPort port) {
597         LOG.trace("neutronPortDeleted - {}", port);
598         if (isRouterInterfacePort(port)) {
599             LOG.trace("Port is router interface - {} does nothing. {} handles router iface.",
600                     NeutronPortAware.class.getSimpleName(), NeutronRouterAware.class.getSimpleName());
601             return;
602         }
603         if (isRouterGatewayPort(port)) {
604             LOG.trace("Port is router gateway - {} does nothing. {} handles router iface.",
605                     NeutronPortAware.class.getSimpleName(), NeutronRouterAware.class.getSimpleName());
606             return;
607         }
608         if (isFloatingIpPort(port)) {
609             LOG.trace("Port is floating ip - {} device id - {}", port.getID(), port.getDeviceID());
610             floatingIpPortByDeviceId.remove(port.getDeviceID());
611         }
612         ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction();
613         TenantId tenantId = new TenantId(Utils.normalizeUuid(port.getTenantID()));
614         L2FloodDomainId l2FdId = new L2FloodDomainId(port.getNetworkUUID());
615         ForwardingCtx fwCtx = MappingUtils.createForwardingContext(tenantId, l2FdId, rwTx);
616         boolean isFwCtxValid = validateForwardingCtx(fwCtx);
617         if (!isFwCtxValid) {
618             rwTx.cancel();
619             return;
620         }
621
622         EndpointKey epKey = new EndpointKey(fwCtx.getL2BridgeDomain().getId(), new MacAddress(port.getMacAddress()));
623         deleteNeutronGbpMapping(port, epKey, rwTx);
624         UnregisterEndpointInput unregisterEpRpcInput = createUnregisterEndpointInput(port, fwCtx);
625         try {
626             RpcResult<Void> rpcResult = epService.unregisterEndpoint(unregisterEpRpcInput).get();
627             if (!rpcResult.isSuccessful()) {
628                 LOG.warn("Illegal state - RPC unregisterEndpoint failed. Input of RPC: {}", unregisterEpRpcInput);
629             }
630         } catch (InterruptedException | ExecutionException e) {
631             LOG.error("addPort - RPC invocation failed.", e);
632             rwTx.cancel();
633         }
634     }
635
636     private static void deleteNeutronGbpMapping(NeutronPort port, EndpointKey epKey, ReadWriteTransaction rwTx) {
637         UniqueId portId = new UniqueId(port.getID());
638         if (isRouterInterfacePort(port)) {
639             LOG.trace("Adding RouterInterfacePort-Endpoint mapping for port {} and endpoint {}", port.getID(), epKey);
640             DataStoreHelper.removeIfExists(LogicalDatastoreType.OPERATIONAL,
641                     NeutronGbpIidFactory.endpointByRouterInterfacePortIid(portId), rwTx);
642             DataStoreHelper.removeIfExists(LogicalDatastoreType.OPERATIONAL,
643                     NeutronGbpIidFactory.routerInterfacePortByEndpointIid(epKey.getL2Context(), epKey.getMacAddress()), rwTx);
644         } else if (isRouterGatewayPort(port)) {
645             LOG.trace("Adding RouterGatewayPort-Endpoint mapping for port {} and endpoint {}", port.getID(), epKey);
646             DataStoreHelper.removeIfExists(LogicalDatastoreType.OPERATIONAL,
647                     NeutronGbpIidFactory.endpointByRouterGatewayPortIid(portId), rwTx);
648             DataStoreHelper.removeIfExists(LogicalDatastoreType.OPERATIONAL,
649                     NeutronGbpIidFactory.routerGatewayPortByEndpointIid(epKey.getL2Context(), epKey.getMacAddress()), rwTx);
650         } else if (isFloatingIpPort(port)) {
651             LOG.trace("Adding FloatingIpPort-Endpoint mapping for port {} and endpoint {}", port.getID(), epKey);
652             DataStoreHelper.removeIfExists(LogicalDatastoreType.OPERATIONAL,
653                     NeutronGbpIidFactory.endpointByFloatingIpPortIid(portId), rwTx);
654             DataStoreHelper.removeIfExists(LogicalDatastoreType.OPERATIONAL,
655                     NeutronGbpIidFactory.floatingIpPortByEndpointIid(epKey.getL2Context(), epKey.getMacAddress()), rwTx);
656         } else {
657             LOG.trace("Adding Port-Endpoint mapping for port {} (device owner {}) and endpoint {}", port.getID(),
658                     port.getDeviceOwner(), epKey);
659             DataStoreHelper.removeIfExists(LogicalDatastoreType.OPERATIONAL, NeutronGbpIidFactory.endpointByPortIid(portId), rwTx);
660             DataStoreHelper.removeIfExists(LogicalDatastoreType.OPERATIONAL,
661                     NeutronGbpIidFactory.portByEndpointIid(epKey.getL2Context(), epKey.getMacAddress()), rwTx);
662         }
663     }
664
665     private static RegisterL3PrefixEndpointInput createRegisterL3PrefixEndpointInput(EndpointL3PrefixKey key, List<EndpointL3Key> endpointL3Keys, TenantId tenantId) {
666         List<EndpointGroupId> epgIds = new ArrayList<>();
667         // each EP has to be in EPG ANY, except dhcp and router
668         epgIds.add(MappingUtils.EPG_ANY_ID);
669
670         List<EndpointL3Gateways> l3Gateways = new ArrayList<EndpointL3Gateways>();
671         for (EndpointL3Key epL3Key : endpointL3Keys) {
672             EndpointL3Gateways l3Gateway = new EndpointL3GatewaysBuilder().setIpAddress(epL3Key.getIpAddress())
673                 .setL3Context(epL3Key.getL3Context())
674                 .build();
675             l3Gateways.add(l3Gateway);
676         }
677         RegisterL3PrefixEndpointInputBuilder inputBuilder = new RegisterL3PrefixEndpointInputBuilder()
678                                                 .setL3Context(key.getL3Context())
679                                                 .setIpPrefix(key.getIpPrefix())
680                                                 .setEndpointGroups(epgIds)
681                                                 .setTenant(tenantId)
682                                                 .setEndpointL3Gateways(l3Gateways)
683                                                 .setTimestamp(System.currentTimeMillis());
684         return inputBuilder.build();
685     }
686
687     private static EndpointL3 createL3Endpoint(TenantId tenantId, EndpointL3Key epL3Key,
688             List<EndpointGroupId> epgIds, NetworkDomainId containment) {
689
690         EndpointL3Builder epL3Builder = new EndpointL3Builder()
691         .setTenant(tenantId)
692         .setNetworkContainment(containment)
693         .setIpAddress(epL3Key.getIpAddress())
694         .setL3Context(epL3Key.getL3Context())
695         .setEndpointGroups(epgIds)
696         .setTimestamp(System.currentTimeMillis());
697
698         return epL3Builder.build();
699     }
700
701     private static RegisterEndpointInput createRegisterEndpointInput(NeutronPort port, ForwardingCtx fwCtx) {
702         List<EndpointGroupId> epgIds = new ArrayList<>();
703         // each EP has to be in EPG ANY, except dhcp and router
704         if (isDhcpPort(port)) {
705             epgIds.add(MappingUtils.EPG_DHCP_ID);
706         } else if (!containsSecRuleWithRemoteSecGroup(port.getSecurityGroups())) {
707             epgIds.add(MappingUtils.EPG_ANY_ID);
708         }
709
710         List<NeutronSecurityGroup> securityGroups = port.getSecurityGroups();
711         if ((securityGroups == null || securityGroups.isEmpty())) {
712             if (isFloatingIpPort(port)) {
713                 epgIds.add(MappingUtils.EPG_EXTERNAL_ID);
714             } else if (!isDhcpPort(port)) {
715                 LOG.warn(
716                         "Port {} does not contain any security group. The port should belong to 'default' security group at least.",
717                         port.getPortUUID());
718             }
719         } else {
720             for (NeutronSecurityGroup secGrp : securityGroups) {
721                 epgIds.add(new EndpointGroupId(secGrp.getSecurityGroupUUID()));
722             }
723         }
724         LocationType locationType = LocationType.Internal;
725         if(isRouterGatewayPort(port)) {
726             locationType = LocationType.External;
727         }
728         RegisterEndpointInputBuilder inputBuilder = new RegisterEndpointInputBuilder().setL2Context(
729                 fwCtx.getL2BridgeDomain().getId())
730             .setMacAddress(new MacAddress(port.getMacAddress()))
731             .setTenant(new TenantId(Utils.normalizeUuid(port.getTenantID())))
732             .setEndpointGroups(epgIds)
733             .addAugmentation(OfOverlayContextInput.class,
734                     new OfOverlayContextInputBuilder()
735                         .setPortName(createTapPortName(port))
736                         .setLocationType(locationType)
737                     .build())
738             .setTimestamp(System.currentTimeMillis());
739         List<Neutron_IPs> fixedIPs = port.getFixedIPs();
740         // TODO Li msunal this getting of just first IP has to be rewrite when OFOverlay renderer
741         // will support l3-endpoints. Then we will register L2 and L3 endpoints separately.
742         Neutron_IPs firstIp = MappingUtils.getFirstIp(fixedIPs);
743         if (firstIp != null) {
744             inputBuilder.setNetworkContainment(new SubnetId(firstIp.getSubnetUUID()));
745             L3Address l3Address = new L3AddressBuilder().setIpAddress(Utils.createIpAddress(firstIp.getIpAddress()))
746                 .setL3Context(fwCtx.getL3Context().getId())
747                 .build();
748             inputBuilder.setL3Address(ImmutableList.of(l3Address));
749         }
750         if (!Strings.isNullOrEmpty(port.getName())) {
751
752         }
753         return inputBuilder.build();
754     }
755
756     private static boolean containsSecRuleWithRemoteSecGroup(List<NeutronSecurityGroup> secGroups) {
757         if (secGroups == null) {
758             return false;
759         }
760         for (NeutronSecurityGroup secGroup : secGroups) {
761             boolean containsSecRuleWithRemoteSecGroup = containsSecRuleWithRemoteSecGroup(secGroup);
762             if (containsSecRuleWithRemoteSecGroup) {
763                 return true;
764             }
765         }
766         return false;
767     }
768
769     private static boolean containsSecRuleWithRemoteSecGroup(NeutronSecurityGroup secGroup) {
770         List<NeutronSecurityRule> secRules = secGroup.getSecurityRules();
771         if (secRules == null) {
772             return false;
773         }
774         for (NeutronSecurityRule secRule : secRules) {
775             if (!Strings.isNullOrEmpty(secRule.getSecurityRemoteGroupID())) {
776                 return true;
777             }
778         }
779         return false;
780     }
781
782     private static Name createTapPortName(NeutronPort port) {
783         return new Name("tap" + port.getID().substring(0, 11));
784     }
785
786     private static boolean isDhcpPort(NeutronPort port) {
787         return DEVICE_OWNER_DHCP.equals(port.getDeviceOwner());
788     }
789
790     private static boolean isRouterInterfacePort(NeutronPort port) {
791         return DEVICE_OWNER_ROUTER_IFACE.equals(port.getDeviceOwner());
792     }
793
794     private static boolean isRouterGatewayPort(NeutronPort port) {
795         return DEVICE_OWNER_ROUTER_GATEWAY.equals(port.getDeviceOwner());
796     }
797
798     private static boolean isFloatingIpPort(NeutronPort port) {
799         return DEVICE_OWNER_FLOATING_IP.equals(port.getDeviceOwner());
800     }
801
802     private UnregisterEndpointInput createUnregisterEndpointInput(Endpoint ep) {
803         UnregisterEndpointInputBuilder inputBuilder = new UnregisterEndpointInputBuilder();
804         L2 l2Ep = new L2Builder().setL2Context(ep.getL2Context()).setMacAddress(ep.getMacAddress()).build();
805         inputBuilder.setL2(ImmutableList.of(l2Ep));
806         // TODO Li msunal this has to be rewrite when OFOverlay renderer will support l3-endpoints.
807         // Endpoint probably will not have l3-addresses anymore, because L2 and L3 endpoints should
808         // be registered separately.
809         if (ep.getL3Address() != null && !ep.getL3Address().isEmpty()) {
810             List<L3> l3Eps = new ArrayList<>();
811             for (L3Address ip : ep.getL3Address()) {
812                 l3Eps.add(new L3Builder().setL3Context(ip.getL3Context()).setIpAddress(ip.getIpAddress()).build());
813             }
814             inputBuilder.setL3(l3Eps);
815         }
816         return inputBuilder.build();
817     }
818
819     private UnregisterEndpointInput createUnregisterEndpointInput(NeutronPort port, ForwardingCtx fwCtx) {
820         UnregisterEndpointInputBuilder inputBuilder = new UnregisterEndpointInputBuilder();
821         L2 l2Ep = new L2Builder().setL2Context(fwCtx.getL2BridgeDomain().getId())
822             .setMacAddress(new MacAddress(port.getMacAddress()))
823             .build();
824         inputBuilder.setL2(ImmutableList.of(l2Ep));
825         // TODO Li msunal this has to be rewrite when OFOverlay renderer will support l3-endpoints.
826         // Endpoint probably will not have l3-addresses anymore, because L2 and L3 endpoints should
827         // be registered separately.
828         if (port.getFixedIPs() != null && !port.getFixedIPs().isEmpty()) {
829             inputBuilder.setL3(createL3s(port.getFixedIPs(), fwCtx.getL3Context().getId()));
830         }
831         return inputBuilder.build();
832     }
833
834     private List<L3> createL3s(List<Neutron_IPs> neutronIps, L3ContextId l3ContextId) {
835         List<L3> l3s = new ArrayList<>();
836         for (Neutron_IPs fixedIp : neutronIps) {
837             String ip = fixedIp.getIpAddress();
838             L3 l3 = new L3Builder().setIpAddress(Utils.createIpAddress(ip)).setL3Context(l3ContextId).build();
839             l3s.add(l3);
840         }
841         return l3s;
842     }
843
844     public static UniqueId getFloatingIpPortIdByDeviceId(String deviceId) {
845         return floatingIpPortByDeviceId.get(deviceId);
846     }
847
848 }