Skip to main content

watchdog_core/
resources.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Watchdog platform capability resources.
5
6use crate::platform::WatchdogPlatform;
7use parking_lot::Mutex;
8use thiserror::Error;
9use vm_resource::CanResolveTo;
10use vm_resource::PlatformResource;
11use vm_resource::ResolveResource;
12use vm_resource::ResourceKind;
13
14/// Resource kind for obtaining a guest-watchdog platform capability.
15///
16/// This is primarily used with [`PlatformResource`].
17pub enum WatchdogPlatformHandleKind {}
18
19impl ResourceKind for WatchdogPlatformHandleKind {
20    const NAME: &'static str = "watchdog_platform";
21}
22
23impl CanResolveTo<ResolvedWatchdogPlatform> for WatchdogPlatformHandleKind {
24    type Input<'a> = ();
25}
26
27/// An owned watchdog platform capability consumed at resolve-time.
28pub struct ResolvedWatchdogPlatform(Box<dyn WatchdogPlatform>);
29
30impl ResolvedWatchdogPlatform {
31    pub fn into_inner(self) -> Box<dyn WatchdogPlatform> {
32        self.0
33    }
34}
35
36#[derive(Debug, Error)]
37pub enum ResolveWatchdogPlatformError {
38    #[error("watchdog platform capability has already been consumed")]
39    AlreadyConsumed,
40}
41
42/// A static platform resolver that serves a pre-built watchdog platform.
43pub struct StaticWatchdogPlatformResolver(Mutex<Option<Box<dyn WatchdogPlatform>>>);
44
45impl StaticWatchdogPlatformResolver {
46    pub fn new(platform: Box<dyn WatchdogPlatform>) -> Self {
47        Self(Mutex::new(Some(platform)))
48    }
49}
50
51impl ResolveResource<WatchdogPlatformHandleKind, PlatformResource>
52    for StaticWatchdogPlatformResolver
53{
54    type Output = ResolvedWatchdogPlatform;
55    type Error = ResolveWatchdogPlatformError;
56
57    fn resolve(
58        &self,
59        _resource: PlatformResource,
60        _input: (),
61    ) -> Result<Self::Output, Self::Error> {
62        let mut guard = self.0.lock();
63        guard
64            .take()
65            .map(ResolvedWatchdogPlatform)
66            .ok_or(ResolveWatchdogPlatformError::AlreadyConsumed)
67    }
68}