コード例 #1
0
ファイル: NetUtils.java プロジェクト: kanishin/Lealone
 /**
  * Get the local host address as a string. For performance, the result is cached for one second.
  *
  * @return the local host address
  */
 public static synchronized String getLocalAddress() {
   long now = System.currentTimeMillis();
   if (cachedLocalAddress != null) {
     if (cachedLocalAddressTime + CACHE_MILLIS > now) {
       return cachedLocalAddress;
     }
   }
   InetAddress bind = null;
   boolean useLocalhost = false;
   try {
     bind = getBindAddress();
     if (bind == null) {
       useLocalhost = true;
     }
   } catch (UnknownHostException e) {
     // ignore
   }
   if (useLocalhost) {
     try {
       bind = InetAddress.getLocalHost();
     } catch (UnknownHostException e) {
       throw DbException.convert(e);
     }
   }
   String address = bind == null ? "localhost" : getHostAddress(bind);
   if (address.equals("127.0.0.1")) {
     address = "localhost";
   }
   cachedLocalAddress = address;
   cachedLocalAddressTime = now;
   return address;
 }
コード例 #2
0
ファイル: PgPortTracker.java プロジェクト: 4399data/Lealone
 public static void deletePgPortEphemeralNode(ServerName sn, int port, boolean isMaster) {
   try {
     ZKUtil.deleteNode(
         ZooKeeperAdmin.getZooKeeperWatcher(), getPgPortEphemeralNodePath(sn, port, isMaster));
   } catch (KeeperException e) {
     throw DbException.convert(e);
   }
 }
コード例 #3
0
ファイル: PgPortTracker.java プロジェクト: 4399data/Lealone
 public static void createPgPortEphemeralNode(ServerName sn, int port, boolean isMaster) {
   try {
     ZKUtil.createEphemeralNodeAndWatch(
         ZooKeeperAdmin.getZooKeeperWatcher(),
         getPgPortEphemeralNodePath(sn, port, isMaster),
         HConstants.EMPTY_BYTE_ARRAY);
   } catch (KeeperException e) {
     throw DbException.convert(e);
   }
 }
コード例 #4
0
  @Override
  public boolean next() {
    readBuffer.clear();
    searchRow = null;
    row = null;
    index++;
    if (result != null && index < result.length) {
      setSearchRow();
      return true;
    }

    Transaction transaction = session.getTransaction();
    List<KeyValue> kvs;
    KeyValue kv;
    Result r;
    long queryTimestamp;
    try {
      result = session.getRegionServer().next(scannerId, fetchSize);
      ArrayList<Result> list = new ArrayList<Result>(result.length);
      for (int i = 0; i < result.length; i++) {
        r = result[i];
        kvs = r.list();
        // 当Result.isEmpty=true时,r.list()也返回null,所以这里不用再判断kvs.isEmpty
        if (kvs != null) {
          kv = kvs.get(0);
          queryTimestamp = kv.getTimestamp();
          if (queryTimestamp < transaction.getStartTimestamp() & queryTimestamp % 2 == 0) {
            if (kv.getValueLength() != 0) // kv已删除,不需要再处理
            list.add(r);
            continue;
          }
        }

        // TODO Filter.filter很慢
        r = new Result(Filter.filter(session.getRegionServer(), regionName, transaction, kvs, 1));
        if (!r.isEmpty()) list.add(r);
      }

      result = list.toArray(new Result[0]);
    } catch (Exception e) {
      close();
      throw DbException.convert(e);
    }

    index = 0;

    if (result != null && result.length > 0) {
      setSearchRow();
      return true;
    }

    close();
    return false;
  }
コード例 #5
0
ファイル: SessionRemote.java プロジェクト: 4399data/Lealone
  public synchronized void checkTransfers() {
    if (transferList != null) {
      for (int i = 0; i < transferList.size(); i++) {
        Transfer transfer = transferList.get(i);

        try {
          if (transfer.available() > 0)
            throw DbException.throwInternalError(
                "the transfer available bytes was " + transfer.available());
        } catch (IOException e) {
          throw DbException.convert(e);
        }
      }
    }
  }
