检查快速入门

本快速入门将向您介绍有关使用组件检查的基础知识。您将学习如何使用特定语言的库将 Inspect 集成到组件中,以及如何使用 ffx inspect 查看数据。

如需查看有关 Inspect 概念的更详细演示,请参阅 Inspect Codelab

项目设置

请参阅下文,了解您所选语言的快速入门指南:

C++

本部分假定您要编写一个异步组件,并且该组件的某些部分(通常为 main.cc)如下所示:

async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread);
auto context_ = sys::ComponentContext::CreateAndServeOutgoingDirectory();
// ...
loop.Run();

这会设置一个异步循环,创建运行时提供的 ComponentContext 封装句柄,然后在一些其他初始化工作后运行该循环。

将 Inspect 库依赖项添加到您的 BUILD.gn 文件中

"//sdk/lib/inspect/component/cpp",
"//sdk/lib/sys/cpp",

添加以下包含内容

#include <lib/inspect/component/cpp/component.h>

添加以下代码以初始化 Inspect

inspector_ = std::make_unique<inspect::ComponentInspector>(async_get_default_dispatcher(),
                                                           inspect::PublishOptions{});

您现在正在使用检查!通过将属性附加到根节点,在检查树中创建属性:

// Attach properties to the root node of the tree
inspect::Node& root_node = inspector_->root();
// Important: Hold references to properties and don't let them go out of scope.
auto total_requests = root_node.CreateUint("total_requests", 0);
auto bytes_processed = root_node.CreateUint("bytes_processed", 0);

如需查看您可以尝试的数据类型的完整列表,请参阅支持的数据类型

健康检查

健康检查子系统提供了针对组件健康状况的标准化检查指标。您可以使用运行状况节点报告组件的总体状态:

inspector_->Health().StartingUp();

// ...

inspector_->Health().Ok();

测试

如需测试检查代码,您可以使用 //sdklib/inspect/testing/cpp/inspect.h

#include <lib/inspect/cpp/inspect.h>
#include <lib/inspect/testing/cpp/inspect.h>

#include <gtest/gtest.h>

using namespace inspect::testing;

此库包含一整套匹配器,用于验证检查树的内容。

// Validate the contents of the tree match
auto hierarchy_result = inspect::ReadFromVmo(inspector_.DuplicateVmo());
ASSERT_TRUE(hierarchy_result.is_ok());
EXPECT_THAT(hierarchy_result.take_value(),
            NodeMatches(AllOf(PropertyList(::testing::UnorderedElementsAre(
                UintIs("bytes_processed", 24), UintIs("total_requests", 2))))));

Rust

本部分假定您要编写一个异步组件,并且该组件的某些部分(通常为 main.rs)如下所示:

async fn main() -> Result<(), Error> {
  // ...
  let mut service_fs = ServiceFs::new();
  // ...
  service_fs.take_and_serve_directory_handle().unwrap();
  service_fs.collect::<()>().await;
  Ok(())
}

将 Inspect 库依赖项添加到您的 BUILD.gn 文件中

"//src/lib/diagnostics/inspect/runtime/rust",
"//src/lib/diagnostics/inspect/rust",

添加以下代码以初始化 Inspect

// This creates the root of an Inspect tree
// The Inspector is a singleton that you can access from any scope
let inspector = fuchsia_inspect::component::inspector();
// This serves the Inspect tree, converting failures into fatal errors
let _inspect_server_task =
    inspect_runtime::publish(inspector, inspect_runtime::PublishOptions::default());

您现在正在使用检查!通过将属性附加到根节点,在检查树中创建属性:

// Attach properties to the root node of the tree
let root_node = inspector.root();
let total_requests = root_node.create_uint("total_requests", 0);
let bytes_processed = root_node.create_uint("bytes_processed", 0);

如需查看您可以尝试的数据类型的完整列表,请参阅支持的数据类型

健康检查

健康检查子系统提供了针对组件健康状况的标准化检查指标。您可以使用运行状况节点报告组件的总体状态:

fuchsia_inspect::component::health().set_starting_up();

// ...

fuchsia_inspect::component::health().set_ok();

测试

如需测试 Inspect 代码,您可以使用 assert_data_tree 验证 Inspect 树的内容:

// Get a reference to the root node of the Inspect tree
let inspector = fuchsia_inspect::component::inspector();

// ...

// Validate the contents of the tree match
diagnostics_assertions::assert_data_tree!(inspector, root: {
    total_requests: 2u64,
    bytes_processed: 24u64,
});

检查库

现在,您已经有了 root_node,可以开始构建层次结构了。本部分介绍了一些重要概念和模式,以帮助您上手。

  • 一个节点可以有任意数量的键值对,称为“属性”
  • 值的键始终是 UTF-8 字符串,该值可以是以下支持的类型之一。
  • 一个节点可以有任意数量的子节点,这些子节点同样也是节点。

C++

使用上面的代码,您可以访问名为“root”的单个节点。hello_world_property 是包含字符串值(通常称为 StringProperty)的 Property。

  • 值和节点在父节点下创建。

