Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(304)

Side by Side Diff: chrome/browser/task_manager/task_manager.h

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

Powered by Google App Engine
This is Rietveld 408576698