/**
 * Copyright 2016 LinkedIn Corp. All rights reserved.
 *
 * 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.
 */
package com.github.ambry.clustermap;

import com.github.ambry.utils.SystemTime;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * FixedBackoffResourceStatePolicy marks a resource as unavailable for retryBackoff milliseconds if the number of
 * consecutive errors the resource encountered is greater than failureCountThreshold.
 */
class FixedBackoffResourceStatePolicy implements ResourceStatePolicy {
  private final Object resource;
  private final boolean hardDown;
  private final AtomicInteger failureCount;
  private final int failureCountThreshold;
  private final long retryBackoffMs;
  private AtomicLong downUntil;
  private final Logger logger = LoggerFactory.getLogger(getClass());

  public FixedBackoffResourceStatePolicy(Object resource, boolean hardDown, int failureCountThreshold,
      long retryBackoffMs) {
    this.resource = resource;
    this.hardDown = hardDown;
    this.failureCountThreshold = failureCountThreshold;
    this.retryBackoffMs = retryBackoffMs;
    this.downUntil = new AtomicLong(0);
    this.failureCount = new AtomicInteger(0);
  }

  /*
   * On an error, if the failureCount is greater than the threshold, mark the node as down.
   */
  @Override
  public void onError() {
    int count = failureCount.incrementAndGet();
    if (count >= failureCountThreshold) {
      if (count == failureCountThreshold) {
        logger.error("Resource " + resource + " has gone down");
      }
      logger.trace("Resource " + resource + " remains in down state at time " + SystemTime.getInstance().milliseconds() + "; Adding downtime of " + retryBackoffMs + " ms");
      downUntil.set(SystemTime.getInstance().milliseconds() + retryBackoffMs);
    }
  }

  /*
   * A single response resets the count.
   */
  @Override
  public void onSuccess() {
    if (failureCount.getAndSet(0) >= failureCountThreshold) {
      logger.info("Resource " + resource + " is back up");
    }
  }

  /*
   * If the number of failures are above the threshold, the resource will be counted as down unless downUntil is in
   * the past.
   * Note how failureCount is not reset to 0 here. This is so that the node is marked as down if the first request after
   * marking a node back up, also times out. We only reset failureCount on an actual response, so down nodes get a
   * 'chance' to prove they are back up every retryBackoffMs - they do not get 'fully up' status until they are actually
   * responsive.
   */
  @Override
  public boolean isDown() {
    boolean down = false;
    if (hardDown) {
      down = true;
    } else if (failureCount.get() >= failureCountThreshold) {
      if (SystemTime.getInstance().milliseconds() < downUntil.get()) {
        down = true;
      }
    }
    logger.trace("Resource " + resource + " is " + (down ? "down" : "not down")
        + "; failureCount: " + failureCount.get()
        + "; failureCountThreshold: " + failureCountThreshold
        + "; remaining time: " + (downUntil.get() - SystemTime.getInstance().milliseconds())
        + "; hard down: " + hardDown);
    return down;
  }

  @Override
  public boolean isHardDown() {
    return hardDown;
  }
}

@@ -2070,32 +2070,18 @@
 esource 
-%22 + resource + %22
+%7B%7D
  remains
@@ -2103,19 +2103,66 @@
 at time 
-%22 +
+%7B%7D; adding downtime of %7B%7D ms%22, resource,%0A         
  SystemT
@@ -2197,36 +2197,9 @@
 ds()
- + %22; Adding downtime of %22 +
+,
  ret
@@ -2213,16 +2213,8 @@
 ffMs
- + %22 ms%22
 );%0A 
@@ -3319,99 +3319,75 @@
   %7D%0A
-    logger.trace(%22Resource %22 + resource + %22 is %22 + (down ? %22down%22 : %22not down%22)%0A        + %22
+%0A    if (down) %7B%0A      logger%0A          .trace(%22Resource %7B%7D is down
 ; fa
@@ -3398,19 +3398,19 @@
 eCount: 
-%22 +
+%7B%7D;
  failure
@@ -3418,54 +3418,102 @@
 ount
-.get()%0A        + %22; failureCountThreshold: %22 +
+Threshold: %7B%7D; remaining time: %7B%7D; hard down: %7B%7D%22,%0A              resource, failureCount.get(),
  fai
@@ -3530,16 +3530,17 @@
 hreshold
+,
 %0A       
@@ -3544,34 +3544,14 @@
     
-+ %22; remaining time: %22 + (
+      
 down
@@ -3607,48 +3607,194 @@
 ds()
-)%0A        + %22; hard down: %22 + hardDown);
+, hardDown);%0A    %7D else %7B%0A      logger.trace(%22Resource %7B%7D is not down; failureCount: %7B%7D; failureCountThreshold: %7B%7D%22, resource,%0A          failureCount.get(), failureCountThreshold);%0A    %7D
 %0A   

Use format expressions in new trace logging messages (#409)