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