コード例 #6
0
ファイル: SessionRemote.java プロジェクト: 4399data/Lealone
 public void parseError(Transfer transfer) throws IOException {
   String sqlstate = transfer.readString();
   String message = transfer.readString();
   String sql = transfer.readString();
   int errorCode = transfer.readInt();
   String stackTrace = transfer.readString();
   JdbcSQLException s = new JdbcSQLException(message, sql, sqlstate, errorCode, null, stackTrace);
   if (errorCode == ErrorCode.CONNECTION_BROKEN_1) {
     // allow re-connect
     IOException e = new IOException(s.toString());
     e.initCause(s);
     throw e;
   }
   throw DbException.convert(s);
 }
コード例 #7
0
 @Override
 public Row get() {
   if (row == null) {
     if (searchRow != null) {
       Result r;
       try {
         Get get = new Get(HBaseUtils.toBytes(searchRow.getRowKey()));
         get.setTimeStamp(searchTimestamp);
         if (columns != null) {
           for (Column c : columns) {
             if (c.isRowKeyColumn()) continue;
             else if (c.getColumnFamilyName() != null)
               get.addColumn(c.getColumnFamilyNameAsBytes(), c.getNameAsBytes());
             else get.addColumn(defaultColumnFamilyName, c.getNameAsBytes());
           }
         }
         r = secondaryIndex.dataTable.get(get);
       } catch (IOException e) {
         throw DbException.convert(e);
       }
       if (r != null) {
         Value[] data = new Value[columns.size()];
         Value rowKey = ValueString.get(Bytes.toString(r.getRow()));
         if (columns != null) {
           int i = 0;
           for (Column c : columns) {
             i = c.getColumnId();
             if (c.isRowKeyColumn()) data[i] = rowKey;
             else
               data[i] =
                   HBaseUtils.toValue( //
                       r.getValue(c.getColumnFamilyNameAsBytes(), c.getNameAsBytes()),
                       c.getType());
           }
         }
         row = new HBaseRow(null, rowKey, data, Row.MEMORY_CALCULATE, r);
       }
     }
   }
   return row;
 }
コード例 #8
0
ファイル: SessionRemote.java プロジェクト: 4399data/Lealone
 /**
  * Open a new (remote or embedded) session.
  *
  * @param openNew whether to open a new session in any case
  * @return the session
  */
 public SessionInterface connectEmbeddedOrServer(boolean openNew) {
   ConnectionInfo ci = connectionInfo;
   if (ci.isRemote() || ci.isDynamic()) {
     connectServer(ci);
     return this;
   }
   // create the session using reflection,
   // so that the JDBC layer can be compiled without it
   boolean autoServerMode = Boolean.valueOf(ci.getProperty("AUTO_SERVER", "false")).booleanValue();
   ConnectionInfo backup = null;
   try {
     if (autoServerMode) {
       backup = (ConnectionInfo) ci.clone();
       connectionInfo = (ConnectionInfo) ci.clone();
     }
     if (openNew) {
       ci.setProperty("OPEN_NEW", "true");
     }
     if (sessionFactory == null) {
       sessionFactory = ci.getSessionFactory();
     }
     return sessionFactory.createSession(ci);
   } catch (Exception re) {
     DbException e = DbException.convert(re);
     if (e.getErrorCode() == ErrorCode.DATABASE_ALREADY_OPEN_1) {
       if (autoServerMode) {
         String serverKey = ((JdbcSQLException) e.getSQLException()).getSQL();
         if (serverKey != null) {
           backup.setServerKey(serverKey);
           // OPEN_NEW must be removed now, otherwise
           // opening a session with AUTO_SERVER fails
           // if another connection is already open
           backup.removeProperty("OPEN_NEW", null);
           connectServer(backup);
           return this;
         }
       }
     }
     throw e;
   }
 }
