/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch licenses this file to you 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.
 */
package org.elasticsearch.hadoop.mr;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.commons.logging.Log;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapred.TaskID;
import org.apache.hadoop.util.Progressable;
import org.elasticsearch.hadoop.util.Assert;
import org.elasticsearch.hadoop.util.unit.TimeValue;

/**
 * Utility class acting as a heart-beat to Hadoop to prevent it from killing es-hadoop jobs, especially when indexing data which can take time a long time.
 */
class HeartBeat {

    private ScheduledExecutorService scheduler;
    private final Progressable progressable;
    private final TimeValue rate;
    private final Log log;
    private final String id;

    HeartBeat(final Progressable progressable, Configuration cfg, TimeValue delay, final Log log) {
        Assert.notNull(progressable, "a valid progressable is required to report status to Hadoop");
        TimeValue tv = HadoopCfgUtils.getTaskTimeout(cfg);
        Assert.isTrue(tv.getSeconds() > delay.getSeconds(), "Hadoop timeout is shorter than the heartbeat");

        this.progressable = progressable;
        this.rate = new TimeValue(tv.getMillis() - delay.getMillis(), TimeUnit.MILLISECONDS);
        this.log = log;
        TaskID taskID = TaskID.forName(HadoopCfgUtils.getTaskId(cfg));

        String taskId;
        if (taskID == null) {
            log.warn("Cannot determine task id...");
            taskId = "<unknown>";
            if (log.isTraceEnabled()) {
                log.trace("Current configuration is " + HadoopCfgUtils.asProperties(cfg));
            }
        }
        else {
            taskId = "" + taskID;
        }

        id = taskId;
    }


    void start() {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        if (log != null && log.isTraceEnabled()) {
            log.trace(String.format("Starting heartbeat for %s", id));
        }

        scheduler.schedule(new Runnable() {
            @Override
            public void run() {
                if (log != null && log.isTraceEnabled()) {
                    log.trace(String.format("Heartbeat/progress sent to Hadoop for %s", id));
                }
                progressable.progress();
            }
            // start the reporter before timing out
        }, rate.getMillis(), TimeUnit.MILLISECONDS);
    }

    void stop() {
        if (log != null && log.isTraceEnabled()) {
            log.trace(String.format("Stopping heartbeat for %s", id));
        }

        if (scheduler != null) {
            scheduler.shutdownNow();
        }
    }
}

@@ -1036,16 +1036,63 @@
 ration;%0A
+import org.apache.hadoop.mapred.TaskAttemptID;%0A
 import o
@@ -1212,16 +1212,66 @@
 Assert;%0A
+import org.elasticsearch.hadoop.util.StringUtils;%0A
 import o
@@ -2209,24 +2209,25 @@
 .log = log;%0A
+%0A
         Task
@@ -2242,54 +2242,588 @@
 D = 
-TaskID.forName(HadoopCfgUtils.getTaskId(cfg));
+null;%0A        // first try with the attempt since some Hadoop versions mix the two%0A%0A        String taskAttemptId = HadoopCfgUtils.getTaskAttemptId(cfg);%0A        if (StringUtils.hasText(taskAttemptId)) %7B%0A            taskID = TaskAttemptID.forName(taskAttemptId).getTaskID();%0A        %7D%0A        else %7B%0A            String taskIdProp = HadoopCfgUtils.getTaskId(cfg);%0A            // double-check task id bug in Hadoop 2.5.x%0A            if (StringUtils.hasText(taskIdProp) && !taskIdProp.contains(%22attempt%22)) %7B%0A                taskID = TaskID.forName(taskIdProp);%0A            %7D%0A        %7D
 %0A%0A  

Improve detection of Hadoop taskID