宣告元件

每個元件都有描述元件屬性和功能的宣告。若是以套件形式發布的元件,系統會使用元件資訊清單檔案表示宣告,並在元件解析器的協助下載入。

這張圖表顯示如何使用「元件資訊清單」宣告元件。資訊清單是由開發人員工具編譯,並在執行階段解析至裝置。

您可以使用元件資訊清單語言 (CML) 檔案宣告元件。在建構期間,元件資訊清單編譯器 (cmc) 工具會驗證資訊清單來源並編譯為二進位格式 (.cm),然後將其儲存在元件套件中。 ComponentDecl

元件資訊清單

CML 檔案是 JSON5 檔案,結尾為 .cml 副檔名。以下是執行 ELF 二進位檔的簡單元件 CML 資訊清單檔案範例,該元件會在系統記錄中顯示「Hello, World」訊息:

{
    // Information about the program to run.
    program: {
        // Use the built-in ELF runner.
        runner: "elf",
        // The binary to run for this component.
        binary: "bin/hello",
        // Program arguments
        args: [
            "Hello",
            "World!",
        ],
    },

    // Capabilities used by this component.
    use: [
        { protocol: "fuchsia.logger.LogSink" },
    ],
}

這個檔案宣告元件的兩個主要資訊部分:

  • program:說明可執行資訊,例如二進位檔案、程式引數,以及相關聯的執行階段。在這個範例中,二進位檔會編譯為 ELF 執行檔,並使用內建的 ELF 執行器
  • use:宣告這個元件需要執行的功能。在此範例中,fuchsia.logger.LogSink 通訊協定可讓元件將訊息寫入系統記錄 (syslog)。

資訊清單資料分割

功能集合代表系統中許多元件通用的用途需求,例如記錄。為了簡化在元件中加入這些功能,架構會將這些功能抽象化至可納入 CML 來源檔案中的資訊清單資料分割

下方是與先前範例相等的 CML。在這種情況下,系統會透過加入 diagnostics/syslog/client.shard.cml 提供必要的記錄功能,而不是明確宣告 fuchsia.logger.LogSink

{
    include: [ "syslog/client.shard.cml" ],

    // Information about the program to run.
    program: {
        // Use the built-in ELF runner.
        runner: "elf",
        // The binary to run for this component.
        binary: "bin/hello-world",
        // Program arguments
        args: [
            "Hello",
            "World!",
        ],
    },
}

建築元件

Fuchsia 建構系統在 //build/components.gni 中提供 GN 匯入範本,用於建構軟體並套件至 Fuchsia 元件。以下是簡易 C++ 元件的 BUILD.gn 檔案範例:


import("//build/components.gni")

executable("bin") {
  sources = [ "main.cc" ]
}

resource("my_file") {
  sources = [ "my_file.txt" ]
  outputs = [ "data/{{source_file_part}}" ]
}

fuchsia_component("hello-world-component") {
  component_name = "hello-world"
  deps = [
    ":bin",
    ":my_file",
  ]
  manifest = "meta/hello-world.cml"
}

fuchsia_package("hello-world") {
  package-name = "hello-world"
  deps = [
    ":hello-world-component",
  ]
}

此檔案包含下列主要元素:

  • executable():將原始碼編譯為二進位檔。這個目標會因程式設計語言而有所不同。舉例來說,executable 目標可用於 C++、rustc_binary 適用於 Rust、go_binary 適用於 Golang。
  • resource():非必要的資料檔案集合,做為資源複製到另一個 GN 目標。這些檔案可供元件命名空間中的二進位檔存取。
  • fuchsia_component():將二進位檔、元件資訊清單和其他資源一併收集至單一目標。這個目標會使用 cmc,將資訊清單來源編譯為元件宣告。
  • fuchsia_package():元件的分佈單位。允許將一或多個元件託管於套件存放區,並納入目標裝置的套件集。這個目標會產生套件中繼資料,並建構 Fuchsia 封存 (.far) 檔案。

套件可以包含多個元件,在 fuchsia_package() 範本中會顯示為 deps。對於只包含一個元件的套件,您可以使用 fuchsia_package_with_single_component() 範本簡化建構檔案。

