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 |
41 ArcProcessService::ArcProcessService(ArcBridgeService* bridge_service) | 35 namespace { |
42 : ArcService(bridge_service), | 36 |
43 worker_pool_(new SequencedWorkerPool(1, | 37 // Weak pointer. This class is owned by ArcServiceManager. |
44 "arc_process_manager", | 38 ArcProcessService* g_arc_process_service = nullptr; |
45 base::TaskPriority::USER_VISIBLE)), | 39 static constexpr char kInitName[] = "/init"; |
46 weak_ptr_factory_(this) { | 40 static constexpr bool kNotFocused = false; |
47 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | 41 static constexpr int64_t kNoActivityTimeInfo = 0L; |
48 arc_bridge_service()->process()->AddObserver(this); | 42 |
49 DCHECK(!g_arc_process_service); | 43 // Matches the process name "/init" in the process tree and get the |
50 g_arc_process_service = this; | 44 // corresponding process ID. |
51 // Not intended to be used from the creating thread. | 45 base::ProcessId GetArcInitProcessId( |
52 thread_checker_.DetachFromThread(); | 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; |
53 } | 58 } |
54 | 59 |
55 ArcProcessService::~ArcProcessService() { | 60 std::vector<arc::ArcProcess> GetArcSystemProcessList() { |
56 DCHECK(g_arc_process_service == this); | 61 std::vector<arc::ArcProcess> ret_processes; |
57 g_arc_process_service = nullptr; | 62 const base::ProcessIterator::ProcessEntries& entry_list = |
58 arc_bridge_service()->process()->RemoveObserver(this); | 63 base::ProcessIterator(nullptr).Snapshot(); |
59 worker_pool_->Shutdown(); | 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; |
60 } | 93 } |
61 | 94 |
62 // static | 95 void UpdateNspidToPidMap( |
63 ArcProcessService* ArcProcessService::Get() { | 96 scoped_refptr<ArcProcessService::NSPidToPidMap> pid_map) { |
64 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | |
65 return g_arc_process_service; | |
66 } | |
67 | |
68 void ArcProcessService::OnInstanceReady() { | |
69 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | |
70 worker_pool_->PostNamedSequencedWorkerTask( | |
71 kSequenceToken, | |
72 FROM_HERE, | |
73 base::Bind(&ArcProcessService::Reset, | |
74 weak_ptr_factory_.GetWeakPtr())); | |
75 } | |
76 | |
77 void ArcProcessService::Reset() { | |
78 DCHECK(thread_checker_.CalledOnValidThread()); | |
79 nspid_to_pid_.clear(); | |
80 } | |
81 | |
82 bool ArcProcessService::RequestProcessList( | |
83 RequestProcessListCallback callback) { | |
84 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | |
85 | |
86 arc::mojom::ProcessInstance* process_instance = | |
87 arc_bridge_service()->process()->instance(); | |
88 if (!process_instance) { | |
89 return false; | |
90 } | |
91 process_instance->RequestProcessList( | |
92 base::Bind(&ArcProcessService::OnReceiveProcessList, | |
93 weak_ptr_factory_.GetWeakPtr(), | |
94 callback)); | |
95 return true; | |
96 } | |
97 | |
98 void ArcProcessService::OnReceiveProcessList( | |
99 const RequestProcessListCallback& callback, | |
100 mojo::Array<arc::mojom::RunningAppProcessInfoPtr> mojo_processes) { | |
101 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | |
102 | |
103 auto* raw_processes = new vector<mojom::RunningAppProcessInfoPtr>(); | |
104 mojo_processes.Swap(raw_processes); | |
105 | |
106 auto* ret_processes = new vector<ArcProcess>(); | |
107 // Post to its dedicated worker thread to avoid race condition. | |
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 } | |
129 | |
130 void ArcProcessService::CallbackRelay( | |
131 const RequestProcessListCallback& callback, | |
132 const vector<ArcProcess>* ret_processes) { | |
133 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); | |
134 callback.Run(*ret_processes); | |
135 } | |
136 | |
137 void ArcProcessService::UpdateAndReturnProcessList( | |
138 const vector<arc::mojom::RunningAppProcessInfoPtr>* raw_processes, | |
139 vector<ArcProcess>* ret_processes) { | |
140 DCHECK(thread_checker_.CalledOnValidThread()); | |
141 | |
142 // Cleanup dead pids in the cache |nspid_to_pid_|. | |
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"); | 97 TRACE_EVENT0("browser", "ArcProcessService::UpdateNspidToPidMap"); |
196 | 98 |
197 // NB: Despite of its name, ProcessIterator::Snapshot() may return | 99 // NB: Despite of its name, ProcessIterator::Snapshot() may return |
198 // inconsistent information because it simply walks procfs. Especially | 100 // inconsistent information because it simply walks procfs. Especially |
199 // we must not assume the parent-child relationships are consistent. | 101 // we must not assume the parent-child relationships are consistent. |
200 const base::ProcessIterator::ProcessEntries& entry_list = | 102 const base::ProcessIterator::ProcessEntries& entry_list = |
201 base::ProcessIterator(nullptr).Snapshot(); | 103 base::ProcessIterator(nullptr).Snapshot(); |
202 | 104 |
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. | 105 // Construct the process tree. |
208 // NB: This can contain a loop in case of race conditions. | 106 // NB: This can contain a loop in case of race conditions. |
209 map<ProcessId, vector<ProcessId> > process_tree; | 107 std::unordered_map<ProcessId, std::vector<ProcessId>> process_tree; |
210 for (const base::ProcessEntry& entry : entry_list) | 108 for (const base::ProcessEntry& entry : entry_list) |
211 process_tree[entry.parent_pid()].push_back(entry.pid()); | 109 process_tree[entry.parent_pid()].push_back(entry.pid()); |
212 | 110 |
213 // Find the ARC init process. | 111 ProcessId arc_init_pid = GetArcInitProcessId(entry_list); |
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 | 112 |
225 // Enumerate all processes under ARC init and create nspid -> pid map. | 113 // Enumerate all processes under ARC init and create nspid -> pid map. |
226 if (arc_init_pid != kNullProcessId) { | 114 if (arc_init_pid != kNullProcessId) { |
227 std::queue<ProcessId> queue; | 115 std::queue<ProcessId> queue; |
228 std::set<ProcessId> visited; | 116 std::unordered_set<ProcessId> visited; |
229 queue.push(arc_init_pid); | 117 queue.push(arc_init_pid); |
230 while (!queue.empty()) { | 118 while (!queue.empty()) { |
231 ProcessId pid = queue.front(); | 119 ProcessId pid = queue.front(); |
232 queue.pop(); | 120 queue.pop(); |
233 // Do not visit the same process twice. Otherwise we may enter an infinite | 121 // Do not visit the same process twice. Otherwise we may enter an infinite |
234 // loop if |process_tree| contains a loop. | 122 // loop if |process_tree| contains a loop. |
235 if (!visited.insert(pid).second) | 123 if (!visited.insert(pid).second) |
236 continue; | 124 continue; |
237 | 125 |
238 ProcessId nspid = base::Process(pid).GetPidInNamespace(); | 126 const ProcessId nspid = base::Process(pid).GetPidInNamespace(); |
239 | 127 |
240 // All ARC processes should be in namespace so nspid is usually non-null, | 128 // All ARC processes should be in namespace so nspid is usually non-null, |
241 // but this can happen if the process has already gone. | 129 // but this can happen if the process has already gone. |
242 // Only add processes we're interested in (those appear as keys in | 130 // Only add processes we're interested in (those appear as keys in |
243 // |nspid_to_pid_|). | 131 // |pid_map|). |
244 if (nspid != kNullProcessId && | 132 if (nspid != kNullProcessId && pid_map->find(nspid) != pid_map->end()) |
245 nspid_to_pid_.find(nspid) != nspid_to_pid_.end()) | 133 (*pid_map)[nspid] = pid; |
246 nspid_to_pid_[nspid] = pid; | |
247 | 134 |
248 for (ProcessId child_pid : process_tree[pid]) | 135 for (ProcessId child_pid : process_tree[pid]) |
249 queue.push(child_pid); | 136 queue.push(child_pid); |
250 } | 137 } |
251 } | 138 } |
252 } | 139 } |
253 | 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 |
| 207 ArcProcessService::ArcProcessService(ArcBridgeService* bridge_service) |
| 208 : ArcService(bridge_service), |
| 209 heavy_task_thread_("ArcProcessServiceThread"), |
| 210 nspid_to_pid_(new NSPidToPidMap()), |
| 211 weak_ptr_factory_(this) { |
| 212 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); |
| 213 arc_bridge_service()->process()->AddObserver(this); |
| 214 DCHECK(!g_arc_process_service); |
| 215 g_arc_process_service = this; |
| 216 heavy_task_thread_.Start(); |
| 217 } |
| 218 |
| 219 ArcProcessService::~ArcProcessService() { |
| 220 DCHECK(g_arc_process_service == this); |
| 221 heavy_task_thread_.Stop(); |
| 222 g_arc_process_service = nullptr; |
| 223 arc_bridge_service()->process()->RemoveObserver(this); |
| 224 } |
| 225 |
| 226 // static |
| 227 ArcProcessService* ArcProcessService::Get() { |
| 228 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); |
| 229 return g_arc_process_service; |
| 230 } |
| 231 |
| 232 void ArcProcessService::OnInstanceReady() { |
| 233 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); |
| 234 GetTaskRunner()->PostTask(FROM_HERE, base::Bind(&Reset, nspid_to_pid_)); |
| 235 } |
| 236 |
| 237 void ArcProcessService::RequestSystemProcessList( |
| 238 RequestProcessListCallback callback) { |
| 239 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); |
| 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 |
| 250 arc::mojom::ProcessInstance* process_instance = |
| 251 arc_bridge_service()->process()->instance(); |
| 252 if (!process_instance) { |
| 253 return false; |
| 254 } |
| 255 process_instance->RequestProcessList( |
| 256 base::Bind(&ArcProcessService::OnReceiveProcessList, |
| 257 weak_ptr_factory_.GetWeakPtr(), callback)); |
| 258 return true; |
| 259 } |
| 260 |
| 261 void ArcProcessService::OnReceiveProcessList( |
| 262 const RequestProcessListCallback& callback, |
| 263 mojo::Array<arc::mojom::RunningAppProcessInfoPtr> instance_processes) { |
| 264 DCHECK_CURRENTLY_ON(content::BrowserThread::UI); |
| 265 |
| 266 base::PostTaskAndReplyWithResult( |
| 267 GetTaskRunner().get(), FROM_HERE, |
| 268 base::Bind(&UpdateAndReturnProcessList, nspid_to_pid_, |
| 269 base::Passed(&instance_processes)), |
| 270 callback); |
| 271 } |
| 272 |
| 273 scoped_refptr<base::SingleThreadTaskRunner> ArcProcessService::GetTaskRunner() { |
| 274 return heavy_task_thread_.task_runner(); |
| 275 } |
| 276 |
254 } // namespace arc | 277 } // namespace arc |
OLD | NEW |