#
# Copyright 2016 FUJITSU LIMITED
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
input {
    kafka {
        zk_connect => "127.0.0.1:2181"
        topic_id => "transformed-log"
        group_id => "logstash-persister"
    }
}

filter {
    date {
        match => ["[log][timestamp]", "UNIX"]
        target => "@timestamp"
    }

    date {
        match => ["creation_time", "UNIX"]
        target => "creation_time"
    }

    grok {
        match => {
            "[@timestamp]" => "^(?<index_date>\d{4}-\d{2}-\d{2})"
        }
    }

    if "dimensions" in [log] {
        ruby {
            code => "
                fieldHash = event['log']['dimensions']
                fieldHash.each do |key, value|
                    event[key] = value
                end
            "
        }
    }

    mutate {
        add_field => {
            message => "%{[log][message]}"
            log_level => "%{[log][level]}"
            tenant => "%{[meta][tenantId]}"
            region => "%{[meta][region]}"
        }
        remove_field => ["@version", "host", "type", "tags" ,"_index_date", "meta", "log"]
    }
}

output {
    elasticsearch {
        index => "%{tenant}-%{index_date}"
        document_type => "log"
        hosts => ["%ES_SERVICE_BIND_HOST%"]
        flush_size => 500
    }
}
