Add ES data rotate & cleanup
[ta/caas-logging.git] / docker-build / elasticsearch / elasticsearch-logrotate.sh
1 #!/bin/bash
2 # Copyright 2019 Nokia
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 #     http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 FS_LIMIT=80
17 DOCS_DROP=100000
18 ES_URL="http://localhost:$ELASTICSEARCH_LOGGING_SERVICE_PORT"
19
20 log () {
21     echo "LOGROTATE: $*" >/proc/1/fd/1
22 }
23
24 log "hourly job started"
25
26 IFS='-' read es type num <<< "$HOSTNAME"
27 if [[ "$type" != "data" ]]; then
28     log "non-data node -> exiting"
29     exit 0
30 fi
31
32 # sleep to avoid concurrent runs across multiple ES data Pods
33 let "SLEEP=($num * 600)+($RANDOM % 30)"
34 log "sleeping $SLEEP seconds..."
35 sleep $SLEEP
36
37 TODAY=`date -u +%Y.%m.%d`
38 declare -i pcent=100
39 while [ $pcent -ge $FS_LIMIT ]
40 do
41     pcent=`df --output=pcent /usr/share/elasticsearch/data | tail -n1 | tr -d '%'`
42     log "current filesystem usage: $pcent%"
43     if [ $pcent -le $FS_LIMIT ]; then break; fi
44     index_drop=`curl -sS -XGET "$ES_URL/_cat/indices?h=index" | egrep '^.+-[[:digit:]]{4}\.[[:digit:]]{2}\.[[:digit:]]{2}$' | grep -v "$TODAY" | sort -t'-' -k2 | head -n1`
45     if [ -n "$index_drop" ]; then
46         log "drop index: $index_drop"
47         curl -sS -XDELETE "$ES_URL/$index_drop" >/dev/null
48         sleep 5
49     else
50         log "drop oldest $DOCS_DROP log entries"
51         curl -sS -XPOST "$ES_URL/*-$TODAY/_delete_by_query?sort=@timestamp:asc&max_docs=$DOCS_DROP&refresh=true&q=*" >/dev/null
52         sleep 5
53         log "reclaim deleted space"
54         curl -sS -XPOST "$ES_URL/*-$TODAY/_forcemerge?only_expunge_deletes=true" >/dev/null
55         sleep 30
56     fi
57     log "flush"
58     curl -sS -XPOST "$ES_URL/*-$TODAY/_flush" >/dev/null
59     sleep 5
60 done
61
62 log "job exited"