DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Mercurial (7ac42b6b5ee8)

VCS Links

Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 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 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 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 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 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 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 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 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Weave Load Test.
 *
 * The Initial Developer of the Original Code is Mozilla.
 * Portions created by the Initial Developer are Copyright (C) 2009
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *  Michael Hanson <mhanson@mozilla.com>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <curl/curl.h>
#include <curl/easy.h>
#include <pthread.h>
#include <sys/time.h>

// Parameters for the run; all can be overridden with command-line args
int g_average_size = 3300;
int g_size_range = 3100;
int g_done = 0;
char *gFrontEndURLBase = NULL;
char *gHostPattern = NULL;
int gHostCount = 0;
int gVerbose = 0;

#define PASSWORD "Hr258$214dvv"

// Protect access to the stats array
pthread_mutex_t g_stats_mutex;

// Functions that simulate some piece of user action
void data_upload(CURL *curl, char *username, char *collection, int dataSize);
void check_all_collections_freshness(CURL *curl, char *username);
int create_new_user(CURL *curl, char *adminServer, char *username);

// User tracking globals: as we create users, we keep their IDs in an array
pthread_mutex_t g_userid_mutex;
unsigned int *g_userids = NULL;
unsigned int g_num_user_ids = 0;
unsigned int g_userid_array_size = 0;

// We'll go up to 10 million users before we cycle
#define MAX_USER_IDS 1024 * 1024 * 10

// A generic buffer struct
typedef struct
{
	char *buf;
	int len;
	int offset;
} Buffer;

// The global Stats struct, updated periodically
struct 
{
	unsigned long targetNumWrites;

	unsigned long total503s;
	unsigned long sleepingCount;

	unsigned long startTime; // total stats
	unsigned long transactionsDone;
	unsigned long createsDone;
	unsigned long writesDone;
	unsigned long readsDone;

	unsigned long mostRecentSampleTime; // stats on a per-second basis
	unsigned long mostRecentTotal;
	unsigned long mostRecentReportTime;

	unsigned long minuteSampleStart; // stats on a per-minute basis
	unsigned long minuteTotal;

} Stats;

// Called periodically from worker threads.  Updates statistics,
// and reports status once a second.
void update_stats(int createCount, int writeCount, int readCount)
{
	pthread_mutex_lock(&g_stats_mutex);

	struct timeval tv;
	gettimeofday(&tv, NULL);
	unsigned long now = tv.tv_sec * 1000000 + tv.tv_usec;
	Stats.mostRecentSampleTime = now;

	int howManyMore = createCount + writeCount + readCount;
	Stats.readsDone += readCount;
	Stats.writesDone += writeCount;
	Stats.createsDone += createCount;
	Stats.transactionsDone += howManyMore;
	Stats.mostRecentTotal += howManyMore;
	Stats.minuteTotal += howManyMore;

	if (Stats.mostRecentReportTime == 0) {
		Stats.mostRecentReportTime = now;
	} else if (now - Stats.mostRecentReportTime > 1000000) { // 1 second interval:

		unsigned long sampleWindow = now - Stats.mostRecentReportTime;
		unsigned long totalTime = now - Stats.startTime;
		double transactionsPerSecond = Stats.transactionsDone / (totalTime / 1000000.0);
		double transactionsPerSecondWindow = Stats.mostRecentTotal / (sampleWindow / 1000000.0);
		
		char timeBuf[256];
		strftime(timeBuf, 256, "%Y-%m-%d %H:%M:%S", localtime(&tv.tv_sec));
		
		char *label = (Stats.targetNumWrites > 0) ? " writes": " actions";
		
		printf("%s %ld%10s: %10g%10g%10g%10g%10g%10g%10ld/%ld (%ld%%) %ld sleeping\n", 
			timeBuf, 
			Stats.targetNumWrites > 0 ? Stats.writesDone : Stats.transactionsDone,
			label,
			
			transactionsPerSecond, 
			Stats.minuteTotal / ((now - Stats.minuteSampleStart) / 1000000.0),
			transactionsPerSecondWindow,

			Stats.createsDone / (totalTime / 1000000.0), 
			Stats.writesDone/ (totalTime / 1000000.0), 
			Stats.readsDone/ (totalTime / 1000000.0),

			Stats.total503s, 
			Stats.transactionsDone, 
			Stats.total503s * 100 / Stats.transactionsDone,
			Stats.sleepingCount);		
			
		fflush(stdout);
		Stats.mostRecentReportTime = now;
		Stats.mostRecentTotal = 0;
	}

	if (now - Stats.minuteSampleStart > 60000000) {
		Stats.minuteSampleStart = now;
		Stats.minuteTotal = 0;
		printf("  %d users created\n", g_num_user_ids);
		printf("%24s%20s%10s%10s%10s%10s%10s%16s\n", "", "Total", "Minute", "Instant", "Create", "Write", "Read", "503s/Total");
		fflush(stdout);
	}
	pthread_mutex_unlock(&g_stats_mutex);
}

