You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@kudu.apache.org by al...@apache.org on 2019/01/03 01:53:59 UTC

[1/3] kudu git commit: [location_awareness] Assign locations to clients

Repository: kudu
Updated Branches:
  refs/heads/master 236fdfe83 -> c7a2d69fb


[location_awareness] Assign locations to clients

This patch makes it so the client is assigned a location by each master
as part of the ConnectToMaster RPC (which is part of the
ConnectToCluster process). The client will store the location it is
assigned by the leader master and potentially update it every time it
reconnects to the cluster.

This assignment will be used in a follow-up to implement location-aware
semantics for CLOSEST_REPLICA scans.

Change-Id: I0efb327293d86168a30b05305f69d011ad15587a
Reviewed-on: http://gerrit.cloudera.org:8080/11923
Tested-by: Kudu Jenkins
Reviewed-by: Adar Dembo <ad...@cloudera.com>


Project: http://git-wip-us.apache.org/repos/asf/kudu/repo
Commit: http://git-wip-us.apache.org/repos/asf/kudu/commit/4a3e7c00
Tree: http://git-wip-us.apache.org/repos/asf/kudu/tree/4a3e7c00
Diff: http://git-wip-us.apache.org/repos/asf/kudu/diff/4a3e7c00

Branch: refs/heads/master
Commit: 4a3e7c0006555c872d0e3a0d78b94a1edfab0d21
Parents: 236fdfe
Author: fwang29 <fw...@cloudera.com>
Authored: Mon Nov 12 23:52:42 2018 -0800
Committer: Will Berkeley <wd...@gmail.com>
Committed: Fri Dec 21 23:03:08 2018 +0000

----------------------------------------------------------------------
 src/kudu/client/CMakeLists.txt     |  3 ++-
 src/kudu/client/client-internal.cc |  2 ++
 src/kudu/client/client-internal.h  |  7 +++++-
 src/kudu/client/client-test.cc     | 31 +++++++++++++++++++++--
 src/kudu/client/client.cc          |  5 ++++
 src/kudu/client/client.h           |  7 ++++++
 src/kudu/master/CMakeLists.txt     |  3 ++-
 src/kudu/master/master-test.cc     | 44 +++++++++++++++++++++++++++++++++
 src/kudu/master/master.proto       |  3 +++
 src/kudu/master/master_service.cc  | 17 +++++++++++++
 src/kudu/master/ts_descriptor.cc   |  9 +------
 src/kudu/master/ts_descriptor.h    | 12 +++++++++
 12 files changed, 130 insertions(+), 13 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/kudu/blob/4a3e7c00/src/kudu/client/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/src/kudu/client/CMakeLists.txt b/src/kudu/client/CMakeLists.txt
index b800a9d..e10a05f 100644
--- a/src/kudu/client/CMakeLists.txt
+++ b/src/kudu/client/CMakeLists.txt
@@ -261,7 +261,8 @@ SET_KUDU_TEST_LINK_LIBS(
   itest_util
   kudu_client
   mini_cluster)
-ADD_KUDU_TEST(client-test NUM_SHARDS 8 PROCESSORS 2)
+ADD_KUDU_TEST(client-test NUM_SHARDS 8 PROCESSORS 2
+                          DATA_FILES ../scripts/first_argument.sh)
 ADD_KUDU_TEST(client-unittest)
 ADD_KUDU_TEST(predicate-test)
 ADD_KUDU_TEST(scan_token-test PROCESSORS 2)

http://git-wip-us.apache.org/repos/asf/kudu/blob/4a3e7c00/src/kudu/client/client-internal.cc
----------------------------------------------------------------------
diff --git a/src/kudu/client/client-internal.cc b/src/kudu/client/client-internal.cc
index 8300ecc..ded9787 100644
--- a/src/kudu/client/client-internal.cc
+++ b/src/kudu/client/client-internal.cc
@@ -706,6 +706,8 @@ void KuduClient::Data::ConnectedToClusterCb(
       hive_metastore_sasl_enabled_ = hive_config.hms_sasl_enabled();
       hive_metastore_uuid_ = hive_config.hms_uuid();
 
+      location_ = connect_response.client_location();
+
       master_proxy_.reset(new MasterServiceProxy(messenger_, leader_addr, leader_hostname));
       master_proxy_->set_user_credentials(user_credentials_);
     }

http://git-wip-us.apache.org/repos/asf/kudu/blob/4a3e7c00/src/kudu/client/client-internal.h
----------------------------------------------------------------------
diff --git a/src/kudu/client/client-internal.h b/src/kudu/client/client-internal.h
index e359114..74b1a10 100644
--- a/src/kudu/client/client-internal.h
+++ b/src/kudu/client/client-internal.h
@@ -244,6 +244,10 @@ class KuduClient::Data {
   // The unique id of this client.
   std::string client_id_;
 
+  // The location of this client. This is an empty string if a location has not
+  // been assigned by the leader master. Protected by 'leader_master_lock_'.
+  std::string location_;
+
   // The user credentials of the client. This field is constant after the client
   // is built.
   rpc::UserCredentials user_credentials_;
@@ -292,7 +296,8 @@ class KuduClient::Data {
   std::vector<StatusCallback> leader_master_callbacks_primary_creds_;
 
   // Protects 'leader_master_rpc_{any,primary}_creds_',
-  // 'leader_master_hostport_', 'master_hostports_', and 'master_proxy_'.
+  // 'leader_master_hostport_', 'master_hostports_', 'master_proxy_', and
+  // 'location_'.
   //
   // See: KuduClient::Data::ConnectToClusterAsync for a more
   // in-depth explanation of why this is needed and how it works.

http://git-wip-us.apache.org/repos/asf/kudu/blob/4a3e7c00/src/kudu/client/client-test.cc
----------------------------------------------------------------------
diff --git a/src/kudu/client/client-test.cc b/src/kudu/client/client-test.cc
index 10a4c6c..dee5d45 100644
--- a/src/kudu/client/client-test.cc
+++ b/src/kudu/client/client-test.cc
@@ -130,6 +130,7 @@ DECLARE_int32(scanner_inject_latency_on_each_batch_ms);
 DECLARE_int32(scanner_max_batch_size_bytes);
 DECLARE_int32(scanner_ttl_ms);
 DECLARE_int32(table_locations_ttl_ms);
+DECLARE_string(location_mapping_cmd);
 DECLARE_string(superuser_acl);
 DECLARE_string(user_acl);
 DEFINE_int32(test_scan_num_rows, 1000, "Number of rows to insert and scan");
@@ -188,14 +189,16 @@ class ClientTest : public KuduTest {
     FLAGS_heartbeat_interval_ms = 10;
     FLAGS_scanner_gc_check_interval_us = 50 * 1000; // 50 milliseconds.
 
+    SetLocationMappingCmd();
+
     // Start minicluster and wait for tablet servers to connect to master.
     cluster_.reset(new InternalMiniCluster(env_, InternalMiniClusterOptions()));
     ASSERT_OK(cluster_->Start());
 
     // Connect to the cluster.
     ASSERT_OK(KuduClientBuilder()
-                     .add_master_server_addr(cluster_->mini_master()->bound_rpc_addr().ToString())
-                     .Build(&client_));
+        .add_master_server_addr(cluster_->mini_master()->bound_rpc_addr().ToString())
+        .Build(&client_));
 
     ASSERT_NO_FATAL_FAILURE(CreateTable(kTableName, 1, GenerateSplitRows(), {}, &client_table_));
   }
@@ -277,6 +280,10 @@ class ClientTest : public KuduTest {
   static const char *kTableName;
   static const int32_t kNoBound;
 
+  // Set the location mapping command for the test's masters. Overridden by
+  // derived classes to test client location assignment.
+  virtual void SetLocationMappingCmd() {}
+
   string GetFirstTabletId(KuduTable* table) {
     GetTableLocationsRequestPB req;
     GetTableLocationsResponsePB resp;
@@ -5779,5 +5786,25 @@ TEST_F(ClientTest, TestBlockScannerHijackingAttempts) {
   }
 }
 
+// Client test that assigns locations to clients and tablet servers.
+// For now, assigns a uniform location to all clients and tablet servers.
+class ClientWithLocationTest : public ClientTest {
+ protected:
+  void SetLocationMappingCmd() override {
+    const string location_cmd_path = JoinPathSegments(GetTestExecutableDirectory(),
+                                                      "testdata/first_argument.sh");
+    const string location = "/foo";
+    FLAGS_location_mapping_cmd = strings::Substitute("$0 $1",
+                                                     location_cmd_path, location);
+  }
+};
+
+TEST_F(ClientTest, TestClientLocationNoLocationMappingCmd) {
+  ASSERT_TRUE(client_->location().empty());
+}
+
+TEST_F(ClientWithLocationTest, TestClientLocation) {
+  ASSERT_EQ("/foo", client_->location());
+}
 } // namespace client
 } // namespace kudu

http://git-wip-us.apache.org/repos/asf/kudu/blob/4a3e7c00/src/kudu/client/client.cc
----------------------------------------------------------------------
diff --git a/src/kudu/client/client.cc b/src/kudu/client/client.cc
index c475f49..720a81d 100644
--- a/src/kudu/client/client.cc
+++ b/src/kudu/client/client.cc
@@ -663,6 +663,11 @@ string KuduClient::GetHiveMetastoreUuid() const {
   return data_->hive_metastore_uuid_;
 }
 
+string KuduClient::location() const {
+  std::lock_guard<simple_spinlock> l(data_->leader_master_lock_);
+  return data_->location_;
+}
+
 ////////////////////////////////////////////////////////////
 // KuduTableCreator
 ////////////////////////////////////////////////////////////

