/* * Send an udp datagram to specified peer. */ void send_udp (unsigned char *data, size_t len, struct peer *p, unsigned char flags) { unsigned char outpkt[MAXPKT]; unsigned char *outbuf=outpkt+1; int olen; struct sockaddr_in *destination=&(p->in_a); unsigned char *crc; if (encryption_disabled || (flags==CMD_CHALLENGE || flags==CMD_LOGIN || flags==CMD_DENY || flags==CMD_AUTH_OK || flags == CMD_KEEPALIVE)){ memcpy(outbuf,data,len); olen=len; }else{ if(flags==PKT_DATA){ set_timestamp(data+len); len+=8; crc = crc32(data,len); memcpy(data+len,crc,4); free(crc); len+=4; } olen = data_encrypt(data,outbuf,len,p); } outpkt[0]=flags; sendto(nfd, outpkt, olen + 1, 0, (struct sockaddr *) destination, sizeof(struct sockaddr_in)); vc_printlog(4,"UDP Sent %dB datagram.",olen+1); }
Time& Time::operator += (ulonglong tm) { ulonglong ts = timestamp(); ts += tm; set_timestamp(ts); return *this; }
/* * Send an udp datagram to specified peer. */ void send_udp (unsigned char *data, size_t len, struct peer *p, unsigned char flags) { unsigned char outpkt[MAXPKT]; unsigned char *outbuf=outpkt+1; int olen; struct sockaddr_in *destination=&(p->in_a); unsigned char *crc; if (len + 8 - 1 > MAXPKT) { len = MAXPKT - 8 + 1; vc_printlog(2,"Warning: Cropping down packet size to %d", len); } if (encryption_disabled || (flags==CMD_CHALLENGE || flags==CMD_LOGIN || flags==CMD_DENY || flags==CMD_AUTH_OK || flags == CMD_KEEPALIVE)){ memcpy(outbuf,data,len); olen=len; }else{ unsigned char *tail = outbuf + len; crc = crc32(data,len); memcpy(tail,crc,4); free(crc); set_timestamp(tail + 4); olen = data_encrypt_decrypt(data, outbuf, len, p->key, tail); olen+=12; } outpkt[0]=flags; sendto(nfd, outpkt, olen + 1, 0, (struct sockaddr *) destination, sizeof(struct sockaddr_in)); vc_printlog(4,"UDP Sent %dB datagram.",olen+1); }
/* *************************************************************************** * Print a Linux restart message (contents of a RESTART record) or a * comment (contents of a COMMENT record). * * IN: * @curr Index in array for current sample statistics. * @use_tm_start Set to TRUE if option -s has been used. * @use_tm_end Set to TRUE if option -e has been used. * @rtype Record type to display. * @ifd Input file descriptor. * * RETURNS: * 1 if the record has been successfully displayed. *************************************************************************** */ int sar_print_special(int curr, int use_tm_start, int use_tm_end, int rtype, int ifd) { char cur_time[26]; int dp = 1; set_timestamp(curr, cur_time, 26); /* The record must be in the interval specified by -s/-e options */ if ((use_tm_start && (datecmp(&rectime, &tm_start) < 0)) || (use_tm_end && (datecmp(&rectime, &tm_end) > 0))) { dp = 0; } if (rtype == R_RESTART) { if (dp) { printf("\n%-11s LINUX RESTART\n", cur_time); return 1; } } else if (rtype == R_COMMENT) { char file_comment[MAX_COMMENT_LEN]; /* Don't forget to read comment record even if it won't be displayed... */ sa_fread(ifd, file_comment, MAX_COMMENT_LEN, HARD_SIZE); file_comment[MAX_COMMENT_LEN - 1] = '\0'; if (dp && DISPLAY_COMMENT(flags)) { printf("%-11s COM %s\n", cur_time, file_comment); return 1; } } return 0; }
void Buffer_pool_node::reset(){ set_fd(INIT); set_pos(INIT); set_timestamp(INIT); mark_clean(); }
/** * @brief actually does the write to kafka of a string with the given * file path * @param path file path to save to kafka * @param buf write buffer * @param size size of the buffer to write * @param offset starting point in the buffer * @return 0 if the write succeeded, 1 otherwise **/ static int actual_kafka_write(const char *path, const char *buf, size_t size, off_t offset) { char* ret = NULL; (void) path; char timestamp[] = "YYYY-MM-ddTHH:mm:ss.SSS+0000"; char* text = base64(buf, size); struct fuse_context* context = fuse_get_context(); struct group* sgroup = getgrgid(context->gid); struct passwd* suser = getpwuid(context->uid); char* user = suser == NULL ? "":suser->pw_name; char* group = sgroup == NULL ? "":sgroup->gr_name; char* command = get_command_line(context->pid); char* format = "{\"path\": \"%s%s\", \"pid\": %d, \"uid\": %d, " "\"gid\": %d, \"@message\": \"%s\", \"@timestamp\": \"%s\"," "\"user\": \"%s\", \"group\": \"%s\", \"command\": \"%s\"," "\"@version\": \"%s\", \"@fields\": %s, \"@tags\": %s}"; kafka_t *private_data = (kafka_t*) fuse_get_context()->private_data; config* conf = (config*)private_data->conf; set_timestamp(timestamp); asprintf(&ret, format, conf->directories[conf->directory_n], path + 1, context->pid, context->uid, context->gid, text, timestamp, user, group, command, VERSION, conf->fields_s, conf->tags_s); free(command); free(text); if (ret == NULL) { fprintf(stderr, "Error in asprintf\n"); return 1; } send_kafka(context->private_data, ret, strlen(ret)); free(ret); return 0; }
static gboolean download_review_stats (GsPlugin *plugin, GCancellable *cancellable, GError **error) { g_autofree gchar *uri = NULL; g_autoptr(SoupMessage) msg = NULL; guint status_code; g_autoptr(JsonParser) result = NULL; if (!send_review_request (plugin, SOUP_METHOD_GET, "/api/1.0/review-stats/any/any/", NULL, FALSE, &status_code, &result, cancellable, error)) return FALSE; if (status_code != SOUP_STATUS_OK) { g_set_error (error, GS_PLUGIN_ERROR, GS_PLUGIN_ERROR_DOWNLOAD_FAILED, "Failed to download review stats, server returned status code %u", status_code); return FALSE; } /* Extract the stats from the data */ if (!parse_review_entries (plugin, result, error)) return FALSE; /* Record the time we downloaded it */ return set_timestamp (plugin, "stats_mtime", error); }
void Nes_Emu::reset( bool full_reset, bool erase_battery_ram ) { require( cart() ); clear_sound_buf(); set_timestamp( 0 ); emu.reset( full_reset, erase_battery_ram ); }
static void sender_insertProducts(void) { pqueue* pq; int status = pq_open(UP7_PQ_PATHNAME, 0, &pq); CU_ASSERT_EQUAL_FATAL(status, 0); product prod; prod_info* info = &prod.info; char ident[80]; void* data = NULL; unsigned short xsubi[3] = {(unsigned short)1234567890, (unsigned short)9876543210, (unsigned short)1029384756 }; info->feedtype = EXP; info->ident = ident; info->origin = "localhost"; (void)memset(info->signature, 0, sizeof(info->signature)); for (int i = 0; i < NUM_PRODS; i++) { const unsigned size = MAX_PROD_SIZE*erand48(xsubi) + 0.5; const ssize_t nbytes = snprintf(ident, sizeof(ident), "%d", i); CU_ASSERT_TRUE_FATAL(nbytes >= 0 && nbytes < sizeof(ident)); status = set_timestamp(&info->arrival); CU_ASSERT_EQUAL_FATAL(status, 0); info->seqno = i; uint32_t signet = htonl(i); (void)memcpy(info->signature+sizeof(signaturet)-sizeof(signet), &signet, sizeof(signet)); info->sz = size; data = realloc(data, size); CU_ASSERT_PTR_NOT_NULL(data); prod.data = data; status = pq_insert(pq, &prod); CU_ASSERT_EQUAL_FATAL(status, 0); char buf[LDM_INFO_MAX]; LOG_ADD1("Inserted: prodInfo=\"%s\"", s_prod_info(buf, sizeof(buf), info, 1)); log_log(LOG_INFO); struct timespec duration; duration.tv_sec = 0; duration.tv_nsec = 5000000; // 5 ms status = nanosleep(&duration, NULL); CU_ASSERT_EQUAL_FATAL(status, 0); } free(data); status = pq_close(pq); CU_ASSERT_EQUAL_FATAL(status, 0); }
/*ARGSUSED0*/ int cfGetProduct( pq_match mt, const prod_class_t* clss, prod_info* info, void** data, void** encProd, size_t* len) { int status; if (currState != READY) { uerror("%s:%d: Configuration file not ready", __FILE__, __LINE__); status = ENOENT; } else { ensure_delay(); *info = prodInfo; status = set_timestamp(&info->arrival); if (status != 0) { uerror("%s:%d: Couldn't set product arrival time: %s", __FILE__, __LINE__, strerror(errno)); } else { XDR xdr; info->seqno = ++prodCount; nextSignature(&info->signature); prod.info = *info; *data = prodData; *len = prodXdrLen; *encProd = prodXdrBuf; xdrmem_create(&xdr, *encProd, *len, XDR_ENCODE); if(xdr_product(&xdr, &prod)) { status = ENOERR; } else { uerror("%s:%d: Couldn't XDR_ENCODE product", __FILE__, __LINE__); status = EIO; } xdr_destroy(&xdr); } } return status; }
RequestHandler(const Request* request, ResponseFuture* future, RetryPolicy* retry_policy) : Handler(request) , future_(future) , retry_policy_(retry_policy) , num_retries_(0) , is_query_plan_exhausted_(true) , io_worker_(NULL) , pool_(NULL) { set_timestamp(request->timestamp()); }
void _normalize() { if ( _exist_auth_map_key("oauth_timestamp") == false ) { time_t t; time(&t); set_timestamp((int)t); } ////////////////////////////////////////////////////////// _generate_signature(); }
/* * Set time stamp and hook up body of message */ static wmo_message * init_wmo_message( xbuf *buf, /* should be a clone ! */ wmo_message *mess ) { mess->len = buf->cnt; mess->msg = buf->get; if(set_timestamp(&mess->arrival) != 0) return NULL; return mess; }
/*ARGSUSED0*/ int pq_last( pqueue* pq, const prod_class_t* clssp, timestampt* tsp) /* modified upon return */ { int status = set_timestamp(tsp); if (status != 0) { uerror("%s:%d: Couldn't set time: %s", __FILE__, __LINE__, strerror(errno)); } return status; }
/** * Set named attribute. * * @param attr Name of the attribute (must be one of "id", "version", "changeset", "timestamp", "uid", "visible") * @param value Value of the attribute */ void set_attribute(const char* attr, const char* value) { if (!strcmp(attr, "id")) { set_id(value); } else if (!strcmp(attr, "version")) { set_version(value); } else if (!strcmp(attr, "changeset")) { set_changeset(value); } else if (!strcmp(attr, "timestamp")) { set_timestamp(osmium::Timestamp(value)); } else if (!strcmp(attr, "uid")) { set_uid(value); } else if (!strcmp(attr, "visible")) { set_visible(value); } }
/* * Set time stamp and hook up body of message */ static faa604_message * init_faa604_message( xbuf *buf, /* should be a clone ! */ faa604_message *mess ) { mess->len = buf->cnt; if( set_timestamp(&mess->arrival) != 0) return NULL; mess->seqno = -1; memset(mess->ident, 0, sizeof(mess->ident)); mess->msg = buf->get; return mess; }
void MirSurface::raise_surface_with_cookie(MirCookie const& cookie) { mp::RaiseRequest raise_request; std::unique_lock<decltype(mutex)> lock(mutex); raise_request.mutable_surface_id()->set_value(surface->id().value()); auto const event_cookie = raise_request.mutable_cookie(); event_cookie->set_timestamp(cookie.timestamp); event_cookie->set_mac(cookie.mac); server->raise_surface_with_cookie( &raise_request, void_response.get(), google::protobuf::NewCallback(google::protobuf::DoNothing)); }
bool Altitude_Hold::ExecuteCycle() { int t = hal.scheduler->micros(); float dt = (t - timestamp()) / 1000.0; set_timestamp(t); update_curr_height(); float height_err = target_height() - curr_height(); float height_correction = height_pid.get_pid(height_err, dt); float throttle = hover_throttle() + height_correction * THROTTLE_CORRECTION_SCALE; ++count; if(!(count % 50) && DEBUG) { hal.console->printf("Height Correction: %f, Throttle: %f, Err: %f\n", height_correction, throttle, height_err); } set_hover_throttle(throttle); flight_control()->execute(up_cntrl(), throttle, 0); return false; }
/* * called at exit */ static void cleanup(void) { log_notice("Exiting"); if (done) { /* * We are not in the interrupt context, so these can be performed * safely. */ fl_closeAll(); if (pq) (void)pq_close(pq); if (!tvEqual(palt_last_insertion, TS_ZERO)) { timestampt now; (void)set_timestamp(&now); log_notice("Behind by %g s", d_diff_timestamp(&now, &palt_last_insertion)); if (stateWrite(&palt_last_insertion) < 0) { log_error("Couldn't save insertion-time of last processed " "data-product"); } } while (reap(-1, WNOHANG) > 0) /*EMPTY*/; } if(shmid != -1) { log_notice("Deleting shared segment."); shmctl(shmid, IPC_RMID, NULL); } if(semid != -1) { semctl(semid, 0, IPC_RMID); } log_fini(); }
void GeneralWriter :: progMsg ( const std :: string & name, uint32_t version, uint64_t done, uint64_t total ) { switch ( state ) { case opened: break; default: return; } size_t str_size = name . size (); if ( str_size == 0 ) throw "zero-length app-name"; if ( str_size > 0x100 ) str_size = 0x100; // timestamp time_t timestamp = time ( NULL ); if ( total == 0 ) throw "illegal total value: would divide by zero"; if ( done > total ) throw "illegal done value: greater than total"; // calculate percentage done double fpercent = ( double ) done / total; assert ( fpercent >= 0.0 && fpercent <= 100.0 ); uint8_t percent = ( uint8_t ) ( fpercent * 100 ); gwp_status_evt_v1 hdr; init ( hdr, 0, evt_progmsg ); set_pid ( hdr, pid ); set_version ( hdr, version ); set_timestamp ( hdr, ( uint32_t ) timestamp ); set_size ( hdr, str_size ); set_percent ( hdr, percent ); write_event ( &hdr . dad, sizeof hdr ); internal_write ( name.data (), str_size ); }
static rt_err_t rt1021_hp_rtc_control(rt_device_t dev, int cmd, void *args) { RT_ASSERT(dev != RT_NULL); switch(cmd) { case RT_DEVICE_CTRL_RTC_GET_TIME: { *(uint32_t *)args = get_timestamp(); } break; case RT_DEVICE_CTRL_RTC_SET_TIME: { set_timestamp(*(time_t *)args); } break; default: return RT_EINVAL; } return RT_EOK; }
static int add_auth_descriptor(varsign_context *ctx, unsigned char dont_sign) { EFI_VARIABLE_AUTHENTICATION_2 *auth; int rc=0, len=0, flags=0; EFI_TIME timestamp; const EVP_MD *md; BIO *data_bio = NULL; PKCS7 *p7; UINT8 *signpkg; if (set_timestamp(×tamp)) return -1; /* create a BIO for our variable data, containing: * * Variablename (not including trailing nul) * * VendorGUID * * Attributes * * TimeStamp * * Data */ if (dont_sign == 0) { data_bio = BIO_new(BIO_s_mem()); BIO_write(data_bio, ctx->var_name, ctx->var_name_bytes); BIO_write(data_bio, &ctx->var_guid, sizeof(ctx->var_guid)); BIO_write(data_bio, &ctx->var_attrs, sizeof(ctx->var_attrs)); BIO_write(data_bio, ×tamp, sizeof(timestamp)); BIO_write(data_bio, ctx->data, ctx->data_len); md = EVP_get_digestbyname("SHA256"); p7 = PKCS7_new(); flags = PKCS7_BINARY | PKCS7_DETACHED | PKCS7_NOSMIMECAP;; PKCS7_set_type(p7, NID_pkcs7_signed); PKCS7_content_new(p7, NID_pkcs7_data); PKCS7_sign_add_signer(p7, ctx->cert, ctx->key, md, flags); PKCS7_set_detached(p7, 1); rc = PKCS7_final(p7, data_bio, flags); if (!rc) { fprintf(stderr, "Error signing variable data\n"); ERR_print_errors_fp(stderr); BIO_free_all(data_bio); return -1; } len = i2d_PKCS7(p7, NULL); } else { len = 0; } /* set up our auth descriptor */ auth = talloc_size(ctx, len + offsetof (EFI_VARIABLE_AUTHENTICATION_2, AuthInfo.CertData)); auth->TimeStamp = timestamp; auth->AuthInfo.Hdr.dwLength = len + offsetof (WIN_CERTIFICATE_UEFI_GUID, CertData); auth->AuthInfo.Hdr.wRevision = 0x0200; auth->AuthInfo.Hdr.wCertificateType = 0x0EF1; auth->AuthInfo.CertType = cert_pkcs7_guid; if (dont_sign == 0) { signpkg = auth->AuthInfo.CertData; i2d_PKCS7(p7, &signpkg); } ctx->auth_descriptor = auth; ctx->auth_descriptor_len = len + offsetof (EFI_VARIABLE_AUTHENTICATION_2, AuthInfo.CertData); BIO_free_all(data_bio); return 0; }
int main(int ac, char *av[]) { char *logfname = 0; unsigned timeo = DEFAULT_TIMEO; unsigned interval = DEFAULT_TIMEO; unsigned TotalTimeo = DEFAULT_TOTALTIMEO; prod_spec spec; int status; prod_class_t *clssp; unsigned remotePort = LDM_PORT; if(set_timestamp(&clss.from) != 0) { fprintf(stderr, "Couldn't set timestamp\n"); exit(1); } clss.to = TS_ENDT; clss.psa.psa_len = 1; clss.psa.psa_val = &spec; spec.feedtype = DEFAULT_FEEDTYPE; spec.pattern = DEFAULT_PATTERN; { /* Begin getopt block */ extern int optind; extern int opterr; extern char *optarg; int ch; int logmask = (LOG_MASK(LOG_ERR) | LOG_MASK(LOG_WARNING) | LOG_MASK(LOG_NOTICE)); int fterr; opterr = 1; while ((ch = getopt(ac, av, "vxl:f:o:t:h:P:p:T:")) != EOF) switch (ch) { case 'v': logmask |= LOG_MASK(LOG_INFO); break; case 'x': logmask |= LOG_MASK(LOG_DEBUG); break; case 'l': logfname = optarg; break; case 'h': remote = optarg; break; case 'P': { char* suffix = ""; long port; errno = 0; port = strtol(optarg, &suffix, 0); if (0 != errno || 0 != *suffix || 0 >= port || 0xffff < port) { (void)fprintf(stderr, "%s: invalid port %s\n", av[0], optarg); usage(av[0]); } remotePort = (unsigned)port; break; } case 'p': spec.pattern = optarg; /* compiled below */ break; case 'f': fterr = strfeedtypet(optarg, &spec.feedtype); if(fterr != FEEDTYPE_OK) { fprintf(stderr, "Bad feedtype \"%s\", %s\n", optarg, strfeederr(fterr)); usage(av[0]); } break; case 'o': clss.from.tv_sec -= atoi(optarg); break; case 'T': TotalTimeo = atoi(optarg); if(TotalTimeo == 0) { fprintf(stderr, "%s: invalid TotalTimeo %s", av[0], optarg); usage(av[0]); } break; case 't': timeo = (unsigned)atoi(optarg); if(timeo == 0 || timeo > 32767) { fprintf(stderr, "%s: invalid timeout %s", av[0], optarg); usage(av[0]); } break; case '?': usage(av[0]); break; } if(ac - optind > 0) usage(av[0]); if (re_isPathological(spec.pattern)) { fprintf(stderr, "Adjusting pathological regular-expression: " "\"%s\"\n", spec.pattern); re_vetSpec(spec.pattern); } status = regcomp(&spec.rgx, spec.pattern, REG_EXTENDED|REG_NOSUB); if(status != 0) { fprintf(stderr, "Bad regular expression \"%s\"\n", spec.pattern); usage(av[0]); } (void) setulogmask(logmask); if(TotalTimeo < timeo) { fprintf(stderr, "TotalTimeo %u < timeo %u\n", TotalTimeo, timeo); usage(av[0]); } } /* End getopt block */ /* * initialize logger */ (void) openulog(ubasename(av[0]), (LOG_CONS|LOG_PID), LOG_LDM, logfname); unotice("Starting Up: %s: %s", remote, s_prod_class(NULL, 0, &clss)); /* * register exit handler */ if(atexit(cleanup) != 0) { serror("atexit"); exit(1); } /* * set up signal handlers */ set_sigactions(); /* * Try forever. */ while (exitIfDone(0)) { clssp = &clss; status = forn5(NOTIFYME, remote, &clssp, timeo, TotalTimeo, notifymeprog_5); (void)exitIfDone(0); switch(status) { /* problems with remote, retry */ case ECONNABORTED: case ECONNRESET: case ETIMEDOUT: case ECONNREFUSED: sleep(interval); break; case 0: /* assert(done); */ break; default: /* some wierd error */ done = 1; exit(1); } } exit(0); /*NOTREACHED*/ }
int main( int ac, char *av[] ) { const char* const pqfname = getQueuePath(); const char* const progname = ubasename(av[0]); int useProductID = FALSE; int signatureFromId = FALSE; char *productID = NULL; int multipleFiles = FALSE; char identifier[KEYSIZE]; int status; int seq_start = 0; enum ExitCode { exit_success = 0, /* all files inserted successfully */ exit_system = 1, /* operating-system failure */ exit_pq_open = 2, /* couldn't open product-queue */ exit_infile = 3, /* couldn't process input file */ exit_dup = 4, /* input-file already in product-queue */ exit_md5 = 6 /* couldn't initialize MD5 processing */ } exitCode = exit_success; #if !USE_MMAP pqeIndex = PQE_NONE; #endif { extern int optind; extern int opterr; extern char *optarg; int ch; (void) openulog(progname, LOG_NOTIME, LOG_LDM, "-"); (void) setulogmask(LOG_UPTO(LOG_NOTICE)); opterr = 0; /* Suppress getopt(3) error messages */ while ((ch = getopt(ac, av, ":ivxl:q:f:s:p:")) != EOF) switch (ch) { case 'i': signatureFromId = 1; break; case 'v': (void) setulogmask(getulogmask() | LOG_MASK(LOG_INFO)); break; case 'x': (void) setulogmask(getulogmask() | LOG_MASK(LOG_DEBUG)); break; case 'l': openulog(progname, ulog_get_options(), LOG_LDM, optarg); break; case 'q': setQueuePath(optarg); break; case 's': seq_start = atoi(optarg); break; case 'f': feedtype = atofeedtypet(optarg); if(feedtype == NONE) { fprintf(stderr, "Unknown feedtype \"%s\"\n", optarg); usage(progname); } break; case 'p': useProductID = TRUE; productID = optarg; break; case ':': { LOG_ADD1("Option \"-%c\" requires an operand", optopt); usage(progname); } /* no break */ default: LOG_ADD1("Unknown option: \"%c\"", optopt); usage(progname); /* no break */ } ac -= optind; av += optind ; if(ac < 1) usage(progname); } /* * register exit handler */ if(atexit(cleanup) != 0) { serror("atexit"); exit(exit_system); } /* * set up signal handlers */ set_sigactions(); /* * who am i, anyway */ (void) strncpy(myname, ghostname(), sizeof(myname)); myname[sizeof(myname)-1] = 0; /* * open the product queue */ if(status = pq_open(pqfname, PQ_DEFAULT, &pq)) { if (PQ_CORRUPT == status) { uerror("The product-queue \"%s\" is inconsistent\n", pqfname); } else { uerror("pq_open: \"%s\" failed: %s", pqfname, status > 0 ? strerror(status) : "Internal error"); } exit(exit_pq_open); } { char *filename; int fd; struct stat statb; product prod; MD5_CTX *md5ctxp = NULL; /* * Allocate an MD5 context */ md5ctxp = new_MD5_CTX(); if(md5ctxp == NULL) { serror("new_md5_CTX failed"); exit(exit_md5); } /* These members are constant over the loop. */ prod.info.origin = myname; prod.info.feedtype = feedtype; if (ac > 1) { multipleFiles = TRUE; } for(prod.info.seqno = seq_start ; ac > 0 ; av++, ac--, prod.info.seqno++) { filename = *av; fd = open(filename, O_RDONLY, 0); if(fd == -1) { serror("open: %s", filename); exitCode = exit_infile; continue; } if( fstat(fd, &statb) == -1) { serror("fstat: %s", filename); (void) close(fd); exitCode = exit_infile; continue; } /* Determine what to use for product identifier */ if (useProductID) { if (multipleFiles) { sprintf(identifier,"%s.%d", productID, prod.info.seqno); prod.info.ident = identifier; } else prod.info.ident = productID; } else prod.info.ident = filename; prod.info.sz = statb.st_size; prod.data = NULL; /* These members, and seqno, vary over the loop. */ status = set_timestamp(&prod.info.arrival); if(status != ENOERR) { serror("set_timestamp: %s, filename"); exitCode = exit_infile; continue; } #if USE_MMAP prod.data = mmap(0, prod.info.sz, PROT_READ, MAP_PRIVATE, fd, 0); if(prod.data == NULL) { serror("mmap: %s", filename); (void) close(fd); exitCode = exit_infile; continue; } status = signatureFromId ? mm_md5(md5ctxp, prod.info.ident, strlen(prod.info.ident), prod.info.signature) : mm_md5(md5ctxp, prod.data, prod.info.sz, prod.info.signature); (void)exitIfDone(1); if (status != 0) { serror("mm_md5: %s", filename); (void) munmap(prod.data, prod.info.sz); (void) close(fd); exitCode = exit_infile; continue; } /* These members, and seqno, vary over the loop. */ status = set_timestamp(&prod.info.arrival); if(status != ENOERR) { serror("set_timestamp: %s, filename"); exitCode = exit_infile; continue; } /* * Do the deed */ status = pq_insert(pq, &prod); switch (status) { case ENOERR: /* no error */ if(ulogIsVerbose()) uinfo("%s", s_prod_info(NULL, 0, &prod.info, ulogIsDebug())) ; break; case PQUEUE_DUP: uerror("Product already in queue: %s", s_prod_info(NULL, 0, &prod.info, 1)); exitCode = exit_dup; break; case PQUEUE_BIG: uerror("Product too big for queue: %s", s_prod_info(NULL, 0, &prod.info, 1)); exitCode = exit_infile; break; case ENOMEM: uerror("queue full?"); exitCode = exit_system; break; case EINTR: #if defined(EDEADLOCK) && EDEADLOCK != EDEADLK case EDEADLOCK: /*FALLTHROUGH*/ #endif case EDEADLK: /* TODO: retry ? */ /*FALLTHROUGH*/ default: uerror("pq_insert: %s", status > 0 ? strerror(status) : "Internal error"); break; } (void) munmap(prod.data, prod.info.sz); #else // USE_MMAP above; !USE_MMAP below status = signatureFromId ? mm_md5(md5ctxp, prod.info.ident, strlen(prod.info.ident), prod.info.signature) : fd_md5(md5ctxp, fd, statb.st_size, prod.info.signature); (void)exitIfDone(1); if (status != 0) { serror("xx_md5: %s", filename); (void) close(fd); exitCode = exit_infile; continue; } if(lseek(fd, 0, SEEK_SET) == (off_t)-1) { serror("rewind: %s", filename); (void) close(fd); exitCode = exit_infile; continue; } pqeIndex = PQE_NONE; status = pqe_new(pq, &prod.info, &prod.data, &pqeIndex); if(status != ENOERR) { serror("pqe_new: %s", filename); exitCode = exit_infile; } else { ssize_t nread = read(fd, prod.data, prod.info.sz); (void)exitIfDone(1); if (nread != prod.info.sz) { serror("read %s %u", filename, prod.info.sz); status = EIO; } else { status = pqe_insert(pq, pqeIndex); pqeIndex = PQE_NONE; switch (status) { case ENOERR: /* no error */ if(ulogIsVerbose()) uinfo("%s", s_prod_info(NULL, 0, &prod.info, ulogIsDebug())) ; break; case PQUEUE_DUP: uerror("Product already in queue: %s", s_prod_info(NULL, 0, &prod.info, 1)); exitCode = exit_dup; break; case ENOMEM: uerror("queue full?"); break; case EINTR: #if defined(EDEADLOCK) && EDEADLOCK != EDEADLK case EDEADLOCK: /*FALLTHROUGH*/ #endif case EDEADLK: /* TODO: retry ? */ /*FALLTHROUGH*/ default: uerror("pq_insert: %s", status > 0 ? strerror(status) : "Internal error"); } } /* data read into `pqeIndex` region */ if (status != ENOERR) { (void)pqe_discard(pq, pqeIndex); pqeIndex = PQE_NONE; } } /* `pqeIndex` region allocated */ #endif (void) close(fd); } /* input-file loop */ free_MD5_CTX(md5ctxp); } /* code block */ exit(exitCode); }
static int process_file(void){ struct stat statb; int ccb_offset = g.opt_ccbsize; int status = 0; product prod; ssize_t nread; ssize_t filedata_size; unsigned char *p; int n; status = pq_open(g.opt_pqfname, PQ_DEFAULT, &g.pq); if(status != 0){ if(status == PQ_CORRUPT) errx(1, "The product queue %s is inconsistent.", g.opt_pqfname); else err(1, "pq_open"); } prod.info.origin = g.opt_origin; prod.info.feedtype = g.opt_feedtype; set_timestamp(&prod.info.arrival); prod.info.seqno = g.seq; prod.info.ident = g.opt_prodid; if(prod.info.ident == NULL) prod.info.ident = g.input_fname; /* * This should not happen because it has been checked in option processing. */ if(prod.info.ident == NULL) errx(1, "No prodid specified."); if(g.input_fname == NULL){ g.fd = STDIN_FILENO; filedata_size = g.opt_filesize; }else { g.fd = open(g.input_fname, O_RDONLY, 0); if(g.fd == -1) err(1, "open"); if(g.opt_filesize == 0){ if(fstat(g.fd, &statb) == -1) err(1, "fstat"); filedata_size = statb.st_size; }else filedata_size = g.opt_filesize; } if(g.opt_noccb == 0){ if(filedata_size <= g.opt_ccbsize) input_file_errx(1, "No data in inputfile"); else filedata_size -= g.opt_ccbsize; }else ccb_offset = 0; prod.info.sz = filedata_size; if(g.opt_gempak == 1){ prod.info.sz += GMPK_HEADER_SIZE + GMPK_TRAILER_SIZE; } if(prod.info.sz <= STATIC_POOL_SIZE) prod.data = (void*)static_pool; else prod.data = malloc(prod.info.sz); if(prod.data == NULL) err(1, "malloc"); if(ccb_offset != 0){ if(lseek(g.fd, ccb_offset, SEEK_SET) == -1) input_file_err(1, "lseek error in inputfile"); } p = (unsigned char*)prod.data; if(g.opt_gempak == 1){ n = sprintf(gmpk_header_str, gmpk_header_fmt, (int)(g.seq % 1000)); if(n != GMPK_HEADER_SIZE) errx(1, "gmpk_header_fmt format error."); memcpy(p, gmpk_header_str, GMPK_HEADER_SIZE); p += GMPK_HEADER_SIZE; } /* * Use readn when nbsp2ldm is opened as a pipe in tcl. */ nread = readn(g.fd, p, filedata_size); if(nread != filedata_size) input_file_err(1, "read() error"); if((g.opt_seq_str != NULL) && (g.opt_md5seq == 1)) status = calc_md5((unsigned char*)g.opt_seq_str, strlen(g.opt_seq_str), prod.info.signature); else status = calc_md5(p, filedata_size, prod.info.signature); if (status != 0) errx(1, "calc_md5"); if(g.opt_gempak == 1){ p += filedata_size; memcpy(p, gmpk_trailer_str, GMPK_TRAILER_SIZE); } status = pq_insert(g.pq, &prod); if(status == PQUEUE_DUP){ status = 0; warnx("Product already in queue: %s.", prod.info.ident); }else if(status != 0) errx(1, "pq_insert: %d", status); return(status); }
int main(int ac, char *av[]) { const char* pqfname = getQueuePath(); const char *opqfname = getSurfQueuePath(); const char *progname = ubasename(av[0]); char *logfname; prod_class_t clss; prod_spec spec; int status = 0; unsigned interval = DEFAULT_INTERVAL; int logoptions = (LOG_CONS|LOG_PID); double age = DEFAULT_AGE; /* these are containers for the pqact args */ char *argv[16]; int argc = 0; int toffset = TOFFSET_NONE; logfname = ""; if(set_timestamp(&clss.from) != ENOERR) /* corrected by toffset below */ { int errnum = errno; fprintf(stderr, "Couldn't set timestamp: %s", strerror(errnum)); exit(1); } clss.to = TS_ENDT; clss.psa.psa_len = 1; clss.psa.psa_val = &spec; spec.feedtype = DEFAULT_FEEDTYPE; spec.pattern = DEFAULT_PATTERN; memset(argv, 0, sizeof(argv)); argv[0] = "pqact"; argc++; { extern int optind; extern int opterr; extern char *optarg; int ch; int logmask = (LOG_MASK(LOG_ERR) | LOG_MASK(LOG_WARNING) | LOG_MASK(LOG_NOTICE)); int fterr; const char *conffilename = getPqsurfConfigPath(); const char *datadir = getPqsurfDataDirPath(); usePil = 1; opterr = 1; while ((ch = getopt(ac, av, "vxl:d:f:p:q:Q:o:i:a:t:")) != EOF) switch (ch) { case 'v': argv[argc++] = "-v"; logmask |= LOG_MASK(LOG_INFO); break; case 'x': argv[argc++] = "-x"; logmask |= LOG_MASK(LOG_DEBUG); break; case 'l': argv[argc++] = "-l"; argv[argc++] = optarg; logfname = optarg; break; case 'd': datadir = optarg; break; case 'f': fterr = strfeedtypet(optarg, &spec.feedtype); if(fterr != FEEDTYPE_OK) { fprintf(stderr, "%s: %s: \"%s\"\n", av[0], strfeederr(fterr), optarg); usage(progname); } argv[argc++] = "-f"; argv[argc++] = optarg; break; case 'p': spec.pattern = optarg; /* compiled below */ break; case 'q': pqfname = optarg; break; case 'Q': opqfname = optarg; break; case 'o': toffset = atoi(optarg); if(toffset == 0 && *optarg != '0') { fprintf(stderr, "%s: invalid offset %s\n", av[0], optarg); usage(av[0]); } argv[argc++] = "-o"; argv[argc++] = optarg; break; case 'i': interval = atoi(optarg); if(interval == 0 && *optarg != '0') { fprintf(stderr, "%s: invalid interval \"%s\"\n", av[0], optarg); usage(av[0]); } /* N.B. -i just used for input queue. */ break; case 'a': age = atof(optarg); if(age < 0.) { (void) fprintf(stderr, "age (%s) must be non negative\n", optarg); usage(av[0]); } break; case 't': /* pipe_timeo */ argv[argc++] = "-t"; argv[argc++] = optarg; break; case '?': usage(progname); break; } (void) setulogmask(logmask); if (re_isPathological(spec.pattern)) { fprintf(stderr, "Adjusting pathological regular-expression: " "\"%s\"\n", spec.pattern); re_vetSpec(spec.pattern); } status = regcomp(&spec.rgx, spec.pattern, REG_EXTENDED|REG_NOSUB); if(status != 0) { fprintf(stderr, "Bad regular expression \"%s\"\n", spec.pattern); usage(av[0]); } if(ac - optind == 1) conffilename = av[optind]; argv[argc++] = "-d"; argv[argc++] = (char*)datadir; argv[argc++] = "-q"; argv[argc++] = (char*)opqfname; argv[argc++] = (char*)conffilename; age *= 3600.; } if(toffset != TOFFSET_NONE) { clss.from.tv_sec -= toffset; } else { clss.from.tv_sec -= (age - interval); } /* * Set up error logging. * N.B. log ident is the remote */ (void) openulog(progname, logoptions, LOG_LDM, logfname); unotice("Starting Up (%d)", getpgrp()); /* * register exit handler */ if(atexit(cleanup) != 0) { serror("atexit"); exit(1); } /* * set up signal handlers */ set_sigactions(); /* * Open the output product queue */ status = pq_open(opqfname, PQ_DEFAULT, &opq); if(status) { if (PQ_CORRUPT == status) { uerror("The output product-queue \"%s\" is inconsistent\n", opqfname); } else { uerror("pq_open failed: %s: %s\n", opqfname, strerror(status)); } exit(1); } act_pid = run_child(argc, argv); if(act_pid == (pid_t)-1) exit(1); /* * Open the input product queue */ status = pq_open(pqfname, PQ_READONLY, &pq); if(status) { if (PQ_CORRUPT == status) { uerror("The product-queue \"%s\" is inconsistent\n", pqfname); } else { uerror("pq_open failed: %s: %s\n", pqfname, strerror(status)); } exit(1); } if(toffset == TOFFSET_NONE) { /* Jump to the end of the queue */ timestampt sav; sav = clss.from; clss.from = TS_ZERO; (void) pq_last(pq, &clss, NULL); clss.from = sav; } else { pq_cset(pq, &clss.from); } if(ulogIsVerbose()) { char buf[1984]; uinfo("%s", s_prod_class(buf, sizeof(buf), &clss)); } while(exitIfDone(0)) { if(stats_req) { dump_stats(); stats_req = 0; } status = pq_sequence(pq, TV_GT, &clss, split_prod, NULL); switch(status) { case 0: /* no error */ continue; /* N.B., other cases sleep */ case PQUEUE_END: udebug("surf: End of Queue"); break; case EAGAIN: case EACCES: udebug("Hit a lock"); break; default: uerror("pq_sequence failed: %s (errno = %d)", strerror(status), status); exit(1); break; } if(interval == 0) { break; } (void) expire(opq, interval, age); pq_suspend(interval); (void) reap_act(WNOHANG); } /* * TODO: how can we determine that pqact has finished * the work in opq? */ sleep(5); exit(0); }
static int expire(pqueue *epq, const unsigned interval, const double age) { int status = ENOERR; static timestampt now; static prod_class eclss; static prod_spec spec; timestampt ts; timestampt cursor; double diff = 0.; double max_latency = 0.; size_t nr; if(eclss.psa.psa_val == 0) { /* first time */ eclss.from = TS_ZERO; eclss.psa.psa_len = 1; eclss.psa.psa_val = &spec; spec.feedtype = ANY; spec.pattern = ".*"; regcomp(&spec.rgx, spec.pattern, REG_EXTENDED|REG_NOSUB); } (void) set_timestamp(&now); if(d_diff_timestamp(&now, &eclss.to) < interval + age) { /* only run this routine every interval seconds */ udebug("not yet"); return ENOERR; } /* else */ eclss.to = now; eclss.to.tv_sec -= age; if(ulogIsDebug()) { char cp[64]; sprint_timestampt(cp, sizeof(cp), &eclss.to); udebug("to %s", cp); } pq_cset(epq, &TS_ZERO); while(exitIfDone(0) && !stats_req) { nr = 0; status = pq_seqdel(epq, TV_GT, &eclss, 0, &nr, &ts); switch(status) { case ENOERR: pq_ctimestamp(epq, &cursor); diff = d_diff_timestamp(&cursor, &ts); if(diff > max_latency) { max_latency = diff; udebug("max_latency %.3f", max_latency); } if(nr == 0) { diff = d_diff_timestamp(&cursor, &eclss.to); udebug("diff %.3f", diff); if(diff > interval + max_latency) { udebug("heuristic depth break"); break; } } continue; /* N.B., other cases break and return */ case PQUEUE_END: udebug("expire: End of Queue"); break; case EAGAIN: case EACCES: udebug("Hit a lock"); break; #if defined(EDEADLOCK) && EDEADLOCK != EDEADLK case EDEADLOCK: #endif case EDEADLK: uerror("%s", strerror(status)); break; default: uerror("pq_seqdel failed: %s (errno = %d)", strerror(status), status); break; } break; } return status; }
int main(int ac, char *av[]) { int status = 0; char* logfname = 0; /// Data directory, conffile paths may be relative const char* datadir; int interval = DEFAULT_INTERVAL; prod_spec spec; prod_class_t clss; int toffset = TOFFSET_NONE; int loggingToStdErr = 0; unsigned queue_size = 5000; const char* progname = basename(av[0]); unsigned logopts = LOG_CONS|LOG_PID; /* * Setup default logging before anything else. */ (void)log_init(progname); const char* pqfname = getQueuePath(); spec.feedtype = DEFAULT_FEEDTYPE; spec.pattern = DEFAULT_PATTERN; if(set_timestamp(&clss.from)) /* corrected by toffset below */ { int errnum = errno; log_error("Couldn't set timestamp: %s", strerror(errnum)); exit(EXIT_FAILURE); /*NOTREACHED*/ } clss.to = TS_ENDT; clss.psa.psa_len = 1; clss.psa.psa_val = &spec; /* * deal with the command line, set options */ { extern int optind; extern int opterr; extern char *optarg; int ch; int fterr; opterr = 1; while ((ch = getopt(ac, av, "vxel:d:f:q:o:p:i:t:")) != EOF) { switch (ch) { case 'v': if (!log_is_enabled_info) (void)log_set_level(LOG_LEVEL_INFO); break; case 'x': (void)log_set_level(LOG_LEVEL_DEBUG); break; case 'e': key = ftok("/etc/rc.d/rc.local",'R'); semkey = ftok("/etc/rc.d/rc.local",'e'); shmid = shmget(key, sizeof(edex_message) * queue_size, 0666 | IPC_CREAT); semid = semget(semkey, 2, 0666 | IPC_CREAT); break; case 'l': logfname = optarg; (void)log_set_destination(logfname); break; case 'd': setPqactDataDirPath(optarg); break; case 'f': fterr = strfeedtypet(optarg, &spec.feedtype); if(fterr != FEEDTYPE_OK) { log_error("Bad feedtype \"%s\", %s\n", optarg, strfeederr(fterr)); usage(progname); } break; case 'q': pqfname = optarg; break; case 'o': toffset = atoi(optarg); if(toffset == 0 && *optarg != '0') { log_error("invalid offset %s\n", optarg); usage(progname); } break; case 'i': interval = atoi(optarg); if(interval == 0 && *optarg != '0') { log_error("invalid interval %s\n", optarg); usage(progname); } break; case 't': pipe_timeo = atoi(optarg); if(pipe_timeo == 0 && *optarg != 0) { log_error("invalid pipe_timeo %s", optarg); usage(progname); } break; case 'p': spec.pattern = optarg; break; default: usage(progname); break; } } conffilename = getPqactConfigPath(); datadir = getPqactDataDirPath(); { int numOperands = ac - optind; if (1 < numOperands) { log_error("Too many operands"); usage(progname); } else if (1 == numOperands) { conffilename = av[optind]; } } } setQueuePath(pqfname); log_notice("Starting Up"); if ('/' != conffilename[0]) { /* * The pathname of the configuration-file is relative. Convert it * to absolute so that it can be (re)read even if the current * working directory changes. */ #ifdef PATH_MAX char buf[PATH_MAX]; /* includes NUL */ #else char buf[_POSIX_PATH_MAX]; /* includes NUL */ #endif if (getcwd(buf, sizeof(buf)) == NULL) { log_syserr("Couldn't get current working directory"); exit(EXIT_FAILURE); } (void)strncat(buf, "/", sizeof(buf)-strlen(buf)-1); (void)strncat(buf, conffilename, sizeof(buf)-strlen(buf)-1); conffilename = strdup(buf); if (conffilename == NULL) { log_syserr("Couldn't duplicate string \"%s\"", buf); exit(EXIT_FAILURE); } } /* * Initialize the previous-state module for this process. */ if (stateInit(conffilename) < 0) { log_error("Couldn't initialize previous-state module"); exit(EXIT_FAILURE); /*NOTREACHED*/ } /* * Configure the standard I/O streams for execution of child processes. */ if (configure_stdio_file_descriptors()) { log_error("Couldn't configure standard I/O streams for execution " "of child processes"); exit(EXIT_FAILURE); } /* * Inform the "filel" module about the number of available file * descriptors. File descriptors are reserved for stdin, stdout, * stderr, the product-queue, the configuration-file, and (possibly) * logging. */ if (0 != set_avail_fd_count(openMax() - 6)) { log_error("Couldn't set number of available file-descriptors"); log_notice("Exiting"); exit(EXIT_FAILURE); /*NOTREACHED*/ } /* * Inform the "filel" module of the shared memory segment */ if (shmid != -1 && semid != -1) { set_shared_space(shmid, semid, queue_size); } /* * Compile the pattern. */ if (re_isPathological(spec.pattern)) { log_error("Adjusting pathological regular-expression: \"%s\"", spec.pattern); re_vetSpec(spec.pattern); } status = regcomp(&spec.rgx, spec.pattern, REG_EXTENDED|REG_NOSUB); if(status != 0) { log_error("Can't compile regular expression \"%s\"", spec.pattern); log_notice("Exiting"); exit(EXIT_FAILURE); /*NOTREACHED*/ } /* * register exit handler */ if(atexit(cleanup) != 0) { log_syserr("atexit"); log_notice("Exiting"); exit(EXIT_FAILURE); /*NOTREACHED*/ } /* * set up signal handlers */ set_sigactions(); /* * Read in (compile) the configuration file. We do this first so * its syntax may be checked without opening a product queue. */ if ((status = readPatFile(conffilename)) < 0) { exit(EXIT_FAILURE); /*NOTREACHED*/ } else if (status == 0) { log_notice("Configuration-file \"%s\" has no entries. " "You should probably not start this program instead.", conffilename); } /* * Open the product queue */ status = pq_open(pqfname, PQ_READONLY, &pq); if(status) { if (PQ_CORRUPT == status) { log_error("The product-queue \"%s\" is inconsistent\n", pqfname); } else { log_error("pq_open failed: %s: %s\n", pqfname, strerror(status)); } exit(EXIT_FAILURE); /*NOTREACHED*/ } if(toffset != TOFFSET_NONE) { /* * Filter and queue position set by "toffset". */ clss.from.tv_sec -= toffset; pq_cset(pq, &clss.from); } else { bool startAtTailEnd = true; timestampt insertTime; clss.from = TS_ZERO; /* * Try getting the insertion-time of the last, * successfully-processed data-product from the previous session. */ status = stateRead(&insertTime); if (status) { log_warning("Couldn't get insertion-time of last-processed " "data-product from previous session"); } else { timestampt now; (void)set_timestamp(&now); if (tvCmp(now, insertTime, <)) { log_warning("Time of last-processed data-product from previous " "session is in the future"); } else { char buf[80]; (void)strftime(buf, sizeof(buf), "%Y-%m-%d %T", gmtime(&insertTime.tv_sec)); log_notice("Starting from insertion-time %s.%06lu UTC", buf, (unsigned long)insertTime.tv_usec); pq_cset(pq, &insertTime); startAtTailEnd = false; } } if (startAtTailEnd) { log_notice("Starting at tail-end of product-queue"); (void)pq_last(pq, &clss, NULL); } }
int main(int ac, char *av[]) { unsigned timeo = DEFAULT_TIMEO; unsigned interval = DEFAULT_TIMEO; unsigned TotalTimeo = DEFAULT_TOTALTIMEO; prod_spec spec; int status; prod_class_t* clssp; /* * initialize logger */ if (log_init(av[0])) { log_syserr("Couldn't initialize logging module"); exit(1); } if(set_timestamp(&clss.from) != 0) { fprintf(stderr, "Couldn't set timestamp\n"); exit(1); } clss.to = TS_ENDT; clss.psa.psa_len = 1; clss.psa.psa_val = &spec; spec.feedtype = DEFAULT_FEEDTYPE; spec.pattern = DEFAULT_PATTERN; { /* Begin getopt block */ extern int optind; extern int opterr; extern char *optarg; int ch; int fterr; opterr = 1; while ((ch = getopt(ac, av, "vxl:f:o:t:h:P:p:T:")) != EOF) switch (ch) { case 'v': if (!log_is_enabled_info) log_set_level(LOG_LEVEL_INFO); break; case 'x': log_set_level(LOG_LEVEL_DEBUG); break; case 'l': if (log_set_destination(optarg)) { log_syserr("Couldn't set logging destination to \"%s\"", optarg); usage(av[0]); } break; case 'h': remote = optarg; break; case 'P': { log_warning("Port specification is ignored"); break; } case 'p': spec.pattern = optarg; /* compiled below */ break; case 'f': fterr = strfeedtypet(optarg, &spec.feedtype); if(fterr != FEEDTYPE_OK) { fprintf(stderr, "Bad feedtype \"%s\", %s\n", optarg, strfeederr(fterr)); usage(av[0]); } break; case 'o': clss.from.tv_sec -= atoi(optarg); break; case 'T': TotalTimeo = atoi(optarg); if(TotalTimeo == 0) { fprintf(stderr, "%s: invalid TotalTimeo %s", av[0], optarg); usage(av[0]); } break; case 't': timeo = (unsigned)atoi(optarg); if(timeo == 0 || timeo > 32767) { fprintf(stderr, "%s: invalid timeout %s", av[0], optarg); usage(av[0]); } break; case '?': usage(av[0]); break; } if(ac - optind > 0) usage(av[0]); if (re_isPathological(spec.pattern)) { fprintf(stderr, "Adjusting pathological regular-expression: " "\"%s\"\n", spec.pattern); re_vetSpec(spec.pattern); } status = regcomp(&spec.rgx, spec.pattern, REG_EXTENDED|REG_NOSUB); if(status != 0) { fprintf(stderr, "Bad regular expression \"%s\"\n", spec.pattern); usage(av[0]); } if(TotalTimeo < timeo) { fprintf(stderr, "TotalTimeo %u < timeo %u\n", TotalTimeo, timeo); usage(av[0]); } } /* End getopt block */ log_notice_q("Starting Up: %s: %s", remote, s_prod_class(NULL, 0, &clss)); /* * register exit handler */ if(atexit(cleanup) != 0) { log_syserr("atexit"); exit(1); } /* * set up signal handlers */ set_sigactions(); /* * Try forever. */ while (exitIfDone(0)) { clssp = &clss; status = forn5(NOTIFYME, remote, &clssp, timeo, TotalTimeo, notifymeprog_5); (void)exitIfDone(0); switch(status) { /* problems with remote, retry */ case ECONNABORTED: case ECONNRESET: case ETIMEDOUT: case ECONNREFUSED: sleep(interval); break; case 0: /* assert(done); */ break; default: /* some wierd error */ done = 1; exit(1); } } exit(0); /*NOTREACHED*/ }
/* *************************************************************************** * Print system statistics * * IN: * @curr Index in array for current sample statistics. * @read_from_file Set to TRUE if stats are read from a system activity * data file. * @use_tm_start Set to TRUE if option -s has been used. * @use_tm_end Set to TRUE if option -e has been used. * @reset Set to TRUE if last_uptime variable should be * reinitialized (used in next_slice() function). * @act_id Activity that can be displayed or ~0 for all. * Remember that when reading stats from a file, only * one activity can be displayed at a time. * * OUT: * @cnt Number of remaining lines to display. * * RETURNS: * 1 if stats have been successfully displayed. *************************************************************************** */ int write_stats(int curr, int read_from_file, long *cnt, int use_tm_start, int use_tm_end, int reset, unsigned int act_id) { int i; unsigned long long itv, g_itv; static int cross_day = 0; static __nr_t cpu_nr = -1; if (cpu_nr < 0) cpu_nr = act[get_activity_position(act, A_CPU)]->nr; /* Check time (1) */ if (read_from_file) { if (!next_slice(record_hdr[2].uptime0, record_hdr[curr].uptime0, reset, interval)) /* Not close enough to desired interval */ return 0; } /* Set previous timestamp */ set_timestamp(!curr, timestamp[!curr], 16); /* Set current timestamp */ set_timestamp(curr, timestamp[curr], 16); /* Check if we are beginning a new day */ if (use_tm_start && record_hdr[!curr].ust_time && (record_hdr[curr].ust_time > record_hdr[!curr].ust_time) && (record_hdr[curr].hour < record_hdr[!curr].hour)) { cross_day = 1; } if (cross_day) { /* * This is necessary if we want to properly handle something like: * sar -s time_start -e time_end with * time_start(day D) > time_end(day D+1) */ rectime.tm_hour +=24; } /* Check time (2) */ if (use_tm_start && (datecmp(&rectime, &tm_start) < 0)) /* it's too soon... */ return 0; /* Get interval values */ get_itv_value(&record_hdr[curr], &record_hdr[!curr], cpu_nr, &itv, &g_itv); /* Check time (3) */ if (use_tm_end && (datecmp(&rectime, &tm_end) > 0)) { /* It's too late... */ *cnt = 0; return 0; } (asum.count)++; /* Nb of lines printed */ /* Test stdout */ TEST_STDOUT(STDOUT_FILENO); for (i = 0; i < NR_ACT; i++) { if ((act_id != ALL_ACTIVITIES) && (act[i]->id != act_id)) continue; if (IS_SELECTED(act[i]->options) && (act[i]->nr > 0)) { /* Display current activity statistics */ if (NEEDS_GLOBAL_ITV(act[i]->options)) (*act[i]->f_print)(act[i], !curr, curr, g_itv); else (*act[i]->f_print)(act[i], !curr, curr, itv); } } return 1; }