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
// Copyright 2021 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.
//
//! # Inspect stats node.
//!
//! Stats installs a lazy node (or a node with a snapshot of the current state of things)
//! reporting stats about the Inspect being served by the component (such as size, number of
//! dynamic children, etc) at the root of the hierarchy.
//!
//! Stats nodes are always at "fuchsia.inspect.Stats".
//!
//! # Examples
//!
//! ```
//! /* This example shows automatically updated stats */
//!
//! use fuchsia_inspect::stats::InspectorExt;
//!
//! let inspector = /* the inspector of your choice */
//! inspector.record_lazy_stats();  // A lazy node containing stats has been installed
//! ```
//!
//! ```
//! /* This example shows stats which must be manually updated */
//! use fuchsia_inspect::stats;
//!
//! let inspector = ...;  // the inspector you want instrumented
//! let stats = stats::StatsNode::new(&inspector);
//! /* do stuff to inspector */
//! /* ... */
//! stats.update();  // update the stats node
//! stats.record_data_to(root);  /* consume the stats node and persist the data */
//! ```

use super::{private::InspectTypeInternal, Inspector, Node, Property, UintProperty};
use futures::FutureExt;

// The metric node name, as exposed by the stats node.
const FUCHSIA_INSPECT_STATS: &str = "fuchsia.inspect.Stats";
const CURRENT_SIZE_KEY: &str = "current_size";
const MAXIMUM_SIZE_KEY: &str = "maximum_size";
const TOTAL_DYNAMIC_CHILDREN_KEY: &str = "total_dynamic_children";
const ALLOCATED_BLOCKS_KEY: &str = "allocated_blocks";
const DEALLOCATED_BLOCKS_KEY: &str = "deallocated_blocks";
const FAILED_ALLOCATIONS_KEY: &str = "failed_allocations";

/// InspectorExt provides a method for installing a "fuchsia.inspect.Stats" lazy node at the root
/// of the Inspector's hierarchy.
pub trait InspectorExt {
    /// Creates a new stats node  that will expose the given `Inspector` stats.
    fn record_lazy_stats(&self);
}

impl InspectorExt for Inspector {
    fn record_lazy_stats(&self) {
        let weak_root_node = self.root().clone_weak();
        self.root().record_lazy_child(FUCHSIA_INSPECT_STATS, move || {
            let weak_root_node = weak_root_node.clone_weak();
            async move {
                let local_inspector = Inspector::default();
                let stats =
                    StatsNode::from_nodes(weak_root_node, local_inspector.root().clone_weak());
                stats.record_data_to(local_inspector.root());
                Ok(local_inspector)
            }
            .boxed()
        });
    }
}

/// Contains information about inspect such as size and number of dynamic children.
#[derive(Default)]
pub struct StatsNode {
    root_of_instrumented_inspector: Node,
    stats_root: Node,
    current_size: UintProperty,
    maximum_size: UintProperty,
    total_dynamic_children: UintProperty,
    allocated_blocks: UintProperty,
    deallocated_blocks: UintProperty,
    failed_allocations: UintProperty,
}

impl StatsNode {
    /// Takes a snapshot of the stats and writes them to the given parent.
    ///
    /// The returned `StatsNode` is RAII.
    pub fn new(inspector: &Inspector) -> Self {
        let stats_root = inspector.root().create_child(FUCHSIA_INSPECT_STATS);
        Self::from_nodes(inspector.root().clone_weak(), stats_root)
    }

    /// Update the stats with the current state of the Inspector being instrumented.
    pub fn update(&self) {
        if let Some(stats) = self
            .root_of_instrumented_inspector
            .state()
            .map(|outer_state| outer_state.try_lock().ok().map(|state| state.stats()))
            .flatten()
        {
            // just piggy-backing on current_size; it doesn't matter how the atomic_update
            // is triggered
            self.current_size.atomic_update(|_| {
                self.current_size.set(stats.current_size as u64);
                self.maximum_size.set(stats.maximum_size as u64);
                self.total_dynamic_children.set(stats.total_dynamic_children as u64);
                self.allocated_blocks.set(stats.allocated_blocks as u64);
                self.deallocated_blocks.set(stats.deallocated_blocks as u64);
                self.failed_allocations.set(stats.failed_allocations as u64);
            });
        }
    }

    /// Tie the lifetime of the statistics to the provided `fuchsia_inspect::Node`.
    pub fn record_data_to(self, lifetime: &Node) {
        lifetime.record(self.stats_root);
        lifetime.record(self.current_size);
        lifetime.record(self.maximum_size);
        lifetime.record(self.total_dynamic_children);
        lifetime.record(self.allocated_blocks);
        lifetime.record(self.deallocated_blocks);
        lifetime.record(self.failed_allocations);
    }

