gpt_component/
service.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
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
// Copyright 2024 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.

use crate::gpt::GptManager;
use anyhow::{Context as _, Error};
use block_client::RemoteBlockClient;
use fidl::endpoints::{DiscoverableProtocolMarker as _, RequestStream as _, ServiceMarker as _};
use futures::lock::Mutex as AsyncMutex;
use futures::stream::TryStreamExt as _;
use std::sync::Arc;
use vfs::directory::entry_container::Directory as _;
use vfs::directory::helper::DirectlyMutable as _;
use vfs::execution_scope::ExecutionScope;
use vfs::path::Path;
use {
    fidl_fuchsia_fs_startup as fstartup, fidl_fuchsia_hardware_block as fblock,
    fidl_fuchsia_io as fio, fidl_fuchsia_process_lifecycle as flifecycle,
    fidl_fuchsia_storage_partitions as fpartitions, fuchsia_async as fasync,
};

pub struct StorageHostService {
    state: AsyncMutex<State>,

    // The execution scope of the pseudo filesystem.
    scope: ExecutionScope,

    // The root of the pseudo filesystem for the component.
    export_dir: Arc<vfs::directory::immutable::Simple>,

    // A directory where partitions are published.
    partitions_dir: Arc<vfs::directory::immutable::Simple>,
}

#[derive(Default)]
enum State {
    #[default]
    Stopped,
    /// The GPT is malformed and needs to be reformatted with ResetPartitionTables before it can be
    /// used.  The component will publish an empty partitions directory.
    NeedsFormatting(fblock::BlockProxy),
    Running(Arc<GptManager>),
}

impl State {
    fn is_stopped(&self) -> bool {
        if let Self::Stopped = self {
            true
        } else {
            false
        }
    }
}

impl StorageHostService {
    pub fn new() -> Arc<Self> {
        let export_dir = vfs::directory::immutable::simple();
        let partitions_dir = vfs::directory::immutable::simple();
        Arc::new(Self {
            state: Default::default(),
            scope: ExecutionScope::new(),
            export_dir,
            partitions_dir,
        })
    }

    pub async fn run(
        self: Arc<Self>,
        outgoing_dir: zx::Channel,
        lifecycle_channel: Option<zx::Channel>,
    ) -> Result<(), Error> {
        let svc_dir = vfs::directory::immutable::simple();
        self.export_dir.add_entry("svc", svc_dir.clone()).expect("Unable to create svc dir");

        let weak = Arc::downgrade(&self);
        let weak2 = weak.clone();
        let weak3 = weak.clone();
        svc_dir.add_entry(
            fstartup::StartupMarker::PROTOCOL_NAME,
            vfs::service::host(move |requests| {
                let weak = weak.clone();
                async move {
                    if let Some(me) = weak.upgrade() {
                        let _ = me.handle_start_requests(requests).await;
                    }
                }
            }),
        )?;
        svc_dir
            .add_entry(
                fpartitions::PartitionServiceMarker::SERVICE_NAME,
                self.partitions_dir.clone(),
            )
            .unwrap();

        svc_dir
            .add_entry(
                fpartitions::PartitionsAdminMarker::PROTOCOL_NAME,
                vfs::service::host(move |requests| {
                    let weak = weak2.clone();
                    async move {
                        if let Some(me) = weak.upgrade() {
                            let _ = me.handle_partitions_admin_requests(requests).await;
                        }
                    }
                }),
            )
            .unwrap();

        svc_dir
            .add_entry(
                fpartitions::PartitionsManagerMarker::PROTOCOL_NAME,
                vfs::service::host(move |requests| {
                    let weak = weak3.clone();
                    async move {
                        if let Some(me) = weak.upgrade() {
                            let _ = me.handle_partitions_manager_requests(requests).await;
                        }
                    }
                }),
            )
            .unwrap();

        self.export_dir.clone().open(
            self.scope.clone(),
            fio::OpenFlags::RIGHT_READABLE
                | fio::OpenFlags::RIGHT_WRITABLE
                | fio::OpenFlags::DIRECTORY
                | fio::OpenFlags::RIGHT_EXECUTABLE,
            Path::dot(),
            outgoing_dir.into(),
        );

        if let Some(channel) = lifecycle_channel {
            let me = self.clone();
            self.scope.spawn(async move {
                if let Err(e) = me.handle_lifecycle_requests(channel).await {
                    tracing::warn!(error = ?e, "handle_lifecycle_requests");
                }
            });
        }

        self.scope.wait().await;

        Ok(())
    }

