void quendi_send_spec(int dsock, const char* name) { char spec_file[200]; char buffer[100]; unsigned length; void *spec; struct stat stat_buf; int fd; GetSpecFile(spec_file, name, NULL); if (stat(spec_file, &stat_buf)) berror(fatal, "cannot stat spec file `%s'", spec_file); length = stat_buf.st_size; if ((fd = open(spec_file, O_RDONLY)) < 0) berror(fatal, "cannot open spec file `%s'", spec_file); snprintf(buffer, 100, "%i Sending Spec File", length); quendi_respond(QUENYA_RESPONSE_SENDING_SPEC, buffer); spec = balloc(fatal, length); if (read(fd, spec, length) < 0) berror(err, "failed to read from spec file"); if (write(dsock, spec, length) < 0) berror(err, "failed to write to spec file"); close(fd); bfree(fatal, spec); quendi_respond(QUENYA_RESPONSE_TRANS_COMPLETE, NULL); }
void block_update(struct block *block) { FILE *child_stdout; int child_status, code; char output[2048], *text = output; if (setup_env(block)) return mark_as_failed(block, "failed to setup env", -1); /* Pipe, fork and exec a shell for the block command line */ child_stdout = popen(block->command, "r"); if (!child_stdout) { berrorx(block, "popen(%s)", block->command); return mark_as_failed(block, "failed to fork", -1); } /* Do not distinguish EOF or error, just read child's output */ memset(output, 0, sizeof(output)); fread(output, 1, sizeof(output) - 1, child_stdout); /* Wait for the child process to terminate */ child_status = pclose(child_stdout); if (child_status == -1) { berrorx(block, "pclose"); return mark_as_failed(block, "failed to wait", -1); } if (!WIFEXITED(child_status)) { berror(block, "child did not exit correctly"); return mark_as_failed(block, "command did not exit", -1); } code = WEXITSTATUS(child_status); if (code != 0 && code != '!') { char reason[1024] = { 0 }; berror(block, "bad exit code %d", code); linecpy(&text, reason, sizeof(reason) - 1); return mark_as_failed(block, reason, code); } /* From here, the update went ok so merge the output */ strncpy(block->urgent, code == '!' ? "true" : "false", sizeof(block->urgent) - 1); linecpy(&text, block->full_text, sizeof(block->full_text) - 1); linecpy(&text, block->short_text, sizeof(block->short_text) - 1); linecpy(&text, block->color, sizeof(block->color) - 1); block->last_update = time(NULL); bdebug(block, "updated successfully"); }
int quendi_read_data(int new_chunk, int* fd, const char* chunk, unsigned long seek_to, int *chunk_total, unsigned frame_size, unsigned long *frames_read, unsigned *remainder) { int n, block_size; struct stat chunk_stat; if (new_chunk) { printf("New chunk ok\n"); if ((*fd = open(chunk, O_RDONLY)) < 0) berror(fatal, "cannot open `%s'", chunk); printf("New chunk fopen ok\n"); if (seek_to > 0) { lseek(*fd, seek_to, SEEK_SET); seek_to = 0; printf("New chunk fseek ok\n"); } if (stat(chunk, &chunk_stat)) berror(fatal, "cannot stat `%s'", chunk); *chunk_total = chunk_stat.st_size / frame_size; printf("New chunk stat ok (%i)\n", *chunk_total); } if ((n = read(*fd, (void*)quendi_input_buffer[0] + *remainder, frame_size * INPUT_BUF_SIZE - *remainder)) < 1) { if (n == 0) return 0; else { berror(err, "error reading `%s'", chunk); close(*fd); if ((*fd = open(chunk, O_RDONLY)) < 0) berror(fatal, "cannot open `%s'", chunk); lseek(*fd, *frames_read * frame_size, SEEK_SET); n = 0; } } block_size = (*remainder + n) / frame_size; *remainder = (*remainder + n) % frame_size; *frames_read += block_size; return block_size; }
int _frcanfit(Frame *f, Point pt, Frbox *b) { int left, w, nr; uchar *p; Rune r; left = f->r.max.x-pt.x; if(b->nrune < 0) return b->a.b.minwid <= left; if(left >= b->wid) return b->nrune; for(nr=0,p=b->a.ptr; *p; p+=w,nr++){ r = *p; if(r < Runeself) w = 1; else w = chartorune(&r, (char*)p); left -= charwidth(f->font, r); if(left < 0) return nr; } berror("_frcanfit can't"); return 0; }
int Stream::Connect(Socket* ptr, const timespec*, int (*on_connect)(int, int, void *), void *data) { CHECK_EQ(ptr->id(), _id); bthread_mutex_lock(&_connect_mutex); if (_connect_meta.on_connect != NULL) { CHECK(false) << "Connect is supposed to be called once"; bthread_mutex_unlock(&_connect_mutex); return -1; } _connect_meta.on_connect = on_connect; _connect_meta.arg = data; if (_connected) { ConnectMeta* meta = new ConnectMeta; meta->on_connect = _connect_meta.on_connect; meta->arg = _connect_meta.arg; meta->ec = _connect_meta.ec; bthread_mutex_unlock(&_connect_mutex); bthread_t tid; if (bthread_start_urgent(&tid, &BTHREAD_ATTR_NORMAL, RunOnConnect, meta) != 0) { LOG(FATAL) << "Fail to start bthread, " << berror(); RunOnConnect(meta); } return 0; } bthread_mutex_unlock(&_connect_mutex); return 0; }
int EventDispatcher::Start(const bthread_attr_t* consumer_thread_attr) { if (_epfd < 0) { LOG(FATAL) << "epoll was not created"; return -1; } if (_tid != 0) { LOG(FATAL) << "Already started this dispatcher(" << this << ") in bthread=" << _tid; return -1; } // Set _consumer_thread_attr before creating epoll thread to make sure // everyting seems sane to the thread. _consumer_thread_attr = (consumer_thread_attr ? *consumer_thread_attr : BTHREAD_ATTR_NORMAL); // Polling thread uses the same attr for consumer threads (NORMAL right // now). Previously, we used small stack (32KB) which may be overflowed // when the older comlog (e.g. 3.1.85) calls com_openlog_r(). Since this // is also a potential issue for consumer threads, using the same attr // should be a reasonable solution. int rc = bthread_start_background( &_tid, &_consumer_thread_attr, RunThis, this); if (rc) { LOG(FATAL) << "Fail to create epoll thread: " << berror(rc); return -1; } return 0; }
int NamingServiceThread::Start(const NamingService* naming_service, const std::string& service_name, const GetNamingServiceThreadOptions* opt_in) { if (naming_service == NULL) { LOG(ERROR) << "Param[naming_service] is NULL"; return -1; } _source_ns = naming_service; _ns = naming_service->New(); _service_name = service_name; if (opt_in) { _options = *opt_in; } _last_sockets.clear(); if (_ns->RunNamingServiceReturnsQuickly()) { RunThis(this); } else { int rc = bthread_start_urgent(&_tid, NULL, RunThis, this); if (rc) { LOG(ERROR) << "Fail to create bthread: " << berror(rc); return -1; } } return WaitForFirstBatchOfServers(); }
void PProfService::growth( ::google::protobuf::RpcController* controller_base, const ::brpc::ProfileRequest* /*request*/, ::brpc::ProfileResponse* /*response*/, ::google::protobuf::Closure* done) { ClosureGuard done_guard(done); Controller* cntl = static_cast<Controller*>(controller_base); MallocExtension* malloc_ext = MallocExtension::instance(); if (malloc_ext == NULL) { cntl->SetFailed(ENOMETHOD, "%s, to enable growth profiler, check out " "docs/cn/heap_profiler.md", berror(ENOMETHOD)); return; } // Log requester std::ostringstream client_info; client_info << cntl->remote_side(); if (cntl->auth_context()) { client_info << "(auth=" << cntl->auth_context()->user() << ')'; } else { client_info << "(no auth)"; } LOG(INFO) << client_info.str() << " requests for growth profile"; std::string obj; malloc_ext->GetHeapGrowthStacks(&obj); cntl->http_response().set_content_type("text/plain"); cntl->response_attachment().append(obj); }
int Stream::AppendIfNotFull(const butil::IOBuf &data) { if (_options.max_buf_size > 0) { std::unique_lock<bthread_mutex_t> lck(_congestion_control_mutex); if (_produced >= _remote_consumed + (size_t)_options.max_buf_size) { const size_t saved_produced = _produced; const size_t saved_remote_consumed = _remote_consumed; lck.unlock(); RPC_VLOG << "Stream=" << _id << " is full" << "_produced=" << saved_produced << " _remote_consumed=" << saved_remote_consumed << " gap=" << saved_produced - saved_remote_consumed << " max_buf_size=" << _options.max_buf_size; return 1; } _produced += data.length(); } butil::IOBuf copied_data(data); const int rc = _fake_socket_weak_ref->Write(&copied_data); if (rc != 0) { CHECK_EQ(0, rc) << "Fail to write to _fake_socket, " << berror(); BAIDU_SCOPED_LOCK(_congestion_control_mutex); _produced -= data.length(); return -1; } return 0; }
void _frdelbox(Frame *f, int n0, int n1) /* inclusive */ { if(n0>=f->nbox || n1>=f->nbox || n1<n0) berror("_frdelbox"); _frfreebox(f, n0, n1); _frclosebox(f, n0, n1); }
SamplerCollector() : _created(false), _stop(false), _cumulated_time_us(0) { int rc = pthread_create(&_tid, NULL, sampling_thread, this); if (rc != 0) { LOG(FATAL) << "Fail to create sampling_thread, " << berror(rc); } else { _created = true; } }
int quendi_dp_open(void) { struct sockaddr_in addr; socklen_t addrlen; int dsock; addrlen = sizeof(addr); getsockname(quendi_server_data->csock, (struct sockaddr*)&addr, &addrlen); if ((dsock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) berror(warning, "socket"); addr.sin_port = htons(0); if (bind(dsock, (struct sockaddr*)&addr, (socklen_t)sizeof(addr)) == -1) berror(warning, "bind"); return dsock; }
void _frgrowbox(Frame *f, int delta) { f->nalloc += delta; f->box = f->box ? realloc(f->box, f->nalloc*sizeof(Frbox)) : malloc(f->nalloc*sizeof(Frbox)); if(f->box == 0) berror("_frgrowbox"); }
static void get_username(std::ostream& os, void*) { char buf[32]; if (getlogin_r(buf, sizeof(buf)) == 0) { buf[sizeof(buf)-1] = '\0'; os << buf; } else { os << "unknown (" << berror() << ')' ; } }
int bbdn_conect(int *socketha, char tkey[], int PORT) { int intrespons; int i; if (((*socketha) = cconnect("127.0.0.1", PORT)) == 0) { bperror("Can't connect to back-end document manager"); return 0; } //sender heder sendpacked((*socketha),bbc_askToAuthenticate,BLDPROTOCOLVERSION, 0, NULL,""); if (!sendall((*socketha),tkey, 32)) { bperror("sendall"); goto bbdn_conect_err; } if ((i=recv((*socketha), &intrespons, sizeof(intrespons),MSG_WAITALL)) == -1) { bperror("Cant recv respons"); goto bbdn_conect_err; } if (intrespons == bbc_authenticate_ok) { debug("bbc authenticate ok\n"); return 1; } else if (intrespons == bbc_authenticate_feiled) { berror("bbc authenticate feiled"); goto bbdn_conect_err; } else { berror("respons from server was nider bbc_authenticate_feiled or bbc_authenticate_ok!\n"); goto bbdn_conect_err; } bbdn_conect_err: close(*socketha); return 0; }
static int parse_property(const char *line, struct block *block) { char *equal = strchr(line, '='); const char *property, *value; if (!equal) { berror(block, "malformated property, should be of the form 'key=value'"); return 1; } /* split property and value */ *equal = '\0'; property = line; value = equal + 1; #define PARSE(_name, _size, _type) \ if (strcmp(property, #_name) == 0) { \ strncpy(block->_name, value, _size - 1); \ goto parsed; \ } \ #define PARSE_NUM(_name) \ if (strcmp(property, #_name) == 0) { \ block->_name = atoi(value); \ goto parsed; \ } \ PROTOCOL_KEYS(PARSE); PARSE(command, sizeof(block->command), _); PARSE_NUM(interval); PARSE_NUM(signal); /* TODO some better check for numbers and boolean */ #undef PARSE_NUM #undef PARSE berror(block, "unknown property: \"%s\"", property); return 1; parsed: bdebug(block, "set property %s to \"%s\"", property, value); return 0; }
static void chopbox(Frame *f, Frbox *b, int n) /* drop first n chars; no allocation done */ { if(b->nrune<0 || b->nrune<n) berror("chopbox"); strcpy((char*)b->a.ptr, (char*)runeindex(b->a.ptr, n)); b->nrune -= n; b->wid = strwidth(f->font, (char *)b->a.ptr); }
uchar * _frallocstr(unsigned n) { uchar *p; p = malloc(ROUNDUP(n)); if(p == 0) berror("out of memory"); return p; }
static void truncatebox(Frame *f, Frbox *b, int n) /* drop last n chars; no allocation done */ { if(b->nrune<0 || b->nrune<n) berror("truncatebox"); b->nrune -= n; runeindex(b->a.ptr, b->nrune)[0] = 0; b->wid = strwidth(f->font, (char *)b->a.ptr); }
void Stream::Wait(void (*on_writable)(StreamId, void*, int), void* arg, const timespec* due_time, bool new_thread, bthread_id_t *join_id) { WritableMeta *wm = new WritableMeta; wm->on_writable = on_writable; wm->id = id(); wm->arg = arg; wm->new_thread = new_thread; wm->has_timer = false; bthread_id_t wait_id; const int rc = bthread_id_create(&wait_id, wm, TriggerOnWritable); if (rc != 0) { CHECK(false) << "Fail to create bthread_id, " << berror(rc); wm->error_code = rc; RunOnWritable(wm); return; } if (join_id) { *join_id = wait_id; } CHECK_EQ(0, bthread_id_lock(wait_id, NULL)); if (due_time != NULL) { wm->has_timer = true; const int rc = bthread_timer_add(&wm->timer, *due_time, OnTimedOut, reinterpret_cast<void*>(wait_id.value)); if (rc != 0) { LOG(ERROR) << "Fail to add timer, " << berror(rc); CHECK_EQ(0, TriggerOnWritable(wait_id, wm, rc)); } } bthread_mutex_lock(&_congestion_control_mutex); if (_options.max_buf_size <= 0 || _produced < _remote_consumed + (size_t)_options.max_buf_size) { bthread_mutex_unlock(&_congestion_control_mutex); CHECK_EQ(0, TriggerOnWritable(wait_id, wm, 0)); return; } else { bthread_id_list_add(&_writable_wait_list, wait_id); bthread_mutex_unlock(&_congestion_control_mutex); } CHECK_EQ(0, bthread_id_unlock(wait_id)); }
void block_update(struct block *block) { struct properties *props = &block->updated_props; char buf[2048] = { 0 }; int nr; /* Read a single line for persistent block, everything otherwise */ if (block->interval == INTER_PERSIST) { nr = io_readline(block->out, buf, sizeof(buf)); if (nr < 0) { berror(block, "failed to read a line"); return mark_as_failed(block, "failed to read"); } else if (nr == 0) { berror(block, "pipe closed"); return mark_as_failed(block, "pipe closed"); } } else { /* Note: read(2) returns 0 for end-of-pipe */ if (read(block->out, buf, sizeof(buf) - 1) == -1) { berrorx(block, "read stdout"); return mark_as_failed(block, strerror(errno)); } } /* Reset the defaults and merge the output */ memcpy(props, &block->default_props, sizeof(struct properties)); if (block->format == FORMAT_JSON) block_update_json(block, buf); else block_update_plain_text(block, buf); if (*FULL_TEXT(block) && *LABEL(block)) { static const size_t size = sizeof(props->full_text); char concat[size]; snprintf(concat, size, "%s %s", LABEL(block), FULL_TEXT(block)); strcpy(props->full_text, concat); } bdebug(block, "updated successfully"); }
long OpenField(int fast, int size, const char* filename) { long file; #ifdef HAVE_LIBZ char gpb[GPB_LEN]; int gzerrno; const char* gze; #endif int offset; if (rc.resume_at >= 0) { offset = rc.resume_at * size * 2; if (!fast) offset /= FAST_PER_SLOW; /* append to file */ if ((file = open(filename, O_WRONLY)) == -1) berror(fatal, "cannot open file `%s'", filename); if (lseek(file, offset, SEEK_SET) < 0) berror(fatal, "cannot lseek file `%s'", filename); } else { /* create new file */ #ifdef HAVE_LIBZ if (rc.gzip_output && (file = (long)gzdopen(creat(filename, 00644), "wb")) == 0) { snprintf(gpb, GPB_LEN, "cannot create file `%s'", filename); if (errno) berror(fatal, "%s\n", gpb); else { gze = gzerror((gzFile)file, &gzerrno); bprintf(fatal, "%s: %s", gpb, gze); } } else if (!rc.gzip_output && (file = creat(filename, 00644)) == -1) #else if ((file = creat(filename, 00644)) == -1) #endif berror(fatal, "cannot create file `%s'", filename); } return file; }
void close_cm(struct CMInfoStruct* cminfo) { bprintf(info,"Closing connection to %s motor.\n", cminfo->motorstr); if (cminfo->open == 0) { bprintf(info, "%s motor port is already closed!", cminfo->motorstr); } else if ( (close(cminfo->fd)) == 0 ) { cminfo->open = 0; bprintf(info, "Connection to %s motor is now closed.", cminfo->motorstr); } else berror(err, "Failed to close motor serial port"); }
/** Write the Previous Status: called whenever anything changes */ static void WritePrevStatus() { int fp, n; /** write the default file */ fp = open("/data/etc/minicp/minicp.prev_status", O_WRONLY|O_CREAT|O_TRUNC, 00666); if (fp < 0) { berror(err, "Commands: mcp.prev_status open()"); return; } if ((n = write(fp, &CommandData, sizeof(struct CommandDataStruct))) < 0) { berror(err, "Commands: mcp.prev_status write()"); return; } if ((n = close(fp)) < 0) { berror(err, "Commands: mcp.prev_status close()"); return; } }
void _frclosebox(Frame *f, int n0, int n1) /* inclusive */ { int i; if(n0>=f->nbox || n1>=f->nbox || n1<n0) berror("_frclosebox"); n1++; for(i=n1; i<f->nbox; i++) f->box[i-(n1-n0)] = f->box[i]; f->nbox -= n1-n0; }
void block_reap(struct block *block) { int status, code; if (block->pid <= 0) { bdebug(block, "not spawned yet"); return; } if (waitpid(block->pid, &status, 0) == -1) { berrorx(block, "waitpid(%d)", block->pid); mark_as_failed(block, strerror(errno)); goto close; } code = WEXITSTATUS(status); bdebug(block, "process %d exited with %d", block->pid, code); /* Process successfully reaped, reset the block PID */ block->pid = 0; block_dump_stderr(block); if (code != 0 && code != EXIT_URGENT) { char reason[32]; if (code == EXIT_ERR_INTERNAL) sprintf(reason, "internal error"); else sprintf(reason, "bad exit code %d", code); berror(block, "%s", reason); mark_as_failed(block, reason); goto close; } /* Do not update unless it was meant to terminate */ if (block->interval == INTER_PERSIST) goto close; block_update(block); /* Exit code takes precedence over the output */ if (code == EXIT_URGENT) strcpy(block->updated_props.urgent, "true"); close: if (close(block->out) == -1) berrorx(block, "close stdout"); if (close(block->err) == -1) berrorx(block, "close stderr"); }
void WriteField(long file, int length, void *buffer) { #ifdef HAVE_LIBZ int gzerrno; const char *gze; if (rc.gzip_output && gzwrite((gzFile)file, buffer, length) == 0) { if (errno) berror(fatal, "Error on write"); else { gze = gzerror((gzFile)file, &gzerrno); if (gzerrno) bprintf(fatal, "Error on write: %s (%i)", gze, gzerrno); } } else if (!rc.gzip_output && write(file, buffer, length) < 0) #else if (write(file, buffer, length) < 0) #endif berror(fatal, "Error on write"); #ifdef DEBUG_FASTSAMP int i; int seq_err = 0; static unsigned long last_fastsamp = 4000000000U; if (file == 5) for (i = 0; i < length / 4; ++i) { if (last_fastsamp < 4000000000U) if (last_fastsamp + 1 != ((unsigned long*)buffer)[i]) seq_err = last_fastsamp + 1; last_fastsamp = ((unsigned long*)buffer)[i]; printf("Fastsamp write: %lu\n", last_fastsamp); } if (seq_err) bprintf(fatal, "sequencing error (%i) detected.\n", seq_err); #endif }
void PProfService::contention( ::google::protobuf::RpcController* controller_base, const ::brpc::ProfileRequest* /*request*/, ::brpc::ProfileResponse* /*response*/, ::google::protobuf::Closure* done) { ClosureGuard done_guard(done); Controller* cntl = static_cast<Controller*>(controller_base); cntl->http_response().set_content_type("text/plain"); int sleep_sec = ReadSeconds(cntl); if (sleep_sec <= 0) { if (!cntl->Failed()) { cntl->SetFailed(EINVAL, "You have to specify ?seconds=N. If you're " "using pprof, add --seconds=N"); } return; } // Log requester std::ostringstream client_info; client_info << cntl->remote_side(); if (cntl->auth_context()) { client_info << "(auth=" << cntl->auth_context()->user() << ')'; } else { client_info << "(no auth)"; } LOG(INFO) << client_info.str() << " requests for contention profile for " << sleep_sec << " seconds"; char prof_name[256]; if (MakeProfName(PROFILING_CONTENTION, prof_name, sizeof(prof_name)) != 0) { cntl->SetFailed(errno, "Fail to create .prof file, %s", berror()); return; } if (!bthread::ContentionProfilerStart(prof_name)) { cntl->SetFailed(EAGAIN, "Another profiler is running, try again later"); return; } if (bthread_usleep(sleep_sec * 1000000L) != 0) { PLOG(WARNING) << "Profiling has been interrupted"; } bthread::ContentionProfilerStop(); butil::fd_guard fd(open(prof_name, O_RDONLY)); if (fd < 0) { cntl->SetFailed(ENOENT, "Fail to open %s", prof_name); return; } butil::IOPortal portal; portal.append_from_file_descriptor(fd, ULONG_MAX); cntl->response_attachment().swap(portal); }
void _fraddbox(Frame *f, int bn, int n) /* add n boxes after bn, shift the rest up, * box[bn+n]==box[bn] */ { int i; if(bn > f->nbox) berror("_fraddbox"); if(f->nbox+n > f->nalloc) _frgrowbox(f, n+SLOP); for(i=f->nbox; --i>=bn; ) f->box[i+n] = f->box[i]; f->nbox+=n; }
void _frfreebox(Frame *f, int n0, int n1) /* inclusive */ { int i; if(n1<n0) return; if(n0>=f->nbox || n1>=f->nbox) berror("_frfreebox"); n1++; for(i=n0; i<n1; i++) if(f->box[i].nrune >= 0) free(f->box[i].a.ptr); }