Beats作为Elastic Stack家族中重要的部分。它可以和方便地让我们把我们的数据发送到Elasticsearch或Logstash之中。如果我们想要生成自己的Beat,请使用GitHub的beats仓库中提供的Beat生成器。在今天的文章中,我们将详细介绍如何一步一步地来创建一个我们自己想要的beat。

设置自己的开发环境

安装go环境

Beats实际上是go程序。我们可以参照链接“Go get started”(https://golang.org/doc/install)来安装自己的golang语言开发环境。等我们安装好我们的go后,我们可以在terminal中打入如下的命令:

    $ which go
/usr/local/go/bin/go

那么我们需要在我们的环境中设置如下的变量:

    export GOROOT=/usr/local/go
export PATH=$GOPATH/bin:$GOROOT/bin:$PATH
export GOPATH=$HOME/go/beats

在这里,我也设置了以GOPATH。你可以设置自己的路径。针对我的情况,我在我的home目录下创建了一个go目录,并在go目录下生产一个叫做beats的目录。在一下,我们会在这个目录里生成我们的定制的beat。

下载Elastic beats源码

在这一步我们下载Elastic beats的源码。在termnial中打入如下的命令:

    mkdir -p ${GOPATH}/src/github.com/elastic
git clone https://github.com/elastic/beats ${GOPATH}/src/github.com/elastic/beats

安装Python

目前generator只对Python2适用,所以,我们需要安装Python2。我们可以参照页面https://www.python.org/downloads/进行安装我们的python2。

安装virtualenv

我们必须安装virtualenv才能使得generator正常工作。可以参照链接https://virtualenv.pypa.io/en/latest/installation/来进行安装。如果自己的电脑上同时已经安装了python3,那么我们需要同时设置如写变量:

    export PYTHON_EXE='python2.7'
export VIRTUALENV_PARAMS='-p python2.7'
export VIRTUALENV_PYTHON='/usr/bin/python2.7' export VIRTUALENV_PYTHON='/usr/local/bin/python' (for Mac)

请注意:这里的python是2.x版本的python,而不是python3。我们需要保证VIRTUALENV_PYTHON指向我们的Python2的执行文件。

安装mage

我们需要在地址https://github.com/magefile/mage下载这个源码,并编译:

    go get -u -d github.com/magefile/mage
cd $GOPATH/src/github.com/magefile/mage
go run bootstrap.go

等上面的命令执行完后,我们可以在如下的目录中找到编译好的执行文件mage:

    liuxg-2:bin liuxg$ ls $GOPATH/bin
mage

创建定制beat

首先创建一个目录在$GOPATH下,并进入该目录。

    mkdir ${GOPATH}/src/github.com/{user}
cd ${GOPATH}/src/github.com/{user}

注意这里的user指的是自己在github上的用户名。比如针对我的情况是liu-xiao-guo。我打入如下写的命令:

    mkdir ${GOPATH}/src/github.com/liu-xiao-guo
cd $GOPATH/src/github.com/elastic/beats/

接下来,我们运行如下的命令:

mage GenerateCustomBeat

执行结果:

    $ mage GenerateCustomBeat
2019/11/13 15:24:01 Found Elastic Beats dir at /Users/liuxg/go/beats/src/github.com/elastic/beats
Enter the beat name [examplebeat]: Countbeat
Enter your github name [your-github-name]: liu-xiao-guo
Enter the beat path [github.com/liu-xiao-guo/countbeat]:
Enter your full name [Firstname Lastname]: Xiaoguo Liu
Enter the beat type [beat]:
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.tuna.tsinghua.edu.cn', port=443): Read timed out. (read timeout=15)",)': /simple/semver/
2019/11/13 15:25:50 Found Elastic Beats dir at /Users/liuxg/go/beats/src/github.com/liu-xiao-guo/countbeat/vendor/github.com/elastic/beats
Generated fields.yml for countbeat to /Users/liuxg/go/beats/src/github.com/liu-xiao-guo/countbeat/fields.yml
2019/11/13 15:25:52 Found Elastic Beats dir at /Users/liuxg/go/beats/src/github.com/liu-xiao-guo/countbeat/vendor/github.com/elastic/beats
Auto packing the repository in background for optimum performance.
See "git help gc" for manual housekeeping.
=======================
Your custom beat is now available as /Users/liuxg/go/beats/src/github.com/liu-xiao-guo/countbeat
=======================

这样,我们基本上就生产了一个最基本的beat的框架。

接下来,我们进入到我们的beat目录里,并进行编译:

cd ${GOPATH}/src/github.com/{user}/countbeat

针对我的情况:

cd ${GOPATH}/src/github.com/liu-xiao-guo/countbeat

我们可以看一下里面最基本的文件:

    $ pwd
/Users/liuxg/go/beats/src/github.com/liu-xiao-guo/countbeat
liuxg-2:countbeat liuxg$ ls
CONTRIBUTING.md cmd magefile.go
LICENSE.txt config main.go
Makefile countbeat.docker.yml main_test.go
NOTICE.txt countbeat.reference.yml make.bat
README.md countbeat.yml tests
_meta docs vendor
beater fields.yml
build include

这里有最基本的框架文件。里面含有一个叫做countbeat.yml的配置文件及一些标准的模板文件。我们在命令行中直接打入如下的指令:

make

    $ make
go build -i -ldflags "-X github.com/liu-xiao-guo/countbeat/vendor/github.com/elastic/beats/libbeat/version.buildTime=2019-11-13T07:33:25Z -X github.com/liu-xiao-guo/countbeat/vendor/github.com/elastic/beats/libbeat/version.commit=501bd87da668346f78398676c78b4a39394a3640"

经过上面的编译,我们可以发现在当前的目录下,有一个已经编译好的countbeat可执行文件:

我们在当前的目录下直接运行这个可执行的文件:

./countbeat -e -d "*"

我们可以在terminal中看到:

那么在我们的Kibana中也可以看到如下信息:

显然数据已经被成功上传到Elasticsearch中了。

每一个文档的内容如下:

    {
"@timestamp": "2019-11-13T07:38:57.095Z",
"agent": {
"version": "8.0.0",
"type": "countbeat",
"ephemeral_id": "d3f0638e-ee58-45ff-92cc-74f188fd66a4",
"hostname": "liuxg-2.local",
"id": "1d35220e-7f75-442a-88eb-43ec1e97f0d0"
},
"counter": 5,
"ecs": {
"version": "1.2.0"
},
"host": {
"hostname": "liuxg-2.local",
"architecture": "x86_64",
"os": {
"build": "19B88",
"platform": "darwin",
"version": "10.15.1",
"family": "darwin",
"name": "Mac OS X",
"kernel": "19.0.0"
},
"id": "E51545F1-4BDC-5890-B194-83D23620325A",
"name": "liuxg-2.local"
},
"type": "liuxg-2.local"
}

它里面含有一个counter的整数值。

所有关于beat的设计上的代码可以在目录${GOPATH}/src/github.com/liu-xiao-guo/countbeat下的/beater/CountBeat.go文件里实现的。设计比较直接。大家可以看一下代码应该可以明白。

读取JSON文件beat

在上面我们已经熟悉了如何去创建一个template的beat。它是一个最基本的beat,并没有什么特别的功能。在这节里,我们接着如法炮制来创建一个稍微有一点用途的beat。我们的这个beat叫做readjson beat。它的源码可以按照如下的方法得到:

git clone https://github.com/liu-xiao-guo/beats-readjson

首先,我们可以准备一个我们想要的json文件,比如:

users.json

    {
"users": [
{
"name": "Elliot",
"type": "Reader",
"age": 23,
"social": {
"facebook": "https://facebook.com",
"twitter": "https://twitter.com"
}
},
{
"name": "Fraser",
"type": "Author",
"age": 17,
"social": {
"facebook": "https://facebook.com",
"twitter": "https://twitter.com"
}
}
]
}

我们可以把这个文件放入到我们如何喜欢的位置。针对我的情况,我把它置于我的电脑的如下位置:

/Users/liuxg/data/beats/users.json

我们可以在readjson.yml文件中进行配置:

readjson.yml

我们的readjson.go设计也相当简单:

readjson.go

    package beater

    import (
"fmt"
"os"
"io/ioutil"
"encoding/json"
"strconv"
"time"
"os/signal"
"syscall" "github.com/elastic/beats/libbeat/beat"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/logp" "github.com/liu-xiao-guo/readjson/config"
) type Users struct {
Users []User `json:"users"`
} // User struct which contains a name
// a type and a list of social links
type User struct {
Name string `json:"name"`
Type string `json:"type"`
Age int `json:"Age"`
Social Social `json:"social"`
} // Social struct which contains a
// list of links
type Social struct {
Facebook string `json:"facebook"`
Twitter string `json:"twitter"`
} // readjson configuration.
type readjson struct {
done chan struct{}
config config.Config
client beat.Client
} // New creates an instance of readjson.
func New(b *beat.Beat, cfg *common.Config) (beat.Beater, error) {
c := config.DefaultConfig
if err := cfg.Unpack(&c); err != nil {
return nil, fmt.Errorf("Error reading config file: %v", err)
} bt := &readjson{
done: make(chan struct{}),
config: c,
}
return bt, nil
} // Run starts readjson.
func (bt *readjson) Run(b *beat.Beat) error {
logp.Info("readjson is running! Hit CTRL-C to stop it.")
var err error
bt.client, err = b.Publisher.Connect()
if err != nil {
return err
} fmt.Println("Path: ", bt.config.Path)
fmt.Println("Period: ", bt.config.Period) // Open our jsonFile
jsonFile, err := os.Open(bt.config.Path)
// if we os.Open returns an error then handle it
if err != nil {
fmt.Println(err)
} fmt.Println("Successfully Opened users.json")
// defer the closing of our jsonFile so that we can parse it later on
defer jsonFile.Close() byteValue, _ := ioutil.ReadAll(jsonFile) // we initialize our Users array
var users Users json.Unmarshal(byteValue, &users) // we iterate through every user within our users array and
// print out the user Type, their name, and their facebook url
// as just an example
for i := 0; i < len(users.Users); i++ {
fmt.Println("User Type: " + users.Users[i].Type)
fmt.Println("User Age: " + strconv.Itoa(users.Users[i].Age))
fmt.Println("User Name: " + users.Users[i].Name)
fmt.Println("Facebook Url: " + users.Users[i].Social.Facebook) event := beat.Event{
Timestamp: time.Now(),
Fields: common.MapStr {
"ostype": b.Info.Name,
"name": users.Users[i].Name,
"type": users.Users[i].Type,
"age": users.Users[i].Age,
"social": users.Users[i].Social,
},
} bt.client.Publish(event)
} c := make(chan os.Signal)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
os.Exit(1)
}() for {
fmt.Println("sleeping...")
time.Sleep(10 * time.Second)
}
} // Stop stops readjson.
func (bt *readjson) Stop() {
bt.client.Close()
close(bt.done)
}