Node 类具有各种受支持值的创建者方法。hello_world_property 是使用 CreateStringProperty 创建的。您可以通过调用 root_node.CreateChild("child name") 在根节点下创建一个子节点。请注意,名称必须始终是 UTF-8 字符串。

  • 值和节点具有严格的所有权语义。

hello_world_property 拥有该媒体资源。当底层属性被销毁(超出范围)时,底层属性会被删除,并且不再出现在组件的“检查”输出中。子节点也是如此。

如果您要创建的值不需要修改,请使用 ValueList 使这些值保持活跃状态,直到不再需要它们为止。

  • 检查会尽力而为。

由于空间限制,Inspect 库可能无法满足 Create 请求。您的代码中不会出现此错误:您会收到一个 Node/Property 对象,该对象的方法为空操作。

  • 模式:将子节点传递给子对象。

在您自己的类的构造函数中添加 inspect::Node 参数会很有用。然后,父对象(应拥有自己的 inspect::Node)可以在其子对象构造时将 CreateChild(...) 的结果传递给其子对象:

class Child {
  public:
    Child(inspect::Node my_node) : my_node_(std::move(my_node)) {
      // Create a string that doesn't change, and emplace it in the ValueList
      my_node_.CreateString("version", "1.0", &values_);
      // Create metrics and properties on my_node_.
    }

  private:
    inspect::Node my_node_;
    inspect::StringProperty some_property_;
    inspect::ValueList values_;
    // ... more properties and metrics
};

class Parent {
  public:
    // ...

    void AddChild() {
      // Note: inspect::UniqueName returns a globally unique name with the specified prefix.
      children_.emplace_back(my_node_.CreateChild(inspect::UniqueName("child-")));
    }

  private:
    std::vector<Child> children_;
    inspect::Node my_node_;
};

Rust

Rust 库提供了两种管理节点和属性的方法:创建和记录。

使用 create_* 方法时,属性或节点对象的所有权属于调用方。丢弃返回的对象时,系统会移除该属性。 例如:

{
    let property = root.create_int("name", 1);
}

在此示例中,property 超出了范围,因此系统调用了属性丢弃操作。读者不会看到此属性。

使用 record_* 方法时,属性的生命周期与父节点相关联。删除节点后,记录的媒体资源也会被删除。

{
    let node = root.create_child("name");
    {
      node.record_uint(2); // no return
    }
    // The uint property will still be visible to readers.
}

在此示例中,与 name 关联的 uint 属性对读取器可见,直到父级 node 超出范围。

动态价值

本部分介绍了 Inspect 库中对在读取时延迟膨胀的节点的支持情况。这些方法接受回调函数而不是值。回调函数会在系统读取属性值时调用。

C++

C++ 库提供了两个动态值属性创建程序:CreateLazyNodeCreateLazyValues

这两个方法都会接受为 inspect::Inspector 返回 promise 的回调,唯一的区别在于动态值在树中的存储方式。

root->CreateLazyNode(name, callback) 会使用给定的 name 创建 root 的子节点。callback 会返回 inspect::Inspector 的 promise,该 promise 的根节点在读取时会被拼合到父层次结构中。以下示例显示,存在一个名为“lazy”的子节点,它具有字符串属性“version”,还有一个额外的名为“lazy”的子节点。

root->CreateLazyValues(name, callback) 的工作方式与 root->CreateLazyNode(name, callback) 类似,不同之处在于,承诺根节点上的所有属性和子节点将作为值直接添加到原始 root 中。在此例的第二个输出中,内部延迟节点并未出现,其值会展平为 root 上的属性。

root->CreateLazy{Node,Values}("lazy", [] {
  Inspector a;
  a.GetRoot().CreateString("version", "1.0", &a);
  a.GetRoot().CreateLazy{Node,Values}("lazy", [] {
    Inspector b;
    b.GetRoot().RecordInt("value", 10);
    return fpromise::make_ok_promise(std::move(b));
  }, &a);

  return fpromise::make_ok_promise(std::move(a));
});

输出 (CreateLazyNode):

root:
  lazy:
    version = "1.0"
    lazy:
      value = 10

输出 (CreateLazyValues):

root:
  value = 10
  version = "1.0"

CreateLazy{Node,Values} 的返回值是拥有所传递回调的 LazyNodeLazyNode 被销毁后,系统永远不会调用该回调函数。如果您在执行回调函数的同时销毁 LazyNode,系统会阻止销毁操作,直到回调函数返回其 promise 为止。

如果要在 this 上动态公开属性,只需编写以下代码即可:

