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