consistent-hash.c 12.1 KB
Newer Older
1
/*
Bernd Zeimetz's avatar
Bernd Zeimetz committed
2
 * Copyright 2013-2017 Fabian Groffen
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
 *
 * Licensed 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.
 */


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

23
#include "fnv1a.h"
24
#include "md5.h"
25 26 27 28 29 30 31 32
#include "server.h"

#define CH_RING struct _ch_ring
#include "consistent-hash.h"


/* This value is hardwired in the carbon sources, and necessary to get
 * fair (re)balancing of metrics in the hash ring.  Because the value
33 34
 * seems reasonable, we use the same value for carbon and fnv1a hash
 * implementations. */
35 36 37 38 39 40 41 42 43 44 45 46 47
#define HASH_REPLICAS  100

typedef struct _ring_entry {
	unsigned short pos;
	unsigned char malloced:1;
	server *server;
	struct _ring_entry *next;
} ch_ring_entry;

struct _ch_ring {
	ch_type type;
	unsigned char hash_replicas;
	ch_ring_entry *entries;
48 49
	ch_ring_entry **entrylist;  /* only used with jump hash */
	int entrycnt;
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
};


/**
 * Computes the hash position for key in a 16-bit unsigned integer
 * space.  Returns a number between 0 and 65535 based on the highest 2
 * bytes of the MD5 sum of key.
 */
static unsigned short
carbon_hashpos(const char *key, const char *end)
{
	unsigned char md5[MD5_DIGEST_LENGTH];

	MD5((unsigned char *)key, end - key, md5);

	return ((md5[0] << 8) + md5[1]);
}

/**
 * Computes the hash position for key in a 16-bit unsigned integer
 * space.  Returns a number between 0 and 65535 based on the FNV1a hash
 * algorithm.
 */
static unsigned short
fnv1a_hashpos(const char *key, const char *end)
{
76
	unsigned int hash;
77

78
	fnv1a_32(hash, key, key, end);
79 80 81 82

	return (unsigned short)((hash >> 16) ^ (hash & (unsigned int)0xFFFF));
}

83 84 85 86
/**
 * Computes the bucket number for key in the range [0, bckcnt).  The
 * algorithm used is the jump consistent hash by Lamping and Veach.
 */
Bernd Zeimetz's avatar
Bernd Zeimetz committed
87
static unsigned int
88 89 90 91 92 93 94 95 96 97 98 99 100
jump_bucketpos(unsigned long long int key, int bckcnt)
{
	long long int b = -1, j = 0;

	while (j < bckcnt) {
		b = j;
		key = key * 2862933555777941757ULL + 1;
		j = (long long int)((double)(b + 1) *
				((double)(1LL << 31) / (double)((key >> 33) + 1))
			);
	}

	/* b cannot exceed the range of bckcnt, see while condition */
Bernd Zeimetz's avatar
Bernd Zeimetz committed
101
	return (unsigned int)b;
102 103
}

104
/**
105
 * Sort comparator for ch_ring_entry structs on pos, ip and instance.
106 107
 */
static int
108
entrycmp_carbon(const void *l, const void *r)
109
{
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
	ch_ring_entry *ch_l = (ch_ring_entry *)l;
	ch_ring_entry *ch_r = (ch_ring_entry *)r;

	if (ch_l->pos != ch_r->pos)
		return ch_l->pos - ch_r->pos;

#ifndef CH_CMP_V40_BEHAVIOUR
	{
		int d = strcmp(server_ip(ch_l->server), server_ip(ch_r->server));
		char *i_l, *i_r;
		if (d != 0)
			return d;
		i_l = server_instance(ch_l->server);
		i_r = server_instance(ch_r->server);
		if (i_l == NULL && i_r == NULL)
			return 0;
		if (i_l == NULL)
			return 1;
		if (i_r == NULL)
			return -1;
		return strcmp(i_l, i_r);
	}
#endif

	return 0;
}

