File: stresssocket.pl

package info (click to toggle)
swi-prolog 8.0.2+dfsg-3+deb10u1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 72,036 kB
  • sloc: ansic: 349,612; perl: 306,654; java: 5,208; cpp: 4,436; sh: 3,042; ruby: 1,594; yacc: 845; makefile: 136; xml: 82; sed: 12; sql: 6
file content (429 lines) | stat: -rw-r--r-- 11,522 bytes parent folder | download | duplicates (2)
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
/*  Part of SWI-Prolog

    Author:        Jan Wielemaker
    E-mail:        J.Wielemaker@vu.nl
    WWW:           http://www.swi-prolog.org
    Copyright (c)  2003-2011, University of Amsterdam
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:

    1. Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright
       notice, this list of conditions and the following disclaimer in
       the documentation and/or other materials provided with the
       distribution.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.
*/

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Stress-testing sockets, message queues and   threads. These elements are
the most important and complicated parts   of multi-threaded servers and
require intensive testing. This program performs the following steps for
each test:

        * Create a server consisting of an accepting thread and 5 workers.
        * Run the tests from test_def.
        * Destroy the server

For simple tests, get yourself a free machine and run

        ?- forever.

It creates a logfile named <host>-forever.txt
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

:- asserta(user:file_search_path(foreign, '.')).
:- use_module(socket).
:- use_module(library(debug)).

:- dynamic
    on_thread/2,
    port/1,
    worker/1.

:- discontiguous
    test_impl/1.

                 /*******************************
                 *             FOREVER          *
                 *******************************/

forever :-
    forever(_).

forever(Test) :-
    gethostname(Host),
    atomic_list_concat([Host, -, 'forever.txt'], Log),
    protocol(Log),
    between(1, 10000000, N),
      get_time(T),
      convert_time(T, S),
      format('***** TEST RUN ~w ***** [~w]~n', [N, S]),
      test(Test),
    fail.
forever(_).                             % takes very long

                 /*******************************
                 *             TOPLEVEL         *
                 *******************************/

test :-
    test(_).

test(T) :-
    create_server(5),
    (   test_def(T, Test),
        (   Test = concurrent(Times, Threads, CTest)
        ->  run(concurrent(Times, Threads, test_impl(CTest)))
        ;   run(test_impl(Test))
        ),
        fail
    ;   true
    ),
    stop_server.

test_def(s1, echo(100)).
test_def(s2, big(100000)).
test_def(s3, big(10000, 10)).
test_def(s5, timeout).
test_def(s6, nohost).
test_def(s7, noport).
test_def(c1, concurrent(10, 3, echo(100))).
test_def(c1, concurrent(10, 3, big(10000))).


                 /*******************************
                 *              SERVER          *
                 *******************************/

create_server :-
    create_server(5).

create_server(Workers) :-
    thread_create(server(Workers), _, [alias(server)]),
    thread_get_message(ready),
    debug(tcp, 'Server started', []).

stop_server :-
    forall(worker(_), client(exit, _)),
    debug(tcp, 'Workers exited, prepare to join server', []),
    connect,                        % make accept return
    thread_join(server).

server(Workers) :-
    create_pool(Workers),
    tcp_socket(Socket),
    tcp_bind(Socket, Port),
    assert(port(Port)),
    tcp_listen(Socket, 5),
    debug(tcp, 'Server ready on port ~w', [Port]),
    thread_send_message(main, ready),
    repeat,
      tcp_accept(Socket, Client, _Peer),
      debug(connect, 'Connection from ~w', [_Peer]),
      (   worker(_)
      ->  thread_send_message(queue, Client),
          fail
      ;   !,
          tcp_close_socket(Client)
      ),
    debug(tcp, 'All workers have gone, stopping', []),
    stop_pool,
    tcp_close_socket(Socket),
    retract(port(Port)).

create_pool(Number) :-
    message_queue_create(queue),
    forall(between(1, Number, _),
           (   thread_create(work(queue), Id, []),
               assert(worker(Id))
           )).


stop_pool :-
    forall(worker(_),
           thread_send_message(queue, stop)),
    forall(retract(worker(Id)),
           thread_join(Id)),
    message_queue_destroy(queue),
    debug(tcp, 'Pool stopped', []).

work(Queue) :-
    repeat,
    thread_get_message(Queue, Socket),
    handle(Socket, Data),
    Data == exit,
    !.

handle(Client, Data) :-
    tcp_open_socket(Client, In, Out),
    read(In, Data),
%       open_null_stream(Null),
%       copy_stream_data(In, Null),
%       close(Null),
    close(In),
    thread_self(Me),
    debug(data, '~p: Received ~W', [Me, Data, [max_depth(10)]]),
    (   debugging(thread)
    ->  assert(on_thread(Me, Data))
    ;   true
    ),
    do_work(Data, Answer),
    writeq(Out, Answer),
    write(Out, '.\n'),
    debug(data, 'Sent ~W', [Answer, [max_depth(10)]]),
    flush_output(Out),
    close(Out).

thread_join(Id) :-
    thread_join(Id, Status),
    (   Status == true
    ->  true
    ;   format('WRONG join-status for ~w: ~w~n', [Id, Status])
    ).


do_work(exit, true) :-
    !,
    thread_self(Me),
    debug(tcp, 'Exit worker ~w', [Me]),
    thread_detach(Me),
    retract(worker(Me)).
do_work(echo(Data), Data) :- !.
do_work(sleep(Time), true) :-
    !,
    sleep(Time).


                 /*******************************
                 *            CLIENT            *
                 *******************************/

