/
process.cpp
3747 lines (2996 loc) · 106 KB
/
process.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
#include <errno.h>
#include <limits.h>
#ifndef __WINDOWS__
#include <netdb.h>
#endif // __WINDOWS__
#include <signal.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef __WINDOWS__
#include <unistd.h>
#include <arpa/inet.h>
#endif // __WINDOWS__
#include <glog/logging.h>
#ifndef __WINDOWS__
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/uio.h>
#endif // __WINDOWS__
#include <algorithm>
#include <deque>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <memory> // TODO(benh): Replace shared_ptr with unique_ptr.
#include <mutex>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <thread>
#include <utility>
#include <vector>
#include <process/address.hpp>
#include <process/check.hpp>
#include <process/clock.hpp>
#include <process/defer.hpp>
#include <process/delay.hpp>
#include <process/dispatch.hpp>
#include <process/executor.hpp>
#include <process/filter.hpp>
#include <process/future.hpp>
#include <process/gc.hpp>
#include <process/help.hpp>
#include <process/id.hpp>
#include <process/io.hpp>
#include <process/logging.hpp>
#include <process/mime.hpp>
#include <process/owned.hpp>
#include <process/process.hpp>
#include <process/profiler.hpp>
#include <process/sequence.hpp>
#include <process/socket.hpp>
#include <process/statistics.hpp>
#include <process/system.hpp>
#include <process/time.hpp>
#include <process/timer.hpp>
#include <process/metrics/metrics.hpp>
#include <process/ssl/flags.hpp>
#include <stout/duration.hpp>
#include <stout/foreach.hpp>
#include <stout/lambda.hpp>
#include <stout/net.hpp>
#include <stout/numify.hpp>
#include <stout/option.hpp>
#include <stout/os.hpp>
#include <stout/os/strerror.hpp>
#include <stout/path.hpp>
#include <stout/strings.hpp>
#include <stout/synchronized.hpp>
#include <stout/thread_local.hpp>
#include "authenticator_manager.hpp"
#include "config.hpp"
#include "decoder.hpp"
#include "encoder.hpp"
#include "event_loop.hpp"
#include "gate.hpp"
#include "process_reference.hpp"
namespace firewall = process::firewall;
namespace metrics = process::metrics;
using process::wait; // Necessary on some OS's to disambiguate.
using process::http::Accepted;
using process::http::BadRequest;
using process::http::Forbidden;
using process::http::InternalServerError;
using process::http::NotFound;
using process::http::OK;
using process::http::Request;
using process::http::Response;
using process::http::ServiceUnavailable;
using process::http::authentication::Authenticator;
using process::http::authentication::AuthenticationResult;
using process::http::authentication::AuthenticatorManager;
using process::http::authorization::AuthorizationCallbacks;
using process::network::Address;
using process::network::Socket;
using std::deque;
using std::find;
using std::list;
using std::map;
using std::ostream;
using std::pair;
using std::queue;
using std::set;
using std::stack;
using std::string;
using std::stringstream;
using std::vector;
namespace process {
namespace ID {
string generate(const string& prefix)
{
static map<string, int>* prefixes = new map<string, int>();
static std::mutex* prefixes_mutex = new std::mutex();
int id;
synchronized (prefixes_mutex) {
int& _id = (*prefixes)[prefix];
_id += 1;
id = _id;
}
return prefix + "(" + stringify(id) + ")";
}
} // namespace ID {
namespace mime {
map<string, string> types;
} // namespace mime {
// Provides a process that manages sending HTTP responses so as to
// satisfy HTTP/1.1 pipelining. Each request should either enqueue a
// response, or ask the proxy to handle a future response. The process
// is responsible for making sure the responses are sent in the same
// order as the requests. Note that we use a 'Socket' in order to keep
// the underlying file descriptor from getting closed while there
// might still be outstanding responses even though the client might
// have closed the connection (see more discussion in
// SocketManager::close and SocketManager::proxy).
class HttpProxy : public Process<HttpProxy>
{
public:
explicit HttpProxy(const Socket& _socket);
virtual ~HttpProxy();
// Enqueues the response to be sent once all previously enqueued
// responses have been processed (e.g., waited for and sent).
void enqueue(const Response& response, const Request& request);
// Enqueues a future to a response that will get waited on (up to
// some timeout) and then sent once all previously enqueued
// responses have been processed (e.g., waited for and sent).
void handle(const Future<Response>& future, const Request& request);
protected:
void initialize() override;
private:
// Starts "waiting" on the next available future response.
void next();
// Invoked once a future response has been satisfied.
void waited(const Future<Response>& future);
// Demuxes and handles a response.
bool process(const Future<Response>& future, const Request& request);
// Handles stream based responses.
void stream(const Owned<Request>& request, const Future<string>& chunk);
Socket socket; // Wrap the socket to keep it from getting closed.
// Describes a queue "item" that wraps the future to the response
// and the original request.
// The original request contains needed information such as what encodings
// are acceptable and whether to persist the connection.
struct Item
{
Item(const Request& _request, const Future<Response>& _future)
: request(_request), future(_future) {}
const Request request; // Make a copy.
Future<Response> future; // Make a copy.
};
queue<Item*> items;
Option<http::Pipe::Reader> pipe; // Current pipe, if streaming.
// We sequence the authentication results exposed to the caller
// in order to satisfy HTTP pipelining.
//
// Note that this needs to be done explicitly here because
// the authentication router does expose ordered completion
// of its Futures (it doesn't have the knowledge of sockets
// necessary to do it in a per-connection manner).
Owned<Sequence> authentications;
};
// Helper for creating routes without a process.
// TODO(benh): Move this into route.hpp.
class Route
{
public:
Route(const string& name,
const Option<string>& help,
const lambda::function<Future<Response>(const Request&)>& handler)
: process(name, help, handler)
{
spawn(process);
}
~Route()
{
terminate(process);
wait(process);
}
private:
class RouteProcess : public Process<RouteProcess>
{
public:
RouteProcess(
const string& name,
const Option<string>& _help,
const lambda::function<Future<Response>(const Request&)>& _handler)
: ProcessBase(strings::remove(name, "/", strings::PREFIX)),
help(_help),
handler(_handler) {}
protected:
virtual void initialize()
{
route("/", help, &RouteProcess::handle);
}
Future<Response> handle(const Request& request)
{
return handler(request);
}
const Option<string> help;
const lambda::function<Future<Response>(const Request&)> handler;
};
RouteProcess process;
};
class SocketManager
{
public:
SocketManager();
~SocketManager();
void accepted(const Socket& socket);
void link(ProcessBase* process,
const UPID& to,
const ProcessBase::RemoteConnection remote,
const Socket::Kind& kind = Socket::DEFAULT_KIND());
// Test-only method to fetch the file descriptor behind a
// persistent socket.
Option<int> get_persistent_socket(const UPID& to);
PID<HttpProxy> proxy(const Socket& socket);
void send(Encoder* encoder, bool persist);
void send(const Response& response,
const Request& request,
const Socket& socket);
void send(Message* message,
const Socket::Kind& kind = Socket::DEFAULT_KIND());
Encoder* next(int s);
void close(int s);
void exited(const Address& address);
void exited(ProcessBase* process);
private:
// TODO(bmahler): Leverage a bidirectional multimap instead, or
// hide the complexity of manipulating 'links' through methods.
struct
{
// For links, we maintain a bidirectional mapping between the
// "linkers" (Processes) and the "linkees" (remote / local UPIDs).
// For remote socket addresses, we also need a mapping to the
// linkees for that socket address, because socket closure only
// notifies at the address level.
hashmap<UPID, hashset<ProcessBase*>> linkers;
hashmap<ProcessBase*, hashset<UPID>> linkees;
hashmap<Address, hashset<UPID>> remotes;
} links;
// Switch the underlying socket that a remote end is talking to.
// This manipulates the data structures below by swapping all data
// mapped to 'from' to being mapped to 'to'. This is useful for
// downgrading a socket from SSL to POLL based.
void swap_implementing_socket(const Socket& from, const Socket& to);
// Helper function for link().
void link_connect(
const Future<Nothing>& future,
Socket socket,
const UPID& to);
// Helper function for send().
void send_connect(
const Future<Nothing>& future,
Socket socket,
Message* message);
// Collection of all active sockets (both inbound and outbound).
map<int, Socket> sockets;
// Collection of sockets that should be disposed when they are
// finished being used (e.g., when there is no more data to send on
// them). Can contain both inbound and outbound sockets.
set<int> dispose;
// Map from socket to socket address for outbound sockets.
map<int, Address> addresses;
// Map from socket address to temporary sockets (outbound sockets
// that will be closed once there is no more data to send on them).
map<Address, int> temps;
// Map from socket address (ip, port) to persistent sockets
// (outbound sockets that will remain open even if there is no more
// data to send on them). We distinguish these from the 'temps'
// collection so we can tell when a persistent socket has been lost
// (and thus generate ExitedEvents).
map<Address, int> persists;
// Map from outbound socket to outgoing queue.
map<int, queue<Encoder*>> outgoing;
// HTTP proxies.
map<int, HttpProxy*> proxies;
// Protects instance variables.
std::recursive_mutex mutex;
};
class ProcessManager
{
public:
explicit ProcessManager(const Option<string>& delegate);
~ProcessManager();
// Initializes the processing threads and the event loop thread,
// and returns the number of processing threads created.
long init_threads();
ProcessReference use(const UPID& pid);
void handle(
const Socket& socket,
Request* request);
bool deliver(
ProcessBase* receiver,
Event* event,
ProcessBase* sender = nullptr);
bool deliver(
const UPID& to,
Event* event,
ProcessBase* sender = nullptr);
UPID spawn(ProcessBase* process, bool manage);
void resume(ProcessBase* process);
void cleanup(ProcessBase* process);
void link(
ProcessBase* process,
const UPID& to,
const ProcessBase::RemoteConnection remote);
void terminate(const UPID& pid, bool inject, ProcessBase* sender = nullptr);
bool wait(const UPID& pid);
void installFirewall(vector<Owned<firewall::FirewallRule>>&& rules);
string absolutePath(const string& path);
void enqueue(ProcessBase* process);
ProcessBase* dequeue();
void settle();
// The /__processes__ route.
Future<Response> __processes__(const Request&);
private:
// Delegate process name to receive root HTTP requests.
const Option<string> delegate;
// Map of all local spawned and running processes.
map<string, ProcessBase*> processes;
std::recursive_mutex processes_mutex;
// Gates for waiting threads (protected by processes_mutex).
map<ProcessBase*, Gate*> gates;
// Queue of runnable processes (implemented using list).
list<ProcessBase*> runq;
std::recursive_mutex runq_mutex;
// Number of running processes, to support Clock::settle operation.
std::atomic_long running;
// Stores the thread handles so that we can join during shutdown.
vector<std::thread*> threads;
// Boolean used to signal processing threads to stop running.
std::atomic_bool joining_threads;
// List of rules applied to all incoming HTTP requests.
vector<Owned<firewall::FirewallRule>> firewallRules;
std::recursive_mutex firewall_mutex;
};
// Server socket listen backlog.
static const int LISTEN_BACKLOG = 500000;
// Local server socket.
static Socket* __s__ = nullptr;
// Local socket address.
static Address __address__;
// Active SocketManager (eventually will probably be thread-local).
static SocketManager* socket_manager = nullptr;
// Active ProcessManager (eventually will probably be thread-local).
static ProcessManager* process_manager = nullptr;
// Scheduling gate that threads wait at when there is nothing to run.
static Gate* gate = new Gate();
// Used for authenticating HTTP requests.
static AuthenticatorManager* authenticator_manager = nullptr;
// Authorization callbacks for HTTP endpoints.
static AuthorizationCallbacks* authorization_callbacks = nullptr;
// Global route that returns process information.
static Route* processes_route = nullptr;
// Filter. Synchronized support for using the filterer needs to be
// recursive in case a filterer wants to do anything fancy (which is
// possible and likely given that filters will get used for testing).
static Filter* filterer = nullptr;
static std::recursive_mutex* filterer_mutex = new std::recursive_mutex();
// Global garbage collector.
GarbageCollector* gc = nullptr;
// Global help.
PID<Help> help;
// Global logging.
PID<Logging> _logging;
// Per thread process pointer.
THREAD_LOCAL ProcessBase* __process__ = nullptr;
// Per thread executor pointer.
THREAD_LOCAL Executor* _executor_ = nullptr;
namespace http {
namespace authentication {
Future<Nothing> setAuthenticator(
const string& realm,
Owned<Authenticator> authenticator)
{
process::initialize();
return authenticator_manager->setAuthenticator(realm, authenticator);
}
Future<Nothing> unsetAuthenticator(const string& realm)
{
process::initialize();
return authenticator_manager->unsetAuthenticator(realm);
}
} // namespace authentication {
namespace authorization {
void setCallbacks(const AuthorizationCallbacks& callbacks)
{
authorization_callbacks = new AuthorizationCallbacks(callbacks);
}
void unsetCallbacks()
{
authorization_callbacks = nullptr;
}
} // namespace authorization {
} // namespace http {
// NOTE: Clock::* implementations are in clock.cpp except for
// Clock::settle which currently has a dependency on
// 'process_manager'.
void Clock::settle()
{
process_manager->settle();
}
static Message* encode(const UPID& from,
const UPID& to,
const string& name,
const string& data = "")
{
Message* message = new Message();
message->from = from;
message->to = to;
message->name = name;
message->body = data;
return message;
}
static void transport(Message* message, ProcessBase* sender = nullptr)
{
if (message->to.address == __address__) {
// Local message.
process_manager->deliver(message->to, new MessageEvent(message), sender);
} else {
// Remote message.
socket_manager->send(message);
}
}
// Returns true if `request` contains an inbound libprocess message.
// A libprocess message can either be sent by another instance of
// libprocess (i.e. both of the "User-Agent" and "Libprocess-From"
// headers will be set), or a client that speaks the libprocess
// protocol (i.e. only the "Libprocess-From" header will be set).
// This function returns true for either case.
static bool libprocess(Request* request)
{
return
(request->method == "POST" &&
request->headers.contains("User-Agent") &&
request->headers["User-Agent"].find("libprocess/") == 0) ||
(request->method == "POST" &&
request->headers.contains("Libprocess-From"));
}
static Message* parse(Request* request)
{
// TODO(benh): Do better error handling (to deal with a malformed
// libprocess message, malicious or otherwise).
// First try and determine 'from'.
Option<UPID> from = None();
if (request->headers.contains("Libprocess-From")) {
from = UPID(strings::trim(request->headers["Libprocess-From"]));
} else {
// Try and get 'from' from the User-Agent.
const string& agent = request->headers["User-Agent"];
const string identifier = "libprocess/";
size_t index = agent.find(identifier);
if (index != string::npos) {
from = UPID(agent.substr(index + identifier.size(), agent.size()));
}
}
if (from.isNone()) {
return nullptr;
}
// Now determine 'to'.
size_t index = request->url.path.find('/', 1);
index = index != string::npos ? index - 1 : string::npos;
// Decode possible percent-encoded 'to'.
Try<string> decode = http::decode(request->url.path.substr(1, index));
if (decode.isError()) {
VLOG(2) << "Failed to decode URL path: " << decode.get();
return nullptr;
}
const UPID to(decode.get(), __address__);
// And now determine 'name'.
index = index != string::npos ? index + 2: request->url.path.size();
const string name = request->url.path.substr(index);
VLOG(2) << "Parsed message name '" << name
<< "' for " << to << " from " << from.get();
Message* message = new Message();
message->name = name;
message->from = from.get();
message->to = to;
message->body = request->body;
return message;
}
namespace internal {
void decode_recv(
const Future<size_t>& length,
char* data,
size_t size,
Socket socket,
DataDecoder* decoder)
{
if (length.isDiscarded() || length.isFailed()) {
if (length.isFailed()) {
VLOG(1) << "Decode failure: " << length.failure();
}
socket_manager->close(socket);
delete[] data;
delete decoder;
return;
}
if (length.get() == 0) {
socket_manager->close(socket);
delete[] data;
delete decoder;
return;
}
// Decode as much of the data as possible into HTTP requests.
const deque<Request*> requests = decoder->decode(data, length.get());
if (requests.empty() && decoder->failed()) {
VLOG(1) << "Decoder error while receiving";
socket_manager->close(socket);
delete[] data;
delete decoder;
return;
}
if (!requests.empty()) {
// Get the peer address to augment the requests.
Try<Address> address = socket.peer();
if (address.isError()) {
VLOG(1) << "Failed to get peer address while receiving: "
<< address.error();
socket_manager->close(socket);
delete[] data;
delete decoder;
return;
}
foreach (Request* request, requests) {
request->client = address.get();
process_manager->handle(decoder->socket(), request);
}
}
socket.recv(data, size)
.onAny(lambda::bind(&decode_recv, lambda::_1, data, size, socket, decoder));
}
} // namespace internal {
void timedout(const list<Timer>& timers)
{
// Update current time of process (if it's present/valid). Note that
// current time may be greater than the timeout if a local message
// was received (and happens-before kicks in).
if (Clock::paused()) {
foreach (const Timer& timer, timers) {
if (ProcessReference process = process_manager->use(timer.creator())) {
Clock::update(process, timer.timeout().time());
}
}
}
// Invoke the timers that timed out (TODO(benh): Do this
// asynchronously so that we don't tie up the event thread!).
foreach (const Timer& timer, timers) {
timer();
}
}
// We might find value in catching terminating signals at some point.
// However, for now, adding signal handlers freely is not allowed
// because they will clash with Java and Python virtual machines and
// causes hard to debug crashes/segfaults.
// void sigbad(int signal, struct sigcontext *ctx)
// {
// // Pass on the signal (so that a core file is produced).
// struct sigaction sa;
// sa.sa_handler = SIG_DFL;
// sigemptyset(&sa.sa_mask);
// sa.sa_flags = 0;
// sigaction(signal, &sa, nullptr);
// raise(signal);
// }
namespace internal {
void on_accept(const Future<Socket>& socket)
{
if (socket.isReady()) {
// Inform the socket manager for proper bookkeeping.
socket_manager->accepted(socket.get());
const size_t size = 80 * 1024;
char* data = new char[size];
DataDecoder* decoder = new DataDecoder(socket.get());
socket.get().recv(data, size)
.onAny(lambda::bind(
&internal::decode_recv,
lambda::_1,
data,
size,
socket.get(),
decoder));
}
__s__->accept()
.onAny(lambda::bind(&on_accept, lambda::_1));
}
} // namespace internal {
namespace firewall {
void install(vector<Owned<FirewallRule>>&& rules)
{
process::initialize();
process_manager->installFirewall(std::move(rules));
}
} // namespace firewall {
bool initialize(
const Option<string>& delegate,
const Option<string>& readwriteAuthenticationRealm,
const Option<string>& readonlyAuthenticationRealm)
{
// TODO(benh): Return an error if attempting to initialize again
// with a different delegate than originally specified.
// NOTE: Rather than calling `initialize` once at the root of the
// dependency tree; we currently rely on libprocess dependency
// declaration by invoking `initialize` prior to use. This is done
// frequently throughout the code base. Therefore we chose to use
// atomics rather than `Once`, as the overhead of a mutex and
// condition variable is excessive here.
static std::atomic_bool initialize_started(false);
static std::atomic_bool initialize_complete(false);
// Try and do the initialization or wait for it to complete.
// If already initialized, there's nothing more to do.
// NOTE: This condition is true as soon as the thread performing
// initialization sets `initialize_complete` to `true` in the *middle*
// of initialization. This is done because some methods called by
// initialization will themselves call `process::initialize`.
if (initialize_started.load() && initialize_complete.load()) {
// Return `false` because `process::initialize()` was already called.
return false;
} else {
// NOTE: `compare_exchange_strong` needs an lvalue.
bool expected = false;
// Any thread that calls `initialize` prior to when `initialize_complete`
// is set to `true` will reach this.
// Atomically sets `initialize_started` to `true`. The thread that
// successfully sets `initialize_started` to `true` will move on to
// perform the initialization logic. All others will wait here for
// initialization to complete.
if (!initialize_started.compare_exchange_strong(expected, true)) {
while (!initialize_complete.load());
// Return `false` because `process::initialize()` was already called.
return false;
}
}
// We originally tried to leave SIGPIPE unblocked and to work
// around SIGPIPE in order to avoid imposing policy on users
// of libprocess. However, for pipes and files, the manual
// suppression of SIGPIPE had become onerous. Also, OS X
// appears to deliver SIGPIPE to the process rather than
// the triggering thread. It is better to just silence it
// and use EPIPE instead. See MESOS-2079 and related tickets.
//
// TODO(bmahler): Should libprocess finalization restore the
// previous handler?
//
// TODO(bmahler): Consider removing SO_NOSIGPIPE and MSG_NOSIGNAL
// to avoid confusion, now that they are no longer relevant.
signal(SIGPIPE, SIG_IGN);
#ifdef USE_SSL_SOCKET
// Notify users of the 'LIBPROCESS_SSL_SUPPORT_DOWNGRADE' flag that
// this setting allows insecure connections.
if (network::openssl::flags().support_downgrade) {
LOG(WARNING) <<
"Failed SSL connections will be downgraded to a non-SSL socket";
}
#endif
// Create a new ProcessManager and SocketManager.
process_manager = new ProcessManager(delegate);
socket_manager = new SocketManager();
// Initialize the event loop.
EventLoop::initialize();
// Setup processing threads.
long num_worker_threads = process_manager->init_threads();
Clock::initialize(lambda::bind(&timedout, lambda::_1));
__address__ = Address::LOCALHOST_ANY();
// Check environment for ip.
Option<string> value = os::getenv("LIBPROCESS_IP");
if (value.isSome()) {
Try<net::IP> ip = net::IP::parse(value.get(), AF_INET);
if (ip.isError()) {
LOG(FATAL) << "Parsing LIBPROCESS_IP=" << value.get()
<< " failed: " << ip.error();
}
__address__.ip = ip.get();
}
// Check environment for port.
value = os::getenv("LIBPROCESS_PORT");
if (value.isSome()) {
Try<int> result = numify<int>(value.get().c_str());
if (result.isSome() && result.get() >=0 && result.get() <= USHRT_MAX) {
__address__.port = result.get();
} else {
LOG(FATAL) << "LIBPROCESS_PORT=" << value.get() << " is not a valid port";
}
}
// Create a "server" socket for communicating.
Try<Socket> create = Socket::create();
if (create.isError()) {
PLOG(FATAL) << "Failed to construct server socket:" << create.error();
}
__s__ = new Socket(create.get());
// Allow address reuse.
// NOTE: We cast to `char*` here because the function prototypes on Windows
// use `char*` instead of `void*`.
int on = 1;
if (::setsockopt(
__s__->get(),
SOL_SOCKET,
SO_REUSEADDR,
reinterpret_cast<char*>(&on),
sizeof(on)) < 0) {
PLOG(FATAL) << "Failed to initialize, setsockopt(SO_REUSEADDR)";
}
Try<Address> bind = __s__->bind(__address__);
if (bind.isError()) {
PLOG(FATAL) << "Failed to initialize: " << bind.error();
}
__address__ = bind.get();
// If advertised IP and port are present, use them instead.
value = os::getenv("LIBPROCESS_ADVERTISE_IP");
if (value.isSome()) {
Try<net::IP> ip = net::IP::parse(value.get(), AF_INET);
if (ip.isError()) {
LOG(FATAL) << "Parsing LIBPROCESS_ADVERTISE_IP=" << value.get()
<< " failed: " << ip.error();
}
__address__.ip = ip.get();
}
value = os::getenv("LIBPROCESS_ADVERTISE_PORT");
if (value.isSome()) {
Try<int> result = numify<int>(value.get().c_str());
if (result.isSome() && result.get() >=0 && result.get() <= USHRT_MAX) {
__address__.port = result.get();
} else {
LOG(FATAL) << "LIBPROCESS_ADVERTISE_PORT=" << value.get()
<< " is not a valid port";
}
}
// Lookup hostname if missing ip or if ip is 0.0.0.0 in case we
// actually have a valid external ip address. Note that we need only
// one ip address, so that other processes can send and receive and
// don't get confused as to whom they are sending to.
if (__address__.ip.isAny()) {
char hostname[512];
if (gethostname(hostname, sizeof(hostname)) < 0) {
LOG(FATAL) << "Failed to initialize, gethostname: "
<< os::hstrerror(h_errno);
}
// Lookup IP address of local hostname.
Try<net::IP> ip = net::getIP(hostname, __address__.ip.family());
if (ip.isError()) {
EXIT(EXIT_FAILURE)
<< "Failed to obtain the IP address for '" << hostname << "';"
<< " the DNS service may not be able to resolve it: " << ip.error();
}
__address__.ip = ip.get();
}
Try<Nothing> listen = __s__->listen(LISTEN_BACKLOG);
if (listen.isError()) {
PLOG(FATAL) << "Failed to initialize: " << listen.error();
}