它在run method里把json文件读入,并把它们分别发送出去到我们的Elasticsearch中。

我们按照上面的步骤进行编译,并最终运行我们的readjson beat。

./readjson -e

我们可以在Kibana中看到我们已经发送上来的beat信息:

参考:

【1】https://www.elastic.co/guide/en/beats/devguide/7.5/newbeat-generate.html

Beats:如何创建一个定制的Elastic Beat的更多相关文章

  1. wordpress插件开发从创建一个新的菜单开始

    创建插件的目的 1.我们为什么要创建一个插件? IT界有一个知名的论调叫做不要造重复的轮子,如果有可能的话,你应该尽可能的从现有的网络资源上选择一个已有的插件来使用,而不是重新创造一个.它耗费的精力很 ...

  2. ASP.NET Core管道深度剖析(2):创建一个“迷你版”的管道来模拟真实管道请求处理流程

    从<ASP.NET Core管道深度剖析(1):采用管道处理HTTP请求>我们知道ASP.NET Core请求处理管道由一个服务器和一组有序的中间件组成,所以从总体设计来讲是非常简单的,但 ...

  3. 利用django创建一个投票网站(一)

    这是教程的原始链接:http://django-intro-zh.readthedocs.io/zh_CN/latest/part1/ 创建你的第一个 Django 项目, 第一部分 来跟着实际项目学 ...

  4. 创建一个Portlet工程

    使用Liferay的SDK创建一个简单的Portlet,此Portlet不包括业务逻辑.不包括数据库,只有简单的页面展现,用以说明Portlet的开发过程. 一.创建Portlet工程 1.打开Lif ...

  5. soapui中文操作手册(二)----通过您的WSDL请求创建一个测试

      1.通过您的WSDL请求创建一个测试 点击加号旁边的导航拓展项目树的Web服务,并选择请求: 在SoapUI Pro中,所述请求编辑出现在右边.SoapUI Pro有一个编辑器,它简化了XML的层 ...

  6. 创建一个Table View

    在本课程中,您将创建应用程序FoodTracker的主屏幕.您将创建第二个,表视图为主场景,列出了用户的菜谱.你会设计定制表格单元格显示每一个菜谱,它是这样的: 学习目标 在课程结束时,你将能够: 创 ...

  7. [转]通过Mesos、Docker和Go,使用300行代码创建一个分布式系统

    http://www.csdn.net/article/2015-07-31/2825348 [编者按]时下,对于大部分IT玩家来说,Docker和Mesos都是熟悉和陌生的:熟悉在于这两个词无疑已成 ...

  8. UE4编程之C++创建一个FPS工程(二)角色网格、动画、HUD、子弹类

    转自:http://blog.csdn.net/u011707076/article/details/44243103 紧接上回,本篇文章将和大家一同整理总结UE4关于角色网格.动画.子弹类和HUD的 ...

  9. 通过 Mesos、Docker 和 Go,使用 300 行代码创建一个分布式系统

    [摘要]虽然 Docker 和 Mesos 已成为不折不扣的 Buzzwords ,但是对于大部分人来说它们仍然是陌生的,下面我们就一起领略 Mesos .Docker 和 Go 配合带来的强大破坏力 ...