下列簡化的 BUILD.gn 範例等同於上一個範例:


import("//build/components.gni")

executable("bin") {
  sources = [ "main.cc" ]
}

resource("my_file") {
  sources = [ "my_file.txt" ]
  outputs = [ "data/{{source_file_part}}" ]
}

fuchsia_package_with_single_component("hello-world") {
  manifest = "meta/hello-world.cml"
  deps = [
    ":bin",
    ":my_file",
  ]
}

運動:建立新元件

在本練習中,您將建構並執行基本元件,用於讀取程式引數,並回應問候語的問候語。

首先,請在 //vendor/fuchsia-codelab 目錄中為名為 echo-args 的新元件建立專案鷹架:

mkdir -p vendor/fuchsia-codelab/echo-args

在新專案目錄中建立以下檔案和目錄結構:

Rust

//vendor/fuchsia-codelab/echo-args
                        |- BUILD.gn
                        |- meta
                        |   |- echo.cml
                        |
                        |- src
                            |- main.rs
  • BUILD.gn:適用於可執行二進位檔、元件和套件的 GN 建構目標。
  • meta/echo.cml:資訊清單會宣告元件的執行檔和必要功能。
  • src/main.rs:Rust 可執行二進位檔和單元測試的原始碼。

C++

//vendor/fuchsia-codelab/echo-args
                        |- BUILD.gn
                        |- meta
                        |   |- echo.cml
                        |
                        |- echo_component.cc
                        |- echo_component.h
                        |- main.cc
  • BUILD.gn:適用於可執行二進位檔、元件和套件的 GN 建構目標。
  • meta/echo.cml:資訊清單會宣告元件的執行檔和必要功能。
  • echo_component.cc:C++ 元件功能的原始碼。
  • main.cc:C++ 可執行二進位檔主要進入點的原始碼。

新增程式引數

元件資訊清單檔案定義了元件執行檔的屬性,包括程式引數和元件的功能。將下列內容新增至 meta/echo.cml

Rust

echo-args/meta/echo.cml:

{
    include: [
        // Enable logging on stdout
        "syslog/client.shard.cml",
    ],

    // Information about the program to run.
    program: {
        // Use the built-in ELF runner.
        runner: "elf",

        // The binary to run for this component.
        binary: "bin/echo-args",

        // Program arguments
        args: [
            "Alice",
            "Bob",
        ],

        // Program environment variables
        environ: [ "FAVORITE_ANIMAL=Spot" ],
    },
}

C++

echo-args/meta/echo.cml:

{
    include: [
        // Enable logging.
        "syslog/client.shard.cml",
    ],

    // Information about the program to run.
    program: {
        // Use the built-in ELF runner.
        runner: "elf",

        // The binary to run for this component.
        binary: "bin/echo-args",

        // Program arguments
        args: [
            "Alice",
            "Bob",
        ],

        // Program environment variables
        environ: [ "FAVORITE_ANIMAL=Spot" ],
    },
}

記錄引數

開啟主要執行檔的來源檔案,並新增下列匯入陳述式:

Rust

echo-args/src/main.rs:

use tracing::info;

C++

echo-args/main.cc:

#include <lib/syslog/cpp/log_settings.h>
#include <lib/syslog/cpp/macros.h>

#include <cstdlib>
#include <iostream>

#include "vendor/fuchsia-codelab/echo-args/echo_component.h"

新增以下程式碼,實作 main() 函式:

Rust

echo-args/src/main.rs:

#[fuchsia::main(logging = true)]
async fn main() -> Result<(), anyhow::Error> {
    // Read program arguments, and strip off binary name
    let mut args: Vec<String> = std::env::args().collect();
    args.remove(0);

    // Include environment variables
    let animal = std::env::var("FAVORITE_ANIMAL").unwrap();
    args.push(animal);

    // Print a greeting to syslog
    info!("Hello, {}!", greeting(&args));

    Ok(())
}

C++

echo-args/main.cc:

