Esempio n. 1
0
void StallTest(bool startTest,char* label)
{
	static  clock_t start;
	if (startTest) start = ElapsedMilliseconds();
	else
	{
		clock_t now = ElapsedMilliseconds();
		if ((now-start) > 40) 
			printf("%d %s\r\n",(unsigned int)(now-start),label);
		//else printf("ok %d %s\r\n",now-start,label);
	}
}
Esempio n. 2
0
void StopWatch::PrintResult() const
{
	RETURN_IF_FALSE(mEnabled);
	float dt = ElapsedMilliseconds();

	HeapString str("***");
	if (!mName.IsEmpty())
	{
		str.AppendFormat("{}\t", mName.Buffer());
	}

	if (mRunTimes > 0 && dt != 0)
	{
		str.AppendFormat("{} / {} = {}", dt, mRunTimes, dt / mRunTimes);
	}

	str += '\n';
	Log::Info(str);
}
Esempio n. 3
0
static void* MainChatbotServer()
{
	sprintf(serverLogfileName,"LOGS/serverlog%d.txt",port);
	ServerStartup(); //   get initial control over the mutex so we can start. - on linux if thread dies, we must reacquire here 
	// we now own the chatlock
	clock_t lastTime = ElapsedMilliseconds(); 

	if (setjmp(scriptJump[MAIN_RECOVERY])) // crashes come back to here
	{
		printf("***Server exception\r\n");
		ReportBug("***Server exception\r\n");
#ifdef WIN32
		char* bad = GetUserVariable("$crashmsg");
		if (*bad) strcpy(outputFeed,bad);
		else strcpy(outputFeed,"Hey, sorry. I forgot what I was thinking about.");
		ServerTransferDataToClient("");
#endif
		ResetBuffers(); //   in the event of a trapped bug, return here, we will still own the chatlock
	}
    chatbotExists = true;   //  if a client can get the chatlock now, he will be happy
	Log(SERVERLOG,"Server ready\r\n");
	printf("Server ready: %s\r\n",serverLogfileName);
#ifdef WIN32
 _try { // catch crashes in windows
#endif
	int counter = 0;
	while (1)
	{
		ServerGetChatLock();
		startServerTime = ElapsedMilliseconds(); 

		// chatlock mutex controls whether server is processing data or client can hand server data.
		// That we now have it means a client has data for us.
		// we own the chatLock again from here on so no new client can try to pass in data. 
		// CLIENT has passed server in globals:  clientBuffer (ip,user,bot,message)
		// We will send back his answer in clientBuffer, overwriting it.
		char user[MAX_WORD_SIZE];
		char bot[MAX_WORD_SIZE];
		char* ip = clientBuffer;
		char* ptr = ip;
		// incoming is 4 strings together:  ip, username, botname, message
		ptr += strlen(ip) + 1;	// ptr to username
		strcpy(user,ptr); // allow user var to be overwriteable, hence a copy
		ptr += strlen(ptr) + 1; // ptr to botname
		strcpy(bot,ptr);
		ptr += strlen(ptr) + 1; // ptr to message
		strcpy(inputFeed,ptr); // xfer user message to our incoming feed
		echo = false;

		PerformChat(user,bot,inputFeed,ip,outputFeed);	// this takes however long it takes, exclusive control of chatbot.
#ifdef STATSERVER
		clock_t now = ElapsedMilliseconds();
		if ( (now / 1000) > (lastTime / 1000)) // starting different second
		{
			printf("%d\r\n",counter);
			counter = 0;
			lastTime = now; 
		}
		++counter;
		if ((now-startServerTime) > 2000) 
		{
			printf("Compute Stall? %d\r\n",now-startServerTime);
		}
#endif		
	ServerTransferDataToClient(priorMessage);
	}
#ifdef WIN32
		}_except (true) {
			ReportBug("crash\r\n"); Crash();}
#endif
	return NULL;
}
Esempio n. 4
0
static void* HandleTCPClient(void *sock1)  // individual client, data on STACK... might overflow...
{
	clock_t starttime = ElapsedMilliseconds(); 
	char* memory = (char*) malloc(2*SERVERTRANSERSIZE+2); // our data in 1st chunk, his reply info in 2nd
	if (!memory) return NULL; // ignore him if we run out of memory
	char* output = memory+SERVERTRANSERSIZE;
	*output = 0;
	char* buffer;
	TCPSocket *sock = (TCPSocket*) sock1;
	char IP[20];
    try {
        strcpy(memory,sock->getForeignAddress().c_str());	// get IP address
		strcpy(IP,memory);
		buffer = memory + strlen(memory) + 1;				// use this space after IP for messaging
    } catch (SocketException e)
	{ 
		ReportBug("Socket errx"); cerr << "Unable to get port" << endl;
		return Done(sock,memory);
	}
	char timeout = ' ';

	char userName[500];
	*userName = 0;
	char* user;
	char* bot;
	char* msg;
	char* prior = "";
	// A user name with a . in front of it means tie it with IP address so it remains unique 
	try{
		unsigned int len = sock->recv(buffer, SERVERTRANSERSIZE-50); // leave ip address in front alone
		memset(buffer+len,0,3); 
	
		user = buffer;
		bot = user + strlen(user) + 1;
		msg = bot + strlen(bot) + 1;

		if (!*user)
		{
			if (*bot == '1' && bot[1] == 0) // echo test to prove server running (generates no log traces)
			{
				strcpy(output,"1");
				return Done(sock,memory);
			}

			ReportBug("%s %s bot: %s msg: %s  NO USER ID \r\n",IP,GetTimeInfo()+SKIPWEEKDAY,bot,msg);
			strcpy(output,"[you have no user id]\r\n"); 
			return Done(sock,memory);
		}

		if (Blacklisted(memory,user)) // if he is blacklisted, we ignore him
		{
			PartialLogin(user,memory); // sets LOG file so we record his messages
			Log(SERVERLOG,"%s %s/%s %s msg: %s  BLOCKED \r\n",IP,user,bot,GetTimeInfo()+SKIPWEEKDAY,msg);
			strcpy(output,"[ignoring you.]\r\n"); //   response is JUST this
 			Log(STDUSERLOG,"blocked %s  =>  %s\r\n",msg,output);
			return Done(sock,memory);
		}
		strcpy(userName,user);

		// wait to get attention of chatbot server, timeout if doesnt come soon enough

		bool ready = ClientGetChatLock( ANSWERTIMELIMIT - (ElapsedMilliseconds() - starttime) ); // chatlock  ...
		if (!ready)  // if it takes to long waiting to get server attn, give up
		{
 			PartialLogin(userName,memory); // sets LOG file so we record his messages
			switch(random(4))
			{
				case 0: strcpy(output,"Hey, sorry. Had to answer the phone. What was I saying?"); break;
				case 1: strcpy(output,"Hey, sorry. There was a salesman at the door. Where were we?"); break;
				case 2: strcpy(output,"Hey, sorry. Got distracted. What did you say?"); break;
				case 3: strcpy(output,"Hey, sorry. What did you say?"); break;
			}
			Log(STDUSERLOG,"Timeout waiting for service: %s  =>  %s\r\n",msg,output);
			return Done(sock,memory);
		}

	  } catch (...)  
	  {
			ReportBug("***%s client presocket failed %s\r\n",IP,GetTimeInfo()+SKIPWEEKDAY);
 			return Done(sock,memory);
	  }
	 clock_t serverstarttime = ElapsedMilliseconds(); 
	 try{
 		chatWanted = true;	// indicate we want the chatbot server - no other client can get chatLock while this is true
		clientBuffer = memory; 
		int remain = ANSWERTIMELIMIT - (ElapsedMilliseconds() - starttime);

		if (!ClientWaitForServer(memory,msg,remain)) // release lock, loop wait for data,  and maybe we give up waiting for him
		{
			timeout = '*';
			switch(random(4))
			{
				case 0: strcpy(output,"Hey, sorry. Had to answer the phone. What was I saying?"); break;
				case 1: strcpy(output,"Hey, sorry. There was a salesman at the door. Where were we?"); break;
				case 2: strcpy(output,"Hey, sorry. Got distracted. What did you say?"); break;
				case 3: strcpy(output,"Hey, sorry. What did you say?"); break;
			}
		}
		unsigned int len = strlen(output);
		if (len) sock->send(output, len);
		prior = output + len + 1;			// bot prior message to us
} catch (...)  {
		printf("client socket fail\r\n");
		ReportBug("***%s client socket failed %s \r\n",IP,GetTimeInfo()+SKIPWEEKDAY);}
	delete sock;
	char* date = GetTimeInfo()+SKIPWEEKDAY;
	date[15] = 0;	// suppress year
	clock_t endtime = ElapsedMilliseconds(); 

	char* prior1 = prior + strlen(prior) + 1;
	int volleys = atoi(prior1);
	if (*msg) Log(SERVERLOG,"%c %s %s/%s %s time:%d/%d v:%d   msg: %s  =>  %s   <= %s\n",timeout,IP,user,bot,date, (int)(endtime - starttime),(int)(endtime - serverstarttime),volleys,msg,output,prior);
	else Log(SERVERLOG,"%c %s %s/%s %s start  =>  %s   <= %s\n",timeout,IP,user,bot,date,output,prior);
	free(memory);
#ifndef WIN32
	pthread_exit(0);
#endif
	return NULL;
}
Esempio n. 5
0
void RegressLoad()// test load for a server
{
	
	FILE* in = fopen("REGRESS/bigregress.txt","rb");
	if (!in) return;
	
	// treat each invocation as a new judge
	FILE* in1 = fopen("load.txt","rb");
	int id = 0;
	char buffer[8000];
	if (in1)
	{
		fread(buffer,1,100,in1);
		fclose(in1);
		id = atoi(buffer);
	}
	++id;
	FILE* out = fopen("load.txt","wb");
	fprintf(out,"%d\r\n",id);
	fclose(out);

	printf("\r\n\r\n** Load %d launched\r\n",id);
	char data[MAX_WORD_SIZE];
	char from[100];
	sprintf(from,"%d",id);
	char* bot = "";
	sprintf(logbuffer,"log-%s.txt",from);
	unsigned int msg = 0;
	unsigned int volleys = 0;
	unsigned int longVolleys = 0;
	unsigned int xlongVolleys = 0;

	int maxTime = 0;
	int cycleTime = 0;
	int currentCycleTime = 0;
	int avgTime = 0;

	// message to server is 3 strings-   username, botname, null (start conversation) or message
	echo = 1;
	char* ptr = data;
	strcpy(ptr,from);
	ptr += strlen(ptr) + 1;
	strcpy(ptr,bot);
	ptr += strlen(ptr) + 1;
	*buffer = 0;
	int counter = 0;
	while (1)
	{

		if (!ReadALine(revertBuffer+1,in)) break; // end of input
		// when reading from file, see if line is empty or comment
		char word[MAX_WORD_SIZE];
		char* at = SkipWhitespace(revertBuffer+1); 
		ReadCompiledWord(at,word);
		if (!*word || *word == '#' || *word == ':') continue;

		strcpy(ptr,revertBuffer+1);
		try 
		{
			unsigned int len = (ptr-data) + 1 + strlen(ptr);
			++volleys;
			clock_t start_time = ElapsedMilliseconds();

			TCPSocket *sock = new TCPSocket(serverIP, port);
			sock->send(data, len );
	
			int bytesReceived = 1;              // Bytes read on each recv()
			int totalBytesReceived = 0;         // Total bytes read
			char* base = ptr;
			while (bytesReceived > 0) 
			{
				// Receive up to the buffer size bytes from the sender
				bytesReceived = sock->recv(base, MAX_WORD_SIZE);
				totalBytesReceived += bytesReceived;
				base += bytesReceived;
			}
			clock_t end_time = ElapsedMilliseconds();
	
			delete(sock);
			*base = 0;
			int diff = end_time - start_time;
			if (diff > maxTime) maxTime = diff;
			if ( diff > 2000) ++longVolleys;
			if (diff > 5000) ++ xlongVolleys;
			currentCycleTime += diff;

			// chatbot replies this
			printf("real:%d avg:%d max:%d volley:%d 2slong:%d 5slong:%d %s => %s\r\n",diff,avgTime,maxTime,volleys,longVolleys,xlongVolleys,ptr,base);
		}
		catch(SocketException e) { printf("failed to connect to server\r\n"); exit(0);}
		if (++counter == 100) 
		{
			counter = 0;
			cycleTime = currentCycleTime;
			currentCycleTime = 0;
			avgTime = cycleTime / 100;
		}
		else msg++;
	}
}
Esempio n. 6
0
void Load()// test load for a server
{
	// treat each invocation as a new judge
	FILE* in = fopen("load.txt","rb");
	int id = 0;
	char buffer[1000];
	if (in)
	{
		fread(buffer,1,100,in);
		fclose(in);
		id = atoi(buffer);
	}
	++id;
	FILE* out = fopen("load.txt","wb");
	fprintf(out,"%d\r\n",id);
	fclose(out);

	printf("\r\n\r\n** Load %d launched\r\n",id);
	char data[MAX_WORD_SIZE];
	char from[100];
	sprintf(from,"%d",id);
	char* bot = "";
	sprintf(logbuffer,"log-%s.txt",from);
	unsigned int msg = 0;
	unsigned int volleys = 0;
	unsigned int longVolleys = 0;
	unsigned int xlongVolleys = 0;
	char* messages[] = {
		"What is an apple?",
		"What is a toy?",
		"What is an elephant?",
		"What is a pear?",
		"What is swimming?",
		"What is the meaning of life?",
		"What is a deal?",
		"What is an exercise?",
		"What is the point?",
		"Where is my toy?",
		"What is a bird?",
		"What is a tiger?",
		"What is a lion?",
		"What is a seahorse?",
		"What is a sawhorse?",
		"What is an egg?",
		"What is a dinosaur?",
		"What is a peach?",
		"What is a banana?",
		"What is a goose?",
		"What is a duck?",
		"What is a tomboy?",
		"What is purple?",
		0,
	};

	int maxTime = 0;
	int cycleTime = 0;
	int currentCycleTime = 0;
	int avgTime = 0;

	// message to server is 3 strings-   username, botname, null (start conversation) or message
	echo = 1;
	char* ptr = data;
	strcpy(ptr,from);
	ptr += strlen(ptr) + 1;
	strcpy(ptr,bot);
	ptr += strlen(ptr) + 1;
	while (1)
	{

		strcpy(ptr,messages[msg]);
		try 
		{
			unsigned int len = (ptr-data) + 1 + strlen(ptr);
			++volleys;
			clock_t start_time = ElapsedMilliseconds();

			TCPSocket *sock = new TCPSocket(serverIP, port);
			sock->send(data, len );
	
			int bytesReceived = 1;              // Bytes read on each recv()
			int totalBytesReceived = 0;         // Total bytes read
			char* base = ptr;
			while (bytesReceived > 0) 
			{
				// Receive up to the buffer size bytes from the sender
				bytesReceived = sock->recv(base, MAX_WORD_SIZE);
				totalBytesReceived += bytesReceived;
				base += bytesReceived;
			}
			clock_t end_time = ElapsedMilliseconds();
	
			delete(sock);
			*base = 0;
			int diff = end_time - start_time;
			if (diff > maxTime) maxTime = diff;
			if ( diff > 2000) ++longVolleys;
			if (diff > 5000) ++ xlongVolleys;
			currentCycleTime += diff;

			// chatbot replies this
			printf("real:%d avg:%d  max:%d   volleys:%d  2slong:%d 5slong:%d\r\n",diff,avgTime,maxTime,volleys,longVolleys,xlongVolleys);
		}
		catch(SocketException e) { printf("failed to connect to server\r\n"); exit(0);}
		if (messages[msg+1] == 0) 
		{
			msg = 0;
			cycleTime = currentCycleTime;
			currentCycleTime = 0;
			avgTime = cycleTime / 23;
		}
		else msg++;
	}
}
VOID CALLBACK TimeCheck( HWND hwnd, UINT uMsg,UINT_PTR idEvent,DWORD dwTime) // every 100 ms
{
	char c;
	static bool init = false;
	static int inputCount = 0;
	if (!init)
	{
		init = true;
	//	char word[MAX_WORD_SIZE];
	//	GetCurrentDir(word, MAX_WORD_SIZE);
		InitChatbot(computerName);
		RECT rect;
		GetClientRect(hwnd, &rect);
		InvalidateRect(hwnd, &rect, TRUE);
		strcpy(response,"Chatbot initialization complete");
	}

	static int counter = 0;
	++counter; // increament each timer interrupt, tracking how long since last key input from user
	static char lastchar = 0;
	static bool keyhit = false;
	while ((c = ReadChar())) // returns 0 if nothing found
	{
		keyhit = true; // user input seen since last output
		RECT rect;
		GetClientRect(hwnd, &rect);
		InvalidateRect(hwnd, &rect, TRUE);
		if ( c == 8) // backspace
		{
			if ( msgPtr != inputMessage) *--msgPtr = 0;
		}
		else if ( c == '\n' || c == '\r') // prepare for NEW input and get response
		{
			if (msgPtr == inputMessage) continue;	// ignore empty lines
			*msgPtr = 0;
			counter = 100;	// treat as end of input
			break;	// dont read until we have responded
		}
		else if (msgPtr == inputMessage && (c == ' ' || c == '\t' )) continue;	// ignore leading whitespace.
		else // accept new character
		{
			*msgPtr++ = c;
			lastchar = c;
			*msgPtr = 0;
		}
		counter = 0; // start time wait over again
	}

	// do we have something we want to respond to?
	bool trigger = false;
	if (counter >= 30 && *inputMessage && (lastchar == '.' || lastchar == '?' || lastchar == '!')) trigger = true; // 3 sec passed and have input ended on closer 
	else if (counter >= 70 && *inputMessage) trigger = true; // 7 seconds + have lingering input
	// or timer oob goes off
	char oob[MAX_WORD_SIZE];
	*oob = 0;
	ProcessInputDelays(oob,keyhit); 

	if (trigger || *oob)
	{
		if (*oob) strcpy(ourMainInputBuffer,oob); // priority is to alarm callback. others will be only if no user input anyway
		else  
		{
			strcpy(ourMainInputBuffer,inputMessage);
			// clear all signs of user input
			lastchar = 0;	
			*inputMessage = 0;
			msgPtr = inputMessage;
			keyhit = false;
		}

		PerformChat(loginID,computerID,ourMainInputBuffer,NULL,ourMainOutputBuffer);
		strcpy(response,ourMainOutputBuffer);
		callBackDelay = 0; // now turned off after an output
		ProcessOOB(ourMainOutputBuffer); // process relevant out of band messaging and remove

		char word[MAX_WORD_SIZE];
		char* p = SkipWhitespace(ourMainOutputBuffer);
		ReadCompiledWord(p,word);
		if (!*word) strcpy(p,"huh?"); // in case we fail to generate output

		// transmit message to user
		++inputCount;
		while (*p) 
		{
			if (SendChar(*p,p[1],inputCount)) p++; // got sent
		}
		SendChar('\n',0,inputCount);
		if (loopBackDelay) loopBackTime = ElapsedMilliseconds() + loopBackDelay; // resets every output

		// write out last sequence id
		FILE* out = fopen("sequence", "wb");
		fprintf(out,"%d",sequence);
		fclose(out);

		counter = 0;
		RECT rect;
		GetClientRect(hwnd, &rect);
		InvalidateRect(hwnd, &rect, TRUE);
	}
}
Esempio n. 8
0
float Timer::ElapsedSeconds() const { return ElapsedMilliseconds() / 1000; }