/**
 * Sort comparator for ch_ring_entry structs on pos, ip and port.
 */
static int
entrycmp_fnv1a(const void *l, const void *r)
{
	ch_ring_entry *ch_l = (ch_ring_entry *)l;
	ch_ring_entry *ch_r = (ch_ring_entry *)r;

	if (ch_l->pos != ch_r->pos)
		return ch_l->pos - ch_r->pos;

#ifndef CH_CMP_V40_BEHAVIOUR
	{
		int d = strcmp(server_ip(ch_l->server), server_ip(ch_r->server));
		if (d != 0)
			return d;
		return server_port(ch_l->server) - server_port(ch_r->server);
	}
#endif

	return 0;
159 160
}

161 162 163 164 165 166 167 168 169 170 171 172
/**
 * Sort comparator for ch_ring_entry structs on instance only.
 */
static int
entrycmp_jump_fnv1a(const void *l, const void *r)
{
	char *si_l = server_instance(((ch_ring_entry *)l)->server);
	char *si_r = server_instance(((ch_ring_entry *)r)->server);

	return strcmp(si_l ? si_l : "", si_r ? si_r : "");
}

173 174 175 176 177 178 179 180
ch_ring *
ch_new(ch_type type)
{
	ch_ring *ret = malloc(sizeof(ch_ring));

	if (ret == NULL)
		return NULL;
	ret->type = type;
181 182 183 184 185 186 187 188 189
	switch (ret->type) {
		case CARBON:
		case FNV1a:
			ret->hash_replicas = HASH_REPLICAS;
			break;
		default:
			ret->hash_replicas = 1;
			break;
	}
190
	ret->entries = NULL;
191 192
	ret->entrylist = NULL;
	ret->entrycnt = 0;
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210

	return ret;
}

/**
 * Computes the hash positions for the server name given.  This is based
 * on the hashpos function.  The server name usually is the IPv4
 * address.  The port component is just stored and not used in the
 * carbon hash calculation in case of carbon_ch.  The instance component
 * is used in the hash calculation of carbon_ch, it is ignored for
 * fnv1a_ch.  Returns an updated ring.
 */
