1 /* Copyright 2015-present Facebook, Inc.
2 * Licensed under the Apache License, Version 2.0 */
3
4 #include "watchman.h"
5
6 /* Periodically connect to our endpoint and verify that we're talking
7 * to ourselves. This is normally a sign of madness, but if we don't
8 * get an answer, or get a reply from someone else, we know things
9 * are bad; someone removed our socket file or there was some kind of
10 * race condition that resulted in multiple instances starting up.
11 */
12
check_my_sock()13 static void check_my_sock() {
14 auto cmd = json_array({typed_string_to_json("get-pid", W_STRING_UNICODE)});
15 w_jbuffer_t buf;
16 json_error_t jerr;
17 json_int_t remote_pid = 0;
18 pid_t my_pid = getpid();
19
20 w_set_thread_name("sockcheck");
21
22 auto client = w_stm_connect(get_sock_name(), 6000);
23 if (!client) {
24 w_log(W_LOG_FATAL, "Failed to connect to myself for get-pid check: %s\n",
25 strerror(errno));
26 /* NOTREACHED */
27 }
28
29 client->setNonBlock(false);
30
31 if (!buf.pduEncodeToStream(is_bser, 0, cmd, client.get())) {
32 w_log(W_LOG_FATAL, "Failed to send get-pid PDU: %s\n",
33 strerror(errno));
34 /* NOTREACHED */
35 }
36
37 buf.clear();
38 auto result = buf.decodeNext(client.get(), &jerr);
39 if (!result) {
40 w_log(W_LOG_FATAL, "Failed to decode get-pid response: %s %s\n",
41 jerr.text, strerror(errno));
42 /* NOTREACHED */
43 }
44
45 if (json_unpack_ex(result, &jerr, 0, "{s:i}",
46 "pid", &remote_pid) != 0) {
47 w_log(W_LOG_FATAL, "Failed to extract pid from get-pid response: %s\n",
48 jerr.text);
49 /* NOTREACHED */
50 }
51
52 if (remote_pid != my_pid) {
53 w_log(W_LOG_FATAL,
54 "remote pid from get-pid (%ld) doesn't match my pid (%ld)\n",
55 (long)remote_pid, (long)my_pid);
56 /* NOTREACHED */
57 }
58 }
59
w_check_my_sock(void)60 void w_check_my_sock(void) {
61 std::thread thr(check_my_sock);
62 thr.detach();
63 }
64
65 /* vim:ts=2:sw=2:et:
66 */
67