Pular para conteúdo

Prática 07 - Camadas da Comunidade e Receitas com CMake e Git

Note

Esta prática é feita no build do QEMU.

  • Diretório de build: ~/treinamento/yp/poky/build-qemu
  • Camada: ~/treinamento/yp/poky/meta-treinamento


Nesta prática vamos:

  1. Pesquisar camadas, receitas e machines no OpenEmbedded Layer Index.
  2. Adicionar as camadas do meta-openembedded ao projeto.
  3. Criar uma receita para um projeto CMake e resolver um erro de dependência.
  4. Criar uma receita que baixa o código de um repositório Git.


Parte 1 - Pesquisando no Layer Index

O Layer Index é o catálogo das camadas da comunidade. Antes de escrever uma receita, sempre procure aqui se ela já existe.

Acesse o Layer Index já no branch scarthgap: https://layers.openembedded.org/layerindex/branch/scarthgap/layers/

  1. Em Layers, pesquise por xilinx. Quantas camadas existem e quem mantém cada uma?

  2. Em Recipes, pesquise por python3-certifi, firefox e greengrass-lite. Anote em qual camada está cada receita: é ela que você precisaria clonar e adicionar ao projeto para usar o pacote.

    DICA

    Em Recipes também é possível combinar filtros:

    layer:meta-qt5          receitas de uma camada
    depends:opencv          receitas que dependem do OpenCV
    
  3. Em Machines, pesquise por raspberrypi5, stm32mp1 e colibri-imx8x. Anote a camada de BSP de cada placa.


Parte 2 - Adicionando as camadas do meta-openembedded

O meta-openembedded é um repositório com várias camadas da comunidade (meta-oe, meta-python, meta-networking...). Clone o repositório no branch scarthgap, o mesmo do Poky:

Executar no HOST
cd ~/treinamento/yp/poky

git clone -b scarthgap https://git.openembedded.org/meta-openembedded

Warning

Sempre clone as camadas no mesmo branch do Poky (scarthgap). Camadas de branches diferentes não são compatíveis entre si.


Carregue o ambiente do build e adicione as camadas com um único comando:

Executar no HOST
source oe-init-build-env build-qemu

bitbake-layers add-layer \
    ../meta-openembedded/meta-oe \
    ../meta-openembedded/meta-python \
    ../meta-openembedded/meta-networking \
    ../meta-openembedded/meta-multimedia \
    ../meta-openembedded/meta-filesystems \
    ../meta-openembedded/meta-initramfs

Note

A ordem importa: cada camada declara de quais outras depende (variável LAYERDEPENDS no conf/layer.conf). Por exemplo, a meta-networking depende da meta-python e da meta-oe. Se uma camada for adicionada antes das suas dependências, o bitbake-layers mostra um erro semelhante a:

ERROR: Layer 'networking-layer' depends on layer 'meta-python', but this layer is not enabled in your configuration


Verifique o resultado:

Executar no HOST
bitbake-layers show-layers

Saída esperada:

layer                 path                                                                    priority
========================================================================================================
core                  /home/b2open/treinamento/yp/poky/meta                                   5
yocto                 /home/b2open/treinamento/yp/poky/meta-poky                              5
yoctobsp              /home/b2open/treinamento/yp/poky/meta-yocto-bsp                         5
meta-treinamento      /home/b2open/treinamento/yp/poky/meta-treinamento                       6
openembedded-layer    /home/b2open/treinamento/yp/poky/meta-openembedded/meta-oe              5
meta-python           /home/b2open/treinamento/yp/poky/meta-openembedded/meta-python          5
networking-layer      /home/b2open/treinamento/yp/poky/meta-openembedded/meta-networking      5
multimedia-layer      /home/b2open/treinamento/yp/poky/meta-openembedded/meta-multimedia      5
filesystems-layer     /home/b2open/treinamento/yp/poky/meta-openembedded/meta-filesystems     5
meta-initramfs        /home/b2open/treinamento/yp/poky/meta-openembedded/meta-initramfs       5

DICA

Na seção Dicas Extras e Avançadas tem a dica Baixando Camadas via bitbake-layers, que clona e adiciona a camada em um passo só, para camadas que estão no Layer Index.


Parte 3 - Receita para projeto CMake

