#!/usr/bin/env python

# -*- coding: utf-8 -*-

from sfo_common.agent import Agent

from sfo_common.import_common import *

class ElkLog(object):

"""

处理ELK数据类

"""

def __init__(self):

pass

def get_elk_log_json(self):

"""

通过调用elasticsearch接口查询指定索引数据,计算集群的平均响应时间

:return:

"""

try:

day = time.strftime("%Y.%m.%d",time.localtime(time.time()))

clusters = config.elk_index_name.split(',')

if clusters:

for cluster in clusters:

index_name="{}-swift-proxy-{}".format(cluster,day)

req_url = '{}{}/_search?pretty'.format(config.elk_server_url,index_name)

headers = {'content-type': "application/json"}

l_time = datetime.datetime.now() + datetime.timedelta(minutes=-5)

now_time = util.local2utc(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'))

now_time_5m = util.local2utc(l_time.strftime('%Y-%m-%d %H:%M:%S.%f'))

body = {

"query": {

"bool":{

"must":{

"match_all":{}

},

"filter":{

"range":{

"@timestamp":{

"gte":now_time_5m,

"lte":now_time

}

}

}

}

},

"size": 10000,

"sort": {

"@timestamp": { "order": "asc" }

},

"_source": ["status", "method","client_ip","remote_ip","timestamp","request_time","@timestamp"]

}

#print req_url,body,headers

response = requests.post(req_url,data=json.dumps(body),headers=headers)

total_time=head_total_time=get_total_time=put_total_time=post_total_time=delete_total_time = 0.0

head_count=get_count=put_count=post_count=delete_count = 0

if response.status_code == 200:

tps = SfoClusterTps()

res_data = json.loads(response.text,encoding='UTF-8')

if res_data and res_data.has_key('hits'):

hits = res_data['hits']

total = hits['total']

list = hits['hits']

if list and total > 0:

for obj in list:

if isinstance(obj,dict) and obj.has_key('_source'):

source = obj['_source']

if source.has_key('request_time'):

total_time += float(source['request_time'])

if source.has_key('method') and str(source['method']).strip().upper()=='HEAD':

head_count += 1

if source.has_key('request_time'):

head_total_time += float(source['request_time'])

if source.has_key('method') and str(source['method']).strip().upper()=='GET':

get_count += 1

if source.has_key('request_time'):

get_total_time += float(source['request_time'])

if source.has_key('method') and str(source['method']).strip().upper()=='PUT':

put_count += 1

if source.has_key('request_time'):

put_total_time += float(source['request_time'])

if source.has_key('method') and str(source['method']).strip().upper()=='POST':

post_count += 1

if source.has_key('request_time'):

post_total_time += float(source['request_time'])

if source.has_key('method') and str(source['method']).strip().upper()=='DELETE':

delete_count += 1

if source.has_key('request_time'):

delete_total_time += float(source['request_time'])

tps.guid = str(uuid.uuid1())

tps.cluster_name = cluster

if total > 0:

tps.avg_time = '%.2f'%(total_time/total*1000)

else:

tps.avg_time = 0

if head_count > 0:

tps.head_time = '%.2f'%(head_total_time/head_count*1000)

else:

tps.head_time = 0

if get_count > 0:

tps.get_time = '%.2f'%(get_total_time/get_count*1000)

else:

tps.get_time = 0

if put_count > 0:

tps.put_time = '%.2f'%(put_total_time/put_count*1000)

else:

tps.put_time = 0

if post_count > 0:

tps.post_time = '%.2f'%(post_total_time/post_count*1000)

else:

tps.post_time = 0

if delete_count > 0:

tps.delete_time = '%.2f'%(delete_total_time/delete_count*1000)

else:

tps.delete_time = 0

tps.add_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))

db.session.add(tps)

db.session.commit()

else:

pass

else:

pass

else:

pass

except Exception as ex:

logger.exception("get_elk_log_json function execute exception:" + str(ex))

finally:

db.session.close()

db.session.remove()

#schedule tasks

def get_elklog_json_schl(executor):

"""

起线程执行日志分析

:param executor:

:return:

"""

try:

el = ElkLog()

executor.submit(el.get_elk_log_json)

#threading.Thread(target=el.get_elk_log_json).start()

except Exception as ex:

logger.exception("get_elklog_json_schl function execute exception:" + str(ex))

class ElklogUnitAgnet(Agent):

def __init__(self, pidfile):

Agent.__init__(self, pidfile)

def run(self):

try:

sys.stdout.flush()

