OLD | NEW |
---|---|
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 if (!nspid_map.get()) { | |
172 return {}; | |
173 } | |
174 ArcProcessService::NSPidToPidMap& pid_map = *nspid_map; | |
175 // Cleanup dead pids in the cache |pid_map|. | |
176 std::unordered_set<ProcessId> nspid_to_remove; | |
177 for (const auto& entry : pid_map) { | |
178 nspid_to_remove.insert(entry.first); | |
179 } | |
180 bool unmapped_nspid = false; | |
181 for (const auto& entry : processes) { | |
182 // erase() returns 0 if coudln't find the key. It means a new process. | |
183 if (nspid_to_remove.erase(entry->pid) == 0) { | |
184 pid_map[entry->pid] = base::kNullProcessId; | |
185 unmapped_nspid = true; | |
186 } | |
187 } | |
188 for (const auto& entry : nspid_to_remove) { | |
189 pid_map.erase(entry); | |
190 } | |
191 | |
192 // The operation is costly so avoid calling it when possible. | |
193 if (unmapped_nspid) { | |
194 UpdateNspidToPidMap(nspid_map); | |
195 } | |
196 | |
197 return FilterProcessList(pid_map, std::move(processes)); | |
198 } | |
199 | |
200 void Reset(scoped_refptr<ArcProcessService::NSPidToPidMap> pid_map) { | |
201 if (pid_map.get()) | |
202 pid_map->clear(); | |
203 } | |
204 | |
205 } // namespace | |
206 | |
41 ArcProcessService::ArcProcessService(ArcBridgeService* bridge_service) | 207 ArcProcessService::ArcProcessService(ArcBridgeService* bridge_service) |
42 : ArcService(bridge_service), | 208 : ArcService(bridge_service), |
43 worker_pool_(new SequencedWorkerPool(1, | 209 heavy_task_thread_("ArcProcessServiceThread"), |
44 "arc_process_manager", | 210 nspid_to_pid_(new NSPidToPidMap), |
Luis Héctor Chávez
2016/08/25 16:53:21
ping: new NSPidtoPidMap().
Hsu-Cheng
2016/08/26 07:55:47
Done.
| |
45 base::TaskPriority::USER_VISIBLE)), | |
46 weak_ptr_factory_(this) { | 211 weak_ptr_factory_(this) { |
47 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | 212 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); |
48 arc_bridge_service()->process()->AddObserver(this); | 213 arc_bridge_service()->process()->AddObserver(this); |
49 DCHECK(!g_arc_process_service); | 214 DCHECK(!g_arc_process_service); |
50 g_arc_process_service = this; | 215 g_arc_process_service = this; |
51 // Not intended to be used from the creating thread. | 216 heavy_task_thread_.Start(); |
52 thread_checker_.DetachFromThread(); | |
53 } | 217 } |
54 | 218 |
55 ArcProcessService::~ArcProcessService() { | 219 ArcProcessService::~ArcProcessService() { |
56 DCHECK(g_arc_process_service == this); | 220 DCHECK(g_arc_process_service == this); |
221 heavy_task_thread_.Stop(); | |
57 g_arc_process_service = nullptr; | 222 g_arc_process_service = nullptr; |
58 arc_bridge_service()->process()->RemoveObserver(this); | 223 arc_bridge_service()->process()->RemoveObserver(this); |
59 worker_pool_->Shutdown(); | |
60 } | 224 } |
61 | 225 |
62 // static | 226 // static |
63 ArcProcessService* ArcProcessService::Get() { | 227 ArcProcessService* ArcProcessService::Get() { |
64 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | 228 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); |
65 return g_arc_process_service; | 229 return g_arc_process_service; |
66 } | 230 } |
67 | 231 |
68 void ArcProcessService::OnInstanceReady() { | 232 void ArcProcessService::OnInstanceReady() { |
69 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | 233 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); |
70 worker_pool_->PostNamedSequencedWorkerTask( | 234 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 } | 235 } |
76 | 236 |
77 void ArcProcessService::Reset() { | 237 void ArcProcessService::RequestSystemProcessList( |
78 DCHECK(thread_checker_.CalledOnValidThread()); | |
79 nspid_to_pid_.clear(); | |
80 } | |
81 | |
82 bool ArcProcessService::RequestProcessList( | |
83 RequestProcessListCallback callback) { | 238 RequestProcessListCallback callback) { |
84 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | 239 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); |
85 | 240 |
241 base::PostTaskAndReplyWithResult(GetTaskRunner().get(), FROM_HERE, | |
242 base::Bind(&GetArcSystemProcessList), | |
243 callback); | |
244 } | |
245 | |
246 bool ArcProcessService::RequestAppProcessList( | |
247 RequestProcessListCallback callback) { | |
248 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | |
249 | |
86 arc::mojom::ProcessInstance* process_instance = | 250 arc::mojom::ProcessInstance* process_instance = |
87 arc_bridge_service()->process()->instance(); | 251 arc_bridge_service()->process()->instance(); |
88 if (!process_instance) { | 252 if (!process_instance) { |
89 return false; | 253 return false; |
90 } | 254 } |
91 process_instance->RequestProcessList( | 255 process_instance->RequestProcessList( |
92 base::Bind(&ArcProcessService::OnReceiveProcessList, | 256 base::Bind(&ArcProcessService::OnReceiveProcessList, |
93 weak_ptr_factory_.GetWeakPtr(), | 257 weak_ptr_factory_.GetWeakPtr(), callback)); |
94 callback)); | |
95 return true; | 258 return true; |
96 } | 259 } |
97 | 260 |
98 void ArcProcessService::OnReceiveProcessList( | 261 void ArcProcessService::OnReceiveProcessList( |
99 const RequestProcessListCallback& callback, | 262 const RequestProcessListCallback& callback, |
100 mojo::Array<arc::mojom::RunningAppProcessInfoPtr> mojo_processes) { | 263 mojo::Array<arc::mojom::RunningAppProcessInfoPtr> instance_processes) { |
101 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | 264 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); |
102 | 265 |
103 auto* raw_processes = new vector<mojom::RunningAppProcessInfoPtr>(); | 266 base::PostTaskAndReplyWithResult( |
104 mojo_processes.Swap(raw_processes); | 267 GetTaskRunner().get(), FROM_HERE, |
105 | 268 base::Bind(&UpdateAndReturnProcessList, nspid_to_pid_, |
106 auto* ret_processes = new vector<ArcProcess>(); | 269 base::Passed(&instance_processes)), |
107 // Post to its dedicated worker thread to avoid race condition. | 270 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 } | 271 } |
129 | 272 |
130 void ArcProcessService::CallbackRelay( | 273 scoped_refptr<base::SingleThreadTaskRunner> ArcProcessService::GetTaskRunner() { |
131 const RequestProcessListCallback& callback, | 274 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 } | 275 } |
136 | 276 |
137 void ArcProcessService::UpdateAndReturnProcessList( | 277 ArcProcessService::NSPidToPidMap::NSPidToPidMap() {} |
Luis Héctor Chávez
2016/08/25 16:53:21
ping: NSPidToPidMap() = default; same below.
Hsu-Cheng
2016/08/26 07:55:47
Done.
| |
138 const vector<arc::mojom::RunningAppProcessInfoPtr>* raw_processes, | |
139 vector<ArcProcess>* ret_processes) { | |
140 DCHECK(thread_checker_.CalledOnValidThread()); | |
141 | 278 |
142 // Cleanup dead pids in the cache |nspid_to_pid_|. | 279 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 | 280 |
254 } // namespace arc | 281 } // namespace arc |
OLD | NEW |