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

Side by Side Diff: chrome/browser/chromeos/arc/arc_process_service.cc

Issue 2025593003: Show all system process in the task_manager. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Remove redundant check. Created 4 years, 3 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 2016 The Chromium Authors. All rights reserved. 1 // Copyright 2016 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 // The main point of this class is to cache ARC proc nspid<->pid mapping 5 // The main point of this class is to cache ARC proc nspid<->pid mapping
6 // globally. Since the calculation is costly, a dedicated worker thread is 6 // globally. Since the calculation is costly, a dedicated worker thread is
7 // used. All read/write of its internal data structure (i.e., the mapping) 7 // used. All read/write of its internal data structure (i.e., the mapping)
8 // should be on this thread. 8 // should be on this thread.
9 9
10 #include "chrome/browser/chromeos/arc/arc_process_service.h" 10 #include "chrome/browser/chromeos/arc/arc_process_service.h"
11 11
12 #include <algorithm>
12 #include <queue> 13 #include <queue>
13 #include <set>
14 #include <string> 14 #include <string>
15 #include <unordered_map>
16 #include <unordered_set>
17 #include <utility>
15 18
19 #include "base/callback.h"
20 #include "base/logging.h"
16 #include "base/process/process.h" 21 #include "base/process/process.h"
17 #include "base/process/process_iterator.h" 22 #include "base/process/process_iterator.h"
18 #include "base/task_runner_util.h" 23 #include "base/task_runner_util.h"
19 #include "base/trace_event/trace_event.h" 24 #include "base/trace_event/trace_event.h"
20 #include "content/public/browser/browser_thread.h" 25 #include "content/public/browser/browser_thread.h"
21 26
22 namespace arc { 27 namespace arc {
23 28
24 namespace {
25
26 const char kSequenceToken[] = "arc_process_service";
27
28 // Weak pointer. This class is owned by ArcServiceManager.
29 ArcProcessService* g_arc_process_service = nullptr;
30
31 } // namespace
32
33 using base::kNullProcessId; 29 using base::kNullProcessId;
34 using base::Process; 30 using base::Process;
35 using base::ProcessId; 31 using base::ProcessId;
36 using base::SequencedWorkerPool; 32 using base::SequencedWorkerPool;
37 using std::map;
38 using std::set;
39 using std::vector; 33 using std::vector;
40 34
35 namespace {
36
37 // Weak pointer. This class is owned by ArcServiceManager.
38 ArcProcessService* g_arc_process_service = nullptr;
39 static constexpr char kInitName[] = "/init";
40 static constexpr bool kNotFocused = false;
41 static constexpr int64_t kNoActivityTimeInfo = 0L;
42
43 // Matches the process name "/init" in the process tree and get the
44 // corresponding process ID.
45 base::ProcessId GetArcInitProcessId(
46 const base::ProcessIterator::ProcessEntries& entry_list) {
47 for (const base::ProcessEntry& entry : entry_list) {
48 if (entry.cmd_line_args().empty()) {
49 continue;
50 }
51 // TODO(nya): Add more constraints to avoid mismatches.
52 const std::string& process_name = entry.cmd_line_args()[0];
53 if (process_name == kInitName) {
54 return entry.pid();
55 }
56 }
57 return base::kNullProcessId;
58 }
59
60 std::vector<arc::ArcProcess> GetArcSystemProcessList() {
61 std::vector<arc::ArcProcess> ret_processes;
62 const base::ProcessIterator::ProcessEntries& entry_list =
63 base::ProcessIterator(nullptr).Snapshot();
64 const base::ProcessId arc_init_pid = GetArcInitProcessId(entry_list);
65
66 if (arc_init_pid == base::kNullProcessId) {
67 return ret_processes;
68 }
69
70 // Enumerate the child processes of ARC init for gathering ARC System
71 // Processes.
72 for (const base::ProcessEntry& entry : entry_list) {
73 if (entry.cmd_line_args().empty()) {
74 continue;
75 }
76 // TODO(hctsai): For now, we only gather direct child process of init, need
77 // to get the processes below. For example, installd might fork dex2oat and
78 // it can be executed for minutes.
79 if (entry.parent_pid() == arc_init_pid) {
80 const base::ProcessId child_pid = entry.pid();
81 const base::ProcessId child_nspid =
82 base::Process(child_pid).GetPidInNamespace();
83 if (child_nspid != base::kNullProcessId) {
84 const std::string& process_name = entry.cmd_line_args()[0];
85 // The is_focused and last_activity_time is not needed thus mocked
86 ret_processes.emplace_back(child_nspid, child_pid, process_name,
87 mojom::ProcessState::PERSISTENT, kNotFocused,
88 kNoActivityTimeInfo);
89 }
90 }
91 }
92 return ret_processes;
93 }
94
95 void UpdateNspidToPidMap(
96 scoped_refptr<ArcProcessService::NSPidToPidMap> pid_map) {
97 TRACE_EVENT0("browser", "ArcProcessService::UpdateNspidToPidMap");
98
99 // NB: Despite of its name, ProcessIterator::Snapshot() may return
100 // inconsistent information because it simply walks procfs. Especially
101 // we must not assume the parent-child relationships are consistent.
102 const base::ProcessIterator::ProcessEntries& entry_list =
103 base::ProcessIterator(nullptr).Snapshot();
104
105 // Construct the process tree.
106 // NB: This can contain a loop in case of race conditions.
107 std::unordered_map<ProcessId, std::vector<ProcessId>> process_tree;
108 for (const base::ProcessEntry& entry : entry_list)
109 process_tree[entry.parent_pid()].push_back(entry.pid());
110
111 ProcessId arc_init_pid = GetArcInitProcessId(entry_list);
112
113 // Enumerate all processes under ARC init and create nspid -> pid map.
114 if (arc_init_pid != kNullProcessId) {
115 std::queue<ProcessId> queue;
116 std::unordered_set<ProcessId> visited;
117 queue.push(arc_init_pid);
118 while (!queue.empty()) {
119 ProcessId pid = queue.front();
120 queue.pop();
121 // Do not visit the same process twice. Otherwise we may enter an infinite
122 // loop if |process_tree| contains a loop.
123 if (!visited.insert(pid).second)
124 continue;
125
126 const ProcessId nspid = base::Process(pid).GetPidInNamespace();
127
128 // All ARC processes should be in namespace so nspid is usually non-null,
129 // but this can happen if the process has already gone.
130 // Only add processes we're interested in (those appear as keys in
131 // |pid_map|).
132 if (nspid != kNullProcessId && pid_map->find(nspid) != pid_map->end())
133 (*pid_map)[nspid] = pid;
134
135 for (ProcessId child_pid : process_tree[pid])
136 queue.push(child_pid);
137 }
138 }
139 }
140
141 std::vector<ArcProcess> FilterProcessList(
142 const ArcProcessService::NSPidToPidMap& pid_map,
143 mojo::Array<arc::mojom::RunningAppProcessInfoPtr> processes) {
144 std::vector<ArcProcess> ret_processes;
145 for (const auto& entry : processes) {
146 const auto it = pid_map.find(entry->pid);
147 // The nspid could be missing due to race condition. For example, the
148 // process is still running when we get the process snapshot and ends when
149 // we update the nspid to pid mapping.
150 if (it == pid_map.end() || it->second == base::kNullProcessId) {
151 continue;
152 }
153 // Constructs the ArcProcess instance if the mapping is found.
154 ArcProcess arc_process(entry->pid, pid_map.at(entry->pid),
155 entry->process_name, entry->process_state,
156 entry->is_focused, entry->last_activity_time);
157 // |entry->packages| is provided only when process.mojom's verion is >=4.
158 if (entry->packages) {
159 for (const auto& package : entry->packages) {
160 arc_process.packages().push_back(package.get());
161 }
162 }
163 ret_processes.push_back(std::move(arc_process));
164 }
165 return ret_processes;
166 }
167
168 std::vector<ArcProcess> UpdateAndReturnProcessList(
169 scoped_refptr<ArcProcessService::NSPidToPidMap> nspid_map,
170 mojo::Array<arc::mojom::RunningAppProcessInfoPtr> processes) {
171 ArcProcessService::NSPidToPidMap& pid_map = *nspid_map;
172 // Cleanup dead pids in the cache |pid_map|.
173 std::unordered_set<ProcessId> nspid_to_remove;
174 for (const auto& entry : pid_map) {
175 nspid_to_remove.insert(entry.first);
176 }
177 bool unmapped_nspid = false;
178 for (const auto& entry : processes) {
179 // erase() returns 0 if coudln't find the key. It means a new process.
180 if (nspid_to_remove.erase(entry->pid) == 0) {
181 pid_map[entry->pid] = base::kNullProcessId;
182 unmapped_nspid = true;
183 }
184 }
185 for (const auto& entry : nspid_to_remove) {
186 pid_map.erase(entry);
187 }
188
189 // The operation is costly so avoid calling it when possible.
190 if (unmapped_nspid) {
191 UpdateNspidToPidMap(nspid_map);
192 }
193
194 return FilterProcessList(pid_map, std::move(processes));
195 }
196
197 void Reset(scoped_refptr<ArcProcessService::NSPidToPidMap> pid_map) {
198 if (pid_map.get())
199 pid_map->clear();
200 }
201
202 } // namespace
203
41 ArcProcessService::ArcProcessService(ArcBridgeService* bridge_service) 204 ArcProcessService::ArcProcessService(ArcBridgeService* bridge_service)
42 : ArcService(bridge_service), 205 : ArcService(bridge_service),
43 worker_pool_(new SequencedWorkerPool(1, 206 heavy_task_thread_("ArcProcessServiceThread"),
44 "arc_process_manager", 207 nspid_to_pid_(new NSPidToPidMap()),
45 base::TaskPriority::USER_VISIBLE)),
46 weak_ptr_factory_(this) { 208 weak_ptr_factory_(this) {
47 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); 209 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
48 arc_bridge_service()->process()->AddObserver(this); 210 arc_bridge_service()->process()->AddObserver(this);
49 DCHECK(!g_arc_process_service); 211 DCHECK(!g_arc_process_service);
50 g_arc_process_service = this; 212 g_arc_process_service = this;
51 // Not intended to be used from the creating thread. 213 heavy_task_thread_.Start();
52 thread_checker_.DetachFromThread();
53 } 214 }
54 215
55 ArcProcessService::~ArcProcessService() { 216 ArcProcessService::~ArcProcessService() {
56 DCHECK(g_arc_process_service == this); 217 DCHECK(g_arc_process_service == this);
218 heavy_task_thread_.Stop();
57 g_arc_process_service = nullptr; 219 g_arc_process_service = nullptr;
58 arc_bridge_service()->process()->RemoveObserver(this); 220 arc_bridge_service()->process()->RemoveObserver(this);
59 worker_pool_->Shutdown();
60 } 221 }
61 222
62 // static 223 // static
63 ArcProcessService* ArcProcessService::Get() { 224 ArcProcessService* ArcProcessService::Get() {
64 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); 225 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
65 return g_arc_process_service; 226 return g_arc_process_service;
66 } 227 }
67 228
68 void ArcProcessService::OnInstanceReady() { 229 void ArcProcessService::OnInstanceReady() {
69 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); 230 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
70 worker_pool_->PostNamedSequencedWorkerTask( 231 GetTaskRunner()->PostTask(FROM_HERE, base::Bind(&Reset, nspid_to_pid_));
71 kSequenceToken,
72 FROM_HERE,
73 base::Bind(&ArcProcessService::Reset,
74 weak_ptr_factory_.GetWeakPtr()));
75 } 232 }
76 233
77 void ArcProcessService::Reset() { 234 void ArcProcessService::RequestSystemProcessList(
78 DCHECK(thread_checker_.CalledOnValidThread());
79 nspid_to_pid_.clear();
80 }
81
82 bool ArcProcessService::RequestProcessList(
83 RequestProcessListCallback callback) { 235 RequestProcessListCallback callback) {
84 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); 236 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
85 237
238 base::PostTaskAndReplyWithResult(GetTaskRunner().get(), FROM_HERE,
239 base::Bind(&GetArcSystemProcessList),
240 callback);
241 }
242
243 bool ArcProcessService::RequestAppProcessList(
244 RequestProcessListCallback callback) {
245 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
246
86 arc::mojom::ProcessInstance* process_instance = 247 arc::mojom::ProcessInstance* process_instance =
87 arc_bridge_service()->process()->instance(); 248 arc_bridge_service()->process()->instance();
88 if (!process_instance) { 249 if (!process_instance) {
89 return false; 250 return false;
90 } 251 }
91 process_instance->RequestProcessList( 252 process_instance->RequestProcessList(
92 base::Bind(&ArcProcessService::OnReceiveProcessList, 253 base::Bind(&ArcProcessService::OnReceiveProcessList,
93 weak_ptr_factory_.GetWeakPtr(), 254 weak_ptr_factory_.GetWeakPtr(), callback));
94 callback));
95 return true; 255 return true;
96 } 256 }
97 257
98 void ArcProcessService::OnReceiveProcessList( 258 void ArcProcessService::OnReceiveProcessList(
99 const RequestProcessListCallback& callback, 259 const RequestProcessListCallback& callback,
100 mojo::Array<arc::mojom::RunningAppProcessInfoPtr> mojo_processes) { 260 mojo::Array<arc::mojom::RunningAppProcessInfoPtr> instance_processes) {
101 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); 261 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
102 262
103 auto* raw_processes = new vector<mojom::RunningAppProcessInfoPtr>(); 263 base::PostTaskAndReplyWithResult(
104 mojo_processes.Swap(raw_processes); 264 GetTaskRunner().get(), FROM_HERE,
105 265 base::Bind(&UpdateAndReturnProcessList, nspid_to_pid_,
106 auto* ret_processes = new vector<ArcProcess>(); 266 base::Passed(&instance_processes)),
107 // Post to its dedicated worker thread to avoid race condition. 267 callback);
108 // Since no two tasks with the same token should be run at the same.
109 // Note: GetSequencedTaskRunner's shutdown behavior defaults to
110 // SKIP_ON_SHUTDOWN (ongoing task blocks shutdown).
111 // So in theory using Unretained(this) should be fine since the life cycle
112 // of |this| is the same as the main browser.
113 // To be safe I still use weak pointers, but weak_ptrs can only bind to
114 // methods without return values. That's why I can't use
115 // PostTaskAndReplyWithResult but handle the return object by myself.
116 auto runner = worker_pool_->GetSequencedTaskRunner(
117 worker_pool_->GetNamedSequenceToken(kSequenceToken));
118 runner->PostTaskAndReply(
119 FROM_HERE,
120 base::Bind(&ArcProcessService::UpdateAndReturnProcessList,
121 weak_ptr_factory_.GetWeakPtr(),
122 base::Owned(raw_processes),
123 base::Unretained(ret_processes)),
124 base::Bind(&ArcProcessService::CallbackRelay,
125 weak_ptr_factory_.GetWeakPtr(),
126 callback,
127 base::Owned(ret_processes)));
128 } 268 }
129 269
130 void ArcProcessService::CallbackRelay( 270 scoped_refptr<base::SingleThreadTaskRunner> ArcProcessService::GetTaskRunner() {
131 const RequestProcessListCallback& callback, 271 return heavy_task_thread_.task_runner();
132 const vector<ArcProcess>* ret_processes) {
133 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
134 callback.Run(*ret_processes);
135 } 272 }
136 273
137 void ArcProcessService::UpdateAndReturnProcessList( 274 inline ArcProcessService::NSPidToPidMap::NSPidToPidMap() {}
138 const vector<arc::mojom::RunningAppProcessInfoPtr>* raw_processes,
139 vector<ArcProcess>* ret_processes) {
140 DCHECK(thread_checker_.CalledOnValidThread());
141 275
142 // Cleanup dead pids in the cache |nspid_to_pid_|. 276 inline ArcProcessService::NSPidToPidMap::~NSPidToPidMap() {}
143 set<ProcessId> nspid_to_remove;
144 for (const auto& entry : nspid_to_pid_) {
145 nspid_to_remove.insert(entry.first);
146 }
147 bool unmapped_nspid = false;
148 for (const auto& entry : *raw_processes) {
149 // erase() returns 0 if coudln't find the key. It means a new process.
150 if (nspid_to_remove.erase(entry->pid) == 0) {
151 nspid_to_pid_[entry->pid] = kNullProcessId;
152 unmapped_nspid = true;
153 }
154 }
155 for (const auto& entry : nspid_to_remove) {
156 nspid_to_pid_.erase(entry);
157 }
158
159 // The operation is costly so avoid calling it when possible.
160 if (unmapped_nspid) {
161 UpdateNspidToPidMap();
162 }
163
164 PopulateProcessList(raw_processes, ret_processes);
165 }
166
167 void ArcProcessService::PopulateProcessList(
168 const vector<arc::mojom::RunningAppProcessInfoPtr>* raw_processes,
169 vector<ArcProcess>* ret_processes) {
170 DCHECK(thread_checker_.CalledOnValidThread());
171
172 for (const auto& entry : *raw_processes) {
173 const auto it = nspid_to_pid_.find(entry->pid);
174 // In case the process already dies so couldn't find corresponding pid.
175 if (it != nspid_to_pid_.end() && it->second != kNullProcessId) {
176 ArcProcess arc_process(entry->pid, it->second, entry->process_name,
177 entry->process_state, entry->is_focused,
178 entry->last_activity_time);
179 // |entry->packages| is provided only when process.mojom's verion is >=4.
180 if (entry->packages) {
181 for (const auto& package : entry->packages) {
182 arc_process.packages().push_back(package.get());
183 }
184 }
185 ret_processes->push_back(std::move(arc_process));
186 }
187 }
188 }
189
190 // Computes a map from PID in ARC namespace to PID in system namespace.
191 // The returned map contains ARC processes only.
192 void ArcProcessService::UpdateNspidToPidMap() {
193 DCHECK(thread_checker_.CalledOnValidThread());
194
195 TRACE_EVENT0("browser", "ArcProcessService::UpdateNspidToPidMap");
196
197 // NB: Despite of its name, ProcessIterator::Snapshot() may return
198 // inconsistent information because it simply walks procfs. Especially
199 // we must not assume the parent-child relationships are consistent.
200 const base::ProcessIterator::ProcessEntries& entry_list =
201 base::ProcessIterator(nullptr).Snapshot();
202
203 // System may contain many different namespaces so several different
204 // processes may have the same nspid. We need to get the proper subset of
205 // processes to create correct nspid -> pid map.
206
207 // Construct the process tree.
208 // NB: This can contain a loop in case of race conditions.
209 map<ProcessId, vector<ProcessId> > process_tree;
210 for (const base::ProcessEntry& entry : entry_list)
211 process_tree[entry.parent_pid()].push_back(entry.pid());
212
213 // Find the ARC init process.
214 ProcessId arc_init_pid = kNullProcessId;
215 for (const base::ProcessEntry& entry : entry_list) {
216 // TODO(nya): Add more constraints to avoid mismatches.
217 std::string process_name =
218 !entry.cmd_line_args().empty() ? entry.cmd_line_args()[0] : "";
219 if (process_name == "/init") {
220 arc_init_pid = entry.pid();
221 break;
222 }
223 }
224
225 // Enumerate all processes under ARC init and create nspid -> pid map.
226 if (arc_init_pid != kNullProcessId) {
227 std::queue<ProcessId> queue;
228 std::set<ProcessId> visited;
229 queue.push(arc_init_pid);
230 while (!queue.empty()) {
231 ProcessId pid = queue.front();
232 queue.pop();
233 // Do not visit the same process twice. Otherwise we may enter an infinite
234 // loop if |process_tree| contains a loop.
235 if (!visited.insert(pid).second)
236 continue;
237
238 ProcessId nspid = base::Process(pid).GetPidInNamespace();
239
240 // All ARC processes should be in namespace so nspid is usually non-null,
241 // but this can happen if the process has already gone.
242 // Only add processes we're interested in (those appear as keys in
243 // |nspid_to_pid_|).
244 if (nspid != kNullProcessId &&
245 nspid_to_pid_.find(nspid) != nspid_to_pid_.end())
246 nspid_to_pid_[nspid] = pid;
247
248 for (ProcessId child_pid : process_tree[pid])
249 queue.push(child_pid);
250 }
251 }
252 }
253 277
254 } // namespace arc 278 } // namespace arc
OLDNEW
« no previous file with comments | « chrome/browser/chromeos/arc/arc_process_service.h ('k') | chrome/browser/memory/tab_manager_delegate_chromeos.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698