ch_ring *
ch_addnode(ch_ring *ring, server *s)
{
	int i;
	char buf[256];
	ch_ring_entry *entries;
211 212
	char *instance = server_instance(s);
	int (*cmp)(const void *, const void *) = NULL;
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232

	if (ring == NULL)
		return NULL;

	entries =
		(ch_ring_entry *)malloc(sizeof(ch_ring_entry) * ring->hash_replicas);
	if (entries == NULL)
		return NULL;

	switch (ring->type) {
		case CARBON:
			for (i = 0; i < ring->hash_replicas; i++) {
				/* this format is actually Python's tuple format that is
				 * used in serialised form as input for the hash */
				snprintf(buf, sizeof(buf), "('%s', %s%s%s):%d",
						server_ip(s),
						instance == NULL ? "" : "'",
						instance == NULL ? "None" : instance,
						instance == NULL ? "" : "'",
						i);
233
				/* carbon upstream committed:
234
				 * https://github.com/graphite-project/carbon/commit/024f9e67ca47619438951c59154c0dec0b0518c7
235 236 237 238
				 * this makes sure no collissions exist on pos, however,
				 * at the expense of being agnostic to the input order,
				 * therefore that change isn't implemented here, see
				 * https://github.com/grobian/carbon-c-relay/issues/84 */
239 240 241 242 243
				entries[i].pos = carbon_hashpos(buf, buf + strlen(buf));
				entries[i].server = s;
				entries[i].next = NULL;
				entries[i].malloced = 0;
			}
244
			cmp = *entrycmp_carbon;
245 246 247 248 249
			break;
		case FNV1a:
			for (i = 0; i < ring->hash_replicas; i++) {
				/* take all server info into account, such that
				 * different port numbers for the same hosts will work
250 251 252 253 254 255 256
				 * (unlike CARBON), unless we got a full overrride */
				if (instance == NULL) {
					snprintf(buf, sizeof(buf), "%d-%s:%u",
							i, server_ip(s), server_port(s));
				} else {
					snprintf(buf, sizeof(buf), "%d-%s", i, instance);
				}
257 258 259 260 261
				entries[i].pos = fnv1a_hashpos(buf, buf + strlen(buf));
				entries[i].server = s;
				entries[i].next = NULL;
				entries[i].malloced = 0;
			}
262
			cmp = *entrycmp_fnv1a;
263
			break;
264 265 266 267 268 269 270
		case JUMP_FNV1a:
			entries[0].pos = 0;
			entries[0].server = s;
			entries[0].next = NULL;
			entries[0].malloced = 0;
			cmp = *entrycmp_jump_fnv1a;
			break;
271 272 273
	}

	/* sort to allow merge joins later down the road */
274
	qsort(entries, ring->hash_replicas, sizeof(ch_ring_entry), cmp);
275 276 277 278 279 280 281 282 283 284 285 286 287
	entries[0].malloced = 1;

	if (ring->entries == NULL) {
		for (i = 1; i < ring->hash_replicas; i++)
			entries[i - 1].next = &entries[i];
		ring->entries = entries;
	} else {
		/* merge-join the two rings */
		ch_ring_entry *w, *last;
		i = 0;
		last = NULL;
		assert(ring->hash_replicas > 0);
		for (w = ring->entries; w != NULL && i < ring->hash_replicas; ) {
288
			if (cmp(w, &entries[i]) <= 0) {
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
				last = w;
				w = w->next;
			} else {
				entries[i].next = w;
				if (last == NULL) {
					ring->entries = &entries[i];
				} else {
					last->next = &entries[i];
				}
				last = &entries[i];
				i++;
			}
		}
		if (w != NULL) {
			last->next = w;
		} else {
			last->next = &entries[i];
			for (i = i + 1; i < ring->hash_replicas; i++)
				entries[i - 1].next = &entries[i];
		}
	}

311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
	if (ring->type == JUMP_FNV1a) {
		ch_ring_entry *w;

		/* count the ring, pos is purely cosmetic, it isn't used */
		for (w = ring->entries, i = 0; w != NULL; w = w->next, i++)
			w->pos = i;
		ring->entrycnt = i;
		/* this is really wasteful, but optimising this isn't worth it
		 * since it's called only a few times during config parsing */
		if (ring->entrylist != NULL)
			free(ring->entrylist);
		ring->entrylist = malloc(sizeof(ch_ring_entry *) * ring->entrycnt);
		for (w = ring->entries, i = 0; w != NULL; w = w->next, i++)
			ring->entrylist[i] = w;

		if (i == CONN_DESTS_SIZE) {
			logerr("ch_addnode: nodes in use exceeds CONN_DESTS_SIZE, "
					"increase CONN_DESTS_SIZE in router.h\n");
			return NULL;
		}
	}

333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
	return ring;
}

/**
 * Retrieve the nodes responsible for storing the given metric.  The
 * replcnt argument specifies how many hosts should be retrieved.
 * Results are stored in ret, an array of ch_ring pointers.  The
 * caller is responsible for ensuring that ret is large enough to store
 * replcnt pointers.
 */
