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