// Called when a thread gets a 503; updates the "currently sleeping" counter
void increase503andSleepCount()
{
	pthread_mutex_lock(&g_stats_mutex);
	Stats.total503s++;
	Stats.sleepingCount++;
	pthread_mutex_unlock(&g_stats_mutex);
}

// Called when a thread stops sleeping
void decreaseSleepCount()
{
	pthread_mutex_lock(&g_stats_mutex);
	Stats.sleepingCount--;
	pthread_mutex_unlock(&g_stats_mutex);
}

// Helper function to consume responses silently
size_t silent_respose_consumer( void *ptr, size_t size, size_t nmemb, void *stream)
{
	return size*nmemb;
}

// Helper function to buffer responses
size_t buffer_save_fn( void *ptr, size_t size, size_t nmemb, void *stream)
{
	Buffer *buf = (Buffer*)stream;
	if (buf->offset + size*nmemb > buf->len) {// uh oh, out of room
		int remaining = buf->len - buf->offset;
		memcpy(buf->buf + buf->offset, ptr, remaining);
		buf->offset += remaining;
		buf->buf[buf->offset-1] = 0;
		return remaining;
	
	} else {
		memcpy(buf->buf + buf->offset, ptr, size*nmemb);
		buf->offset += size*nmemb;
		buf->buf[buf->offset] = 0;
		return size*nmemb;
	}
}

// Helper function to write a buffer into a request
size_t buffer_read_fn( void *ptr, size_t size, size_t nmemb, void *stream)
{
	Buffer *buf = (Buffer*)stream;

	if (buf->offset + buf->len < size*nmemb) { // we'll finish this time
		int left = buf->len - buf->offset;
		memcpy(ptr, buf->buf + buf->offset, left);
		buf->offset = buf->len;
		return left;
	} else {
		memcpy(ptr, buf->buf + buf->offset, size*nmemb);
		buf->offset += size*nmemb;
		return size*nmemb;
	}
}

// Add a user ID to the array atomically
void add_user_id(unsigned int uid)
{
	pthread_mutex_lock(&g_userid_mutex);
	if (g_num_user_ids < MAX_USER_IDS) {
		if (g_num_user_ids == g_userid_array_size) {
			g_userids = (unsigned int*)realloc(g_userids, sizeof(unsigned int) * (g_userid_array_size + 65536));
			g_userid_array_size += 65536;
		}	
		g_userids[g_num_user_ids++] = uid;
	}	
	pthread_mutex_unlock(&g_userid_mutex);
}

// Get a random user ID, or, if none are available, sleep a bit
unsigned int get_random_user_id()
{
	while (g_num_user_ids == 0) sleep(1);
	
	unsigned int idx = ((unsigned int)rand()) % g_num_user_ids;
	pthread_mutex_lock(&g_userid_mutex);
	unsigned int ret = g_userids[idx];
	pthread_mutex_unlock(&g_userid_mutex);
	return ret;
}

// This thread creates new users
void *create_worker_thread(void *arg)
{
	unsigned long user_base = rand() % 10000000;
	unsigned long user_creation_index = user_base;
	
	int createCount = 0, writeCount = 0, rc = 0;
	
	// Commented-out bits are to calculate latency.
	
/*	Timer creationTimer, storageNodeGetTimer, storageNodeGetTimer2, writeTimer;
	initTimer(&creationTimer);
	initTimer(&storageNodeGetTimer);
	initTimer(&writeTimer);
	initTimer(&storageNodeGetTimer2);*/
	
	while (!g_done) {
		CURL *curl = curl_easy_init();
		char username[32];
		
//		snprintf(username, 32, "user%09d", user_creation_index++);
		snprintf(username, 32, "%lu", user_creation_index++);
//		startTimer(&creationTimer);
		rc = create_new_user(curl, gFrontEndURLBase, username);
//		stopTimer(&creationTimer);
		if (rc == 0)
		{
			curl_easy_cleanup(curl);
			curl = curl_easy_init();
//			startTimer(&storageNodeGetTimer);
			rc = get_storage_node(curl, gFrontEndURLBase, username);
//			stopTimer(&storageNodeGetTimer);

			if (rc == 0)
			{
				// Put some data in there
				curl_easy_cleanup(curl);
				curl = curl_easy_init();
				char *table = "history";
				int size = g_average_size + (((unsigned int)rand()) % g_size_range) - g_size_range/2;
				if (size < 0) size = 0;
				
//				startTimer(&writeTimer);
				data_upload(curl, username, table, size);
//				stopTimer(&writeTimer);
				add_user_id(user_creation_index-1);
				writeCount++;

			}
			createCount++;
		}
		curl_easy_cleanup(curl);		
		if ((createCount % 10) == 0 && createCount != 0) {
//		if (createCount != 0) {
			update_stats(createCount, writeCount, 0);
/*			printf("Timers (per action): Creation %ld  StorageNodeLookup %ld   Write %ld  2ndStorageNodeLookup %ld\n",
				getTotalTime(&creationTimer) / createCount,
				getTotalTime(&storageNodeGetTimer) / createCount,
				getTotalTime(&writeTimer) / writeCount, 
				getTotalTime(&storageNodeGetTimer2) / createCount);*/
/*			initTimer(&creationTimer);
			initTimer(&storageNodeGetTimer);
			initTimer(&writeTimer);*/

			createCount = writeCount = 0;
		}
	}
	return NULL;
}

// This thread reads data
void *read_worker_thread(void *arg)
{
	int readCount =0;
	while (!g_done) {
		CURL *curl = curl_easy_init();
		char username[32];
		
		unsigned int uid = get_random_user_id();
		snprintf(username, 32, "%u", uid);
		check_all_collections_freshness(curl, username);		
		readCount++;
		curl_easy_cleanup(curl);

		if ((readCount % 10) == 0 && readCount != 0) {
			update_stats(0,0, readCount*7);
			readCount=0;
		}
	}

	return NULL;
}


// This thread writes data into random tables for the created users
void *write_worker_thread(void *arg)
{
	// From an access log in mid-October 2009, we believe the POST loading on these
	// is as follows {.45, .268, .137, .121, .098, .008, .003};

	int table_loading[] = {45, 27, 13, 12, 1, 1, 1};
	char *tables[] = {"tabs", "history", "bookmarks", "forms", "prefs", "passwords", "clients"};
	int NUM_COLLECTIONS = 7;
	int collection_lookup[100];// used to pick a random collection to insert into...
	int i, ptr=0;
	for (i=0;i<100;i++) {
		if (table_loading[ptr] == 0) ptr++;
		collection_lookup[i] = ptr;
		table_loading[ptr]--;
	}

	int writeCount = 0;
	while (!g_done) {
		CURL *curl = curl_easy_init();
		char username[32];
	
		unsigned int uid = get_random_user_id();
		snprintf(username, 32, "%u", uid);
		char *table = tables[collection_lookup[((unsigned int)rand()) % 100]];
		int size = g_average_size + (((unsigned int)rand()) % g_size_range) - g_size_range/2;
		if (size < 0) size = 0;

		data_upload(curl, username, table, size);
		writeCount++;

		curl_easy_cleanup(curl);
		
		if ((writeCount % 100) == 0 && writeCount != 0) {
			update_stats(0, writeCount, 0);
			writeCount=0;
		}

		if (Stats.writesDone >= Stats.targetNumWrites) {
			g_done = 1;
			break;
		}
	}
	if ((writeCount % 100) == 0 && writeCount != 0) {
		update_stats(0, writeCount, 0);
		writeCount=0;
	}
	return NULL;
}


