月度归档:2017年10月

Elasticsearch Analysis Ik 中文分词模块安装

Elasticsearch本身内置了很多分词器,但中文词库 chinese 效果不佳,所以需要安装三方 ik 插件实现生产需求。

什么是 IK Analyzer?

IK Analyzer是一个开源的,基于java语言开发的轻量级的中文分词工具包。从2006年12月推出1.0版开始, IKAnalyzer已经推出了4个大版本。最初,它是以开源项目Luence为应用主体的,结合词典分词和文法分析算法的中文分词组件。从3.0版本开始,IK发展为面向Java的公用分词组件,独立于Lucene项目,同时提供了对Lucene的默认优化实现。在2012版本中,IK实现了简单的分词歧义排除算法,标志着IK分词器从单纯的词典分词向模拟语义分词衍化。

先决条件:

安装配置 Elasticsearch 搜索引擎集群

1.安装 Ik

登录到ES服务器,进入Bin目录开始安装

$ cd /usr/local/elasticsearch
$ bin/elasticsearch-plugin install //github.com/medcl/elasticsearch-analysis-ik/releases/download/v5.6.3/elasticsearch-analysis-ik-5.6.3.zip
-> Downloading //github.com/medcl/elasticsearch-analysis-ik/releases/download/v5.6.3/elasticsearch-analysis-ik-5.6.3.zip
[=================================================] 100%
-> Installed analysis-ik

安装成功。

2.如果卸载,请执行如下命令

$ bin/elasticsearch-plugin remove analysis-ik

3.重启ES服务

$ systemctl restart elasticsearch

4.查看启动日志

$ cat /usr/local/elasticsearch/logs/my-apprenwole.log

其中elasticsearch在启动中加载模块的时会生成以下日志记录,说明analysis-ik中文分词插件已经可以使用。

[INFO ][o.e.p.PluginsService ] [renwolenode-1] loaded plugin [analysis-ik]

5.创建一个名为index的索引

$ curl -u elastic -XPUT //10.28.204.65:9200/index
Enter host password for user 'elastic':
{"acknowledged":true,"shards_acknowledged":true,"index":"index"}

说明:

-u 是用户名
回车后会让你输入密码,默认是用户名是:elastic 密码是:changeme

6.创建一个映射

curl -u elastic -XPUT //10.28.204.65:9200/index/fulltext/_mapping -d'
{
"properties": {
"content": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_max_word"
}
}
}'

7.创建测试数据

curl -u elastic -XPUT //10.28.204.65:9200/index/fulltext/1 -d'
{"content":"元芳和你先后跟随于我,总共有十多年了吧,除了危险我没有给过你们什么"}
'

curl -u elastic -XPUT //10.28.204.65:9200/index/fulltext/2 -d'
{"content":"还记得吗,元芳总是开玩笑说:吃上我一顿真是不容易"}
'

curl -u elastic -XPUT //10.28.204.65:9200/index/fulltext/3 -d'
{"content":"可现在我真想把我身上所有的钱都拿出来请他吃上一顿"}
'

curl -u elastic -XPUT //10.28.204.65:9200/index/fulltext/4 -d'
{"content":"元芳总是叫我大人,可我知道,其实在他心中将我当成了父辈"}
'

curl -u elastic -XPUT //10.28.204.65:9200/index/fulltext/5 -d'
{"content":"可是我这个父辈又为他做了什么呢。生与死,我总是让他选择后者"}
'

curl -u elastic -XPUT //10.28.204.65:9200/index/fulltext/6 -d'
{"content":"幽州是这样、湖州是这样、崇州也是这样,这一次他终于没有回来,我能说什么呢,我还能说什么呢"}
'

curl -u elastic -XPUT //10.28.204.65:9200/index/fulltext/7 -d'
{"content":"元芳是为了国家,为社稷,为黎明百姓献出了生命"}
'

curl -u elastic -XPUT //10.28.204.65:9200/index/fulltext/8 -d'
{"content":"如果说此刻我心中还有一丝欣慰,那就是替元芳感到自豪"}
'

curl -u elastic -XPUT //10.28.204.65:9200/index/fulltext/9 -d'
{"content":"如果说此刻我心中还有什么比悲伤更加强烈,那就是仇恨"}
'

8.查询数据

curl -u elastic -XPOST //10.28.204.65:9200/index/fulltext/_search -d'
{
"query" : { "match" : { "content" : "如果" }},
"highlight" : {
"pre_tags" : ["<tag1>", "<tag2>"],
"post_tags" : ["</tag1>", "</tag2>"],
"fields" : {
"content" : {}
}
}
}
'

9.查询返回的数据

{
"took": 21,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 2,
"max_score": 0.43353066,
"hits": [
{
"_index": "index",
"_type": "fulltext",
"_id": "8",
"_score": 0.43353066,
"_source": {
"content": "如果说此刻我心中还有一丝欣慰,那就是替元芳感到自豪"
},
"highlight": {
"content": [
"<tag1>如果</tag1>说此刻我心中还有一丝欣慰,那就是替元芳感到自豪"
]
}
},
{
"_index": "index",
"_type": "fulltext",
"_id": "9",
"_score": 0.43353066,
"_source": {
"content": "如果说此刻我心中还有什么比悲伤更加强烈,那就是仇恨"
},
"highlight": {
"content": [
"<tag1>如果</tag1>说此刻我心中还有什么比悲伤更加强烈,那就是仇恨"
]
}
}
]
}
}

结语:

建议通过 //10.28.204.65:5601 中的 Dev Tools 开发工具管理,kibana可视化管理真的很方便。

参考:

//github.com/medcl/elasticsearch-analysis-ik

Elasticsearch Kibana 集群 安装配置 X-pack 扩展包

X-pack概述:

X-pack 是一种 Elastic Stack 扩展包,它将安全性、警报、监视、报告和图形功能打包成一个易于安装的包。X-pack可以无缝协同ElasticSearch、 Kibana工作,它可以很好的启用或禁用您要使用的功能。

Elasticsearch 5.0之前,您必须单独安装Shield,Watcher和Marvel插件才能获得在X-Pack中所有的功能。随着X-Pack出现您不再需要担心是否拥有每个插件的正确版本,只需安装您正在运行的Elasticsearch、Kibana版本的X-Pack就可以了。

X-pack安装相对简单很多,下面我将详细介绍。

先决条件:

安装配置 Elasticsearch 搜索引擎集群
ElasticSearch 之 Kibana 二进制安装配置

:您必须运行和ElasticSearch、Kibana版本相匹配的X-Pack版本。

说明:

由于我是集群分布式,所以需要在每台Kibana、ElasticSearch集群服务器上安装X-pack。如果你是单机模式,只需要在单台服务器安装X-pack即可。另外我采用的是网络安装。

1.在 Kibana 服务器安装 X-Pack

全程自动完成安装无需配置,在kibana中安装X-pack时间较久,慢慢等待吧。

直接进入kibana安装目录执行以下命令:

$ cd /usr/local/kibana
$ bin/kibana-plugin install x-pack
Found previous install attempt. Deleting...
Attempting to transfer from x-pack
Attempting to transfer from //artifacts.elastic.co/downloads/kibana-plugins/x-pack/x-pack-5.6.3.zip
Transferring 119526941 bytes....................
Transfer complete
Retrieving metadata from plugin archive
Extracting plugin archive
Extraction complete
Optimizing and caching browser bundles...
Plugin installation complete

安装完成。

2.如果卸载请执行以下命令

$ bin/kibana-plugin remove x-pack

3.在 Elasticsearch 服务器安装 X-Pack

全程自动完成安装也无需配置,这个速度很快。

进入elasticsearch安装目录执行以下命令开始安装:
$ cd /usr/local/elasticsearch
$ bin/elasticsearch-plugin install x-pack
-> Downloading x-pack from elastic
[=================================================] 100%
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: plugin requires additional permissions @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* java.io.FilePermission \\.\pipe\* read,write
* java.lang.RuntimePermission accessClassInPackage.com.sun.activation.registries
* java.lang.RuntimePermission getClassLoader
* java.lang.RuntimePermission setContextClassLoader
* java.lang.RuntimePermission setFactory
* java.security.SecurityPermission createPolicy.JavaPolicy
* java.security.SecurityPermission getPolicy
* java.security.SecurityPermission putProviderProperty.BC
* java.security.SecurityPermission setPolicy
* java.util.PropertyPermission * read,write
* java.util.PropertyPermission sun.nio.ch.bugLevel write
* javax.net.ssl.SSLPermission setHostnameVerifier
See //docs.oracle.com/javase/8/docs/technotes/guides/security/permissions.html
for descriptions of what these permissions allow and the associated risks.

Continue with installation? [y/N]y
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: plugin forks a native controller @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
This plugin launches a native controller that is not subject to the Java
security manager nor to system call filters.

Continue with installation? [y/N]y
-> Installed x-pack

注意:中途会让你输入两次 Y 表示确认安装。

最后安装完成。

4.如果卸载请执行如下命令

$ bin/elasticsearch-plugin remove x-pack

5.重启服务

$ systemctl restart elasticsearch
$ systemctl restart kibana

重启完成后你就可以通过 //10.28.204.65:5601 进行管理。默认登录账号是:elastic 密码是:changeme

登录后点击 Monitoring 可查看 Elasticsearch 和 Kibana 集群信息,再进一步可以查看监控图表信息。此外还可以进行账户设置等,我就不上图了。

