Mongodb文档数据库和ELK日志分析系统

一 部署3节点mongodb复制集。

1.介绍

在MongoDB中,集合(Collection)的概念是用来存储文档的。集合类似于关系数据库中的表,但是在MongoDB中并没有严格的模式定义,允许存储灵活的数据结构。所以,可以说在MongoDB中叫集合(Collection)。每个集合包含一个或多个文档,文档是键值对的形式存储的

mongodb与mysql对应关系

mongo mysql
库 ----->库
集合----->表
文档----->数据行

2.安装

2.1 yum安装

MongoDB启动失败


问题1:Mongo启动失败
systemctl start mongod
Job for mongod.service failed because the control process exited with error code.
See "systemctl status mongod.service" and "journalctl -xe" for details
使用  tail  -f mongod.log  查看日志
{"t":{"$date":"2023-07-31T020:33:36.110+08:00"},"s":"E",  "c":"WT",       "id":22435,   "ctx":"initandlisten","msg":"WiredTiger error message","attr":{"error":13,"message":"[1690738416:110859][21844:0x7fe9b55c7000], wiredtiger_open: [WT_VERB_DEFAULT][ERROR]: __posix_open_file, 805: /var/lib/mongo/WiredTiger.turtle: handle-open: open: Permission denied"}}
{"t":{"$date":"2023-07-31T20:33:36.111+08:00"},"s":"W",  "c":"STORAGE",  "id":22347,   "ctx":"initandlisten","msg":"Failed to start up WiredTiger under any compatibility version. This may be due to an unsupported upgrade or downgrade."}
{"t":{"$date":"2023-07-31T20:33:36.111+08:00"},"s":"F",  "c":"STORAGE",  "id":28595,   "ctx":"initandlisten","msg":"Terminating.","attr":{"reason":"13: Permission denied"}}
chown -R  mongod:mongod  /var/lib/mongo/  由于用root用户使用  mongod -f /etc/mongod.conf 二进制启动,导致目录里生成了root权限的文件,重新授权mongod即可



2.2 二进制安装

wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel80-5.0.19.tgz
tar -xf mongodb-linux-x86_64-rhel80-5.0.19.tgz
mongo命令添加到环境变量:export PATH=/usr/local/mongodb/bin:$PATH

echo never > /sys/kernel/mm/transparent hugepage/enabled

这个命令是用于禁用透明大页(Transparent Huge Pages)功能。透明大页是一种用于内存管理的技术,可以提高大型数据集和内存密集型应用程序的性能。

使用这个命令将"never"写入"/sys/kernel/mm/transparent_hugepage/enabled"文件中,意味着禁用透明大页功能。这样做可能会对性能产生一些影响,特别是对于使用大量内存的应用程序来说,因为透明大页可以提供更高效的内存管理。

但是,禁用透明大页可能并不适用于所有环境和应用程序。在实际使用前,建议对特定的应用程序进行测试,以确定是否要禁用透明大页功能。

请注意,在执行此类系统命令之前,请确保你了解其含义和可能的影响,并在必要时以管理员权限运行该命令

[root@openvpn-server ~]# mongosh #mongo的高级版

3. mongodb 管理

3.1常见命令

> db   #查看当前数据库
test
> show tables;  #查看表(集合)    也可以用 show collections
users

db.test.insert({name:"haha",age:22}) #当插入一个文档的时候,一个集合(表)就会自动创建。

> db.users.find()  #查看表中的内容   
{ "_id" : ObjectId("64be92fcae52cd979e1087fb"), "id" : 0, "name" : "wang0", "age" : 20 }

myrepl:PRIMARY> db.test.drop()  #删除test表(集合)
true

python访问
pip3 install pymongo

删除当前数据库

> db.dropDatabase()
{ "ok" : 1 }

db.t1.stats() 查看表t1状态信息

删除uid=9998的集合记录
test> db.student.remove({uid: 9998})
{ acknowledged: true, deletedCount: 1 }

#修改文档,如果没有加multi: true.默认只修改第一个符合条件的文档

test> db.student.update({uid:1},{$set:{age: 20}},{multi: true})
DeprecationWarning: Collection.update() is deprecated. Use updateOne, updateMany, or bulkWrite.
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 2,
  modifiedCount: 2,
  upsertedCount: 0
}
test> 

3.2 用户权限管理

验证库

在 MongoDB 中,身份验证库是用来存储用户凭据和权限信息的特殊数据库。当用户尝试进行身份验证时,MongoDB 将在身份验证库中查找用户的凭据,并验证其身份是否有效。

