File: rmad_client.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (705 lines) | stat: -rw-r--r-- 26,289 bytes parent folder | download | duplicates (6)
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chromeos/ash/components/dbus/rmad/rmad_client.h"

#include <optional>
#include <utility>

#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/functional/callback_forward.h"
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
#include "base/observer_list.h"
#include "base/path_service.h"
#include "base/task/thread_pool.h"
#include "chromeos/ash/components/dbus/rmad/fake_rmad_client.h"
#include "chromeos/dbus/constants/dbus_paths.h"
#include "dbus/bus.h"
#include "dbus/message.h"
#include "dbus/object_proxy.h"
#include "third_party/cros_system_api/dbus/service_constants.h"

namespace ash {
namespace {

RmadClient* g_instance = nullptr;

}  // namespace

class RmadClientImpl : public RmadClient {
 public:
  void Init(dbus::Bus* bus);

  bool WasRmaStateDetected() override;
  void SetRmaRequiredCallbackForSessionManager(
      base::OnceClosure session_manager_callback) override;
  void GetCurrentState(
      chromeos::DBusMethodCallback<rmad::GetStateReply> callback) override;
  void TransitionNextState(
      const rmad::RmadState& state,
      chromeos::DBusMethodCallback<rmad::GetStateReply> callback) override;
  void TransitionPreviousState(
      chromeos::DBusMethodCallback<rmad::GetStateReply> callback) override;
  void AbortRma(
      chromeos::DBusMethodCallback<rmad::AbortRmaReply> callback) override;
  void GetLog(
      chromeos::DBusMethodCallback<rmad::GetLogReply> callback) override;
  void SaveLog(
      const std::string& diagnostics_log_text,
      chromeos::DBusMethodCallback<rmad::SaveLogReply> callback) override;
  void RecordBrowserActionMetric(
      const rmad::RecordBrowserActionMetricRequest request,
      chromeos::DBusMethodCallback<rmad::RecordBrowserActionMetricReply>
          callback) override;
  void ExtractExternalDiagnosticsApp(
      chromeos::DBusMethodCallback<rmad::ExtractExternalDiagnosticsAppReply>
          callback) override;
  void InstallExtractedDiagnosticsApp(
      chromeos::DBusMethodCallback<rmad::InstallExtractedDiagnosticsAppReply>
          callback) override;
  void GetInstalledDiagnosticsApp(
      chromeos::DBusMethodCallback<rmad::GetInstalledDiagnosticsAppReply>
          callback) override;
  void AddObserver(Observer* observer) override;
  void RemoveObserver(Observer* observer) override;
  bool HasObserver(const Observer* observer) const override;

  RmadClientImpl() = default;
  RmadClientImpl(const RmadClientImpl&) = delete;
  RmadClientImpl& operator=(const RmadClientImpl&) = delete;
  ~RmadClientImpl() override = default;

 private:
  void CheckIfRmaIsRequired();
  void OnCheckIfRmaIsRequired(dbus::Response* response);

  template <class T>
  void OnProtoReply(chromeos::DBusMethodCallback<T> callback,
                    dbus::Response* response);

  void CalibrationProgressReceived(dbus::Signal* signal);
  void CalibrationOverallProgressReceived(dbus::Signal* signal);
  void ErrorReceived(dbus::Signal* signal);
  void HardwareWriteProtectionStateReceived(dbus::Signal* signal);
  void PowerCableStateReceived(dbus::Signal* signal);
  void ExternalDiskStatusReceived(dbus::Signal* signal);
  void ProvisioningProgressReceived(dbus::Signal* signal);
  void HardwareVerificationResultReceived(dbus::Signal* signal);
  void FinalizationProgressReceived(dbus::Signal* signal);
  void RoFirmwareUpdateProgressReceived(dbus::Signal* signal);

  void SignalConnected(const std::string& interface_name,
                       const std::string& signal_name,
                       bool success);

  // Saves the response from base::PathExists().
  void OnFetchRmadExecutableExists(bool exists);

  // Saves the response from base::PathExists().
  void OnFetchRmadStateFileExists(bool exists);