6.许可证管理

初次安装X-Pack提供30天的试用许可证,允许使用X-Pack所有功能。但试用期结束后,将禁用其所有功能,所以我们需要申请订阅免费的许可证(当然你也可以购买企业许可证)。

7.更新许可证

申请完许可证后会通过邮箱发你一封邮件,下载对应的 json 文件即可,许可证作为您使用 API 安装的JSON文件提供license,你可以将其上传到服务器/tmp目录。

然后执行以下命令:

$ curl -XPUT -u elastic '//10.28.204.65:9200/_xpack/license?acknowledge=true' -H "Content-Type: application/json" -d @/tmp/license.json

许可证更新成功后是1年有效期,在订阅的时候有说明。

接下来你就愉快的玩耍吧。

vim 命令编辑 Hosts 文件 详细使用方法

用vim命令打开Hosts文件

$ vim /etc/hosts

按”i“键,进入编辑模式 按”Esc“键,退出编辑模式

按”Backspace“键,删除光标前一个字符
按”Delete“键,删除光标后一个字符
按”dd“键,删除当前行

按”yy“键,复制当前行
按”p“键,粘贴复制的内容到下一行

按”:wq“,保存退出
按”:x“,保存退出
按”:q!“,强行退出不保存

“上”键:光标移至上一行
“下”键:光标移至下一行
“左”键:光标移至左移一个字符
“右”键:光标移至右移一个字符

Home“键,光标移至当前行首
End“键,光标一直当前行尾

PgUp“,向上翻页
PgDn“,向下翻页

ElasticSearch 之 Kibana 二进制安装配置

介绍:

Kibana 是一个开源分析数据可视化平台。你可以使用 Kibana 对数据进行高效的搜索、可视化、分析,还可以与 Elasticsearch 搜索引擎之中的数据进行交互。

Kibana 可以轻松掌握大量的数据。 其基于浏览器的界面使您能够快速创建共享动态仪表板,实时监控 ElasticSearch 的查询与更改。

先决条件:

安装配置 Elasticsearch 搜索引擎集群

要求:Kibana 与 Elasticsearch 的版本必须一致。

1.创建用户和组

$ groupadd kibana
$ useradd -g kibana kibana

2.安装 Kibana

下载地址://www.elastic.co/products

解压创建软连接:

$ cd /tmp
$ sha1sum kibana-5.6.3-linux-x86_64.tar.gz
$ tar zxvf kibana-5.6.3-linux-x86_64.tar.gz
$ mv kibana-5.6.3-linux-x86_64 /usr/local
$ cd /usr/local
$ ln -s kibana-5.6.3-linux-x86_64 kibana

3.配置 kibana

配置完成后的内容如下:

$ egrep -v "^$|^#|^;" /usr/local/kibana/config/kibana.yml

server.port: 5601
server.host: "10.28.204.65"
server.name: "10.28.204.65"
elasticsearch.url: "//10.28.204.65:9200"
elasticsearch.preserveHost: true
elasticsearch.pingTimeout: 1500
elasticsearch.requestTimeout: 30000
pid.file: /usr/local/kibana/kibana.pid

更多配置请参阅配置 Kibana

4.赋予 Kibana 目录权限

$ cd /usr/local
$ chown -R kibana.kibana kibana*

5.启动 kibana

$ cd /usr/local/kibana/bin
$ ./kibana
log [02:01:19.285] [info][status][plugin:kibana@5.6.3] Status changed from uninitialized to green - Ready
log [02:01:19.819] [info][status][plugin:elasticsearch@5.6.3] Status changed from uninitialized to yellow - Waiting for Elasticsearch
log [02:01:20.078] [info][status][plugin:console@5.6.3] Status changed from uninitialized to green - Ready
log [02:01:20.288] [info][status][plugin:metrics@5.6.3] Status changed from uninitialized to green - Ready
log [02:01:21.263] [info][status][plugin:timelion@5.6.3] Status changed from uninitialized to green - Ready
log [02:01:21.306] [info][listening] Server running at //10.28.204.65:5601
log [02:01:21.315] [info][status][ui settings] Status changed from uninitialized to yellow - Elasticsearch plugin is yellow
log [02:01:25.304] [info][status][plugin:elasticsearch@5.6.3] Status changed from yellow to yellow - No existing Kibana index found
log [02:01:29.992] [info][status][plugin:elasticsearch@5.6.3] Status changed from yellow to green - Kibana index ready
log [02:01:30.008] [info][status][ui settings] Status changed from yellow to green - Ready

打印出了启动状态,已经启动成功。

现在你可以使用 //10.28.204.65:5601 进行访问配置即可。

6.创建 systemctl 系统 Kibana 单元文件

我们需要创建单元服务文件,目的是为了便于管理:

$ vim /usr/lib/systemd/system/kibana.service

添加以下内容:

[Unit]
Description=Kibana

[Service]
Type=simple
User=kibana
Group=kibana
# Load env vars from /etc/default/ and /etc/sysconfig/ if they exist.
# Prefixing the path with '-' makes it try to load, but if the file doesn't
# exist, it continues onward.
EnvironmentFile=-/usr/local/kibana/config
EnvironmentFile=-/etc/sysconfig/kibana
ExecStart=/usr/local/kibana/bin/kibana "-c /usr/local/kibana/config/kibana.yml"
Restart=always
WorkingDirectory=/

[Install]
WantedBy=multi-user.target

7.启动并加入开机启动

$ systemctl restart kibana
$ systemctl enable kibana

8.设置防火墙

$ firewall-cmd --permanent --zone=public --add-port=5601/tcp
$ firewall-cmd --reload

到目前为止 Kibana 已经安装完成,并可以正常使用。

安装配置 Elasticsearch 搜索引擎集群

Elasticsearch是一个高度可扩展的开源全文搜索和分析引擎。它允许您快速,实时地存储,搜索和分析大量数据。它通常用作为具有复杂的搜索功能和要求的应用程序提供的底层引擎技术。

Elasticsearch 安装方式如同Tomcat,开箱即用,无需安装复杂的依赖包。

先决条件:

Elasticsearch至少需要Java 8版本。以下是安装文档,所以我们在这里不再赘述。

Linux JAVA JDK JRE 环境变量安装与配置

集群部署环境及设备配置:

/台/16G/8核/500G

10.28.204.62
10.28.204.63
10.28.204.64
10.28.204.65

Elasticsearch 5.6.3
CentOS Linux release 7.4.1708 (Core)
Kernel: Linux 3.10.0-693.2.2.el7.x86_64

说明:以下安装步骤,我在 10.28.204.65 服务器操作,其他机器均相同,我会标注集群重点部分。

1.创建用户及组并设置密码

$ groupadd es
$ useradd -g es es
$ passwd es

2.安装 Elasticsearch

下载地址 //www.elastic.co/downloads/elasticsearch#ga-release

解压:

$ cd /tmp
$ tar zxvf elasticsearch-5.6.3.tar.gz

移动目录并创建软连接:

$ mv elasticsearch-5.6.3 /usr/local
$ cd /usr/local
$ ln -s elasticsearch-5.6.3 elasticsearch

设置目录用户权限:

$ chown -R es.es elasticsearch*

3.配置  jvm.options

Elasticsearch默认堆内存为2 GB,无法满足需求,需要将以下文件中的2个Xms、Xmx修改为8G即可,其他默认。

$ vim /usr/local/elasticsearch/config/jvm.options
...
-Xms8g
-Xmx8g
...

注意:建议分配机器物理内存一半大小,最大不要超过32GB。

4.配置 elasticsearch.yml

配置后的内容如下:

$ egrep -v "(^#|^$)" /usr/local/elasticsearch/config/elasticsearch.yml
cluster.name: my-apprenwole
#集群名称,任意。ES启动后会将具有相同集群名字的节点放到一个集群下。

node.name: renwolenode-1
#节点名称 任意 唯一值。

bootstrap.memory_lock: false
#关闭锁定内存。

network.host: 10.28.204.65
#本机IP地址,每个节点都要修改。

http.port: 9200
#http访问端口为了安全建议修改。

discovery.zen.ping.unicast.hosts: ["10.28.204.62","10.28.204.63", "10.28.204.64","10.28.204.65"]
#当新节点启动时,传递主机的初始列表以执行发现。如果端口不是默认,需加上端口。

discovery.zen.minimum_master_nodes: 3
#指定集群节点中有几个有master资格的节点。如果是多个集群可以写3个以上。

client.transport.ping_timeout: 120s
#等待来自节点的ping响应的时间。默认为60s。

discovery.zen.ping_timeout: 120s
#允许选举时间处理速度慢或拥塞网络的情况下的调整(较高的值保证故障少的几率)。

http.cors.enabled: true
#启用或禁用跨原始资源共享,即;另一来源上的浏览器是否可以针对Elasticsearch执行请求。

http.cors.allow-origin: "*"
#默认为不允许来源。如果您预先添加并附/加到该值,则将其视为正则表达式,允许您支持HTTP和HTTP。例如使用/https?:\/\/localhost(:[0-9]+)?/将在两种情况下适当返回请求头。*是一个有效的值,但被认为是一个安全风险,因为您的弹性搜索实例可以从任何地方交叉发起请求。

