int client_main(struct client_ctx *cctx) { struct pollfd pfd; int n, nfds; siginit(); logfile("client"); /* * imsg_read in the first client poll loop (before the terminal has * been initialiased) may have read messages into the buffer after the * MSG_READY switched to here. Process anything outstanding now so poll * doesn't hang waiting for messages that have already arrived. */ if (client_msg_dispatch(cctx) != 0) goto out; for (;;) { if (sigterm) client_write_server(cctx, MSG_EXITING, NULL, 0); if (sigchld) { waitpid(WAIT_ANY, NULL, WNOHANG); sigchld = 0; } if (sigwinch) client_handle_winch(cctx); if (sigcont) { siginit(); client_write_server(cctx, MSG_WAKEUP, NULL, 0); sigcont = 0; } pfd.fd = cctx->ibuf.fd; pfd.events = POLLIN; if (cctx->ibuf.w.queued > 0) pfd.events |= POLLOUT; if ((nfds = poll(&pfd, 1, INFTIM)) == -1) { if (errno == EAGAIN || errno == EINTR) continue; fatal("poll failed"); } if (nfds == 0) continue; if (pfd.revents & (POLLERR|POLLHUP|POLLNVAL)) fatalx("socket error"); if (pfd.revents & POLLIN) { if ((n = imsg_read(&cctx->ibuf)) == -1 || n == 0) { cctx->exittype = CCTX_DIED; break; } if (client_msg_dispatch(cctx) != 0) break; } if (pfd.revents & POLLOUT) { if (msgbuf_write(&cctx->ibuf.w) < 0) { cctx->exittype = CCTX_DIED; break; } } } out: if (sigterm) { printf("[terminated]\n"); return (1); } switch (cctx->exittype) { case CCTX_DIED: printf("[lost server]\n"); return (0); case CCTX_SHUTDOWN: printf("[server exited]\n"); return (0); case CCTX_EXIT: if (cctx->errstr != NULL) { printf("[error: %s]\n", cctx->errstr); return (1); } printf("[exited]\n"); return (0); case CCTX_DETACH: printf("[detached]\n"); return (0); default: printf("[unknown error]\n"); return (1); } }
static int ssl_servername_cb(SSL *cnx, int *al, void *arg) { CertResult result; const char *sni_name; (void) al; (void) arg; if ((sni_name = SSL_get_servername(cnx, TLSEXT_NAMETYPE_host_name)) == NULL || *sni_name == 0 || validate_sni_name(sni_name) != 0) { return SSL_TLSEXT_ERR_NOACK; } logfile(LOG_INFO, "SNI: [%s]", sni_name); if (chrooted != 0 || loggedin != 0) { return SSL_TLSEXT_ERR_NOACK; } if (use_extcert == 0) { return SSL_TLSEXT_ERR_OK; } memset(&result, 0, sizeof result); tls_extcert_get(&result, sni_name); if (result.cert_ok != 1) { die(400, LOG_ERR, "Cert handler not ready"); } if (result.action == CERT_ACTION_DENY) { die(400, LOG_INFO, MSG_LOGOUT); } if (result.action == CERT_ACTION_DEFAULT) { return SSL_TLSEXT_ERR_OK; } if (result.cert_file == NULL) { if (result.action == CERT_ACTION_STRICT) { die(400, LOG_ERR, "Missing certificate"); } else { return SSL_TLSEXT_ERR_OK; } } if (result.key_file == NULL) { result.key_file = result.cert_file; } SSL_CTX_free(tls_ctx); tls_ctx = NULL; if (tls_create_new_context(result.cert_file, result.key_file) != 0) { if (result.action != CERT_ACTION_FALLBACK) { die(400, LOG_ERR, "Invalid certificate"); } if (tls_create_new_context(cert_file, key_file) != 0) { die(400, LOG_ERR, "SSL error"); } } if ((client_sni_name = strdup(sni_name)) == NULL) { die_mem(); } if (tls_cnx != NULL) { const long ctx_options = SSL_CTX_get_options(tls_ctx); SSL_set_SSL_CTX(tls_cnx, tls_ctx); # ifdef SSL_CTRL_CLEAR_OPTIONS SSL_clear_options(tls_cnx, SSL_get_options(tls_cnx) & ~ctx_options); # endif SSL_set_options(tls_cnx, ctx_options); } if (tls_data_cnx != NULL) { const long ctx_options = SSL_CTX_get_options(tls_ctx); SSL_set_SSL_CTX(tls_data_cnx, tls_ctx); # ifdef SSL_CTRL_CLEAR_OPTIONS SSL_clear_options(tls_data_cnx, SSL_get_options(tls_cnx) & ~ctx_options); # endif SSL_set_options(tls_data_cnx, ctx_options); } return SSL_TLSEXT_ERR_OK; }
int main(int argc, char *argv[]){ std::string line; std::string kersource=""; std::ifstream myfile ("Matmul.cl"); if (myfile.is_open()) { while ( getline (myfile,line) ) { kersource=kersource+line; kersource=kersource+"\n"; } myfile.close(); } const char* kernelSource = kersource.c_str(); unsigned int n = 1000; // Host input vectors float *h_a; float *h_b; // Host output vector float *h_c; // Device input buffers cl::Buffer d_a; cl::Buffer d_b; // Device output buffer cl::Buffer d_c; cl::LocalSpaceArg d_bwrk; // Size, in bytes, of each vector size_t bytes = n*n*sizeof (float); // Allocate memory for each vector on host h_a = new float[n*n]; h_b = new float[n*n]; h_c = new float[n*n]; // Initialize vectors on host for(int i = 0; i < n*n; i++ ) { h_a[i] = 1; h_b[i] = 2; } cl::STRING_CLASS buildlog; cl::Program program_; std::vector<cl::Device> devices; cl_int err = CL_SUCCESS; try { // Query platforms std::vector<cl::Platform> platforms; cl::Platform::get(&platforms); if (platforms.size() == 0) { std::cout << "Platform size 0\n"; return -1; } // Get list of devices on default platform and create context cl_context_properties properties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)(platforms[0])(), 0}; cl::Context context(CL_DEVICE_TYPE_CPU, properties); devices = context.getInfo<CL_CONTEXT_DEVICES>(); // Create command queue for first device cl::CommandQueue queue(context, devices[0], 0, &err); // Create device memory buffers d_a = cl::Buffer(context, CL_MEM_READ_ONLY, bytes); d_b = cl::Buffer(context, CL_MEM_READ_ONLY, bytes); d_c = cl::Buffer(context, CL_MEM_WRITE_ONLY, bytes); d_bwrk = cl::Local(n*sizeof(float)); // Bind memory buffers queue.enqueueWriteBuffer(d_a, CL_TRUE, 0, bytes, h_a); queue.enqueueWriteBuffer(d_b, CL_TRUE, 0, bytes, h_b); //Build kernel from source string cl::Program::Sources source(1, std::make_pair(kernelSource,strlen(kernelSource))); program_ = cl::Program(context, source); program_.build(devices); std::cout<<"BuildLog: \n"<<buildlog; // Create kernel object cl::Kernel kernel(program_, "multiMat", &err); // Bind kernel arguments to kernel kernel.setArg(0, d_a); kernel.setArg(1, d_b); kernel.setArg(2, d_c); kernel.setArg(3, n); kernel.setArg(4,d_bwrk); // Number of work items in each local work group cl::NDRange localSize(64); // Number of total work items - localSize must be devisor cl::NDRange globalSize((int)(ceil(n/(float)64)*64)); // Enqueue kernel cl::Event event; queue.enqueueNDRangeKernel( kernel, cl::NullRange, globalSize, localSize, NULL, &event); // Block until kernel completion event.wait(); // Read back d_c queue.enqueueReadBuffer(d_c, CL_TRUE, 0, bytes, h_c); } catch (cl::Error err) { std::cerr << "ERROR: "<<err.what()<<"("<<err.err()<<")"<<std::endl; buildlog = program_.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[0], NULL); std::ofstream logfile ("Matmullog.txt"); logfile<<buildlog; logfile.close(); } std::cout<<"Global Size side :"<< (int)(ceil(n/(float)64)*64)<<"\n"; // Sum up vector c and print result divided by n, this should equal 1 within error float sum = 0; for(int i=0; i<n*n; i++) sum += h_c[i]; std::cout<<"final result: "<<sum<<std::endl; //std::ofstream outfile ("MatmulAns.txt"); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { // outfile<<h_c[i*n+j]<<" "; } // outfile<<"\n"; } //outfile.close(); // Release host memory delete(h_a); delete(h_b); delete(h_c); return 0; }
LOG_FILE() { const std::int32_t TASK_NAME_LEN = 1024; char name[TASK_NAME_LEN] = { 0 }; #ifdef PLATFORM_IS_WINDOWS char path[TASK_NAME_LEN] = {0}; GetModuleFileName(NULL, path, TASK_NAME_LEN); char *p = strrchr(path, '\\'); if (p == nullptr) throw std::logic_error("windows can't identify the program name"); char proName[TASK_NAME_LEN]{ 0 }; char *dot = strrchr(path, '.'); if ((dot != nullptr) && (dot - p > 0)) { std::int32_t n = dot - p - 1; strncpy(proName, p + 1, n); proName[n] = 0; } CreateDirectory("log", NULL); strcat(name, "log\\"); #endif #ifdef PLATFORM_IS_LINUX std::int32_t count = 0; std::int32_t nIndex = 0; char path[TASK_NAME_LEN] = {0}; char cParam[100] = {0}; char *proName = path; pid_t pId = getpid(); sprintf(cParam,"/proc/%d/exe",pId); count = readlink(cParam, path, TASK_NAME_LEN); if (count < 0 || count >= TASK_NAME_LEN) { throw std::logic_error("Current System Not Surport Proc.\n"); } else { nIndex = count - 1; for( ; nIndex >= 0; nIndex--) { if( path[nIndex] == '/' )//筛选出进程名 { nIndex++; proName += nIndex; break; } } } if(opendir("log")==nullptr) { umask(0); if(mkdir("log",0777 )!=0) throw std::logic_error("can't create log folder\n"); } strcat(name, "log/"); #endif time(&beginTime); struct tm * timeinfo; timeinfo = localtime(&beginTime); char timeCh[TASK_NAME_LEN]={0}; strftime(timeCh,TASK_NAME_LEN,"_%Y-%m-%d_%H-%M-%S_log.txt",timeinfo); strcat(name,proName); strcat(name,timeCh); logfile(name); this->fileName = name; };
void putlog(int type, const char *chname, const char *format, ...) { char va_out[LOGLINEMAX + 1] = ""; va_list va; va_start(va, format); egg_vsnprintf(va_out, sizeof(va_out), format, va); va_end(va); if (!va_out[0]) { putlog(LOG_ERRORS, "*", "Empty putlog() detected"); return; } if (!log_repeated) { if (type == last_type && !egg_strncasecmp(chname, last_chname, sizeof(last_chname)) && !egg_strncasecmp(va_out, last_log, sizeof(last_log))) { ++log_repeats; return; } if (log_repeats) { log_repeated = 1; putlog(type, last_chname, "Last message repeated %d times.\n", log_repeats); log_repeats = 0; } strlcpy(last_log, va_out, sizeof(last_log)); last_type = type; strlcpy(last_chname, chname, sizeof(last_chname)); } else log_repeated = 0; char *p = NULL; if ((p = strchr(va_out, '\n'))) /* make sure no trailing newline */ *p = 0; int idx = 0; char out[LOGLINEMAX + 1] = ""; if (conf.bot && conf.bot->hub) { char stamp[34] = ""; struct tm *t = gmtime(&now); egg_strftime(stamp, sizeof(stamp), LOG_TS, t); /* Place the timestamp in the string to be printed */ strlcpy(out, stamp, sizeof(out)); strlcat(out, " ", sizeof(out)); strlcat(out, va_out, sizeof(out)); } else strlcpy(out, va_out, sizeof(out)); /* strcat(out, "\n"); */ #ifdef no /* FIXME: WRITE LOG HERE */ int logfile_masks = LOG_CMDS|LOG_ERRORS|LOG_WARN|LOG_BOTS|LOG_MISC; if (logfile_masks && (logfile_masks & type)) logfile(type, out); #endif /* broadcast to hubs */ if (chname[0] == '*' && conf.bot && conf.bot->nick) botnet_send_log(-1, conf.bot->nick, type, out); for (idx = 0; idx < dcc_total; idx++) { if (dcc[idx].type && (dcc[idx].type == &DCC_CHAT && dcc[idx].simul == -1) && (dcc[idx].u.chat->con_flags & type)) { if ((chname[0] == '@') || (chname[0] == '*') || (dcc[idx].u.chat->con_chan[0] == '*') || (!rfc_casecmp(chname, dcc[idx].u.chat->con_chan))) dprintf(idx, "%s\n", out); } } if ((!backgrd) && (!term_z)) { dprintf(DP_STDOUT, "%s\n", out); } else if ((type & LOG_ERRORS || type & LOG_MISC) && use_stderr) { dprintf(DP_STDERR, "%s\n", va_out); } }
/*! This calls on the grasp_manager to start the testing process. If the results are to be saved, the filename is also provided to the grasp_tester. */ void PlannerDlg::testGrasps() { QString planFilename,quadFilename; World *world = graspItGUI->getIVmgr()->getWorld(); /* if (TestButton->text() == "Pause") { TestButton->setText("Continue"); myGraspManager->get_graspTester()->pauseTests(); return; } if (TestButton->text() == "Continue") { TestButton->setText("Pause"); myGraspManager->get_graspTester()->continueTests(); return; } */ if (!masterFile.isOpen()) { if (!savefileLineEdit->text().isEmpty()) myGraspManager->get_graspTester()-> saveGraspsToFile(savefileLineEdit->text(),false); //TestButton->setText("Pause"); myGraspManager->testGrasps(); } else { // This is just a hack for a project we are working on if (stream.atEnd()) { masterFile.close(); return; } if (!savefileLineEdit->text().isEmpty()) myGraspManager->get_graspTester()-> saveGraspsToFile(savefileLineEdit->text(),true); if (world->getNumGB() > 0) world->destroyElement(world->getGB(0)); stream >> quadFilename >> planFilename; stream.readLine(); // if (quadFilename.stripWhiteSpace().isEmpty() || planFilename.stripWhiteSpace().isEmpty()) world->importBody("GraspableBody",quadFilename); world->getHand(0)->getGrasp()->setObject(world->getGB(0)); QFile logfile("grasplog.txt"); if (logfile.open(QIODevice::WriteOnly | QIODevice::Append)) { QTextStream lout(&logfile); lout << "Evaluating grasps of "<< world->getGB(0)->getName() << endl; logfile.close(); } if (myGraspManager-> readCandidateGraspsFile(planFilename)) { QTWARNING("Could not read grasps from file."); masterFile.close(); return; } myGraspManager->testGrasps(); } //TestButton->setText("Test"); }
static struct passwd *pw_ldap_getpwnam(const char *name, AuthResult * const result) { static struct passwd pwret; LDAP *ld; LDAPMessage *res; char *attrs[] = { /* OpenLDAP forgot a 'const' ... */ LDAP_HOMEDIRECTORY, LDAP_UIDNUMBER, LDAP_FTPUID, LDAP_GIDNUMBER, LDAP_FTPGID, LDAP_USERPASSWORD, LDAP_LOGINSHELL, LDAP_FTPSTATUS, # ifdef QUOTAS LDAP_QUOTAFILES, LDAP_QUOTAMBYTES, # endif # ifdef RATIOS LDAP_DOWNLOADRATIO, LDAP_UPLOADRATIO, # endif #ifdef THROTTLING LDAP_DOWNLOADBANDWIDTH, LDAP_UPLOADBANDWIDTH, #endif NULL }; const char *pw_uid_s = NULL; const char *pw_gid_s = NULL; const char *pw_passwd_ldap = NULL; const char *pw_enabled = NULL; #ifdef QUOTAS const char *quota_files = NULL; const char *quota_mbytes = NULL; #endif #ifdef RATIOS const char *ratio_ul = NULL; const char *ratio_dl = NULL; #endif #ifdef THROTTLING const char *bandwidth_ul = NULL; const char *bandwidth_dl = NULL; #endif memset(&pwret, 0, sizeof pwret); pwret.pw_name = pwret.pw_passwd = pwret.pw_gecos = pwret.pw_dir = pwret.pw_shell = NULL; pwret.pw_uid = (uid_t) 0; pwret.pw_gid = (gid_t) 0; if (pw_ldap_validate_name(name) != 0) { return NULL; } if ((ld = pw_ldap_connect(binddn, pwd)) == NULL) { return NULL; } attrs[0] = ldap_homedirectory; if ((res = pw_ldap_uid_search(ld, name, attrs)) == NULL) { goto error; } pw_ldap_getpwnam_freefields(&pwret); pwret.pw_name = (char *) name; pw_enabled = pw_ldap_getvalue(ld, res, LDAP_FTPSTATUS); if (pw_enabled != NULL && strcasecmp(pw_enabled, "enabled") != 0 && strcasecmp(pw_enabled, "TRUE") != 0) { goto error; } free((void *) pw_enabled); pw_enabled = NULL; #ifdef QUOTAS if ((quota_files = pw_ldap_getvalue(ld, res, LDAP_QUOTAFILES)) != NULL) { const unsigned long long q = strtoull(quota_files, NULL, 10); if (q > 0ULL) { result->user_quota_files = q; result->quota_files_changed = 1; } } if ((quota_mbytes = pw_ldap_getvalue(ld, res, LDAP_QUOTAMBYTES)) != NULL) { const unsigned long long q = strtoull(quota_mbytes, NULL, 10); if (q > 0ULL) { result->user_quota_size = q * (1024UL * 1024UL); result->quota_size_changed = 1; } } #endif #ifdef RATIOS if ((ratio_dl = pw_ldap_getvalue(ld, res, LDAP_DOWNLOADRATIO)) != NULL) { const unsigned int q = strtoul(ratio_dl, NULL, 10); if (q > 0U) { result->ratio_download = q; result->ratio_dl_changed = 1; } } if ((ratio_ul = pw_ldap_getvalue(ld, res, LDAP_UPLOADRATIO)) != NULL) { const unsigned int q = strtoul(ratio_ul, NULL, 10); if (q > 0U) { result->ratio_upload = q; result->ratio_ul_changed = 1; } } #endif #ifdef THROTTLING if ((bandwidth_dl = pw_ldap_getvalue(ld, res, LDAP_DOWNLOADBANDWIDTH)) != NULL) { const unsigned long q = (unsigned long) strtoul(bandwidth_dl, NULL, 10); if (q > 0UL) { result->throttling_bandwidth_dl = q * 1024UL; result->throttling_dl_changed = 1; } } if ((bandwidth_ul = pw_ldap_getvalue(ld, res, LDAP_UPLOADBANDWIDTH)) != NULL) { const unsigned long q = (unsigned long) strtoul(bandwidth_ul, NULL, 10); if (q > 0UL) { result->throttling_bandwidth_ul = q * 1024UL; result->throttling_ul_changed = 1; } } #endif if (use_ldap_bind_method == 0) { if ((pw_passwd_ldap = pw_ldap_getvalue(ld, res, LDAP_USERPASSWORD)) == NULL) { /* The LDAP userPassword is empty, this happens when binding to LDAP without sufficient privileges. */ logfile(LOG_WARNING, MSG_WARN_LDAP_USERPASS_EMPTY); goto error; } pwret.pw_passwd = strdup(pw_passwd_ldap); free((void *) pw_passwd_ldap); pw_passwd_ldap = NULL; } else { pwret.pw_passwd = strdup(""); } if (pwret.pw_passwd == NULL) { logfile(LOG_ERR, MSG_OUT_OF_MEMORY); goto error; } /* only force the uid if default_uid has been set */ if (!force_default_uid && default_uid > 0) { if ((pw_uid_s = pw_ldap_getvalue(ld, res, LDAP_FTPUID)) == NULL || *pw_uid_s == 0 || (pwret.pw_uid = (uid_t) strtoul(pw_uid_s, NULL, 10)) <= (uid_t) 0) { free((void *) pw_uid_s); pw_uid_s = NULL; if ((pw_uid_s = pw_ldap_getvalue(ld, res, LDAP_UIDNUMBER)) == NULL || *pw_uid_s == 0 || (pwret.pw_uid = (uid_t) strtoul(pw_uid_s, NULL, 10)) <= (uid_t) 0) { pwret.pw_uid = default_uid; } } } else { pwret.pw_uid = default_uid; } free((void *) pw_uid_s); pw_uid_s = NULL; /* only force the gid if default_gid has been set */ if (!force_default_gid && default_gid > 0) { if ((pw_gid_s = pw_ldap_getvalue(ld, res, LDAP_FTPGID)) == NULL || *pw_gid_s == 0 || (pwret.pw_gid = (gid_t) strtoul(pw_gid_s, NULL, 10)) <= (gid_t) 0) { free((void *) pw_gid_s); pw_gid_s = NULL; if ((pw_gid_s = pw_ldap_getvalue(ld, res, LDAP_GIDNUMBER)) == NULL || *pw_gid_s == 0 || (pwret.pw_gid = (gid_t) strtoul(pw_gid_s, NULL, 10)) <= (gid_t) 0) { pwret.pw_gid = default_gid; } } } else { pwret.pw_gid = default_gid; } free((void *) pw_gid_s); pw_gid_s = NULL; if ((pwret.pw_dir = pw_ldap_getvalue(ld, res, ldap_homedirectory)) == NULL || *pwret.pw_dir == 0) { if (ldap_default_home_directory == NULL || *ldap_default_home_directory == 0) { goto error; } if ((pwret.pw_dir = strdup(ldap_default_home_directory)) == NULL) { die_mem(); } } if ((pwret.pw_shell = pw_ldap_getvalue(ld, res, LDAP_LOGINSHELL)) == NULL) { pwret.pw_shell = strdup(DEFAULT_SHELL); } result->backend_data = ldap_get_dn(ld, res); ldap_msgfree(res); ldap_unbind(ld); return &pwret; error: if (res != NULL) { ldap_msgfree(res); } ldap_unbind(ld); pw_ldap_getpwnam_freefields(&pwret); free((void *) pw_uid_s); free((void *) pw_gid_s); free((void *) pw_passwd_ldap); free((void *) pw_enabled); #ifdef QUOTAS free((void *) quota_files); free((void *) quota_mbytes); #endif #ifdef RATIOS free((void *) ratio_ul); free((void *) ratio_dl); #endif #ifdef THROTTLING free((void *) bandwidth_ul); free((void *) bandwidth_dl); #endif return NULL; }
fs::path GetDebugLogPath() { fs::path logfile(gArgs.GetArg("-debuglogfile", DEFAULT_DEBUGLOGFILE)); return AbsPathForConfigVal(logfile); }
stat Stats::TestBloomFilter(string fname_){ std::vector<string> urlsInList_ = BruteForce(fname_); std::vector<int> present_; //indicate the relevant url is in the list or not(according to bloom filter) std::vector<int> inList_; //indicate the relevant url is actually in the list or not std::ifstream ifp(fname_.c_str()); string line; int urlcount_ = 0; if(!ifp.good()){ cout<<"Can not open input data file"<<endl; } else{ do{ getline(ifp, line); if(line.size()<=f->urlLen_ && line.size()>=f->min_urlLen_ && line.size()>0) urlcount_++; Element * e = new Element(line); if(f->QueryElement(e)) present_.push_back(1); else present_.push_back(0); bool x = false; for (int i = 0; i < urlsInList_.size(); ++i) { if(line == urlsInList_[i]){ x = true; break; } } if(x) inList_.push_back(1); else inList_.push_back(0); }while(!ifp.eof()); } ifp.close(); double ffp_; double total_present = 0; double total_inlist = 0; for (int i = 0; i < present_.size(); ++i) { if(present_[i]==1) total_present++; if(inList_[i]==1) total_inlist++; } ffp_ = 1-(total_inlist/total_present); std::ofstream logfile("testresults.log",ios::app); logfile<<"Testing: "; logfile<<"out of "<<urlcount_<<";\n\n\ttotal present(according to BloomFilter): "<<total_present<<"\n\ttotal in list: "<<total_inlist<<"\n\tffp: "<<ffp_<<endl; logfile.close(); stat a; a.present = total_present; a.inList = total_inlist; a.ffp = ffp_; a.urlcount = urlcount_; return a; }
int logfile_noformat(AppContext * const context, const int crit, const char * const msg) { return logfile(context, crit, "%s", msg); }
void LogLoader::run() { QFile logfile(m_filename); logfile.open(QIODevice::ReadOnly); //QByteArray arr = logfile.readAll(); //logfile.close(); int curr = 0; //bool escape = false; bool inpacket = false; QByteArray currPacket; //while (!escape || curr >= arr.size()) QByteArray retval; while (!logfile.atEnd()) { //logfile.read(&retval,1); emit logProgress(logfile.pos(),logfile.size()); retval = logfile.read(1); if (retval[0] == (char)0xAA) { if (inpacket) { //in the middle of a packet currPacket.clear(); } currPacket.append(retval[0]); //Start byte //qDebug() << "Start byte"; inpacket = true; } else if (retval[0] == (char)0xCC) { //currPacket currPacket.append(retval[0]); QString output; for (int i=0;i<currPacket.size();i++) { int num = (unsigned char)currPacket[i]; output.append(" ").append((num < 0xF) ? "0" : "").append(QString::number(num,16)); } qDebug() << "Full packet:"; //qDebug() << output; parseBuffer(currPacket); currPacket.clear(); //qDebug() << "loop"; msleep(25); } else if (inpacket) { if (retval[0] == (char)0xBB) { //Need to escape the next byte retval = logfile.read(1); if (retval[0] == (char)0x55) { currPacket.append((char)0xAA); } else if (retval[0] == (char)0x44) { currPacket.append((char)0xBB); } else if (retval[0] == (char)0x33) { currPacket.append((char)0xCC); } } else { currPacket.append(retval[0]); } } curr++; } emit endOfLog(); logfile.close(); return; /*for (int i=0;i<arr.size();i++) { //i++; //qDebug() << QString::number(arr[i],16); curr = i; curr+=3; curr += 1; i += curr-1; //i++; }*/ }
int fill_mac_address(void) { int s; if ((s = socket(HWINFO_DOMAIN, HWINFO_TYPE, 0)) == -1) { logfile(LOG_ERR, _("Unable to open raw device: [%s]"), strerror(errno)); return -1; } #ifdef SIOCGIFHWADDR { struct ifreq ifr; if (strlen(interface) >= sizeof ifr.ifr_name) { logfile(LOG_ERR, _("Interface name too long")); return -1; } strncpy(ifr.ifr_name, interface, sizeof ifr.ifr_name); if (ioctl(s, SIOCGIFHWADDR, &ifr) != 0) { logfile(LOG_ERR, _("Unable to get hardware info about an interface: %s"), strerror(errno)); (void) close(s); return -1; } switch (ifr.ifr_hwaddr.sa_family) { case ARPHRD_ETHER: case ARPHRD_IEEE802: break; default: logfile(LOG_ERR, _("Unknown hardware type [%u]"), (unsigned int) ifr.ifr_hwaddr.sa_family); } memcpy(hwaddr, &ifr.ifr_hwaddr.sa_data, sizeof hwaddr); } #elif defined(HAVE_GETIFADDRS) { struct ifaddrs *ifas; struct ifaddrs *ifa; struct sockaddr_dl *sadl; struct ether_addr *ea; if (getifaddrs(&ifas) != 0) { logfile(LOG_ERR, _("Unable to get interface address: %s"), strerror(errno)); return -1; } ifa = ifas; while (ifa != NULL) { if (strcmp(ifa->ifa_name, interface) == 0 && ifa->ifa_addr->sa_family == AF_LINK) { sadl = (struct sockaddr_dl *) ifa->ifa_addr; if (sadl == NULL || sadl->sdl_type != IFT_ETHER || sadl->sdl_alen <= 0) { logfile(LOG_ERR, _("Invalid media / hardware address for [%s]"), interface); return -1; } ea = (struct ether_addr *) LLADDR(sadl); memcpy(hwaddr, ea, sizeof hwaddr); return 0; } ifa = ifa->ifa_next; } return -1; } #elif defined(SIOCGLIFNUM) { struct lifconf lifc; struct lifnum lifn; struct lifreq *lifr; caddr_t *lifrspace; struct arpreq arpreq; lifn.lifn_flags = 0; lifn.lifn_family = AF_INET; if (ioctl(s, SIOCGLIFNUM, &lifn) < 0) { logfile(LOG_ERR, _("ioctl SIOCGLIFNUM error")); return -1; } if (lifn.lifn_count <= 0) { logfile(LOG_ERR, _("No interface found")); return -1; } lifc.lifc_family = lifn.lifn_family; lifc.lifc_len = lifn.lifn_count * sizeof *lifr; lifrspace = ALLOCA(lifc.lifc_len); lifc.lifc_buf = (caddr_t) lifrspace; if (ioctl(s, SIOCGLIFCONF, &lifc) < 0) { logfile(LOG_ERR, _("ioctl SIOCGLIFCONF error")); ALLOCA_FREE(lifrspace); return -1; } lifr = lifc.lifc_req; for(;;) { if (lifn.lifn_count <= 0) { logfile(LOG_ERR, _("Interface [%s] not found"), interface); ALLOCA_FREE(lifrspace); return -1; } lifn.lifn_count--; if (strcmp(lifr->lifr_name, interface) == 0) { break; } lifr++; } memcpy(&arpreq.arp_pa, &lifr->lifr_addr, sizeof arpreq.arp_pa); ALLOCA_FREE(lifrspace); if (ioctl(s, SIOCGARP, &arpreq) != 0) { logfile(LOG_ERR, _("Unable to get hardware info about [%s]"), interface); return -1; } memcpy(hwaddr, &arpreq.arp_ha.sa_data, sizeof hwaddr); } #endif (void) close(s); return 0; }
static int init (void) { static int initialized = 0; int do_warn = 0, i; char configFiles[2][MAX_PATH], log[MAX_PATH], *bridge, *hypervisor, *s, *tmp; struct stat mystat; struct statfs fs; struct handlers ** h; long long fs_free_blocks = 0; long long fs_block_size = 0; long long instances_bytes = 0; pthread_t tcb; if (initialized>0) /* 0 => hasn't run, -1 => failed, 1 => ok */ return 0; else if (initialized<0) return 1; bzero (&nc_state, sizeof(struct nc_state_t)); // ensure that MAXes are zeroed out /* from now on we have unrecoverable failure, so no point in * retrying to re-init */ initialized = -1; /* read in configuration - this should be first! */ tmp = getenv(EUCALYPTUS_ENV_VAR_NAME); if (!tmp) { nc_state.home[0] = '\0'; do_warn = 1; } else strncpy(nc_state.home, tmp, MAX_PATH); /* set the minimum log for now */ snprintf(log, MAX_PATH, "%s/var/log/eucalyptus/nc.log", nc_state.home); logfile(log, EUCADEBUG); if (do_warn) logprintfl (EUCAWARN, "env variable %s not set, using /\n", EUCALYPTUS_ENV_VAR_NAME); /* search for the config file */ snprintf(configFiles[1], MAX_PATH, EUCALYPTUS_CONF_LOCATION, nc_state.home); if (stat(configFiles[1], &mystat)) { logprintfl (EUCAFATAL, "could not open configuration file %s\n", configFiles[1]); return 1; } snprintf(configFiles[0], MAX_PATH, EUCALYPTUS_CONF_OVERRIDE_LOCATION, nc_state.home); logprintfl (EUCAINFO, "NC is looking for configuration in %s,%s\n", configFiles[1], configFiles[0]); /* reset the log to the right value */ tmp = getConfString(configFiles, 2, "LOGLEVEL"); i = EUCADEBUG; if (tmp) { if (!strcmp(tmp,"INFO")) {i=EUCAINFO;} else if (!strcmp(tmp,"WARN")) {i=EUCAWARN;} else if (!strcmp(tmp,"ERROR")) {i=EUCAERROR;} else if (!strcmp(tmp,"FATAL")) {i=EUCAFATAL;} free(tmp); } logfile(log, i); #define GET_VAR_INT(var,name) \ s = getConfString(configFiles, 2, name); \ if (s){ \ var = atoi(s);\ free (s);\ } GET_VAR_INT(nc_state.config_max_mem, CONFIG_MAX_MEM); GET_VAR_INT(nc_state.config_max_disk, CONFIG_MAX_DISK); GET_VAR_INT(nc_state.config_max_cores, CONFIG_MAX_CORES); GET_VAR_INT(nc_state.save_instance_files, CONFIG_SAVE_INSTANCES); nc_state.config_network_port = NC_NET_PORT_DEFAULT; strcpy(nc_state.admin_user_id, EUCALYPTUS_ADMIN); hyp_sem = sem_alloc (1, "mutex"); inst_sem = sem_alloc (1, "mutex"); addkey_sem = sem_alloc (1, "mutex"); if (!hyp_sem || !inst_sem) { logprintfl (EUCAFATAL, "failed to create and initialize a semaphore\n"); return ERROR_FATAL; } /* set default in the paths. the driver will override */ nc_state.config_network_path[0] = '\0'; nc_state.gen_libvirt_cmd_path[0] = '\0'; nc_state.xm_cmd_path[0] = '\0'; nc_state.virsh_cmd_path[0] = '\0'; nc_state.get_info_cmd_path[0] = '\0'; snprintf (nc_state.rootwrap_cmd_path, MAX_PATH, EUCALYPTUS_ROOTWRAP, nc_state.home); /* prompt the SC to read the configuration too */ if (scInitConfig()) { logprintfl (EUCAFATAL, "ERROR: scInitConfig() failed\n"); return ERROR_FATAL; } /* determine the hypervisor to use */ //if (get_conf_var(config, CONFIG_HYPERVISOR, &hypervisor)<1) { hypervisor = getConfString(configFiles, 2, CONFIG_HYPERVISOR); if (!hypervisor) { logprintfl (EUCAFATAL, "value %s is not set in the config file\n", CONFIG_HYPERVISOR); return ERROR_FATAL; } /* let's look for the right hypervisor driver */ for (h = available_handlers; *h; h++ ) { if (!strncmp ((*h)->name, "default", CHAR_BUFFER_SIZE)) nc_state.D = *h; if (!strncmp ((*h)->name, hypervisor, CHAR_BUFFER_SIZE)) nc_state.H = *h; } if (nc_state.H == NULL) { logprintfl (EUCAFATAL, "requested hypervisor type (%s) is not available\n", hypervisor); free (hypervisor); return ERROR_FATAL; } /* only load virtio config for kvm */ if (!strncmp("kvm", hypervisor, CHAR_BUFFER_SIZE) || !strncmp("KVM", hypervisor, CHAR_BUFFER_SIZE)) { GET_VAR_INT(nc_state.config_use_virtio_net, CONFIG_USE_VIRTIO_NET); GET_VAR_INT(nc_state.config_use_virtio_disk, CONFIG_USE_VIRTIO_DISK); GET_VAR_INT(nc_state.config_use_virtio_root, CONFIG_USE_VIRTIO_ROOT); } free (hypervisor); /* NOTE: this is the only call which needs to be called on both * the default and the specific handler! All the others will be * either or */ i = nc_state.D->doInitialize(&nc_state); if (nc_state.H->doInitialize) i += nc_state.H->doInitialize(&nc_state); if (i) { logprintfl(EUCAFATAL, "ERROR: failed to initialized hypervisor driver!\n"); return ERROR_FATAL; } /* adopt running instances */ adopt_instances(); /* setup the network */ nc_state.vnetconfig = malloc(sizeof(vnetConfig)); if (!nc_state.vnetconfig) { logprintfl (EUCAFATAL, "Cannot allocate vnetconfig!\n"); return 1; } snprintf (nc_state.config_network_path, MAX_PATH, NC_NET_PATH_DEFAULT, nc_state.home); hypervisor = getConfString(configFiles, 2, "VNET_PUBINTERFACE"); if (!hypervisor) hypervisor = getConfString(configFiles, 2, "VNET_INTERFACE"); bridge = getConfString(configFiles, 2, "VNET_BRIDGE"); tmp = getConfString(configFiles, 2, "VNET_MODE"); vnetInit(nc_state.vnetconfig, tmp, nc_state.home, nc_state.config_network_path, NC, hypervisor, hypervisor, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, bridge, NULL, NULL); if (hypervisor) free(hypervisor); if (bridge) free(bridge); if (tmp) free(tmp); /* cleanup from previous runs and verify integrity of * instances directory */ sem_p (inst_sem); instances_bytes = scFSCK (&global_instances); sem_v (inst_sem); if (instances_bytes < 0) { logprintfl (EUCAFATAL, "instances store failed integrity check (error=%lld)\n", instances_bytes); return ERROR_FATAL; } /* get disk max */ strncpy(log, scGetInstancePath(), MAX_PATH); if (statfs(log, &fs) == -1) { logprintfl(EUCAWARN, "Failed to stat %s\n", log); } else { nc_state.disk_max = (long long)fs.f_bsize * (long long)fs.f_bavail + instances_bytes; /* max for Euca, not total */ nc_state.disk_max /= BYTES_PER_DISK_UNIT; if (nc_state.config_max_disk && nc_state.config_max_disk < nc_state.disk_max) nc_state.disk_max = nc_state.config_max_disk; logprintfl (EUCAINFO, "Maximum disk available: %lld (under %s)\n", nc_state.disk_max, log); } /* start the monitoring thread */ if (pthread_create(&tcb, NULL, monitoring_thread, &nc_state)) { logprintfl (EUCAFATAL, "failed to spawn a monitoring thread\n"); return ERROR_FATAL; } if (pthread_detach(tcb)) { logprintfl(EUCAFATAL, "failed to detach the monitoring thread\n"); return ERROR_FATAL; } initialized = 1; return OK; }
/////////////////////////////////////// PUBLIC FUNCTIONS //////////////////////////////// // // Function to put all of input fields received via DBus:RequestInput into a // QMap<QString,QString> where key is the input field received and value is // generally blank but can be used for informational text. // // If we asked to log the input request create the log file in /tmp/cmst/input_request.log void ConnmanAgent::createInputMap(const QMap<QString,QVariant>& r_map) { // Initialize our data map input_map.clear(); // QFile object for logging QTextStream log; QFile logfile("/tmp/cmst/input_request.log"); if (b_loginputrequest) { QDir d; d.mkpath("/tmp/cmst"); if (logfile.exists()) logfile.remove(); if (!logfile.open(QIODevice::WriteOnly | QIODevice::Text)) b_loginputrequest = false; else log.setDevice(&logfile); } // Run through the r_map getting the keys and the few values we are interested in. QMap<QString, QVariant>::const_iterator i = r_map.constBegin(); while (i != r_map.constEnd()) { // Lets see what the values contain, but first make sure we can get to them. if (b_loginputrequest) log << "\nMap Key: " << i.key() << "\n"; if (! i.value().canConvert<QDBusArgument>() ) return; const QDBusArgument qdba = i.value().value<QDBusArgument>(); if ( ! qdba.currentType() == QDBusArgument::MapType ) { if (b_loginputrequest) log << "Error - QDBusArgument as the value is not a MapType\n"; return; } // The r_map.value() is a QDBusArgument::MapType so extract this map into a new QMap called m. qdba.beginMap(); QMap<QString,QString> m; m.clear(); if (b_loginputrequest) log << "Extracting the DBusArgument Map...\n"; while ( ! qdba.atEnd() ) { QString k; QVariant v; qdba.beginMapEntry(); qdba >> k >> v; qdba.endMapEntry(); m.insert(k, v.toString()); if (b_loginputrequest) log << "{ " << k << " , " << v.toString() << "}\n"; } // while qdba.endMap(); // Browse through QMap m and get things we need to look at // Types we don' really care about. We ignore "optional" and "alternate" requirements // and only extract the "mandatory" and "informational" requirements with values if (m.contains("Requirement") ) { QString val = QString(); if ( m.value("Requirement").contains("mandatory", Qt::CaseInsensitive) || m.value("Requirement").contains("informational", Qt::CaseInsensitive) ) { if (m.contains("Value") ) val = m.value("Value"); } // if mandatory or informational // create our input_map entry input_map[i.key()] = val; } // if requirement ++i; } // while logfile.close(); return; }
void singlePlanner::logTrajectory() { char logNameWorkspace[50]; char logNameResult[50]; sprintf(logNameWorkspace,"%s_workspacePlanner.txt",controlPoint.c_str()); sprintf(logNameResult,"%s_resultPlanner.txt",controlPoint.c_str()); ofstream logfile(logNameWorkspace); ofstream logfile1(logNameResult); // ofstream logfile("workspacePlanner.txt"); // ofstream logfile1("resultPlanner.txt"); if (logfile.is_open()) { logfile<< "Workspace\t"; logfile<< rrts.system->regionOperating.center[0] <<"\t"; logfile<< rrts.system->regionOperating.center[1] <<"\t"; logfile<< rrts.system->regionOperating.center[2] <<"\t"; //logfile<< "Space_size\t"; logfile<< rrts.system->regionOperating.size[0] <<"\t"; logfile<< rrts.system->regionOperating.size[1] <<"\t"; logfile<< rrts.system->regionOperating.size[2] <<"\n"; logfile<< "Target\t"; logfile<< rrts.system->regionGoal.center[0]<<"\t"; logfile<< rrts.system->regionGoal.center[1]<<"\t"; logfile<< rrts.system->regionGoal.center[2]<<"\t"; //logfile<< "Target_size\t"; logfile<< rrts.system->regionGoal.size[0]<<"\t"; logfile<< rrts.system->regionGoal.size[1]<<"\t"; logfile<< rrts.system->regionGoal.size[2]<<"\n"; logfile<< "Start\t"; logfile<< startPos[0]<<"\t"; logfile<< startPos[1]<<"\t"; logfile<< startPos[2]<<"\t"; logfile<< "0" <<"\t"; logfile<< "0" <<"\t"; logfile<< "0" <<"\n"; //logfile<< "==============================="<<"\n"; for (int j=0; j<obsSet.size(); j++) { logfile<< "Obs"<<j<<"\t"; for (int i=0; i<2*nDim; i++) logfile<< obsSet[j][i] <<"\t"; logfile<<"\n"; } } else cerr << "File not open!"<< endl; if (logfile1.is_open()) { logfile1<<"Solving_time:\t"<<solveTime<<"\n"; for (int j=0; j<bestTraj.size(); j++) { logfile1<< "Way-point"<<j<<"\t"; for (int i=0; i<nDim; i++) logfile1<< bestTraj[j][i] <<"\t"; logfile1<<"\n"; } } logfile.close(); logfile.close(); }
int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName()); arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is a utility for converting between various input and output databases formats."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display command line parameters"); arguments.getApplicationUsage()->addCommandLineOption("--help-env","Display environmental variables available"); //arguments.getApplicationUsage()->addCommandLineOption("--formats","List supported file formats"); //arguments.getApplicationUsage()->addCommandLineOption("--plugins","List database olugins"); // if user request help write it out to cout. if (arguments.read("-h") || arguments.read("--help")) { osg::setNotifyLevel(osg::NOTICE); usage( arguments.getApplicationName().c_str(), 0 ); //arguments.getApplicationUsage()->write(std::cout); return 1; } if (arguments.read("--help-env")) { arguments.getApplicationUsage()->write(std::cout, osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE); return 1; } if (arguments.read("--plugins")) { osgDB::FileNameList plugins = osgDB::listAllAvailablePlugins(); for(osgDB::FileNameList::iterator itr = plugins.begin(); itr != plugins.end(); ++itr) { std::cout<<"Plugin "<<*itr<<std::endl; } return 0; } std::string plugin; if (arguments.read("--plugin", plugin)) { osgDB::outputPluginDetails(std::cout, plugin); return 0; } std::string ext; if (arguments.read("--format", ext)) { plugin = osgDB::Registry::instance()->createLibraryNameForExtension(ext); osgDB::outputPluginDetails(std::cout, plugin); return 0; } if (arguments.read("--formats")) { osgDB::FileNameList plugins = osgDB::listAllAvailablePlugins(); for(osgDB::FileNameList::iterator itr = plugins.begin(); itr != plugins.end(); ++itr) { osgDB::outputPluginDetails(std::cout,*itr); } return 0; } if (arguments.argc()<=1) { arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION); return 1; } FileNameList fileNames; OrientationConverter oc; bool do_convert = false; if (arguments.read("--use-world-frame")) { oc.useWorldFrame(true); } std::string str; while (arguments.read("-O",str)) { osgDB::ReaderWriter::Options* options = new osgDB::ReaderWriter::Options; options->setOptionString(str); osgDB::Registry::instance()->setOptions(options); } while (arguments.read("-e",ext)) { std::string libName = osgDB::Registry::instance()->createLibraryNameForExtension(ext); osgDB::Registry::instance()->loadLibrary(libName); } std::string libName; while (arguments.read("-l",libName)) { osgDB::Registry::instance()->loadLibrary(libName); } while (arguments.read("-o",str)) { osg::Vec3 from, to; if( sscanf( str.c_str(), "%f,%f,%f-%f,%f,%f", &from[0], &from[1], &from[2], &to[0], &to[1], &to[2] ) != 6 ) { float degrees; osg::Vec3 axis; // Try deg-axis format if( sscanf( str.c_str(), "%f-%f,%f,%f", °rees, &axis[0], &axis[1], &axis[2] ) != 4 ) { usage( argv[0], "Orientation argument format incorrect." ); return 1; } else { oc.setRotation( degrees, axis ); do_convert = true; } } else { oc.setRotation( from, to ); do_convert = true; } } while (arguments.read("-s",str)) { osg::Vec3 scale(0,0,0); if( sscanf( str.c_str(), "%f,%f,%f", &scale[0], &scale[1], &scale[2] ) != 3 ) { usage( argv[0], "Scale argument format incorrect." ); return 1; } oc.setScale( scale ); do_convert = true; } float simplifyPercent = 1.0; bool do_simplify = false; while ( arguments.read( "--simplify",str ) ) { float nsimp = 1.0; if( sscanf( str.c_str(), "%f", &nsimp ) != 1 ) { usage( argv[0], "Scale argument format incorrect." ); return 1; } std::cout << str << " " << nsimp << std::endl; simplifyPercent = nsimp; osg::notify( osg::INFO ) << "Simplifying with percentage: " << simplifyPercent << std::endl; do_simplify = true; } while (arguments.read("-t",str)) { osg::Vec3 trans(0,0,0); if( sscanf( str.c_str(), "%f,%f,%f", &trans[0], &trans[1], &trans[2] ) != 3 ) { usage( argv[0], "Translation argument format incorrect." ); return 1; } oc.setTranslation( trans ); do_convert = true; } FixTransparencyVisitor::FixTransparencyMode fixTransparencyMode = FixTransparencyVisitor::NO_TRANSPARANCY_FIXING; std::string fixString; while(arguments.read("--fix-transparency")) fixTransparencyMode = FixTransparencyVisitor::MAKE_OPAQUE_TEXTURE_STATESET_OPAQUE; while(arguments.read("--fix-transparency-mode",fixString)) { if (fixString=="MAKE_OPAQUE_TEXTURE_STATESET_OPAQUE") fixTransparencyMode = FixTransparencyVisitor::MAKE_OPAQUE_TEXTURE_STATESET_OPAQUE; if (fixString=="MAKE_ALL_STATESET_OPAQUE") fixTransparencyMode = FixTransparencyVisitor::MAKE_ALL_STATESET_OPAQUE; }; bool pruneStateSet = false; while(arguments.read("--prune-StateSet")) pruneStateSet = true; osg::Texture::InternalFormatMode internalFormatMode = osg::Texture::USE_IMAGE_DATA_FORMAT; while(arguments.read("--compressed") || arguments.read("--compressed-arb")) { internalFormatMode = osg::Texture::USE_ARB_COMPRESSION; } while(arguments.read("--compressed-dxt1")) { internalFormatMode = osg::Texture::USE_S3TC_DXT1_COMPRESSION; } while(arguments.read("--compressed-dxt3")) { internalFormatMode = osg::Texture::USE_S3TC_DXT3_COMPRESSION; } while(arguments.read("--compressed-dxt5")) { internalFormatMode = osg::Texture::USE_S3TC_DXT5_COMPRESSION; } bool smooth = false; while(arguments.read("--smooth")) { smooth = true; } bool addMissingColours = false; while(arguments.read("--addMissingColours") || arguments.read("--addMissingColors")) { addMissingColours = true; } bool do_overallNormal = false; while(arguments.read("--overallNormal") || arguments.read("--overallNormal")) { do_overallNormal = true; } bool enableObjectCache = false; while(arguments.read("--enable-object-cache")) { enableObjectCache = true; } // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occurred when parsing the program arguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } for(int pos=1;pos<arguments.argc();++pos) { if (!arguments.isOption(pos)) { fileNames.push_back(arguments[pos]); } } if (enableObjectCache) { if (osgDB::Registry::instance()->getOptions()==0) osgDB::Registry::instance()->setOptions(new osgDB::Options()); osgDB::Registry::instance()->getOptions()->setObjectCacheHint(osgDB::Options::CACHE_ALL); } std::string fileNameOut("converted.osg"); if (fileNames.size()>1) { fileNameOut = fileNames.back(); fileNames.pop_back(); } osg::Timer_t startTick = osg::Timer::instance()->tick(); osg::ref_ptr<osg::Node> root = osgDB::readNodeFiles(fileNames); if (root.valid()) { osg::Timer_t endTick = osg::Timer::instance()->tick(); osg::notify(osg::INFO)<<"Time to load files "<<osg::Timer::instance()->delta_m(startTick, endTick)<<" ms"<<std::endl; } if (pruneStateSet) { PruneStateSetVisitor pssv; root->accept(pssv); } if (fixTransparencyMode != FixTransparencyVisitor::NO_TRANSPARANCY_FIXING) { FixTransparencyVisitor atv(fixTransparencyMode); root->accept(atv); } if ( root.valid() ) { if (smooth) { osgUtil::SmoothingVisitor sv; root->accept(sv); } if (addMissingColours) { AddMissingColoursToGeometryVisitor av; root->accept(av); } auto to_lower = std::bind(&boost::to_lower_copy<std::string>,std::placeholders::_1,std::locale()); // all names to lower Utils::CommonVisitor<osg::Node> names_lower( [=](osg::Node& n)->void { n.setName(to_lower(n.getName())); }); root->accept(names_lower); // optimize the scene graph, remove rendundent nodes and state etc. osgUtil::Optimizer optimizer; FindNodeVisitor::nodeNamesList list_name; for(int i=0; i<sizeof(do_not_optimize::names)/sizeof(do_not_optimize::names[0]);++i) { list_name.push_back(do_not_optimize::names[i]); } FindNodeVisitor findNodes(list_name,FindNodeVisitor::not_exact); root->accept(findNodes); const FindNodeVisitor::nodeListType& wln_list = findNodes.getNodeList(); for(auto it = wln_list.begin(); it != wln_list.end(); ++it ) { optimizer.setPermissibleOptimizationsForObject(*it,0); } optimizer.optimize(root.get(), osgUtil::Optimizer::FLATTEN_STATIC_TRANSFORMS | osgUtil::Optimizer::REMOVE_REDUNDANT_NODES | osgUtil::Optimizer::SHARE_DUPLICATE_STATE | osgUtil::Optimizer::MERGE_GEOMETRY | osgUtil::Optimizer::MERGE_GEODES | osgUtil::Optimizer::STATIC_OBJECT_DETECTION ); boost::filesystem::path pathFileOut(fileNameOut); std::string base_file_name = pathFileOut.parent_path().string() + "/" + pathFileOut.stem().string(); cg::point_3 offset; bool res = generateBulletFile(base_file_name + ".bullet", root, offset); if (res) { osg::notify(osg::NOTICE)<<"Data written to '"<< base_file_name + ".bullet"<<"'."<< std::endl; } else { osg::notify(osg::NOTICE)<< "Error Occurred While Writing to "<< base_file_name + ".bullet"<< std::endl; } osg::Group* newroot = dynamic_cast<osg::Group*>(findFirstNode(root,"Root")); if(newroot==nullptr) { newroot = new osg::Group; newroot->setName("Root"); newroot->addChild( root ); root = newroot; } std::ofstream filelogic( base_file_name + ".stbin", std::ios_base::binary ); std::ofstream logfile ( base_file_name + std::string("_structure") + ".txt" ); heilVisitor hv(filelogic, logfile, offset); hv.apply(*root.get()); if( do_convert ) root = oc.convert( root.get() ); FIXME(Without textures useless) #if 0 const std::string name = pathFileOut.stem().string(); osgDB::FilePathList fpl_; fpl_.push_back(pathFileOut.parent_path().string() + "/"); std::string mat_file_name = osgDB::findFileInPath(name+".dae.mat.xml", /*fpl.*/fpl_,osgDB::CASE_INSENSITIVE); MaterialVisitor::namesList nl; nl.push_back("building"); nl.push_back("default"); nl.push_back("tree"); nl.push_back("ground"); nl.push_back("concrete"); nl.push_back("mountain"); nl.push_back("sea"); nl.push_back("railing"); nl.push_back("panorama"); nl.push_back("plane"); //nl.push_back("rotor"); /// �ללללללללללללל נאסךמלוםעאנטע� ט הטםאלטקוסךטי ףבתועס� MaterialVisitor mv ( nl, std::bind(&creators::createMaterial,sp::_1,sp::_2,name,sp::_3,sp::_4),creators::computeAttributes,mat::reader::read(mat_file_name)); root->accept(mv); #endif if (internalFormatMode != osg::Texture::USE_IMAGE_DATA_FORMAT) { std::string ext = osgDB::getFileExtension(fileNameOut); CompressTexturesVisitor ctv(internalFormatMode); root->accept(ctv); ctv.compress(); osgDB::ReaderWriter::Options *options = osgDB::Registry::instance()->getOptions(); if (ext!="ive" || (options && options->getOptionString().find("noTexturesInIVEFile")!=std::string::npos)) { ctv.write(osgDB::getFilePath(fileNameOut)); } } // scrub normals if ( do_overallNormal ) { DefaultNormalsGeometryVisitor dngv; root->accept( dngv ); } // apply any user-specified simplification if ( do_simplify ) { osgUtil::Simplifier simple; simple.setSmoothing( smooth ); osg::notify( osg::ALWAYS ) << " smoothing: " << smooth << std::endl; simple.setSampleRatio( simplifyPercent ); root->accept( simple ); } osgDB::ReaderWriter::WriteResult result = osgDB::Registry::instance()->writeNode(*root,fileNameOut,osgDB::Registry::instance()->getOptions()); if (result.success()) { osg::notify(osg::NOTICE)<<"Data written to '"<<fileNameOut<<"'."<< std::endl; } else if (result.message().empty()) { osg::notify(osg::NOTICE)<<"Warning: file write to '"<<fileNameOut<<"' not supported."<< std::endl; } else { osg::notify(osg::NOTICE)<<result.message()<< std::endl; } } else {
int main(int argc, char *argv[]) { int res = 0; { #ifdef DEBUG lString8 loglevel("TRACE"); lString8 logfile("stdout"); #else lString8 loglevel("ERROR"); lString8 logfile("stderr"); #endif for ( int i=1; i<argc; i++ ) { if ( !strcmp("-h", argv[i]) || !strcmp("-?", argv[i]) || !strcmp("/?", argv[i]) || !strcmp("--help", argv[i]) ) { printHelp(); return 0; } if ( !strcmp("-v", argv[i]) || !strcmp("/v", argv[i]) || !strcmp("--version", argv[i]) ) { printVersion(); return 0; } if ( !strcmp("--stats", argv[i]) && i<argc-4 ) { if ( i!=argc-5 ) { printf("To calculate character encoding statistics, use cr3 <infile.txt> <outfile.cpp> <codepagename> <langname>\n"); return 1; } lString8 list; FILE * out = fopen(argv[i+2], "wb"); if ( !out ) { printf("Cannot create file %s", argv[i+2]); return 1; } MakeStatsForFile( argv[i+1], argv[i+3], argv[i+4], 0, out, list ); fclose(out); return 0; } lString8 s(argv[i]); if ( s.startsWith(lString8("--loglevel=")) ) { loglevel = s.substr(11, s.length()-11); } else if ( s.startsWith(lString8("--logfile=")) ) { logfile = s.substr(10, s.length()-10); } } // set logger if ( logfile=="stdout" ) CRLog::setStdoutLogger(); else if ( logfile=="stderr" ) CRLog::setStderrLogger(); else if ( !logfile.empty() ) CRLog::setFileLogger(logfile.c_str()); if ( loglevel=="TRACE" ) CRLog::setLogLevel(CRLog::LL_TRACE); else if ( loglevel=="DEBUG" ) CRLog::setLogLevel(CRLog::LL_DEBUG); else if ( loglevel=="INFO" ) CRLog::setLogLevel(CRLog::LL_INFO); else if ( loglevel=="WARN" ) CRLog::setLogLevel(CRLog::LL_WARN); else if ( loglevel=="ERROR" ) CRLog::setLogLevel(CRLog::LL_ERROR); else CRLog::setLogLevel(CRLog::LL_FATAL); lString16 exename = LocalToUnicode( lString8(argv[0]) ); lString16 exedir = LVExtractPath(exename); lString16 datadir = lString16(CR3_DATA_DIR); LVAppendPathDelimiter(exedir); LVAppendPathDelimiter(datadir); lString16 exefontpath = exedir + L"fonts"; CRLog::info("main()"); lString16Collection fontDirs; //fontDirs.add( lString16(L"/usr/local/share/crengine/fonts") ); //fontDirs.add( lString16(L"/usr/local/share/fonts/truetype/freefont") ); //fontDirs.add( lString16(L"/mnt/fonts") ); fontDirs.add( lString16(L"/usr/share/fonts/truetype") ); fontDirs.add( lString16(L"/opt/onyx/arm/lib/fonts") ); fontDirs.add( lString16(L"/app/fonts") ); #if 0 fontDirs.add( exefontpath ); fontDirs.add( lString16(L"/usr/share/fonts/truetype") ); fontDirs.add( lString16(L"/usr/share/fonts/truetype/liberation") ); fontDirs.add( lString16(L"/usr/share/fonts/truetype/freefont") ); #endif // TODO: use fontconfig instead //fontDirs.add( lString16(L"/root/fonts/truetype") ); if ( !InitCREngine( argv[0], fontDirs ) ) { printf("Cannot init CREngine - exiting\n"); return 2; } if ( argc>=2 && !strcmp(argv[1], "unittest") ) { #ifdef _DEBUG runTinyDomUnitTests(); #endif CRLog::info("UnitTests finished: exiting"); return 0; } //if ( argc!=2 ) { // printf("Usage: cr3 <filename_to_open>\n"); // return 3; //} { QApplication a(argc, argv); Q_INIT_RESOURCE(onyx_ui_images); Q_INIT_RESOURCE(tts_images); #ifdef _WIN32 QString exeDir = QDir::toNativeSeparators(qApp->applicationDirPath() + "/"); //QDir::separator(); QString translations = exeDir + "i18n"; #else QString exeDir = cr2qt(datadir); QString translations = exeDir + "i18n/"; #endif QTranslator qtTranslator; if (qtTranslator.load("qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath))) QApplication::installTranslator(&qtTranslator); QTranslator myappTranslator; QString trname = "cr3_" + QLocale::system().name(); CRLog::info("Using translation file %s from dir %s", UnicodeToUtf8(qt2cr(trname)).c_str(), UnicodeToUtf8(qt2cr(translations)).c_str() ); if ( myappTranslator.load(trname, translations) ) QApplication::installTranslator(&myappTranslator); else CRLog::error("Canot load translation file %s from dir %s", UnicodeToUtf8(qt2cr(trname)).c_str(), UnicodeToUtf8(qt2cr(translations)).c_str() ); // Make sure you load translator before main widget created. ui::loadTranslator (QLocale::system().name()); OnyxMainWindow w; //w.showMaximized(); w.showFullScreen(); sys::SysStatus::instance().setSystemBusy(false); w.updateScreenManually(); res = a.exec(); } } ShutdownCREngine(); return res; }
int tls_init_library(void) { unsigned int rnd; tls_cnx_handshook = 0; tls_data_cnx_handshook = 0; SSL_library_init(); SSL_load_error_strings(); OpenSSL_add_all_algorithms(); while (RAND_status() == 0) { rnd = zrand(); RAND_seed(&rnd, (int) sizeof rnd); } if ((tls_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) { tls_error(__LINE__, 0); } # ifdef SSL_OP_CIPHER_SERVER_PREFERENCE SSL_CTX_set_options(tls_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE); # endif # ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION SSL_CTX_set_options(tls_ctx, SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION); # endif SSL_CTX_set_options(tls_ctx, SSL_OP_NO_SSLv2); SSL_CTX_set_options(tls_ctx, SSL_OP_NO_SSLv3); # ifdef SSL_OP_NO_TLSv1 SSL_CTX_clear_options(tls_ctx, SSL_OP_NO_TLSv1); # endif # ifdef SSL_OP_NO_TLSv1_1 SSL_CTX_clear_options(tls_ctx, SSL_OP_NO_TLSv1_1); # endif # ifdef SSL_OP_NO_TLSv1_2 SSL_CTX_clear_options(tls_ctx, SSL_OP_NO_TLSv1_2); # endif if (tlsciphersuite != NULL) { if (SSL_CTX_set_cipher_list(tls_ctx, tlsciphersuite) != 1) { logfile(LOG_ERR, MSG_TLS_CIPHER_FAILED, tlsciphersuite); _EXIT(EXIT_FAILURE); } } if (SSL_CTX_use_certificate_chain_file(tls_ctx, cert_file) != 1) { die(421, LOG_ERR, MSG_FILE_DOESNT_EXIST ": [%s]", cert_file); } if (SSL_CTX_use_PrivateKey_file(tls_ctx, cert_file, SSL_FILETYPE_PEM) != 1) { tls_error(__LINE__, 0); } if (SSL_CTX_check_private_key(tls_ctx) != 1) { tls_error(__LINE__, 0); } tls_init_cache(); # ifdef SSL_CTRL_SET_ECDH_AUTO SSL_CTX_ctrl(tls_ctx, SSL_CTRL_SET_ECDH_AUTO, 1, NULL); # else tls_init_ecdh_curve(); # endif # ifdef SSL_CTRL_SET_DH_AUTO if (tls_init_dhparams() != 0) { SSL_CTX_ctrl(tls_ctx, SSL_CTRL_SET_DH_AUTO, 1, NULL); } # else if (tls_init_dhparams() != 0) { tls_init_dhparams_default(); } # endif # ifdef DISABLE_SSL_RENEGOTIATION SSL_CTX_set_info_callback(tls_ctx, ssl_info_cb); # endif SSL_CTX_set_verify_depth(tls_ctx, 6); if (ssl_verify_client_cert) { SSL_CTX_set_verify(tls_ctx, SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_PEER, NULL); if (SSL_CTX_load_verify_locations(tls_ctx, cert_file, NULL) != 1) { tls_error(__LINE__, 0); } } return 0; }
// debug on /var/log/messages static void dbgmsg(const char *msg) { logfile(LOG_INFO, "%s", msg); }
int batchProcessing(const string rootPath, const string listPath, const string faceDetectModel, const string detectionModelPath, const string trackingModelPath, const float ec_mc_y, const float ec_y, const string saveRootPath, const int size) { ofstream logfile("log.txt"); ifstream infile(listPath); string filename; vecS lines; while(infile >> filename) lines.push_back(filename); infile.close(); cout << "A total of " << lines.size() << " images." << endl; string str; Mat img; FACE_HANDLE face_detection_handle; int ret_fd_init = getDetectionHandle(&face_detection_handle, faceDetectModel); if(0 != ret_fd_init || NULL == &face_detection_handle) { cout << "Error init for face alignment!" << endl; return -1; } vecR rect; string error; FACE_HANDLE face_alignment_handle; int ret_fa = getAlignmentHandle(&face_alignment_handle, detectionModelPath, trackingModelPath); if(0 != ret_fa || NULL == face_alignment_handle) { cout << "Error init for face alignment!" << endl; return -1; } for(int i = 0; i < lines.size(); ++i) { rect.clear(); str = rootPath + lines[i]; img = imread(str, CV_LOAD_IMAGE_GRAYSCALE); int ret_fd = detectFace(face_detection_handle, img, rect, error); if(0 != ret_fd) { cout << "The " << i << " image has "<< error <<endl; logfile << lines[i] << " [Face Detection Error]." << endl; continue; } for(int j = 0; j < rect.size(); ++j) { Mat result; int ret_fa = faceAlignment(face_alignment_handle, img, rect[j], ec_mc_y, ec_y, result, error); if(0 != ret_fa) { cout << "The " << i << " image has "<< error <<endl; logfile << lines[i] << " [Facial Points Detection Error]." << endl; continue; } resize(result, result, Size(size, size)); string savePath; stringstream count; char dir[1024]; //sprintf(savePath, "%s%s_%d.jpg", saveRootPath.c_str(), lines[i].c_str(), j); count << j; savePath = saveRootPath + lines[i] + "_" + count.str() + ".jpg"; get_dir_from_filename(savePath.c_str(), dir); int ret = create_directory(dir); if(0 != ret) { cout << savePath << " create file error!" << endl; logfile << lines[i] << " [IO Error]." << endl; } else cout << savePath << " is finished." << endl; imwrite(savePath, result); } } logfile.close(); releaseDetectionHandle(&face_detection_handle); releaseAlignmentHandle(&face_alignment_handle); }
void purgeInvoices::sPurge() { if (!_cutOffDate->isValid()) { QMessageBox::warning( this, tr("Enter Cutoff Date"), tr("You must enter a valid cutoff date before purging Invoice Records.") ); return; } if ( QMessageBox::warning( this, tr("Delete Invoice Records"), tr( "This function will purge Invoices and all of the associated documents including:\n" "Return Authorizations, Lot/Serial Registrations, Sales Orders, Shipments, and Billing.\n" "The results of the process are saved in the log file purgeInvoices.log.\n" "You will not be able to re-print an Invoice if you delete that Invoice's Records.\n" "\n" "Are you sure that you want to delete the selected Invoice Records?" ), tr("Yes"), tr("No"), QString::null, 0, 1) == 0) { QString logpath; QString logname; QString logtogether; logpath = ""; logname = "purgeInvoices.log"; logtogether = logpath + logname; QFile logfile(logtogether); logfile.remove(); logfile.open(QIODevice::WriteOnly); int _invoices = 1; int _kount = 1; XSqlQuery invoices; invoices.prepare("SELECT COUNT(*) AS invoice_count " "FROM invchead " "WHERE ( (invchead_invcdate <= :cutOffDate) " " AND (invchead_posted) " " AND (invchead_recurring_invchead_id!=invchead_id) " " AND (checkInvoiceSitePrivs(invchead_id)) );"); invoices.bindValue(":cutOffDate", _cutOffDate->date()); invoices.exec(); if (invoices.first()) _invoices = (invoices.value("invoice_count").toInt()); QProgressDialog _progress(tr("Purge Invoices in progress..."), tr("Cancel"), 0, _invoices, this); _progress.setWindowModality(Qt::WindowModal); invoices.prepare("SELECT invchead_id, invchead_invcnumber " "FROM invchead " "WHERE ( (invchead_invcdate <= :cutOffDate) " " AND (invchead_posted) " " AND (NOT invchead_recurring) " " AND (checkInvoiceSitePrivs(invchead_id)) );"); invoices.bindValue(":cutOffDate", _cutOffDate->date()); invoices.exec(); while (invoices.next()) { q.prepare("SELECT purgeInvoiceRecord(:cutOffDate, :invchead_id) AS result;"); q.bindValue(":cutOffDate", _cutOffDate->date()); q.bindValue(":invchead_id", invoices.value("invchead_id").toInt()); q.exec(); if (q.first()) { QString logmessage = "Invoice "; logmessage += invoices.value("invchead_invcnumber").toString(); logmessage += ", result="; logmessage += q.value("result").toString(); logfile.write(logmessage.toAscii()); logfile.write("\n"); } if (_progress.wasCanceled()) break; _progress.setValue(_kount); _kount++; } _progress.setValue(_invoices); accept(); } }
/** * @brief The NSSI xfer-server. * * NSSI has already been initialized and the client already knows the URL of the * server. This function simply registers the server methods and starts the * service loop. The client will send a request to kill the service upon completion. * */ int xfer_mpi_server_main(MPI_Comm server_comm) { int rc = 0; log_level debug_level = xfer_debug_level; int server_rank; MPI_Comm_rank(server_comm, &server_rank); log_debug(debug_level, "%d: Starting server", server_rank); /* options that can be overriden by the command-line */ std::string logfile(""); bool done=false; MPI_Status status; // Server loop just waits for requests from any of the clients. The // server isn't expecting any particular type of request. while (!done) { int req_buf[3]; log_debug(debug_level, "Waiting for request"); // Receive the next request, the tag identifies the type of request MPI_Recv(&req_buf, 3, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status); int len = req_buf[0]; int seed = req_buf[1]; int validate = req_buf[2]; log_debug(debug_level, "Server Received Request (source=%d, tag=%d, len=%d, seed=%d, validate=%d)", status.MPI_SOURCE, status.MPI_TAG, len, seed, validate); switch (status.MPI_TAG) { case XFER_MPI_SEND_REQ_TAG: rc = process_mpi_send(len, seed, validate, status.MPI_SOURCE); if (rc != 0) log_error(debug_level, "Error processing SEND request"); break; case XFER_MPI_ISEND_REQ_TAG: log_debug(debug_level, "Server Calling ISEND"); rc = process_mpi_isend(len, seed, validate, status.MPI_SOURCE); if (rc != 0) log_error(debug_level, "Error processing ISEND request"); break; case XFER_MPI_PUT_REQ_TAG: log_debug(debug_level, "Server Calling PUT"); rc = process_mpi_put(len, seed, validate, status.MPI_SOURCE); if (rc != 0) log_error(debug_level, "Error processing PUT request"); break; case XFER_MPI_GET_REQ_TAG: log_debug(debug_level, "Server Calling PUT"); rc = process_mpi_get(len, seed, validate, status.MPI_SOURCE); if (rc != 0) log_error(debug_level, "Error processing GET request"); break; case XFER_MPI_FINI_REQ: log_debug(debug_level, "Server Received EXIT"); done = true; break; default: log_error(debug_level, "tag=%d is not supported", status.MPI_TAG); return -1; } } log_debug(debug_level, "Exiting server"); return rc; }
int main(int argc, char *argv[]) { int ret, keeppidfile = 1; setlocale(LC_ALL, ""); bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); lyxml_init(); lyauth_init(); /* start initializeing g_c */ CLCConfig *c = malloc(sizeof(CLCConfig)); if (c == NULL) { printf(_("malloc for g_c have a error.\n")); return -255; } g_c = c; /* parse command line option and configuration file */ ret = clc_config(argc, argv, c); if (ret == CLC_CONFIG_RET_HELP) usage(); else if (ret == CLC_CONFIG_RET_VER) printf(_("%s : Version %s\n"), PROGRAM_NAME, PROGRAM_VERSION); else if (ret == CLC_CONFIG_RET_ERR_CMD) printf(_ ("command line parsing error, use -h option to display usage\n")); else if (ret == CLC_CONFIG_RET_ERR_NOCONF) { printf(_ ("missing lyclc config file, default build-in settings are used.\n")); ret = 0; } else if (ret == CLC_CONFIG_RET_ERR_ERRCONF) printf(_("can not find %s.\n"), c->conf_path); else if (ret == CLC_CONFIG_RET_ERR_CONF) printf(_("reading config file %s returned error\n"), c->conf_path); else if (ret == CLC_CONFIG_RET_ERR_WEBCONF) printf(_("reading web config file %s returned error\n"), c->web_conf_path); else if (ret == CLC_CONFIG_RET_ERR_UNKNOWN) printf(_("internal error\n")); /* exit if ret is not zero */ if (ret != 0) goto out; /* for debuuging */ if (c->debug) __print_config(c); /* make sure data directory exists */ if (lyutil_create_dir(c->clc_data_dir)) { printf(_("%s is not accessible\n"), c->clc_data_dir); ret = -255; goto out; } /* check whether program is started already */ ret = lyutil_check_pid_file(c->pid_path, PROGRAM_NAME); if (ret == 1) { printf(_("%s is running already.\n"), PROGRAM_NAME); goto out; } else if (ret != 0) { printf(_("error checking pid file.\n")); goto out; } /* check DB */ if (ly_db_check() < 0) { printf(_("failed connecting DB\n")); ret = -255; goto out; } /* get clc ip */ if (c->clc_ip == NULL && ly_clc_ip_get() < 0) { logerror(_("CLC no proper network interface to use.\n")); goto out; } /* Daemonize the progress */ if (c->daemon) { if (c->debug == LYDEBUG) printf(_("Run as daemon, log to %s.\n"), c->log_path); lyutil_daemonize(__main_clean, keeppidfile); logfile(c->log_path, c->debug ? LYDEBUG : c->verbose ? LYINFO : LYWARN); } else logfile(NULL, c->debug ? LYDEBUG : c->verbose ? LYINFO : LYWARN); /* create lock file */ ret = lyutil_create_pid_file(c->pid_path, PROGRAM_NAME); if (ret == 1) { logsimple(_("%s is running already.\n"), PROGRAM_NAME); ret = 0; goto out; } else if (ret != 0) { logsimple(_("error creating pid file.\n")); goto out; } keeppidfile = 0; /* init db connection */ if (ly_db_init() < 0) { logsimple(_("ly_db_init failed.\n")); ret = -255; goto out; } /* initialize entity store */ if (ly_entity_store_init() < 0) { logsimple(_("ly_entity_init failed.\n")); ret = -255; goto out; } /* init job queue */ if (job_init() < 0 || job_internal_init() < 0) { logsimple(_("job_init failed.\n")); ret = -255; goto out; } if (c->debug) job_print_queue(); /* set up signal handler */ lyutil_signal_init(); /* handle specific signal */ struct sigaction sa; sa.sa_flags = 0; sigemptyset(&sa.sa_mask); sa.sa_sigaction = __sig_handler; if (sigaction(SIGTERM, &sa, NULL)) { logsimple(_("Setting signal handler error.\n")); ret = -255; goto out; } /* initialize g_c->efd */ if (ly_epoll_init(EPOLL_EVENTS_MAX) != 0) { logsimple(_("ly_epoll_init failed.\n")); ret = -255; goto out; } if (ly_epoll_work_start(g_c->clc_port) != 0) { ret = -1; logsimple(_("ly_epoll_init failed.\n")); goto out; } /* init timeout values */ time_t mcast_join_time, job_dispatch_time, job_internal_time; mcast_join_time = 0; time(&job_dispatch_time); job_internal_time = job_dispatch_time + (CLC_MCAST_JOIN_INTERVAL<<1); job_dispatch_time = job_dispatch_time + (CLC_MCAST_JOIN_INTERVAL<<2); /* start main event driven loop */ if (c->clc_ip) loginfo(_("clc uses IP %s\n"), c->clc_ip); else loginfo(_("clc uses IP automatically detected\n")); loginfo(_("start event loop, waiting for events ...\n")); int i, n = 0; struct epoll_event events[EPOLL_EVENTS_MAX]; while (1) { time_t time_now; time(&time_now); /* send mcast request */ if (time_now - mcast_join_time > CLC_MCAST_JOIN_INTERVAL) { if (ly_mcast_send_join() < 0) logerror(_("failed sending mcast request.\n")); mcast_join_time = time_now; } else if (time_now < mcast_join_time) mcast_join_time = time_now; /* job dispatch */ if (time_now - job_dispatch_time > CLC_JOB_DISPATCH_INTERVAL) { if (job_dispatch() < 0) logerror(_("job_dispatch failed.\n")); job_dispatch_time = time_now; } else if (time_now < job_dispatch_time) job_dispatch_time = time_now; /* internal job dispatch */ if (time_now - job_internal_time > CLC_JOB_INTERNAL_INTERVAL) { if (job_internal_dispatch() < 0) logerror(_("job_internal failed.\n")); job_internal_time = time_now; } else if (time_now < job_internal_time) job_internal_time = time_now; n = epoll_wait(g_efd, events, EPOLL_EVENTS_MAX, CLC_EPOLL_TIMEOUT); if (n != 0) logdebug(_("waiting ... got %d events\n"), n); for (i = 0; i < n; i++) { int id = events[i].data.fd; if (events[i].events & EPOLLIN) { ret = ly_epoll_entity_recv(id); if (ret < 0) { logerror(_("epoll_data_recv error\n")); } else if (ret > 0) { loginfo(_("release entity %d\n"), id); ly_entity_release(id); } } else if (events[i].events & EPOLLRDHUP) { loginfo(_("epoll entity(%d) got rdhup. close.\n"), id); ly_entity_release(id); } else if (events[i].events & EPOLLHUP) { loginfo(_("epoll entity(%d) got hup. close.\n"), id); ly_entity_release(id); } else { logerror(_("unexpected event(%d, %d). ignore.\n"), events[i].events, id); } } } out: __main_clean(keeppidfile); if (ret <= 0) loginfo(_("%s exits\n"), PROGRAM_NAME); return ret; }
/*! * @brief logfile出力のテスト * * - ログレベルを ERROR にした場合のファイル出力が正しく行われるか? */ void test_logfile_ERROR(void) { // std::cout << "test_logfile_ERROR() IN" << std::endl; coil::LogStreamBuffer logger; std::string logfile("rtcERROR.log"); std::filebuf of; of.open(logfile.c_str(), std::ios::out); if (!of.is_open()) { std::cerr << "Error: cannot open logfile: " << logfile << std::endl; } logger.addStream(&of, true); RTC::Logger rtclog(&logger); rtclog.setName("Test"); rtclog.setDateFormat("%b %d %H:%M:%S"); rtclog.setLevel("ERROR"); // 汎用ログ出力マクロ、各種ログ出力マクロで正しくファイル出力されるか? RTC_LOG( ::RTC::Logger::RTL_PARANOID,("RTL_PARANOID tests %s","fmt")); RTC_LOG_STR(::RTC::Logger::RTL_PARANOID, "RTL_PARANOID tests str"); RTC_PARANOID( ("Macro RTL_PARANOID tests %s","fmt")); RTC_PARANOID_STR("Macro RTL_PARANOID tests str"); RTC_LOG( ::RTC::Logger::RTL_VERBOSE,("RTL_VERBOSE tests %s","fmt")); RTC_LOG_STR(::RTC::Logger::RTL_VERBOSE, "RTL_VERBOSE tests str"); RTC_VERBOSE( ("Macro RTL_VERBOSE tests %s","fmt")); RTC_VERBOSE_STR("Macro RTL_VERBOSE tests str"); RTC_LOG( ::RTC::Logger::RTL_TRACE,("RTL_TRACE tests %s","fmt")); RTC_LOG_STR(::RTC::Logger::RTL_TRACE, "RTL_TRACE tests str"); RTC_TRACE( ("Macro RTL_TRACE tests %s","fmt")); RTC_TRACE_STR("Macro RTL_TRACE tests str"); RTC_LOG( ::RTC::Logger::RTL_DEBUG,("RTL_DEBUG tests %s","fmt")); RTC_LOG_STR(::RTC::Logger::RTL_DEBUG, "RTL_DEBUG tests str"); RTC_DEBUG( ("Macro RTL_DEBUG tests %s","fmt")); RTC_DEBUG_STR("Macro RTL_DEBUG tests str"); RTC_LOG( ::RTC::Logger::RTL_INFO,("RTL_INFO tests %s","fmt")); RTC_LOG_STR(::RTC::Logger::RTL_INFO, "RTL_INFO tests str"); RTC_INFO( ("Macro RTL_INFO tests %s","fmt")); RTC_INFO_STR("Macro RTL_INFO tests str"); RTC_LOG( ::RTC::Logger::RTL_WARN,("RTL_WARN tests %s","fmt")); RTC_LOG_STR(::RTC::Logger::RTL_WARN, "RTL_WARN tests str"); RTC_WARN( ("Macro RTL_WARN tests %s","fmt")); RTC_WARN_STR("Macro RTL_WARN tests str"); RTC_LOG( ::RTC::Logger::RTL_ERROR,("RTL_ERROR tests %s","fmt")); RTC_LOG_STR(::RTC::Logger::RTL_ERROR, "RTL_ERROR tests str"); RTC_ERROR( ("Macro RTL_ERROR tests %s","fmt")); RTC_ERROR_STR("Macro RTL_ERROR tests str"); RTC_LOG( ::RTC::Logger::RTL_FATAL,("RTL_FATAL tests %s","fmt")); RTC_LOG_STR(::RTC::Logger::RTL_FATAL, "RTL_FATAL tests str"); RTC_FATAL( ("Macro RTL_FATAL tests %s","fmt")); RTC_FATAL_STR("Macro RTL_FATAL tests str"); RTC_LOG( ::RTC::Logger::RTL_SILENT,("RTL_SILENT tests %s","fmt")); RTC_LOG_STR(::RTC::Logger::RTL_SILENT, "RTL_SILENT tests str"); of.close(); // ファイル出力があるか? std::string rstr; std::ifstream ifs(logfile.c_str()); ifs >> rstr; CPPUNIT_ASSERT(rstr.size() > 0); ifs >> rstr; ifs >> rstr; ifs >> rstr; CPPUNIT_ASSERT_EQUAL(std::string("ERROR:"), rstr); ifs >> rstr; CPPUNIT_ASSERT_EQUAL(std::string("Test:"), rstr); ifs >> rstr; CPPUNIT_ASSERT_EQUAL(std::string("RTL_ERROR"), rstr); ifs >> rstr; CPPUNIT_ASSERT_EQUAL(std::string("tests"), rstr); ifs >> rstr; CPPUNIT_ASSERT_EQUAL(std::string("fmt"), rstr); // std::cout << "test_logfile_ERROR() OUT" << std::endl; }