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

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

Powered by Google App Engine
This is Rietveld 408576698