class Employee {
  public:
    Employee(inspect::Node node) : node_(std::move(node)) {
      calls_ = node_.CreateInt("calls", 0);

      // Create a lazy node that populates values on its parent
      // dynamically.
      // Note: The callback will never be called after the LazyNode is
      // destroyed, so it is safe to capture "this."
      lazy_ = node_.CreateLazyValues("lazy", [this] {
        // Create a new Inspector and put any data in it you want.
        inspect::Inspector inspector;

        // Keep track of the number of times this callback is executed.
        // This is safe because the callback is executed without locking
        // any state in the parent node.
        calls_.Add(1);

        // ERROR: You cannot modify the LazyNode from the callback. Doing
        // so may deadlock!
        // lazy_ = ...

        // The value is set to the result of calling a method on "this".
        inspector.GetRoot().RecordInt("performance_score",
                                      this->CalculatePerformance());

        // Callbacks return a fpromise::promise<Inspector>, so return a result
        // promise containing the value we created.
        // You can alternatively return a promise that is completed by
        // some asynchronous task.
        return fpromise::make_ok_promise(std::move(inspector));
      });
    }

  private:
    inspect::Node node_;
    inspect::IntProperty calls_;
    inspect::LazyNode lazy_;
};

Rust

由于类似概念在 Rust 中也适用,请参阅 C++ 动态值支持

示例:

root.create_lazy_{child,values}("lazy", [] {
    async move {
        let inspector = Inspector::default();
        inspector.root().record_string("version", "1.0");
        inspector.root().record_lazy_{node,values}("lazy", || {
            let inspector = Inspector::default();
            inspector.root().record_int("value", 10);
            // `_value`'s drop is called when the function returns, so it will be removed.
            // For these situations `record_` is provided.
            let _value = inspector.root().create_int("gone", 2);
            Ok(inspector)
        });
        Ok(inspector)
    }
    .boxed()
});

Output (create_lazy_node):
root:
  lazy:
    version = "1.0"
    lazy:
      value = 10

Output (create_lazy_values):
root:
  value = 10
  version = "1.0"

字符串引用

C++

您可以使用 inspect::StringReference 来减少包含大量重复数据的 Inspect 层次结构的内存占用量。例如,

using inspect::Inspector;

Inspector inspector;

for (int i = 0; i < 100; i++) {
  inspector.GetRoot().CreateChild("child", &inspector);
}

将在检查输出中包含字符串 "child" 的 100 个副本。

或者,

using inspect::Inspector;
using inspect::StringReference;

namespace {
  const StringReference kChild("child");
}

Inspector inspector;
for (int i = 0; i < 100; i++) {
  inspector.GetRoot().CreateChild(kChild, &inspector)
}

将仅生成引用 100 次的 "child" 的副本。

这会为每个子节点节省 16 个字节的费用,而共享数据的费用为 32 个字节。最终节省了 1568 个字节。

建议在需要使用全局常量键的任何位置使用此模式。

Rust

在 Rust Inspect 中,系统会自动删除重复的字符串名称。例如,

use fuchsia_inspect::Inspector;

let inspector = Inspector::default();
for _ in 0..100 {
  inspector.root().record_child("child");
}

将仅生成 1 个 "child" 副本,副本引用 100 次。

这会为每个子节点节省 16 个字节的费用,而共享数据的费用为 32 个字节。最终节省了 1568 个字节。

查看检查数据

您可以使用 ffx inspect 命令来查看从组件中导出的检查数据。

本部分假定您对正在运行的 Fuchsia 系统具有 SSH 访问权限,并且已开始运行组件。我们将使用名称 my_component.cm 作为组件清单名称的占位符。

读取您的检查数据

以下命令可输出系统中运行的所有组件的检查层次结构:

ffx inspect show

您可以使用 ffx inspect list 的输出,指定单个组件(例如 my_component.cm)作为 ffx inspect show 的输入:

ffx inspect show --manifest my_component.cm

上面指定 --manifest 将返回系统上运行的组件的所有实例的数据。如果您知道组件的特定名称(例如 core/my_component),则可以改为传递该名称:

ffx inspect show core/my_component

您可以指定多个组件(例如 core/font_providercore/my_component):

ffx inspect show core/font_provider core/my_component

您还可以指定节点和属性值。如需查看所有可能的选择器的列表,请使用 ffx inspect selectors

ffx inspect selectors core/my_component

然后,您可以指定选择器(例如 core/my_component:root)作为 ffx inspect show 的输入:

ffx inspect show core/my_component:root

如果您不知道组件的名称,可以将 --manifest 与适用于所有匹配组件名称的选择器(使用 *)搭配使用:

ffx inspect show --manifest my_component.cm *:root

如果您遵循了上述步骤,上述命令将输出以下内容:

root:
  hello = world

支持的数据类型

类型 说明 备注
IntProperty 包含带符号的 64 位整数的指标。 所有语言
UIntProperty 包含无符号 64 位整数的指标。 Dart 中不支持
DoubleProperty 包含双浮点数的指标。 所有语言
BoolProperty 包含双浮点数的指标。 所有语言
{Int,Double,Uint}数组 指标类型的数组,包括各种直方图的类型化封装容器。 支持与基本指标类型相同的语言
StringArray 一个字符串数组。以 StringReference 表示。 在 Dart 中不受支持。
StringProperty 具有 UTF-8 字符串值的属性。 所有语言
ByteVectorProperty 具有任意字节值的属性。 所有语言
节点 一个节点,可在其下嵌套指标、属性和更多节点。 所有语言
LazyNode 动态实例化完整的节点树。 C++、Rust