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