Skip to content

Instantly share code, notes, and snippets.

@markuskont
Created March 29, 2019 09:49
Show Gist options
  • Save markuskont/734a9ec946bf40801494f14b368a0668 to your computer and use it in GitHub Desktop.
Save markuskont/734a9ec946bf40801494f14b368a0668 to your computer and use it in GitHub Desktop.
Periodic python script for managing moloch indices in elasticsearch hot-cold setup.
#!/usr/bin/env python
from elasticsearch import Elasticsearch
import sys
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--conn",
dest="connection",
default="localhost:9200",
help="elasticsearch proxy")
parser.add_argument("--cold-replicas",
dest="coldReplicas",
default=0,
help="Replica count for indices on cold nodes")
parser.add_argument("--shards",
dest="shards",
default=1,
help="Shard count for all new indices")
args = parser.parse_args()
connection = args.connection
coldReplicas = args.coldReplicas
shardCount = args.shards
name = "sessions2_template"
replicas = 0
hours = 3
pattern = "sessions2"
coldnode = "cold"
es = Elasticsearch(hosts=[connection])
if not es.ping():
print("No connection to elastic")
sys.exit(1)
tpl = es.indices.get_template(name)
tpl[name]["settings"]["index"]["number_of_shards"] = shardCount
tpl[name]["settings"]["index"]["routing"]["allocation"]["require"] = {}
tpl[name]["settings"]["index"]["routing"]["allocation"]["require"]["box_type"] = "hot"
es.indices.put_template(name, body=tpl[name])
indices = es.cat.indices(format="json")
indices = [i["index"] for i in indices if pattern in i["index"]]
indices = sorted(indices)
if len(indices) < hours:
print("not enough indices to reconfigure")
sys.exit(1)
indices = indices[:len(indices)-hours]
for i in indices:
resp = es.indices.put_settings(
{
"index": {
"routing.allocation.require.box_type": "cold"
}
}, i)
print("Cold routing: {}:{}".format(i, resp))
shards = es.cat.shards(format="json")
shards = [s for s in shards if pattern in s["index"]]
shards = [s for s in shards if s["state"] != "UNASSIGNED" and coldnode in s["node"] and s["state"] == "STARTED"]
sys.exit(1)
ok = {s["index"]: 0 for s in shards}
for s in shards: ok[s["index"]] += 1
for k, v in ok.items():
resp = es.indices.put_settings(
{
"index": {
"number_of_replicas": coldReplicas
}
}, k)
print("Cold replica: {}:{}".format(i, resp))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment