/
index_ops.py
178 lines (138 loc) · 5.86 KB
/
index_ops.py
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
#! /usr/bin/python
import arrow
import click
import requests
from datetime import date, timedelta
import logging
from humanize import intword, naturalsize
log = logging.getLogger("Console")
log.setLevel(logging.DEBUG)
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
log.addHandler(console)
ES_INDEX_URL = "http://localhost:9200/{}?pretty"
ES_INDEX_STATS_URL = "http://localhost:9200/{}/_stats"
INDEX_NAME_PATTERN = "logstash-{}"
MARVEL_NAME_PATTERN = ".marvel-{}"
class Index(object):
name = None
def __init__(self, date=None, marvel=False):
self.name = INDEX_NAME_PATTERN.format(date.isoformat().replace("-", "."))
if marvel:
self.name = MARVEL_NAME_PATTERN.format(date.isoformat().replace("-", "."))
self._date = date
self._exists = None
self._url = None
self._deleted = False
self._stats = None
# log.debug("Index Name: {}".format(self.name))
def exists(self):
self._url = ES_INDEX_URL.format(self.name)
try:
resp = requests.head(self._url)
self._exists = resp.ok
except:
log.exception("Exception while checking if Index exists. INDEX: {}".format(self.name))
self._exists = False
return self._exists
def delete(self):
if self._exists is None:
self.exists()
if self._exists and self._url:
try:
resp = requests.delete(self._url)
if resp.ok and resp.json() and resp.json().get('acknowledged') is True:
log.info("Deleting Index: [{}] -> Resp: {}".format(self.name, resp.json()))
self._deleted = True
else:
log.error("Error while deleting. Index:{}, Code: {}, Msg: {}".format(self.name, resp.status_code, resp.content))
except:
log.exception("Exception while deleting Index. Index: {}".format(self.name))
return self._deleted
def show_stats(self):
url = ES_INDEX_STATS_URL.format(self.name)
if self._exists is None:
self.exists()
if self._exists:
try:
resp = requests.get(url)
if resp.ok and resp.json():
self._stats = {
'index': self.name,
'docs_count': resp.json().get('indices').get(self.name).get('total').get('docs').get('count'),
'docs_size': resp.json().get('indices').get(self.name).get('total').get('store').get('size_in_bytes')
}
log.info("Index Stats: [{}]. Docs: {}, Size: {}".format(self.name, intword(self._stats['docs_count']),
naturalsize(self._stats['docs_size'])))
else:
log.error("Error while fetching stats. Index:{}, Code: {}, Msg: {}".format(self.name, resp.status_code, resp.content))
except:
log.exception("Exception while fetching stats. Index: {}".format(self.name))
return self._stats
@click.group()
def cli():
pass
@cli.command()
@click.argument("start")
@click.argument("end")
@click.option("--marvel", is_flag=True)
def stats(start, end, marvel=False):
try:
start_date = arrow.get(start, "YYYY-MM-DD")
end_date = arrow.get(end, "YYYY-MM-DD")
cur_date = start_date
days = 0
found = 0
total_docs = 0
total_size = 0
while cur_date.date() != end_date.date():
index = Index(cur_date.date(), marvel=marvel)
if index.exists():
found += 1
result = index.show_stats()
total_docs += result['docs_count']
total_size += result['docs_size']
days += 1
cur_date = cur_date.replace(days=+1)
click.echo("Details regarding Indices from [{}] -> [{}]".format(start_date.format("MMM DD, YYYY"), end_date.format("MMM DD, YYYY")))
click.echo("Found {} Indices, in {} days".format(found, days))
click.echo("Total Docs Found: {}".format(intword(total_docs)))
click.echo("Total Size estimated: {}".format(naturalsize(total_size)))
except arrow.parser.ParserError:
log.error("Exception while parsing Start/End dates")
click.echo("Start/End dates in Incorrect format! Please enter Dates in ISO-Format: YYYY-MM-DD")
@cli.command()
@click.argument("start")
@click.argument("end")
@click.option("--marvel", is_flag=True)
def delete(start, end, marvel=False):
try:
start_date = arrow.get(start, "YYYY-MM-DD")
end_date = arrow.get(end, "YYYY-MM-DD")
cur_date = start_date
days = 0
found = 0
total_docs = 0
total_size = 0
while cur_date.date() != end_date.date():
index = Index(cur_date.date(), marvel=marvel)
if index.exists():
found += 1
result = index.show_stats()
total_docs += result['docs_count']
total_size += result['docs_size']
index.delete()
days += 1
cur_date = cur_date.replace(days=+1)
click.echo("Details regarding Indices from [{}] -> [{}]".format(start_date.format("MMM DD, YYYY"), end_date.format("MMM DD, YYYY")))
click.echo("Found {} Indices, in {} days".format(found, days))
click.echo("Total Docs deleted: {}".format(intword(total_docs)))
click.echo("Total Size freed: {}".format(naturalsize(total_size)))
except arrow.parser.ParserError:
log.error("Exception while parsing Start/End dates")
click.echo("Start/End dates in Incorrect format! Please enter Dates in ISO-Format: YYYY-MM-DD")
if __name__ == '__main__':
try:
cli()
except KeyboardInterrupt:
print "Quitting application..."