檢查程式碼研究室

本文件包含 C++ 和 Rust 中檢查功能的程式碼研究室。

這個程式碼位於:

本程式碼研究室分為數個部分,每個部分都有專屬的子目錄。本程式碼研究室的起點為第 1 部分,每個部分的程式碼都包含前一單元的解決方案。

編寫本程式碼研究室時,您可以繼續將解決方案新增至「part_1」,也可在現有解決方案的基礎上進行建構。

必要條件

設定開發環境。

本程式碼研究室假設您已完成入門指南,並具有:

  1. 一旁有貨,並建造了富希亞樹。
  2. 執行 Fuchsia 的裝置或模擬器 (ffx emu)。
  3. 用來為 Fuchsia 裝置或模擬器提供元件 (fx serve) 的工作站。

如要在本程式碼研究室中建構並執行範例,請在 fx set 叫用中加入下列引數:

C++

fx set core.x64 \
--with //examples/diagnostics/inspect/codelab/cpp \
--with //examples/diagnostics/inspect/codelab/cpp:tests

Rust

fx set core.x64 \
--with //examples/diagnostics/inspect/codelab/rust \
--with //examples/diagnostics/inspect/codelab/rust:tests

第 1 部分:含有錯誤的元件

有一個元件會提供名為 Reverser 的通訊協定:

// Implementation of a string reverser.
@discoverable
closed protocol Reverser {
    // Returns the input string reversed character-by-character.
    strict Reverse(struct {
        input string:1024;
    }) -> (struct {
        response string:1024;
    });
};

這個通訊協定含有名為 Reverse 的單一方法,可反轉傳送至該通訊協定的任何字串。已提供通訊協定的實作,但存在重大錯誤。這項錯誤會導致嘗試呼叫 Reverse 方法的用戶端發現通話無限期停止。您必須自行修正這個錯誤。

執行元件

有一個用戶端應用程式會啟動 Reverser 元件,並將其餘指令列引數做為字串傳送至反向:

  1. 查看用量

    根據您要執行的程式碼研究室,您要啟動 client_i 元件,其中 i 是介於 [1, 5] 之間的數字。舉例來說,如要啟動用戶端與程式碼研究室第 2 部分向反向作業通訊的功能:

    C++

    ffx component run /core/ffx-laboratory:client_part_2 fuchsia-pkg://fuchsia.com/inspect_cpp_codelab#meta/client_part_2.cm
    

    Rust

    ffx component run /core/ffx-laboratory:client_part_2 fuchsia-pkg://fuchsia.com/inspect_rust_codelab#meta/client_part_2.cm
    
  2. 執行第 1 部分程式碼,然後將「Hello」字串反向

    如果只要指定單一字串「Hello」,請修改 common.shard.cmlprogram.args 區段,然後建構並執行下列項目:

    C++

    ffx component run /core/ffx-laboratory:client_part_1 fuchsia-pkg://fuchsia.com/inspect_cpp_codelab#meta/client_part_1.cm
    

    如要查看指令輸出內容,請查看記錄檔:

    ffx log --tags inspect_cpp_codelab
    

    這個指令會輸出一些含有錯誤的輸出內容。

    Rust

    ffx component run /core/ffx-laboratory:client_part_1 fuchsia-pkg://fuchsia.com/inspect_rust_codelab#meta/client_part_1.cm
    

    如要查看指令輸出內容,請查看記錄檔:

    ffx log --tags inspect_rust_codelab
    

    我們在記錄中看到元件收到「Hello」做為輸入內容,但我們並未看到正確的反向輸出內容。

    如記錄所示,反向工具無法正常運作。

  3. 請嘗試使用更多引數執行用戶端:

    將「World」字串新增至 common.shard.cmlprogram.args 區段:

    {
        program: {
            args: [
                "Hello",
                "World",
            ],
        },
    }
    

    建構並執行下列項目:

    C++

     ffx component run --recreate /core/ffx-laboratory:client_part_1 fuchsia-pkg://fuchsia.com/inspect_cpp_codelab#meta/client_part_1.cm
     ```
    

    Rust

     ffx component run --recreate /core/ffx-laboratory:client_part_1 fuchsia-pkg://fuchsia.com/inspect_rust_codelab#meta/client_part_1.cm
     ```
    

    我們可以看見元件輸出了第一個輸入,但沒有看到預期的輸出內容,也沒有第二個輸入。

您現在可以查看程式碼來排解問題。

瀏覽程式碼

現在可以重現問題了,現在請看看用戶端做了什麼事:

C++

在「用戶端 main」中:

// Repeatedly send strings to be reversed to the other component.
for (int i = 1; i < argc; i++) {
  FX_LOGS(INFO) << "Input: " << argv[i];

  std::string output;
  status = zx::make_result(reverser->Reverse(argv[i], &output));
  if (status.is_error()) {
    FX_LOGS(ERROR) << "Error: Failed to reverse string.";
    return status.status_value();
  }

  FX_LOGS(INFO) << "Output: " << output;
}

Rust

在「用戶端 main」中:

for string in args.strings {
    info!("Input: {}", string);
    match reverser.reverse(&string).await {
        Ok(output) => info!("Output: {}", output),
        Err(e) => error!(error = ?e, "Failed to reverse string"),
    }
}

在這個程式碼片段中,用戶端會呼叫 Reverse 方法,但沒看到任何回應。看起來不像是錯誤訊息或輸出內容

請查看本程式碼研究室這部分的伺服器程式碼。有很多標準元件設定:

C++

第 1 部分主要部分:

  • 記錄初始化

    fuchsia_logging::SetTags({"inspect_cpp_codelab", "part1"});
    
  • 建立非同步執行程式

    async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread);
    auto context = sys::ComponentContext::CreateAndServeOutgoingDirectory();
    
  • 提供公共服務

    context->outgoing()->AddPublicService(Reverser::CreateDefaultHandler());
    

Rust

第 1 部分主要部分:

  • 記錄初始化

    #[fuchsia::main(logging_tags = ["inspect_rust_codelab", "part1"])]
    
  • ServiceF 初始化

    let mut fs = ServiceFs::new();
    
  • ServiceFs 集合

    let running_service_fs = fs.collect::<()>().map(Ok);
    
  • 提供公共服務

    fs.dir("svc").add_fidl_service(move |stream| reverser_factory.spawn_new(stream));
    fs.take_and_serve_directory_handle()?;
    

查看反向器的定義:

C++

reverser.h 中:

class Reverser final : public fuchsia::examples::inspect::Reverser {
 public:
  // CODELAB: Create a new constructor for Reverser that takes an Inspect node.

  // Implementation of Reverser.Reverse().
  void Reverse(std::string input, ReverseCallback callback) override;

  // Return a request handler for the Reverser protocol that binds incoming requests to new
  // Reversers.
  static fidl::InterfaceRequestHandler<fuchsia::examples::inspect::Reverser> CreateDefaultHandler();
};

這個類別會實作 Reverser 通訊協定。名為 CreateDefaultHandler 的輔助方法會建構 InterfaceRequestHandler,為傳入要求建立新的 Reverser

Rust

reverser.rs 中:

pub struct ReverserServerFactory {}

impl ReverserServerFactory {
    // CODELAB: Create a new() constructor that takes an Inspect node.
    pub fn new() -> Self {
        Self {}
    }

    pub fn spawn_new(&self, stream: ReverserRequestStream) {
        // CODELAB: Add stats about incoming connections.
        ReverserServer::new().spawn(stream);
    }
}

struct ReverserServer {}

impl ReverserServer {
    // CODELAB: Create a new() constructor that takes an Inspect node.
    fn new() -> Self {
        Self {}
    }

    pub fn spawn(self, mut stream: ReverserRequestStream) {
        fasync::Task::local(async move {
            while let Some(request) = stream.try_next().await.expect("serve reverser") {
                // CODELAB: Add stats about incoming requests.
                let ReverserRequest::Reverse { input, responder: _ } = request;
                let _result = input.chars().rev().collect::<String>();
                // Yes, this is silly. Just for codelab purposes.
                fasync::Timer::new(fasync::Time::after(10.hours())).await
            }
        })
        .detach();
    }
}

這個結構會提供 Reverser 通訊協定。ReverserServerFactory (稍後會比較適合) 會在建立新的 Reverser 連線時建構 ReverserServer

新增檢查項目

現在您已瞭解程式碼結構,可以開始使用「檢查」檢測程式碼,找出問題所在。