http://git-wip-us.apache.org/repos/asf/kudu/blob/4a3e7c00/src/kudu/client/client.h
----------------------------------------------------------------------
diff --git a/src/kudu/client/client.h b/src/kudu/client/client.h
index f8a9fc1..f3486df 100644
--- a/src/kudu/client/client.h
+++ b/src/kudu/client/client.h
@@ -585,6 +585,13 @@ class KUDU_EXPORT KuduClient : public sp::enable_shared_from_this<KuduClient> {
   ///   arbitrary value if the Hive Metastore integration is not enabled.
   std::string GetHiveMetastoreUuid() const KUDU_NO_EXPORT;
 
+  /// Private API.
+  ///
+  /// @return The location of the client, assigned when it first connects to
+  ///   a cluster. An empty string will be returned if no location has been
+  ///   assigned yet, or if the leader master did not assign a location to
+  ///   the client.
+  std::string location() const KUDU_NO_EXPORT;
   /// @endcond
 
  private:

http://git-wip-us.apache.org/repos/asf/kudu/blob/4a3e7c00/src/kudu/master/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/src/kudu/master/CMakeLists.txt b/src/kudu/master/CMakeLists.txt
index 9b536b7..89fd9c6 100644
--- a/src/kudu/master/CMakeLists.txt
+++ b/src/kudu/master/CMakeLists.txt
@@ -79,7 +79,8 @@ SET_KUDU_TEST_LINK_LIBS(
 
 ADD_KUDU_TEST(catalog_manager-test)
 ADD_KUDU_TEST(hms_notification_log_listener-test)
-ADD_KUDU_TEST(master-test RESOURCE_LOCK "master-web-port")
+ADD_KUDU_TEST(master-test RESOURCE_LOCK "master-web-port"
+                          DATA_FILES ../scripts/first_argument.sh)
 ADD_KUDU_TEST(mini_master-test RESOURCE_LOCK "master-web-port")
 ADD_KUDU_TEST(placement_policy-test)
 ADD_KUDU_TEST(sentry_authz_provider-test)

http://git-wip-us.apache.org/repos/asf/kudu/blob/4a3e7c00/src/kudu/master/master-test.cc
----------------------------------------------------------------------
diff --git a/src/kudu/master/master-test.cc b/src/kudu/master/master-test.cc
index 5916448..54dac9d 100644
--- a/src/kudu/master/master-test.cc
+++ b/src/kudu/master/master-test.cc
@@ -1619,6 +1619,50 @@ TEST_F(MasterTest, TestConnectToMaster) {
   ASSERT_EQ(1, resp.master_addrs_size());
   ASSERT_EQ("127.0.0.1", resp.master_addrs(0).host());
   ASSERT_NE(0, resp.master_addrs(0).port());
+
+  // The returned location should be empty because no location mapping command
+  // is defined.
+  ASSERT_TRUE(resp.client_location().empty());
+}
+
+TEST_F(MasterTest, TestConnectToMasterAndAssignLocation) {
+  // Test first with a valid location mapping command.
+  const string kLocationCmdPath = JoinPathSegments(GetTestExecutableDirectory(),
+                                                   "testdata/first_argument.sh");
+  const string location = "/foo";
+  FLAGS_location_mapping_cmd = Substitute("$0 $1", kLocationCmdPath, location);
+  {
+    ConnectToMasterRequestPB req;
+    ConnectToMasterResponsePB resp;
+    RpcController rpc;
+    ASSERT_OK(proxy_->ConnectToMaster(req, &resp, &rpc));
+    ASSERT_FALSE(resp.has_error());
+    ASSERT_EQ(location, resp.client_location());
+  }
+
+  // Now try again with an invalid command. The RPC should succeed but no
+  // location should be assigned.
+  FLAGS_location_mapping_cmd = "false";
+  {
+    ConnectToMasterRequestPB req;
+    ConnectToMasterResponsePB resp;
+    RpcController rpc;
+    ASSERT_OK(proxy_->ConnectToMaster(req, &resp, &rpc));
+    ASSERT_FALSE(resp.has_error());
+    ASSERT_TRUE(resp.client_location().empty());
+  }
+
+  // Finally, use a command returning a different location.
+  const string new_location = "/bar";
+  FLAGS_location_mapping_cmd = Substitute("$0 $1", kLocationCmdPath, new_location);
+  {
+    ConnectToMasterRequestPB req;
+    ConnectToMasterResponsePB resp;
+    RpcController rpc;
+    ASSERT_OK(proxy_->ConnectToMaster(req, &resp, &rpc));
+    ASSERT_FALSE(resp.has_error());
+    ASSERT_EQ(new_location, resp.client_location());
+  }
 }
 
 // Test that the master signs its on server certificate when it becomes the leader,

http://git-wip-us.apache.org/repos/asf/kudu/blob/4a3e7c00/src/kudu/master/master.proto
----------------------------------------------------------------------
diff --git a/src/kudu/master/master.proto b/src/kudu/master/master.proto
index 393394f..583644c 100644
--- a/src/kudu/master/master.proto
+++ b/src/kudu/master/master.proto
@@ -673,6 +673,9 @@ message ConnectToMasterResponsePB {
   // If the master is configured with the Hive Metastore integration enabled,
   // this field will include the configuration options.
   optional HiveMetastoreConfig hms_config = 6;
+
+  // The location of the client assigned by the master.
+  optional string client_location = 7;
 }
 
 // Hive Metastore integration options and configuration.

http://git-wip-us.apache.org/repos/asf/kudu/blob/4a3e7c00/src/kudu/master/master_service.cc
----------------------------------------------------------------------
diff --git a/src/kudu/master/master_service.cc b/src/kudu/master/master_service.cc
index ef1edb5..b87e681 100644
--- a/src/kudu/master/master_service.cc
+++ b/src/kudu/master/master_service.cc
@@ -57,6 +57,7 @@
 DECLARE_bool(hive_metastore_sasl_enabled);
 DECLARE_bool(raft_prepare_replacement_before_eviction);
 DECLARE_string(hive_metastore_uris);
+DECLARE_string(location_mapping_cmd);
 
 DEFINE_int32(master_inject_latency_on_tablet_lookups_ms, 0,
              "Number of milliseconds that the master will sleep before responding to "
@@ -522,6 +523,22 @@ void MasterServiceImpl::ConnectToMaster(const ConnectToMasterRequestPB* /*req*/,
     // TODO(dan): set the hms_uuid field.
   }
 
+  // Assign a location to the client if needed.
+  if (!FLAGS_location_mapping_cmd.empty()) {
+    string location;
+    Status s = GetLocationFromLocationMappingCmd(FLAGS_location_mapping_cmd,
+                                                 rpc->remote_address().host(),
+                                                 &location);
+    if (s.ok()) {
+      resp->set_client_location(location);
+    } else {
+      LOG(WARNING) << Substitute("unable to assign location to client $0@$1: $2",
+                                 rpc->remote_user().ToString(),
+                                 rpc->remote_address().ToString(),
+                                 s.ToString());
+    }
+  }
+
   // Rather than consulting the current consensus role, instead base it
   // on the catalog manager's view. This prevents us from advertising LEADER
   // until we have taken over all the associated responsibilities.

http://git-wip-us.apache.org/repos/asf/kudu/blob/4a3e7c00/src/kudu/master/ts_descriptor.cc
----------------------------------------------------------------------
diff --git a/src/kudu/master/ts_descriptor.cc b/src/kudu/master/ts_descriptor.cc
index 3a400b2..321b2fd 100644
--- a/src/kudu/master/ts_descriptor.cc
+++ b/src/kudu/master/ts_descriptor.cc
@@ -95,13 +95,8 @@ bool IsValidLocation(const string& location) {
   }
   return true;
 }
+} // anonymous namespace
 
-// Resolves 'host', which is the IP address or hostname of a tablet server or
-// client, into a location using the command 'cmd'. The result will be stored
-// in 'location', which must not be null. If there is an error running the
-// command or the output is invalid, an error Status will be returned.
-// TODO(wdberkeley): Eventually we may want to get multiple locations at once
-// by giving the script multiple arguments (like Hadoop).
 Status GetLocationFromLocationMappingCmd(const string& cmd,
                                          const string& host,
                                          string* location) {
@@ -132,7 +127,6 @@ Status GetLocationFromLocationMappingCmd(const string& cmd,
   *location = std::move(location_temp);
   return Status::OK();
 }
-} // anonymous namespace
 
 Status TSDescriptor::RegisterNew(const NodeInstancePB& instance,
                                  const ServerRegistrationPB& registration,
@@ -404,6 +398,5 @@ string TSDescriptor::ToString() const {
   const auto& addr = registration_->rpc_addresses(0);
   return Substitute("$0 ($1:$2)", permanent_uuid_, addr.host(), addr.port());
 }
-
 } // namespace master
 } // namespace kudu