hostname = socket.getfqdn()

hostip = socket.gethostbyname(hostname)

logger.info("hostname is {}, ip is {}".format(hostname, hostip))

#use schedule

with ThreadPoolExecutor(config.thread_workers) as executor:

schedule.every(config.upload_refresh).seconds.do(get_elklog_json_schl,executor)

schedule.run_all(0)

while True:

schedule.run_pending()

time.sleep(0.1)

except Exception as ex:

logger.exception("elk log agent run exception:" + str(ex))

def main():

agent = ElklogUnitAgnet(config.elklog_agnet_pfile)

try:

if len(sys.argv) == 3:

if 'elklog' == sys.argv[1]:

if 'start' == sys.argv[2]:

agent.start()

if 'stop' == sys.argv[2]:

agent.stop()

else:

print("Unknown command")

sys.exit(2)

else:

print("usage: %s" % (sys.argv[0],))

sys.exit(2)

except Exception as ex:

logger.exception("elk log process run exception:" + str(ex))

if __name__ == '__main__':

main()

###########################################################################################

更多查询方式接口:

查询一条记录

curl -H "Content-Type: application/json" -X POST 'http://192.168.1.1:9200/swift-nginx-2018.08.31/_search?pretty' -d '{"query": { "match_all": {} },"size": 1}'

查询offset为20的记录

curl -H "Content-Type: application/json" -X POST 'http://192.168.1.1:9200/swift-nginx-2018.08.31/_search?pretty' -d '{"query": { "match": { "offset": 20 } }}'

查询结果只返回指定的字段

curl -H "Content-Type: application/json" -X POST 'http://192.168.1.1:9200/swift-nginx-2018.08.31/_search?pretty' -d '{"query": { "match_all": {} },"_source": ["host", "message"]}'

查询结果排序

curl -H "Content-Type: application/json" -X POST 'http://192.168.1.1:9200/swift-nginx-2018.08.31/_search?pretty' -d '{"query": { "match_all": {} },"_source": ["offset","host", "message"]},"sort": { "offset": { "order": "desc" } }'

返回从10开始的10条记录

curl -H "Content-Type: application/json" -X POST 'http://192.168.1.1:9200/swift-nginx-2018.08.31/_search?pretty' -d '{"query": { "match_all": {} },"from": 10,"size": 10,"_source": ["offset","host", "message"]},"sort": { "offset": { "order": "desc" } }'

集群健康状态查询:

curl '192.168.1.1:9200/_cat/health?v'

查询索引列表:

curl '192.168.1.1:9200/_cat/indices?v'

查询集群节点列表:

curl '192.168.1.1:9200/_cat/nodes?v'

创建索引:

curl -XPUT '192.168.1.1:9200/test-index?pretty'

注意:索引名中不能使用大写,否则会报错:

Could not index event to Elasticsearch.     "reason"=>"Invalid index name [iTech-swift-proxy-2018.11.08], must be lowercase",

删除索引:

curl -XDELETE '192.168.1.1:9200/test-index?pretty'

向索引中插入数据:

curl -XPUT '192.168.1.1:9200/test-index/<_type>/<_id>?pretty' -d '{"name": "test name"}'

获取插入的数据:

curl -XGET '192.168.1.1:9200/test-index/<_type>/<_id>?pretty'

(<_type>和<_id>用实际需要插入的属性名和id值替换)

更新数据:

curl -XPOST '192.168.1.1:9200/test-index/<_type>/<_id>/_update?pretty' -d '{"doc": { "name": "test2 Name" }}'

删除数据:

curl -XDELETE '192.168.1.1:9200/test-index/<_type>/<_id>?pretty'

查询数据:

curl -XPOST '192.168.1.1:9200/test-index/_search?pretty' -d '{"query": { "match_all": {} }}'

如果有一台elasticsearch磁盘空间不足,将会导致index变成readonly状态,此时扩容后需要用以下命令修改其状态,恢复正常:

curl -XPUT -H "Content-Type: application/json" http://10.202.233.78:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'

全部查询接口实例请参考:

https://www.cnblogs.com/pilihaotian/p/5830754.html

