Created
July 8, 2019 23:52
-
-
Save arslanm/4c10d7587012258fde5c8d0fffddc918 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python2.7 | |
# | |
# This script cancels long running searches on Elasticsearch. | |
# Tested on 5.6 but should work with all versions above 5.1 (which introduced Task API). | |
# Search task duration in seconds to be cancelled | |
LIMIT = 30 | |
# Timeout for cancel requests in seconds | |
TIMEOUT = 5 | |
import urllib, requests, json | |
url = "http://localhost:9200/_tasks" | |
def cancel(id): | |
print "cancelling", id | |
try: | |
r = requests.post("%s/%s/_cancel" % (url, id), timeout=TIMEOUT) | |
if r.status_code == "200": print "ok" | |
else: print r.status_code | |
except requests.exceptions.RequestException as e: | |
print "error:", e | |
response = urllib.urlopen(url) | |
data = json.loads(response.read()) | |
nodes = data['nodes'] | |
for node in nodes: | |
nodetasks = nodes[node]['tasks'] | |
for nodetask_id in nodetasks: | |
task = nodetasks[nodetask_id] | |
action = task['action'] | |
if action[0:24] != "indices:data/read/search" \ | |
and action[0:25] != "indices:data/read/msearch": | |
continue | |
duration = task['running_time_in_nanos'] / 1000000000 | |
if duration < LIMIT: | |
continue | |
cancel(nodetask_id) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment