varnish-cache/bin/varnishtest/vtc_barrier.c
1
/*-
2
 * Copyright (c) 2005 Varnish Software AS
3
 * All rights reserved.
4
 *
5
 * Author: Dridi Boukelmoune <dridi@varnish-software.com>
6
 *
7
 * Redistribution and use in source and binary forms, with or without
8
 * modification, are permitted provided that the following conditions
9
 * are met:
10
 * 1. Redistributions of source code must retain the above copyright
11
 *    notice, this list of conditions and the following disclaimer.
12
 * 2. Redistributions in binary form must reproduce the above copyright
13
 *    notice, this list of conditions and the following disclaimer in the
14
 *    documentation and/or other materials provided with the distribution.
15
 *
16
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19
 * ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
20
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26
 * SUCH DAMAGE.
27
 */
28
29
#include "config.h"
30
31
#include <errno.h>
32
#include <poll.h>
33
#include <stdio.h>
34
#include <stdlib.h>
35
#include <string.h>
36
#include <unistd.h>
37
38
#include <sys/socket.h>
39
#include <sys/time.h> /* for MUSL */
40
41
#include "vtc.h"
42
#include "vtcp.h"
43
44
enum barrier_e {
45
        BARRIER_NONE = 0,
46
        BARRIER_COND,
47
        BARRIER_SOCK,
48
};
49
50
struct barrier {
51
        unsigned                magic;
52
#define BARRIER_MAGIC           0x7b54c275
53
        char                    *name;
54
        VTAILQ_ENTRY(barrier)   list;
55
        pthread_mutex_t         mtx;
56
        pthread_cond_t          cond;
57
58
        unsigned                waiters;
59
        unsigned                expected;
60
        unsigned                cyclic;
61
62
        enum barrier_e          type;
63
        /* fields below are only for BARRIER_SOCK */
64
        pthread_t               thread;
65
        volatile unsigned       active;
66
        volatile unsigned       need_join;
67
};
68
69
static VTAILQ_HEAD(, barrier)   barriers = VTAILQ_HEAD_INITIALIZER(barriers);
70
71
static struct barrier *
72 240
barrier_new(const char *name, struct vtclog *vl)
73
{
74
        struct barrier *b;
75
76 240
        ALLOC_OBJ(b, BARRIER_MAGIC);
77 240
        AN(b);
78 240
        if (pthread_self() != vtc_thread)
79 0
                vtc_fatal(vl,
80
                    "Barrier %s can only be created on the top thread", name);
81 240
        REPLACE(b->name, name);
82
83 240
        AZ(pthread_mutex_init(&b->mtx, NULL));
84 240
        AZ(pthread_cond_init(&b->cond, NULL));
85 240
        b->waiters = 0;
86 240
        b->expected = 0;
87 240
        VTAILQ_INSERT_TAIL(&barriers, b, list);
88 240
        return (b);
89
}
90
91
/**********************************************************************
92
 * Init a barrier
93
 */
94
95
static void
96 240
barrier_expect(struct barrier *b, const char *av, struct vtclog *vl)
97
{
98
        unsigned expected;
99
100 240
        if (b->type != BARRIER_NONE)
101 0
                vtc_fatal(vl,
102
                    "Barrier(%s) use error: already initialized", b->name);
103
104 240
        AZ(b->expected);
105 240
        AZ(b->waiters);
106 240
        expected = strtoul(av, NULL, 0);
107 240
        if (expected < 2)
108 0
                vtc_fatal(vl,
109
                    "Barrier(%s) use error: wrong expectation (%u)",
110
                    b->name, expected);
111
112 240
        b->expected = expected;
113 240
}
114
115
static void
116 202
barrier_cond(struct barrier *b, const char *av, struct vtclog *vl)
117
{
118
119 202
        CHECK_OBJ_NOTNULL(b, BARRIER_MAGIC);
120 202
        barrier_expect(b, av, vl);
121 202
        b->type = BARRIER_COND;
122 202
}
123
124
static void *
125 38
barrier_sock_thread(void *priv)
126
{
127
        struct barrier *b;
128
        struct vtclog *vl;
129
        const char *err;
130
        char abuf[16], pbuf[6];
131
        int i, sock, *conns;
132
        struct pollfd pfd[1];
133
134 38
        CAST_OBJ_NOTNULL(b, priv, BARRIER_MAGIC);
135 38
        assert(b->type == BARRIER_SOCK);
136
137 38
        AZ(pthread_mutex_lock(&b->mtx));
138
139 38
        vl = vtc_logopen(b->name);
140 38
        pthread_cleanup_push(vtc_logclose, vl);
141
142 38
        sock = VTCP_listen_on("127.0.0.1:0", NULL, b->expected, &err);
143 38
        if (sock < 0) {
144 0
                AZ(pthread_cond_signal(&b->cond));
145 0
                AZ(pthread_mutex_unlock(&b->mtx));
146 0
                vtc_fatal(vl, "Barrier(%s) %s fails: %s (errno=%d)",
147 0
                    b->name, err, strerror(errno), errno);
148
        }
149 38
        assert(sock > 0);
150 38
        (void)VTCP_nonblocking(sock);
151 38
        VTCP_myname(sock, abuf, sizeof abuf, pbuf, sizeof pbuf);
152
153 38
        macro_def(vl, b->name, "addr", "%s", abuf);
154 38
        macro_def(vl, b->name, "port", "%s", pbuf);
155 38
        macro_def(vl, b->name, "sock", "%s:%s", abuf, pbuf);
156
157 38
        AZ(pthread_cond_signal(&b->cond));
158 38
        AZ(pthread_mutex_unlock(&b->mtx));
159
160 39
        conns = calloc(b->expected, sizeof *conns);
161 39
        AN(conns);
162
163 366
        while (b->active) {
164 293
                pfd[0].fd = sock;
165 293
                pfd[0].events = POLLIN;
166
167 293
                i = poll(pfd, 1, 1000);
168 288
                if (i == 0)
169 160
                        continue;
170 128
                if (i < 0) {
171 0
                        if (errno == EINTR)
172 0
                                continue;
173 0
                        closefd(&sock);
174 0
                        vtc_fatal(vl,
175
                            "Barrier(%s) select fails: %s (errno=%d)",
176 0
                            b->name, strerror(errno), errno);
177
                }
178 128
                assert(i == 1);
179 128
                assert(b->waiters <= b->expected);
180 128
                if (b->waiters == b->expected)
181 0
                        vtc_fatal(vl,
182
                            "Barrier(%s) use error: "
183
                            "more waiters than the %u expected",
184
                            b->name, b->expected);
185
186 128
                i = accept(sock, NULL, NULL);
187 128
                if (i < 0) {
188 0
                        closefd(&sock);
189 0
                        vtc_fatal(vl,
190
                            "Barrier(%s) accept fails: %s (errno=%d)",
191 0
                            b->name, strerror(errno), errno);
192
                }
193
194
                /* NB. We don't keep track of the established connections, only
195
                 *     that connections were made to the barrier's socket.
196
                 */
197 128
                conns[b->waiters] = i;
198
199 128
                if (++b->waiters < b->expected) {
200 82
                        vtc_log(vl, 4, "Barrier(%s) wait %u of %u",
201
                            b->name, b->waiters, b->expected);
202 82
                        continue;
203
                }
204
205 46
                vtc_log(vl, 4, "Barrier(%s) wake %u", b->name, b->expected);
206 174
                for (i = 0; i < b->expected; i++)
207 128
                        closefd(&conns[i]);
208
209 46
                if (b->cyclic)
210 12
                        b->waiters = 0;
211
                else
212 34
                        b->active = 0;
213
        }
214
215 34
        macro_undef(vl, b->name, "addr");
216 34
        macro_undef(vl, b->name, "port");
217 34
        macro_undef(vl, b->name, "sock");
218 34
        closefd(&sock);
219 34
        free(conns);
220 34
        pthread_cleanup_pop(0);
221 34
        vtc_logclose(vl);
222 34
        return (NULL);
223
}
224
225
static void
226 38
barrier_sock(struct barrier *b, const char *av, struct vtclog *vl)
227
{
228
229 38
        CHECK_OBJ_NOTNULL(b, BARRIER_MAGIC);
230 38
        barrier_expect(b, av, vl);
231 38
        b->type = BARRIER_SOCK;
232 38
        b->active = 1;
233 38
        b->need_join = 1;
234
235
        /* NB. We can use the BARRIER_COND's pthread_cond_t to wait until the
236
         *     socket is ready for convenience.
237
         */
238 38
        AZ(pthread_create(&b->thread, NULL, barrier_sock_thread, b));
239 38
        AZ(pthread_cond_wait(&b->cond, &b->mtx));
240 38
}
241
242
static void
243 8
barrier_cyclic(struct barrier *b, struct vtclog *vl)
244
{
245
246 8
        CHECK_OBJ_NOTNULL(b, BARRIER_MAGIC);
247
248 8
        if (b->type == BARRIER_NONE)
249 0
                vtc_fatal(vl,
250
                    "Barrier(%s) use error: not initialized", b->name);
251
252 8
        if (b->waiters != 0)
253 0
                vtc_fatal(vl,
254
                    "Barrier(%s) use error: already in use", b->name);
255
256 8
        b->cyclic = 1;
257 8
}
258
259
/**********************************************************************
260
 * Sync a barrier
261
 */