Vamos criar a receita b2open-usbmon, um programa que lista os dispositivos USB e monitora quando são conectados ou removidos, usando a biblioteca libudev.

Crie o diretório e os arquivos do projeto:

Executar no HOST
cd ~/treinamento/yp/poky/meta-treinamento/recipes-b2open/apps

mkdir b2open-usbmon

touch b2open-usbmon/usb_mon.c

touch b2open-usbmon/CMakeLists.txt


No arquivo b2open-usbmon/usb_mon.c adicione o código abaixo:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libudev.h>

void show_device(struct udev_device *dev)
{
        if (dev) {
            if (udev_device_get_devnode(dev)) {
                  const char* action = udev_device_get_action(dev);

                  const char* vendor =
udev_device_get_sysattr_value(dev,"idVendor");
                  if (! vendor)
                        vendor = "0000";

                  const char* product =
udev_device_get_sysattr_value(dev,"idProduct");
                  if (! product)
                        product = "0000";

                  printf("%s %s %6s %s:%s %s\n",
                              udev_device_get_subsystem(dev),
                              udev_device_get_devtype(dev),
                              action,
                              vendor,
                              product,
                              udev_device_get_devnode(dev));
            }
      }
}

static void monitor_devices(struct udev* udev)
{
    struct udev_monitor* mon = udev_monitor_new_from_netlink(udev,"udev");

    udev_monitor_filter_add_match_subsystem_devtype(mon, "usb", NULL);
    udev_monitor_enable_receiving(mon);

    int fd = udev_monitor_get_fd(mon);

    /*
     * select() -> https://man7.org/linux/man-pages/man2/select.2.html
     */
    while (1) {
           fd_set fds;
           FD_ZERO(&fds);
           FD_SET(fd, &fds);

           int ret = select(fd+1, &fds, NULL, NULL, NULL);
           if (ret <= 0)
                break;

           if (FD_ISSET(fd, &fds)) {
                 struct udev_device* dev = udev_monitor_receive_device(mon);
                show_device(dev);

           }

     }
}

int main()
{
      struct udev *udev;
      struct udev_enumerate *enumerate;
      struct udev_list_entry *devices, *dev_list_entry;

      /* create udev object */
      udev = udev_new();
      if (!udev) {
            fprintf(stderr, "Cannot create udev context.\n");
            return 1;
      }

      /* create enumerate object */
      enumerate = udev_enumerate_new(udev);
      if (!enumerate) {
            fprintf(stderr, "Cannot create enumerate context.\n");
            return 1;
      }

      udev_enumerate_add_match_subsystem(enumerate,"usb");
      udev_enumerate_scan_devices(enumerate);

      /* fillup device list */
      devices = udev_enumerate_get_list_entry(enumerate);
      if (!devices) {
            fprintf(stderr,"Failed to get device list.\n");
            return 1;
      }

      udev_list_entry_foreach(dev_list_entry, devices) {
            const char *path;
            path = udev_list_entry_get_name(dev_list_entry);
            struct udev_device* dev = udev_device_new_from_syspath(udev,path);

            show_device(dev);

            /* free dev */
            udev_device_unref(dev);
      }


      /* free enumerate */
      udev_enumerate_unref(enumerate);

      /* Loop Monitor Events Udev (add and remove devices */
      monitor_devices(udev);


      /* free udev */
      udev_unref(udev);

      return 0;
}


No arquivo b2open-usbmon/CMakeLists.txt adicione:

cmake_minimum_required(VERSION 3.12)
project(usb_mon C)

set(CMAKE_C_STANDARD 11)

# Encontre a biblioteca libudev
find_package(PkgConfig REQUIRED)
pkg_check_modules(UDEV REQUIRED libudev)

# Adicione o diretório de inclusao e as bibliotecas da libudev
include_directories(${UDEV_INCLUDE_DIRS})
link_directories(${UDEV_LIBRARY_DIRS})

# Adicione os arquivos-fonte do seu programa
add_executable(usb_mon usb_mon.c)

# Vincule seu programa com a libudev
target_link_libraries(usb_mon ${UDEV_LIBRARIES})


Crie a receita b2open-usbmon_1.0.bb:

Executar no HOST
touch b2open-usbmon_1.0.bb
DESCRIPTION = "B2Open Application USB Monitor"
SECTION = "examples"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"