int main(int argc, const char* argv[], char* envp[]) {
  fuchsia_logging::SetTags({"echo"});
  // Read program arguments, and exclude the binary name in argv[0]
  std::vector<std::string> arguments;
  for (int i = 1; i < argc; i++) {
    arguments.push_back(argv[i]);
  }

  // Include environment variables
  const char* favorite_animal = std::getenv("FAVORITE_ANIMAL");
  arguments.push_back(favorite_animal);

  // Print a greeting to syslog
  FX_SLOG(INFO, "Hello", FX_KV("greeting", echo::greeting(arguments).c_str()));

  return 0;
}

此程式碼會讀取程式引數,並傳遞至名為 greeting() 的函式,以產生系統記錄項目的回應。

新增以下程式碼,實作 greeting() 函式:

Rust

echo-args/src/main.rs:

// Return a proper greeting for the list
fn greeting(names: &Vec<String>) -> String {
    // Join the list of names based on length
    match names.len() {
        0 => String::from("Nobody"),
        1 => names.join(""),
        2 => names.join(" and "),
        _ => names.join(", "),
    }
}

C++

echo-args/echo_component.h:

#include <string>
#include <vector>

namespace echo {

std::string greeting(std::vector<std::string>& names);

}  // namespace echo

echo-args/echo_component.cc:

#include "vendor/fuchsia-codelab/echo-args/echo_component.h"

#include <numeric>

namespace echo {

static std::string join(std::vector<std::string>& input_list, const std::string& separator) {
  return std::accumulate(std::begin(input_list), std::end(input_list), std::string(""),
                         [&separator](std::string current, std::string& next) {
                           return current.empty() ? next : (std::move(current) + separator + next);
                         });
}

// Return a proper greeting for the list
std::string greeting(std::vector<std::string>& names) {
  // Join the list of names based on length
  auto number_of_names = names.size();
  switch (number_of_names) {
    case 0:
      return "Nobody!";
    case 1:
      return join(names, "");
    case 2:
      return join(names, " and ");
    default:
      return join(names, ", ");
  }
}

}  // namespace echo

這個函式會根據清單長度,從提供的引數清單中建立簡單字串。

新增至建構設定

更新 BUILD.gn 檔案中程式的依附元件:

Rust

echo-args/BUILD.gn:

import("//build/components.gni")
import("//build/rust/rustc_binary.gni")


group("echo-args") {
  testonly = true
  deps = [
    ":package",
  ]
}

rustc_binary("bin") {
  output_name = "echo-args"
  edition = "2021"

  # Generates a GN target for unit-tests with the label `bin_test`,
  # and a binary named `echo_bin_test`.
  with_unit_tests = true

  deps = [
    "//src/lib/fuchsia",
    "//third_party/rust_crates:anyhow",
    "//third_party/rust_crates:tracing",
  ]

  sources = [ "src/main.rs" ]
}

fuchsia_component("component") {
  component_name = "echo-args"
  manifest = "meta/echo.cml"
  deps = [ ":bin" ]
}

fuchsia_package("package") {
  package_name = "echo-args"
  deps = [ ":component" ]
}

C++

echo-args/BUILD.gn:

import("//build/components.gni")


group("echo-args") {
  testonly = true
  deps = [
    ":package",
  ]
}

executable("bin") {
  output_name = "echo-args"

  sources = [ "main.cc" ]

  deps = [
    ":cpp-lib",
    "//sdk/lib/syslog/cpp",
    "//zircon/system/ulib/async-default",
    "//zircon/system/ulib/async-loop:async-loop-cpp",
    "//zircon/system/ulib/async-loop:async-loop-default",
  ]
}

source_set("cpp-lib") {
  sources = [
    "echo_component.cc",
    "echo_component.h",
  ]
}

fuchsia_component("component") {
  component_name = "echo-args"
  manifest = "meta/echo.cml"
  deps = [ ":bin" ]
}

fuchsia_package("package") {
  package_name = "echo-args"
  deps = [ ":component" ]
}

將新元件新增至建構設定:

fx set workstation_eng.x64 --with //vendor/fuchsia-codelab/echo-args

執行 fx build,並確認建構作業已成功完成:

fx build

在下一節中,您會將這個元件整合至建構作業,並在系統記錄中測試輸出內容。