随机推荐

  1. int 和 字节 相互转换

    In [10]: n = 0xf1f2 In [11]: bin(n) Out[11]: '0b1111000111110010' In [12]: n.bit_length() Out[12]: 1 ...

  2. original和source的区别

    最近跟网页翻译怼上了,在给翻译前的页面起名是纠结于使用original page还是source page,就查了一下original和source的区别. original: n. 原件:原作:原物 ...

  3. 测开之路一百二十四:flask之MVC响应过程

    MVC流程 原本的请求响应 结构: 视图: from flask import Flask, render_template app = Flask(__name__) @app.route(&quo ...

  4. final关键字的案例

    package com.company.java.oop.cls; class ClassF { // static ClassF instance =new ClassF(); static { S ...

  5. spring boot 将对象转换为json返回

    Spring Boot默认使用Jackson将对象转换为json,需要配置以下依赖: compile group: 'com.fasterxml.jackson.core', name: 'jacks ...

  6. Parameter setting for Jemeter Post method

    1. create CSV file note: the first line is parameter name 2. Add Controller Edit >Add >Logic C ...

  7. Vue 基础 day05 webpack 3.x

    什么是webpack webpack 是前端的一个项目构建工具, 它是基于 Node.js 开发出来的一个前端工具 借助于webpack这个前端自动化构建工具, 可以完美实现资源的合并.打包.压缩.混 ...

  8. 无法打开内核设备"\\.\Global\vmx86":系统找不到指定的文件. 是否在安装 VMwareWorksation 后重新引到 ? 问题解决

    节前正常使用的工作环境, 过完春节后, 上班第一天就不正常工作了, 难不成机器也要放假休息, 虚拟机打不开了, 没办法办公可是不行的. 上网查原因, 解决问题. 上网看了很多关于此问题的解决办法, 很 ...

  9. SpringBoot(四) -- SpringBoot与Web开发

    一.发开前准备 1.创建一个SpringBoot应用,引入我们需要的模块 2.SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置,就能运行起来 3.编写业务代码 二.静态资 ...

  10. 【洛谷p3958】奶酪

    奶酪[题目链接] 题前废话不知道说啥了啊qwq(越来越沉默寡言) 好了看题: SOLUTION: 思路的话,大概是搜索,然后大概广搜??? 但是我们今天写深搜(也是听xcg大佬讲了以后的整理博) 首先 ...