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

    This file is part of 0MQ.

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

    0MQ 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
14
    GNU Lesser General Public License for more details.
Martin Sustrik's avatar
Martin Sustrik committed
15

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

20
#include <new>
21
#include <stddef.h>
22

Martin Sustrik's avatar
Martin Sustrik committed
23
#include "pipe.hpp"
24
#include "err.hpp"
Martin Sustrik's avatar
Martin Sustrik committed
25

26 27 28
#include "ypipe.hpp"
#include "ypipe_conflate.hpp"

29
int zmq::pipepair (class object_t *parents_ [2], class pipe_t* pipes_ [2],
Ian Barber's avatar
Ian Barber committed
30
    int hwms_ [2], bool conflate_ [2])
31 32 33 34
{
    //   Creates two pipe objects. These objects are connected by two ypipes,
    //   each to pass messages in one direction.

35 36 37 38 39 40 41 42
    typedef ypipe_t      <msg_t, message_pipe_granularity> upipe_normal_t;
    typedef ypipe_conflate_t <msg_t, message_pipe_granularity> upipe_conflate_t;

    pipe_t::upipe_t *upipe1;
    if(conflate_ [0])
        upipe1 = new (std::nothrow) upipe_conflate_t ();
    else
        upipe1 = new (std::nothrow) upipe_normal_t ();
43
    alloc_assert (upipe1);
44 45 46 47 48 49

    pipe_t::upipe_t *upipe2;
    if(conflate_ [1])
        upipe2 = new (std::nothrow) upipe_conflate_t ();
    else
        upipe2 = new (std::nothrow) upipe_normal_t ();
50 51 52
    alloc_assert (upipe2);

    pipes_ [0] = new (std::nothrow) pipe_t (parents_ [0], upipe1, upipe2,
Ian Barber's avatar
Ian Barber committed
53
        hwms_ [1], hwms_ [0], conflate_ [0]);
54 55
    alloc_assert (pipes_ [0]);
    pipes_ [1] = new (std::nothrow) pipe_t (parents_ [1], upipe2, upipe1,
Ian Barber's avatar
Ian Barber committed
56
        hwms_ [0], hwms_ [1], conflate_ [1]);
57 58 59 60 61 62 63 64 65
    alloc_assert (pipes_ [1]);

    pipes_ [0]->set_peer (pipes_ [1]);
    pipes_ [1]->set_peer (pipes_ [0]);

    return 0;
}

zmq::pipe_t::pipe_t (object_t *parent_, upipe_t *inpipe_, upipe_t *outpipe_,
Ian Barber's avatar
Ian Barber committed
66
      int inhwm_, int outhwm_, bool conflate_) :
Martin Sustrik's avatar
Martin Sustrik committed
67
    object_t (parent_),
68 69 70 71 72 73
    inpipe (inpipe_),
    outpipe (outpipe_),
    in_active (true),
    out_active (true),
    hwm (outhwm_),
    lwm (compute_lwm (inhwm_)),
Martin Hurton's avatar
Martin Hurton committed
74
    msgs_read (0),
75 76 77
    msgs_written (0),
    peers_msgs_read (0),
    peer (NULL),
78
    sink (NULL),
79
    state (active),
Ian Barber's avatar
Ian Barber committed
80
    delay (true),
81
    conflate (conflate_)
82 83 84
{
}

85
zmq::pipe_t::~pipe_t ()
86 87
{
}
Martin Sustrik's avatar
Martin Sustrik committed
88

89
void zmq::pipe_t::set_peer (pipe_t *peer_)
Martin Sustrik's avatar
Martin Sustrik committed
90
{
91 92 93
    //  Peer can be set once only.
    zmq_assert (!peer);
    peer = peer_;
Martin Sustrik's avatar
Martin Sustrik committed
94 95
}

