forked from OsamaMahmood/OpenSearch-Snapshots-S3-Repo
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathopensearch-s3.py
377 lines (314 loc) · 13 KB
/
opensearch-s3.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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
#!/usr/bin/env python
import requests, json, argparse, os
from requests.exceptions import HTTPError
from colorama import Style,Fore
from datetime import datetime
# The following line is responsible for suppressing the SSL Cert warning.
requests.packages.urllib3.disable_warnings()
def start():
print('''
Creating OpenSearch Snapshots on AWS S3 for Backup.
Author: OsamaMahmood - ( https://github.com/OsamaMahmood )
''')
parser = argparse.ArgumentParser(description='Script Creating and Restoring OpenSearch Snapshots on AWS S3 for Backup.')
parser.add_argument('--host',
help = 'Opensearch Host',
type = str,
required=True)
parser.add_argument('--testcon',
help = 'To test connection to Opensearch RestAPI',
action = 'store_true')
parser.add_argument('--indices',
help = 'Name of indices to be backedup Ex: indice1,indice2-*,..',
type = str)
parser.add_argument('--s3repo',
help = 'S3 Snapshot Repository Name',
type = str)
parser.add_argument('--snap',
help = 'Name of snapshot you want to create',
type = str)
parser.add_argument('--auth',
help = 'Basic HTTP Auth Token',
type = str)
parser.add_argument('--action',
help = 'List of actions register repo, take snapshot, get snapshot status, restore them.',
choices = ('registerrepo', 'takesnap', 'status', 'restore', 'restoreindice', 'listsnaps', 'listrepos', 'listindices', 'deleterepo', 'deletesnap', 'deleteindice'))
args = parser.parse_args()
host = args.host
s3repo = args.s3repo
indices = args.indices
snapname = args.snap
# Get environment variables
if args.auth:
authtoken = args.auth
else:
authtoken = os.environ.get('authtoken')
# Global variables
url = 'https://'+host+':9200/_snapshot/'
headers = {'content-type': 'application/json', 'Authorization': 'Basic '+authtoken}
def testconn(_host_):
'''
Simple Function to check if the Opensearch host is live and accessable.
Args:
_host_ (string): IP or hostname of the server.
'''
try:
url = 'https://'+host+':9200/'
response = requests.get(url, headers=headers, verify=False)
response.raise_for_status()
except HTTPError as http_err:
print(f'HTTP error: {http_err}')
except Exception as err:
print(f'Other error: {err}')
else:
print(Fore.GREEN + 'Connection to Opensearch Successful!!')
json_object = json.loads(response.content)
print('Name: ' +json_object['name'])
print('Cluster Name: ' +json_object['cluster_name'])
print('Version: ' +json_object['version']['number']+Style.RESET_ALL)
def listrepos():
'''
Function to list all snapshot repositories
'''
print ('[+] {}'.format('List of Snapshot Repositories'))
try:
response = requests.get(url, headers=headers, verify=False)
response.raise_for_status()
except HTTPError as http_err:
print(f'HTTP error: {http_err}')
except Exception as err:
print(f'Other error: {err}')
else:
print(response)
json_object = json.loads(response.content)
print(Fore.GREEN +json.dumps(json_object, indent = 1)+Style.RESET_ALL)
def listsnaps(_s3repo_):
'''
Function to list all snapshots in a repositoriey
'''
print ('[+] {}'.format('List of Snapshot Repositories'))
try:
response = requests.get(url+_s3repo_+'/_all', headers=headers, verify=False)
response.raise_for_status()
except HTTPError as http_err:
print(f'HTTP error: {http_err}')
except Exception as err:
print(f'Other error: {err}')
else:
print(response)
json_object = json.loads(response.content)
print(Fore.GREEN +json.dumps(json_object, indent = 1)+Style.RESET_ALL)
def listindices(_host_):
'''
Function to list all opensearch indices
'''
print ('[+] {}'.format('List of indices'))
try:
url = 'https://'+host+':9200/_cat/indices'
response = requests.get(url, headers=headers, verify=False)
response.raise_for_status()
except HTTPError as http_err:
print(f'HTTP error: {http_err}')
except Exception as err:
print(f'Other error: {err}')
else:
print(response)
print(Fore.GREEN +response.content.decode('utf-8')+Style.RESET_ALL)
def registerrepo(_reponame_):
'''Register S3 Repo for snapshots using the Opensearch RestAPI
Args:
_reponame_ (string): Name of the snapshot repo this should be same as S3 bucket name for easier managment.
Returns:
If the snapshot repo does not exist it will create the repo.
'''
print ('[+] {}'.format('Register Snapshot Repository: '+_reponame_))
# Register Snapshot Repository
payload = {'type':'s3','settings':{'bucket':_reponame_}}
try:
response = requests.put(url+_reponame_, data=json.dumps(payload), headers=headers, verify=False)
response.raise_for_status()
except HTTPError as http_err:
print(f'HTTP error: {http_err}')
except Exception as err:
print(f'Other error: {err}')
else:
print(response)
json_object = json.loads(response.content)
if json_object['acknowledged']:
print(Fore.GREEN +'S3 Snapshot Repo Registered Successfully: '+_reponame_+Style.RESET_ALL)
def takesnapshot(_reponame_,_snapname_,_indicename_):
'''Taking snapshot and storing it to S3 repo for backup
Args:
_reponame_ (string): Name of the snapshot repo this should be same as S3 bucket name for easier managment.
_snapname_ (string): Name of the snapshot that is going to be created in the S3 repo.
_indicename_ (string): Name of the indices you want to take snapshot of.
Returns:
If the S3 snapshot repo exist it will create new snapshot in the S3 repo.
'''
print ('[+] {}'.format('Name of Snapshot to be created: '+_snapname_))
snapnamedate=_snapname_+'-'+str(datetime.date(datetime.now()))
print(snapnamedate)
# Name of indices that need to be backedup.
payload = {'indices':''+_indicename_+'','ignore_unavailable':'true','include_global_state':'false','partial':'false'}
try:
response = requests.put(url+_reponame_+'/'+snapnamedate, data=json.dumps(payload), headers=headers, verify=False)
response.raise_for_status()
except HTTPError as http_err:
print(f'Snapshot with same name already exists: {http_err}')
except Exception as err:
print(f'Other error: {err}')
else:
print(response)
json_object = json.loads(response.content)
print(Fore.GREEN +json.dumps(json_object, indent = 1)+Style.RESET_ALL)
print(Fore.GREEN +'Snapshot Registered Successfully: '+_reponame_+'/'+_snapname_+Style.RESET_ALL)
def status(_reponame_,_snapname_):
'''Check the status of Snapshot if its complete of in progress or if there is any error
Args:
_reponame_ (string): Name of the snapshot repo this should be same as S3 bucket name for easier managment.
_snapname_ (string): Name of the snapshot that is going to be created in the S3 repo.
'''
print ('[+] {}'.format('Check the status of: '+_snapname_))
try:
response = requests.get(url+_reponame_+'/'+_snapname_, headers=headers, verify=False)
response.raise_for_status()
except HTTPError as http_err:
print(f'Snapshot not found: {http_err}')
except Exception as err:
print(f'Other error: {err}')
else:
print(response)
print(Fore.GREEN + 'Snapshot Status!!')
json_object = json.loads(response.content)
print(json.dumps(json_object, indent = 1)+Style.RESET_ALL)
def restore(_reponame_,_snapname_):
'''
Function to restore complete snapshot to opensearch.
Args:
_reponame_ (string): name of the opensearch s3 repo
_snapname_ (string): name of the snapshot want to restore
'''
print ('[+] {}'.format('Restore Snapshot: '+_snapname_))
try:
response = requests.post(url+_reponame_+'/'+_snapname_+'/_restore', headers=headers, verify=False)
response.raise_for_status()
except HTTPError as http_err:
print(f'Open index with same name already exists delete them inorder to restore: {http_err}')
except Exception as err:
print(f'Other error: {err}')
else:
print(response)
print(Fore.GREEN + 'Snapshot Successfully Restored!!')
json_object = json.loads(response.content)
print(json.dumps(json_object, indent = 1)+Style.RESET_ALL)
def restoreindice(_reponame_,_snapname_,_indices_):
'''
Fucntion to restore specific indices from a snapshot
Args:
_reponame_ (string): name of the opensearch s3 repo
_snapname_ (string): name of snapshot
_indices_ (string): name of indices you want to restore ex indice1,indice2
'''
print ('[+] {}'.format('Restore Specific indices form Snapshot: '+_snapname_+' Indices: '+_indices_))
payload = {'indices':''+_indices_+'','ignore_unavailable':'true','include_global_state':'false','include_aliases':'false','partial':'false'}
try:
response = requests.post(url+_reponame_+'/'+_snapname_+'/_restore', data=json.dumps(payload), headers=headers, verify=False)
response.raise_for_status()
except HTTPError as http_err:
print(f'Open index with same name already exists delete them inorder to restore: {http_err}')
except Exception as err:
print(f'Other error: {err}')
else:
print(response)
print(Fore.GREEN + 'Indices restore Status!!')
json_object = json.loads(response.content)
print(json.dumps(json_object, indent = 1)+Style.RESET_ALL)
def deleterepo(_s3repo_):
'''
Function to delete repository
'''
print ('[+] {}'.format('Delete Snapshot Repository'))
try:
response = requests.delete(url+_s3repo_, headers=headers, verify=False)
response.raise_for_status()
except HTTPError as http_err:
print(f'HTTP error: {http_err}')
except Exception as err:
print(f'Other error: {err}')
else:
print(response)
json_object = json.loads(response.content)
print(Fore.GREEN +json.dumps(json_object, indent = 1)+Style.RESET_ALL)
def deletesnap(_s3repo_,_snapname_):
'''
Function to delete snapshot in repository
'''
print ('[+] {}'.format('Delete Snapshot in Repository'))
try:
response = requests.delete(url+_s3repo_+'/'+_snapname_, headers=headers, verify=False)
response.raise_for_status()
except HTTPError as http_err:
print(f'HTTP error: {http_err}')
except Exception as err:
print(f'Other error: {err}')
else:
print(response)
json_object = json.loads(response.content)
print(Fore.GREEN +json.dumps(json_object, indent = 1)+Style.RESET_ALL)
def deleteindice(_host_,_indice_):
'''
Function to delete indices from opensearch
'''
print ('[+] {}'.format('Delete indices'))
url = 'https://'+host+':9200/'
try:
response = requests.delete(url+_indice_, headers=headers, verify=False)
response.raise_for_status()
except HTTPError as http_err:
print(f'HTTP error: {http_err}')
except Exception as err:
print(f'Other error: {err}')
else:
print(response)
json_object = json.loads(response.content)
print(Fore.GREEN +json.dumps(json_object, indent = 1)+Style.RESET_ALL)
def main():
start()
#If testcon is passed in args following function will be called
if args.testcon:
testconn(host)
#If action arg is set to registerrepo following functiuon will be called to register s3 snapshot repo
elif args.action == 'registerrepo':
registerrepo(s3repo)
#If action arg is set to takesnap following function will be called with the repo name, name of snapshot and the indices that you want to include in the snapshot.
elif args.action == 'takesnap':
takesnapshot(s3repo, snapname, indices)
#if action arg is set to status following function will be called with repo name and the name of snapshot to check the status.
elif args.action == 'status':
status(s3repo, snapname)
#if action arg is set to restore following function will be called with repo name and the name of snapshot to restore to openserarch.
elif args.action == 'restore':
restore(s3repo, snapname)
#if action arg is set to restore following function will be called with repo name and the name of snapshot to restore specific indices to openserarch.
elif args.action == 'restoreindice':
restoreindice(s3repo, snapname, indices)
#if action arg is set to listrepos following function will be called to list all repos that are registered.
elif args.action == 'listrepos':
listrepos()
#if action arg is set to listsnaps following function will be called to list all snapshots in a repo.
elif args.action == 'listsnaps':
listsnaps(s3repo)
#if action arg is set to listindices following function will be called to list all indices in opensearch.
elif args.action == 'listindices':
listindices(host)
#if action arg is set to deleterepo following function will be called with s3repo name to delete the repo.
elif args.action == 'deleterepo':
deleterepo(s3repo)
#if action arg is set to deletesnap following function will be called with repo name and snap name to delete snapshot in repo.
elif args.action == 'deletesnap':
deletesnap(s3repo, snapname)
#if action arg is set to deleteindice following function will be called to delete that indice on opensearch
elif args.action == 'deleteindice':
deleteindice(host, indices)
if __name__ == '__main__':
main()