<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 org.apache.accumulo.server.master;

import static org.apache.accumulo.core.zookeeper.ZooUtil.NodeMissingPolicy.SKIP;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TimerTask;

import org.apache.accumulo.core.Constants;
import org.apache.accumulo.core.client.Instance;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.core.data.KeyExtent;
import org.apache.accumulo.core.master.thrift.TabletServerStatus;
import org.apache.accumulo.core.security.thrift.ThriftSecurityException;
import org.apache.accumulo.core.tabletserver.thrift.NotServingTabletException;
import org.apache.accumulo.core.tabletserver.thrift.TabletClientService;
import org.apache.accumulo.core.util.ServerServices;
import org.apache.accumulo.core.util.ThriftUtil;
import org.apache.accumulo.core.zookeeper.ZooUtil;
import org.apache.accumulo.server.conf.ServerConfiguration;
import org.apache.accumulo.server.master.state.TServerInstance;
import org.apache.accumulo.server.security.SecurityConstants;
import org.apache.accumulo.server.util.AddressUtil;
import org.apache.accumulo.server.util.Halt;
import org.apache.accumulo.server.util.time.SimpleTimer;
import org.apache.accumulo.server.zookeeper.ZooCache;
import org.apache.accumulo.server.zookeeper.ZooLock;
import org.apache.accumulo.server.zookeeper.ZooReaderWriter;
import org.apache.hadoop.io.Text;
import org.apache.log4j.Logger;
import org.apache.thrift.TException;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;

public class LiveTServerSet implements Watcher {
  
  public interface Listener {
    void update(LiveTServerSet current, Set<TServerInstance> deleted, Set<TServerInstance> added);
  }
  
  private static final Logger log = Logger.getLogger(LiveTServerSet.class);
  
  private final Listener cback;
  private final Instance instance;
  private ZooCache zooCache;
  
  public class TServerConnection {
    private final InetSocketAddress address;
    
    TabletClientService.Iface client = null;
    
    public TServerConnection(InetSocketAddress addr) throws TException {
      address = addr;
      try {
        client = ThriftUtil.getClient(new TabletClientService.Client.Factory(), address, ServerConfiguration.getSystemConfiguration());
      } catch (Exception ex) {
        log.error(ex, ex);
      }
    }
    
    private String lockString(ZooLock mlock) {
      return mlock.getLockID().serialize(ZooUtil.getRoot(instance) + Constants.ZMASTER_LOCK);
    }
    
    synchronized public void close() {
      if (client != null) {
        ThriftUtil.returnClient(client);
        client = null;
      }
    }
    
    synchronized public void assignTablet(ZooLock lock, KeyExtent extent) throws TException {
      client.loadTablet(null, SecurityConstants.getSystemCredentials(), lockString(lock), extent.toThrift());
    }
    
    synchronized public void unloadTablet(ZooLock lock, KeyExtent extent, boolean save) throws TException {
      client.unloadTablet(null, SecurityConstants.getSystemCredentials(), lockString(lock), extent.toThrift(), save);
    }
    
    synchronized public TabletServerStatus getTableMap() throws TException, ThriftSecurityException {
      return client.getTabletServerStatus(null, SecurityConstants.getSystemCredentials());
    }
    
    synchronized public void halt(ZooLock lock) throws TException, ThriftSecurityException {
      if (client != null)
        client.halt(null, SecurityConstants.getSystemCredentials(), lockString(lock));
    }
    
    public void fastHalt(ZooLock lock) throws TException {
      if (client != null)
        client.fastHalt(null, SecurityConstants.getSystemCredentials(), lockString(lock));
    }
    
    synchronized public void flush(ZooLock lock, String tableId, byte[] startRow, byte[] endRow) throws TException {
      client.flush(null, SecurityConstants.getSystemCredentials(), lockString(lock), tableId, startRow == null ? null : ByteBuffer.wrap(startRow),
          endRow == null ? null : ByteBuffer.wrap(endRow));
    }
    
    synchronized public void useLoggers(Set<String> loggers) throws TException {
      client.useLoggers(null, SecurityConstants.getSystemCredentials(), loggers);
    }
    
    synchronized public void chop(ZooLock lock, KeyExtent extent) throws TException {
      client.chop(null, SecurityConstants.getSystemCredentials(), lockString(lock), extent.toThrift());
    }
    
    synchronized public void splitTablet(ZooLock lock, KeyExtent extent, Text splitPoint) throws TException, ThriftSecurityException, NotServingTabletException {
      client.splitTablet(null, SecurityConstants.getSystemCredentials(), extent.toThrift(), ByteBuffer.wrap(splitPoint.getBytes(), 0, splitPoint.getLength()));
    }
    
    synchronized public void flushTablet(ZooLock lock, KeyExtent extent) throws TException {
      client.flushTablet(null, SecurityConstants.getSystemCredentials(), lockString(lock), extent.toThrift());
    }
    
    synchronized public void compact(ZooLock lock, String tableId, byte[] startRow, byte[] endRow) throws TException {
      client.compact(null, SecurityConstants.getSystemCredentials(), lockString(lock), tableId, startRow == null ? null : ByteBuffer.wrap(startRow),
          endRow == null ? null : ByteBuffer.wrap(endRow));
    }
    
    synchronized public boolean isActive(long tid) throws TException {
      return client.isActive(null, tid);
    }
    
  }
  
  static class TServerInfo {
    ZooLock lock;
    TServerConnection connection;
    TServerInstance instance;
    TServerLockWatcher watcher;
    
    TServerInfo(ZooLock lock, TServerInstance instance, TServerConnection connection, TServerLockWatcher watcher) {
      this.lock = lock;
      this.connection = connection;
      this.instance = instance;
      this.watcher = watcher;
    }
    
    void cleanup() throws InterruptedException, KeeperException {
      lock.tryToCancelAsyncLockOrUnlock();
      connection.close();
    }
  };
  
  // Map from tserver master service to server information
  private Map<String,TServerInfo> current = new HashMap<String,TServerInfo>();
  
