Coverage Report

Created: 2025-03-08 07:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/build/source/nativelink-util/src/platform_properties.rs
Line
Count
Source
1
// Copyright 2024 The NativeLink Authors. All rights reserved.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//    http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
use std::borrow::Cow;
16
use std::collections::HashMap;
17
18
use nativelink_metric::{
19
    publish, MetricFieldData, MetricKind, MetricPublishKnownKindData, MetricsComponent,
20
};
21
use nativelink_proto::build::bazel::remote::execution::v2::platform::Property as ProtoProperty;
22
use nativelink_proto::build::bazel::remote::execution::v2::Platform as ProtoPlatform;
23
use serde::{Deserialize, Serialize};
24
25
/// `PlatformProperties` helps manage the configuration of platform properties to
26
/// keys and types. The scheduler uses these properties to decide what jobs
27
/// can be assigned to different workers. For example, if a job states it needs
28
/// a specific key, it will never be run on a worker that does not have at least
29
/// all the platform property keys configured on the worker.
30
///
31
/// Additional rules may be applied based on `PlatfromPropertyValue`.
32
#[derive(Eq, PartialEq, Clone, Debug, Default, Serialize, Deserialize, MetricsComponent)]
33
pub struct PlatformProperties {
34
    #[metric]
35
    pub properties: HashMap<String, PlatformPropertyValue>,
36
}
37
38
impl PlatformProperties {
39
    #[must_use]
40
46
    pub const fn new(map: HashMap<String, PlatformPropertyValue>) -> Self {
41
46
        Self { properties: map }
42
46
    }
43
44
    /// Determines if the worker's `PlatformProperties` is satisfied by this struct.
45
    #[must_use]
46
33
    pub fn is_satisfied_by(&self, worker_properties: &Self) -> bool {
47
37
        for (
property, check_value9
) in &self.properties {
48
9
            if let Some(worker_value) = worker_properties.properties.get(property) {
  Branch (48:20): [True: 9, False: 0]
  Branch (48:20): [Folded - Ignored]
49
9
                if !check_value.is_satisfied_by(worker_value) {
  Branch (49:20): [True: 5, False: 4]
  Branch (49:20): [Folded - Ignored]
50
5
                    return false;
51
4
                }
52
            } else {
53
0
                return false;
54
            }
55
        }
56
28
        true
57
33
    }
58
}
59
60
impl From<ProtoPlatform> for PlatformProperties {
61
0
    fn from(platform: ProtoPlatform) -> Self {
62
0
        let mut properties = HashMap::with_capacity(platform.properties.len());
63
0
        for property in platform.properties {
64
0
            properties.insert(
65
0
                property.name,
66
0
                PlatformPropertyValue::Unknown(property.value),
67
0
            );
68
0
        }
69
0
        Self { properties }
70
0
    }
71
}
72
73
impl From<&PlatformProperties> for ProtoPlatform {
74
29
    fn from(val: &PlatformProperties) -> Self {
75
29
        ProtoPlatform {
76
29
            properties: val
77
29
                .properties
78
29
                .iter()
79
29
                .map(|(name, value)| ProtoProperty {
80
5
                    name: name.clone(),
81
5
                    value: value.as_str().to_string(),
82
29
                })
83
29
                .collect(),
84
29
        }
85
29
    }
86
}
87
88
/// Holds the associated value of the key and type.
89
///
90
/// Exact    - Means the worker must have this exact value.
91
/// Minimum  - Means that workers must have at least this number available. When
92
///            a worker executes a task that has this value, the worker will have
93
///            this value subtracted from the available resources of the worker.
94
/// Priority - Means the worker is given this information, but does not restrict
95
///            what workers can take this value. However, the worker must have the
96
///            associated key present to be matched.
97
///            TODO(allada) In the future this will be used by the scheduler and
98
///            worker to cause the scheduler to prefer certain workers over others,
99
///            but not restrict them based on these values.
100
#[derive(Eq, PartialEq, Hash, Clone, Ord, PartialOrd, Debug, Serialize, Deserialize)]
101
pub enum PlatformPropertyValue {
102
    Exact(String),
103
    Minimum(u64),
104
    Priority(String),
105
    Unknown(String),
106
}
107
108
impl PlatformPropertyValue {
109
    /// Same as `PlatformProperties::is_satisfied_by`, but on an individual value.
110
    #[must_use]
111
9
    pub fn is_satisfied_by(&self, worker_value: &Self) -> bool {
112
9
        if self == worker_value {
  Branch (112:12): [True: 4, False: 5]
  Branch (112:12): [Folded - Ignored]
113
4
            return true;
114
5
        }
115
5
        match self {
116
3
            Self::Minimum(v) => {
117
3
                if let Self::Minimum(worker_v) = worker_value {
  Branch (117:24): [True: 3, False: 0]
  Branch (117:24): [Folded - Ignored]
118
3
                    return worker_v >= v;
119
0
                }
120
0
                false
121
            }
122
            // Priority is used to pass info to the worker and not restrict which
123
            // workers can be selected, but might be used to prefer certain workers
124
            // over others.
125
0
            Self::Priority(_) => true,
126
            // Success exact case is handled above.
127
2
            Self::Exact(_) | Self::Unknown(_) => false,
128
        }
129
9
    }
130
131
7
    pub fn as_str(&self) -> Cow<str> {
132
7
        match self {
133
2
            Self::Exact(value) | Self::Priority(
value0
) | Self::Unknown(
value0
) => {
134
2
                Cow::Borrowed(value)
135
            }
136
5
            Self::Minimum(value) => Cow::Owned(value.to_string()),
137
        }
138
7
    }
139
}
140
141
impl MetricsComponent for PlatformPropertyValue {
142
0
    fn publish(
143
0
        &self,
144
0
        kind: MetricKind,
145
0
        field_metadata: MetricFieldData,
146
0
    ) -> Result<MetricPublishKnownKindData, nativelink_metric::Error> {
147
0
        let name = field_metadata.name.into_owned();
148
0
        let help = field_metadata.help.as_ref();
149
0
        match self {
150
0
            Self::Exact(v) => publish!(name, v, kind, help, "exact"),
151
0
            Self::Minimum(v) => publish!(name, v, kind, help, "minimum"),
152
0
            Self::Priority(v) => publish!(name, v, kind, help, "priority"),
153
0
            Self::Unknown(v) => publish!(name, v, kind, help, "unknown"),
154
        }
155
156
0
        Ok(MetricPublishKnownKindData::Component)
157
0
    }
158
}