您先前可能已透過列印或記錄對程式進行偵錯。雖然這種做法通常有效,但經常執行的非同步元件經常會輸出多個有關內部狀態的記錄。這個程式碼研究室將說明「檢查」如何提供元件目前狀態的快照,而無需瀏覽記錄。

  1. 包含檢查依附元件:

    C++

    BUILD.gn

    source_set("lib") {
      sources = [
        "reverser.cc",
        "reverser.h",
      ]
    
      public_deps = [
        "//examples/diagnostics/inspect/codelab/fidl:fuchsia.examples.inspect_hlcpp",
        "//sdk/lib/inspect/component/cpp",
      ]
    }
    
    

    Rust

    depsrustc_binary("bin") 中的 BUILD.gn

    "//src/lib/diagnostics/inspect/runtime/rust",
    "//src/lib/diagnostics/inspect/rust",
    "//src/lib/fuchsia",
    
    
  2. 初始化檢查:

    C++

    main.cc 中:

    #include <lib/inspect/component/cpp/component.h>
    inspect::ComponentInspector inspector(loop.dispatcher(), {});
    

    Rust

    main.rs 中:

    use fuchsia_inspect::component;
    let _inspect_server_task = inspect_runtime::publish(
        component::inspector(),
        inspect_runtime::PublishOptions::default(),
    );
    
    

    您目前使用的是「檢查」功能。

  3. 新增簡單的「version」屬性,顯示目前使用的版本:

    C++

    inspector.root().RecordString("version", "part2");
    

    這個程式碼片段會執行下列作業:

    1. 取得檢查階層的「根」節點。

      元件的檢查階層是由節點的樹狀結構組成,每個節點都包含任意數量的屬性。

    2. 使用 CreateString 建立新屬性。

      這會在根層級新增 StringProperty。這個 StringProperty 稱為「版本」,且值為「part2」。將屬性設為「part1」

    3. 將新屬性放入檢查器中。

      屬性的生命週期與 Create 傳回的物件相關聯,如果刪除該物件,屬性就會消失。選用的第三個參數會將新屬性置於 inspector 中,而不是傳回。因此,只要檢查器本身 (元件的完整執行作業),新屬性就會持續存在。

    Rust

    component::inspector().root().record_string("version", "part2");
    

    這個程式碼片段會執行下列作業:

    1. 取得檢查階層的「根」節點。

    元件的檢查階層是由節點的樹狀結構組成,每個節點都包含任意數量的屬性。

    1. 使用 record_string 建立新屬性。

    這會在根層級新增 StringProperty。這個 StringProperty 稱為「版本」,且值為「part2」。將屬性設為「part1」

    1. 該憑證會記錄在根節點中。

    建立屬性的常見方式是透過節點上的 create_* 方法。使用這些方法建立的屬性的生命週期與傳回的物件有關聯,如果刪除物件,則會導致屬性消失。程式庫提供便利的方法 record_*,可建立屬性,並將屬性生命週期連結至呼叫該方法的節點。因此,只要節點本身存在,新屬性就會持續存在 (在此例中只要節點是根節點,則整個執行元件)。

讀取檢查資料