说明:Elasticsearch默认值配置具有良好设置,并且需要很少的配置,默认经过少许配置即可用于生产。

更多配置信息,请参阅 Elasticsearch modules

注:其他三台机器除以下参数不同,其他均为相同:

node.name
network.host

5.Memlock设置

在该文件中添加以下内容:

$ vim /etc/security/limits.conf

es soft memlock unlimited
es hard memlock unlimited
es - nofile 65536

如果不添加,启动的时候会报警告信息:

Unable to lock JVM Memory: error=12, reason=Cannot allocate memory
This can result in part of the JVM being swapped out.
Increase RLIMIT_MEMLOCK, soft limit: 65536, hard limit: 65536
These can be adjusted by modifying /etc/security/limits.conf, for example:
# allow user 'es' mlockall
es soft memlock unlimited
es hard memlock unlimited

以上错误信息还给出了解决方案。

6.服务器内存设置

$ vim /etc/sysctl.conf

vm.max_map_count=262144

$ sysctl -p

7.启动 Elasticsearch

由于ES默认不允许root直接启动,这是为了安全起见,下面切换为 es 账号启动:

[root@102820465 ~]# su es
[es@102820465 ~]$ cd /usr/local/elasticsearch/bin
[es@102820465 bin]$ ./elasticsearch
[INFO ][o.e.n.Node ] [renwolenode-1] initializing ...
[INFO ][o.e.e.NodeEnvironment ] [renwolenode-1] using [1] data paths, mounts [[/ (rootfs)]], net usable_space [4021.3mb], net total_space [15.9gb], spins? [unknown], types [rootfs]
[INFO ][o.e.e.NodeEnvironment ] [renwolenode-1] heap size [7.9gb], compressed ordinary object pointers [true]
[INFO ][o.e.n.Node ] [renwolenode-1] node name [renwolenode-1], node ID [vkixu3LZTPq82SAWWXyNcg]
[INFO ][o.e.n.Node ] [renwolenode-1] version[5.6.3], pid[21425], build[667b497/2017-10-18T19:22:05.189Z], OS[Linux/3.10.0-514.el7.x86_64/amd64], JVM[Oracle Corporation/Java HotSpot(TM) 64-Bit Server VM/1.8.0_144/25.144-b01]
[INFO ][o.e.n.Node ] [renwolenode-1] JVM arguments [-Xms8g, -Xmx8g, -XX:+UseConcMarkSweepGC, -XX:CMSInitiatingOccupancyFraction=75, -XX:+UseCMSInitiatingOccupancyOnly, -XX:+AlwaysPreTouch, -Xss1m, -Djava.awt.headless=true, -Dfile.encoding=UTF-8, -Djna.nosys=true, -Djdk.io.permissionsUseCanonicalPath=true, -Dio.netty.noUnsafe=true, -Dio.netty.noKeySetOptimization=true, -Dio.netty.recycler.maxCapacityPerThread=0, -Dlog4j.shutdownHookEnabled=false, -Dlog4j2.disable.jmx=true, -Dlog4j.skipJansi=true, -XX:+HeapDumpOnOutOfMemoryError, -Des.path.home=/usr/local/elasticsearch]
[INFO ][o.e.p.PluginsService ] [renwolenode-1] loaded module [aggs-matrix-stats]
[INFO ][o.e.p.PluginsService ] [renwolenode-1] loaded module [ingest-common]
[INFO ][o.e.p.PluginsService ] [renwolenode-1] loaded module [lang-expression]
[INFO ][o.e.p.PluginsService ] [renwolenode-1] loaded module [lang-groovy]
[INFO ][o.e.p.PluginsService ] [renwolenode-1] loaded module [lang-mustache]
[INFO ][o.e.p.PluginsService ] [renwolenode-1] loaded module [lang-painless]
[INFO ][o.e.p.PluginsService ] [renwolenode-1] loaded module [parent-join]
[INFO ][o.e.p.PluginsService ] [renwolenode-1] loaded module [percolator]
[INFO ][o.e.p.PluginsService ] [renwolenode-1] loaded module [reindex]
[INFO ][o.e.p.PluginsService ] [renwolenode-1] loaded module [transport-netty3]
[INFO ][o.e.p.PluginsService ] [renwolenode-1] loaded module [transport-netty4]
[INFO ][o.e.p.PluginsService ] [renwolenode-1] no plugins loaded
[INFO ][o.e.d.DiscoveryModule ] [renwolenode-1] using discovery type [zen]
[INFO ][o.e.n.Node ] [renwolenode-1] initialized
[INFO ][o.e.n.Node ] [renwolenode-1] starting ...
[INFO ][o.e.t.TransportService ] [renwolenode-1] publish_address {10.28.204.65:9300}, bound_addresses {10.28.204.65:9300}
[INFO ][o.e.b.BootstrapChecks ] [renwolenode-1] bound or publishing to a non-loopback or non-link-local address, enforcing bootstrap checks
[WARN ][o.e.n.Node ] [renwolenode-1] timed out while waiting for initial discovery state - timeout: 30s
[INFO ][o.e.h.n.Netty4HttpServerTransport] [renwolenode-1] publish_address {10.28.204.65:9200}, bound_addresses {10.28.204.65:9200}
[INFO ][o.e.n.Node ] [renwolenode-1] started