    async fn handle_start_requests(
        self: Arc<Self>,
        mut stream: fstartup::StartupRequestStream,
    ) -> Result<(), Error> {
        while let Some(request) = stream.try_next().await.context("Reading request")? {
            tracing::debug!(?request);
            match request {
                fstartup::StartupRequest::Start { device, options: _, responder } => {
                    responder
                        .send(
                            self.start(device.into_proxy())
                                .await
                                .map_err(|status| status.into_raw()),
                        )
                        .unwrap_or_else(|e| tracing::error!(?e, "Failed to send Start response"));
                }
                fstartup::StartupRequest::Format { responder, .. } => {
                    responder
                        .send(Err(zx::Status::NOT_SUPPORTED.into_raw()))
                        .unwrap_or_else(|e| tracing::error!(?e, "Failed to send Check response"));
                }
                fstartup::StartupRequest::Check { responder, .. } => {
                    responder
                        .send(Err(zx::Status::NOT_SUPPORTED.into_raw()))
                        .unwrap_or_else(|e| tracing::error!(?e, "Failed to send Check response"));
                }
            }
        }
        Ok(())
    }

    async fn start(self: &Arc<Self>, device: fblock::BlockProxy) -> Result<(), zx::Status> {
        let mut state = self.state.lock().await;
        if !state.is_stopped() {
            tracing::warn!("Device already bound");
            return Err(zx::Status::ALREADY_BOUND);
        }

        // TODO(https://fxbug.dev/339491886): It would be better if `start` failed on a malformed
        // device, rather than hiding this state from fshost.  However, fs_management isn't well set
        // up to deal with this, because it ties the outgoing directory to a successful return from
        // `start` (see `ServingMultiVolumeFilesystem`), and fshost resolves the queued requests for
        // the filesystem only after `start` is successful.  We should refactor fs_management and
        // fshost to better support this case, which might require changing how queueing works so
        // there's more flexibility to either resolve queueing when the component starts up (what we
        // need here), or when `Start` is successful (what a filesystem like Fxfs needs).
        *state = match GptManager::new(&device, self.partitions_dir.clone()).await {
            Ok(runner) => State::Running(runner),
            Err(err) => {
                tracing::error!(?err, "Failed to load GPT.  Reformatting may be required.");
                State::NeedsFormatting(device)
            }
        };
        Ok(())
    }

    async fn handle_partitions_manager_requests(
        self: Arc<Self>,
        mut stream: fpartitions::PartitionsManagerRequestStream,
    ) -> Result<(), Error> {
        while let Some(request) = stream.try_next().await.context("Reading request")? {
            tracing::debug!(?request);
            match request {
                fpartitions::PartitionsManagerRequest::GetBlockInfo { responder } => {
                    responder
                        .send(self.get_block_info().await.map_err(|status| status.into_raw()))
                        .unwrap_or_else(|e| {
                            tracing::error!(?e, "Failed to send GetBlockInfo response")
                        });
                }
                fpartitions::PartitionsManagerRequest::CreateTransaction { responder } => {
                    responder
                        .send(self.create_transaction().await.map_err(|status| status.into_raw()))
                        .unwrap_or_else(|e| tracing::error!(?e, "Failed to send Start response"));
                }
                fpartitions::PartitionsManagerRequest::CommitTransaction {
                    transaction,
                    responder,
                } => {
                    responder
                        .send(
                            self.commit_transaction(transaction)
                                .await
                                .map_err(|status| status.into_raw()),
                        )
                        .unwrap_or_else(|e| tracing::error!(?e, "Failed to send Start response"));
                }
            }
        }
        Ok(())
    }