現在,您已在元件中新增檢查項目,所以您可以閱讀:

  1. 重建及更新目標系統

    fx build && fx ota
    
  2. 執行用戶端:

    C++

    ffx component run --recreate /core/ffx-laboratory:client_part_1 fuchsia-pkg://fuchsia.com/inspect_cpp_codelab#meta/client_part_1.cm
    ffx log --tags inspect_cpp_codelab
    

    Rust

    ffx component run --recreate /core/ffx-laboratory:client_part_1 fuchsia-pkg://fuchsia.com/inspect_rust_codelab#meta/client_part_1.cm
    ffx log --tags inspect_rust_codelab
    
  3. 使用 ffx inspect 查看輸出內容:

    ffx inspect show
    

    這會傾印整個系統的所有檢查資料,這可能為大量資料。

  4. 由於 ffx inspect 支援 glob 比對,因此請執行:

    C++

    $ ffx inspect show 'core/ffx-laboratory\:client_part_1/reverser'
    # or `ffx inspect show --manifest inspect_cpp_codelab`
    metadata:
      filename = fuchsia.inspect.Tree
      component_url = fuchsia-pkg://fuchsia.com/inspect_cpp_codelab#meta/part_1.cm
      timestamp = 4728864898476
    payload:
      root:
        version = part1
    

    Rust

    $ ffx inspect show 'core/ffx-laboratory\:client_part_1/reverser'
    # or `ffx inspect show --manifest inspect_rust_codelab`
    metadata:
      filename = fuchsia.inspect.Tree
      component_url = fuchsia-pkg://fuchsia.com/inspect_rust_codelab#meta/part_1.cm
      timestamp = 4728864898476
    payload:
      root:
        version = part1
    
  5. 您也可以透過 JSON 查看輸出內容:

    C++

    $ ffx --machine json-pretty inspect show 'core/ffx-laboratory\:client_part_1/reverser'
    [
      {
        "data_source": "Inspect",
        "metadata": {
          "errors": null,
          "filename": "fuchsia.inspect.Tree",
          "component_url": "fuchsia-pkg://fuchsia.com/inspect_pp_codelab#meta/part_1.cm",
          "timestamp": 5031116776282
        },
        "moniker": "core/ffx-laboratory\\:client_part_5/reverser",
        "payload": {
          "root": {
            "version": "part1",
        },
        "version": 1
      }
    ]
    

    Rust

    $ ffx --machine json-pretty inspect show 'core/ffx-laboratory\:client_part_1/reverser'
    [
      {
        "data_source": "Inspect",
        "metadata": {
          "errors": null,
          "filename": "fuchsia.inspect.Tree",
          "component_url": "fuchsia-pkg://fuchsia.com/inspect_rust_codelab#meta/part_1.cm",
          "timestamp": 5031116776282
        },
        "moniker": "core/ffx-laboratory\\:client_part_5/reverser",
        "payload": {
          "root": {
            "version": "part1",
        },
        "version": 1
      }
    ]
    

檢測程式碼以找出錯誤

現在,您已初始化檢查並瞭解如何讀取資料,現在可以開始檢測程式碼並找出錯誤。

先前的輸出內容顯示元件實際執行的方式,以及元件未完全停止運作。否則,檢查讀取會停止運作。

為每個連線新增資訊,觀察元件是否正在處理連線。

  1. 將新的子項新增至根節點,使其包含 reverser 服務的統計資料:

    C++

    context->outgoing()->AddPublicService(
        Reverser::CreateDefaultHandler(inspector.root().CreateChild("reverser_service")));
    

    Rust

    let reverser_factory =
        ReverserServerFactory::new(component::inspector().root().create_child("reverser_service"));
    
  2. 更新伺服器以接受這個節點:

    C++

    更新 reverser.hreverser.cc 中的 CreateDefaultHandler 定義:

    #include <lib/inspect/cpp/inspect.h>
    fidl::InterfaceRequestHandler<fuchsia::examples::inspect::Reverser> Reverser::CreateDefaultHandler(
        inspect::Node node) {
    

    Rust

    更新 ReverserServerFactory::new,在 reverser.rs 中接受這個節點:

    use fuchsia_inspect as inspect;
    pub struct ReverserServerFactory {
        node: inspect::Node,
        // ...
    }
    
    impl ReverserServerFactory {
        pub fn new(node: inspect::Node) -> Self {
            // ...
            Self {
                node,
                // ...
            }
        }
    
        // ...
    }
    
  3. 新增資源以追蹤連線數量:

    C++

    fidl::InterfaceRequestHandler<fuchsia::examples::inspect::Reverser> Reverser::CreateDefaultHandler(
        inspect::Node node) {
      // ...
    
      // Return a handler for incoming FIDL connections to Reverser.
      //
      // The returned closure contains a binding set, which is used to bind incoming requests to a
      // particular implementation of a FIDL interface. This particular binding set is configured to
      // bind incoming requests to unique_ptr<Reverser>, which means the binding set itself takes
      // ownership of the created Reversers and frees them when the connection is closed.
      return [connection_count = node.CreateUint("connection_count", 0), node = std::move(node),
              // ...
    

    Rust

    use {
        // ...
        fuchsia_inspect::NumericProperty,
        // ...
    };
    
    pub struct ReverserServerFactory {
        node: inspect::Node,
        // ...
        connection_count: inspect::UintProperty,
    }
    
    impl ReverserServerFactory {
        pub fn new(node: inspect::Node) -> Self {
            // ...
            let connection_count = node.create_uint("connection_count", 0);
            Self {
                node,
                // ...
                connection_count,
            }
        }
    
        pub fn spawn_new(&self, stream: ReverserRequestStream) {
            self.connection_count.add(1);
    

    程式碼片段示範如何建立一個名為 connection_count 的新 UintProperty (包含 64 位元未簽署的 int),並將其設定為 0。在 (針對每次連線執行) 中,屬性會按 1 遞增。

  4. 重新建構、重新執行元件,然後執行 ffx inspect

    C++

    $ ffx --machine json-pretty inspect show --manifest inspect_cpp_codelab
    

    Rust

    $ ffx --machine json-pretty inspect show --manifest inspect_rust_codelab
    

    您現在應該會看到:

    ...
    "payload": {
     "root": {
       "version": "part1",
       "reverser_service": {
         "connection_count": 1,
       }
     }
    }
    

上述輸出結果顯示用戶端已成功連線至服務,因此當機問題必須由反向實作本身造成。尤其是以下資訊:

  1. 在用戶端等待期間,如果連線仍為開啟狀態。

  2. 如果呼叫 Reverse 方法。

運動:為每個連線建立子節點,並在撤銷工具內記錄「request_count」。

  • 提示:有一個公用程式函式可以產生不重複名稱:

    C++

    auto child = node.CreateChild(node.UniqueName("connection-"));
    

    Rust

    let node = self.node.create_child(inspect::unique_name("connection"));
    

    這項操作會建立不重複的名稱,而且名稱開頭是「connection」。

C++

提示:建立採用 inspect::Node 的反向建構函式會相當實用。本程式碼研究室的第 3 部分說明瞭為什麼這是實用的模式。

Rust

提示:您會發現建立 ReverserServer 的建構函式,且採用 inspect::Node 的原因與 ReverserServerFactory 的方式相同。

  • 提示:您必須在撤銷者中建立成員,才能保留 request_count 屬性。其類型為 inspect::UintProperty

  • 後續追蹤:要求數量是否提供您需要的所有資訊?並新增 response_count

  • 進階:您是否可以在「所有」連線上新增「所有」要求的數量?撤銷物件必須共用某個狀態。建議您將引數重構為反向結構,這樣做可能會有幫助 (請參閱第 2 部分中的解決方案)。

完成本運動並執行 ffx inspect 後,畫面會顯示如下的內容:

...
"payload": {
  "root": {
    "version": "part1",
    "reverser_service": {
      "connection_count": 1,
      "connection0": {
        "request_count": 1,
      }
    }
  }
}

上方的輸出內容顯示連線仍在開啟,並收到一項要求。

C++

如果您也新增了「response_count」,可能會注意到這個錯誤。Reverse 方法會收到 callback,但絕不會使用 output 的值呼叫此方法。

Rust

如果您也新增了「response_count」,可能會注意到這個錯誤。Reverse 方法會收到 responder,但絕不會使用 result 的值呼叫此方法。

  1. 傳送回應:

    C++

    // At the end of Reverser::Reverse
    callback(std::move(output));
    

    Rust

    responder.send(&result).expect("send reverse request response");
    
  2. 再次執行用戶端:

    C++

    ffx component run --recreate /core/ffx-laboratory:client_part_1 fuchsia-pkg://fuchsia.com/inspect_cpp_codelab#meta/client_part_1.cm
    Creating component instance: client_part_1
    
    ffx log --tags inspect_cpp_codelab
    [00039.129068][39163][39165][inspect_cpp_codelab, client] INFO: Input: Hello
    [00039.194151][39163][39165][inspect_cpp_codelab, client] INFO: Output: olleH
    [00039.194170][39163][39165][inspect_cpp_codelab, client] INFO: Input: World
    [00039.194402][39163][39165][inspect_cpp_codelab, client] INFO: Output: dlroW
    [00039.194407][39163][39165][inspect_cpp_codelab, client] INFO: Done reversing! Please use `ffx component stop`
    

    Rust

    ffx component run --recreate /core/ffx-laboratory:client_part_1 fuchsia-pkg://fuchsia.com/inspect_rust_codelab#meta/client_part_1.cm
    Creating component instance: client_part_1
    
    ffx log --tags inspect_rust_codelab
    [00039.129068][39163][39165][inspect_rust_codelab, client] INFO: Input: Hello
    [00039.194151][39163][39165][inspect_rust_codelab, client] INFO: Output: olleH
    [00039.194170][39163][39165][inspect_rust_codelab, client] INFO: Input: World
    [00039.194402][39163][39165][inspect_rust_codelab, client] INFO: Output: dlroW
    [00039.194407][39163][39165][inspect_rust_codelab, client] INFO: Done reversing! Please use `ffx component stop`
    

元件會持續執行,直到您執行 ffx component stop 為止。只要元件執行,您就可以執行 ffx inspect 並觀察輸出內容。

本簡報到第 1 部分。您可以修訂目前為止所做的變更:

git commit -am "solution to part 1"

第 2 部分:診斷跨元件問題

您已收到錯誤報告。「FizzBuzz」團隊表示他們沒有收到您的元件資料。

除了提供撤銷通訊協定外,這個元件也會連線至「FizzBuzz」服務,並輸出回應:

C++

fuchsia::examples::inspect::FizzBuzzPtr fizz_buzz;
context->svc()->Connect(fizz_buzz.NewRequest());
fizz_buzz->Execute(30, [](std::string result) { FX_LOGS(INFO) << "Got FizzBuzz: " << result; });

Rust

let fizzbuzz_fut = async move {
    let fizzbuzz = client::connect_to_protocol::<FizzBuzzMarker>()
        .context("failed to connect to fizzbuzz")?;
    match fizzbuzz.execute(30u32).await {
        Ok(result) => info!(%result, "Got FizzBuzz"),
        Err(_) => {}
    };
    Ok(())
};

如果看到記錄,則會看到此記錄從未列印。

C++

ffx log --tags inspect_cpp_codelab

Rust

ffx log --tags inspect_rust_codelab

您需要診斷並解決這個問題。

使用檢查功能診斷問題

  1. 執行元件以瞭解情況:

    C++

    ffx component run /core/ffx-laboratory:client_part_2 fuchsia-pkg://fuchsia.com/inspect_cpp_codelab#meta/client_part_2.cm
    

    Rust

    ffx component run /core/ffx-laboratory:client_part_2 fuchsia-pkg://fuchsia.com/inspect_rust_codelab#meta/client_part_2.cm
    

    幸好,FizzBuzz 團隊已利用「檢查」檢測元件元件。

  2. 和先前一樣,使用 ffx inspect 讀取 FizzBuzz Inspect 資料,將可獲得:

    "payload": {
        "root": {
            "fizzbuzz_service": {
                "closed_connection_count": 0,
                "incoming_connection_count": 0,
                "request_count": 0,
                ...
    

    這項輸出會確認 FizzBuzz 未接收任何連線。

  3. 新增檢查功能以找出問題:

    C++

    // CODELAB: Instrument our connection to FizzBuzz using Inspect. Is there an error?
    fuchsia::examples::inspect::FizzBuzzPtr fizz_buzz;
    context->svc()->Connect(fizz_buzz.NewRequest());
    fizz_buzz.set_error_handler([&](zx_status_t status) {
      // CODELAB: Add Inspect here to see if there is a response.
    });
    fizz_buzz->Execute(30, [](std::string result) {
      // CODELAB: Add Inspect here to see if there was a response.
      FX_LOGS(INFO) << "Got FizzBuzz: " << result;
    });
    

    Rust

    let fizzbuzz_fut = async move {
        let fizzbuzz = client::connect_to_protocol::<FizzBuzzMarker>()
            .context("failed to connect to fizzbuzz")?;
        match fizzbuzz.execute(30u32).await {
            Ok(result) => {
                // CODELAB: Add Inspect here to see if there is a response.
                info!(%result, "Got FizzBuzz");
            }
            Err(_) => {
                // CODELAB: Add Inspect here to see if there is an error
            }
        };
        Ok(())
    };
    

運動:在 FizzBuzz 連線中加入檢查功能,藉此找出問題

  • 提示:使用上方的程式碼片段做為起點,其會提供錯誤處理常式來進行連線嘗試。

C++

後續追蹤:你可以將狀態儲存在某處嗎?您可以使用 zx_status_get_string(status) 將字串轉換為字串。

進階inspector 有一個名為 Health() 的方法,用於公告特殊位置的整體健康狀態。由於我們的服務必須連線至 FizzBuzz,因此才有健康狀態。您可以納入這項做法:

 /*
 "fuchsia.inspect.Health": {
     "status": "STARTING_UP"
 }
 */
 inspector.Health().StartingUp();

 /*
 "fuchsia.inspect.Health": {
     "status": "OK"
 }
 */
 inspector.Health().Ok();

 /*
 "fuchsia.inspect.Health": {
     "status": "UNHEALTHY",
     "message": "Something went wrong!"
 }
 */
 inspector.Health().Unhealthy("Something went wrong!");

Rust

進階fuchsia_inspect::component 有一個名為 health() 的函式,這個函式會傳回特殊位置 (檢查樹狀結構根層級節點子項) 的物件來宣告整體健康狀態。由於除非能連線至 FizzBuzz,否則我們的服務不會健康狀態良好,你可以納入這項做法:

/*
"fuchsia.inspect.Health": {
    "status": "STARTING_UP"
}
*/
fuchsia_inspect::component::health().set_starting_up();

/*
"fuchsia.inspect.Health": {
    "status": "OK"
}
*/
fuchsia_inspect::component::health().set_ok();

/*
"fuchsia.inspect.Health": {
    "status": "UNHEALTHY",
    "message": "Something went wrong!"
}
*/
fuchsia_inspect::component::health().set_unhealthy("something went wrong!");

完成這項練習後,您應該會看到連線錯誤處理常式受到「找不到」錯誤所呼叫。檢查輸出內容顯示 FizzBuzz 正在執行,因此可能有設定錯誤。但很遺憾,目前並非所有項目都使用檢查功能,因此查看記錄:

C++

$ ffx log --filter FizzBuzz
...
...  No capability available at path /svc/fuchsia.examples.inspect.FizzBuzz
for component /core/ffx-laboratory:client_part_2/reverser, verify the
component has the proper `use` declaration. ...

Rust

$ ffx log --filter FizzBuzz
...
... No capability available at path /svc/fuchsia.examples.inspect.FizzBuzz
for component /core/ffx-laboratory:client_part_2/reverser, verify the
component has the proper `use` declaration. ...

沙箱錯誤是難以發現的常見錯誤。

查看第 2 部分中繼後,您可以看出它缺少服務:

C++

Fizzbuzzuse 項目新增至 part_2/meta use: [ { protocol: "fuchsia.examples.inspect.FizzBuzz" }, ],

Rust

Fizzbuzzuse 項目新增至 part_2/meta use: [ { protocol: "fuchsia.examples.inspect.FizzBuzz" }, ],

加入「fuchsia.examples.inspect.FizzBuzz」後,請重新建構並再次執行。您現在應該會在記錄中看到 FizzBuzz 以及「OK」狀態:

C++

$ ffx log --tags inspect_cpp_codelab
[inspect_cpp_codelab, part2] INFO: main.cc(57): Got FizzBuzz: 1 2 Fizz
4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fizz
22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz

Rust

$ ffx log --tags inspect_rust_codelab
[inspect_rust_codelab, part2] INFO: main.rs(52): Got FizzBuzz: 1 2 Fizz
4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fizz
22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz

本章節到第 2 部分。

您現在可以修訂解決方案:

git commit -am "solution for part 2"

第 3 部分:檢查的單元測試

應該測試 Fuchsia 上的所有程式碼,這也適用於檢查資料。

雖然一般來說,檢查資料並非「必要」的測試範圍,但您需要測試依賴於其他工具 (例如分類或意見回饋) 的檢查資料。

撤銷工具有基本的單元測試。執行:

C++

單元測試位於 reverser_unittests.cc

fx test inspect_cpp_codelab_unittests

Rust

單元測試位於 reverser.rs > mod 測試

fx test inspect_rust_codelab_unittests

單元測試可確保撤銷工具正常運作 (不會停止運作!),但不會檢查「檢查」輸出內容是否符合預期。

將節點傳遞至建構函式是一種依附元件插入,可讓您傳遞依附元件的測試版本來檢查其狀態。

開啟撤銷工具的程式碼如下所示:

C++

binding_set_.AddBinding(std::make_unique<Reverser>(ReverserStats::CreateDefault()),
                        ptr.NewRequest());
// Alternatively
binding_set_.AddBinding(std::make_unique<Reverser>(inspect::Node()),
                        ptr.NewRequest());

Rust

let (proxy, stream) = fidl::endpoints::create_proxy_and_stream::<ReverserMarker>()?;
let reverser = ReverserServer::new(ReverserServerMetrics::default());
reverser.spawn(stream);

系統會將預設的檢查節點版本傳遞至撤銷工具。這可讓反向程式碼在測試中正確執行,但不支援檢查輸出內容的斷言。

C++

運動:變更 OpenReverser,將撤銷者的依附元件做為引數,並在建構還原工具時使用。

  • 提示:在測試函式中建立 inspect::Inspector。您可以使用 inspector.GetRoot() 取得根層級。

  • 提示:您必須在根層級建立子項,才能傳入 OpenReverser

Rust

運動:變更 open_reverser 以採用 ReverserServerFactory 的依附元件做為引數,並在建構撤銷工具時使用。

  • 提示:在測試函式中建立 fuchsia_inspect::Inspector。您可以使用 inspector.root() 取得根層級。

  • 注意:請不要在測試中直接使用 component::inspector(),這麼做會建立會在所有測試中生效的靜態檢查器,並可能導致暫時性或非預期行為。對單元測試來說,阿波偏好使用新的 fuchsia_inspect::Inspector

  • 提示:您必須在根層級建立子項,才能傳入 ReverserServerFactory::new

追蹤:建立多個反向連線並個別測試。

完成這項練習後,單元測試會在檢查階層中設定實際值。

新增程式碼,在「檢查」中測試輸出內容:

C++

#include <lib/inspect/testing/cpp/inspect.h>
fpromise::result<inspect::Hierarchy> hierarchy =
    RunPromise(inspect::ReadFromInspector(inspector));
ASSERT_TRUE(hierarchy.is_ok());

上方的程式碼片段會讀取包含檢查資料的基礎虛擬記憶體物件 (VMO),並將其剖析為可讀取的階層。

您現在可以讀取個別屬性和子項,如下所示:

auto* global_count =
    hierarchy.value().node().get_property<inspect::UintPropertyValue>("request_count");
ASSERT_TRUE(global_count);
EXPECT_EQ(3u, global_count->value());

auto* connection_0 = hierarchy.value().GetByPath({"connection_0x0"});
ASSERT_TRUE(connection_0);
auto* requests_0 =
    connection_0->node().get_property<inspect::UintPropertyValue>("request_count");
ASSERT_TRUE(requests_0);
EXPECT_EQ(2u, requests_0->value());

Rust

use diagnostics_assertions::assert_data_tree;
let inspector = inspect::Inspector::default();
assert_data_tree!(inspector, root: {
    reverser_service: {
        total_requests: 3u64,
        connection_count: 2u64,
        "connection0": {
            request_count: 2u64,
            response_count: 2u64,
        },
        "connection1": {
            request_count: 1u64,
            response_count: 1u64,
        },
    }
});

上述程式碼片段會從包含檢查資料的基礎虛擬記憶體物件 (VMO) 讀取快照,並將其剖析為可讀取的階層。

運動:為檢查的其他資料新增斷言。

本章節到第 3 部分。

您可以修訂變更:

git commit -am "solution to part 3"

第 4 部分:檢查的整合測試

整合測試是 Fuuchsia 軟體開發工作流程中重要的一環。整合測試可讓您觀察實際元件在系統執行時的行為。

執行整合測試

您可以按照下列步驟執行程式碼研究室的整合測試:

C++

$ fx test inspect_cpp_codelab_integration_tests

Rust

$ fx test inspect_rust_codelab_integration_tests

查看程式碼

以下說明整合測試的設定方式:

  1. 查看整合測試的元件資訊清單:

    C++

    part_4/meta 中找到元件資訊清單 (cml)

    Rust

    part_4/meta 中找到元件資訊清單 (cml)

{
   ...
   use: [
       { protocol: "fuchsia.diagnostics.ArchiveAccessor" },
   ]
}

此檔案使用父項的通訊協定 fuchsia.diagnostics.ArchiveAccessor。這個通訊協定適用於所有測試,都能讀取測試領域下所有元件的診斷資訊。

  1. 查看整合測試本身。個別測試案例相當簡單:

    C++

    part4/tests/integration_test.cc 中找到整合測試。

    TEST_F(IntegrationTestPart4, StartWithFizzBuzz) {
      auto ptr = ConnectToReverser({.include_fizzbuzz = true});
    
      bool error = false;
      ptr.set_error_handler([&](zx_status_t unused) { error = true; });
    
      bool done = false;
      std::string result;
      ptr->Reverse("hello", [&](std::string value) {
        result = std::move(value);
        done = true;
      });
      RunLoopUntil([&] { return done || error; });
    
      ASSERT_FALSE(error);
      EXPECT_EQ("olleh", result);
    
      // CODELAB: Check that the component was connected to FizzBuzz.
    }
    

    StartComponentAndConnect 負責建立新的測試環境,並啟動其中的程式碼研究室元件。include_fizzbuzz_service 選項會指示方法是否要加入 FizzBuzz。這項功能會測試您的檢查輸出內容是否符合預期,以免在無法像第 2 部分一樣連線至 FizzBuzz。

    Rust

    part4/tests/integration_test.rs 中找出整合測試。

    #[fuchsia::test]
    async fn start_with_fizzbuzz() -> Result<(), Error> {
        let test = IntegrationTest::start(4, TestOptions::default()).await?;
        let reverser = test.connect_to_reverser()?;
        let result = reverser.reverse("hello").await?;
        assert_eq!(result, "olleh");
    
        // CODELAB: Check that the component was connected to FizzBuzz.
    
        Ok(())
    }
    

    IntegrationTest::start 負責建立新的測試環境,並啟動其中的程式碼研究室元件。include_fizzbuzz 選項會指示方法選擇性啟動 FizzBuzz 元件。這項功能會測試,在無法像第 2 部分一樣連線至 FizzBuzz 時,您的檢查輸出內容是否如預期運作。

  2. 將下列方法新增到測試固件,從 ArchiveAccessor 服務讀取資料:

    C++

    #include <rapidjson/document.h>
    #include <rapidjson/pointer.h>
    std::string GetInspectJson() {
      fuchsia::diagnostics::ArchiveAccessorPtr archive;
      auto svc = sys::ServiceDirectory::CreateFromNamespace();
      svc->Connect(archive.NewRequest());
    
      while (true) {
        ContentVector current_entries;
    
        fuchsia::diagnostics::BatchIteratorPtr iterator;
        fuchsia::diagnostics::StreamParameters stream_parameters;
        stream_parameters.set_data_type(fuchsia::diagnostics::DataType::INSPECT);
        stream_parameters.set_stream_mode(fuchsia::diagnostics::StreamMode::SNAPSHOT);
        stream_parameters.set_format(fuchsia::diagnostics::Format::JSON);
    
        {
          std::vector<fuchsia::diagnostics::SelectorArgument> args;
          args.emplace_back();
          args[0].set_raw_selector(ReverserMonikerForSelectors() + ":root");
    
          fuchsia::diagnostics::ClientSelectorConfiguration client_selector_config;
          client_selector_config.set_selectors(std::move(args));
          stream_parameters.set_client_selector_configuration(std::move(client_selector_config));
        }
        archive->StreamDiagnostics(std::move(stream_parameters), iterator.NewRequest());
    
        bool done = false;
        iterator->GetNext([&](auto result) {
          if (result.is_response()) {
            current_entries = std::move(result.response().batch);
          }
    
          done = true;
        });
    
        RunLoopUntil([&] { return done; });
    
        // Should be at most one component.
        ZX_ASSERT(current_entries.size() <= 1);
        if (!current_entries.empty()) {
          std::string json;
          fsl::StringFromVmo(current_entries[0].json(), &json);
          // Ensure the component is either OK or UNHEALTHY.
          if (json.find("OK") != std::string::npos || json.find("UNHEALTHY") != std::string::npos) {
            return json;
          }
        }
    
        // Retry with delay until the data appears.
        usleep(150000);
      }
    
      return "";
    }
    

    Rust

    use {
        anyhow::format_err,
        diagnostics_assertions::{assert_data_tree, AnyProperty},
        diagnostics_reader::{ArchiveReader, DiagnosticsHierarchy, Inspect},
    };
    async fn get_inspect_hierarchy(test: &IntegrationTest) -> Result<DiagnosticsHierarchy, Error> {
        let moniker = test.reverser_moniker_for_selectors();
        ArchiveReader::new()
            .add_selector(format!("{}:root", moniker))
            .snapshot::<Inspect>()
            .await?
            .into_iter()
            .next()
            .and_then(|result| result.payload)
            .ok_or(format_err!("expected one inspect hierarchy"))
    }
    
  3. 運動。在測試中使用傳回的資料,並將斷言新增至傳回的資料:

    C++

    rapidjson::Document document;
    document.Parse(GetInspectJson());
    

    針對傳回的 JSON 資料新增斷言。

    • 提示:列印 JSON 輸出內容以查看結構定義。

    • 提示:您可以按照以下方式按照路徑讀取值:

    • 提示:您可以以快速 json::Value: rapidjson::Value("OK") 的形式傳入預期值來 EXPECT_EQ

    rapidjson::GetValueByPointerWithDefault(
        document, "/payload/root/fuchsia.inspect.Health/status", "")
    

    Rust

    let hierarchy = get_inspect_hierarchy(&test).await?;
    

    在傳回的 DiagnosticsHierarchy 上新增斷言。

    • 提示:列印 JSON 輸出內容以查看結構定義。

整合測試現在可確認您的檢查輸出內容正確無誤。

本簡報到第 4 部分。

可以提議的解決方案:

git commit -am "solution to part 4"

第 5 部分:意見回饋選取器

這個部分仍在建構中。

  • 任務:編寫意見回饋選取器,並在整合測試中新增測試。

  • 待辦事項:意見回饋工具和其他管道的選取工具