-
Notifications
You must be signed in to change notification settings - Fork 283
Expand file tree
/
Copy pathelastic.py
More file actions
189 lines (146 loc) · 5.88 KB
/
elastic.py
File metadata and controls
189 lines (146 loc) · 5.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
'''
@author: Sid Probstein
@contact: sid@swirl.today
'''
from sys import path
from os import environ
from datetime import datetime
import django
from swirl.utils import swirl_setdir
path.append(swirl_setdir()) # path to settings.py file
environ.setdefault('DJANGO_SETTINGS_MODULE', 'swirl_server.settings')
django.setup()
from celery.utils.log import get_task_logger
logger = get_task_logger(__name__)
from swirl.connectors.utils import bind_query_mappings
from swirl.connectors.verify_ssl_common import VerifyCertsCommon
from elasticsearch import Elasticsearch
from elasticsearch import *
import re
import ast
########################################
########################################
class Elastic(VerifyCertsCommon):
type = "Elastic"
def __init__(self, provider_id, search_id, update, request_id=''):
super().__init__(provider_id, search_id, update, request_id)
########################################
def construct_query(self):
logger.debug(f"{self}: construct_query()")
query_to_provider = bind_query_mappings(self.provider.query_template, self.provider.query_mappings)
if '{query_string}' in self.provider.query_template:
query_to_provider = query_to_provider.replace('{query_string}', self.query_string_to_provider)
sort_field = ""
if 'sort_by_date' in self.query_mappings:
sort_field = self.query_mappings['sort_by_date']
# end if
elastic_query = ""
if self.search.sort.lower() == 'date':
if sort_field:
# to do: support ascending??? p2
elastic_query = query_to_provider + f", sort=[{{f'{sort_field}': 'desc'}}], size=" + str(self.provider.results_per_query)
# endif
else:
elastic_query = query_to_provider + ', size=' + str(self.provider.results_per_query)
# end if
if elastic_query == "":
self.error(f"elastic_query unexpectedly blank")
self.query_to_provider = elastic_query
logger.debug(f"Constructed query_to_provider: {self.query_to_provider}")
return
def execute_search(self, size, session=None):
logger.debug(f"{self}: execute_search()")
auth = None
bearer = None
(username,password,verify_certs,ca_certs,bearer)=self.get_creds()
if self.status in ("ERR_INVALID_CREDENTIALS", "ERR_NO_CREDENTIALS"):
return
if bearer:
self.warning(f"bearer token specified but not supported")
auth = (username, password)
url = None
if self.provider.url:
if self.provider.url.startswith('hosts='):
url = self.provider.url.split('hosts=')[1][:]
if url.startswith("'"):
url = url[1:-1]
else:
url = self.provider.url
if not url:
self.status = "ERR_NO_URL"
return
try:
if verify_certs:
es = Elasticsearch(basic_auth=tuple(auth),hosts=url,verify_certs=verify_certs,ca_certs=ca_certs)
else:
if auth:
es = Elasticsearch(basic_auth=tuple(auth),hosts=url)
else:
es = Elasticsearch(hosts=url)
except NameError as err:
self.error(f'NameError: {err}')
except TypeError as err:
self.error(f'TypeError: {err}')
except Exception as err:
self.error(f"Exception: {err}")
# extract index (str)
index_name_pattern = r"index='([^']+)'"
match = re.search(index_name_pattern, self.query_to_provider)
if match:
index = match.group(1)
else:
self.status = "ERR_NO_INDEX_SPECIFIED"
return
# extract query (dict)
query_pattern = r"query=({.*})"
match = re.search(query_pattern, self.query_to_provider)
if match:
query_s = match.group(1)
query = ast.literal_eval(query_s)
else:
self.status = "ERR_NO_QUERY_SPECIFIED"
return
# Extract size (int) - Optional
size_pattern = r"size=(\d+)"
match = re.search(size_pattern, self.query_to_provider)
if match:
size = int(match.group(1))
else:
size = 10 # Default size if not specified
response = None
try:
response = es.search(index=index, query=query, size=size)
except ConnectionError as err:
self.error(f"es.search reports: {err}")
except NotFoundError:
self.error(f"es.search reports HTTP/404 (Not Found)")
except RequestError as err:
self.error(f"es.search reports Bad Request {err}")
except AuthenticationException:
self.error(f"es.search reports HTTP/401 (Forbidden)")
except AuthorizationException:
self.error(f"es.search reports HTTP/403 (Access Denied)")
except ApiError as err:
self.error(f"es.search reports '{err}'")
self.response = response
return
########################################
def normalize_response(self):
logger.debug(f"{self}: normalize_response()")
if len(self.response) == 0:
self.error("search succeeded, but found no json data in response")
if not 'hits' in self.response.keys():
self.error("search succeeded, but json data was missing key 'hits'")
found = self.response['hits']['total']['value']
self.found = found
if found == 0:
# no results, not an error
self.retrieved = 0
self.message(f"Retrieved 0 of 0 results from: {self.provider.name}")
self.status = 'READY'
return
results = self.response['hits']['hits']
self.results = results
retrieved = len(results)
self.retrieved = retrieved
return