http://git-wip-us.apache.org/repos/asf/kudu/blob/4a3e7c00/src/kudu/master/ts_descriptor.h
----------------------------------------------------------------------
diff --git a/src/kudu/master/ts_descriptor.h b/src/kudu/master/ts_descriptor.h
index c7fdd60..65724fe 100644
--- a/src/kudu/master/ts_descriptor.h
+++ b/src/kudu/master/ts_descriptor.h
@@ -53,6 +53,18 @@ class TabletServerAdminServiceProxy;
 
 namespace master {
 
+// Resolves 'host', which is the IP address or hostname of a tablet server or
+// client, into a location using the command 'cmd'. The result will be stored
+// in 'location', which must not be null. If there is an error running the
+// command or the output is invalid, an error Status will be returned.
+// TODO(wdberkeley): Refactor into a separate class and implement a caching
+// policy.
+// TODO(wdberkeley): Eventually we may want to get multiple locations at once
+// by giving the script multiple arguments (like Hadoop).
+Status GetLocationFromLocationMappingCmd(const std::string& cmd,
+                                         const std::string& host,
+                                         std::string* location);
+
 // Master-side view of a single tablet server.
 //
 // Tracks the last heartbeat, status, instance identifier, location, etc.


[2/3] kudu git commit: [python] handle DisableOpenSSLInitialization() result status

Posted by al...@apache.org.
[python] handle DisableOpenSSLInitialization() result status

This patch adds verification for DisableOpenSSLInitialization().

The motivation for this change is two-fold:
  a) avoid glitches while initializing the OpenSSL library
     by python Kudu client if DisableOpenSSLInitialization()
     de facto failed
  b) get rid of compilation warnings on unhandled return value
     of the DisableOpenSSLInitialization() function

Change-Id: I1963b6d87d731fbfa87a09b986595aa8ea00da60
Reviewed-on: http://gerrit.cloudera.org:8080/12135
Tested-by: Alexey Serbin <as...@cloudera.com>
Reviewed-by: Adar Dembo <ad...@cloudera.com>


Project: http://git-wip-us.apache.org/repos/asf/kudu/repo
Commit: http://git-wip-us.apache.org/repos/asf/kudu/commit/7337cf5f
Tree: http://git-wip-us.apache.org/repos/asf/kudu/tree/7337cf5f
Diff: http://git-wip-us.apache.org/repos/asf/kudu/diff/7337cf5f

Branch: refs/heads/master
Commit: 7337cf5fbffa954dab9f21fe6115f6df3ba7c6c7
Parents: 4a3e7c0
Author: Alexey Serbin <al...@apache.org>
Authored: Thu Dec 27 10:32:28 2018 -0800
Committer: Alexey Serbin <as...@cloudera.com>
Committed: Wed Jan 2 20:17:04 2019 +0000

----------------------------------------------------------------------
 python/kudu/client.pyx | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/kudu/blob/7337cf5f/python/kudu/client.pyx
----------------------------------------------------------------------
diff --git a/python/kudu/client.pyx b/python/kudu/client.pyx
index 095488d..a37bd93 100644
--- a/python/kudu/client.pyx
+++ b/python/kudu/client.pyx
@@ -290,10 +290,11 @@ cdef class Client:
         # whether _ssl is present, and if we can import it, we disable
         # Kudu's initialization to avoid a conflict.
         try:
-          import _ssl
-          DisableOpenSSLInitialization()
+            import _ssl
         except:
