Skip to content

Commit c062f3b

Browse files
committed
0.3.0a5 fix index creation ES 5.x
1 parent ba3d5c9 commit c062f3b

File tree

7 files changed

+107
-74
lines changed

7 files changed

+107
-74
lines changed

CHANGES.rst

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,15 @@
11
Changelog
22
=========
33

4+
0.3.0a5
5+
-------
6+
7+
- Fix issue with index creation on ElasticSearch 5.x.
8+
9+
Thanks to Kristoffer Olsson and Daniel Lindberg for reporting this and for their extensive support.
10+
11+
- Improved template for index creation.
12+
413
0.3.0a4
514
-------
615

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
{
2+
"mappings": {
3+
"_default_": {
4+
"_all" : { "enabled" : false },
5+
6+
"_source" : { "enabled" : true },
7+
8+
"dynamic_templates": [
9+
{
10+
"string_template" : {
11+
"match" : "*",
12+
"match_mapping_type" : "string",
13+
"mapping": { "type": "string", "index": "not_analyzed" }
14+
}
15+
}
16+
],
17+
18+
"properties": {
19+
"@timestamp": { "type": "date" },
20+
"bytes": { "type": "long" },
21+
"packets": { "type": "long" },
22+
"flows": { "type": "long" }
23+
}
24+
}
25+
}
26+
}

distrib/new-index-template.json

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,26 @@
11
{
2-
"mappings": {
3-
"_default_": {
4-
"_all" : { "enabled" : false },
2+
"mappings": {
3+
"_default_": {
4+
"_all" : { "enabled" : false },
55

6-
"_source" : { "enabled" : true },
6+
"_source" : { "enabled" : true },
77

8-
"dynamic_templates": [
9-
{
10-
"string_template" : {
11-
"match" : "*",
12-
"match_mapping_type" : "string",
13-
"mapping": { "type": "string", "index": "not_analyzed" }
14-
}
15-
}
16-
],
8+
"dynamic_templates": [
9+
{
10+
"string_template" : {
11+
"match" : "*",
12+
"match_mapping_type" : "string",
13+
"mapping": { "type": "keyword", "index": true }
14+
}
15+
}
16+
],
1717

18-
"properties": {
19-
"@timestamp": { "type": "date" },
20-
"bytes": { "type": "long" },
21-
"packets": { "type": "long" },
22-
"flows": { "type": "long" }
23-
}
24-
}
25-
}
18+
"properties": {
19+
"@timestamp": { "type": "date" },
20+
"bytes": { "type": "long" },
21+
"packets": { "type": "long" },
22+
"flows": { "type": "long" }
23+
}
24+
}
25+
}
2626
}

pierky/p2es/es.py

Lines changed: 49 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,36 @@
22
# See full license in LICENSE file.
33

44
import json
5-
import urllib2
5+
import requests
6+
from requests.auth import HTTPDigestAuth, HTTPBasicAuth
67

78
from errors import P2ESError
89

10+
def http(CONFIG, url, method="GET", data=None):
11+
auth = None
12+
if CONFIG['ES_AuthType'] != 'none':
13+
if CONFIG['ES_AuthType'] == 'basic':
14+
auth = HTTPBasicAuth(CONFIG['ES_UserName'], CONFIG['ES_Password'])
15+
elif CONFIG['ES_AuthType'] == 'digest':
16+
auth = HTTPDigestAuth(CONFIG['ES_UserName'], CONFIG['ES_Password'])
17+
else:
18+
raise P2ESError(
19+
'Unexpected authentication type: {}'.format(CONFIG['ES_AuthType'])
20+
)
21+
22+
headers = {'Content-Type': 'application/x-ndjson'}
23+
24+
if method == "GET":
25+
return requests.get(url, auth=auth, headers=headers)
26+
elif method == "POST":
27+
return requests.post(url, auth=auth, data=data, headers=headers)
28+
elif method == "PUT":
29+
return requests.put(url, auth=auth, data=data, headers=headers)
30+
elif method == "HEAD":
31+
return requests.head(url, auth=auth, headers=headers)
32+
else:
33+
raise Exception("Method unknown: {}".format(method))
34+
935
# Sends data to ES.
1036
# Raises exceptions: yes.
1137
def send_to_es(CONFIG, index_name, data):
@@ -18,7 +44,7 @@ def send_to_es(CONFIG, index_name, data):
1844
)
1945

