installer/
lib.rs

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
// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

//! # Installer library
//!
//! The installer library exposes functionality to install Fuchsia to a disk by copying images from
//! one block device to another. The primary use case is an installer USB, which contains the images
//! to write to persistent storage.

pub mod partition;

use anyhow::{anyhow, Context, Error};
use fidl::endpoints::{Proxy, ServerEnd};
use fidl_fuchsia_hardware_power_statecontrol::{AdminMarker, RebootReason};
use fidl_fuchsia_paver::{
    BootManagerMarker, Configuration, DynamicDataSinkProxy, PaverMarker, PaverProxy,
};
use fidl_fuchsia_sysinfo::SysInfoMarker;
use fuchsia_component::client;

use partition::Partition;
use recovery_util_block::BlockDevice;
use std::sync::Mutex;

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum BootloaderType {
    Efi,
    Coreboot,
}

#[derive(Clone, Debug, PartialEq)]
pub struct InstallationPaths {
    pub install_source: Option<BlockDevice>,
    pub install_target: Option<BlockDevice>,
    pub bootloader_type: Option<BootloaderType>,
    pub install_destinations: Vec<BlockDevice>,
    pub available_disks: Vec<BlockDevice>,
}

impl InstallationPaths {
    pub fn new() -> InstallationPaths {
        InstallationPaths {
            install_source: None,
            install_target: None,
            bootloader_type: None,
            install_destinations: Vec::new(),
            available_disks: Vec::new(),
        }
    }
}

pub async fn find_install_source(
    block_devices: &Vec<BlockDevice>,
    bootloader: BootloaderType,
) -> Result<&BlockDevice, Error> {
    let mut candidate = Err(anyhow!("Could not find the installer disk. Is it plugged in?"));
    for device in block_devices.iter().filter(|d| d.is_disk()) {
        // get_partitions returns an empty vector if it doesn't find any partitions
        // with the workstation-installer GUID on the disk.
        let partitions = Partition::get_partitions(device, block_devices, bootloader).await?;
        if !partitions.is_empty() {
            if candidate.is_err() {
                candidate = Ok(device);
            } else {
                return Err(anyhow!(
                    "Please check you only have one installation disk plugged in!"
                ));
            }
        }
    }
    candidate
}

fn paver_connect() -> Result<(PaverProxy, DynamicDataSinkProxy), Error> {
    let (data_sink_chan, data_remote) = zx::Channel::create();
    let paver: PaverProxy =
        client::connect_to_protocol::<PaverMarker>().context("Could not connect to paver")?;
    paver.find_partition_table_manager(ServerEnd::from(data_remote))?;

    let data_sink =
        DynamicDataSinkProxy::from_channel(fidl::AsyncChannel::from_channel(data_sink_chan));
    Ok((paver, data_sink))
}

pub async fn get_bootloader_type() -> Result<BootloaderType, Error> {
    let proxy = fuchsia_component::client::connect_to_protocol::<SysInfoMarker>()
        .context("Could not connect to 'fuchsia.sysinfo.SysInfo' service")?;
    let (status, bootloader) =
        proxy.get_bootloader_vendor().await.context("Getting bootloader vendor")?;
    if let Some(bootloader) = bootloader {
        tracing::info!("Bootloader vendor = {}", bootloader);
        if bootloader == "coreboot" {
            Ok(BootloaderType::Coreboot)
        } else {
            // The installer only supports coreboot and EFI,
            // and EFI BIOS vendor depends on the manufacturer,
            // so we assume that non-coreboot bootloader vendors
            // mean EFI.
            Ok(BootloaderType::Efi)
        }
    } else {
        Err(Error::new(zx::Status::from_raw(status)))
    }
}

/// Restart the machine.
pub async fn restart() {
    let proxy = fuchsia_component::client::connect_to_protocol::<AdminMarker>()
        .expect("Could not connect to 'fuchsia.hardware.power.statecontrol.Admin' service");

    proxy
        .reboot(RebootReason::UserRequest)
        .await
        .expect("Failed to reboot")
        .expect("Failed to reboot");
}

/// Set the active boot configuration for the newly-installed system. We always boot from the "A"
/// slot to start with.
async fn set_active_configuration(paver: &PaverProxy) -> Result<(), Error> {
    let (boot_manager, server) = fidl::endpoints::create_proxy::<BootManagerMarker>();

    paver.find_boot_manager(server).context("Could not find boot manager")?;

    zx::Status::ok(
        boot_manager
            .set_configuration_active(Configuration::A)
            .await
            .context("Sending set configuration active")?,
    )
    .context("Setting active configuration")?;

    zx::Status::ok(boot_manager.flush().await.context("Sending boot manager flush")?)
        .context("Flushing active configuration")
}

pub async fn do_install<F>(
    installation_paths: InstallationPaths,
    progress_callback: &F,
) -> Result<(), Error>
where
    F: Send + Sync + Fn(String),
{
    if installation_paths.install_target.is_some() {
        tracing::warn!("Ignoring install target; this will be removed in the future.");
    }
    let install_source =
        installation_paths.install_source.ok_or_else(|| anyhow!("No installation source?"))?;
    let bootloader_type = installation_paths.bootloader_type.unwrap();

    let (paver, data_sink) = paver_connect().context("Could not contact paver")?;

    tracing::info!("Initializing Fuchsia partition tables...");
    progress_callback(String::from("Initializing Fuchsia partition tables..."));
    data_sink.initialize_partition_tables().await?;

    tracing::info!("Getting source partitions");
    progress_callback(String::from("Getting source partitions"));
    let to_install = Partition::get_partitions(
        &install_source,
        &installation_paths.available_disks,
        bootloader_type,
    )
    .await
    .context("Getting source partitions")?;

    let num_partitions = to_install.len();
    let mut current_partition = 1;
    for part in to_install {
        progress_callback(String::from(format!(
            "paving partition {} of {}",
            current_partition, num_partitions
        )));

        let prev_percent = Mutex::new(0 as i64);

        let pave_progress_callback = |data_read, data_total| {
            if data_total == 0 {
                return;
            }
            let cur_percent: i64 =
                unsafe { (((data_read as f64) / (data_total as f64)) * 100.0).to_int_unchecked() };
            let mut prev = prev_percent.lock().unwrap();
            if cur_percent == *prev {
                return;
            }
            *prev = cur_percent;

            progress_callback(String::from(format!(
                "paving partition {} of {}: {}%",
                current_partition, num_partitions, cur_percent
            )));
        };

        tracing::info!("Paving partition: {:?}", part);
        part.pave(&data_sink, &pave_progress_callback).await?;
        if part.is_ab() {
            tracing::info!("Paving partition: {:?} [-B]", part);
            part.pave_b(&data_sink).await?
        }

        current_partition += 1;
    }

    progress_callback(String::from("Flushing Partitions"));
    zx::Status::ok(data_sink.flush().await.context("Sending flush")?)
        .context("Flushing partitions")?;

    progress_callback(String::from("Setting active configuration for the new system"));
    set_active_configuration(&paver)
        .await
        .context("Setting active configuration for the new system")?;

    Ok(())
}