96
void zmq::pipe_t::set_event_sink (i_pipe_events *sink_)
unknown's avatar
unknown committed
97
{
98
    // Sink can be set once only.
99
    zmq_assert (!sink);
100
    sink = sink_;
unknown's avatar
unknown committed
101 102
}

103
void zmq::pipe_t::set_identity (const blob_t &identity_)
104
{
105
    identity = identity_;
106 107
}

108
zmq::blob_t zmq::pipe_t::get_identity ()
109
{
110
    return identity;
111 112
}

113
bool zmq::pipe_t::check_read ()
114
{
115 116 117
    if (unlikely (!in_active))
        return false;
    if (unlikely (state != active && state != waiting_for_delimiter))
118 119
        return false;

120
    //  Check if there's an item in the pipe.
121 122
    if (!inpipe->check_read ()) {
        in_active = false;
123
        return false;
124
    }
125 126

    //  If the next item in the pipe is message delimiter,
127 128
    //  initiate termination process.
    if (inpipe->probe (is_delimiter)) {
129
        msg_t msg;
130
        bool ok = inpipe->read (&msg);
131
        zmq_assert (ok);
132
        process_delimiter ();
133 134 135 136
        return false;
    }

    return true;
137 138
}

139
bool zmq::pipe_t::read (msg_t *msg_)
Martin Sustrik's avatar
Martin Sustrik committed
140
{
141 142 143
    if (unlikely (!in_active))
        return false;
    if (unlikely (state != active && state != waiting_for_delimiter))
144 145
        return false;

146 147
    if (!inpipe->read (msg_)) {
        in_active = false;
Martin Sustrik's avatar
Martin Sustrik committed
148
        return false;
149
    }
Martin Sustrik's avatar
Martin Sustrik committed
150 151

    //  If delimiter was read, start termination process of the pipe.
152
    if (msg_->is_delimiter ()) {
153
        process_delimiter ();
Martin Sustrik's avatar
Martin Sustrik committed
154 155
        return false;
    }
Martin Sustrik's avatar
Martin Sustrik committed
156

157
    if (!(msg_->flags () & msg_t::more))
158 159
        msgs_read++;

Martin Hurton's avatar
Martin Hurton committed
160
    if (lwm > 0 && msgs_read % lwm == 0)
161
        send_activate_write (peer, msgs_read);
Martin Sustrik's avatar
Martin Sustrik committed
162 163

    return true;
Martin Sustrik's avatar
Martin Sustrik committed
164 165
}

166
bool zmq::pipe_t::check_write ()
Martin Sustrik's avatar
Martin Sustrik committed
167
{
168
    if (unlikely (!out_active || state != active))
169
        return false;
170

171
    bool full = hwm > 0 && msgs_written - peers_msgs_read == uint64_t (hwm);
Martin Sustrik's avatar
Martin Sustrik committed
172

173 174 175 176 177 178
    if (unlikely (full)) {
        out_active = false;
        return false;
    }

    return true;
Martin Sustrik's avatar
Martin Sustrik committed
179 180
}

181
bool zmq::pipe_t::write (msg_t *msg_)
Martin Sustrik's avatar
Martin Sustrik committed
182
{
183
    if (unlikely (!check_write ()))
184
        return false;
185

186
    bool more = msg_->flags () & msg_t::more ? true : false;
187 188
    outpipe->write (*msg_, more);
    if (!more)
189
        msgs_written++;
190

191
    return true;
Martin Sustrik's avatar
Martin Sustrik committed
192 193
}

194
void zmq::pipe_t::rollback ()
Martin Sustrik's avatar
Martin Sustrik committed
195
{
196 197
    //  Remove incomplete message from the outbound pipe.
    msg_t msg;
198
    if (outpipe) {
199 200 201 202 203
        while (outpipe->unwrite (&msg)) {
            zmq_assert (msg.flags () & msg_t::more);
            int rc = msg.close ();
            errno_assert (rc == 0);
        }
204
    }
Martin Sustrik's avatar
Martin Sustrik committed
205 206
}

