/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF 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.apache.hadoop.hbase.regionserver;

import java.io.IOException;
import java.net.InetAddress;
import java.util.Optional;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.CompatibilitySingletonFactory;
import org.apache.hadoop.hbase.ipc.RpcServer;
import org.apache.hadoop.hbase.ipc.ServerRpcConnection;
import org.apache.hadoop.hbase.security.User;
import org.apache.hadoop.hbase.security.UserProvider;
import org.apache.hadoop.hbase.util.LossyCounting;
import org.apache.yetus.audience.InterfaceAudience;

import org.apache.hadoop.hbase.shaded.protobuf.generated.RPCProtos;

@InterfaceAudience.Private
public class MetricsUserAggregateImpl implements MetricsUserAggregate {

  /** Provider for mapping principal names to Users */
  private final UserProvider userProvider;

  private final MetricsUserAggregateSource source;
  private final LossyCounting<MetricsUserSource> userMetricLossyCounting;

  public MetricsUserAggregateImpl(Configuration conf) {
    source = CompatibilitySingletonFactory.getInstance(MetricsRegionServerSourceFactory.class)
      .getUserAggregate();
    userMetricLossyCounting = new LossyCounting<>("userMetrics", conf, source::deregister);
    this.userProvider = UserProvider.instantiate(conf);
  }

  /**
   * Returns the active user to which authorization checks should be applied. If we are in the
   * context of an RPC call, the remote user is used, otherwise the currently logged in user is
   * used.
   */
  private String getActiveUser() {
    Optional<User> user = RpcServer.getRequestUser();
    if (!user.isPresent()) {
      // for non-rpc handling, fallback to system user
      try {
        user = Optional.of(userProvider.getCurrent());
      } catch (IOException ignore) {
      }
    }
    return user.map(User::getShortName).orElse(null);
  }

  @Override
  public MetricsUserAggregateSource getSource() {
    return source;
  }

  @Override
  public void updatePut(long t) {
    String user = getActiveUser();
    if (user != null) {
      MetricsUserSource userSource = getOrCreateMetricsUser(user);
      userSource.updatePut(t);
      incrementClientWriteMetrics(userSource);
    }

  }

  private String getClient() {
    Optional<InetAddress> ipOptional = RpcServer.getRemoteAddress();
    return ipOptional.map(InetAddress::getHostName).orElse(null);
  }

  private void incrementClientReadMetrics(MetricsUserSource userSource) {
    ClientConnectionContext ctx = getClientConnectionContext();
    String client = getClient();
    if (client != null && userSource != null) {
      userSource.getOrCreateMetricsClient(client, ctx.hostAddress, ctx.userName, ctx.clientVersion,
        ctx.serviceName).incrementReadRequest();
    }
  }

  private void incrementFilteredReadRequests(MetricsUserSource userSource) {
    ClientConnectionContext ctx = getClientConnectionContext();
    String client = getClient();
    if (client != null && userSource != null) {
      userSource.getOrCreateMetricsClient(client, ctx.hostAddress, ctx.userName, ctx.clientVersion,
        ctx.serviceName).incrementFilteredReadRequests();
    }
  }

  private void incrementClientWriteMetrics(MetricsUserSource userSource) {
    ClientConnectionContext ctx = getClientConnectionContext();
    String client = getClient();
    if (client != null && userSource != null) {
      userSource.getOrCreateMetricsClient(client, ctx.hostAddress, ctx.userName, ctx.clientVersion,
        ctx.serviceName).incrementWriteRequest();
    }
  }

  @Override
  public void updateDelete(long t) {
    String user = getActiveUser();
    if (user != null) {
      MetricsUserSource userSource = getOrCreateMetricsUser(user);
      userSource.updateDelete(t);
      incrementClientWriteMetrics(userSource);
    }
  }

  @Override
  public void updateGet(long time, long blockBytesScanned) {
    String user = getActiveUser();
    if (user != null) {
      MetricsUserSource userSource = getOrCreateMetricsUser(user);
      userSource.updateGet(time, blockBytesScanned);
    }
  }