    async fn get_block_info(&self) -> Result<(u64, u32), zx::Status> {
        let state = self.state.lock().await;
        match &*state {
            State::Stopped => return Err(zx::Status::BAD_STATE),
            State::NeedsFormatting(block) => {
                let info = block
                    .get_info()
                    .await
                    .map_err(|err| {
                        tracing::error!(?err, "get_block_info: failed to query block info");
                        zx::Status::IO
                    })?
                    .map_err(zx::Status::from_raw)?;
                Ok((info.block_count, info.block_size))
            }
            State::Running(gpt) => Ok((gpt.block_count(), gpt.block_size())),
        }
    }

    async fn create_transaction(&self) -> Result<zx::EventPair, zx::Status> {
        let gpt_manager = self.gpt_manager().await?;
        gpt_manager.create_transaction().await
    }

    async fn commit_transaction(&self, transaction: zx::EventPair) -> Result<(), zx::Status> {
        let gpt_manager = self.gpt_manager().await?;
        gpt_manager.commit_transaction(transaction).await
    }

    async fn handle_partitions_admin_requests(
        self: Arc<Self>,
        mut stream: fpartitions::PartitionsAdminRequestStream,
    ) -> Result<(), Error> {
        while let Some(request) = stream.try_next().await.context("Reading request")? {
            tracing::debug!(?request);
            match request {
                fpartitions::PartitionsAdminRequest::ResetPartitionTable {
                    partitions,
                    responder,
                } => {
                    responder
                        .send(
                            self.reset_partition_table(partitions)
                                .await
                                .map_err(|status| status.into_raw()),
                        )
                        .unwrap_or_else(|e| tracing::error!(?e, "Failed to send Start response"));
                }
            }
        }
        Ok(())
    }

    async fn reset_partition_table(
        &self,
        partitions: Vec<fpartitions::PartitionInfo>,
    ) -> Result<(), zx::Status> {
        fn convert_partition_info(info: fpartitions::PartitionInfo) -> gpt::PartitionInfo {
            gpt::PartitionInfo {
                label: info.name,
                type_guid: gpt::Guid::from_bytes(info.type_guid.value),
                instance_guid: gpt::Guid::from_bytes(info.instance_guid.value),
                start_block: info.start_block,
                num_blocks: info.num_blocks,
                flags: info.flags,
            }
        }
        let partitions = partitions.into_iter().map(convert_partition_info).collect::<Vec<_>>();

        let mut state = self.state.lock().await;
        match &mut *state {
            State::Stopped => return Err(zx::Status::BAD_STATE),
            State::NeedsFormatting(block) => {
                tracing::info!("reset_partition_table: Reformatting GPT.");
                let client = Arc::new(RemoteBlockClient::new(&*block).await?);

                tracing::info!("reset_partition_table: Reformatting GPT...");
                gpt::Gpt::format(client, partitions).await.map_err(|err| {
                    tracing::error!(?err, "reset_partition_table: failed to init GPT");
                    zx::Status::IO
                })?;
                *state = State::Running(
                    GptManager::new(&*block, self.partitions_dir.clone()).await.map_err(|err| {
                        tracing::error!(?err, "reset_partition_table: failed to re-launch GPT");
                        zx::Status::BAD_STATE
                    })?,
                );
            }
            State::Running(gpt) => {
                tracing::info!("reset_partition_table: Updating GPT.");
                gpt.reset_partition_table(partitions).await?;
            }
        }
        Ok(())
    }