int create_new_user(CURL *curl, char *adminServer, char *username)
{
	int result =1;
 
	// create an account
	char urlBuf[256];
	snprintf(urlBuf, 256, "%s/user/1/%s/", adminServer, username);
	// https://server/pathname/version/username/ 

	CURLcode rc;
	rc = curl_easy_setopt(curl, CURLOPT_URL, urlBuf);
	if (rc != 0) {
		fprintf(stderr, "Error: error code %d on CURLOPT_URL\n", rc);
		return;
	}

	// Read the response: it should contain the username on success
	rc = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, buffer_save_fn);
	Buffer outputBuffer;
	outputBuffer.buf = malloc(4096);
	outputBuffer.buf[0] = 0;
	outputBuffer.len = 4096;
	outputBuffer.offset = 0;
	
	rc = curl_easy_setopt(curl, CURLOPT_FILE, &outputBuffer);
	
	rc = curl_easy_setopt(curl, CURLOPT_PUT, 1);
	Buffer inputBuffer;
	char uploadBuffer[1024];
	inputBuffer.buf = uploadBuffer;
	inputBuffer.offset = 0;
	inputBuffer.len = snprintf(uploadBuffer, 1024, "{\"password\":\"%s\", \"email\":\"weavetest_%s@mozilla.com\"}", PASSWORD, username);

	rc = curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);// I'm not sure what this does.  But the sample code does it.
	if (rc != 0) {
		fprintf(stderr, "Error: error code %d on CURLOPT_UPLOAD\n", rc);
		goto done;
	}	
	curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
	curl_easy_setopt(curl, CURLOPT_READDATA, &inputBuffer);
	curl_easy_setopt(curl, CURLOPT_READFUNCTION, buffer_read_fn);

	// Off we go:
	//printf("Trying to create user %s\n", username);
	rc = curl_easy_perform(curl);
	
	if (rc != 0) {
		fprintf(stderr, "Error: code %d on curl_easy_perform\n", rc);
		goto done;
	}	
	long responseCode;
	curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &responseCode);
	if (rc != 0) {
		fprintf(stderr, "Error: code %d on curl_easy_getinfo\n", rc);
		goto done;
	}
	if (responseCode != 200) {
		fprintf(stderr, "Error: response code %ld while creating a new user\n", responseCode);
	}

	// Take a look in our output buffer:
	char expected[128];
	snprintf(expected, 128, "\"%s\"", username);
	if (strcmp(expected, outputBuffer.buf)) {
		fprintf(stderr, "Error: response body for user creation was '%s' instead of '%s' as expected\n", outputBuffer.buf, expected);
	} else {
		//printf("That seemed to work.\n");
		result = 0;
	}
	
	done:
		free(outputBuffer.buf);
		return result;
}

