#! /usr/bin/env python
# Script to delete indexes before a particular number of days.
# PLEASE SET months_list according to year.
# Params required: efk_host_ip, number_of_days, efk_port
# Author : Ajay Kumar Mahto <ajay.mahto@snapdeal.com>

import time
import requests
import sys
from subprocess import Popen, PIPE

#Getting current day number
def get_current_day_number():
        return time.localtime().tm_yday

#Getting day_number from date_dict({'year': , 'month': , 'day': })
def get_day_from_date_dict(date_dict):

	#month_list_according_to_2017
	month_list = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
	day_number = 0
	for i in range(date_dict['month']-1):
		day_number += month_list[i]
	day_number += date_dict['day']
	return day_number

#Getting efk_indices list
def get_indices_list(efk_host_ip, efk_port):
	try:
        	cmd = "curl -XGET '%s:%s/_cat/indices?v&pretty'" % (efk_host_ip, efk_port)
        	p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
    	        output, error = p.communicate()
    	        if output:
    			indexes = [line.strip().split()[2] for line in output.strip().splitlines()][1:]
    			indexes.remove('.kibana')
    			return indexes
	except:
		return []

#Getting date_dict from index
#<node_type>-YYYY.MM.DD --> {'year': , 'month': , 'day': }
def get_date_dict_from_index(index):
	date_elements = index.split('-')[1].split('.')
	date_dict = {}
	date_dict['year'] = int(date_elements[0])
	date_dict['month'] = int(date_elements[1])
	date_dict['day'] = int(date_elements[2])
	return date_dict

def main():
	if len(sys.argv) < 4:
		print "Usage: %s <EFK_HOST_IP> <EFK_PORT> <RETENTION_IN_DAYS>" % sys.argv[0]
		return
	
	efk_host_ip = sys.argv[1]
	efk_port = int(sys.argv[2])
	days_to_retain = int(sys.argv[3])
	indexes = get_indices_list(efk_host_ip, efk_port)
        deleted_indexes = []	
	for index in indexes:
		print index
		date_dict = get_date_dict_from_index(index)
		day_number = get_day_from_date_dict(date_dict)
		current_day_number = get_current_day_number()
		if current_day_number - day_number > days_to_retain:
			deleted_indexes.append(index)
			try:
				cmd = "curl -XDELETE '%s:%s/%s?pretty'" % (efk_host_ip, efk_port, index)
				p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
				output, error = p.communicate()
				print output, error
			except Exception as e:
				print e

	if len(deleted_indexes) == 0:
		print
		print "All Good, Nothing to delete!"
	else:
		print "Deleted Indexes: "
		for index in deleted_indexes:
			print index	

if __name__ == '__main__':
	main()
