Home | History | Annotate | Download | only in metrics
      1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 //
      5 // A StatsTable is a table of statistics.  It can be used across multiple
      6 // processes and threads, maintaining cheap statistics counters without
      7 // locking.
      8 //
      9 // The goal is to make it very cheap and easy for developers to add
     10 // counters to code, without having to build one-off utilities or mechanisms
     11 // to track the counters, and also to allow a single "view" to display
     12 // the contents of all counters.
     13 //
     14 // To achieve this, StatsTable creates a shared memory segment to store
     15 // the data for the counters.  Upon creation, it has a specific size
     16 // which governs the maximum number of counters and concurrent
     17 // threads/processes which can use it.
     18 //
     19 
     20 #ifndef BASE_METRICS_STATS_TABLE_H_
     21 #define BASE_METRICS_STATS_TABLE_H_
     22 
     23 #include <string>
     24 
     25 #include "base/base_export.h"
     26 #include "base/basictypes.h"
     27 #include "base/containers/hash_tables.h"
     28 #include "base/memory/shared_memory.h"
     29 #include "base/synchronization/lock.h"
     30 #include "base/threading/thread_local_storage.h"
     31 
     32 namespace base {
     33 
     34 class BASE_EXPORT StatsTable {
     35  public:
     36   // Create a new StatsTable.
     37   // If a StatsTable already exists with the specified name, this StatsTable
     38   // will use the same shared memory segment as the original.  Otherwise,
     39   // a new StatsTable is created and all counters are zeroed.
     40   //
     41   // name is the name of the StatsTable to use.
     42   //
     43   // max_threads is the maximum number of threads the table will support.
     44   // If the StatsTable already exists, this number is ignored.
     45   //
     46   // max_counters is the maximum number of counters the table will support.
     47   // If the StatsTable already exists, this number is ignored.
     48   StatsTable(const std::string& name, int max_threads, int max_counters);
     49 
     50   // Destroys the StatsTable.  When the last StatsTable is destroyed
     51   // (across all processes), the StatsTable is removed from disk.
     52   ~StatsTable();
     53 
     54   // For convenience, we create a static table.  This is generally
     55   // used automatically by the counters.
     56   static StatsTable* current();
     57 
     58   // Set the global table for use in this process.
     59   static void set_current(StatsTable* value);
     60 
     61   // Get the slot id for the calling thread. Returns 0 if no
     62   // slot is assigned.
     63   int GetSlot() const;
     64 
     65   // All threads that contribute data to the table must register with the
     66   // table first.  This function will set thread local storage for the
     67   // thread containing the location in the table where this thread will
     68   // write its counter data.
     69   //
     70   // name is just a debugging tag to label the thread, and it does not
     71   // need to be unique.  It will be truncated to kMaxThreadNameLength-1
     72   // characters.
     73   //
     74   // On success, returns the slot id for this thread.  On failure,
     75   // returns 0.
     76   int RegisterThread(const std::string& name);
     77 
     78   // Returns the number of threads currently registered.  This is really not
     79   // useful except for diagnostics and debugging.
     80   int CountThreadsRegistered() const;
     81 
     82   // Find a counter in the StatsTable.
     83   //
     84   // Returns an id for the counter which can be used to call GetLocation().
     85   // If the counter does not exist, attempts to create a row for the new
     86   // counter.  If there is no space in the table for the new counter,
     87   // returns 0.
     88   int FindCounter(const std::string& name);
     89 
     90   // TODO(mbelshe): implement RemoveCounter.
     91 
     92   // Gets the location of a particular value in the table based on
     93   // the counter id and slot id.
     94   int* GetLocation(int counter_id, int slot_id) const;
     95 
     96   // Gets the counter name at a particular row.  If the row is empty,
     97   // returns NULL.
     98   const char* GetRowName(int index) const;
     99 
    100   // Gets the sum of the values for a particular row.
    101   int GetRowValue(int index) const;
    102 
    103   // Gets the sum of the values for a particular row for a given pid.
    104   int GetRowValue(int index, int pid) const;
    105 
    106   // Gets the sum of the values for a particular counter.  If the counter
    107   // does not exist, creates the counter.
    108   int GetCounterValue(const std::string& name);
    109 
    110   // Gets the sum of the values for a particular counter for a given pid.
    111   // If the counter does not exist, creates the counter.
    112   int GetCounterValue(const std::string& name, int pid);
    113 
    114   // The maxinum number of counters/rows in the table.
    115   int GetMaxCounters() const;
    116 
    117   // The maxinum number of threads/columns in the table.
    118   int GetMaxThreads() const;
    119 
    120 #if defined(OS_POSIX)
    121   // Get the underlying shared memory handle for the table.
    122   base::SharedMemoryHandle GetSharedMemoryHandle() const;
    123 #endif
    124 
    125   // The maximum length (in characters) of a Thread's name including
    126   // null terminator, as stored in the shared memory.
    127   static const int kMaxThreadNameLength = 32;
    128 
    129   // The maximum length (in characters) of a Counter's name including
    130   // null terminator, as stored in the shared memory.
    131   static const int kMaxCounterNameLength = 64;
    132 
    133   // Convenience function to lookup a counter location for a
    134   // counter by name for the calling thread.  Will register
    135   // the thread if it is not already registered.
    136   static int* FindLocation(const char *name);
    137 
    138  private:
    139   class Internal;
    140   struct TLSData;
    141   typedef hash_map<std::string, int> CountersMap;
    142 
    143   // Returns the space occupied by a thread in the table.  Generally used
    144   // if a thread terminates but the process continues.  This function
    145   // does not zero out the thread's counters.
    146   // Cannot be used inside a posix tls destructor.
    147   void UnregisterThread();
    148 
    149   // This variant expects the tls data to be passed in, so it is safe to
    150   // call from inside a posix tls destructor (see doc for pthread_key_create).
    151   void UnregisterThread(TLSData* tls_data);
    152 
    153   // The SlotReturnFunction is called at thread exit for each thread
    154   // which used the StatsTable.
    155   static void SlotReturnFunction(void* data);
    156 
    157   // Locates a free slot in the table.  Returns a number > 0 on success,
    158   // or 0 on failure.  The caller must hold the shared_memory lock when
    159   // calling this function.
    160   int FindEmptyThread() const;
    161 
    162   // Locates a counter in the table or finds an empty row.  Returns a
    163   // number > 0 on success, or 0 on failure.  The caller must hold the
    164   // shared_memory_lock when calling this function.
    165   int FindCounterOrEmptyRow(const std::string& name) const;
    166 
    167   // Internal function to add a counter to the StatsTable.  Assumes that
    168   // the counter does not already exist in the table.
    169   //
    170   // name is a unique identifier for this counter, and will be truncated
    171   // to kMaxCounterNameLength-1 characters.
    172   //
    173   // On success, returns the counter_id for the newly added counter.
    174   // On failure, returns 0.
    175   int AddCounter(const std::string& name);
    176 
    177   // Get the TLS data for the calling thread.  Returns NULL if none is
    178   // initialized.
    179   TLSData* GetTLSData() const;
    180 
    181   Internal* internal_;
    182 
    183   // The counters_lock_ protects the counters_ hash table.
    184   base::Lock counters_lock_;
    185 
    186   // The counters_ hash map is an in-memory hash of the counters.
    187   // It is used for quick lookup of counters, but is cannot be used
    188   // as a substitute for what is in the shared memory.  Even though
    189   // we don't have a counter in our hash table, another process may
    190   // have created it.
    191   CountersMap counters_;
    192   ThreadLocalStorage::Slot tls_index_;
    193 
    194   DISALLOW_COPY_AND_ASSIGN(StatsTable);
    195 };
    196 
    197 }  // namespace base
    198 
    199 #endif  // BASE_METRICS_STATS_TABLE_H_
    200