顯示具有 java 標籤的文章。 顯示所有文章
顯示具有 java 標籤的文章。 顯示所有文章

2018年10月9日 星期二

HBase Split Table And Base64 Pre-Split Shell

Split Table 的三種方法

第一種:Pre-Splitting

當 Table 被建立時,預設會配置一個 Region 給 Table,這時所有讀寫請求都會訪問到同一個 RegionServer 的同一個 Region 中,此時是沒有負載平衡的效果的,集群中可能存在空閒的 RegionServer。為了解決這個問題可以利用 Pre-Splitting,在建立 Table 的時候配置多個 Region 到同一個 Table 以期許達到分散的效果。
在 Table 初始化時,HBase 是不知道如何去 Split Region 的,因為 HBase 不知道RowKey 會以怎樣的方式被配置及產生。HBase 自帶了數種 Pre-Split 的算法,如 HexStringSplit 和 UniformSplit,我們可以根據 RowKey 的前綴來決定使用哪種 Split 方法。
範例
Bash
$ hbase org.apache.hadoop.hbase.util.RegionSplitter pre_split_table HexStringSplit -c 10 -f f1
P.S. -c 10 為 Region 數目;-f f1 為 Table's Column Family.

Base64 Pre-Split Table Shell

由於小編用的是 Base64 字元當前綴,所以另外寫了一個小工具可以幫助切割 Table,產出的結果可在 HBase Shell 中執行。
preSplit.sh
Bash
#!/bin/bash

CHARS="1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM+/"
TABLE=$1
PARTS=$2

CHARS_LEN=$(echo $CHARS | perl -pe 's/(\S)/\1\n/g' | xargs -I {} | wc -l)
RANGE=$(($CHARS_LEN/($PARTS)))
SPLIT=$(($PARTS-1))

function split_table() {
    echo $CHARS | perl -pe 's/(\S)/\1\n/g' | LC_ALL=C sort | xargs -n $2 \
    | cut -s -d ' ' -f $2 | head -n $SPLIT | xargs | sed "s/ /','/g" \
    | sed "s/^/create '$1', 'cf', SPLITS => ['/g" | sed "s/$/']/g"
}

split_table $TABLE $RANGE
Demo
Bash
# 執行方式
$ ./preSplit.sh {Table Name} {Region Count}

# Sample 1
$ ./preSplit.sh UserTable 3
create 'UserTable', 'cf', SPLITS => ['I','d']

# Sample 2
$ seq 2 10 | xargs -I {} ./preSplit.sh UserTable {}
create 'UserTable', 'cf', SPLITS => ['T']
create 'UserTable', 'cf', SPLITS => ['I','d']
create 'UserTable', 'cf', SPLITS => ['D','T','j']
create 'UserTable', 'cf', SPLITS => ['9','L','X','j']
create 'UserTable', 'cf', SPLITS => ['7','H','R','b','l']
create 'UserTable', 'cf', SPLITS => ['6','F','O','X','g','p']
create 'UserTable', 'cf', SPLITS => ['5','D','L','T','b','j','r']
create 'UserTable', 'cf', SPLITS => ['4','B','I','P','W','d','k','r']
create 'UserTable', 'cf', SPLITS => ['3','9','F','L','R','X','d','j','p']

第二種:Auto Splitting

觸發時機

  1. After Memstore Flush
  2. After Compact

Split 策略

  • ConstantSizeRegionSplitPolicy:0.94 版本前默認的切割策略。
程式註解
vim
A RegionSplitPolicy implementation which splits a region as soon as any of its store 
files exceeds a maximum configurable size. 

This is the default split policy. From 0.94.0 on the default split policy has changed 
to IncreasingToUpperBoundRegionSplitPolicy
關鍵程式碼
Java
@Override
protected boolean shouldSplit() {
  boolean force = region.shouldForceSplit();
  boolean foundABigStore = false;

  for (HStore store : region.getStores()) {
    if ((!store.canSplit())) {
       return false;
    }
    if (store.getSize() > desiredMaxFileSize) {
      foundABigStore = true;
    }
  }
  return foundABigStore || force;
}
切分規則
使用 ConstantSizeRegionSplitPolicy 策略,即 storefile 固定大小策略,當任一個 Storefile 的大小大於 hbase.hregion.max.filesize(Default: 10G) 的時候 Region 就會自動切割。

  • IncreasingToUpperBoundRegionSplitPolicy:0.94 ~ 2.0版本間默認的切割策略。