    async fn handle_lifecycle_requests(&self, lifecycle_channel: zx::Channel) -> Result<(), Error> {
        let mut stream = flifecycle::LifecycleRequestStream::from_channel(
            fasync::Channel::from_channel(lifecycle_channel),
        );
        match stream.try_next().await.context("Reading request")? {
            Some(flifecycle::LifecycleRequest::Stop { .. }) => {
                tracing::info!("Received Lifecycle::Stop request");
                let mut state = self.state.lock().await;
                if let State::Running(gpt) = std::mem::take(&mut *state) {
                    gpt.shutdown().await;
                }
                self.scope.shutdown();
                tracing::info!("Shutdown complete");
            }
            None => {}
        }
        Ok(())
    }

    async fn gpt_manager(&self) -> Result<Arc<GptManager>, zx::Status> {
        match &*self.state.lock().await {
            State::Stopped | State::NeedsFormatting(_) => Err(zx::Status::BAD_STATE),
            State::Running(gpt) => Ok(gpt.clone()),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::StorageHostService;
    use block_client::RemoteBlockClient;
    use fake_block_server::FakeServer;
    use fidl::endpoints::Proxy as _;
    use fidl_fuchsia_process_lifecycle::LifecycleMarker;
    use fuchsia_component::client::connect_to_protocol_at_dir_svc;
    use futures::FutureExt as _;
    use gpt::{Gpt, Guid, PartitionInfo};
    use std::sync::Arc;
    use {
        fidl_fuchsia_fs_startup as fstartup, fidl_fuchsia_hardware_block as fblock,
        fidl_fuchsia_hardware_block_volume as fvolume, fidl_fuchsia_io as fio,
        fidl_fuchsia_storage_partitions as fpartitions, fuchsia_async as fasync,
    };

    async fn setup_server(
        block_size: u32,
        block_count: u64,
        partitions: Vec<PartitionInfo>,
    ) -> Arc<FakeServer> {
        let vmo = zx::Vmo::create(block_size as u64 * block_count).unwrap();
        let server = Arc::new(FakeServer::from_vmo(512, vmo));
        {
            let (block_client, block_server) =
                fidl::endpoints::create_proxy::<fblock::BlockMarker>();
            let volume_stream = fidl::endpoints::ServerEnd::<fvolume::VolumeMarker>::from(
                block_server.into_channel(),
            )
            .into_stream();
            let server_clone = server.clone();
            let _task = fasync::Task::spawn(async move { server_clone.serve(volume_stream).await });
            let client = Arc::new(RemoteBlockClient::new(block_client).await.unwrap());
            Gpt::format(client, partitions).await.unwrap();
        }
        server
    }

    #[fuchsia::test]
    async fn lifecycle() {
        let (outgoing_dir, outgoing_dir_server) =
            fidl::endpoints::create_proxy::<fio::DirectoryMarker>();
        let (lifecycle_client, lifecycle_server) =
            fidl::endpoints::create_proxy::<LifecycleMarker>();
        let (block_client, block_server) =
            fidl::endpoints::create_endpoints::<fblock::BlockMarker>();
        let volume_stream =
            fidl::endpoints::ServerEnd::<fvolume::VolumeMarker>::from(block_server.into_channel())
                .into_stream();

        futures::join!(
            async {
                // Client
                let client =
                    connect_to_protocol_at_dir_svc::<fstartup::StartupMarker>(&outgoing_dir)
                        .unwrap();
                client
                    .start(
                        block_client,
                        fstartup::StartOptions {
                            read_only: false,
                            verbose: false,
                            fsck_after_every_transaction: false,
                            write_compression_algorithm:
                                fstartup::CompressionAlgorithm::ZstdChunked,
                            write_compression_level: 0,
                            cache_eviction_policy_override: fstartup::EvictionPolicyOverride::None,
                            startup_profiling_seconds: 0,
                        },
                    )
                    .await
                    .expect("FIDL error")
                    .expect("Start failed");
                lifecycle_client.stop().expect("Stop failed");
                fasync::OnSignals::new(
                    &lifecycle_client.into_channel().expect("into_channel failed"),
                    zx::Signals::CHANNEL_PEER_CLOSED,
                )
                .await
                .expect("OnSignals failed");
            },
            async {
                // Server
                let service = StorageHostService::new();
                service
                    .run(outgoing_dir_server.into_channel(), Some(lifecycle_server.into_channel()))
                    .await
                    .expect("Run failed");
            },
            async {
                // Block device
                let server = setup_server(
                    512,
                    8,
                    vec![PartitionInfo {
                        label: "part".to_string(),
                        type_guid: Guid::from_bytes([0xabu8; 16]),
                        instance_guid: Guid::from_bytes([0xcdu8; 16]),
                        start_block: 4,
                        num_blocks: 1,
                        flags: 0,
                    }],
                )
                .await;
                let _ = server.serve(volume_stream).await;
            }
            .fuse(),
        );
    }

    #[fuchsia::test]
    async fn transaction_lifecycle() {
        let (outgoing_dir, outgoing_dir_server) =
            fidl::endpoints::create_proxy::<fio::DirectoryMarker>();
        let (lifecycle_client, lifecycle_server) =
            fidl::endpoints::create_proxy::<LifecycleMarker>();
        let (block_client, block_server) =
            fidl::endpoints::create_endpoints::<fblock::BlockMarker>();
        let volume_stream =
            fidl::endpoints::ServerEnd::<fvolume::VolumeMarker>::from(block_server.into_channel())
                .into_stream();

        futures::join!(
            async {
                // Client
                connect_to_protocol_at_dir_svc::<fstartup::StartupMarker>(&outgoing_dir)
                    .unwrap()
                    .start(
                        block_client,
                        fstartup::StartOptions {
                            read_only: false,
                            verbose: false,
                            fsck_after_every_transaction: false,
                            write_compression_algorithm:
                                fstartup::CompressionAlgorithm::ZstdChunked,
                            write_compression_level: 0,
                            cache_eviction_policy_override: fstartup::EvictionPolicyOverride::None,
                            startup_profiling_seconds: 0,
                        },
                    )
                    .await
                    .expect("FIDL error")
                    .expect("Start failed");

                let pm_client = connect_to_protocol_at_dir_svc::<
                    fpartitions::PartitionsManagerMarker,
                >(&outgoing_dir)
                .unwrap();
                let transaction = pm_client
                    .create_transaction()
                    .await
                    .expect("FIDL error")
                    .expect("create_transaction failed");

                pm_client
                    .create_transaction()
                    .await
                    .expect("FIDL error")
                    .expect_err("create_transaction should fail while other txn exists");

                pm_client
                    .commit_transaction(transaction)
                    .await
                    .expect("FIDL error")
                    .expect("commit_transaction failed");

                {
                    let _transaction = pm_client
                        .create_transaction()
                        .await
                        .expect("FIDL error")
                        .expect("create_transaction should succeed after committing txn");
                }

                pm_client
                    .create_transaction()
                    .await
                    .expect("FIDL error")
                    .expect("create_transaction should succeed after dropping txn");

                lifecycle_client.stop().expect("Stop failed");
                fasync::OnSignals::new(
                    &lifecycle_client.into_channel().expect("into_channel failed"),
                    zx::Signals::CHANNEL_PEER_CLOSED,
                )
                .await
                .expect("OnSignals failed");
            },
            async {
                // Server
                let service = StorageHostService::new();
                service
                    .run(outgoing_dir_server.into_channel(), Some(lifecycle_server.into_channel()))
                    .await
                    .expect("Run failed");
            },
            async {
                // Block device
                let server = setup_server(
                    512,
                    16,
                    vec![PartitionInfo {
                        label: "part".to_string(),
                        type_guid: Guid::from_bytes([0xabu8; 16]),
                        instance_guid: Guid::from_bytes([0xcdu8; 16]),
                        start_block: 4,
                        num_blocks: 1,
                        flags: 0,
                    }],
                )
                .await;
                let _ = server.serve(volume_stream).await;
            }
            .fuse(),
        );
    }
}