    /// Write stats from the state of `root_of_instrumented_inspector` to `stats_root`
    fn from_nodes(root_of_instrumented_inspector: Node, stats_root: Node) -> Self {
        if let Some(stats) = root_of_instrumented_inspector
            .state()
            .map(|outer_state| outer_state.try_lock().ok().map(|state| state.stats()))
            .flatten()
        {
            let mut n = stats_root.atomic_update(|stats_root| StatsNode {
                root_of_instrumented_inspector,
                current_size: stats_root.create_uint(CURRENT_SIZE_KEY, stats.current_size as u64),
                maximum_size: stats_root.create_uint(MAXIMUM_SIZE_KEY, stats.maximum_size as u64),
                total_dynamic_children: stats_root
                    .create_uint(TOTAL_DYNAMIC_CHILDREN_KEY, stats.total_dynamic_children as u64),
                allocated_blocks: stats_root
                    .create_uint(ALLOCATED_BLOCKS_KEY, stats.allocated_blocks as u64),
                deallocated_blocks: stats_root
                    .create_uint(DEALLOCATED_BLOCKS_KEY, stats.deallocated_blocks as u64),
                failed_allocations: stats_root
                    .create_uint(FAILED_ALLOCATIONS_KEY, stats.failed_allocations as u64),
                ..StatsNode::default()
            });
            n.stats_root = stats_root;
            n
        } else {
            StatsNode { root_of_instrumented_inspector, ..StatsNode::default() }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use diagnostics_assertions::{assert_data_tree, assert_json_diff};
    use inspect_format::constants;

    #[fuchsia::test]
    fn inspect_stats() {
        let inspector = Inspector::default();
        inspector.record_lazy_stats();

        assert_data_tree!(inspector, root: {
            "fuchsia.inspect.Stats": {
                current_size: 4096u64,
                maximum_size: constants::DEFAULT_VMO_SIZE_BYTES as u64,
                total_dynamic_children: 1u64,  // snapshot was taken before adding any lazy node.
                allocated_blocks: 4u64,
                deallocated_blocks: 0u64,
                failed_allocations: 0u64,
            },
        });

        inspector.root().record_lazy_child("foo", || {
            async move {
                let inspector = Inspector::default();
                inspector.root().record_uint("a", 1);
                Ok(inspector)
            }
            .boxed()
        });
        assert_data_tree!(inspector, root: {
            foo: {
                a: 1u64,
            },
            "fuchsia.inspect.Stats": {
                current_size: 4096u64,
                maximum_size: constants::DEFAULT_VMO_SIZE_BYTES as u64,
                total_dynamic_children: 2u64,
                allocated_blocks: 7u64,
                deallocated_blocks: 0u64,
                failed_allocations: 0u64,
            },
        });

        for i in 0..100 {
            inspector.root().record_string(format!("testing-{}", i), "testing".repeat(i + 1));
        }

        {
            let _ = inspector.root().create_int("drop", 1);
        }

        assert_data_tree!(inspector, root: contains {
            "fuchsia.inspect.Stats": {
                current_size: 61440u64,
                maximum_size: constants::DEFAULT_VMO_SIZE_BYTES as u64,
                total_dynamic_children: 2u64,
                allocated_blocks: 309u64,
                // 2 blocks are deallocated because of the "drop" int block and its
                // STRING_REFERENCE
                deallocated_blocks: 2u64,
                failed_allocations: 0u64,
            }
        });

        for i in 101..220 {
            inspector.root().record_string(format!("testing-{}", i), "testing".repeat(i + 1));
        }

        assert_data_tree!(inspector, root: contains {
            "fuchsia.inspect.Stats": {
                current_size: 262144u64,
                maximum_size: constants::DEFAULT_VMO_SIZE_BYTES as u64,
                total_dynamic_children: 2u64,
                allocated_blocks: 665u64,
                // 2 additional blocks are deallocated because of the failed allocation
                deallocated_blocks: 4u64,
                failed_allocations: 1u64,
            }
        });
    }

    #[fuchsia::test]
    fn stats_are_updated() {
        let inspector = Inspector::default();
        let stats = super::StatsNode::new(&inspector);
        assert_json_diff!(inspector, root: {
            "fuchsia.inspect.Stats": {
                current_size: 4096u64,
                maximum_size: constants::DEFAULT_VMO_SIZE_BYTES as u64,
                total_dynamic_children: 0u64,
                allocated_blocks: 3u64,
                deallocated_blocks: 0u64,
                failed_allocations: 0u64,
            }
        });

        inspector.root().record_int("abc", 5);

        // asserting that everything is the same, since we didn't call `stats.update()`
        assert_json_diff!(inspector, root: {
            abc: 5i64,
            "fuchsia.inspect.Stats": {
                current_size: 4096u64,
                maximum_size: constants::DEFAULT_VMO_SIZE_BYTES as u64,
                total_dynamic_children: 0u64,
                allocated_blocks: 3u64,
                deallocated_blocks: 0u64,
                failed_allocations: 0u64,
            }
        });

        stats.update();

        assert_json_diff!(inspector, root: {
            abc: 5i64,
            "fuchsia.inspect.Stats": {
                current_size: 4096u64,
                maximum_size: constants::DEFAULT_VMO_SIZE_BYTES as u64,
                total_dynamic_children: 0u64,
                allocated_blocks: 17u64,
                deallocated_blocks: 0u64,
                failed_allocations: 0u64,
            }
        });
    }

    #[fuchsia::test]
    fn recorded_stats_are_persisted() {
        let inspector = Inspector::default();
        {
            let stats = super::StatsNode::new(&inspector);
            stats.record_data_to(inspector.root());
        }

        assert_data_tree!(inspector, root: {
            "fuchsia.inspect.Stats": {
                current_size: 4096u64,
                maximum_size: constants::DEFAULT_VMO_SIZE_BYTES as u64,
                total_dynamic_children: 0u64,
                allocated_blocks: 3u64,
                deallocated_blocks: 0u64,
                failed_allocations: 0u64,
            }
        });
    }
}