2020-07-08 12:15:47 +00:00
|
|
|
import hashlib
|
|
|
|
from elasticsearch import Elasticsearch
|
|
|
|
|
2020-07-08 12:57:48 +00:00
|
|
|
|
2020-07-08 12:15:47 +00:00
|
|
|
def remove_prefix(text, prefix):
|
|
|
|
return text[text.startswith(prefix) and len(prefix):]
|
|
|
|
|
2020-07-08 12:57:48 +00:00
|
|
|
|
2020-07-08 12:15:47 +00:00
|
|
|
def hash_string(text):
|
|
|
|
return hashlib.sha256(text.encode('utf-8')).hexdigest()
|
|
|
|
|
|
|
|
|
2020-07-08 12:57:48 +00:00
|
|
|
class ESQueryPeers():
|
2020-07-08 12:15:47 +00:00
|
|
|
def __init__(self, host='localhost', port=9200, timeout=1200):
|
2020-07-08 12:57:48 +00:00
|
|
|
self.client = Elasticsearch([{
|
|
|
|
'host': host,
|
|
|
|
'port': port,
|
|
|
|
}],
|
|
|
|
timeout=timeout,
|
|
|
|
retry_on_timeout=True)
|
2020-07-08 12:15:47 +00:00
|
|
|
self.cluster = self.client.info().get('cluster_name')
|
2020-07-08 12:57:48 +00:00
|
|
|
|
2020-07-08 12:15:47 +00:00
|
|
|
def get_indices(self, pattern='logstash-*'):
|
|
|
|
return self.client.indices.get(index=pattern).keys()
|
|
|
|
|
2020-07-15 18:00:40 +00:00
|
|
|
def get_peers(self, index, field='peer_id', fleet='eth.prod', max_query=100000):
|
2020-07-08 12:15:47 +00:00
|
|
|
body = {
|
2020-07-08 12:57:48 +00:00
|
|
|
'size': 0, # Don't return actual values
|
2020-07-08 12:15:47 +00:00
|
|
|
'aggs': { 'peers': {
|
2020-07-15 18:00:40 +00:00
|
|
|
'filter': {
|
|
|
|
'term': { 'fleet': fleet },
|
|
|
|
},
|
|
|
|
'aggs': {
|
|
|
|
'fpeers': { 'terms': { 'field': field, 'size': max_query, }, },
|
2020-07-08 12:15:47 +00:00
|
|
|
},
|
|
|
|
}, },
|
|
|
|
}
|
|
|
|
# Query
|
|
|
|
resp = self.client.search(index=index, body=body)
|
|
|
|
aggs = resp.get('aggregations')
|
|
|
|
|
|
|
|
# Collect results as list of dicts
|
|
|
|
rval = []
|
2020-07-15 18:00:40 +00:00
|
|
|
for bucket in aggs['peers']['fpeers']['buckets']:
|
2020-07-08 12:15:47 +00:00
|
|
|
rval.append({
|
|
|
|
'Date': remove_prefix(index, 'logstash-'),
|
|
|
|
'Peer': hash_string(bucket['key']),
|
|
|
|
'Count': bucket['doc_count'],
|
|
|
|
})
|
|
|
|
|
|
|
|
return rval
|