-          pass
+            pass
+        else:
+            check_status(DisableOpenSSLInitialization())
 
         if isinstance(addr_or_addrs, six.string_types):
             addr_or_addrs = [addr_or_addrs]


[3/3] kudu git commit: [util] use lighter locking scheme for ThreadMgr

Posted by al...@apache.org.
[util] use lighter locking scheme for ThreadMgr

Use the rw_spinlock primitive to guard the ThreadMgr's registry
threads instead of Mutex.  Also, use the shared lock pattern to deal
with write and read access to the guarded entities of the ThreadMgr.
In addition, do not hold the lock for the whole duration of generating
the /threadz page for the embedded webserver.

With this patch, ThreadMgr now uses std::unordered_map as a container
for category-specific thread information and enforces stricter
consistency rules while removing thread information from its registry.
The process of adding an information about a thread into the registry
is not guarded by stricter consistency checks (i.e. it stays as it was
before this patch); see below for explanation.

NOTE:
  The stricter consistency around adding a thread into the ThreadMgr's
  registry caused issues with multiprocessing in Python tests,
  and I spent some time trying to work around that.  However, that was
  not fruitful.  I think the proper solution would be keeping the thread
  registry bound to some top-level object (like Kudu client or
  ServerBase object) and cleaning it up in accordance with the object's
  life cycle.

  In essence, the problem happens due to the combination of the
  following:
    * The way how workers are spawned by the multiprocessing.Pool,
      i.e. calling fork() at the point where Pool is instantiated.
    * The fact that pthread_t handles might be the same for threads
      in different processes.

  In detail, if multiprocessing.Pool is spawning worker processes after
  an instance of Kudu client has been created in the main test process,
  every worker gets a copy of the thread registry in its address space.
  The unexpected copy of the registry in a worker process is populated
  with the information on threads spawned due to the activity of the
  Kudu client in the main test process.  Later on, if a worker
  instantiates a Kudu client on its own, the newly spawned threads by
  the worker's Kudu client might have the same pthread_t handles
  as the threads whose information records are inadvertently inherited
  from the main test process.

  Also, it turned out it's impossible to handle worker's crash in a
  multiprocessing.Pool, and that's by design: for details see:
    https://stackoverflow.com/questions/24894682/

  BTW, in Python 3 the problem with the duplicated address space
  in worker processes has been resolved by using context and additional
  worker spawn modes (e.g., 'forkserver').

Change-Id: I4d49c1c39392e01c45019844430a4fe3d116c277
Reviewed-on: http://gerrit.cloudera.org:8080/12112
Reviewed-by: Adar Dembo <ad...@cloudera.com>
Tested-by: Kudu Jenkins


Project: http://git-wip-us.apache.org/repos/asf/kudu/repo
Commit: http://git-wip-us.apache.org/repos/asf/kudu/commit/c7a2d69f
Tree: http://git-wip-us.apache.org/repos/asf/kudu/tree/c7a2d69f
Diff: http://git-wip-us.apache.org/repos/asf/kudu/diff/c7a2d69f

Branch: refs/heads/master
Commit: c7a2d69fbd4f0a6f3b0938c31a439049f3733767
Parents: 7337cf5
Author: Alexey Serbin <al...@apache.org>
Authored: Wed Dec 19 13:23:03 2018 -0800
Committer: Alexey Serbin <as...@cloudera.com>
Committed: Thu Jan 3 01:53:05 2019 +0000

----------------------------------------------------------------------
 src/kudu/util/os-util.cc |  23 ++---
 src/kudu/util/thread.cc  | 206 +++++++++++++++++++++++++-----------------
 2 files changed, 131 insertions(+), 98 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/kudu/blob/c7a2d69f/src/kudu/util/os-util.cc
----------------------------------------------------------------------
diff --git a/src/kudu/util/os-util.cc b/src/kudu/util/os-util.cc
index df7761f..85ceb9f 100644
--- a/src/kudu/util/os-util.cc
+++ b/src/kudu/util/os-util.cc
@@ -29,7 +29,7 @@
 #include <unistd.h>
 
 #include <cstddef>
-#include <fstream>
+#include <ostream>
 #include <string>
 #include <utility>
 #include <vector>
@@ -45,10 +45,8 @@
 #include "kudu/util/env.h"
 #include "kudu/util/faststring.h"
 #include "kudu/util/logging.h"
+#include "kudu/util/status.h"
 
-using std::ifstream;
-using std::istreambuf_iterator;
-using std::ostringstream;
 using std::string;
 using std::vector;
 using strings::Split;
@@ -75,7 +73,7 @@ static const int64_t kIoWait = 41 - 2;
 // Largest offset we are interested in, to check we get a well formed stat file.
 static const int64_t kMaxOffset = kIoWait;
 