262
263
static void
264 466
barrier_cond_sync(struct barrier *b, struct vtclog *vl)
265
{
266
267 466
        CHECK_OBJ_NOTNULL(b, BARRIER_MAGIC);
268 466
        assert(b->type == BARRIER_COND);
269
270 466
        assert(b->waiters <= b->expected);
271 466
        if (b->waiters == b->expected)
272 0
                vtc_fatal(vl,
273
                    "Barrier(%s) use error: more waiters than the %u expected",
274
                    b->name, b->expected);
275
276 466
        if (++b->waiters == b->expected) {
277 206
                vtc_log(vl, 4, "Barrier(%s) wake %u", b->name, b->expected);
278 206
                AZ(pthread_cond_broadcast(&b->cond));
279
        } else {
280 260
                vtc_log(vl, 4, "Barrier(%s) wait %u of %u",
281
                    b->name, b->waiters, b->expected);
282 260
                AZ(pthread_cond_wait(&b->cond, &b->mtx));
283
        }
284
285 466
        if (b->cyclic)
286 32
                b->waiters = 0;
287 466
}
288
289
static void
290 86
barrier_sock_sync(struct barrier *b, struct vtclog *vl)
291
{
292
        struct vsb *vsb;
293
        const char *err;
294
        char buf[32];
295
        int i, sock;
296
        ssize_t sz;
297
298 86
        CHECK_OBJ_NOTNULL(b, BARRIER_MAGIC);
299 86
        assert(b->type == BARRIER_SOCK);
300
301 86
        vsb = macro_expandf(vl, "${%s_sock}", b->name);
302 86
        vtc_log(vl, 4, "Barrier(%s) sync with socket", b->name);
303
304 86
        sock = VTCP_open(VSB_data(vsb), NULL, 0., &err);
305 86
        if (sock < 0)
306 0
                vtc_fatal(vl, "Barrier(%s) connection failed: %s",
307
                    b->name, err);
308
309 86
        VSB_delete(vsb);
310
311
        /* emulate pthread_cond_wait's behavior */
312 86
        AZ(pthread_mutex_unlock(&b->mtx));
313 86
        sz = read(sock, buf, sizeof buf); /* XXX loop with timeout? */
314 86
        AZ(pthread_mutex_lock(&b->mtx));
315
316 86
        i = errno;
317 86
        closefd(&sock);
318
319 86
        if (sz < 0)
320 0
                vtc_fatal(vl, "Barrier(%s) read failed: %s (errno=%d)",
321
                    b->name, strerror(i), i);
322 86
        if (sz > 0)
323 0
                vtc_fatal(vl, "Barrier(%s) unexpected data (%zdB)",
324
                    b->name, sz);
325 86
}
326
327
static void
328 552
barrier_sync(struct barrier *b, struct vtclog *vl)
329
{
330
331 552
        CHECK_OBJ_NOTNULL(b, BARRIER_MAGIC);
332
333 552
        switch (b->type) {
334
        case BARRIER_NONE:
335 0
                vtc_fatal(vl,
336
                    "Barrier(%s) use error: not initialized", b->name);
337
                break;
338
        case BARRIER_COND:
339 466
                barrier_cond_sync(b, vl);
340 466
                break;
341
        case BARRIER_SOCK:
342 86
                barrier_sock_sync(b, vl);
343 86
                break;
344
        default:
345 0
                WRONG("Wrong barrier type");
346
        }
347 552
}
348
349
/* SECTION: barrier barrier
350
 *
351
 * NOTE: This command is available everywhere commands are given.
352
 *
353
 * Barriers allows you to synchronize different threads to make sure events
354
 * occur in the right order. It's even possible to use them in VCL.
355
 *
356
 * First, it's necessary to declare the barrier::
357
 *
358
 *         barrier bNAME TYPE NUMBER [-cyclic]
359
 *
360
 * With the arguments being:
361
 *
362
 * bNAME
363
 *         this is the name of the barrier, used to identify it when you'll
364
 *         create sync points. It must start with 'b'.
365
 *
366
 * TYPE
367
 *         it can be "cond" (mutex) or "sock" (socket) and sets internal
368
 *         behavior. If you don't need VCL synchronization, use cond.
369
 *
370
 * NUMBER
371
 *         number of sync point needed to go through the barrier.
372
 *
373
 * \-cyclic
374
 *         if present, the barrier will reset itself and be ready for another
375
 *         round once gotten through.
376
 *
377
 * Then, to add a sync point::
378
 *
379
 *         barrier bNAME sync
380
 *
381
 * This will block the parent thread until the number of sync points for bNAME
382
 * reaches the NUMBER given in the barrier declaration.
383
 *
384
 * If you wish to synchronize the VCL, you need to declare a "sock" barrier.
385
 * This will emit a macro definition named "bNAME_sock" that you can use in
386
 * VCL (after importing the debug vmod)::
387
 *
388
 *         debug.barrier_sync("${bNAME_sock}");
389
 *
390
 * This function returns 0 if everything went well and is the equivalent of
391
 * ``barrier bNAME sync`` at the VTC top-level.
392
 *
393
 *
394
 */
