summaryrefslogtreecommitdiffstats
path: root/src/jaegertracing/thrift/lib/d/test/async_test.d
blob: 51529ba867e66daf9c1d0586e0465585991c2281 (plain)
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless enforced by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
module async_test;

import core.atomic;
import core.sync.condition : Condition;
import core.sync.mutex : Mutex;
import core.thread : dur, Thread, ThreadGroup;
import std.conv : text;
import std.datetime;
import std.getopt;
import std.exception : collectException, enforce;
import std.parallelism : TaskPool;
import std.stdio;
import std.string;
import std.variant : Variant;
import thrift.base;
import thrift.async.base;
import thrift.async.libevent;
import thrift.async.socket;
import thrift.async.ssl;
import thrift.codegen.async_client;
import thrift.codegen.async_client_pool;
import thrift.codegen.base;
import thrift.codegen.processor;
import thrift.protocol.base;
import thrift.protocol.binary;
import thrift.server.base;
import thrift.server.simple;
import thrift.server.transport.socket;
import thrift.server.transport.ssl;
import thrift.transport.base;
import thrift.transport.buffered;
import thrift.transport.ssl;
import thrift.util.cancellation;

version (Posix) {
  import core.stdc.signal;
  import core.sys.posix.signal;

  // Disable SIGPIPE because SSL server will write to broken socket after
  // client disconnected (see TSSLSocket docs).
  shared static this() {
    signal(SIGPIPE, SIG_IGN);
  }
}

interface AsyncTest {
  string echo(string value);
  string delayedEcho(string value, long milliseconds);

  void fail(string reason);
  void delayedFail(string reason, long milliseconds);

  enum methodMeta = [
    TMethodMeta("fail", [], [TExceptionMeta("ate", 1, "AsyncTestException")]),
    TMethodMeta("delayedFail", [], [TExceptionMeta("ate", 1, "AsyncTestException")])
  ];
  alias .AsyncTestException AsyncTestException;
}

class AsyncTestException : TException {
  string reason;
  mixin TStructHelpers!();
}

void main(string[] args) {
  ushort port = 9090;
  ushort managerCount = 2;
  ushort serversPerManager = 5;
  ushort threadsPerServer = 10;
  uint iterations = 10;
  bool ssl;
  bool trace;

  getopt(args,
    "iterations", &iterations,
    "managers", &managerCount,
    "port", &port,
    "servers-per-manager", &serversPerManager,
    "ssl", &ssl,
    "threads-per-server", &threadsPerServer,
    "trace", &trace,
  );

  TTransportFactory clientTransportFactory;
  TSSLContext serverSSLContext;
  if (ssl) {
    auto clientSSLContext = new TSSLContext();
    with (clientSSLContext) {
      authenticate = true;
      ciphers = "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH";
      loadTrustedCertificates("../../../test/keys/CA.pem");
    }
    clientTransportFactory = new TAsyncSSLSocketFactory(clientSSLContext);

    serverSSLContext = new TSSLContext();
    with (serverSSLContext) {
      serverSide = true;
      ciphers = "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH";
      loadCertificate("../../../test/keys/server.crt");
      loadPrivateKey("../../../test/keys/server.key");
    }
  } else {
    clientTransportFactory = new TBufferedTransportFactory;
  }


  auto serverCancel = new TCancellationOrigin;
  scope(exit) {
    writeln("Triggering server shutdown...");
    serverCancel.trigger();
    writeln("done.");
  }

  auto managers = new TLibeventAsyncManager[managerCount];
  scope (exit) foreach (ref m; managers) destroy(m);

  auto clientsThreads = new ThreadGroup;
  foreach (managerIndex, ref manager; managers) {
    manager = new TLibeventAsyncManager;
    foreach (serverIndex; 0 .. serversPerManager) {
      auto currentPort = cast(ushort)
        (port + managerIndex * serversPerManager + serverIndex);

      // Start the server and wait until it is up and running.
      auto servingMutex = new Mutex;
      auto servingCondition = new Condition(servingMutex);
      auto handler = new PreServeNotifyHandler(servingMutex, servingCondition);
      synchronized (servingMutex) {
        (new ServerThread!TSimpleServer(currentPort, serverSSLContext, trace,
          serverCancel, handler)).start();
        servingCondition.wait();
      }

      // We only run the timing tests for the first server on each async
      // manager, so that we don't get spurious timing errors becaue of
      // ordering issues.
      auto runTimingTests = (serverIndex == 0);

      auto c = new ClientsThread(manager, currentPort, clientTransportFactory,
        threadsPerServer, iterations, runTimingTests, trace);
      clientsThreads.add(c);
      c.start();
    }
  }
  clientsThreads.joinAll();
}