207
void zmq::pipe_t::flush ()
Martin Sustrik's avatar
Martin Sustrik committed
208
{
209
    //  The peer does not exist anymore at this point.
210
    if (state == term_ack_sent)
211 212
        return;

213
    if (outpipe && !outpipe->flush ())
214
        send_activate_read (peer);
Martin Sustrik's avatar
Martin Sustrik committed
215 216
}

217
void zmq::pipe_t::process_activate_read ()
unknown's avatar
unknown committed
218
{
219
    if (!in_active && (state == active || state == waiting_for_delimiter)) {
220 221 222
        in_active = true;
        sink->read_activated (this);
    }
unknown's avatar
unknown committed
223 224
}

225
void zmq::pipe_t::process_activate_write (uint64_t msgs_read_)
Martin Sustrik's avatar
Martin Sustrik committed
226
{
227 228
    //  Remember the peers's message sequence number.
    peers_msgs_read = msgs_read_;
229

230
    if (!out_active && state == active) {
231 232
        out_active = true;
        sink->write_activated (this);
Martin Hurton's avatar
Martin Hurton committed
233
    }
Martin Sustrik's avatar
Martin Sustrik committed
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
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)) {
       int rc = msg.close ();
       errno_assert (rc == 0);
    }
    delete outpipe;

    //  Plug in the new outpipe.
    zmq_assert (pipe_);
    outpipe = (upipe_t*) pipe_;
    out_active = true;

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

259
void zmq::pipe_t::process_pipe_term ()
Martin Sustrik's avatar
Martin Sustrik committed
260
{
261 262
    //  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
263 264 265
    //  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.
266 267
    if (state == active) {
        if (!delay) {
268
            state = term_ack_sent;
269
            outpipe = NULL;
270 271
            send_pipe_term_ack (peer);
        }
Martin Hurton's avatar
Martin Hurton committed
272
        else
273
            state = waiting_for_delimiter;
Martin Hurton's avatar
Martin Hurton committed
274
        return;
275 276 277
    }

    //  Delimiter happened to arrive before the term command. Now we have the
278 279 280
    //  term command as well, so we can move straight to term_ack_sent state.
    if (state == delimiter_received) {
        state = term_ack_sent;
281
        outpipe = NULL;
282 283 284 285 286 287 288
        send_pipe_term_ack (peer);
        return;
    }

    //  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.
289 290
    if (state == term_req_sent1) {
        state = term_req_sent2;
291
        outpipe = NULL;
292
        send_pipe_term_ack (peer);
293
        return;
294
    }
295 296 297

    //  pipe_term is invalid in other states.
    zmq_assert (false);
Martin Sustrik's avatar
Martin Sustrik committed
298 299
}

300
void zmq::pipe_t::process_pipe_term_ack ()
301
{
302 303
    //  Notify the user that all the references to the pipe should be dropped.
    zmq_assert (sink);
304
    sink->pipe_terminated (this);
305

306 307 308 309 310
    //  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) {
311
        outpipe = NULL;
312
        send_pipe_term_ack (peer);
313
    }
314
    else
315
        zmq_assert (state == term_ack_sent || state == term_req_sent2);
316 317 318 319 320 321

    //  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.
322

danielkr's avatar
danielkr committed
323
    if (!conflate) {
324 325 326 327 328
        msg_t msg;
        while (inpipe->read (&msg)) {
            int rc = msg.close ();
            errno_assert (rc == 0);
        }
Martin Hurton's avatar
Martin Hurton committed
329
    }
330

331
    delete inpipe;
332

333 334
    //  Deallocate the pipe object
    delete this;
Martin Sustrik's avatar
Martin Sustrik committed
335 336
}

Ian Barber's avatar
Ian Barber committed
337 338 339 340 341
void zmq::pipe_t::set_nodelay ()
{
    this->delay = false;
}