395
396
void
397 792
cmd_barrier(CMD_ARGS)
398
{
399
        struct barrier *b, *b2;
400
        int r;
401
402
        (void)priv;
403
        (void)cmd;
404
405 792
        if (av == NULL) {
406
                /* Reset and free */
407 0
                VTAILQ_FOREACH_SAFE(b, &barriers, list, b2) {
408 0
                        r = pthread_mutex_trylock(&b->mtx);
409 0
                        assert(r == 0 || r == EBUSY);
410 0
                        switch (b->type) {
411
                        case BARRIER_COND:
412 0
                                break;
413
                        case BARRIER_SOCK:
414 0
                                if (b->need_join) {
415 0
                                        b->active = 0;
416 0
                                        AZ(pthread_join(b->thread, NULL));
417 0
                                        b->need_join = 0;
418
                                }
419 0
                                break;
420
                        default:
421 0
                                WRONG("Wrong barrier type");
422
                        }
423 0
                        if (r == 0)
424 0
                                AZ(pthread_mutex_unlock(&b->mtx));
425
                }
426 0
                return;
427
        }
428
429 792
        AZ(strcmp(av[0], "barrier"));
430 792
        av++;
431
432 792
        VTC_CHECK_NAME(vl, av[0], "Barrier", 'b');
433 1280
        VTAILQ_FOREACH(b, &barriers, list)
434 1040
                if (!strcmp(b->name, av[0]))
435 552
                        break;
436 792
        if (b == NULL)
437 240
                b = barrier_new(av[0], vl);
438 792
        av++;
439
440 792
        AZ(pthread_mutex_lock(&b->mtx));
441 1592
        for (; *av != NULL; av++) {
442 800
                if (!strcmp(*av, "cond")) {
443 202
                        av++;
444 202
                        AN(*av);
445 202
                        barrier_cond(b, *av, vl);
446 202
                        continue;
447
                }
448 598
                if (!strcmp(*av, "sock")) {
449 38
                        av++;
450 38
                        AN(*av);
451 38
                        barrier_sock(b, *av, vl);
452 38
                        continue;
453
                }
454 560
                if (!strcmp(*av, "sync")) {
455 552
                        barrier_sync(b, vl);
456 552
                        continue;
457
                }
458 8
                if (!strcmp(*av, "-cyclic")) {
459 8
                        barrier_cyclic(b, vl);
460 8
                        continue;
461
                }
462 0
                vtc_fatal(vl, "Unknown barrier argument: %s", *av);
463
        }
464 792
        AZ(pthread_mutex_unlock(&b->mtx));
465
}