annotate win64-msvc/include/kj/async-unix.h @ 47:d93140aac40b

Current Capnp libs and headers from git
author Chris Cannam
date Thu, 20 Oct 2016 18:15:38 +0100
parents
children 0f2d93caa50c
rev   line source
Chris@47 1 // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
Chris@47 2 // Licensed under the MIT License:
Chris@47 3 //
Chris@47 4 // Permission is hereby granted, free of charge, to any person obtaining a copy
Chris@47 5 // of this software and associated documentation files (the "Software"), to deal
Chris@47 6 // in the Software without restriction, including without limitation the rights
Chris@47 7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
Chris@47 8 // copies of the Software, and to permit persons to whom the Software is
Chris@47 9 // furnished to do so, subject to the following conditions:
Chris@47 10 //
Chris@47 11 // The above copyright notice and this permission notice shall be included in
Chris@47 12 // all copies or substantial portions of the Software.
Chris@47 13 //
Chris@47 14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
Chris@47 15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
Chris@47 16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
Chris@47 17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
Chris@47 18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
Chris@47 19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
Chris@47 20 // THE SOFTWARE.
Chris@47 21
Chris@47 22 #ifndef KJ_ASYNC_UNIX_H_
Chris@47 23 #define KJ_ASYNC_UNIX_H_
Chris@47 24
Chris@47 25 #if defined(__GNUC__) && !KJ_HEADER_WARNINGS
Chris@47 26 #pragma GCC system_header
Chris@47 27 #endif
Chris@47 28
Chris@47 29 #include "async.h"
Chris@47 30 #include "time.h"
Chris@47 31 #include "vector.h"
Chris@47 32 #include "io.h"
Chris@47 33 #include <signal.h>
Chris@47 34
Chris@47 35 #if __linux__ && !__BIONIC__ && !defined(KJ_USE_EPOLL)
Chris@47 36 // Default to epoll on Linux, except on Bionic (Android) which doesn't have signalfd.h.
Chris@47 37 #define KJ_USE_EPOLL 1
Chris@47 38 #endif
Chris@47 39
Chris@47 40 namespace kj {
Chris@47 41
Chris@47 42 class UnixEventPort: public EventPort {
Chris@47 43 // An EventPort implementation which can wait for events on file descriptors as well as signals.
Chris@47 44 // This API only makes sense on Unix.
Chris@47 45 //
Chris@47 46 // The implementation uses `poll()` or possibly a platform-specific API (e.g. epoll, kqueue).
Chris@47 47 // To also wait on signals without race conditions, the implementation may block signals until
Chris@47 48 // just before `poll()` while using a signal handler which `siglongjmp()`s back to just before
Chris@47 49 // the signal was unblocked, or it may use a nicer platform-specific API like signalfd.
Chris@47 50 //
Chris@47 51 // The implementation reserves a signal for internal use. By default, it uses SIGUSR1. If you
Chris@47 52 // need to use SIGUSR1 for something else, you must offer a different signal by calling
Chris@47 53 // setReservedSignal() at startup.
Chris@47 54 //
Chris@47 55 // WARNING: A UnixEventPort can only be used in the thread and process that created it. In
Chris@47 56 // particular, note that after a fork(), a UnixEventPort created in the parent process will
Chris@47 57 // not work correctly in the child, even if the parent ceases to use its copy. In particular
Chris@47 58 // note that this means that server processes which daemonize themselves at startup must wait
Chris@47 59 // until after daemonization to create a UnixEventPort.
Chris@47 60
Chris@47 61 public:
Chris@47 62 UnixEventPort();
Chris@47 63 ~UnixEventPort() noexcept(false);
Chris@47 64
Chris@47 65 class FdObserver;
Chris@47 66 // Class that watches an fd for readability or writability. See definition below.
Chris@47 67
Chris@47 68 Promise<siginfo_t> onSignal(int signum);
Chris@47 69 // When the given signal is delivered to this thread, return the corresponding siginfo_t.
Chris@47 70 // The signal must have been captured using `captureSignal()`.
Chris@47 71 //
Chris@47 72 // If `onSignal()` has not been called, the signal will remain blocked in this thread.
Chris@47 73 // Therefore, a signal which arrives before `onSignal()` was called will not be "missed" -- the
Chris@47 74 // next call to 'onSignal()' will receive it. Also, you can control which thread receives a
Chris@47 75 // process-wide signal by only calling `onSignal()` on that thread's event loop.
Chris@47 76 //
Chris@47 77 // The result of waiting on the same signal twice at once is undefined.
Chris@47 78
Chris@47 79 static void captureSignal(int signum);
Chris@47 80 // Arranges for the given signal to be captured and handled via UnixEventPort, so that you may
Chris@47 81 // then pass it to `onSignal()`. This method is static because it registers a signal handler
Chris@47 82 // which applies process-wide. If any other threads exist in the process when `captureSignal()`
Chris@47 83 // is called, you *must* set the signal mask in those threads to block this signal, otherwise
Chris@47 84 // terrible things will happen if the signal happens to be delivered to those threads. If at
Chris@47 85 // all possible, call `captureSignal()` *before* creating threads, so that threads you create in
Chris@47 86 // the future will inherit the proper signal mask.
Chris@47 87 //
Chris@47 88 // To un-capture a signal, simply install a different signal handler and then un-block it from
Chris@47 89 // the signal mask.
Chris@47 90
Chris@47 91 static void setReservedSignal(int signum);
Chris@47 92 // Sets the signal number which `UnixEventPort` reserves for internal use. If your application
Chris@47 93 // needs to use SIGUSR1, call this at startup (before any calls to `captureSignal()` and before
Chris@47 94 // constructing an `UnixEventPort`) to offer a different signal.
Chris@47 95
Chris@47 96 TimePoint steadyTime() { return frozenSteadyTime; }
Chris@47 97 Promise<void> atSteadyTime(TimePoint time);
Chris@47 98
Chris@47 99 // implements EventPort ------------------------------------------------------
Chris@47 100 bool wait() override;
Chris@47 101 bool poll() override;
Chris@47 102 void wake() const override;
Chris@47 103
Chris@47 104 private:
Chris@47 105 struct TimerSet; // Defined in source file to avoid STL include.
Chris@47 106 class TimerPromiseAdapter;
Chris@47 107 class SignalPromiseAdapter;
Chris@47 108
Chris@47 109 Own<TimerSet> timers;
Chris@47 110 TimePoint frozenSteadyTime;
Chris@47 111
Chris@47 112 SignalPromiseAdapter* signalHead = nullptr;
Chris@47 113 SignalPromiseAdapter** signalTail = &signalHead;
Chris@47 114
Chris@47 115 TimePoint currentSteadyTime();
Chris@47 116 void processTimers();
Chris@47 117 void gotSignal(const siginfo_t& siginfo);
Chris@47 118
Chris@47 119 friend class TimerPromiseAdapter;
Chris@47 120
Chris@47 121 #if KJ_USE_EPOLL
Chris@47 122 AutoCloseFd epollFd;
Chris@47 123 AutoCloseFd signalFd;
Chris@47 124 AutoCloseFd eventFd; // Used for cross-thread wakeups.
Chris@47 125
Chris@47 126 sigset_t signalFdSigset;
Chris@47 127 // Signal mask as currently set on the signalFd. Tracked so we can detect whether or not it
Chris@47 128 // needs updating.
Chris@47 129
Chris@47 130 bool doEpollWait(int timeout);
Chris@47 131
Chris@47 132 #else
Chris@47 133 class PollContext;
Chris@47 134
Chris@47 135 FdObserver* observersHead = nullptr;
Chris@47 136 FdObserver** observersTail = &observersHead;
Chris@47 137
Chris@47 138 unsigned long long threadId; // actually pthread_t
Chris@47 139 #endif
Chris@47 140 };
Chris@47 141
Chris@47 142 class UnixEventPort::FdObserver {
Chris@47 143 // Object which watches a file descriptor to determine when it is readable or writable.
Chris@47 144 //
Chris@47 145 // For listen sockets, "readable" means that there is a connection to accept(). For everything
Chris@47 146 // else, it means that read() (or recv()) will return data.
Chris@47 147 //
Chris@47 148 // The presence of out-of-band data should NOT fire this event. However, the event may
Chris@47 149 // occasionally fire spuriously (when there is actually no data to read), and one thing that can
Chris@47 150 // cause such spurious events is the arrival of OOB data on certain platforms whose event
Chris@47 151 // interfaces fail to distinguish between regular and OOB data (e.g. Mac OSX).
Chris@47 152 //
Chris@47 153 // WARNING: The exact behavior of this class differs across systems, since event interfaces
Chris@47 154 // vary wildly. Be sure to read the documentation carefully and avoid depending on unspecified
Chris@47 155 // behavior. If at all possible, use the higher-level AsyncInputStream interface instead.
Chris@47 156
Chris@47 157 public:
Chris@47 158 enum Flags {
Chris@47 159 OBSERVE_READ = 1,
Chris@47 160 OBSERVE_WRITE = 2,
Chris@47 161 OBSERVE_URGENT = 4,
Chris@47 162 OBSERVE_READ_WRITE = OBSERVE_READ | OBSERVE_WRITE
Chris@47 163 };
Chris@47 164
Chris@47 165 FdObserver(UnixEventPort& eventPort, int fd, uint flags);
Chris@47 166 // Begin watching the given file descriptor for readability. Only one ReadObserver may exist
Chris@47 167 // for a given file descriptor at a time.
Chris@47 168
Chris@47 169 ~FdObserver() noexcept(false);
Chris@47 170
Chris@47 171 KJ_DISALLOW_COPY(FdObserver);
Chris@47 172
Chris@47 173 Promise<void> whenBecomesReadable();
Chris@47 174 // Resolves the next time the file descriptor transitions from having no data to read to having
Chris@47 175 // some data to read.
Chris@47 176 //
Chris@47 177 // KJ uses "edge-triggered" event notification whenever possible. As a result, it is an error
Chris@47 178 // to call this method when there is already data in the read buffer which has been there since
Chris@47 179 // prior to the last turn of the event loop or prior to creation FdWatcher. In this case, it is
Chris@47 180 // unspecified whether the promise will ever resolve -- it depends on the underlying event
Chris@47 181 // mechanism being used.
Chris@47 182 //
Chris@47 183 // In order to avoid this problem, make sure that you only call `whenBecomesReadable()`
Chris@47 184 // only at times when you know the buffer is empty. You know this for sure when one of the
Chris@47 185 // following happens:
Chris@47 186 // * read() or recv() fails with EAGAIN or EWOULDBLOCK. (You MUST have non-blocking mode
Chris@47 187 // enabled on the fd!)
Chris@47 188 // * The file descriptor is a regular byte-oriented object (like a socket or pipe),
Chris@47 189 // read() or recv() returns fewer than the number of bytes requested, and `atEndHint()`
Chris@47 190 // returns false. This can only happen if the buffer is empty but EOF is not reached. (Note,
Chris@47 191 // though, that for record-oriented file descriptors like Linux's inotify interface, this
Chris@47 192 // rule does not hold, because it could simply be that the next record did not fit into the
Chris@47 193 // space available.)
Chris@47 194 //
Chris@47 195 // It is an error to call `whenBecomesReadable()` again when the promise returned previously
Chris@47 196 // has not yet resolved. If you do this, the previous promise may throw an exception.
Chris@47 197
Chris@47 198 inline Maybe<bool> atEndHint() { return atEnd; }
Chris@47 199 // Returns true if the event system has indicated that EOF has been received. There may still
Chris@47 200 // be data in the read buffer, but once that is gone, there's nothing left.
Chris@47 201 //
Chris@47 202 // Returns false if the event system has indicated that EOF had NOT been received as of the
Chris@47 203 // last turn of the event loop.
Chris@47 204 //
Chris@47 205 // Returns nullptr if the event system does not know whether EOF has been reached. In this
Chris@47 206 // case, the only way to know for sure is to call read() or recv() and check if it returns
Chris@47 207 // zero.
Chris@47 208 //
Chris@47 209 // This hint may be useful as an optimization to avoid an unnecessary system call.
Chris@47 210
Chris@47 211 Promise<void> whenBecomesWritable();
Chris@47 212 // Resolves the next time the file descriptor transitions from having no space available in the
Chris@47 213 // write buffer to having some space available.
Chris@47 214 //
Chris@47 215 // KJ uses "edge-triggered" event notification whenever possible. As a result, it is an error
Chris@47 216 // to call this method when there is already space in the write buffer which has been there
Chris@47 217 // since prior to the last turn of the event loop or prior to creation FdWatcher. In this case,
Chris@47 218 // it is unspecified whether the promise will ever resolve -- it depends on the underlying
Chris@47 219 // event mechanism being used.
Chris@47 220 //
Chris@47 221 // In order to avoid this problem, make sure that you only call `whenBecomesWritable()`
Chris@47 222 // only at times when you know the buffer is full. You know this for sure when one of the
Chris@47 223 // following happens:
Chris@47 224 // * write() or send() fails with EAGAIN or EWOULDBLOCK. (You MUST have non-blocking mode
Chris@47 225 // enabled on the fd!)
Chris@47 226 // * write() or send() succeeds but accepts fewer than the number of bytes provided. This can
Chris@47 227 // only happen if the buffer is full.
Chris@47 228 //
Chris@47 229 // It is an error to call `whenBecomesWritable()` again when the promise returned previously
Chris@47 230 // has not yet resolved. If you do this, the previous promise may throw an exception.
Chris@47 231
Chris@47 232 Promise<void> whenUrgentDataAvailable();
Chris@47 233 // Resolves the next time the file descriptor's read buffer contains "urgent" data.
Chris@47 234 //
Chris@47 235 // The conditions for availability of urgent data are specific to the file descriptor's
Chris@47 236 // underlying implementation.
Chris@47 237 //
Chris@47 238 // It is an error to call `whenUrgentDataAvailable()` again when the promise returned previously
Chris@47 239 // has not yet resolved. If you do this, the previous promise may throw an exception.
Chris@47 240 //
Chris@47 241 // WARNING: This has some known weird behavior on macOS. See
Chris@47 242 // https://github.com/sandstorm-io/capnproto/issues/374.
Chris@47 243
Chris@47 244 private:
Chris@47 245 UnixEventPort& eventPort;
Chris@47 246 int fd;
Chris@47 247 uint flags;
Chris@47 248
Chris@47 249 kj::Maybe<Own<PromiseFulfiller<void>>> readFulfiller;
Chris@47 250 kj::Maybe<Own<PromiseFulfiller<void>>> writeFulfiller;
Chris@47 251 kj::Maybe<Own<PromiseFulfiller<void>>> urgentFulfiller;
Chris@47 252 // Replaced each time `whenBecomesReadable()` or `whenBecomesWritable()` is called. Reverted to
Chris@47 253 // null every time an event is fired.
Chris@47 254
Chris@47 255 Maybe<bool> atEnd;
Chris@47 256
Chris@47 257 void fire(short events);
Chris@47 258
Chris@47 259 #if !KJ_USE_EPOLL
Chris@47 260 FdObserver* next;
Chris@47 261 FdObserver** prev;
Chris@47 262 // Linked list of observers which currently have a non-null readFulfiller or writeFulfiller.
Chris@47 263 // If `prev` is null then the observer is not currently in the list.
Chris@47 264
Chris@47 265 short getEventMask();
Chris@47 266 #endif
Chris@47 267
Chris@47 268 friend class UnixEventPort;
Chris@47 269 };
Chris@47 270
Chris@47 271 } // namespace kj
Chris@47 272
Chris@47 273 #endif // KJ_ASYNC_UNIX_H_