在RGW里面每个存储到rados的Object都需要先计算出对应元数据存储的shard number,之后再将元数据信息更新到shard number对应的Object里面。代码如下所示
代码语言:javascript复制int RGWRados::get_bucket_index_object(const string& bucket_oid_base, const string& obj_key,
uint32_t num_shards, RGWBucketInfo::BIShardsHashType hash_type, string *bucket_obj, int *shard_id)
{
int r = 0;
switch (hash_type) {
case RGWBucketInfo::MOD:
if (!num_shards) {
// By default with no sharding, we use the bucket oid as itself
(*bucket_obj) = bucket_oid_base;
if (shard_id) {
*shard_id = -1;
}
} else { uint32_t sid = ceph_str_hash_linux(obj_key.c_str(), obj_key.size());
uint32_t sid2 = sid ^ ((sid & 0xFF) << 24);
sid = sid2 % MAX_BUCKET_INDEX_SHARDS_PRIME % num_shards;
char buf[bucket_oid_base.size() 32];
snprintf(buf, sizeof(buf), "%s.%d", bucket_oid_base.c_str(), sid);
(*bucket_obj) = buf;
if (shard_id) {
*shard_id = (int)sid;
}
}
break;
default:
r = -ENOTSUP;
}
return r;
}
有同学提问,为什么不直接写成 sid = sid %num_shards,而是获取到对应sid以后再做一次sid2 = sid ^ ((sid & 0xFF) << 24),下面把这段代码截取出来说明原因。
编辑头文件 hash_shard.h,内容如下
代码语言:javascript复制#ifndef hash_shard_h
#define hash_shard_h
#ifndef _UINT32_T
#define _UINT32_T
typedef unsigned int uint32_t;
#endif /* _UINT32_T */
#endif /* hash_shard_h */
unsigned ceph_str_hash_linux(const char *str, unsigned long length)
{
unsigned long hash = 0;
while (length--) {
unsigned char c = *str ;
hash = (hash (c << 4) (c >> 4)) * 11;
}
return hash;
}
编辑 main.cpp,内容如下
代码语言:javascript复制#include <iostream>
#include "hash_shard.h"
void hash_obj(std::string obj_key){
uint32_t sid = ceph_str_hash_linux(obj_key.c_str(), obj_key.size());
uint32_t sid1 = sid ^ ((sid & 0xFF) << 24);
uint32_t sid2 = sid1 % 7877 % 8;
uint32_t sid3 = sid % 7877 % 8;
std::cout << "hash2=" << sid2 <<std::endl;
std::cout << "hash1="<< sid3 <<std::endl;
}
int main(int argc, const char * argv[]) {
std::string obj_key1 = "aa2";
hash_obj(obj_key1);
std::string obj_key2 = "aa1";
hash_obj(obj_key2);
std::string obj_key3 = "aa0";
hash_obj(obj_key3);
std::string obj_key4 = "aa3";
hash_obj(obj_key4);
std::string obj_key5 = "aa3";
hash_obj(obj_key5);
return 0;
}
代码语言:javascript复制root@demohost:/home/demouser/hash_shard# g main.cpp -o hash_shard
root@demohost:/home/demouser/hash_shard# ./hash_shard
hash2=7hash1=1hash2=7hash1=1hash2=7hash1=1hash2=4hash1=1hash2=4hash1=1
从裁剪出来的代码运行结果来看,直接sid = sid %num_shards会导致hash计算出来的结果不够离散,最终导致数据都集中写到一个shard文件上造成写入上的单点热数据(hash1计算出来的结果都是1)。
另外MAX_BUCKET_INDEX_SHARDS_PRIME为什么是7877,可以是其他数吗?答案是可以的,但是这个最好是质数,从而保障取余得到的结果足够随机。