File: device_command_run_routine_job.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (656 lines) | stat: -rw-r--r-- 29,295 bytes parent folder | download | duplicates (3)
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
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ash/policy/remote_commands/device_command_run_routine_job.h"

#include <memory>
#include <optional>
#include <string>
#include <type_traits>
#include <utility>

#include "base/functional/bind.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/notimplemented.h"
#include "base/notreached.h"
#include "base/numerics/safe_conversions.h"
#include "base/syslog_logging.h"
#include "base/task/single_thread_task_runner.h"
#include "base/time/time.h"
#include "base/values.h"
#include "chromeos/ash/services/cros_healthd/public/cpp/service_connection.h"
#include "chromeos/ash/services/cros_healthd/public/mojom/nullable_primitives.mojom.h"
#include "components/policy/proto/device_management_backend.pb.h"

namespace policy {

namespace em = enterprise_management;

namespace {

// String constant identifying the id field in the result payload.
constexpr char kIdFieldName[] = "id";
// String constant identifying the status field in the result payload.
constexpr char kStatusFieldName[] = "status";

// String constant identifying the routine enum field in the command payload.
constexpr char kRoutineEnumFieldName[] = "routineEnum";
// String constant identifying the parameter dictionary field in the command
// payload.
constexpr char kParamsFieldName[] = "params";

// Returns a RunRoutineResponse with an id of kFailedToStartId and a status of
// kFailedToStart.
ash::cros_healthd::mojom::RunRoutineResponsePtr
MakeInvalidParametersResponse() {
  return ash::cros_healthd::mojom::RunRoutineResponse::New(
      ash::cros_healthd::mojom::kFailedToStartId,
      ash::cros_healthd::mojom::DiagnosticRoutineStatusEnum::kFailedToStart);
}

template <typename T>
bool PopulateMojoEnumValueIfValid(int possible_enum, T* valid_enum_out) {
  DCHECK(valid_enum_out);
  if (!base::IsValueInRangeForNumericType<
          typename std::underlying_type<T>::type>(possible_enum)) {
    return false;
  }
  T enum_to_check = static_cast<T>(possible_enum);
  if (!ash::cros_healthd::mojom::IsKnownEnumValue(enum_to_check)) {
    return false;
  }
  *valid_enum_out = enum_to_check;
  return true;
}

std::string CreatePayload(
    ash::cros_healthd::mojom::RunRoutineResponsePtr response) {
  auto root_dict =
      base::Value::Dict()
          .Set(kIdFieldName, response->id)
          .Set(kStatusFieldName, static_cast<int>(response->status));

  std::string payload;
  base::JSONWriter::Write(root_dict, &payload);
  return payload;
}
}  // namespace

// static
constexpr char DeviceCommandRunRoutineJob::kStunServerHostnameFieldName[];

DeviceCommandRunRoutineJob::DeviceCommandRunRoutineJob() = default;

DeviceCommandRunRoutineJob::~DeviceCommandRunRoutineJob() = default;

em::RemoteCommand_Type DeviceCommandRunRoutineJob::GetType() const {
  return em::RemoteCommand_Type_DEVICE_RUN_DIAGNOSTIC_ROUTINE;
}

bool DeviceCommandRunRoutineJob::ParseCommandPayload(
    const std::string& command_payload) {
  std::optional<base::Value::Dict> root =
      base::JSONReader::ReadDict(command_payload);
  if (!root) {
    return false;
  }

  // Make sure the command payload specified a valid DiagnosticRoutineEnum.
  std::optional<int> routine_enum = root->FindInt(kRoutineEnumFieldName);
  if (!routine_enum.has_value()) {
    return false;
  }
  if (!PopulateMojoEnumValueIfValid(routine_enum.value(), &routine_enum_)) {
    SYSLOG(ERROR) << "Unknown DiagnosticRoutineEnum in command payload: "
                  << routine_enum.value();
    return false;
  }

  // Make sure there's a dictionary with parameter values for the routine.
  // Validation of routine-specific parameters will be done before running the
  // routine, so here we just check that any dictionary was given to us.
  auto* params_dict = root->FindDict(kParamsFieldName);
  if (!params_dict) {
    return false;
  }
  params_dict_ = std::move(*params_dict);

  return true;
}

void DeviceCommandRunRoutineJob::RunImpl(CallbackWithResult result_callback) {
  SYSLOG(INFO) << "Executing RunRoutine command with DiagnosticRoutineEnum "
               << routine_enum_;
  auto* diagnostics_service =
      ash::cros_healthd::ServiceConnection::GetInstance()
          ->GetDiagnosticsService();

  switch (routine_enum_) {
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kUnknown: {
      NOTREACHED() << "This default value should not be used.";
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kBatteryCapacity: {
      diagnostics_service->RunBatteryCapacityRoutine(base::BindOnce(
          &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
          weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kBatteryHealth: {
      diagnostics_service->RunBatteryHealthRoutine(base::BindOnce(
          &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
          weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kUrandom: {
      constexpr char kLengthSecondsFieldName[] = "lengthSeconds";
      std::optional<int> length_seconds =
          params_dict_.FindInt(kLengthSecondsFieldName);
      ash::cros_healthd::mojom::NullableUint32Ptr routine_duration;
      if (length_seconds.has_value()) {
        // If the optional integer parameter is specified, it must be >= 0.
        int value = length_seconds.value();
        if (value < 0) {
          SYSLOG(ERROR) << "Invalid parameters for Urandom routine.";
          base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
              FROM_HERE,
              base::BindOnce(std::move(result_callback), ResultType::kFailure,
                             CreatePayload(MakeInvalidParametersResponse())));
          break;
        }
        routine_duration = ash::cros_healthd::mojom::NullableUint32::New(value);
      }
      diagnostics_service->RunUrandomRoutine(
          std::move(routine_duration),
          base::BindOnce(
              &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
              weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kSmartctlCheck: {
      diagnostics_service->RunSmartctlCheckRoutine(
          ash::cros_healthd::mojom::NullableUint32Ptr(),
          base::BindOnce(
              &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
              weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::
        kSmartctlCheckWithPercentageUsed: {
      constexpr char kPercentageUsedThresholdFieldName[] =
          "percentageUsedThreshold";
      std::optional<int> percentage_used_threshold =
          params_dict_.FindInt(kPercentageUsedThresholdFieldName);
      ash::cros_healthd::mojom::NullableUint32Ptr input_threshold;
      // The smartctl check routine expects one optional integer >= 0.
      if (percentage_used_threshold.has_value()) {
        // If the optional integer parameter is specified, it must be [0, 255].
        int value = percentage_used_threshold.value();
        if (value < 0 || value > 255) {
          SYSLOG(ERROR) << "Invalid parameters for smartctl check routine.";
          base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
              FROM_HERE,
              base::BindOnce(std::move(result_callback), ResultType::kFailure,
                             CreatePayload(MakeInvalidParametersResponse())));
          break;
        }
        input_threshold = ash::cros_healthd::mojom::NullableUint32::New(value);
      }
      diagnostics_service->RunSmartctlCheckRoutine(
          std::move(input_threshold),
          base::BindOnce(
              &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
              weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kAcPower: {
      constexpr char kExpectedStatusFieldName[] = "expectedStatus";
      // Note that expectedPowerType is an optional parameter.
      constexpr char kExpectedPowerTypeFieldName[] = "expectedPowerType";
      std::optional<int> expected_status =
          params_dict_.FindInt(kExpectedStatusFieldName);
      std::string* expected_power_type =
          params_dict_.FindString(kExpectedPowerTypeFieldName);
      ash::cros_healthd::mojom::AcPowerStatusEnum expected_status_enum;
      // The AC power routine expects a valid ACPowerStatusEnum, and optionally
      // a string.
      if (!expected_status.has_value() ||
          !PopulateMojoEnumValueIfValid(expected_status.value(),
                                        &expected_status_enum)) {
        SYSLOG(ERROR) << "Invalid parameters for AC Power routine.";
        base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
            FROM_HERE,
            base::BindOnce(std::move(result_callback), ResultType::kFailure,
                           CreatePayload(MakeInvalidParametersResponse())));
        break;
      }
      diagnostics_service->RunAcPowerRoutine(
          expected_status_enum,
          expected_power_type ? std::optional<std::string>(*expected_power_type)
                              : std::nullopt,
          base::BindOnce(
              &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
              weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kCpuCache: {
      constexpr char kLengthSecondsFieldName[] = "lengthSeconds";
      std::optional<int> length_seconds =
          params_dict_.FindInt(kLengthSecondsFieldName);
      ash::cros_healthd::mojom::NullableUint32Ptr routine_duration;
      if (length_seconds.has_value()) {
        // If the optional integer parameter is specified, it must be >= 0.
        int value = length_seconds.value();
        if (value < 0) {
          SYSLOG(ERROR) << "Invalid parameters for CPU cache routine.";
          base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
              FROM_HERE,
              base::BindOnce(std::move(result_callback), ResultType::kFailure,
                             CreatePayload(MakeInvalidParametersResponse())));
          break;
        }
        routine_duration = ash::cros_healthd::mojom::NullableUint32::New(value);
      }
      diagnostics_service->RunCpuCacheRoutine(
          std::move(routine_duration),
          base::BindOnce(
              &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
              weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kCpuStress: {
      constexpr char kLengthSecondsFieldName[] = "lengthSeconds";
      std::optional<int> length_seconds =
          params_dict_.FindInt(kLengthSecondsFieldName);
      ash::cros_healthd::mojom::NullableUint32Ptr routine_duration;
      if (length_seconds.has_value()) {
        // If the optional integer parameter is specified, it must be >= 0.
        int value = length_seconds.value();
        if (value < 0) {
          SYSLOG(ERROR) << "Invalid parameters for CPU stress routine.";
          base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
              FROM_HERE,
              base::BindOnce(std::move(result_callback), ResultType::kFailure,
                             CreatePayload(MakeInvalidParametersResponse())));
          break;
        }
        routine_duration = ash::cros_healthd::mojom::NullableUint32::New(value);
      }
      diagnostics_service->RunCpuStressRoutine(
          std::move(routine_duration),
          base::BindOnce(
              &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
              weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::
        kFloatingPointAccuracy: {
      constexpr char kLengthSecondsFieldName[] = "lengthSeconds";
      std::optional<int> length_seconds =
          params_dict_.FindInt(kLengthSecondsFieldName);
      ash::cros_healthd::mojom::NullableUint32Ptr routine_duration;
      if (length_seconds.has_value()) {
        // If the optional integer parameter is specified, it must be >= 0.
        int value = length_seconds.value();
        if (value < 0) {
          SYSLOG(ERROR)
              << "Invalid parameters for floating point accuracy routine.";
          base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
              FROM_HERE,
              base::BindOnce(std::move(result_callback), ResultType::kFailure,
                             CreatePayload(MakeInvalidParametersResponse())));
          break;
        }
        routine_duration = ash::cros_healthd::mojom::NullableUint32::New(value);
      }
      diagnostics_service->RunFloatingPointAccuracyRoutine(
          std::move(routine_duration),
          base::BindOnce(
              &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
              weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::
        DEPRECATED_kNvmeWearLevel: {
      NOTIMPLEMENTED();
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kNvmeSelfTest: {
      constexpr char kNvmeSelfTestTypeFieldName[] = "nvmeSelfTestType";
      std::optional<int> nvme_self_test_type =
          params_dict_.FindInt(kNvmeSelfTestTypeFieldName);
      ash::cros_healthd::mojom::NvmeSelfTestTypeEnum nvme_self_test_type_enum;
      // The NVMe self-test routine expects a valid NvmeSelfTestTypeEnum.
      if (!nvme_self_test_type.has_value() ||
          !PopulateMojoEnumValueIfValid(nvme_self_test_type.value(),
                                        &nvme_self_test_type_enum)) {
        SYSLOG(ERROR) << "Invalid parameters for NVMe self-test routine.";
        base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
            FROM_HERE,
            base::BindOnce(std::move(result_callback), ResultType::kFailure,
                           CreatePayload(MakeInvalidParametersResponse())));
        break;
      }
      diagnostics_service->RunNvmeSelfTestRoutine(
          nvme_self_test_type_enum,
          base::BindOnce(
              &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
              weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kDiskRead: {
      constexpr char kTypeFieldName[] = "type";
      constexpr char kLengthSecondsFieldName[] = "lengthSeconds";
      constexpr char kFileSizeMbFieldName[] = "fileSizeMb";
      std::optional<int> type = params_dict_.FindInt(kTypeFieldName);
      std::optional<int> length_seconds =
          params_dict_.FindInt(kLengthSecondsFieldName);
      std::optional<int> file_size_mb =
          params_dict_.FindInt(kFileSizeMbFieldName);
      ash::cros_healthd::mojom::DiskReadRoutineTypeEnum type_enum;
      if (!length_seconds.has_value() || length_seconds.value() < 0 ||
          !file_size_mb.has_value() || file_size_mb.value() < 0 ||
          !type.has_value() ||
          !PopulateMojoEnumValueIfValid(type.value(), &type_enum)) {
        SYSLOG(ERROR) << "Invalid parameters for disk read routine.";
        base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
            FROM_HERE,
            base::BindOnce(std::move(result_callback), ResultType::kFailure,
                           CreatePayload(MakeInvalidParametersResponse())));
        break;
      }
      diagnostics_service->RunDiskReadRoutine(
          type_enum, length_seconds.value(), file_size_mb.value(),
          base::BindOnce(
              &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
              weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kPrimeSearch: {
      constexpr char kLengthSecondsFieldName[] = "lengthSeconds";
      std::optional<int> length_seconds =
          params_dict_.FindInt(kLengthSecondsFieldName);
      ash::cros_healthd::mojom::NullableUint32Ptr routine_duration;
      if (length_seconds.has_value()) {
        // If the optional integer parameter is specified, it must be >= 0.
        int value = length_seconds.value();
        if (value < 0) {
          SYSLOG(ERROR) << "Invalid parameters for prime search routine.";
          base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
              FROM_HERE,
              base::BindOnce(std::move(result_callback), ResultType::kFailure,
                             CreatePayload(MakeInvalidParametersResponse())));
          break;
        }
        routine_duration = ash::cros_healthd::mojom::NullableUint32::New(value);
      }
      diagnostics_service->RunPrimeSearchRoutine(
          std::move(routine_duration),
          base::BindOnce(
              &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
              weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kBatteryDischarge: {
      constexpr char kLengthSecondsFieldName[] = "lengthSeconds";
      constexpr char kMaximumDischargePercentAllowedFieldName[] =
          "maximumDischargePercentAllowed";
      std::optional<int> length_seconds =
          params_dict_.FindInt(kLengthSecondsFieldName);
      std::optional<int> maximum_discharge_percent_allowed =
          params_dict_.FindInt(kMaximumDischargePercentAllowedFieldName);
      // The battery discharge routine expects two integers >= 0.
      if (!length_seconds.has_value() ||
          !maximum_discharge_percent_allowed.has_value() ||
          length_seconds.value() < 0 ||
          maximum_discharge_percent_allowed.value() < 0) {
        SYSLOG(ERROR) << "Invalid parameters for BatteryDischarge routine.";
        base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
            FROM_HERE,
            base::BindOnce(std::move(result_callback), ResultType::kFailure,
                           CreatePayload(MakeInvalidParametersResponse())));
        break;
      }
      diagnostics_service->RunBatteryDischargeRoutine(
          length_seconds.value(), maximum_discharge_percent_allowed.value(),
          base::BindOnce(
              &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
              weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kBatteryCharge: {
      constexpr char kLengthSecondsFieldName[] = "lengthSeconds";
      constexpr char kMinimumChargePercentRequiredFieldName[] =
          "minimumChargePercentRequired";
      std::optional<int> length_seconds =
          params_dict_.FindInt(kLengthSecondsFieldName);
      std::optional<int> minimum_charge_percent_required =
          params_dict_.FindInt(kMinimumChargePercentRequiredFieldName);
      // The battery charge routine expects two integers >= 0.
      if (!length_seconds.has_value() ||
          !minimum_charge_percent_required.has_value() ||
          length_seconds.value() < 0 ||
          minimum_charge_percent_required.value() < 0) {
        SYSLOG(ERROR) << "Invalid parameters for BatteryCharge routine.";
        base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
            FROM_HERE,
            base::BindOnce(std::move(result_callback), ResultType::kFailure,
                           CreatePayload(MakeInvalidParametersResponse())));
        break;
      }
      diagnostics_service->RunBatteryChargeRoutine(
          length_seconds.value(), minimum_charge_percent_required.value(),
          base::BindOnce(
              &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
              weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kMemory: {
      diagnostics_service->RunMemoryRoutine(
          std::nullopt,
          base::BindOnce(
              &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
              weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kLanConnectivity: {
      diagnostics_service->RunLanConnectivityRoutine(base::BindOnce(
          &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
          weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kSignalStrength: {
      diagnostics_service->RunSignalStrengthRoutine(base::BindOnce(
          &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
          weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kGatewayCanBePinged: {
      diagnostics_service->RunGatewayCanBePingedRoutine(base::BindOnce(
          &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
          weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::
        kHasSecureWiFiConnection: {
      diagnostics_service->RunHasSecureWiFiConnectionRoutine(base::BindOnce(
          &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
          weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kDnsResolverPresent: {
      diagnostics_service->RunDnsResolverPresentRoutine(base::BindOnce(
          &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
          weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kDnsLatency: {
      diagnostics_service->RunDnsLatencyRoutine(base::BindOnce(
          &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
          weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kDnsResolution: {
      diagnostics_service->RunDnsResolutionRoutine(base::BindOnce(
          &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
          weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kCaptivePortal: {
      diagnostics_service->RunCaptivePortalRoutine(base::BindOnce(
          &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
          weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kHttpFirewall: {
      diagnostics_service->RunHttpFirewallRoutine(base::BindOnce(
          &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
          weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kHttpsFirewall: {
      diagnostics_service->RunHttpsFirewallRoutine(base::BindOnce(
          &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
          weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kHttpsLatency: {
      diagnostics_service->RunHttpsLatencyRoutine(base::BindOnce(
          &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
          weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kVideoConferencing: {
      std::string* stun_server_hostname =
          params_dict_.FindString(kStunServerHostnameFieldName);
      diagnostics_service->RunVideoConferencingRoutine(
          stun_server_hostname
              ? std::make_optional<std::string>(*stun_server_hostname)
              : std::nullopt,
          base::BindOnce(
              &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
              weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kArcHttp: {
      diagnostics_service->RunArcHttpRoutine(base::BindOnce(
          &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
          weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kArcPing: {
      diagnostics_service->RunArcPingRoutine(base::BindOnce(
          &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
          weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kArcDnsResolution: {
      diagnostics_service->RunArcDnsResolutionRoutine(base::BindOnce(
          &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
          weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kSensitiveSensor: {
      diagnostics_service->RunSensitiveSensorRoutine(base::BindOnce(
          &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
          weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kFingerprint: {
      diagnostics_service->RunFingerprintRoutine(base::BindOnce(
          &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
          weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kFingerprintAlive: {
      diagnostics_service->RunFingerprintAliveRoutine(base::BindOnce(
          &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
          weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kPrivacyScreen: {
      constexpr char kPrivacyScreenTargetState[] = "targetState";
      std::optional<bool> target_state =
          params_dict_.FindBool(kPrivacyScreenTargetState);
      diagnostics_service->RunPrivacyScreenRoutine(
          target_state.value_or(true),
          base::BindOnce(
              &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
              weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::
        DEPRECATED_kLedLitUp: {
      NOTIMPLEMENTED();
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kEmmcLifetime: {
      diagnostics_service->RunEmmcLifetimeRoutine(base::BindOnce(
          &DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived,
          weak_ptr_factory_.GetWeakPtr(), std::move(result_callback)));
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::
        DEPRECATED_kAudioSetVolume: {
      NOTIMPLEMENTED();
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::
        DEPRECATED_kAudioSetGain: {
      NOTIMPLEMENTED();
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kBluetoothPower: {
      NOTIMPLEMENTED();
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kBluetoothDiscovery: {
      NOTIMPLEMENTED();
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kBluetoothScanning: {
      NOTIMPLEMENTED();
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kBluetoothPairing: {
      NOTIMPLEMENTED();
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kPowerButton: {
      NOTIMPLEMENTED();
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kAudioDriver: {
      NOTIMPLEMENTED();
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kUfsLifetime: {
      NOTIMPLEMENTED();
      break;
    }
    case ash::cros_healthd::mojom::DiagnosticRoutineEnum::kFan: {
      NOTIMPLEMENTED();
      break;
    }
  }
}

void DeviceCommandRunRoutineJob::OnCrosHealthdResponseReceived(
    CallbackWithResult result_callback,
    ash::cros_healthd::mojom::RunRoutineResponsePtr response) {
  if (!response) {
    SYSLOG(ERROR) << "No RunRoutineResponse received from cros_healthd.";
    base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE, base::BindOnce(std::move(result_callback),
                                  ResultType::kFailure, std::nullopt));
    return;
  }

  base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
      FROM_HERE,
      base::BindOnce(std::move(result_callback), ResultType::kSuccess,
                     CreatePayload(std::move(response))));
}

}  // namespace policy