use admin  #使用那个验证库
db.createUser ( {user: "luo",pwd: "123456" ,roles:  [{ role:"root",db: "admin"}] })

#创建名为luo的用户,拥有root权限,对admin库

开启用户认证。在mongo配置文件添加配置

vi  mongo.conf
security:
 authorization: enabled

连接

mongo --host   192.168.1.188 -u luo -p 123456 --authenticationDatabase admin

–authenticationDatabase 指定验证库

4. 复制集

复制集环境规划

使用三个节点部署复制集,ip分别是192.168.1.124,192.168.1.128,192.168.1.129

准备配置文件

修改配置文件,并拷贝到其他节点

cat  /mongodb/conf/mongo.conf 
systemLog:
  destination: file
  path: "/mongodb/log/mongodb.log"
  logAppend: true

storage:
  dbPath: "/mongodb/data/"
  journal:
    enabled: true
 
processManagement:
  fork: true

net:
  port: 27017
  bindIp: 0.0.0.0
replication:
  replSetName: myrepl  #指定复制集名称,所有复制集成员此名称要一致

配置复制集

mongo #登录mongo

#指定复制集的所有成员信息
config = { _id: 'myrepl', members: [
 {_id: 0, host: '192.168.1.124:27017'},
 {_id: 1, host: '192.168.1.128:27017'} ,
 {_id: 2, host: '192.168.1.129:27017'}]
 }

#初始化并启动复制集
> rs.initiate(config)
{ "ok" : 1 }
myrepl:SECONDARY> 

批量添加1万条记录,在主节点执行

for(i=0;i<10000;i++){db.student.insert({uid:i, name: "wang"+i , "age":18,"date": new Date()})}

注:在mongodb复制集当中,默认从库不允许读。在从库打开读配置

myrepl:SECONDARY> rs.secondaryOk()              #secondary代表从库
myrepl:PRIMARY> db.student.count()     #统计student中集合的数量
10000

停止主,一个从节点变为从,查看日志,

root@redis07:~# tail  -f /mongodb/log/mongodb.log 

