hashtablez_sampler.h
Go to the documentation of this file.
00001 // Copyright 2018 The Abseil Authors.
00002 //
00003 // Licensed under the Apache License, Version 2.0 (the "License");
00004 // you may not use this file except in compliance with the License.
00005 // You may obtain a copy of the License at
00006 //
00007 //      https://www.apache.org/licenses/LICENSE-2.0
00008 //
00009 // Unless required by applicable law or agreed to in writing, software
00010 // distributed under the License is distributed on an "AS IS" BASIS,
00011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00012 // See the License for the specific language governing permissions and
00013 // limitations under the License.
00014 //
00015 // -----------------------------------------------------------------------------
00016 // File: hashtablez_sampler.h
00017 // -----------------------------------------------------------------------------
00018 //
00019 // This header file defines the API for a low level library to sample hashtables
00020 // and collect runtime statistics about them.
00021 //
00022 // `HashtablezSampler` controls the lifecycle of `HashtablezInfo` objects which
00023 // store information about a single sample.
00024 //
00025 // `Record*` methods store information into samples.
00026 // `Sample()` and `Unsample()` make use of a single global sampler with
00027 // properties controlled by the flags hashtablez_enabled,
00028 // hashtablez_sample_rate, and hashtablez_max_samples.
00029 //
00030 // WARNING
00031 //
00032 // Using this sampling API may cause sampled Swiss tables to use the global
00033 // allocator (operator `new`) in addition to any custom allocator.  If you
00034 // are using a table in an unusual circumstance where allocation or calling a
00035 // linux syscall is unacceptable, this could interfere.
00036 //
00037 // This utility is internal-only. Use at your own risk.
00038 
00039 #ifndef ABSL_CONTAINER_INTERNAL_HASHTABLEZ_SAMPLER_H_
00040 #define ABSL_CONTAINER_INTERNAL_HASHTABLEZ_SAMPLER_H_
00041 
00042 #include <atomic>
00043 #include <functional>
00044 #include <memory>
00045 #include <vector>
00046 
00047 #include "absl/base/internal/per_thread_tls.h"
00048 #include "absl/base/optimization.h"
00049 #include "absl/container/internal/have_sse.h"
00050 #include "absl/synchronization/mutex.h"
00051 #include "absl/utility/utility.h"
00052 
00053 namespace absl {
00054 namespace container_internal {
00055 
00056 // Stores information about a sampled hashtable.  All mutations to this *must*
00057 // be made through `Record*` functions below.  All reads from this *must* only
00058 // occur in the callback to `HashtablezSampler::Iterate`.
00059 struct HashtablezInfo {
00060   // Constructs the object but does not fill in any fields.
00061   HashtablezInfo();
00062   ~HashtablezInfo();
00063   HashtablezInfo(const HashtablezInfo&) = delete;
00064   HashtablezInfo& operator=(const HashtablezInfo&) = delete;
00065 
00066   // Puts the object into a clean state, fills in the logically `const` members,
00067   // blocking for any readers that are currently sampling the object.
00068   void PrepareForSampling() EXCLUSIVE_LOCKS_REQUIRED(init_mu);
00069 
00070   // These fields are mutated by the various Record* APIs and need to be
00071   // thread-safe.
00072   std::atomic<size_t> capacity;
00073   std::atomic<size_t> size;
00074   std::atomic<size_t> num_erases;
00075   std::atomic<size_t> max_probe_length;
00076   std::atomic<size_t> total_probe_length;
00077   std::atomic<size_t> hashes_bitwise_or;
00078   std::atomic<size_t> hashes_bitwise_and;
00079 
00080   // `HashtablezSampler` maintains intrusive linked lists for all samples.  See
00081   // comments on `HashtablezSampler::all_` for details on these.  `init_mu`
00082   // guards the ability to restore the sample to a pristine state.  This
00083   // prevents races with sampling and resurrecting an object.
00084   absl::Mutex init_mu;
00085   HashtablezInfo* next;
00086   HashtablezInfo* dead GUARDED_BY(init_mu);
00087 
00088   // All of the fields below are set by `PrepareForSampling`, they must not be
00089   // mutated in `Record*` functions.  They are logically `const` in that sense.
00090   // These are guarded by init_mu, but that is not externalized to clients, who
00091   // can only read them during `HashtablezSampler::Iterate` which will hold the
00092   // lock.
00093   static constexpr int kMaxStackDepth = 64;
00094   absl::Time create_time;
00095   int32_t depth;
00096   void* stack[kMaxStackDepth];
00097 };
00098 
00099 inline void RecordRehashSlow(HashtablezInfo* info, size_t total_probe_length) {
00100 #if SWISSTABLE_HAVE_SSE2
00101   total_probe_length /= 16;
00102 #else
00103   total_probe_length /= 8;
00104 #endif
00105   info->total_probe_length.store(total_probe_length, std::memory_order_relaxed);
00106   info->num_erases.store(0, std::memory_order_relaxed);
00107 }
00108 
00109 inline void RecordStorageChangedSlow(HashtablezInfo* info, size_t size,
00110                                      size_t capacity) {
00111   info->size.store(size, std::memory_order_relaxed);
00112   info->capacity.store(capacity, std::memory_order_relaxed);
00113   if (size == 0) {
00114     // This is a clear, reset the total/num_erases too.
00115     RecordRehashSlow(info, 0);
00116   }
00117 }
00118 
00119 void RecordInsertSlow(HashtablezInfo* info, size_t hash,
00120                       size_t distance_from_desired);
00121 
00122 inline void RecordEraseSlow(HashtablezInfo* info) {
00123   info->size.fetch_sub(1, std::memory_order_relaxed);
00124   info->num_erases.fetch_add(1, std::memory_order_relaxed);
00125 }
00126 
00127 HashtablezInfo* SampleSlow(int64_t* next_sample);
00128 void UnsampleSlow(HashtablezInfo* info);
00129 
00130 class HashtablezInfoHandle {
00131  public:
00132   explicit HashtablezInfoHandle() : info_(nullptr) {}
00133   explicit HashtablezInfoHandle(HashtablezInfo* info) : info_(info) {}
00134   ~HashtablezInfoHandle() {
00135     if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
00136     UnsampleSlow(info_);
00137   }
00138 
00139   HashtablezInfoHandle(const HashtablezInfoHandle&) = delete;
00140   HashtablezInfoHandle& operator=(const HashtablezInfoHandle&) = delete;
00141 
00142   HashtablezInfoHandle(HashtablezInfoHandle&& o) noexcept
00143       : info_(absl::exchange(o.info_, nullptr)) {}
00144   HashtablezInfoHandle& operator=(HashtablezInfoHandle&& o) noexcept {
00145     if (ABSL_PREDICT_FALSE(info_ != nullptr)) {
00146       UnsampleSlow(info_);
00147     }
00148     info_ = absl::exchange(o.info_, nullptr);
00149     return *this;
00150   }
00151 
00152   inline void RecordStorageChanged(size_t size, size_t capacity) {
00153     if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
00154     RecordStorageChangedSlow(info_, size, capacity);
00155   }
00156 
00157   inline void RecordRehash(size_t total_probe_length) {
00158     if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
00159     RecordRehashSlow(info_, total_probe_length);
00160   }
00161 
00162   inline void RecordInsert(size_t hash, size_t distance_from_desired) {
00163     if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
00164     RecordInsertSlow(info_, hash, distance_from_desired);
00165   }
00166 
00167   inline void RecordErase() {
00168     if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
00169     RecordEraseSlow(info_);
00170   }
00171 
00172   friend inline void swap(HashtablezInfoHandle& lhs,
00173                           HashtablezInfoHandle& rhs) {
00174     std::swap(lhs.info_, rhs.info_);
00175   }
00176 
00177  private:
00178   friend class HashtablezInfoHandlePeer;
00179   HashtablezInfo* info_;
00180 };
00181 
00182 #if ABSL_PER_THREAD_TLS == 1
00183 extern ABSL_PER_THREAD_TLS_KEYWORD int64_t global_next_sample;
00184 #endif  // ABSL_PER_THREAD_TLS
00185 
00186 // Returns an RAII sampling handle that manages registration and unregistation
00187 // with the global sampler.
00188 inline HashtablezInfoHandle Sample() {
00189 #if ABSL_PER_THREAD_TLS == 0
00190   static auto* mu = new absl::Mutex;
00191   static int64_t global_next_sample = 0;
00192   absl::MutexLock l(mu);
00193 #endif  // !ABSL_HAVE_THREAD_LOCAL
00194 
00195   if (ABSL_PREDICT_TRUE(--global_next_sample > 0)) {
00196     return HashtablezInfoHandle(nullptr);
00197   }
00198   return HashtablezInfoHandle(SampleSlow(&global_next_sample));
00199 }
00200 
00201 // Holds samples and their associated stack traces with a soft limit of
00202 // `SetHashtablezMaxSamples()`.
00203 //
00204 // Thread safe.
00205 class HashtablezSampler {
00206  public:
00207   // Returns a global Sampler.
00208   static HashtablezSampler& Global();
00209 
00210   HashtablezSampler();
00211   ~HashtablezSampler();
00212 
00213   // Registers for sampling.  Returns an opaque registration info.
00214   HashtablezInfo* Register();
00215 
00216   // Unregisters the sample.
00217   void Unregister(HashtablezInfo* sample);
00218 
00219   // The dispose callback will be called on all samples the moment they are
00220   // being unregistered. Only affects samples that are unregistered after the
00221   // callback has been set.
00222   // Returns the previous callback.
00223   using DisposeCallback = void (*)(const HashtablezInfo&);
00224   DisposeCallback SetDisposeCallback(DisposeCallback f);
00225 
00226   // Iterates over all the registered `StackInfo`s.  Returning the number of
00227   // samples that have been dropped.
00228   int64_t Iterate(const std::function<void(const HashtablezInfo& stack)>& f);
00229 
00230  private:
00231   void PushNew(HashtablezInfo* sample);
00232   void PushDead(HashtablezInfo* sample);
00233   HashtablezInfo* PopDead();
00234 
00235   std::atomic<size_t> dropped_samples_;
00236   std::atomic<size_t> size_estimate_;
00237 
00238   // Intrusive lock free linked lists for tracking samples.
00239   //
00240   // `all_` records all samples (they are never removed from this list) and is
00241   // terminated with a `nullptr`.
00242   //
00243   // `graveyard_.dead` is a circular linked list.  When it is empty,
00244   // `graveyard_.dead == &graveyard`.  The list is circular so that
00245   // every item on it (even the last) has a non-null dead pointer.  This allows
00246   // `Iterate` to determine if a given sample is live or dead using only
00247   // information on the sample itself.
00248   //
00249   // For example, nodes [A, B, C, D, E] with [A, C, E] alive and [B, D] dead
00250   // looks like this (G is the Graveyard):
00251   //
00252   //           +---+    +---+    +---+    +---+    +---+
00253   //    all -->| A |--->| B |--->| C |--->| D |--->| E |
00254   //           |   |    |   |    |   |    |   |    |   |
00255   //   +---+   |   | +->|   |-+  |   | +->|   |-+  |   |
00256   //   | G |   +---+ |  +---+ |  +---+ |  +---+ |  +---+
00257   //   |   |         |        |        |        |
00258   //   |   | --------+        +--------+        |
00259   //   +---+                                    |
00260   //     ^                                      |
00261   //     +--------------------------------------+
00262   //
00263   std::atomic<HashtablezInfo*> all_;
00264   HashtablezInfo graveyard_;
00265 
00266   std::atomic<DisposeCallback> dispose_;
00267 };
00268 
00269 // Enables or disables sampling for Swiss tables.
00270 void SetHashtablezEnabled(bool enabled);
00271 
00272 // Sets the rate at which Swiss tables will be sampled.
00273 void SetHashtablezSampleParameter(int32_t rate);
00274 
00275 // Sets a soft max for the number of samples that will be kept.
00276 void SetHashtablezMaxSamples(int32_t max);
00277 
00278 // Configuration override.
00279 // This allows process-wide sampling without depending on order of
00280 // initialization of static storage duration objects.
00281 // The definition of this constant is weak, which allows us to inject a
00282 // different value for it at link time.
00283 extern "C" const bool kAbslContainerInternalSampleEverything;
00284 
00285 }  // namespace container_internal
00286 }  // namespace absl
00287 
00288 #endif  // ABSL_CONTAINER_INTERNAL_HASHTABLEZ_SAMPLER_H_


abseil_cpp
Author(s):
autogenerated on Wed Jun 19 2019 19:42:14