int get_storage_node(CURL *curl, char *adminServer, char *username)
{
	int result =1;
 
	// create an account
	char urlBuf[256];
	snprintf(urlBuf, 256, "%s/user/1/%s/node/weave", adminServer, username);

	CURLcode rc;
	rc = curl_easy_setopt(curl, CURLOPT_URL, urlBuf);
	if (rc != 0) {
		fprintf(stderr, "Error: error code %d on CURLOPT_URL\n", rc);
		return;
	}

	char authBuf[32];
	snprintf(authBuf, 32, "%s:%s", username, PASSWORD);
	rc = curl_easy_setopt(curl, CURLOPT_USERPWD, authBuf);
	if (rc != 0) {
		fprintf(stderr, "Error: error code %d on CURLOPT_USERPWD\n", rc);
		return;
	}		

	// Read the response: it should contain the storage node on success
	rc = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, buffer_save_fn);
	Buffer outputBuffer;
	char stackBuffer[1024];
	outputBuffer.buf = stackBuffer;
	outputBuffer.buf[0] = 0;
	outputBuffer.len = 1024;
	outputBuffer.offset = 0;
	rc = curl_easy_setopt(curl, CURLOPT_FILE, &outputBuffer);
	
	rc = curl_easy_perform(curl);
	if (rc != 0) {
		fprintf(stderr, "Error: code %d on curl_easy_perform\n", rc);
		return 1;
	}	
	long responseCode;
	curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &responseCode);
	if (rc != 0) {
		fprintf(stderr, "Error: code %d on curl_easy_getinfo\n", rc);
		return 1;
	}
	if (responseCode != 200) {
		fprintf(stderr, "Error: response code %ld while creating a new user\n", responseCode);
		return 1;
	}

	// Take a look in our output buffer
/*	char urlBuf[128];
	snprintf(urlBuf, 128, "http://%s/0.5/%s/storage/%s", gFrontEndURLBase, username, collection);

	if (strcmp(, outputBuffer.buf)) {
		fprintf(stderr, "Error: response body for user creation was '%s' instead of '%s' as expected\n", outputBuffer.buf, username);
	} else {
		printf("That seemed to work.\n");
		result = 0;
	}
	*/
	//printf("Got \n\n%s\n\n\n", outputBuffer.buf);
	return 0;
}

int doAuthenticatedGet(CURL *curl, char *username, char *url, char *targetBuffer, int targetBufferLen)
{
	int retryCount = 0;
	while (retryCount < 10) {
		// loop to handle 503s; keep trying.
		CURLcode rc;
		rc = curl_easy_setopt(curl, CURLOPT_URL, url);
		if (rc != 0) {
			fprintf(stderr, "Error: error code %d on CURLOPT_URL\n", rc);
			return 1;
		}

		// Force Host header if needed
		struct curl_slist *slist = NULL;
		char formatBuf[32], headerBuf[128];
		if (gHostPattern) {
		  snprintf(formatBuf, 32, "Host: %s", gHostPattern);
		  snprintf(headerBuf, 128, formatBuf, atoi(username) % gHostCount);
		  curl_slist_append(slist, headerBuf);
		  curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
		}

		char authBuf[32];
		snprintf(authBuf, 32, "%s:%s", username, PASSWORD);
		rc = curl_easy_setopt(curl, CURLOPT_USERPWD, authBuf);
		if (rc != 0) {
		  fprintf(stderr, "Error: error code %d on CURLOPT_USERPWD\n", rc);
		  if (slist) curl_slist_free_all(slist);
		  return 1;
		}		

		Buffer outputBuffer;
		if (targetBuffer) {
			outputBuffer.buf = targetBuffer;
			outputBuffer.buf[0] = 0;
			outputBuffer.len = targetBufferLen;
			outputBuffer.offset = 0;
			curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, buffer_save_fn);
			curl_easy_setopt(curl, CURLOPT_FILE, &outputBuffer);
		} else {
			curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, silent_respose_consumer);
		}

		rc = curl_easy_perform(curl);
		if (rc != 0) {
			fprintf(stderr, "Error: code %d on curl_easy_perform\n", rc);
			if (slist) curl_slist_free_all(slist);
			return;
		}	
		long responseCode;
		curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &responseCode);
		if (rc != 0) {
			fprintf(stderr, "Error: code %d on curl_easy_getinfo\n", rc);
			if (slist) curl_slist_free_all(slist);
			return 1;
		}
		if (responseCode == 503) {
			increase503andSleepCount();
			sleep(1);
			decreaseSleepCount();
		} else if (responseCode != 200) {
			printf("Error %ld on GET %s\n", responseCode, url);
			if (slist) curl_slist_free_all(slist);
			return 1;
		} else {// happy day, off we go.
		  if (slist) curl_slist_free_all(slist);
			return 0;
		}
		retryCount++;
		if (slist) curl_slist_free_all(slist);
	}
	printf("10 failures while trying to GET %s: giving up\n", url);
	// too many 503s
	return 1;
}