SRC_URI = " \
    file://CMakeLists.txt \
    file://usb_mon.c \
    "

S = "${WORKDIR}"

inherit cmake pkgconfig

do_install() {
    install -d ${D}${bindir}
    install -m 0755 usb_mon ${D}${bindir}/b2open-usbmon
}

Repare no inherit cmake pkgconfig: a classe cmake já sabe configurar e compilar projetos CMake, por isso a receita não precisa de do_configure nem de do_compile.


Confira a estrutura da camada:

Executar no HOST
cd ~/treinamento/yp/poky/meta-treinamento

tree recipes-b2open/

Saída esperada:

recipes-b2open/
└── apps
    ├── b2open-hello
    │   └── main.c
    ├── b2open-hello_1.0.bb
    ├── b2open-usbmon
    │   ├── CMakeLists.txt
    │   └── usb_mon.c
    └── b2open-usbmon_1.0.bb

4 directories, 5 files


Volte para o build e compile:

Executar no HOST
cd ~/treinamento/yp/poky/build-qemu

bitbake b2open-usbmon


O build falha na tarefa do_configure. Saída esperada (trecho):

NOTE: Executing Tasks
ERROR: b2open-usbmon-1.0-r0 do_configure: ExecutionError('/home/b2open/treinamento/yp/poky/build-qemu/tmp/work/cortexa15t2hf-neon-poky-linux-gnueabi/b2open-usbmon/1.0/temp/run.do_configure.9094', 1, None, None)
ERROR: Logfile of failure stored in: /home/b2open/treinamento/yp/poky/build-qemu/tmp/work/cortexa15t2hf-neon-poky-linux-gnueabi/b2open-usbmon/1.0/temp/log.do_configure.9094
Log data follows:
| DEBUG: Executing python function extend_recipe_sysroot
| NOTE: Direct dependencies are ['/home/b2open/treinamento/yp/poky/meta/recipes-core/glibc/glibc_2.39.bb:do_populate_sysroot', '/home/b2open/treinamento/yp/poky/meta/recipes-devtools/cmake/cmake-native_3.28.3.bb:do_populate_sysroot', '/home/b2open/treinamento/yp/poky/meta/recipes-devtools/gcc/gcc-cross_13.5.bb:do_populate_sysroot', '/home/b2open/treinamento/yp/poky/meta/recipes-devtools/gcc/gcc-runtime_13.5.bb:do_populate_sysroot', '/home/b2open/treinamento/yp/poky/meta/recipes-devtools/quilt/quilt-native_0.67.bb:do_populate_sysroot', 'virtual:native:/home/b2open/treinamento/yp/poky/meta/recipes-devtools/ninja/ninja_1.11.1.bb:do_populate_sysroot', 'virtual:native:/home/b2open/treinamento/yp/poky/meta/recipes-devtools/patch/patch_2.7.6.bb:do_populate_sysroot', 'virtual:native:/home/b2open/treinamento/yp/poky/meta/recipes-devtools/pkgconfig/pkgconfig_git.bb:do_populate_sysroot', 'virtual:native:/home/b2open/treinamento/yp/poky/meta/recipes-devtools/pseudo/pseudo_git.bb:do_populate_sysroot']
| NOTE: Installed into sysroot: []
| NOTE: Skipping as already exists in sysroot: ['gettext-minimal-native', 'glibc', 'binutils-cross-arm', 'cmake-native', 'gcc-cross-arm', 'gcc-runtime', 'libgcc', 'libtool-native', 'm4-native', 'quilt-native', 'texinfo-dummy-native', 'linux-libc-headers', 'openssl-native', 'ncurses-native', 'zlib-native', 'flex-native', 'gnu-config-native', 'make-native', 'ninja-native', 'patch-native', 'perl-native', 'pkgconfig-native', 'pseudo-native', 'bzip2-native', 'xz-native', 'zstd-native', 'attr-native', 'gdbm-native', 'gmp-native', 'libmpc-native', 'mpfr-native', 're2c-native', 'sqlite3-native']
| DEBUG: Python function extend_recipe_sysroot finished
| DEBUG: Executing shell function do_configure
| -- The C compiler identification is GNU 13.5.0
| -- Detecting C compiler ABI info
| -- Detecting C compiler ABI info - done
| -- Check for working C compiler: /home/b2open/treinamento/yp/poky/build-qemu/tmp/work/cortexa15t2hf-neon-poky-linux-gnueabi/b2open-usbmon/1.0/recipe-sysroot-native/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-gcc - skipped
| -- Detecting C compile features
| -- Detecting C compile features - done
| -- Found PkgConfig: /home/b2open/treinamento/yp/poky/build-qemu/tmp/work/cortexa15t2hf-neon-poky-linux-gnueabi/b2open-usbmon/1.0/recipe-sysroot-native/usr/bin/pkg-config (found version "0.29.2")
| -- Checking for module 'libudev'
| --   No package 'libudev' found
| CMake Error at recipe-sysroot-native/usr/share/cmake-3.28/Modules/FindPkgConfig.cmake:619 (message):
|   The following required packages were not found:
| 
|    - libudev
| 
| Call Stack (most recent call first):
|   recipe-sysroot-native/usr/share/cmake-3.28/Modules/FindPkgConfig.cmake:841 (_pkg_check_modules_internal)
|   CMakeLists.txt:8 (pkg_check_modules)
| 
| 
| -- Configuring incomplete, errors occurred!
| WARNING: exit code 1 from a shell command.
ERROR: Task (/home/b2open/treinamento/yp/poky/meta-treinamento/recipes-b2open/apps/b2open-usbmon_1.0.bb:do_configure) failed with exit code '1'
NOTE: Tasks Summary: Attempted 856 tasks of which 846 didn't need to be rerun and 1 failed.


