pipe.cpp 15.2 KB
Newer Older
Martin Sustrik's avatar
Martin Sustrik committed
1
/*
2
    Copyright (c) 2007-2016 Contributors as noted in the AUTHORS file
Martin Sustrik's avatar
Martin Sustrik committed
3

4
    This file is part of libzmq, the ZeroMQ core engine in C++.
Martin Sustrik's avatar
Martin Sustrik committed
5

6 7 8
    libzmq is free software; you can redistribute it and/or modify it under
    the terms of the GNU Lesser General Public License (LGPL) as published
    by the Free Software Foundation; either version 3 of the License, or
Martin Sustrik's avatar
Martin Sustrik committed
9 10
    (at your option) any later version.

11 12 13 14 15 16 17 18 19 20 21 22 23 24
    As a special exception, the Contributors give you permission to link
    this library with independent modules to produce an executable,
    regardless of the license terms of these independent modules, and to
    copy and distribute the resulting executable under terms of your choice,
    provided that you also meet, for each linked independent module, the
    terms and conditions of the license of that module. An independent
    module is a module which is not derived from or based on this library.
    If you modify this library, you must extend this exception to your
    version of the library.

    libzmq is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
    License for more details.
Martin Sustrik's avatar
Martin Sustrik committed
25

26
    You should have received a copy of the GNU Lesser General Public License
Martin Sustrik's avatar
Martin Sustrik committed
27 28 29
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

30
#include "precompiled.hpp"
31
#include <new>
32
#include <stddef.h>
33

34
#include "macros.hpp"
Martin Sustrik's avatar
Martin Sustrik committed
35
#include "pipe.hpp"
36
#include "err.hpp"
Martin Sustrik's avatar
Martin Sustrik committed
37

38 39 40
#include "ypipe.hpp"
#include "ypipe_conflate.hpp"

41 42 43 44
int zmq::pipepair (class object_t *parents_[2],
                   class pipe_t *pipes_[2],
                   int hwms_[2],
                   bool conflate_[2])
45 46 47 48
{
    //   Creates two pipe objects. These objects are connected by two ypipes,
    //   each to pass messages in one direction.

49 50
    typedef ypipe_t<msg_t, message_pipe_granularity> upipe_normal_t;
    typedef ypipe_conflate_t<msg_t> upipe_conflate_t;
51 52

    pipe_t::upipe_t *upipe1;
53
    if (conflate_[0])
54 55 56
        upipe1 = new (std::nothrow) upipe_conflate_t ();
    else
        upipe1 = new (std::nothrow) upipe_normal_t ();
57
    alloc_assert (upipe1);
58 59

    pipe_t::upipe_t *upipe2;
60
    if (conflate_[1])
61 62 63
        upipe2 = new (std::nothrow) upipe_conflate_t ();
    else
        upipe2 = new (std::nothrow) upipe_normal_t ();
64 65
    alloc_assert (upipe2);

66 67 68 69 70 71
    pipes_[0] = new (std::nothrow)
      pipe_t (parents_[0], upipe1, upipe2, hwms_[1], hwms_[0], conflate_[0]);
    alloc_assert (pipes_[0]);
    pipes_[1] = new (std::nothrow)
      pipe_t (parents_[1], upipe2, upipe1, hwms_[0], hwms_[1], conflate_[1]);
    alloc_assert (pipes_[1]);
72

73 74
    pipes_[0]->set_peer (pipes_[1]);
    pipes_[1]->set_peer (pipes_[0]);
75 76 77 78

    return 0;
}

79 80 81 82 83 84
zmq::pipe_t::pipe_t (object_t *parent_,
                     upipe_t *inpipe_,
                     upipe_t *outpipe_,
                     int inhwm_,
                     int outhwm_,
                     bool conflate_) :
Martin Sustrik's avatar
Martin Sustrik committed
85
    object_t (parent_),
86 87 88 89 90 91
    inpipe (inpipe_),
    outpipe (outpipe_),
    in_active (true),
    out_active (true),
    hwm (outhwm_),
    lwm (compute_lwm (inhwm_)),
92 93
    inhwmboost (-1),
    outhwmboost (-1),
Martin Hurton's avatar
Martin Hurton committed
94
    msgs_read (0),
95 96 97
    msgs_written (0),
    peers_msgs_read (0),
    peer (NULL),
98
    sink (NULL),
99
    state (active),
Ian Barber's avatar
Ian Barber committed
100
    delay (true),
101
    server_socket_routing_id (0),
102
    conflate (conflate_)
103 104 105
{
}

106
zmq::pipe_t::~pipe_t ()
107 108
{
}
Martin Sustrik's avatar
Martin Sustrik committed
109

110
void zmq::pipe_t::set_peer (pipe_t *peer_)
Martin Sustrik's avatar
Martin Sustrik committed
111
{
112 113 114
    //  Peer can be set once only.
    zmq_assert (!peer);
    peer = peer_;
Martin Sustrik's avatar
Martin Sustrik committed
115 116
}

117
void zmq::pipe_t::set_event_sink (i_pipe_events *sink_)
unknown's avatar
unknown committed
118
{
119
    // Sink can be set once only.
120
    zmq_assert (!sink);
121
    sink = sink_;
unknown's avatar
unknown committed
122 123
}

124 125
void zmq::pipe_t::set_server_socket_routing_id (
  uint32_t server_socket_routing_id_)
126
{
127
    server_socket_routing_id = server_socket_routing_id_;
128 129
}

130
uint32_t zmq::pipe_t::get_server_socket_routing_id ()
131
{
132
    return server_socket_routing_id;
133 134
}

135 136
void zmq::pipe_t::set_router_socket_routing_id (
  const blob_t &router_socket_routing_id_)
137
{
138
    router_socket_routing_id.set_deep_copy (router_socket_routing_id_);
139 140
}

141
const zmq::blob_t &zmq::pipe_t::get_routing_id ()
142
{
143
    return router_socket_routing_id;
144 145
}

146
const zmq::blob_t &zmq::pipe_t::get_credential () const
147 148 149 150
{
    return credential;
}

151
bool zmq::pipe_t::check_read ()
152
{
153 154 155
    if (unlikely (!in_active))
        return false;
    if (unlikely (state != active && state != waiting_for_delimiter))
156 157
        return false;

158
    //  Check if there's an item in the pipe.
159 160
    if (!inpipe->check_read ()) {
        in_active = false;
161
        return false;
162
    }
163 164

    //  If the next item in the pipe is message delimiter,
165 166
    //  initiate termination process.
    if (inpipe->probe (is_delimiter)) {
167
        msg_t msg;
168
        bool ok = inpipe->read (&msg);
169
        zmq_assert (ok);
170
        process_delimiter ();
171 172 173 174
        return false;
    }

    return true;
175 176
}

177
bool zmq::pipe_t::read (msg_t *msg_)
Martin Sustrik's avatar
Martin Sustrik committed
178
{
179 180 181
    if (unlikely (!in_active))
        return false;
    if (unlikely (state != active && state != waiting_for_delimiter))
182 183
        return false;

184
read_message:
185 186
    if (!inpipe->read (msg_)) {
        in_active = false;
Martin Sustrik's avatar
Martin Sustrik committed
187
        return false;
188
    }
Martin Sustrik's avatar
Martin Sustrik committed
189

190 191
    //  If this is a credential, save a copy and receive next message.
    if (unlikely (msg_->is_credential ())) {
192 193
        const unsigned char *data =
          static_cast<const unsigned char *> (msg_->data ());
194
        credential.set (data, msg_->size ());
195 196 197 198 199
        const int rc = msg_->close ();
        zmq_assert (rc == 0);
        goto read_message;
    }

Martin Sustrik's avatar
Martin Sustrik committed
200
    //  If delimiter was read, start termination process of the pipe.
201
    if (msg_->is_delimiter ()) {
202
        process_delimiter ();
Martin Sustrik's avatar
Martin Sustrik committed
203 204
        return false;
    }
Martin Sustrik's avatar
Martin Sustrik committed
205

206
    if (!(msg_->flags () & msg_t::more) && !msg_->is_routing_id ())
207 208
        msgs_read++;

Martin Hurton's avatar
Martin Hurton committed
209
    if (lwm > 0 && msgs_read % lwm == 0)
210
        send_activate_write (peer, msgs_read);
Martin Sustrik's avatar
Martin Sustrik committed
211 212

    return true;
Martin Sustrik's avatar
Martin Sustrik committed
213 214
}

215
bool zmq::pipe_t::check_write ()
Martin Sustrik's avatar
Martin Sustrik committed
216
{
217
    if (unlikely (!out_active || state != active))
218
        return false;
219

220
    bool full = !check_hwm ();
Martin Sustrik's avatar
Martin Sustrik committed
221

222 223 224 225 226 227
    if (unlikely (full)) {
        out_active = false;
        return false;
    }

    return true;
Martin Sustrik's avatar
Martin Sustrik committed
228 229
}

230
bool zmq::pipe_t::write (msg_t *msg_)
Martin Sustrik's avatar
Martin Sustrik committed
231
{
232
    if (unlikely (!check_write ()))
233
        return false;
234

235
    bool more = msg_->flags () & msg_t::more ? true : false;
236
    const bool is_routing_id = msg_->is_routing_id ();
237
    outpipe->write (*msg_, more);
238
    if (!more && !is_routing_id)
239
        msgs_written++;
240

241
    return true;
Martin Sustrik's avatar
Martin Sustrik committed
242 243
}

244
void zmq::pipe_t::rollback ()
Martin Sustrik's avatar
Martin Sustrik committed
245
{
246 247
    //  Remove incomplete message from the outbound pipe.
    msg_t msg;
248
    if (outpipe) {
249 250 251 252 253
        while (outpipe->unwrite (&msg)) {
            zmq_assert (msg.flags () & msg_t::more);
            int rc = msg.close ();
            errno_assert (rc == 0);
        }
254
    }
Martin Sustrik's avatar
Martin Sustrik committed
255 256
}

257
void zmq::pipe_t::flush ()
Martin Sustrik's avatar
Martin Sustrik committed
258
{
259
    //  The peer does not exist anymore at this point.
260
    if (state == term_ack_sent)
261 262
        return;

263
    if (outpipe && !outpipe->flush ())
264
        send_activate_read (peer);
Martin Sustrik's avatar
Martin Sustrik committed
265 266
}

267
void zmq::pipe_t::process_activate_read ()
unknown's avatar
unknown committed
268
{
269
    if (!in_active && (state == active || state == waiting_for_delimiter)) {
270 271 272
        in_active = true;
        sink->read_activated (this);
    }
unknown's avatar
unknown committed
273 274
}

275
void zmq::pipe_t::process_activate_write (uint64_t msgs_read_)
Martin Sustrik's avatar
Martin Sustrik committed
276
{
277
    //  Remember the peer's message sequence number.
278
    peers_msgs_read = msgs_read_;
279

280
    if (!out_active && state == active) {
281 282
        out_active = true;
        sink->write_activated (this);
Martin Hurton's avatar
Martin Hurton committed
283
    }
Martin Sustrik's avatar
Martin Sustrik committed
284 285
}

286 287 288 289 290 291 292 293
void zmq::pipe_t::process_hiccup (void *pipe_)
{
    //  Destroy old outpipe. Note that the read end of the pipe was already
    //  migrated to this thread.
    zmq_assert (outpipe);
    outpipe->flush ();
    msg_t msg;
    while (outpipe->read (&msg)) {
294
        if (!(msg.flags () & msg_t::more))
295
            msgs_written--;
296 297
        int rc = msg.close ();
        errno_assert (rc == 0);
298
    }
299
    LIBZMQ_DELETE (outpipe);
300 301 302

    //  Plug in the new outpipe.
    zmq_assert (pipe_);
303
    outpipe = (upipe_t *) pipe_;
304 305 306 307 308 309 310
    out_active = true;

    //  If appropriate, notify the user about the hiccup.
    if (state == active)
        sink->hiccuped (this);
}

311
void zmq::pipe_t::process_pipe_term ()
Martin Sustrik's avatar
Martin Sustrik committed
312
{
313 314
    zmq_assert (state == active || state == delimiter_received
                || state == term_req_sent1);
Martin Hurton's avatar
Martin Hurton committed
315

316 317
    //  This is the simple case of peer-induced termination. If there are no
    //  more pending messages to read, or if the pipe was configured to drop
318 319 320
    //  pending messages, we can move directly to the term_ack_sent state.
    //  Otherwise we'll hang up in waiting_for_delimiter state till all
    //  pending messages are read.
321
    if (state == active) {
Martin Hurton's avatar
Martin Hurton committed
322 323 324
        if (delay)
            state = waiting_for_delimiter;
        else {
325
            state = term_ack_sent;
326
            outpipe = NULL;
327 328 329 330 331
            send_pipe_term_ack (peer);
        }
    }

    //  Delimiter happened to arrive before the term command. Now we have the
332
    //  term command as well, so we can move straight to term_ack_sent state.
333
    else if (state == delimiter_received) {
334
        state = term_ack_sent;
335
        outpipe = NULL;
336 337 338 339 340 341
        send_pipe_term_ack (peer);
    }

    //  This is the case where both ends of the pipe are closed in parallel.
    //  We simply reply to the request by ack and continue waiting for our
    //  own ack.
342
    else if (state == term_req_sent1) {
343
        state = term_req_sent2;
344
        outpipe = NULL;
345 346
        send_pipe_term_ack (peer);
    }
Martin Sustrik's avatar
Martin Sustrik committed
347 348
}

349
void zmq::pipe_t::process_pipe_term_ack ()
350
{
351 352
    //  Notify the user that all the references to the pipe should be dropped.
    zmq_assert (sink);
353
    sink->pipe_terminated (this);
354

355 356 357 358 359
    //  In term_ack_sent and term_req_sent2 states there's nothing to do.
    //  Simply deallocate the pipe. In term_req_sent1 state we have to ack
    //  the peer before deallocating this side of the pipe.
    //  All the other states are invalid.
    if (state == term_req_sent1) {
360
        outpipe = NULL;
361
        send_pipe_term_ack (peer);
362
    } else
363
        zmq_assert (state == term_ack_sent || state == term_req_sent2);
364 365 366 367 368 369

    //  We'll deallocate the inbound pipe, the peer will deallocate the outbound
    //  pipe (which is an inbound pipe from its point of view).
    //  First, delete all the unread messages in the pipe. We have to do it by
    //  hand because msg_t doesn't have automatic destructor. Then deallocate
    //  the ypipe itself.
370

danielkr's avatar
danielkr committed
371
    if (!conflate) {
372 373 374 375 376
        msg_t msg;
        while (inpipe->read (&msg)) {
            int rc = msg.close ();
            errno_assert (rc == 0);
        }
Martin Hurton's avatar
Martin Hurton committed
377
    }
378

379
    LIBZMQ_DELETE (inpipe);
380

381 382
    //  Deallocate the pipe object
    delete this;
Martin Sustrik's avatar
Martin Sustrik committed
383 384
}

385 386
void zmq::pipe_t::process_pipe_hwm (int inhwm_, int outhwm_)
{
387
    set_hwms (inhwm_, outhwm_);
388 389
}

Ian Barber's avatar
Ian Barber committed
390 391 392 393 394
void zmq::pipe_t::set_nodelay ()
{
    this->delay = false;
}

395
void zmq::pipe_t::terminate (bool delay_)
Martin Sustrik's avatar
Martin Sustrik committed
396
{
397 398 399
    //  Overload the value specified at pipe creation.
    delay = delay_;

400
    //  If terminate was already called, we can ignore the duplicate invocation.
401
    if (state == term_req_sent1 || state == term_req_sent2) {
402
        return;
403
    }
404 405
    //  If the pipe is in the final phase of async termination, it's going to
    //  closed anyway. No need to do anything special here.
406
    else if (state == term_ack_sent) {
407
        return;
408
    }
409 410
    //  The simple sync termination case. Ask the peer to terminate and wait
    //  for the ack.
411
    else if (state == active) {
412
        send_pipe_term (peer);
413
        state = term_req_sent1;
414 415 416
    }
    //  There are still pending messages available, but the user calls
    //  'terminate'. We can act as if all the pending messages were read.
417
    else if (state == waiting_for_delimiter && !delay) {
418 419
        //  Drop any unfinished outbound messages.
        rollback ();
Martin Hurton's avatar
Martin Hurton committed
420 421
        outpipe = NULL;
        send_pipe_term_ack (peer);
422
        state = term_ack_sent;
423
    }
Sergey M․'s avatar
Sergey M․ committed
424
    //  If there are pending messages still available, do nothing.
425
    else if (state == waiting_for_delimiter) {
426 427 428
    }
    //  We've already got delimiter, but not term command yet. We can ignore
    //  the delimiter and ack synchronously terminate as if we were in
Martin Hurton's avatar
Martin Hurton committed
429
    //  active state.
430
    else if (state == delimiter_received) {
431
        send_pipe_term (peer);
432
        state = term_req_sent1;
433 434
    }
    //  There are no other states.
435
    else {
436
        zmq_assert (false);
437
    }
Martin Sustrik's avatar
Martin Sustrik committed
438

439
    //  Stop outbound flow of messages.
440
    out_active = false;
Martin Hurton's avatar
Martin Hurton committed
441

442
    if (outpipe) {
443 444
        //  Drop any unfinished outbound messages.
        rollback ();
445

446 447 448 449 450 451
        //  Write the delimiter into the pipe. Note that watermarks are not
        //  checked; thus the delimiter can be written even when the pipe is full.
        msg_t msg;
        msg.init_delimiter ();
        outpipe->write (msg, false);
        flush ();
452
    }
Martin Sustrik's avatar
Martin Sustrik committed
453 454
}

455
bool zmq::pipe_t::is_delimiter (const msg_t &msg_)
Martin Sustrik's avatar
Martin Sustrik committed
456
{
457
    return msg_.is_delimiter ();
Martin Sustrik's avatar
Martin Sustrik committed
458
}
459

460
int zmq::pipe_t::compute_lwm (int hwm_)
461
{
462
    //  Compute the low water mark. Following point should be taken
463 464 465 466 467 468 469 470 471 472 473 474 475
    //  into consideration:
    //
    //  1. LWM has to be less than HWM.
    //  2. LWM cannot be set to very low value (such as zero) as after filling
    //     the queue it would start to refill only after all the messages are
    //     read from it and thus unnecessarily hold the progress back.
    //  3. LWM cannot be set to very high value (such as HWM-1) as it would
    //     result in lock-step filling of the queue - if a single message is
    //     read from a full queue, writer thread is resumed to write exactly one
    //     message to the queue and go back to sleep immediately. This would
    //     result in low performance.
    //
    //  Given the 3. it would be good to keep HWM and LWM as far apart as
476 477 478
    //  possible to reduce the thread switching overhead to almost zero.
    //  Let's make LWM 1/2 of HWM.
    int result = (hwm_ + 1) / 2;
479

480
    return result;
481
}
482

483
void zmq::pipe_t::process_delimiter ()
484
{
485
    zmq_assert (state == active || state == waiting_for_delimiter);
486

487 488 489
    if (state == active)
        state = delimiter_received;
    else {
490
        outpipe = NULL;
491
        send_pipe_term_ack (peer);
492
        state = term_ack_sent;
493 494
    }
}
495 496 497 498 499 500 501 502 503 504 505 506

void zmq::pipe_t::hiccup ()
{
    //  If termination is already under way do nothing.
    if (state != active)
        return;

    //  We'll drop the pointer to the inpipe. From now on, the peer is
    //  responsible for deallocating it.
    inpipe = NULL;

    //  Create new inpipe.
507
    if (conflate)
508
        inpipe = new (std::nothrow) ypipe_conflate_t<msg_t> ();
509
    else
510
        inpipe = new (std::nothrow) ypipe_t<msg_t, message_pipe_granularity> ();
511

512 513 514 515
    alloc_assert (inpipe);
    in_active = true;

    //  Notify the peer about the hiccup.
516
    send_hiccup (peer, (void *) inpipe);
517 518
}

519 520
void zmq::pipe_t::set_hwms (int inhwm_, int outhwm_)
{
521 522
    int in = inhwm_ + (inhwmboost > 0 ? inhwmboost : 0);
    int out = outhwm_ + (outhwmboost > 0 ? outhwmboost : 0);
523 524

    // if either send or recv side has hwm <= 0 it means infinite so we should set hwms infinite
525
    if (inhwm_ <= 0 || inhwmboost == 0)
526 527
        in = 0;

528
    if (outhwm_ <= 0 || outhwmboost == 0)
529
        out = 0;
530

531
    lwm = compute_lwm (in);
532
    hwm = out;
533 534
}

535
void zmq::pipe_t::set_hwms_boost (int inhwmboost_, int outhwmboost_)
536 537 538
{
    inhwmboost = inhwmboost_;
    outhwmboost = outhwmboost_;
539
}
540

Martin Hurton's avatar
Martin Hurton committed
541
bool zmq::pipe_t::check_hwm () const
542
{
543
    bool full = hwm > 0 && msgs_written - peers_msgs_read >= uint64_t (hwm);
544
    return (!full);
545
}
546

547
void zmq::pipe_t::send_hwms_to_peer (int inhwm_, int outhwm_)
548
{
549
    send_pipe_hwm (peer, inhwm_, outhwm_);
550
}