aboutsummaryrefslogtreecommitdiffstats
path: root/container-search/src/test/java/com/yahoo/search/federation/http/PingTestCase.java
blob: 8c1ff69666bafbe9d6bced2c46ded4685de161da (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.federation.http;

import com.yahoo.component.ComponentId;
import com.yahoo.prelude.Ping;
import com.yahoo.prelude.Pong;
import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.StupidSingleThreadedHttpServer;
import com.yahoo.search.result.ErrorMessage;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.statistics.Statistics;
import com.yahoo.text.Utf8;
import com.yahoo.yolean.Exceptions;
import org.apache.http.HttpEntity;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

/**
 * Check for different keep-alive scenarios. What we really want to test
 * is the server does not hang.
 *
 * @author Steinar Knutsen
 */
public class PingTestCase {

    private static final int TIMEOUT_MS = 60000;

    @Test
    public void testNiceCase() throws Exception {
        NiceStupidServer server = new NiceStupidServer();
        server.start();
        checkSearchAndPing(true, true, true, server.getServerPort());
        server.stop();
    }

    private void checkSearchAndPing(boolean firstSearch, boolean pongCheck, boolean secondSearch, int port) {
        String resultThing;
        String comment;
        TestHTTPClientSearcher searcher = new TestHTTPClientSearcher("test",
                "localhost", port);
        try {

            Query query = new Query("/?query=test");

            query.setWindow(0, 10);
            // high timeout to allow for overloaded test machine
            query.setTimeout(TIMEOUT_MS);
            Ping ping = new Ping(TIMEOUT_MS);

            long start = System.currentTimeMillis();
            Execution exe = new Execution(searcher, Execution.Context.createContextStub());
            exe.search(query);

            resultThing = firstSearch ? "ok" : null;
            comment = firstSearch ? "First search should have succeeded." : "First search should fail.";
            assertEquals(comment, resultThing, query.properties().get("gotResponse"));
            Pong pong = searcher.ping(ping, searcher.getConnection());
            if (pongCheck) {
                assertEquals("Ping should not have failed.", 0, pong.getErrorSize());
            } else {
                assertEquals("Ping should have failed.", 1, pong.getErrorSize());
            }
            exe = new Execution(searcher, Execution.Context.createContextStub());
            exe.search(query);

            resultThing = secondSearch ? "ok" : null;
            comment = secondSearch ? "Second search should have succeeded." : "Second search should fail.";

            assertEquals(resultThing, query.properties().get("gotResponse"));
            long duration = System.currentTimeMillis() - start;
            // target for duration based on the timeout values + some slack
            assertTrue("This test probably hanged.", duration < TIMEOUT_MS + 4000);
            searcher.shutdownConnectionManagers();
        } finally {
            searcher.deconstruct();
        }
    }

    @Test
    public void testUselessCase() throws Exception {
        UselessStupidServer server = new UselessStupidServer();
        server.start();
        checkSearchAndPing(false, true, false, server.getServerPort());
        server.stop();
    }

    @Test
    public void testGrumpyCase() throws Exception {
        GrumpyStupidServer server = new GrumpyStupidServer();
        server.start();
        checkSearchAndPing(false, false, false, server.getServerPort());
        server.stop();
    }

    @Test
    public void testPassiveAggressiveCase() throws Exception {
        PassiveAggressiveStupidServer server = new PassiveAggressiveStupidServer();
        server.start();
        checkSearchAndPing(true, false, true, server.getServerPort());
        server.stop();
    }

    // OK on ping and search
    private static class NiceStupidServer extends StupidSingleThreadedHttpServer {
        private NiceStupidServer() throws IOException {
            super(0, 0);
        }

        @Override
        protected byte[] getResponse(String request) {
            return Utf8.toBytes("HTTP/1.1 200 OK\r\n" +
                                "Content-Type: text/xml; charset=UTF-8\r\n" +
                                "Connection: close\r\n" +
                                "Content-Length: 6\r\n" +
                                "\r\n" +
                                "hello\n");
        }
    }

    // rejects ping and accepts search
    private static class PassiveAggressiveStupidServer extends StupidSingleThreadedHttpServer {

        private PassiveAggressiveStupidServer() throws IOException {
            super(0, 0);
        }

        @Override
        protected byte[] getResponse(String request) {
            if (request.contains("/ping")) {
                return Utf8.toBytes("HTTP/1.1 404 Not found\r\n" +
                                    "Content-Type: text/xml; charset=UTF-8\r\n" +
                                    "Connection: close\r\n" +
                                    "Content-Length: 8\r\n" +
                                    "\r\n" +
                                    "go away\n");
            } else {
                return Utf8.toBytes("HTTP/1.1 200 OK\r\n" +
                                    "Content-Type: text/xml; charset=UTF-8\r\n" +
                                    "Connection: close\r\n" +
                                    "Content-Length: 6\r\n" +
                                    "\r\n" +
                                    "hello\n");
            }
        }
    }

    // accepts ping and rejects search
    private static class UselessStupidServer extends StupidSingleThreadedHttpServer {
        private UselessStupidServer() throws IOException {
            super(0, 0);
        }


        @Override
        protected byte[] getResponse(String request) {
            if (request.contains("/ping")) {
                return Utf8.toBytes("HTTP/1.1 200 OK\r\n" +
                                    "Content-Type: text/xml; charset=UTF-8\r\n" +
                                    "Connection: close\r\n" +
                                    "Content-Length: 6\r\n" +
                                    "\r\n" +
                                    "hello\n");
            } else {
                return Utf8.toBytes("HTTP/1.1 404 Not found\r\n" +
                                    "Content-Type: text/xml; charset=UTF-8\r\n" +
                                    "Connection: close\r\n" +
                                    "Content-Length: 8\r\n" +
                                    "\r\n" +
                                    "go away\n");
            }
        }
    }

    // rejects ping and search
    private static class GrumpyStupidServer extends StupidSingleThreadedHttpServer {
        private GrumpyStupidServer() throws IOException {
            super(0, 0);
        }

        @Override
        protected byte[] getResponse(String request) {
            return Utf8.toBytes("HTTP/1.1 404 Not found\r\n" +
                                "Content-Type: text/xml; charset=UTF-8\r\n" +
                                "Connection: close\r\n" +
                                "Content-Length: 8\r\n" +
                                "\r\n" +
                                "go away\n");
        }
    }

    private static class TestHTTPClientSearcher extends HTTPClientSearcher {

        public TestHTTPClientSearcher(String id, String hostName, int port) {
            super(new ComponentId(id), toConnections(hostName,port), "", Statistics.nullImplementation);
        }

        private static List<Connection> toConnections(String hostName,int port) {
            List<Connection> connections=new ArrayList<>();
            connections.add(new Connection(hostName,port));
            return connections;
        }

        @Override
        public Query handleResponse(InputStream inputStream, long contentLength, Query query) throws IOException {
            query.properties().set("gotResponse","ok");
            return query;
        }

        @Override
        public Result search(Query query, Execution execution,
                Connection connection) {
            URI uri;
            try {
                uri = new URL("http", connection.getHost(), connection
                        .getPort(), "/search").toURI();
            } catch (MalformedURLException e) {
                query.errors().add(createMalformedUrlError(query, e));
                return execution.search(query);
            } catch (URISyntaxException e) {
                query.errors().add(createMalformedUrlError(query, e));
                return execution.search(query);
            }

            HttpEntity entity;
            try {
                entity = getEntity(uri, query);
            } catch (IOException e) {
                query.errors().add(
                        ErrorMessage.createBackendCommunicationError("Error when trying to connect to HTTP backend in "
                                + this + " using " + connection
                                + " for " + query + ": "
                                + Exceptions.toMessageString(e)));
                return execution.search(query);
            } catch (TimeoutException e) {
                query.errors().add(ErrorMessage.createTimeout("No time left for HTTP traffic in "
                        + this
                        + " for " + query + ": " + e.getMessage()));
                return execution.search(query);
            }
            if (entity == null) {
                query.errors().add(
                        ErrorMessage.createBackendCommunicationError("No result from connecting to HTTP backend in "
                                + this + " using " + connection + " for " + query));
                return execution.search(query);
            }

            try {
                query = handleResponse(entity, query);
            } catch (IOException e) {
                query.errors().add(
                        ErrorMessage.createBackendCommunicationError("Error when trying to consume input in "
                                + this + ": " + Exceptions.toMessageString(e)));
            } finally {
                cleanupHttpEntity(entity);
            }
            return execution.search(query);
        }

        @Override
        public Map<String, String> getCacheKey(Query q) {
            return null;
        }

        @Override
        protected URI getPingURI(Connection connection)
                throws MalformedURLException, URISyntaxException {
            return new URL("http", connection.getHost(), connection.getPort(), "/ping").toURI();
        }

        Connection getConnection() {
            return getHasher().getNodes().select(0, 0);
        }
    }

}