class AsyncTestHandler : AsyncTest {
  this(bool trace) {
    trace_ = trace;
  }

  override string echo(string value) {
    if (trace_) writefln(`echo("%s")`, value);
    return value;
  }

  override string delayedEcho(string value, long milliseconds) {
    if (trace_) writef(`delayedEcho("%s", %s ms)... `, value, milliseconds);
    Thread.sleep(dur!"msecs"(milliseconds));
    if (trace_) writeln("returning.");

    return value;
  }

  override void fail(string reason) {
    if (trace_) writefln(`fail("%s")`, reason);
    auto ate = new AsyncTestException;
    ate.reason = reason;
    throw ate;
  }

  override void delayedFail(string reason, long milliseconds) {
    if (trace_) writef(`delayedFail("%s", %s ms)... `, reason, milliseconds);
    Thread.sleep(dur!"msecs"(milliseconds));
    if (trace_) writeln("returning.");

    auto ate = new AsyncTestException;
    ate.reason = reason;
    throw ate;
  }

private:
  bool trace_;
  AsyncTestException ate_;
}

class PreServeNotifyHandler : TServerEventHandler {
  this(Mutex servingMutex, Condition servingCondition) {
    servingMutex_ = servingMutex;
    servingCondition_ = servingCondition;
  }

  void preServe() {
    synchronized (servingMutex_) {
      servingCondition_.notifyAll();
    }
  }
  Variant createContext(TProtocol input, TProtocol output) { return Variant.init; }
  void deleteContext(Variant serverContext, TProtocol input, TProtocol output) {}
  void preProcess(Variant serverContext, TTransport transport) {}

private:
  Mutex servingMutex_;
  Condition servingCondition_;
}

class ServerThread(ServerType) : Thread {
  this(ushort port, TSSLContext sslContext, bool trace,
    TCancellation cancellation, TServerEventHandler eventHandler
  ) {
    port_ = port;
    sslContext_ = sslContext;
    trace_ = trace;
    cancellation_ = cancellation;
    eventHandler_ = eventHandler;

    super(&run);
  }

  void run() {
    TServerSocket serverSocket;
    if (sslContext_) {
      serverSocket = new TSSLServerSocket(port_, sslContext_);
    } else {
      serverSocket = new TServerSocket(port_);
    }
    auto transportFactory = new TBufferedTransportFactory;
    auto protocolFactory = new TBinaryProtocolFactory!();
    auto processor = new TServiceProcessor!AsyncTest(new AsyncTestHandler(trace_));

    auto server = new ServerType(processor, serverSocket, transportFactory,
      protocolFactory);
    server.eventHandler = eventHandler_;

    writefln("Starting server on port %s...", port_);
    server.serve(cancellation_);
    writefln("Server thread on port %s done.", port_);
  }

private:
  ushort port_;
  bool trace_;
  TCancellation cancellation_;
  TSSLContext sslContext_;
  TServerEventHandler eventHandler_;
}

class ClientsThread : Thread {
  this(TAsyncSocketManager manager, ushort port, TTransportFactory tf,
    ushort threads, uint iterations, bool runTimingTests, bool trace
  ) {
    manager_ = manager;
    port_ = port;
    transportFactory_ = tf;
    threads_ = threads;
    iterations_ = iterations;
    runTimingTests_ = runTimingTests;
    trace_ = trace;
    super(&run);
  }

