Wasm 필터 플러그인
WebAssembly(Wasm)로 작성한 프로그램을 Fluent Bit의 필터로 실행하고 싶을 때 참고하는 개발자용 문서입니다. 함께 살펴보겠습니다.
출처: 문서
본문
WebAssembly (Wasm)는 스택 기반 가상 머신을 위한 이진 명령 형식입니다.
Fluent Bit는 입력과 필터 플러그인에 대해서만 Wasm/WASI 객체로 빌드된 Wasm 플러그인의 통합을 지원합니다. Wasm 필터 플러그인의 인터페이스는 현재 개발 중이지만 기능적으로는 동작합니다.
Prerequisites
Fluent Bit 빌드
Wasm 플러그인을 실행하는 데 추가 요구 사항은 없습니다.
flb-wamrc 빌드 (선택 사항)
flb-wamrc는 wasm-micro-runtime에서 제공되는 flb 접두사 Ahead of Time (AOT) 컴파일러입니다.
flb-wamrc 지원을 위해서는 LLVM 인프라와 몇 가지 추가 라이브러리(libmlir, libPolly, libedit, libpfm)를 설치해야 합니다. 예를 들어:
# apt install -y llvm libmlir-14-dev libclang-common-14-dev libedit-dev libpfm4-dev
Wasm 프로그램용
Fluent Bit는 다음 Wasm 툴 체인을 지원합니다:
wasm32-unknown-unknown용 Rust- rustc 1.62.1 (
e092d0b6b2022-07-16) 이상
- rustc 1.62.1 (
wasm32-wasi용 TinyGo- v0.24.0 이상
- WASI SDK 13 이상.
시작하기
소스 설치 가이드의 일반 옵션에서 설명했듯이 Wasm 지원은 기본적으로 활성화되어 있습니다. 예를 들어 Wasm 지원으로 Fluent Bit를 컴파일하세요:
cd build/
cmake .. [-DFLB_WAMRC=On]
make
AOT 컴파일된 Wasm을 필터 플러그인으로 실행하려면 -DFLB_WAMRC=On으로 Fluent Bit를 빌드하세요.
컴파일이 끝나면 wasm을 처리하는 새 플러그인을 볼 수 있습니다. 예를 들어:
bin/fluent-bit -h
다음과 유사한 결과가 반환됩니다:
Usage: fluent-bit [OPTION]
Inputs
# ... other input plugin stuffs
exec_wasi Exec WASI Input
Filters
# ... other filter plugin stuffs
wasm WASM program filter
필터 플러그인용 Wasm 필터 빌드
Fluent Bit Wasm 필터는 C ABI를 가정하며, Rust 타깃에서는 wasm32-unknown-unknown, TinyGo 타깃에서는 wasm32-wasi로도 알려져 있습니다.
추가 구성 요소 설치
TinyGo와 WASI SDK는 기본적으로 Wasm 타깃을 지원합니다. Rust의 wasm32-unknown-unknown 타깃을 사용할 때는 rustup으로 wasm32-unknown-unknown을 설치해야 합니다. 그런 다음 타깃 구성 요소를 다음과 같이 설치합니다:
rustup target add wasm32-unknown-unknown
Wasm 프로그램의 요구 사항
Wasm 필터 플러그인은 다음 시그니처를 가진 함수를 실행합니다.
C의 경우:
// We can use an arbitrary function name for filter operations w/ Wasm.
char* c_filter(char*, int, uint32_t, uint32_t, char*, int);
Go (TinyGo)의 경우:
//export go_filter
// And this function should be placed in the main package.
func go_filter(tag *uint8, tag_len uint, time_sec uint, time_nsec uint, record *uint8, record_len uint) *uint8
Rust의 경우:
// #[no_mangle] attribute is needed for preventing mangles and align C ABI.
// Also we can use an arbitrary function name for filter operations w/ Wasm.
#[no_mangle]
pub extern "C" fn rust_filter(tag: *const c_char, tag_len: u32, time_sec: u32, time_nsec: u32, record: *const c_char, record_len: u32)
TinyGo의 //export XXX 속성과 Rust의 #[no_mangle] 속성은 필수입니다. 지정하지 않으면 TinyGo와 Rust가 함수 이름을 맹글링하기 때문입니다.
빌드가 완료되면 Wasm 프로그램을 사용할 수 있습니다. 그러면 다음 Fluent Bit 구성 중 하나로 빌드된 프로그램을 실행할 수 있어요:
{% tabs %} {% tab title="fluent-bit.yaml" %}
pipeline:
inputs:
- name: dummy
tag: dummy.local
filters:
- name: wasm
match: 'dummy.*'
wasm_path: /path/to/built_filter.wasm
function_name: super_awesome_filter
# Note: run Fluent Bit from the 'wasm_path' location.
accessible_paths: /path/to/fluent-bit
outputs:
- name: stdout
match: '*'
{% endtab %}
{% tab title="fluent-bit.conf" %}
[INPUT]
Name dummy
Tag dummy.local
[FILTER]
Name wasm
Match dummy.*
WASM_Path /path/to/built_filter.wasm
Function_Name super_awesome_filter
accessible_paths /path/to/fluent-bit
[OUTPUT]
Name stdout
Match *
{% endtab %} {% endtabs %}
예를 들어, 샘플 Rust Wasm 필터 중 하나는 다음과 같이 필터링된 로그를 생성합니다:
[0] dummy.local: [1666270588.271704000, {"lang"=>"Rust", "message"=>"dummy", "original"=>"{"message":"dummy"}", "tag"=>"dummy.local", "time"=>"2022-10-20T12:56:28.271704000 +0000"}]
[0] dummy.local: [1666270589.270348000, {"lang"=>"Rust", "message"=>"dummy", "original"=>"{"message":"dummy"}", "tag"=>"dummy.local", "time"=>"2022-10-20T12:56:29.270348000 +0000"}]
[0] dummy.local: [1666270590.271107000, {"lang"=>"Rust", "message"=>"dummy", "original"=>"{"message":"dummy"}", "tag"=>"dummy.local", "time"=>"2022-10-20T12:56:30.271107000 +0000"}]
Rust Wasm 필터의 또 다른 예시는 flb_filter_iis 필터입니다.
이 필터는 Internet Information Services (IIS)의 w3c 로그(일부 커스텀 수정 포함)를 가져와 원시 문자열을 표준 Fluent Bit JSON 구조화 레코드로 변환합니다.
{% tabs %} {% tab title="fluent-bit.yaml" %}
pipeline:
inputs:
- name: dummy
dummy: '{"log": "2023-08-11 19:56:44 W3SVC1 WIN-PC1 ::1 GET / - 80 ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/115.0.0.0+Safari/537.36+Edg/115.0.1901.200 - - localhost 304 142 756 1078 -"}'
tag: 'iis.*'
filters:
- name: wasm
match: 'iis.*'
wasm_path: /plugins/flb_filter_iis_wasm.wasm
function_name: flb_filter_log_iis_w3c_custom
accessible_paths: .
outputs:
- name: stdout
match: 'iis.*'
{% endtab %}
{% tab title="fluent-bit.conf" %}
[INPUT]
Name dummy
Dummy {"log": "2023-08-11 19:56:44 W3SVC1 WIN-PC1 ::1 GET / - 80 ::1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/115.0.0.0+Safari/537.36+Edg/115.0.1901.200 - - localhost 304 142 756 1078 -"}
Tag iis.*
[FILTER]
Name wasm
match iis.*
WASM_Path /plugins/flb_filter_iis_wasm.wasm
Function_Name flb_filter_log_iis_w3c_custom
accessible_paths .
[OUTPUT]
name stdout
match iis.*
{% endtab %} {% endtabs %}
IIS 로그의 들어오는 원시 문자열은 다음 필드들로 구성됩니다:
date time s-sitename s-computername s-ip cs-method cs-uri-stem cs-uri-query s-port c-ip cs(User-Agent) cs(Cookie) cs(Referer) cs-host sc-status sc-bytes cs-bytes time-taken c-authorization-header
필터 로직을 거친 후의 출력은 다음과 같습니다:
[0] iis.*: [[1692131925.559486675, {}], {"c_authorization_header"=>"-", "c_ip"=>"::1", "cs_bytes"=>756, "cs_cookie"=>"-", "cs_host"=>"localhost", "cs_method"=>"GET", "cs_referer"=>"-", "cs_uri_query"=>"-", "cs_uri_stem"=>"/", "cs_user_agent"=>"Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/115.0.0.0+Safari/537.36+Edg/115.0.1901.200", "date"=>"2023-08-11 19:56:44", "s_computername"=>"WIN-PC1", "s_ip"=>"::1", "s_port"=>"80", "s_sitename"=>"W3SVC1", "sc_bytes"=>142, "sc_status"=>"304", "source"=>"LogEntryIIS", "tag"=>"iis.*", "time"=>"2023-08-15T20:38:45.559486675 +0000", "time_taken"=>1078}]
이 필터 접근 방식은 프로그래밍 언어에 내재된 몇 가지 장점을 제공합니다. 예를 들어:
sc_bytes,cs_bytes,time_taken같은 필드에 유형 변환을 추가해 확장할 수 있습니다. 데이터 결과를 검증하는 데 사용할 수 있어요.- 더 설명적인 필터를 적용하기 위해 조건을 사용할 수 있습니다. 예를 들어,
4xx나5xx보다 높은 상태 코드를 포함한 모든 로그만 가져올 수 있어요. - 미리 정의된 IP 주소를 저장하는 데이터 구조 배열이나 파일을 사용해 허용 목록과 차단 목록을 정의할 수 있습니다.
- 데이터를 향상시키기 위해 API나 데이터베이스 같은 외부 리소스를 호출할 수 있습니다.
- 모든 메서드를 철저히 테스트하고 이진 번들이나 라이브러리로 공유할 수 있습니다.
이 예시들은 데모에 적용할 수 있으며, 요구 사항에 따라 더 복잡한 로직을 만들기 위한 이상적인 시작점이 될 수 있어요.
Wasm 프로그램 실행 최적화
Wasm 프로그램 실행을 최적화하려면 flb-wamrc를 사용하는 옵션이 있습니다. 이 옵션은 런타임 풋프린트를 줄이고 필터링 작업에서 최상의 성능을 제공합니다.
이 도구는 -DFLB_WAMRC=On CMake 옵션이 지정되고 빌드 머신에 LLVM 인프라가 설치되어 있을 때 빌드됩니다.
flb-wamrc -o /path/to/built_wasm.aot /path/to/built_wasm.wasm
Cortex-A57 시리즈 같은 특정 CPU에 대한 추가 최적화:
flb-wamrc --size-level=3 --target=aarch64v8 --cpu=cortex-a57 -o /path/to/built_wasm.aot /path/to/built_wasm.wasm
그런 다음 AOT (Ahead Of Time) 컴파일이 성공하면:
Create AoT compiler with:
target: aarch64v8
target cpu: cortex-a57
cpu features:
opt level: 3
size level: 3
output format: AoT file
Compile success, file /path/to/built_wasm.aot was generated.
AOT 컴파일은 CPU 아키텍처에 종속적인 객체를 생성해야 합니다. 다른 아키텍처에서 AOT 컴파일된 객체를 사용하려면 실제 환경에 맞게 target과 target cpu를 맞춰야 합니다.