程式註解
vim
Split size is the number of regions that are on this server that all are of the same table, 
cubed, times 2x the region flush size OR the maximum region split size, whichever is smaller.

For example, if the flush size is 128MB, then after two flushes (256MB) we will split which 
will make two regions that will split when their size is 2^3 * 128MB*2 = 2048MB.

If one of these regions splits, then there are three regions and now the split size is 
3^3 * 128MB*2 = 6912MB, and so on until we reach the configured maximum file size and then 
from there on out, we'll use that.
關鍵程式碼
Java
protected long initialSize;

@Override
protected void configureForRegion(HRegion region) {
  super.configureForRegion(region);
  Configuration conf = getConf();
  initialSize = conf.getLong("hbase.increasing.policy.initial.size", -1);
  if (initialSize > 0) {
    return;
  }
  TableDescriptor desc = region.getTableDescriptor();
  if (desc != null) {
    initialSize = 2 * desc.getMemStoreFlushSize();
  }
  if (initialSize <= 0) {
    initialSize = 2 * conf.getLong(HConstants.HREGION_MEMSTORE_FLUSH_SIZE,
                                   TableDescriptorBuilder.DEFAULT_MEMSTORE_FLUSH_SIZE);
  }
}

@Override
protected boolean shouldSplit() {
  boolean force = region.shouldForceSplit();
  boolean foundABigStore = false;
  int tableRegionsCount = getCountOfCommonTableRegions();
  long sizeToCheck = getSizeToCheck(tableRegionsCount);
  
  for (HStore store : region.getStores()) {
    if (!store.canSplit()) {
      return false;
    }
    long size = store.getSize();
    if (size > sizeToCheck) {
      foundABigStore = true;
    }
  }
  return foundABigStore || force;
}

protected long getSizeToCheck(final int tableRegionsCount) {
  // safety check for 100 to avoid numerical overflow in extreme cases
  return tableRegionsCount == 0 || tableRegionsCount > 100
             ? getDesiredMaxFileSize()
             : Math.min(getDesiredMaxFileSize(),
                        initialSize * tableRegionsCount * tableRegionsCount * tableRegionsCount);
}
切分規則
使用 IncreasingToUpperBoundRegionSplitPolicy 策略,0.94 (包含)之後默認使用此策略,當 Storefile 大於 getSizeToCheck() 所回傳的值時會進行切割。此策略與 RegionServer 上的 Region 個數有關(假定其個數為 RS)
getSizeToCheck() 的規則如下:
  1. 當 RS 等於 0 或大於 100 時,與 ConstantSizeRegionSplitPolicy 策略相同
  2. 當 RS 介於 0 ~ 100 之間時,公式如下:
    • Min(hbase.hregion.max.filesize, hbase.increasing.policy.initial.size * RS ^ 3)
註解
  1. hbase.increasing.policy.initial.size 在未設定的情況下為 hbase.hregion.memstore.flush.size * 2
  2. hbase.hregion.memstore.flush.size 預設值為 128M

  • SteppingSplitPolicy:從 2.0版本開始默認的切割策略。
關鍵程式碼
Java
public class SteppingSplitPolicy extends IncreasingToUpperBoundRegionSplitPolicy {
  @Override
  protected long getSizeToCheck(final int tableRegionsCount) {
    return tableRegionsCount == 1 ? this.initialSize : getDesiredMaxFileSize();
  }
}
切分規則
繼承 IncreasingToUpperBoundRegionSplitPolicy 策略,當 Storefile 大於 getSizeToCheck() 所回傳的值時會進行切割。
getSizeToCheck() 的規則如下:
  1. 當 Regions 數量為 1 時,回傳 hbase.increasing.policy.initial.size
  2. 當 Regions 數量不為 1 時,與 ConstantSizeRegionSplitPolicy 策略相同

第三種:forced splits

使用 HBase Shell 可以強制切分 Table,方法如下:
HBase Shell
Bash
hbase(main):001:0> split

ERROR: wrong number of arguments (0 for 1)

Here is some help for this command:
Split entire table or pass a region to split individual region.  With the
second parameter, you can specify an explicit split key for the region.
Examples:
    split 'tableName'
    split 'namespace:tableName'
    split 'regionName' # format: 'tableName,startKey,id'
    split 'tableName', 'splitKey'
    split 'regionName', 'splitKey'