void doFreshnessGet(CURL *curl, char *username, char *collection)
{
	char urlBuf[256];
	time_t t = time(NULL);	
	snprintf(urlBuf, 256, "%s/1.0/%s/storage/%s/?newer=%lu&full=1&sort=index", 
		gFrontEndURLBase, username, collection, (long)t - 300);

	doAuthenticatedGet(curl, username, urlBuf, NULL, 0);
}

void check_all_collections_freshness(CURL *curl, char *username)
{
	
/*
char urlBuf[256];
	snprintf(urlBuf, 256, "%s/1.0/%s/info/collections", gFrontEndURLBase, username);
	char resultBuffer[1024];
	if (!doAuthenticatedGet(curl, username, urlBuf, resultBuffer, 1024))
	{
		// looks like: {"history":1266981783.61,"tabs":1266981781.18,"prefs":1266981781.05,"forms":1266981778.19,"bookmarks":1266981270.71,"clients":1266979500.74,"passwords":1266979172.86}
		// json_object *collectionTimestamps;
		// collectionTimestamps = json_tokener_parse(resultBuffer);
		// lh_table* json_object_get_object
		return;
	} else {
		return;
	}
*/
	doFreshnessGet(curl, username, "clients");
	doFreshnessGet(curl, username, "tabs");
	doFreshnessGet(curl, username, "forms");
	doFreshnessGet(curl, username, "prefs");
	doFreshnessGet(curl, username, "history");
	doFreshnessGet(curl, username, "bookmarks");
	doFreshnessGet(curl, username, "passwords");
	// we could also do meta/global and crypto/[collection]
}


