1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
ash / components / arc / session / arc_session_runner.cc [blame]
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/components/arc/session/arc_session_runner.h"
#include <optional>
#include <utility>
#include "ash/components/arc/arc_util.h"
#include "base/functional/bind.h"
#include "base/logging.h"
#include "base/metrics/histogram_macros.h"
#include "base/task/task_runner.h"
namespace arc {
namespace {
constexpr base::TimeDelta kDefaultRestartDelay = base::Seconds(5);
void RecordInstanceCrashUma(ArcContainerLifetimeEvent sample) {
UMA_HISTOGRAM_ENUMERATION("Arc.ContainerLifetimeEvent", sample,
ArcContainerLifetimeEvent::COUNT);
// Log the metric to facilitate finding feedback reports in Xamine.
VLOG(1) << "Arc.ContainerLifetimeEvent: "
<< static_cast<std::underlying_type_t<ArcContainerLifetimeEvent>>(
sample);
}
void RecordInstanceRestartAfterCrashUma(size_t restart_after_crash_count) {
UMA_HISTOGRAM_COUNTS_100("Arc.ContainerRestartAfterCrashCount",
restart_after_crash_count);
}
// Gets an ArcContainerLifetimeEvent value to record. Returns nullopt when no
// UMA recording is needed.
std::optional<ArcContainerLifetimeEvent> GetArcContainerLifetimeEvent(
size_t restart_after_crash_count,
ArcStopReason stop_reason,
bool was_running) {
// Record UMA only when this is the first non-early crash. This has to be
// done before checking other conditions. Otherwise, an early crash after
// container restart might be recorded. Each CONTAINER_STARTED event can
// be paired up to one non-START event.
if (restart_after_crash_count)
return std::nullopt;
switch (stop_reason) {
case ArcStopReason::SHUTDOWN:
case ArcStopReason::LOW_DISK_SPACE:
// We don't record these events.
return std::nullopt;
case ArcStopReason::GENERIC_BOOT_FAILURE:
return ArcContainerLifetimeEvent::CONTAINER_FAILED_TO_START;
case ArcStopReason::CRASH:
return was_running ? ArcContainerLifetimeEvent::CONTAINER_CRASHED
: ArcContainerLifetimeEvent::CONTAINER_CRASHED_EARLY;
}
NOTREACHED();
}
// Returns true if restart is needed for given conditions.
bool IsRestartNeeded(std::optional<ArcInstanceMode> target_mode,
ArcStopReason stop_reason,
bool was_running) {
if (!target_mode.has_value()) {
// The request to run ARC is canceled by the caller. No need to restart.
return false;
}
switch (stop_reason) {
case ArcStopReason::SHUTDOWN:
// This is a part of stop requested by ArcSessionRunner.
// If ARC is re-requested to start, restart is necessary.
// This case happens, e.g., RequestStart() -> RequestStop() ->
// RequestStart(), case. If the second RequestStart() is called before
// the instance previously running is stopped, then just |target_mode_|
// is set. On completion, restart is needed.
return true;
case ArcStopReason::GENERIC_BOOT_FAILURE:
case ArcStopReason::LOW_DISK_SPACE:
// These two are errors on starting. To prevent failure loop, do not
// restart.
return false;
case ArcStopReason::CRASH:
// ARC instance is crashed unexpectedly, so automatically restart.
// However, to avoid crash loop, do not restart if it is not successfully
// started yet. So, check |was_running|.
return was_running;
}
NOTREACHED();
}
// Returns true if the request to start/upgrade ARC instance is allowed
// operation.
bool IsRequestAllowed(const std::optional<ArcInstanceMode>& current_mode,
ArcInstanceMode request_mode) {
if (!current_mode.has_value()) {
// This is a request to start a new ARC instance (either mini instance
// or full instance).
return true;
}
if (current_mode == ArcInstanceMode::MINI_INSTANCE &&
request_mode == ArcInstanceMode::FULL_INSTANCE) {
// This is a request to upgrade the running mini instance to full instance.
return true;
}
// Otherwise, not allowed.
LOG(ERROR) << "Unexpected ARC instance mode transition request: "
<< current_mode << " -> " << request_mode;
return false;
}
} // namespace
ArcSessionRunner::ArcSessionRunner(const ArcSessionFactory& factory)
: restart_delay_(kDefaultRestartDelay),
restart_after_crash_count_(0),
factory_(factory) {}
ArcSessionRunner::~ArcSessionRunner() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (arc_session_)
arc_session_->RemoveObserver(this);
}
void ArcSessionRunner::AddObserver(Observer* observer) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
observer_list_.AddObserver(observer);
}
void ArcSessionRunner::RemoveObserver(Observer* observer) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
observer_list_.RemoveObserver(observer);
}
void ArcSessionRunner::ResumeRunner() {
VLOG(1) << "ArcSessionRunner is resumed";
resumed_ = true;
if (target_mode_) {
ArcInstanceMode original_mode = *target_mode_;
target_mode_ = std::nullopt;
RequestStart(original_mode);
}
}
void ArcSessionRunner::RequestStartMiniInstance() {
RequestStart(ArcInstanceMode::MINI_INSTANCE);
}
void ArcSessionRunner::RequestUpgrade(UpgradeParams params) {
upgrade_params_ = std::move(params);
RequestStart(ArcInstanceMode::FULL_INSTANCE);
}
void ArcSessionRunner::RequestStart(ArcInstanceMode request_mode) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (target_mode_ == request_mode) {
// Consecutive RequestStart() call for the same mode. Do nothing.
return;
}
if (!IsRequestAllowed(target_mode_, request_mode))
return;
VLOG(1) << "Session start requested: " << request_mode;
target_mode_ = request_mode;
if (arc_session_ && arc_session_->IsStopRequested()) {
// This is the case where RequestStop() was called, but before
// |arc_session_| had finshed stopping, RequestStart() is called.
// Do nothing in the that case, since when |arc_session_| does actually
// stop, OnSessionStopped() will be called, where it should automatically
// restart.
return;
}
if (restart_timer_.IsRunning()) {
// |restart_timer_| may be running if this is upgrade request in a
// following scenario.
// - RequestStart(MINI_INSTANCE)
// - RequestStop()
// - RequestStart(MINI_INSTANCE)
// - OnSessionStopped()
// - RequestStart(FULL_INSTANCE) before RestartArcSession() is called.
// In such a case, defer the operation to RestartArcSession() called later.
return;
}
if (!resumed_) {
VLOG(1) << "Deferring to start ARC instance. "
<< "This runner hasn't been resumed yet.";
return;
}
// No asynchronous event is expected later. Trigger the ArcSession now.
StartArcSession();
}
void ArcSessionRunner::RequestStop() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
VLOG(1) << "Session stop requested";
target_mode_ = std::nullopt;
if (arc_session_) {
// If |arc_session_| is running, stop it.
// Note that |arc_session_| may be already in the process of stopping or
// be stopped.
// E.g. RequestStart() -> RequestStop() -> RequestStart() -> RequestStop()
// case. If the second RequestStop() is called before the first
// RequestStop() is not yet completed for the instance, Stop() of the
// instance is called again, but it is no-op as expected.
arc_session_->Stop();
}
// In case restarting is in progress, cancel it.
restart_timer_.Stop();
}
void ArcSessionRunner::OnShutdown() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
VLOG(1) << "OnShutdown";
target_mode_ = std::nullopt;
restart_timer_.Stop();
if (arc_session_)
arc_session_->OnShutdown();
// ArcSession::OnShutdown() invokes OnSessionStopped() synchronously.
// In the observer method, |arc_session_| should be destroyed.
DCHECK(!arc_session_);
}
void ArcSessionRunner::SetUserInfo(
const cryptohome::Identification& cryptohome_id,
const std::string& hash,
const std::string& serial_number) {
// |cryptohome_id.id()| and |hash| can be empty in unit tests. This function
// can also be called multiple times in tests.
// TODO(khmel): Fix tests and add DCHECKs to make sure they are not empty
// and the function is called only once.
DCHECK(!IsArcVmEnabled() || !serial_number.empty());
cryptohome_id_ = cryptohome_id;
user_id_hash_ = hash;
serial_number_ = serial_number;
if (arc_session_)
arc_session_->SetUserInfo(cryptohome_id_, user_id_hash_, serial_number_);
}
void ArcSessionRunner::SetDemoModeDelegate(
std::unique_ptr<ArcClientAdapter::DemoModeDelegate> delegate) {
demo_mode_delegate_ = std::move(delegate);
}
void ArcSessionRunner::TrimVmMemory(TrimVmMemoryCallback callback,
int page_limit) {
if (arc_session_) {
arc_session_->TrimVmMemory(std::move(callback), page_limit);
return;
}
LOG(WARNING) << "TrimVmMemory is called when no ARC session is running";
std::move(callback).Run(/*success=*/false,
/*failure_reason=*/"No ARC session is running");
}
void ArcSessionRunner::SetRestartDelayForTesting(
const base::TimeDelta& restart_delay) {
DCHECK(!arc_session_);
DCHECK(!restart_timer_.IsRunning());
restart_delay_ = restart_delay;
}
void ArcSessionRunner::StartArcSession() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(!restart_timer_.IsRunning());
DCHECK(target_mode_.has_value());
VLOG(1) << "Starting ARC instance";
if (!arc_session_) {
arc_session_ = factory_.Run();
if (!cryptohome_id_.id().empty() && !user_id_hash_.empty() &&
!serial_number_.empty()) {
arc_session_->SetUserInfo(cryptohome_id_, user_id_hash_, serial_number_);
}
arc_session_->SetDefaultDeviceScaleFactor(default_device_scale_factor_);
arc_session_->SetDemoModeDelegate(demo_mode_delegate_.get());
arc_session_->SetUseVirtioBlkData(use_virtio_blk_data_);
arc_session_->SetArcSignedIn(arc_signed_in_);
arc_session_->AddObserver(this);
arc_session_->StartMiniInstance();
// Record the UMA only when |restart_after_crash_count_| is zero to avoid
// recording an auto-restart-then-crash loop. Such a crash loop is recorded
// separately with RecordInstanceRestartAfterCrashUma().
if (!restart_after_crash_count_)
RecordInstanceCrashUma(ArcContainerLifetimeEvent::CONTAINER_STARTING);
}
if (target_mode_ == ArcInstanceMode::FULL_INSTANCE) {
// Do not std::move the params intentionally. RestartArcSession() can
// reuse the params without preceded by resetting them.
arc_session_->RequestUpgrade(upgrade_params_);
}
}
void ArcSessionRunner::RestartArcSession() {
VLOG(0) << "Restarting ARC instance";
// The order is important here. Call StartArcSession(), then notify observers.
StartArcSession();
for (auto& observer : observer_list_)
observer.OnSessionRestarting();
}
void ArcSessionRunner::OnSessionStopped(ArcStopReason stop_reason,
bool was_running,
bool full_requested) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(arc_session_);
DCHECK(!restart_timer_.IsRunning());
VLOG(0) << "ARC stopped: " << stop_reason;
arc_session_->RemoveObserver(this);
arc_session_.reset();
const std::optional<ArcContainerLifetimeEvent> uma_to_record =
GetArcContainerLifetimeEvent(restart_after_crash_count_, stop_reason,
was_running);
if (uma_to_record.has_value())
RecordInstanceCrashUma(uma_to_record.value());
const bool restarting =
IsRestartNeeded(target_mode_, stop_reason, was_running);
if (restarting && stop_reason == ArcStopReason::CRASH) {
++restart_after_crash_count_;
} else {
// The session ended. Record the restart count.
RecordInstanceRestartAfterCrashUma(restart_after_crash_count_);
restart_after_crash_count_ = 0;
}
if (restarting) {
// There was a previous invocation and it crashed for some reason. Try
// starting ARC instance later again.
// Note that even |restart_delay_| is 0 (for testing), it needs to
// PostTask, because observer callback may call RequestStart()/Stop().
VLOG(0) << "ARC restarting";
restart_timer_.Start(FROM_HERE, restart_delay_,
base::BindOnce(&ArcSessionRunner::RestartArcSession,
weak_ptr_factory_.GetWeakPtr()));
}
// The observers should be agnostic to the existence of the limited-purpose
// instance.
if (full_requested) {
for (auto& observer : observer_list_)
observer.OnSessionStopped(stop_reason, restarting);
}
}
} // namespace arc