节点成功启动,状态:started 启动后当前终端会一直显示 ElasticSearch 状态信息。

假如启动失败,会显示详细错误说明,根据报错解决即可。

如果退出按 Ctrl + c 同时 ElasticSearch 也会停止。

8.重开一个终端访问ES

$ curl //10.28.204.65:9200/

{
"name" : "renwolenode-1",
"cluster_name" : "my-apprenwole",
"cluster_uuid" : "Xf_ZdW0XQum4rycQA40PfQ",
"version" : {
"number" : "5.6.3",
"build_hash" : "667b497",
"build_date" : "2017-10-18T19:22:05.189Z",
"build_snapshot" : false,
"lucene_version" : "6.6.1"
},
"tagline" : "You Know, for Search"
}

返回ES的部分信息,说明ES可以正常使用。

9.创建 systemd 单元服务文件

事实上我们在生产环境中,管理ES的时候,不可能来回切换账号用 ./elasticsearch 方式启动。若Elasticsearch服务器宕机恢复时无法随机启动,就会给运维人员带来不必要的麻烦。

因此创建开机自启动文件:

$ vim /usr/lib/systemd/system/elasticsearch.service

添加以下内容:

[Service]
Environment=ES_HOME=/usr/local/elasticsearch
Environment=CONF_DIR=/usr/local/elasticsearch/config
Environment=DATA_DIR=/usr/local/elasticsearch/data
Environment=LOG_DIR=/usr/local/elasticsearch/logs
Environment=PID_DIR=/usr/local/elasticsearch
EnvironmentFile=-/usr/local/elasticsearch/config

WorkingDirectory=/usr/local/elasticsearch

User=es
Group=es

ExecStartPre=/usr/local/elasticsearch/bin/elasticsearch-systemd-pre-exec

ExecStart=/usr/local/elasticsearch/bin/elasticsearch \
-p ${PID_DIR}/elasticsearch.pid \
--quiet \
-Edefault.path.logs=${LOG_DIR} \
-Edefault.path.data=${DATA_DIR} \
-Edefault.path.conf=${CONF_DIR}

# StandardOutput is configured to redirect to journalctl since
# some error messages may be logged in standard output before
# elasticsearch logging system is initialized. Elasticsearch
# stores its logs in /var/log/elasticsearch and does not use
# journalctl by default. If you also want to enable journalctl
# logging, you can simply remove the "quiet" option from ExecStart.
StandardOutput=journal
StandardError=inherit

# Specifies the maximum file descriptor number that can be opened by this process
LimitNOFILE=65536

# Specifies the maximum number of processes
LimitNPROC=2048

# Specifies the maximum size of virtual memory
LimitAS=infinity

# Specifies the maximum file size
LimitFSIZE=infinity

# Disable timeout logic and wait until process is stopped
TimeoutStopSec=0

# SIGTERM signal is used to stop the Java process
KillSignal=SIGTERM

# Send the signal only to the JVM rather than its control group
KillMode=process

# Java process is never killed
SendSIGKILL=no

# When a JVM receives a SIGTERM signal it exits with code 143
SuccessExitStatus=143

[Install]
WantedBy=multi-user.target

# Built for distribution-5.6.3 (distribution)

10.重启 elasticsearch

$ systemctl restart elasticsearch

注:重启ES后不会立即运行,它有一个启动过程,约1min左右,即可通过 ss -ntlp 查看 9200、9300是否运行,运行后再查看集群状态。

11.设置 Firewalld 防火墙

$ firewall-cmd --permanent --add-port={9200/tcp,9300/tcp}
$ firewall-cmd --reload
$ firewall-cmd --list-all

12.查看集群状态

在集群中输入以下URL即可获取集群健康状态信息:

$ curl //10.28.204.65:9200/_cluster/health?pretty

