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