/* This function is a wrapper for gettimeofday(). It uses local storage to * guarantee that the returned time will always be monotonic. If the time goes * backwards, it returns the same as previous one and readjust its internal * drift. If the time goes forward further than TIME_MAX_FORWARD_US * microseconds since last call, it will bound it to that value. It is designed * to be used as a drop-in replacement of gettimeofday(&now, NULL). It will * normally return 0, unless <now> is NULL, in which case it will return -1 and * set errno to EFAULT. */ static int monotonic_gettimeofday(timeval_t *now) { static timeval_t mono_date; static timeval_t drift; /* warning: signed seconds! */ timeval_t sys_date, adjusted, deadline; if (!now) { errno = EFAULT; return -1; } timer_reset_lazy(*now); gettimeofday(&sys_date, NULL); /* on first call, we set mono_date to system date */ if (mono_date.tv_sec == 0) { mono_date = sys_date; timer_reset(drift); *now = mono_date; return 0; } /* compute new adjusted time by adding the drift offset */ adjusted = timer_add(sys_date, drift); /* check for jumps in the past, and bound to last date */ if (timer_cmp(adjusted, mono_date) < 0) goto fixup; /* check for jumps too far in the future, and bound them to * TIME_MAX_FORWARD_US microseconds. */ deadline = timer_add_long(mono_date, TIME_MAX_FORWARD_US); if (timer_cmp (adjusted, deadline) >= 0) { mono_date = deadline; goto fixup; } /* adjusted date is correct */ mono_date = adjusted; *now = mono_date; return 0; fixup: /* Now we have to recompute the drift between sys_date and * mono_date. Since it can be negative and we don't want to * play with negative carries in all computations, we take * care of always having the microseconds positive. */ drift = timer_sub(mono_date, sys_date); *now = mono_date; return 0; }
static long vrrp_timer_fd(const int fd) { timeval_t timer, vrrp_timer; long vrrp_long; timer = vrrp_compute_timer(fd); vrrp_timer = timer_sub(timer, time_now); vrrp_long = timer_long(vrrp_timer); return (vrrp_long < 0) ? TIMER_MAX_SEC : vrrp_long; }
static int stop_profiler(ClipMachine * ClipMachineMemory, ProfileBucket * bp, struct timeval *tv) { struct timeval dt, rt; if (!bp->started_of_ProfileBucket) return 0; timer_sub(tv, &bp->timeval_start_of_ProfileBucket, &dt); timer_add(&bp->timeval_self_of_ProfileBucket, &dt, &rt); bp->timeval_self_of_ProfileBucket = rt; bp->started_of_ProfileBucket = 0; return 0; }
time_t microseconds() { static bool us_initted = false; static struct timeval us_time_zero; struct timeval tv, t; struct timezone tz; gettimeofday(&tv, &tz); if (us_initted == false) { us_initted = true; us_time_zero = tv; return 0; } else { timer_sub(tv, us_time_zero, t); return (t.tv_sec * USEC_PER_SEC + t.tv_usec); } }
/* timer sub from current time */ TIMEVAL timer_sub_now(TIMEVAL a) { return timer_sub(time_now, a); }
int main(int argc, char **argv) { char errbuf[PCAP_ERRBUF_SIZE]; bpf_u_int32 net = PCAP_NETMASK_UNKNOWN; char *filter_exp = "ip"; struct bpf_program fp; int i; int c; int opt_count = 0; int tmp_ret; char *ifile = NULL; unsigned int file_count = 0; char filename[MAX_FILENAME_LEN]; /* output file */ char pcap_filename[MAX_FILENAME_LEN*2]; /* output file */ char *cli_interface = NULL; char *cli_filename = NULL; char *config_file = NULL; struct interface ifl[IFL_MAX]; int num_interfaces; char *capture_if; unsigned int file_base_len = 0; unsigned int num_cmds = 0; unsigned int done_with_options = 0; struct stat sb; DIR *dir; struct dirent *ent; enum operating_mode mode = mode_none; /* sanity check sizeof() expectations */ if (data_sanity_check() != ok) { fprintf(stderr, "error: failed data size sanity check\n"); } /* sanity check arguments */ for (i=1; i<argc; i++) { if (strchr(argv[i], '=')) { if (done_with_options) { fprintf(stderr, "error: option (%s) found after filename (%s)\n", argv[i], argv[i-1]); exit(EXIT_FAILURE); } } else { done_with_options = 1; } } /* * set "info" to stderr; this output stream is used for * debug/info/warnings/errors. setting it here is actually * defensive coding, just in case some function that writes to * "info" gets invoked before info gets set below (if we are in * online mode, it will be set to a log file) */ info = stderr; /* in debug mode, turn off output buffering */ #if P2F_DEBUG setvbuf(stderr, NULL, _IONBF, 0); setbuf(stdout, NULL); #endif /* * set configuration from command line arguments that contain * LHS=RHS commands, then update argv/argc so that those arguments * are not subjected to any further processing */ num_cmds = config_set_from_argv(&config, argv, argc); argv += num_cmds; argc -= num_cmds; /* process command line options */ while (1) { int option_index = 0; struct option long_options[] = { {"help", no_argument, 0, 'h' }, {"xconfig", required_argument, 0, 'x' }, {0, 0, 0, 0 } }; c = getopt_long(argc, argv, "hx:", long_options, &option_index); if (c == -1) break; switch (c) { case 'x': config_file = optarg; opt_count++; break; case 'h': default: return usage(argv[0]); } opt_count++; } if (config_file) { /* * read in configuration from file; note that if we don't read in * a file, then the config structure will use the static defaults * set when it was declared */ config_set_from_file(&config, config_file); } if (config_file || (num_cmds != 0)) { /* * set global variables as needed, if we got some configuration * commands from the config_file or from command line arguments */ bidir = config.bidir; include_zeroes = config.include_zeroes; byte_distribution = config.byte_distribution; report_entropy = config.report_entropy; report_wht = config.report_wht; report_hd = config.report_hd; include_tls = config.include_tls; include_classifier = config.include_classifier; output_level = config.output_level; report_idp = config.idp; report_dns = config.dns; salt_algo = config.type; nfv9_capture_port = config.nfv9_capture_port; if (config.bpf_filter_exp) { filter_exp = config.bpf_filter_exp; } } /* * allow some command line variables to override the config file */ if (cli_filename) { /* * output filename provided on command line supersedes that * provided in the config file */ config.filename = cli_filename; } if (cli_interface) { /* * interface provided on command line supersedes that provided * in the config file */ config.interface = cli_interface; } if (config.filename) { strncpy(filename, config.filename, MAX_FILENAME_LEN); } /* * set the operating mode to online or offline */ if (config.interface != NULL && strcmp(config.interface, NULL_KEYWORD)) { mode = mode_online; } else { mode = mode_offline; } /* * if we are doing a live capture, get interface list, and set "info" * output stream to log file */ if (mode == mode_online) { if (config.logfile && strcmp(config.logfile, NULL_KEYWORD)) { info = fopen(config.logfile, "a"); if (info == NULL) { fprintf(stderr, "error: could not open log file %s\n", config.logfile); return -1; } fprintf(stderr, "writing errors/warnings/info/debug output to %s\n", config.logfile); } /* * cheerful message to indicate the start of a new run of the * daemon */ fprintf(info, "--- %s initialization ---\n", argv[0]); flocap_stats_output(info); num_interfaces = interface_list_get(ifl); if (num_interfaces == 0) { fprintf(info, "warning: could not obtain inferface information\n"); } else { for(i=0; i<num_interfaces; i++) { unsigned char *a = ifl[i].mac_addr; fprintf(info, "interface: %8s\tstatus: %s\t%02x%02x%02x%02x%02x%02x\n", ifl[i].name, (ifl[i].active ? "up" : "down"), a[0], a[1], a[2], a[3], a[4], a[5]); } } } else { info = stderr; } /* * report on running configuration (which may depend on the command * line, the config file, or both) */ config_print(info, &config); /* * configure labeled subnets (which uses a radix trie to identify * addresses that match subnets associated with labels) */ if (config.num_subnets > 0) { attr_flags subnet_flag; enum status err; rt = radix_trie_alloc(); if (rt == NULL) { fprintf(info, "could not allocate memory\n"); } err = radix_trie_init(rt); if (err != ok) { fprintf(stderr, "error: could not initialize subnet labels (radix_trie)\n"); } for (i=0; i<config.num_subnets; i++) { char label[LINEMAX], subnet_file[LINEMAX]; int num; num = sscanf(config.subnet[i], "%[^=:]:%[^=:\n#]", label, subnet_file); if (num != 2) { fprintf(info, "error: could not parse command \"%s\" into form label:subnet\n", config.subnet[i]); exit(1); } subnet_flag = radix_trie_add_attr_label(rt, label); if (subnet_flag == 0) { fprintf(info, "error: count not add subnet label %s to radix_trie\n", label); exit(1); } err = radix_trie_add_subnets_from_file(rt, subnet_file, subnet_flag, info); if (err != ok) { fprintf(info, "error: could not add labeled subnets from file %s\n", subnet_file); exit(1); } } fprintf(info, "configured labeled subnets (radix_trie), using %u bytes of memory\n", get_rt_mem_usage()); } if (config.anon_addrs_file != NULL) { if (anon_init(config.anon_addrs_file, info) == failure) { fprintf(info, "error: could not initialize anonymization subnets from file %s\n", config.anon_addrs_file); return -1; } } if (config.filename != NULL) { char *outputdir; /* * set output directory */ if (config.outputdir) { outputdir = config.outputdir; } else { outputdir = "."; } /* * generate an "auto" output file name, based on the MAC address * and the current time, if we are "auto" configured */ if (strncmp(config.filename, "auto", strlen("auto")) == 0) { if (mode == mode_online) { unsigned char *addr = ifl[0].mac_addr; time_t now = time(0); struct tm *t = localtime(&now); snprintf(filename, MAX_FILENAME_LEN, "%s/flocap-%02x%02x%02x%02x%02x%02x-h%d-m%d-s%d-D%d-M%d-Y%d-%s-", outputdir, addr[0], addr[1], addr[2], addr[3], addr[4], addr[5], t->tm_hour, t->tm_min, t->tm_sec, t->tm_mday, t->tm_mon, t->tm_year + 1900, t->tm_zone); } else { fprintf(info, "error: cannot use \"output = auto\" with no interface specified; use -o or -l options\n"); return usage(argv[0]); } fprintf(info, "auto generated output filename: %s\n", filename); } else { /* set output file based on command line or config file */ if (cli_filename) { strncpy(filename, config.filename, MAX_FILENAME_LEN); } else { char tmp_filename[MAX_FILENAME_LEN]; strncpy(tmp_filename, filename, MAX_FILENAME_LEN); snprintf(filename, MAX_FILENAME_LEN, "%s/%s", outputdir, tmp_filename); } } file_base_len = strlen(filename); if (config.max_records != 0) { snprintf(filename + file_base_len, MAX_FILENAME_LEN - file_base_len, "%d", file_count); } output = fopen(filename, "w"); if (output == NULL) { fprintf(info, "error: could not open output file %s (%s)\n", filename, strerror(errno)); return -1; } } else { output = stdout; } if (ifile != NULL) { opt_count--; argv[1+opt_count] = ifile; } if (mode == mode_online) { /* live capture */ int linktype; /* * sanity check: we can't be in both offline mode and online mode * simultaneously */ if ((argc-opt_count > 1) || (ifile != NULL)) { fprintf(info, "error: both interface (%s) and pcap input file (%s) specified\n", config.interface, argv[1+opt_count]); return usage(argv[0]); } anon_print_subnets(info); signal(SIGINT, sig_close); /* Ctl-C causes graceful shutdown */ signal(SIGTERM, sig_close); // signal(SIGHUP, sig_reload); // signal(SIGTSTP, sig_reload); signal(SIGQUIT, sig_reload); /* Ctl-\ causes an info dump */ /* * set capture interface as needed */ if (strncmp(config.interface, "auto", strlen("auto")) == 0) { capture_if = ifl[0].name; fprintf(info, "starting capture on interface %s\n", ifl[0].name); } else { capture_if = config.interface; } errbuf[0] = 0; handle = pcap_open_live(capture_if, 65535, config.promisc, 10000, errbuf); if (handle == NULL) { fprintf(info, "could not open device %s: %s\n", capture_if, errbuf); return -1; } if (errbuf[0] != 0) { fprintf(stderr, "warning: %s\n", errbuf); } /* verify that we can handle the link layer headers */ linktype = pcap_datalink(handle); if (linktype != DLT_EN10MB) { fprintf(info, "device %s has unsupported linktype (%d)\n", capture_if, linktype); return -2; } if (filter_exp) { /* compile the filter expression */ if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) { fprintf(info, "error: could not parse filter %s: %s\n", filter_exp, pcap_geterr(handle)); return -3; } /* apply the compiled filter */ if (pcap_setfilter(handle, &fp) == -1) { fprintf(info, "error: could not install filter %s: %s\n", filter_exp, pcap_geterr(handle)); return -4; } } /* * run as daemon, if so configured, without closing stderr and * stdout, and without changing the working directory */ if (config.daemon) { daemon(1, 1); } /* * flush "info" output stream to ensure log file accuracy */ fflush(info); /* * write out JSON preamble */ fprintf(output, "{\n"); config_print_json(output, &config); fprintf(output, "\"appflows\": [\n"); while(1) { struct timeval time_of_day, inactive_flow_cutoff; /* loop over packets captured from interface */ pcap_loop(handle, NUM_PACKETS_IN_LOOP, process_packet, NULL); if (output_level > none) { fprintf(output, "# pcap processing loop done\n"); } if (config.report_exe) { /* * periodically obtain host/process flow data */ if (get_host_flow_data() != 0) { fprintf(info, "warning: could not obtain host/process flow data\n"); } } /* * periodically report on progress */ if ((flocap_stats_get_num_packets() % NUM_PACKETS_BETWEEN_STATS_OUTPUT) == 0) { flocap_stats_output(info); } /* print out inactive flows */ gettimeofday(&time_of_day, NULL); timer_sub(&time_of_day, &time_window, &inactive_flow_cutoff); flow_record_list_print_json(&inactive_flow_cutoff); if (config.filename) { /* rotate output file if needed */ if (config.max_records && (records_in_file > config.max_records)) { /* * write JSON postamble */ fprintf(output, "\n] }\n"); fclose(output); if (config.upload_servername) { upload_file(filename, config.upload_servername, config.upload_key, config.retain_local); } // printf("records: %d\tmax_records: %d\n", records_in_file, config.max_records); file_count++; if (config.max_records != 0) { snprintf(filename + file_base_len, MAX_FILENAME_LEN - file_base_len, "%d", file_count); } output = fopen(filename, "w"); if (output == NULL) { perror("error: could not open output file"); return -1; } records_in_file = 0; fprintf(output, "{ \"appflows\": [\n"); } /* * flush out buffered debug/info/log messages on the "info" stream */ fflush(info); } // fflush(output); } fprintf(output, "\n] }\n"); if (filter_exp) { pcap_freecode(&fp); } pcap_close(handle); } else { /* mode = mode_offline */ if ((argc-opt_count <= 1) && (ifile == NULL)) { fprintf(stderr, "error: missing pcap file name(s)\n"); return usage(argv[0]); } fprintf(output, "{\n"); config_print_json(output, &config); fprintf(output, "\"appflows\": [\n"); flow_record_list_init(); flocap_stats_timer_init(); for (i=1+opt_count; i<argc; i++) { if (stat(argv[i], &sb) == 0 && S_ISDIR(sb.st_mode)) { if ((dir = opendir(argv[i])) != NULL) { while ((ent = readdir(dir)) != NULL) { if (strcmp(ent->d_name, ".") && strcmp(ent->d_name, "..")) { strcpy(pcap_filename, argv[i]); if (pcap_filename[strlen(pcap_filename)-1] != '/') { strcat(pcap_filename, "/"); } strcat(pcap_filename, ent->d_name); tmp_ret = process_pcap_file(pcap_filename, filter_exp, &net, &fp); if (tmp_ret < 0) { return tmp_ret; } } } closedir(dir); } else { /* error opening directory*/ printf("Error opening directory: %s\n", argv[i]); return -1; } } else { tmp_ret = process_pcap_file(argv[i], filter_exp, &net, &fp); if (tmp_ret < 0) { return tmp_ret; } } } fprintf(output, "\n]"); fprintf(output, "\n}\n"); } flocap_stats_output(info); // config_print(info, &config); return 0; }
static void run(unsigned specific_battle) { // N^2 battles struct combatant *u[NUM_UNITS]; unsigned int i, j, k, battle = 0; struct timeval start, end, total; for (i = 0; i < NUM_UNITS; ++i) { unsigned hp = 1 + ((i*3)%23); u[i] = new combatant(hp, hp + (i+7)%17, false); u[i]->set_weapon((i % 4) + 1, (i % 9) == 0, (i % 5) == 0, ((i+4) % 4) == 0, ((i+3) % 5) == 0); u[i]->set_effectiveness((i % 7) + 2, 0.3 + (i % 6)*0.1, (i % 8) == 0); } gettimeofday(&start, NULL); for (i = 0; i < NUM_UNITS; ++i) { for (j = 0; j < NUM_UNITS; ++j) { if (i == j) continue; for (k = 0; k < NUM_UNITS; ++k) { double untouched; if (i == k || j == k) continue; ++battle; if (specific_battle && battle != specific_battle) continue; u[j]->fight(*u[i]); // We need this here, because swarm means // out num hits can change. u[i]->set_effectiveness((i % 7) + 2, 0.3 + (i % 6)*0.1, (i % 8) == 0); u[k]->fight(*u[i]); u[i]->print("Defender", battle); u[j]->print("Attacker #1", battle); u[k]->print("Attacker #2", battle); u[i]->reset(); u[j]->reset(); u[k]->reset(); } } } gettimeofday(&end, NULL); timer_sub(&end, &start, &total); #ifdef BENCHMARK printf("Total time for %i combats was %lu.%06lu\n", NUM_UNITS*(NUM_UNITS-1)*(NUM_UNITS-2), total.tv_sec, total.tv_usec); printf("Time per calc = %li us\n", ((end.tv_sec-start.tv_sec)*1000000 + (end.tv_usec-start.tv_usec)) / (NUM_UNITS*(NUM_UNITS-1)*(NUM_UNITS-2))); #else printf("Total combats: %i\n", NUM_UNITS*(NUM_UNITS-1)*(NUM_UNITS-2)); #endif for (i = 0; i < NUM_UNITS; ++i) { delete u[i]; } exit(0); }
/* timer sub from current time */ timeval_t timer_sub_now(timeval_t a) { return timer_sub(time_now, a); }
/* timer sub from current time */ timeval_t timer_sub_now(timeval_t a) { return timer_sub(a, time_now); }
int PronyADMMClient(char* server_host, char* server_port, char* data_port, char* strategy, char* backupserver1_host, char* backupserver2_host, char* backupserver3_host, char* backupserver4_host, char* backupserver_port, char* num_of_attack, char* num_of_pdcs) { FILE* fFile; Logger* fLogger; fFile = fopen("/tmp/PronyADMM_client.log", "a"); fLogger = Logger_create(fFile, 0); log_debug(fLogger,"Start Prony client"); //For collecting event log and result int argc = 15; ofstream myfile; char filename[50]; char tempbuf1[5]; char tempbuf2[5]; char tempbuf3[5]; char timebuffer[25]; time_t now_time; time(&now_time); struct tm * tm_info; tm_info = localtime(&now_time); strcpy(filename, "/tmp/DistriProny_Result_"); strcat(filename, data_port); strcat(filename, "_"); snprintf(tempbuf1, 5, "%d", tm_info->tm_year+1900); strcat(filename, tempbuf1); strcat(filename, "-"); //itoa(now->tm_mon + 1, tempbuf2, 10); snprintf(tempbuf2, 5, "%d", tm_info->tm_mon + 1); strcat(filename, tempbuf2); strcat(filename, "-"); //itoa(now->tm_mday, tempbuf3, 10); snprintf(tempbuf3, 5, "%d", tm_info->tm_mday); strcat(filename, tempbuf3); strcat(filename, ".txt"); myfile.open(filename); int Iteration = 0; // Iteration = packet_no int counter = 0; int num_attack = 0; int i = 0; int Algorithm_Finishes = 0; struct timeval tvalStart, Start, End, Result, algo_start_time, timeout; gettimeofday (&Start, NULL); // Read sock for connection monitor of resiliency mechanism fd_set readfds; int select_ret; // Declare a vector for store the sample data vector<double> theta; theta.clear(); //===============1. Setup a TCP connection of client for sending localpara to main Prony_server============// struct hostent *he; struct in_addr **addr_list; char* ip; if ((he = gethostbyname(server_host)) == NULL) { // get the host info exit(1); } // print information about this host: addr_list = (struct in_addr **)he->h_addr_list; for(i = 0; addr_list[i] != NULL; i++) { ip = inet_ntoa(*addr_list[i]); } int sockfd = 0; struct sockaddr_in serv_addr; memset(&serv_addr, '0', sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(atoi(server_port)); if(inet_pton(AF_INET, ip, &serv_addr.sin_addr)<=0) { log_error(fLogger,"inet pton error"); return 1; } log_debug(fLogger, "Server Host: %s, IP: %s, Port:%s", server_host, ip, server_port); // Create a socket and connection with old server if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { log_error(fLogger,"Could not create socket."); return 1; } log_debug(fLogger,"Socket created"); if(connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) == -1) { log_error(fLogger,"connect() failed."); return 1; } log_debug(fLogger,"TCP Connection has been set up"); //===============2. Setup a TCP connection of server for receiving sample data from PMU============// // Set up TCP socket of server side for collecting PMU measurements for single PMU machine int Server_sockfd, data_sockfd; struct sockaddr_in LocalAddr, PMU_address; int Client_len = sizeof(PMU_address); // Initiate local TCP server socket LocalAddr.sin_family = AF_INET; LocalAddr.sin_addr.s_addr = htonl(INADDR_ANY); LocalAddr.sin_port = htons(atoi(data_port)); // Create, bind and listen the TCP_socket Server_sockfd = socket(AF_INET, SOCK_STREAM, 0); if (bind(Server_sockfd, (struct sockaddr *)&LocalAddr, sizeof(LocalAddr)) < 0) { log_debug(fLogger,"bind issue"); cout<<"Error: Can not bind the TCP socket! \n Please wait a few seconds or change port number."<<endl; return 1; } listen(Server_sockfd, DEFAULT_QUEUE_LEN); data_sockfd = accept(Server_sockfd,(struct sockaddr *)&PMU_address, (socklen_t*)&Client_len); printf("PMU Connection has been accepted and Prony VM is waiting for data ...\n"); //===============3. Parameters for Receiving PMU data and Parse data ====================// // Declare char pointer to token when parsing data char *token; string last; char b, lastchar; last = &b; int length, last_flag; int j, k; char Buffer[DEFAULT_MAX_BUFFER_LEN] = {0}; char tempBuffer[DEFAULT_MAX_BUFFER_LEN]; unsigned data_length; long int packet_send_time; // Prepare packet receiver buffer char *receive_packet; if((receive_packet=(char *)malloc(SERVER_MAX_BUF+sizeof(struct TCP_header)))==NULL) { cout<<"Fail to allocate memory for receive buffer, program is exiting ... "<<endl; exit(1); } struct TCP_header *receive_packet_header=(struct TCP_header *)receive_packet; char *receive_packet_content=(char *)(receive_packet_header+1); //================4. Calculate initial parameter vector a ================================// // Construct Intermedia Matrix H, C, a mat I(ParaNum, ParaNum); mat a(ParaNum,1); mat new_a(ParaNum,1); mat avgpara(ParaNum,1); mat new_avgpara(ParaNum,1); mat w(ParaNum,1); mat new_w(ParaNum,1); mat H(IniHeight,ParaNum); mat C(IniHeight,1); int TT; for (i=0; i<ParaNum; i++) { for (j=0; j<ParaNum; j++) { if (i==j){ I(i,j) = 1; } else { I(i,j) = 0; } } } for (i=0; i<ParaNum; i++) { a(i,0) = 1; w(i,0) = 0; avgpara(i,0) = 1; } //===============5. Parameters for Exchange Estimated Parameters with Server=====================// // form localpara message char* buffer = (char*)malloc(512*sizeof(char)); int size, avgBufferLen, flag; // Prepare receive buffer for avgpara char *avgBuffer = (char*)malloc(512*sizeof(char)); // For calculate new local parameters char *pht; // ======================= Main loop: Receive PMU data and Parse data and PronyADMM =========================// while(1) { log_debug(fLogger,"Main loop begin. Iteration: %d", Iteration); read(data_sockfd, receive_packet, DEFAULT_MAX_BUFFER_LEN); data_length = receive_packet_header->data_length; last_flag = receive_packet_header->last_flag; packet_send_time = receive_packet_header->packet_sending_time; // If this is not last package, request next one if (last_flag == 0) { size=sprintf(tempBuffer, "Request Next Package %d! \r\n\r\n",(Iteration+1)); printf( "Prony client VM Writes:\n %s \n", tempBuffer); write(data_sockfd, tempBuffer, size); // end request next one } memset(Buffer, '\0', 15); //log_debug(fLogger, "The length of last string is %d", last.length()); if((last.length()!= 0) && (Iteration != 0)) strncat(Buffer, last.c_str(), last.length()+1); strncat(Buffer, receive_packet_content, data_length); lastchar = Buffer[last.length()*sizeof(char)+data_length-1]; //log_debug(fLogger, "After receive packet %d, Buffer contains \n %s \n", Iteration, Buffer); memset(Buffer+(last.length()+data_length+1)*sizeof(char), '\0', 20); // ================= Parse the data from the Buffer ================= // length = 0; while (1) { token = strtok(Buffer+length*sizeof(char), "\n"); if (token == NULL){ if(last_flag == 0) theta.pop_back(); //if this is not last packet, the last record is discarded. break; } last = token; //log_debug(fLogger, "The data is %s", token); theta.push_back(strtod(token, NULL)); length = length + strlen(token) + 1; } // end of parsing data if (lastchar == '\n') last.append("\n"); for (i=0; i<(int)theta.size(); i++) //cout<<"theta["<<i<<"] is "<<theta[i]<<endl; // (II): Process each sample in this packet if (theta.size() >= IniHeight+ParaNum) { log_debug(fLogger, "size of theta is %d", theta.size()); for (k=counter; k<(int)theta.size(); k++) { log_debug(fLogger, "Iteration: %d", k); gettimeofday(&algo_start_time, NULL); // Step 1: Update matrice H and C, and Calculate new_a if (IniHeight+floor(k/5)<Height_H){ TT = IniHeight + floor(k/5); } else { TT = Height_H; } H.set_size(TT,ParaNum); C.set_size(TT,1); for (i=0; i<TT; i++){ C(i,0) = theta[ParaNum+i]; } //Note: we donot update C matrix real-time //C.print("C is"); for (i=0; i<TT; i++){ for (j=0; j<ParaNum; j++){ H(i,j) = theta[i+ParaNum-1-j]; } } new_a = inv(trans(H)*H + rho*I)*(trans(H) * C - w + rho*avgpara); // Step 2: Send out local parameter vector new_a gettimeofday (&tvalStart, NULL); // Record sending time // Format the export message size = sprintf(buffer, "Iteration: %d, %s: %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f\r\n Starttime: %ld \r\n\r\n", k, data_port, new_a(0), new_a(1), new_a(2), new_a(3), new_a(4), new_a(5), new_a(6), new_a(7), new_a(8), new_a(9), new_a(10), new_a(11), new_a(12), new_a(13), new_a(14), new_a(15), new_a(16), new_a(17), new_a(18), new_a(19), (tvalStart.tv_sec*1000000 + tvalStart.tv_usec)); //log_debug(fLogger, "The value of size is %d", size); log_debug(fLogger, "Sending message with time %ld", (tvalStart.tv_sec*1000000 + tvalStart.tv_usec)); // =========================== Resiliency Mechanism ===========================// //log_debug(fLogger, "Writing to server"); flag = write(sockfd, buffer, size); if (flag <= 0) { log_debug(fLogger, "Main server got attacked because the return value of write() function is negative."); num_attack++; sockfd = attackResProtocol(backupserver1_host, backupserver2_host, backupserver3_host, backupserver4_host, backupserver_port, num_of_attack, num_of_pdcs, num_attack, sockfd, fLogger); write(sockfd, buffer, size); // Write the local estimation to new server } //log_debug(fLogger, "Write successful"); if (Iteration == 1) { timeout.tv_sec = TEMP_TIMEOUT_SEC; timeout.tv_usec = TEMP_TIMEOUT_USEC; } else { timeout.tv_sec = TIMEOUT_SEC; timeout.tv_usec = TIMEOUT_USEC; } // initializes the set of active read sockets FD_ZERO(&readfds); FD_SET(sockfd, &readfds); log_debug(fLogger, "Selecting sockets to read"); select_ret = select(sockfd+1, &readfds, NULL, NULL, &timeout); log_debug(fLogger,"Return value of select is %d", select_ret); if(select_ret <= 0) { //case: error or timeout of select_ret is 0 num_attack++; log_debug(fLogger,"Main Server's link got attacked because the read() function times out."); sockfd = attackResProtocol(backupserver1_host, backupserver2_host, backupserver3_host, backupserver4_host, backupserver_port, num_of_attack, num_of_pdcs, num_attack, sockfd, fLogger); write(sockfd, buffer, size); // Write the local estimation to new server }// end if //log_debug(fLogger, "Select successful"); // ========================== End of Resiliency Mechanisim ==========================// //log_debug(fLogger, "Reading from server"); avgBufferLen = read(sockfd, avgBuffer, DEFAULT_MAX_BUFFER_LEN); log_debug(fLogger,"Return value of read is %d", avgBufferLen); if (avgBufferLen <= 0) { num_attack++; log_info(fLogger,"Main server got attacked because the return value of read() function is negative. Error: %d", errno); sockfd = attackResProtocol(backupserver1_host, backupserver2_host, backupserver3_host, backupserver4_host, backupserver_port, num_of_attack, num_of_pdcs, num_attack, sockfd, fLogger); write(sockfd, buffer, size); // Write the local estimation to new server avgBufferLen = read(sockfd, avgBuffer, DEFAULT_MAX_BUFFER_LEN); } //log_debug(fLogger, "Read successful"); avgBuffer[avgBufferLen]=0; if (strcmp(avgBuffer,"Distributed Prony Alogrithm finishes! \r\n\r\n")==0) { Algorithm_Finishes = 1; log_info(fLogger,"Distributed Prony Alogrithm finishes!"); break; } //Parse new_avgpara pht = strtok(avgBuffer, " "); pht = strtok(NULL, " "); pht = strtok(NULL, " "); //printf("This should be %s\n", pht); for (j=0; j<ParaNum; j++){ pht = strtok(NULL, " "); new_avgpara(j,0) = strtod(pht, NULL); } // Step 4: Update newer matrix C, H, and local para, Iteration ====================/ new_w = w + rho*(new_a - new_avgpara); a = new_a; avgpara = new_avgpara; w = new_w; }//end of for loop break; }//end of if sentence with theta.size()>initialHeight log_debug(fLogger,"End of Main loop. Iteration: %d", Iteration); if (Algorithm_Finishes == 1) break; counter = theta.size(); Iteration++; } //end big while loop if (Algorithm_Finishes == 1) { size = sprintf(tempBuffer, "Distributed Prony Alogrithm finishes! \r\n\r\n"); printf( "Prony Client VM Writes to PMU machine:\n %s \n", tempBuffer); write(data_sockfd, tempBuffer, size); } close(sockfd); log_debug(fLogger,"Prony algorithm ends happily. ^_^"); gettimeofday (&End, NULL); timer_sub(&Start, &End, &Result); fclose(fFile); return 0; } /* end of PronyADMMClient */