{
"cluster_name" : "my-apprenwole", //集群名称
"status" : "green", //集群的状态分为:红/绿/灯,绿:健康,黄:亚健康,红:病态
"timed_out" : false,
"number_of_nodes" : 4, //节点数
"number_of_data_nodes" : 4, //数据节点
"active_primary_shards" : 6, //主分片总数
"active_shards" : 22, //集群内所有索引的分片总数
"relocating_shards" : 0, //正在迁移中的分片数
"initializing_shards" : 0, //正在初始化的分片数
"unassigned_shards" : 0, //未分配到具体节点上的分片数
"delayed_unassigned_shards" : 0,
"number_of_pending_tasks" : 0,
"number_of_in_flight_fetch" : 0,
"task_max_waiting_in_queue_millis" : 0,
"active_shards_percent_as_number" : 100.0 //活动碎片百分比
}

我们采用4台ES实例,所以集群也显示了具体数据,说明集群运行正常。

ES集群已经安装完成。此文为原创内容,可直接用于生产。ES有很多插件,后期我会写一些相关文档,例如:Kibana、Logstash、X-Pack 这些插件都是官方插件,相当实用。

禁用 Transparent Huge Pages (THP) 透明巨大页面

Transparent Huge Pages (THP)是一种Linux内存管理系统,可以通过使用更大的内存页来减少对带有大量内存的机器Translation Lookaside Buffer (TLB)的开销。

然而,数据库工作负载通常在THP上表现不佳,因为它们往往是稀疏而非连续性的内存访问模式。所以你应该禁用Linux机器上的THP,以确保Redis、ORACLE、MariaDB、MongoDB等数据库的最佳性能。

Transparent Huge Pages是在CentOS/RedHat 6.0中引入的优化,从CentOS 7 版本开始,该特性默认启用,其目的是减少大量内存的系统的开销。然而,由于某些数据库使用内存的方式,这个特性实际上弊大于利,因为内存访问很少是连续的。

下面介绍如何禁用RedHat/CentOS 6/7上的透明巨大页面。对于其他系统,请查阅供应商的文档。

生产环境:

$ hostnamectl
...
Operating System: CentOS Linux 7 (Core)
CPE OS Name: cpe:/o:centos:centos:7.4 1708
Kernel: Linux 3.10.0-693.2.2.el7.x86_64
Architecture: x86-64

先查看 THP 状态:

$ cat /sys/kernel/mm/transparent_hugepage/enabled
[always] madvise never

$ cat /sys/kernel/mm/transparent_hugepage/defrag
[always] madvise never

状态显示:启用。

创建脚本:

$ vim /etc/init.d/disable-transparent-hugepages

添加以下内容:

#!/bin/bash
### BEGIN INIT INFO
# Provides:          disable-transparent-hugepages
# Required-Start:    $local_fs
# Required-Stop:
# X-Start-Before:    mongod mongodb-mms-automation-agent
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Disable Linux transparent huge pages
# Description:       Disable Linux transparent huge pages, to improve
#                    database performance.
### END INIT INFO

case $1 in
  start)
    if [ -d /sys/kernel/mm/transparent_hugepage ]; then
      thp_path=/sys/kernel/mm/transparent_hugepage
    elif [ -d /sys/kernel/mm/redhat_transparent_hugepage ]; then
      thp_path=/sys/kernel/mm/redhat_transparent_hugepage
    else
      return 0
    fi

    echo 'never' > ${thp_path}/enabled
    echo 'never' > ${thp_path}/defrag

    re='^[0-1]+$'
    if [[ $(cat ${thp_path}/khugepaged/defrag) =~ $re ]]
    then
      # RHEL 7
      echo 0  > ${thp_path}/khugepaged/defrag
    else
      # RHEL 6
      echo 'no' > ${thp_path}/khugepaged/defrag
    fi

    unset re
    unset thp_path
    ;;
esac

保存并退出!

给予该文件可执行权限,命令如下:

$ chmod 755 /etc/init.d/disable-transparent-hugepages

加入开机自启动并重启系统:

$ systemctl enable disable-transparent-hugepages
$ systemctl start disable-transparent-hugepages
$ sudo reboot

再次查看THP状态:

$ cat /sys/kernel/mm/transparent_hugepage/enabled
always madvise [never]

$ cat /sys/kernel/mm/transparent_hugepage/defrag
always madvise [never]

状态显示:已经禁用。

到此 禁用 Transparent Huge Pages 的目的已经实现。

注意:该教程不适用于Debian/Ubuntu或CentOS/RedHat 5 及更低版本。原因上述已说明。

Nginx 反向代理实现 Kibana 登录认证功能

Kibana 5.5 版后,已不支持认证功能,也就是说,直接打开页面就能管理,想想都不安全,不过官方提供了 X-Pack 认证,但有时间限制。毕竟X-Pack是商业版。

下面我将操作如何使用Nginx反向代理实现kibana的认证功能。

先决条件:

Centos 7 源码编译安装 Nginx

1.安装 Apache Httpd 密码生成工具

$ yum install httpd-tools -y

2.生成Kibana认证密码

