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

Side by Side Diff: chrome/browser/extensions/api/processes/processes_api.cc

Issue 1584473004: Migrate ProcessesEventRouter to the new task manager (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Fix edge case in detecting background calculations completion Created 4 years, 10 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
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "chrome/browser/extensions/api/processes/processes_api.h" 5 #include "chrome/browser/extensions/api/processes/processes_api.h"
6 6
7 #include <stddef.h> 7 #include <algorithm>
8 #include <stdint.h> 8
9 #include <utility>
10
11 #include "base/callback.h"
12 #include "base/json/json_writer.h"
13 #include "base/lazy_instance.h" 9 #include "base/lazy_instance.h"
14 #include "base/location.h" 10 #include "base/metrics/histogram_macros.h"
15 #include "base/metrics/histogram.h" 11 #include "base/process/process.h"
16 #include "base/single_thread_task_runner.h"
17 #include "base/strings/string_number_conversions.h" 12 #include "base/strings/string_number_conversions.h"
18 #include "base/strings/utf_string_conversions.h" 13 #include "base/strings/utf_string_conversions.h"
19 #include "base/thread_task_runner_handle.h"
20 #include "base/values.h"
21 #include "chrome/browser/chrome_notification_types.h"
22 #include "chrome/browser/extensions/api/processes/processes_api_constants.h"
23 #include "chrome/browser/extensions/api/tabs/tabs_constants.h" 14 #include "chrome/browser/extensions/api/tabs/tabs_constants.h"
24 #include "chrome/browser/extensions/extension_service.h"
25 #include "chrome/browser/extensions/extension_tab_util.h" 15 #include "chrome/browser/extensions/extension_tab_util.h"
26 #include "chrome/browser/profiles/profile.h" 16 #include "chrome/browser/profiles/profile.h"
27 #include "chrome/browser/task_manager/resource_provider.h" 17 #include "chrome/browser/task_management/task_manager_interface.h"
28 #include "chrome/browser/task_manager/task_manager.h" 18 #include "chrome/common/extensions/api/processes.h"
29 #include "content/public/browser/browser_context.h" 19 #include "content/public/browser/browser_child_process_host.h"
30 #include "content/public/browser/notification_details.h" 20 #include "content/public/browser/child_process_data.h"
31 #include "content/public/browser/notification_service.h"
32 #include "content/public/browser/notification_source.h"
33 #include "content/public/browser/notification_types.h"
34 #include "content/public/browser/render_process_host.h" 21 #include "content/public/browser/render_process_host.h"
35 #include "content/public/browser/render_view_host.h"
36 #include "content/public/browser/render_widget_host.h"
37 #include "content/public/browser/render_widget_host_iterator.h"
38 #include "content/public/browser/web_contents.h" 22 #include "content/public/browser/web_contents.h"
23 #include "content/public/common/child_process_host.h"
39 #include "content/public/common/result_codes.h" 24 #include "content/public/common/result_codes.h"
40 #include "extensions/browser/event_router.h"
41 #include "extensions/browser/extension_function_registry.h"
42 #include "extensions/browser/extension_function_util.h"
43 #include "extensions/common/error_utils.h" 25 #include "extensions/common/error_utils.h"
26 #include "third_party/WebKit/public/web/WebCache.h"
44 27
45 namespace extensions { 28 namespace extensions {
46 29
47 namespace keys = processes_api_constants; 30 namespace errors {
48 namespace errors = processes_api_constants; 31 const char kNotAllowedToTerminate[] = "Not allowed to terminate process: *.";
32 const char kProcessNotFound[] = "Process not found: *.";
33 const char kInvalidArgument[] = "Invalid argument: *.";
34 } // namespace errors
49 35
50 namespace { 36 namespace {
51 37
52 #if defined(ENABLE_TASK_MANAGER) 38 base::LazyInstance<BrowserContextKeyedAPIFactory<ProcessesAPI> >
53 39 g_processes_api_factory = LAZY_INSTANCE_INITIALIZER;
54 base::DictionaryValue* CreateCacheData( 40
41 int64_t GetRefreshTypesFlagOnlyEssentialData() {
42 // This is the only non-optional data in the Process as defined by the API in
43 // processes.idl.
44 return task_management::REFRESH_TYPE_NACL;
45 }
46
47 // This does not include memory. The memory refresh flag will only be added once
48 // a listener to OnUpdatedWithMemory event is added.
49 int64_t GetRefreshTypesFlagIncludeOptionalData() {
50 return GetRefreshTypesFlagOnlyEssentialData() |
51 task_management::REFRESH_TYPE_CPU |
52 task_management::REFRESH_TYPE_NETWORK_USAGE |
53 task_management::REFRESH_TYPE_SQLITE_MEMORY |
54 task_management::REFRESH_TYPE_V8_MEMORY |
55 task_management::REFRESH_TYPE_WEBCACHE_STATS;
56 }
57
58 scoped_ptr<api::processes::Cache> CreateCacheData(
55 const blink::WebCache::ResourceTypeStat& stat) { 59 const blink::WebCache::ResourceTypeStat& stat) {
56 60 scoped_ptr<api::processes::Cache> cache(new api::processes::Cache);
57 base::DictionaryValue* cache = new base::DictionaryValue(); 61 cache->size = static_cast<double>(stat.size);
58 cache->SetDouble(keys::kCacheSize, static_cast<double>(stat.size)); 62 cache->live_size = static_cast<double>(stat.liveSize);
59 cache->SetDouble(keys::kCacheLiveSize, static_cast<double>(stat.liveSize));
60 return cache; 63 return cache;
61 } 64 }
62 65
63 void SetProcessType(base::DictionaryValue* result, 66 api::processes::ProcessType GetProcessType(
64 TaskManagerModel* model, 67 task_management::Task::Type task_type) {
65 int index) { 68 switch (task_type) {
66 // Determine process type. 69 case task_management::Task::BROWSER:
67 std::string type = keys::kProcessTypeOther; 70 return api::processes::PROCESS_TYPE_BROWSER;
68 task_manager::Resource::Type resource_type = model->GetResourceType(index); 71
69 switch (resource_type) { 72 case task_management::Task::RENDERER:
70 case task_manager::Resource::BROWSER: 73 return api::processes::PROCESS_TYPE_RENDERER;
71 type = keys::kProcessTypeBrowser; 74
72 break; 75 case task_management::Task::EXTENSION:
73 case task_manager::Resource::RENDERER: 76 case task_management::Task::GUEST:
74 type = keys::kProcessTypeRenderer; 77 return api::processes::PROCESS_TYPE_EXTENSION;
75 break; 78
76 case task_manager::Resource::EXTENSION: 79 case task_management::Task::PLUGIN:
77 type = keys::kProcessTypeExtension; 80 return api::processes::PROCESS_TYPE_PLUGIN;
78 break; 81
79 case task_manager::Resource::NOTIFICATION: 82 case task_management::Task::WORKER:
80 type = keys::kProcessTypeNotification; 83 return api::processes::PROCESS_TYPE_WORKER;
81 break; 84
82 case task_manager::Resource::PLUGIN: 85 case task_management::Task::NACL:
83 type = keys::kProcessTypePlugin; 86 return api::processes::PROCESS_TYPE_NACL;
84 break; 87
85 case task_manager::Resource::WORKER: 88 case task_management::Task::UTILITY:
86 type = keys::kProcessTypeWorker; 89 return api::processes::PROCESS_TYPE_UTILITY;
87 break; 90
88 case task_manager::Resource::NACL: 91 case task_management::Task::GPU:
89 type = keys::kProcessTypeNacl; 92 return api::processes::PROCESS_TYPE_GPU;
90 break; 93
91 case task_manager::Resource::UTILITY: 94 case task_management::Task::UNKNOWN:
92 type = keys::kProcessTypeUtility; 95 case task_management::Task::ARC:
93 break; 96 case task_management::Task::SANDBOX_HELPER:
94 case task_manager::Resource::GPU: 97 case task_management::Task::ZYGOTE:
95 type = keys::kProcessTypeGPU; 98 return api::processes::PROCESS_TYPE_OTHER;
96 break; 99 }
97 case task_manager::Resource::ZYGOTE: 100
98 case task_manager::Resource::SANDBOX_HELPER: 101 NOTREACHED() << "Unknown task type.";
99 case task_manager::Resource::UNKNOWN: 102 return api::processes::PROCESS_TYPE_NONE;
100 type = keys::kProcessTypeOther; 103 }
101 break; 104
102 default: 105 // Fills |out_process| with the data of the process in which the task with |id|
103 NOTREACHED() << "Unknown resource type."; 106 // is running. If |include_optional| is true, this function will fill the
104 } 107 // optional fields in |api::processes::Process| except for |private_memory|,
105 result->SetString(keys::kTypeKey, type); 108 // which should be filled later if needed.
106 } 109 void FillProcessData(
107 110 task_management::TaskId id,
108 base::ListValue* GetTabsForProcess(int process_id) { 111 task_management::TaskManagerInterface* task_manager,
109 base::ListValue* tabs_list = new base::ListValue(); 112 bool include_optional,
110 113 api::processes::Process* out_process) {
111 // The tabs list only makes sense for render processes, so if we don't find 114 DCHECK(out_process);
112 // one, just return the empty list. 115
113 content::RenderProcessHost* rph = 116 out_process->id = task_manager->GetChildProcessUniqueId(id);
114 content::RenderProcessHost::FromID(process_id); 117 out_process->os_process_id = task_manager->GetProcessId(id);
115 if (rph == NULL) 118 out_process->type = GetProcessType(task_manager->GetType(id));
116 return tabs_list; 119 out_process->profile = base::UTF16ToUTF8(task_manager->GetProfileName(id));
117 120 out_process->nacl_debug_port = task_manager->GetNaClDebugStubPort(id);
118 int tab_id = -1; 121
119 // We need to loop through all the RVHs to ensure we collect the set of all 122 // Collect the tab IDs of all the tasks sharing this renderer if any.
120 // tabs using this renderer process. 123 const task_management::TaskIdList tasks_on_process =
121 scoped_ptr<content::RenderWidgetHostIterator> widgets( 124 task_manager->GetIdsOfTasksSharingSameProcess(id);
122 content::RenderWidgetHost::GetRenderWidgetHosts()); 125 for (const auto& task_id : tasks_on_process) {
123 while (content::RenderWidgetHost* widget = widgets->GetNextHost()) { 126 linked_ptr<api::processes::TaskInfo> task_info(
124 if (widget->GetProcess()->GetID() != process_id) 127 new api::processes::TaskInfo);
125 continue; 128 task_info->title = base::UTF16ToUTF8(task_manager->GetTitle(task_id));
126 129 const int tab_id = task_manager->GetTabId(task_id);
127 content::RenderViewHost* host = content::RenderViewHost::From(widget); 130 if (tab_id != -1)
128 content::WebContents* contents = 131 task_info->tab_id.reset(new int(tab_id));
129 content::WebContents::FromRenderViewHost(host); 132
130 if (contents) { 133 out_process->tasks.push_back(task_info);
131 tab_id = ExtensionTabUtil::GetTabId(contents); 134 }
132 if (tab_id != -1)
133 tabs_list->Append(new base::FundamentalValue(tab_id));
134 }
135 }
136
137 return tabs_list;
138 }
139
140 // This function creates a Process object to be returned to the extensions
141 // using these APIs. For memory details, which are not added by this function,
142 // the callers need to use AddMemoryDetails.
143 base::DictionaryValue* CreateProcessFromModel(int process_id,
144 TaskManagerModel* model,
145 int index,
146 bool include_optional) {
147 base::DictionaryValue* result = new base::DictionaryValue();
148 size_t mem;
149
150 result->SetInteger(keys::kIdKey, process_id);
151 result->SetInteger(keys::kOsProcessIdKey, model->GetProcessId(index));
152 SetProcessType(result, model, index);
153 result->SetString(keys::kTitleKey, model->GetResourceTitle(index));
154 result->SetString(keys::kProfileKey,
155 model->GetResourceProfileName(index));
156 result->SetInteger(keys::kNaClDebugPortKey,
157 model->GetNaClDebugStubPort(index));
158
159 result->Set(keys::kTabsListKey, GetTabsForProcess(process_id));
160 135
161 // If we don't need to include the optional properties, just return now. 136 // If we don't need to include the optional properties, just return now.
162 if (!include_optional) 137 if (!include_optional)
163 return result; 138 return;
164 139
165 result->SetDouble(keys::kCpuKey, model->GetCPUUsage(index)); 140 out_process->cpu.reset(new double(task_manager->GetCpuUsage(id)));
166 141
167 if (model->GetV8Memory(index, &mem)) 142 out_process->network.reset(new double(static_cast<double>(
168 result->SetDouble(keys::kJsMemoryAllocatedKey, 143 task_manager->GetProcessTotalNetworkUsage(id))));
169 static_cast<double>(mem)); 144
170 145 int64_t v8_allocated;
171 if (model->GetV8MemoryUsed(index, &mem)) 146 int64_t v8_used;
172 result->SetDouble(keys::kJsMemoryUsedKey, 147 if (task_manager->GetV8Memory(id, &v8_allocated, & v8_used)) {
173 static_cast<double>(mem)); 148 out_process->js_memory_allocated.reset(new double(static_cast<double>(
174 149 v8_allocated)));
175 if (model->GetSqliteMemoryUsedBytes(index, &mem)) 150 out_process->js_memory_used.reset(new double(static_cast<double>(v8_used)));
176 result->SetDouble(keys::kSqliteMemoryKey, 151 }
177 static_cast<double>(mem)); 152
153 const int64_t sqlite_bytes = task_manager->GetSqliteMemoryUsed(id);
154 if (sqlite_bytes != -1) {
155 out_process->sqlite_memory.reset(new double(static_cast<double>(
156 sqlite_bytes)));
157 }
178 158
179 blink::WebCache::ResourceTypeStats cache_stats; 159 blink::WebCache::ResourceTypeStats cache_stats;
180 if (model->GetWebCoreCacheStats(index, &cache_stats)) { 160 if (task_manager->GetWebCacheStats(id, &cache_stats)) {
181 result->Set(keys::kImageCacheKey, 161 out_process->image_cache = CreateCacheData(cache_stats.images);
182 CreateCacheData(cache_stats.images)); 162 out_process->script_cache = CreateCacheData(cache_stats.scripts);
183 result->Set(keys::kScriptCacheKey, 163 out_process->css_cache = CreateCacheData(cache_stats.cssStyleSheets);
184 CreateCacheData(cache_stats.scripts)); 164 }
185 result->Set(keys::kCssCacheKey, 165 }
186 CreateCacheData(cache_stats.cssStyleSheets));
187 }
188
189 // Network is reported by the TaskManager per resource (tab), not per
190 // process, therefore we need to iterate through the group of resources
191 // and aggregate the data.
192 int64_t net = 0;
193 int length = model->GetGroupRangeForResource(index).second;
194 for (int i = 0; i < length; ++i)
195 net += model->GetNetworkUsage(index + i);
196 result->SetDouble(keys::kNetworkKey, static_cast<double>(net));
197
198 return result;
199 }
200
201 // Since memory details are expensive to gather, we don't do it by default.
202 // This function is a helper to add memory details data to an existing
203 // Process object representation.
204 void AddMemoryDetails(base::DictionaryValue* result,
205 TaskManagerModel* model,
206 int index) {
207 size_t mem;
208 int64_t pr_mem =
209 model->GetPrivateMemory(index, &mem) ? static_cast<int64_t>(mem) : -1;
210 result->SetDouble(keys::kPrivateMemoryKey, static_cast<double>(pr_mem));
211 }
212
213 #endif // defined(ENABLE_TASK_MANAGER)
214 166
215 } // namespace 167 } // namespace
216 168
169 ////////////////////////////////////////////////////////////////////////////////
170 // ProcessesEventRouter:
171 ////////////////////////////////////////////////////////////////////////////////
172
217 ProcessesEventRouter::ProcessesEventRouter(content::BrowserContext* context) 173 ProcessesEventRouter::ProcessesEventRouter(content::BrowserContext* context)
218 : browser_context_(context), listeners_(0), task_manager_listening_(false) { 174 : task_management::TaskManagerObserver(
219 #if defined(ENABLE_TASK_MANAGER) 175 base::TimeDelta::FromSeconds(1),
220 model_ = TaskManager::GetInstance()->model(); 176 GetRefreshTypesFlagIncludeOptionalData()),
221 model_->AddObserver(this); 177 browser_context_(context),
222 178 listeners_(0) {
223 registrar_.Add(this, content::NOTIFICATION_RENDER_WIDGET_HOST_HANG,
224 content::NotificationService::AllSources());
225 registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_CLOSED,
226 content::NotificationService::AllSources());
227 #endif // defined(ENABLE_TASK_MANAGER)
228 } 179 }
229 180
230 ProcessesEventRouter::~ProcessesEventRouter() { 181 ProcessesEventRouter::~ProcessesEventRouter() {
231 #if defined(ENABLE_TASK_MANAGER) 182 if (observed_task_manager()) {
232 registrar_.Remove(this, content::NOTIFICATION_RENDER_WIDGET_HOST_HANG, 183 task_management::TaskManagerInterface::GetTaskManager()->RemoveObserver(
233 content::NotificationService::AllSources()); 184 this);
234 registrar_.Remove(this, content::NOTIFICATION_RENDERER_PROCESS_CLOSED, 185 }
235 content::NotificationService::AllSources());
236
237 if (task_manager_listening_)
238 model_->StopListening();
239
240 model_->RemoveObserver(this);
241 #endif // defined(ENABLE_TASK_MANAGER)
242 } 186 }
243 187
244 void ProcessesEventRouter::ListenerAdded() { 188 void ProcessesEventRouter::ListenerAdded() {
245 #if defined(ENABLE_TASK_MANAGER) 189 // Do we need to update memory usage?
246 // The task manager has its own ref count to balance other callers of 190 if (HasEventListeners(api::processes::OnUpdatedWithMemory::kEventName))
247 // StartUpdating/StopUpdating. 191 AddRefreshType(task_management::REFRESH_TYPE_MEMORY);
248 model_->StartUpdating(); 192
249 #endif // defined(ENABLE_TASK_MANAGER) 193 if (listeners_++ == 0) {
250 ++listeners_; 194 // The first listener to be added.
195 task_management::TaskManagerInterface::GetTaskManager()->AddObserver(this);
196 }
251 } 197 }
252 198
253 void ProcessesEventRouter::ListenerRemoved() { 199 void ProcessesEventRouter::ListenerRemoved() {
254 DCHECK_GT(listeners_, 0); 200 // No more listeners for memory usage?
255 --listeners_; 201 if (!HasEventListeners(api::processes::OnUpdatedWithMemory::kEventName))
256 #if defined(ENABLE_TASK_MANAGER) 202 RemoveRefreshType(task_management::REFRESH_TYPE_MEMORY);
257 // The task manager has its own ref count to balance other callers of 203
258 // StartUpdating/StopUpdating. 204 if (--listeners_ == 0) {
259 model_->StopUpdating(); 205 // Last listener to be removed.
260 #endif // defined(ENABLE_TASK_MANAGER) 206 task_management::TaskManagerInterface::GetTaskManager()->RemoveObserver(
261 } 207 this);
262 208 }
263 void ProcessesEventRouter::StartTaskManagerListening() { 209 }
264 #if defined(ENABLE_TASK_MANAGER) 210
265 if (!task_manager_listening_) { 211 void ProcessesEventRouter::OnTaskAdded(task_management::TaskId id) {
266 model_->StartListening(); 212 if (!HasEventListeners(api::processes::OnCreated::kEventName))
267 task_manager_listening_ = true; 213 return;
268 } 214
269 #endif // defined(ENABLE_TASK_MANAGER) 215 // Is this the first task to be created on the process and hence its creation
270 } 216 // corresponds to the creation of the process?
271 217 if (observed_task_manager()->GetNumberOfTasksOnSameProcess(id) != 1)
272 void ProcessesEventRouter::Observe( 218 return;
273 int type, 219
274 const content::NotificationSource& source, 220 // Ignore tasks that don't have a valid child process host ID like ARC
275 const content::NotificationDetails& details) { 221 // processes, as well as the browser process (onCreate() shouldn't report the
276 222 // creation of the browser process).
277 switch (type) { 223 const int child_process_host_id =
278 case content::NOTIFICATION_RENDER_WIDGET_HOST_HANG: 224 observed_task_manager()->GetChildProcessUniqueId(id);
279 ProcessHangEvent( 225 if (child_process_host_id == content::ChildProcessHost::kInvalidUniqueID ||
280 content::Source<content::RenderWidgetHost>(source).ptr()); 226 child_process_host_id == 0) {
281 break; 227 return;
282 case content::NOTIFICATION_RENDERER_PROCESS_CLOSED: 228 }
283 ProcessClosedEvent( 229
284 content::Source<content::RenderProcessHost>(source).ptr(), 230 api::processes::Process process;
285 content::Details<content::RenderProcessHost::RendererClosedDetails>( 231 FillProcessData(id, observed_task_manager(), false, &process);
286 details).ptr()); 232 DispatchEvent(events::PROCESSES_ON_CREATED,
287 break; 233 api::processes::OnCreated::kEventName,
288 default: 234 api::processes::OnCreated::Create(process));
289 NOTREACHED() << "Unexpected observe of type " << type; 235 }
290 } 236
291 return; 237 void ProcessesEventRouter::OnTaskToBeRemoved(task_management::TaskId id) {
292 } 238 if (!HasEventListeners(api::processes::OnExited::kEventName))
293 239 return;
294 void ProcessesEventRouter::OnItemsAdded(int start, int length) { 240
295 #if defined(ENABLE_TASK_MANAGER) 241 // Is this the last task to be removed from the process, and hence its removal
296 DCHECK_EQ(length, 1); 242 // corresponds to the termination of the process?
297 int index = start; 243 if (observed_task_manager()->GetNumberOfTasksOnSameProcess(id) != 1)
298 244 return;
299 std::string event(keys::kOnCreated); 245
300 if (!HasEventListeners(event)) 246 // Ignore tasks that don't have a valid child process host ID like ARC
301 return; 247 // processes, as well as the browser process (onExited() shouldn't report the
302 248 // exit of the browser process).
303 // If the item being added is not the first one in the group, find the base 249 const int child_process_host_id =
304 // index and use it for retrieving the process data. 250 observed_task_manager()->GetChildProcessUniqueId(id);
305 if (!model_->IsResourceFirstInGroup(start)) { 251 if (child_process_host_id == content::ChildProcessHost::kInvalidUniqueID ||
306 index = model_->GetGroupIndexForResource(start); 252 child_process_host_id == 0) {
307 } 253 return;
308 254 }
309 scoped_ptr<base::ListValue> args(new base::ListValue()); 255
310 base::DictionaryValue* process = CreateProcessFromModel( 256 int exit_code = 0;
311 model_->GetUniqueChildProcessId(index), model_, index, false); 257 base::TerminationStatus status = base::TERMINATION_STATUS_STILL_RUNNING;
312 DCHECK(process != NULL); 258 observed_task_manager()->GetTerminationStatus(id, &status, &exit_code);
313 259
314 if (process == NULL) 260 DispatchEvent(events::PROCESSES_ON_EXITED,
315 return; 261 api::processes::OnExited::kEventName,
316 262 api::processes::OnExited::Create(child_process_host_id,
317 args->Append(process); 263 status,
318 264 exit_code));
319 DispatchEvent(events::PROCESSES_ON_CREATED, keys::kOnCreated, 265
320 std::move(args)); 266 }
321 #endif // defined(ENABLE_TASK_MANAGER) 267
322 } 268 void ProcessesEventRouter::OnTasksRefreshedWithBackgroundCalculations(
323 269 const task_management::TaskIdList& task_ids) {
324 void ProcessesEventRouter::OnItemsChanged(int start, int length) { 270 const bool has_on_updated_listeners =
325 #if defined(ENABLE_TASK_MANAGER) 271 HasEventListeners(api::processes::OnUpdated::kEventName);
326 // If we don't have any listeners, return immediately. 272 const bool has_on_updated_with_memory_listeners =
327 if (listeners_ == 0) 273 HasEventListeners(api::processes::OnUpdatedWithMemory::kEventName);
328 return; 274
329 275 if (!has_on_updated_listeners && !has_on_updated_with_memory_listeners)
330 if (!model_) 276 return;
331 return; 277
332 278 // Get the data of tasks sharing the same process only once.
333 // We need to know which type of onUpdated events to fire and whether to 279 std::set<base::ProcessId> seen_processes;
334 // collect memory or not. 280 base::DictionaryValue processes_dictionary;
335 std::string updated_event(keys::kOnUpdated); 281 for (const auto& task_id : task_ids) {
336 std::string updated_event_memory(keys::kOnUpdatedWithMemory); 282 // We are not interested in tasks, but rather the processes on which they
337 bool updated = HasEventListeners(updated_event); 283 // run.
338 bool updated_memory = HasEventListeners(updated_event_memory); 284 const base::ProcessId proc_id =
339 285 observed_task_manager()->GetProcessId(task_id);
340 DCHECK(updated || updated_memory); 286 if (seen_processes.count(proc_id))
341 287 continue;
342 IDMap<base::DictionaryValue> processes_map; 288
343 for (int i = start; i < start + length; i++) { 289 const int child_process_host_id =
344 if (model_->IsResourceFirstInGroup(i)) { 290 observed_task_manager()->GetChildProcessUniqueId(task_id);
345 int id = model_->GetUniqueChildProcessId(i); 291 // Ignore tasks that don't have a valid child process host ID like ARC
346 base::DictionaryValue* process = CreateProcessFromModel(id, model_, i, 292 // processes. We report the browser process info here though.
347 true); 293 if (child_process_host_id == content::ChildProcessHost::kInvalidUniqueID)
348 processes_map.AddWithID(process, i); 294 continue;
295
296 seen_processes.insert(proc_id);
297 api::processes::Process process;
298 FillProcessData(task_id, observed_task_manager(), true, &process);
299
300 if (has_on_updated_with_memory_listeners) {
301 // Append the private memory usage to the process data.
302 const int64_t private_memory =
303 observed_task_manager()->GetPrivateMemoryUsage(task_id);
304 process.private_memory.reset(new double(static_cast<double>(
305 private_memory)));
349 } 306 }
350 } 307
351 308 // Store each process indexed by the string version of its ChildProcessHost
352 int id; 309 // ID.
353 std::string idkey(keys::kIdKey); 310 processes_dictionary.Set(base::IntToString(child_process_host_id),
354 base::DictionaryValue* processes = new base::DictionaryValue(); 311 process.ToValue());
355 312 }
356 if (updated) { 313
357 IDMap<base::DictionaryValue>::iterator it(&processes_map); 314 // Done with data collection. Now dispatch the appropriate events according to
358 for (; !it.IsAtEnd(); it.Advance()) { 315 // the present listeners.
359 if (!it.GetCurrentValue()->GetInteger(idkey, &id)) 316 DCHECK(has_on_updated_listeners || has_on_updated_with_memory_listeners);
360 continue; 317 if (has_on_updated_listeners) {
361 318 api::processes::OnUpdated::Processes processes;
362 // Store each process indexed by the string version of its id. 319 processes.additional_properties.MergeDictionary(&processes_dictionary);
363 processes->Set(base::IntToString(id), it.GetCurrentValue()); 320 // NOTE: If there are listeners to the updates with memory as well,
364 } 321 // listeners to onUpdated (without memory) will also get the memory info
365 322 // of processes as an added bonus.
366 scoped_ptr<base::ListValue> args(new base::ListValue()); 323 DispatchEvent(events::PROCESSES_ON_UPDATED,
367 args->Append(processes); 324 api::processes::OnUpdated::kEventName,
368 DispatchEvent(events::PROCESSES_ON_UPDATED, keys::kOnUpdated, 325 api::processes::OnUpdated::Create(processes));
369 std::move(args)); 326 }
370 } 327
371 328 if (has_on_updated_with_memory_listeners) {
372 if (updated_memory) { 329 api::processes::OnUpdatedWithMemory::Processes processes;
373 IDMap<base::DictionaryValue>::iterator it(&processes_map); 330 processes.additional_properties.MergeDictionary(&processes_dictionary);
374 for (; !it.IsAtEnd(); it.Advance()) {
375 if (!it.GetCurrentValue()->GetInteger(idkey, &id))
376 continue;
377
378 AddMemoryDetails(it.GetCurrentValue(), model_, it.GetCurrentKey());
379
380 // Store each process indexed by the string version of its id if we didn't
381 // already insert it as part of the onUpdated processing above.
382 if (!updated)
383 processes->Set(base::IntToString(id), it.GetCurrentValue());
384 }
385
386 scoped_ptr<base::ListValue> args(new base::ListValue());
387 args->Append(processes);
388 DispatchEvent(events::PROCESSES_ON_UPDATED_WITH_MEMORY, 331 DispatchEvent(events::PROCESSES_ON_UPDATED_WITH_MEMORY,
389 keys::kOnUpdatedWithMemory, std::move(args)); 332 api::processes::OnUpdatedWithMemory::kEventName,
390 } 333 api::processes::OnUpdatedWithMemory::Create(processes));
391 #endif // defined(ENABLE_TASK_MANAGER) 334 }
392 } 335 }
393 336
394 void ProcessesEventRouter::OnItemsToBeRemoved(int start, int length) { 337 void ProcessesEventRouter::OnTaskUnresponsive(task_management::TaskId id) {
395 #if defined(ENABLE_TASK_MANAGER) 338 if (!HasEventListeners(api::processes::OnUnresponsive::kEventName))
396 DCHECK_EQ(length, 1); 339 return;
397 340
398 // Process exit for renderer processes has the data about exit code and 341 api::processes::Process process;
399 // termination status, therefore we will rely on notifications and not on 342 FillProcessData(id, observed_task_manager(), false, &process);
400 // the Task Manager data. We do use the rest of this method for non-renderer 343 DispatchEvent(events::PROCESSES_ON_UNRESPONSIVE,
401 // processes. 344 api::processes::OnUnresponsive::kEventName,
402 if (model_->GetResourceType(start) == task_manager::Resource::RENDERER) 345 api::processes::OnUnresponsive::Create(process));
403 return;
404
405 // The callback function parameters.
406 scoped_ptr<base::ListValue> args(new base::ListValue());
407
408 // First arg: The id of the process that was closed.
409 args->Append(new base::FundamentalValue(
410 model_->GetUniqueChildProcessId(start)));
411
412 // Second arg: The exit type for the process.
413 args->Append(new base::FundamentalValue(0));
414
415 // Third arg: The exit code for the process.
416 args->Append(new base::FundamentalValue(0));
417
418 DispatchEvent(events::PROCESSES_ON_EXITED, keys::kOnExited, std::move(args));
419 #endif // defined(ENABLE_TASK_MANAGER)
420 }
421
422 void ProcessesEventRouter::ProcessHangEvent(content::RenderWidgetHost* widget) {
423 #if defined(ENABLE_TASK_MANAGER)
424 std::string event(keys::kOnUnresponsive);
425 if (!HasEventListeners(event))
426 return;
427
428 base::DictionaryValue* process = NULL;
429 int count = model_->ResourceCount();
430 int id = widget->GetProcess()->GetID();
431
432 for (int i = 0; i < count; ++i) {
433 if (model_->IsResourceFirstInGroup(i)) {
434 if (id == model_->GetUniqueChildProcessId(i)) {
435 process = CreateProcessFromModel(id, model_, i, false);
436 break;
437 }
438 }
439 }
440
441 if (process == NULL)
442 return;
443
444 scoped_ptr<base::ListValue> args(new base::ListValue());
445 args->Append(process);
446
447 DispatchEvent(events::PROCESSES_ON_UNRESPONSIVE, keys::kOnUnresponsive,
448 std::move(args));
449 #endif // defined(ENABLE_TASK_MANAGER)
450 }
451
452 void ProcessesEventRouter::ProcessClosedEvent(
453 content::RenderProcessHost* rph,
454 content::RenderProcessHost::RendererClosedDetails* details) {
455 #if defined(ENABLE_TASK_MANAGER)
456 // The callback function parameters.
457 scoped_ptr<base::ListValue> args(new base::ListValue());
458
459 // First arg: The id of the process that was closed.
460 args->Append(new base::FundamentalValue(rph->GetID()));
461
462 // Second arg: The exit type for the process.
463 args->Append(new base::FundamentalValue(details->status));
464
465 // Third arg: The exit code for the process.
466 args->Append(new base::FundamentalValue(details->exit_code));
467
468 DispatchEvent(events::PROCESSES_ON_EXITED, keys::kOnExited, std::move(args));
469 #endif // defined(ENABLE_TASK_MANAGER)
470 } 346 }
471 347
472 void ProcessesEventRouter::DispatchEvent( 348 void ProcessesEventRouter::DispatchEvent(
473 events::HistogramValue histogram_value, 349 events::HistogramValue histogram_value,
474 const std::string& event_name, 350 const std::string& event_name,
475 scoped_ptr<base::ListValue> event_args) { 351 scoped_ptr<base::ListValue> event_args) const {
476 EventRouter* event_router = EventRouter::Get(browser_context_); 352 EventRouter* event_router = EventRouter::Get(browser_context_);
477 if (event_router) { 353 if (event_router) {
478 scoped_ptr<Event> event( 354 scoped_ptr<Event> event(
479 new Event(histogram_value, event_name, std::move(event_args))); 355 new Event(histogram_value, event_name, std::move(event_args)));
480 event_router->BroadcastEvent(std::move(event)); 356 event_router->BroadcastEvent(std::move(event));
481 } 357 }
482 } 358 }
483 359
484 bool ProcessesEventRouter::HasEventListeners(const std::string& event_name) { 360 bool ProcessesEventRouter::HasEventListeners(
361 const std::string& event_name) const {
485 EventRouter* event_router = EventRouter::Get(browser_context_); 362 EventRouter* event_router = EventRouter::Get(browser_context_);
486 return event_router && event_router->HasEventListener(event_name); 363 return event_router && event_router->HasEventListener(event_name);
487 } 364 }
488 365
366 ////////////////////////////////////////////////////////////////////////////////
367 // ProcessesAPI:
368 ////////////////////////////////////////////////////////////////////////////////
369
489 ProcessesAPI::ProcessesAPI(content::BrowserContext* context) 370 ProcessesAPI::ProcessesAPI(content::BrowserContext* context)
490 : browser_context_(context) { 371 : browser_context_(context) {
491 EventRouter* event_router = EventRouter::Get(browser_context_); 372 EventRouter* event_router = EventRouter::Get(browser_context_);
492 event_router->RegisterObserver(this, processes_api_constants::kOnUpdated); 373 // Monitor when the following events are being listened to in order to know
374 // when to start the task manager.
375 event_router->RegisterObserver(this, api::processes::OnUpdated::kEventName);
376 event_router->RegisterObserver(
377 this, api::processes::OnUpdatedWithMemory::kEventName);
378 event_router->RegisterObserver(this, api::processes::OnCreated::kEventName);
493 event_router->RegisterObserver(this, 379 event_router->RegisterObserver(this,
494 processes_api_constants::kOnUpdatedWithMemory); 380 api::processes::OnUnresponsive::kEventName);
495 ExtensionFunctionRegistry* registry = 381 event_router->RegisterObserver(this, api::processes::OnExited::kEventName);
496 ExtensionFunctionRegistry::GetInstance();
497 registry->RegisterFunction<GetProcessIdForTabFunction>();
498 registry->RegisterFunction<TerminateFunction>();
499 registry->RegisterFunction<GetProcessInfoFunction>();
500 } 382 }
501 383
502 ProcessesAPI::~ProcessesAPI() { 384 ProcessesAPI::~ProcessesAPI() {
385 // This object has already been unregistered as an observer in Shutdown().
503 } 386 }
504 387
505 void ProcessesAPI::Shutdown() {
506 EventRouter::Get(browser_context_)->UnregisterObserver(this);
507 }
508
509 static base::LazyInstance<BrowserContextKeyedAPIFactory<ProcessesAPI> >
510 g_factory = LAZY_INSTANCE_INITIALIZER;
511
512 // static 388 // static
513 BrowserContextKeyedAPIFactory<ProcessesAPI>* 389 BrowserContextKeyedAPIFactory<ProcessesAPI>*
514 ProcessesAPI::GetFactoryInstance() { 390 ProcessesAPI::GetFactoryInstance() {
515 return g_factory.Pointer(); 391 return g_processes_api_factory.Pointer();
516 } 392 }
517 393
518 // static 394 // static
519 ProcessesAPI* ProcessesAPI::Get(content::BrowserContext* context) { 395 ProcessesAPI* ProcessesAPI::Get(content::BrowserContext* context) {
520 return BrowserContextKeyedAPIFactory<ProcessesAPI>::Get(context); 396 return BrowserContextKeyedAPIFactory<ProcessesAPI>::Get(context);
521 } 397 }
522 398
399 void ProcessesAPI::Shutdown() {
400 EventRouter::Get(browser_context_)->UnregisterObserver(this);
401 }
402
403 void ProcessesAPI::OnListenerAdded(const EventListenerInfo& details) {
404 // The ProcessesEventRouter will observe the TaskManager as long as there are
405 // listeners for the processes.onUpdated/.onUpdatedWithMemory/.onCreated ...
406 // etc. events.
407 processes_event_router()->ListenerAdded();
408 }
409
410 void ProcessesAPI::OnListenerRemoved(const EventListenerInfo& details) {
411 // If a processes.onUpdated/.onUpdatedWithMemory/.onCreated ... etc. event
412 // listener is removed (or a process with one exits), then we let the
413 // extension API know that it has one fewer listener.
414 processes_event_router()->ListenerRemoved();
415 }
416
523 ProcessesEventRouter* ProcessesAPI::processes_event_router() { 417 ProcessesEventRouter* ProcessesAPI::processes_event_router() {
524 if (!processes_event_router_) 418 if (!processes_event_router_.get())
525 processes_event_router_.reset(new ProcessesEventRouter(browser_context_)); 419 processes_event_router_.reset(new ProcessesEventRouter(browser_context_));
526 return processes_event_router_.get(); 420 return processes_event_router_.get();
527 } 421 }
528 422
529 void ProcessesAPI::OnListenerAdded(const EventListenerInfo& details) { 423 ////////////////////////////////////////////////////////////////////////////////
530 // We lazily tell the TaskManager to start updating when listeners to the 424 // ProcessesGetProcessIdForTabFunction:
531 // processes.onUpdated or processes.onUpdatedWithMemory events arrive. 425 ////////////////////////////////////////////////////////////////////////////////
532 processes_event_router()->ListenerAdded(); 426
533 } 427 ExtensionFunction::ResponseAction ProcessesGetProcessIdForTabFunction::Run() {
534 428 // For this function, the task manager doesn't even need to be running.
535 void ProcessesAPI::OnListenerRemoved(const EventListenerInfo& details) { 429 scoped_ptr<api::processes::GetProcessIdForTab::Params> params(
536 // If a processes.onUpdated or processes.onUpdatedWithMemory event listener 430 api::processes::GetProcessIdForTab::Params::Create(*args_));
537 // is removed (or a process with one exits), then we let the extension API 431 EXTENSION_FUNCTION_VALIDATE(params.get());
538 // know that it has one fewer listener. 432
539 processes_event_router()->ListenerRemoved(); 433 const int tab_id = params->tab_id;
540 } 434 content::WebContents* contents = nullptr;
541 435 int tab_index = -1;
542 GetProcessIdForTabFunction::GetProcessIdForTabFunction() : tab_id_(-1) { 436 if (!ExtensionTabUtil::GetTabById(
543 } 437 tab_id,
544 438 Profile::FromBrowserContext(browser_context()),
545 bool GetProcessIdForTabFunction::RunAsync() { 439 include_incognito(),
546 #if defined(ENABLE_TASK_MANAGER) 440 nullptr,
547 EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &tab_id_)); 441 nullptr,
548 442 &contents,
549 // Add a reference, which is balanced in GetProcessIdForTab to keep the object 443 &tab_index)) {
550 // around and allow for the callback to be invoked. 444 return RespondNow(Error(tabs_constants::kTabNotFoundError,
445 base::IntToString(tab_id)));
446 }
447
448 const int process_id = contents->GetRenderProcessHost()->GetID();
449 return RespondNow(ArgumentList(
450 api::processes::GetProcessIdForTab::Results::Create(process_id)));
451 }
452
453 ////////////////////////////////////////////////////////////////////////////////
454 // ProcessesTerminateFunction:
455 ////////////////////////////////////////////////////////////////////////////////
456
457 ExtensionFunction::ResponseAction ProcessesTerminateFunction::Run() {
458 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
459
460 // For this function, the task manager doesn't even need to be running.
461 scoped_ptr<api::processes::Terminate::Params> params(
462 api::processes::Terminate::Params::Create(*args_));
463 EXTENSION_FUNCTION_VALIDATE(params.get());
464
465 child_process_host_id_ = params->process_id;
466 if (child_process_host_id_ < 0) {
467 return RespondNow(Error(errors::kInvalidArgument,
468 base::IntToString(child_process_host_id_)));
469 } else if (child_process_host_id_ == 0) {
470 // Cannot kill the browser process.
471 return RespondNow(Error(errors::kNotAllowedToTerminate,
472 base::IntToString(child_process_host_id_)));
473 }
474
475 content::BrowserThread::PostTaskAndReplyWithResult(
476 content::BrowserThread::IO,
477 FROM_HERE,
478 base::Bind(&ProcessesTerminateFunction::GetProcessHandleIO,
479 this,
480 child_process_host_id_),
481 base::Bind(&ProcessesTerminateFunction::OnProcessHandleUI, this));
482
483 // Promise to respond later.
484 return RespondLater();
485 }
486
487 base::ProcessHandle ProcessesTerminateFunction::GetProcessHandleIO(
488 int child_process_host_id) const {
489 DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
490
491 auto* host = content::BrowserChildProcessHost::FromID(child_process_host_id);
492 if (host)
493 return host->GetData().handle;
494
495 return base::kNullProcessHandle;
496 }
497
498 void ProcessesTerminateFunction::OnProcessHandleUI(base::ProcessHandle handle) {
499 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
500
501 if (handle == base::kNullProcessHandle) {
502 // If we didn't get anything from BrowserChildProcessHost, then it could be
503 // a renderer.
504 auto* render_process_host =
505 content::RenderProcessHost::FromID(child_process_host_id_);
506 if (render_process_host)
507 handle = render_process_host->GetHandle();
508 }
509
510 if (handle == base::kNullProcessHandle) {
511 Respond(Error(errors::kProcessNotFound,
512 base::IntToString(child_process_host_id_)));
513 return;
514 }
515
516 if (handle == base::GetCurrentProcessHandle()) {
517 // Cannot kill the browser process.
518 Respond(Error(errors::kNotAllowedToTerminate,
519 base::IntToString(child_process_host_id_)));
520 return;
521 }
522
523 base::Process process = base::Process::Open(base::GetProcId(handle));
524 const bool did_terminate =
525 process.Terminate(content::RESULT_CODE_KILLED, true);
526 if (did_terminate)
527 UMA_HISTOGRAM_COUNTS("ChildProcess.KilledByExtensionAPI", 1);
528
529 Respond(ArgumentList(
530 api::processes::Terminate::Results::Create(did_terminate)));
531 }
532
533 ////////////////////////////////////////////////////////////////////////////////
534 // ProcessesGetProcessInfoFunction:
535 ////////////////////////////////////////////////////////////////////////////////
536
537 ProcessesGetProcessInfoFunction::ProcessesGetProcessInfoFunction()
538 : task_management::TaskManagerObserver(
539 base::TimeDelta::FromSeconds(1),
540 GetRefreshTypesFlagOnlyEssentialData()) {
541 }
542
543 ExtensionFunction::ResponseAction ProcessesGetProcessInfoFunction::Run() {
544 scoped_ptr<api::processes::GetProcessInfo::Params> params(
545 api::processes::GetProcessInfo::Params::Create(*args_));
546 EXTENSION_FUNCTION_VALIDATE(params.get());
547 if (params->process_ids.as_integer)
548 process_host_ids_.push_back(*params->process_ids.as_integer);
549 else
550 process_host_ids_.swap(*params->process_ids.as_integers);
551
552 include_memory_ = params->include_memory;
553 if (include_memory_)
554 AddRefreshType(task_management::REFRESH_TYPE_MEMORY);
555
556 // Keep this object alive until the first of either OnTasksRefreshed() or
557 // OnTasksRefreshedWithBackgroundCalculations() is received depending on
558 // |include_memory_|.
551 AddRef(); 559 AddRef();
552 560
553 // If the task manager is already listening, just post a task to execute 561 // The task manager needs to be enabled for this function.
554 // which will invoke the callback once we have returned from this function. 562 // Start observing the task manager and wait for the next refresh event.
555 // Otherwise, wait for the notification that the task manager is done with 563 task_management::TaskManagerInterface::GetTaskManager()->AddObserver(this);
556 // the data gathering. 564
557 if (ProcessesAPI::Get(GetProfile()) 565 return RespondLater();
558 ->processes_event_router() 566 }
559 ->is_task_manager_listening()) { 567
560 base::ThreadTaskRunnerHandle::Get()->PostTask( 568 void ProcessesGetProcessInfoFunction::OnTasksRefreshed(
561 FROM_HERE, 569 const task_management::TaskIdList& task_ids) {
562 base::Bind(&GetProcessIdForTabFunction::GetProcessIdForTab, this)); 570 // Memory is background calculated and will be ready when
563 } else { 571 // OnTasksRefreshedWithBackgroundCalculations() is invoked.
564 TaskManager::GetInstance()->model()->RegisterOnDataReadyCallback( 572 if (include_memory_)
565 base::Bind(&GetProcessIdForTabFunction::GetProcessIdForTab, this)); 573 return;
566 574
567 ProcessesAPI::Get(GetProfile()) 575 GatherDataAndRespond(task_ids);
568 ->processes_event_router() 576 }
569 ->StartTaskManagerListening(); 577
570 } 578 void
571 579 ProcessesGetProcessInfoFunction::OnTasksRefreshedWithBackgroundCalculations(
572 return true; 580 const task_management::TaskIdList& task_ids) {
573 #else 581 if (!include_memory_)
574 error_ = errors::kExtensionNotSupported; 582 return;
575 return false; 583
576 #endif // defined(ENABLE_TASK_MANAGER) 584 GatherDataAndRespond(task_ids);
577 } 585 }
578 586
579 void GetProcessIdForTabFunction::GetProcessIdForTab() { 587 ProcessesGetProcessInfoFunction::~ProcessesGetProcessInfoFunction() {}
580 content::WebContents* contents = NULL; 588
581 int tab_index = -1; 589 void ProcessesGetProcessInfoFunction::GatherDataAndRespond(
582 if (!ExtensionTabUtil::GetTabById(tab_id_, 590 const task_management::TaskIdList& task_ids) {
583 GetProfile(),
584 include_incognito(),
585 NULL,
586 NULL,
587 &contents,
588 &tab_index)) {
589 error_ = ErrorUtils::FormatErrorMessage(tabs_constants::kTabNotFoundError,
590 base::IntToString(tab_id_));
591 SetResult(new base::FundamentalValue(-1));
592 SendResponse(false);
593 } else {
594 int process_id = contents->GetRenderProcessHost()->GetID();
595 SetResult(new base::FundamentalValue(process_id));
596 SendResponse(true);
597 }
598
599 // Balance the AddRef in the RunAsync.
600 Release();
601 }
602
603 TerminateFunction::TerminateFunction() : process_id_(-1) {
604 }
605
606 bool TerminateFunction::RunAsync() {
607 #if defined(ENABLE_TASK_MANAGER)
608 EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &process_id_));
609
610 // Add a reference, which is balanced in TerminateProcess to keep the object
611 // around and allow for the callback to be invoked.
612 AddRef();
613
614 // If the task manager is already listening, just post a task to execute
615 // which will invoke the callback once we have returned from this function.
616 // Otherwise, wait for the notification that the task manager is done with
617 // the data gathering.
618 if (ProcessesAPI::Get(GetProfile())
619 ->processes_event_router()
620 ->is_task_manager_listening()) {
621 base::ThreadTaskRunnerHandle::Get()->PostTask(
622 FROM_HERE, base::Bind(&TerminateFunction::TerminateProcess, this));
623 } else {
624 TaskManager::GetInstance()->model()->RegisterOnDataReadyCallback(
625 base::Bind(&TerminateFunction::TerminateProcess, this));
626
627 ProcessesAPI::Get(GetProfile())
628 ->processes_event_router()
629 ->StartTaskManagerListening();
630 }
631
632 return true;
633 #else
634 error_ = errors::kExtensionNotSupported;
635 return false;
636 #endif // defined(ENABLE_TASK_MANAGER)
637 }
638
639
640 void TerminateFunction::TerminateProcess() {
641 #if defined(ENABLE_TASK_MANAGER)
642 TaskManagerModel* model = TaskManager::GetInstance()->model();
643
644 bool found = false;
645 for (int i = 0, count = model->ResourceCount(); i < count; ++i) {
646 if (!model->IsResourceFirstInGroup(i) ||
647 process_id_ != model->GetUniqueChildProcessId(i)) {
648 continue;
649 }
650 base::ProcessHandle process_handle = model->GetProcess(i);
651 if (process_handle == base::GetCurrentProcessHandle()) {
652 // Cannot kill the browser process.
653 // TODO(kalman): Are there other sensitive processes?
654 error_ = ErrorUtils::FormatErrorMessage(errors::kNotAllowedToTerminate,
655 base::IntToString(process_id_));
656 } else {
657 base::Process process =
658 base::Process::DeprecatedGetProcessFromHandle(process_handle);
659 bool did_terminate = process.Terminate(content::RESULT_CODE_KILLED, true);
660 if (did_terminate)
661 UMA_HISTOGRAM_COUNTS("ChildProcess.KilledByExtensionAPI", 1);
662 SetResult(new base::FundamentalValue(did_terminate));
663 }
664 found = true;
665 break;
666 }
667 if (!found) {
668 error_ = ErrorUtils::FormatErrorMessage(errors::kProcessNotFound,
669 base::IntToString(process_id_));
670 }
671
672 SendResponse(error_.empty());
673
674 // Balance the AddRef in the RunAsync.
675 Release();
676 #else
677 error_ = errors::kExtensionNotSupported;
678 SendResponse(false);
679 #endif // defined(ENABLE_TASK_MANAGER)
680 }
681
682 GetProcessInfoFunction::GetProcessInfoFunction()
683 #if defined(ENABLE_TASK_MANAGER)
684 : memory_(false)
685 #endif
686 {
687 }
688
689 GetProcessInfoFunction::~GetProcessInfoFunction() {
690 }
691
692 bool GetProcessInfoFunction::RunAsync() {
693 #if defined(ENABLE_TASK_MANAGER)
694 base::Value* processes = NULL;
695
696 EXTENSION_FUNCTION_VALIDATE(args_->Get(0, &processes));
697 EXTENSION_FUNCTION_VALIDATE(args_->GetBoolean(1, &memory_));
698 EXTENSION_FUNCTION_VALIDATE(ReadOneOrMoreIntegers(processes, &process_ids_));
699
700 // Add a reference, which is balanced in GatherProcessInfo to keep the object
701 // around and allow for the callback to be invoked.
702 AddRef();
703
704 // If the task manager is already listening, just post a task to execute
705 // which will invoke the callback once we have returned from this function.
706 // Otherwise, wait for the notification that the task manager is done with
707 // the data gathering.
708 if (ProcessesAPI::Get(GetProfile())
709 ->processes_event_router()
710 ->is_task_manager_listening()) {
711 base::ThreadTaskRunnerHandle::Get()->PostTask(
712 FROM_HERE,
713 base::Bind(&GetProcessInfoFunction::GatherProcessInfo, this));
714 } else {
715 TaskManager::GetInstance()->model()->RegisterOnDataReadyCallback(
716 base::Bind(&GetProcessInfoFunction::GatherProcessInfo, this));
717
718 ProcessesAPI::Get(GetProfile())
719 ->processes_event_router()
720 ->StartTaskManagerListening();
721 }
722 return true;
723
724 #else
725 error_ = errors::kExtensionNotSupported;
726 return false;
727 #endif // defined(ENABLE_TASK_MANAGER)
728 }
729
730 void GetProcessInfoFunction::GatherProcessInfo() {
731 #if defined(ENABLE_TASK_MANAGER)
732 TaskManagerModel* model = TaskManager::GetInstance()->model();
733 base::DictionaryValue* processes = new base::DictionaryValue();
734
735 // If there are no process IDs specified, it means we need to return all of 591 // If there are no process IDs specified, it means we need to return all of
736 // the ones we know of. 592 // the ones we know of.
737 if (process_ids_.size() == 0) { 593 const bool specific_processes_requested = !process_host_ids_.empty();
738 int resources = model->ResourceCount(); 594 std::set<base::ProcessId> seen_processes;
739 for (int i = 0; i < resources; ++i) { 595 // Create the results object as defined in the generated API from process.idl
740 if (model->IsResourceFirstInGroup(i)) { 596 // and fill it with the processes info.
741 int id = model->GetUniqueChildProcessId(i); 597 api::processes::GetProcessInfo::Results::Processes processes;
742 base::DictionaryValue* d = CreateProcessFromModel(id, model, i, false); 598 for (const auto& task_id : task_ids) {
743 if (memory_) 599 const base::ProcessId proc_id =
744 AddMemoryDetails(d, model, i); 600 observed_task_manager()->GetProcessId(task_id);
745 processes->Set(base::IntToString(id), d); 601 if (seen_processes.count(proc_id))
746 } 602 continue;
603
604 const int child_process_host_id =
605 observed_task_manager()->GetChildProcessUniqueId(task_id);
606 // Ignore tasks that don't have a valid child process host ID like ARC
607 // processes. We report the browser process info here though.
608 if (child_process_host_id == content::ChildProcessHost::kInvalidUniqueID)
609 continue;
610
611 if (specific_processes_requested) {
612 // Note: we can't use |!process_host_ids_.empty()| directly in the above
613 // condition as we will erase from |process_host_ids_| below.
614 auto itr = std::find(process_host_ids_.begin(),
615 process_host_ids_.end(),
616 child_process_host_id);
617 if (itr == process_host_ids_.end())
618 continue;
619
620 // If found, we remove it from |process_host_ids|, so that at the end if
621 // anything remains in |process_host_ids|, those were invalid arguments
622 // that will be reported on the console.
623 process_host_ids_.erase(itr);
747 } 624 }
748 } else { 625
749 int resources = model->ResourceCount(); 626 seen_processes.insert(proc_id);
750 for (int i = 0; i < resources; ++i) { 627
751 if (model->IsResourceFirstInGroup(i)) { 628 // We do not include the optional data in this function results.
752 int id = model->GetUniqueChildProcessId(i); 629 api::processes::Process process;
753 std::vector<int>::iterator proc_id = std::find(process_ids_.begin(), 630 FillProcessData(task_id, observed_task_manager(), false, &process);
754 process_ids_.end(), id); 631
755 if (proc_id != process_ids_.end()) { 632 if (include_memory_) {
756 base::DictionaryValue* d = 633 // Append the private memory usage to the process data.
757 CreateProcessFromModel(id, model, i, false); 634 const int64_t private_memory =
758 if (memory_) 635 observed_task_manager()->GetPrivateMemoryUsage(task_id);
759 AddMemoryDetails(d, model, i); 636 process.private_memory.reset(new double(static_cast<double>(
760 processes->Set(base::IntToString(id), d); 637 private_memory)));
761
762 process_ids_.erase(proc_id);
763 if (process_ids_.size() == 0)
764 break;
765 }
766 }
767 } 638 }
768 // If not all processes were found, log them to the extension's console to 639
769 // help the developer, but don't fail the API call. 640 // Store each process indexed by the string version of its
770 for (int pid : process_ids_) { 641 // ChildProcessHost ID.
771 WriteToConsole(content::CONSOLE_MESSAGE_LEVEL_ERROR, 642 processes.additional_properties.Set(
772 ErrorUtils::FormatErrorMessage(errors::kProcessNotFound, 643 base::IntToString(child_process_host_id),
773 base::IntToString(pid))); 644 process.ToValue());
774 } 645 }
775 } 646
776 647 // Report the invalid host ids sent in the arguments.
777 SetResult(processes); 648 for (const auto& host_id : process_host_ids_) {
778 SendResponse(true); 649 WriteToConsole(content::CONSOLE_MESSAGE_LEVEL_ERROR,
779 650 ErrorUtils::FormatErrorMessage(errors::kProcessNotFound,
780 // Balance the AddRef in the RunAsync. 651 base::IntToString(host_id)));
652 }
653
654 // Send the response.
655 Respond(ArgumentList(
656 api::processes::GetProcessInfo::Results::Create(processes)));
657
658 // Stop observing the task manager, and balance the AddRef() in Run().
659 task_management::TaskManagerInterface::GetTaskManager()->RemoveObserver(this);
781 Release(); 660 Release();
782 #endif // defined(ENABLE_TASK_MANAGER)
783 } 661 }
784 662
785 } // namespace extensions 663 } // namespace extensions
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698