1 // Copyright 2015 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_INTERFACE_H_
6 #define CHROME_BROWSER_TASK_MANAGER_TASK_MANAGER_INTERFACE_H_
7 
8 #include <stddef.h>
9 #include <stdint.h>
10 
11 #include <memory>
12 #include <utility>
13 
14 #include "base/macros.h"
15 #include "base/observer_list.h"
16 #include "base/process/kill.h"
17 #include "base/process/process_handle.h"
18 #include "base/time/time.h"
19 #include "base/timer/timer.h"
20 #include "chrome/browser/task_manager/providers/task.h"
21 #include "chrome/browser/task_manager/task_manager_observer.h"
22 #include "components/sessions/core/session_id.h"
23 #include "ui/gfx/image/image_skia.h"
24 
25 class PrefRegistrySimple;
26 
27 namespace content {
28 class WebContents;
29 }  // namespace content
30 
31 namespace task_manager {
32 
33 // Defines the interface for any implementation of the task manager.
34 // Concrete implementations have no control over the refresh rate nor the
35 // enabled calculations of the usage of the various resources.
36 class TaskManagerInterface {
37  public:
38   // Registers the task manager related prefs.
39   static void RegisterPrefs(PrefRegistrySimple* registry);
40 
41   // Returns true if the user is allowed to end processes.
42   static bool IsEndProcessEnabled();
43 
44   // Gets the existing instance of the task manager if any, otherwise it will
45   // create it first. Must be called on the UI thread.
46   static TaskManagerInterface* GetTaskManager();
47 
48   void AddObserver(TaskManagerObserver* observer);
49   void RemoveObserver(TaskManagerObserver* observer);
50 
51   // Activates the task with |task_id| by bringing its container to the front if
52   // possible.
53   virtual void ActivateTask(TaskId task_id) = 0;
54 
55   // Returns if the task is killable.
56   virtual bool IsTaskKillable(TaskId task_id) = 0;
57 
58   // Kills the task with |task_id|.
59   virtual void KillTask(TaskId task_id) = 0;
60 
61   // Returns the CPU usage of the process on which |task_id| is running, over
62   // the most recent refresh cycle. The value is in the range zero to
63   // base::SysInfo::NumberOfProcessors() * 100%.
64   virtual double GetPlatformIndependentCPUUsage(TaskId task_id) const = 0;
65 
66   // Returns the start time for the process on which the task
67   // with |task_id| is running. Only implemented in Windows now.
68   virtual base::Time GetStartTime(TaskId task_id) const = 0;
69 
70   // Returns the CPU time for the process on which the task
71   // with |task_id| is running during the current refresh cycle.
72   // Only implemented in Windows now.
73   virtual base::TimeDelta GetCpuTime(TaskId task_id) const = 0;
74 
75   // Returns the current memory footprint/swapped memory of the task with
76   // |task_id| in bytes. A value of -1 means no valid value is currently
77   // available.
78   virtual int64_t GetMemoryFootprintUsage(TaskId task_id) const = 0;
79   virtual int64_t GetSwappedMemoryUsage(TaskId task_id) const = 0;
80 
81   // Returns the GPU memory usage of the task with |task_id| in bytes. A value
82   // of -1 means no valid value is currently available.
83   // |has_duplicates| will be set to true if this process' GPU resource count is
84   // inflated because it is counting other processes' resources.
85   virtual int64_t GetGpuMemoryUsage(TaskId task_id,
86                                     bool* has_duplicates) const = 0;
87 
88   // Returns the number of average idle CPU wakeups per second since the last
89   // refresh cycle. A value of -1 means no valid value is currently available.
90   virtual int GetIdleWakeupsPerSecond(TaskId task_id) const = 0;
91 
92   // Returns the number of hard page faults per second since the last refresh
93   // cycle. A value of -1 means no valid value is currently available.
94   virtual int GetHardFaultsPerSecond(TaskId task_id) const = 0;
95 
96   // Returns the NaCl GDB debug stub port. A value of
97   // |nacl::kGdbDebugStubPortUnknown| means no valid value is currently
98   // available. A value of -2 means NaCl is not enabled for this build.
99   virtual int GetNaClDebugStubPort(TaskId task_id) const = 0;
100 
101   // On Windows, gets the current and peak number of GDI and USER handles in
102   // use. A value of -1 means no valid value is currently available.
103   virtual void GetGDIHandles(TaskId task_id,
104                              int64_t* current,
105                              int64_t* peak) const = 0;
106   virtual void GetUSERHandles(TaskId task_id,
107                               int64_t* current,
108                               int64_t* peak) const = 0;
109 
110   // On Linux and ChromeOS, gets the number of file descriptors currently open
111   // by the process on which the task with |task_id| is running, or -1 if no
112   // valid value is currently available.
113   virtual int GetOpenFdCount(TaskId task_id) const = 0;
114 
115   // Returns whether the task with |task_id| is running on a backgrounded
116   // process.
117   virtual bool IsTaskOnBackgroundedProcess(TaskId task_id) const = 0;
118 
119   // Returns the title of the task with |task_id|.
120   virtual const base::string16& GetTitle(TaskId task_id) const = 0;
121 
122   // Returns the name of the profile associated with the browser context of the
123   // render view host that the task with |task_id| represents (if that task
124   // represents a renderer).
125   virtual base::string16 GetProfileName(TaskId task_id) const = 0;
126 
127   // Returns the favicon of the task with |task_id|.
128   virtual const gfx::ImageSkia& GetIcon(TaskId task_id) const = 0;
129 
130   // Returns the ID and handle of the process on which the task with |task_id|
131   // is running.
132   virtual const base::ProcessHandle& GetProcessHandle(TaskId task_id) const = 0;
133   virtual const base::ProcessId& GetProcessId(TaskId task_id) const = 0;
134 
135   // Returns the type of the task with |task_id|.
136   virtual Task::Type GetType(TaskId task_id) const = 0;
137 
138   // Gets the unique ID of the tab if the task with |task_id| represents a
139   // WebContents of a tab. Returns -1 otherwise.
140   virtual SessionID GetTabId(TaskId task_id) const = 0;
141 
142   // Returns the unique ID of the BrowserChildProcessHost/RenderProcessHost on
143   // which the task with |task_id| is running. It is not the PID nor the handle
144   // of the process.
145   // For a task that represents the browser process, the return value is 0.
146   // For a task that doesn't have a host on the browser process, the return
147   // value is also 0. For other tasks that represent renderers and other child
148   // processes, the return value is whatever unique IDs of their hosts in the
149   // browser process.
150   virtual int GetChildProcessUniqueId(TaskId task_id) const = 0;
151 
152   // If the process, in which the task with |task_id| is running, is terminated
153   // this gets the termination status. Currently implemented only for Renderer
154   // processes. The values will only be valid if the process has actually
155   // terminated.
156   virtual void GetTerminationStatus(TaskId task_id,
157                                     base::TerminationStatus* out_status,
158                                     int* out_error_code) const = 0;
159 
160   // Returns the network usage (in bytes per second) during the current refresh
161   // cycle for the task with |task_id|.
162   virtual int64_t GetNetworkUsage(TaskId task_id) const = 0;
163 
164   // Returns the network usage during the current lifetime of the task
165   // for the task with |task_id|.
166   virtual int64_t GetCumulativeNetworkUsage(TaskId task_id) const = 0;
167 
168   // Returns the total network usage (in bytes per second) during the current
169   // refresh cycle for the process on which the task with |task_id| is running.
170   // This is the sum of all the network usage of the individual tasks (that
171   // can be gotten by the above GetNetworkUsage()). A value of -1 means network
172   // usage calculation refresh is currently not available.
173   virtual int64_t GetProcessTotalNetworkUsage(TaskId task_id) const = 0;
174 
175   // Returns the total network usage during the lifetime of the process
176   // on which the task with |task_id| is running.
177   // This is the sum of all the network usage of the individual tasks (that
178   // can be gotten by the above GetTotalNetworkUsage()).
179   virtual int64_t GetCumulativeProcessTotalNetworkUsage(
180       TaskId task_id) const = 0;
181 
182   // Returns the Sqlite used memory (in bytes) for the task with |task_id|.
183   // A value of -1 means no valid value is currently available.
184   virtual int64_t GetSqliteMemoryUsed(TaskId task_id) const = 0;
185 
186   // Returns the allocated and used V8 memory (in bytes) for the task with
187   // |task_id|. A return value of false means no valid value is currently
188   // available.
189   virtual bool GetV8Memory(TaskId task_id,
190                            int64_t* allocated,
191                            int64_t* used) const = 0;
192 
193   // Gets the Blink resource cache stats for the task with |task_id|.
194   // A return value of false means that task does NOT report WebCache stats.
195   virtual bool GetWebCacheStats(
196       TaskId task_id,
197       blink::WebCacheResourceTypeStats* stats) const = 0;
198 
199   // Returns the keep-alive counter if the Task is an event page, -1 otherwise.
200   virtual int GetKeepaliveCount(TaskId task_id) const = 0;
201 
202   // Gets the list of task IDs currently tracked by the task manager. Tasks that
203   // share the same process id will always be consecutive. The list will be
204   // sorted in a way that reflects the process tree: the browser process will be
205   // first, followed by the gpu process if it exists. Related processes (e.g., a
206   // subframe process and its parent) will be kept together if possible. Callers
207   // can expect this ordering to be stable when a process is added or removed.
208   virtual const TaskIdList& GetTaskIdsList() const = 0;
209 
210   // Gets the list of task IDs of the tasks that run on the same process as the
211   // task with |task_id|. The returned list will at least include |task_id|.
212   virtual TaskIdList GetIdsOfTasksSharingSameProcess(TaskId task_id) const = 0;
213 
214   // Gets the number of task-manager tasks running on the same process on which
215   // the Task with |task_id| is running.
216   virtual size_t GetNumberOfTasksOnSameProcess(TaskId task_id) const = 0;
217 
218   // Returns true if the task is running inside a VM.
219   virtual bool IsRunningInVM(TaskId task_id) const = 0;
220 
221   // Returns the TaskId associated with the main task for |web_contents|.
222   // Returns -1 if |web_contents| is nullptr or does not currently have an
223   // associated Task.
224   virtual TaskId GetTaskIdForWebContents(
225       content::WebContents* web_contents) const = 0;
226 
227   // Returns true if the resource |type| usage calculation is enabled and
228   // the implementation should refresh its value (this means that at least one
229   // of the observers require this value). False otherwise.
230   bool IsResourceRefreshEnabled(RefreshType type) const;
231 
232  protected:
233   TaskManagerInterface();
234   virtual ~TaskManagerInterface();
235 
236   // Notifying observers of various events.
237   void NotifyObserversOnTaskAdded(TaskId id);
238   void NotifyObserversOnTaskToBeRemoved(TaskId id);
239   void NotifyObserversOnRefresh(const TaskIdList& task_ids);
240   void NotifyObserversOnRefreshWithBackgroundCalculations(
241       const TaskIdList& task_ids);
242   void NotifyObserversOnTaskUnresponsive(TaskId id);
243 
244   // Refresh all the enabled resources usage of all the available tasks.
245   virtual void Refresh() = 0;
246 
247   // StartUpdating will be called once an observer is added, and StopUpdating
248   // will be called when the last observer is removed.
249   virtual void StartUpdating() = 0;
250   virtual void StopUpdating() = 0;
251 
252   // Returns the current refresh time that this task manager is running at. It
253   // will return base::TimeDelta::Max() if the task manager is not running.
254   base::TimeDelta GetCurrentRefreshTime() const;
255 
enabled_resources_flags()256   int64_t enabled_resources_flags() const { return enabled_resources_flags_; }
257 
set_timer_for_testing(std::unique_ptr<base::RepeatingTimer> timer)258   void set_timer_for_testing(std::unique_ptr<base::RepeatingTimer> timer) {
259     refresh_timer_ = std::move(timer);
260   }
261 
262  private:
263   friend class TaskManagerObserver;
264 
265   // This should be called after each time an observer changes its own desired
266   // resources refresh flags.
267   void RecalculateRefreshFlags();
268 
269   // Appends |flags| to the |enabled_resources_flags_|.
270   void ResourceFlagsAdded(int64_t flags);
271 
272   // Sets |enabled_resources_flags_| to |flags|.
273   void SetEnabledResourceFlags(int64_t flags);
274 
275   // Schedules the task manager refresh cycles using the given |refresh_time|.
276   // It stops any existing refresh schedule.
277   void ScheduleRefresh(base::TimeDelta refresh_time);
278 
279   // The list of observers.
280   base::ObserverList<TaskManagerObserver>::Unchecked observers_;
281 
282   // The timer that will be used to schedule the successive refreshes.
283   std::unique_ptr<base::RepeatingTimer> refresh_timer_;
284 
285   // The flags containing the enabled resources types calculations.
286   int64_t enabled_resources_flags_;
287 
288   DISALLOW_COPY_AND_ASSIGN(TaskManagerInterface);
289 };
290 
291 }  // namespace task_manager
292 
293 #endif  // CHROME_BROWSER_TASK_MANAGER_TASK_MANAGER_INTERFACE_H_
294