A mensagem No package 'libudev' found mostra que a biblioteca não está disponível no sysroot da receita. Cada receita compila isolada e só enxerga as bibliotecas que declarou como dependência de build. A libudev é fornecida pela receita udev (no scarthgap, implementada pelo systemd ou pelo eudev, conforme a distro).

Adicione na receita b2open-usbmon_1.0.bb, acima do SRC_URI:

DEPENDS += "udev"


Compile novamente e confira o binário gerado:

Executar no HOST
bitbake b2open-usbmon

tree $(bitbake-getvar -q -r b2open-usbmon --value D)

Saída esperada (semelhante a):

/home/b2open/treinamento/yp/poky/build-qemu/tmp/work/cortexa15t2hf-neon-poky-linux-gnueabi/b2open-usbmon/1.0/image
└── usr
    └── bin
        └── b2open-usbmon

3 directories, 1 file

DICA

A variável D é o diretório onde o do_install instala os arquivos. Com o bitbake-getvar não é preciso decorar o caminho completo, que muda conforme a arquitetura e a distro.


Parte 4 - Receita que baixa o código de um repositório Git

Crie a receita b2-sniffer_git.bb:

Executar no HOST
cd ~/treinamento/yp/poky/meta-treinamento/recipes-b2open/apps/

touch b2-sniffer_git.bb
SUMMARY = "Sniffer B2Open Systems in C++ and based in libpcap"
DESCRIPTION = "Simple sniffer in C++ with libpcap to capture and save pcap files. \
Use wireshark to view the generated .pcap files."
LICENSE = "Apache-2.0"
LIC_FILES_CHKSUM = "file://LICENSE;md5=86d3f3a95c324c9479bd8986968f4327"

DEPENDS = "libcap libpcap"

SRC_URI = "gitsm://github.com/b2open/b2-sniffer.git;protocol=https;branch=main"
SRCREV = "2822051cca9e34363424e09d5d440e8f6a7b22ac"

S = "${WORKDIR}/git"

inherit cmake pkgconfig

Destaques da receita:

  • gitsm://: baixa o repositório Git e também os submódulos (o b2-sniffer usa a biblioteca fmt como submódulo).
  • SRCREV: o commit exato a ser usado. Fixar o commit garante que o build seja reproduzível.
  • S = "${WORKDIR}/git": o fetcher Git sempre coloca o código no diretório git.
  • LIC_FILES_CHKSUM: aponta para o arquivo LICENSE do próprio projeto.


Volte para o build e compile:

Executar no HOST
cd ~/treinamento/yp/poky/build-qemu/

bitbake b2-sniffer


O build falha na tarefa do_compile. Saída esperada (trecho):