pythonsearch结果_python 查询Elasticsearch的小例子相关推荐

  1. python elasticsearch查询_python 查询Elasticsearch的小例子

    #!/usr/bin/env python # -*- coding: utf-8 -*- from sfo_common.agent import Agent from sfo_common.imp ...

  2. python装饰设备_Python: 装饰器的小例子

    折腾了一天的装饰器,貌似理解了其中的一点点...#!/usr/bin/env python3 #coding=utf-8 import getpass from netmiko import Conn ...

  3. c/c++ 继承与多态 文本查询的小例子(非智能指针版本)

    问题:在上一篇继承与多态 文本查询的小例子(智能指针版本)在Query类里使用的是智能指针,只把智能指针换成普通的指针,并不添加拷贝构造方法,会发生什么呢? 执行时,代码崩掉. 分析下面一行代码: Q ...

  4. python 真多线程_Python之路200个小例子,在线网页版来了,从此学习更方便!

    历史两个月,利用所有业余时间,与朋友一起搜集.创作Python小例子,截止目前已超过200个例子,全新整合汇总为九大章节: 感受Python之美 | 一.Python基础 | 二.Python字符串和 ...

  5. 有趣的python代码实例_Python之路:200个Python有趣的小例子一网打尽

    概述 博主最近在学习python,看完了一整套学习视频,然后呃呃呃,还是用不太流畅.碰巧在全球最大的 同性交友论坛GayHub(呸!是开源代码托管平台Github)上面发现了一个项目,该项目列举了20 ...

  6. python operator 多属性排序_Python之路200个小例子网页版,真诚奉献,从一而终!...

    历史两个月,利用所有业余时间,与朋友一起搜集.创作Python小例子,截止目前已超过200个例子,全新整合汇总为九大章节: 感受Python之美 | 一.Python基础 | 二.Python字符串和 ...

  7. Flask+Axios+jQuery构建前后端通信的小例子

    比较暴力但好理解的方法,下面详细说一下. 工具准备 Flask pip install flask Axios https://cdnjs.cloudflare.com/ajax/libs/axios ...

  8. pyqt5菜鸟教程_PyQt5系列教程(61):PyQt5与数据库互联的小例子1

    今天我们一起来学习一下如何使用PyQt5与数据进行互联.当然如果你觉得使用PyQt5与数据库互联很麻烦,你也可以使用Python第三方库进行数据互联,达到你的目的就行了. 本次数据的数据库,我们选择的 ...

  9. python迭代举例_大神总结223个Python小例子,建议收藏

    元素都为真 接受一个可迭代对象,如果可迭代对象的所有元素都为真,那么返回 True,否则返回False 元素至少一个为真 接受一个可迭代对象,如果可迭代对象里至少有一个元素为真,那么返回True,否则 ...

最新文章

  1. 中文文本中的关键字提取算法总结
  2. WebKit与event.layerX和event.layerY有关的问题
  3. ----------------------过滤器filter简单登录和乱码过滤----
  4. docker之数据卷管理
  5. 创客运动引发第三次工业革命
  6. XmlPullParser
  7. CodeForces - 888C K-Dominant Character 思维
  8. 实用juniper SRX NAT小技巧。
  9. linux配置ARP内核参数,详细讲解linux内核参数arp_announce和arp_ignore
  10. Spring MVC访问页面拦截js和css文件解决方法( No mapping found for HTTP request with URI [/Recruit/js/popper1.15.0.)
  11. hdu 6092 Rikka with Subset 01背包 思维
  12. 操作文件和目录【TLCL】
  13. 驱动lx4f120h,头文件配置,没有完全吃透,望指点
  14. httpclient架构原理介绍 连接池详解
  15. Delphi XE 操作sqlite数据库
  16. 离散数学 习题篇 —— 最小生成树
  17. [项目管理-6]:软硬件项目管理 - 项目沟通管理(渠道、方法)
  18. 病毒分析与防护实验3—— 反汇编工具(Ollydbg)的使用
  19. Mint-ui MessageBox.confirm 确定和取消事件
  20. Laurent(洛朗或者劳伦)多项式,泰勒展开式

热门文章

  1. QT学习笔记(十三):绘制图像
  2. QT安装和Hello,world
  3. Spring Data JPA 从入门到精通~方法的查询策略设置
  4. Change Unidirectional Association to Bidirectional(将单向关联改为双向关联)
  5. 外设驱动库开发笔记9:SHT1x系列温湿度传感器驱动
  6. React Native使用指南-在设备上运行
  7. sed 删除某一行_Linux常用命令三剑客之sed,您真的会用吗?
  8. 无限超越超级机器人nds_阿里重新定义个人电脑!仅名片大小,无限升级,不怕丢失无惧病毒,价格仅传统PC一半...
  9. table表头固定4种方法_在常见的3种工资条场景中,教你4种批量打印工资条的方法...
  10. JAVA入门级教学之(异常的处理try...catch)