  public LiveTServerSet(Instance instance, Listener cback) {
    this.cback = cback;
    this.instance = instance;<commit_msg>ACCUMULO-79: lazily create a connection to tablet servers<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 org.apache.accumulo.server.master;

import static org.apache.accumulo.core.zookeeper.ZooUtil.NodeMissingPolicy.SKIP;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TimerTask;

import org.apache.accumulo.core.Constants;
import org.apache.accumulo.core.client.Instance;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.core.data.KeyExtent;
import org.apache.accumulo.core.master.thrift.TabletServerStatus;
import org.apache.accumulo.core.security.thrift.ThriftSecurityException;
import org.apache.accumulo.core.tabletserver.thrift.NotServingTabletException;
import org.apache.accumulo.core.tabletserver.thrift.TabletClientService;
import org.apache.accumulo.core.util.ServerServices;
import org.apache.accumulo.core.util.ThriftUtil;
import org.apache.accumulo.core.zookeeper.ZooUtil;
import org.apache.accumulo.server.conf.ServerConfiguration;
import org.apache.accumulo.server.master.state.TServerInstance;
import org.apache.accumulo.server.security.SecurityConstants;
import org.apache.accumulo.server.util.AddressUtil;
import org.apache.accumulo.server.util.Halt;
import org.apache.accumulo.server.util.time.SimpleTimer;
import org.apache.accumulo.server.zookeeper.ZooCache;
import org.apache.accumulo.server.zookeeper.ZooLock;
import org.apache.accumulo.server.zookeeper.ZooReaderWriter;
import org.apache.hadoop.io.Text;
import org.apache.log4j.Logger;
import org.apache.thrift.TException;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;

public class LiveTServerSet implements Watcher {
  
  public interface Listener {
    void update(LiveTServerSet current, Set<TServerInstance> deleted, Set<TServerInstance> added);
  }
  
  private static final Logger log = Logger.getLogger(LiveTServerSet.class);
  
  private final Listener cback;
  private final Instance instance;
  private ZooCache zooCache;
  
  public class TServerConnection {
    private final InetSocketAddress address;
    
    TabletClientService.Iface client = null;
    
    public TServerConnection(InetSocketAddress addr) throws TException {
      address = addr;
    }
    
    synchronized private TabletClientService.Iface connect() {
      if (client == null) {
        try {
          client = ThriftUtil.getClient(new TabletClientService.Client.Factory(), address, ServerConfiguration.getSystemConfiguration());
        } catch (Exception ex) {
          client = null;
          log.error(ex, ex);
        }
      }
      return client;
    }
    
    private String lockString(ZooLock mlock) {
      return mlock.getLockID().serialize(ZooUtil.getRoot(instance) + Constants.ZMASTER_LOCK);
    }
    
    synchronized public void close() {
      if (client != null) {
        ThriftUtil.returnClient(client);
        client = null;
      }
    }
    
    synchronized public void assignTablet(ZooLock lock, KeyExtent extent) throws TException {
      connect().loadTablet(null, SecurityConstants.getSystemCredentials(), lockString(lock), extent.toThrift());
    }
    
    synchronized public void unloadTablet(ZooLock lock, KeyExtent extent, boolean save) throws TException {
      connect().unloadTablet(null, SecurityConstants.getSystemCredentials(), lockString(lock), extent.toThrift(), save);
    }
    
    synchronized public TabletServerStatus getTableMap() throws TException, ThriftSecurityException {
      return connect().getTabletServerStatus(null, SecurityConstants.getSystemCredentials());
    }
    
    synchronized public void halt(ZooLock lock) throws TException, ThriftSecurityException {
      if (client != null) {
        client.halt(null, SecurityConstants.getSystemCredentials(), lockString(lock));
      }
    }
    
    public void fastHalt(ZooLock lock) throws TException {
      if (client != null) {
        client.fastHalt(null, SecurityConstants.getSystemCredentials(), lockString(lock));
      }
    }
    
    synchronized public void flush(ZooLock lock, String tableId, byte[] startRow, byte[] endRow) throws TException {
      connect().flush(null, SecurityConstants.getSystemCredentials(), lockString(lock), tableId, startRow == null ? null : ByteBuffer.wrap(startRow),
          endRow == null ? null : ByteBuffer.wrap(endRow));
    }
    
    synchronized public void useLoggers(Set<String> loggers) throws TException {
      connect().useLoggers(null, SecurityConstants.getSystemCredentials(), loggers);
    }
    
    synchronized public void chop(ZooLock lock, KeyExtent extent) throws TException {
      connect().chop(null, SecurityConstants.getSystemCredentials(), lockString(lock), extent.toThrift());
    }
    
    synchronized public void splitTablet(ZooLock lock, KeyExtent extent, Text splitPoint) throws TException, ThriftSecurityException, NotServingTabletException {
      connect().splitTablet(null, SecurityConstants.getSystemCredentials(), extent.toThrift(), ByteBuffer.wrap(splitPoint.getBytes(), 0, splitPoint.getLength()));
    }
    
    synchronized public void flushTablet(ZooLock lock, KeyExtent extent) throws TException {
      connect().flushTablet(null, SecurityConstants.getSystemCredentials(), lockString(lock), extent.toThrift());
    }
    
    synchronized public void compact(ZooLock lock, String tableId, byte[] startRow, byte[] endRow) throws TException {
      connect().compact(null, SecurityConstants.getSystemCredentials(), lockString(lock), tableId, startRow == null ? null : ByteBuffer.wrap(startRow),
          endRow == null ? null : ByteBuffer.wrap(endRow));
    }
    
    synchronized public boolean isActive(long tid) throws TException {
      return connect().isActive(null, tid);
    }
    
  }
  
  static class TServerInfo {
    ZooLock lock;
    TServerConnection connection;
    TServerInstance instance;
    TServerLockWatcher watcher;
    
    TServerInfo(ZooLock lock, TServerInstance instance, TServerConnection connection, TServerLockWatcher watcher) {
      this.lock = lock;
      this.connection = connection;
      this.instance = instance;
      this.watcher = watcher;
    }
    
    void cleanup() throws InterruptedException, KeeperException {
      lock.tryToCancelAsyncLockOrUnlock();
      connection.close();
    }
  };
  
  // Map from tserver master service to server information
  private Map<String,TServerInfo> current = new HashMap<String,TServerInfo>();
  
  public LiveTServerSet(Instance instance, Listener cback) {
    this.cback = cback;
    this.instance = instance;
{'fraction_non_alphanumeric': 0.09141613385933886, 'fraction_numerical': 0.0009522513943681131, 'mean_word_length': 4.195406360424029, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, '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': '3753963', 'n_tokens_mistral': 4099, 'n_tokens_neox': 4124, 'n_words': 1011}