void
ch_get_nodes(
		destination ret[],
		ch_ring *ring,
		const char replcnt,
		const char *metric,
		const char *firstspace)
{
	ch_ring_entry *w;
	unsigned short pos = 0;
	int i, j;

	switch (ring->type) {
		case CARBON:
			pos = carbon_hashpos(metric, firstspace);
			break;
		case FNV1a:
			pos = fnv1a_hashpos(metric, firstspace);
			break;
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
		case JUMP_FNV1a: {
			/* this is really a short route, since the jump hash gives
			 * us a bucket immediately */
			unsigned long long int hash;
			ch_ring_entry *bcklst[CONN_DESTS_SIZE];
			const char *p;

			i = ring->entrycnt;
			pos = replcnt;

			memcpy(bcklst, ring->entrylist, sizeof(bcklst[0]) * i);
			fnv1a_64(hash, p, metric, firstspace);

			while (i > 0) {
				j = jump_bucketpos(hash, i);

				(*ret).dest = bcklst[j]->server;
				(*ret).metric = strdup(metric);
				ret++;

				if (--pos == 0)
					break;

				/* use xorshift to generate a different hash for input
				 * in the hump hash again */
				hash ^= hash >> 12;
				hash ^= hash << 25;
				hash ^= hash >> 27;
				hash *= 2685821657736338717ULL;

				/* remove the server we just selected, such that we can
				 * be sure the next iteration will fetch another server */
				bcklst[j] = bcklst[--i];
			}
		}	return;
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
	}

	assert(ring->entries);

	/* implement behaviour of Python's bisect_left on the ring (used in
	 * carbon hash source), one day we might want to implement it as
	 * real binary search iso forward pointer chasing */
	for (w = ring->entries, i = 0; w != NULL; i++, w = w->next)
		if (w->pos >= pos)
			break;
	/* now fetch enough unique servers to match the requested count */
	for (i = 0; i < replcnt; i++, w = w->next) {
		if (w == NULL)
			w = ring->entries;
		for (j = i - 1; j >= 0; j--) {
			if (ret[j].dest == w->server) {
				j = i;
				break;
			}
		}
		if (j == i) {
			i--;
			continue;
		}
		ret[i].dest = w->server;
		ret[i].metric = strdup(metric);
	}
}

426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
void
ch_printhashring(ch_ring *ring, FILE *f)
{
	ch_ring_entry *w;
	char column = 0;
	char srvbuf[21];

	for (w = ring->entries; w != NULL; w = w->next) {
		snprintf(srvbuf, sizeof(srvbuf), "%s:%d%s%s",
				server_ip(w->server),
				server_port(w->server),
				server_instance(w->server) ? "=" : "",
				server_instance(w->server) ? server_instance(w->server) : "");
		fprintf(f, "%5d@%-20s", w->pos, srvbuf);
		if (column < 2) {
			fprintf(f, " ");
			column++;
		} else {
			fprintf(f, "\n");
			column = 0;
		}
	}
448 449
	if (column != 0)
		fprintf(f, "\n");
450 451 452 453 454 455 456 457 458 459
}

unsigned short
ch_gethashpos(ch_ring *ring, const char *key, const char *end)
{
	switch (ring->type) {
		case CARBON:
			return carbon_hashpos(key, end);
		case FNV1a:
			return fnv1a_hashpos(key, end);
460 461 462 463 464
		case JUMP_FNV1a: {
			unsigned long long int hash;
			fnv1a_64(hash, key, key, end);
			return jump_bucketpos(hash, ring->entrycnt);
		}
465 466 467 468 469 470 471
		default:
			assert(0);  /* this shouldn't happen */
	}

	return 0;  /* pacify compiler */
}

472
/**
473 474
 * Frees the ring structure and its added nodes, leaves the referenced
 * servers untouched.
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
 */
void
ch_free(ch_ring *ring)
{
	ch_ring_entry *deletes = NULL;
	ch_ring_entry *w = NULL;

	for (; ring->entries != NULL; ring->entries = ring->entries->next) {
		if (ring->entries->malloced) {
			if (deletes == NULL) {
				w = deletes = ring->entries;
			} else {
				w = w->next = ring->entries;
			}
		}
	}

Bernd Zeimetz's avatar
Bernd Zeimetz committed
492 493 494 495 496 497 498
	if (w != NULL) {
		w->next = NULL;
		while (deletes != NULL) {
			w = deletes->next;
			free(deletes);
			deletes = w;
		}
499 500
	}

501 502 503
	if (ring->entrylist != NULL)
		free(ring->entrylist);

504 505
	free(ring);
}