342
void zmq::pipe_t::terminate (bool delay_)
Martin Sustrik's avatar
Martin Sustrik committed
343
{
344 345 346
    //  Overload the value specified at pipe creation.
    delay = delay_;

347
    //  If terminate was already called, we can ignore the duplicit invocation.
348
    if (state == term_req_sent1 || state == term_req_sent2)
349
        return;
350 351 352

    //  If the pipe is in the final phase of async termination, it's going to
    //  closed anyway. No need to do anything special here.
353 354
    else
    if (state == term_ack_sent)
355 356 357 358
        return;

    //  The simple sync termination case. Ask the peer to terminate and wait
    //  for the ack.
359
    else
360
    if (state == active) {
361
        send_pipe_term (peer);
362
        state = term_req_sent1;
363 364 365 366
    }

    //  There are still pending messages available, but the user calls
    //  'terminate'. We can act as if all the pending messages were read.
367
    else
Martin Hurton's avatar
Martin Hurton committed
368
    if (state == waiting_for_delimiter && !delay) {
Martin Hurton's avatar
Martin Hurton committed
369 370
        outpipe = NULL;
        send_pipe_term_ack (peer);
371
        state = term_ack_sent;
372 373 374
    }

    //  If there are pending messages still availabe, do nothing.
375 376
    else
    if (state == waiting_for_delimiter) {
377 378 379 380
    }

    //  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
381
    //  active state.
382 383
    else
    if (state == delimiter_received) {
384
        send_pipe_term (peer);
385
        state = term_req_sent1;
386 387 388 389 390
    }

    //  There are no other states.
    else
        zmq_assert (false);
Martin Sustrik's avatar
Martin Sustrik committed
391

392
    //  Stop outbound flow of messages.
393
    out_active = false;
Martin Hurton's avatar
Martin Hurton committed
394

395
    if (outpipe) {
396

397 398
        //  Drop any unfinished outbound messages.
        rollback ();
399

400 401 402 403 404 405
        //  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 ();
406
    }
Martin Sustrik's avatar
Martin Sustrik committed
407 408
}

409
bool zmq::pipe_t::is_delimiter (msg_t &msg_)
Martin Sustrik's avatar
Martin Sustrik committed
410
{
411
    return msg_.is_delimiter ();
Martin Sustrik's avatar
Martin Sustrik committed
412
}
413

414
int zmq::pipe_t::compute_lwm (int hwm_)
415
{
416
    //  Compute the low water mark. Following point should be taken
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
    //  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
    //  possible to reduce the thread switching overhead to almost zero,
    //  say HWM-LWM should be max_wm_delta.
    //
    //  That done, we still we have to account for the cases where
    //  HWM < max_wm_delta thus driving LWM to negative numbers.
    //  Let's make LWM 1/2 of HWM in such cases.
436
    int result = (hwm_ > max_wm_delta * 2) ?
437 438
        hwm_ - max_wm_delta : (hwm_ + 1) / 2;

439
    return result;
440
}
441

442
void zmq::pipe_t::process_delimiter ()
443
{
444 445
    zmq_assert (state == active
            ||  state == waiting_for_delimiter);
446

447 448 449
    if (state == active)
        state = delimiter_received;
    else {
450
        outpipe = NULL;
451
        send_pipe_term_ack (peer);
452
        state = term_ack_sent;
453 454
    }
}
455 456 457 458 459 460 461 462 463 464 465 466

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.
467 468 469 470 471 472 473
    if (conflate)
        inpipe = new (std::nothrow)
            ypipe_t <msg_t, message_pipe_granularity> ();
    else
        inpipe = new (std::nothrow)
            ypipe_conflate_t <msg_t, message_pipe_granularity> ();

474 475 476 477 478 479 480
    alloc_assert (inpipe);
    in_active = true;

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

481 482
void zmq::pipe_t::set_hwms (int inhwm_, int outhwm_)
{
483 484
    lwm = compute_lwm (inhwm_);
    hwm = outhwm_;
485
}