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

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: [NOT a WIP] All tests are passing. 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:
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,
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) {
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 api::processes::Process process;
275 const content::NotificationDetails& details) { 216 FillProcessData(&process, id, observed_task_manager(), false);
276 217 DispatchEvent(events::PROCESSES_ON_CREATED,
277 switch (type) { 218 api::processes::OnCreated::kEventName,
278 case content::NOTIFICATION_RENDER_WIDGET_HOST_HANG: 219 api::processes::OnCreated::Create(process));
279 ProcessHangEvent( 220 }
280 content::Source<content::RenderWidgetHost>(source).ptr()); 221
281 break; 222 void ProcessesEventRouter::OnTaskToBeRemoved(task_management::TaskId id) {
282 case content::NOTIFICATION_RENDERER_PROCESS_CLOSED: 223 if (!HasEventListeners(api::processes::OnExited::kEventName))
283 ProcessClosedEvent( 224 return;
284 content::Source<content::RenderProcessHost>(source).ptr(), 225
285 content::Details<content::RenderProcessHost::RendererClosedDetails>( 226 // Is this the last task to be removed from the process, and hence its removal
286 details).ptr()); 227 // corresponds to the termination of the process?
287 break; 228 if (observed_task_manager()->GetNumberOfTasksOnSameProcess(id) != 1)
288 default: 229 return;
289 NOTREACHED() << "Unexpected observe of type " << type; 230
290 } 231 int exit_code = 0;
291 return; 232 base::TerminationStatus status = base::TERMINATION_STATUS_STILL_RUNNING;
292 } 233 observed_task_manager()->GetTerminationStatus(id, &status, &exit_code);
293 234
294 void ProcessesEventRouter::OnItemsAdded(int start, int length) { 235 DispatchEvent(events::PROCESSES_ON_EXITED,
295 #if defined(ENABLE_TASK_MANAGER) 236 api::processes::OnExited::kEventName,
296 DCHECK_EQ(length, 1); 237 api::processes::OnExited::Create(
297 int index = start; 238 observed_task_manager()->GetChildProcessUniqueID(id),
298 239 status,
299 std::string event(keys::kOnCreated); 240 exit_code));
300 if (!HasEventListeners(event)) 241
301 return; 242 }
302 243
303 // If the item being added is not the first one in the group, find the base 244 void ProcessesEventRouter::OnTasksRefreshed(
304 // index and use it for retrieving the process data. 245 const task_management::TaskIdList& task_ids) {
305 if (!model_->IsResourceFirstInGroup(start)) { 246 const bool has_on_updated_listeners =
306 index = model_->GetGroupIndexForResource(start); 247 HasEventListeners(api::processes::OnUpdated::kEventName);
307 } 248 const bool has_on_updated_with_memory_listeners =
308 249 HasEventListeners(api::processes::OnUpdatedWithMemory::kEventName);
309 scoped_ptr<base::ListValue> args(new base::ListValue()); 250
310 base::DictionaryValue* process = CreateProcessFromModel( 251 if (!has_on_updated_listeners && !has_on_updated_with_memory_listeners)
311 model_->GetUniqueChildProcessId(index), model_, index, false); 252 return;
312 DCHECK(process != NULL); 253
313 254 // Get the data of tasks sharing the same process only once.
314 if (process == NULL) 255 std::set<base::ProcessId> seen_processes;
315 return; 256 base::DictionaryValue processes_dictionary;
316 257 for (const auto& task_id : task_ids) {
317 args->Append(process); 258 // We are not interested in tasks, but rather the processes on which they
318 259 // run.
319 DispatchEvent(events::PROCESSES_ON_CREATED, keys::kOnCreated, 260 const base::ProcessId proc_id =
320 std::move(args)); 261 observed_task_manager()->GetProcessId(task_id);
321 #endif // defined(ENABLE_TASK_MANAGER) 262 if (seen_processes.count(proc_id))
322 } 263 continue;
323 264
324 void ProcessesEventRouter::OnItemsChanged(int start, int length) { 265 seen_processes.insert(proc_id);
325 #if defined(ENABLE_TASK_MANAGER) 266 const int child_process_host_id =
326 // If we don't have any listeners, return immediately. 267 observed_task_manager()->GetChildProcessUniqueID(task_id);
327 if (listeners_ == 0) 268 api::processes::Process process;
328 return; 269 FillProcessData(&process, task_id, observed_task_manager(), true);
329 270
330 if (!model_) 271 if (has_on_updated_with_memory_listeners) {
331 return; 272 // Append the private memory usage to the process data.
332 273 const int64_t private_memory =
333 // We need to know which type of onUpdated events to fire and whether to 274 observed_task_manager()->GetPrivateMemoryUsage(task_id);
334 // collect memory or not. 275 process.private_memory.reset(new double(static_cast<double>(
335 std::string updated_event(keys::kOnUpdated); 276 private_memory)));
336 std::string updated_event_memory(keys::kOnUpdatedWithMemory);
337 bool updated = HasEventListeners(updated_event);
338 bool updated_memory = HasEventListeners(updated_event_memory);
339
340 DCHECK(updated || updated_memory);
341
342 IDMap<base::DictionaryValue> processes_map;
343 for (int i = start; i < start + length; i++) {
344 if (model_->IsResourceFirstInGroup(i)) {
345 int id = model_->GetUniqueChildProcessId(i);
346 base::DictionaryValue* process = CreateProcessFromModel(id, model_, i,
347 true);
348 processes_map.AddWithID(process, i);
349 } 277 }
350 } 278
351 279 // Store each process indexed by the string version of its ChildProcessHost
352 int id; 280 // ID.
353 std::string idkey(keys::kIdKey); 281 processes_dictionary.Set(base::IntToString(child_process_host_id),
354 base::DictionaryValue* processes = new base::DictionaryValue(); 282 process.ToValue());
355 283 }
356 if (updated) { 284
357 IDMap<base::DictionaryValue>::iterator it(&processes_map); 285 // Done with data collection. Now dispatch the appropriate events according to
358 for (; !it.IsAtEnd(); it.Advance()) { 286 // the present listeners.
359 if (!it.GetCurrentValue()->GetInteger(idkey, &id)) 287 DCHECK(has_on_updated_listeners || has_on_updated_with_memory_listeners);
360 continue; 288 if (has_on_updated_listeners) {
361 289 api::processes::OnUpdated::Processes processes;
362 // Store each process indexed by the string version of its id. 290 processes.additional_properties.MergeDictionary(&processes_dictionary);
363 processes->Set(base::IntToString(id), it.GetCurrentValue()); 291 // NOTE: If there are listeners to the updates with memory as well,
364 } 292 // listeners to onUpdated (without memory) will also get the memory info
365 293 // of processes as an added bonus.
366 scoped_ptr<base::ListValue> args(new base::ListValue()); 294 DispatchEvent(events::PROCESSES_ON_UPDATED,
367 args->Append(processes); 295 api::processes::OnUpdated::kEventName,
368 DispatchEvent(events::PROCESSES_ON_UPDATED, keys::kOnUpdated, 296 api::processes::OnUpdated::Create(processes));
369 std::move(args)); 297 }
370 } 298
371 299 if (has_on_updated_with_memory_listeners) {
372 if (updated_memory) { 300 api::processes::OnUpdatedWithMemory::Processes processes;
373 IDMap<base::DictionaryValue>::iterator it(&processes_map); 301 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, 302 DispatchEvent(events::PROCESSES_ON_UPDATED_WITH_MEMORY,
389 keys::kOnUpdatedWithMemory, std::move(args)); 303 api::processes::OnUpdatedWithMemory::kEventName,
390 } 304 api::processes::OnUpdatedWithMemory::Create(processes));
391 #endif // defined(ENABLE_TASK_MANAGER) 305 }
392 } 306 }
393 307
394 void ProcessesEventRouter::OnItemsToBeRemoved(int start, int length) { 308 void ProcessesEventRouter::OnTaskUnresponsive(task_management::TaskId id) {
395 #if defined(ENABLE_TASK_MANAGER) 309 if (!HasEventListeners(api::processes::OnUnresponsive::kEventName))
396 DCHECK_EQ(length, 1); 310 return;
397 311
398 // Process exit for renderer processes has the data about exit code and 312 api::processes::Process process;
399 // termination status, therefore we will rely on notifications and not on 313 FillProcessData(&process, id, observed_task_manager(), false);
400 // the Task Manager data. We do use the rest of this method for non-renderer 314 DispatchEvent(events::PROCESSES_ON_UNRESPONSIVE,
401 // processes. 315 api::processes::OnUnresponsive::kEventName,
402 if (model_->GetResourceType(start) == task_manager::Resource::RENDERER) 316 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 } 317 }
471 318
472 void ProcessesEventRouter::DispatchEvent( 319 void ProcessesEventRouter::DispatchEvent(
473 events::HistogramValue histogram_value, 320 events::HistogramValue histogram_value,
474 const std::string& event_name, 321 const std::string& event_name,
475 scoped_ptr<base::ListValue> event_args) { 322 scoped_ptr<base::ListValue> event_args) const {
476 EventRouter* event_router = EventRouter::Get(browser_context_); 323 EventRouter* event_router = EventRouter::Get(browser_context_);
477 if (event_router) { 324 if (event_router) {
478 scoped_ptr<Event> event( 325 scoped_ptr<Event> event(
479 new Event(histogram_value, event_name, std::move(event_args))); 326 new Event(histogram_value, event_name, std::move(event_args)));
480 event_router->BroadcastEvent(std::move(event)); 327 event_router->BroadcastEvent(std::move(event));
481 } 328 }
482 } 329 }
483 330
484 bool ProcessesEventRouter::HasEventListeners(const std::string& event_name) { 331 bool ProcessesEventRouter::HasEventListeners(
332 const std::string& event_name) const {
485 EventRouter* event_router = EventRouter::Get(browser_context_); 333 EventRouter* event_router = EventRouter::Get(browser_context_);
486 return event_router && event_router->HasEventListener(event_name); 334 return event_router && event_router->HasEventListener(event_name);
487 } 335 }
488 336
337 ////////////////////////////////////////////////////////////////////////////////
338 // ProcessesAPI:
339 ////////////////////////////////////////////////////////////////////////////////
340
489 ProcessesAPI::ProcessesAPI(content::BrowserContext* context) 341 ProcessesAPI::ProcessesAPI(content::BrowserContext* context)
490 : browser_context_(context) { 342 : browser_context_(context) {
491 EventRouter* event_router = EventRouter::Get(browser_context_); 343 EventRouter* event_router = EventRouter::Get(browser_context_);
492 event_router->RegisterObserver(this, processes_api_constants::kOnUpdated); 344 // Monitor when the following events are being listened to in order to know
345 // when to start the task manager.
346 event_router->RegisterObserver(this, api::processes::OnUpdated::kEventName);
347 event_router->RegisterObserver(
348 this, api::processes::OnUpdatedWithMemory::kEventName);
349 event_router->RegisterObserver(this, api::processes::OnCreated::kEventName);
493 event_router->RegisterObserver(this, 350 event_router->RegisterObserver(this,
494 processes_api_constants::kOnUpdatedWithMemory); 351 api::processes::OnUnresponsive::kEventName);
495 ExtensionFunctionRegistry* registry = 352 event_router->RegisterObserver(this, api::processes::OnExited::kEventName);
496 ExtensionFunctionRegistry::GetInstance();
497 registry->RegisterFunction<GetProcessIdForTabFunction>();
498 registry->RegisterFunction<TerminateFunction>();
499 registry->RegisterFunction<GetProcessInfoFunction>();
500 } 353 }
501 354
502 ProcessesAPI::~ProcessesAPI() { 355 ProcessesAPI::~ProcessesAPI() {
503 } 356 // 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 } 357 }
517 358
518 // static 359 // static
519 ProcessesAPI* ProcessesAPI::Get(content::BrowserContext* context) { 360 ProcessesAPI* ProcessesAPI::Get(content::BrowserContext* context) {
520 return BrowserContextKeyedAPIFactory<ProcessesAPI>::Get(context); 361 return BrowserContextKeyedAPIFactory<ProcessesAPI>::Get(context);
521 } 362 }
522 363
523 ProcessesEventRouter* ProcessesAPI::processes_event_router() { 364 // static
524 if (!processes_event_router_) 365 BrowserContextKeyedAPIFactory<ProcessesAPI>*
525 processes_event_router_.reset(new ProcessesEventRouter(browser_context_)); 366 ProcessesAPI::GetFactoryInstance() {
526 return processes_event_router_.get(); 367 return g_processes_api_factory.Pointer();
368 }
369
370 void ProcessesAPI::Shutdown() {
371 EventRouter::Get(browser_context_)->UnregisterObserver(this);
527 } 372 }
528 373
529 void ProcessesAPI::OnListenerAdded(const EventListenerInfo& details) { 374 void ProcessesAPI::OnListenerAdded(const EventListenerInfo& details) {
530 // We lazily tell the TaskManager to start updating when listeners to the 375 // The ProcessesEventRouter will observe the TaskManager as long as there are
531 // processes.onUpdated or processes.onUpdatedWithMemory events arrive. 376 // listeners for the processes.onUpdated or processes.onUpdatedWithMemory
377 // events.
532 processes_event_router()->ListenerAdded(); 378 processes_event_router()->ListenerAdded();
533 } 379 }
534 380
535 void ProcessesAPI::OnListenerRemoved(const EventListenerInfo& details) { 381 void ProcessesAPI::OnListenerRemoved(const EventListenerInfo& details) {
536 // If a processes.onUpdated or processes.onUpdatedWithMemory event listener 382 // If a processes.onUpdated or processes.onUpdatedWithMemory event listener
537 // is removed (or a process with one exits), then we let the extension API 383 // is removed (or a process with one exits), then we let the extension API
538 // know that it has one fewer listener. 384 // know that it has one fewer listener.
539 processes_event_router()->ListenerRemoved(); 385 processes_event_router()->ListenerRemoved();
540 } 386 }
541 387
542 GetProcessIdForTabFunction::GetProcessIdForTabFunction() : tab_id_(-1) { 388 ProcessesEventRouter* ProcessesAPI::processes_event_router() {
543 } 389 if (!processes_event_router_.get())
544 390 processes_event_router_.reset(new ProcessesEventRouter(browser_context_));
545 bool GetProcessIdForTabFunction::RunAsync() { 391 return processes_event_router_.get();
546 #if defined(ENABLE_TASK_MANAGER) 392 }
547 EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &tab_id_)); 393
548 394 ////////////////////////////////////////////////////////////////////////////////
549 // Add a reference, which is balanced in GetProcessIdForTab to keep the object 395 // ProcessesTerminateFunction:
550 // around and allow for the callback to be invoked. 396 ////////////////////////////////////////////////////////////////////////////////
397
398 ExtensionFunction::ResponseAction ProcessesTerminateFunction::Run() {
399 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
400
401 // For this function, the task manager doesn't even need to be running.
402 scoped_ptr<api::processes::Terminate::Params> params(
403 api::processes::Terminate::Params::Create(*args_));
404 EXTENSION_FUNCTION_VALIDATE(params.get());
405
406 child_process_host_id_ = params->process_id;
407 if (child_process_host_id_ == 0) {
408 // Cannot kill the browser process.
409 return RespondNow(Error(errors::kNotAllowedToTerminate,
410 base::IntToString(child_process_host_id_)));
411 }
412
413 content::BrowserThread::PostTaskAndReplyWithResult(
414 content::BrowserThread::IO,
415 FROM_HERE,
416 base::Bind(&ProcessesTerminateFunction::GetProcessHandleIO,
417 this,
418 child_process_host_id_),
419 base::Bind(&ProcessesTerminateFunction::OnProcessHandleUI, this));
420
421 // Promise to respond later.
422 return RespondLater();
423 }
424
425 base::ProcessHandle ProcessesTerminateFunction::GetProcessHandleIO(
426 int child_process_host_id) const {
427 DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
428
429 auto* host = content::BrowserChildProcessHost::FromID(child_process_host_id);
430 if (host)
431 return host->GetData().handle;
432
433 return base::kNullProcessHandle;
434 }
435
436 void ProcessesTerminateFunction::OnProcessHandleUI(base::ProcessHandle handle) {
437 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
438
439 if (handle == base::kNullProcessHandle) {
440 // If we didn't get anything from BrowserChildProcessHost, then it could be
441 // a renderer.
442 auto* render_host =
443 content::RenderProcessHost::FromID(child_process_host_id_);
444 if (render_host)
445 handle = render_host->GetHandle();
446 }
447
448 if (handle == base::kNullProcessHandle) {
449 Respond(Error(errors::kProcessNotFound,
450 base::IntToString(child_process_host_id_)));
451 return;
452 }
453
454 if (handle == base::GetCurrentProcessHandle()) {
455 // Cannot kill the browser process.
456 Respond(Error(errors::kNotAllowedToTerminate,
457 base::IntToString(child_process_host_id_)));
458 return;
459 }
460
461 base::Process process = base::Process::Open(base::GetProcId(handle));
462 const bool did_terminate =
463 process.Terminate(content::RESULT_CODE_KILLED, true);
464 if (did_terminate)
465 UMA_HISTOGRAM_COUNTS("ChildProcess.KilledByExtensionAPI", 1);
466
467 Respond(ArgumentList(
468 api::processes::Terminate::Results::Create(did_terminate)));
469 }
470
471 ////////////////////////////////////////////////////////////////////////////////
472 // ProcessesGetProcessIdForTabFunction:
473 ////////////////////////////////////////////////////////////////////////////////
474
475 ExtensionFunction::ResponseAction ProcessesGetProcessIdForTabFunction::Run() {
476 // For this function, the task manager doesn't even need to be running.
477 scoped_ptr<api::processes::GetProcessIdForTab::Params> params(
478 api::processes::GetProcessIdForTab::Params::Create(*args_));
479 EXTENSION_FUNCTION_VALIDATE(params.get());
480
481 const int tab_id = params->tab_id;
482 content::WebContents* contents = nullptr;
483 int tab_index = -1;
484 if (!ExtensionTabUtil::GetTabById(
485 tab_id,
486 Profile::FromBrowserContext(browser_context()),
487 include_incognito(),
488 nullptr,
489 nullptr,
490 &contents,
491 &tab_index)) {
492 return RespondNow(Error(tabs_constants::kTabNotFoundError,
493 base::IntToString(tab_id)));
494 }
495
496 const int process_id = contents->GetRenderProcessHost()->GetID();
497 return RespondNow(ArgumentList(
498 api::processes::GetProcessIdForTab::Results::Create(process_id)));
499 }
500
501 ////////////////////////////////////////////////////////////////////////////////
502 // ProcessesGetProcessInfoFunction:
503 ////////////////////////////////////////////////////////////////////////////////
504
505 ProcessesGetProcessInfoFunction::ProcessesGetProcessInfoFunction()
506 : task_management::TaskManagerObserver(
507 base::TimeDelta::FromSeconds(1),
508 GetRefreshTypesFlagOnlyEssentialData()) {
509 }
510
511 ExtensionFunction::ResponseAction ProcessesGetProcessInfoFunction::Run() {
512 scoped_ptr<api::processes::GetProcessInfo::Params> params(
513 api::processes::GetProcessInfo::Params::Create(*args_));
514 EXTENSION_FUNCTION_VALIDATE(params.get());
515 if (params->process_ids.as_integer)
516 process_host_ids_.push_back(*params->process_ids.as_integer);
517 else
518 process_host_ids_.swap(*params->process_ids.as_integers);
519 include_memory_ = params->include_memory;
520
521 // Keep this object alive until the OnTasksRefreshed() is received.
551 AddRef(); 522 AddRef();
552 523
553 // If the task manager is already listening, just post a task to execute 524 // The task manager needs to be enabled for this function.
554 // which will invoke the callback once we have returned from this function. 525 // 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 526 task_management::TaskManagerInterface::GetTaskManager()->AddObserver(this);
556 // the data gathering. 527
557 if (ProcessesAPI::Get(GetProfile()) 528 return RespondLater();
558 ->processes_event_router() 529 }
559 ->is_task_manager_listening()) { 530
560 base::ThreadTaskRunnerHandle::Get()->PostTask( 531 void ProcessesGetProcessInfoFunction::OnTasksRefreshed(
561 FROM_HERE, 532 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 533 // If there are no process IDs specified, it means we need to return all of
736 // the ones we know of. 534 // the ones we know of.
737 if (process_ids_.size() == 0) { 535 const bool specific_processes_requested = !process_host_ids_.empty();
738 int resources = model->ResourceCount(); 536 std::set<base::ProcessId> seen_processes;
739 for (int i = 0; i < resources; ++i) { 537 // Create the results object as defined in the generated API from process.idl
740 if (model->IsResourceFirstInGroup(i)) { 538 // and fill it with the processes info.
741 int id = model->GetUniqueChildProcessId(i); 539 api::processes::GetProcessInfo::Results::Processes processes;
742 base::DictionaryValue* d = CreateProcessFromModel(id, model, i, false); 540 for (const auto& task_id : task_ids) {
743 if (memory_) 541 const base::ProcessId proc_id =
744 AddMemoryDetails(d, model, i); 542 observed_task_manager()->GetProcessId(task_id);
745 processes->Set(base::IntToString(id), d); 543 if (seen_processes.count(proc_id))
746 } 544 continue;
545
546 const int child_process_host_id =
547 observed_task_manager()->GetChildProcessUniqueID(task_id);
548
549 if (specific_processes_requested) {
550 // Note: we can't use |!process_host_ids_.empty()| directly in the above
551 // condition as we will erase from |process_host_ids_| below.
552 auto itr = std::find(process_host_ids_.begin(),
553 process_host_ids_.end(),
554 child_process_host_id);
555 if (itr == process_host_ids_.end())
556 continue;
557
558 // If found, we remove it from |process_host_ids|, so that at the end if
559 // anything remains in |process_host_ids|, those were invalid arguments
560 // that will be reported on the console.
561 process_host_ids_.erase(itr);
747 } 562 }
748 } else { 563
749 int resources = model->ResourceCount(); 564 seen_processes.insert(proc_id);
750 for (int i = 0; i < resources; ++i) { 565
751 if (model->IsResourceFirstInGroup(i)) { 566 // We do not include the optional data in this function results.
752 int id = model->GetUniqueChildProcessId(i); 567 api::processes::Process process;
753 std::vector<int>::iterator proc_id = std::find(process_ids_.begin(), 568 FillProcessData(&process, task_id, observed_task_manager(), false);
754 process_ids_.end(), id); 569
755 if (proc_id != process_ids_.end()) { 570 if (include_memory_) {
756 base::DictionaryValue* d = 571 // Append the private memory usage to the process data.
757 CreateProcessFromModel(id, model, i, false); 572 const int64_t private_memory =
758 if (memory_) 573 observed_task_manager()->GetPrivateMemoryUsage(task_id);
759 AddMemoryDetails(d, model, i); 574 process.private_memory.reset(new double(static_cast<double>(
760 processes->Set(base::IntToString(id), d); 575 private_memory)));
761
762 process_ids_.erase(proc_id);
763 if (process_ids_.size() == 0)
764 break;
765 }
766 }
767 } 576 }
768 // If not all processes were found, log them to the extension's console to 577
769 // help the developer, but don't fail the API call. 578 // Store each process indexed by the string version of its
770 for (int pid : process_ids_) { 579 // ChildProcessHost ID.
771 WriteToConsole(content::CONSOLE_MESSAGE_LEVEL_ERROR, 580 processes.additional_properties.Set(
772 ErrorUtils::FormatErrorMessage(errors::kProcessNotFound, 581 base::IntToString(child_process_host_id),
773 base::IntToString(pid))); 582 process.ToValue());
774 } 583 }
775 } 584
776 585 // Report the invalid host ids sent in the arguments.
777 SetResult(processes); 586 for (const auto& host_id : process_host_ids_) {
778 SendResponse(true); 587 WriteToConsole(content::CONSOLE_MESSAGE_LEVEL_ERROR,
779 588 ErrorUtils::FormatErrorMessage(errors::kProcessNotFound,
780 // Balance the AddRef in the RunAsync. 589 base::IntToString(host_id)));
590 }
591
592 // Send the response.
593 Respond(ArgumentList(
594 api::processes::GetProcessInfo::Results::Create(processes)));
595
596 // Stop observing the task manager, and balance the AddRef() in Run().
597 task_management::TaskManagerInterface::GetTaskManager()->RemoveObserver(this);
781 Release(); 598 Release();
782 #endif // defined(ENABLE_TASK_MANAGER) 599 }
783 } 600
601 ProcessesGetProcessInfoFunction::~ProcessesGetProcessInfoFunction() {}
784 602
785 } // namespace extensions 603 } // namespace extensions
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698