| FAILED: CMakeFiles/b2-sniffer.dir/b2sniffer.cpp.o
| /home/b2open/treinamento/yp/poky/build-qemu/tmp/work/cortexa15t2hf-neon-poky-linux-gnueabi/b2-sniffer/git/recipe-sysroot-native/usr/bin/arm-poky-linux-gnueabi/arm-poky-linux-gnueabi-g++ --sysroot=/home/b2open/treinamento/yp/poky/build-qemu/tmp/work/cortexa15t2hf-neon-poky-linux-gnueabi/b2-sniffer/git/recipe-sysroot  -I/home/b2open/treinamento/yp/poky/build-qemu/tmp/work/cortexa15t2hf-neon-poky-linux-gnueabi/b2-sniffer/git/git/3rdparty/fmt/include -mthumb -mfpu=neon -mfloat-abi=hard -mcpu=cortex-a15 -fstack-protector-strong  -O2 -D_FORTIFY_SOURCE=2 -Wformat -Wformat-security -Werror=format-security -D_TIME_BITS=64 -D_FILE_OFFSET_BITS=64  --sysroot=/home/b2open/treinamento/yp/poky/build-qemu/tmp/work/cortexa15t2hf-neon-poky-linux-gnueabi/b2-sniffer/git/recipe-sysroot  -O2 -pipe -g -feliminate-unused-debug-types -fcanon-prefix-map  -fmacro-prefix-map=/home/b2open/treinamento/yp/poky/build-qemu/tmp/work/cortexa15t2hf-neon-poky-linux-gnueabi/b2-sniffer/git/git=/usr/src/debug/b2-sniffer/git  -fdebug-prefix-map=/home/b2open/treinamento/yp/poky/build-qemu/tmp/work/cortexa15t2hf-neon-poky-linux-gnueabi/b2-sniffer/git/git=/usr/src/debug/b2-sniffer/git  -fmacro-prefix-map=/home/b2open/treinamento/yp/poky/build-qemu/tmp/work/cortexa15t2hf-neon-poky-linux-gnueabi/b2-sniffer/git/build=/usr/src/debug/b2-sniffer/git  -fdebug-prefix-map=/home/b2open/treinamento/yp/poky/build-qemu/tmp/work/cortexa15t2hf-neon-poky-linux-gnueabi/b2-sniffer/git/build=/usr/src/debug/b2-sniffer/git  -fdebug-prefix-map=/home/b2open/treinamento/yp/poky/build-qemu/tmp/work/cortexa15t2hf-neon-poky-linux-gnueabi/b2-sniffer/git/recipe-sysroot=  -fmacro-prefix-map=/home/b2open/treinamento/yp/poky/build-qemu/tmp/work/cortexa15t2hf-neon-poky-linux-gnueabi/b2-sniffer/git/recipe-sysroot=  -fdebug-prefix-map=/home/b2open/treinamento/yp/poky/build-qemu/tmp/work/cortexa15t2hf-neon-poky-linux-gnueabi/b2-sniffer/git/recipe-sysroot-native=  -fvisibility-inlines-hidden -Wall -Werror -std=gnu++14 -MD -MT CMakeFiles/b2-sniffer.dir/b2sniffer.cpp.o -MF CMakeFiles/b2-sniffer.dir/b2sniffer.cpp.o.d -o CMakeFiles/b2-sniffer.dir/b2sniffer.cpp.o -c /home/b2open/treinamento/yp/poky/build-qemu/tmp/work/cortexa15t2hf-neon-poky-linux-gnueabi/b2-sniffer/git/git/b2sniffer.cpp
| /home/b2open/treinamento/yp/poky/build-qemu/tmp/work/cortexa15t2hf-neon-poky-linux-gnueabi/b2-sniffer/git/git/b2sniffer.cpp: In member function 'void b2::Sniffer::listInterfaces()':
| /home/b2open/treinamento/yp/poky/build-qemu/tmp/work/cortexa15t2hf-neon-poky-linux-gnueabi/b2-sniffer/git/git/b2sniffer.cpp:192:14: error: ignoring return value of 'int scanf(const char*, ...)' declared with attribute 'warn_unused_result' [-Werror=unused-result]
|   192 |         scanf("%d", &n);
|       |         ~~~~~^~~~~~~~~~
| cc1plus: all warnings being treated as errors


DESAFIO: Resolver o erro de compilação do b2-sniffer usando apenas recursos da receita, sem alterar o código-fonte.

