File: bruschetta_launcher.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 (239 lines) | stat: -rw-r--r-- 8,324 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
// Copyright 2022 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/bruschetta/bruschetta_launcher.h"

#include <memory>
#include <optional>

#include "base/functional/callback.h"
#include "base/logging.h"
#include "base/memory/weak_ptr.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/strcat.h"
#include "base/task/sequenced_task_runner.h"
#include "base/time/time.h"
#include "chrome/browser/ash/bruschetta/bruschetta_service.h"
#include "chrome/browser/ash/bruschetta/bruschetta_service_factory.h"
#include "chrome/browser/ash/bruschetta/bruschetta_util.h"
#include "chrome/browser/ash/guest_os/guest_os_dlc_helper.h"
#include "chrome/browser/ash/guest_os/guest_os_pref_names.h"
#include "chrome/browser/ash/guest_os/guest_os_session_tracker.h"
#include "chrome/browser/ash/guest_os/guest_os_session_tracker_factory.h"
#include "chrome/browser/ash/guest_os/public/types.h"
#include "chrome/browser/ash/profiles/profile_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chromeos/ash/components/dbus/concierge/concierge_client.h"
#include "chromeos/ash/components/dbus/vm_concierge/concierge_service.pb.h"
#include "content/public/browser/browser_thread.h"

namespace bruschetta {

namespace {

// TODO(b/233289313): Once we have an installer and multiple Bruschettas this
// needs to be dynamic, but for now we hardcode the same path that the go/brua
// instructions have people using for the alpha, and the same disk name that
// people following the instructions will have (base64 encoded "bru").
const char kDiskName[] = "YnJ1.img";

}  // namespace

// Wrapper class for dispatching `OnTimeout` calls so we can cancel the timeout
// by destroying the wrapper instance.
class BruschettaLauncher::Timeout {
 public:
  explicit Timeout(BruschettaLauncher* launcher) : launcher_(launcher) {}
  void OnTimeout() { launcher_->OnTimeout(); }

  // BruschettaLauncher owns us so it will always outlive us, hence raw_ptr is
  // fine.
  raw_ptr<BruschettaLauncher> launcher_;

  // Must be last.
  base::WeakPtrFactory<Timeout> weak_factory_{this};
};

BruschettaLauncher::BruschettaLauncher(std::string vm_name, Profile* profile)
    : vm_name_(vm_name), profile_(profile) {}
BruschettaLauncher::~BruschettaLauncher() = default;

void BruschettaLauncher::EnsureRunning(
    base::OnceCallback<void(BruschettaResult)> callback) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  bool launch_in_progress = false;
  if (!callbacks_.empty()) {
    launch_in_progress = true;
  }
  callbacks_.AddUnsafe(std::move(callback));
  if (!launch_in_progress) {
    EnsureToolsDlcInstalled();
    timeout_ = std::make_unique<Timeout>(this);
    // If we're not complete after 4 minutes time out the entire launch.
    base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
        FROM_HERE,
        base::BindOnce(&BruschettaLauncher::Timeout::OnTimeout,
                       timeout_->weak_factory_.GetWeakPtr()),
        base::Seconds(240));
  }
}

void BruschettaLauncher::EnsureToolsDlcInstalled() {
  in_progress_dlc_ = std::make_unique<guest_os::GuestOsDlcInstallation>(
      kToolsDlc,
      base::BindOnce(&BruschettaLauncher::OnMountToolsDlc,
                     weak_factory_.GetWeakPtr()),
      base::DoNothing());
}

void BruschettaLauncher::OnMountToolsDlc(
    guest_os::GuestOsDlcInstallation::Result install_result) {
  in_progress_dlc_.reset();
  if (!install_result.has_value()) {
    LOG(ERROR) << "Error installing tools DLC: " << install_result.error();
    Finish(BruschettaResult::kDlcInstallError);
    return;
  }

  EnsureFirmwareDlcInstalled();
}

void BruschettaLauncher::EnsureFirmwareDlcInstalled() {
  in_progress_dlc_ = std::make_unique<guest_os::GuestOsDlcInstallation>(
      kUefiDlc,
      base::BindOnce(&BruschettaLauncher::OnMountFirmwareDlc,
                     weak_factory_.GetWeakPtr()),
      base::DoNothing());
}

void BruschettaLauncher::OnMountFirmwareDlc(
    guest_os::GuestOsDlcInstallation::Result install_result) {
  if (!install_result.has_value()) {
    LOG(ERROR) << "Error installing firmware DLC: " << install_result.error();
    Finish(BruschettaResult::kDlcInstallError);
    return;
  }

  EnsureConciergeAvailable();
}