$ mkdir -p /usr/local/nginx/conf/passwd
$ htpasswd -c -b /usr/local/nginx/conf/passwd/kibana.passwd Userrenwolecom GN5SKorJ
Adding password for user Userrenwolecom

3.配置Nginx反向代理

在Nginx配置文件中添加如下内容(或新建配置文件包含):

$ vim /usr/local/nginx/conf/nginx.conf

server {
listen 10.28.204.65:5601;
auth_basic "Restricted Access";
auth_basic_user_file /usr/local/nginx/conf/passwd/kibana.passwd;
location / {
proxy_pass //10.28.204.65:5601;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade; 
}
}

4.配置Kibana

取消下面注释:

$ vim /usr/local/kibana/config/kibana.yml

server.host: "10.28.204.65"

5.重启 Kibana 及 Nginx 服务使配置生效

$ systemctl restart kibana.service
$ systemctl restart nginx.service

接下来浏览器访问 //103.28.204.65:5601/ 会提示验证弹窗,输入以上生成的用户密码登录即可。

Zabbix 监控 Redis 数据库性能

说明:以下所有操作均在 Zabbix Agent 客户端操作。

部署环境:

OS:CentOS Linux release 7.4.1708 (Core) x64
Zabbix Servers:3.4
Redis Servers:4.0

先决条件:

Linux Centos7 Redis 源码编译安装配置

1.修改主机 Host

文件末端添加以下内容:

$ vim /etc/hosts

10.28.204.65 s102820465

2.安装 Python 依赖包

$ yum -y install python-pip
$ pip install argparse
$ pip install redis

3.下载 Zabbix 官方提供的 Template Redis 模板

将下载到本地的压缩包传入到tmp目录后解压:

//github.com/adubkov/zbx_redis_template

$ cd /tmp
$ tar zxvf zbx_redis_template-master.zip
$ cd zbx_redis_template-master

将以下2个配置文件拷贝到相关目录:

$ cp zbx_redis_stats.py /usr/local/zabbix/bin
$ cp zbx_redis.conf /usr/local/zabbix/etc/zabbix_agentd.conf.d/

注意:除上面两个文件外,其他的可以忽略。因为官方Zabbix template 模板提供了两种监控redis的方案,分别是 node.js 、python。本文教程采用后者。

4.配置zbx_redis_stats.py

将以下文件中的参数修改为 Zabbix Server 主机IP及端口:

$ cd /usr/local/zabbix/bin
$ vim zbx_redis_stats.py
...
zabbix_host = '10.28.204.62' # Zabbix Server IP
zabbix_port = 10051 # Zabbix Server Port
...

给该文件可执行权限:

$ chmod +x zbx_redis_stats.py

5.配置zbx_redis.conf

$ cd /usr/local/zabbix/etc/zabbix_agentd.conf.d/

将文件修改为以下内容:

$ vim zbx_redis.conf

UserParameter=redis[*],/usr/local/zabbix/bin/zbx_redis_stats.py -p 6379 -a RenwoleQxl5qpKHrh $1 $2 $3

6.测试zbx_redis_status.py是否可以连接 Redis 数据库

$ cd /usr/local/zabbix/bin
$ ./zbx_redis_stats.py -h 127.0.0.1 -p 6379 -a RenwoleQxl5qpKHrh

usage: zbx_redis_stats.py [-h] [-p REDIS_PORT] [-a REDIS_PASS]
[redis_hostname] [metric] [db]

Zabbix Redis status script

positional arguments:
redis_hostname
metric
db

optional arguments:
-h, --help show this help message and exit
-p REDIS_PORT, --port REDIS_PORT
Redis server port
-a REDIS_PASS, --auth REDIS_PASS
Redis server pass

出现以上内容说明连接正常。

参数说明:

-h Redis bind 地址
-p Redis端口
-a Redis密码

7.测试是否获取到数据

$ ./zbx_redis_stats.py -p 6379 -a RenwoleQxl5qpKHrh S102820465 used_cpu_user_children none
0.71

返回 0.71,此值不固定,只要有数据返回,说明脚本运行正常。

参数说明:

zbx_redis.conf文件中的$1 $2 $3这时就派上用场了。

$1 对应 S102820465 主机Host
$2 对应 used_cpu_user_children
$3 对应 none

最后将 zbx_redis_templates.xml 模板导入到 Zabbix Servers UI 中,然后链接到需要监控的主机即可。

如果在Zabbix UI中无法获取的到数据,可以在 Zabbix Agent 客户端直接运行 zbx_redis_stats.py 脚本,如果有配置不正确的地方,会反馈出来,再根据报错处理即可。

结语:

其实监控redis状态的模板太多了,基本都是大同小异,选择一个适合自己的,比如监控项目非常多的,这样就可以了解redis更多性能指标。