<commit_before>/**
 * 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 com.cloudera.llama.server;

import com.cloudera.llama.am.impl.FastFormat;
import com.cloudera.llama.util.NamedThreadFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.thrift.TProcessor;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TTransportFactory;

import javax.security.auth.Subject;
import java.net.InetAddress;
import java.security.PrivilegedExceptionAction;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public abstract class ThriftServer<T extends TProcessor, A extends TProcessor>
    extends AbstractServer {
  private Class<? extends ServerConfiguration> serverConfClass;
  private ServerConfiguration sConf;
  private TServer tServer;
  private TServerSocket tServerSocket;
  private TServer tAdminServer;
  private TServerSocket tAdminServerSocket;
  private String hostname;
  private int port;
  private String adminHostname;
  private int adminPort;


  protected ThriftServer(String serviceName,
      Class<? extends ServerConfiguration> serverConfClass) {
    super(serviceName);
    this.serverConfClass = serverConfClass;
  }

  protected ServerConfiguration getServerConf() {
    return sConf;
  }

  @Override
  public void setConf(Configuration conf) {
    if (conf.get(ServerConfiguration.CONFIG_DIR_KEY) == null) {
      throw new RuntimeException(FastFormat.format(
          "Required configuration property '{}' missing",
          ServerConfiguration.CONFIG_DIR_KEY));
    }
    super.setConf(conf);
    sConf = ReflectionUtils.newInstance(serverConfClass, conf);
  }

  ExecutorService createExecutorService(String name, int minThreads,
      final int maxThreads,  final int queueSize) {
    BlockingQueue<Runnable> queue = 
        new LinkedBlockingQueue<Runnable>(queueSize);
    ThreadPoolExecutor executor = new ThreadPoolExecutor(minThreads, maxThreads,
        60, TimeUnit.SECONDS, queue, new NamedThreadFactory(name));
    executor.prestartAllCoreThreads();
    executor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
      @Override
      public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        getLog().error("Discarding incoming calls, using maximum threads " +
            "'{}' and calls queue if full with '{}' entries", maxThreads, 
            queueSize);
      }
    });
    //TODO: add metric gauge for the queue and the executor active threads.
    return executor;
  }

  @Override
  protected Subject loginServerSubject() {
    try {
      return Security.loginServerSubject(sConf);
    } catch (Exception ex) {
      throw new RuntimeException(ex);
    }
  }

  @Override
  protected void startTransport() {
    try {
      Subject.doAs(getServerSubject(), new PrivilegedExceptionAction<Object>() {
        @Override
        public Object run() throws Exception {
          int minThreads = sConf.getServerMinThreads();
          int maxThreads = sConf.getServerMaxThreads();
          int queueSize = sConf.getServerCallsQueueSize();
          tServerSocket = ThriftEndPoint.createTServerSocket(sConf);
          TTransportFactory tTransportFactory = ThriftEndPoint
              .createTTransportFactory(sConf);
          TProcessor processor = createServiceProcessor();
          processor = ThriftEndPoint.createTProcessorWrapper(sConf, false,
              processor);
          TThreadPoolServer.Args args = new TThreadPoolServer.Args<commit_msg>Adding gauge to thrift threadpools to track used threads<commit_after>/**
 * 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 com.cloudera.llama.server;

import com.cloudera.llama.am.impl.FastFormat;
import com.cloudera.llama.util.NamedThreadFactory;
import com.codahale.metrics.Gauge;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.thrift.TProcessor;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TTransportFactory;

import javax.security.auth.Subject;
import java.net.InetAddress;
import java.security.PrivilegedExceptionAction;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public abstract class ThriftServer<T extends TProcessor, A extends TProcessor>
    extends AbstractServer {
  private Class<? extends ServerConfiguration> serverConfClass;
  private ServerConfiguration sConf;
  private TServer tServer;
  private TServerSocket tServerSocket;
  private TServer tAdminServer;
  private TServerSocket tAdminServerSocket;
  private String hostname;
  private int port;
  private String adminHostname;
  private int adminPort;


  protected ThriftServer(String serviceName,
      Class<? extends ServerConfiguration> serverConfClass) {
    super(serviceName);
    this.serverConfClass = serverConfClass;
  }

  protected ServerConfiguration getServerConf() {
    return sConf;
  }

  @Override
  public void setConf(Configuration conf) {
    if (conf.get(ServerConfiguration.CONFIG_DIR_KEY) == null) {
      throw new RuntimeException(FastFormat.format(
          "Required configuration property '{}' missing",
          ServerConfiguration.CONFIG_DIR_KEY));
    }
    super.setConf(conf);
    sConf = ReflectionUtils.newInstance(serverConfClass, conf);
  }

  ExecutorService createExecutorService(String name, int minThreads,
      final int maxThreads,  final int queueSize) {
    BlockingQueue<Runnable> queue = 
        new LinkedBlockingQueue<Runnable>(queueSize);
    final ThreadPoolExecutor executor = new ThreadPoolExecutor(minThreads,
        maxThreads, 60, TimeUnit.SECONDS, queue, new NamedThreadFactory(name));
    executor.prestartAllCoreThreads();
    executor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
      @Override
      public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        getLog().error("Discarding incoming calls, using maximum threads " +
            "'{}' and calls queue if full with '{}' entries", maxThreads, 
            queueSize);
      }
    });
    if (getMetricRegistry() != null) {
      getMetricRegistry().register("llama.am." + name + ".threads.in.use.gauge",
          new Gauge<Integer>() {
            @Override
            public Integer getValue() {
              return executor.getActiveCount();
            }
          });
    }
    return executor;
  }

  @Override
  protected Subject loginServerSubject() {
    try {
      return Security.loginServerSubject(sConf);
    } catch (Exception ex) {
      throw new RuntimeException(ex);
    }
  }

  @Override
  protected void startTransport() {
    try {
      Subject.doAs(getServerSubject(), new PrivilegedExceptionAction<Object>() {
        @Override
        public Object run() throws Exception {
          int minThreads = sConf.getServerMinThreads();
          int maxThreads = sConf.getServerMaxThreads();
          int queueSize = sConf.getServerCallsQueueSize();
          tServerSocket = ThriftEndPoint.createTServerSocket(sConf);
          TTransportFactory tTransportFactory = ThriftEndPoint
              .createTTransportFactory(sConf);
          TProcessor processor = createServiceProcessor();
          processor = ThriftEndPoint.createTProcessorWrapper(sConf, false,
              processor);
          TThreadPoolServer.Args args = new TThreadPoolServer.Args
{'fraction_non_alphanumeric': 0.07942010715411282, 'fraction_numerical': 0.0012606366214938543, 'mean_word_length': 3.9097472924187726, 'pattern_counts': {'":': 0, '<': 16, '<?xml version=': 0, '>': 16, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6646654', 'n_tokens_mistral': 2505, 'n_tokens_neox': 2477, 'n_words': 704}