void main (void) { boardinit (); puts ("Going\n\r"); starttimer (10010000); while (gettimer () > 10000); puts ("Gone\n\r"); stoptimer (); }
static void net_worker_heartbeat(void) { time_t now; if (!locatorid || (locatorsvc == ST_MAX)) return; now = gettimer(); if (now > locatorhb) { locator_serverup(locatorid, locatorsvc); locatorhb = now + 60; } }
int state10(void) { unsigned char RecBuf[2]; char v=1; int otime,ctime; unsigned char Data_next; int Control=0; serialinit(); initAudio(); initCompr(); /* Synch with PC... */ serialtransmit('A'); otime=10000000; starttimer(SAMPLE_DELAY); ctime=gettimer(); while ( otime > ctime ) { otime=ctime; ctime=gettimer(); } RecBuf[0] = (getsample()); otime=1000; while (1) { /*starttimer(SAMPLE_DELAY);*/ while ( otime > (otime= gettimer() > 0) ); RecBuf[v] = (getsample()); if (v) { Control = compress(RecBuf[0],RecBuf[1]); } else { Control = serialtransmit(Control); if (Control) { serialclose(); return Control; } } v=1-v; } }
// =================================== // timersignal... // ----------------------------------- void timersignal(void) { int pid; int val; switch (tpid = fork()) { case 0: signal(SIGUSR2,resettimer); settimer(timeout); pid = getppid(); while(1) { val = gettimer(); sleep(1); kill (pid,SIGTRAP); } } }
/* Write a 1 */ void ringwriteone (void) { /* Set to output, expecting high */ spit->dra = 0xE0; spit->ddra = 0xE0; starttimer (10000000); /* Pull low for 10 us - this works... */ spit->dra = 0xC0; spit->dra = 0xC0; spit->dra = 0xC0; /* Set to input */ spit->ddra = 0xC0; /* Wait for a total of 120 us */ while (gettimer () > 10000000 - 40); }
void plot() { printf("Plotting %i ...\n",bs.len); RGBmp out=RGBmp(rm.width,rm.height,myRGB::black); starttimer(); for (int i=1;i<=bs.len;i++) { Blob *b=bs.p2num(i); if (!b->blobbed) { b->plot(&out); } } printf("%.1f seconds\n",gettimer()); String fname=getnextfilename("out","bmp"); out.writefile(fname); out.freedom(); if (usexv) system(Sconc("xv ",fname," &")); }
void informdoorbell (void) { packet pkt; char buzzer_pressed=BUZZER_PRESSED; /* Make a noise */ starttimer(40000); buzzerled(BUZZER); while(gettimer()>10000); buzzerled(ALLOFF); stoptimer(); /* Send packet */ pkt.datatype=CONTROL; pkt.data=&(buzzer_pressed); pkt.length=1; senddata(&pkt); }
/*********************************************************************************** * This function is the testing routine for the adaptive multilevel partitioning code. * It computes a partition from scratch, it then moves the graph and changes some * of the vertex weights and then call the adaptive code. ************************************************************************************/ void TestParMGridGen(char *filename, int *options, int minsize, int maxsize, MPI_Comm comm) { int i, nparts, npes, mype; MGridGraphType graph; idxtype *part; double tmr; MPI_Comm_size(comm, &npes); MPI_Comm_rank(comm, &mype); MGridReadTestGraph(&graph, filename, comm); part = idxmalloc(graph.nvtxs, "TestParMGridGen: part"); /*====================================================================== / ParMETIS_AspectRatio /=======================================================================*/ if (mype==0) printf("------------------------ PARAMETERS --------------------------------------\n"); for (i=0; i<npes; i++) if (mype == i) printf("%s, Dim=%d [%2d %2d] CType=%d RType=%d Nvtxs=%d Nedges=%d\n", filename, options[OPTION_DIM], minsize, maxsize, options[OPTION_CTYPE], options[OPTION_RTYPE], graph.nvtxs, graph.nedges); cleartimer(tmr); MPI_Barrier(comm); starttimer(tmr); ParMGridGen(graph.vtxdist, graph.xadj, graph.vvol, graph.vsurf, graph.adjncy, graph.adjwgt, &nparts, minsize, maxsize, options, part, &comm); MPI_Barrier(comm); stoptimer(tmr); printf("Total Time = %lf\n", gettimer(tmr)); WriteParallelPartition(filename, part, graph.vtxdist, nparts, mype, npes); IMfree(&graph.vtxdist, &graph.xadj, &graph.vvol, &graph.vsurf, &graph.vwgt, &graph.adjncy, &graph.adjwgt, &part, LTERM); }
int main(int argc, char *argv[]) { char *msg; int seq; int argi; int alertcolors, alertinterval; char *configfn = NULL; char *checkfn = NULL; int checkpointinterval = 900; char acklogfn[PATH_MAX]; FILE *acklogfd = NULL; char notiflogfn[PATH_MAX]; FILE *notiflogfd = NULL; char *tracefn = NULL; struct sigaction sa; int configchanged; time_t lastxmit = 0; MEMDEFINE(acklogfn); MEMDEFINE(notiflogfn); libxymon_init(argv[0]); /* Dont save the error buffer */ save_errbuf = 0; /* Load alert config */ alertcolors = colorset(xgetenv("ALERTCOLORS"), ((1 << COL_GREEN) | (1 << COL_BLUE))); alertinterval = 60*atoi(xgetenv("ALERTREPEAT")); /* Create our loookup-trees */ hostnames = xtreeNew(strcasecmp); testnames = xtreeNew(strcasecmp); locations = xtreeNew(strcasecmp); for (argi=1; (argi < argc); argi++) { if (argnmatch(argv[argi], "--config=")) { configfn = strdup(strchr(argv[argi], '=')+1); } else if (argnmatch(argv[argi], "--checkpoint-file=")) { checkfn = strdup(strchr(argv[argi], '=')+1); } else if (argnmatch(argv[argi], "--checkpoint-interval=")) { char *p = strchr(argv[argi], '=') + 1; checkpointinterval = atoi(p); } else if (argnmatch(argv[argi], "--dump-config")) { load_alertconfig(configfn, alertcolors, alertinterval); dump_alertconfig(1); return 0; } else if (argnmatch(argv[argi], "--cfid")) { include_configid = 1; } else if (argnmatch(argv[argi], "--test")) { char *testhost = NULL, *testservice = NULL, *testpage = NULL, *testcolor = "red", *testgroups = NULL; void *hinfo; int testdur = 0; FILE *logfd = NULL; activealerts_t *awalk = NULL; int paramno = 0; argi++; if (argi < argc) testhost = argv[argi]; argi++; if (argi < argc) testservice = argv[argi]; argi++; while (argi < argc) { if (strncasecmp(argv[argi], "--duration=", 11) == 0) { testdur = durationvalue(strchr(argv[argi], '=')+1); } else if (strncasecmp(argv[argi], "--color=", 8) == 0) { testcolor = strchr(argv[argi], '=')+1; } else if (strncasecmp(argv[argi], "--group=", 8) == 0) { testgroups = strchr(argv[argi], '=')+1; } else if (strncasecmp(argv[argi], "--time=", 7) == 0) { fakestarttime = (time_t)atoi(strchr(argv[argi], '=')+1); } else { paramno++; if (paramno == 1) testdur = atoi(argv[argi]); else if (paramno == 2) testcolor = argv[argi]; else if (paramno == 3) fakestarttime = (time_t) atoi(argv[argi]); } argi++; } if ((testhost == NULL) || (testservice == NULL)) { printf("Usage: xymond_alert --test HOST SERVICE [options]\n"); printf("Possible options:\n\t[--duration=MINUTES]\n\t[--color=COLOR]\n\t[--group=GROUPNAME]\n\t[--time=TIMESPEC]\n"); return 1; } load_hostnames(xgetenv("HOSTSCFG"), NULL, get_fqdn()); hinfo = hostinfo(testhost); if (hinfo) { testpage = strdup(xmh_item(hinfo, XMH_ALLPAGEPATHS)); } else { errprintf("Host not found in hosts.cfg - assuming it is on the top page\n"); testpage = ""; } awalk = (activealerts_t *)calloc(1, sizeof(activealerts_t)); awalk->hostname = find_name(hostnames, testhost); awalk->testname = find_name(testnames, testservice); awalk->location = find_name(locations, testpage); awalk->ip = strdup("127.0.0.1"); awalk->color = awalk->maxcolor = parse_color(testcolor); awalk->pagemessage = "Test of the alert configuration"; awalk->eventstart = getcurrenttime(NULL) - testdur*60; awalk->groups = (testgroups ? strdup(testgroups) : NULL); awalk->state = A_PAGING; awalk->cookie = 12345; awalk->next = NULL; logfd = fopen("/dev/null", "w"); starttrace(NULL); testonly = 1; load_alertconfig(configfn, alertcolors, alertinterval); load_holidays(0); send_alert(awalk, logfd); return 0; } else if (argnmatch(argv[argi], "--trace=")) { tracefn = strdup(strchr(argv[argi], '=')+1); starttrace(tracefn); } else if (net_worker_option(argv[argi])) { /* Handled in the subroutine */ } else if (standardoption(argv[argi])) { if (showhelp) return 0; } else { errprintf("Unknown option '%s'\n", argv[argi]); } } /* Do the network stuff if needed */ net_worker_run(ST_ALERT, LOC_SINGLESERVER, NULL); if (checkfn) { load_checkpoint(checkfn); nextcheckpoint = gettimer() + checkpointinterval; dbgprintf("Next checkpoint at %d, interval %d\n", (int) nextcheckpoint, checkpointinterval); } setup_signalhandler("xymond_alert"); /* Need to handle these ourselves, so we can shutdown and save state-info */ memset(&sa, 0, sizeof(sa)); sa.sa_handler = sig_handler; sigaction(SIGPIPE, &sa, NULL); sigaction(SIGTERM, &sa, NULL); sigaction(SIGINT, &sa, NULL); sigaction(SIGCHLD, &sa, NULL); sigaction(SIGUSR1, &sa, NULL); sigaction(SIGHUP, &sa, NULL); if (xgetenv("XYMONSERVERLOGS")) { sprintf(acklogfn, "%s/acknowledge.log", xgetenv("XYMONSERVERLOGS")); acklogfd = fopen(acklogfn, "a"); sprintf(notiflogfn, "%s/notifications.log", xgetenv("XYMONSERVERLOGS")); notiflogfd = fopen(notiflogfn, "a"); } /* * The general idea here is that this loop handles receiving of alert- * and ack-messages from the master daemon, and maintains a list of * host+test combinations that may have alerts going out. * * This module does not deal with any specific alert-configuration, * it just picks up the alert messages, maintains the list of * known tests that are in some sort of critical condition, and * periodically pushes alerts to the do_alert.c module for handling. * * The only modification of alerts that happen here is the handling * of when the next alert is due. It calls into the next_alert() * routine to learn when an alert should be repeated, and also * deals with Acknowledgments that stop alerts from going out for * a period of time. */ while (running) { char *eoln, *restofmsg; char *metadata[20]; char *p; int metacount; char *hostname = NULL, *testname = NULL; struct timespec timeout; time_t now, nowtimer; int anytogo; activealerts_t *awalk; int childstat; nowtimer = gettimer(); if (checkfn && (nowtimer > nextcheckpoint)) { dbgprintf("Saving checkpoint\n"); nextcheckpoint = nowtimer + checkpointinterval; save_checkpoint(checkfn); if (acklogfd) acklogfd = freopen(acklogfn, "a", acklogfd); if (notiflogfd) notiflogfd = freopen(notiflogfn, "a", notiflogfd); } timeout.tv_sec = 60; timeout.tv_nsec = 0; msg = get_xymond_message(C_PAGE, "xymond_alert", &seq, &timeout); if (msg == NULL) { running = 0; continue; } /* See what time it is - must happen AFTER the timeout */ now = getcurrenttime(NULL); /* Split the message in the first line (with meta-data), and the rest */ eoln = strchr(msg, '\n'); if (eoln) { *eoln = '\0'; restofmsg = eoln+1; } else { restofmsg = ""; } /* * Now parse the meta-data into elements. * We use our own "gettok()" routine which works * like strtok(), but can handle empty elements. */ metacount = 0; memset(&metadata, 0, sizeof(metadata)); p = gettok(msg, "|"); while (p && (metacount < 19)) { metadata[metacount] = p; metacount++; p = gettok(NULL, "|"); } metadata[metacount] = NULL; if (metacount > 3) hostname = metadata[3]; if (metacount > 4) testname = metadata[4]; if ((metacount > 10) && (strncmp(metadata[0], "@@page", 6) == 0)) { /* @@page|timestamp|sender|hostname|testname|hostip|expiretime|color|prevcolor|changetime|location|cookie|osname|classname|grouplist|modifiers */ int newcolor, newalertstatus, oldalertstatus; dbgprintf("Got page message from %s:%s\n", hostname, testname); traceprintf("@@page %s:%s:%s=%s\n", hostname, testname, metadata[10], metadata[7]); awalk = find_active(hostname, testname); if (awalk == NULL) { char *hwalk = find_name(hostnames, hostname); char *twalk = find_name(testnames, testname); char *pwalk = find_name(locations, metadata[10]); awalk = (activealerts_t *)calloc(1, sizeof(activealerts_t)); awalk->hostname = hwalk; awalk->testname = twalk; awalk->location = pwalk; awalk->cookie = -1; awalk->state = A_DEAD; /* * Use changetime here, if we restart the alert module then * this gets the duration values more right than using "now". * Also, define this only when a new alert arrives - we should * NOT clear this when a status goes yellow->red, or if it * flaps between yellow and red. */ awalk->eventstart = atoi(metadata[9]); add_active(awalk->hostname, awalk); traceprintf("New record\n"); } newcolor = parse_color(metadata[7]); oldalertstatus = ((alertcolors & (1 << awalk->color)) != 0); newalertstatus = ((alertcolors & (1 << newcolor)) != 0); traceprintf("state %d->%d\n", oldalertstatus, newalertstatus); if (newalertstatus) { /* It's in an alert state. */ awalk->color = newcolor; awalk->state = A_PAGING; if (newcolor > awalk->maxcolor) { if (awalk->maxcolor != 0) { /* * Severity has increased (yellow -> red). * Clear the repeat-interval, and set maxcolor to * the new color. If it drops to yellow again, * maxcolor stays at red, so a test that flaps * between yellow and red will only alert on red * the first time, and then follow the repeat * interval. */ dbgprintf("Severity increased, cleared repeat interval: %s/%s %s->%s\n", awalk->hostname, awalk->testname, colorname(awalk->maxcolor), colorname(newcolor)); clear_interval(awalk); } awalk->maxcolor = newcolor; } } else { /* * Send one "recovered" message out now, then go to A_DEAD. * Dont update the color here - we want recoveries to go out * only if the alert color triggered an alert */ awalk->state = (newcolor == COL_BLUE) ? A_DISABLED : A_RECOVERED; } if (oldalertstatus != newalertstatus) { dbgprintf("Alert status changed from %d to %d\n", oldalertstatus, newalertstatus); clear_interval(awalk); } if (awalk->ip) xfree(awalk->ip); awalk->ip = strdup(metadata[5]); awalk->cookie = atoi(metadata[11]); if (awalk->osname) xfree(awalk->osname); awalk->osname = (metadata[12] ? strdup(metadata[12]) : NULL); if (awalk->classname) xfree(awalk->classname); awalk->classname = (metadata[13] ? strdup(metadata[13]) : NULL); if (awalk->groups) xfree(awalk->groups); awalk->groups = (metadata[14] ? strdup(metadata[14]) : NULL); if (awalk->pagemessage) xfree(awalk->pagemessage); if (metadata[15]) { /* Modifiers are more interesting than the message itself */ awalk->pagemessage = (char *)malloc(strlen(awalk->hostname) + strlen(awalk->testname) + strlen(colorname(awalk->color)) + strlen(metadata[15]) + strlen(restofmsg) + 10); sprintf(awalk->pagemessage, "%s:%s %s\n%s\n%s", awalk->hostname, awalk->testname, colorname(awalk->color), metadata[15], restofmsg); } else { awalk->pagemessage = strdup(restofmsg); } } else if ((metacount > 5) && (strncmp(metadata[0], "@@ack", 5) == 0)) { /* @@ack|timestamp|sender|hostname|testname|hostip|expiretime */ /* * An ack is handled simply by setting the next * alert-time to when the ack expires. */ time_t nextalert = atoi(metadata[6]); dbgprintf("Got ack message from %s:%s\n", hostname, testname); traceprintf("@@ack: %s:%s now=%d, ackeduntil %d\n", hostname, testname, (int)now, (int)nextalert); awalk = find_active(hostname, testname); if (acklogfd) { int cookie = (awalk ? awalk->cookie : -1); int color = (awalk ? awalk->color : 0); fprintf(acklogfd, "%d\t%d\t%d\t%d\t%s\t%s.%s\t%s\t%s\n", (int)now, cookie, (int)((nextalert - now) / 60), cookie, "np_filename_not_used", hostname, testname, colorname(color), nlencode(restofmsg)); fflush(acklogfd); } if (awalk && (awalk->state == A_PAGING)) { traceprintf("Record updated\n"); awalk->state = A_ACKED; awalk->nextalerttime = nextalert; if (awalk->ackmessage) xfree(awalk->ackmessage); awalk->ackmessage = strdup(restofmsg); } else { traceprintf("No record\n"); } } else if ((metacount > 4) && (strncmp(metadata[0], "@@notify", 5) == 0)) { /* @@notify|timestamp|sender|hostname|testname|pagepath */ char *hwalk = find_name(hostnames, hostname); char *twalk = find_name(testnames, testname); char *pwalk = find_name(locations, (metadata[5] ? metadata[5] : "")); awalk = (activealerts_t *)calloc(1, sizeof(activealerts_t)); awalk->hostname = hwalk; awalk->testname = twalk; awalk->location = pwalk; awalk->cookie = -1; awalk->pagemessage = strdup(restofmsg); awalk->eventstart = getcurrenttime(NULL); awalk->state = A_NOTIFY; add_active(awalk->hostname, awalk); } else if ((metacount > 3) && ((strncmp(metadata[0], "@@drophost", 10) == 0) || (strncmp(metadata[0], "@@dropstate", 11) == 0))) { /* @@drophost|timestamp|sender|hostname */ /* @@dropstate|timestamp|sender|hostname */ xtreePos_t handle; handle = xtreeFind(hostnames, hostname); if (handle != xtreeEnd(hostnames)) { alertanchor_t *anchor = (alertanchor_t *)xtreeData(hostnames, handle); for (awalk = anchor->head; (awalk); awalk = awalk->next) awalk->state = A_DEAD; } } else if ((metacount > 4) && (strncmp(metadata[0], "@@droptest", 10) == 0)) { /* @@droptest|timestamp|sender|hostname|testname */ awalk = find_active(hostname, testname); if (awalk) awalk->state = A_DEAD; } else if ((metacount > 4) && (strncmp(metadata[0], "@@renamehost", 12) == 0)) { /* @@renamehost|timestamp|sender|hostname|newhostname */ /* * We handle rename's simply by dropping the alert. If there is still an * active alert for the host, it will have to be dealt with when the next * status update arrives. */ xtreePos_t handle; handle = xtreeFind(hostnames, hostname); if (handle != xtreeEnd(hostnames)) { alertanchor_t *anchor = (alertanchor_t *)xtreeData(hostnames, handle); for (awalk = anchor->head; (awalk); awalk = awalk->next) awalk->state = A_DEAD; } } else if ((metacount > 5) && (strncmp(metadata[0], "@@renametest", 12) == 0)) { /* @@renametest|timestamp|sender|hostname|oldtestname|newtestname */ /* * We handle rename's simply by dropping the alert. If there is still an * active alert for the host, it will have to be dealt with when the next * status update arrives. */ awalk = find_active(hostname, testname); if (awalk) awalk->state = A_DEAD; } else if (strncmp(metadata[0], "@@shutdown", 10) == 0) { running = 0; errprintf("Got a shutdown message\n"); continue; } else if (strncmp(metadata[0], "@@logrotate", 11) == 0) { char *fn = xgetenv("XYMONCHANNEL_LOGFILENAME"); if (fn && strlen(fn)) { reopen_file(fn, "a", stdout); reopen_file(fn, "a", stderr); if (tracefn) { stoptrace(); starttrace(tracefn); } } continue; } else if (strncmp(metadata[0], "@@reload", 8) == 0) { /* Nothing ... right now */ } else if (strncmp(metadata[0], "@@idle", 6) == 0) { /* Timeout */ } /* * When a burst of alerts happen, we get lots of alert messages * coming in quickly. So lets handle them in bunches and only * do the full alert handling once every 10 secs - that lets us * combine a bunch of alerts into one transmission process. */ if (nowtimer < (lastxmit+10)) continue; lastxmit = nowtimer; /* * Loop through the activealerts list and see if anything is pending. * This is an optimization, we could just as well just fork off the * notification child and let it handle all of it. But there is no * reason to fork a child process unless it is going to do something. */ configchanged = load_alertconfig(configfn, alertcolors, alertinterval); configchanged += load_holidays(0); anytogo = 0; for (awalk = alistBegin(); (awalk); awalk = alistNext()) { int anymatch = 0; switch (awalk->state) { case A_NORECIP: if (!configchanged) break; /* The configuration has changed - switch NORECIP -> PAGING */ awalk->state = A_PAGING; clear_interval(awalk); /* Fall through */ case A_PAGING: if (have_recipient(awalk, &anymatch)) { if (awalk->nextalerttime <= now) anytogo++; } else { if (!anymatch) { awalk->state = A_NORECIP; cleanup_alert(awalk); } } break; case A_ACKED: if (awalk->nextalerttime <= now) { /* An ack has expired, so drop the ack message and switch to A_PAGING */ anytogo++; if (awalk->ackmessage) xfree(awalk->ackmessage); awalk->state = A_PAGING; } break; case A_RECOVERED: case A_DISABLED: case A_NOTIFY: anytogo++; break; case A_DEAD: break; } } dbgprintf("%d alerts to go\n", anytogo); if (anytogo) { pid_t childpid; childpid = fork(); if (childpid == 0) { /* The child */ start_alerts(); for (awalk = alistBegin(); (awalk); awalk = alistNext()) { switch (awalk->state) { case A_PAGING: if (awalk->nextalerttime <= now) { send_alert(awalk, notiflogfd); } break; case A_ACKED: /* Cannot be A_ACKED unless the ack is still valid, so no alert. */ break; case A_RECOVERED: case A_DISABLED: case A_NOTIFY: send_alert(awalk, notiflogfd); break; case A_NORECIP: case A_DEAD: break; } } finish_alerts(); /* Child does not continue */ exit(0); } else if (childpid < 0) { errprintf("Fork failed, cannot send alerts: %s\n", strerror(errno)); } } /* Update the state flag and the next-alert timestamp */ for (awalk = alistBegin(); (awalk); awalk = alistNext()) { switch (awalk->state) { case A_PAGING: if (awalk->nextalerttime <= now) awalk->nextalerttime = next_alert(awalk); break; case A_NORECIP: break; case A_ACKED: /* Still cannot get here except if ack is still valid */ break; case A_RECOVERED: case A_DISABLED: case A_NOTIFY: awalk->state = A_DEAD; /* Fall through */ case A_DEAD: cleanup_alert(awalk); break; } } clean_all_active(); /* Pickup any finished child processes to avoid zombies */ while (wait3(&childstat, WNOHANG, NULL) > 0) ; } if (checkfn) save_checkpoint(checkfn); if (acklogfd) fclose(acklogfd); if (notiflogfd) fclose(notiflogfd); stoptrace(); MEMUNDEFINE(notiflogfn); MEMUNDEFINE(acklogfn); if (termsig >= 0) { errprintf("Terminated by signal %d\n", termsig); } return 0; }
int main(int argc, char *argv[]) { int daemonize = 0; char *pidfile = NULL; char *envarea = NULL; int cnid = -1; pcre *msgfilter = NULL; pcre *stdfilter = NULL; int argi; struct sigaction sa; RbtIterator handle; /* Dont save the error buffer */ save_errbuf = 0; /* Create the peer container */ peers = rbtNew(name_compare); for (argi=1; (argi < argc); argi++) { if (argnmatch(argv[argi], "--debug")) { debug = 1; } else if (argnmatch(argv[argi], "--channel=")) { char *cn = strchr(argv[argi], '=') + 1; for (cnid = C_STATUS; (channelnames[cnid] && strcmp(channelnames[cnid], cn)); cnid++) ; if (channelnames[cnid] == NULL) cnid = -1; } else if (argnmatch(argv[argi], "--daemon")) { daemonize = 1; } else if (argnmatch(argv[argi], "--no-daemon")) { daemonize = 0; } else if (argnmatch(argv[argi], "--pidfile=")) { char *p = strchr(argv[argi], '='); pidfile = strdup(p+1); } else if (argnmatch(argv[argi], "--log=")) { char *p = strchr(argv[argi], '='); logfn = strdup(p+1); } else if (argnmatch(argv[argi], "--env=")) { char *p = strchr(argv[argi], '='); loadenv(p+1, envarea); } else if (argnmatch(argv[argi], "--area=")) { char *p = strchr(argv[argi], '='); envarea = strdup(p+1); } else if (argnmatch(argv[argi], "--locator=")) { char *p = strchr(argv[argi], '='); locator_init(p+1); locatorbased = 1; } else if (argnmatch(argv[argi], "--service=")) { char *p = strchr(argv[argi], '='); locatorservice = get_servicetype(p+1); } else if (argnmatch(argv[argi], "--filter=")) { char *p = strchr(argv[argi], '='); msgfilter = compileregex(p+1); if (!msgfilter) { errprintf("Invalid filter (bad expression): %s\n", p+1); } else { stdfilter = compileregex("^@@(logrotate|shutdown|drophost|droptest|renamehost|renametest)"); } } else { char *childcmd; char **childargs; int i = 0; childcmd = argv[argi]; childargs = (char **) calloc((1 + argc - argi), sizeof(char *)); while (argi < argc) { childargs[i++] = argv[argi++]; } addlocalpeer(childcmd, childargs); } } /* Sanity checks */ if (cnid == -1) { errprintf("No channel/unknown channel specified\n"); return 1; } if (locatorbased && (locatorservice == ST_MAX)) { errprintf("Must specify --service when using locator\n"); return 1; } if (!locatorbased && (rbtBegin(peers) == rbtEnd(peers))) { errprintf("Must specify command for local worker\n"); return 1; } /* Do cache responses to avoid doing too many lookups */ if (locatorbased) locator_prepcache(locatorservice, 0); /* Go daemon */ if (daemonize) { /* Become a daemon */ pid_t daemonpid = fork(); if (daemonpid < 0) { /* Fork failed */ errprintf("Could not fork child\n"); exit(1); } else if (daemonpid > 0) { /* Parent creates PID file and exits */ FILE *fd = NULL; if (pidfile) fd = fopen(pidfile, "w"); if (fd) { fprintf(fd, "%d\n", (int)daemonpid); fclose(fd); } exit(0); } /* Child (daemon) continues here */ setsid(); } /* Catch signals */ setup_signalhandler("xymond_channel"); memset(&sa, 0, sizeof(sa)); sa.sa_handler = sig_handler; sigaction(SIGINT, &sa, NULL); sigaction(SIGTERM, &sa, NULL); sigaction(SIGCHLD, &sa, NULL); signal(SIGALRM, SIG_IGN); /* Switch stdout/stderr to the logfile, if one was specified */ freopen("/dev/null", "r", stdin); /* xymond_channel's stdin is not used */ if (logfn) { freopen(logfn, "a", stdout); freopen(logfn, "a", stderr); } /* Attach to the channel */ channel = setup_channel(cnid, CHAN_CLIENT); if (channel == NULL) { errprintf("Channel not available\n"); running = 0; } while (running) { /* * Wait for GOCLIENT to go up. * * Note that we use IPC_NOWAIT if there are messages in the * queue, because then we just want to pick up a message if * there is one, and if not we want to continue pushing the * queued data to the worker. */ struct sembuf s; int n; s.sem_num = GOCLIENT; s.sem_op = -1; s.sem_flg = ((pendingcount > 0) ? IPC_NOWAIT : 0); n = semop(channel->semid, &s, 1); if (n == 0) { /* * GOCLIENT went high, and so we got alerted about a new * message arriving. Copy the message to our own buffer queue. */ char *inbuf = NULL; if (!msgfilter || matchregex(channel->channelbuf, msgfilter) || matchregex(channel->channelbuf, stdfilter)) { inbuf = strdup(channel->channelbuf); } /* * Now we have safely stored the new message in our buffer. * Wait until any other clients on the same channel have picked up * this message (GOCLIENT reaches 0). * * We wrap this into an alarm handler, because it can occasionally * fail, causing the whole system to lock up. We dont want that.... * We'll set the alarm to trigger after 1 second. Experience shows * that we'll either succeed in a few milliseconds, or fail completely * and wait the full alarm-timer duration. */ gotalarm = 0; signal(SIGALRM, sig_handler); alarm(2); do { s.sem_num = GOCLIENT; s.sem_op = 0; s.sem_flg = 0; n = semop(channel->semid, &s, 1); } while ((n == -1) && (errno == EAGAIN) && running && (!gotalarm)); signal(SIGALRM, SIG_IGN); if (gotalarm) { errprintf("Gave up waiting for GOCLIENT to go low.\n"); } /* * Let master know we got it by downing BOARDBUSY. * This should not block, since BOARDBUSY is upped * by the master just before he ups GOCLIENT. */ do { s.sem_num = BOARDBUSY; s.sem_op = -1; s.sem_flg = IPC_NOWAIT; n = semop(channel->semid, &s, 1); } while ((n == -1) && (errno == EINTR)); if (n == -1) { errprintf("Tried to down BOARDBUSY: %s\n", strerror(errno)); } if (inbuf) { /* * See if they want us to rotate logs. We pass this on to * the worker module as well, but must handle our own logfile. */ if (strncmp(inbuf, "@@logrotate", 11) == 0) { freopen(logfn, "a", stdout); freopen(logfn, "a", stderr); } /* * Put the new message on our outbound queue. */ if (addmessage(inbuf) != 0) { /* Failed to queue message, free the buffer */ xfree(inbuf); } } } else { if (errno != EAGAIN) { dbgprintf("Semaphore wait aborted: %s\n", strerror(errno)); continue; } } /* * We've picked up messages from the master. Now we * must push them to the worker process. Since there * is no way to hang off both a semaphore and select(), * we'll just push as much data as possible into the * pipe. If we get to a point where we would block, * then wait a teeny bit of time and restart the * whole loop with checking for new messages from the * master etc. * * In theory, this could become an almost busy-wait loop. * In practice, however, the queue will be empty most * of the time because we'll just shove the data to the * worker child. */ for (handle = rbtBegin(peers); (handle != rbtEnd(peers)); handle = rbtNext(peers, handle)) { int canwrite = 1, hasfailed = 0; xymon_peer_t *pwalk; time_t msgtimeout = gettimer() - MSGTIMEOUT; int flushcount = 0; pwalk = (xymon_peer_t *) gettreeitem(peers, handle); if (pwalk->msghead == NULL) continue; /* Ignore peers with nothing queued */ switch (pwalk->peerstatus) { case P_UP: canwrite = 1; break; case P_DOWN: openconnection(pwalk); canwrite = (pwalk->peerstatus == P_UP); break; case P_FAILED: canwrite = 0; break; } /* See if we have stale messages queued */ while (pwalk->msghead && (pwalk->msghead->tstamp < msgtimeout)) { flushmessage(pwalk); flushcount++; } if (flushcount) { errprintf("Flushed %d stale messages for %s:%d\n", flushcount, inet_ntoa(pwalk->peeraddr.sin_addr), ntohs(pwalk->peeraddr.sin_port)); } while (pwalk->msghead && canwrite) { fd_set fdwrite; struct timeval tmo; /* Check that this peer is ready for writing. */ FD_ZERO(&fdwrite); FD_SET(pwalk->peersocket, &fdwrite); tmo.tv_sec = 0; tmo.tv_usec = 2000; n = select(pwalk->peersocket+1, NULL, &fdwrite, NULL, &tmo); if (n == -1) { errprintf("select() failed: %s\n", strerror(errno)); canwrite = 0; hasfailed = 1; continue; } else if ((n == 0) || (!FD_ISSET(pwalk->peersocket, &fdwrite))) { canwrite = 0; continue; } n = write(pwalk->peersocket, pwalk->msghead->bufp, pwalk->msghead->buflen); if (n >= 0) { pwalk->msghead->bufp += n; pwalk->msghead->buflen -= n; if (pwalk->msghead->buflen == 0) flushmessage(pwalk); } else if (errno == EAGAIN) { /* * Write would block ... stop for now. */ canwrite = 0; } else { hasfailed = 1; } if (hasfailed) { /* Write failed, or message grew stale */ errprintf("Peer at %s:%d failed: %s\n", inet_ntoa(pwalk->peeraddr.sin_addr), ntohs(pwalk->peeraddr.sin_port), strerror(errno)); canwrite = 0; shutdownconnection(pwalk); if (pwalk->peertype == P_NET) locator_serverdown(pwalk->peername, locatorservice); pwalk->peerstatus = P_FAILED; } } } } /* Detach from channels */ close_channel(channel, CHAN_CLIENT); /* Close peer connections */ for (handle = rbtBegin(peers); (handle != rbtEnd(peers)); handle = rbtNext(peers, handle)) { xymon_peer_t *pwalk = (xymon_peer_t *) gettreeitem(peers, handle); shutdownconnection(pwalk); } /* Remove the PID file */ if (pidfile) unlink(pidfile); return 0; }
void openconnection(xymon_peer_t *peer) { int n; int pfd[2]; pid_t childpid; time_t now; peer->peerstatus = P_DOWN; now = gettimer(); if (now < (peer->lastopentime + 60)) return; /* Will only attempt one open per minute */ dbgprintf("Connecting to peer %s:%d\n", inet_ntoa(peer->peeraddr.sin_addr), ntohs(peer->peeraddr.sin_port)); peer->lastopentime = now; switch (peer->peertype) { case P_NET: /* Get a socket, and connect to the peer */ peer->peersocket = socket(PF_INET, SOCK_STREAM, 0); if (peer->peersocket == -1) { errprintf("Cannot get socket: %s\n", strerror(errno)); return; } n = connect(peer->peersocket, (struct sockaddr *)&peer->peeraddr, sizeof(peer->peeraddr)); if (n == -1) { errprintf("Cannot connect to peer %s:%d : %s\n", inet_ntoa(peer->peeraddr.sin_addr), ntohs(peer->peeraddr.sin_port), strerror(errno)); return; } break; case P_LOCAL: /* Create a pipe to the child handler program, and run it */ n = pipe(pfd); if (n == -1) { errprintf("Could not get a pipe: %s\n", strerror(errno)); return; } childpid = fork(); if (childpid == -1) { errprintf("Could not fork channel handler: %s\n", strerror(errno)); return; } else if (childpid == 0) { /* The channel handler child */ if (logfn) { char *logfnenv = (char *)malloc(strlen(logfn) + 30); sprintf(logfnenv, "XYMONCHANNEL_LOGFILENAME=%s", logfn); putenv(logfnenv); } n = dup2(pfd[0], STDIN_FILENO); close(pfd[0]); close(pfd[1]); n = execvp(peer->childcmd, peer->childargs); /* We should never go here */ errprintf("exec() failed for child command %s: %s\n", peer->childcmd, strerror(errno)); exit(1); } /* Parent process continues */ close(pfd[0]); peer->peersocket = pfd[1]; peer->childpid = childpid; break; } fcntl(peer->peersocket, F_SETFL, O_NONBLOCK); peer->peerstatus = P_UP; dbgprintf("Peer is UP\n"); }
// render earth and terrain geometry void miniview::render_geometry(float sbase, BOOLINT anaglyph) { minilayer *nst; if (m_cam==NULL) return; // start timer starttimer(); // get camera lens float fovy = m_cam->get_fovy(); float aspect = (float)get()->winwidth/get()->winheight; double nearp = m_cam->get_nearp(); double farp = m_cam->get_farp(); // update camera lens m_cam->set_lens(fovy, aspect, nearp, farp); // propagate camera lens PARAMS.fovy = fovy; PARAMS.nearp = nearp; PARAMS.farp = farp; miniscene::propagate(); // set reference layer nst = getearth()->getnearest(m_cam->get_eye()); getearth()->setreference(nst); // update scene cache(m_cam->get_eye(), m_cam->get_dir(), m_cam->get_up(), m_cam->get_aspect()); // clear scene clear(); // render scene if (sbase==0.0f) { setup_matrix(); render(); } else { // left stereo channel setup_matrix(-sbase); if (anaglyph) enableRwriting(); else writeleftbuffer(); render(); // right stereo channel setup_matrix(sbase); cleardepthbuffer(); if (anaglyph) enableGBwriting(); else writerightbuffer(); render(); if (anaglyph) enableRGBwriting(); else writebackbuffer(); } // get time spent double delta = gettimer(); // update quality parameters adapt(delta); }
void findlines() { int tolerance=1; while (true && tolerance<rm.width+rm.height) { bool change=true; while (change) { printf("Extending words %i ...\n",bs.len); change=false; starttimer(); for (int i=1;i<=bs.len;i++) { Blob *b=bs.p2num(i); if (!b->blobbed) if (b->gettype()==Word) { // printf("%i/%i\n",i,bs.len); V2d cen=b->centroid; V2d o=b->ori(); float len=b->width(); V2d u=o*len; float hei=b->height(); V2d v=o.perp()*hei; // Search cen, ori List<int> hits; List<Pixel> search; V2d out=o*hei*Extension; V2d up=o.perp()*hei/2.0; search.addandfree(Pixel::line(cen+u+up,cen+u+up+out)); search.addandfree(Pixel::line(cen+u+up+out,cen+u-up+out)); search.addandfree(Pixel::line(cen+u-up+out,cen+u-up)); search.addandfree(Pixel::line(cen-u+up,cen-u+up-out)); search.addandfree(Pixel::line(cen-u+up-out,cen-u-up-out)); search.addandfree(Pixel::line(cen-u-up-out,cen-u-up)); for (int j=1;j<=search.len;j++) { int g=rm.getpos(search.num(j)); if (g>0) { g=finddad(g); if (g!=i) hits.addifnot(g); } } search.freedom(); if (hits.len==0) b->type=Sentence; else { // printf("%i hits\n",hits.len); addhits(i,hits); change=true; } hits.freedom(); } } printf("%.1f seconds\n",gettimer()); if (change) { lookforparagraphs(); // plot(); } } change=false; printf("Joining neighbours %i ...\n",bs.len); starttimer(); while (!change) { int bsatstart=bs.len; for (int i=1;i<=bs.len;i++) { if (!bs.p2num(i)->blobbed) { if (showprogress && ((i % 10)==1)) printf("%i/%i\n",i,bs.len); List<int> hits=findfriends(i,tolerance); if (hits.len>0) { addhits(i,hits); change=true; } } } if ((bsatstart!=bs.len)!=change) printf("Addhits says change %i, bs num change says %i\n",change,(bsatstart!=bs.len)); if (change) { lookforparagraphs(); } tolerance++; } printf("%.1f seconds\n",gettimer()); plot(); } }
int main(int argc, char *argv[]) { char *msg; int argi; struct sigaction sa; char *exthandler = NULL; char *extids = NULL; char *processor = NULL; struct sockaddr_un ctlsockaddr; int ctlsocket; /* Handle program options. */ for (argi = 1; (argi < argc); argi++) { if (strcmp(argv[argi], "--debug") == 0) { debug = 1; } else if (argnmatch(argv[argi], "--rrddir=")) { char *p = strchr(argv[argi], '='); rrddir = strdup(p+1); } else if (argnmatch(argv[argi], "--extra-script=")) { char *p = strchr(argv[argi], '='); exthandler = strdup(p+1); } else if (argnmatch(argv[argi], "--extra-tests=")) { char *p = strchr(argv[argi], '='); extids = strdup(p+1); } else if (argnmatch(argv[argi], "--processor=")) { char *p = strchr(argv[argi], '='); processor = strdup(p+1); } else if (strcmp(argv[argi], "--no-cache") == 0) { use_rrd_cache = 0; } else if (net_worker_option(argv[argi])) { /* Handled in the subroutine */ } } save_errbuf = 0; if ((rrddir == NULL) && xgetenv("XYMONRRDS")) { rrddir = strdup(xgetenv("XYMONRRDS")); } if (exthandler && extids) setup_exthandler(exthandler, extids); /* Do the network stuff if needed */ net_worker_run(ST_RRD, LOC_STICKY, update_locator_hostdata); setup_signalhandler("xymond_rrd"); memset(&sa, 0, sizeof(sa)); sa.sa_handler = sig_handler; sigaction(SIGHUP, &sa, NULL); sigaction(SIGCHLD, &sa, NULL); sigaction(SIGTERM, &sa, NULL); sigaction(SIGINT, &sa, NULL); signal(SIGPIPE, SIG_DFL); /* Setup the control socket that receives cache-flush commands */ memset(&ctlsockaddr, 0, sizeof(ctlsockaddr)); sprintf(ctlsockaddr.sun_path, "%s/rrdctl.%d", xgetenv("XYMONTMP"), getpid()); unlink(ctlsockaddr.sun_path); /* In case it was accidentally left behind */ ctlsockaddr.sun_family = AF_UNIX; ctlsocket = socket(AF_UNIX, SOCK_DGRAM, 0); if (ctlsocket == -1) { errprintf("Cannot create cache-control socket (%s)\n", strerror(errno)); return 1; } fcntl(ctlsocket, F_SETFL, O_NONBLOCK); if (bind(ctlsocket, (struct sockaddr *)&ctlsockaddr, sizeof(ctlsockaddr)) == -1) { errprintf("Cannot bind to cache-control socket (%s)\n", strerror(errno)); return 1; } /* Linux obeys filesystem permissions on the socket file, so make it world-accessible */ if (chmod(ctlsockaddr.sun_path, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH) == -1) { errprintf("Setting permissions on cache-control socket failed: %s\n", strerror(errno)); } /* Load the RRD definitions */ load_rrddefs(); /* If we are passing data to an external processor, create the pipe to it */ setup_extprocessor(processor); running = 1; while (running) { char *eoln, *restofmsg = NULL; char *metadata[MAX_META+1]; int metacount; char *p; char *hostname = NULL, *testname = NULL, *sender = NULL, *classname = NULL, *pagepaths = NULL; xymonrrd_t *ldef = NULL; time_t tstamp; int childstat; ssize_t n; char ctlbuf[PATH_MAX]; int gotcachectlmessage; time_t now; /* See if we have any cache-control messages pending */ do { n = recv(ctlsocket, ctlbuf, sizeof(ctlbuf), 0); gotcachectlmessage = (n > 0); if (gotcachectlmessage) { /* We have a control message */ char *bol, *eol; ctlbuf[n] = '\0'; bol = ctlbuf; do { eol = strchr(bol, '\n'); if (eol) *eol = '\0'; rrdcacheflushhost(bol); if (eol) { bol = eol+1; } else bol = NULL; } while (bol && *bol); } } while (gotcachectlmessage); /* Get next message */ msg = get_xymond_message(C_LAST, argv[0], &seq, NULL); if (msg == NULL) { running = 0; continue; } now = gettimer(); if (reloadtime < now) { /* Reload configuration files */ load_hostnames(xgetenv("HOSTSCFG"), NULL, get_fqdn()); load_client_config(NULL); reloadtime = now + 600; } /* Split the message in the first line (with meta-data), and the rest */ eoln = strchr(msg, '\n'); if (eoln) { *eoln = '\0'; restofmsg = eoln+1; } /* Parse the meta-data */ metacount = 0; memset(&metadata, 0, sizeof(metadata)); p = gettok(msg, "|"); while (p && (metacount < MAX_META)) { metadata[metacount++] = p; p = gettok(NULL, "|"); } metadata[metacount] = NULL; if ((metacount >= 14) && (strncmp(metadata[0], "@@status", 8) == 0)) { /* * @@status|timestamp|sender|origin|hostname|testname|expiretime|color|testflags|\ * prevcolor|changetime|ackexpiretime|ackmessage|disableexpiretime|disablemessage|\ * clienttstamp|flapping|classname|pagepaths */ int color = parse_color(metadata[7]); switch (color) { case COL_GREEN: case COL_YELLOW: case COL_RED: case COL_BLUE: /* Blue is OK, because it only arrives here when an update is sent */ tstamp = atoi(metadata[1]); sender = metadata[2]; hostname = metadata[4]; testname = metadata[5]; classname = (metadata[17] ? metadata[17] : ""); pagepaths = (metadata[18] ? metadata[18] : ""); ldef = find_xymon_rrd(testname, metadata[8]); update_rrd(hostname, testname, restofmsg, tstamp, sender, ldef, classname, pagepaths); break; default: /* Ignore reports with purple, blue or clear - they have no data we want. */ break; } } else if ((metacount > 5) && (strncmp(metadata[0], "@@data", 6) == 0)) { /* @@data|timestamp|sender|origin|hostname|testname|classname|pagepaths */ tstamp = atoi(metadata[1]); sender = metadata[2]; hostname = metadata[4]; testname = metadata[5]; classname = (metadata[6] ? metadata[6] : ""); pagepaths = (metadata[7] ? metadata[7] : ""); ldef = find_xymon_rrd(testname, ""); update_rrd(hostname, testname, restofmsg, tstamp, sender, ldef, classname, pagepaths); } else if (strncmp(metadata[0], "@@shutdown", 10) == 0) { running = 0; continue; } else if (strncmp(metadata[0], "@@idle", 6) == 0) { /* Ignored */ continue; } else if (strncmp(metadata[0], "@@logrotate", 11) == 0) { char *fn = xgetenv("XYMONCHANNEL_LOGFILENAME"); if (fn && strlen(fn)) { freopen(fn, "a", stdout); freopen(fn, "a", stderr); } continue; } else if (strncmp(metadata[0], "@@reload", 8) == 0) { reloadtime = 0; } else if ((metacount > 3) && (strncmp(metadata[0], "@@drophost", 10) == 0)) { char hostdir[PATH_MAX]; hostname = metadata[3]; MEMDEFINE(hostdir); sprintf(hostdir, "%s/%s", rrddir, hostname); dropdirectory(hostdir, 1); MEMUNDEFINE(hostdir); } else if ((metacount > 4) && (strncmp(metadata[0], "@@droptest", 10) == 0)) { /* * Not implemented. Mappings of testnames -> rrd files is * too complex, so on the rare occasion that a single test * is deleted, they will have to delete the rrd files themselves. */ } else if ((metacount > 4) && (strncmp(metadata[0], "@@renamehost", 12) == 0)) { char oldhostdir[PATH_MAX]; char newhostdir[PATH_MAX]; char *newhostname; MEMDEFINE(oldhostdir); MEMDEFINE(newhostdir); hostname = metadata[3]; newhostname = metadata[4]; sprintf(oldhostdir, "%s/%s", rrddir, hostname); sprintf(newhostdir, "%s/%s", rrddir, newhostname); rename(oldhostdir, newhostdir); if (net_worker_locatorbased()) locator_rename_host(hostname, newhostname, ST_RRD); MEMUNDEFINE(newhostdir); MEMUNDEFINE(oldhostdir); } else if ((metacount > 5) && (strncmp(metadata[0], "@@renametest", 12) == 0)) { /* Not implemented. See "droptest". */ } /* * We fork a subprocess when processing drophost requests. * Pickup any finished child processes to avoid zombies */ while (wait3(&childstat, WNOHANG, NULL) > 0) ; } /* Flush all cached updates to disk */ errprintf("Shutting down, flushing cached updates to disk\n"); rrdcacheflushall(); errprintf("Cache flush completed\n"); /* Close the external processor */ shutdown_extprocessor(); /* Close the control socket */ close(ctlsocket); unlink(ctlsockaddr.sun_path); return 0; }
void main (void) { int i; unsigned char k; ringinfo ri; puts ("G7 hardware diagnostics\n\r"); puts ("\n\rInitialising board..."); boardinit (); puts (" done\n\r"); puts ("\n\r ** Timer test\n\r"); puts ("Waiting for 3 seconds..."); starttimer (1010000); while (gettimer () > 10000); puts (" done\n\r"); puts ("\n\r ** iButton reader test\n\r"); puts ("Place an iButton in the reader...\n\r"); i = 0; do { while (!checkring ()); ri = getringinfo (); i++; } while (ri.crc == 0xFF); puts ("iButton read ("); putn (i, 10, 2); puts (" times); product family "); putn (ri.product, 16, 2); puts ("; user ID "); for (i = 0; i < 6; i++) putn (ri.id [i], 16, 2); puts ("; CRC "); putn (ri.crc, 16, 2); puts ("\n\r"); puts ("\n\r ** Keypad test\n\r"); puts ("Press all the keys and the doorbell...\n\r"); for (i = 0; i < 13; i++) { k = getkeypad (); starttimer (40000); buzzerled (BUZZER); while (gettimer () > 10000); buzzerled (ALLOFF); stoptimer (); puts ("Key pressed: "); if (k < 10) putn (k, 10, 1); else switch (k) { case KP_STAR: puts ("*"); break; case KP_HASH: puts ("#"); break; case KP_DOORBELL: puts ("doorbell"); break; case KP_UNDEF: puts ("undefined ("); putn (k, 16, 2); puts (")"); break; } puts ("\n\r"); } puts ("\n\r ** Beeper test\n\r"); starttimer (10000000); buzzerled (BUZZER); while (gettimer () > 10000000 - 30000); buzzerled (ALLOFF); while (gettimer () > 10000000 - 40000); buzzerled (BUZZER); while (gettimer () > 10000000 - 70000); buzzerled (ALLOFF); stoptimer (); puts ("\n\r ** Door open test\n\r"); for (i = 0; i < 5; i++) { starttimer (210000); buzzerled (LEDGREEN); while (gettimer () > 110000); buzzerled (ALLOFF); while (gettimer () > 10000); stoptimer (); } puts ("\n\r ** Entry denied test\n\r"); for (i = 0; i < 5; i++) { starttimer (210000); buzzerled (LEDRED); while (gettimer () > 110000); buzzerled (ALLOFF); while (gettimer () > 10000); stoptimer (); } puts ("\n\r ** Door status test\n\r"); puts ("Close the door, then press a key\n\r"); mon_getc (); puts ("Door status is "); putn (getdoorstatus (), 10, 1); puts ("\n\r"); puts ("Open the door, then press a key\n\r"); mon_getc (); puts ("Door status is "); putn (getdoorstatus (), 10, 1); puts ("\n\r"); puts ("\n\r ** Testing done\n\r"); }
/************************************************************************* * Let the game begin **************************************************************************/ main(int argc, char *argv[]) { int i, j, ne, nn, etype, numflag=0, nparts, edgecut; idxtype *elmnts, *epart, *npart; timer IOTmr, DUALTmr; char etypestr[4][5] = {"TRI", "TET", "HEX", "QUAD"}; GraphType graph; if (argc != 3) { printf("Usage: %s <meshfile> <nparts>\n",argv[0]); exit(0); } nparts = atoi(argv[2]); if (nparts < 2) { printf("nparts must be greater than one.\n"); exit(0); } cleartimer(IOTmr); cleartimer(DUALTmr); starttimer(IOTmr); elmnts = ReadMesh(argv[1], &ne, &nn, &etype); stoptimer(IOTmr); epart = idxmalloc(ne, "main: epart"); npart = idxmalloc(nn, "main: npart"); printf("**********************************************************************\n"); printf("%s", METISTITLE); printf("Mesh Information ----------------------------------------------------\n"); printf(" Name: %s, #Elements: %d, #Nodes: %d, Etype: %s\n\n", argv[1], ne, nn, etypestr[etype-1]); printf("Partitioning Nodal Graph... -----------------------------------------\n"); starttimer(DUALTmr); METIS_PartMeshNodal(&ne, &nn, elmnts, &etype, &numflag, &nparts, &edgecut, epart, npart); stoptimer(DUALTmr); printf(" %d-way Edge-Cut: %7d, Balance: %5.2f\n", nparts, edgecut, ComputeElementBalance(ne, nparts, epart)); starttimer(IOTmr); WriteMeshPartition(argv[1], nparts, ne, epart, nn, npart); stoptimer(IOTmr); printf("\nTiming Information --------------------------------------------------\n"); printf(" I/O: \t\t %7.3f\n", gettimer(IOTmr)); printf(" Partitioning: \t\t %7.3f\n", gettimer(DUALTmr)); printf("**********************************************************************\n"); /* graph.nvtxs = ne; graph.xadj = idxmalloc(ne+1, "xadj"); graph.vwgt = idxsmalloc(ne, 1, "vwgt"); graph.adjncy = idxmalloc(10*ne, "adjncy"); graph.adjwgt = idxsmalloc(10*ne, 1, "adjncy"); METIS_MeshToDual(&ne, &nn, elmnts, &etype, &numflag, graph.xadj, graph.adjncy); ComputePartitionInfo(&graph, nparts, epart); GKfree(&graph.xadj, &graph.adjncy, &graph.vwgt, &graph.adjwgt, LTERM); */ GKfree(&elmnts, &epart, &npart, LTERM); }
int main(int argc, char *argv[]) { char *msg; int running; int argi, seq; struct timespec *timeout = NULL; pcre *hostexp = NULL; pcre *exhostexp = NULL; pcre *testexp = NULL; pcre *extestexp = NULL; pcre *colorexp = NULL; const char *errmsg = NULL; int errofs = 0; FILE *logfd = stdout; int batchtimeout = 30; char *batchcmd = NULL; strbuffer_t *batchbuf = NULL; time_t lastmsgtime = 0; /* Handle program options. */ for (argi = 1; (argi < argc); argi++) { if (strcmp(argv[argi], "--debug") == 0) { /* * A global "debug" variable is available. If * it is set, then "dbgprintf()" outputs debug messages. */ debug = 1; } else if (strncmp(argv[argi], "--timeout=", 10) == 0) { /* * You can have a timeout when waiting for new * messages. If it happens, you will get a "@@idle\n" * message with sequence number 0. * If you dont want a timeout, just pass a NULL for the timeout parameter. */ timeout = (struct timespec *)(malloc(sizeof(struct timespec))); timeout->tv_sec = (atoi(argv[argi]+10)); timeout->tv_nsec = 0; } else if (argnmatch(argv[argi], "--hosts=")) { char *exp = strchr(argv[argi], '=') + 1; hostexp = pcre_compile(exp, PCRE_CASELESS, &errmsg, &errofs, NULL); if (hostexp == NULL) printf("Invalid expression '%s'\n", exp); } else if (argnmatch(argv[argi], "--exhosts=")) { char *exp = strchr(argv[argi], '=') + 1; exhostexp = pcre_compile(exp, PCRE_CASELESS, &errmsg, &errofs, NULL); if (exhostexp == NULL) printf("Invalid expression '%s'\n", exp); } else if (argnmatch(argv[argi], "--tests=")) { char *exp = strchr(argv[argi], '=') + 1; testexp = pcre_compile(exp, PCRE_CASELESS, &errmsg, &errofs, NULL); if (testexp == NULL) printf("Invalid expression '%s'\n", exp); } else if (argnmatch(argv[argi], "--extests=")) { char *exp = strchr(argv[argi], '=') + 1; extestexp = pcre_compile(exp, PCRE_CASELESS, &errmsg, &errofs, NULL); if (extestexp == NULL) printf("Invalid expression '%s'\n", exp); } else if (argnmatch(argv[argi], "--colors=")) { char *exp = strchr(argv[argi], '=') + 1; colorexp = pcre_compile(exp, PCRE_CASELESS, &errmsg, &errofs, NULL); if (colorexp == NULL) printf("Invalid expression '%s'\n", exp); } else if (argnmatch(argv[argi], "--outfile=")) { char *fn = strchr(argv[argi], '=') + 1; logfd = fopen(fn, "a"); if (logfd == NULL) { printf("Cannot open logfile %s: %s\n", fn, strerror(errno)); logfd = stdout; } } else if (argnmatch(argv[argi], "--batch-timeout=")) { char *p = strchr(argv[argi], '='); batchtimeout = atoi(p+1); timeout = (struct timespec *)(malloc(sizeof(struct timespec))); timeout->tv_sec = batchtimeout; timeout->tv_nsec = 0; } else if (argnmatch(argv[argi], "--batch-command=")) { char *p = strchr(argv[argi], '='); batchcmd = strdup(p+1); batchbuf = newstrbuffer(0); } else { printf("Unknown option %s\n", argv[argi]); printf("Usage: %s [--hosts=EXP] [--tests=EXP] [--exhosts=EXP] [--extests=EXP] [--color=EXP] [--outfile=FILENAME] [--batch-timeout=N] [--batch-command=COMMAND]\n", argv[0]); return 0; } } signal(SIGCHLD, SIG_IGN); running = 1; while (running) { char *eoln, *restofmsg, *p; char *metadata[MAX_META+1]; int metacount; msg = get_hobbitd_message(C_LAST, argv[0], &seq, timeout); if (msg == NULL) { /* * get_hobbitd_message will return NULL if hobbitd_channel closes * the input pipe. We should shutdown when that happens. */ running = 0; continue; } /* * Now we have a message. So do something with it. * * The first line of the message is always a '|' separated * list of meta-data about the message. After the first * line, the content varies by channel. */ /* Split the message in the first line (with meta-data), and the rest */ eoln = strchr(msg, '\n'); if (eoln) { *eoln = '\0'; restofmsg = eoln+1; } else { restofmsg = ""; } /* * Now parse the meta-data into elements. * We use our own "gettok()" routine which works * like strtok(), but can handle empty elements. */ metacount = 0; memset(&metadata, 0, sizeof(metadata)); p = gettok(msg, "|"); while (p && (metacount < MAX_META)) { metadata[metacount++] = p; p = gettok(NULL, "|"); } metadata[metacount] = NULL; /* * A "shutdown" message is sent when the master daemon * terminates. The child workers should shutdown also. */ if (strncmp(metadata[0], "@@shutdown", 10) == 0) { printf("Shutting down\n"); running = 0; continue; } /* * A "logrotate" message is sent when the Hobbit logs are * rotated. The child workers must re-open their logfiles, * typically stdin and stderr - the filename is always * provided in the HOBBITCHANNEL_LOGFILENAME environment. */ else if (strncmp(metadata[0], "@@logrotate", 11) == 0) { char *fn = xgetenv("HOBBITCHANNEL_LOGFILENAME"); if (fn && strlen(fn)) { freopen(fn, "a", stdout); freopen(fn, "a", stderr); } continue; } /* * An "idle" message appears when get_hobbitd_message() * exceeds the timeout setting (ie. you passed a timeout * value). This allows your worker module to perform * some internal processing even though no messages arrive. */ else if (strncmp(metadata[0], "@@idle", 6) == 0) { dbgprintf("Got an 'idle' message\n"); } /* * The "drophost", "droptest", "renamehost" and "renametst" * indicates that a host/test was deleted or renamed. If the * worker module maintains some internal storage (in memory * or persistent file-storage), it should act on these * messages to maintain data consistency. */ else if ((metacount > 3) && (strncmp(metadata[0], "@@drophost", 10) == 0)) { dbgprintf("Got a 'drophost' message for host '%s'\n", metadata[3]); } else if ((metacount > 3) && (strncmp(metadata[0], "@@dropstate", 11) == 0)) { dbgprintf("Got a 'dropstate' message for host '%s'\n", metadata[3]); } else if ((metacount > 4) && (strncmp(metadata[0], "@@droptest", 10) == 0)) { dbgprintf("Got a 'droptest' message for host '%s' test '%s'\n", metadata[3], metadata[4]); } else if ((metacount > 4) && (strncmp(metadata[0], "@@renamehost", 12) == 0)) { dbgprintf("Got a 'renamehost' message for host '%s' -> '%s'\n", metadata[3], metadata[4]); } else if ((metacount > 5) && (strncmp(metadata[0], "@@renametest", 12) == 0)) { dbgprintf("Got a 'renametest' message for host '%s' test '%s' -> '%s'\n", metadata[3], metadata[4], metadata[5]); } /* * Process this message. */ else { int ovector[30]; int match, i; char *hostname = metadata[4]; char *testname = metadata[5]; char *color = metadata[7]; /* See if we should handle the batched messages we've got */ if (batchcmd && ((lastmsgtime + batchtimeout) < gettimer()) && (STRBUFLEN(batchbuf) > 0)) { pid_t childpid = fork(); int childres = 0; if (childpid < 0) { /* Fork failed! */ errprintf("Fork failed: %s\n", strerror(errno)); } else if (childpid == 0) { /* Child */ FILE *cmdpipe = popen(batchcmd, "w"); if (cmdpipe) { /* Write the data to the batch command pipe */ int n, bytesleft = STRBUFLEN(batchbuf); char *outp = STRBUF(batchbuf); while (bytesleft) { n = fwrite(outp, 1, bytesleft, cmdpipe); if (n >= 0) { bytesleft -= n; outp += n; } else { errprintf("Error while writing data to batch command\n"); bytesleft = 0; } } childres = pclose(cmdpipe); } else { errprintf("Could not open pipe to batch command '%s'\n", batchcmd); childres = 127; } exit(childres); } else if (childpid > 0) { /* Parent continues */ } clearstrbuffer(batchbuf); } if (hostexp) { match = (pcre_exec(hostexp, NULL, hostname, strlen(hostname), 0, 0, ovector, (sizeof(ovector)/sizeof(int))) >= 0); if (!match) continue; } if (exhostexp) { match = (pcre_exec(exhostexp, NULL, hostname, strlen(hostname), 0, 0, ovector, (sizeof(ovector)/sizeof(int))) >= 0); if (match) continue; } if (testexp) { match = (pcre_exec(testexp, NULL, testname, strlen(testname), 0, 0, ovector, (sizeof(ovector)/sizeof(int))) >= 0); if (!match) continue; } if (exhostexp) { match = (pcre_exec(extestexp, NULL, testname, strlen(testname), 0, 0, ovector, (sizeof(ovector)/sizeof(int))) >= 0); if (match) continue; } if (colorexp) { match = (pcre_exec(colorexp, NULL, color, strlen(color), 0, 0, ovector, (sizeof(ovector)/sizeof(int))) >= 0); if (!match) continue; } lastmsgtime = gettimer(); if (batchcmd) { addtobuffer(batchbuf, "## "); for (i=0; (i < metacount); i++) { addtobuffer(batchbuf, metadata[i]); addtobuffer(batchbuf, " "); } addtobuffer(batchbuf, "\n"); addtobuffer(batchbuf, restofmsg); addtobuffer(batchbuf, "\n"); } else { fprintf(logfd, "## "); for (i=0; (i < metacount); i++) fprintf(logfd, "%s ", metadata[i]); fprintf(logfd, "\n"); fprintf(logfd, "%s\n", restofmsg); } } } return 0; }
/************************************************************************* * This function prints the various timers **************************************************************************/ void PrintTimers(CtrlType *ctrl) { printf("\nTiming Information -------------------------------------------------"); printf("\n Multilevel: \t\t %7.3f", gettimer(ctrl->TotalTmr)); printf("\n Coarsening: \t\t %7.3f", gettimer(ctrl->CoarsenTmr)); printf("\n Matching: \t\t\t %7.3f", gettimer(ctrl->MatchTmr)); printf("\n Contract: \t\t\t %7.3f", gettimer(ctrl->ContractTmr)); printf("\n Initial Partition: \t %7.3f", gettimer(ctrl->InitPartTmr)); printf("\n Construct Separator: \t %7.3f", gettimer(ctrl->SepTmr)); printf("\n Uncoarsening: \t\t %7.3f", gettimer(ctrl->UncoarsenTmr)); printf("\n Refinement: \t\t\t %7.3f", gettimer(ctrl->RefTmr)); printf("\n Projection: \t\t\t %7.3f", gettimer(ctrl->ProjectTmr)); printf("\n Splitting: \t\t %7.3f", gettimer(ctrl->SplitTmr)); printf("\n AUX1: \t\t %7.3f", gettimer(ctrl->AuxTmr1)); printf("\n AUX2: \t\t %7.3f", gettimer(ctrl->AuxTmr2)); printf("\n AUX3: \t\t %7.3f", gettimer(ctrl->AuxTmr3)); printf("\n********************************************************************\n"); }
/* *Main */ int main(int argc, char** argv) { int estado=0; int* pestado=&estado; int estadomenu=POS1; int* pestadomenu=&estadomenu; int estadoconfiguracion=USUARIO; int* pestadoconfiguracion=&estadoconfiguracion; int condiciones=0; //por lo que me devuelva la funcion setear comienzo int estadomensaje=0; int* pestadomensaje=&estadomensaje; if(inicializar()){ return -1; } ALLEGRO_DISPLAY* display=NULL; ALLEGRO_EVENT_QUEUE* eventos=NULL; //Son basicamente los punteros a estructuras propias de Allegro para la inicializacion de lo ALLEGRO_TIMER* timer=NULL; //basico y necesario para hacer funcionar las funciones de esta libreria display=getdisplay(PANTALLA_ANCHO,PANTALLA_ALTO); eventos=geteventqueue(); //llamo las funciones que crearan los displays y eventos timer=gettimer(1.0/FPS); if(display==ERROR||eventos==ERROR||timer==ERROR){ return -1; //si fallo alguna de las funciones llamadas, retorno del main, mostrando que hubo un error } al_register_event_source(eventos, al_get_display_event_source(display)); al_register_event_source(eventos, al_get_timer_event_source(timer)); //registro los eventos al_register_event_source(eventos, al_get_mouse_event_source()); al_register_event_source(eventos,al_get_keyboard_event_source()); ALLEGRO_BITMAP* imagencelular=NULL; imagencelular=al_load_bitmap("foto_celular.png"); if(imagencelular==NULL){fprintf(stderr,"No se pudo cargar la imagen\n");return -1;} //chequeo que no haya habido errores al_draw_bitmap(imagencelular,-40,-20,0); al_flip_display(); ALLEGRO_BITMAP* pantalla=NULL; //a partir de ahora, solo trabajaremos graficamente en la pantalla pantalla=al_create_bitmap(220,288); //tiene el tamaño de la pantalla cambiopantalla(display,pantalla); al_clear_to_color(al_map_rgb(255,255,255)); //siempre que quiera modificar al bitmap pantalla para despues "pegarlo" cambiopantalla(display,pantalla); /* * La secuencia que realizamos aqui... al_set_target_bitmap(pantalla); * * CAMBIOS ASOCIADOS A LA PANTALLA * * al_set_target_bitmap(al_get_backbuffer(display)); * al_draw_bitmap(pantalla,48,118,0); * al_flip_display(); * es la que esta comprimida en estas dos funciones * */ al_start_timer(timer); //inicializo el timer INFOPANTALLA mipantalla=getuserdata(); INFOPANTALLA* pmipantalla=&mipantalla; iniciarpantalla(mipantalla,display,pantalla); while(estado!=FINALIZAR){ if(estado==PANTALLAPRINCIPAL){ mantenerpantalla(mipantalla,display,pantalla); analizartecladopantalla(eventos,pestado,display,pantalla); } if(estado==MENU){ mantenermenu(pestado,pestadomenu,display,pantalla,mipantalla); analizartecladomenu(eventos,pestado,pestadomenu); } if(estado==MENSAJE){ escribirmensaje(eventos,display,pantalla,pestado,pestadomensaje,pmipantalla); } if(estado==PERSONALIZAR){ mantenerconfiguracion(pestadoconfiguracion,display,pantalla,eventos,pestado,pmipantalla); analizartecladoconfiguracion(eventos,pestadoconfiguracion,pestado,pmipantalla); } } putuserdata(mipantalla); *pestado=PANTALLAPRINCIPAL; return (EXIT_SUCCESS); }
int main(int argc, char *argv[]) { time_t starttime = gettimer(); char *histdir = NULL; char *histlogdir = NULL; char *msg; int argi, seq; int save_allevents = 1; int save_hostevents = 1; int save_statusevents = 1; int save_histlogs = 1, defaultsaveop = 1; FILE *alleventsfd = NULL; int running = 1; struct sigaction sa; char newcol2[3]; char oldcol2[3]; char alleventsfn[PATH_MAX]; char pidfn[PATH_MAX]; int logdirfull = 0; int minlogspace = 5; MEMDEFINE(pidfn); MEMDEFINE(alleventsfn); MEMDEFINE(newcol2); MEMDEFINE(oldcol2); /* Dont save the error buffer */ save_errbuf = 0; sprintf(pidfn, "%s/xymond_history.pid", xgetenv("XYMONSERVERLOGS")); if (xgetenv("XYMONALLHISTLOG")) save_allevents = (strcmp(xgetenv("XYMONALLHISTLOG"), "TRUE") == 0); if (xgetenv("XYMONHOSTHISTLOG")) save_hostevents = (strcmp(xgetenv("XYMONHOSTHISTLOG"), "TRUE") == 0); if (xgetenv("SAVESTATUSLOG")) save_histlogs = (strncmp(xgetenv("SAVESTATUSLOG"), "FALSE", 5) != 0); for (argi = 1; (argi < argc); argi++) { if (argnmatch(argv[argi], "--histdir=")) { histdir = strchr(argv[argi], '=')+1; } else if (argnmatch(argv[argi], "--histlogdir=")) { histlogdir = strchr(argv[argi], '=')+1; } else if (argnmatch(argv[argi], "--pidfile=")) { strcpy(pidfn, strchr(argv[argi], '=')+1); } else if (argnmatch(argv[argi], "--minimum-free=")) { minlogspace = atoi(strchr(argv[argi], '=')+1); } else if (argnmatch(argv[argi], "--debug")) { debug = 1; } } if (xgetenv("XYMONHISTDIR") && (histdir == NULL)) { histdir = strdup(xgetenv("XYMONHISTDIR")); } if (histdir == NULL) { errprintf("No history directory given, aborting\n"); return 1; } if (save_histlogs && (histlogdir == NULL) && xgetenv("XYMONHISTLOGS")) { histlogdir = strdup(xgetenv("XYMONHISTLOGS")); } if (save_histlogs && (histlogdir == NULL)) { errprintf("No history-log directory given, aborting\n"); return 1; } columndefs = xtreeNew(strcmp); { char *defaultsave, *tok; char *savelist; columndef_t *newrec; savelist = strdup(xgetenv("SAVESTATUSLOG")); defaultsave = strtok(savelist, ","); /* * TRUE: Save everything by default; may list some that are not saved. * ONLY: Save nothing by default; may list some that are saved. * FALSE: Save nothing. */ defaultsaveop = (strcasecmp(defaultsave, "TRUE") == 0); tok = strtok(NULL, ","); while (tok) { newrec = (columndef_t *)malloc(sizeof(columndef_t)); if (*tok == '!') { newrec->saveit = 0; newrec->name = strdup(tok+1); } else { newrec->saveit = 1; newrec->name = strdup(tok); } xtreeAdd(columndefs, newrec->name, newrec); tok = strtok(NULL, ","); } xfree(savelist); } { FILE *pidfd = fopen(pidfn, "w"); if (pidfd) { fprintf(pidfd, "%lu\n", (unsigned long)getpid()); fclose(pidfd); } } sprintf(alleventsfn, "%s/allevents", histdir); if (save_allevents) { alleventsfd = fopen(alleventsfn, "a"); if (alleventsfd == NULL) { errprintf("Cannot open the all-events file '%s'\n", alleventsfn); } setvbuf(alleventsfd, (char *)NULL, _IOLBF, 0); } /* For picking up lost children */ setup_signalhandler("xymond_history"); memset(&sa, 0, sizeof(sa)); sa.sa_handler = sig_handler; sigaction(SIGCHLD, &sa, NULL); sigaction(SIGHUP, &sa, NULL); signal(SIGPIPE, SIG_DFL); while (running) { char *metadata[20] = { NULL, }; int metacount; char *p; char *statusdata = ""; char *hostname, *hostnamecommas, *testname, *dismsg, *modifiers; time_t tstamp, lastchg, disabletime, clienttstamp; int tstamp_i, lastchg_i; int newcolor, oldcolor; int downtimeactive; struct tm tstamptm; int trend; int childstat; /* Pickup any finished child processes to avoid zombies */ while (wait3(&childstat, WNOHANG, NULL) > 0) ; if (rotatefiles && alleventsfd) { fclose(alleventsfd); alleventsfd = fopen(alleventsfn, "a"); if (alleventsfd == NULL) { errprintf("Cannot re-open the all-events file '%s'\n", alleventsfn); } else { setvbuf(alleventsfd, (char *)NULL, _IOLBF, 0); } } msg = get_xymond_message(C_STACHG, "xymond_history", &seq, NULL); if (msg == NULL) { running = 0; continue; } if (nextfscheck < gettimer()) { logdirfull = (chkfreespace(histlogdir, minlogspace, minlogspace) != 0); if (logdirfull) errprintf("Historylog directory %s has less than %d%% free space - disabling save of data for 5 minutes\n", histlogdir, minlogspace); nextfscheck = gettimer() + 300; } p = strchr(msg, '\n'); if (p) { *p = '\0'; statusdata = msg_data(p+1, 0); } metacount = 0; memset(&metadata, 0, sizeof(metadata)); p = gettok(msg, "|"); while (p && (metacount < 20)) { metadata[metacount++] = p; p = gettok(NULL, "|"); } if ((metacount > 9) && (strncmp(metadata[0], "@@stachg", 8) == 0)) { xtreePos_t handle; columndef_t *saveit = NULL; /* @@stachg#seq|timestamp|sender|origin|hostname|testname|expiretime|color|prevcolor|changetime|disabletime|disablemsg|downtimeactive|clienttstamp|modifiers */ sscanf(metadata[1], "%d.%*d", &tstamp_i); tstamp = tstamp_i; hostname = metadata[4]; testname = metadata[5]; newcolor = parse_color(metadata[7]); oldcolor = parse_color(metadata[8]); lastchg = atoi(metadata[9]); disabletime = atoi(metadata[10]); dismsg = metadata[11]; downtimeactive = (atoi(metadata[12]) > 0); clienttstamp = atoi(metadata[13]); modifiers = metadata[14]; if (newcolor == -1) { errprintf("Bad message: newcolor is unknown '%s'\n", metadata[7]); continue; } p = hostnamecommas = strdup(hostname); while ((p = strchr(p, '.')) != NULL) *p = ','; handle = xtreeFind(columndefs, testname); if (handle == xtreeEnd(columndefs)) { saveit = (columndef_t *)malloc(sizeof(columndef_t)); saveit->name = strdup(testname); saveit->saveit = defaultsaveop; xtreeAdd(columndefs, saveit->name, saveit); } else { saveit = (columndef_t *) xtreeData(columndefs, handle); } if (save_statusevents) { char statuslogfn[PATH_MAX]; int logexists; FILE *statuslogfd; char oldcol[100]; char timestamp[40]; struct stat st; MEMDEFINE(statuslogfn); MEMDEFINE(oldcol); MEMDEFINE(timestamp); sprintf(statuslogfn, "%s/%s.%s", histdir, hostnamecommas, testname); stat(statuslogfn, &st); statuslogfd = fopen(statuslogfn, "r+"); logexists = (statuslogfd != NULL); *oldcol = '\0'; if (logexists) { /* * There is a fair chance xymond has not been * running all the time while this system was monitored. * So get the time of the latest status change from the file, * instead of relying on the "lastchange" value we get * from xymond. This is also needed when migrating from * standard bbd to xymond. */ off_t pos = -1; char l[1024]; int gotit; MEMDEFINE(l); fseeko(statuslogfd, 0, SEEK_END); if (ftello(statuslogfd) > 512) { /* Go back 512 from EOF, and skip to start of a line */ fseeko(statuslogfd, -512, SEEK_END); gotit = (fgets(l, sizeof(l)-1, statuslogfd) == NULL); } else { /* Read from beginning of file */ fseeko(statuslogfd, 0, SEEK_SET); gotit = 0; } while (!gotit) { off_t tmppos = ftello(statuslogfd); int dur_i; if (fgets(l, sizeof(l)-1, statuslogfd)) { /* Sun Oct 10 06:49:42 2004 red 1097383782 602 */ if ((strlen(l) > 24) && (sscanf(l+24, " %s %d %d", oldcol, &lastchg_i, &dur_i) == 2) && (parse_color(oldcol) != -1)) { /* * Record the start location of the line */ pos = tmppos; lastchg = lastchg_i; } } else { gotit = 1; } } if (pos == -1) { /* * Couldnt find anything in the log. * Take lastchg from the timestamp of the logfile, * and just append the data. */ lastchg = st.st_mtime; fseeko(statuslogfd, 0, SEEK_END); } else { /* * lastchg was updated above. * Seek to where the last line starts. */ fseeko(statuslogfd, pos, SEEK_SET); } MEMUNDEFINE(l); } else { /* * Logfile does not exist. */ lastchg = tstamp; statuslogfd = fopen(statuslogfn, "a"); if (statuslogfd == NULL) { errprintf("Cannot open status historyfile '%s' : %s\n", statuslogfn, strerror(errno)); } } if (strcmp(oldcol, colorname(newcolor)) == 0) { /* We wont update history unless the color did change. */ if ((gettimer() - starttime) > 300) { errprintf("Will not update %s - color unchanged (%s)\n", statuslogfn, oldcol); } if (hostnamecommas) xfree(hostnamecommas); if (statuslogfd) fclose(statuslogfd); MEMUNDEFINE(statuslogfn); MEMUNDEFINE(oldcol); MEMUNDEFINE(timestamp); continue; } if (statuslogfd) { if (logexists) { struct tm oldtm; /* Re-print the old record, now with the final duration */ memcpy(&oldtm, localtime(&lastchg), sizeof(oldtm)); strftime(timestamp, sizeof(timestamp), "%a %b %e %H:%M:%S %Y", &oldtm); fprintf(statuslogfd, "%s %s %d %d\n", timestamp, oldcol, (int)lastchg, (int)(tstamp - lastchg)); } /* And the new record. */ memcpy(&tstamptm, localtime(&tstamp), sizeof(tstamptm)); strftime(timestamp, sizeof(timestamp), "%a %b %e %H:%M:%S %Y", &tstamptm); fprintf(statuslogfd, "%s %s %d", timestamp, colorname(newcolor), (int)tstamp); fclose(statuslogfd); } MEMUNDEFINE(statuslogfn); MEMUNDEFINE(oldcol); MEMUNDEFINE(timestamp); } if (save_histlogs && saveit->saveit && !logdirfull) { char *hostdash; char fname[PATH_MAX]; FILE *histlogfd; MEMDEFINE(fname); p = hostdash = strdup(hostname); while ((p = strchr(p, '.')) != NULL) *p = '_'; sprintf(fname, "%s/%s", histlogdir, hostdash); mkdir(fname, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH); p = fname + sprintf(fname, "%s/%s/%s", histlogdir, hostdash, testname); mkdir(fname, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH); p += sprintf(p, "/%s", histlogtime(tstamp)); histlogfd = fopen(fname, "w"); if (histlogfd) { /* * When a host gets disabled or goes purple, the status * message data is not changed - so it will include a * wrong color as the first word of the message. * Therefore we need to fixup this so it matches the * newcolor value. */ int txtcolor = parse_color(statusdata); char *origstatus = statusdata; char *eoln, *restofdata; int written, closestatus, ok = 1; if (txtcolor != -1) { fprintf(histlogfd, "%s", colorname(newcolor)); statusdata += strlen(colorname(txtcolor)); } if (dismsg && *dismsg) nldecode(dismsg); if (disabletime > 0) { fprintf(histlogfd, " Disabled until %s\n%s\n\n", ctime(&disabletime), (dismsg ? dismsg : "")); fprintf(histlogfd, "Status message when disabled follows:\n\n"); statusdata = origstatus; } else if (dismsg && *dismsg) { fprintf(histlogfd, " Planned downtime: %s\n\n", dismsg); fprintf(histlogfd, "Original status message follows:\n\n"); statusdata = origstatus; } restofdata = statusdata; if (modifiers && *modifiers) { char *modtxt; /* We must finish writing the first line before putting in the modifiers */ eoln = strchr(restofdata, '\n'); if (eoln) { restofdata = eoln+1; *eoln = '\0'; fprintf(histlogfd, "%s\n", statusdata); } nldecode(modifiers); modtxt = strtok(modifiers, "\n"); while (modtxt) { fprintf(histlogfd, "%s\n", modtxt); modtxt = strtok(NULL, "\n"); } } written = fwrite(restofdata, 1, strlen(restofdata), histlogfd); if (written != strlen(restofdata)) { ok = 0; errprintf("Error writing to file %s: %s\n", fname, strerror(errno)); closestatus = fclose(histlogfd); /* Ignore any errors on close */ } else { fprintf(histlogfd, "Status unchanged in 0.00 minutes\n"); fprintf(histlogfd, "Message received from %s\n", metadata[2]); if (clienttstamp) fprintf(histlogfd, "Client data ID %d\n", (int) clienttstamp); closestatus = fclose(histlogfd); if (closestatus != 0) { ok = 0; errprintf("Error writing to file %s: %s\n", fname, strerror(errno)); } } if (!ok) remove(fname); } else { errprintf("Cannot create histlog file '%s' : %s\n", fname, strerror(errno)); } xfree(hostdash); MEMUNDEFINE(fname); } strncpy(oldcol2, ((oldcolor >= 0) ? colorname(oldcolor) : "-"), 2); strncpy(newcol2, colorname(newcolor), 2); newcol2[2] = oldcol2[2] = '\0'; if (oldcolor == -1) trend = -1; /* we dont know how bad it was */ else if (newcolor > oldcolor) trend = 2; /* It's getting worse */ else if (newcolor < oldcolor) trend = 1; /* It's getting better */ else trend = 0; /* Shouldn't happen ... */ if (save_hostevents) { char hostlogfn[PATH_MAX]; FILE *hostlogfd; MEMDEFINE(hostlogfn); sprintf(hostlogfn, "%s/%s", histdir, hostname); hostlogfd = fopen(hostlogfn, "a"); if (hostlogfd) { fprintf(hostlogfd, "%s %d %d %d %s %s %d\n", testname, (int)tstamp, (int)lastchg, (int)(tstamp - lastchg), newcol2, oldcol2, trend); fclose(hostlogfd); } else { errprintf("Cannot open host logfile '%s' : %s\n", hostlogfn, strerror(errno)); } MEMUNDEFINE(hostlogfn); } if (save_allevents) { fprintf(alleventsfd, "%s %s %d %d %d %s %s %d\n", hostname, testname, (int)tstamp, (int)lastchg, (int)(tstamp - lastchg), newcol2, oldcol2, trend); fflush(alleventsfd); } xfree(hostnamecommas); } else if ((metacount > 3) && ((strncmp(metadata[0], "@@drophost", 10) == 0))) { /* @@drophost|timestamp|sender|hostname */ hostname = metadata[3]; if (save_histlogs) { char *hostdash; char testdir[PATH_MAX]; MEMDEFINE(testdir); /* Remove all directories below the host-specific histlog dir */ p = hostdash = strdup(hostname); while ((p = strchr(p, '.')) != NULL) *p = '_'; sprintf(testdir, "%s/%s", histlogdir, hostdash); dropdirectory(testdir, 1); xfree(hostdash); MEMUNDEFINE(testdir); } if (save_hostevents) { char hostlogfn[PATH_MAX]; struct stat st; MEMDEFINE(hostlogfn); sprintf(hostlogfn, "%s/%s", histdir, hostname); if ((stat(hostlogfn, &st) == 0) && S_ISREG(st.st_mode)) { unlink(hostlogfn); } MEMUNDEFINE(hostlogfn); } if (save_statusevents) { DIR *dirfd; struct dirent *de; char *hostlead; char statuslogfn[PATH_MAX]; struct stat st; MEMDEFINE(statuslogfn); /* Remove $XYMONVAR/hist/host,name.* */ p = hostnamecommas = strdup(hostname); while ((p = strchr(p, '.')) != NULL) *p = ','; hostlead = malloc(strlen(hostname) + 2); strcpy(hostlead, hostnamecommas); strcat(hostlead, "."); dirfd = opendir(histdir); if (dirfd) { while ((de = readdir(dirfd)) != NULL) { if (strncmp(de->d_name, hostlead, strlen(hostlead)) == 0) { sprintf(statuslogfn, "%s/%s", histdir, de->d_name); if ((stat(statuslogfn, &st) == 0) && S_ISREG(st.st_mode)) { unlink(statuslogfn); } } } closedir(dirfd); } xfree(hostlead); xfree(hostnamecommas); MEMUNDEFINE(statuslogfn); } } else if ((metacount > 4) && ((strncmp(metadata[0], "@@droptest", 10) == 0))) { /* @@droptest|timestamp|sender|hostname|testname */ hostname = metadata[3]; testname = metadata[4]; if (save_histlogs) { char *hostdash; char testdir[PATH_MAX]; MEMDEFINE(testdir); p = hostdash = strdup(hostname); while ((p = strchr(p, '.')) != NULL) *p = '_'; sprintf(testdir, "%s/%s/%s", histlogdir, hostdash, testname); dropdirectory(testdir, 1); xfree(hostdash); MEMUNDEFINE(testdir); } if (save_statusevents) { char *hostnamecommas; char statuslogfn[PATH_MAX]; struct stat st; MEMDEFINE(statuslogfn); p = hostnamecommas = strdup(hostname); while ((p = strchr(p, '.')) != NULL) *p = ','; sprintf(statuslogfn, "%s/%s.%s", histdir, hostnamecommas, testname); if ((stat(statuslogfn, &st) == 0) && S_ISREG(st.st_mode)) unlink(statuslogfn); xfree(hostnamecommas); MEMUNDEFINE(statuslogfn); } } else if ((metacount > 4) && ((strncmp(metadata[0], "@@renamehost", 12) == 0))) { /* @@renamehost|timestamp|sender|hostname|newhostname */ char *newhostname; hostname = metadata[3]; newhostname = metadata[4]; if (save_histlogs) { char *hostdash; char *newhostdash; char olddir[PATH_MAX]; char newdir[PATH_MAX]; MEMDEFINE(olddir); MEMDEFINE(newdir); p = hostdash = strdup(hostname); while ((p = strchr(p, '.')) != NULL) *p = '_'; p = newhostdash = strdup(newhostname); while ((p = strchr(p, '.')) != NULL) *p = '_'; sprintf(olddir, "%s/%s", histlogdir, hostdash); sprintf(newdir, "%s/%s", histlogdir, newhostdash); rename(olddir, newdir); xfree(newhostdash); xfree(hostdash); MEMUNDEFINE(newdir); MEMUNDEFINE(olddir); } if (save_hostevents) { char hostlogfn[PATH_MAX]; char newhostlogfn[PATH_MAX]; MEMDEFINE(hostlogfn); MEMDEFINE(newhostlogfn); sprintf(hostlogfn, "%s/%s", histdir, hostname); sprintf(newhostlogfn, "%s/%s", histdir, newhostname); rename(hostlogfn, newhostlogfn); MEMUNDEFINE(hostlogfn); MEMUNDEFINE(newhostlogfn); } if (save_statusevents) { DIR *dirfd; struct dirent *de; char *hostlead; char *newhostnamecommas; char statuslogfn[PATH_MAX]; char newlogfn[PATH_MAX]; MEMDEFINE(statuslogfn); MEMDEFINE(newlogfn); p = hostnamecommas = strdup(hostname); while ((p = strchr(p, '.')) != NULL) *p = ','; hostlead = malloc(strlen(hostname) + 2); strcpy(hostlead, hostnamecommas); strcat(hostlead, "."); p = newhostnamecommas = strdup(newhostname); while ((p = strchr(p, '.')) != NULL) *p = ','; dirfd = opendir(histdir); if (dirfd) { while ((de = readdir(dirfd)) != NULL) { if (strncmp(de->d_name, hostlead, strlen(hostlead)) == 0) { char *testname = strchr(de->d_name, '.'); sprintf(statuslogfn, "%s/%s", histdir, de->d_name); sprintf(newlogfn, "%s/%s%s", histdir, newhostnamecommas, testname); rename(statuslogfn, newlogfn); } } closedir(dirfd); } xfree(newhostnamecommas); xfree(hostlead); xfree(hostnamecommas); MEMUNDEFINE(statuslogfn); MEMUNDEFINE(newlogfn); } } else if ((metacount > 5) && (strncmp(metadata[0], "@@renametest", 12) == 0)) { /* @@renametest|timestamp|sender|hostname|oldtestname|newtestname */ char *newtestname; hostname = metadata[3]; testname = metadata[4]; newtestname = metadata[5]; if (save_histlogs) { char *hostdash; char olddir[PATH_MAX]; char newdir[PATH_MAX]; MEMDEFINE(olddir); MEMDEFINE(newdir); p = hostdash = strdup(hostname); while ((p = strchr(p, '.')) != NULL) *p = '_'; sprintf(olddir, "%s/%s/%s", histlogdir, hostdash, testname); sprintf(newdir, "%s/%s/%s", histlogdir, hostdash, newtestname); rename(olddir, newdir); xfree(hostdash); MEMUNDEFINE(newdir); MEMUNDEFINE(olddir); } if (save_statusevents) { char *hostnamecommas; char statuslogfn[PATH_MAX]; char newstatuslogfn[PATH_MAX]; MEMDEFINE(statuslogfn); MEMDEFINE(newstatuslogfn); p = hostnamecommas = strdup(hostname); while ((p = strchr(p, '.')) != NULL) *p = ','; sprintf(statuslogfn, "%s/%s.%s", histdir, hostnamecommas, testname); sprintf(newstatuslogfn, "%s/%s.%s", histdir, hostnamecommas, newtestname); rename(statuslogfn, newstatuslogfn); xfree(hostnamecommas); MEMUNDEFINE(newstatuslogfn); MEMUNDEFINE(statuslogfn); } } else if (strncmp(metadata[0], "@@idle", 6) == 0) { /* Nothing */ } else if (strncmp(metadata[0], "@@shutdown", 10) == 0) { running = 0; } else if (strncmp(metadata[0], "@@logrotate", 11) == 0) { char *fn = xgetenv("XYMONCHANNEL_LOGFILENAME"); if (fn && strlen(fn)) { reopen_file(fn, "a", stdout); reopen_file(fn, "a", stderr); } continue; } else if (strncmp(metadata[0], "@@reload", 8) == 0) { /* Do nothing */ } } MEMUNDEFINE(newcol2); MEMUNDEFINE(oldcol2); MEMUNDEFINE(alleventsfn); MEMUNDEFINE(pidfn); fclose(alleventsfd); unlink(pidfn); return 0; }
void go() { String fname=Sconc(ImageDir,iname,".bmp"); String ename=Sconc(ImageDir,"exp/",iname,".bmp"); printf("read %s\n",fname); orig=RGBmp::readfile(fname); // image=orig->scaledby(scale)->getv3ds(); image=orig->scaletowidth(processwidth)->getv3ds(); printf("Scanning image %i x %i\n",image->width,image->height); printf("done\n"); if (train || test) expected=Map2d<float>::readfile(ename)->threshold(0.5)->binscaleto(image->width,image->height); greyscale=image->applyfn(&V3dtofloat); starttimer(); greyscale->edgedetection(Map2d<float>::sobel(),&edgemag,&edgeang); ghistscale=1.0/(float)windres; ghs=new Map2d<GHist *>(image->width*ghistscale,image->height*ghistscale,(GHist *)NULL); if (train) data=List<IOData>(2000); printf("Starting segmentation...\n"); Seg seg; if (train) seg=Seg(&classifytrain); else seg=Seg(&classifynn); if (show) for (int i=1;i<=nummeasures;i++) measmaps.add(new Map2d<float>(image->width,image->height,(float)0)); if (twopass) { pass=1; printf("First scan, reading measures...\n"); Map2d<bool> *b=seg.classifywindows(); destroy(b); normalisedata(); pausetimer(); printf("Asking neural network...\n"); printf("A\n"); for (int i=1;i<=data.len;i++) { writetraindata(data.num(i).input,123.456); data.p2num(i)->freedom(); } printf("Freeing data\n"); data.freedom(); printf("B\n"); addheaderto(&traindata,numtrainexs); writelinestofile(&traindata,"question.pat"); printf("Not freeing traindata strings\n"); // traindata.freeall(); printf("Freeing traindata\n"); traindata.freedom(); system("./asknn"); traindata=readlinesfromfile("answer.res"); unpausetimer(); currentline=14; pass=2; printf("Second scan...\n"); } Map2d<bool> *b=seg.classifywindows(); printf("Time taken: %f seconds.\n",gettimer()); if (show) for (int i=1;i<=nummeasures;i++) measmaps.num(i)->writefile(getnextfilename("meas","bmp")); // Seg seg=Seg(&measureglvariance); // Map2d<bool> *b=seg.classifytopdown(); // Map2d<bool> *b=seg.classifyneighbours(); // Map2d<bool> *b=seg.classifywindows(); b->scaleto(image->width,image->height)->writefile("initseg.bmp"); // Reject small regions List< Region * > *l=b->getrealregions(); b=new Map2d<bool>(b->width,b->height,false); for (int i=1;i<=l->len;i++) { List<Pixel> *ps=l->num(i)->getlist(); if (ps->len>=minarea) for (int j=1;j<=ps->len;j++) b->setpos(ps->num(j),true); } b->writefile("initb4join.bmp"); // Perform morphological joining (dilation and erosion) b=b->binscaleto(b->width/windres,b->height/windres); b=b->expand(morphrad)->contract(2*morphrad)->expand(morphrad); // b=b->contract(morphrad)->expand(2*morphrad)->contract(morphrad); // b=b->expand(morphrad)->inverse()->expand(morphrad)->inverse(); b=b->binscaleto(image->width,image->height); // b->writefile("initjoined.bmp"); b->writefile("textseg.bmp"); if (test) { int correct=0; int wrong=0; int ctextcorrect=0; int cnottextcorrect=0; int ctextincorrect=0; int cnottextincorrect=0; int total=0; for (int i=0;i<b->width;i++) for (int j=0;j<b->height;j++) { total++; bool exp=expected->getpos(i*expected->width/b->width,j*expected->height/b->height); bool cla=b->getpos(i,j); if (exp==cla) correct++; else wrong++; if (exp) if (cla) ctextcorrect++; else cnottextincorrect++; else if (cla) ctextincorrect++; else cnottextcorrect++; } if (fileexists("test.dat")) { List<String> ls=readlinesfromfile("test.dat"); correct+=tofloat(ls.num(1)); wrong+=tofloat(ls.num(2)); ctextcorrect+=tofloat(ls.num(3)); cnottextcorrect+=tofloat(ls.num(4)); ctextincorrect+=tofloat(ls.num(5)); cnottextincorrect+=tofloat(ls.num(6)); total+=tofloat(ls.num(7)); } List<String> ls; ls.add(Sformat("%i correctly classified",correct)); ls.add(Sformat("%i incorrectly classified",wrong)); ls.add(Sformat("%i correctly classified as text",ctextcorrect)); ls.add(Sformat("%i correct classified as non-text",cnottextcorrect)); ls.add(Sformat("%i classified as text when not",ctextincorrect)); ls.add(Sformat("%i classified as non-text when was text",cnottextincorrect)); ls.add(Sformat("%i total",total)); ls.add(""); int totaltext=ctextcorrect+cnottextincorrect; int totalnottext=ctextincorrect+cnottextcorrect; ls.add(Sformat("That's %i text in total",totaltext)); ls.add(Sformat("and %i non-text in total",totalnottext)); ls.add(""); ls.add("And in percent:"); ls.add(Sformat("%f percent correctly classified",100.0*(float)correct/(float)total)); ls.add(Sformat("%f percent incorrectly classified",100.0*(float)wrong/(float)total)); ls.add(Sformat("%f percent of text correctly classified as text",100.0*(float)ctextcorrect/(float)totaltext)); ls.add(Sformat("%f percent of non-text correctly classified as non-text",100.0*(float)cnottextcorrect/(float)totalnottext)); writelinestofile(ls,"test.dat"); } }
int main(int argc, char *argv[]) { tasklist_t *twalk, *dwalk; grouplist_t *gwalk; int argi; int daemonize = 1; int verbose = 0; char *config = "/etc/tasks.cfg"; char *logfn = NULL; char *pidfn = NULL; pid_t cpid; int status; struct sigaction sa; char *envarea = NULL; for (argi=1; (argi < argc); argi++) { if (strcmp(argv[argi], "--debug") == 0) { debug = 1; } else if (strcmp(argv[argi], "--no-daemon") == 0) { daemonize = 0; } else if (strcmp(argv[argi], "--verbose") == 0) { verbose = 1; } else if (argnmatch(argv[argi], "--config=")) { char *p = strchr(argv[argi], '='); config = strdup(expand_env(p+1)); } else if (argnmatch(argv[argi], "--log=")) { char *p = strchr(argv[argi], '='); logfn = strdup(expand_env(p+1)); } else if (argnmatch(argv[argi], "--area=")) { char *p = strchr(argv[argi], '='); envarea = strdup(p+1); } else if (argnmatch(argv[argi], "--env=")) { char *p = strchr(argv[argi], '='); loadenv(p+1, envarea); } else if (argnmatch(argv[argi], "--pidfile=")) { char *p = strchr(argv[argi], '='); pidfn = strdup(expand_env(p+1)); } else if (strcmp(argv[argi], "--dump") == 0) { /* Dump configuration */ forcereload=1; load_config(config); forcereload=0; for (gwalk = grouphead; (gwalk); gwalk = gwalk->next) { if (gwalk->maxuse > 1) printf("GROUP %s %d\n", gwalk->groupname, gwalk->maxuse); } printf("\n"); for (twalk = taskhead; (twalk); twalk = twalk->next) { printf("[%s]\n", twalk->key); printf("\tCMD %s\n", twalk->cmd); if (twalk->disabled) printf("\tDISABLED\n"); if (twalk->group) printf("\tGROUP %s\n", twalk->group->groupname); if (twalk->depends) printf("\tNEEDS %s\n", twalk->depends->key); if (twalk->interval > 0) printf("\tINTERVAL %d\n", twalk->interval); if (twalk->cronstr) printf("\tCRONDATE %s\n", twalk->cronstr); if (twalk->maxruntime) printf("\tMAXTIME %d\n", twalk->maxruntime); if (twalk->logfile) printf("\tLOGFILE %s\n", twalk->logfile); if (twalk->envfile) printf("\tENVFILE %s\n", twalk->envfile); if (twalk->envarea) printf("\tENVAREA %s\n", twalk->envarea); if (twalk->onhostptn) printf("\tONHOST %s\n", twalk->onhostptn); printf("\n"); } fflush(stdout); return 0; } else { fprintf(stderr,"%s: Unsupported argument: %s\n",argv[0],argv[argi]); fflush(stderr); return 1; } } /* Go daemon */ if (daemonize) { pid_t childpid; /* Become a daemon */ childpid = fork(); if (childpid < 0) { /* Fork failed */ errprintf("Could not fork child\n"); exit(1); } else if (childpid > 0) { /* Parent exits */ if (pidfn) { FILE *pidfd = fopen(pidfn, "w"); if (pidfd) { fprintf(pidfd, "%d\n", (int)childpid); fclose(pidfd); } } exit(0); } /* Child (daemon) continues here */ setsid(); } /* If using a logfile, switch stdout and stderr to go there */ if (logfn) { /* Should we close stdin here ? No ... */ reopen_file("/dev/null", "r", stdin); reopen_file(logfn, "a", stdout); reopen_file(logfn, "a", stderr); } save_errbuf = 0; setup_signalhandler("xymonlaunch"); memset(&sa, 0, sizeof(sa)); sa.sa_handler = sig_handler; sigaction(SIGHUP, &sa, NULL); sigaction(SIGTERM, &sa, NULL); sigaction(SIGCHLD, &sa, NULL); errprintf("xymonlaunch starting\n"); while (running) { time_t now = gettimer(); if (now >= nextcfgload) { load_config(config); nextcfgload = (now + 30); } if (logfn && dologswitch) { reopen_file(logfn, "a", stdout); reopen_file(logfn, "a", stderr); dologswitch = 0; } /* Pick up children that have terminated */ while ((cpid = wait3(&status, WNOHANG, NULL)) > 0) { for (twalk = taskhead; (twalk && (twalk->pid != cpid)); twalk = twalk->next); if (twalk) { twalk->pid = 0; twalk->beingkilled = 0; if (WIFEXITED(status)) { twalk->exitcode = WEXITSTATUS(status); if (twalk->exitcode) { errprintf("Task %s terminated, status %d\n", twalk->key, twalk->exitcode); twalk->failcount++; } else { twalk->failcount = 0; } } else if (WIFSIGNALED(status)) { twalk->exitcode = -WTERMSIG(status); twalk->failcount++; errprintf("Task %s terminated by signal %d\n", twalk->key, abs(twalk->exitcode)); } if (twalk->group) twalk->group->currentuse--; /* Tasks that depend on this task should be killed ... */ for (dwalk = taskhead; (dwalk); dwalk = dwalk->next) { if ((dwalk->depends == twalk) && (dwalk->pid > 0)) { dwalk->beingkilled = 1; kill(dwalk->pid, SIGTERM); } } } } /* See what new tasks need to get going */ dbgprintf("\n"); dbgprintf("Starting tasklist scan\n"); crongettime(); for (twalk = taskhead; (twalk); twalk = twalk->next) { if ( (twalk->pid == 0) && !twalk->disabled && ( ((twalk->interval >= 0) && (now >= (twalk->laststart + twalk->interval))) || /* xymon interval condition */ (twalk->crondate && ((twalk->laststart + 55) < now) && cronmatch(twalk->crondate)) /* cron date */ ) ) { if (twalk->depends && ((twalk->depends->pid == 0) || (twalk->depends->laststart > (now - 5)))) { dbgprintf("Postponing start of %s due to %s not yet running\n", twalk->key, twalk->depends->key); continue; } if (twalk->group && (twalk->group->currentuse >= twalk->group->maxuse)) { dbgprintf("Postponing start of %s due to group %s being busy\n", twalk->key, twalk->group->groupname); continue; } if ((twalk->failcount > MAX_FAILS) && ((twalk->laststart + 600) < now)) { dbgprintf("Releasing %s from failure hold\n", twalk->key); twalk->failcount = 0; } if (twalk->failcount > MAX_FAILS) { dbgprintf("Postponing start of %s due to multiple failures\n", twalk->key); continue; } if (twalk->laststart > (now - 5)) { dbgprintf("Postponing start of %s, will not try more than once in 5 seconds\n", twalk->key); continue; } dbgprintf("About to start task %s\n", twalk->key); twalk->laststart = now; twalk->pid = fork(); if (twalk->pid == 0) { /* Exec the task */ char *cmd; char **cmdargs = NULL; static char tasksleepenv[20],bbsleepenv[20]; /* Setup environment */ if (twalk->envfile) { dbgprintf("%s -> Loading environment from %s area %s\n", twalk->key, expand_env(twalk->envfile), (twalk->envarea ? twalk->envarea : "")); loadenv(expand_env(twalk->envfile), twalk->envarea); } /* Setup TASKSLEEP to match the interval */ sprintf(tasksleepenv, "TASKSLEEP=%d", twalk->interval); sprintf(bbsleepenv, "BBSLEEP=%d", twalk->interval); /* For compatibility */ putenv(tasksleepenv); putenv(bbsleepenv); /* Setup command line and arguments */ cmdargs = setup_commandargs(twalk->cmd, &cmd); /* Point stdout/stderr to a logfile, if requested */ if (twalk->logfile) { char *logfn = expand_env(twalk->logfile); dbgprintf("%s -> Assigning stdout/stderr to log '%s'\n", twalk->key, logfn); reopen_file(logfn, "a", stdout); reopen_file(logfn, "a", stderr); } /* Go! */ dbgprintf("%s -> Running '%s', XYMONHOME=%s\n", twalk->key, cmd, xgetenv("XYMONHOME")); execvp(cmd, cmdargs); /* Should never go here */ errprintf("Could not start task %s using command '%s': %s\n", twalk->key, cmd, strerror(errno)); exit(0); } else if (twalk->pid == -1) { /* Fork failed */ errprintf("Fork failed!\n"); twalk->pid = 0; } else { if (twalk->group) twalk->group->currentuse++; if (verbose) errprintf("Task %s started with PID %d\n", twalk->key, (int)twalk->pid); } } else if (twalk->pid > 0) { dbgprintf("Task %s active with PID %d\n", twalk->key, (int)twalk->pid); if (twalk->maxruntime && ((now - twalk->laststart) > twalk->maxruntime)) { errprintf("Killing hung task %s (PID %d) after %d seconds\n", twalk->key, (int)twalk->pid, (now - twalk->laststart)); kill(twalk->pid, (twalk->beingkilled ? SIGKILL : SIGTERM)); twalk->beingkilled = 1; /* Next time it's a real kill */ } } } sleep(5); } /* Shutdown running tasks */ for (twalk = taskhead; (twalk); twalk = twalk->next) { if (twalk->pid) kill(twalk->pid, SIGTERM); } if (pidfn) unlink(pidfn); return 0; }
/************************************************************************* * Let the game begin **************************************************************************/ main(int argc, char *argv[]) { int i, nparts, options[10]; idxtype *part; float rubvec[MAXNCON], lbvec[MAXNCON]; GraphType graph; char filename[256]; int numflag = 0, wgtflag = 0, edgecut; timer TOTALTmr, METISTmr, IOTmr; if (argc != 3) { printf("Usage: %s <GraphFile> <Nparts>\n",argv[0]); exit(0); } strcpy(filename, argv[1]); nparts = atoi(argv[2]); if (nparts < 2) { printf("The number of partitions should be greater than 1!\n"); exit(0); } cleartimer(TOTALTmr); cleartimer(METISTmr); cleartimer(IOTmr); starttimer(TOTALTmr); starttimer(IOTmr); ReadGraph(&graph, filename, &wgtflag); if (graph.nvtxs <= 0) { printf("Empty graph. Nothing to do.\n"); exit(0); } stoptimer(IOTmr); printf("**********************************************************************\n"); printf("%s", METISTITLE); printf("Graph Information ---------------------------------------------------\n"); printf(" Name: %s, #Vertices: %d, #Edges: %d, #Parts: %d\n", filename, graph.nvtxs, graph.nedges/2, nparts); if (graph.ncon > 1) printf(" Balancing Constraints: %d\n", graph.ncon); printf("\nK-way Partitioning... -----------------------------------------------\n"); part = idxmalloc(graph.nvtxs, "main: part"); options[0] = 0; starttimer(METISTmr); if (graph.ncon == 1) { METIS_PartGraphKway(&graph.nvtxs, graph.xadj, graph.adjncy, graph.vwgt, graph.adjwgt, &wgtflag, &numflag, &nparts, options, &edgecut, part); } else { for (i=0; i<graph.ncon; i++) rubvec[i] = HORIZONTAL_IMBALANCE; METIS_mCPartGraphKway(&graph.nvtxs, &graph.ncon, graph.xadj, graph.adjncy, graph.vwgt, graph.adjwgt, &wgtflag, &numflag, &nparts, rubvec, options, &edgecut, part); } stoptimer(METISTmr); ComputePartitionBalance(&graph, nparts, part, lbvec); printf(" %d-way Edge-Cut: %7d, Balance: ", nparts, edgecut); for (i=0; i<graph.ncon; i++) printf("%5.2f ", lbvec[i]); printf("\n"); starttimer(IOTmr); WritePartition(filename, part, graph.nvtxs, nparts); stoptimer(IOTmr); stoptimer(TOTALTmr); printf("\nTiming Information --------------------------------------------------\n"); printf(" I/O: \t\t %7.3f\n", gettimer(IOTmr)); printf(" Partitioning: \t\t %7.3f (KMETIS time)\n", gettimer(METISTmr)); printf(" Total: \t\t %7.3f\n", gettimer(TOTALTmr)); printf("**********************************************************************\n"); GKfree(&graph.xadj, &graph.adjncy, &graph.vwgt, &graph.adjwgt, &part, LTERM); }
int main(int argc, char *argv[]) { char *msg; int running; int argi, seq; int recentperiod = 3600; int maxrecentcount = 5; int logdirfull = 0; int minlogspace = 5; struct sigaction sa; /* Handle program options. */ for (argi = 1; (argi < argc); argi++) { if (argnmatch(argv[argi], "--logdir=")) { clientlogdir = strchr(argv[argi], '=')+1; } else if (argnmatch(argv[argi], "--recent-period=")) { char *p = strchr(argv[argi], '='); recentperiod = 60*atoi(p+1); } else if (argnmatch(argv[argi], "--recent-count=")) { char *p = strchr(argv[argi], '='); maxrecentcount = atoi(p+1); } else if (argnmatch(argv[argi], "--minimum-free=")) { minlogspace = atoi(strchr(argv[argi], '=')+1); } else if (strcmp(argv[argi], "--debug") == 0) { /* * A global "debug" variable is available. If * it is set, then "dbgprintf()" outputs debug messages. */ debug = 1; } else if (net_worker_option(argv[argi])) { /* Handled in the subroutine */ } } if (clientlogdir == NULL) clientlogdir = xgetenv("CLIENTLOGS"); if (clientlogdir == NULL) { clientlogdir = (char *)malloc(strlen(xgetenv("XYMONVAR")) + 10); sprintf(clientlogdir, "%s/hostdata", xgetenv("XYMONVAR")); } save_errbuf = 0; /* Do the network stuff if needed */ net_worker_run(ST_HOSTDATA, LOC_STICKY, update_locator_hostdata); setup_signalhandler("xymond_hostdata"); memset(&sa, 0, sizeof(sa)); sa.sa_handler = sig_handler; signal(SIGCHLD, SIG_IGN); sigaction(SIGHUP, &sa, NULL); signal(SIGPIPE, SIG_DFL); savetimes = xtreeNew(strcasecmp); running = 1; while (running) { char *eoln, *restofmsg, *p; char *metadata[MAX_META+1]; int metacount; msg = get_xymond_message(C_CLICHG, "xymond_hostdata", &seq, NULL); if (msg == NULL) { /* * get_xymond_message will return NULL if xymond_channel closes * the input pipe. We should shutdown when that happens. */ running = 0; continue; } if (nextfscheck < gettimer()) { logdirfull = (chkfreespace(clientlogdir, minlogspace, minlogspace) != 0); if (logdirfull) errprintf("Hostdata directory %s has less than %d%% free space - disabling save of data for 5 minutes\n", clientlogdir, minlogspace); nextfscheck = gettimer() + 300; } /* Split the message in the first line (with meta-data), and the rest */ eoln = strchr(msg, '\n'); if (eoln) { *eoln = '\0'; restofmsg = eoln+1; } else { restofmsg = ""; } metacount = 0; memset(&metadata, 0, sizeof(metadata)); p = gettok(msg, "|"); while (p && (metacount < MAX_META)) { metadata[metacount++] = p; p = gettok(NULL, "|"); } metadata[metacount] = NULL; if (strncmp(metadata[0], "@@clichg", 8) == 0) { xtreePos_t handle; savetimes_t *itm; int i, recentcount; time_t now = gettimer(); char hostdir[PATH_MAX]; char fn[PATH_MAX]; FILE *fd; /* metadata[3] is the hostname */ handle = xtreeFind(savetimes, metadata[3]); if (handle != xtreeEnd(savetimes)) { itm = (savetimes_t *)xtreeData(savetimes, handle); } else { itm = (savetimes_t *)calloc(1, sizeof(savetimes_t)); itm->hostname = strdup(metadata[3]); xtreeAdd(savetimes, itm->hostname, itm); } /* See how many times we've saved the hostdata recently (within the past 'recentperiod' seconds) */ for (i=0, recentcount=0; ((i < 12) && (itm->tstamp[i] > (now - recentperiod))); i++) recentcount++; /* If it's been saved less than 'maxrecentcount' times, then save it. Otherwise just drop it */ if (!logdirfull && (recentcount < maxrecentcount)) { int written, closestatus, ok = 1; for (i = 10; (i > 0); i--) itm->tstamp[i+1] = itm->tstamp[i]; itm->tstamp[0] = now; sprintf(hostdir, "%s/%s", clientlogdir, metadata[3]); mkdir(hostdir, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH); sprintf(fn, "%s/%s", hostdir, metadata[4]); fd = fopen(fn, "w"); if (fd == NULL) { errprintf("Cannot create file %s: %s\n", fn, strerror(errno)); continue; } written = fwrite(restofmsg, 1, strlen(restofmsg), fd); if (written != strlen(restofmsg)) { errprintf("Cannot write hostdata file %s: %s\n", fn, strerror(errno)); closestatus = fclose(fd); /* Ignore any close errors */ ok = 0; } else { closestatus = fclose(fd); if (closestatus != 0) { errprintf("Cannot write hostdata file %s: %s\n", fn, strerror(errno)); ok = 0; } } if (!ok) remove(fn); } } /* * A "shutdown" message is sent when the master daemon * terminates. The child workers should shutdown also. */ else if (strncmp(metadata[0], "@@shutdown", 10) == 0) { running = 0; continue; } else if (strncmp(metadata[0], "@@idle", 6) == 0) { /* Ignored */ continue; } /* * A "logrotate" message is sent when the Xymon logs are * rotated. The child workers must re-open their logfiles, * typically stdin and stderr - the filename is always * provided in the XYMONCHANNEL_LOGFILENAME environment. */ else if (strncmp(metadata[0], "@@logrotate", 11) == 0) { char *fn = xgetenv("XYMONCHANNEL_LOGFILENAME"); if (fn && strlen(fn)) { reopen_file(fn, "a", stdout); reopen_file(fn, "a", stderr); } continue; } else if ((metacount > 3) && (strncmp(metadata[0], "@@drophost", 10) == 0)) { /* @@drophost|timestamp|sender|hostname */ char hostdir[PATH_MAX]; snprintf(hostdir, sizeof(hostdir), "%s/%s", clientlogdir, basename(metadata[3])); dropdirectory(hostdir, 1); } else if ((metacount > 4) && (strncmp(metadata[0], "@@renamehost", 12) == 0)) { /* @@renamehost|timestamp|sender|hostname|newhostname */ char oldhostdir[PATH_MAX], newhostdir[PATH_MAX]; snprintf(oldhostdir, sizeof(oldhostdir), "%s/%s", clientlogdir, basename(metadata[3])); snprintf(newhostdir, sizeof(newhostdir), "%s/%s", clientlogdir, basename(metadata[4])); rename(oldhostdir, newhostdir); if (net_worker_locatorbased()) locator_rename_host(metadata[3], metadata[4], ST_HOSTDATA); } else if (strncmp(metadata[0], "@@reload", 8) == 0) { /* Do nothing */ } } return 0; }
/************************************************************************* * Let the game begin **************************************************************************/ main(int argc, char *argv[]) { int i, options[10]; idxtype *perm, *iperm; GraphType graph; char filename[256]; int numflag = 0, wgtflag; timer TOTALTmr, METISTmr, IOTmr, SMBTmr; if (argc != 2) { printf("Usage: %s <GraphFile>\n",argv[0]); exit(0); } strcpy(filename, argv[1]); cleartimer(TOTALTmr); cleartimer(METISTmr); cleartimer(IOTmr); cleartimer(SMBTmr); starttimer(TOTALTmr); starttimer(IOTmr); ReadGraph(&graph, filename, &wgtflag); if (graph.nvtxs <= 0) { printf("Empty graph. Nothing to do.\n"); exit(0); } if (graph.ncon != 1) { printf("Ordering can only be applied to graphs with one constraint.\n"); exit(0); } stoptimer(IOTmr); /* Ordering does not use weights! */ GKfree(&graph.vwgt, &graph.adjwgt, LTERM); printf("**********************************************************************\n"); printf("%s", METISTITLE); printf("Graph Information ---------------------------------------------------\n"); printf(" Name: %s, #Vertices: %d, #Edges: %d\n\n", filename, graph.nvtxs, graph.nedges/2); printf("Node-Based Ordering... ----------------------------------------------\n"); perm = idxmalloc(graph.nvtxs, "main: perm"); iperm = idxmalloc(graph.nvtxs, "main: iperm"); options[0] = 0; starttimer(METISTmr); METIS_NodeND(&graph.nvtxs, graph.xadj, graph.adjncy, &numflag, options, perm, iperm); stoptimer(METISTmr); starttimer(IOTmr); WritePermutation(filename, iperm, graph.nvtxs); stoptimer(IOTmr); starttimer(SMBTmr); ComputeFillIn(&graph, iperm); stoptimer(SMBTmr); stoptimer(TOTALTmr); printf("\nTiming Information --------------------------------------------------\n"); printf(" I/O: \t %7.3f\n", gettimer(IOTmr)); printf(" Ordering: \t %7.3f (ONMETIS time)\n", gettimer(METISTmr)); printf(" Symbolic Factorization: \t %7.3f\n", gettimer(SMBTmr)); printf(" Total: \t %7.3f\n", gettimer(TOTALTmr)); printf("**********************************************************************\n"); GKfree(&graph.xadj, &graph.adjncy, &perm, &iperm, LTERM); }
void do_tcp_tests(int timeout, int concurrency) { int selres; fd_set readfds, writefds; struct timespec timestamp; int absmaxconcurrency; int activesockets = 0; /* Number of allocated sockets */ int pending = 0; /* Total number of tests */ tcptest_t *nextinqueue; /* Points to the next item to start testing */ tcptest_t *firstactive; /* Points to the first item currently being tested */ /* Thus, active connections are between firstactive..nextinqueue */ tcptest_t *item; int sockok; int maxfd; int res; socklen_t connressize; char msgbuf[4096]; struct rlimit lim; /* If timeout or concurrency are 0, set them to reasonable defaults */ if (timeout == 0) timeout = 10; /* seconds */ /* * Decide how many tests to run in parallel. * If no --concurrency set by user, default to (FD_SETSIZE / 4) - typically 256. * But never go above the ressource limit that is set, or above FD_SETSIZE. * And we save 10 fd's for stdio, libs etc. */ absmaxconcurrency = (FD_SETSIZE - 10); getrlimit(RLIMIT_NOFILE, &lim); if ((lim.rlim_cur > 10) && ((lim.rlim_cur - 10) < absmaxconcurrency)) absmaxconcurrency = (lim.rlim_cur - 10); if (concurrency == 0) concurrency = (FD_SETSIZE / 4); if (concurrency > absmaxconcurrency) concurrency = absmaxconcurrency; dbgprintf("Concurrency evaluation: rlim_cur=%lu, FD_SETSIZE=%d, absmax=%d, initial=%d\n", lim.rlim_cur, FD_SETSIZE, absmaxconcurrency, concurrency); if (shuffletests) { struct timeval tv; struct timezone tz; gettimeofday(&tv, &tz); srandom(tv.tv_usec); } /* How many tests to do ? */ for (item = thead; (item); item = item->next) { if (shuffletests) item->randomizer = random(); pending++; } if (shuffletests) thead = msort(thead, tcptest_compare, tcptest_getnext, tcptest_setnext); firstactive = nextinqueue = thead; dbgprintf("About to do %d TCP tests running %d in parallel, abs.max %d\n", pending, concurrency, absmaxconcurrency); while (pending > 0) { int slowrunning, cclimit; time_t slowtimestamp = gettimer() - SLOWLIMSECS; /* * First, see if we need to allocate new sockets and initiate connections. */ /* * We start by counting the number of tests where the latest activity * happened more than SLOWLIMSECS seconds ago. These are ignored when counting * how many more tests we can start concurrenly. But never exceed the absolute * max. number of concurrently open sockets possible. */ for (item=firstactive, slowrunning = 0; (item != nextinqueue); item=item->next) { if ((item->fd > -1) && (item->lastactive < slowtimestamp)) slowrunning++; } cclimit = concurrency + slowrunning; if (cclimit > absmaxconcurrency) cclimit = absmaxconcurrency; sockok = 1; while (sockok && nextinqueue && (activesockets < cclimit)) { /* * We need to allocate a new socket that has O_NONBLOCK set. */ nextinqueue->fd = socket(PF_INET, SOCK_STREAM, 0); sockok = (nextinqueue->fd != -1); if (sockok) { /* Set the source address */ if (nextinqueue->srcaddr) { struct sockaddr_in src; int isip; memset(&src, 0, sizeof(src)); src.sin_family = PF_INET; src.sin_port = 0; isip = (inet_aton(nextinqueue->srcaddr, (struct in_addr *) &src.sin_addr.s_addr) != 0); if (!isip) { char *envaddr = getenv(nextinqueue->srcaddr); isip = (envaddr && (inet_aton(envaddr, (struct in_addr *) &src.sin_addr.s_addr) != 0)); } if (isip) { res = bind(nextinqueue->fd, (struct sockaddr *)&src, sizeof(src)); if (res != 0) errprintf("WARNING: Could not bind to source IP %s for test %s: %s\n", nextinqueue->srcaddr, nextinqueue->tspec, strerror(errno)); } else { errprintf("WARNING: Invalid source IP %s for test %s, using default\n", nextinqueue->srcaddr, nextinqueue->tspec); } } res = fcntl(nextinqueue->fd, F_SETFL, O_NONBLOCK); if (res == 0) { /* * Initiate the connection attempt ... */ getntimer(&nextinqueue->timestart); nextinqueue->lastactive = nextinqueue->timestart.tv_sec; nextinqueue->cutoff = nextinqueue->timestart.tv_sec + timeout + 1; res = connect(nextinqueue->fd, (struct sockaddr *)&nextinqueue->addr, sizeof(nextinqueue->addr)); /* * Did it work ? */ if ((res == 0) || ((res == -1) && (errno == EINPROGRESS))) { /* This is OK - EINPROGRES and res=0 pick up status in select() */ activesockets++; tcp_stats_connects++; } else if (res == -1) { /* connect() failed. Flag the item as "not open" */ nextinqueue->connres = errno; nextinqueue->open = 0; nextinqueue->errcode = CONTEST_ENOCONN; close(nextinqueue->fd); nextinqueue->fd = -1; pending--; switch (nextinqueue->connres) { /* These may happen if connection is refused immediately */ case ECONNREFUSED : break; case EHOSTUNREACH : break; case ENETUNREACH : break; case EHOSTDOWN : break; /* Not likely ... */ case ETIMEDOUT : break; /* These should not happen. */ case EBADF : errprintf("connect returned EBADF!\n"); break; case ENOTSOCK : errprintf("connect returned ENOTSOCK!\n"); break; case EADDRNOTAVAIL: errprintf("connect returned EADDRNOTAVAIL!\n"); break; case EAFNOSUPPORT : errprintf("connect returned EAFNOSUPPORT!\n"); break; case EISCONN : errprintf("connect returned EISCONN!\n"); break; case EADDRINUSE : errprintf("connect returned EADDRINUSE!\n"); break; case EFAULT : errprintf("connect returned EFAULT!\n"); break; case EALREADY : errprintf("connect returned EALREADY!\n"); break; default : errprintf("connect returned %d, errno=%d\n", res, errno); } } else { /* Should NEVER happen. connect returns 0 or -1 */ errprintf("Strange result from connect: %d, errno=%d\n", res, errno); } } else { /* Could net set to non-blocking mode! Hmmm ... */ sockok = 0; errprintf("Cannot set O_NONBLOCK\n"); } nextinqueue=nextinqueue->next; } else { int newconcurrency = ((activesockets > 5) ? (activesockets-1) : 5); /* Could not get a socket */ switch (errno) { case EPROTONOSUPPORT: errprintf("Cannot get socket - EPROTONOSUPPORT\n"); break; case EAFNOSUPPORT : errprintf("Cannot get socket - EAFNOSUPPORT\n"); break; case EMFILE : errprintf("Cannot get socket - EMFILE\n"); break; case ENFILE : errprintf("Cannot get socket - ENFILE\n"); break; case EACCES : errprintf("Cannot get socket - EACCESS\n"); break; case ENOBUFS : errprintf("Cannot get socket - ENOBUFS\n"); break; case ENOMEM : errprintf("Cannot get socket - ENOMEM\n"); break; case EINVAL : errprintf("Cannot get socket - EINVAL\n"); break; default : errprintf("Cannot get socket - errno=%d\n", errno); break; } if (newconcurrency != concurrency) { errprintf("Reducing --concurrency setting from %d to %d\n", concurrency, newconcurrency); concurrency = newconcurrency; } } } /* Ready to go - we have a bunch of connections being established */ dbgprintf("%d tests pending - %d active tests, %d slow tests\n", pending, activesockets, slowrunning); restartselect: /* * Setup the FDSET's */ FD_ZERO(&readfds); FD_ZERO(&writefds); maxfd = -1; for (item=firstactive; (item != nextinqueue); item=item->next) { if (item->fd > -1) { /* * WRITE events are used to signal that a * connection is ready, or it has been refused. * READ events are only interesting for sockets * that have already been found to be open, and * thus have the "readpending" flag set. * * So: On any given socket, we want either a * write-event or a read-event - never both. */ if (item->readpending) FD_SET(item->fd, &readfds); else FD_SET(item->fd, &writefds); if (item->fd > maxfd) maxfd = item->fd; } } if (maxfd == -1) { /* No active connections */ if (activesockets == 0) { /* This can happen, if we get an immediate CONNREFUSED on all connections. */ continue; } else { errprintf("contest logic error: No FD's, active=%d, pending=%d\n", activesockets, pending); continue; } } /* * Wait for something to happen: connect, timeout, banner arrives ... */ if (maxfd < 0) { errprintf("select - no active fd's found, but pending is %d\n", pending); selres = 0; } else { struct timeval tmo = { 1, 0 }; dbgprintf("Doing select with maxfd=%d\n", maxfd); selres = select((maxfd+1), &readfds, &writefds, NULL, &tmo); dbgprintf("select returned %d\n", selres); } if (selres == -1) { int selerr = errno; /* * select() failed - this is BAD! */ switch (selerr) { case EINTR : errprintf("select failed - EINTR\n"); goto restartselect; case EBADF : errprintf("select failed - EBADF\n"); break; case EINVAL: errprintf("select failed - EINVAL\n"); break; case ENOMEM: errprintf("select failed - ENOMEM\n"); break; default : errprintf("Unknown select() error %d\n", selerr); break; } /* Leave this mess ... */ errprintf("Aborting TCP tests with %d tests pending\n", pending); return; } /* selres == 0 (timeout) isn't special - just go through the list of active tests */ /* Fetch the timestamp so we can tell how long the connect took */ getntimer(×tamp); /* Now find out which connections had something happen to them */ for (item=firstactive; (item != nextinqueue); item=item->next) { if (item->fd > -1) { /* Only active sockets have this */ if (timestamp.tv_sec > item->cutoff) { /* * Request timed out. */ if (item->readpending) { /* Final read timeout - just shut this socket */ socket_shutdown(item); item->errcode = CONTEST_ETIMEOUT; } else { /* Connection timeout */ item->open = 0; item->errcode = CONTEST_ETIMEOUT; } get_totaltime(item, ×tamp); close(item->fd); item->fd = -1; activesockets--; pending--; if (item == firstactive) firstactive = item->next; } else { if (FD_ISSET(item->fd, &writefds)) { int do_talk = 1; unsigned char *outbuf = NULL; unsigned int outlen = 0; item->lastactive = timestamp.tv_sec; if (!item->open) { /* * First time here. * * Active response on this socket - either OK, or * connection refused. * We determine what happened by getting the SO_ERROR status. * (cf. select_tut(2) manpage). */ connressize = sizeof(item->connres); res = getsockopt(item->fd, SOL_SOCKET, SO_ERROR, &item->connres, &connressize); item->open = (item->connres == 0); if (!item->open) item->errcode = CONTEST_ENOCONN; do_talk = item->open; get_connectiontime(item, ×tamp); } if (item->open && (item->svcinfo->flags & TCP_SSL)) { /* * Setup the SSL connection, if not done already. * * NB: This can be triggered many times, as setup_ssl() * may need more data from the remote and return with * item->sslrunning == SSLSETUP_PENDING */ if (item->sslrunning == SSLSETUP_PENDING) { setup_ssl(item); if (item->sslrunning == 1) { /* * Update connectiontime to include * time for SSL handshake. */ get_connectiontime(item, ×tamp); } } do_talk = (item->sslrunning == 1); } /* * Connection succeeded - port is open, if SSL then the * SSL handshake is complete. * * If we have anything to send then send it. * If we want the banner, set the "readpending" flag to initiate * select() for read()'s. * NB: We want the banner EITHER if the GET_BANNER flag is set, * OR if we need it to match the expect string in the servicedef. */ item->readpending = (do_talk && !item->silenttest && ( (item->svcinfo->flags & TCP_GET_BANNER) || item->svcinfo->exptext )); if (do_talk) { if (item->telnetnegotiate && item->telnetbuflen) { /* * Return the telnet negotiate data response */ outbuf = item->telnetbuf; outlen = item->telnetbuflen; } else if (item->sendtxt && !item->silenttest) { outbuf = item->sendtxt; outlen = (item->sendlen ? item->sendlen : strlen(outbuf)); } if (outbuf && outlen) { /* * It may be that we cannot write all of the * data we want to. Tough ... */ res = socket_write(item, outbuf, outlen); tcp_stats_written += res; if (res == -1) { /* Write failed - this socket is done. */ dbgprintf("write failed\n"); item->readpending = 0; item->errcode = CONTEST_EIO; } else if (item->svcinfo->flags & TCP_HTTP) { /* * HTTP tests require us to send the full buffer. * So adjust sendtxt/sendlen accordingly. * If no more to send, switch to read-mode. */ item->sendtxt += res; item->sendlen -= res; item->readpending = (item->sendlen == 0); } } } /* If closed and/or no bannergrabbing, shut down socket */ if (item->sslrunning != SSLSETUP_PENDING) { if (!item->open || !item->readpending) { if (item->open) { socket_shutdown(item); } close(item->fd); get_totaltime(item, ×tamp); if (item->finalcallback) item->finalcallback(item->priv); item->fd = -1; activesockets--; pending--; if (item == firstactive) firstactive = item->next; } } } else if (FD_ISSET(item->fd, &readfds)) { /* * Data ready to read on this socket. Grab the * banner - we only do one read (need the socket * for other tests), so if the banner takes more * than one cycle to arrive, too bad! */ int wantmoredata = 0; int datadone = 0; item->lastactive = timestamp.tv_sec; /* * We may be in the process of setting up an SSL connection */ if (item->sslrunning == SSLSETUP_PENDING) setup_ssl(item); if (item->sslrunning == SSLSETUP_PENDING) break; /* Loop again waiting for more data */ /* * Connection is ready - plain or SSL. Read data. */ res = socket_read(item, msgbuf, sizeof(msgbuf)-1); tcp_stats_read += res; dbgprintf("read %d bytes from socket\n", res); if ((res > 0) && item->datacallback) { datadone = item->datacallback(msgbuf, res, item->priv); } if ((res > 0) && item->telnetnegotiate) { /* * telnet data has telnet options first. * We must negotiate the session before we * get the banner. */ item->telnetbuf = item->banner; item->telnetbuflen = res; /* * Safety measure: Dont loop forever doing * telnet options. * This puts a maximum on how many times * we go here. */ item->telnetnegotiate--; if (!item->telnetnegotiate) { dbgprintf("Max. telnet negotiation (%d) reached for host %s\n", MAX_TELNET_CYCLES, inet_ntoa(item->addr.sin_addr)); } if (do_telnet_options(item)) { /* Still havent seen the session banner */ item->banner = NULL; item->bannerbytes = 0; item->readpending = 0; wantmoredata = 1; } else { /* No more options - we have the banner */ item->telnetnegotiate = 0; } } if ((item->svcinfo->flags & TCP_HTTP) && ((res > 0) || item->sslagain) && (!datadone) ) { /* * HTTP : Grab the entire response. */ wantmoredata = 1; } if (!wantmoredata) { if (item->open) { socket_shutdown(item); } item->readpending = 0; close(item->fd); get_totaltime(item, ×tamp); if (item->finalcallback) item->finalcallback(item->priv); item->fd = -1; activesockets--; pending--; if (item == firstactive) firstactive = item->next; } } } } } /* end for loop */ } /* end while (pending) */ dbgprintf("TCP tests completed normally\n"); }
int main(int argc, char *argv[]) { int i, npart; idxtype *part; float ncut=0; GraphType graph; char filename[256],outputFile[256]; int wgtflag = 0, addSelfLoop=1, outputFileGiven=0, txtFormat=0 ; int randomInit = 0; idxtype minEdgeWeight = 0; Options opt; timer TOTALTmr, METISTmr, IOTmr; initOptions(&opt); if (argc < 2) { print_help(argv[0]); exit(0); } for (argv++; *argv != NULL; argv++){ if ((*argv)[0] == '-') { int temp; switch ((*argv)[1]) { case 'b': case 'B': opt.penalty_power=atof(*(++argv)); break; case 'i': case 'I': opt.gamma=atof(*(++argv)); break; case 'o': case 'O': strcpy(outputFile,*(++argv)); outputFileGiven=1; break; case 'D'://quality threshold. This is a post-processing step proposed in SR-MCL. If you dont want post-processing (this is what original MLR-MCL, R-MCL, MCL do, please set "-d 0" case 'd': opt.quality_threshold = atof(*(++argv)); break; case 'w': case 'W': opt.weighted_density = true; break; case 'c': case 'C': opt.coarsenTo= atoi(*(++argv)); break; default: printf("Invalid option %s\n", *argv); print_help(argv[0]); exit(0); } } else { strcpy(filename, *argv); } } if ( randomInit > 0 ) InitRandom(time(NULL)); else InitRandom(-1); cleartimer(TOTALTmr); cleartimer(METISTmr); cleartimer(IOTmr); starttimer(TOTALTmr); starttimer(IOTmr); ReadGraph(&graph, filename, &wgtflag, addSelfLoop, txtFormat); if ( opt.matchType == MATCH_UNSPECIFIED ) { // opt.matchType = (graph.nvtxs>50000) ? MATCH_POWERLAW_FC : // MATCH_SHEMN; opt.matchType = MATCH_SHEMN; } stoptimer(IOTmr); if (graph.nvtxs <= 0) { printf("Empty graph. Nothing to do.\n"); exit(0); } int noOfSingletons = 0; GraphType *noSingletonGraph ; idxtype* nodeMap = lookForSingletons(&graph, &noOfSingletons); if ( noOfSingletons > 0 ) { getSubgraph(&graph, nodeMap, graph.nvtxs-noOfSingletons, wgtflag, &noSingletonGraph); GKfree((void**)&(graph.xadj), (void**)&(graph.adjncy), LTERM); if ( wgtflag&1 > 0 ) GKfree( (void**)&(graph.adjwgt), LTERM); // free(graph.gdata); printf("Found %d singleton nodes in the", noOfSingletons); printf(" input graph. Removing them.\n"); } if ( !outputFileGiven ) { strcpy(outputFile, filename); sprintf(outputFile,"%s.c%d.i%1.1f.b%1.1f",outputFile,opt.coarsenTo,opt.gamma,opt.penalty_power); } printf("Input graph information ---------------------------------------------------\n"); printf(" Name: %s, #Vertices: %d, #Edges: %d\n", filename, graph.nvtxs, graph.nedges/2); printf("Output shall be placed in the file %s\n", outputFile); fflush(stdout); part = idxmalloc(graph.nvtxs, "main: part"); printf("------------------------------------------------\n"); printf("Clustering....\n"); fflush(stdout); starttimer(METISTmr); //YK: main algorithm starts here! if ( noOfSingletons > 0 ) { mlmcl(&(noSingletonGraph->nvtxs), noSingletonGraph->xadj, noSingletonGraph->adjncy, noSingletonGraph->vwgt,noSingletonGraph->adjwgt, &wgtflag, part, opt ); } else { mlmcl(&graph.nvtxs, graph.xadj, graph.adjncy,graph.vwgt, graph.adjwgt, &wgtflag, part, opt ); } stoptimer(METISTmr); printf("------------------------------------------------\n"); if ( noOfSingletons > 0 ) { npart=mapPartition(part,noSingletonGraph->nvtxs); ncut=ComputeNCut(noSingletonGraph, part,npart); // printf("In graph that does not include singletons,"); // printf("No. of Clusters: %d, N-Cut value: %.2f\n",npart,ncut); idxtype *clusterSizes = histogram(part, graph.nvtxs-noOfSingletons, npart); int maxSize = clusterSizes[idxamax(npart, clusterSizes)]; float avgClusterSize = (graph.nvtxs-noOfSingletons)*1.0/(npart); float balance = (maxSize*1.0) / ((graph.nvtxs-noOfSingletons)*1.0/npart); float stdDevn = stdDeviation(clusterSizes, npart); float avgNcut = ncut * 1.0/npart; float normStdDevn = stdDevn/avgClusterSize; // Warning: This computation only works if the singletons // have been placed in their own clusters. This works for // MLR-MCL, in other words, because it is guaranteed to // place singletons in their own clusters. printf("Output statistics for graph without singletons\n"); printf("Clusters: %d N-Cut: %.3f", npart, ncut); printf(" AvgN-Cut: %.3f Balance in cluster sizes: %.2f ",avgNcut, balance); printf("Std_Deviation in cluster sizes: %.2f ", stdDevn); printf("Coefficient_of_Variation: %.2f\n", normStdDevn); free( clusterSizes ); npart += noOfSingletons; // ncut += noOfSingletons; printf("Output statistics for original graph\n"); mapIndices(part, nodeMap, graph.nvtxs, npart-noOfSingletons); } else { npart=mapPartition(part,graph.nvtxs); ncut=ComputeNCut(&graph, part,npart); } idxtype* clusterSizes = histogram(part, graph.nvtxs, npart); int maxSize = clusterSizes[idxamax(npart, clusterSizes)]; float avgClusterSize = (graph.nvtxs)*1.0/(npart); float balance = (maxSize*1.0)/(graph.nvtxs*1.0/npart); float stdDevn = stdDeviation(clusterSizes, npart); float avgNcut = ncut * 1.0/npart; float normStdDevn = stdDevn/avgClusterSize; printf("Clusters: %d N-Cut: %.3f AvgN-Cut: %.3f", npart, ncut, avgNcut ); printf(" Balance in cluster sizes: %.2f Std.Deviation in cluster sizes: %.2f ", balance, stdDevn); printf("Coefficient_of_Variation: %.2f\n", normStdDevn); starttimer(IOTmr); my_WritePartition(outputFile, part, graph.nvtxs, opt.gamma); if ( noOfSingletons > 0 ) { free(nodeMap); nodeMap = NULL; } printf("\nOutput is written to file: %s\n", outputFile); stoptimer(IOTmr); stoptimer(TOTALTmr); printf("\nTiming Information --------------------------------------------------\n"); printf(" I/O: \t\t %7.3f\n", gettimer(IOTmr)); printf(" Partitioning: \t\t %7.3f (MLR-MCL time)\n", gettimer(METISTmr)); printf(" Total: \t\t %7.3f\n", gettimer(TOTALTmr)); printf("**********************************************************************\n"); GKfree((void**)&graph.xadj, (void**)&graph.adjncy, (void**)&graph.vwgt, (void**)&graph.adjwgt, (void**)&part, LTERM); }
short send_message(char *msg_text, int errno_val, int severity, mtyp_t msg_type) { char char_time[22]; /* variable string for formatted system time */ char error_msg[128]; /* error message string */ char *str_time_ptr; /* pointer to string format of system time */ extern char *program_name; /* this program's name (argv[0]) */ extern int msgqid; /* IPC message queue id */ int errno_save = 0; /* save area for errno value */ short exit_code = 0; /* exit program return code */ size_t str_length = 0; /* string length variable */ struct htx_msg_buf msg_buffer; /* message buffer for HTX IPC msg queue */ #if defined(__HTX_LINUX__) || defined(__OS400__) time_t system_time; #else struct timestruc_t system_time; /* system time value from gettimer() */ #endif exit_code = GOOD; /* * message queue set up ? */ if(msgqid != -1) { /* * Check message length... */ if (htx_strlen(msg_text) > MAX_TEXT_MSG) { msg_text[MAX_TEXT_MSG] = '\0'; /* truncate to max length */ exit_code |= MSG_TOO_LONG; /* set message too log bit */ } /* endif */ /* * Build the character time string... */ errno = 0; #if defined(__HTX_LINUX__) || defined(__OS400__) system_time = time((time_t *) NULL); str_time_ptr = ctime((const time_t *) &system_time); htx_strncpy(char_time, "", sizeof(char_time)); htx_strncpy(char_time, (str_time_ptr + 4), 20); #else if (gettimer(TIMEOFDAY , &system_time) != GOOD) { errno_save = errno; sprintf(error_msg, "\n%s -- Error in the gettimer() system call of the send_message() function.\nerrno: %d (%s).\n", program_name, errno_save, strerror(errno_save)); fprintf(stderr, "%s", error_msg); fflush(stderr); exit_code |= BAD_GETTIMER; htx_strcpy(char_time, "gettimer() error"); } else { str_time_ptr = ctime((time_t *) (&(system_time.tv_sec))); htx_strncpy(char_time, "", sizeof(char_time)); htx_strncpy(char_time, (str_time_ptr + 4), 20); } /* endif */ #endif /* * Set up the "htx_data" portion of the message buffer... */ htx_strncpy(msg_buffer.htx_data.sdev_id, "", sizeof(msg_buffer.htx_data.sdev_id)); htx_strncpy(msg_buffer.htx_data.sdev_id, "htx_messages", (sizeof(msg_buffer.htx_data.sdev_id) - 1)); msg_buffer.htx_data.error_code = errno_val; msg_buffer.htx_data.severity_code = severity; htx_strncpy(msg_buffer.htx_data.HE_name, "", sizeof(msg_buffer.htx_data.HE_name)); htx_strncpy(msg_buffer.htx_data.HE_name, program_name, (sizeof(msg_buffer.htx_data.HE_name) - 1)); /* * Format the message... */ sprintf(msg_buffer.htx_data.msg_text, "%-18s%-20s err=%-8.8x sev=%-1.1u %-14s\n%-s\n", msg_buffer.htx_data.sdev_id, char_time, msg_buffer.htx_data.error_code, msg_buffer.htx_data.severity_code, msg_buffer.htx_data.HE_name, msg_text); /* * Make sure that the last two characters are '\n'... */ str_length = htx_strlen(msg_buffer.htx_data.msg_text); if (msg_buffer.htx_data.msg_text[str_length - 2] != '\n') { htx_strcat(msg_buffer.htx_data.msg_text, "\n"); } msg_buffer.mtype = msg_type; errno = 0; if(msgsnd(msgqid, &msg_buffer, (sizeof(msg_buffer) - sizeof(mtyp_t)), 0) != GOOD) { errno_save = errno; sprintf(error_msg, "\n%s -- Error in msgsnd() system call of the send_message() function.\nerrno: %d (%s).\n", program_name, errno_save, strerror(errno_save)); fprintf(stderr, "%s", error_msg); fflush(stderr); exit_code |= BAD_MSGSND; } /* endif */ } /* * message queue not set up -- write to stderr */ else { fprintf(stderr, "%s", msg_text); fflush(stderr); exit_code |= NO_MSG_QUEUE; } /* endif */ return(exit_code); } /* send_message() */