void BruschettaLauncher::EnsureConciergeAvailable() {
  auto* client = ash::ConciergeClient::Get();
  if (!client) {
    LOG(ERROR) << "Error connecting to concierge. Client is NULL.";
    Finish(BruschettaResult::kConciergeUnavailable);
    return;
  }

  client->WaitForServiceToBeAvailable(base::BindOnce(
      &BruschettaLauncher::OnConciergeAvailable, weak_factory_.GetWeakPtr()));
}

void BruschettaLauncher::OnConciergeAvailable(bool service_is_available) {
  if (!service_is_available) {
    LOG(ERROR) << "Error connecting to concierge. Service is not available.";
    Finish(BruschettaResult::kConciergeUnavailable);
    return;
  }

  StartVm();
}

void BruschettaLauncher::StartVm() {
  auto* client = ash::ConciergeClient::Get();
  if (!client) {
    LOG(ERROR) << "Error connecting to concierge. Client is NULL.";
    Finish(BruschettaResult::kStartVmFailed);
    return;
  }

  const std::string config_id =
      GetContainerPrefValue(profile_, MakeBruschettaId(vm_name_),
                            guest_os::prefs::kBruschettaConfigId)
          ->GetString();
  RunningVmPolicy launch_policy;
  auto opt = GetLaunchPolicyForConfig(profile_, config_id);
  if (!opt.has_value()) {
    // Policy prohibits starting the VM, so don't.
    LOG(ERROR) << "Starting VM prohibited by policy";
    Finish(BruschettaResult::kForbiddenByPolicy);
    return;
  } else {
    launch_policy = *opt;
  }

  std::string user_hash =
      ash::ProfileHelper::GetUserIdHashFromProfile(profile_);
  std::string vm_username = GetVmUsername(profile_);
  vm_tools::concierge::StartVmRequest request;
  request.set_start_termina(false);
  request.set_name(vm_name_);
  request.mutable_vm()->set_tools_dlc_id(kToolsDlc);
  request.mutable_vm()->set_bios_dlc_id(kUefiDlc);
  request.set_owner_id(user_hash);
  request.set_vm_username(vm_username);
  request.set_start_termina(false);
  request.set_timeout(240);
  request.set_vtpm_proxy(launch_policy.vtpm_enabled);

  auto* disk = request.mutable_disks()->Add();
  *disk->mutable_path() =
      base::StrCat({"/run/daemon-store/crosvm/", user_hash, "/", kDiskName});
  disk->set_writable(true);
  disk->set_do_mount(false);

  client->StartVm(request,
                  base::BindOnce(&BruschettaLauncher::OnStartVm,
                                 weak_factory_.GetWeakPtr(), launch_policy));
}

void BruschettaLauncher::OnStartVm(
    RunningVmPolicy launch_policy,
    std::optional<vm_tools::concierge::StartVmResponse> response) {
  if (!response || !response->success()) {
    if (response) {
      LOG(ERROR) << "Error starting VM, got status: " << response->status()
                 << " and reason " << response->failure_reason();
    } else {
      LOG(ERROR) << "Error starting VM: no response from Concierge";
    }
    Finish(BruschettaResult::kStartVmFailed);
    return;
  }

  BruschettaServiceFactory::GetForProfile(profile_)->RegisterVmLaunch(
      vm_name_, launch_policy);

  auto* tracker =
      guest_os::GuestOsSessionTrackerFactory::GetForProfile(profile_);
  subscription_ = tracker->RunOnceContainerStarted(
      guest_os::GuestId{guest_os::VmType::BRUSCHETTA, vm_name_, "penguin"},
      base::BindOnce(&BruschettaLauncher::OnContainerRunning,
                     weak_factory_.GetWeakPtr()));
}

void BruschettaLauncher::OnContainerRunning(guest_os::GuestInfo info) {
  Finish(BruschettaResult::kSuccess);
}

void BruschettaLauncher::OnTimeout() {
  subscription_.reset();
  Finish(BruschettaResult::kTimeout);

  // We don't actually abort or cancel the launch, let it keep going in the
  // background in case it's really slow for some reason then the next time they
  // try it might succeed.
}

void BruschettaLauncher::Finish(BruschettaResult result) {
  base::UmaHistogramEnumeration("Bruschetta.LaunchResult", result);
  callbacks_.Notify(result);
  timeout_.reset();
}

base::WeakPtr<BruschettaLauncher> BruschettaLauncher::GetWeakPtr() {
  return weak_factory_.GetWeakPtr();
}

}  // namespace bruschetta