host(localhost).

client(Term, Reply) :-
    client(Term, Reply, 0).
client(Term, Reply, TimeOut) :-
    host(Host),
    port(Port),
    client(Host, Port, TimeOut, Term, Reply).
client(Host, Port, Timeout, Term, Reply) :-
    tcp_socket(Socket),
    tcp_connect(Socket, Host:Port),
    tcp_open_socket(Socket, In, Out),
    send_output(Term, Out),
    close(Out),
    (   Timeout == 0
    ->  true
    ;   set_stream(In, timeout(Timeout))
    ),
    call_cleanup(read(In, Reply), close(In)),
    debug(data, 'Reply = ~W', [Reply, [max_depth(10)]]).

send_output(List, Out) :-
    is_list(List),
    !,
    send_list_output(List, Out).
send_output(Term, Out) :-
    send_term(Term, Out).

send_term(Term, Out) :-
    writeq(Out, Term),
    write(Out, '.\n').

send_list_output([], _).
send_list_output([H|T], Out) :-
    send_term(H, Out),
    send_list_output(T, Out).

echo(Term) :-
    client(echo(Term), Reply),
    assertion(Term =@= Reply).

connect :-
    host(Host),
    port(Port),
    tcp_socket(Socket),
    tcp_connect(Socket, Host:Port),
    tcp_close_socket(Socket).


                 /*******************************
                 *             TESTS            *
                 *******************************/

%       echo(Times)
%
%       Send a lot of short messages to the server

test_impl(echo(Times)) :-
    !,
    forall(between(1, Times, N),
           echo(N)).

%       big(Size)
%
%       Send a list of 1...Size to the server

test_impl(big(Size)) :-
    findall(X, between(1, Size, X), L),
    echo(L).

%       big(Size, Times)
%
%       Send Times lists of 1...Size to the server

test_impl(big(Size, Times)) :-
    findall(X, between(1, Size, X), L),
    forall(between(1, Times, _),
           echo(L)).

test_impl(timeout) :-
    catch(client(sleep(2), _Reply, 1), E, true),
    assertion(E = error(timeout_error(read, '$stream'(_)), _G285)).


                 /*******************************
                 *             RUN              *
                 *******************************/

:- meta_predicate
    run(:).

run(Goal) :-
    debug(run, ' ** Run ~p ...', [Goal]),
    call_cleanup(Goal, E, cleanup(Goal, E)).

cleanup(Goal, E) :-
    debug(run, ' ** Finished ~p: ~p', [Goal, E]).


                 /*******************************
                 *        SPECIAL TESTS         *
                 *******************************/

test_impl(nohost) :-
    tcp_socket(S),
    catch(tcp_connect(S, 'foo.bar':80), E, true),
    tcp_close_socket(S),
    assertion(E =@= error(socket_error(eai_noname, _), _)).

test_impl(noport) :-
    tcp_socket(S),
    catch(call_with_time_limit(5, tcp_connect(S, localhost:4321)),
          E, true),
    tcp_close_socket(S),
    assertion(E = error(socket_error(_,_), _)).


                 /*******************************
                 *         DISTRIBUTION         *
                 *******************************/

on_threads :-
    (   bagof(D, on_thread(Id, D), Ds),
        length(Ds, L),
        format('Thread ~w handled ~w~n', [Id, L]),
        fail
    ;   true
    ).

clean :-
    retractall(on_thread(_, _)).


                 /*******************************
                 *             CONCUR           *
                 *******************************/

:- meta_predicate
    concurrent(+, +, :),
    ok(:).

%       concurrent(+Times, +Threads, :Goal)
%
%       Run Goal Times times concurrent in Threads

concurrent(Times, 1, Goal) :-
    !,
    forall(between(1, Times, _),
           ok(Goal)).
concurrent(Times, Threads, Goal) :-
    strip_module(Goal, M, G),
    message_queue_create(Done),
    message_queue_create(Queue),
    create_workers(Threads, M, Queue, Done),
    forall(between(1, Times, _),
           thread_send_message(Queue, goal(G))),
    debug(concurrent, 'Waiting for ~w replies', [Times]),
    wait_n(Times, Done),
    forall(between(1, Threads, _),
           thread_send_message(Queue, done)),
    debug(concurrent, 'Waiting for ~w threads', [Threads]),
    wait_n(Threads, Done),
    message_queue_destroy(Queue),
    message_queue_destroy(Done),
    debug(concurrent, 'All done', []).

wait_n(0, _) :- !.
wait_n(N, Queue) :-
    thread_get_message(Queue, done),
    N2 is N - 1,
    wait_n(N2, Queue).

create_workers(N, Module, Queue, Done) :-
    N > 0,
    !,
    thread_create(worker(Module, Queue, Done),
                  _,
                  [ detached(true)
                  ]),
    N2 is N - 1,
    create_workers(N2, Module, Queue, Done).
create_workers(_, _, _, _).


worker(Module, Queue, Done) :-
    thread_get_message(Queue, Message),
    (   Message = goal(Goal)
    ->  ok(Module:Goal),
        thread_send_message(Done, done),
        worker(Module, Queue, Done)
    ;   thread_send_message(Done, done)
    ).

ok(Goal) :-
    (   catch(Goal, E, true)
    ->  (   var(E)
        ->  true
        ;   print_message(error, E)
        )
    ;   print_message(warning, failed(Goal))
    ).

                 /*******************************
                 *             DEBUG            *
                 *******************************/

%:- interactor.
:- debug(tcp).
%:- debug(data).
:- debug(run).
:- debug(concurrent).