// Performs an upload using the given fields - generates a random payload and data key.
void data_upload(CURL *curl, char *username, char *collection, int dataSize)
{
	char *bodyBuf = NULL;
	char urlBuf[128];

	snprintf(urlBuf, 128, "%s/1.0/%s/storage/%s", gFrontEndURLBase, username, collection);
	CURLcode rc;
	rc = curl_easy_setopt(curl, CURLOPT_URL, urlBuf);
	if (rc != 0) {
		fprintf(stderr, "Error: error code %d on CURLOPT_URL\n", rc);
		goto done;
	}
	
	// Force Host header if needed
	struct curl_slist *slist = NULL;
	char formatBuf[32], headerBuf[128];
	if (gHostPattern) {
	  snprintf(formatBuf, 32, "Host: %s", gHostPattern);
	  snprintf(headerBuf, 128, formatBuf, atoi(username) % gHostCount);
	  slist = curl_slist_append(slist, headerBuf);
	  curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
	  if (gVerbose) printf("Overriding host header with %s\n", headerBuf);
	}

	int bufLen = dataSize + 256;
	bodyBuf = malloc(bufLen); // TODO: replace this with a streaming payload callback
	char id[64];
	snprintf(id, 64, "%010d-4477-1640-b6b2-%010d", (unsigned int)rand(), (unsigned int)rand());
	char *ptr = bodyBuf;
	ptr += snprintf(bodyBuf, bufLen, "[{\"id\":\"%s]\",\"payload\":\"{\\\"encryption\\\":\\\"https://someStorageNode.services.mozilla.com/1.0/%s/storage/crypto/history\\\",\\\"ciphertext\\\":\\\"",
		id, username, collection);
	memset(ptr, 'A', dataSize);
	ptr += dataSize;
	ptr += snprintf(ptr, bodyBuf + bufLen - ptr, "\\\"}\"}]");
	
	curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
	rc = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, silent_respose_consumer);
	rc = curl_easy_setopt(curl, CURLOPT_POST, 1);
	if (rc != 0) {
		fprintf(stderr, "Error: error code %d on CURLOPT_POST\n", rc);
		goto done;
	}	
	rc = curl_easy_setopt(curl, CURLOPT_POSTFIELDS, bodyBuf);
	if (rc != 0) {
		fprintf(stderr, "Error: error code %d on CURLOPT_POSTFIELDS\n", rc);
		goto done;
	}	
	rc = curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, ptr - bodyBuf);
	if (rc != 0) {
		fprintf(stderr, "Error: error code %d on CURLOPT_POSTFIELDSIZE\n", rc);
		goto done;
	}		
	char authBuf[32];
	snprintf(authBuf, 32, "%s:%s", username, PASSWORD);
	rc = curl_easy_setopt(curl, CURLOPT_USERPWD, authBuf);
	if (rc != 0) {
		fprintf(stderr, "Error: error code %d on CURLOPT_USERPWD\n", rc);
		goto done;
	}		
	if (gVerbose) {
	  time_t t;
	  time(&t);
	  char timebuf[256];
	  strftime(timebuf, 256, "%y/%m/%d %H:%M:%S", gmtime(&t));
	  printf("%s POST %s%s%s/storage/%s\n", timebuf, gHostPattern?headerBuf:"", gHostPattern?" ":"", 
		 username, collection);
	}
	rc = curl_easy_perform(curl);
	if (rc != 0) {
		fprintf(stderr, "Error: code %d on curl_easy_perform\n", rc);
		goto done;
	}	
	long responseCode;
	curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &responseCode);
	if (rc != 0) {
		fprintf(stderr, "Error: code %d on curl_easy_getinfo\n", rc);
		goto done;
	}
	if (responseCode != 200) {
	  if (responseCode == 503) {
	    increase503andSleepCount();
	    sleep(1);
	    decreaseSleepCount();
	  }
	  else
	    {
	      printf("While writing, got %ld\n", responseCode);
	    }
	}
 done:
	if (bodyBuf) free(bodyBuf);
	if (slist) curl_slist_free_all(slist);
}


void printUsage()
{
	printf("weavetest\n\t-c <num_create_threads\n\t-w <num_write_threads>\n\t-r <num_read_threads>\n\t-s <average_payload_size>\n\t-z <payload_size_range>\n\t-W <target_num_writes>\n\t-U <server-url>  (required)\n\t-H <host-pattern> <printf-style host format string> (optional)\n\t-C <host-count> <number of hosts to be rotated through with -H>\n");
	printf("\nAt least one of -c, -r, or -w must be provided.\n");
	printf("Actual payload size will be average size + rand(size_range) - size_range/2\n");
	printf("Default payload size is 3300 with a range of 3100\n");
	printf("\n");
	printf("The statistics are updated by each thread as it completes 100 requests;\n");
	printf("  there will be a delay at startup before the threads make their first report.\n");
}