添加节点
myrepl:PRIMARY> rs.add(“192.168.1.250:27017”)
{
“ok” : 1, #1表示成功

myrepl:PRIMARY> rs.isMaster()   #查看节点状态
{
	"topologyVersion" : {
		"processId" : ObjectId("64c102590ce0e1864b77734c"),
		"counter" : NumberLong(13)
	},
	"hosts" : [
		"192.168.1.124:27017",
		"192.168.1.128:27017",
		"192.168.1.129:27017",
		"192.168.1.250:27017"
	],
	"setName" : "myrepl",
	"setVersion" : 3,
	"ismaster" : true,
	"secondary" : false,
	"primary" : "192.168.1.124:27017",
	"me" : "192.168.1.124:27017",
	"electionId" : ObjectId("7fffffff0000000000000003"),
	"lastWrite" : {
		"opTime" : {
			"ts" : Timestamp(1690379364, 1),
			"t" : NumberLong(3)
		},
		"lastWriteDate" : ISODate("2023-07-26T13:49:24Z"),
		"majorityOpTime" : {
			"ts" : Timestamp(1690379364, 1),
			"t" : NumberLong(3)
		},
		"majorityWriteDate" : ISODate("2023-07-26T13:49:24Z")
	},
	"maxBsonObjectSize" : 16777216,
	"maxMessageSizeBytes" : 48000000,
	"maxWriteBatchSize" : 100000,
	"localTime" : ISODate("2023-07-26T13:49:32.732Z"),
	"logicalSessionTimeoutMinutes" : 30,
	"connectionId" : 46,
	"minWireVersion" : 0,
	"maxWireVersion" : 13,
	"readOnly" : false,
	"ok" : 1,
	"$clusterTime" : {
		"clusterTime" : Timestamp(1690379364, 1),
		"signature" : {
			"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
			"keyId" : NumberLong(0)
		}
	},
	"operationTime" : Timestamp(1690379364, 1)
}
删除节点
rs.remove("192.168.1.250:27017")

添加为仲裁节点,添加一直卡住,初始化时添加
rs.addArb("192.168.1.250:27017")

“arbiterOnly”: true 指定为仲裁节点

config = { _id: 'myrepl', members: [
 {_id: 0, host: '192.168.1.124:27017'},
 {_id: 1, host: '192.168.1.128:27017'} ,
 {_id: 2, host: '192.168.1.129:27017', "arbiterOnly": true}]
 }

二、使用filebeat收集tomcat日志到ES并利用kibana展示。

环境:dpkg 安装好es集群、kibana和filebeat
efk版本:8.9.0
系统: ubuntu20.04

IP软件
192.168.1.136elasticsearch
192.168.1.137elasticsearch
192.168.1.138elasticsearch
192.168.1.140kibana
192.168.1.141filebeat+tomcat

在这里插入图片描述

安装配置tomcat

#apt -y install tomcat9 tomcat9-admin

修改 Tomcat 的访问日志为Json格式,在tomcat配置文件中修改

vim /etc/tomcat9/server.xml

prefix="tomcat_access_log" suffix=".txt"
pattern="{&quot;clientip&quot;:&quot;%h&quot;,&quot;ClientUser&quot;:&quot;%l&quot;,&quot;authenticated&quot;:&quot;%u&quot;,&quot;AccessTime&quot;:&quot;%t&quot;,&quot;method&quot;:&quot;%r&quot;,&quot;status&quot;:&quot;%s&quot;,&quot;SendBytes&quot;:&quot;%b&quot;,&quot;Query?string&quot;:&quot;%q&quot;,&quot;partner&quot;:&quot;%{Referer}i&quot;,&quot;AgentVersion&quot;:&quot;%{User-Agent}i&quot;}"/>

配置filebeat

 cat filebeat.yml 
filebeat.inputs:
- type: log
  enabled: true
  paths:
    - /var/log/tomcat9/tomcat_access_log.*.txt
  json.keys_under_root: true #默认False会将json数据存储至message,改为true则会独立message外存储
  json.overwrite_keys: false  #设为true,覆盖默认的message字段,使用自定义json格式中的key
  tags: ["tomcat-access"]

- type: log
  enabled: true
  paths:
    - /var/log/tomcat9/catalina.*
  tags: ["tomcat-error"]
  multiline.type: pattern           #此为默认值,可省略
  multiline.pattern: '^[0-3][0-9]-'  #正则表达式匹配以两位,或为'^\d{2}'
  multiline.negate: true
  multiline.match: after
  multiline.maxlines: 10000  #默认只合并500行,指定最大合并1万行
  
output.elasticsearch:
  hosts: ["192.168.1.137:9200"]        #指定ELK集群服务器地址和端口
  indices:
    - index: "tomcat-access-%{[agent.version]}-%{+yyy.MM.dd}" 
      when.contains:
        tags: "tomcat-access"
    - index: "tomcat-error-%{[agent.version]}-%{+yyy.MM.dd}"
      when.contains:
        tags: "tomcat-error"
  
setup.ilm.enabled: false 
setup.template.name: "tomcat" 
setup.template.pattern: "tomcat-*"


kibana添加索引

通过插件查看新增索引
在这里插入图片描述http://192.168.1.140:5601/

访问kibana为tomcat-access 和tomcat-error创建数据视图
http://192.168.1.140:5601/
在这里插入图片描述

在Discover页面查看日志
在这里插入图片描述

收集 Tomat 的多行错误日志

添加

  multiline.type: pattern           #此为默认值,可省略
  multiline.pattern: '^[0-3][0-9]-'  #正则表达式匹配以两位,或为'^\d{2}'
  multiline.negate: true
  multiline.match: after
  multiline.maxlines: 10000  #默认只合并500行,指定最大合并1万行
 cat filebeat.yml 
filebeat.inputs:
- type: log
  enabled: true
  paths:
    - /var/log/tomcat9/tomcat_access_log.*.txt
  json.keys_under_root: true #默认False会将json数据存储至message,改为true则会独立message外存储
  json.overwrite_keys: false  #设为true,覆盖默认的message字段,使用自定义json格式中的key
  tags: ["tomcat-access"]

- type: log
  enabled: true
  paths:
    - /var/log/tomcat9/catalina.*
  tags: ["tomcat-error"]
  multiline.type: pattern           #此为默认值,可省略
  multiline.pattern: '^[0-3][0-9]-'  #正则表达式匹配以两位,或者为'^\d{2}'
  multiline.negate: true
  multiline.match: after
  multiline.maxlines: 10000  #默认只合并500行,指定最大合并1万行
  
output.elasticsearch:
  hosts: ["192.168.1.137:9200"]        #指定ELK集群服务器地址和端口
  indices:
    - index: "tomcat-access-%{[agent.version]}-%{+yyy.MM.dd}" 
      when.contains:
        tags: "tomcat-access"
    - index: "tomcat-error-%{[agent.version]}-%{+yyy.MM.dd}"
      when.contains:
        tags: "tomcat-error"
  
setup.ilm.enabled: false 
setup.template.name: "tomcat" 
setup.template.pattern: "tomcat-*"

需要点击按钮才能完整显示
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值