Action() { char *results = NULL; int rescnt = 0; lr_save_string("199.35.107.2","DnsServer"); // Set DNS server IP Address lr_save_string("www.merc-int.com", "Hostname"); // Set hostname to resolve // Perform DNS Query results = (char *) ms_dns_query("DnsQuery", "URL=dns://{DnsServer}", "QueryHost={Hostname}", LAST); // List all the results... (if more than one) while (*results) { rescnt++; lr_log_message( lr_eval_string("(%d) IP address for {Hostname} is %s"), rescnt, results); results = (char *) ms_dns_nextresult(results); } return 0; }
Action() { char chQuery[128]; MYSQL *Mconn; lr_load_dll("libmysql.dll"); Mconn = lr_mysql_connect(MYSQLSERVER, MYSQLUSERNAME, MYSQLPASSWORD, MYSQLDB, atoi(MYSQLPORT)); lr_save_string(lr_eval_string("{pTransactionName}"),"sTransactionName"); lr_save_string(lr_eval_string("{pResult}"),"sResult"); lr_save_string(lr_eval_string("{pRandom}"),"sResponseTime"); lr_save_datetime("%H:%M:%S", TIME_NOW, "sTime"); sprintf(chQuery, "insert into test.sample_writes (sqTransactionName, sqResult, sqResponseTime, sqTime) values ('%s','%s','%s','%s');", lr_eval_string("{sTransactionName}"), lr_eval_string("{sResult}"), lr_eval_string("{sResponseTime}"), lr_eval_string("{sTime}")); lr_mysql_query(Mconn, chQuery); lr_mysql_disconnect(Mconn); return 0; }
int WriteToFile(char *cDOSPath, char * cDOS) { //Save Epoch time to an array web_save_timestamp_param("sEpochMilliseconds", LAST); strcpy(cEpochTime, lr_eval_string("{sEpochMilliseconds}")); //Save the unique filename in the format C:\temp\x_yyyyyyyyyyyyy.txt where x is vUserID and yyyyyyyyyyyyy is Current EpochTime lr_save_string("C:\\temp\\", "FilePath"); lr_save_string(".txt", "FileType"); strcpy(file_path, lr_eval_string("{FilePath}")); strcat(file_path, lr_eval_string("{pVuser}")); strcat(file_path, "_"); strcat(file_path, cEpochTime); strcat(file_path, lr_eval_string("{FileType}")); // Uncomment the following line for debugging - output current filepath // lr_output_message("File Path - %s", file_path); //This is the command thich will write data to the external file. //It starts by writing the DOS command into a string called "command" sprintf(cCommand, "%s%s > %s", cDOSPath, cDOS ,file_path); lr_output_message("cCommand - %s", cCommand); lr_output_message("cDOS - %s", cDOS); lr_output_message("file_path - %s", file_path); // Uncomment the following line for debugging - output current command lr_output_message("command - %s", cCommand); //Execute the DOS command "command" system(cCommand); }
/*! \brief Split a string into 2 parts using the search string. Save the left part into the result parameter. \param [in] original_parameter The parameter to search. \param [in] search The text after the text we're looking for. \param [in] result_parameter The name of the parameter to store the result in. \b Example: \code lr_save_string("AstrixObelixIdefix", "Test"); lr_message(lr_eval_string("Original: {Test}\n")); // {Test}=AstrixObelixIdefix y_left( "Test", "Obelix", "Test2" ); lr_message(lr_eval_string("New Param: {Test2}\n")); // {Test2}=Astrix \endcode \author Floris Kraak */ void y_left( const char *original_parameter, const char *search, const char *result_parameter ) { char *original = y_get_parameter_or_null(original_parameter); if( original == NULL ) { lr_error_message("y_left(): Error: Parameter %s does not exist!", original_parameter); lr_abort(); } else if( search == NULL || strlen(search) == 0 ) { lr_save_string(original, result_parameter); lr_log_message("Warning: Empty search parameter passed to y_left()"); return; } else { char *buffer; char *posPtr = (char *)strstr(original, search); int pos = (int)(posPtr - original); //lr_log_message("y_left: original=%s, search=%s, resultParam=%s", original, search, resultParam); if( posPtr == NULL ) { lr_save_string(original, result_parameter); return; } //lr_log_message("pos = %d", pos); // Copy the original to a temporary buffer buffer = y_strdup(original); buffer[pos] = '\0'; // make the cut lr_save_string(buffer, result_parameter); // save the result free(buffer); } }
// -------------------------------------------------------------------------------------------------- // Same as y_right(), but don't stop at the first match, rather use the last match instead. // @author Floris Kraak // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // example usage: // lr_save_string("WackoYackoDotWarner", "Test"); // lr_message(lr_eval_string("Original: {Test}\n")); // {Test}=WackoYackoDotWarner // y_last_right( "Test", "ot", "Test2" ); // lr_message(lr_eval_string("New Param: {Test2}\n")); // // note: previous name: tail_tail() // // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - y_last_right( const char *originalParameter, const char *search, const char *resultParameter) { char *result = y_get_parameter(originalParameter); char *posPtr; //int pos; if( search == NULL || strlen(search) == 0 ) { lr_save_string(result, resultParameter); //lr_log_message("Warning: Empty search parameter passed to y_last_right()"); return; } //lr_log_message("y_last_right: original=%s, search=%s, resultParam=%s", original, search, resultParameter); do { posPtr = (char *)strstr(result, search); //pos = (int)(posPtr - result); //lr_log_message("pos = %d", pos); // not found, save what we have as the result. if( posPtr == NULL ) { lr_save_string(result, resultParameter); return; } // found, update the result pointer and go find more.. result = posPtr + strlen(search); } while(1); }
/*! \brief Split a string into 2 parts using the search string. Save the right part into the result parameter. \param [in] original_parameter The parameter to search. \param [in] search The text preceding the text we're looking for. \param [in] result_parameter The name of the parameter to store the result in. \b Example: \code lr_save_string("AstrixObelixIdefix", "Test"); lr_message(lr_eval_string("Original: {Test}\n")); // {Test}=AstrixObelixIdefix y_right( "Test", "Obelix", "Test4" ); lr_message(lr_eval_string("New Param: {Test4}\n")); // {Test4}=Idefix \endcode \author Floris Kraak */ void y_right( const char *original_parameter, const char *search, const char *result_parameter) { char* original = y_get_parameter_or_null(original_parameter); if( original == NULL ) { lr_error_message("y_right(): Error: Parameter %s does not exist!", original_parameter); lr_abort(); } else if( search == NULL || strlen(search) == 0 ) { lr_save_string(original, result_parameter); lr_log_message("Warning: Empty search parameter passed to y_right()"); return; } else { char* posPtr = (char *)strstr(original, search); //int pos = (int)(posPtr - original); //lr_log_message("y_right: original=%s, search=%s, resultParam=%s", original, search, result_parameter); if( posPtr == NULL ) { lr_save_string(original, result_parameter); return; } //lr_log_message("pos = %d", pos); posPtr = posPtr + strlen(search); lr_save_string(posPtr, result_parameter); } }
//************************************************** // created by Mark Sibley // modified by Richard Bishop // Saves left and right parts of a string into two separate strings // Similar to Excel LEFT() and RIGHT() functions //-------------------------------------------------- int SplitString(char * StringToSplit, int iLeftSplit) { int iSLenA, iSLenB, iLoopLen; int iLooper = 0; char sStringB[200], sFullString[200], sParam[2000], n, sCharacter[200]; //-------------------------------------------------- // This saves the left hand x characters of the account number string strncpy(sStringB, StringToSplit, iLeftSplit); lr_save_string(lr_eval_string(sStringB),"sLeftString"); //-------------------------------------------------- // this calculates the string lengths iSLenA = strlen(lr_eval_string(StringToSplit)); iSLenB = strlen(lr_eval_string("{sLeftString}")); iLoopLen = iSLenA - iSLenB; //-------------------------------------------------- // this saves the right hand characters of the account string sprintf(sParam,"%s",lr_eval_string(StringToSplit)); for (iLooper = iSLenB; iLooper < iSLenA; iLooper++) { sscanf(sParam+iLooper, "%c", &n); sprintf(sCharacter,"%c",n); strcat(sFullString, sCharacter); } lr_save_string(lr_eval_string(sFullString),"sRightString"); //-------------------------------------------------- // used when debugging this function lr_output_message("Original string:[%s]",lr_eval_string(StringToSplit)); lr_output_message("Left hand split:[%s]",lr_eval_string("{sLeftString}")); lr_output_message("Right hand split:[%s]",lr_eval_string("{sRightString}")); //-------------------------------------------------- }
SSNGenerator(char* param_name, char* ssnNoSpace) { int randSSN[3]; char EmployeeDep1SSN[100]; char EmployeeDep1SSN_1[100]; char p_SSN_1[100]; randSSN[0] = RandomRange(100,999); randSSN[1] = RandomRange(10,99); randSSN[2] = RandomRange(1000,9999); lr_save_int(randSSN[0],"pSSN1dep1_1"); lr_save_int(randSSN[1],"pSSN2dep1_1"); lr_save_int(randSSN[2],"pSSN3dep1_1"); sprintf(EmployeeDep1SSN, "%s-%s-%s", lr_eval_string("{pSSN1dep1_1}"), lr_eval_string("{pSSN2dep1_1}"), lr_eval_string("{pSSN3dep1_1}")); sprintf(EmployeeDep1SSN_1, "%s%s%s", lr_eval_string("{pSSN1dep1_1}"), lr_eval_string("{pSSN2dep1_1}"), lr_eval_string("{pSSN3dep1_1}")); lr_save_string(EmployeeDep1SSN, "EmployeeDep1SSN"); lr_save_string(EmployeeDep1SSN, param_name); lr_save_string(EmployeeDep1SSN_1, ssnNoSpace); return 0; }
get_google_access_token(){ int rc=LR_PASS; char sOut[256]; // used by wi_EncodePlainToURL() rc=get_pJWTAssertion(); // into parameter pJWTAssertion used by this function. if( rc != LR_PASS ){ return rc; } // No input data to process. if( stricmp("Token",LPCSTR_RunType ) == FOUND ){ // "Token" or "TOKEN" specified in Run-time Attribute "RunType" or command line option "-RunType". wi_startPrintingTrace(); lr_output_message(">> RunType=\"%s\". JWT=%s." ,LPCSTR_RunType ,lr_eval_string("{pJWTAssertion}") ); wi_stopPrinting(); return LR_PASS; } web_add_header("Content-Type","application/x-www-form-urlencoded"); web_add_header("X-Frame-Options","deny"); // to protect against drag'n drop clickjacking attacks in older browsers. web_reg_save_param_ex("ParamName=pAccessToken","LB=\"access_token\" : \"","RB=\"",SEARCH_FILTERS,"Scope=body",LAST); // Example: "Body=grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion={pJWTAssertion}", wi_EncodePlainToOAuth("grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=",sOut ); lr_save_string(sOut,"pJWTAssertion_request"); wi_startPrintingTrace(); lr_output_message(">> sOut=\"%s\"." ,lr_eval_string("{pJWTAssertion_request}") ); wi_stopPrinting(); // TODO: 15. If you want to, change the transaction name suffix for access authorization requests. sprintf( tempString1, "%s_1access", lr_eval_string("{pTransSequence}") ); lr_save_string(tempString1,"pTransName"); wi_start_transaction(); // web_rest("Token", web_custom_request("Token", "URL=https://accounts.google.com/o/oauth2/token", "Method=POST", //"ResType=JSON", "Body={pJWTAssertion_request}{pJWTAssertion}", LAST); // The %3A are urlencoded from colons. (but %2D for the dash causes an "Invalid request" response): // "Body=grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion={pJWTAssertion}", // Common name for "jwt-bearer" is JWT Bearer Token Grant Type Profile for OAuth 2.0 // Defined at http://tools.ietf.org/html/draft-ietf-oauth-jwt-bearer-04 rc = wi_end_transaction(); // "Error -27796: Could not resolve address of hot accounts.google.com" is issued if there in no internet connection. // Google API does not issue "error_description" such as "Audience validation failed". /* The response should look something like: { "access_token" : "1/_5pUwJZs9a545HSeXXXXXuNGITp1XtHhZXXxxyyaacqkbc", "token_type" : "Bearer", "expires_in" : 3600 } */ return rc; } // get_google_access_token()
vuser_init() { lrs_startup(257); lrs_create_socket("socket0","UDP","RemoteHost=ad3.norouter.cn:1500",LrsLastArg); lr_whoami(&id, &vuser_group, &scid); srand(id+time(NULL)); rand_mac(randmac); rand_ip(randip); lr_output_message("randip=%s",randip); lr_output_message("rand_mac=%s",randmac); lr_save_string(randmac,"mac"); lr_save_string(randip,"ip"); lrs_send("socket0", "buf0", LrsLastArg); lrs_receive("socket0", "buf1", LrsLastArg); ids = lrs_get_received_buffer("socket0",18,18,NULL); buffer_convert_to_hex_string(ids,18,buf); lr_output_message("ids=%s",buf); lrs_get_buffer_by_name("buf2",&data,&size); memcpy(dev_id,ids,8); memcpy(id_rand,ids+8,10); memcpy(data+18,dev_id,8); buffer_convert_to_hex_string(data,36,buf); //lr_output_message("buf=%s",buf); lrs_set_receive_option(Mismatch,MISMATCH_CONTENT); lrs_set_send_buffer("socket0",buf,strlen(buf)); lrs_send("socket0", "buf2", LrsLastArg); lrs_receive("socket0","buf3",LrsLastArg); lrs_set_receive_option(Mismatch,MISMATCH_SIZE); lrs_get_buffer_by_name("buf4",&data,&size); memcpy(data+18,dev_id,8); buffer_convert_to_hex_string(data,44,buf); lrs_set_send_buffer("socket0",buf,strlen(buf)); lrs_send("socket0", "buf4", LrsLastArg); lrs_receive("socket0","buf5",LrsLastArg); p = lrs_get_received_buffer("socket0",18,16,NULL); memcpy(ran,p,16); oemMD5Init(&context); oemMD5Update(&context,(unsigned char*)id_rand,10); oemMD5Update(&context,(unsigned char*)ran,16); oemMD5Final((unsigned char*)digest,&context); lrs_get_buffer_by_name("buf6",&data,&size); memcpy(data+18,dev_id,8); memcpy(data+30,digest,16); buffer_convert_to_hex_string(data,131,buf); lrs_set_receive_option(Mismatch,MISMATCH_CONTENT); lrs_set_send_buffer("socket0",buf,strlen(buf)); lrs_send("socket0", "buf6", LrsLastArg); lrs_receive("socket0","buf7",LrsLastArg); lrs_set_receive_option(Mismatch,MISMATCH_SIZE); return 0; }
//******************************************************* Action() { lr_save_string("ABC123456","Param"); Reverse(lr_eval_string("{Param}"),"NewParam"); lr_output_message(lr_eval_string("Changed [{Param}] to [{NewParam}]")); lr_save_string("Peter Piper","Param"); Reverse(lr_eval_string("{Param}"),"NewParam"); lr_output_message(lr_eval_string("Changed [{Param}] to [{NewParam}]")); lr_save_string("Fiddlesticks","Param"); Reverse(lr_eval_string("{Param}"),"NewParam"); lr_output_message(lr_eval_string("Changed [{Param}] to [{NewParam}]")); return 0; }
// -------------------------------------------------------------------------------------------------- // Lightweight alternative to the y_replace() function. // Remove all occorrances of 'removeMe' in the parameter named 'paramName' // Stores the result in the original parameter. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // example usage: // lr_save_string("test123", "par1"); // y_remove_string_from_parameter("par1", "1"); // {par1} now has the value test23 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - y_remove_string_from_parameter(const char* paramName, const char* removeMe) { char *parameter; char *removePtr; int remlen; //lr_log_message("y_remove_string_from_parameter( remove:%s, parameter:%s )", removeMe, paramName); if(!removeMe || !*removeMe) return; // fetch the contents of the parameter to change parameter = y_get_parameter(paramName); // removePtr is used to track our progress through this string removePtr = parameter; remlen = strlen(removeMe); // while we find occurrances of the string we're looking for while ( removePtr = (char *)strstr( removePtr, removeMe ) ) { // copy the characters between the end of the data we wish to remove and end-of-string // to the place where we found our offending content. char* origin = removePtr + remlen; strncpy(removePtr, origin, (strlen(origin)+1)); } // store it in the original parameter lr_save_string( parameter, paramName ); }
SplitStringCalculations() { int iValue; char cBuffer[1024]=""; char cConcatenatedOutput[1024]=""; web_save_timestamp_param("sLoadRunnerTimeStamp", LAST); lr_output_message( "Current UNIX time in milliseconds is #%s", lr_eval_string( "{sLoadRunnerTimeStamp}" ) ); //Splits the saved string {sLoadRunnerTimeStamp} into two parts, first 7 and remainder //fSplitString function is declared in vuser_init fSplitString(lr_eval_string("{sLoadRunnerTimeStamp}"),7); //Convert {sRightString} to integer iValue to perform calculation //In this case subtract 1000 milliseconds to get timestamp from one second ago iValue = atoi(lr_eval_string("{sRightString}")); iValue = iValue-1000; sprintf(cBuffer, "%d", iValue); //Save Right part of the string lr_save_string(cBuffer, "sCalculatedRightString"); //Copy {sLeftString} into cConcatenatedOutput, then concatenate (append) {sCalculatedRightString} strcpy(cConcatenatedOutput, lr_eval_string("{sLeftString}")); strcat(cConcatenatedOutput, lr_eval_string("{sCalculatedRightString}")); lr_output_message("Epoch time minus 1000 milliseconds is:[%s]",cConcatenatedOutput); return 0; }
// -------------------------------------------------------------------------------------------------- // Convert the content of a parameter to UPPERCASE. Does not affect non-alphabetic characters. // @author Floris Kraak // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // example usage: // lr_save_string("aBcDeFgHiJ &*45#$@#)!({}", "Test"); // lr_message(lr_eval_string("Original: {Test}\n")); // y_uppercase_parameter("Test"); // lr_message(lr_eval_string("Altered: {Test}\n")); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - y_uppercase_parameter(const char* paramName) { char *result = y_get_parameter(paramName); // Note that in Vugen files, you need to explicitly declare C functions that do not return integers. strupr(result); lr_save_string(result, paramName); }
// -------------------------------------------------------------------------------------------------- // Clean a parameter by removing any embedded \x00 (null) characters from it. // This would only happen if you have used to web_reg_save_param() and the result contains // a null-character. // Any such characters are replaced with ' '. (space) // Since this changes existing parameters be careful what types of parameters // you use this on.But when no null-character is found, the result is unaltered. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // example usage: // char *test; // web_reg_save_param("TestParam", "LB=\"name=LastName\" Value=\"", "RB=\"", LAST); // web_submit_data(...); // will fail, obiously. // lr_message(lr_eval_string("TestParam: {TestParam}\n")); // y_cleanse_parameter("TestParam"); // test=y_get_parameter("TestParam"); // lr_message("\nTest: >%s<\n", test); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void y_cleanse_parameter(const char* paramName) { char *result; unsigned long resultLen; size_t resultStrlen; size_t param_size = strlen(paramName) +3; // parameter name + "{}" + '\0' (end of string) char *tmp = y_mem_alloc( param_size ); //lr_log_message("y_cleanse_parameter(%s)", paramName ); // Get the contents of the parameter using lr_eval_string_ext() - we can't use the // regular version if we expect to find \x00 in there. snprintf( tmp, param_size, "{%s}", paramName ); lr_eval_string_ext(tmp, strlen(tmp), &result, &resultLen, 0, 0, -1); free(tmp); // replace NULL bytes (\x00) in the input with something else.. for( resultStrlen = strlen(result); resultStrlen < resultLen; resultStrlen = strlen(result)) { result[resultStrlen] = ' '; } // Put the result back into the original parameter. lr_save_string(result, paramName); lr_eval_string_ext_free(&result); }
set_pShortHostKey_from_url(char* strURL){ // From URL supplied with the call, extract the pShortHostKey LR parameter string: token = (char *)strtok( strURL,"/"); // Get the first token before the separator character. if(!token) { // blank means separator character not found. // move on. }else{ token = (char *)strtok(NULL, "/"); // Get the number after. lr_save_string(token,"pShortHostKey"); token = (char *)strtok(NULL, "/"); // Get the number after. lr_save_string(token,"pShortHostKey"); // lr_output_message(">> token=%s",token); } return LR_PASS; } // set_pShortHostKey_from_url()
/*! \brief Save a substring of a parameter into a new parameter. Search for a specific substring inside a parameter using left and right boundaries and save that into a new parameter. \param [in] original_parameter The parameter to search. \param [in] result_parameter The name of the parameter to store the result in. \param [in] left The left boundary - the text immediately preceding the substring in question. \param [in] right The right boundary. \b Example: \code char* str = "LorumIpsumLipsum"; lr_save_string(str, "param"); y_substr("param", "param", "Lorum", "Lipsum"); lr_log_message(lr_eval_string("{param}")); // Prints "Ipsum". \endcode \author André Luyer, Marcel Jepma & Floris Kraak */ void y_substr(const char *original_parameter, const char *result_parameter, const char *left, const char *right) { char *p1; char *str = y_get_parameter_or_null(original_parameter); if( str == NULL ) { lr_error_message("y_substr(): Error: Parameter %s does not exist!", original_parameter); lr_abort(); } // zoek start if (left) { p1 = strstr(str, left); if (p1) str = p1 + strlen(left); // else start is positie 0... } // zoek eind if (right) { p1 = strstr(str, right); if (p1) { lr_param_sprintf(result_parameter, "%.*s", p1 - str, str); // of sprintf return; } } lr_save_string(str, result_parameter); }
// -------------------------------------------------------------------------------------------------- // Remove leading and trailing whitespace from a parameter. Does not support Unicode so use with care. // Whitespace can be: " "(=space) "\r"(=carrige return) "\n"(=line feed) "\t"(=tab) // @author: Floris Kraak // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // example usage: // lr_save_string(" WackoYackoDot ", "Test"); // lr_message(lr_eval_string("Original: >{Test}<\n")); // {Test}= " WackoYackoDot " // y_chop("Test"); // lr_message(lr_eval_string("Original: >{Test}<\n")); // {Test}= "WackoYackoDot" // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - y_chop( const char* parameter ) { char *result; int i = 0; char character; //lr_output_message( "y_chop(%s)", parameter); result = y_get_parameter(parameter); // y_chop leading whitespace character = result[i]; while( (character == ' ') || (character == '\r') || (character == '\n') || (character == '\t') ) { character = result[++i]; } result += i; //lr_output_message("result after removal of leading whitespace: %s", result); // y_chop trailing whitespace i = strlen(result)-1; character = result[i]; while( (i >= 0) && ( (character == ' ' ) || (character == '\r') || (character == '\n') || (character == '\t') ) ) { character = result[--i]; } result[i+1] = '\0'; lr_save_string(result, parameter); }
int wi_set_unique_id(){ int rc=LR_PASS; char* my_controller_name; char* my_host; // host_name of load generator (injector): int iScenarioID; char* vuser_group; int iVuserID; // -1 if run in VuGen. char* sVuserID[32]; // from lr_get_vuser_ip() // char my_unique_id[64]=""; // defined as global variable. int vuser_pid=0; // Windows Process ID my_controller_name = lr_get_master_host_name(); my_host = lr_get_host_name(); vuser_pid = wi_get_vuser_pid(); lr_whoami(&iVuserID, &vuser_group, &iScenarioID); // lr_whoami returns void by design (no rc). // NOTE: When run in VuGen: Controller=None, host=%MACHINENAME%, ScenarioID=0, vuser_group=None, iVuserID=-1. wi_startPrintingInfo(); lr_output_message(">> Controller=%s, Host=%s, ScenarioID=%d, Group=%s, Vuser=%d, PID=%d." ,my_controller_name ,my_host ,iScenarioID, vuser_group ,iVuserID, vuser_pid ); wi_resetPrinting(); sprintf( global_unique_id,"C%s.H%d.S%s.G%s.U%d.P%d" ,my_controller_name ,my_host ,iScenarioID ,vuser_group ,iVuserID ,vuser_pid ); lr_save_string(global_unique_id,"global_unique_id"); return rc; } // wi_set_unique_id
/*! \brief Detect low disk space situations on the generator and turn all logging off if not enough space is left. When called, this function will check the amount of space left on the generator's "output" device / directory. If the percentage of free space is lower than the treshold percentage, it will generate an error transaction "---DISK SPACE LOW IN LOG FOLDER FOR {y_hostname_generator}---" and turn all further logging off until the end of the test, using y_log_turn_off_permanently(). \note Scripts that call lr_debug_message() or the various y_lib() toggle functions to turn the loglevel back up may ignore this restriction. Loadrunner does not protect the generators' disks from overflowing, even if the test is writing out a lot of information to the logs really quickly. If a disk fills up on the generator or the disk the controller uses for results collation overflows there is no graceful recovery. Collation will fail and test results may be hard or impossible to recover. This kind of situation can occur when temporary service disruptions happen (triggering a flood of 'log on error' messages), but also if runtime settings are incorrect and the test was configured to log *everything*. In order to prevent this from happening scripts should regularly call to both y_disk_space_guard() and y_disk_space_usage_guard() with some reasonable limits. \param [in] max_free_percentage The amount of free diskspace as a percentage of total space that will cause the logging to turn off. \author Floris Kraak */ void y_disk_space_guard(double max_free_percentage) { char* hostname; static int disk_space_warning_given = 0; double free_space_percentage; char* log_folder = lr_get_attrib_string("out"); // check already fired once before. if( disk_space_warning_given ) { // guard against accidental re-enablement of the logs by turning them off explicitly. y_log_turn_off_permanently(); return; } free_space_percentage = y_get_free_disk_space_percentage(log_folder); // data point hostname = lr_get_host_name(); lr_save_string(hostname, "y_hostname_generator"); lr_user_data_point( lr_eval_string("disk_space_{y_hostname_generator}_free_percentage"), free_space_percentage); if( free_space_percentage < max_free_percentage ) { y_setup(); lr_set_transaction(lr_eval_string("---DISK SPACE LOW IN LOG FOLDER FOR {y_hostname_generator}---"), 0, LR_FAIL); lr_error_message("Diskspace low on %s in folder %s. %.2lf%% remaining, exceeding the limit of %.21f%% Logging turned off for user id %d for the remainder of the test!", hostname, log_folder, free_space_percentage, max_free_percentage, y_virtual_user_id); disk_space_warning_given = 1; // turn off further warnings. y_log_turn_off_permanently(); } }
Action() { lr_save_string(randmac,"mac"); lr_save_string(randip,"ip"); lrs_get_buffer_by_name("buf4",&data,&size); memcpy(data+18,dev_id,8); buffer_convert_to_hex_string(data,44,buf); lrs_set_receive_option(Mismatch,MISMATCH_CONTENT); lrs_set_send_buffer("socket0",buf,strlen(buf)); lrs_send("socket0", "buf4", LrsLastArg); lrs_receive("socket0","buf8",LrsLastArg); lrs_set_receive_option(Mismatch,MISMATCH_SIZE); lr_think_time(1); return 0; }
Action() { int iDebug; web_cleanup_cookies( ); lr_start_transaction("_TIVApp_001_My_Test"); lr_save_string("TIVApp_001_001_Homepage", "pTransactionName"); web_reg_find("Fail=NotFound", "Search=Body", "Text=Test site.", LAST); web_reg_save_param("cServerName", "LB=Set-Cookie: ROUTEID=.", "RB=;", "Notfound=warning", LAST); web_reg_save_param("cVersion", "LB=version\">", "RB=<", "Notfound=warning", LAST); lr_start_transaction(lr_eval_string("{pTransactionName}")); web_url("Homepage", "URL=http://{pURL}/", "Resource=0", "RecContentType=text/html", "Referer=", "Snapshot=t1.inf", "Mode=HTML", LAST); // Log Levels: // LR_MSG_CLASS_DISABLE_LOG // LR_MSG_CLASS_BRIEF_LOG // LR_MSG_CLASS_EXTENDED_LOG // LR_MSG_CLASS_RESULT_DATA // LR_MSG_CLASS_PARAMETERS // LR_MSG_CLASS_FULL_TRACE iDebug = lr_get_debug_message(); lr_output_message("TIVMsg: Msg Level was: %d", iDebug); lr_set_debug_message(LR_MSG_CLASS_EXTENDED_LOG, LR_SWITCH_ON); lr_debug_message(LR_MSG_CLASS_EXTENDED_LOG | LR_MSG_CLASS_RESULT_DATA,"TIVMsg: %s loaded via server: %s", lr_eval_string("{pTransactionName}"), lr_eval_string("{cServerName}")); lr_set_debug_message(iDebug, LR_SWITCH_ON); lr_end_transaction(lr_eval_string("{pTransactionName}"), LR_AUTO); lr_end_transaction("_TIVApp_001_My_Test", LR_AUTO); return 0; }
// -------------------------------------------------------------------------------------------------- // y_breadcrumb(); // Adds a string to the parameter {breadcrumb}. // Use this to keep track of the steps taken by the script. Very useful is you have a script which // does things in a random order and you want to know (in the end) which order it used. // You can, ofcourse, write this to a (log)file. // Don't forget to use y_breadcrumb_reset() to clear the parameter at the start of the script. // @author: Raymond de Jongh // Example: // y_breadcrumb_reset(); // clean the breadcrumb-variable. (previous data in {breadcrumb} is deleted. // y_breadcrumb("start"); // .... some code.... // y_breadcrumb("processing data") // ... some code .... // y_breadcrumb("finished") // The result is that {breadcrumb} contains "start;processing data;finished" // -------------------------------------------------------------------------------------------------- void y_breadcrumb(char *breadcrumb) { lr_message("---------------------------------------------------------------------------------"); if ((strcmp(lr_eval_string("{breadcrumb}"), "{breadcrumb}") == 0) || ((strcmp(breadcrumb, "") == 0))) { lr_save_string("", "breadcrumb"); lr_save_string(breadcrumb, "y_breadcrumb_temp"); lr_save_string(lr_eval_string("{y_breadcrumb_temp}"), "breadcrumb"); } else { lr_save_string(breadcrumb, "y_breadcrumb_temp"); lr_save_string(lr_eval_string("{breadcrumb};{y_breadcrumb_temp}"), "breadcrumb"); } }
// This will fetch attributes from the vUser's command line (as set in the scenario!) // and store them in a parameter. // See also y_save_attribute() // // These attributes are defined in the details of the vUser group // They take the form "-attributename value" // // Arguments: // - attrib: The name of the attribute to fetch // - param : The name of the parameter to store the attribute in. // // @author: Floris Kraak // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // example usage: // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - y_save_attribute_to_parameter( char* attrib, char* param ) { char *tmp; if( (tmp = lr_get_attrib_string(attrib)) != NULL ) { lr_save_string(tmp, param); } }
Action() { //Saves the string (normally this would be a correlated value hence the "c" prefix - cParameterToSplit lr_save_string("1234567890abcdefghijklmnopqrstuvwxyz","cParameterToSplit"); //Splits the saved string into two parts, first x characters as declared in "iLeftSplit" and remainder SplitString(lr_eval_string("{cParameterToSplit}"),10); return 0; }
// -------------------------------------------------------------------------------------------------- // Split the string into 2 parts, using the search string. Save the right part into the // resultParameter. // // @author Floris Kraak // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // example usage: // lr_save_string("AstrixObelixIdefix", "Test"); // lr_message(lr_eval_string("Original: {Test}\n")); // {Test}=AstrixObelixIdefix // y_right( "Test", "Obelix", "Test4" ); // lr_message(lr_eval_string("New Param: {Test4}\n")); // {Test4}=Idefix // // note: previous name: head() and y_head() // // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - y_right( const char *originalParameter, const char *search, const char *resultParameter) { char *original = y_get_parameter(originalParameter); char *posPtr = (char *)strstr(original, search); int pos = (int)(posPtr - original); //lr_log_message("y_right: original=%s, search=%s, resultParam=%s", original, search, resultParameter); if( posPtr == NULL ) { lr_save_string(original, resultParameter); return; } //lr_log_message("pos = %d", pos); posPtr = posPtr + strlen(search); lr_save_string(posPtr, resultParameter); }
// -------------------------------------------------------------------------------------------------- // y_split a string in two based on a seperating string. // @author Floris Kraak // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // example usage: // lr_save_string("WackoYackoDotWarner", "Test"); // lr_message(lr_eval_string("Original: {Test}\n")); // {Test} = WackoYackoDotWarner // y_split("Test", "Yacko", "Left", "Right"); // Use "Yacko" as the separator // lr_message(lr_eval_string("Original: {Test}\n")); // {Test} = WackoYackoDotWarner // lr_message(lr_eval_string("Left : {Left}\n")); // {Left} = Wacko // lr_message(lr_eval_string("Right : {Right}\n")); // {Right} = DotWarner // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - y_split( const char *originalParameter, const char *separator, const char *leftParameter, const char *rightParameter) { char *item = y_get_parameter(originalParameter); int len = strlen(item); if( len < strlen(separator) ) { // Since the separator doesn't even fit in the item, searching is pointless. // Store the original in the left hand parameter, the right hand is empty. lr_save_string(originalParameter, leftParameter); lr_save_string("", rightParameter); return; } else { // Left hand side // If the separator isn't found the full original string gets stored here. // Don't forget the 0 byte at the end though.. char *left = y_mem_alloc(len+1); // Right hand side // If the separator gets found in position 1 the remainder of the // original string gets stored here (and left gets a zero-length string). char *right = y_mem_alloc(len-strlen(separator)+1); // Start off with zero-length strings. We can safely assume // both variables contain garbage when freshly allocated. left[0] = '\0'; right[0] = '\0'; // This is where the magic happens. y_split_str(item, separator, left, right); // Store the results in parameters. lr_save_string(left, leftParameter); free(left); lr_save_string(right, rightParameter); free(right); } }
/*! \brief Convert the content of a parameter to UPPERCASE. This will replace the content of the paramenter named in 'param_name' with the uppercased version. Does not affect non-alphabetic characters. \param [in] param_name The parameter to convert to uppercase. \b Example: \code lr_save_string("aBcDeFgHiJ &*45#$@#)!({}", "Test"); lr_message(lr_eval_string("Original: {Test}\n")); y_uppercase_parameter("Test"); lr_message(lr_eval_string("Altered: {Test}\n")); // prints "Altered: ABCDEFGHIJ &*45#$@#)!({}". \endcode \author Floris Kraak */ void y_uppercase_parameter(const char* param_name) { char *result = y_get_parameter_or_null(param_name); if(result == NULL) { lr_error_message("Nonexistant parameter %s passed to y_uppercase_parameter(): Aborting.", param_name); lr_abort(); } strupr(result); lr_save_string(result, param_name); }
GetSourceDataRegister() { //Connect to first VTS server (may prefer to do this in vuser_init) pvci = vtc_connect(VtsServer1,nPort1,VTOPT_KEEP_ALIVE); //lr_output_message("pvci=%d\n", pvci); lr_start_transaction("BP1_RegisterNew_GetData"); //Retrieve the topmost row, removes the row from the table. //To take data from the table non destructively, use the lrvtc_query_row function. ret = vtc_retrieve_row(pvci, &colnames, &rowdata); //lr_output_message("Row retrieval ret=%d\n", ret); // Because the vtc_retrieve_row function returns an array, not a populated list // We have to check the content and save the parameters ourselves // If we stick to lrvtc_retrieve_row this step is unneeded if (!colnames){ // lr_output_message("No data found"); lr_save_string("","first_name"); }else for (inx=0; colnames[inx]; inx++){ lr_save_string(rowdata[inx],colnames[inx]); } lr_end_transaction("BP1_RegisterNew_GetData", LR_AUTO); //Can refer to the variables returned from VTS using the parameter names. //lr_output_message("First name was : %s . Last name was : %s", // lr_eval_string("{first_name}"), // lr_eval_string("{last_name}")); //Deallocate the buffers containing arrays of returned strings vtc_free_list(colnames); vtc_free_list(rowdata); //Disconnect from VTS (may prefer to do this in vuser_end) vtc_disconnect(pvci); return 0; }
/*! \brief Detect excessive disk usage by the test and turn all further logging off if more than a specific limit number of mebibytes has been used. When called, this function will check the amount of space used on the generator's "output" device / directory since the first call to this function. If the amount of used space exceeds the treshold it will generate an error transaction "---DISK SPACE LOW IN LOG FOLDER FOR {y_hostname_generator}---" and turn all further logging off until the end of the test, using y_log_turn_off_permanently(). \note Scripts that call lr_debug_message() or the various y_lib() toggle functions to turn the loglevel back up may ignore this restriction. Loadrunner does not protect the generators' disks from overflowing, even if the test is writing out a lot of information to the logs really quickly. If a disk fills up on the generator or the disk the controller uses for results collation overflows there is no graceful recovery. Collation will fail and test results may be hard or impossible to recover. This kind of situation can occur when temporary service disruptions happen (triggering a flood of 'log on error' messages), but also if runtime settings are incorrect and the test was configured to log *everything*. \note Because of the way this measurement is done, it may also trigger if some other process on the same machine starts writing large amounts of data to the same device. In order to prevent this from happening scripts should regularly call to both y_disk_space_guard() and y_disk_space_usage_guard() with some reasonable limits. \note The contents of the generator's output folder will be transferred to the controller during collation. If the sum of the output directories for the generators exceed the size of that filesystem collation will fail, even if there is enough space on the generators. Therefore, set this low enough to make sure that if all generators output folders get filled to the limit the controller will still have enough space for it's collation process. \param [in] limit_mebibytes_used The amount of mebibytes the test is allowed to used on the generator's target directory. \author Floris Kraak */ void y_disk_space_usage_guard(double limit_mebibytes_used) { char* hostname; char* log_folder = lr_get_attrib_string("out"); double free_mebibytes; static double max_free_mebibytes = -1; double mebibytes_used; static int disk_space_warning_given = 0; // check already fired once before. if( disk_space_warning_given ) { // guard against accidental re-enablement of the logs by turning them off explicitly. y_log_turn_off_permanently(); return; } free_mebibytes = y_get_free_disk_space_in_mebibytes(log_folder); lr_log_message("y_disk_space_usage_guard: current free: %f MB, max free: %f MB, limit: %f MB used in folder: %s", free_mebibytes, max_free_mebibytes, limit_mebibytes_used, log_folder); if(max_free_mebibytes < 0) { lr_log_message("Storing free space as detected maximum"); max_free_mebibytes = free_mebibytes; return; } else if(max_free_mebibytes < free_mebibytes) { lr_output_message("Warning: Free disk space increased from %f to %f, test disk space usage measurements may have become unreliable.", max_free_mebibytes, free_mebibytes); max_free_mebibytes = free_mebibytes; return; } // Ok, so we used *something*. Now let's see if it exceeds our limit. mebibytes_used = max_free_mebibytes - free_mebibytes; // data points hostname = lr_get_host_name(); lr_save_string(hostname, "y_hostname_generator"); lr_user_data_point( lr_eval_string("disk_space_{y_hostname_generator}_free_mebibytes"), free_mebibytes); lr_user_data_point( lr_eval_string("disk_space_{y_hostname_generator}_used_mebibytes"), mebibytes_used); if( mebibytes_used >= limit_mebibytes_used ) { y_setup(); lr_set_transaction(lr_eval_string("---DISKSPACE USAGE TOO HIGH IN LOG FOLDER FOR {y_hostname_generator}---"), 0, LR_FAIL); lr_output_message("Disk space used on host %s in folder %s was %f mebibytes, reaching the limit of %f. Logging turned off for user id %d for the remainder of the test!", hostname, log_folder, mebibytes_used, limit_mebibytes_used, y_virtual_user_id); disk_space_warning_given = 1; // turn off further warnings. y_log_turn_off_permanently(); } }