  @Override
  public void updateIncrement(long time, long blockBytesScanned) {
    String user = getActiveUser();
    if (user != null) {
      MetricsUserSource userSource = getOrCreateMetricsUser(user);
      userSource.updateIncrement(time, blockBytesScanned);
      incrementClientWriteMetrics(userSource);
    }
  }

  @Override
  public void updateAppend(long time, long blockBytesScanned) {
    String user = getActiveUser();
    if (user != null) {
      MetricsUserSource userSource = getOrCreateMetricsUser(user);
      userSource.updateAppend(time, blockBytesScanned);
      incrementClientWriteMetrics(userSource);
    }
  }

  @Override
  public void updateReplay(long t) {
    String user = getActiveUser();
    if (user != null) {
      MetricsUserSource userSource = getOrCreateMetricsUser(user);
      userSource.updateReplay(t);
      incrementClientWriteMetrics(userSource);
    }
  }

  @Override
  public void updateScan(long time, long blockBytesScanned) {
    String user = getActiveUser();
    if (user != null) {
      MetricsUserSource userSource = getOrCreateMetricsUser(user);
      userSource.updateScan(time, blockBytesScanned);
    }
  }

  @Override
  public void updateCheckAndMutate(long blockBytesScanned) {
    String user = getActiveUser();
    if (user != null) {
      MetricsUserSource userSource = getOrCreateMetricsUser(user);
      userSource.updateCheckAndMutate(blockBytesScanned);
    }
  }

  @Override
  public void updateFilteredReadRequests() {
    String user = getActiveUser();
    if (user != null) {
      MetricsUserSource userSource = getOrCreateMetricsUser(user);
      incrementFilteredReadRequests(userSource);
    }
  }

  @Override
  public void updateReadRequestCount() {
    String user = getActiveUser();
    if (user != null) {
      MetricsUserSource userSource = getOrCreateMetricsUser(user);
      incrementClientReadMetrics(userSource);
    }
  }

  private MetricsUserSource getOrCreateMetricsUser(String user) {
    MetricsUserSource userSource = source.getOrCreateMetricsUser(user);
    userMetricLossyCounting.add(userSource);
    return userSource;
  }

  private ClientConnectionContext getClientConnectionContext() {
    String hostAddress = null;
    String userName = "Unknown";
    String clientVersion = "Unknown";
    String serviceName = "Unknown";

    Optional<ServerRpcConnection> rpcConnectionOptional = RpcServer.getCurrentServerRpcConnection();
    if (rpcConnectionOptional.isPresent()) {
      ServerRpcConnection rpcConnection = rpcConnectionOptional.get();
      hostAddress = rpcConnection.getHostAddress();
      RPCProtos.ConnectionHeader connectionHeader = rpcConnection.getConnectionHeader();
      if (connectionHeader.hasUserInfo()) {
        RPCProtos.UserInformation userInfoProto = connectionHeader.getUserInfo();
        if (userInfoProto.hasEffectiveUser()) {
          userName = userInfoProto.getEffectiveUser();
        }
      }
      if (connectionHeader.hasVersionInfo()) {
        clientVersion = connectionHeader.getVersionInfo().getVersion();
      }
      if (connectionHeader.hasServiceName()) {
        serviceName = connectionHeader.getServiceName();
      }
    }
    return new ClientConnectionContext(hostAddress, userName, clientVersion, serviceName);
  }

  private static class ClientConnectionContext {
    final String hostAddress;
    final String userName;
    final String clientVersion;
    final String serviceName;

    ClientConnectionContext(String hostAddress, String userName, String clientVersion,
      String serviceName) {
      this.hostAddress = hostAddress;
      this.userName = userName;
      this.clientVersion = clientVersion;
      this.serviceName = serviceName;
    }

    public String toString() {
      return "ClientConnectionContext{hostAddress=" + hostAddress + ", userName=" + userName
        + ", clientVersion=" + clientVersion + ", serviceName=" + serviceName + "}";
    }
  }
}
