Migrate isFoo() callers
[lispflowmapping.git] / integrationtest / src / test / java / org / opendaylight / lispflowmapping / integrationtest / MappingServiceIntegrationTest.java
1 /*
2  * Copyright (c) 2014, 2017 Contextream, 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.lispflowmapping.integrationtest;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertNotNull;
12 import static org.junit.Assert.assertNull;
13 import static org.junit.Assert.assertTrue;
14 import static org.junit.Assert.fail;
15 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_A;
16 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_A_SB;
17 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_B;
18 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_B_SB;
19 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_C;
20 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_C_NEGATIVE;
21 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_C_RLOC_10;
22 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_C_SB;
23 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_C_WP_100_1_SB;
24 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_C_WP_50_2_SB;
25 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_D4;
26 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_D5;
27 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_D_DELETE_SB;
28 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_D_WP_100_1_SB;
29 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_D_WP_50_2_SB;
30 import static org.opendaylight.lispflowmapping.integrationtest.MultiSiteScenarioUtil.SITE_E_SB;
31 import static org.ops4j.pax.exam.CoreOptions.maven;
32 import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.configureConsole;
33 import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.editConfigurationFilePut;
34 import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.keepRuntimeFolder;
35
36 import com.google.common.collect.Lists;
37 import com.google.common.collect.Sets;
38 import java.io.File;
39 import java.io.IOException;
40 import java.net.DatagramSocket;
41 import java.net.InetAddress;
42 import java.net.InetSocketAddress;
43 import java.net.SocketException;
44 import java.net.SocketTimeoutException;
45 import java.net.UnknownHostException;
46 import java.nio.ByteBuffer;
47 import java.util.ArrayList;
48 import java.util.Arrays;
49 import java.util.HashSet;
50 import java.util.List;
51 import java.util.Set;
52 import javax.inject.Inject;
53 import org.junit.After;
54 import org.junit.Assert;
55 import org.junit.Before;
56 import org.junit.Test;
57 import org.junit.runner.RunWith;
58 import org.opendaylight.controller.mdsal.it.base.AbstractMdsalTestBase;
59 import org.opendaylight.lispflowmapping.config.ConfigIni;
60 import org.opendaylight.lispflowmapping.implementation.LispMappingService;
61 import org.opendaylight.lispflowmapping.interfaces.dao.SubKeys;
62 import org.opendaylight.lispflowmapping.interfaces.dao.Subscriber;
63 import org.opendaylight.lispflowmapping.interfaces.lisp.IFlowMapping;
64 import org.opendaylight.lispflowmapping.interfaces.mappingservice.IMappingService;
65 import org.opendaylight.lispflowmapping.lisp.serializer.MapRegisterSerializer;
66 import org.opendaylight.lispflowmapping.lisp.serializer.MapRequestSerializer;
67 import org.opendaylight.lispflowmapping.lisp.type.LispMessage;
68 import org.opendaylight.lispflowmapping.lisp.type.MappingData;
69 import org.opendaylight.lispflowmapping.lisp.util.LispAddressStringifier;
70 import org.opendaylight.lispflowmapping.lisp.util.LispAddressUtil;
71 import org.opendaylight.lispflowmapping.lisp.util.MappingRecordUtil;
72 import org.opendaylight.lispflowmapping.lisp.util.MaskUtil;
73 import org.opendaylight.lispflowmapping.type.sbplugin.IConfigLispSouthboundPlugin;
74 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
75 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpPrefix;
76 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
77 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
78 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.AfiListLcaf;
79 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.ApplicationDataLcaf;
80 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.ExplicitLocatorPathLcaf;
81 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.InstanceIdType;
82 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.Ipv4PrefixAfi;
83 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.KeyValueAddressLcaf;
84 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.MacAfi;
85 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.SimpleAddress;
86 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.SourceDestKeyLcaf;
87 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.Address;
88 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.AfiList;
89 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.ApplicationData;
90 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.ExplicitLocatorPath;
91 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.Ipv4Prefix;
92 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.Ipv4PrefixBuilder;
93 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.KeyValueAddress;
94 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.Mac;
95 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.SourceDestKey;
96 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.afi.list.AfiListBuilder;
97 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.application.data.ApplicationDataBuilder;
98 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.explicit.locator.path.ExplicitLocatorPathBuilder;
99 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.explicit.locator.path.explicit.locator.path.Hop;
100 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.explicit.locator.path.explicit.locator.path.Hop.LrsBits;
101 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.explicit.locator.path.explicit.locator.path.HopBuilder;
102 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105.lisp.address.address.source.dest.key.SourceDestKeyBuilder;
103 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.inet.binary.types.rev160303.Ipv4AddressBinary;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.binary.address.types.rev160504.Ipv4PrefixBinaryAfi;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.binary.address.types.rev160504.augmented.lisp.address.address.Ipv4PrefixBinaryBuilder;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.AddMapping;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.GotMapNotify;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.GotMapReply;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapNotify;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRegister;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapReply;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRequest;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MappingKeepAlive;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MessageType;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.OdlLispProtoListener;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.RequestMapping;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.XtrReplyMapping;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.XtrRequestMapping;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.container.Eid;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.container.EidBuilder;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.list.EidItem;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.eid.list.EidItemBuilder;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.locatorrecords.LocatorRecord;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.locatorrecords.LocatorRecordBuilder;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.authkey.container.MappingAuthkey;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.authkey.container.MappingAuthkeyBuilder;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecord;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecord.Action;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.container.MappingRecordBuilder;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.list.MappingRecordItem;
132 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapping.record.list.MappingRecordItemBuilder;
133 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.mapregisternotification.MapRegisterBuilder;
134 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequest.ItrRloc;
135 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequest.ItrRlocBuilder;
136 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequest.SourceEidBuilder;
137 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.maprequestnotification.MapRequestBuilder;
138 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.rloc.container.Rloc;
139 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.rloc.container.RlocBuilder;
140 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.mappingservice.rev150906.MappingOrigin;
141 import org.opendaylight.yangtools.yang.common.Uint8;
142 import org.ops4j.io.FileUtils;
143 import org.ops4j.pax.exam.Option;
144 import org.ops4j.pax.exam.junit.PaxExam;
145 import org.ops4j.pax.exam.karaf.options.LogLevelOption.LogLevel;
146 import org.ops4j.pax.exam.options.MavenUrlReference;
147 import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
148 import org.ops4j.pax.exam.spi.reactors.PerClass;
149 import org.ops4j.pax.exam.util.Filter;
150 import org.osgi.framework.Bundle;
151 import org.osgi.framework.BundleContext;
152 import org.osgi.framework.InvalidSyntaxException;
153 import org.slf4j.Logger;
154 import org.slf4j.LoggerFactory;
155
156 @RunWith(PaxExam.class)
157 @ExamReactorStrategy(PerClass.class)
158 public class MappingServiceIntegrationTest extends AbstractMdsalTestBase {
159     private static final Logger LOG = LoggerFactory.getLogger(MappingServiceIntegrationTest.class);
160
161     private byte[] mapRequestPacket;
162     private byte[] mapRegisterPacketWithNotify;
163     private byte[] mapRegisterPacketWithoutNotify;
164     String lispBindAddress = "127.0.0.1";
165     static final String ourAddress = "127.0.0.2";
166     private Rloc locatorEid;
167     private DatagramSocket socket;
168     private byte[] mapRegisterPacketWithAuthenticationAndMapNotify;
169
170     public static final String ODL = "org.opendaylight.controller";
171     public static final String YANG = "org.opendaylight.yangtools";
172     private static final int MULTI_SITE_SLEEP_TIME = 2;
173     private static final int MAX_NOTIFICATION_RETRYS = 20;
174     private static final MappingAuthkey NULL_AUTH_KEY = new MappingAuthkeyBuilder().setKeyType(0).build();
175
176     // This is temporary, since the properties in the pom file are not picked up
177     @Override
178     public String getKarafDistro() {
179         return maven()
180                 .groupId("org.opendaylight.lispflowmapping")
181                 .artifactId("lispflowmapping-karaf")
182                 .versionAsInProject()
183                 .type("zip")
184                 .getURL();
185     }
186
187     @Override
188     public MavenUrlReference getFeatureRepo() {
189         return maven()
190                 .groupId("org.opendaylight.lispflowmapping")
191                 .artifactId("features-lispflowmapping")
192                 .classifier("features")
193                 .type("xml")
194                 .versionAsInProject();
195     }
196
197     @Override
198     public String getFeatureName() {
199         return "odl-lispflowmapping-msmr";
200     }
201
202     @Override
203     protected Option[] getAdditionalOptions() {
204         return new Option[] {
205                 keepRuntimeFolder(),
206                 configureConsole().ignoreLocalConsole().ignoreRemoteShell(),
207                 editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
208                         "log4j2.logger.lispflowmapping.name",
209                         "org.opendaylight.lispflowmapping"),
210                 editConfigurationFilePut(ORG_OPS4J_PAX_LOGGING_CFG,
211                         "log4j2.logger.lispflowmapping.level",
212                         LogLevel.TRACE.name())
213         };
214     }
215
216     @Test
217     public void testLispFlowMappingFeatureLoad() {
218         Assert.assertTrue(true);
219     }
220
221     @After
222     public void after() {
223         if (socket != null) {
224             socket.close();
225         }
226     }
227
228     @Before
229     public void before() throws Exception {
230         File paxExamDirectory = new File("target/exam/");
231         FileUtils.delete(paxExamDirectory);
232
233         areWeReady();
234         mapService.setLookupPolicy(IMappingService.LookupPolicy.NB_FIRST);
235         mapService.setMappingMerge(false);
236         ConfigIni.getInstance().setSmrRetryCount(1);
237
238         socket = MappingServiceIntegrationTestUtil.initSocket(LispMessage.PORT_NUM);
239
240         // SRC: 127.0.0.1:58560 to 127.0.0.1:4342
241         // LISP(Type = 8 - Encapsulated)
242         // IP: 192.168.136.10 -> 153.16.254.1
243         // UDP: 56756
244         // LISP(Type = 1 Map-Request
245         // Record Count: 1
246         // ITR-RLOC count: 0
247         // Source EID AFI: 1
248         // Source EID 1.2.3.4
249         // Nonce: 0x3d8d2acd39c8d608
250         // ITR-RLOC AFI=1 Address=192.168.136.10
251         // Record 1: 153.16.254.1/32
252         mapRequestPacket = extractWSUdpByteArray("0000   00 00 00 00 00 00 00 00 00 00 00 00 08 00 45 00 "
253                 + "0010   00 58 00 00 40 00 40 11 3c 93 7f 00 00 01 7f 00 "
254                 + "0020   00 01 e4 c0 10 f6 00 44 fe 57 80 00 00 00 45 00 "
255                 + "0030   00 3c d4 31 00 00 ff 11 56 f3 7f 00 00 02 99 10 "
256                 + "0040   fe 01 dd b4 10 f6 00 28 ef 3a 10 00 00 01 3d 8d "
257                 + "0050   2a cd 39 c8 d6 08 00 01 01 02 03 04 00 01 7f 00 00 02 00 20 "
258                 + "0060   00 01 99 10 fe 01");
259
260         // IP: 192.168.136.10 -> 128.223.156.35
261         // UDP: 49289 -> 4342
262         // LISP(Type = 3 Map-Register, P=1, M=1
263         // Record Counter: 1
264         // Nonce: 0
265         // Key ID: 0x0001
266         // AuthDataLength: 20 Data:
267         // e8:f5:0b:c5:c5:f2:b0:21:27:a8:21:41:04:f3:46:5a:a5:68:89:ec
268         // EID prefix: 153.16.254.1/32 (EID=0x9910FE01), TTL: 10, Authoritative,
269         // No-Action
270         // Local RLOC: 192.168.136.10 (RLOC=0xC0A8880A), Reachable,
271         // Priority/Weight: 1/100, Multicast Priority/Weight:
272         // 255/0
273         //
274
275         mapRegisterPacketWithAuthenticationAndMapNotify = extractWSUdpByteArray(
276                   "0000   00 50 56 ee d1 4f 00 0c 29 7a ce 79 08 00 45 00 "
277                 + "0010   00 5c 00 00 40 00 40 11 d4 db c0 a8 88 0a 80 df "
278                 + "0020   9c 23 d6 40 10 f6 00 48 59 a4 38 00 01 01 00 00 "
279                 + "0030   00 00 00 00 00 00 00 01 00 14 0e a4 c6 d8 a4 06 "
280                 + "0040   71 7c 33 a4 5c 4a 83 1c de 74 53 03 0c ad 00 00 "
281                 + "0050   00 0a 01 20 10 00 00 00 00 01 99 10 fe 01 01 64 "
282                 + "0060   ff 00 00 05 00 01 c0 a8 88 0a");
283
284         // IP: 192.168.136.10 -> 128.223.156.35
285         // UDP: 49289 -> 4342
286         // LISP(Type = 3 Map-Register, P=1, M=1
287         // Record Counter: 1
288         // Nonce: 7
289         // Key ID: 0x0000 NO AUTHENTICATION!!
290         // AuthDataLength: 00 Data:
291         // EID prefix: 153.16.254.1/32 (EID=0x9910FE01), TTL: 10, Authoritative,
292         // No-Action
293         // Local RLOC: 192.168.136.10 (RLOC=0xC0A8880A), Reachable,
294         // Priority/Weight: 1/100, Multicast Priority/Weight:
295         // 255/0
296         //
297
298         mapRegisterPacketWithNotify = extractWSUdpByteArray(
299                   "0000   00 50 56 ee d1 4f 00 0c 29 7a ce 79 08 00 45 00 "
300                 + "0010   00 5c 00 00 40 00 40 11 d4 db c0 a8 88 0a 80 df "
301                 + "0020   9c 23 d6 40 10 f6 00 48 59 a4 38 00 01 01 00 00 "
302                 + "0030   00 00 00 00 00 07 00 00 00 14 0e a4 c6 d8 a4 06 "
303                 + "0040   71 7c 33 a4 5c 4a 83 1c de 74 53 03 0c ad 00 00 "
304                 + "0050   00 0a 01 20 10 00 00 00 00 01 99 10 fe 01 01 64 "
305                 + "0060   ff 00 00 05 00 01 c0 a8 88 0a");
306
307         // IP: 192.168.136.10 -> 128.223.156.35
308         // UDP: 49289 -> 4342
309         // LISP(Type = 3 Map-Register, P=1, M=1
310         // Record Counter: 1
311         // Nonce: 7
312         // Key ID: 0x0000 NO AUTHENTICATION!!
313         // AuthDataLength: 00 Data:
314         // EID prefix: 153.16.254.1/32 (EID=0x9910FE01), TTL: 10, Authoritative,
315         // No-Action
316         // Local RLOC: 192.168.136.10 (RLOC=0xC0A8880A), Reachable,
317         // Priority/Weight: 1/100, Multicast Priority/Weight:
318         // 255/0
319         //
320
321         mapRegisterPacketWithoutNotify = extractWSUdpByteArray(
322                   "0000   00 50 56 ee d1 4f 00 0c 29 7a ce 79 08 00 45 00 "
323                 + "0010   00 5c 00 00 40 00 40 11 d4 db c0 a8 88 0a 80 df "
324                 + "0020   9c 23 d6 40 10 f6 00 48 59 a4 38 00 00 01 00 00 "
325                 + "0030   00 00 00 00 00 07 00 00 00 14 0e a4 c6 d8 a4 06 "
326                 + "0040   71 7c 33 a4 5c 4a 83 1c de 74 53 03 0c ad 00 00 "
327                 + "0050   00 0a 01 20 10 00 00 00 00 01 99 10 fe 01 01 64 "
328                 + "0060   ff 00 00 05 00 01 c0 a8 88 0a");
329     }
330
331     @Inject
332     private BundleContext bc;
333     //private HttpURLConnection connection;
334     protected static boolean notificationCalled;
335
336     @Inject @Filter(timeout=60000)
337     private IFlowMapping lms;
338
339     @Inject @Filter(timeout=60000)
340     private IMappingService mapService;
341
342     @Inject @Filter(timeout=10000)
343     private IConfigLispSouthboundPlugin configLispPlugin;
344
345     @Test
346     public void testSimpleUsage() throws Exception {
347         mapRequestSimple();
348         mapRegisterWithMapNotify();
349         mapRegisterWithMapNotifyAndMapRequest();
350         registerAndQuery__MAC();
351         mapRequestMapRegisterAndMapRequest();
352         mapRegisterWithAuthenticationWithoutConfiguringAKey();
353         mapRegisterWithoutMapNotify();
354     }
355
356     @Test
357     public void testLCAFs() throws Exception {
358         registerAndQuery__SrcDestLCAF();
359         registerAndQuery__SrcDestLCAFOverlap();
360         registerAndQuery__KeyValueLCAF();
361         //registerAndQuery__ListLCAF();
362         //registerAndQuery__ApplicationData();
363         //registerAndQuery__TrafficEngineering();
364         //registerAndQuery__SegmentLCAF();
365     }
366
367     @Test
368     public void testMask() throws Exception {
369         //testPasswordExactMatch();                     TODO commented because it needs NB
370         //testPasswordMaskMatch();                      TODO commented because it needs NB
371         eidPrefixLookupIPv4();
372         eidPrefixLookupIPv6();
373     }
374 /*
375     @Test
376     public void testNorthbound() throws Exception {
377         northboundAddKey();
378         northboundAddMapping();
379         northboundDeleteMapping();
380         northboundRetrieveKey();
381         northboundRetrieveMapping();
382         northboundRetrieveSourceDestKey();
383         northboundRetrieveSourceDestMapping();
384     }
385 */
386     @Test
387     public void testTimeOuts() throws Exception {
388         timedOutMappingRecord();
389         mapRequestMapRegisterAndMapRequestTestTimeout();
390         //mapRequestMapRegisterAndMapRequestTestNativelyForwardTimeoutResponse();   TODO commented because it needs NB
391     }
392
393 //    @Test
394 //    public void testNonProxy() throws Throwable {
395 //        testSimpleNonProxy();
396 //        testNonProxyOtherPort();
397 //        testRecievingNonProxyOnXtrPort();
398 //    }
399
400     @Test
401     public void testSmr() throws Exception {
402         registerQueryRegisterWithSmr();
403         //testRepeatedSmr();
404     }
405
406     @Test
407     public void testMultiSite() throws Exception {
408         testMultiSiteScenarioA();
409         testMultiSiteScenarioB();
410     }
411
412     @Test
413     public void testNbAndSbNegativePrefix() throws UnknownHostException {
414         insertMappings();
415         testGapIntersection();
416
417         insertMappings();
418         testMultipleMappings();
419     }
420
421     @Test
422     public void testExplicitSbNegativePrefixes() {
423         // https://bugs.opendaylight.org/show_bug.cgi?id=8679
424         testNegativePrefix();
425
426         // https://bugs.opendaylight.org/show_bug.cgi?id=9023
427         testPositiveMappingRemoval();
428
429         // https://bugs.opendaylight.org/show_bug.cgi?id=9037
430         testPositivePrefixOverlappingNegativePrefix_moreSpecific();
431
432         // https://bugs.opendaylight.org/show_bug.cgi?id=9116
433         testPositivePrefixOverlappingNegativePrefix_lessSpecific();
434     }
435
436     @Test
437     public void testMappingChangeCases() {
438         // Test numbers described in the below Google Sheet:
439         // https://docs.google.com/spreadsheets/d/1we3eBBilS-HoAZgtHH3jtmvq4-6lBvVX2yMgxfF48w0/edit?usp=sharing
440
441         test1nullToNB();
442         test2nullToSB();
443         test3deleteNB();
444         test4NBtoNBmoreSpecific();
445         test5NBtoNBexactMatch();
446         test6NBtoNBlessSpecific();
447         test7NBtoSBmoreSpecific();
448         test8NBtoSBexactMatch();
449         test9NBtoSBlessSpecific();
450         test10deleteSBpositive();
451         test11SBpositiveToNBmoreSpecific();
452         test12SBpositiveToNBexactMatch();
453         test13SBtoNBlessSpecific();
454         test14SBpositiveToSBmoreSpecific();
455         test15SBpositiveToSBexactMatch();
456         test16SBpositiveToSBlessSpecific();
457         test17deleteSBnegative();
458         test18SBnegativeToNBmoreSpecific();
459         test19SBnegativeToNBexactMatch();
460         test20SBnegativeToNBlessSpecific();
461         test21SBnegativeToSBmoreSpecific();
462         test22SBnegativeToSBexactMatch();
463         test23SBnegativeToSBlessSpecific();
464
465         testNbSourceDest();
466
467         testSubtree();
468     }
469
470     private void testRepeatedSmr() throws SocketTimeoutException, UnknownHostException {
471         cleanUP();
472         long timeout = ConfigIni.getInstance().getSmrTimeout();
473         ConfigIni.getInstance().setSmrRetryCount(5);
474
475         final InstanceIdType iid = new InstanceIdType(1L);
476         final Eid eid1 = LispAddressUtil.asIpv4Eid("1.1.1.1", 1L);
477         final Eid subscriberEid = LispAddressUtil.asIpv4Eid("2.2.2.2", 1L);
478         final int expectedSmrs1 = 2;
479         final int expectedSmrs2 = 3;
480
481         /* set auth */
482         final Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("0.0.0.0/0", iid);
483         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
484
485         /* add subscribers */
486         final String subscriberSrcRloc1 = "127.0.0.3";
487         final String subscriberSrcRloc2 = "127.0.0.4";
488         final Set<Subscriber> subscriberSet1 = Sets.newHashSet(newSubscriber(subscriberEid, subscriberSrcRloc1),
489                 newSubscriber(subscriberEid, subscriberSrcRloc2));
490         mapService.addData(MappingOrigin.Southbound, eid1, SubKeys.SUBSCRIBERS, subscriberSet1);
491
492         final SocketReader reader1 = startSocketReader(subscriberSrcRloc1, 15000);
493         final SocketReader reader2 = startSocketReader(subscriberSrcRloc2, 15000);
494         sleepForSeconds(1);
495
496         /* add mapping */
497         final MappingRecord mapping1 = new MappingRecordBuilder()
498                 .setEid(eid1).setTimestamp(System.currentTimeMillis()).setRecordTtl(1440).build();
499         mapService.addMapping(MappingOrigin.Northbound, eid1, null, new MappingData(mapping1));
500
501         sleepForMilliseconds((timeout * expectedSmrs1) - (timeout / 2));
502         final List<MapRequest> requests1 = processSmrPackets(reader1, subscriberSrcRloc1, expectedSmrs1);
503         final MapReply mapReply1 = lms.handleMapRequest(
504                 new MapRequestBuilder(requests1.get(0))
505                         .setSourceEid(new SourceEidBuilder().setEid(subscriberEid).build())
506                         .setItrRloc(Lists.newArrayList(new ItrRlocBuilder()
507                                 .setRloc(LispAddressUtil.asIpv4Rloc(subscriberSrcRloc1)).build()))
508                         .setEidItem(Lists.newArrayList(new EidItemBuilder().setEid(eid1).build()))
509                         .setSmrInvoked(true)
510                         .setSmr(false).build());
511
512         // sleep to get 1 extra smr request
513         sleepForMilliseconds(timeout * 1);
514         final List<MapRequest> requests2 = processSmrPackets(reader2, subscriberSrcRloc2, expectedSmrs2);
515         final MapReply mapReply2 = lms.handleMapRequest(
516                 new MapRequestBuilder(requests2.get(0))
517                         .setSourceEid(new SourceEidBuilder().setEid(subscriberEid).build())
518                         .setItrRloc(Lists.newArrayList(new ItrRlocBuilder()
519                                 .setRloc(LispAddressUtil.asIpv4Rloc(subscriberSrcRloc2)).build()))
520                         .setEidItem(Lists.newArrayList(new EidItemBuilder().setEid(eid1).build()))
521                         .setSmrInvoked(true)
522                         .setSmr(false).build());
523
524         sleepForSeconds(3);
525         assertEquals(expectedSmrs1, requests1.size());
526         assertEquals(expectedSmrs2, requests2.size());
527         assertEquals((long) mapReply1.getNonce(), (long) requests1.get(0).getNonce());
528         assertEquals((long) mapReply2.getNonce(), (long) requests2.get(0).getNonce());
529         assertNextBufferEmpty(reader1);
530         assertNextBufferEmpty(reader2);
531
532         reader1.stopReading();
533         reader2.stopReading();
534     }
535
536     private SocketReader startSocketReader(String address, int timeout) {
537         DatagramSocket receivingSocket = null;
538
539         try {
540             receivingSocket = new DatagramSocket(new InetSocketAddress(address, LispMessage.PORT_NUM));
541         } catch (SocketException e) {
542             LOG.error("Can't initialize socket for {}", address, e);
543         }
544         return SocketReader.startReadingInStandaloneThread(receivingSocket, timeout);
545     }
546
547     private List<MapRequest> processSmrPackets(SocketReader reader, String address, int expectedSmrs) {
548         InetAddress inetAddress = null;
549         try {
550             inetAddress = InetAddress.getByName(address);
551         } catch (UnknownHostException e) {
552             LOG.error("Unknown address {}.", address, e);
553         }
554
555         final List<MapRequest> requests = Lists.newArrayList();
556         byte[][] buffers = reader.getBuffers(expectedSmrs);
557         for (byte[] buf : buffers) {
558             ByteBuffer packet = ByteBuffer.wrap(buf);
559             if (MappingServiceIntegrationTestUtil.checkType(packet, MessageType.MapRequest)) {
560                 MapRequest request = MapRequestSerializer.getInstance().deserialize(packet, inetAddress);
561                 requests.add(request);
562             }
563         }
564         return requests;
565     }
566
567     private void assertNextBufferEmpty(SocketReader socketReader) {
568         assertTrue(MultiSiteScenario.areBuffersEmpty(socketReader.getBuffers(1)));
569     }
570
571     private static Subscriber newSubscriber(Eid srcEid, String srcRlocIp) {
572         final int timeout = 5;
573         final Rloc srcRloc = LispAddressUtil.asIpv4Rloc(srcRlocIp);
574         return new Subscriber(srcRloc, srcEid, timeout);
575     }
576
577     private void testMultipleMappings() throws UnknownHostException {
578         final InstanceIdType iid = new InstanceIdType(1L);
579         final String prefix1 = "1.1.127.10/32"; // prefix from the intersection of NB and SB gaps
580         final String prefix2 = "1.1.200.255/32"; // prefix with existing mapping in NB
581         final String prefix3 = "1.3.255.255/32";
582
583         final MapRequest mapRequest = new MapRequestBuilder().setSmrInvoked(false).setEidItem(Lists.newArrayList(
584                 new EidItemBuilder()
585                         .setEidItemId(LispAddressStringifier
586                                 .getString(LispAddressUtil.asIpv4PrefixBinaryEid(prefix1, iid)))
587                         .setEid(LispAddressUtil.asIpv4PrefixBinaryEid(prefix1, iid))
588                         .build(),
589                 new EidItemBuilder()
590                         .setEidItemId(LispAddressStringifier
591                                 .getString(LispAddressUtil.asIpv4PrefixBinaryEid(prefix2, iid)))
592                         .setEid(LispAddressUtil.asIpv4PrefixBinaryEid(prefix2, iid))
593                         .build(),
594                 new EidItemBuilder()
595                         .setEidItemId(LispAddressStringifier
596                                 .getString(LispAddressUtil.asIpv4PrefixBinaryEid(prefix3, iid)))
597                         .setEid(LispAddressUtil.asIpv4PrefixBinaryEid(prefix3, iid))
598                         .build()))
599                 .build();
600         final MapReply mapReply = lms.handleMapRequest(mapRequest);
601
602         // expected result
603         final String resultPrefix1 = "1.1.64.0";
604         final Address resultNegMapping1 = new Ipv4PrefixBinaryBuilder()
605                 .setIpv4AddressBinary(new Ipv4AddressBinary(InetAddress.getByName(resultPrefix1).getAddress()))
606                 .setIpv4MaskLength((short) 18).build();
607
608         final String resultPrefix2 = "1.1.128.0";
609         final Address resultMapping2 = new Ipv4PrefixBinaryBuilder()
610                 .setIpv4AddressBinary(new Ipv4AddressBinary(InetAddress.getByName(resultPrefix2).getAddress()))
611                 .setIpv4MaskLength((short) 17).build();
612
613         final String resultPrefix3 = "1.3.0.0";
614         final Address resultNegMapping3 = new Ipv4PrefixBinaryBuilder()
615                 .setIpv4AddressBinary(new Ipv4AddressBinary(InetAddress.getByName(resultPrefix3).getAddress()))
616                 .setIpv4MaskLength((short) 16).build();
617
618         assertEquals(resultNegMapping1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getEid()
619                 .getAddress());
620         assertEquals(resultMapping2, mapReply.getMappingRecordItem().get(1).getMappingRecord().getEid()
621                 .getAddress());
622         assertEquals(resultNegMapping3, mapReply.getMappingRecordItem().get(2).getMappingRecord().getEid()
623                 .getAddress());
624     }
625
626     /**
627      * Tests a negative mapping from an intersection of gaps in northbound and southbound.
628      */
629     private void testGapIntersection() throws UnknownHostException {
630         // request an Eid from a gap between mappings
631         final MapReply mapReply = lms.handleMapRequest(newMapRequest(1L, "1.1.127.10/32"));
632
633         // expected negative mapping
634         final Address resultNegMapping = new Ipv4PrefixBinaryBuilder()
635                 .setIpv4AddressBinary(new Ipv4AddressBinary(InetAddress.getByName("1.1.64.0").getAddress()))
636                 .setIpv4MaskLength((short) 18).build();
637         assertEquals(resultNegMapping, mapReply.getMappingRecordItem().get(0).getMappingRecord().getEid()
638                 .getAddress());
639     }
640
641     private void testNegativePrefix() {
642         // First, we test with one mapping in NB and one mapping in SB
643         cleanUP();
644         allowNullAuthenticationForAllIPv4(1L);
645
646         insertNBMappings(1L, "192.0.2.0/24");
647         insertSBMappings(false, 1L, "10.0.0.0/32");
648
649         restartSocket();
650         sleepForSeconds(2);
651
652         MapReply mapReply = lms.handleMapRequest(newMapRequest(1L, "11.1.1.1/32"));
653         Eid expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "11.0.0.0/8");
654         assertEquals(expectedNegativePrefix, mapReply.getMappingRecordItem().get(0).getMappingRecord().getEid());
655         assertTrue(MappingRecordUtil.isNegativeMapping(mapReply.getMappingRecordItem().get(0).getMappingRecord()));
656
657         // Second, we test with two mappings in NB only
658         cleanUP();
659
660         insertNBMappings(1L, "192.167.0.0/16", "192.169.0.0/16");
661
662         restartSocket();
663         sleepForSeconds(2);
664
665         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
666         expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/16");
667         MappingRecord mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
668         assertEquals(expectedNegativePrefix, mr.getEid());
669         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
670     }
671
672     private void testPositiveMappingRemoval() {
673         cleanUP();
674         allowNullAuthenticationForAllIPv4(1L);
675
676         insertNBMappings(1L, "192.167.0.0/16", "192.169.0.0/16");
677         insertSBMappings(false, 1L, "192.168.32.0/19");
678
679         MapReply mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
680         Eid expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/19");
681         MappingRecord mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
682         assertEquals(expectedNegativePrefix, mr.getEid());
683         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
684
685         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.64.1/32"));
686         expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.64.0/18");
687         mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
688         assertEquals(expectedNegativePrefix, mr.getEid());
689         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
690
691         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.128.1/32"));
692         expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.128.0/17");
693         mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
694         assertEquals(expectedNegativePrefix, mr.getEid());
695         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
696
697         MappingServiceIntegrationTestUtil.printMapCacheState(mapService);
698
699         mapService.removeMapping(MappingOrigin.Southbound, LispAddressUtil.asIpv4PrefixBinaryEid(
700                 1L, "192.168.32.0/19"));
701
702         MappingServiceIntegrationTestUtil.printMapCacheState(mapService);
703
704         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.32.1/32"));
705         expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/16");
706         mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
707         assertEquals(expectedNegativePrefix, mr.getEid());
708         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
709
710         MappingServiceIntegrationTestUtil.printMapCacheState(mapService);
711     }
712
713     private void testPositivePrefixOverlappingNegativePrefix_moreSpecific() {
714         cleanUP();
715
716         insertNBMappings(1L, "192.167.0.0/16", "192.169.0.0/16");
717
718         MapReply mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
719         Eid expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/16");
720         MappingRecord mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
721         assertEquals(expectedNegativePrefix, mr.getEid());
722         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
723
724         insertNBMappings(1L, "192.168.1.0/24");
725         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
726
727         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
728         expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/24");
729         mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
730         assertEquals(expectedNegativePrefix, mr.getEid());
731         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
732     }
733
734     private void testPositivePrefixOverlappingNegativePrefix_lessSpecific() {
735         cleanUP();
736
737         insertNBMappings(1L, "192.167.0.0/16", "192.169.0.0/16");
738
739         MapReply mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
740         Eid expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/16");
741         MappingRecord mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
742         assertEquals(expectedNegativePrefix, mr.getEid());
743         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
744
745         insertNBMappings(1L, "192.0.0.0/8");
746         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
747
748         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
749         Eid expectedPositivePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.0.0.0/8");
750         mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
751         assertEquals(expectedPositivePrefix, mr.getEid());
752         assertTrue(MappingRecordUtil.isPositiveMapping(mr));
753     }
754
755     /*
756      * Mapping change: NO old mapping, new mapping is from northbound
757      * Support status: SUPPORTED
758      * Description: If no mappings exists in either NB or SB, that means no subscriptions exist either, so
759      *              this is just a simple case of adding a new mapping, no SMR required.
760      */
761     private void test1nullToNB() {
762         cleanUP();
763
764         insertNBMappings(1L, "192.168.0.0/16");
765         MappingServiceIntegrationTestUtil.assertNoMoreSMRs(socket, mapService);
766     }
767
768     /*
769      * Mapping change: NO old mapping, new mapping is from southbound
770      * Support status: SUPPORTED
771      * Description: If no mappings exists in either NB or SB, that means no subscriptions exist either, so
772      *              this is just a simple case of adding a new mapping, no SMR required.
773      */
774     private void test2nullToSB() {
775         cleanUP();
776         allowNullAuthenticationForAllIPv4(1L);
777
778         registerSBMapping(1L, "192.168.0.0/16", "10.10.10.10");
779         MappingServiceIntegrationTestUtil.assertNoMoreSMRs(socket, mapService);
780     }
781
782     /*
783      * Mapping change: deleting a mapping from northbound
784      * Support status: SUPPORTED
785      * Description: When a NB mapping is deleted, its subscribers, and the subscribers of its children are notified.
786      */
787     private void test3deleteNB() {
788         cleanUP();
789         allowNullAuthenticationForAllIPv4(1L);
790
791         // Overlapping SB mapping, which will stay
792         insertSBMappings(false, 1L, "192.168.255.0/24");
793         // Subscribe to the overlapping SB mapping
794         lms.handleMapRequest(newMapRequest(1L, "192.168.255.1/32"));
795         // NB mapping which will be removed
796         insertNBMappings(1L, "192.168.0.0/16");
797         // The child prefix is notified of the change
798         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.255.0");
799         // The above SMR will result in a SMR-invoked Map-Request for 192.168.255.0/32, which in turn will result  in
800         // subscribing to the new NB mapping
801
802         // Remove NB mapping
803         removeNBMapping(1L, "192.168.0.0/16");
804         // The removed prefix and the child prefix are both notified of the change
805         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0", "192.168.255.0");
806     }
807
808     /*
809      * Mapping change: adding a more specific northbound mapping overlapping a less specific one
810      * Support status: PARTIALLY SUPPORTED (?)
811      * Description: Overlapping prefixes in general are not "officially" supported in NB and should not be used.
812      *              That said, adding a more specific does result in an SMR, but adding a less specific does not (see
813      *              test 6 below).
814      */
815     private void test4NBtoNBmoreSpecific() {
816         cleanUP();
817
818         // Original (less specific) NB mapping
819         insertNBMappings(1L, "192.168.0.0/16");
820         // Subscribe, by sending a Map-Request
821         lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
822         // Add the more specific new overlapping mapping
823         insertNBMapping(1L, "192.168.1.0/24", "10.10.10.10");
824         // No notification is sent
825         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
826     }
827
828     /*
829      * Mapping change: updating a northbound mapping
830      * Support status: SUPPORTED
831      * Description: Simple case of updating an exact match NB prefix.
832      */
833     private void test5NBtoNBexactMatch() {
834         cleanUP();
835
836         // Original NB mapping
837         insertNBMappings(1L, "192.168.0.0/16");
838         // Subscribe, by sending a Map-Request
839         lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
840         // Updated NB mapping with different locator set for the same exact prefix
841         insertNBMapping(1L, "192.168.0.0/16", "10.10.10.10");
842         // Notification is sent for the prefix
843         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
844     }
845
846     /*
847      * Mapping change: adding a less specific northbound mapping overlapping a more specific one
848      * Support status: NOT SUPPORTED
849      * Description: Overlapping prefixes in general are not "officially" supported in NB and should not be used.
850      *              That said, adding a more specific does result in an SMR (see test 4 above), but adding a less
851      *              specific does not.
852      */
853     private void test6NBtoNBlessSpecific() {
854         cleanUP();
855
856         // Original (more specific) NB mapping
857         insertNBMappings(1L, "192.168.0.0/16");
858         // Subscribe, by sending a Map-Request
859         lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
860         // Add the less specific new overlapping mapping
861         insertNBMapping(1L, "192.0.0.0/8", "10.10.10.10");
862         // No notification is sent
863         MappingServiceIntegrationTestUtil.assertNoMoreSMRs(socket, mapService);
864     }
865
866     /*
867      * Mapping change: adding a more specific southbound mapping overlapping a less specific northbound mapping
868      * Support status: SUPPORTED
869      * Description: This is not an issue for NB_FIRST, since there is no change in the resolved mappings for the
870      *              prefix range covered by the existing NB mapping. For NB_AND_SB it does make a difference, and that
871      *              case is supported.
872      */
873     private void test7NBtoSBmoreSpecific() {
874         cleanUP();
875         allowNullAuthenticationForAllIPv4(1L);
876         mapService.setLookupPolicy(IMappingService.LookupPolicy.NB_AND_SB);
877
878         // Original (less specific) NB mapping
879         insertNBMapping(1L, "192.168.0.0/16", "172.16.0.1", "10.10.10.10");
880         // Subscribe, by sending a Map-Request
881         lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
882         // Add the more specific new overlapping SB mapping
883         registerSBMapping(1L, "192.168.1.0/24", "10.10.10.10");
884         // Notification is sent for the original prefix
885         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
886     }
887
888     /*
889      * Mapping change: adding a southbound mapping matching a northbound mapping
890      * Support status: SUPPORTED
891      * Description: When a SB mapping is added that has an existing exact match NB counterpart the subscribers of the
892      *              prefix are notified. This is not strictly necessary for the NB_FIRST policy, but it is still useful
893      *              for the NB_AND_SB policy.
894      */
895     private void test8NBtoSBexactMatch() {
896         cleanUP();
897         allowNullAuthenticationForAllIPv4(1L);
898         mapService.setLookupPolicy(IMappingService.LookupPolicy.NB_AND_SB);
899
900         // Original NB mapping
901         insertNBMapping(1L, "192.168.0.0/16", "172.16.0.1", "10.10.10.10");
902         // Subscribe, by sending a Map-Request
903         MapReply mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
904         // Add a mapping with the same EID but different locator set in SB
905         registerSBMapping(1L, "192.168.0.0/16", "10.10.10.10");
906         // Notification is sent for the prefix
907         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
908     }
909
910     /*
911      * Mapping change: adding a less specific southbound mapping overlapping a more specific northbound mapping
912      * Support status: PARTIALLY SUPPORTED (?)
913      * Description: When a less specific SB mapping is added no SMR is sent, but for the NB mapping subscribers there
914      *              is no actual change in the mapping. Part of the southbound prefix is not covered by the existing NB,
915      *              and queries for that part will resolve to the full SB prefix, shadowing the NB prefix. This is a
916      *              general problem with overlapping prefixes, but this particular combination is pretty bad.
917      */
918     private void test9NBtoSBlessSpecific() {
919         cleanUP();
920         allowNullAuthenticationForAllIPv4(1L);
921
922         // Original (more specific) NB mapping
923         insertNBMappings(1L, "192.168.0.0/16");
924         // Subscribe, by sending a Map-Request
925         lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
926         // Add the less specific new overlapping SB mapping
927         registerSBMapping(1L, "192.0.0.0/8", "10.10.10.10");
928         // No notification is sent
929         MappingServiceIntegrationTestUtil.assertNoMoreSMRs(socket, mapService);
930     }
931
932     /*
933      * Mapping change: deleting a positive mapping from southbound
934      * Support status: SUPPORTED
935      * Description: When a positive SB mapping is deleted, its subscribers, and the subscribers of its children are
936      *              notified.
937      */
938     private void test10deleteSBpositive() {
939         cleanUP();
940         allowNullAuthenticationForAllIPv4(1L);
941
942         // Overlapping SB mapping, which will stay
943         insertSBMappings(false, 1L, "192.168.255.0/24");
944         // Subscribe to the overlapping SB mapping
945         lms.handleMapRequest(newMapRequest(1L, "192.168.255.1/32"));
946         // Overlapping negative mapping
947         insertSBMappings(true, 1L, "192.168.127.0/24");
948         // Subscribe to the overlapping negative SB mapping
949         lms.handleMapRequest(newMapRequest(1L, "192.168.127.1/32"));
950         // Positive SB mapping which will be removed
951         insertSBMappings(false, 1L, "192.168.0.0/16");
952         // The child prefix is notified of the change
953         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.127.0", "192.168.255.0");
954         // The above SMR will result in a SMR-invoked Map-Request for 192.168.255.0/32 and 192.168.255.0/32, which in
955         // turn will result  in subscribing to the new SB mapping
956
957         // Remove positive SB mapping
958         removeSBMapping(1L, "192.168.0.0/16");
959         // The removed prefix and the child prefix are both notified of the change
960         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0", "192.168.255.0");
961     }
962
963     /*
964      * Mapping change: adding a more specific northbound mapping overlapping a less specific southbound mapping
965      * Support status: PARTIALLY SUPPORTED (?)
966      * Description: This mapping change is detected and an SMR is sent, but the EID prefix in it is for the base address
967      *              of the old prefix. When xTRs query for that, they won't actually install the new mapping. This is
968      *              one of those cases where saving the original request causing the subscription would help the xTR get
969      *              the correct mapping. Additionally, similar to case 9 above, this combination will shadow the NB
970      *              mapping for new requests into the non-overlapping part.
971      */
972     private void test11SBpositiveToNBmoreSpecific() {
973         cleanUP();
974         allowNullAuthenticationForAllIPv4(1L);
975
976         // Original (less specific) SB mapping
977         insertSBMappings(false, 1L, "192.168.0.0/16");
978         // Subscribe, by sending a Map-Request
979         lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
980         // Add the more specific new overlapping NB mapping
981         insertNBMappings(1L, "192.168.1.0/24");
982         // Notification is sent for the original prefix
983         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
984     }
985
986     /*
987      * Mapping change: adding a northbound mapping matching a southbound mapping
988      * Support status: SUPPORTED
989      * Description: When a NB mapping is added that has an existing exact match SB counterpart, the subscribers of the
990      *              prefix are notified.
991      */
992     private void test12SBpositiveToNBexactMatch() {
993         cleanUP();
994         allowNullAuthenticationForAllIPv4(1L);
995
996         // Original SB mapping
997         insertSBMappings(false, 1L, "192.168.0.0/16");
998         // Subscribe, by sending a Map-Request
999         lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1000         // Add a mapping with the same EID but different locator set in NB
1001         insertNBMappings(1L, "192.168.0.0/16");
1002         // Notification is sent for the prefix
1003         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
1004     }
1005
1006     /*
1007      * Mapping change: adding a less specific northbound mapping overlapping a more specific southbound mapping
1008      * Support status: PARTIALLY SUPPORTED (?)
1009      * Description: No SMR is sent, but the NB mapping takes precedence for new requests.
1010      */
1011     private void test13SBtoNBlessSpecific() {
1012         cleanUP();
1013         allowNullAuthenticationForAllIPv4(1L);
1014
1015         // Original (more specific) SB mapping
1016         insertNBMappings(1L, "192.168.0.0/16");
1017         // Subscribe, by sending a Map-Request
1018         lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1019         // Add the less specific new overlapping SB mapping
1020         registerSBMapping(1L, "192.0.0.0/8", "10.10.10.10");
1021         // No notification is sent
1022         MappingServiceIntegrationTestUtil.assertNoMoreSMRs(socket, mapService);
1023     }
1024
1025     /*
1026      * Mapping change: adding a more specific southbound mapping overlapping a less specific one
1027      * Support status: SUPPORTED
1028      * Description: When a more specific SB mapping is added, the subscribers of the overlapping less specific existing
1029      *              SB mapping are notified.
1030      */
1031     private void test14SBpositiveToSBmoreSpecific() {
1032         cleanUP();
1033         allowNullAuthenticationForAllIPv4(1L);
1034
1035         insertSBMappings(false, 1L, "192.168.0.0/16");
1036
1037         MapReply mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1038         Eid expectedPositivePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/16");
1039         MappingRecord mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
1040         assertEquals(expectedPositivePrefix, mr.getEid());
1041         assertTrue(MappingRecordUtil.isPositiveMapping(mr));
1042
1043         registerSBMapping(1L, "192.168.254.0/24", "10.10.10.10");
1044         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
1045
1046         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1047         expectedPositivePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/16");
1048         mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
1049         assertEquals(expectedPositivePrefix, mr.getEid());
1050         assertTrue(MappingRecordUtil.isPositiveMapping(mr));
1051
1052         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.254.1/32"));
1053         expectedPositivePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.254.0/24");
1054         mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
1055         assertEquals(expectedPositivePrefix, mr.getEid());
1056         assertTrue(MappingRecordUtil.isPositiveMapping(mr));
1057     }
1058
1059     /*
1060      * Mapping change: updating a southbound mapping
1061      * Support status: SUPPORTED
1062      * Description: Simple case of updating an exact match SB prefix.
1063      */
1064     private void test15SBpositiveToSBexactMatch() {
1065         cleanUP();
1066         allowNullAuthenticationForAllIPv4(1L);
1067
1068         // Original SB mapping
1069         insertSBMappings(false, 1L, "192.168.0.0/16");
1070         // Subscribe, by sending a Map-Request
1071         lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1072         // Updated SB mapping with different locator set for the same exact prefix
1073         registerSBMapping(1L, "192.168.0.0/16", "10.10.10.10");
1074         // Notification is sent for the prefix
1075         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
1076     }
1077
1078     /*
1079      * Mapping change: adding a less specific southbound mapping overlapping a more specific one
1080      * Support status: SUPPORTED
1081      * Description: When a less specific SB mapping is added, all child prefixes with subscribers are notified.
1082      */
1083     private void test16SBpositiveToSBlessSpecific() {
1084         cleanUP();
1085         allowNullAuthenticationForAllIPv4(1L);
1086
1087         // Original (more specific) SB mapping
1088         insertSBMappings(false, 1L, "192.168.0.0/16");
1089         // Subscribe, by sending a Map-Request
1090         lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1091         // Add the less specific new overlapping SB mapping
1092         registerSBMapping(1L, "192.0.0.0/8", "10.10.10.10");
1093         // Notification is sent for the original prefix
1094         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
1095     }
1096
1097     /*
1098      * Mapping change: deleting a negative mapping from southbound
1099      * Support status: SUPPORTED
1100      * Description: When a negative SB mapping is deleted, its subscribers are notified.
1101      */
1102     private void test17deleteSBnegative() {
1103         cleanUP();
1104         allowNullAuthenticationForAllIPv4(1L);
1105
1106         // First we add two negative mappings to NB with a hole between them
1107         insertNBMappings(1L, "192.167.0.0/16", "192.169.0.0/16");
1108         // We query for the hole, adding a negative SB mapping for 192.168.0.0/16 with a subscriber in the process
1109         lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1110         // Remove positive SB mapping
1111         removeSBMapping(1L, "192.168.0.0/16");
1112         // Notification is sent for the prefix
1113         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
1114     }
1115
1116     /*
1117      * Mapping change: adding a more specific northbound mapping overlapping a less specific negative southbound mapping
1118      * Support status: SUPPORTED
1119      * Description: When a more specific NB mapping is added, the overlapping negative prefix is deleted, its
1120      *              subscribers notified, and then more specific negatives are created when requested.
1121      */
1122     private void test18SBnegativeToNBmoreSpecific() {
1123         cleanUP();
1124
1125         // First we add two negative mappings to NB with a hole between them
1126         insertNBMappings(1L, "192.167.0.0/16", "192.169.0.0/16");
1127         // We query for the hole, adding a negative SB mapping for 192.168.0.0/16 with a subscriber in the process
1128         MapReply mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1129         Eid expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/16");
1130         MappingRecord mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
1131         assertEquals(expectedNegativePrefix, mr.getEid());
1132         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
1133
1134         // Add the more specific new overlapping NB mapping
1135         insertNBMappings(1L, "192.168.1.0/24");
1136         // Notification is sent for the original prefix
1137         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
1138
1139         // The original negative should now be broken up
1140         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1141         expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/24");
1142         mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
1143         assertEquals(expectedNegativePrefix, mr.getEid());
1144         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
1145
1146         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.64.1/32"));
1147         expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.64.0/18");
1148         mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
1149         assertEquals(expectedNegativePrefix, mr.getEid());
1150         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
1151
1152         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.1.1/32"));
1153         Eid expectedPositivePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.1.0/24");
1154         mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
1155         assertEquals(expectedPositivePrefix, mr.getEid());
1156         assertTrue(MappingRecordUtil.isPositiveMapping(mr));
1157     }
1158
1159     /*
1160      * Mapping change: adding a northbound mapping matching a negative southbound mapping
1161      * Support status: SUPPORTED
1162      * Description: When a NB mapping is added that has an existing exact match negative SB counterpart,
1163      *              the subscribers of the prefix are notified, and the negative is deleted.
1164      */
1165     private void test19SBnegativeToNBexactMatch() {
1166         cleanUP();
1167
1168         // First we add two negative mappings to NB with a hole between them
1169         insertNBMappings(1L, "192.167.0.0/16", "192.169.0.0/16");
1170         // We query for the hole, adding a negative SB mapping for 192.168.0.0/16 with a subscriber in the process
1171         lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1172         insertNBMappings(1L, "192.168.0.0/16");
1173         // Notification is sent for the prefix
1174         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0", "192.168.0.0");
1175     }
1176
1177     /*
1178      * Mapping change: adding a less specific northbound mapping overlapping a more specific negative southbound mapping
1179      * Support status: PARTIALLY SUPPORTED (?)
1180      * Description: When a less specific NB mapping covering a more specific negative SB mapping is added, the negative
1181      *              is deleted and its subscribers notified. Depending on the particular xTR map-cache implementation,
1182      *              the negative prefix may or may not stay cached (hence partially supported).
1183      */
1184     private void test20SBnegativeToNBlessSpecific() {
1185         cleanUP();
1186         allowNullAuthenticationForAllIPv4(1L);
1187
1188         // Add a negative mapping
1189         insertSBMappings(true, 1L, "192.168.0.0/16");
1190         // Subscribe for the mapping
1191         lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1192         // Add less specific northbound mapping
1193         insertNBMappings(1L, "192.0.0.0/8");
1194         // Notification is sent for the negative prefix
1195         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
1196     }
1197
1198     /*
1199      * Mapping change: adding a more specific southbound mapping overlapping a less specific negative mapping
1200      * Support status: SUPPORTED
1201      * Description: When a more specific SB mapping is added, the subscribers of the overlapping less specific existing
1202      *              negative SB mapping are notified, the negative is deleted, and then more specific negatives are
1203      *              created when requested.
1204      */
1205     private void test21SBnegativeToSBmoreSpecific() {
1206         cleanUP();
1207         allowNullAuthenticationForAllIPv4(1L);
1208
1209         // First we add two negative mappings to NB with a hole between them
1210         insertNBMappings(1L, "192.167.0.0/16", "192.169.0.0/16");
1211         // We query for the hole, adding a negative SB mapping for 192.168.0.0/16 with a subscriber in the process
1212         MapReply mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1213         Eid expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/16");
1214         MappingRecord mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
1215         assertEquals(expectedNegativePrefix, mr.getEid());
1216         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
1217
1218         // Add the more specific new overlapping SB mapping
1219         registerSBMapping(1L, "192.168.254.0/24", "10.10.10.10");
1220         // Notification is sent for the original prefix
1221         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L,"192.168.0.0");
1222
1223         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1224         expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/17");
1225         mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
1226         assertEquals(expectedNegativePrefix, mr.getEid());
1227         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
1228
1229         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.254.1/32"));
1230         Eid expectedPositivePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.254.0/24");
1231         mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
1232         assertEquals(expectedPositivePrefix, mr.getEid());
1233         assertTrue(MappingRecordUtil.isPositiveMapping(mr));
1234     }
1235
1236     /*
1237      * Mapping change: updating a negative southbound mapping with a positive one
1238      * Support status: SUPPORTED
1239      * Description: Simple case of updating an exact match SB prefix.
1240      */
1241     private void test22SBnegativeToSBexactMatch() {
1242         cleanUP();
1243         allowNullAuthenticationForAllIPv4(1L);
1244
1245         // First we add two negative mappings to NB with a hole between them
1246         insertNBMappings(1L, "192.167.0.0/16", "192.169.0.0/16");
1247         // We query for the hole, adding a negative SB mapping for 192.168.0.0/16 with a subscriber in the process
1248         MapReply mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1249         Eid expectedNegativePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/16");
1250         MappingRecord mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
1251         assertEquals(expectedNegativePrefix, mr.getEid());
1252         assertTrue(MappingRecordUtil.isNegativeMapping(mr));
1253         // Updated SB mapping with different locator set for the same exact prefix
1254         registerSBMapping(1L, "192.168.0.0/16", "10.10.10.10");
1255         // Notification is sent for the prefix
1256         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
1257
1258         mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1259         Eid expectedPositivePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/16");
1260         mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
1261         assertEquals(expectedPositivePrefix, mr.getEid());
1262         assertTrue(MappingRecordUtil.isPositiveMapping(mr));
1263     }
1264
1265     /*
1266      * Mapping change: adding a less specific southbound mapping overlapping a more specific negative mapping
1267      * Support status: SUPPORTED
1268      * Description: When a less specific SB mapping is added, all child prefixes with subscribers are notified. In this
1269      *              case, the overlapping more specific negative is removed.
1270      */
1271     private void test23SBnegativeToSBlessSpecific() {
1272         cleanUP();
1273         allowNullAuthenticationForAllIPv4(1L);
1274
1275         // Add a negative mapping
1276         insertSBMappings(true, 1L, "192.168.0.0/16");
1277         // Subscribe for the mapping
1278         lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1279         // Add less specific southbound mapping
1280         registerSBMapping(1L, "192.0.0.0/8", "10.10.10.10");
1281         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
1282     }
1283
1284     private void testNbSourceDest() {
1285         cleanUP();
1286
1287         insertNBMappingSourceDest(1L, "192.0.2.0/24", "192.168.0.0/16",
1288                 MappingServiceIntegrationTestUtil.DEFAULT_IPV4_RLOC_STRING);
1289
1290         MapReply mapReply = lms.handleMapRequest(newMapRequest(1L, "192.168.0.1/32"));
1291         Eid expectedPositivePrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "192.168.0.0/16");
1292         MappingRecord mr = mapReply.getMappingRecordItem().get(0).getMappingRecord();
1293         assertEquals(expectedPositivePrefix, mr.getEid());
1294         assertTrue(MappingRecordUtil.isPositiveMapping(mr));
1295
1296         insertNBMapping(1L, "192.168.0.0/16", "10.10.10.10");
1297         MappingServiceIntegrationTestUtil.checkSmr(socket, lms, mapService, 1L, "192.168.0.0");
1298     }
1299
1300     private void testSubtree() {
1301         cleanUP();
1302         allowNullAuthenticationForAllIPv4(1L);
1303
1304         insertSBMappings(false, 1L, "10.0.0.0/8",
1305                 "10.0.0.0/16", "10.2.0.0/16", "10.255.0.0/16");
1306         Eid queryPrefix = LispAddressUtil.asIpv4PrefixBinaryEid(1L, "10.0.0.0/9");
1307         Set<Eid> subtreePrefixes = mapService.getSubtree(MappingOrigin.Southbound, queryPrefix);
1308         LOG.debug("Subtree prefix set for EID {}: {}", LispAddressStringifier.getString(queryPrefix),
1309                 LispAddressStringifier.getString(subtreePrefixes));
1310         Set<Eid> expectedSubtreePrefixes = new HashSet<>();
1311         expectedSubtreePrefixes.add(LispAddressUtil.asIpv4PrefixBinaryEid(1L, "10.0.0.0/16"));
1312         expectedSubtreePrefixes.add(LispAddressUtil.asIpv4PrefixBinaryEid(1L, "10.2.0.0/16"));
1313         assertEquals(expectedSubtreePrefixes, subtreePrefixes);
1314     }
1315
1316     private void insertMappings() {
1317         cleanUP();
1318         allowNullAuthenticationForAllIPv4(1L);
1319         mapService.setLookupPolicy(IMappingService.LookupPolicy.NB_AND_SB);
1320
1321         insertNBMappings(1L, "1.2.0.0/16", "1.1.128.0/17");
1322         insertSBMappings(false, 1L, "1.1.32.0/19", "1.0.0.0/8");
1323
1324         restartSocket();
1325         sleepForSeconds(2);
1326     }
1327
1328     private void insertNBMappings(long iid, String ... prefixes) {
1329         LOG.debug("Adding Northbound mappings in VNI {} for prefixes: {}", iid, prefixes);
1330         final InstanceIdType iiType = new InstanceIdType(iid);
1331         for (String prefix : prefixes) {
1332             MappingRecord record = newMappingRecord(prefix, iiType);
1333             mapService.addMapping(MappingOrigin.Northbound, record.getEid(), null, new MappingData(record));
1334         }
1335         sleepForMilliseconds(100);
1336         MappingServiceIntegrationTestUtil.printMapCacheState(mapService);
1337     }
1338
1339     private void removeNBMapping(long iid, String prefix) {
1340         LOG.debug("Removing Northbound mapping in VNI {} for prefix {}", iid, prefix);
1341         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid(iid, prefix);
1342         mapService.removeMapping(MappingOrigin.Northbound, eid);
1343     }
1344
1345     private void insertNBMapping(long iid, String prefix, String ... locators) {
1346         LOG.debug("Adding Northbound mapping in VNI {} for prefix {}, locators {}", iid, prefix, locators);
1347         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid(iid, prefix);
1348         List<Rloc> rlocs = new ArrayList<>();
1349         for (String locator : locators) {
1350             rlocs.add(LispAddressUtil.asIpv4Rloc(locator));
1351         }
1352         insertNBMapping(eid, rlocs);
1353     }
1354
1355     private void insertNBMappingSourceDest(long iid, String src, String dst, String locator) {
1356         String srcAddress = MaskUtil.getPrefixAddress(src);
1357         String dstAddress = MaskUtil.getPrefixAddress(dst);
1358         int srcMask = Integer.parseInt(MaskUtil.getPrefixMask(src));
1359         int dstMask = Integer.parseInt(MaskUtil.getPrefixMask(dst));
1360         LOG.debug("Adding Northbound mapping in VNI {} for prefix {}|{}, locator {}", iid, src, dst, locator);
1361         Eid eid = LispAddressUtil.asSrcDstEid(srcAddress, dstAddress, srcMask, dstMask, iid);
1362         List<Rloc> rlocs = Arrays.asList(LispAddressUtil.asIpv4Rloc(locator));
1363         insertNBMapping(eid, rlocs);
1364     }
1365
1366     private void insertNBMapping(Eid eid, List<Rloc> rlocs) {
1367         MappingRecord record = MappingServiceIntegrationTestUtil.getDefaultMappingRecordBuilder(eid, rlocs).build();
1368         mapService.addMapping(MappingOrigin.Northbound, record.getEid(), null, new MappingData(record));
1369         sleepForMilliseconds(100);
1370         MappingServiceIntegrationTestUtil.printMapCacheState(mapService);
1371     }
1372
1373     private void allowNullAuthenticationForAllIPv4(long iid) {
1374         final InstanceIdType iiType = new InstanceIdType(iid);
1375         Eid allIPs = LispAddressUtil.asIpv4PrefixBinaryEid("0.0.0.0/0", iiType);
1376         mapService.addAuthenticationKey(allIPs, NULL_AUTH_KEY);
1377     }
1378
1379     private void insertSBMappings(boolean negative, long iid, String... prefixes) {
1380         LOG.debug("Adding Southbound mappings in VNI {} for prefixes: {}", iid, prefixes);
1381         final InstanceIdType iiType = new InstanceIdType(iid);
1382
1383         for (String prefix : prefixes) {
1384             MappingRecord record;
1385             if (negative) {
1386                 record = newMappingRecordNegative(prefix, iiType);
1387             } else {
1388                 record = newMappingRecord(prefix, iiType);
1389             }
1390             mapService.addMapping(MappingOrigin.Southbound, record.getEid(), null,
1391                     new MappingData(record, System.currentTimeMillis()));
1392         }
1393         MappingServiceIntegrationTestUtil.printMapCacheState(mapService);
1394     }
1395
1396     private void registerSBMapping(long iid, String prefix, String locator) {
1397         LOG.debug("Registering Southbound mapping in VNI {} for prefix {}, locator {}" +
1398                 " via simulated Map-Register a.k.a. handleMapRegister()", iid, prefix, locator);
1399
1400         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid(iid, prefix);
1401         Rloc rloc = LispAddressUtil.asIpv4Rloc(locator);
1402         MapRegister mr = MappingServiceIntegrationTestUtil.getDefaultMapRegisterBuilder(eid, rloc).build();
1403         lms.handleMapRegister(mr);
1404         sleepForMilliseconds(100);
1405         MappingServiceIntegrationTestUtil.printMapCacheState(mapService);
1406     }
1407
1408     private void removeSBMapping(long iid, String prefix) {
1409         LOG.debug("Removing Southbound mapping in VNI {} for prefix {}", iid, prefix);
1410         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid(iid, prefix);
1411         mapService.removeMapping(MappingOrigin.Southbound, eid);
1412     }
1413
1414     private MappingRecord newMappingRecord(String prefix, InstanceIdType iid) {
1415         final Eid prefixBinary = LispAddressUtil.asIpv4PrefixBinaryEid(prefix, iid);
1416         return MappingServiceIntegrationTestUtil.getDefaultMappingRecordBuilder(prefixBinary).build();
1417     }
1418
1419     private MappingRecord newMappingRecordNegative(String prefix, InstanceIdType iid) {
1420         final Eid prefixBinary = LispAddressUtil.asIpv4PrefixBinaryEid(prefix, iid);
1421         return MappingServiceIntegrationTestUtil.getDefaultMappingRecordBuilder(prefixBinary, (List<Rloc>) null)
1422                 .setAction(Action.NativelyForward).build();
1423     }
1424
1425     private MapRequest newMapRequest(long iid, String prefix) {
1426         final Eid prefixBinary = LispAddressUtil.asIpv4PrefixBinaryEid(prefix, new InstanceIdType(iid));
1427         return MappingServiceIntegrationTestUtil.getDefaultMapRequestBuilder(prefixBinary).build();
1428     }
1429
1430     /**
1431      * TEST SCENARIO A
1432      */
1433     public void testMultiSiteScenarioA() throws IOException {
1434         cleanUP();
1435         ConfigIni.getInstance().setSmrRetryCount(1);
1436         ConfigIni.getInstance().setSmrTimeout(30000L);
1437
1438         final MultiSiteScenario multiSiteScenario = new MultiSiteScenario(mapService, lms);
1439         multiSiteScenario.setCommonAuthentication();
1440
1441         restartSocket();
1442         final SocketReader socketReader = SocketReader.startReadingInStandaloneThread(socket);
1443
1444         //TEST CASE 1
1445         multiSiteScenario.storeSouthboundMappings(false, SITE_A, SITE_B, SITE_C, SITE_D4, SITE_D5);
1446         multiSiteScenario.storeNorthMappingSrcDst(SITE_B, SITE_C);
1447         multiSiteScenario.storeNorthMappingNegative(SITE_C_NEGATIVE, Action.Drop);
1448         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1449         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_B, 4);
1450         multiSiteScenario.assertPingWorks(SITE_B, 5, SITE_C, 4);
1451         multiSiteScenario.assertPingFails(SITE_A, 1, SITE_C, 4);
1452
1453         //TEST CASE 2
1454         //following action should trigger generating of SMR messages:
1455         // 1) 192.0.2.5/32
1456         // 2) 192.0.1.1/32
1457         multiSiteScenario.storeNorthMappingSrcDst(SITE_A, SITE_C);
1458         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1459         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B.getHost(5), SITE_A.getHost(1));
1460         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_C, 4);
1461         multiSiteScenario.assertPingWorks(SITE_B, 5, SITE_C, 4);
1462         multiSiteScenario.assertPingFails(SITE_D4, 5, SITE_C, 4);
1463
1464         //TEST CASE 3
1465         // following action should trigger generating of SMR messages:
1466         // 1) 192.0.2.5/32
1467         // 2) 192.0.1.1/32
1468         // 3) 192.0.1.5/32
1469         // 4) 192.0.4.5/32
1470         multiSiteScenario.deleteNorthMappingNegative(SITE_C);
1471         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1472         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B.getHost(5), SITE_A.getHost(1), SITE_A
1473                         .getHost(5),
1474                 SITE_D4.getHost(5));
1475         multiSiteScenario.assertPingWorks(SITE_D4, 5, SITE_C, 4);
1476
1477         //TEST CASE 4
1478         // following action should trigger generating of SMR messages:
1479         // 1) 192.0.2.5/32
1480         // 2) 192.0.1.1/32
1481         // 3) 192.0.1.5/32
1482         // 4) 192.0.4.5/32
1483         multiSiteScenario.storeNorthMappingSrcDst(SITE_B, SITE_C_RLOC_10);
1484         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1485         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B.getHost(5), SITE_A.getHost(1),
1486                 SITE_A.getHost(5), SITE_D4.getHost(5));
1487         //way of testing ping - get RLOC for mapping src-dst and compare it with awaited value doesn't test
1488         //that ping won't be successfull
1489         multiSiteScenario.assertPingFails(SITE_B, 5, SITE_C, 4);
1490
1491         //TEST CASE 5
1492         // following action should trigger generating of SMR messages:
1493         // 1) 192.0.2.5/32
1494         // 2) 192.0.1.1/32
1495         // 3) 192.0.1.5/32
1496         // 4) 192.0.4.5/32
1497         multiSiteScenario.storeNorthMappingNegative(SITE_C, Action.Drop);
1498         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1499         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B.getHost(5), SITE_A.getHost(1),
1500                 SITE_A.getHost(5), SITE_D4.getHost(5));
1501         multiSiteScenario.assertPingFails(SITE_D4, 5, SITE_C, 4);
1502
1503         //TEST CASE 6
1504         multiSiteScenario.assertPingFails(SITE_D5, 5, SITE_C, 3);
1505
1506         //TEST CASE 7
1507         // following action should trigger generating of SMR messages:
1508         // 1) 192.0.4.5/32
1509         // 2) 192.0.2.5/32
1510         // 3) 192.0.5.5/32
1511         // 4) 192.0.1.5/32
1512         // 5) 192.0.1.1/32
1513         multiSiteScenario.deleteNorthMapingSrcDst(SITE_A, SITE_C);
1514         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1515         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_D5.getHost(5), SITE_D4.getHost(5),
1516                 SITE_B.getHost(5), SITE_A.getHost(1), SITE_A.getHost(5));
1517
1518         // following action should trigger generating of SMR messages:
1519         // 1) 192.0.4.5/32
1520         // 2) 192.0.2.5/32
1521         // 3) 192.0.5.5/32
1522         // 4) 192.0.1.5/32
1523         // 5) 192.0.1.1/32
1524         multiSiteScenario.storeNorthMappingSrcDst(SITE_B, SITE_C);
1525         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1526         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_D5.getHost(5), SITE_D4.getHost(5),
1527                 SITE_B.getHost(5), SITE_A.getHost(1), SITE_A.getHost(5));
1528
1529         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_B, 4);
1530         multiSiteScenario.assertPingWorks(SITE_B, 5, SITE_C, 4);
1531         multiSiteScenario.assertPingFails(SITE_A, 1, SITE_C, 4);
1532
1533         //TEST CASE 8
1534         // following action should trigger generating of SMR messages:
1535         // 1) 192.0.4.5/32
1536         // 2) 192.0.2.5/32
1537         // 3) 192.0.5.5/32
1538         // 4) 192.0.1.5/32
1539         // 5) 192.0.1.1/32
1540         multiSiteScenario.deleteNorthMapingSrcDst(SITE_B, SITE_C);
1541         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1542         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_D5.getHost(5), SITE_D4.getHost(5),
1543                 SITE_B.getHost(5), SITE_A.getHost(1), SITE_A.getHost(5));
1544         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_B, 4);
1545         multiSiteScenario.assertPingFails(SITE_B, 5, SITE_C, 4);
1546         multiSiteScenario.assertPingFails(SITE_A, 1, SITE_C, 4);
1547
1548         //TEST CASE 9
1549         // following action should trigger generating of SMR messages:
1550         // 1) 192.0.4.5/32
1551         // 2) 192.0.2.5/32
1552         // 3) 192.0.5.5/32
1553         // 4) 192.0.1.5/32
1554         // 5) 192.0.1.1/32
1555         multiSiteScenario.deleteNorthMappingNegative(SITE_C);
1556         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1557         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_D5.getHost(5), SITE_D4.getHost(5),
1558                 SITE_B.getHost(5), SITE_A.getHost(1), SITE_A.getHost(5));
1559         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_B, 4);
1560         multiSiteScenario.assertPingWorks(SITE_B, 5, SITE_C, 4);
1561         multiSiteScenario.assertPingWorks(SITE_A, 5, SITE_C, 4);
1562
1563         socketReader.stopReading();
1564
1565     }
1566
1567     /**
1568      * TEST SCENARIO B
1569      */
1570     public void testMultiSiteScenarioB() throws IOException {
1571         restartSocket();
1572         cleanUP();
1573
1574         final MultiSiteScenario multiSiteScenario = new MultiSiteScenario(mapService, lms);
1575         multiSiteScenario.setCommonAuthentication();
1576
1577         restartSocket();
1578         final SocketReader socketReader = SocketReader.startReadingInStandaloneThread(socket);
1579
1580         mapService.setLookupPolicy(IMappingService.LookupPolicy.NB_AND_SB);
1581         mapService.setMappingMerge(true);
1582
1583         //TEST CASE 1
1584         multiSiteScenario.storeSouthboundMappings(true, SITE_A_SB, SITE_B_SB, SITE_C_WP_100_1_SB, SITE_D_WP_100_1_SB,
1585                 SITE_E_SB);
1586         multiSiteScenario.storeNorthMappingIpPrefix(SITE_A_SB);
1587         multiSiteScenario.storeNorthMappingIpPrefix(SITE_B_SB);
1588         multiSiteScenario.storeNorthMappingIpPrefix(SITE_C_WP_50_2_SB, SITE_D_WP_50_2_SB);
1589         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1590         multiSiteScenario.assertPingWorks(SITE_A_SB, 5, SITE_C_WP_50_2_SB, 4, SITE_D_WP_50_2_SB);
1591         multiSiteScenario.assertPingWorks(SITE_B_SB, 5, SITE_C_WP_50_2_SB, 4, SITE_D_WP_50_2_SB);
1592
1593         //TEST CASE 2
1594         // following action should trigger generating of SMR messages:
1595         // 1) 192.0.2.5/32
1596         // 2) 192.0.1.5/32
1597         multiSiteScenario.storeNorthMappingSrcDst(SITE_A_SB, SITE_C_WP_50_2_SB, SITE_D_WP_50_2_SB);
1598         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1599         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
1600
1601         // following action should trigger generating of SMR messages:
1602         // 1) 192.0.2.5/32
1603         // 2) 192.0.1.5/32
1604         multiSiteScenario.storeNorthMappingNegative(SITE_C_SB, Action.Drop);
1605         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1606         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
1607
1608         multiSiteScenario.assertPingWorks(SITE_A_SB, 5, SITE_C_WP_50_2_SB, 4, SITE_D_WP_50_2_SB);
1609         multiSiteScenario.assertPingFails(SITE_B_SB, 5, SITE_C_SB, 4);
1610
1611
1612         //TEST CASE 3
1613         // following action should trigger generating of SMR messages:
1614         // 1) 192.0.2.5/32
1615         // 2) 192.0.1.5/32
1616         multiSiteScenario.storeNorthMappingSrcDst(SITE_A_SB, SITE_C_WP_50_2_SB);
1617         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1618         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
1619         multiSiteScenario.assertPingWorks(SITE_A_SB, 5, SITE_C_WP_50_2_SB, 4);
1620
1621         //TEST CASE 4
1622         multiSiteScenario.storeNorthMappingSrcDst(SITE_B_SB, SITE_C_WP_50_2_SB, SITE_D_WP_50_2_SB);
1623         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1624         // following action should trigger generating of SMR messages:
1625         // 1) 192.0.2.5/32
1626         // 2) 192.0.1.5/32
1627         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
1628         multiSiteScenario.assertPingWorks(SITE_B_SB, 5, SITE_C_WP_50_2_SB, 4, SITE_D_WP_50_2_SB);
1629
1630         //TEST CASE 5
1631         multiSiteScenario.deleteSouthboundMappings(SITE_D_DELETE_SB);
1632         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1633         // following action should trigger generating of SMR messages:
1634         // 1) 192.0.2.5/32
1635         // 2) 192.0.1.5/32
1636         //multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
1637
1638         multiSiteScenario.assertPingWorks(SITE_B_SB, 5, SITE_C_WP_50_2_SB, 4);
1639
1640         //TEST CASE 6
1641         multiSiteScenario.deleteNorthMapingSrcDst(SITE_A_SB, SITE_C_WP_50_2_SB);
1642         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1643         // following action should trigger generating of SMR messages:
1644         // 1) 192.0.2.5/32
1645         // 2) 192.0.1.5/32
1646         multiSiteScenario.checkSMR(socketReader, SITE_C.getEidPrefix(), SITE_B_SB.getHost(5), SITE_A_SB.getHost(5));
1647
1648         multiSiteScenario.deleteNorthMapingSrcDst(SITE_B_SB, SITE_C_WP_50_2_SB);
1649         sleepForSeconds(MULTI_SITE_SLEEP_TIME);
1650         multiSiteScenario.assertPingFails(SITE_B_SB, 5, SITE_C_WP_50_2_SB, 4);
1651
1652         socketReader.stopReading();
1653
1654     }
1655
1656     // ------------------------------- Simple Tests ---------------------------
1657
1658     public void mapRequestSimple() throws SocketTimeoutException {
1659         cleanUP();
1660
1661         // This Map-Request is sent from a source port different from 4342
1662         // We close and bind the socket on the correct port
1663         if (socket != null) {
1664             socket.close();
1665         }
1666         socket = MappingServiceIntegrationTestUtil.initSocket(56756);
1667
1668         sendPacket(mapRequestPacket);
1669         MapReply reply = receiveMapReply();
1670         assertEquals(4435248268955932168L, reply.getNonce().longValue());
1671         restartSocket();
1672     }
1673
1674     public void mapRegisterWithMapNotify() throws SocketTimeoutException {
1675         cleanUP();
1676         mapService.addAuthenticationKey(LispAddressUtil.asIpv4PrefixBinaryEid("153.16.254.1/32"), NULL_AUTH_KEY);
1677
1678         sleepForSeconds(2);
1679         sendPacket(mapRegisterPacketWithNotify);
1680         MapNotify reply = receiveMapNotify();
1681         assertEquals(7, reply.getNonce().longValue());
1682     }
1683
1684     public void mapRegisterWithMapNotifyAndMapRequest() throws SocketTimeoutException {
1685         cleanUP();
1686         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
1687
1688         MapReply mapReply = registerAddressAndQuery(eid);
1689
1690         assertEquals(4, mapReply.getNonce().longValue());
1691         assertEquals(MappingServiceIntegrationTestUtil.DEFAULT_IPV4_RLOC,
1692                 mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0).getRloc());
1693
1694     }
1695
1696     public void registerAndQuery__MAC() throws SocketTimeoutException {
1697         cleanUP();
1698         String macAddress = "01:02:03:04:05:06";
1699
1700         MapReply reply = registerAddressAndQuery(LispAddressUtil.asMacEid(macAddress));
1701
1702         assertTrue(true);
1703         Eid addressFromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
1704         assertEquals(MacAfi.class, addressFromNetwork.getAddressType());
1705         String macAddressFromReply = ((Mac) addressFromNetwork.getAddress()).getMac().getValue();
1706
1707         assertEquals(macAddress, macAddressFromReply);
1708     }
1709
1710     public void mapRequestMapRegisterAndMapRequest() throws SocketTimeoutException {
1711         cleanUP();
1712         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
1713         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
1714         sleepForSeconds(1);
1715
1716         MapRequest mapRequest = MappingServiceIntegrationTestUtil.getDefaultMapRequestBuilder(eid).build();
1717         sendMapRequest(mapRequest);
1718         MapReply mapReply = receiveMapReply();
1719         assertEquals(4, mapReply.getNonce().longValue());
1720         assertEquals(0, mapReply.getMappingRecordItem().get(0).getMappingRecord().nonnullLocatorRecord().size());
1721         MapRegister mapRegister = MappingServiceIntegrationTestUtil.getDefaultMapRegisterBuilder(eid).build();
1722         sendMapRegister(mapRegister);
1723         MapNotify mapNotify = receiveMapNotify();
1724         assertEquals(8, mapNotify.getNonce().longValue());
1725         sleepForSeconds(1);
1726         sendMapRequest(mapRequest);
1727         mapReply = receiveMapReply();
1728         assertEquals(4, mapReply.getNonce().longValue());
1729         assertEquals(MappingServiceIntegrationTestUtil.DEFAULT_IPV4_RLOC,
1730                 mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0).getRloc());
1731
1732     }
1733
1734     public void testMapRegisterDosntOverwritesOtherSubKeys() throws SocketTimeoutException {
1735         cleanUP();
1736         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
1737         SimpleAddress rloc1Value = new SimpleAddress(new IpAddress(new Ipv4Address("4.3.2.1")));
1738         Rloc rloc1 = LispAddressUtil.asKeyValueAddress("subkey1", rloc1Value);
1739         SimpleAddress rloc2Value = new SimpleAddress(new IpAddress(new Ipv4Address("4.3.2.2")));
1740         Rloc rloc2 = LispAddressUtil.asKeyValueAddress("subkey2", rloc2Value);
1741         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1, rloc2);
1742         assertEquals(2, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
1743         assertEquals(rloc2, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
1744                 .getRloc());
1745         assertEquals(rloc1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(1)
1746                 .getRloc());
1747     }
1748
1749     public void testMapRegisterOverwritesSameSubkey() throws SocketTimeoutException {
1750         cleanUP();
1751         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
1752         SimpleAddress rloc1Value = new SimpleAddress(new IpAddress(new Ipv4Address("4.3.2.1")));
1753         Rloc rloc1 = LispAddressUtil.asKeyValueAddress("subkey1", rloc1Value);
1754         SimpleAddress rloc2Value = new SimpleAddress(new IpAddress(new Ipv4Address("4.3.2.2")));
1755         Rloc rloc2 = LispAddressUtil.asKeyValueAddress("subkey2", rloc2Value);
1756         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1, rloc2);
1757         assertEquals(1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
1758         assertEquals(rloc2, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
1759                 .getRloc());
1760     }
1761
1762     public void testMapRegisterOverwritesNoSubkey() throws SocketTimeoutException {
1763         cleanUP();
1764         mapService.setMappingMerge(false);
1765         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
1766         Rloc rloc1Value = LispAddressUtil.asIpv4Rloc("4.3.2.1");
1767         Rloc rloc2Value = LispAddressUtil.asIpv4Rloc("4.3.2.2");
1768         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1Value, rloc2Value);
1769         assertEquals(1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
1770         assertEquals(rloc2Value, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
1771                 .getRloc());
1772     }
1773
1774     public void testMapRegisterDoesntOverwritesNoSubkey() throws SocketTimeoutException {
1775         cleanUP();
1776         mapService.setMappingMerge(true);
1777         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
1778         Rloc rloc1Value = LispAddressUtil.asIpv4Rloc("4.3.2.1");
1779         Rloc rloc2Value = LispAddressUtil.asIpv4Rloc("4.3.2.2");
1780         MapReply mapReply = sendMapRegisterTwiceWithDiffrentValues(eid, rloc1Value, rloc2Value);
1781         assertEquals(1, mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().size());
1782         Rloc rloc1ReturnValueContainer = mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord()
1783                 .get(0).getRloc();
1784         Rloc rloc2ReturnValueContainer = mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord()
1785                 .get(1).getRloc();
1786         assertTrue((rloc1Value.equals(rloc1ReturnValueContainer) && rloc2Value.equals(rloc2ReturnValueContainer))
1787                 || (rloc1Value.equals(rloc2ReturnValueContainer) && rloc2Value.equals(rloc1ReturnValueContainer)));
1788     }
1789
1790     private MapReply sendMapRegisterTwiceWithDiffrentValues(Eid eid, Rloc rloc1, Rloc rloc2)
1791             throws SocketTimeoutException {
1792         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
1793         sleepForSeconds(1);
1794         MapRegister mb = createMapRegister(eid, rloc1);
1795         MapNotify mapNotify = lms.handleMapRegister(mb).getLeft();
1796         MapRequest mr = createMapRequest(eid);
1797         MapReply mapReply = lms.handleMapRequest(mr);
1798         assertEquals(mb.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0).getRloc(),
1799                 mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0).getRloc());
1800         mb = createMapRegister(eid, rloc2);
1801         mapNotify = lms.handleMapRegister(mb).getLeft();
1802         assertEquals(8, mapNotify.getNonce().longValue());
1803         mr = createMapRequest(eid);
1804         sendMapRequest(mr);
1805         mapReply = lms.handleMapRequest(mr);
1806         return mapReply;
1807     }
1808
1809     public void mapRegisterWithAuthenticationWithoutConfiguringAKey() throws SocketTimeoutException {
1810         cleanUP();
1811         sendPacket(mapRegisterPacketWithAuthenticationAndMapNotify);
1812         try {
1813             receivePacket(3000);
1814             // If didn't timeout then fail:
1815             fail();
1816         } catch (SocketTimeoutException ste) {
1817         }
1818     }
1819
1820     public void mapRegisterWithoutMapNotify() {
1821         cleanUP();
1822         sendPacket(mapRegisterPacketWithoutNotify);
1823         try {
1824             receivePacket(3000);
1825             // If didn't timeout then fail:
1826             fail();
1827         } catch (SocketTimeoutException ste) {
1828         }
1829     }
1830
1831     public void registerQueryRegisterWithSmr() throws SocketTimeoutException {
1832         cleanUP();
1833         lms.setShouldUseSmr(true);
1834         mapService.addAuthenticationKey(LispAddressUtil.asIpv4PrefixBinaryEid("153.16.254.1/32"), NULL_AUTH_KEY);
1835         sleepForSeconds(1);
1836
1837         sendPacket(mapRegisterPacketWithNotify);
1838         receiveMapNotify();
1839
1840         sleepForSeconds(1);
1841         sendPacket(mapRequestPacket);
1842         sleepForSeconds(1);
1843
1844         mapRegisterPacketWithoutNotify[mapRegisterPacketWithoutNotify.length - 1] += 1;
1845         sendPacket(mapRegisterPacketWithoutNotify);
1846
1847         MapRequest smr = receiveMapRequest();
1848         assertTrue(smr.getSmr());
1849         Eid sourceEid = smr.getSourceEid().getEid();
1850         assertTrue(LispAddressUtil.asIpv4Eid("153.16.254.1").equals(sourceEid));
1851         Eid smrEid = smr.getEidItem().get(0).getEid();
1852         assertTrue(LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32").equals(smrEid));
1853     }
1854
1855     // --------------------- Northbound Tests ---------------------------
1856 /*
1857     private void northboundAddKey() throws Exception {
1858         cleanUP();
1859         LispIpv4Address address = LispAddressUtil.asIPAfiAddress("1.2.3.4");
1860         int mask = 32;
1861         String pass = "asdf";
1862
1863         URL url = createPutURL("key");
1864         String authKeyJSON = createAuthKeyJSON(pass, address, mask);
1865         callURL("PUT", "application/json", "text/plain", authKeyJSON, url);
1866
1867         String retrievedKey = lms.getAuthenticationKey(LispAddressUtil.toContainer(address), mask);
1868
1869         // Check stored password matches the one sent
1870         assertEquals(pass, retrievedKey);
1871
1872     }
1873
1874     private void northboundRetrieveSourceDestKey() throws Exception {
1875         cleanUP();
1876         org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispsimpleaddress.primitiveaddress.Ipv4
1877                 address1 = (org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev150820.lispsimpleaddress
1878                 .primitiveaddress.Ipv4) LispAddressUtil
1879                 .toPrimitive(LispAddressUtil.asIPAfiAddress("10.0.0.1"));
1880         org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispsimpleaddress.primitiveaddress.Ipv4
1881                 address2 = (org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev150820.lispsimpleaddress
1882                 .primitiveaddress.Ipv4) LispAddressUtil
1883                 .toPrimitive(LispAddressUtil.asIPAfiAddress("10.0.0.2"));
1884         int mask1 = 32;
1885         int mask2 = 32;
1886         LcafSourceDestAddr sourceDestAddress = new LcafSourceDestAddrBuilder().setAfi(
1887                 AddressFamilyNumberEnum.LCAF.getIanaCode())
1888                 .setLcafType((short) LispCanonicalAddressFormatEnum.SOURCE_DEST.getLispCode())
1889                 .setSrcAddress(new SrcAddressBuilder().setPrimitiveAddress(address1).build())
1890                 .setSrcMaskLength((short) mask1)
1891                 .setDstAddress(new DstAddressBuilder().setPrimitiveAddress(address2).build())
1892                 .setDstMaskLength((short) mask2).build();
1893         String pass = "asdf";
1894
1895         lms.addAuthenticationKey(LispAddressUtil.toContainer(sourceDestAddress), mask1, pass);
1896
1897         // URL url = createGetKeyIPv4URL(address1, mask1);
1898         URL url = createGetKeySourceDestURL(address1.getIpv4Address().getAfi(),
1899                 ((LispIpv4Address) LispAddressUtil.toAFIfromPrimitive(sourceDestAddress.getSrcAddress()
1900                 .getPrimitiveAddress())).getIpv4Address().getValue(), sourceDestAddress.getSrcMaskLength(),
1901                 ((LispIpv4Address) LispAddressUtil.toAFIfromPrimitive(sourceDestAddress.getDstAddress()
1902                 .getPrimitiveAddress())).getIpv4Address().getValue(), sourceDestAddress.getDstMaskLength());
1903         String reply = callURL("GET", null, "application/json", null, url);
1904         JSONTokener jt = new JSONTokener(reply);
1905         JSONObject json = new JSONObject(jt);
1906
1907         // test that the password matches what was we expected.
1908         assertEquals(pass, json.get("key"));
1909
1910     }
1911
1912     private void northboundRetrieveKey() throws Exception {
1913         cleanUP();
1914         LispIpv4Address address = LispAddressUtil.asIPAfiAddress("10.0.0.1");
1915         int mask = 32;
1916         String pass = "asdf";
1917
1918         lms.addAuthenticationKey(LispAddressUtil.toContainer(address), mask, pass);
1919
1920         URL url = createGetKeyIPv4URL(address, mask);
1921         String reply = callURL("GET", null, "application/json", null, url);
1922         JSONTokener jt = new JSONTokener(reply);
1923         JSONObject json = new JSONObject(jt);
1924
1925         // test that the password matches what was we expected.
1926         assertEquals(pass, json.get("key"));
1927
1928     }
1929
1930     private String createAuthKeyJSON(String key, LispIpv4Address address, int mask) {
1931         return "{\"key\" : \"" + key + "\",\"maskLength\" : " + mask + ",\"address\" : " + "{\"ipAddress\" : \""
1932                 + address.getIpv4Address().getValue() + "\",\"afi\" : " + address.getAfi().shortValue() + "}}";
1933     }
1934
1935     private void northboundAddMapping() throws Exception {
1936         cleanUP();
1937         String pass = "asdf";
1938         LispIpv4Address eid = LispAddressUtil.asIPAfiAddress("10.0.0.1");
1939         int mask = 32;
1940         LispIpv4Address rloc = LispAddressUtil.asIPAfiAddress("20.0.0.2");
1941
1942         // NB add mapping always checks the key
1943         lms.addAuthenticationKey(LispAddressUtil.toContainer(eid), mask, pass);
1944
1945         URL url = createPutURL("mapping");
1946         String mapRegisterJSON = createMapRegisterJSON(pass, eid, mask, rloc);
1947         callURL("PUT", "application/json", "text/plain", mapRegisterJSON, url);
1948
1949         // Retrieve the RLOC from the database
1950         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
1951         mapRequestBuilder.setPitr(false);
1952         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
1953         mapRequestBuilder.getEidItem().add(
1954                 new EidRecordBuilder().setMask((short) mask).setLispAddressContainer(
1955                 LispAddressUtil.toContainer(eid)).build());
1956         MapReply mapReply = lms.handleMapRequest(mapRequestBuilder.build());
1957
1958         LispIpv4Address retrievedRloc = (LispIpv4Address) LispAddressUtil.toAFI(
1959                 mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0)
1960                 .getLispAddressContainer());
1961
1962         assertEquals(rloc.getIpv4Address().getValue(), retrievedRloc.getIpv4Address().getValue());
1963
1964     }
1965
1966     private String createMapRegisterJSON(String key, LispIpv4Address eid, int mask, LispIpv4Address rloc) {
1967         String jsonString = "{ " + "\"key\" : \"" + key + "\"," + "\"mapregister\" : " + "{ "
1968                 + "\"proxyMapReply\" : false, "
1969                 + "\"eidToLocatorRecords\" : " + "[ " + "{ " + "\"authoritative\" : true," + "\"prefixGeneric\" : "
1970                 + "{ " + "\"ipAddress\" : \""
1971                 + eid.getIpv4Address().getValue() + "\"," + "\"afi\" : " + eid.getAfi().shortValue() + "},"
1972                 + "\"mapVersion\" : 0,"
1973                 + "\"maskLength\" : " + mask + ", " + "\"action\" : \"NoAction\"," + "\"locators\" : " + "[ " + "{ "
1974                 + "\"multicastPriority\" : 1,"
1975                 + "\"locatorGeneric\" : " + "{ " + "\"ipAddress\" : \"" + rloc.getIpv4Address().getValue() + "\","
1976                 + "\"afi\" : "
1977                 + rloc.getAfi().shortValue() + "}, " + "\"routed\" : true," + "\"multicastWeight\" : 50,"
1978                 + "\"rlocProbed\" : false, "
1979                 + "\"localLocator\" : false, " + "\"priority\" : 1, " + "\"weight\" : 50 " + "} " + "], "
1980                 + "\"recordTtl\" : 100" + "} " + "], "
1981                 + "\"nonce\" : 3," + "\"keyId\" : 0 " + "} " + "}";
1982
1983         return jsonString;
1984     }
1985
1986     private void northboundRetrieveMapping() throws Exception {
1987         cleanUP();
1988         LispIpv4Address eid = LispAddressUtil.asIPAfiAddress("10.0.0.1");
1989         int mask = 32;
1990         LispIpv4Address rloc = LispAddressUtil.asIPAfiAddress("20.0.0.2");
1991         // Insert mapping in the database
1992         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
1993         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
1994         etlr.setLispAddressContainer(LispAddressUtil.toContainer(eid));
1995         etlr.setMaskLength((short) mask);
1996         etlr.setRecordTtl(254);
1997         etlr.setAuthoritative(false);
1998         etlr.setAction(Action.NoAction);
1999         LocatorRecordBuilder record = new LocatorRecordBuilder();
2000         record.setLispAddressContainer(LispAddressUtil.toContainer(rloc));
2001         record.setRouted(true);
2002         record.setRlocProbed(false);
2003         record.setLocalLocator(false);
2004         record.setPriority((short) 1);
2005         record.setWeight((short) 50);
2006         record.setMulticastPriority((short) 1);
2007         record.setMulticastWeight((short) 1);
2008         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
2009         etlr.getLocatorRecord().add(record.build());
2010         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
2011         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
2012         lms.handleMapRegister(mapRegister.build());
2013
2014         // Get mapping using NB interface. No IID used
2015         URL url = createGetMappingIPv4URL(0, eid, mask);
2016         String reply = callURL("GET", null, "application/json", null, url);
2017         JSONTokener jt = new JSONTokener(reply);
2018         JSONObject json = new JSONObject(jt);
2019
2020         // With just one locator, locators is not a JSONArray
2021         String rlocRetrieved = json.getJSONArray("locators").getJSONObject(0).getJSONObject("locatorGeneric")
2022                 .getString("ipAddress");
2023
2024         assertEquals(rloc.getIpv4Address().getValue(), rlocRetrieved);
2025
2026     }
2027
2028     private void northboundDeleteMapping() throws Exception {
2029         cleanUP();
2030         LispIpv4Address eid = LispAddressUtil.asIPAfiAddress("10.0.0.1");
2031         int mask = 32;
2032         LispIpv4Address rloc = LispAddressUtil.asIPAfiAddress("20.0.0.2");
2033         // Insert mapping in the database
2034         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
2035         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
2036         etlr.setLispAddressContainer(LispAddressUtil.toContainer(eid));
2037         etlr.setMaskLength((short) mask);
2038         etlr.setRecordTtl(254);
2039         etlr.setAuthoritative(false);
2040         etlr.setAction(Action.NoAction);
2041         LocatorRecordBuilder record = new LocatorRecordBuilder();
2042         record.setLispAddressContainer(LispAddressUtil.toContainer(rloc));
2043         record.setRouted(true);
2044         record.setRlocProbed(false);
2045         record.setLocalLocator(false);
2046         record.setPriority((short) 1);
2047         record.setWeight((short) 50);
2048         record.setMulticastPriority((short) 1);
2049         record.setMulticastWeight((short) 1);
2050         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
2051         etlr.getLocatorRecord().add(record.build());
2052         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
2053         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
2054         lms.handleMapRegister(mapRegister.build());
2055
2056         // Delete mapping using NB interface. No IID used
2057         URL url = createDeleteMappingIPv4URL(0, eid, mask);
2058         String reply = callURL("DELETE", null, "application/json", null, url);
2059
2060         // Get mapping using NB interface. No IID used
2061         url = createGetMappingIPv4URL(0, eid, mask);
2062         reply = callURL("GET", null, "application/json", null, url);
2063         JSONTokener jt = new JSONTokener(reply);
2064         JSONObject json = new JSONObject(jt);
2065
2066         // With just one locator, locators is not a JSONArray
2067         assertEquals(json.getJSONArray("locators").length(), 0);
2068     }
2069
2070     private void northboundRetrieveSourceDestMapping() throws Exception {
2071         cleanUP();
2072         org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispsimpleaddress.primitiveaddress.Ipv4
2073                 address1 = (org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev150820.lispsimpleaddress
2074                 .primitiveaddress.Ipv4) LispAddressUtil
2075                 .toPrimitive(LispAddressUtil.asIPAfiAddress("10.0.0.1"));
2076         org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.lispsimpleaddress.primitiveaddress.Ipv4
2077                 address2 = (org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev150820.lispsimpleaddress
2078                 .primitiveaddress.Ipv4) LispAddressUtil
2079                 .toPrimitive(LispAddressUtil.asIPAfiAddress("10.0.0.2"));
2080         int mask1 = 32;
2081         int mask2 = 32;
2082         LcafSourceDestAddr sourceDestAddress = new LcafSourceDestAddrBuilder().setAfi(
2083                 AddressFamilyNumberEnum.LCAF.getIanaCode())
2084                 .setLcafType((short) LispCanonicalAddressFormatEnum.SOURCE_DEST.getLispCode())
2085                 .setSrcAddress(new SrcAddressBuilder().setPrimitiveAddress(
2086                         address1).build()).setSrcMaskLength((short) mask1)
2087                 .setDstAddress(new DstAddressBuilder().setPrimitiveAddress(
2088                         address2).build()).setDstMaskLength((short) mask2).build();
2089         LispIpv4Address rloc = LispAddressUtil.asIPAfiAddress("20.0.0.2");
2090
2091         // Insert mapping in the database
2092         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
2093         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
2094         etlr.setLispAddressContainer(LispAddressUtil.toContainer(sourceDestAddress));
2095         etlr.setMaskLength((short) mask1);
2096         etlr.setRecordTtl(254);
2097         etlr.setAuthoritative(false);
2098         etlr.setAction(Action.NoAction);
2099         LocatorRecordBuilder record = new LocatorRecordBuilder();
2100         record.setLispAddressContainer(LispAddressUtil.toContainer(rloc));
2101         record.setRouted(true);
2102         record.setRlocProbed(false);
2103         record.setLocalLocator(false);
2104         record.setPriority((short) 1);
2105         record.setWeight((short) 50);
2106         record.setMulticastPriority((short) 1);
2107         record.setMulticastWeight((short) 1);
2108         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
2109         etlr.getLocatorRecord().add(record.build());
2110         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
2111         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
2112         lms.handleMapRegister(mapRegister.build());
2113
2114         // Get mapping using NB interface. No IID used
2115         URL url = createGetMappingSourceDestURL(address1.getIpv4Address().getAfi(),
2116                 address1.getIpv4Address().getIpv4Address().getValue(),
2117                 mask1,
2118                 address2.getIpv4Address().getIpv4Address().getValue(),
2119                 mask2);
2120         String reply = callURL("GET", null, "application/json", null, url);
2121         JSONTokener jt = new JSONTokener(reply);
2122         JSONObject json = new JSONObject(jt);
2123
2124         // With just one locator, locators is not a JSONArray
2125         String rlocRetrieved = json.getJSONArray("locators").getJSONObject(0).getJSONObject("locatorGeneric")
2126         .getString("ipAddress");
2127
2128         assertEquals(rloc.getIpv4Address().getValue(), rlocRetrieved);
2129
2130     }
2131
2132     private URL createGetKeyIPv4URL(LispIpv4Address address, int mask) throws MalformedURLException {
2133         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/0/%d/%s/%d", "key",
2134                 address.getAfi().shortValue(),
2135                 address.getIpv4Address().getValue(), mask);
2136         URL url = new URL(restUrl);
2137         return url;
2138     }
2139
2140     private URL createGetKeySourceDestURL(int afi, String srcAddress, int srcMask, String dstAddress, int dstMask)
2141             throws MalformedURLException {
2142         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/0/%d/%s/%d/%s/%d",
2143                 "key", afi, srcAddress, srcMask,
2144                 dstAddress, dstMask);
2145         URL url = new URL(restUrl);
2146         return url;
2147     }
2148
2149     private URL createGetMappingSourceDestURL(int afi, String srcAddress, int srcMask, String dstAddress, int dstMask)
2150             throws MalformedURLException {
2151         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/0/%d/%s/%d/%s/%d",
2152                 "mapping", afi, srcAddress,
2153                 srcMask, dstAddress, dstMask);
2154         URL url = new URL(restUrl);
2155         return url;
2156     }
2157
2158     private URL createGetMappingIPv4URL(int iid, LispIpv4Address address, int mask) throws MalformedURLException {
2159         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/%d/%d/%s/%d", "mapping",
2160                 iid, address.getAfi()
2161                 .shortValue(), address.getIpv4Address().getValue(), mask);
2162         URL url = new URL(restUrl);
2163         return url;
2164     }
2165
2166     private URL createDeleteMappingIPv4URL(int iid, LispIpv4Address address, int mask) throws MalformedURLException {
2167         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s/%d/%d/%s/%d", "mapping",
2168                 iid, address.getAfi()
2169                 .shortValue(), address.getIpv4Address().getValue(), mask);
2170         URL url = new URL(restUrl);
2171         return url;
2172     }
2173
2174     private URL createPutURL(String resource) throws MalformedURLException {
2175
2176         String restUrl = String.format("http://localhost:8080/lispflowmapping/nb/v2/default/%s", resource);
2177
2178         URL url = new URL(restUrl);
2179         return url;
2180     }
2181
2182     private String createAuthenticationString() {
2183         String authString = "admin:admin";
2184         byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
2185         String authStringEnc = new String(authEncBytes);
2186         return authStringEnc;
2187     }
2188
2189     private String callURL(String method, String content, String accept, String body, URL url) throws IOException,
2190             JSONException {
2191         String authStringEnc = createAuthenticationString();
2192         connection = (HttpURLConnection) url.openConnection();
2193         connection.setRequestMethod(method);
2194         connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
2195         if (content != null) {
2196             connection.setRequestProperty("Content-Type", content);
2197         }
2198         if (accept != null) {
2199             connection.setRequestProperty("Accept", accept);
2200         }
2201         if (body != null) {
2202             // now add the request body
2203             connection.setDoOutput(true);
2204             OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
2205             wr.write(body);
2206             wr.flush();
2207         }
2208         connection.connect();
2209
2210         // getting the result, first check response code
2211         Integer httpResponseCode = connection.getResponseCode();
2212
2213         if (httpResponseCode > 299) {
2214             LOG.trace("HTTP Address: " + url);
2215             LOG.trace("HTTP Response Code: " + httpResponseCode);
2216             fail();
2217         }
2218
2219         InputStream is = connection.getInputStream();
2220         BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
2221         StringBuilder sb = new StringBuilder();
2222         int cp;
2223         while ((cp = rd.read()) != -1) {
2224             sb.append((char) cp);
2225         }
2226         is.close();
2227         connection.disconnect();
2228         return (sb.toString());
2229     }
2230
2231     // timePeriod - in ms
2232     public void assertNoPacketReceived(int timePeriod) {
2233         try {
2234             receivePacket(timePeriod);
2235             // If didn't timeout then fail:
2236             fail();
2237         } catch (SocketTimeoutException ste) {
2238         }
2239     }
2240 */
2241     // ------------------------------- Mask Tests ---------------------------
2242
2243     public void eidPrefixLookupIPv4() throws SocketTimeoutException {
2244         cleanUP();
2245         runPrefixTest(LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/16"),
2246                 LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.2/32"),
2247                 LispAddressUtil.asIpv4PrefixBinaryEid("1.1.1.1/32"));
2248     }
2249
2250     public void eidPrefixLookupIPv6() throws SocketTimeoutException {
2251         cleanUP();
2252         runPrefixTest(LispAddressUtil.asIpv6PrefixBinaryEid("1:2:3:4:5:6:7:8/64"),
2253                 LispAddressUtil.asIpv6PrefixBinaryEid("1:2:3:4:5:1:2:3/128"),
2254                 LispAddressUtil.asIpv6PrefixBinaryEid("1:2:3:1:2:3:1:2/128"));
2255     }
2256
2257     private void runPrefixTest(Eid registerEID, Eid matchedAddress, Eid unMatchedAddress)
2258             throws SocketTimeoutException {
2259         mapService.addAuthenticationKey(registerEID, NULL_AUTH_KEY);
2260         sleepForSeconds(1);
2261
2262         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
2263         mapRegister.setWantMapNotify(true);
2264         mapRegister.setNonce((long) 8);
2265         mapRegister.setWantMapNotify(true);
2266         mapRegister.setKeyId((short) 0);
2267         mapRegister.setAuthenticationData(new byte[0]);
2268         mapRegister.setNonce((long) 8);
2269         mapRegister.setProxyMapReply(false);
2270         MappingRecordBuilder etlr = new MappingRecordBuilder();
2271         etlr.setRecordTtl(254);
2272         etlr.setAction(Action.NoAction);
2273         etlr.setAuthoritative(false);
2274         etlr.setMapVersion((short) 0);
2275         etlr.setEid(registerEID);
2276         etlr.setRecordTtl(254);
2277         LocatorRecordBuilder record = new LocatorRecordBuilder();
2278         record.setLocatorId("4.3.2.1");
2279         record.setRloc(LispAddressUtil.asIpv4Rloc("4.3.2.1"));
2280         record.setLocalLocator(false);
2281         record.setRlocProbed(false);
2282         record.setRouted(true);
2283         record.setMulticastPriority(Uint8.valueOf(0));
2284         record.setMulticastWeight(Uint8.valueOf(0));
2285         record.setPriority(Uint8.valueOf(0));
2286         record.setWeight(Uint8.valueOf(0));
2287         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
2288         etlr.getLocatorRecord().add(record.build());
2289         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
2290         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder()
2291                 .setMappingRecordItemId(LispAddressStringifier.getString(registerEID))
2292                 .setMappingRecord(etlr.build()).build());
2293         sendMapRegister(mapRegister.build());
2294         MapNotify mapNotify = receiveMapNotify();
2295         assertEquals(8, mapNotify.getNonce().longValue());
2296         sleepForSeconds(1);
2297         MapRequestBuilder mapRequest = new MapRequestBuilder();
2298         mapRequest.setNonce((long) 4);
2299         mapRequest.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.asIpv4Eid(ourAddress)).build());
2300         mapRequest.setEidItem(new ArrayList<EidItem>());
2301         mapRequest.setAuthoritative(false);
2302         mapRequest.setMapDataPresent(false);
2303         mapRequest.setPitr(false);
2304         mapRequest.setProbe(false);
2305         mapRequest.setSmr(false);
2306         mapRequest.setSmrInvoked(false);
2307         mapRequest.getEidItem().add(new EidItemBuilder()
2308                 .setEidItemId(LispAddressStringifier.getString(matchedAddress))
2309                 .setEid(matchedAddress).build());
2310         mapRequest.setItrRloc(new ArrayList<ItrRloc>());
2311         mapRequest.getItrRloc().add(new ItrRlocBuilder()
2312                 .setItrRlocId(ourAddress)
2313                 .setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
2314         sendMapRequest(mapRequest.build());
2315         MapReply mapReply = receiveMapReply();
2316         assertEquals(4, mapReply.getNonce().longValue());
2317         assertEquals(record.getRloc(), mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord()
2318                 .get(0).getRloc());
2319         mapRequest.setEidItem(new ArrayList<EidItem>());
2320         mapRequest.getEidItem().add(new EidItemBuilder()
2321                 .setEidItemId(LispAddressStringifier.getString(unMatchedAddress))
2322                 .setEid(unMatchedAddress).build());
2323         sendMapRequest(mapRequest.build());
2324         mapReply = receiveMapReply();
2325         assertEquals(0, mapReply.getMappingRecordItem().get(0).getMappingRecord().nonnullLocatorRecord().size());
2326     }
2327 /*
2328     // This registers an IP with a MapRegister, then adds a password via the
2329     // northbound REST API
2330     // and checks that the password works
2331     public void testPasswordExactMatch() throws Exception {
2332         cleanUP();
2333         String ipString = "10.0.0.1";
2334         LispIpv4Address address = LispAddressUtil.asIPAfiAddress(ipString);
2335         int mask = 32;
2336         String pass = "pass";
2337
2338         URL url = createPutURL("key");
2339
2340         String jsonAuthData = createAuthKeyJSON(pass, address, mask);
2341
2342         LOG.trace("Sending this JSON to LISP server: \n" + jsonAuthData);
2343         LOG.trace("Address: " + address);
2344
2345         byte[] expectedSha = new byte[] { (byte) 146, (byte) 234, (byte) 52, (byte) 247, (byte) 186, (byte) 232,
2346                 (byte) 31, (byte) 249, (byte) 87,
2347                 (byte) 73, (byte) 234, (byte) 54, (byte) 225, (byte) 160, (byte) 129, (byte) 251, (byte) 73, (byte) 53,
2348                 (byte) 196, (byte) 62 };
2349
2350         byte[] zeros = new byte[20];
2351
2352         callURL("PUT", "application/json", "text/plain", jsonAuthData, url);
2353
2354         // build a MapRegister
2355         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
2356         mapRegister.setWantMapNotify(true);
2357         mapRegister.setNonce((long) 8);
2358         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
2359         etlr.setLispAddressContainer(LispAddressUtil.toContainer(address));
2360         etlr.setMaskLength((short) mask);
2361         etlr.setRecordTtl(254);
2362         LocatorRecordBuilder record = new LocatorRecordBuilder();
2363         record.setLispAddressContainer(LispAddressUtil.toContainer(locatorEid));
2364         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
2365         etlr.getLocatorRecord().add(record.build());
2366         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
2367         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
2368
2369         mapRegister.setKeyId((short) 1); // LispKeyIDEnum.SHA1.getKeyID()
2370         mapRegister.setAuthenticationData(zeros);
2371
2372         sendMapRegister(mapRegister.build());
2373         assertNoPacketReceived(3000);
2374
2375         mapRegister.setAuthenticationData(expectedSha);
2376
2377         sendMapRegister(mapRegister.build());
2378
2379         assertMapNotifyReceived();
2380     }
2381
2382     public void testPasswordMaskMatch() throws Exception {
2383         cleanUP();
2384         LispIpv4Address addressInRange = LispAddressUtil.asIPAfiAddress("10.20.30.40");
2385         LispIpv4Address addressOutOfRange = LispAddressUtil.asIPAfiAddress("20.40.30.40");
2386         LispIpv4Address range = LispAddressUtil.asIPAfiAddress("10.20.30.0");
2387
2388         int mask = 32;
2389         String pass = "pass";
2390
2391         URL url = createPutURL("key");
2392         String jsonAuthData = createAuthKeyJSON(pass, range, 8);
2393
2394         callURL("PUT", "application/json", "text/plain", jsonAuthData, url);
2395         // build a MapRegister
2396         MapRegisterBuilder mapRegister = new MapRegisterBuilder();
2397
2398         mapRegister.setWantMapNotify(true);
2399         mapRegister.setNonce((long) 8);
2400         EidToLocatorRecordBuilder etlr = new EidToLocatorRecordBuilder();
2401         etlr.setLispAddressContainer(LispAddressUtil.toContainer(addressInRange));
2402         etlr.setMaskLength((short) mask);
2403         etlr.setRecordTtl(254);
2404         LocatorRecordBuilder record = new LocatorRecordBuilder();
2405         record.setLispAddressContainer(LispAddressUtil.toContainer(locatorEid));
2406         record.setLispAddressContainer(LispAddressUtil.toContainer(locatorEid));
2407         etlr.setLocatorRecord(new ArrayList<LocatorRecord>());
2408         etlr.getLocatorRecord().add(record.build());
2409         mapRegister.setMappingRecordItem(new ArrayList<MappingRecordItem>());
2410         mapRegister.getMappingRecordItem().add(new MappingRecordItemBuilder().setMappingRecord(etlr.build()).build());
2411
2412         mapRegister.setKeyId((short) 1); // LispKeyIDEnum.SHA1.getKeyID()
2413         mapRegister
2414                 .setAuthenticationData(new byte[] { -15, -52, 38, -94, 125, -111, -68, -79, 68, 6, 101, 45, -1, 47, -4,
2415                 -67, -113, 104, -110, -71 });
2416
2417         sendMapRegister(mapRegister.build());
2418
2419         assertMapNotifyReceived();
2420
2421         etlr.setLispAddressContainer(LispAddressUtil.toContainer(addressOutOfRange));
2422         mapRegister
2423                 .setAuthenticationData(new byte[] { -54, 68, -58, -91, -23, 22, -88, -31, 113, 39, 115, 78, -68, -123,
2424                 -71, -14, -99, 67, -23, -73 });
2425
2426         sendMapRegister(mapRegister.build());
2427         assertNoPacketReceived(3000);
2428     }
2429 */
2430     // takes an address, packs it in a MapRegister and sends it
2431     private void registerAddress(Eid eid) throws SocketTimeoutException {
2432         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
2433         sleepForSeconds(1);
2434         MapRegister mapRegister = MappingServiceIntegrationTestUtil.getDefaultMapRegisterBuilder(eid).build();
2435         sendMapRegister(mapRegister);
2436         MapNotify mapNotify = receiveMapNotify();
2437         assertEquals(8, mapNotify.getNonce().longValue());
2438     }
2439
2440     private MapReply queryForAddress(Eid eid, String srcEid) throws SocketTimeoutException {
2441         MapRequestBuilder mapRequestBuilder = new MapRequestBuilder();
2442         mapRequestBuilder.setNonce((long) 4);
2443         mapRequestBuilder.setEidItem(new ArrayList<EidItem>());
2444         mapRequestBuilder.getEidItem().add(new EidItemBuilder()
2445                 .setEidItemId(LispAddressStringifier.getString(eid))
2446                 .setEid(eid).build());
2447         mapRequestBuilder.setItrRloc(new ArrayList<ItrRloc>());
2448         if (srcEid != null) {
2449             mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.asIpv4Eid(srcEid)).build());
2450         } else {
2451             mapRequestBuilder.setSourceEid(new SourceEidBuilder().setEid(LispAddressUtil.asIpv4Eid(ourAddress))
2452                     .build());
2453         }
2454         mapRequestBuilder.getItrRloc().add(
2455                 new ItrRlocBuilder()
2456                         .setItrRlocId(ourAddress)
2457                         .setRloc(LispAddressUtil.asIpv4Rloc(ourAddress)).build());
2458         mapRequestBuilder.setAuthoritative(false);
2459         mapRequestBuilder.setMapDataPresent(false);
2460         mapRequestBuilder.setPitr(false);
2461         mapRequestBuilder.setProbe(false);
2462         mapRequestBuilder.setSmr(false);
2463         mapRequestBuilder.setSmrInvoked(false);
2464         sendMapRequest(mapRequestBuilder.build());
2465         return receiveMapReply();
2466     }
2467
2468     // takes an address, packs it in a MapRegister, sends it, returns the
2469     // MapReply
2470     private MapReply registerAddressAndQuery(Eid eid) throws SocketTimeoutException {
2471         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
2472         sleepForSeconds(1);
2473         MapRegister mapRegister = MappingServiceIntegrationTestUtil.getDefaultMapRegisterBuilder(eid).build();
2474         LOG.trace("Sending Map-Register via socket: {}", mapRegister);
2475         sendMapRegister(mapRegister);
2476         MapNotify mapNotify = receiveMapNotify();
2477         LOG.trace("Received Map-Notify via socket: {}", mapNotify);
2478         assertEquals(8, mapNotify.getNonce().longValue());
2479         // wait for the notifications to propagate
2480         sleepForSeconds(1);
2481         MapRequest mapRequest = MappingServiceIntegrationTestUtil.getDefaultMapRequestBuilder(eid).build();
2482         sendMapRequest(mapRequest);
2483         return receiveMapReply();
2484     }
2485
2486     // ------------------------------- LCAF Tests ---------------------------
2487
2488     public void registerAndQuery__SrcDestLCAF() throws SocketTimeoutException {
2489         cleanUP();
2490         String ipPrefix = "10.20.30.200/32";
2491         String macString = "01:02:03:04:05:06";
2492
2493         SourceDestKeyBuilder builder = new SourceDestKeyBuilder();
2494         builder.setSource(new SimpleAddress(new IpPrefix(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
2495                 .ietf.inet.types.rev130715.Ipv4Prefix(ipPrefix))));
2496         builder.setDest(new SimpleAddress(new MacAddress(macString)));
2497
2498         EidBuilder eb = new EidBuilder();
2499         eb.setAddressType(SourceDestKeyLcaf.class);
2500         eb.setVirtualNetworkId(null);
2501         eb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
2502                 .lisp.address.address.SourceDestKeyBuilder().setSourceDestKey(builder.build()).build());
2503
2504         MapReply reply = registerAddressAndQuery(eb.build());
2505
2506         Eid fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
2507         assertEquals(SourceDestKeyLcaf.class, fromNetwork.getAddressType());
2508         SourceDestKey sourceDestFromNetwork = (SourceDestKey) fromNetwork.getAddress();
2509
2510         SimpleAddress receivedAddr1 = sourceDestFromNetwork.getSourceDestKey().getSource();
2511         SimpleAddress receivedAddr2 = sourceDestFromNetwork.getSourceDestKey().getDest();
2512
2513         assertNotNull(receivedAddr1.getIpPrefix().getIpv4Prefix());
2514         assertNotNull(receivedAddr2.getMacAddress());
2515
2516         IpPrefix receivedIP = receivedAddr1.getIpPrefix();
2517         MacAddress receivedMAC = receivedAddr2.getMacAddress();
2518
2519         assertEquals(ipPrefix, receivedIP.getIpv4Prefix().getValue());
2520         assertEquals(macString, receivedMAC.getValue());
2521     }
2522
2523     public void registerAndQuery__SrcDestLCAFOverlap() throws SocketTimeoutException {
2524         cleanUP();
2525         String ipString1 = "10.10.10.0";
2526         String ipString2 = "20.20.20.0";
2527         String ipPrefix1 = ipString1 + "/24";
2528         String ipPrefix2 = ipString2 + "/24";
2529
2530         Eid srcDst = LispAddressUtil.asSrcDstEid(ipString1, ipString2, 24, 24, 0);
2531         registerAddress(LispAddressUtil.asIpv4PrefixBinaryEid(ipPrefix2));
2532         registerAddress(srcDst);
2533
2534         // exact match
2535         MapReply reply = queryForAddress(srcDst, null);
2536
2537         Eid fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
2538         assertEquals(SourceDestKeyLcaf.class, fromNetwork.getAddressType());
2539         SourceDestKey sourceDestFromNetwork = (SourceDestKey) fromNetwork.getAddress();
2540
2541         IpPrefix receivedAddr1 = sourceDestFromNetwork.getSourceDestKey().getSource().getIpPrefix();
2542         IpPrefix receivedAddr2 = sourceDestFromNetwork.getSourceDestKey().getDest().getIpPrefix();
2543
2544         assertNotNull(receivedAddr1.getIpv4Prefix());
2545         assertNotNull(receivedAddr2.getIpv4Prefix());
2546
2547         assertEquals(ipPrefix1, receivedAddr1.getIpv4Prefix().getValue());
2548         assertEquals(ipPrefix2, receivedAddr2.getIpv4Prefix().getValue());
2549
2550         // srcEid/dstEid match
2551         reply = queryForAddress(LispAddressUtil.asIpv4PrefixBinaryEid("20.20.20.1/32"), "10.10.10.1");
2552         fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
2553         assertEquals(Ipv4PrefixBinaryAfi.class, fromNetwork.getAddressType());
2554
2555         assertEquals(LispAddressUtil.asIpv4PrefixBinaryEid(ipPrefix2), fromNetwork);
2556
2557         // dstEid match only
2558         reply = queryForAddress(LispAddressUtil.asIpv4PrefixBinaryEid("20.20.20.1/32"), "1.2.3.4");
2559         fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
2560         assertEquals(Ipv4PrefixBinaryAfi.class, fromNetwork.getAddressType());
2561
2562         assertEquals(LispAddressUtil.asIpv4PrefixBinaryEid(ipPrefix2), fromNetwork);
2563     }
2564
2565     public void registerAndQuery__KeyValueLCAF() throws SocketTimeoutException {
2566         cleanUP();
2567         String ipString = "10.20.30.200";
2568         String macString = "01:02:03:04:05:06";
2569         SimpleAddress addrToSend1 = new SimpleAddress(new IpAddress(new Ipv4Address(ipString)));
2570         SimpleAddress addrToSend2 = new SimpleAddress(new MacAddress(macString));
2571         Eid kv = LispAddressUtil.asKeyValueAddressEid(addrToSend1, addrToSend2);
2572
2573         MapReply reply = registerAddressAndQuery(kv);
2574
2575         Eid fromNetwork = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
2576         assertEquals(KeyValueAddressLcaf.class, fromNetwork.getAddressType());
2577         KeyValueAddress keyValueFromNetwork = (KeyValueAddress) fromNetwork.getAddress();
2578
2579         SimpleAddress receivedAddr1 = keyValueFromNetwork.getKeyValueAddress().getKey();
2580         SimpleAddress receivedAddr2 = keyValueFromNetwork.getKeyValueAddress().getValue();
2581
2582         assertNotNull(receivedAddr1.getIpAddress().getIpv4Address());
2583         assertNotNull(receivedAddr2.getMacAddress());
2584
2585         Ipv4Address receivedIP = receivedAddr1.getIpAddress().getIpv4Address();
2586         MacAddress receivedMAC = receivedAddr2.getMacAddress();
2587
2588         assertEquals(ipString, receivedIP.getValue());
2589         assertEquals(macString, receivedMAC.getValue());
2590     }
2591
2592     public void registerAndQuery__ListLCAF() throws SocketTimeoutException {
2593         cleanUP();
2594         String macString = "01:02:03:04:05:06";
2595         String ipString = "10.20.255.30";
2596         List<SimpleAddress> addresses = new ArrayList<SimpleAddress>();
2597         addresses.add(new SimpleAddress(new IpAddress(new Ipv4Address(ipString))));
2598         addresses.add(new SimpleAddress(new MacAddress(macString)));
2599         AfiListBuilder listbuilder = new AfiListBuilder();
2600         listbuilder.setAddressList(addresses);
2601
2602         EidBuilder eb = new EidBuilder();
2603         eb.setAddressType(AfiListLcaf.class);
2604         eb.setVirtualNetworkId(null);
2605         eb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
2606                 .lisp.address.address.AfiListBuilder().setAfiList(listbuilder.build()).build());
2607
2608         MapReply reply = registerAddressAndQuery(eb.build());
2609
2610         Eid receivedAddress = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
2611
2612         assertEquals(AfiListLcaf.class, receivedAddress.getAddressType());
2613
2614         AfiList listAddrFromNetwork = (AfiList) receivedAddress.getAddress();
2615         SimpleAddress receivedAddr1 = (SimpleAddress) listAddrFromNetwork.getAfiList().getAddressList().get(0);
2616         SimpleAddress receivedAddr2 = (SimpleAddress) listAddrFromNetwork.getAfiList().getAddressList().get(1);
2617
2618         assertNotNull(receivedAddr1.getIpAddress().getIpv4Address());
2619         assertNotNull(receivedAddr2.getMacAddress());
2620
2621         assertEquals(macString, receivedAddr2.getMacAddress().getValue());
2622         assertEquals(ipString, receivedAddr1.getIpAddress().getIpv4Address().getValue());
2623     }
2624
2625     public void registerAndQuery__SegmentLCAF() throws SocketTimeoutException {
2626         cleanUP();
2627         String ipString = "10.20.255.30";
2628         int instanceId = 6;
2629
2630         EidBuilder eb = new EidBuilder();
2631         eb.setAddressType(Ipv4PrefixAfi.class);
2632         eb.setVirtualNetworkId(new InstanceIdType((long) instanceId));
2633         eb.setAddress(new Ipv4PrefixBuilder().setIpv4Prefix(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns
2634                 .yang.ietf.inet.types.rev130715.Ipv4Prefix(ipString)).build());
2635
2636         MapReply reply = registerAddressAndQuery(eb.build());
2637
2638         Eid receivedAddress = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
2639         assertEquals(Ipv4PrefixAfi.class, receivedAddress.getAddressType());
2640
2641         assertEquals(ipString, ((Ipv4Prefix) receivedAddress.getAddress()).getIpv4Prefix().getValue());
2642
2643         assertEquals(instanceId, receivedAddress.getVirtualNetworkId().getValue().intValue());
2644     }
2645
2646     public void registerAndQuery__TrafficEngineering() throws SocketTimeoutException {
2647         cleanUP();
2648         String macString = "01:02:03:04:05:06";
2649         String ipString = "10.20.255.30";
2650         HopBuilder hopBuilder = new HopBuilder();
2651         hopBuilder.setAddress(new SimpleAddress(new IpAddress(new Ipv4Address(ipString))));
2652         hopBuilder.setLrsBits(new LrsBits(true, false, true));
2653         Hop hop1 = hopBuilder.build();
2654         hopBuilder.setAddress(new SimpleAddress(new MacAddress(macString)));
2655         hopBuilder.setLrsBits(new LrsBits(false, true, false));
2656         Hop hop2 = hopBuilder.build();
2657         ExplicitLocatorPathBuilder elpBuilder = new ExplicitLocatorPathBuilder();
2658         elpBuilder.setHop(new ArrayList<Hop>());
2659         elpBuilder.getHop().add(hop1);
2660         elpBuilder.getHop().add(hop2);
2661
2662         EidBuilder eb = new EidBuilder();
2663         eb.setAddressType(ExplicitLocatorPathLcaf.class);
2664         eb.setVirtualNetworkId(null);
2665         eb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
2666                 .lisp.address.address.ExplicitLocatorPathBuilder().setExplicitLocatorPath(elpBuilder.build()).build());
2667
2668         MapReply reply = registerAddressAndQuery(eb.build());
2669
2670         assertEquals(ExplicitLocatorPathLcaf.class, reply.getMappingRecordItem().get(0).getMappingRecord().getEid()
2671                 .getAddressType());
2672
2673         ExplicitLocatorPath receivedAddress = (ExplicitLocatorPath) reply.getMappingRecordItem().get(0)
2674                 .getMappingRecord().getEid().getAddress();
2675
2676         Hop receivedHop1 = (Hop) receivedAddress.getExplicitLocatorPath().getHop().get(0);
2677         Hop receivedHop2 = (Hop) receivedAddress.getExplicitLocatorPath().getHop().get(1);
2678
2679         assertEquals(true, receivedHop1.getLrsBits().getLookup());
2680         assertEquals(false, receivedHop1.getLrsBits().getRlocProbe());
2681         assertEquals(true, receivedHop1.getLrsBits().getStrict());
2682
2683         assertEquals(false, receivedHop2.getLrsBits().getLookup());
2684         assertEquals(true, receivedHop2.getLrsBits().getRlocProbe());
2685         assertEquals(false, receivedHop2.getLrsBits().getStrict());
2686
2687         assertNotNull(receivedHop1.getAddress().getIpAddress().getIpv4Address());
2688         assertNotNull(receivedHop2.getAddress().getMacAddress());
2689
2690         assertEquals(ipString, receivedHop1.getAddress().getIpAddress().getIpv4Address().getValue());
2691         assertEquals(macString, receivedHop2.getAddress().getMacAddress().getValue());
2692     }
2693
2694     public void registerAndQuery__ApplicationData() throws SocketTimeoutException {
2695         cleanUP();
2696         String ipString = "1.2.3.4";
2697         short protocol = 1;
2698         int ipTOs = 2;
2699         int localPortLow = 3;
2700         int localPortHigh = 4;
2701         int remotePortLow = 4;
2702         int remotePortHigh = 5;
2703
2704         ApplicationDataBuilder builder = new ApplicationDataBuilder();
2705         builder.setIpTos(ipTOs);
2706         builder.setProtocol(protocol);
2707         builder.setLocalPortLow(new PortNumber(localPortLow));
2708         builder.setLocalPortHigh(new PortNumber(localPortHigh));
2709         builder.setRemotePortLow(new PortNumber(remotePortLow));
2710         builder.setRemotePortHigh(new PortNumber(remotePortHigh));
2711         builder.setAddress(new SimpleAddress(new IpAddress(new Ipv4Address(ipString))));
2712
2713         EidBuilder eb = new EidBuilder();
2714         eb.setAddressType(ApplicationDataLcaf.class);
2715         eb.setVirtualNetworkId(null);
2716         eb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
2717                 .lisp.address.address.ApplicationDataBuilder().setApplicationData(builder.build()).build());
2718         Eid addressToSend = eb.build();
2719
2720         MapReply reply = registerAddressAndQuery(addressToSend);
2721
2722         Eid receivedAddress = reply.getMappingRecordItem().get(0).getMappingRecord().getEid();
2723
2724         assertEquals(ApplicationDataLcaf.class, receivedAddress.getAddressType());
2725
2726         ApplicationData receivedApplicationDataAddress = (ApplicationData) receivedAddress.getAddress();
2727         assertEquals(protocol, receivedApplicationDataAddress.getApplicationData().getProtocol().intValue());
2728         assertEquals(ipTOs, receivedApplicationDataAddress.getApplicationData().getIpTos().intValue());
2729         assertEquals(localPortLow, receivedApplicationDataAddress.getApplicationData().getLocalPortLow().getValue()
2730                 .intValue());
2731         assertEquals(localPortHigh, receivedApplicationDataAddress.getApplicationData().getLocalPortHigh().getValue()
2732                 .intValue());
2733         assertEquals(remotePortLow, receivedApplicationDataAddress.getApplicationData().getRemotePortLow().getValue()
2734                 .intValue());
2735         assertEquals(remotePortHigh, receivedApplicationDataAddress.getApplicationData().getRemotePortHigh().getValue()
2736                 .intValue());
2737
2738         SimpleAddress ipAddressReceived = receivedApplicationDataAddress.getApplicationData().getAddress();
2739         assertEquals(ipString, ipAddressReceived.getIpAddress().getIpv4Address().getValue());
2740     }
2741
2742     // ------------------- TimeOut Tests -----------
2743
2744     public void mapRequestMapRegisterAndMapRequestTestTimeout() throws SocketTimeoutException {
2745         cleanUP();
2746         ConfigIni.getInstance().setSmrRetryCount(0);
2747         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
2748         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
2749         sleepForSeconds(1);
2750
2751         MapRequest mapRequest = MappingServiceIntegrationTestUtil.getDefaultMapRequestBuilder(eid).build();
2752         sendMapRequest(mapRequest);
2753         MapReply mapReply = receiveMapReply();
2754         assertEquals(4, mapReply.getNonce().longValue());
2755         assertEquals(0, mapReply.getMappingRecordItem().get(0).getMappingRecord().nonnullLocatorRecord().size());
2756
2757         MapRegister mapRegister = MappingServiceIntegrationTestUtil.getDefaultMapRegisterBuilder(eid).build();
2758         sendMapRegister(mapRegister);
2759         MapNotify mapNotify = receiveMapNotify();
2760         assertEquals(8, mapNotify.getNonce().longValue());
2761         sleepForSeconds(1);
2762
2763         sendMapRequest(mapRequest);
2764         mapReply = receiveMapReply();
2765         assertEquals(4, mapReply.getNonce().longValue());
2766         assertEquals(MappingServiceIntegrationTestUtil.DEFAULT_IPV4_RLOC,
2767                 mapReply.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().get(0).getRloc());
2768
2769         causeEntryToBeCleaned();
2770         sendMapRequest(mapRequest);
2771         mapReply = receiveMapReply();
2772         assertEquals(0, mapReply.getMappingRecordItem().get(0).getMappingRecord().nonnullLocatorRecord().size());
2773     }
2774
2775     public void mapRequestMapRegisterAndMapRequestTestNativelyForwardTimeoutResponse() throws Exception {
2776         cleanUP();
2777         Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32");
2778         MapRequest mapRequest = createMapRequest(eid);
2779
2780         testTTLBeforeRegister(mapRequest);
2781
2782         registerForTTL(eid);
2783
2784         testTTLAfterRegister(mapRequest);
2785
2786         causeEntryToBeCleaned();
2787         testTTLAfterClean(mapRequest);
2788
2789         //northboundAddKey();
2790         //testTTLAfterAutherize(mapRequest);
2791
2792     }
2793
2794     private void timedOutMappingRecord() {
2795         cleanUP();
2796         mapService.setMappingMerge(true);
2797         // mapping expires after 1 second
2798         ConfigIni.getInstance().setRegistrationValiditySb(1000L);
2799
2800         final Eid eid = LispAddressUtil.asIpv4PrefixBinaryEid("1.2.3.4/32", new InstanceIdType(10L));
2801         final MappingRecord mappingRecord = MappingServiceIntegrationTestUtil.getDefaultMappingRecordBuilder(eid)
2802                 .setRecordTtl(1000).build();
2803
2804         mapService.addAuthenticationKey(eid, NULL_AUTH_KEY);
2805         mapService.addMapping(MappingOrigin.Southbound, eid, MappingServiceIntegrationTestUtil.DEFAULT_SITE_ID,
2806                 new MappingData(mappingRecord, System.currentTimeMillis()));
2807         sleepForSeconds(2);
2808
2809         MappingRecord resultRecord = (MappingRecord) mapService.getMapping(MappingOrigin.Southbound, eid);
2810         assertNull(resultRecord);
2811         ConfigIni.getInstance().setRegistrationValiditySb(ConfigIni.getInstance().getDefaultRegistrationValiditySb());
2812     }
2813
2814     private void testTTLAfterClean(MapRequest mapRequest) throws SocketTimeoutException {
2815         MapReply mapReply;
2816         sendMapRequest(mapRequest);
2817         mapReply = receiveMapReply();
2818         assertCorrectMapReplyTTLAndAction(mapReply, 15, Action.NativelyForward);
2819     }
2820
2821     private void causeEntryToBeCleaned() {
2822         // TODO XXX for the time being, to keep master and stable/lithium in sync, we need to remove the forceful
2823         // expiration of DAO entries. Once we're past this, we'll have to expose methods to setTimeUnit(TimeUnit)
2824         // and cleanOld() (expired) entries in IFlowMapping (and perhaps ILispDAO) and use them here.
2825         mapService.cleanCachedMappings();
2826     }
2827
2828     private void testTTLAfterRegister(MapRequest mapRequest) throws SocketTimeoutException {
2829         MapReply mapReply;
2830         sendMapRequest(mapRequest);
2831         mapReply = receiveMapReply();
2832         assertEquals(LispAddressUtil.asIpv4Rloc("4.3.2.1"), mapReply.getMappingRecordItem().get(0).getMappingRecord()
2833                 .getLocatorRecord().get(0).getRloc());
2834         assertCorrectMapReplyTTLAndAction(mapReply, 254, Action.NoAction);
2835     }
2836
2837     private void registerForTTL(Eid eid) throws SocketTimeoutException {
2838         MapRegister mapRegister = createMapRegister(eid);
2839         sendMapRegister(mapRegister);
2840         assertMapNotifyReceived();
2841     }
2842
2843     private void testTTLBeforeRegister(MapRequest mapRequest) throws SocketTimeoutException {
2844         MapReply mapReply;
2845         sendMapRequest(mapRequest);
2846         mapReply = receiveMapReply();
2847         assertCorrectMapReplyTTLAndAction(mapReply, 15, Action.NativelyForward);
2848     }
2849 /*
2850     private void testTTLAfterAutherize(MapRequest mapRequest) throws SocketTimeoutException {
2851         MapReply mapReply;
2852         sendMapRequest(mapRequest);
2853         mapReply = receiveMapReply();
2854         assertCorrectMapReplyTTLAndAction(mapReply, 1, Action.NativelyForward);
2855     }
2856 */
2857     private void assertCorrectMapReplyTTLAndAction(MapReply mapReply, int expectedTTL, Action expectedAction) {
2858         assertEquals(expectedTTL, mapReply.getMappingRecordItem().get(0).getMappingRecord().getRecordTtl().intValue());
2859         assertEquals(expectedAction, mapReply.getMappingRecordItem().get(0).getMappingRecord().getAction());
2860     }
2861
2862     private MapRegister createMapRegister(Eid eid, Rloc rloc) {
2863         return MappingServiceIntegrationTestUtil.getDefaultMapRegisterBuilder(eid, rloc).build();
2864     }
2865
2866     private MapRegister createMapRegister(Eid eid) {
2867         return MappingServiceIntegrationTestUtil.getDefaultMapRegisterBuilder(eid).build();
2868     }
2869
2870     private MapRequest createMapRequest(Eid eid) {
2871         return MappingServiceIntegrationTestUtil.getDefaultMapRequestBuilder(eid).build();
2872     }
2873
2874     public void testSimpleNonProxy() throws SocketTimeoutException, SocketException {
2875         cleanUP();
2876         String rloc = "127.0.0.3";
2877         int port = LispMessage.PORT_NUM;
2878         Rloc ipRloc = LispAddressUtil.asIpv4Rloc(rloc);
2879         sendProxyMapRequest(rloc, port, ipRloc);
2880
2881     }
2882
2883     public void testNonProxyOtherPort() throws SocketTimeoutException, SocketException {
2884         cleanUP();
2885         String rloc = "127.0.0.3";
2886         int port = 4350;
2887
2888         RlocBuilder rb = new RlocBuilder();
2889         rb.setAddressType(ApplicationDataLcaf.class);
2890         rb.setVirtualNetworkId(null);
2891         rb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
2892                 .lisp.address.address.ApplicationDataBuilder()
2893                 .setApplicationData(new ApplicationDataBuilder().setAddress(new SimpleAddress(new IpAddress(
2894                 new Ipv4Address(rloc)))).setLocalPortLow(new PortNumber(port)).build()).build());
2895         Rloc adLcaf = rb.build();
2896
2897         LOG.info("testNonProxyOtherPort:" + LispAddressStringifier.getString(adLcaf));
2898         sendProxyMapRequest(rloc, port, adLcaf);
2899
2900     }
2901
2902     private class XtrRequestMappingListener implements OdlLispProtoListener {
2903
2904         @Override
2905         public void onGotMapReply(GotMapReply notification) {
2906         }
2907
2908         @Override
2909         public void onAddMapping(AddMapping notification) {
2910         }
2911
2912         @Override
2913         public void onXtrReplyMapping(XtrReplyMapping notification) {
2914         }
2915
2916         @Override
2917         public void onRequestMapping(RequestMapping notification) {
2918         }
2919
2920         @Override
2921         public void onGotMapNotify(GotMapNotify notification) {
2922         }
2923
2924         @Override
2925         public void onXtrRequestMapping(XtrRequestMapping notification) {
2926         }
2927
2928         @Override
2929         public void onMappingKeepAlive(MappingKeepAlive notification) {
2930         }
2931
2932     }
2933
2934     public void testRecievingNonProxyOnXtrPort() throws SocketTimeoutException, SocketException, Throwable {
2935         cleanUP();
2936         configLispPlugin.shouldListenOnXtrPort(true);
2937         notificationCalled = false;
2938         final String eid = "10.10.10.10/32";
2939         String rloc = "127.0.0.3";
2940         int port = LispMessage.XTR_PORT_NUM;
2941
2942         RlocBuilder rb = new RlocBuilder();
2943         rb.setAddressType(ApplicationDataLcaf.class);
2944         rb.setVirtualNetworkId(null);
2945         rb.setAddress(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.lisp.address.types.rev151105
2946                 .lisp.address.address.ApplicationDataBuilder()
2947                 .setApplicationData(new ApplicationDataBuilder().setAddress(new SimpleAddress(new IpAddress(
2948                 new Ipv4Address(rloc)))).setLocalPortLow(new PortNumber(port)).build()).build());
2949         Rloc adLcaf = rb.build();
2950
2951         final MapRequest mapRequest = createNonProxyMapRequest(eid, adLcaf);
2952         ((LispMappingService) lms).getNotificationService().registerNotificationListener(
2953                 new XtrRequestMappingListener() {
2954
2955             @Override
2956             public void onXtrRequestMapping(XtrRequestMapping notification) {
2957                 assertEquals(((Ipv4Prefix) mapRequest.getEidItem().get(0).getEid().getAddress())
2958                         .getIpv4Prefix().getValue(), eid);
2959                 notificationCalled = true;
2960                 LOG.warn("notification arrived");
2961             }
2962         });
2963         sendMapRequest(mapRequest, port);
2964         for (int i = 0; i < MAX_NOTIFICATION_RETRYS; i++) {
2965             if (notificationCalled) {
2966                 return;
2967             } else {
2968                 LOG.warn("notification hasn't arrived, sleeping...");
2969                 Thread.sleep(500);
2970             }
2971         }
2972
2973         fail("Notification hasn't arrived");
2974
2975     }
2976
2977     private void sendProxyMapRequest(String rloc, int port, Rloc adLcaf) throws SocketTimeoutException,
2978             SocketException {
2979         String eid = "10.1.0.1/32";
2980         MapRequest mapRequest = createNonProxyMapRequest(eid, adLcaf);
2981         sendMapRequest(mapRequest);
2982         DatagramSocket nonProxySocket = new DatagramSocket(new InetSocketAddress(rloc, port));
2983         MapRequest receivedMapRequest = MappingServiceIntegrationTestUtil.receiveMapRequest(
2984                 nonProxySocket, MappingServiceIntegrationTestUtil.DEFAULT_SOCKET_TIMEOUT);
2985         assertEquals(mapRequest.getNonce(), receivedMapRequest.getNonce());
2986         assertEquals(mapRequest.getSourceEid(), receivedMapRequest.getSourceEid());
2987         assertEquals(mapRequest.getItrRloc(), receivedMapRequest.getItrRloc());
2988         assertEquals(mapRequest.getEidItem(), receivedMapRequest.getEidItem());
2989         nonProxySocket.close();
2990     }
2991
2992     private MapRequest createNonProxyMapRequest(String eid, Rloc adLcaf) throws SocketTimeoutException {
2993         MapRegister mr = createMapRegister(LispAddressUtil.asIpv4PrefixBinaryEid(eid));
2994         LocatorRecord record = new LocatorRecordBuilder(mr.getMappingRecordItem().get(0).getMappingRecord()
2995                 .getLocatorRecord().get(0)).setRloc(adLcaf).build();
2996         mr.getMappingRecordItem().get(0).getMappingRecord().getLocatorRecord().set(0, record);
2997         sendMapRegister(mr);
2998         assertMapNotifyReceived();
2999         MapRequest mapRequest = createMapRequest(LispAddressUtil.asIpv4PrefixBinaryEid(eid));
3000         MapRequestBuilder builder = new MapRequestBuilder(mapRequest);
3001         builder.setPitr(true);
3002         mapRequest = builder.build();
3003         return mapRequest;
3004     }
3005
3006     private void sendMapRequest(MapRequest mapRequest) {
3007         sendMapRequest(mapRequest, LispMessage.PORT_NUM);
3008     }
3009
3010     private void sendMapRequest(MapRequest mapRequest, int port) {
3011         sendPacket(MapRequestSerializer.getInstance().serialize(mapRequest).array(), port);
3012     }
3013
3014     private void sendMapRegister(MapRegister mapRegister) {
3015         sendPacket(MapRegisterSerializer.getInstance().serialize(mapRegister).array());
3016     }
3017
3018     private void sendPacket(byte[] bytesToSend) {
3019         sendPacket(bytesToSend, LispMessage.PORT_NUM);
3020     }
3021
3022     private void sendPacket(byte[] bytesToSend, int port) {
3023         MappingServiceIntegrationTestUtil.sendPacket(socket, bytesToSend, port);
3024     }
3025
3026     private ByteBuffer receivePacket() throws SocketTimeoutException {
3027         return MappingServiceIntegrationTestUtil.receivePacket(socket);    }
3028
3029     private ByteBuffer receivePacket(int timeout) throws SocketTimeoutException {
3030         return MappingServiceIntegrationTestUtil.receivePacket(socket, timeout);
3031     }
3032
3033     private void assertMapNotifyReceived() throws SocketTimeoutException {
3034         MappingServiceIntegrationTestUtil.receiveMapNotify(
3035                 socket, MappingServiceIntegrationTestUtil.DEFAULT_SOCKET_TIMEOUT);
3036     }
3037
3038     private MapRequest receiveMapRequest() throws SocketTimeoutException {
3039         return MappingServiceIntegrationTestUtil.receiveMapRequest(
3040                 socket, MappingServiceIntegrationTestUtil.DEFAULT_SOCKET_TIMEOUT);
3041     }
3042
3043     private MapReply receiveMapReply() throws SocketTimeoutException {
3044         return MappingServiceIntegrationTestUtil.receiveMapReply(
3045                 socket, MappingServiceIntegrationTestUtil.DEFAULT_SOCKET_TIMEOUT);
3046     }
3047
3048     private MapNotify receiveMapNotify() throws SocketTimeoutException {
3049         return MappingServiceIntegrationTestUtil.receiveMapNotify(
3050                 socket, MappingServiceIntegrationTestUtil.DEFAULT_SOCKET_TIMEOUT);
3051     }
3052
3053     private void sleepForSeconds(int seconds) {
3054         try {
3055             Thread.sleep(seconds*1000);
3056         } catch (InterruptedException e) {
3057             LOG.warn("Interrupted while sleeping", e);
3058         }
3059     }
3060
3061     private void sleepForMilliseconds(long milliseconds) {
3062         try {
3063             Thread.sleep(milliseconds);
3064         } catch (InterruptedException e) {
3065             LOG.warn("Interrupted while sleeping", e);
3066         }
3067     }
3068
3069     private byte[] extractWSUdpByteArray(String wiresharkHex) {
3070         final int HEADER_LEN = 42;
3071         byte[] res = new byte[1000];
3072         String[] split = wiresharkHex.split(" ");
3073         int counter = 0;
3074         for (String cur : split) {
3075             cur = cur.trim();
3076             if (cur.length() == 2) {
3077                 ++counter;
3078                 if (counter > HEADER_LEN) {
3079                     res[counter - HEADER_LEN - 1] = (byte) Integer.parseInt(cur, 16);
3080                 }
3081
3082             }
3083         }
3084         return Arrays.copyOf(res, counter - HEADER_LEN);
3085     }
3086
3087     private String stateToString(int state) {
3088         switch (state) {
3089         case Bundle.ACTIVE:
3090             return "ACTIVE";
3091         case Bundle.INSTALLED:
3092             return "INSTALLED";
3093         case Bundle.RESOLVED:
3094             return "RESOLVED";
3095         case Bundle.UNINSTALLED:
3096             return "UNINSTALLED";
3097         default:
3098             return "Not CONVERTED";
3099         }
3100     }
3101
3102     private void areWeReady() throws InvalidSyntaxException {
3103         sleepForSeconds(5);
3104
3105         assertNotNull(bc);
3106         boolean debugit = false;
3107         Bundle b[] = bc.getBundles();
3108         for (Bundle element : b) {
3109             int state = element.getState();
3110             LOG.trace("Bundle[" + element.getBundleId() + "]:" + element.getSymbolicName() + ",v"
3111                     + element.getVersion() + ", state:" + stateToString(state));
3112             if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) {
3113                 LOG.debug("Bundle:" + element.getSymbolicName() + " state:" + stateToString(state));
3114
3115                 // try {
3116                 // String host = element.getHeaders().get("FRAGMENT-HOST");
3117                 // if (host != null) {
3118                 // LOG.warn("Bundle " + element.getSymbolicName() +
3119                 // " is a fragment which is part of: " + host);
3120                 // LOG.warn("Required imports are: " +
3121                 // element.getHeaders().get("IMPORT-PACKAGE"));
3122                 // } else {
3123                 // element.start();
3124                 // }
3125                 // } catch (BundleException e) {
3126                 // LOG.error("BundleException:", e);
3127                 // fail();
3128                 // }
3129
3130                 debugit = true;
3131
3132             }
3133         }
3134         if (debugit) {
3135             LOG.warn(("Do some debugging because some bundle is unresolved"));
3136         }
3137         // assertNotNull(broker);
3138
3139         configLispPlugin.setLispAddress(lispBindAddress);
3140
3141         // Uncomment this code to Know which services were actually loaded to
3142         // BundleContext
3143
3144         /*
3145         for (ServiceReference sr : bc.getAllServiceReferences(null, null)) {
3146             LOG.info(sr.getBundle().getSymbolicName());
3147             LOG.info(sr.toString());
3148         }
3149         */
3150
3151         sleepForSeconds(1);
3152     }
3153
3154     private void cleanUP() {
3155         LOG.debug("\n\n\nCleaning up...\n\n");
3156         mapService.cleanCachedMappings();
3157         mapService.setLookupPolicy(IMappingService.LookupPolicy.NB_FIRST);
3158         configLispPlugin.shouldListenOnXtrPort(false);
3159         MappingServiceIntegrationTestUtil.drainSocket(socket);
3160         LOG.debug("\n\n\n... finished cleaning up!\n\n");
3161     }
3162
3163     private void restartSocket() {
3164         after();
3165         socket = MappingServiceIntegrationTestUtil.initSocket(LispMessage.PORT_NUM);
3166         MappingServiceIntegrationTestUtil.drainSocket(socket);
3167     }
3168
3169 }