2046
try:
21-
http_res = urllib2.urlopen(url, data)
47+
http_res = http(CONFIG, url, method="POST", data=data)
2248
except Exception as e:
2349
raise P2ESError(
2450
'Error while executing HTTP bulk insert on {} - {}'.format(
@@ -27,27 +53,24 @@ def send_to_es(CONFIG, index_name, data):
2753
)
2854

2955
# Interpreting HTTP bulk insert response
30-
31-
http_plaintext = http_res.read()
32-
33-
if(http_res.getcode() != 200):
56+
if http_res.status_code != 200:
3457
raise P2ESError(
3558
'Bulk insert on {} failed - '
3659
'HTTP status code = {} - '
3760
'Response {}'.format(
38-
index_name, http_res.getcode(), http_plaintext
61+
index_name, http_res.status_code, http_res.text
3962
)
4063
)
4164

4265
try:
43-
json_res = json.loads(http_plaintext)
66+
json_res = http_res.json()
4467
except Exception as e:
4568
raise P2ESError(
4669
'Error while decoding JSON HTTP response - '
4770
'{} - '
4871
'first 100 characters: {}'.format(
4972
str(e),
50-
http_plaintext[:100],
73+
http_res.text[:100],
5174
)
5275
)
5376

@@ -64,27 +87,19 @@ def does_index_exist(index_name, CONFIG):
6487
url = '{}/{}'.format(CONFIG['ES_URL'], index_name)
6588

6689
try:
67-
head_req = urllib2.Request(url)
68-
head_req.get_method = lambda : 'HEAD'
69-
http_res = urllib2.urlopen(head_req)
70-
return http_res.getcode() == 200
71-
except urllib2.HTTPError as err:
72-
if err.code == 404:
90+
status_code = http(CONFIG, url, method="HEAD").status_code
91+
if status_code == 200:
92+
return True
93+
if status_code == 404:
7394
return False
74-
else:
75-
raise P2ESError(
76-
'Error while checking if {} index exists: {}'.format(
77-
index_name, str(err)
78-
)
79-
)
95+
raise Exception("Unexpected status code: {}".format(status_code))
8096
except Exception as err:
8197
raise P2ESError(
8298
'Error while checking if {} index exists: {}'.format(
8399
index_name, str(err)
84100
)
85101
)
86102

87-
88103
# Creates index 'index_name' using template given in config.
89104
# Raises exceptions: yes.
90105
def create_index(index_name, CONFIG):
@@ -110,11 +125,18 @@ def create_index(index_name, CONFIG):
110125

111126
last_err = None
112127
try:
113-
http_res = urllib2.urlopen(url, tpl)
114-
except Exception as e:
115-
# something went wrong: does index exist anyway?
116-
last_err = str(e)
117-
pass
128+
# using PUT
129+
http_res = http(CONFIG, url, method="PUT", data=tpl)
130+
except Exception as e1:
131+
last_err = "Error using PUT method: {}".format(str(e1))
132+
# trying the old way
133+
try:
134+
http_res = http(CONFIG, url, method="POST", data=tpl)
135+
except Exception as e2:
136+
# something went wrong: does index exist anyway?
137+
last_err += " - "
138+
last_err += "Error using old way: {}".format(str(e2))
139+
pass
118140

119141
try:
120142
if does_index_exist(index_name, CONFIG):
@@ -128,25 +150,3 @@ def create_index(index_name, CONFIG):
128150
else:
129151
err += "error unknown"
130152
raise P2ESError(err.format(index_name, tpl_path))
131-
132-
def prepare_for_http_auth(CONFIG):
133-
if CONFIG['ES_AuthType'] != 'none':
134-
pwdman = urllib2.HTTPPasswordMgrWithDefaultRealm()
135-
pwdman.add_password(
136-
None,
137-
CONFIG['ES_URL'],
138-
CONFIG['ES_UserName'],
139-
CONFIG['ES_Password']
140-
)
141-
142-
if CONFIG['ES_AuthType'] == 'basic':
143-
auth_handler = urllib2.HTTPBasicAuthHandler(pwdman)
144-
elif CONFIG['ES_AuthType'] == 'digest':
145-
auth_handler = urllib2.HTTPDigestAuthHandler(pwdman)
146-
else:
147-
raise P2ESError(
148-
'Unexpected authentication type: {}'.format(CONFIG['ES_AuthType'])
149-
)
150-
151-
opener = urllib2.build_opener(auth_handler)
152-
urllib2.install_opener(opener)

pierky/p2es/version.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
# This code is Copyright 2014-2017 by Pier Carlo Chiodi.
22
# See full license in LICENSE file.
33

4-
__version__ = "0.3.0a4"
4+
__version__ = "0.3.0a5"

pierky/p2es/writers.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -66,9 +66,6 @@ class ESWriterThread(BaseWriterThread):
6666
def __init__(self, *args, **kwargs):
6767
BaseWriterThread.__init__(self, *args, **kwargs)
6868

69-
# Preparing for HTTP authentication
70-
prepare_for_http_auth(self.CONFIG)
71-
7269
# Creating index
7370
self.index_name = datetime.datetime.now().strftime(
7471
self.CONFIG['ES_IndexName']

setup.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@
5353
maintainer_email="[email protected]",
5454

5555
install_requires=[
56+
"requests"
5657
],
5758

5859
scripts=["scripts/pmacct-to-elasticsearch"],

0 commit comments

Comments
 (0)