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