1 // Copyright (c) 2012 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 #ifndef CHROME_BROWSER_PERFORMANCE_MONITOR_PERFORMANCE_MONITOR_H_ 6 #define CHROME_BROWSER_PERFORMANCE_MONITOR_PERFORMANCE_MONITOR_H_ 7 8 #include <map> 9 #include <set> 10 #include <string> 11 12 #include "base/files/file_path.h" 13 #include "base/memory/scoped_ptr.h" 14 #include "base/process/process_handle.h" 15 #include "base/time/time.h" 16 #include "base/timer/timer.h" 17 #include "chrome/browser/performance_monitor/event_type.h" 18 #include "chrome/browser/performance_monitor/process_metrics_history.h" 19 #include "content/public/browser/notification_observer.h" 20 #include "content/public/browser/notification_registrar.h" 21 #include "content/public/browser/render_process_host.h" 22 23 template <typename Type> 24 struct DefaultSingletonTraits; 25 26 namespace extensions { 27 class Extension; 28 } 29 30 namespace net { 31 class URLRequest; 32 } 33 34 namespace performance_monitor { 35 class Database; 36 class Event; 37 struct Metric; 38 39 // PerformanceMonitor is a tool which will allow the user to view information 40 // about Chrome's performance over a period of time. It will gather statistics 41 // pertaining to performance-oriented areas (e.g. CPU usage, memory usage, and 42 // network usage) and will also store information about significant events which 43 // are related to performance, either being indicative (e.g. crashes) or 44 // potentially causal (e.g. extension installation/uninstallation). 45 // 46 // Thread Safety: PerformanceMonitor lives on multiple threads. When interacting 47 // with the Database, PerformanceMonitor acts on a background thread (which has 48 // the sequence guaranteed by a token, Database::kDatabaseSequenceToken). At 49 // other times, the PerformanceMonitor will act on the appropriate thread for 50 // the task (for instance, gathering statistics about CPU and memory usage 51 // is done on the background thread, but most notifications occur on the UI 52 // thread). 53 class PerformanceMonitor : public content::NotificationObserver { 54 public: 55 struct PerformanceDataForIOThread { 56 PerformanceDataForIOThread(); 57 58 uint64 network_bytes_read; 59 }; 60 61 typedef std::map<base::ProcessHandle, ProcessMetricsHistory> MetricsMap; 62 63 // Set the path which the PerformanceMonitor should use for the database files 64 // constructed. This must be done prior to the initialization of the 65 // PerformanceMonitor. Returns true on success, false on failure (failure 66 // likely indicates that PerformanceMonitor has already been started at the 67 // time of the call). 68 bool SetDatabasePath(const base::FilePath& path); 69 database_logging_enabled()70 bool database_logging_enabled() const { return database_logging_enabled_; } 71 72 // Returns the current PerformanceMonitor instance if one exists; otherwise 73 // constructs a new PerformanceMonitor. 74 static PerformanceMonitor* GetInstance(); 75 76 // Begins the initialization process for the PerformanceMonitor in order to 77 // start collecting data. 78 void Initialize(); 79 80 // Start the cycle of metrics gathering. 81 void StartGatherCycle(); 82 83 // Inform PerformanceMonitor that bytes have been read; if these came across 84 // the network (and PerformanceMonitor is initialized), then increment the 85 // count accordingly. 86 void BytesReadOnIOThread(const net::URLRequest& request, const int bytes); 87 88 // content::NotificationObserver 89 // Wait for various notifications; insert events into the database upon 90 // occurance. 91 virtual void Observe(int type, 92 const content::NotificationSource& source, 93 const content::NotificationDetails& details) OVERRIDE; 94 database()95 Database* database() { return database_.get(); } database_path()96 base::FilePath database_path() { return database_path_; } initialized()97 static bool initialized() { return initialized_; } 98 99 private: 100 friend struct DefaultSingletonTraits<PerformanceMonitor>; 101 friend class PerformanceMonitorBrowserTest; 102 FRIEND_TEST_ALL_PREFIXES(PerformanceMonitorUncleanExitBrowserTest, 103 OneProfileUncleanExit); 104 FRIEND_TEST_ALL_PREFIXES(PerformanceMonitorUncleanExitBrowserTest, 105 TwoProfileUncleanExit); 106 FRIEND_TEST_ALL_PREFIXES(PerformanceMonitorBrowserTest, NetworkBytesRead); 107 108 PerformanceMonitor(); 109 virtual ~PerformanceMonitor(); 110 111 // Perform any additional initialization which must be performed on a 112 // background thread (e.g. constructing the database). 113 void InitOnBackgroundThread(); 114 115 void FinishInit(); 116 117 // Create the persistent database if we haven't already done so. 118 void InitializeDatabaseIfNeeded(); 119 120 // Register for the appropriate notifications as a NotificationObserver. 121 void RegisterForNotifications(); 122 123 // Checks for whether the previous profiles closed uncleanly; this method 124 // should only be called once per run in order to avoid duplication of events 125 // (exceptions made for testing purposes where we construct the environment). 126 void CheckForUncleanExits(); 127 128 // Find the last active time for the profile and insert the event into the 129 // database. 130 void AddUncleanExitEventOnBackgroundThread(const std::string& profile_name); 131 132 // Check the previous Chrome version from the Database and determine if 133 // it has been updated. If it has, insert an event in the database. 134 void CheckForVersionUpdateOnBackgroundThread(); 135 136 // Wrapper function for inserting events into the database. 137 void AddEvent(scoped_ptr<Event> event); 138 139 void AddEventOnBackgroundThread(scoped_ptr<Event> event); 140 141 // Since Database::AddMetric() is overloaded, base::Bind() does not work and 142 // we need a helper function. 143 void AddMetricOnBackgroundThread(const Metric& metric); 144 145 // Notify any listeners that PerformanceMonitor has finished the initializing. 146 void NotifyInitialized(); 147 148 // Perform any collections that are done on a timed basis. 149 void DoTimedCollections(); 150 151 // Update the database record of the last time the active profiles were 152 // running; this is used in determining when an unclean exit occurred. 153 #if !defined(OS_ANDROID) 154 void UpdateLiveProfiles(); 155 void UpdateLiveProfilesHelper( 156 scoped_ptr<std::set<std::string> > active_profiles, std::string time); 157 #endif 158 159 // Stores CPU/memory usage metrics to the database. 160 void StoreMetricsOnBackgroundThread( 161 int current_update_sequence, 162 const PerformanceDataForIOThread& performance_data_for_io_thread); 163 164 // Mark the given process as alive in the current update iteration. 165 // This means adding an entry to the map of watched processes if it's not 166 // already present. 167 void MarkProcessAsAlive(const base::ProcessHandle& handle, 168 int process_type, 169 int current_update_sequence); 170 171 // Updates the ProcessMetrics map with the current list of processes and 172 // gathers metrics from each entry. 173 void GatherMetricsMapOnUIThread(); 174 void GatherMetricsMapOnIOThread(int current_update_sequence); 175 176 // Generate an appropriate ExtensionEvent for an extension-related occurrance 177 // and insert it in the database. 178 void AddExtensionEvent(EventType type, 179 const extensions::Extension* extension); 180 181 // Generate an appropriate RendererFailure for a renderer crash and insert it 182 // in the database. 183 void AddRendererClosedEvent( 184 content::RenderProcessHost* host, 185 const content::RenderProcessHost::RendererClosedDetails& details); 186 187 // The store for all performance data that must be gathered from the IO 188 // thread. 189 PerformanceDataForIOThread performance_data_for_io_thread_; 190 191 // The location at which the database files are stored; if empty, the database 192 // will default to '<user_data_dir>/performance_monitor_dbs'. 193 base::FilePath database_path_; 194 195 scoped_ptr<Database> database_; 196 197 // A map of currently running ProcessHandles to ProcessMetrics. 198 MetricsMap metrics_map_; 199 200 // The next time we should collect averages from the performance metrics 201 // and act on them. 202 base::Time next_collection_time_; 203 204 // How long to wait between collections. 205 int gather_interval_in_seconds_; 206 207 // Enable persistent logging of performance metrics to a database. 208 bool database_logging_enabled_; 209 210 // The timer to signal PerformanceMonitor to perform its timed collections. 211 base::DelayTimer<PerformanceMonitor> timer_; 212 213 content::NotificationRegistrar registrar_; 214 215 // A flag indicating whether or not PerformanceMonitor is initialized. Any 216 // external sources accessing PerformanceMonitor should either wait for 217 // the PERFORMANCE_MONITOR_INITIALIZED notification or should check this 218 // flag. 219 static bool initialized_; 220 221 // Disable auto-starting the collection timer; used for tests. 222 bool disable_timer_autostart_for_testing_; 223 224 DISALLOW_COPY_AND_ASSIGN(PerformanceMonitor); 225 }; 226 227 } // namespace performance_monitor 228 229 #endif // CHROME_BROWSER_PERFORMANCE_MONITOR_PERFORMANCE_MONITOR_H_ 230