forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdlcservice_client.cc
500 lines (426 loc) · 17.7 KB
/
dlcservice_client.cc
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
// Copyright (c) 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/dbus/dlcservice/dlcservice_client.h"
#include <stdint.h>
#include <algorithm>
#include <deque>
#include <map>
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/no_destructor.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/task/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chromeos/dbus/constants/dbus_switches.h"
#include "chromeos/dbus/dlcservice/fake_dlcservice_client.h"
#include "dbus/bus.h"
#include "dbus/message.h"
#include "dbus/object_path.h"
#include "dbus/object_proxy.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/cros_system_api/dbus/service_constants.h"
namespace chromeos {
namespace {
DlcserviceClient* g_instance = nullptr;
class DlcserviceErrorResponseHandler {
public:
explicit DlcserviceErrorResponseHandler(dbus::ErrorResponse* err_response)
: err_(dlcservice::kErrorInternal) {
if (!err_response) {
LOG(ERROR) << "Failed to set err since ErrorResponse is null.";
return;
}
VerifyAndSetError(err_response);
VerifyAndSetErrorMessage(err_response);
VLOG(1) << "Handling err=" << err_ << " err_msg=" << err_msg_;
}
DlcserviceErrorResponseHandler(const DlcserviceErrorResponseHandler&) =
delete;
DlcserviceErrorResponseHandler& operator=(
const DlcserviceErrorResponseHandler&) = delete;
~DlcserviceErrorResponseHandler() = default;
std::string get_err() { return err_; }
std::string get_err_msg() { return err_msg_; }
private:
void VerifyAndSetError(dbus::ErrorResponse* err_response) {
const std::string& err = err_response->GetErrorName();
static const base::NoDestructor<std::unordered_set<std::string>> err_set({
dlcservice::kErrorNone,
dlcservice::kErrorInternal,
dlcservice::kErrorBusy,
dlcservice::kErrorNeedReboot,
dlcservice::kErrorInvalidDlc,
dlcservice::kErrorNoImageFound,
});
// Lookup the dlcservice error code and provide default on invalid.
auto itr = err_set->find(err);
if (itr == err_set->end()) {
LOG(ERROR) << "Failed to set error based on ErrorResponse "
"defaulted to kErrorInternal, was:" << err;
err_ = dlcservice::kErrorInternal;
return;
}
err_ = *itr;
}
void VerifyAndSetErrorMessage(dbus::ErrorResponse* err_response) {
if (!dbus::MessageReader(err_response).PopString(&err_msg_)) {
LOG(ERROR) << "Failed to set error message from ErrorResponse.";
}
}
// Holds the dlcservice specific error.
std::string err_;
// Holds the entire error message from error response.
std::string err_msg_;
};
} // namespace
// The DlcserviceClient implementation used in production.
class DlcserviceClientImpl : public DlcserviceClient {
public:
DlcserviceClientImpl() : dlcservice_proxy_(nullptr) {}
DlcserviceClientImpl(const DlcserviceClientImpl&) = delete;
DlcserviceClientImpl& operator=(const DlcserviceClientImpl&) = delete;
~DlcserviceClientImpl() override = default;
void Install(const dlcservice::InstallRequest& install_request,
InstallCallback install_callback,
ProgressCallback progress_callback) override {
CheckServiceAvailable("Install");
const std::string& id = install_request.id();
// If another installation for the same DLC ID was already called, go ahead
// and hold the installation fields.
if (installation_holder_.find(id) != installation_holder_.end()) {
HoldInstallation(install_request, std::move(install_callback),
std::move(progress_callback));
return;
}
if (installing_) {
EnqueueTask(base::BindOnce(
&DlcserviceClientImpl::Install, weak_ptr_factory_.GetWeakPtr(),
std::move(install_request), std::move(install_callback),
std::move(progress_callback)));
return;
}
TaskStarted();
dbus::MethodCall method_call(dlcservice::kDlcServiceInterface,
dlcservice::kInstallMethod);
dbus::MessageWriter writer(&method_call);
writer.AppendProtoAsArrayOfBytes(install_request);
VLOG(1) << "Requesting to install DLC(s).";
// TODO(b/166782419): dlcservice hashes preloadable DLC images which can
// cause timeouts during preloads. Transitioning into F20 will fix this as
// preloading will be deprecated.
constexpr int timeout_ms = 5 * 60 * 1000;
dlcservice_proxy_->CallMethodWithErrorResponse(
&method_call, timeout_ms,
base::BindOnce(&DlcserviceClientImpl::OnInstall,
weak_ptr_factory_.GetWeakPtr(), install_request,
std::move(install_callback),
std::move(progress_callback)));
}
void Uninstall(const std::string& dlc_id,
UninstallCallback uninstall_callback) override {
CheckServiceAvailable("Uninstall");
dbus::MethodCall method_call(dlcservice::kDlcServiceInterface,
dlcservice::kUninstallMethod);
dbus::MessageWriter writer(&method_call);
writer.AppendString(dlc_id);
VLOG(1) << "Requesting to uninstall DLC=" << dlc_id;
dlcservice_proxy_->CallMethodWithErrorResponse(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::BindOnce(&DlcserviceClientImpl::OnUninstall,
weak_ptr_factory_.GetWeakPtr(),
std::move(uninstall_callback)));
}
void Purge(const std::string& dlc_id, PurgeCallback purge_callback) override {
CheckServiceAvailable("Purge");
dbus::MethodCall method_call(dlcservice::kDlcServiceInterface,
dlcservice::kPurgeMethod);
dbus::MessageWriter writer(&method_call);
writer.AppendString(dlc_id);
VLOG(1) << "Requesting to purge DLC=" << dlc_id;
dlcservice_proxy_->CallMethodWithErrorResponse(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::BindOnce(&DlcserviceClientImpl::OnPurge,
weak_ptr_factory_.GetWeakPtr(),
std::move(purge_callback)));
}
void GetDlcState(const std::string& dlc_id,
GetDlcStateCallback callback) override {
CheckServiceAvailable("GetDlcState");
dbus::MethodCall method_call(dlcservice::kDlcServiceInterface,
dlcservice::kGetDlcStateMethod);
dbus::MessageWriter writer(&method_call);
writer.AppendString(dlc_id);
VLOG(1) << "Requesting DLC state of" << dlc_id;
dlcservice_proxy_->CallMethodWithErrorResponse(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::BindOnce(&DlcserviceClientImpl::OnGetDlcState,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void GetExistingDlcs(GetExistingDlcsCallback callback) override {
CheckServiceAvailable("GetExistingDlcs");
dbus::MethodCall method_call(dlcservice::kDlcServiceInterface,
dlcservice::kGetExistingDlcsMethod);
VLOG(1) << "Requesting to get existing DLC(s).";
dlcservice_proxy_->CallMethodWithErrorResponse(
&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
base::BindOnce(&DlcserviceClientImpl::OnGetExistingDlcs,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void DlcStateChangedForTest(dbus::Signal* signal) override {
DlcStateChanged(signal);
}
void AddObserver(Observer* observer) override {
observers_.AddObserver(observer);
}
void RemoveObserver(Observer* observer) override {
observers_.RemoveObserver(observer);
}
void Init(dbus::Bus* bus) {
dlcservice_proxy_ = bus->GetObjectProxy(
dlcservice::kDlcServiceServiceName,
dbus::ObjectPath(dlcservice::kDlcServiceServicePath));
dlcservice_proxy_->ConnectToSignal(
dlcservice::kDlcServiceInterface, dlcservice::kDlcStateChangedSignal,
base::BindRepeating(&DlcserviceClientImpl::DlcStateChanged,
weak_ptr_factory_.GetWeakPtr()),
base::BindOnce(&DlcserviceClientImpl::DlcStateChangedConnected,
weak_ptr_factory_.GetWeakPtr()));
dlcservice_proxy_->WaitForServiceToBeAvailable(
base::BindOnce(&DlcserviceClientImpl::OnServiceAvailable,
weak_ptr_factory_.GetWeakPtr()));
}
private:
// Fields related to an installation allowing for multiple installations to be
// in flight concurrently and handled by this dlcservice client. The callbacks
// are used to report progress and the final installation.
struct InstallationHolder {
InstallCallback install_callback;
ProgressCallback progress_callback;
InstallationHolder(InstallCallback install_callback,
ProgressCallback progress_callback)
: install_callback(std::move(install_callback)),
progress_callback(std::move(progress_callback)) {}
};
void OnServiceAvailable(bool service_available) {
if (service_available)
VLOG(1) << "dlcservice is available.";
else
LOG(ERROR) << "dlcservice is not available.";
service_available_ = service_available;
}
// Set the indication that an install is being performed which was requested
// from this client (Chrome specifically).
void TaskStarted() { installing_ = true; }
// Clears any state an installation had setup while being performed.
void TaskEnded() { installing_ = false; }
void HoldInstallation(const dlcservice::InstallRequest& install_request,
InstallCallback install_callback,
ProgressCallback progress_callback) {
installation_holder_[install_request.id()].emplace_back(
std::move(install_callback), std::move(progress_callback));
}
void ReleaseInstallation(const std::string& id) {
installation_holder_.erase(id);
}
void EnqueueTask(base::OnceClosure task) {
pending_tasks_.emplace_back(std::move(task));
}
void CheckAndRunPendingTask() {
TaskEnded();
if (!pending_tasks_.empty()) {
std::move(pending_tasks_.front()).Run();
pending_tasks_.pop_front();
}
}
void SendProgress(const dlcservice::DlcState& dlc_state) {
auto id = dlc_state.id();
auto progress = dlc_state.progress();
VLOG(2) << "Installation for DLC " << id << " in progress: " << progress;
for (auto& installation_state : installation_holder_[id])
installation_state.progress_callback.Run(progress);
}
void SendCompleted(const dlcservice::DlcState& dlc_state) {
auto id = dlc_state.id();
if (dlc_state.state() == dlcservice::DlcState::NOT_INSTALLED) {
LOG(ERROR) << "Failed to install DLC " << id
<< " with error code: " << dlc_state.last_error_code();
} else {
VLOG(1) << "DLC " << id << " installed successfully.";
if (dlc_state.last_error_code() != dlcservice::kErrorNone) {
LOG(WARNING) << "DLC installation was sucessful but non-success "
<< "error code: " << dlc_state.last_error_code();
}
}
InstallResult result = {
.error = dlc_state.last_error_code(),
.dlc_id = id,
.root_path = dlc_state.root_path(),
};
for (auto& installation_state : installation_holder_[id])
std::move(installation_state.install_callback).Run(result);
ReleaseInstallation(id);
}
void DlcStateChanged(dbus::Signal* signal) {
dlcservice::DlcState dlc_state;
if (!dbus::MessageReader(signal).PopArrayOfBytesAsProto(&dlc_state)) {
LOG(ERROR) << "Failed to parse proto as install status.";
return;
}
// Notify all observers of change in the state of this DLC.
for (Observer& observer : observers_) {
observer.OnDlcStateChanged(dlc_state);
}
// Skip DLCs not installing from this dlcservice client.
if (installation_holder_.find(dlc_state.id()) == installation_holder_.end())
return;
switch (dlc_state.state()) {
case dlcservice::DlcState::NOT_INSTALLED:
case dlcservice::DlcState::INSTALLED:
SendCompleted(dlc_state);
break;
case dlcservice::DlcState::INSTALLING:
SendProgress(dlc_state);
// Need to return here since we don't want to try starting another
// pending install from the queue (would waste time checking).
return;
default:
NOTREACHED();
}
// Try to run a pending install since we have complete/failed the current
// install, but do not waste trying to run a pending install when the
// current install is running at the moment.
CheckAndRunPendingTask();
}
void DlcStateChangedConnected(const std::string& interface,
const std::string& signal,
bool success) {
LOG_IF(ERROR, !success) << "Failed to connect to DlcStateChanged signal.";
}
void OnInstall(const dlcservice::InstallRequest& install_request,
InstallCallback install_callback,
ProgressCallback progress_callback,
dbus::Response* response,
dbus::ErrorResponse* err_response) {
const std::string& id = install_request.id();
if (response) {
HoldInstallation(install_request, std::move(install_callback),
std::move(progress_callback));
return;
}
const auto err = DlcserviceErrorResponseHandler(err_response).get_err();
if (err == dlcservice::kErrorBusy) {
EnqueueTask(base::BindOnce(&DlcserviceClientImpl::Install,
weak_ptr_factory_.GetWeakPtr(),
install_request, std::move(install_callback),
std::move(progress_callback)));
} else {
HoldInstallation(install_request, std::move(install_callback),
std::move(progress_callback));
dlcservice::DlcState dlc_state;
dlc_state.set_id(id);
dlc_state.set_last_error_code(err);
SendCompleted(dlc_state);
}
CheckAndRunPendingTask();
}
void OnUninstall(UninstallCallback uninstall_callback,
dbus::Response* response,
dbus::ErrorResponse* err_response) {
std::move(uninstall_callback)
.Run(response ? dlcservice::kErrorNone
: DlcserviceErrorResponseHandler(err_response).get_err());
}
void OnPurge(PurgeCallback purge_callback,
dbus::Response* response,
dbus::ErrorResponse* err_response) {
std::move(purge_callback)
.Run(response ? dlcservice::kErrorNone
: DlcserviceErrorResponseHandler(err_response).get_err());
}
void OnGetDlcState(GetDlcStateCallback callback,
dbus::Response* response,
dbus::ErrorResponse* err_response) {
dlcservice::DlcState dlc_state;
if (response &&
dbus::MessageReader(response).PopArrayOfBytesAsProto(&dlc_state)) {
std::move(callback).Run(dlcservice::kErrorNone, dlc_state);
} else {
std::move(callback).Run(
DlcserviceErrorResponseHandler(err_response).get_err(),
dlcservice::DlcState());
}
}
void OnGetExistingDlcs(GetExistingDlcsCallback callback,
dbus::Response* response,
dbus::ErrorResponse* err_response) {
dlcservice::DlcsWithContent dlcs_with_content;
if (response && dbus::MessageReader(response).PopArrayOfBytesAsProto(
&dlcs_with_content)) {
std::move(callback).Run(dlcservice::kErrorNone, dlcs_with_content);
} else {
std::move(callback).Run(
DlcserviceErrorResponseHandler(err_response).get_err(),
dlcservice::DlcsWithContent());
}
}
// TODO(b/164310699): This check is added in order to see if dlcservice daemon
// not being available is the cause of flakes in the CQ.
void CheckServiceAvailable(const std::string& method_name) {
if (!service_available_)
LOG(WARNING) << method_name
<< " called when dlcservice is not available.";
}
// DLC ID to `InstallationHolder` mapping.
std::map<std::string, std::vector<InstallationHolder>> installation_holder_;
dbus::ObjectProxy* dlcservice_proxy_;
// TODO(crbug.com/928805): Once platform dlcservice batches, can be removed.
// Specifically when platform dlcservice doesn't return a busy status.
// Whether an install is currently in progress. Can be used to decide whether
// to queue up incoming install requests.
bool installing_ = false;
// A list of postponed installs to dlcservice.
std::deque<base::OnceClosure> pending_tasks_;
// A list of observers that are listening on state changes, etc.
base::ObserverList<Observer> observers_;
// Indicates if dlcservice daemon is available.
bool service_available_ = false;
// Note: This should remain the last member so it'll be destroyed and
// invalidate its weak pointers before any other members are destroyed.
base::WeakPtrFactory<DlcserviceClientImpl> weak_ptr_factory_{this};
};
DlcserviceClient::DlcserviceClient() {
CHECK(!g_instance);
g_instance = this;
}
DlcserviceClient::~DlcserviceClient() {
CHECK_EQ(this, g_instance);
g_instance = nullptr;
}
// static
void DlcserviceClient::Initialize(dbus::Bus* bus) {
CHECK(bus);
(new DlcserviceClientImpl())->Init(bus);
}
// static
void DlcserviceClient::InitializeFake() {
new FakeDlcserviceClient();
}
// static
void DlcserviceClient::Shutdown() {
CHECK(g_instance);
delete g_instance;
}
// static
DlcserviceClient* DlcserviceClient::Get() {
return g_instance;
}
} // namespace chromeos