Skip to content

Commit

Permalink
Merge pull request #50 from nagypeterjob/peter-nagy-es-plugin-python3
Browse files Browse the repository at this point in the history
feat(es): make elasticsearch plugin work with python3
  • Loading branch information
vfuse authored Nov 29, 2021
2 parents c451de3 + b648c19 commit 9516e74
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions nixstatsagent/plugins/elasticsearch.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib.request
try:
from urllib.parse import urlparse, urlencode
from urllib.request import urlopen, Request
Expand All @@ -12,7 +13,7 @@
import plugins
import json
import collections

import base64

class Plugin(plugins.BasePlugin):
__name__ = 'elasticsearch'
Expand All @@ -24,6 +25,10 @@ def run(self, config):
[elasticsearch]
enabled = yes
status_page_url = http://127.0.0.1:9200/_stats
# In case basic_auth is needed:
basic_auth = yes
username = <username>
password = <password>
'''

def ascii_encode_dict(data):
Expand All @@ -32,8 +37,14 @@ def ascii_encode_dict(data):

results = dict()
next_cache = dict()
request = urllib2.Request(config.get('elasticsearch', 'status_page_url'))
raw_response = urllib2.urlopen(request)
request = urllib.request.Request(config.get('elasticsearch', 'status_page_url'))
basic_auth_enabled = config.get('elasticsearch', 'basic_auth')
if bool(basic_auth_enabled):
user = config.get('elasticsearch', 'username')
password = config.get('elasticsearch', 'password')
b64auth = base64.b64encode(bytes("%s:%s" % (user, password), 'ascii'))
request.add_header("Authorization", "Basic %s" % b64auth.decode('utf-8'))
raw_response = urllib.request.urlopen(request)
next_cache['ts'] = time.time()
prev_cache = self.get_agent_cache() # Get absolute values from previous check
def flatten(d, parent_key='', sep='_'):
Expand All @@ -46,7 +57,7 @@ def flatten(d, parent_key='', sep='_'):
items.append((new_key, v))
return dict(items)
try:
j = flatten(json.loads(raw_response.read(), object_hook=ascii_encode_dict)['_all']['total'])
j = flatten(json.loads(raw_response.read())['_all']['total'])
except Exception:
return False

Expand Down

0 comments on commit 9516e74

Please sign in to comment.