Added support of multiple routers from neutron
[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.HashSet;
15 import java.util.List;
16 import java.util.Set;
17 import java.util.concurrent.ExecutionException;
18
19 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
20 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
21 import org.opendaylight.controller.md.sal.binding.api.ReadTransaction;
22 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
23 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
24 import org.opendaylight.groupbasedpolicy.neutron.mapper.util.DataStoreHelper;
25 import org.opendaylight.groupbasedpolicy.neutron.mapper.util.IidFactory;
26 import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils;
27 import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils.ForwardingCtx;
28 import org.opendaylight.groupbasedpolicy.neutron.mapper.util.NeutronUtils;
29 import org.opendaylight.groupbasedpolicy.neutron.mapper.util.Utils;
30 import org.opendaylight.neutron.spi.INeutronPortAware;
31 import org.opendaylight.neutron.spi.NeutronPort;
32 import org.opendaylight.neutron.spi.NeutronRouter;
33 import org.opendaylight.neutron.spi.NeutronRouter_Interface;
34 import org.opendaylight.neutron.spi.NeutronSecurityGroup;
35 import org.opendaylight.neutron.spi.NeutronSecurityRule;
36 import org.opendaylight.neutron.spi.Neutron_IPs;
37 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2FloodDomainId;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L3ContextId;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.Name;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubnetId;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.EndpointService;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterEndpointInput;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterEndpointInputBuilder;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.UnregisterEndpointInput;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.UnregisterEndpointInputBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoint.fields.L3Address;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoint.fields.L3AddressBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.Endpoint;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointKey;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.unregister.endpoint.input.L2;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.unregister.endpoint.input.L2Builder;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.unregister.endpoint.input.L3;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.unregister.endpoint.input.L3Builder;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.ofoverlay.rev140528.OfOverlayContextInput;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.ofoverlay.rev140528.OfOverlayContextInputBuilder;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.EndpointGroup;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.Subnet;
62 import org.opendaylight.yangtools.yang.common.RpcResult;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
65
66 import com.google.common.base.Function;
67 import com.google.common.base.Optional;
68 import com.google.common.base.Strings;
69 import com.google.common.collect.Collections2;
70 import com.google.common.collect.ImmutableList;
71
72 public class NeutronPortAware implements INeutronPortAware {
73
74     public static final Logger LOG = LoggerFactory.getLogger(NeutronPortAware.class);
75     private static final String DEVICE_OWNER_DHCP = "network:dhcp";
76     private static final String DEVICE_OWNER_ROUTER_IFACE = "network:router_interface";
77     private static final int DHCP_CLIENT_PORT = 68;
78     private static final int DHCP_SERVER_PORT = 67;
79     private final DataBroker dataProvider;
80     private final EndpointService epService;
81
82     public NeutronPortAware(DataBroker dataProvider, EndpointService epService) {
83         this.dataProvider = checkNotNull(dataProvider);
84         this.epService = checkNotNull(epService);
85     }
86
87     /**
88      * @see org.opendaylight.neutron.spi.INeutronPortAware#canCreatePort(org.opendaylight.neutron.spi.NeutronPort)
89      */
90     @Override
91     public int canCreatePort(NeutronPort port) {
92         LOG.trace("canCreatePort - {}", port);
93         // TODO Li msunal this has to be rewrite when OFOverlay renderer will support l3-endpoints.
94         List<Neutron_IPs> fixedIPs = port.getFixedIPs();
95         if (fixedIPs != null && fixedIPs.size() > 1) {
96             LOG.warn("Neutron mapper does not support multiple IPs on the same port.");
97             return StatusCode.BAD_REQUEST;
98         }
99         return StatusCode.OK;
100     }
101
102     /**
103      * @see org.opendaylight.neutron.spi.INeutronPortAware#neutronPortCreated(org.opendaylight.neutron.spi.NeutronPort)
104      */
105     @Override
106     public void neutronPortCreated(NeutronPort port) {
107         LOG.trace("neutronPortCreated - {}", port);
108         if (isRouterInterfacePort(port)) {
109             LOG.trace("Port is router interface.");
110             NeutronRouter neutronRouter = createRouter(port);
111             NeutronRouter_Interface routerIface = createRouterInterface(port);
112             int canAttachInterface = NeutronRouterAware.getInstance().canAttachInterface(neutronRouter, routerIface);
113             if (canAttachInterface == StatusCode.OK) {
114                 NeutronRouterAware.getInstance().neutronRouterInterfaceAttached(neutronRouter, routerIface);
115             }
116             return;
117         }
118
119         ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction();
120         TenantId tenantId = new TenantId(Utils.normalizeUuid(port.getTenantID()));
121
122         if (isDhcpPort(port)) {
123             LOG.trace("Port is DHCP port.");
124             List<NeutronSecurityRule> dhcpSecRules = createDhcpSecRules(port, null, rwTx);
125             if (dhcpSecRules == null) {
126                 rwTx.cancel();
127                 return;
128             }
129
130             for (NeutronSecurityRule dhcpSecRule : dhcpSecRules) {
131                 boolean isDhcpSecRuleAdded = NeutronSecurityRuleAware.addNeutronSecurityRule(dhcpSecRule, rwTx);
132                 if (!isDhcpSecRuleAdded) {
133                     rwTx.cancel();
134                     return;
135                 }
136             }
137         } else {
138             List<NeutronSecurityGroup> secGroups = port.getSecurityGroups();
139             if (secGroups != null) {
140                 for (NeutronSecurityGroup secGroup : secGroups) {
141                     EndpointGroupId epgId = new EndpointGroupId(secGroup.getSecurityGroupUUID());
142                     Optional<EndpointGroup> potentialEpg = DataStoreHelper.readFromDs(LogicalDatastoreType.CONFIGURATION,
143                             IidFactory.endpointGroupIid(tenantId, epgId), rwTx);
144                     if (!potentialEpg.isPresent()) {
145                         boolean isSecGroupCreated = NeutronSecurityGroupAware.addNeutronSecurityGroup(secGroup, rwTx);
146                         if (!isSecGroupCreated) {
147                             rwTx.cancel();
148                             return;
149                         }
150                         if (containsSecRuleWithRemoteSecGroup(secGroup)) {
151                             List<NeutronSecurityRule> dhcpSecRules = createDhcpSecRules(port, epgId, rwTx);
152                             if (dhcpSecRules == null) {
153                                 rwTx.cancel();
154                                 return;
155                             }
156                             List<NeutronSecurityRule> routerSecRules = NeutronRouterAware.createRouterSecRules(port, epgId, rwTx);
157                             if (routerSecRules == null) {
158                                 rwTx.cancel();
159                                 return;
160                             }
161                         }
162                     } else {
163                         List<NeutronSecurityRule> secRules = secGroup.getSecurityRules();
164                         if (secRules != null) {
165                             for (NeutronSecurityRule secRule : secRules) {
166                                 NeutronSecurityRuleAware.addNeutronSecurityRule(secRule, rwTx);
167                             }
168                         }
169                     }
170                 }
171             }
172         }
173
174         boolean isNeutronPortCreated = addNeutronPort(port, rwTx, epService);
175         if (!isNeutronPortCreated) {
176             rwTx.cancel();
177             return;
178         }
179
180         DataStoreHelper.submitToDs(rwTx);
181     }
182
183     private static NeutronRouter createRouter(NeutronPort port) {
184         NeutronRouter neutronRouter = new NeutronRouter();
185         neutronRouter.setRouterUUID(port.getDeviceID());
186         neutronRouter.setTenantID(port.getTenantID());
187         neutronRouter.setName("Router_port__" + Strings.nullToEmpty(port.getName()));
188         return neutronRouter;
189     }
190
191     private static NeutronRouter_Interface createRouterInterface(NeutronPort port) {
192         Neutron_IPs firstIp = MappingUtils.getFirstIp(port.getFixedIPs());
193         if (firstIp == null) {
194             throw new IllegalStateException("Illegal state - Port " + port.getID() + " representing router interface does not have an IP.");
195         }
196         NeutronRouter_Interface routerIface = new NeutronRouter_Interface(firstIp.getSubnetUUID(), port.getID());
197         routerIface.setTenantID(port.getTenantID());
198         return routerIface;
199     }
200
201     public static boolean addNeutronPort(NeutronPort port, ReadWriteTransaction rwTx, EndpointService epService) {
202         TenantId tenantId = new TenantId(Utils.normalizeUuid(port.getTenantID()));
203         L2FloodDomainId l2FdId = new L2FloodDomainId(port.getNetworkUUID());
204         ForwardingCtx fwCtx = MappingUtils.createForwardingContext(tenantId, l2FdId, rwTx);
205         boolean isFwCtxValid = validateForwardingCtx(fwCtx);
206         if (!isFwCtxValid) {
207             return false;
208         }
209
210         try {
211             RegisterEndpointInput registerEpRpcInput = createRegisterEndpointInput(port, fwCtx);
212             RpcResult<Void> rpcResult = epService.registerEndpoint(registerEpRpcInput).get();
213             if (!rpcResult.isSuccessful()) {
214                 LOG.warn("Illegal state - RPC registerEndpoint failed. Input of RPC: {}", registerEpRpcInput);
215                 return false;
216             }
217         } catch (InterruptedException | ExecutionException e) {
218             LOG.error("addPort - RPC invocation failed.", e);
219             return false;
220         }
221         return true;
222     }
223
224     private static boolean validateForwardingCtx(ForwardingCtx fwCtx) {
225         if (fwCtx.getL2FloodDomain() == null) {
226             LOG.warn("Illegal state - l2-flood-domain does not exist.");
227             return false;
228         }
229         if (fwCtx.getL2BridgeDomain() == null) {
230             LOG.warn("Illegal state - l2-bridge-domain does not exist.");
231             return false;
232         }
233         if (fwCtx.getL3Context() == null) {
234             LOG.warn("Illegal state - l3-context does not exist.");
235             return false;
236         }
237         return true;
238     }
239
240     private List<NeutronSecurityRule> createDhcpSecRules(NeutronPort port, EndpointGroupId consumerEpgId, ReadTransaction rTx) {
241         TenantId tenantId = new TenantId(Utils.normalizeUuid(port.getTenantID()));
242         Neutron_IPs firstIp = MappingUtils.getFirstIp(port.getFixedIPs());
243         if (firstIp == null) {
244             LOG.warn("Illegal state - DHCP port does not have an IP address.");
245             return null;
246         }
247         SubnetId dhcpSubnetId = new SubnetId(firstIp.getSubnetUUID());
248         Optional<Subnet> potentialSubnet = DataStoreHelper.readFromDs(LogicalDatastoreType.CONFIGURATION,
249                 IidFactory.subnetIid(tenantId, dhcpSubnetId), rTx);
250         if (!potentialSubnet.isPresent()) {
251             LOG.warn("Illegal state - Subnet {} where is DHCP port does not exist.", dhcpSubnetId.getValue());
252             return null;
253         }
254         IpPrefix ipSubnet = potentialSubnet.get().getIpPrefix();
255         NeutronSecurityRule dhcpRuleEgress = createDhcpSecRule(port.getID(), tenantId, ipSubnet, consumerEpgId, true);
256         NeutronSecurityRule dhcpRuleIngress = createDhcpSecRule(port.getID(), tenantId, ipSubnet, consumerEpgId, false);
257         return ImmutableList.of(dhcpRuleEgress, dhcpRuleIngress);
258     }
259
260     private NeutronSecurityRule createDhcpSecRule(String ruleUuid, TenantId tenantId, IpPrefix ipSubnet, EndpointGroupId consumerEpgId,
261             boolean isEgress) {
262         NeutronSecurityRule dhcpSecRule = new NeutronSecurityRule();
263         dhcpSecRule.setSecurityRuleGroupID(MappingUtils.EPG_DHCP_ID.getValue());
264         dhcpSecRule.setSecurityRuleTenantID(tenantId.getValue());
265         dhcpSecRule.setSecurityRuleRemoteIpPrefix(Utils.getStringIpPrefix(ipSubnet));
266         if (consumerEpgId != null) {
267             dhcpSecRule.setSecurityRemoteGroupID(consumerEpgId.getValue());
268         }
269         if (isEgress) {
270             dhcpSecRule.setSecurityRuleUUID(NeutronUtils.EGRESS + "__" + ruleUuid);
271             dhcpSecRule.setSecurityRuleDirection(NeutronUtils.EGRESS);
272             dhcpSecRule.setSecurityRulePortMin(DHCP_CLIENT_PORT);
273             dhcpSecRule.setSecurityRulePortMax(DHCP_CLIENT_PORT);
274         } else {
275             dhcpSecRule.setSecurityRuleUUID(NeutronUtils.INGRESS + "__" + ruleUuid);
276             dhcpSecRule.setSecurityRuleDirection(NeutronUtils.INGRESS);
277             dhcpSecRule.setSecurityRulePortMin(DHCP_SERVER_PORT);
278             dhcpSecRule.setSecurityRulePortMax(DHCP_SERVER_PORT);
279         }
280         dhcpSecRule.setSecurityRuleProtocol(NeutronUtils.UDP);
281         if (ipSubnet.getIpv4Prefix() != null) {
282             dhcpSecRule.setSecurityRuleEthertype(NeutronUtils.IPv4);
283         } else {
284             dhcpSecRule.setSecurityRuleEthertype(NeutronUtils.IPv6);
285         }
286         return dhcpSecRule;
287     }
288
289     /**
290      * @see org.opendaylight.neutron.spi.INeutronPortAware#canUpdatePort(org.opendaylight.neutron.spi.NeutronPort,
291      *      org.opendaylight.neutron.spi.NeutronPort)
292      */
293     @Override
294     public int canUpdatePort(NeutronPort delta, NeutronPort original) {
295         LOG.trace("canUpdatePort - delta: {} original: {}", delta, original);
296         if (delta.getFixedIPs() == null || delta.getFixedIPs().isEmpty()) {
297             return StatusCode.OK;
298         }
299         // TODO Li msunal this has to be rewrite when OFOverlay renderer will support l3-endpoints.
300         List<Neutron_IPs> fixedIPs = delta.getFixedIPs();
301         if (fixedIPs != null && fixedIPs.size() > 1) {
302             LOG.warn("Neutron mapper does not support multiple IPs on the same port.");
303             return StatusCode.BAD_REQUEST;
304         }
305         return StatusCode.OK;
306     }
307
308     /**
309      * @see org.opendaylight.neutron.spi.INeutronPortAware#neutronPortUpdated(org.opendaylight.neutron.spi.NeutronPort)
310      */
311     @Override
312     public void neutronPortUpdated(NeutronPort port) {
313         LOG.trace("neutronPortUpdated - {}", port);
314         if (isRouterInterfacePort(port)) {
315             LOG.trace("Port is router interface - do nothing - NeutronRouterAware handles router iface");
316             return;
317         }
318         ReadOnlyTransaction rTx = dataProvider.newReadOnlyTransaction();
319         TenantId tenantId = new TenantId(Utils.normalizeUuid(port.getTenantID()));
320         MacAddress macAddress = new MacAddress(port.getMacAddress());
321         L2FloodDomainId l2FdId = new L2FloodDomainId(port.getNetworkUUID());
322         ForwardingCtx fwCtx = MappingUtils.createForwardingContext(tenantId, l2FdId, rTx);
323         boolean isFwCtxValid = validateForwardingCtx(fwCtx);
324         if (!isFwCtxValid) {
325             rTx.close();
326             return;
327         }
328
329         Optional<Endpoint> potentionalEp = DataStoreHelper.readFromDs(LogicalDatastoreType.OPERATIONAL,
330                 IidFactory.endpointIid(fwCtx.getL2BridgeDomain().getId(), macAddress), rTx);
331         if (!potentionalEp.isPresent()) {
332             LOG.warn("Illegal state - endpoint {} does not exist.", new EndpointKey(fwCtx.getL2BridgeDomain().getId(),
333                     macAddress));
334             rTx.close();
335             return;
336         }
337
338         Endpoint ep = potentionalEp.get();
339         if (isEpIpDifferentThanPortFixedIp(ep, port) || isEpgDifferentThanSecGrp(ep, port)) {
340             UnregisterEndpointInput unregisterEpRpcInput = createUnregisterEndpointInput(ep);
341             RegisterEndpointInput registerEpRpcInput = createRegisterEndpointInput(port, fwCtx);
342             try {
343                 RpcResult<Void> rpcResult = epService.unregisterEndpoint(unregisterEpRpcInput).get();
344                 if (!rpcResult.isSuccessful()) {
345                     LOG.warn("Illegal state - RPC unregisterEndpoint failed. Input of RPC: {}", unregisterEpRpcInput);
346                     rTx.close();
347                     return;
348                 }
349                 rpcResult = epService.registerEndpoint(registerEpRpcInput).get();
350                 if (!rpcResult.isSuccessful()) {
351                     LOG.warn("Illegal state - RPC registerEndpoint failed. Input of RPC: {}", registerEpRpcInput);
352                     rTx.close();
353                     return;
354                 }
355             } catch (InterruptedException | ExecutionException e) {
356                 LOG.error("addPort - RPC invocation failed.", e);
357                 rTx.close();
358                 return;
359             }
360         }
361         rTx.close();
362     }
363
364     private boolean isEpIpDifferentThanPortFixedIp(Endpoint ep, NeutronPort port) {
365         List<L3Address> l3Addresses = ep.getL3Address();
366         List<Neutron_IPs> fixedIPs = port.getFixedIPs();
367         if ((l3Addresses == null || l3Addresses.isEmpty()) && (fixedIPs == null || fixedIPs.isEmpty())) {
368             return false;
369         }
370         if (l3Addresses != null && !l3Addresses.isEmpty() && fixedIPs != null && !fixedIPs.isEmpty()) {
371             if (fixedIPs.get(0).getIpAddress().equals(Utils.getStringIpAddress(l3Addresses.get(0).getIpAddress()))) {
372                 return false;
373             }
374         }
375         return true;
376     }
377
378     private boolean isEpgDifferentThanSecGrp(Endpoint ep, NeutronPort port) {
379         List<EndpointGroupId> epgIds = ep.getEndpointGroups();
380         List<NeutronSecurityGroup> secGroups = port.getSecurityGroups();
381         if ((epgIds == null || epgIds.isEmpty()) && (secGroups == null || secGroups.isEmpty())) {
382             return false;
383         }
384         if (epgIds != null && !epgIds.isEmpty() && secGroups != null && !secGroups.isEmpty()) {
385             if (epgIds.size() != secGroups.size()) {
386                 return true;
387             }
388             Collection<EndpointGroupId> epgIdsFromSecGroups = Collections2.transform(secGroups,
389                     new Function<NeutronSecurityGroup, EndpointGroupId>() {
390
391                         @Override
392                         public EndpointGroupId apply(NeutronSecurityGroup input) {
393                             return new EndpointGroupId(input.getSecurityGroupUUID());
394                         }
395                     });
396             // order independent equals
397             Set<EndpointGroupId> one = new HashSet<>(epgIds);
398             Set<EndpointGroupId> two = new HashSet<>(epgIdsFromSecGroups);
399             if (one.equals(two)) {
400                 return false;
401             }
402         }
403         return true;
404     }
405
406     /**
407      * @see org.opendaylight.neutron.spi.INeutronPortAware#canDeletePort(org.opendaylight.neutron.spi.NeutronPort)
408      */
409     @Override
410     public int canDeletePort(NeutronPort port) {
411         LOG.trace("canDeletePort - {}", port);
412         // nothing to consider
413         return StatusCode.OK;
414     }
415
416     /**
417      * @see org.opendaylight.neutron.spi.INeutronPortAware#neutronPortDeleted(org.opendaylight.neutron.spi.NeutronPort)
418      */
419     @Override
420     public void neutronPortDeleted(NeutronPort port) {
421         LOG.trace("neutronPortDeleted - {}", port);
422         if (isRouterInterfacePort(port)) {
423             LOG.trace("Port is router interface - do nothing - NeutronRouterAware handles router iface");
424             return;
425         }
426         ReadOnlyTransaction rTx = dataProvider.newReadOnlyTransaction();
427         TenantId tenantId = new TenantId(Utils.normalizeUuid(port.getTenantID()));
428         L2FloodDomainId l2FdId = new L2FloodDomainId(port.getNetworkUUID());
429         ForwardingCtx fwCtx = MappingUtils.createForwardingContext(tenantId, l2FdId, rTx);
430         boolean isFwCtxValid = validateForwardingCtx(fwCtx);
431         if (!isFwCtxValid) {
432             rTx.close();
433             return;
434         }
435
436         UnregisterEndpointInput unregisterEpRpcInput = createUnregisterEndpointInput(port, fwCtx);
437         try {
438             RpcResult<Void> rpcResult = epService.unregisterEndpoint(unregisterEpRpcInput).get();
439             if (!rpcResult.isSuccessful()) {
440                 LOG.warn("Illegal state - RPC unregisterEndpoint failed. Input of RPC: {}", unregisterEpRpcInput);
441             }
442         } catch (InterruptedException | ExecutionException e) {
443             LOG.error("addPort - RPC invocation failed.", e);
444         } finally {
445             rTx.close();
446         }
447     }
448
449     private static RegisterEndpointInput createRegisterEndpointInput(NeutronPort port, ForwardingCtx fwCtx) {
450         List<EndpointGroupId> epgIds = new ArrayList<>();
451         // each EP has to be in EPG ANY, except dhcp and router
452         if (isDhcpPort(port)) {
453             epgIds.add(MappingUtils.EPG_DHCP_ID);
454         } else if (isRouterInterfacePort(port)) {
455             epgIds.add(MappingUtils.EPG_ROUTER_ID);
456         } else if (!containsSecRuleWithRemoteSecGroup(port.getSecurityGroups())) {
457             epgIds.add(MappingUtils.EPG_ANY_ID);
458         }
459
460         List<NeutronSecurityGroup> securityGroups = port.getSecurityGroups();
461         if ((securityGroups == null || securityGroups.isEmpty())) {
462             if (!isDhcpPort(port) && !isRouterInterfacePort(port)) {
463                 LOG.warn(
464                         "Port {} does not contain any security group. The port should belong to 'default' security group at least.",
465                         port.getPortUUID());
466             }
467         } else {
468             for (NeutronSecurityGroup secGrp : securityGroups) {
469                 epgIds.add(new EndpointGroupId(secGrp.getSecurityGroupUUID()));
470             }
471         }
472         RegisterEndpointInputBuilder inputBuilder = new RegisterEndpointInputBuilder().setL2Context(
473                 fwCtx.getL2BridgeDomain().getId())
474             .setMacAddress(new MacAddress(port.getMacAddress()))
475             .setTenant(new TenantId(Utils.normalizeUuid(port.getTenantID())))
476             .setEndpointGroups(epgIds)
477             .addAugmentation(OfOverlayContextInput.class,
478                     new OfOverlayContextInputBuilder().setPortName(createTapPortName(port)).build())
479             .setTimestamp(System.currentTimeMillis());
480         List<Neutron_IPs> fixedIPs = port.getFixedIPs();
481         // TODO Li msunal this getting of just first IP has to be rewrite when OFOverlay renderer
482         // will support l3-endpoints. Then we will register L2 and L3 endpoints separately.
483         Neutron_IPs firstIp = MappingUtils.getFirstIp(fixedIPs);
484         if (firstIp != null) {
485             inputBuilder.setNetworkContainment(new SubnetId(firstIp.getSubnetUUID()));
486             L3Address l3Address = new L3AddressBuilder().setIpAddress(Utils.createIpAddress(firstIp.getIpAddress()))
487                 .setL3Context(fwCtx.getL3Context().getId())
488                 .build();
489             inputBuilder.setL3Address(ImmutableList.of(l3Address));
490         }
491         if (!Strings.isNullOrEmpty(port.getName())) {
492
493         }
494         return inputBuilder.build();
495     }
496
497     private static boolean containsSecRuleWithRemoteSecGroup(List<NeutronSecurityGroup> secGroups) {
498         if (secGroups == null) {
499             return false;
500         }
501         for (NeutronSecurityGroup secGroup : secGroups) {
502             boolean containsSecRuleWithRemoteSecGroup = containsSecRuleWithRemoteSecGroup(secGroup);
503             if (containsSecRuleWithRemoteSecGroup) {
504                 return true;
505             }
506         }
507         return false;
508     }
509
510     private static boolean containsSecRuleWithRemoteSecGroup(NeutronSecurityGroup secGroup) {
511         List<NeutronSecurityRule> secRules = secGroup.getSecurityRules();
512         if (secRules == null) {
513             return false;
514         }
515         for (NeutronSecurityRule secRule : secRules) {
516             if (!Strings.isNullOrEmpty(secRule.getSecurityRemoteGroupID())) {
517                 return true;
518             }
519         }
520         return false;
521     }
522
523     private static Name createTapPortName(NeutronPort port) {
524         return new Name("tap" + port.getID().substring(0, 11));
525     }
526
527     private static boolean isDhcpPort(NeutronPort port) {
528         return DEVICE_OWNER_DHCP.equals(port.getDeviceOwner());
529     }
530
531     private static boolean isRouterInterfacePort(NeutronPort port) {
532         return DEVICE_OWNER_ROUTER_IFACE.equals(port.getDeviceOwner());
533     }
534
535     private UnregisterEndpointInput createUnregisterEndpointInput(Endpoint ep) {
536         UnregisterEndpointInputBuilder inputBuilder = new UnregisterEndpointInputBuilder();
537         L2 l2Ep = new L2Builder().setL2Context(ep.getL2Context()).setMacAddress(ep.getMacAddress()).build();
538         inputBuilder.setL2(ImmutableList.of(l2Ep));
539         // TODO Li msunal this has to be rewrite when OFOverlay renderer will support l3-endpoints.
540         // Endpoint probably will not have l3-addresses anymore, because L2 and L3 endpoints should
541         // be registered separately.
542         if (ep.getL3Address() != null && !ep.getL3Address().isEmpty()) {
543             List<L3> l3Eps = new ArrayList<>();
544             for (L3Address ip : ep.getL3Address()) {
545                 l3Eps.add(new L3Builder().setL3Context(ip.getL3Context()).setIpAddress(ip.getIpAddress()).build());
546             }
547             inputBuilder.setL3(l3Eps);
548         }
549         return inputBuilder.build();
550     }
551
552     private UnregisterEndpointInput createUnregisterEndpointInput(NeutronPort port, ForwardingCtx fwCtx) {
553         UnregisterEndpointInputBuilder inputBuilder = new UnregisterEndpointInputBuilder();
554         L2 l2Ep = new L2Builder().setL2Context(fwCtx.getL2BridgeDomain().getId())
555             .setMacAddress(new MacAddress(port.getMacAddress()))
556             .build();
557         inputBuilder.setL2(ImmutableList.of(l2Ep));
558         // TODO Li msunal this has to be rewrite when OFOverlay renderer will support l3-endpoints.
559         // Endpoint probably will not have l3-addresses anymore, because L2 and L3 endpoints should
560         // be registered separately.
561         if (port.getFixedIPs() != null && !port.getFixedIPs().isEmpty()) {
562             inputBuilder.setL3(createL3s(port.getFixedIPs(), fwCtx.getL3Context().getId()));
563         }
564         return inputBuilder.build();
565     }
566
567     private List<L3> createL3s(List<Neutron_IPs> neutronIps, L3ContextId l3ContextId) {
568         List<L3> l3s = new ArrayList<>();
569         for (Neutron_IPs fixedIp : neutronIps) {
570             String ip = fixedIp.getIpAddress();
571             L3 l3 = new L3Builder().setIpAddress(Utils.createIpAddress(ip)).setL3Context(l3ContextId).build();
572             l3s.add(l3);
573         }
574         return l3s;
575     }
576
577 }