コード例 #9
0
ファイル: SessionRemote.java プロジェクト: 4399data/Lealone
  private void connectServer(ConnectionInfo ci) {
    String name = ci.getName();
    if (name.startsWith("//")) {
      name = name.substring("//".length());
    }
    int idx = name.indexOf('/');
    if (idx < 0) {
      throw ci.getFormatException();
    }
    databaseName = name.substring(idx + 1);
    String server = name.substring(0, idx);
    traceSystem = new TraceSystem(null);
    String traceLevelFile = ci.getProperty(SetTypes.TRACE_LEVEL_FILE, null);
    if (traceLevelFile != null) {
      int level = Integer.parseInt(traceLevelFile);
      String prefix = getFilePrefix(SysProperties.CLIENT_TRACE_DIRECTORY);
      try {
        traceSystem.setLevelFile(level);
        if (level > 0) {
          String file = FileUtils.createTempFile(prefix, Constants.SUFFIX_TRACE_FILE, false, false);
          traceSystem.setFileName(file);
        }
      } catch (IOException e) {
        throw DbException.convertIOException(e, prefix);
      }
    }
    String traceLevelSystemOut = ci.getProperty(SetTypes.TRACE_LEVEL_SYSTEM_OUT, null);
    if (traceLevelSystemOut != null) {
      int level = Integer.parseInt(traceLevelSystemOut);
      traceSystem.setLevelSystemOut(level);
    }
    trace = traceSystem.getTrace(Trace.JDBC);
    String serverList = null;
    if (server.indexOf(',') >= 0) {
      serverList = StringUtils.quoteStringSQL(server);
      ci.setProperty("CLUSTER", Constants.CLUSTERING_ENABLED);
    }
    autoReconnect = Boolean.valueOf(ci.getProperty("AUTO_RECONNECT", "false")).booleanValue();
    // AUTO_SERVER implies AUTO_RECONNECT
    boolean autoServer = Boolean.valueOf(ci.getProperty("AUTO_SERVER", "false")).booleanValue();
    if (autoServer && serverList != null) {
      throw DbException.getUnsupportedException("autoServer && serverList != null");
    }
    autoReconnect |= autoServer;
    if (autoReconnect) {
      String className = ci.getProperty("DATABASE_EVENT_LISTENER");
      if (className != null) {
        className = StringUtils.trim(className, true, true, "'");
        try {
          eventListener = (DatabaseEventListener) Utils.loadUserClass(className).newInstance();
        } catch (Throwable e) {
          throw DbException.convert(e);
        }
      }
    }
    cipher = ci.getProperty("CIPHER");
    if (cipher != null) {
      fileEncryptionKey = MathUtils.secureRandomBytes(32);
    }

    String[] servers;
    if (ci.isDynamic()) {
      servers = new String[] {ci.getOnlineServer(server)};
    } else {
      servers = StringUtils.arraySplit(server, ',', true);

      if (servers.length > 1 && !ci.removeProperty("USE_H2_CLUSTER_MODE", false))
        servers = new String[] {servers[random.nextInt(servers.length)]};
    }
    int len = servers.length;
    transferList.clear();
    sessionId = StringUtils.convertBytesToHex(MathUtils.secureRandomBytes(32));
    // TODO cluster: support more than 2 connections
    boolean switchOffCluster = false;
    try {
      for (int i = 0; i < len; i++) {
        String s = servers[i];
        try {
          Transfer trans = initTransfer(ci, databaseName, s);
          transferList.add(trans);
        } catch (IOException e) {
          if (len == 1) {
            throw DbException.get(ErrorCode.CONNECTION_BROKEN_1, e, e + ": " + s);
          }
          switchOffCluster = true;
        }
      }
      checkClosed();
      if (switchOffCluster) {
        switchOffCluster();
      }
      checkClusterDisableAutoCommit(serverList);
    } catch (DbException e) {
      traceSystem.close();
      throw e;
    }
  }