pipe.cpp 12 KB
Newer Older
Martin Sustrik's avatar
Martin Sustrik committed
1
/*
Martin Sustrik's avatar
Martin Sustrik committed
2
    Copyright (c) 2009-2011 250bpm s.r.o.
3
    Copyright (c) 2007-2009 iMatix Corporation
4
    Copyright (c) 2011 VMware, Inc.
5
    Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
Martin Sustrik's avatar
Martin Sustrik committed
6 7 8 9

    This file is part of 0MQ.

    0MQ is free software; you can redistribute it and/or modify it under
10
    the terms of the GNU Lesser General Public License as published by
Martin Sustrik's avatar
Martin Sustrik committed
11 12 13 14 15 16
    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
17
    GNU Lesser General Public License for more details.
Martin Sustrik's avatar
Martin Sustrik committed
18

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

23
#include <new>
24
#include <stddef.h>
25

Martin Sustrik's avatar
Martin Sustrik committed
26
#include "pipe.hpp"
27
#include "err.hpp"
Martin Sustrik's avatar
Martin Sustrik committed
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
int zmq::pipepair (class object_t *parents_ [2], class pipe_t* pipes_ [2],
    int hwms_ [2], bool delays_ [2])
{
    //   Creates two pipe objects. These objects are connected by two ypipes,
    //   each to pass messages in one direction.

    pipe_t::upipe_t *upipe1 = new (std::nothrow) pipe_t::upipe_t ();
    alloc_assert (upipe1);
    pipe_t::upipe_t *upipe2 = new (std::nothrow) pipe_t::upipe_t ();
    alloc_assert (upipe2);

    pipes_ [0] = new (std::nothrow) pipe_t (parents_ [0], upipe1, upipe2,
        hwms_ [1], hwms_ [0], delays_ [0]);
    alloc_assert (pipes_ [0]);
    pipes_ [1] = new (std::nothrow) pipe_t (parents_ [1], upipe2, upipe1,
        hwms_ [0], hwms_ [1], delays_ [1]);
    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_,
      int inhwm_, int outhwm_, bool delay_) :
Martin Sustrik's avatar
Martin Sustrik committed
55
    object_t (parent_),
56 57 58 59 60 61
    inpipe (inpipe_),
    outpipe (outpipe_),
    in_active (true),
    out_active (true),
    hwm (outhwm_),
    lwm (compute_lwm (inhwm_)),
Martin Hurton's avatar
Martin Hurton committed
62
    msgs_read (0),
63 64 65
    msgs_written (0),
    peers_msgs_read (0),
    peer (NULL),
66
    sink (NULL),
67
    state (active),
68
    delay (delay_)
69 70 71
{
}

72
zmq::pipe_t::~pipe_t ()
73 74
{
}
Martin Sustrik's avatar
Martin Sustrik committed
75

76
void zmq::pipe_t::set_peer (pipe_t *peer_)
Martin Sustrik's avatar
Martin Sustrik committed
77
{
78 79 80
    //  Peer can be set once only.
    zmq_assert (!peer);
    peer = peer_;
Martin Sustrik's avatar
Martin Sustrik committed
81 82
}

83
void zmq::pipe_t::set_event_sink (i_pipe_events *sink_)
unknown's avatar
unknown committed
84
{
85
    // Sink can be set once only.
86
    zmq_assert (!sink);
87
    sink = sink_;
unknown's avatar
unknown committed
88 89
}

90
void zmq::pipe_t::set_identity (const blob_t &identity_)
91
{
92
    identity = identity_;
93 94
}

95
zmq::blob_t zmq::pipe_t::get_identity ()
96
{
97
    return identity;
98 99
}

100
bool zmq::pipe_t::check_read ()
101
{
102
    if (unlikely (!in_active || (state != active && state != pending)))
103 104
        return false;

105
    //  Check if there's an item in the pipe.
106 107
    if (!inpipe->check_read ()) {
        in_active = false;
108
        return false;
109
    }
110 111

    //  If the next item in the pipe is message delimiter,
112 113
    //  initiate termination process.
    if (inpipe->probe (is_delimiter)) {
114
        msg_t msg;
115
        bool ok = inpipe->read (&msg);
116
        zmq_assert (ok);
117
        delimit ();
118 119 120 121
        return false;
    }

    return true;
122 123
}

124
bool zmq::pipe_t::read (msg_t *msg_)
Martin Sustrik's avatar
Martin Sustrik committed
125
{
126
    if (unlikely (!in_active || (state != active && state != pending)))
127 128
        return false;

129 130
    if (!inpipe->read (msg_)) {
        in_active = false;
Martin Sustrik's avatar
Martin Sustrik committed
131
        return false;
132
    }
Martin Sustrik's avatar
Martin Sustrik committed
133 134

    //  If delimiter was read, start termination process of the pipe.
135
    if (msg_->is_delimiter ()) {
136
        delimit ();
Martin Sustrik's avatar
Martin Sustrik committed
137 138
        return false;
    }
Martin Sustrik's avatar
Martin Sustrik committed
139

140
    if (!(msg_->flags () & msg_t::more))
141 142
        msgs_read++;

Martin Hurton's avatar
Martin Hurton committed
143
    if (lwm > 0 && msgs_read % lwm == 0)
144
        send_activate_write (peer, msgs_read);
Martin Sustrik's avatar
Martin Sustrik committed
145 146

    return true;
Martin Sustrik's avatar
Martin Sustrik committed
147 148
}

149
bool zmq::pipe_t::check_write ()
Martin Sustrik's avatar
Martin Sustrik committed
150
{
151
    if (unlikely (!out_active || state != active))
152
        return false;
153

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

156 157 158 159 160 161
    if (unlikely (full)) {
        out_active = false;
        return false;
    }

    return true;
Martin Sustrik's avatar
Martin Sustrik committed
162 163
}

164
bool zmq::pipe_t::write (msg_t *msg_)
Martin Sustrik's avatar
Martin Sustrik committed
165
{
166
    if (unlikely (!check_write ()))
167
        return false;
168

169
    bool more = msg_->flags () & msg_t::more ? true : false;
170 171
    outpipe->write (*msg_, more);
    if (!more)
172
        msgs_written++;
173

174
    return true;
Martin Sustrik's avatar
Martin Sustrik committed
175 176
}

177
void zmq::pipe_t::rollback ()
Martin Sustrik's avatar
Martin Sustrik committed
178
{
179 180
    //  Remove incomplete message from the outbound pipe.
    msg_t msg;
181
    if (outpipe) {
182 183 184 185 186
        while (outpipe->unwrite (&msg)) {
            zmq_assert (msg.flags () & msg_t::more);
            int rc = msg.close ();
            errno_assert (rc == 0);
        }
187
    }
Martin Sustrik's avatar
Martin Sustrik committed
188 189
}

190
void zmq::pipe_t::flush ()
Martin Sustrik's avatar
Martin Sustrik committed
191
{
192 193 194 195
    //  The peer does not exist anymore at this point.
    if (state == terminating)
        return;

196
    if (outpipe && !outpipe->flush ())
197
        send_activate_read (peer);
Martin Sustrik's avatar
Martin Sustrik committed
198 199
}

200
void zmq::pipe_t::process_activate_read ()
unknown's avatar
unknown committed
201
{
202
    if (!in_active && (state == active || state == pending)) {
203 204 205
        in_active = true;
        sink->read_activated (this);
    }
unknown's avatar
unknown committed
206 207
}

208
void zmq::pipe_t::process_activate_write (uint64_t msgs_read_)
Martin Sustrik's avatar
Martin Sustrik committed
209
{
210 211
    //  Remember the peers's message sequence number.
    peers_msgs_read = msgs_read_;
212

213
    if (!out_active && state == active) {
214 215
        out_active = true;
        sink->write_activated (this);
Martin Hurton's avatar
Martin Hurton committed
216
    }
Martin Sustrik's avatar
Martin Sustrik committed
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
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);
}

242
void zmq::pipe_t::process_pipe_term ()
Martin Sustrik's avatar
Martin Sustrik committed
243
{
244 245 246 247 248 249 250 251
    //  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
    //  pending messages, we can move directly to the terminating state.
    //  Otherwise we'll hang up in pending state till all the pending messages
    //  are sent.
    if (state == active) {
        if (!delay) {
            state = terminating;
252
            outpipe = NULL;
253 254
            send_pipe_term_ack (peer);
        }
Martin Hurton's avatar
Martin Hurton committed
255
        else
256
            state = pending;
Martin Hurton's avatar
Martin Hurton committed
257
        return;
258 259 260 261 262 263
    }

    //  Delimiter happened to arrive before the term command. Now we have the
    //  term command as well, so we can move straight to terminating state.
    if (state == delimited) {
        state = terminating;
264
        outpipe = NULL;
265 266 267 268 269 270 271 272 273
        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.
    if (state == terminated) {
        state = double_terminated;
274
        outpipe = NULL;
275
        send_pipe_term_ack (peer);
276
        return;
277
    }
278 279 280

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

283
void zmq::pipe_t::process_pipe_term_ack ()
284
{
285 286 287 288
    //  Notify the user that all the references to the pipe should be dropped.
    zmq_assert (sink);
    sink->terminated (this);

289 290 291 292
    //  In terminating and double_terminated states there's nothing to do.
    //  Simply deallocate the pipe. In terminated state we have to ack the
    //  peer before deallocating this side of the pipe. All the other states
    //  are invalid.
Martin Hurton's avatar
Martin Hurton committed
293
    if (state == terminated) {
294
        outpipe = NULL;
295
        send_pipe_term_ack (peer);
296
    }
297
    else
Martin Hurton's avatar
Martin Hurton committed
298
        zmq_assert (state == terminating || state == double_terminated);
299 300 301 302 303 304

    //  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.
305
    msg_t msg;
306 307 308
    while (inpipe->read (&msg)) {
       int rc = msg.close ();
       errno_assert (rc == 0);
Martin Hurton's avatar
Martin Hurton committed
309
    }
310
    delete inpipe;
311

312 313
    //  Deallocate the pipe object
    delete this;
Martin Sustrik's avatar
Martin Sustrik committed
314 315
}

316
void zmq::pipe_t::terminate (bool delay_)
Martin Sustrik's avatar
Martin Sustrik committed
317
{
318 319 320
    //  Overload the value specified at pipe creation.
    delay = delay_;

321 322
    //  If terminate was already called, we can ignore the duplicit invocation.
    if (state == terminated || state == double_terminated)
323
        return;
324 325 326

    //  If the pipe is in the final phase of async termination, it's going to
    //  closed anyway. No need to do anything special here.
327 328
    else 
    if (state == terminating)
329 330 331 332
        return;

    //  The simple sync termination case. Ask the peer to terminate and wait
    //  for the ack.
333 334
    else 
    if (state == active) {
335 336 337 338 339 340
        send_pipe_term (peer);
        state = terminated;
    }

    //  There are still pending messages available, but the user calls
    //  'terminate'. We can act as if all the pending messages were read.
341 342
    else 
    if (state == pending && !delay) {
Martin Hurton's avatar
Martin Hurton committed
343 344 345
        outpipe = NULL;
        send_pipe_term_ack (peer);
        state = terminating;
346 347 348
    }

    //  If there are pending messages still availabe, do nothing.
349 350
    else 
    if (state == pending) {
351 352 353 354
    }

    //  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
355
    //  active state.
356 357
    else 
    if (state == delimited) {
358
        send_pipe_term (peer);
Sergey KHripchenko's avatar
Sergey KHripchenko committed
359
        state = terminated;
360 361 362 363 364
    }

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

366
    //  Stop outbound flow of messages.
367
    out_active = false;
Martin Hurton's avatar
Martin Hurton committed
368

369
    if (outpipe) {
370

371 372
        //  Drop any unfinished outbound messages.
        rollback ();
373

374 375 376 377 378 379
        //  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 ();
380
    }
Martin Sustrik's avatar
Martin Sustrik committed
381 382
}

383
bool zmq::pipe_t::is_delimiter (msg_t &msg_)
Martin Sustrik's avatar
Martin Sustrik committed
384
{
385
    return msg_.is_delimiter ();
Martin Sustrik's avatar
Martin Sustrik committed
386
}
387

388
int zmq::pipe_t::compute_lwm (int hwm_)
389
{
390
    //  Compute the low water mark. Following point should be taken
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
    //  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.
410
    int result = (hwm_ > max_wm_delta * 2) ?
411 412
        hwm_ - max_wm_delta : (hwm_ + 1) / 2;

413
    return result;
414
}
415 416 417 418 419 420 421 422 423

void zmq::pipe_t::delimit ()
{
    if (state == active) {
        state = delimited;
        return;
    }

    if (state == pending) {
424
        outpipe = NULL;
425 426 427 428 429 430 431 432
        send_pipe_term_ack (peer);
        state = terminating;
        return;
    }

    //  Delimiter in any other state is invalid.
    zmq_assert (false);
}
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452

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.
    inpipe = new (std::nothrow) pipe_t::upipe_t ();
    alloc_assert (inpipe);
    in_active = true;

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