DICA

O projeto compila com -Wall -Werror, então qualquer aviso vira erro. Na receita conseguimos passar flags para ligar e desligar recursos como CXXFLAGS/CFLAGS.


SOLUÇÃO: Edite a receita b2-sniffer_git.bb, e adicione a variável abaixo:

CXXFLAGS:append = " -Wno-unused-result"


Parte 5 - Serviço systemd e Empacotamento


Nesta prática vamos criar a receita b2open-monitor, um pequeno monitor do sistema que roda como serviço do systemd e sobe automaticamente no boot. No caminho vamos passar por um erro clássico de empacotamento, o installed-vs-shipped.

O que será praticado:

  • Receita com serviço systemd: inherit systemd, SYSTEMD_SERVICE e SYSTEMD_AUTO_ENABLE.
  • Variável FILES e o erro installed-vs-shipped.
  • Divisão em pacotes com PACKAGES e dependência entre eles com RDEPENDS.
  • Inspeção de pacotes com oe-pkgdata-util.
  • Validação do serviço no TARGET com systemctl e journalctl.


Criando os arquivos da aplicação

Crie o diretório da aplicação dentro de recipes-b2open/apps, seguindo o padrão das práticas anteriores:

Executar no HOST
cd ~/treinamento/yp/poky/meta-treinamento

mkdir -p recipes-b2open/apps/b2open-monitor

touch recipes-b2open/apps/b2open-monitor/b2open-monitor.sh

touch recipes-b2open/apps/b2open-monitor/b2open-monitor.conf

touch recipes-b2open/apps/b2open-monitor/b2open-monitor.service


Edite o arquivo b2open-monitor.sh. A cada intervalo ele imprime o uptime, a carga e a memória disponível do sistema:

#!/bin/sh
#
# B2Open Systems - Monitor do sistema
#

CONF=/etc/b2open/monitor.conf
INTERVALO=10

[ -f "$CONF" ] && . "$CONF"

while true; do
    UPTIME=$(cut -d' ' -f1 /proc/uptime)
    CARGA=$(cut -d' ' -f1-3 /proc/loadavg)
    MEMORIA=$(grep MemAvailable /proc/meminfo | awk '{print $2}')

    echo "uptime: ${UPTIME}s | carga: ${CARGA} | memoria livre: ${MEMORIA} kB"

    sleep "$INTERVALO"
done


Edite o arquivo b2open-monitor.conf, com o intervalo em segundos:

# Intervalo entre as leituras, em segundos
INTERVALO=10


Edite o arquivo b2open-monitor.service, a unit do systemd:

[Unit]
Description=B2Open Systems - Monitor do sistema

[Service]
Type=simple
ExecStart=/opt/b2open/bin/b2open-monitor.sh
Restart=on-failure

[Install]
WantedBy=multi-user.target

Note

Tudo o que o serviço escreve na saída padrão (echo) vai para o log do systemd, consultado com journalctl. Por isso o script não precisa gravar arquivos de log.


Criando a receita

Crie a receita recipes-b2open/apps/b2open-monitor_1.0.bb:

Executar no HOST
touch recipes-b2open/apps/b2open-monitor_1.0.bb


Adicione o conteúdo abaixo. Repare que o script será instalado em /opt/b2open/bin, um diretório comum em produtos para separar o software do fabricante:

DESCRIPTION = "B2Open Systems - Monitor do sistema como servico systemd"
SECTION = "examples"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"

SRC_URI = " \
    file://b2open-monitor.sh \
    file://b2open-monitor.conf \
    file://b2open-monitor.service \
    "

S = "${WORKDIR}"

inherit systemd

SYSTEMD_SERVICE:${PN} = "b2open-monitor.service"
SYSTEMD_AUTO_ENABLE = "enable"

do_install() {
    install -d ${D}/opt/b2open/bin
    install -m 0755 ${S}/b2open-monitor.sh ${D}/opt/b2open/bin/

    install -d ${D}${sysconfdir}/b2open
    install -m 0644 ${S}/b2open-monitor.conf ${D}${sysconfdir}/b2open/monitor.conf

    install -d ${D}${systemd_system_unitdir}
    install -m 0644 ${S}/b2open-monitor.service ${D}${systemd_system_unitdir}/
}