int main (int argc, const char * argv[]) 
{
	int write_thread_ct = 0, read_thread_ct = 0, create_thread_ct= 0;
	int num_writes_count = 0;
	char c;
	
	while ((c = getopt(argc, (char**)argv, "c:w:W:r:U:H:C:s:z:hv")) != -1) {
		switch(c) {
		case 'c':
			create_thread_ct = atoi(optarg);
			break;
		case 'w':
			write_thread_ct = atoi(optarg);
			break;
		case 'W':
			num_writes_count= atoi(optarg);
			break;
		case 'r':
			read_thread_ct = atoi(optarg);
			break;
		case 'U':
			gFrontEndURLBase = optarg;
			break;
		case 'H':
		  gHostPattern = optarg;
		  break;
		case 'C':
		  gHostCount = atoi(optarg);
		  break;
		case 's':
			g_average_size = atoi(optarg);
			break;
		case 'z':
			g_size_range = atoi(optarg);
			break;
		case 'h':
			printUsage();
			exit(0);
		case 'v':
		  gVerbose = 1;
		}
	}
	if (write_thread_ct == 0 && read_thread_ct == 0 && create_thread_ct == 0)
	{
		fprintf(stderr, "Error: you must specify at least one of -c, -r, or -w.  Use -h for help.\n");
		exit(1);
	}
	if (gFrontEndURLBase == NULL) {
		fprintf(stderr, "Error: you must specify a server URL (e.g. http://pm-weave06.mozilla.org) with -U\n");
		exit(1);	
	}
	if (gHostPattern != NULL && gHostCount == 0) {
	  fprintf(stderr, "Error: You must provide a count with -C if you use -H.\n");
	  exit(1);
	}
	if (gHostPattern != NULL && create_thread_ct != 0) {
	  fprintf(stderr, "Error: Sorry, you can't use -H with -c.  I've only implemented integer host rotation for when I control the userIDs.\n");
	  exit(1);
	}

	memset(&Stats, 0, sizeof(Stats));

	pthread_t *create_threads = (pthread_t*)malloc(sizeof(pthread_t) * create_thread_ct);
	pthread_t *read_threads = (pthread_t*)malloc(sizeof(pthread_t) * read_thread_ct);
	pthread_t *write_threads = (pthread_t*)malloc(sizeof(pthread_t) * write_thread_ct);
	int i;
	
	int rc = pthread_mutex_init(&g_stats_mutex, NULL);
	if (rc != 0) {
			fprintf(stderr, "Couldn't initialize stats mutex\n");
			exit(1);
	}
	rc = pthread_mutex_init(&g_userid_mutex, NULL);
	if (rc != 0) {
			fprintf(stderr, "Couldn't initialize userid mutex\n");
			exit(1);
	}

	
	struct timeval tv;
	gettimeofday(&tv, NULL);
	unsigned long startTime = (unsigned long)tv.tv_sec * 1000000 + tv.tv_usec;
	srand(tv.tv_usec);
	Stats.startTime = startTime;

	if (num_writes_count) {
		Stats.targetNumWrites = num_writes_count;
	}

		
	for (i=0;i<create_thread_ct;i++) {
		int rc = pthread_create(&create_threads[i], NULL, create_worker_thread, NULL);
		if (rc != 0) {
			fprintf(stderr, "pthread_create error: %d\n", rc);
			exit(1);
		}
	}
	if (create_thread_ct == 0) {
		int numUsers = 10000;
		int i;
		printf("No create threads: rotating through %d integer user IDs.\n", numUsers);
		g_num_user_ids = numUsers;
		g_userids = (unsigned int*)realloc(g_userids, sizeof(unsigned int) * (numUsers));
		g_userid_array_size = numUsers;
		for (i=0;i<numUsers;i++) {
			g_userids[i] = i+1;
		}
	}	

	for (i=0;i<write_thread_ct;i++) {
		int rc = pthread_create(&write_threads[i], NULL, write_worker_thread, NULL);
		if (rc != 0) {
			fprintf(stderr, "pthread_create error: %d\n", rc);
			exit(1);
		}
	}
	for (i=0;i<read_thread_ct;i++) {
		int rc = pthread_create(&read_threads[i], NULL, read_worker_thread, NULL);
		if (rc != 0) {
			fprintf(stderr, "pthread_create error: %d\n", rc);
			exit(1);
		}
	}

	for (i=0;i<create_thread_ct;i++) {
		void *retVal = NULL;
		int rc = pthread_join(create_threads[i], &retVal);
	}
	for (i=0;i<write_thread_ct;i++) {
		void *retVal = NULL;
		int rc = pthread_join(write_threads[i], &retVal);
	}
	for (i=0;i<read_thread_ct;i++) {
		void *retVal = NULL;
		int rc = pthread_join(read_threads[i], &retVal);
	}

	return 0;
}