-Status ParseStat(const std::string& buffer, std::string* name, ThreadStats* stats) {
+Status ParseStat(const string& buffer, string* name, ThreadStats* stats) {
   DCHECK(stats != nullptr);
 
   // The thread name should be the only field with parentheses. But the name
@@ -117,18 +115,11 @@ Status GetThreadStats(int64_t tid, ThreadStats* stats) {
   if (kTicksPerSec <= 0) {
     return Status::NotSupported("ThreadStats not supported");
   }
+  faststring buf;
+  RETURN_NOT_OK(ReadFileToString(
+      Env::Default(), Substitute("/proc/self/task/$0/stat", tid), &buf));
 
-  ostringstream proc_path;
-  proc_path << "/proc/self/task/" << tid << "/stat";
-  ifstream proc_file(proc_path.str().c_str());
-  if (!proc_file.is_open()) {
-    return Status::IOError("Could not open ifstream");
-  }
-
-  string buffer((istreambuf_iterator<char>(proc_file)),
-      istreambuf_iterator<char>());
-
-  return ParseStat(buffer, nullptr, stats); // don't want the name
+  return ParseStat(buf.ToString(), nullptr, stats);
 }
 
 void DisableCoreDumps() {

http://git-wip-us.apache.org/repos/asf/kudu/blob/c7a2d69f/src/kudu/util/thread.cc
----------------------------------------------------------------------
diff --git a/src/kudu/util/thread.cc b/src/kudu/util/thread.cc
index bb53f5a..e134a27 100644
--- a/src/kudu/util/thread.cc
+++ b/src/kudu/util/thread.cc
@@ -30,6 +30,7 @@
 #include <cstring>
 #include <map>
 #include <memory>
+#include <mutex>
 #include <sstream>
 #include <unordered_map>
 #include <utility>
@@ -44,6 +45,7 @@
 #include "kudu/gutil/bind.h"
 #include "kudu/gutil/bind_helpers.h"
 #include "kudu/gutil/dynamic_annotations.h"
+#include "kudu/gutil/map-util.h"
 #include "kudu/gutil/mathlimits.h"
 #include "kudu/gutil/once.h"
 #include "kudu/gutil/port.h"
@@ -51,10 +53,10 @@
 #include "kudu/util/env.h"
 #include "kudu/util/flag_tags.h"
 #include "kudu/util/kernel_stack_watchdog.h"
+#include "kudu/util/locks.h"
 #include "kudu/util/logging.h"
 #include "kudu/util/metrics.h"
 #include "kudu/util/monotime.h"
-#include "kudu/util/mutex.h"
 #include "kudu/util/os-util.h"
 #include "kudu/util/scoped_cleanup.h"
 #include "kudu/util/stopwatch.h"
@@ -64,12 +66,12 @@
 
 using boost::bind;
 using boost::mem_fn;
-using std::endl;
 using std::map;
 using std::ostringstream;
 using std::shared_ptr;
 using std::string;
 using std::vector;
+using std::unordered_map;
 using strings::Substitute;
 
 METRIC_DEFINE_gauge_uint64(server, threads_started,
@@ -162,13 +164,13 @@ class ThreadMgr {
   }
 
   ~ThreadMgr() {
-    MutexLock l(lock_);
     thread_categories_.clear();
   }
 
-  static void SetThreadName(const std::string& name, int64_t tid);
+  static void SetThreadName(const string& name, int64_t tid);
 
-  Status StartInstrumentation(const scoped_refptr<MetricEntity>& metrics, WebCallbackRegistry* web);
+  Status StartInstrumentation(const scoped_refptr<MetricEntity>& metrics,
+                              WebCallbackRegistry* web) const;
 
   // Registers a thread to the supplied category. The key is a pthread_t,
   // not the system TID, since pthread_t is less prone to being recycled.
@@ -180,7 +182,7 @@ class ThreadMgr {
   void RemoveThread(const pthread_t& pthread_id, const string& category);
 
   // Metric callback for number of threads running. Also used for error messages.
-  uint64_t ReadThreadsRunning();
+  uint64_t ReadThreadsRunning() const;
 
  private:
   // Container class for any details we want to capture about a thread
@@ -204,18 +206,29 @@ class ThreadMgr {
     int64_t thread_id_;
   };
 
+  struct ThreadIdHash {
+    size_t operator()(pthread_t thread_id) const noexcept {
+      return std::hash<pthread_t>()(thread_id);
+    }
+  };
+
+  struct ThreadIdEqual {
+    bool operator()(pthread_t lhs, pthread_t rhs) const {
+      return pthread_equal(lhs, rhs) != 0;
+    }
+  };
+
   // A ThreadCategory is a set of threads that are logically related.
-  // TODO: unordered_map is incompatible with pthread_t, but would be more
-  // efficient here.
-  typedef map<const pthread_t, ThreadDescriptor> ThreadCategory;
+  typedef unordered_map<const pthread_t, ThreadDescriptor,
+                        ThreadIdHash, ThreadIdEqual> ThreadCategory;
 
-  // All thread categorys, keyed on the category name.
-  typedef map<string, ThreadCategory> ThreadCategoryMap;
+  // All thread categories, keyed on the category name.
+  typedef unordered_map<string, ThreadCategory> ThreadCategoryMap;
 
   // Protects thread_categories_ and thread metrics.
-  Mutex lock_;
+  mutable rw_spinlock lock_;
 
-  // All thread categorys that ever contained a thread, even if empty
+  // All thread categories that ever contained a thread, even if empty.
   ThreadCategoryMap thread_categories_;
 
   // Counters to track all-time total number of threads, and the
@@ -224,12 +237,13 @@ class ThreadMgr {
   uint64_t threads_running_metric_;
 
   // Metric callback for number of threads started.
-  uint64_t ReadThreadsStarted();
+  uint64_t ReadThreadsStarted() const;
 
   // Webpage callback; prints all threads by category.
   void ThreadPathHandler(const WebCallbackRegistry::WebRequest& req,
-                         WebCallbackRegistry::PrerenderedWebResponse* resp);
-  void PrintThreadCategoryRows(const ThreadCategory& category, ostringstream* output);
+                         WebCallbackRegistry::PrerenderedWebResponse* resp) const;
+  void PrintThreadDescriptorRow(const ThreadDescriptor& desc,
+                                ostringstream* output) const;
 };
 
 void ThreadMgr::SetThreadName(const string& name, int64_t tid) {
@@ -258,9 +272,7 @@ void ThreadMgr::SetThreadName(const string& name, int64_t tid) {
 }
 
 Status ThreadMgr::StartInstrumentation(const scoped_refptr<MetricEntity>& metrics,
-                                       WebCallbackRegistry* web) {
-  MutexLock l(lock_);
-
+                                       WebCallbackRegistry* web) const {
   // Use function gauges here so that we can register a unique copy of these metrics in
   // multiple tservers, even though the ThreadMgr is itself a singleton.
   metrics->NeverRetire(
@@ -292,13 +304,13 @@ Status ThreadMgr::StartInstrumentation(const scoped_refptr<MetricEntity>& metric
   return Status::OK();
 }
 
-uint64_t ThreadMgr::ReadThreadsStarted() {
-  MutexLock l(lock_);
+uint64_t ThreadMgr::ReadThreadsStarted() const {
+  shared_lock<decltype(lock_)> l(lock_);
   return threads_started_metric_;
 }
 
-uint64_t ThreadMgr::ReadThreadsRunning() {
-  MutexLock l(lock_);
+uint64_t ThreadMgr::ReadThreadsRunning() const {
+  shared_lock<decltype(lock_)> l(lock_);
   return threads_running_metric_;
 }
 
@@ -319,10 +331,23 @@ void ThreadMgr::AddThread(const pthread_t& pthread_id, const string& name,
   ANNOTATE_IGNORE_SYNC_BEGIN();
   ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN();
   {
-    MutexLock l(lock_);
-    thread_categories_[category][pthread_id] = ThreadDescriptor(category, name, tid);
-    threads_running_metric_++;
-    threads_started_metric_++;
+    // NOTE: Not using EmplaceOrDie() here -- that's because in environments
+    //   where fork() is called after some threads have been spawned, child
+    //   processes will inadvertently inherit the contents of the thread
+    //   registry (i.e. the entries in the thread_categories_ container).
+    //   For some platforms, pthread_t handles for threads in different
+    //   processes might be the same, so using EmplaceOrDie() would induce
+    //   a crash when ThreadMgr::AddThread() is called for a new thread
+    //   in the child process.
+    //
+    // TODO(aserbin): maybe, keep the thread_categories_ registry not in a
+    //   global static container, but bind the container with the life cycle
+    //   of some top-level object that uses the ThreadMgr as a singleton.
+    std::lock_guard<decltype(lock_)> l(lock_);
+    thread_categories_[category][pthread_id] =
+        ThreadDescriptor(category, name, tid);
+    ++threads_running_metric_;
+    ++threads_started_metric_;
   }
   ANNOTATE_IGNORE_SYNC_END();
   ANNOTATE_IGNORE_READS_AND_WRITES_END();
@@ -332,77 +357,94 @@ void ThreadMgr::RemoveThread(const pthread_t& pthread_id, const string& category
   ANNOTATE_IGNORE_SYNC_BEGIN();
   ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN();
   {
-    MutexLock l(lock_);
-    auto category_it = thread_categories_.find(category);
-    DCHECK(category_it != thread_categories_.end());
-    category_it->second.erase(pthread_id);
-    threads_running_metric_--;
+    std::lock_guard<decltype(lock_)> l(lock_);
+    auto& threads = FindOrDie(thread_categories_, category);
+    auto num_erased = threads.erase(pthread_id);
+    CHECK_EQ(1, num_erased);
+    --threads_running_metric_;
   }
   ANNOTATE_IGNORE_SYNC_END();
   ANNOTATE_IGNORE_READS_AND_WRITES_END();
 }
 
-void ThreadMgr::PrintThreadCategoryRows(const ThreadCategory& category,
-    ostringstream* output) {
-  for (const ThreadCategory::value_type& thread : category) {
-    ThreadStats stats;
-    Status status = GetThreadStats(thread.second.thread_id(), &stats);
-    if (!status.ok()) {
-      KLOG_EVERY_N(INFO, 100) << "Could not get per-thread statistics: "
-                              << status.ToString();
-    }
-    (*output) << "<tr><td>" << thread.second.name() << "</td><td>"
-              << (static_cast<double>(stats.user_ns) / 1e9) << "</td><td>"
-              << (static_cast<double>(stats.kernel_ns) / 1e9) << "</td><td>"
-              << (static_cast<double>(stats.iowait_ns) / 1e9) << "</td></tr>";
+void ThreadMgr::PrintThreadDescriptorRow(const ThreadDescriptor& desc,
+                                         ostringstream* output) const {
+  ThreadStats stats;
+  Status status = GetThreadStats(desc.thread_id(), &stats);
+  if (!status.ok()) {
+    KLOG_EVERY_N(INFO, 100) << "Could not get per-thread statistics: "
+                            << status.ToString();
   }
+  (*output) << "<tr><td>" << desc.name() << "</td><td>"
+            << (static_cast<double>(stats.user_ns) / 1e9) << "</td><td>"
+            << (static_cast<double>(stats.kernel_ns) / 1e9) << "</td><td>"
+            << (static_cast<double>(stats.iowait_ns) / 1e9) << "</td></tr>";
 }
 
-void ThreadMgr::ThreadPathHandler(const WebCallbackRegistry::WebRequest& req,
-                                  WebCallbackRegistry::PrerenderedWebResponse* resp) {
-  ostringstream* output = resp->output;
-  MutexLock l(lock_);
-  vector<const ThreadCategory*> categories_to_print;
-  auto category_name = req.parsed_args.find("group");
+void ThreadMgr::ThreadPathHandler(
+    const WebCallbackRegistry::WebRequest& req,
+    WebCallbackRegistry::PrerenderedWebResponse* resp) const {
+  ostringstream& output = *(resp->output);
+  vector<ThreadDescriptor> descriptors_to_print;
+  const auto category_name = req.parsed_args.find("group");
   if (category_name != req.parsed_args.end()) {
-    string group = EscapeForHtmlToString(category_name->second);
-    (*output) << "<h2>Thread Group: " << group << "</h2>" << endl;
+    const auto& group = category_name->second;
+    const auto& group_esc = EscapeForHtmlToString(group);
+    output << "<h2>Thread Group: " << group_esc << "</h2>";
     if (group != "all") {
-      ThreadCategoryMap::const_iterator category = thread_categories_.find(group);
-      if (category == thread_categories_.end()) {
-        (*output) << "Thread group '" << group << "' not found" << endl;
+      shared_lock<decltype(lock_)> l(lock_);
+      const auto it = thread_categories_.find(group);
+      if (it == thread_categories_.end()) {
+        output << "Thread group '" << group_esc << "' not found";
         return;
       }
-      categories_to_print.push_back(&category->second);
-      (*output) << "<h3>" << category->first << " : " << category->second.size()
-                << "</h3>";
+      for (const auto& elem : it->second) {
+        descriptors_to_print.push_back(elem.second);
+      }
+      output << "<h3>" << it->first << " : " << it->second.size() << "</h3>";
     } else {
-      for (const ThreadCategoryMap::value_type& category : thread_categories_) {
-        categories_to_print.push_back(&category.second);
+      shared_lock<decltype(lock_)> l(lock_);
+      for (const auto& category : thread_categories_) {
+        for (const auto& elem : category.second) {
+          descriptors_to_print.push_back(elem.second);
+        }
       }
-      (*output) << "<h3>All Threads : </h3>";
+      output << "<h3>All Threads : </h3>";
     }
-
-    (*output) << "<table class='table table-hover table-border'>";
-    (*output) << "<thead><tr><th>Thread name</th><th>Cumulative User CPU(s)</th>"
-              << "<th>Cumulative Kernel CPU(s)</th>"
-              << "<th>Cumulative IO-wait(s)</th></tr></thead>";
-    (*output) << "<tbody>\n";
-
-    for (const ThreadCategory* category : categories_to_print) {
-      PrintThreadCategoryRows(*category, output);
+    output << "<table class='table table-hover table-border'>"
+              "<thead><tr><th>Thread name</th><th>Cumulative User CPU(s)</th>"
+              "<th>Cumulative Kernel CPU(s)</th>"
+              "<th>Cumulative IO-wait(s)</th></tr></thead>"
+              "<tbody>\n";
+    // Sort the entries in the table by the name of a thread.
+    // TODO(aserbin): use "mustache + fancy table" instead.
+    std::sort(descriptors_to_print.begin(), descriptors_to_print.end(),
+              [](const ThreadDescriptor& lhs, const ThreadDescriptor& rhs) {
+                return lhs.name() < rhs.name();
+              });
+    for (const auto& desc : descriptors_to_print) {
+      PrintThreadDescriptorRow(desc, &output);
     }
-    (*output) << "</tbody></table>";
+    output << "</tbody></table>";
   } else {
-    (*output) << "<h2>Thread Groups</h2>";
-    (*output) << "<h4>" << threads_running_metric_ << " thread(s) running";
-    (*output) << "<a href='/threadz?group=all'><h3>All Threads</h3>";
-
-    for (const ThreadCategoryMap::value_type& category : thread_categories_) {
+    // Using the tree map (std::map) to have the list of the thread categories
+    // at the '/threadz' page sorted alphabetically.
+    // TODO(aserbin): use "mustache + fancy table" instead.
+    map<string, size_t> thread_categories_info;
+    {
+      shared_lock<decltype(lock_)> l(lock_);
+      output << "<h2>Thread Groups</h2>"
+                "<h4>" << threads_running_metric_ << " thread(s) running"
+                "<a href='/threadz?group=all'><h3>All Threads</h3>";
+      for (const auto& category : thread_categories_) {
+        thread_categories_info.emplace(category.first, category.second.size());
+      }
+    }
+    for (const auto& elem : thread_categories_info) {
       string category_arg;
-      UrlEncode(category.first, &category_arg);
-      (*output) << "<a href='/threadz?group=" << category_arg << "'><h3>"
-                << category.first << " : " << category.second.size() << "</h3></a>";
+      UrlEncode(elem.first, &category_arg);
+      output << "<a href='/threadz?group=" << category_arg << "'><h3>"
+             << elem.first << " : " << elem.second << "</h3></a>";
     }
   }
 }
@@ -496,7 +538,7 @@ Thread::~Thread() {
   }
 }
 
-std::string Thread::ToString() const {
+string Thread::ToString() const {
   return Substitute("Thread $0 (name: \"$1\", category: \"$2\")", tid(), name_, category_);
 }
 
@@ -513,7 +555,7 @@ int64_t Thread::WaitForTid() const {
 }
 
 
-Status Thread::StartThread(const std::string& category, const std::string& name,
+Status Thread::StartThread(const string& category, const string& name,
                            const ThreadFunctor& functor, uint64_t flags,
                            scoped_refptr<Thread> *holder) {
   TRACE_COUNTER_INCREMENT("threads_started", 1);