Destaques da receita:

  • inherit systemd: classe que cuida de habilitar o serviço na imagem.
  • SYSTEMD_SERVICE:${PN}: qual unit pertence a qual pacote.
  • SYSTEMD_AUTO_ENABLE = "enable": o serviço sobe automaticamente no boot.
  • ${systemd_system_unitdir}: diretório padrão das units, normalmente /usr/lib/systemd/system ou /lib/systemd/system.

Note

A partir do Yocto Project 5.1 (styhead) os arquivos de SRC_URI são extraídos em ${UNPACKDIR}, então nessas versões use S = "${UNPACKDIR}". No scarthgap continua S = "${WORKDIR}".


Confira a estrutura:

Executar no HOST
tree recipes-b2open/apps

Saída esperada:

recipes-b2open/apps
├── b2open-hello
│   └── main.c
├── b2open-hello_1.0.bb
├── b2open-monitor
│   ├── b2open-monitor.conf
│   ├── b2open-monitor.service
│   └── b2open-monitor.sh
├── b2open-monitor_1.0.bb
├── b2open-usbmon
│   ├── CMakeLists.txt
│   └── usb_mon.c
├── b2open-usbmon_1.0.bb
└── b2-sniffer_git.bb

4 directories, 10 files


Compilando e analisando o erro

Volte para o diretório de build e compile a receita:

Executar no HOST
cd ~/treinamento/yp/poky/build-qemu

bitbake b2open-monitor


O build falha na tarefa do_package. Saída esperada (semelhante a):

ERROR: b2open-monitor-1.0-r0 do_package: QA Issue: b2open-monitor: Files/directories were installed but not shipped in any package:
  /opt
  /opt/b2open
  /opt/b2open/bin
  /opt/b2open/bin/b2open-monitor.sh
Please set FILES such that these items are packaged. Alternatively if they are unneeded, avoid installing them or delete them within do_install.
b2open-monitor: 4 installed and not shipped files. [installed-vs-shipped]
ERROR: b2open-monitor-1.0-r0 do_package: Fatal QA errors were found, failing task.
ERROR: Logfile of failure stored in: /home/b2open/treinamento/yp/poky/build-qemu/tmp/work/cortexa15t2hf-neon-poky-linux-gnueabi/b2open-monitor/1.0/temp/log.do_package.17457
ERROR: Task (/home/b2open/treinamento/yp/poky/meta-treinamento/recipes-b2open/apps/b2open-monitor_1.0.bb:do_package) failed with exit code '1'


Por que isso aconteceu? O do_install instala os arquivos em ${D}, e depois o do_package distribui esses arquivos entre os pacotes da receita usando a variável FILES. Cada pacote tem a sua lista de diretórios padrão, e /opt não está em nenhuma delas. O arquivo foi instalado, mas nenhum pacote o "pegou".

Veja os diretórios que o pacote principal aceita por padrão:

Executar no HOST
bitbake-getvar -r b2open-monitor FILES:b2open-monitor

Repare que aparecem /usr/bin, /etc, /usr/lib e outros, mas não /opt. Já a unit em ${systemd_system_unitdir} não deu erro porque a classe systemd acrescenta esse diretório ao pacote automaticamente.


Corrigindo com FILES

Edite a receita b2open-monitor_1.0.bb e, logo abaixo de SYSTEMD_AUTO_ENABLE, adicione:

FILES:${PN} += "/opt/b2open"


Compile novamente:

Executar no HOST
bitbake b2open-monitor


Agora o build termina sem erros. Liste os pacotes gerados e os arquivos de cada um:

Executar no HOST
oe-pkgdata-util list-pkgs -p b2open-monitor

oe-pkgdata-util list-pkg-files -p b2open-monitor

Saída esperada (semelhante a):

b2open-monitor

b2open-monitor:
        /etc/b2open/monitor.conf
        /opt/b2open/bin/b2open-monitor.sh

Tip

1
Toda receita gera vários pacotes (`-dbg`, `-dev`, `-doc`...), mas o `oe-pkgdata-util list-pkgs -p` mostra só os que têm arquivos. Como o b2open-monitor é um script, só o pacote principal tem conteúdo. Para ver também os pacotes vazios, use `oe-pkgdata-util list-pkgs -u -p b2open-monitor`.


Prática 07 realizada com sucesso!