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