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_TASK_MANAGER_TASK_MANAGER_H_ 6 #define CHROME_BROWSER_TASK_MANAGER_TASK_MANAGER_H_ 7 8 #include <map> 9 #include <vector> 10 11 #include "base/basictypes.h" 12 #include "base/callback_forward.h" 13 #include "base/gtest_prod_util.h" 14 #include "base/memory/ref_counted.h" 15 #include "base/memory/singleton.h" 16 #include "base/observer_list.h" 17 #include "base/strings/string16.h" 18 #include "base/timer/timer.h" 19 #include "chrome/browser/renderer_host/web_cache_manager.h" 20 #include "chrome/browser/task_manager/resource_provider.h" 21 #include "chrome/browser/ui/host_desktop.h" 22 #include "content/public/common/gpu_memory_stats.h" 23 #include "third_party/WebKit/public/web/WebCache.h" 24 25 class PrefRegistrySimple; 26 class TaskManagerModel; 27 class TaskManagerModelGpuDataManagerObserver; 28 29 namespace base { 30 class ProcessMetrics; 31 } 32 33 namespace content { 34 class WebContents; 35 } 36 37 namespace extensions { 38 class Extension; 39 } 40 41 namespace gfx { 42 class ImageSkia; 43 } 44 45 namespace net { 46 class URLRequest; 47 } 48 49 // This class is a singleton. 50 class TaskManager { 51 public: 52 static void RegisterPrefs(PrefRegistrySimple* registry); 53 54 // Returns true if the process at the specified index is the browser process. 55 bool IsBrowserProcess(int index) const; 56 57 // Terminates the process at the specified index. 58 void KillProcess(int index); 59 60 // Activates the browser tab associated with the process in the specified 61 // index. 62 void ActivateProcess(int index); 63 64 // These methods are invoked by the resource providers to add/remove resources 65 // to the Task Manager. Note that the resources are owned by the 66 // ResourceProviders and are not valid after StopUpdating() has been called 67 // on the ResourceProviders. 68 void AddResource(task_manager::Resource* resource); 69 void RemoveResource(task_manager::Resource* resource); 70 71 void OnWindowClosed(); 72 73 // Invoked when a change to a resource has occurred that should cause any 74 // observers to completely refresh themselves (for example, the creation of 75 // a background resource in a process). Results in all observers receiving 76 // OnModelChanged() events. 77 void ModelChanged(); 78 79 // Returns the singleton instance (and initializes it if necessary). 80 static TaskManager* GetInstance(); 81 82 TaskManagerModel* model() const { return model_.get(); } 83 84 void OpenAboutMemory(chrome::HostDesktopType desktop_type); 85 86 private: 87 FRIEND_TEST_ALL_PREFIXES(TaskManagerTest, Basic); 88 FRIEND_TEST_ALL_PREFIXES(TaskManagerTest, Resources); 89 FRIEND_TEST_ALL_PREFIXES(TaskManagerTest, RefreshCalled); 90 FRIEND_TEST_ALL_PREFIXES(TaskManagerWindowControllerTest, Init); 91 FRIEND_TEST_ALL_PREFIXES(TaskManagerWindowControllerTest, Sort); 92 FRIEND_TEST_ALL_PREFIXES(TaskManagerWindowControllerTest, 93 SelectionAdaptsToSorting); 94 95 // Obtain an instance via GetInstance(). 96 TaskManager(); 97 friend struct DefaultSingletonTraits<TaskManager>; 98 99 ~TaskManager(); 100 101 // The model used for gathering and processing task data. It is ref counted 102 // because it is passed as a parameter to MessageLoop::InvokeLater(). 103 scoped_refptr<TaskManagerModel> model_; 104 105 DISALLOW_COPY_AND_ASSIGN(TaskManager); 106 }; 107 108 class TaskManagerModelObserver { 109 public: 110 virtual ~TaskManagerModelObserver() {} 111 112 // Invoked when the model has been completely changed. 113 virtual void OnModelChanged() = 0; 114 115 // Invoked when a range of items has changed. 116 virtual void OnItemsChanged(int start, int length) = 0; 117 118 // Invoked when new items are added. 119 virtual void OnItemsAdded(int start, int length) = 0; 120 121 // Invoked when a range of items has been removed. 122 virtual void OnItemsRemoved(int start, int length) = 0; 123 124 // Invoked when a range of items is to be immediately removed. It differs 125 // from OnItemsRemoved by the fact that the item is still in the task manager, 126 // so it can be queried for and found. 127 virtual void OnItemsToBeRemoved(int start, int length) {} 128 129 // Invoked when the initialization of the model has been finished and 130 // periodical updates is started. The first periodical update will be done 131 // in a few seconds. (depending on platform) 132 virtual void OnReadyPeriodicalUpdate() {} 133 }; 134 135 // The model used by TaskManager. 136 // 137 // TaskManagerModel caches the values from all task_manager::Resources. This is 138 // done so the UI sees a consistant view of the resources until it is told a 139 // value has been updated. 140 class TaskManagerModel : public base::RefCountedThreadSafe<TaskManagerModel> { 141 public: 142 // (start, length) 143 typedef std::pair<int, int> GroupRange; 144 145 explicit TaskManagerModel(TaskManager* task_manager); 146 147 void AddObserver(TaskManagerModelObserver* observer); 148 void RemoveObserver(TaskManagerModelObserver* observer); 149 150 // Returns number of registered resources. 151 int ResourceCount() const; 152 // Returns number of registered groups. 153 int GroupCount() const; 154 155 // Methods to return raw resource information. 156 int GetNaClDebugStubPort(int index) const; 157 int64 GetNetworkUsage(int index) const; 158 double GetCPUUsage(int index) const; 159 int GetIdleWakeupsPerSecond(int index) const; 160 base::ProcessId GetProcessId(int index) const; 161 base::ProcessHandle GetProcess(int index) const; 162 163 // Catchall method that calls off to the appropriate GetResourceXXX method 164 // based on |col_id|. |col_id| is an IDS_ value used to identify the column. 165 base::string16 GetResourceById(int index, int col_id) const; 166 167 // Methods to return formatted resource information. 168 const base::string16& GetResourceTitle(int index) const; 169 const base::string16& GetResourceProfileName(int index) const; 170 base::string16 GetResourceNaClDebugStubPort(int index) const; 171 base::string16 GetResourceNetworkUsage(int index) const; 172 base::string16 GetResourceCPUUsage(int index) const; 173 base::string16 GetResourcePrivateMemory(int index) const; 174 base::string16 GetResourceSharedMemory(int index) const; 175 base::string16 GetResourcePhysicalMemory(int index) const; 176 base::string16 GetResourceProcessId(int index) const; 177 base::string16 GetResourceGDIHandles(int index) const; 178 base::string16 GetResourceUSERHandles(int index) const; 179 base::string16 GetResourceWebCoreImageCacheSize(int index) const; 180 base::string16 GetResourceWebCoreScriptsCacheSize(int index) const; 181 base::string16 GetResourceWebCoreCSSCacheSize(int index) const; 182 base::string16 GetResourceVideoMemory(int index) const; 183 base::string16 GetResourceSqliteMemoryUsed(int index) const; 184 base::string16 GetResourceIdleWakeupsPerSecond(int index) const; 185 base::string16 GetResourceGoatsTeleported(int index) const; 186 base::string16 GetResourceV8MemoryAllocatedSize(int index) const; 187 188 // Gets the private memory (in bytes) that should be displayed for the passed 189 // resource index. Caches the result since this calculation can take time on 190 // some platforms. 191 bool GetPrivateMemory(int index, size_t* result) const; 192 193 // Gets the shared memory (in bytes) that should be displayed for the passed 194 // resource index. Caches the result since this calculation can take time on 195 // some platforms. 196 bool GetSharedMemory(int index, size_t* result) const; 197 198 // Gets the physical memory (in bytes) that should be displayed for the passed 199 // resource index. 200 bool GetPhysicalMemory(int index, size_t* result) const; 201 202 // On Windows, get the current and peak number of GDI handles in use. 203 void GetGDIHandles(int index, size_t* current, size_t* peak) const; 204 205 // On Windows, get the current and peak number of USER handles in use. 206 void GetUSERHandles(int index, size_t* current, size_t* peak) const; 207 208 // Gets the statuses of webkit. Return false if the resource for the given row 209 // isn't a renderer. 210 bool GetWebCoreCacheStats(int index, 211 blink::WebCache::ResourceTypeStats* result) const; 212 213 // Gets the GPU memory allocated of the given page. 214 bool GetVideoMemory(int index, 215 size_t* video_memory, 216 bool* has_duplicates) const; 217 218 // Gets the sqlite memory (in byte). Return false if the resource for the 219 // given row doesn't report information. 220 bool GetSqliteMemoryUsedBytes(int index, size_t* result) const; 221 222 // Gets the amount of memory allocated for javascript. Returns false if the 223 // resource for the given row isn't a renderer. 224 bool GetV8Memory(int index, size_t* result) const; 225 226 // Gets the amount of memory used for javascript. Returns false if the 227 // resource for the given row isn't a renderer. 228 bool GetV8MemoryUsed(int index, size_t* result) const; 229 230 // Returns true if resource for the given row can be activated. 231 bool CanActivate(int index) const; 232 233 // Returns true if resource for the given row can be inspected using developer 234 // tools. 235 bool CanInspect(int index) const; 236 237 // Invokes or reveals developer tools window for resource in the given row. 238 void Inspect(int index) const; 239 240 // See design doc at http://go/at-teleporter for more information. 241 int GetGoatsTeleported(int index) const; 242 243 // Returns true if the resource is first/last in its group (resources 244 // rendered by the same process are groupped together). 245 bool IsResourceFirstInGroup(int index) const; 246 bool IsResourceLastInGroup(int index) const; 247 248 // Returns icon to be used for resource (for example a favicon). 249 gfx::ImageSkia GetResourceIcon(int index) const; 250 251 // Returns the group range of resource. 252 GroupRange GetGroupRangeForResource(int index) const; 253 254 // Returns an index of groups to which the resource belongs. 255 int GetGroupIndexForResource(int index) const; 256 257 // Returns an index of resource which belongs to the |group_index|th group 258 // and which is the |index_in_group|th resource in group. 259 int GetResourceIndexForGroup(int group_index, int index_in_group) const; 260 261 // Compares values in column |col_id| and rows |row1|, |row2|. 262 // Returns -1 if value in |row1| is less than value in |row2|, 263 // 0 if they are equal, and 1 otherwise. 264 int CompareValues(int row1, int row2, int col_id) const; 265 266 // Returns the unique child process ID generated by Chromium, not the OS 267 // process id. This is used to identify processes internally and for 268 // extensions. It is not meant to be displayed to the user. 269 int GetUniqueChildProcessId(int index) const; 270 271 // Returns the type of the given resource. 272 task_manager::Resource::Type GetResourceType(int index) const; 273 274 // Returns WebContents of given resource or NULL if not applicable. 275 content::WebContents* GetResourceWebContents(int index) const; 276 277 void AddResource(task_manager::Resource* resource); 278 void RemoveResource(task_manager::Resource* resource); 279 280 void StartUpdating(); 281 void StopUpdating(); 282 283 // Listening involves calling StartUpdating on all resource providers. This 284 // causes all of them to subscribe to notifications and enumerate current 285 // resources. It differs from StartUpdating that it doesn't start the 286 // Refresh timer. The end result is that we have a full view of resources, but 287 // don't spend unneeded time updating, unless we have a real need to. 288 void StartListening(); 289 void StopListening(); 290 291 void Clear(); // Removes all items. 292 293 // Sends OnModelChanged() to all observers to inform them of significant 294 // changes to the model. 295 void ModelChanged(); 296 297 // Updates the values for all rows. 298 void Refresh(); 299 300 void NotifyResourceTypeStats( 301 base::ProcessId renderer_id, 302 const blink::WebCache::ResourceTypeStats& stats); 303 304 void NotifyVideoMemoryUsageStats( 305 const content::GPUVideoMemoryUsageStats& video_memory_usage_stats); 306 307 void NotifyV8HeapStats(base::ProcessId renderer_id, 308 size_t v8_memory_allocated, 309 size_t v8_memory_used); 310 311 void NotifyBytesRead(const net::URLRequest& request, int bytes_read); 312 313 void RegisterOnDataReadyCallback(const base::Closure& callback); 314 315 void NotifyDataReady(); 316 317 private: 318 friend class base::RefCountedThreadSafe<TaskManagerModel>; 319 friend class TaskManagerBrowserTest; 320 FRIEND_TEST_ALL_PREFIXES(ExtensionApiTest, ProcessesVsTaskManager); 321 FRIEND_TEST_ALL_PREFIXES(TaskManagerTest, RefreshCalled); 322 FRIEND_TEST_ALL_PREFIXES(TaskManagerWindowControllerTest, 323 SelectionAdaptsToSorting); 324 325 enum UpdateState { 326 IDLE = 0, // Currently not updating. 327 TASK_PENDING, // An update task is pending. 328 STOPPING // A update task is pending and it should stop the update. 329 }; 330 331 // The delay between updates of the information (in ms). 332 #if defined(OS_MACOSX) 333 // Match Activity Monitor's default refresh rate. 334 static const int kUpdateTimeMs = 2000; 335 #else 336 static const int kUpdateTimeMs = 1000; 337 #endif 338 339 // Values cached per resource. Values are validated on demand. The is_XXX 340 // members indicate if a value is valid. 341 struct PerResourceValues { 342 PerResourceValues(); 343 ~PerResourceValues(); 344 345 bool is_title_valid; 346 base::string16 title; 347 348 bool is_profile_name_valid; 349 base::string16 profile_name; 350 351 // No is_network_usage since default (0) is fine. 352 int64 network_usage; 353 354 bool is_process_id_valid; 355 base::ProcessId process_id; 356 357 bool is_goats_teleported_valid; 358 int goats_teleported; 359 360 bool is_webcore_stats_valid; 361 blink::WebCache::ResourceTypeStats webcore_stats; 362 363 bool is_sqlite_memory_bytes_valid; 364 size_t sqlite_memory_bytes; 365 366 bool is_v8_memory_valid; 367 size_t v8_memory_allocated; 368 size_t v8_memory_used; 369 }; 370 371 // Values cached per process. Values are validated on demand. The is_XXX 372 // members indicate if a value is valid. 373 struct PerProcessValues { 374 PerProcessValues(); 375 ~PerProcessValues(); 376 377 bool is_cpu_usage_valid; 378 double cpu_usage; 379 380 bool is_idle_wakeups_valid; 381 int idle_wakeups; 382 383 bool is_private_and_shared_valid; 384 size_t private_bytes; 385 size_t shared_bytes; 386 387 bool is_physical_memory_valid; 388 size_t physical_memory; 389 390 bool is_video_memory_valid; 391 size_t video_memory; 392 bool video_memory_has_duplicates; 393 394 bool is_gdi_handles_valid; 395 size_t gdi_handles; 396 size_t gdi_handles_peak; 397 398 bool is_user_handles_valid; 399 size_t user_handles; 400 size_t user_handles_peak; 401 402 bool is_nacl_debug_stub_port_valid; 403 int nacl_debug_stub_port; 404 }; 405 406 typedef std::vector<task_manager::Resource*> ResourceList; 407 typedef std::vector<scoped_refptr<task_manager::ResourceProvider> > 408 ResourceProviderList; 409 typedef std::map<base::ProcessHandle, ResourceList> GroupMap; 410 typedef std::map<base::ProcessHandle, base::ProcessMetrics*> MetricsMap; 411 typedef std::map<task_manager::Resource*, int64> ResourceValueMap; 412 typedef std::map<task_manager::Resource*, 413 PerResourceValues> PerResourceCache; 414 typedef std::map<base::ProcessHandle, PerProcessValues> PerProcessCache; 415 416 // This struct is used to exchange information between the io and ui threads. 417 struct BytesReadParam { 418 BytesReadParam(int origin_pid, 419 int child_id, 420 int route_id, 421 int byte_count) 422 : origin_pid(origin_pid), 423 child_id(child_id), 424 route_id(route_id), 425 byte_count(byte_count) {} 426 427 // The process ID that triggered the request. For plugin requests this 428 // will differ from the renderer process ID. 429 int origin_pid; 430 431 // The child ID of the process this request was routed through. 432 int child_id; 433 434 int route_id; 435 int byte_count; 436 }; 437 438 ~TaskManagerModel(); 439 440 // Callback from the timer to refresh. Invokes Refresh() as appropriate. 441 void RefreshCallback(); 442 443 void RefreshVideoMemoryUsageStats(); 444 445 // Returns the network usage (in bytes per seconds) for the specified 446 // resource. That's the value retrieved at the last timer's tick. 447 int64 GetNetworkUsageForResource(task_manager::Resource* resource) const; 448 449 // Called on the UI thread when some bytes are read. 450 void BytesRead(BytesReadParam param); 451 452 void MultipleBytesRead(const std::vector<BytesReadParam>* params); 453 454 // Notifies the UI thread about all the bytes read. Allows for coalescing 455 // multiple bytes read into a single task for the UI thread. This is important 456 // for when downloading a lot of data on the IO thread, since posting a Task 457 // for each one is expensive. 458 void NotifyMultipleBytesRead(); 459 460 // Returns the network usage (in byte per second) that should be displayed for 461 // the passed |resource|. -1 means the information is not available for that 462 // resource. 463 int64 GetNetworkUsage(task_manager::Resource* resource) const; 464 465 // Returns the CPU usage (in %) that should be displayed for the passed 466 // |resource|. 467 double GetCPUUsage(task_manager::Resource* resource) const; 468 469 // Returns the idle wakeups that should be displayed for the passed 470 // |resource|. 471 int GetIdleWakeupsPerSecond(task_manager::Resource* resource) const; 472 473 // Given a number, this function returns the formatted string that should be 474 // displayed in the task manager's memory cell. 475 base::string16 GetMemCellText(int64 number) const; 476 477 // Verifies the private and shared memory for |handle| is valid in 478 // |per_process_cache_|. Returns true if the data in |per_process_cache_| is 479 // valid. 480 bool CachePrivateAndSharedMemory(base::ProcessHandle handle) const; 481 482 // Verifies |webcore_stats| in |per_resource_cache_|, returning true on 483 // success. 484 bool CacheWebCoreStats(int index) const; 485 486 // Verifies |v8_memory_allocated| and |v8_memory_used| in 487 // |per_resource_cache_|. Returns true if valid, false if not valid. 488 bool CacheV8Memory(int index) const; 489 490 // Adds a resource provider to be managed. 491 void AddResourceProvider(task_manager::ResourceProvider* provider); 492 493 // Returns the PerResourceValues for the specified index. 494 PerResourceValues& GetPerResourceValues(int index) const; 495 496 // Returns the Resource for the specified index. 497 task_manager::Resource* GetResource(int index) const; 498 499 // The list of providers to the task manager. They are ref counted. 500 ResourceProviderList providers_; 501 502 // The list of all the resources displayed in the task manager. They are owned 503 // by the ResourceProviders. 504 ResourceList resources_; 505 506 // A map to keep tracks of the grouped resources (they are grouped if they 507 // share the same process). The groups (the Resources vectors) are owned by 508 // the model (but the actual Resources are owned by the ResourceProviders). 509 GroupMap group_map_; 510 511 // A map to retrieve the process metrics for a process. The ProcessMetrics are 512 // owned by the model. 513 MetricsMap metrics_map_; 514 515 // A map that keeps track of the number of bytes read per process since last 516 // tick. The Resources are owned by the ResourceProviders. 517 ResourceValueMap current_byte_count_map_; 518 519 // A map that contains the video memory usage for a process 520 content::GPUVideoMemoryUsageStats video_memory_usage_stats_; 521 522 // Set to true when we've requested video stats and false once we get them. 523 bool pending_video_memory_usage_stats_update_; 524 525 // An observer waiting for video memory usage stats updates from the GPU 526 // process 527 scoped_ptr<TaskManagerModelGpuDataManagerObserver> 528 video_memory_usage_stats_observer_; 529 530 ObserverList<TaskManagerModelObserver> observer_list_; 531 532 // How many calls to StartUpdating have been made without matching calls to 533 // StopUpdating. 534 int update_requests_; 535 536 // How many calls to StartListening have been made without matching calls to 537 // StopListening. 538 int listen_requests_; 539 540 // Whether we are currently in the process of updating. 541 UpdateState update_state_; 542 543 // A salt lick for the goats. 544 uint64 goat_salt_; 545 546 // Buffer for coalescing BytesReadParam so we don't have to post a task on 547 // each NotifyBytesRead() call. 548 std::vector<BytesReadParam> bytes_read_buffer_; 549 550 std::vector<base::Closure> on_data_ready_callbacks_; 551 552 // All per-Resource values are stored here. 553 mutable PerResourceCache per_resource_cache_; 554 555 // All per-Process values are stored here. 556 mutable PerProcessCache per_process_cache_; 557 558 DISALLOW_COPY_AND_ASSIGN(TaskManagerModel); 559 }; 560 561 #endif // CHROME_BROWSER_TASK_MANAGER_TASK_MANAGER_H_ 562