  void run() {
    auto transport = new TAsyncSocket(manager_, "localhost", port_);

    {
      auto client = new TAsyncClient!AsyncTest(
        transport,
        transportFactory_,
        new TBinaryProtocolFactory!()
      );
      transport.open();
      auto clientThreads = new ThreadGroup;
      foreach (clientId; 0 .. threads_) {
        clientThreads.create({
          auto c = clientId;
          return {
            foreach (i; 0 .. iterations_) {
              immutable id = text(port_, ":", c, ":", i);

              {
                if (trace_) writefln(`Calling echo("%s")... `, id);
                auto a = client.echo(id);
                enforce(a == id);
                if (trace_) writefln(`echo("%s") done.`, id);
              }

              {
                if (trace_) writefln(`Calling fail("%s")... `, id);
                auto a = cast(AsyncTestException)collectException(client.fail(id).waitGet());
                enforce(a && a.reason == id);
                if (trace_) writefln(`fail("%s") done.`, id);
              }
            }
          };
        }());
      }
      clientThreads.joinAll();
      transport.close();
    }

    if (runTimingTests_) {
      auto client = new TAsyncClient!AsyncTest(
        transport,
        transportFactory_,
        new TBinaryProtocolFactory!TBufferedTransport
      );

      // Temporarily redirect error logs to stdout, as SSL errors on the server
      // side are expected when the client terminates aburptly (as is the case
      // in the timeout test).
      auto oldErrorLogSink = g_errorLogSink;
      g_errorLogSink = g_infoLogSink;
      scope (exit) g_errorLogSink = oldErrorLogSink;

      foreach (i; 0 .. iterations_) {
        transport.open();

        immutable id = text(port_, ":", i);

        {
          if (trace_) writefln(`Calling delayedEcho("%s", 100 ms)...`, id);
          auto a = client.delayedEcho(id, 100);
          enforce(!a.completion.wait(dur!"usecs"(1)),
            text("wait() succeeded early (", a.get(), ", ", id, ")."));
          enforce(!a.completion.wait(dur!"usecs"(1)),
            text("wait() succeeded early (", a.get(), ", ", id, ")."));
          enforce(a.completion.wait(dur!"msecs"(200)),
            text("wait() didn't succeed as expected (", id, ")."));
          enforce(a.get() == id);
          if (trace_) writefln(`... delayedEcho("%s") done.`, id);
        }

        {
          if (trace_) writefln(`Calling delayedFail("%s", 100 ms)... `, id);
          auto a = client.delayedFail(id, 100);
          enforce(!a.completion.wait(dur!"usecs"(1)),
            text("wait() succeeded early (", id, ", ", collectException(a.get()), ")."));
          enforce(!a.completion.wait(dur!"usecs"(1)),
            text("wait() succeeded early (", id, ", ", collectException(a.get()), ")."));
          enforce(a.completion.wait(dur!"msecs"(200)),
            text("wait() didn't succeed as expected (", id, ")."));
          auto e = cast(AsyncTestException)collectException(a.get());
          enforce(e && e.reason == id);
          if (trace_) writefln(`... delayedFail("%s") done.`, id);
        }

        {
          transport.recvTimeout = dur!"msecs"(50);

          if (trace_) write(`Calling delayedEcho("socketTimeout", 100 ms)... `);
          auto a = client.delayedEcho("socketTimeout", 100);
          auto e = cast(TTransportException)collectException(a.waitGet());
          enforce(e, text("Operation didn't fail as expected (", id, ")."));
          enforce(e.type == TTransportException.Type.TIMED_OUT,
            text("Wrong timeout exception type (", id, "): ", e));
          if (trace_) writeln(`timed out as expected.`);

          // Wait until the server thread reset before the next iteration.
          Thread.sleep(dur!"msecs"(50));
          transport.recvTimeout = dur!"hnsecs"(0);
        }

        transport.close();
      }
    }

    writefln("Clients thread for port %s done.", port_);
  }

  TAsyncSocketManager manager_;
  ushort port_;
  TTransportFactory transportFactory_;
  ushort threads_;
  uint iterations_;
  bool runTimingTests_;
  bool trace_;
}