相關的配置參數

  1. hbase.regionserver.regionSplitLimit 預設值為 Integer.MAX(Cloudera)
控制 RegionServer 的最大 Region 數量,超過則不會進行 Auto Splitting。如果不禁止 Auto Splitting 在每次 flush 或著 compact 之後,RegionServer 都會檢查是否需要 Split,Split 過程老 Region 會先下線在上線 Split 後的 Region,在此期間 Client 訪問會失敗,Retry 過程中會成功但是如果是提供實時服務的系統則想印時長會增加,同時 Split 後的 Compact 是一個比較消耗資源的行為。
  1. hbase.hregion.max.filesize 預設值為 10G
設定 Region's Store Size 的 Max 值,此參數是主要觸發 Split 的條件之一,建議勿將此值設定過低,否則可能會有過多的零碎的 Region,一般的建議是 5G ~ 10G。

2016年8月10日 星期三

How to Use Java to Make an HTTPS Connection without Authentication

注意事項:
    1. TrustModifier 使用上需確認 HTTPS Protocol 是否為 TLS
    2. 本文供參考及學習使用

Catalog

Abstract

過去小編曾撰寫過不同語言的 HTTPS 連線,必須 PASS 掉 HTTPS 中 X509 和 HostName 的狀況並不算少數,這時以 Python 來講只需要增加一個布林值即可,但在 Java 中卻需要實作兩個類別,為了能更簡單的有效的進行程式開發及測試,小編撰寫了一個 TrustModifier,此類別中僅有一個外部可以呼叫的方法,通過此方法可以快速 PASS 掉 X509 及 HostName 驗證

關於 HTTPS 的小知識

在撰寫爬蟲或串接第三方 API 時,不可避免的在某些情況下必須用到 HTTPS 協定,這時如果對方伺服器所提供的是合法的接口,那在實作上只需要直接用 HTTPS 方式去連接即可。但事實並非總是如此,在測試中或使用到內部網路時,會因為伺服器不被信任而造成程式中斷,就小編所知這時我們的選擇,有以下兩種:
  1. 將對方伺服器中的憑證加入信任名單,並設法欺騙己方的伺服器,認為對方的 HostName 是正確的
  2. 在連線過程中無條件 Pass 第一種的兩種檢查
P.S 無論哪一種在傳輸時都仍然有加密,只是目前所要連線的伺服器並未通過驗證可能不安全

TrustModifier.java

import javax.net.ssl.*;
import java.net.URLConnection;
import java.security.cert.*;

/**
 * Created by Cookie on 16/8/9.
 */
public class TrustModifier {
    private static final HostnameVerifier VERIFIER = new AllowHostnameVerifier();
    private static final TrustManager[] MANAGER = new TrustManager[]{new AllowManager()};
    private static final TrustModifier MODIFIER = new TrustModifier("TLS");

    private final SSLSocketFactory factory;

    private TrustModifier(String protocol) {
        try {
            SSLContext ctx = SSLContext.getInstance(protocol);
            ctx.init(null, MANAGER, null);
            factory = ctx.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException("Create Trust Modifier Failed.", e);
        }
    }

    private HttpsURLConnection modify(HttpsURLConnection conn) {
        conn.setSSLSocketFactory(factory);
        conn.setHostnameVerifier(VERIFIER);
        return conn;
    }

    /** Call this method and it will modify connection with trust settings. */
    public static URLConnection trust(URLConnection conn) {
        return (conn instanceof HttpsURLConnection)?
                MODIFIER.modify((HttpsURLConnection) conn) : conn;
    }

    private static final class AllowHostnameVerifier implements HostnameVerifier {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    private static final class AllowManager implements X509TrustManager {
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) {}
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) {}
        public X509Certificate[] getAcceptedIssuers() { return null; }
    }
}

SampleMain.java

import java.io.*;
import java.net.*;

/**
 * Created by Cookie on 16/8/9.
 */
public class SampleMain {

    public static void main(String[] args) throws IOException {
        URLConnection conn = new URL("https://74.125.203.94/").openConnection();

        /** Modify connection */
        TrustModifier.trust(conn);

        String inputLine;
        try(InputStreamReader stream = new InputStreamReader(conn.getInputStream());
            BufferedReader in = new BufferedReader(stream)) {
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
            }
        }
    }
}

Output

在 Output 中可以看出成功拿到了一段內容並未出現例外,連線成功
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>