  // Sends out the requests to verify if RMAD files exist on device.
  void StartCheckForRmadFiles();

  raw_ptr<dbus::ObjectProxy> rmad_proxy_ = nullptr;
  base::ObserverList<Observer, /*check_empty=*/true, /*allow_reentrancy=*/false>
      observers_;

  // True if the RMAD executable exists.
  std::optional<bool> rma_executable_exists_;

  // True if the RMAD state file exists.
  std::optional<bool> rma_state_file_exists_;

  // Set from the response to the RMA daemon D-Bus call.
  bool is_rma_required_ = false;

  // The ChromeSessionManager callback invoked when |is_rma_required_| is set.
  base::OnceClosure session_manager_callback_;

  // 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<RmadClientImpl> weak_ptr_factory_{this};
};

void RmadClientImpl::Init(dbus::Bus* bus) {
  StartCheckForRmadFiles();
  rmad_proxy_ = bus->GetObjectProxy(rmad::kRmadServiceName,
                                    dbus::ObjectPath(rmad::kRmadServicePath));
  // Listen to D-Bus signals emitted by rmad.
  typedef void (RmadClientImpl::*SignalMethod)(dbus::Signal*);
  const std::pair<const char*, SignalMethod> kSignalMethods[] = {
      {rmad::kCalibrationProgressSignal,
       &RmadClientImpl::CalibrationProgressReceived},
      {rmad::kCalibrationOverallSignal,
       &RmadClientImpl::CalibrationOverallProgressReceived},
      {rmad::kErrorSignal, &RmadClientImpl::ErrorReceived},
      {rmad::kHardwareWriteProtectionStateSignal,
       &RmadClientImpl::HardwareWriteProtectionStateReceived},
      {rmad::kPowerCableStateSignal, &RmadClientImpl::PowerCableStateReceived},
      {rmad::kExternalDiskDetectedSignal,
       &RmadClientImpl::ExternalDiskStatusReceived},
      {rmad::kProvisioningProgressSignal,
       &RmadClientImpl::ProvisioningProgressReceived},
      {rmad::kHardwareVerificationResultSignal,
       &RmadClientImpl::HardwareVerificationResultReceived},
      {rmad::kFinalizeProgressSignal,
       &RmadClientImpl::FinalizationProgressReceived},
      {rmad::kUpdateRoFirmwareStatusSignal,
       &RmadClientImpl::RoFirmwareUpdateProgressReceived},
  };
  auto on_connected_callback = base::BindRepeating(
      &RmadClientImpl::SignalConnected, weak_ptr_factory_.GetWeakPtr());
  for (const auto& p : kSignalMethods) {
    rmad_proxy_->ConnectToSignal(
        rmad::kRmadInterfaceName, p.first,
        base::BindRepeating(p.second, weak_ptr_factory_.GetWeakPtr()),
        on_connected_callback);
  }
  CheckIfRmaIsRequired();
}

void RmadClientImpl::CheckIfRmaIsRequired() {
  dbus::MethodCall method_call(rmad::kRmadInterfaceName,
                               rmad::kIsRmaRequiredMethod);
  dbus::MessageWriter writer(&method_call);
  rmad_proxy_->CallMethod(
      &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
      base::BindOnce(&RmadClientImpl::OnCheckIfRmaIsRequired,
                     weak_ptr_factory_.GetWeakPtr()));
}

void RmadClientImpl::OnCheckIfRmaIsRequired(dbus::Response* response) {
  // TODO(b/230924565): Remove LOG statement after feature release.
  VLOG(1) << "RmadClientImpl::OnCheckIfRmaIsRequired rma_executable_exists_: "
          << rma_executable_exists_.value_or(false)
          << " rma_state_file_exists_: "
          << rma_state_file_exists_.value_or(false);

  if (!response) {
    LOG(ERROR) << "Error calling rmad function for OnCheckIfRmaIsRequired";
    return;
  }

  dbus::MessageReader reader(response);
  if (!reader.PopBool(&is_rma_required_)) {
    LOG(ERROR) << "Unable to decode response for " << response->GetMember();
    return;
  }
  DCHECK(!reader.HasMoreData());

  if (!is_rma_required_) {
    // TODO(b/230924565): Remove LOG statement after feature release.
    VLOG(1) << "RmadClientImpl::OnCheckIfRmaIsRequired RMA is not required";

    // If RMA isn't required, callback is no longer needed.
    session_manager_callback_.Reset();
    return;
  }

  // TODO(b/230924565): Remove LOG statements after feature release.
  if (session_manager_callback_) {
    VLOG(1) << "RmadClientImpl::OnCheckIfRmaIsRequired invoking session "
               "manager callback";
    std::move(session_manager_callback_).Run();
  } else {
    VLOG(1) << "RmadClientImpl::OnCheckIfRmaIsRequired the callback is not set";
  }
}

// Called when a dbus signal is initially connected.
void RmadClientImpl::SignalConnected(const std::string& interface_name,
                                     const std::string& signal_name,
                                     bool success) {
  if (!success) {
    LOG(ERROR) << "Failed to connect to signal " << signal_name << ".";
  }
}

void RmadClientImpl::CalibrationProgressReceived(dbus::Signal* signal) {
  DCHECK_EQ(signal->GetMember(), rmad::kCalibrationProgressSignal);
  dbus::MessageReader reader(signal);
  // Read proto message
  dbus::MessageReader sub_reader(nullptr);
  if (!reader.PopStruct(&sub_reader)) {
    LOG(ERROR) << "Unable to decode signal for " << signal->GetMember();
    return;
  }
  DCHECK(!reader.HasMoreData());
  int32_t component;
  int32_t status;
  double progress;
  if (!sub_reader.PopInt32(&component) || !sub_reader.PopInt32(&status) ||
      !sub_reader.PopDouble(&progress)) {
    LOG(ERROR) << "Unable to decode signal for " << signal->GetMember();
    return;
  }
  rmad::CalibrationComponentStatus signal_proto;
  signal_proto.set_component(static_cast<rmad::RmadComponent>(component));
  signal_proto.set_status(
      static_cast<rmad::CalibrationComponentStatus::CalibrationStatus>(status));
  signal_proto.set_progress(progress);
  for (auto& observer : observers_) {
    observer.CalibrationProgress(signal_proto);
  }
}

void RmadClientImpl::CalibrationOverallProgressReceived(dbus::Signal* signal) {
  DCHECK_EQ(signal->GetMember(), rmad::kCalibrationOverallSignal);
  dbus::MessageReader reader(signal);
  int32_t overall_progress_status;
  if (!reader.PopInt32(&overall_progress_status)) {
    LOG(ERROR) << "Unable to decode overall progress status int32 from "
               << signal->GetMember() << " signal";
    return;
  }
  DCHECK(!reader.HasMoreData());
  for (auto& observer : observers_) {
    observer.CalibrationOverallProgress(
        static_cast<rmad::CalibrationOverallStatus>(overall_progress_status));
  }
}

void RmadClientImpl::ErrorReceived(dbus::Signal* signal) {
  DCHECK_EQ(signal->GetMember(), rmad::kErrorSignal);
  dbus::MessageReader reader(signal);
  int32_t error;
  if (!reader.PopInt32(&error)) {
    LOG(ERROR) << "Unable to decode error int32 from " << signal->GetMember()
               << " signal";
    return;
  }
  DCHECK(!reader.HasMoreData());
  for (auto& observer : observers_) {
    observer.Error(static_cast<rmad::RmadErrorCode>(error));
  }
}

void RmadClientImpl::HardwareWriteProtectionStateReceived(
    dbus::Signal* signal) {
  DCHECK_EQ(signal->GetMember(), rmad::kHardwareWriteProtectionStateSignal);
  dbus::MessageReader reader(signal);
  bool enabled;
  if (!reader.PopBool(&enabled)) {
    LOG(ERROR) << "Unable to decode enabled bool from " << signal->GetMember()
               << " signal";
    return;
  }
  DCHECK(!reader.HasMoreData());
  for (auto& observer : observers_) {
    observer.HardwareWriteProtectionState(enabled);
  }
}

void RmadClientImpl::PowerCableStateReceived(dbus::Signal* signal) {
  DCHECK_EQ(signal->GetMember(), rmad::kPowerCableStateSignal);
  dbus::MessageReader reader(signal);
  bool plugged_in;
  if (!reader.PopBool(&plugged_in)) {
    LOG(ERROR) << "Unable to decode plugged_in bool from "
               << signal->GetMember() << " signal";
    return;
  }
  DCHECK(!reader.HasMoreData());
  for (auto& observer : observers_) {
    observer.PowerCableState(plugged_in);
  }
}

void RmadClientImpl::ExternalDiskStatusReceived(dbus::Signal* signal) {
  DCHECK_EQ(signal->GetMember(), rmad::kExternalDiskDetectedSignal);
  dbus::MessageReader reader(signal);
  bool detected;
  if (!reader.PopBool(&detected)) {
    LOG(ERROR) << "Unable to decode detected bool from " << signal->GetMember()
               << " signal";
    return;
  }
  DCHECK(!reader.HasMoreData());
  for (auto& observer : observers_) {
    observer.ExternalDiskState(detected);
  }
}

void RmadClientImpl::ProvisioningProgressReceived(dbus::Signal* signal) {
  DCHECK_EQ(signal->GetMember(), rmad::kProvisioningProgressSignal);
  dbus::MessageReader reader(signal);
  // Read proto message
  dbus::MessageReader sub_reader(nullptr);
  if (!reader.PopStruct(&sub_reader)) {
    LOG(ERROR) << "Unable to decode signal for " << signal->GetMember();
    return;
  }
  DCHECK(!reader.HasMoreData());
  int32_t status;
  double progress;
  int32_t error;
  if (!sub_reader.PopInt32(&status) || !sub_reader.PopDouble(&progress) ||
      !sub_reader.PopInt32(&error)) {
    LOG(ERROR) << "Unable to decode signal for " << signal->GetMember();
    return;
  }
  rmad::ProvisionStatus signal_proto;
  signal_proto.set_status(static_cast<rmad::ProvisionStatus::Status>(status));
  signal_proto.set_progress(progress);
  signal_proto.set_error(static_cast<rmad::ProvisionStatus::Error>(error));
  for (auto& observer : observers_) {
    observer.ProvisioningProgress(signal_proto);
  }
}

void RmadClientImpl::HardwareVerificationResultReceived(dbus::Signal* signal) {
  DCHECK_EQ(signal->GetMember(), rmad::kHardwareVerificationResultSignal);
  dbus::MessageReader reader(signal);
  // Read message
  dbus::MessageReader sub_reader(nullptr);
  if (!reader.PopStruct(&sub_reader)) {
    LOG(ERROR) << "Unable to decode signal for " << signal->GetMember();
    return;
  }
  DCHECK(!reader.HasMoreData());
  bool is_compliant = true;
  bool is_skipped = false;
  std::string error_str = "";
  if (!sub_reader.PopBool(&is_compliant) || !sub_reader.PopString(&error_str) ||
      !sub_reader.PopBool(&is_skipped)) {
    LOG(ERROR) << "Unable to decode signal for " << signal->GetMember();
    return;
  }
  DCHECK(!reader.HasMoreData());
  rmad::HardwareVerificationResult signal_proto;
  signal_proto.set_is_compliant(is_compliant);
  signal_proto.set_error_str(error_str);
  signal_proto.set_is_skipped(is_skipped);
  for (auto& observer : observers_) {
    observer.HardwareVerificationResult(signal_proto);
  }
}

void RmadClientImpl::FinalizationProgressReceived(dbus::Signal* signal) {
  DCHECK_EQ(signal->GetMember(), rmad::kFinalizeProgressSignal);
  dbus::MessageReader reader(signal);
  // Read message
  dbus::MessageReader sub_reader(nullptr);
  if (!reader.PopStruct(&sub_reader)) {
    LOG(ERROR) << "Unable to decode signal for " << signal->GetMember();
    return;
  }
  DCHECK(!reader.HasMoreData());
  int32_t status;
  double progress;
  int32_t error;
  if (!sub_reader.PopInt32(&status) || !sub_reader.PopDouble(&progress) ||
      !sub_reader.PopInt32(&error)) {
    LOG(ERROR) << "Unable to decode signal for " << signal->GetMember();
    return;
  }
  rmad::FinalizeStatus signal_proto;
  signal_proto.set_status(static_cast<rmad::FinalizeStatus::Status>(status));
  signal_proto.set_progress(progress);
  signal_proto.set_error(static_cast<rmad::FinalizeStatus::Error>(error));
  for (auto& observer : observers_) {
    observer.FinalizationProgress(signal_proto);
  }
}

void RmadClientImpl::RoFirmwareUpdateProgressReceived(dbus::Signal* signal) {
  DCHECK_EQ(signal->GetMember(), rmad::kUpdateRoFirmwareStatusSignal);
  dbus::MessageReader reader(signal);
  // Read message
  int32_t status;
  if (!reader.PopInt32(&status)) {
    LOG(ERROR) << "Unable to decode signal for " << signal->GetMember();
    return;
  }
  DCHECK(!reader.HasMoreData());
  for (auto& observer : observers_) {
    observer.RoFirmwareUpdateProgress(
        static_cast<rmad::UpdateRoFirmwareStatus>(status));
  }
}

void RmadClientImpl::GetCurrentState(
    chromeos::DBusMethodCallback<rmad::GetStateReply> callback) {
  dbus::MethodCall method_call(rmad::kRmadInterfaceName,
                               rmad::kGetCurrentStateMethod);
  dbus::MessageWriter writer(&method_call);
  rmad_proxy_->CallMethod(
      &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
      base::BindOnce(&RmadClientImpl::OnProtoReply<rmad::GetStateReply>,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}

void RmadClientImpl::TransitionNextState(
    const rmad::RmadState& state,
    chromeos::DBusMethodCallback<rmad::GetStateReply> callback) {
  dbus::MethodCall method_call(rmad::kRmadInterfaceName,
                               rmad::kTransitionNextStateMethod);
  dbus::MessageWriter writer(&method_call);
  // Create the empty request proto.
  rmad::TransitionNextStateRequest protobuf_request;
  protobuf_request.set_allocated_state(new rmad::RmadState(state));
  if (!writer.AppendProtoAsArrayOfBytes(protobuf_request)) {
    LOG(ERROR) << "Error constructing message for "
               << rmad::kTransitionNextStateMethod;
    std::move(callback).Run(std::nullopt);
    return;
  }
  rmad_proxy_->CallMethod(
      &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
      base::BindOnce(&RmadClientImpl::OnProtoReply<rmad::GetStateReply>,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void RmadClientImpl::TransitionPreviousState(
    chromeos::DBusMethodCallback<rmad::GetStateReply> callback) {
  dbus::MethodCall method_call(rmad::kRmadInterfaceName,
                               rmad::kTransitionPreviousStateMethod);
  dbus::MessageWriter writer(&method_call);
  rmad_proxy_->CallMethod(
      &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
      base::BindOnce(&RmadClientImpl::OnProtoReply<rmad::GetStateReply>,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}

void RmadClientImpl::AbortRma(
    chromeos::DBusMethodCallback<rmad::AbortRmaReply> callback) {
  dbus::MethodCall method_call(rmad::kRmadInterfaceName, rmad::kAbortRmaMethod);
  dbus::MessageWriter writer(&method_call);
  rmad_proxy_->CallMethod(
      &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
      base::BindOnce(&RmadClientImpl::OnProtoReply<rmad::AbortRmaReply>,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}

void RmadClientImpl::GetLog(
    chromeos::DBusMethodCallback<rmad::GetLogReply> callback) {
  dbus::MethodCall method_call(rmad::kRmadInterfaceName, rmad::kGetLogMethod);
  dbus::MessageWriter writer(&method_call);
  rmad_proxy_->CallMethod(
      &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
      base::BindOnce(&RmadClientImpl::OnProtoReply<rmad::GetLogReply>,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}

void RmadClientImpl::SaveLog(
    const std::string& diagnostics_log_text,
    chromeos::DBusMethodCallback<rmad::SaveLogReply> callback) {
  dbus::MethodCall method_call(rmad::kRmadInterfaceName, rmad::kSaveLogMethod);
  dbus::MessageWriter writer(&method_call);
  writer.AppendString(diagnostics_log_text);
  rmad_proxy_->CallMethod(
      &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
      base::BindOnce(&RmadClientImpl::OnProtoReply<rmad::SaveLogReply>,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}

void RmadClientImpl::RecordBrowserActionMetric(
    const rmad::RecordBrowserActionMetricRequest request,
    chromeos::DBusMethodCallback<rmad::RecordBrowserActionMetricReply>
        callback) {
  dbus::MethodCall method_call(rmad::kRmadInterfaceName,
                               rmad::kRecordBrowserActionMetricMethod);
  dbus::MessageWriter writer(&method_call);

  if (!writer.AppendProtoAsArrayOfBytes(request)) {
    LOG(ERROR) << "Error constructing message for "
               << rmad::kRecordBrowserActionMetricMethod;
    std::move(callback).Run(std::nullopt);
    return;
  }

  rmad_proxy_->CallMethod(
      &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
      base::BindOnce(
          &RmadClientImpl::OnProtoReply<rmad::RecordBrowserActionMetricReply>,
          weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}

void RmadClientImpl::ExtractExternalDiagnosticsApp(
    chromeos::DBusMethodCallback<rmad::ExtractExternalDiagnosticsAppReply>
        callback) {
  dbus::MethodCall method_call(rmad::kRmadInterfaceName,
                               rmad::kExtractExternalDiagnosticsAppMethod);
  dbus::MessageWriter writer(&method_call);
  rmad_proxy_->CallMethod(
      &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
      base::BindOnce(&RmadClientImpl::OnProtoReply<
                         rmad::ExtractExternalDiagnosticsAppReply>,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}

void RmadClientImpl::InstallExtractedDiagnosticsApp(
    chromeos::DBusMethodCallback<rmad::InstallExtractedDiagnosticsAppReply>
        callback) {
  dbus::MethodCall method_call(rmad::kRmadInterfaceName,
                               rmad::kInstallExtractedDiagnosticsAppMethod);
  dbus::MessageWriter writer(&method_call);
  rmad_proxy_->CallMethod(
      &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
      base::BindOnce(&RmadClientImpl::OnProtoReply<
                         rmad::InstallExtractedDiagnosticsAppReply>,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}

void RmadClientImpl::GetInstalledDiagnosticsApp(
    chromeos::DBusMethodCallback<rmad::GetInstalledDiagnosticsAppReply>
        callback) {
  dbus::MethodCall method_call(rmad::kRmadInterfaceName,
                               rmad::kGetInstalledDiagnosticsAppMethod);
  dbus::MessageWriter writer(&method_call);
  rmad_proxy_->CallMethod(
      &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
      base::BindOnce(
          &RmadClientImpl::OnProtoReply<rmad::GetInstalledDiagnosticsAppReply>,
          weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}

void RmadClientImpl::AddObserver(Observer* observer) {
  // Currently there is only one observer (chromeos::ShimlessRmaService) and it
  // is added before any signals are expected, so there is no need to preserve
  // any signals and send them to new observers.
  CHECK(observer);
  observers_.AddObserver(observer);
}

void RmadClientImpl::RemoveObserver(Observer* observer) {
  observers_.RemoveObserver(observer);
}

bool RmadClientImpl::HasObserver(const Observer* observer) const {
  return observers_.HasObserver(observer);
}

template <class T>
void RmadClientImpl::OnProtoReply(chromeos::DBusMethodCallback<T> callback,
                                  dbus::Response* response) {
  if (!response) {
    LOG(ERROR) << "Error calling rmad function";
    std::move(callback).Run(std::nullopt);
    return;
  }

  dbus::MessageReader reader(response);
  T response_proto;
  if (!reader.PopArrayOfBytesAsProto(&response_proto)) {
    LOG(ERROR) << "Unable to decode response for " << response->GetMember();
    std::move(callback).Run(std::nullopt);
    return;
  }
  DCHECK(!reader.HasMoreData());

  std::move(callback).Run(std::move(response_proto));
}

void RmadClientImpl::StartCheckForRmadFiles() {
  base::FilePath rmad_executable_path;
  if (!base::PathService::Get(
          chromeos::dbus_paths::FILE_RMAD_SERVICE_EXECUTABLE,
          &rmad_executable_path)) {
    LOG(ERROR)
        << "Could not get rmad executable path. RMA will not be available";
    return;
  }
  base::FilePath rmad_state_file_path;
  if (!base::PathService::Get(chromeos::dbus_paths::FILE_RMAD_SERVICE_STATE,
                              &rmad_state_file_path)) {
    LOG(ERROR)
        << "Could not get rmad state file path. RMA will not be available";
    return;
  }

  base::ThreadPool::PostTaskAndReplyWithResult(
      FROM_HERE,
      {base::MayBlock(), base::TaskPriority::USER_VISIBLE,
       base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
      base::BindOnce(&base::PathExists, rmad_executable_path),
      base::BindOnce(&RmadClientImpl::OnFetchRmadExecutableExists,
                     weak_ptr_factory_.GetWeakPtr()));
  base::ThreadPool::PostTaskAndReplyWithResult(
      FROM_HERE,
      {base::MayBlock(), base::TaskPriority::USER_VISIBLE,
       base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
      base::BindOnce(&base::PathExists, rmad_state_file_path),
      base::BindOnce(&RmadClientImpl::OnFetchRmadStateFileExists,
                     weak_ptr_factory_.GetWeakPtr()));
}

void RmadClientImpl::OnFetchRmadExecutableExists(bool exists) {
  rma_executable_exists_ = exists;
}

void RmadClientImpl::OnFetchRmadStateFileExists(bool exists) {
  rma_state_file_exists_ = exists;
}

bool RmadClientImpl::WasRmaStateDetected() {
  if (!rma_executable_exists_.has_value()) {
    LOG(WARNING) << "Checking if RMA executable exists not completed before "
                    "WasRmaStateDetected() called.";
  }
  if (!rma_state_file_exists_.has_value()) {
    LOG(WARNING) << "Checking if RMA state file exists not completed before "
                    "WasRmaStateDetected() called.";
  }

  // TODO(b/230924565): Remove LOG statement after feature release.
  VLOG(1) << "RmadClientImpl::WasRmaStateDetected rma_executable_exists_: "
          << rma_executable_exists_.value_or(false)
          << " is_rma_required_: " << is_rma_required_
          << " rma_state_file_exists_: "
          << rma_state_file_exists_.value_or(false);

  return rma_executable_exists_.value_or(false) &&
         (is_rma_required_ || rma_state_file_exists_.value_or(false));
}

void RmadClientImpl::SetRmaRequiredCallbackForSessionManager(
    base::OnceClosure session_manager_callback) {
  if (WasRmaStateDetected()) {
    std::move(session_manager_callback).Run();
  } else {
    session_manager_callback_ = std::move(session_manager_callback);
  }
}

RmadClient::RmadClient() {
  CHECK(!g_instance);
  g_instance = this;
}

RmadClient::~RmadClient() {
  CHECK_EQ(this, g_instance);
  g_instance = nullptr;
}

// static
void RmadClient::Initialize(dbus::Bus* bus) {
  CHECK(bus);
  (new RmadClientImpl())->Init(bus);
}

// static
void RmadClient::Shutdown() {
  CHECK(g_instance);
  delete g_instance;
}

// static
RmadClient* RmadClient::Get() {
  return g_instance;
}

// static
void RmadClient::InitializeFake() {
  // Do not create a new fake if it was initialized early in a browser test (for
  // early setup calls dependent on RmadClient).
  if (!FakeRmadClient::Get()) {
    new FakeRmadClient();
  }
}

}  // namespace ash