초보자를 위한 기여 가이드 (Contribution guide for beginners)
C에 대한 지식이 있다면, 이 가이드가 Fluent Bit에 코드 변경을 어떻게 하는지 이해하는 데 도움이 될 거예요.
출처: 문서
본문
C에 대한 지식이 있다면, 이 가이드가 Fluent Bit에 코드 변경을 어떻게 하는지 이해하는 데 도움이 될 거예요.
라이브러리 (Libraries)
대부분의 외부 라이브러리는 프로젝트의 /lib 폴더에 내장돼 있어요. 풋프린트를 낮게 유지하고 크로스 플랫폼 빌드에서 호환성을 최대화하기 위해, Fluent Bit는 의존성 그래프를 작게 유지하려고 해요.
내장 라이브러리 전체 목록과 그 용도는 외부 라이브러리를 참고하세요.
가장 많이 상호작용하게 될 외부 라이브러리는 MessagePack이에요.
암호화 지원을 위해 Fluent Bit는 시스템에 설치된 OpenSSL 버전을 사용해요. Fluent Bit를 빌드하기 전에 OpenSSL 라이브러리와 헤더를 설치해야 해요.
메모리 관리 (Memory management)
Fluent Bit 코드를 작성할 때는 메모리 작업을 위해 표준 C 함수의 Fluent Bit 버전을 사용하게 돼요:
flb_malloc():malloc에 해당하며 메모리를 할당해요.flb_calloc():calloc에 해당하며 메모리를 할당하고 0으로 초기화해요.flb_realloc():realloc에 해당해요.flb_free():free에 해당하며 할당된 메모리를 해제해요.
{% hint style="info" %}
많은 타입에는 flb_sds_create()와 flb_sds_destroy() 같은 전용 create/destroy 함수가 있어요.
{% endhint %}
문자열 (Strings)
Fluent Bit에는 인기 있는 SDS 문자열 라이브러리의 축소판이 있어요. API는 flb_sds.h를 참고하세요.
일반적으로 문자열 처리 코드에서는 SDS 문자열을 사용해야 해요. SDS 문자열은 null로 끝나는 문자 시퀀스를 받아들이는 모든 C 함수와 완전히 호환돼요. 그것이 어떻게 동작하는지 이해하려면 GitHub의 설명을 참고하세요.
HTTP 클라이언트 (HTTP client)
Fluent Bit에는 자체 네트워크 연결 라이브러리가 있어요. 핵심 타입과 함수는 다음 헤더 파일에 정의돼 있어요:
다음 코드는 Fluent Bit에서 HTTP 요청을 보여줘요:
#include <fluent-bit/flb_upstream.h>
#include <fluent-bit/flb_io.h>
#include <fluent-bit/flb_http_client.h>
#include <fluent-bit/flb_info.h>
#include <fluent-bit/flb_config.h>
#define HOST "127.0.0.1"
#define PORT 80
static flb_sds_t make_request(struct flb_config *config)
{
struct flb_upstream *upstream;
struct flb_http_client *client;
size_t b_sent;
int ret;
struct flb_upstream_conn *u_conn;
flb_sds_t resp;
/* Create an 'upstream' context */
upstream = flb_upstream_create(config, HOST, PORT, FLB_IO_TCP, NULL);
if (!upstream) {
flb_error("[example] connection initialization error");
return -1;
}
/* Retrieve a TCP connection from the 'upstream' context */
u_conn = flb_upstream_conn_get(upstream);
if (!u_conn) {
flb_error("[example] connection initialization error");
flb_upstream_destroy(upstream);
return -1;
}
/* Create HTTP Client request/context */
client = flb_http_client(u_conn,
FLB_HTTP_GET, metadata_path,
NULL, 0,
FLB_FILTER_AWS_IMDS_V2_HOST, 80,
NULL, 0);
if (!client) {
flb_error("[example] count not create http client");
flb_upstream_conn_release(u_conn);
flb_upstream_destroy(upstream);
return -1;
}
/* Perform the HTTP request */
ret = flb_http_do(client, &b_sent)
/* Validate return status and HTTP status if set */
if (ret != 0 || client->resp.status != 200) {
if (client->resp.payload_size > 0) {
flb_debug("[example] Request failed and returned: \n%s",
client->resp.payload);
}
flb_http_client_destroy(client);
flb_upstream_conn_release(u_conn);
flb_upstream_destroy(upstream);
return -1;
}
/* Copy payload response to an output SDS buffer */
data = flb_sds_create_len(client->resp.payload,
client->resp.payload_size);
flb_http_client_destroy(client);
flb_upstream_conn_release(u_conn);
flb_upstream_destroy(upstream);
return resp;
}
flb_upstream 구조체는 호출하려는 호스트/엔드포인트를 나타내요. 보통 이 구조체를 어딘가에 저장해 재사용할 수 있어요. flb_upstream_conn은 단일 HTTP 요청을 위해 그 호스트에 대한 연결을 나타내요. 이 연결 구조체는 하나 이상의 요청에 사용하면 안 돼요.
연결 리스트 (Linked lists)
Fluent Bit에는 연결 리스트를 구성하는 라이브러리, cfl_list가 있어요. 이 타입은 데이터를 원형 연결 리스트로 저장해요.
cfl_list.h 헤더 파일에는 리스트와 함께 사용할 여러 매크로와 함수가 들어 있어요. 다음 예시는 리스트를 만들고, 순회하고, 요소를 삭제하는 방법을 보여줘요.
#include <cfl/cfl.h>
#include <fluent-bit/flb_info.h>
struct item {
char some_data;
struct cfl_list _head;
};
static int example()
{
struct cfl_list *tmp;
struct cfl_list *head;
struct cfl_list items;
int i;
int len;
char characters[] = "abcdefghijk";
struct item *an_item;
len = strlen(characters);
/* construct a list */
cfl_list_init(&items);
for (i = 0; i < len; i++) {
an_item = flb_malloc(sizeof(struct item));
if (!an_item) {
flb_errno();
return -1;
}
an_item->some_data = characters[i];
cfl_list_add(&an_item->_head, &items);
}
/* iterate through the list */
flb_info("Iterating through list");
cfl_list_foreach_safe(head, tmp, &items) {
an_item = cfl_list_entry(head, struct item, _head);
flb_info("list item data value: %c", an_item->some_data);
}
/* remove an item */
cfl_list_foreach_safe(head, tmp, &items) {
an_item = cfl_list_entry(head, struct item, _head);
if (an_item->some_data == 'b') {
cfl_list_del(&an_item->_head);
flb_free(an_item);
}
}
}
MessagePack
Fluent Bit는 데이터를 내부적으로 저장할 때 MessagePack을 사용해요. Fluent Bit용 코드를 작성한다면 MessagePack과 상호작용할 것이 거의 확실해요.
Fluent Bit는 msgpack-c 라이브러리를 내장해요. 다음 예시는 메시지 팩을 조작해서 레코드에 새 키/값 쌍을 추가하는 방법을 보여줘요. Fluent Bit에서 filter_record_modifier 플러그인은 레코드에 키를 추가하거나 삭제해요. 더 많은 내용은 그 코드를 참고하세요.
#define A_NEW_KEY "key"
#define A_NEW_KEY_LEN 3
#define A_NEW_VALUE "value"
#define A_NEW_VALUE_LEN 5
static int cb_filter(const void *data, size_t bytes,
const char *tag, int tag_len,
void **out_buf, size_t *out_size,
struct flb_filter_instance *f_ins,
void *context,
struct flb_config *config)
{
(void) f_ins;
(void) config;
size_t off = 0;
int i = 0;
int ret;
struct flb_time tm;
int total_records;
int new_keys = 1;
msgpack_sbuffer tmp_sbuf;
msgpack_packer tmp_pck;
msgpack_unpacked result;
msgpack_object *obj;
msgpack_object_kv *kv;
/* Create temporary msgpack buffer */
msgpack_sbuffer_init(&tmp_sbuf);
msgpack_packer_init(&tmp_pck, &tmp_sbuf, msgpack_sbuffer_write);
/* Iterate over each item */
msgpack_unpacked_init(&result);
while (msgpack_unpack_next(&result, data, bytes, &off) == MSGPACK_UNPACK_SUCCESS) {
/*
* Each record is a msgpack array [timestamp, map] of the
* timestamp and record map. We 'unpack' each record, and then re-pack
* it with the new fields added.
*/
if (result.data.type != MSGPACK_OBJECT_ARRAY) {
continue;
}
/* unpack the array of [timestamp, map] */
flb_time_pop_from_msgpack(&tm, &result, &obj);
/* obj should now be the record map */
if (obj->type != MSGPACK_OBJECT_MAP) {
continue;
}
/* re-pack the array into a new buffer */
msgpack_pack_array(&tmp_pck, 2);
flb_time_append_to_msgpack(&tm, &tmp_pck, 0);
/* new record map size is old size + the new keys we will add */
total_records = obj->via.map.size + new_keys;
msgpack_pack_map(&tmp_pck, total_records);
/* iterate through the old record map and add it to the new buffer */
kv = obj->via.map.ptr;
for(i=0; i < obj->via.map.size; i++) {
msgpack_pack_object(&tmp_pck, (kv+i)->key);
msgpack_pack_object(&tmp_pck, (kv+i)->val);
}
/* append new keys */
msgpack_pack_str(&tmp_pck, A_NEW_KEY_LEN);
msgpack_pack_str_body(&tmp_pck, A_NEW_KEY, A_NEW_KEY_LEN);
msgpack_pack_str(&tmp_pck, A_NEW_VALUE_LEN);
msgpack_pack_str_body(&tmp_pck, A_NEW_VALUE, A_NEW_VALUE_LEN);
}
msgpack_unpacked_destroy(&result);
/* link new buffers */
*out_buf = tmp_sbuf.data;
*out_size = tmp_sbuf.size;
return FLB_FILTER_MODIFIED;
자세한 내용은 msgpack-c GitHub 저장소의 MessagePack 예시를 참고하세요.
플러그인 API (Plugin API)
각 플러그인은 dlopen과 dlsym을 사용해 Fluent Bit에 로드되는 공유 객체예요.
입력 (Input)
입력 플러그인 구조체는 flb_input.h에 정의돼 있어요. 플러그인이 구현할 수 있는 함수가 여러 개 있지만, 대부분은 cb_init, cb_collect, cb_exit만 구현해요.
"dummy" 입력 플러그인은 매우 기본적이어서 더 이해하기에 좋은 예시예요.
입력 플러그인은 FLB_INPUT_THREADED 플래그를 제공하면 스레드 모드를 사용할 수 있어요. 플러그인에서 스레딩을 활성화하려면 등록할 때 flags 집합에 FLB_INPUT_THREADED를 추가하세요:
struct flb_input_plugin in_your_example_plugin = {
.name = "your example",
.description = "Ingest example data",
.cb_init = in_your_example_init,
.cb_pre_run = NULL,
.cb_collect = in_your_example_collect,
.cb_flush_buf = NULL,
.config_map = config_map,
.cb_pause = in_your_example_pause,
.cb_resume = in_example_resume,
.cb_exit = in_example_exit,
.flags = FLB_INPUT_THREADED
};
필터 (Filter)
필터 플러그인의 구조체는 flb_filter.h에 정의돼 있어요. 각 플러그인은 cb_init, cb_filter, cb_exit을 구현해야 해요.
filter_record_modifier는 필터 플러그인의 좋은 예시예요.
필터 플러그인은 HTTP 요청을 비동기적으로 만들 수 없어요. 플러그인에 요청이 필요하면 flb_upstream을 초기화할 때 다음 코드를 추가하세요:
/* Remove async flag from upstream */
upstream->flags &= ~(FLB_IO_ASYNC);
출력 (Output)
출력 플러그인은 flb_output.h에 정의돼 있어요. 각 플러그인은 cb_init, cb_flush, cb_exit을 구현해야 해요.
stdout 플러그인은 매우 기본적이니, 출력 플러그인이 어떻게 동작하는지 이해하려면 그 코드를 검토하세요.
개발 환경 (Development environment)
Fluent Bit는 개발용 독립 환경을 제공해요. 서로 다른 운영 체제나 배포판을 사용하는 개발자는 기본적이고 공통적인 스택에서 개발할 수 있어요. 개발 환경은 필요한 라이브러리와 도구를 제공해요.
개발 환경은 다음을 위해 제공돼요:
테스트 (Testing)
개발 중에는 다음과 같이 Fluent Bit를 빌드할 수 있어요:
cd build
cmake -DFLB_DEV=On ../
make
{% hint style="info" %}
Fluent Bit는 CMake 3를 사용해요. 일부 시스템에서는 cmake3으로 호출해야 할 수도 있어요.
{% endhint %}
유닛 테스트를 활성화하려면 다음 명령을 실행하세요:
cmake -DFLB_DEV=On -DFLB_TESTS_RUNTIME=On -DFLB_TESTS_INTERNAL=On ../
make
내부 테스트는 Fluent Bit의 내부 라이브러리를 위한 것이에요. 런타임 테스트는 플러그인을 위한 것이에요.
make test로 유닛 테스트를 실행할 수 있어요. 하지만 실무에서는 불편해요. 각 테스트 파일은 build/bin 디렉터리에 실행 파일을 만들며, 이를 직접 실행할 수 있어요. 예를 들어 SDS 테스트를 실행하려면 다음과 같이 호출할 수 있어요:
$ ./bin/flb-it-sds
Test sds_usage... [ OK ]
Test sds_printf... [ OK ]
SUCCESS: All unit tests have passed.