2 * Copyright (C) 2006-2010 Brian Aker
5 * Use and distribution licensed under the BSD license. See
6 * the COPYING file in the parent directory for full text.
15 uint32_t memcached_generate_hash_value(const char *key
, size_t key_length
, memcached_hash_t hash_algorithm
)
17 return libhashkit_digest(key
, key_length
, (hashkit_hash_algorithm_t
)hash_algorithm
);
20 uint32_t generate_hash(memcached_st
*ptr
, const char *key
, size_t key_length
)
22 uint32_t hash
= 1; /* Just here to remove compile warning */
25 WATCHPOINT_ASSERT(memcached_server_count(ptr
));
27 if (memcached_server_count(ptr
) == 1)
30 hash
= hashkit_digest(&ptr
->hashkit
, key
, key_length
);
35 static uint32_t dispatch_host(memcached_st
*ptr
, uint32_t hash
)
37 switch (ptr
->distribution
)
39 case MEMCACHED_DISTRIBUTION_CONSISTENT
:
40 case MEMCACHED_DISTRIBUTION_CONSISTENT_KETAMA
:
41 case MEMCACHED_DISTRIBUTION_CONSISTENT_KETAMA_SPY
:
43 uint32_t num
= ptr
->continuum_points_counter
;
44 WATCHPOINT_ASSERT(ptr
->continuum
);
47 memcached_continuum_item_st
*begin
, *end
, *left
, *right
, *middle
;
48 begin
= left
= ptr
->continuum
;
49 end
= right
= ptr
->continuum
+ num
;
53 middle
= left
+ (right
- left
) / 2;
54 if (middle
->value
< hash
)
63 case MEMCACHED_DISTRIBUTION_MODULA
:
64 return hash
% memcached_server_count(ptr
);
65 case MEMCACHED_DISTRIBUTION_RANDOM
:
66 return (uint32_t) random() % memcached_server_count(ptr
);
67 case MEMCACHED_DISTRIBUTION_CONSISTENT_MAX
:
69 WATCHPOINT_ASSERT(0); /* We have added a distribution without extending the logic */
70 return hash
% memcached_server_count(ptr
);
76 One day make this public, and have it return the actual memcached_server_st
77 to the calling application.
79 uint32_t memcached_generate_hash(memcached_st
*ptr
, const char *key
, size_t key_length
)
81 uint32_t hash
= 1; /* Just here to remove compile warning */
83 WATCHPOINT_ASSERT(memcached_server_count(ptr
));
85 if (memcached_server_count(ptr
) == 1)
88 if (ptr
->flags
.hash_with_prefix_key
)
90 size_t temp_length
= ptr
->prefix_key_length
+ key_length
;
91 char temp
[temp_length
];
93 if (temp_length
> MEMCACHED_MAX_KEY
-1)
96 strncpy(temp
, ptr
->prefix_key
, ptr
->prefix_key_length
);
97 strncpy(temp
+ ptr
->prefix_key_length
, key
, key_length
);
98 hash
= generate_hash(ptr
, temp
, temp_length
);
102 hash
= generate_hash(ptr
, key
, key_length
);
105 if (memcached_behavior_get(ptr
, MEMCACHED_BEHAVIOR_AUTO_EJECT_HOSTS
) && ptr
->next_distribution_rebuild
)
109 if (gettimeofday(&now
, NULL
) == 0 &&
110 now
.tv_sec
> ptr
->next_distribution_rebuild
)
112 run_distribution(ptr
);
116 return dispatch_host(ptr
, hash
);
119 hashkit_st
*memcached_get_hashkit(memcached_st
*ptr
)
121 return &ptr
->hashkit
;