id stringlengths 2 7 | text stringlengths 17 51.2k | title stringclasses 1 value |
|---|---|---|
c174600 | net.Dial(network, address)
if err == nil {
c.Close()
return true
}
return false
})
} | |
c174601 |
name: name,
body: body,
occuredTime: time.Now(),
}
} | |
c174602 | v := range b.handlers {
if v == h {
return false
}
}
b.handlers = append(b.handlers, h)
return true
} | |
c174603 | b.handlers {
if v == h {
b.handlers = append(b.handlers[:i], b.handlers[i+1:]...)
return true
}
}
return false
} | |
c174604 |
defer b.mu.RUnlock()
for _, h := range b.handlers {
h.Handle(e)
}
} | |
c174605 | {
for _, name := range names {
if e.Name() == name {
h.Handle(e)
break
}
}
})
} | |
c174606 | context.WithValue(ctx, KeyPublisher, pub)
} | |
c174607 | ctx.Value(KeyPublisher).(Publisher)
if !ok {
return nil
}
return pub
} | |
c174608 | reflect.TypeOf(eventBody).Name()
pub.Publish(name, eventBody)
} | |
c174609 | nil {
return
}
pub.Publish(eventName, eventBody)
} | |
c174610 | reflect.TypeOf(eventBody).Name()
PublishEventContext(ctx, name, eventBody)
} | |
c174611 | "WARNING"
case NOTICE:
return "NOTICE"
case INFO:
return "INFO"
default:
return "DEBUG"
}
} | |
c174612 | "4":
*level = WARNING
case `"NOTICE"`, "5":
*level = NOTICE
case `"INFO"`, "6":
*level = INFO
case `"DEBUG"`, "7":
*level = DEBUG
default:
return ErrInvalidLevel
}
return nil
} | |
c174613 | f := apply
apply = func(s STM) error {
s.Get(opts.prefetch...)
return f(s)
}
}
return runSTM(mkSTM(c, opts), apply)
} | |
c174614 | rev := resp.Header.Revision; rev < ret {
ret = rev
}
}
return ret
} | |
c174615 | cmps = append(cmps, v3.Compare(v3.ModRevision(key), "<", rev))
}
return cmps
} | |
c174616 | (*v3.TxnResponse, error) {
return NewSTM(c, apply, WithAbortContext(ctx), WithIsolation(RepeatableReads))
} | |
c174617 | error) (*v3.TxnResponse, error) {
return NewSTM(c, apply, WithAbortContext(ctx), WithIsolation(Serializable))
} | |
c174618 | error) (*v3.TxnResponse, error) {
return NewSTM(c, apply, WithAbortContext(ctx), WithIsolation(ReadCommitted))
} | |
c174619 | break
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, err
}
certPool.AddCert(cert)
}
}
return certPool, nil
} | |
c174620 | parseFunc = tls.X509KeyPair
}
tlsCert, err := parseFunc(cert, key)
if err != nil {
return nil, err
}
return &tlsCert, nil
} | |
c174621 |
p.msgAppReader.pause()
p.msgAppV2Reader.pause()
} | |
c174622 |
p.msgAppReader.resume()
p.msgAppV2Reader.resume()
} | |
c174623 | else if writec, ok = p.msgAppV2Writer.writec(); ok && isMsgApp(m) {
return writec, streamAppV2
} else if writec, ok = p.writer.writec(); ok {
return writec, streamMsg
}
return p.pipeline.msgc, pipelineMsg
} | |
c174624 | after
// successfully receives the request body.
time.AfterFunc(snapResponseReadTimeout, func() { httputil.GracefulClose(resp) })
body, err := ioutil.ReadAll(resp.Body)
result <- responseAndError{resp, body, err}
}()
select {
case <-s.stopc:
return errStopped
case r := <-result:
if r.err != nil {
return r.err
}
return checkPostResponse(r.resp, r.body, req, s.to)
}
} | |
c174625 |
case *pb.RequestOp_RequestDeleteRange:
resps[i] = &pb.ResponseOp{Response: &pb.ResponseOp_ResponseDeleteRange{}}
case *pb.RequestOp_RequestTxn:
resp, txns := newTxnResp(tv.RequestTxn, txnPath[1:])
resps[i] = &pb.ResponseOp{Response: &pb.ResponseOp_ResponseTxn{ResponseTxn: resp}}
txnPath = txnPath[1+txns:]
txnCount += txns + 1
default:
}
}
return txnResp, txnCount
} | |
c174626 | on a key/keys that doesn't exist;
// nil == empty string in grpc; no way to represent missing value
return false
}
return compareKV(c, mvccpb.KeyValue{})
}
for _, kv := range rr.KVs {
if !compareKV(c, kv) {
return false
}
}
return true
} | |
c174627 | {
ret := CompactOp{revision: rev}
ret.applyCompactOpts(opts)
return ret
} | |
c174628 | &PriorityQueue{client, context.TODO(), key + "/"}
} | |
c174629 | := fmt.Sprintf("%s%05d", q.key, pr)
_, err := newSequentialKV(q.client, prefix, val)
return err
} | |
c174630 | id,
Followers: make(map[string]*FollowerStats),
},
}
} | |
c174631 | fs.Latency.Maximum = fs.Latency.Current
}
if fs.Latency.Current < fs.Latency.Minimum {
fs.Latency.Minimum = fs.Latency.Current
}
fs.Latency.Average = (total + fs.Latency.Current) / float64(fs.Counts.Success)
fs.Latency.averageSquare = (totalSquare + fs.Latency.Current*fs.Latency.Current) / float64(fs.Counts.Success)
// sdv = sqrt(avg(x^2) - avg(x)^2)
fs.Latency.StandardDeviation = math.Sqrt(fs.Latency.averageSquare - fs.Latency.Average*fs.Latency.Average)
} | |
c174632 | fs.Unlock()
fs.Counts.Fail++
} | |
c174633 | {
panic("deleting missing watcher from broadcasts")
}
delete(wbs.watchers, w)
wb.delete(w)
if wb.empty() {
delete(wbs.bcasts, wb)
wb.stop()
}
return len(wbs.bcasts)
} | |
c174634 |
connc: make(chan *outgoingConn),
stopc: make(chan struct{}),
done: make(chan struct{}),
}
go w.run()
return w
} | |
c174635 | supportedStream[nv.String()] {
if s == t {
return true
}
}
return false
} | |
c174636 |
if pr.Next < n+1 {
pr.Next = n + 1
}
return updated
} | |
c174637 | ProgressStateSnapshot:
return true
default:
panic("unexpected state")
}
} | |
c174638 | ProgressStateSnapshot && pr.Match >= pr.PendingSnapshot
} | |
c174639 | size
}
if next >= len(in.buffer) {
in.growBuf()
}
in.buffer[next] = inflight
in.count++
} | |
c174640 | make([]uint64, newSize)
copy(newBuffer, in.buffer)
in.buffer = newBuffer
} | |
c174641 | -= size
}
}
// free i inflights and set new start index
in.count -= i
in.start = idx
if in.count == 0 {
// inflights is empty, reset the start index so that we don't grow the
// buffer unnecessarily.
in.start = 0
}
} | |
c174642 |
return n, err
}
fn := s.dbFilePath(id)
if fileutil.Exist(fn) {
os.Remove(f.Name())
return n, nil
}
err = os.Rename(f.Name(), fn)
if err != nil {
os.Remove(f.Name())
return n, err
}
if s.lg != nil {
s.lg.Info(
"saved database snapshot to disk",
zap.String("path", fn),
zap.Int64("bytes", n),
zap.String("size", humanize.Bytes(uint64(n))),
)
} else {
plog.Infof("saved database snapshot to disk [total bytes: %d]", n)
}
snapDBSaveSec.Observe(time.Since(start).Seconds())
return n, nil
} | |
c174643 | "failed to find [SNAPSHOT-INDEX].snap.db",
zap.Uint64("snapshot-index", id),
zap.String("snapshot-file-path", fn),
zap.Error(ErrNoDBSnapshot),
)
}
return "", ErrNoDBSnapshot
} | |
c174644 | := range strings.Split(s, ",") {
us.Values[v] = struct{}{}
}
return nil
} | |
c174645 | != nil {
plog.Panicf("new UniqueStringsValue should never fail: %v", err)
}
return us
} | |
c174646 | (*fs.Lookup(flagName).Value.(*UniqueStringsValue)).stringSlice()
} | |
c174647 | (*fs.Lookup(flagName).Value.(*UniqueStringsValue)).Values
} | |
c174648 | return pctls, percentiles(nums)
} | |
c174649 |
return fmt.Errorf("initial cluster %s has duplicate url", c.InitialPeerURLsMap)
}
if c.InitialPeerURLsMap.String() == "" && c.DiscoveryURL == "" {
return fmt.Errorf("initial cluster unset and no discovery URL found")
}
return nil
} | |
c174650 | cluster %s has duplicate url", c.InitialPeerURLsMap)
}
if c.DiscoveryURL != "" {
return fmt.Errorf("discovery URL should not be set when joining existing initial cluster")
}
return nil
} | |
c174651 | local name %q in the initial cluster configuration", c.Name)
}
return nil
} | |
c174652 | range apMap {
if _, ok := initMap[url]; !ok {
missing = append(missing, url)
}
}
if len(missing) > 0 {
mstr := strings.Join(missing, ",")
umap := types.URLsMap(map[string]types.URLs{c.Name: c.PeerURLs})
return fmt.Errorf("--initial-advertise-peer-urls has %s but missing from --initial-cluster=%s", mstr, umap.String())
}
// resolved URLs from "--initial-advertise-peer-urls" and "--initial-cluster" did not match or failed
apStr := strings.Join(apurls, ",")
umap := types.URLsMap(map[string]types.URLs{c.Name: c.PeerURLs})
return fmt.Errorf("failed to resolve %s to match --initial-cluster=%s (%v)", apStr, umap.String(), err)
} | |
c174653 | possible leader election
return 5*time.Second + 2*time.Duration(c.ElectionTicks*int(c.TickMs))*time.Millisecond
} | |
c174654 |
if s.RaftState == StateLeader {
s.Progress = getProgressCopy(r)
}
return s
} | |
c174655 |
}
sort.Ints(families)
for _, f := range families {
family := uint8(f)
if host, err := chooseHost(family, rmsgs[family]); host != "" || err != nil {
return host, err
}
}
return "", errNoDefaultHost
} | |
c174656 | rerr := binary.Read(buf, cpuutil.ByteOrder(), &ifaddrmsg); rerr != nil {
continue
}
if ifaddrmsg.Index == idx {
return &m, nil
}
}
return nil, fmt.Errorf("could not find address for interface index %v", idx)
} | |
c174657 |
for _, m := range msgs {
if m.Header.Type != syscall.RTM_NEWLINK {
continue
}
buf := bytes.NewBuffer(m.Data[:syscall.SizeofIfInfomsg])
if rerr := binary.Read(buf, cpuutil.ByteOrder(), &ifinfomsg); rerr != nil {
continue
}
if ifinfomsg.Index == int32(idx) {
return &m, nil
}
}
return nil, fmt.Errorf("could not find link for interface index %v", idx)
} | |
c174658 | quorum := c.Bool("quorum")
ctx, cancel := contextWithTotalTimeout(c)
resp, err := ki.Get(ctx, key, &client.GetOptions{Sort: sort, Recursive: recursive, Quorum: quorum})
cancel()
if err != nil {
handleError(c, ExitServerError, err)
}
printLs(c, resp)
} | |
c174659 | }
} else {
// user wants JSON or extended output
printResponseKey(resp, c.GlobalString("output"))
}
} | |
c174660 | n.Key))
} else {
fmt.Println(n.Key)
}
for _, node := range n.Nodes {
rPrint(c, node)
}
} | |
c174661 | runLeaseRenewerFunc,
}
cmd.Flags().Int64Var(&leaseTTL, "ttl", 5, "lease's ttl")
return cmd
} | |
c174662 | ErrEmptySnapshot
}
crc := crc32.Update(0, crcTable, serializedSnap.Data)
if crc != serializedSnap.Crc {
if lg != nil {
lg.Warn("snap file is corrupt",
zap.String("path", snapname),
zap.Uint32("prev-crc", serializedSnap.Crc),
zap.Uint32("new-crc", crc),
)
} else {
plog.Errorf("corrupted snapshot file %v: crc mismatch", snapname)
}
return nil, ErrCRCMismatch
}
var snap raftpb.Snapshot
if err = snap.Unmarshal(serializedSnap.Data); err != nil {
if lg != nil {
lg.Warn("failed to unmarshal raftpb.Snapshot", zap.String("path", snapname), zap.Error(err))
} else {
plog.Errorf("corrupted snapshot file %v: %v", snapname, err)
}
return nil, err
}
return &snap, nil
} | |
c174663 | ok := cipherSuites[s]
return v, ok
} | |
c174664 | := ioutil.ReadAll(resp.Body)
if err != nil {
p.picker.unreachable(u)
return err
}
err = checkPostResponse(resp, b, req, p.peerID)
if err != nil {
p.picker.unreachable(u)
// errMemberRemoved is a critical error since a removed member should
// always be stopped. So we use reportCriticalError to report it to errorc.
if err == errMemberRemoved {
reportCriticalError(err, p.errorc)
}
return err
}
return nil
} | |
c174665 | panic(fmt.Sprintf("term should be set when sending %s", m.Type))
}
} else {
if m.Term != 0 {
panic(fmt.Sprintf("term should not be set when sending %s (was %d)", m.Type, m.Term))
}
// do not attach term to MsgProp, MsgReadIndex
// proposals are a way to forward to the leader and
// should be treated as local message.
// MsgReadIndex is also forwarded to leader.
if m.Type != pb.MsgProp && m.Type != pb.MsgReadIndex {
m.Term = r.Term
}
}
r.msgs = append(r.msgs, m)
} | |
c174666 | // or it might not have all the committed entries.
// The leader MUST NOT forward the follower's commit to
// an unmatched index.
commit := min(r.getProgress(to).Match, r.raftLog.committed)
m := pb.Message{
To: to,
Type: pb.MsgHeartbeat,
Commit: commit,
Context: ctx,
}
r.send(m)
} | |
c174667 | r.id {
return
}
r.sendAppend(id)
})
} | |
c174668 |
} else {
r.bcastHeartbeatWithCtx([]byte(lastCtx))
}
} | |
c174669 | && r.pastElectionTimeout() {
r.electionElapsed = 0
r.Step(pb.Message{From: r.id, Type: pb.MsgHup})
}
} | |
c174670 | && r.leadTransferee != None {
r.abortLeaderTransfer()
}
}
if r.state != StateLeader {
return
}
if r.heartbeatElapsed >= r.heartbeatTimeout {
r.heartbeatElapsed = 0
r.Step(pb.Message{From: r.id, Type: pb.MsgBeat})
}
} | |
c174671 | case pb.MsgHeartbeat:
r.becomeFollower(m.Term, m.From) // always m.Term == r.Term
r.handleHeartbeat(m)
case pb.MsgSnap:
r.becomeFollower(m.Term, m.From) // always m.Term == r.Term
r.handleSnapshot(m)
case myVoteRespType:
gr := r.poll(m.From, m.Type, !m.Reject)
r.logger.Infof("%x [quorum:%d] has received %d %s votes and %d vote rejections", r.id, r.quorum(), gr, m.Type, len(r.votes)-gr)
switch r.quorum() {
case gr:
if r.state == StatePreCandidate {
r.campaign(campaignElection)
} else {
r.becomeLeader()
r.bcastAppend()
}
case len(r.votes) - gr:
// pb.MsgPreVoteResp contains future term of pre-candidate
// m.Term > r.Term; reuse r.Term
r.becomeFollower(r.Term, None)
}
case pb.MsgTimeoutNow:
r.logger.Debugf("%x [term %d state %v] ignored MsgTimeoutNow from %x", r.id, r.Term, r.state, m.From)
}
return nil
} | |
c174672 | if !r.isLearner {
for _, id := range s.Metadata.ConfState.Learners {
if id == r.id {
r.logger.Errorf("%x can't become learner when restores snapshot [index: %d, term: %d]", r.id, s.Metadata.Index, s.Metadata.Term)
return false
}
}
}
r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] starts to restore snapshot [index: %d, term: %d]",
r.id, r.raftLog.committed, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
r.raftLog.restore(s)
r.prs = make(map[uint64]*Progress)
r.learnerPrs = make(map[uint64]*Progress)
r.restoreNode(s.Metadata.ConfState.Nodes, false)
r.restoreNode(s.Metadata.ConfState.Learners, true)
return true
} | |
c174673 | ok := r.prs[r.id]
return ok
} | |
c174674 | }
if pr.RecentActive && !pr.IsLearner {
act++
}
pr.RecentActive = false
})
return act >= r.quorum()
} | |
c174675 | // proposal. Otherwise, limit the size of the uncommitted tail of the
// log and drop any proposal that would push the size over the limit.
return false
}
r.uncommittedSize += s
return true
} | |
c174676 |
s += uint64(PayloadSize(e))
}
if s > r.uncommittedSize {
// uncommittedSize may underestimate the size of the uncommitted Raft
// log tail but will never overestimate it. Saturate at 0 instead of
// allowing overflow.
r.uncommittedSize = 0
} else {
r.uncommittedSize -= s
}
} | |
c174677 | revs: make([]int64, 0),
}
pc.ctx, pc.cancel = context.WithCancel(context.Background())
return pc
} | |
c174678 | = true
pc.mu.Unlock()
} | |
c174679 | = false
pc.mu.Unlock()
} | |
c174680 | // if no key on prefix / the minimum rev is key, already hold the lock
ownerKey := resp.Responses[1].GetResponseRange().Kvs
if len(ownerKey) == 0 || ownerKey[0].CreateRevision == m.myRev {
m.hdr = resp.Header
return nil
}
// wait for deletion revisions prior to myKey
hdr, werr := waitDeletes(ctx, client, m.pfx, m.myRev-1)
// release lock key if wait failed
if werr != nil {
m.Unlock(client.Ctx())
} else {
m.hdr = hdr
}
return werr
} | |
c174681 | &lockerMutex{NewMutex(s, pfx)}
} | |
c174682 | f.ctx, f.cancel = context.WithCancel(context.Background())
go f.run()
return f
} | |
c174683 | case f.resume <- struct{}{}:
default:
}
}
f.pendings = append(f.pendings, j)
} | |
c174684 | = nil
f.mu.Unlock()
<-f.donec
} | |
c174685 | rpcpb.Operation_NOT_STARTED,
advertiseClientPortToProxy: make(map[int]proxy.Server),
advertisePeerPortToProxy: make(map[int]proxy.Server),
}
} | |
c174686 | rpcpb.RegisterTransportServer(srv.grpcServer, srv)
srv.lg.Info(
"gRPC server started",
zap.String("address", srv.address),
zap.String("listener-address", srv.ln.Addr().String()),
)
err = srv.grpcServer.Serve(srv.ln)
if err != nil && strings.Contains(err.Error(), "use of closed network connection") {
srv.lg.Info(
"gRPC server is shut down",
zap.String("address", srv.address),
zap.Error(err),
)
} else {
srv.lg.Warn(
"gRPC server returned with error",
zap.String("address", srv.address),
zap.Error(err),
)
}
return err
} | |
c174687 | srv.lg.Info("gRPC server stopped", zap.String("address", srv.address))
} | |
c174688 | }
if req.Tester != nil {
srv.Tester = req.Tester
}
var resp *rpcpb.Response
resp, err = srv.handleTesterRequest(req)
if err != nil {
errc <- err
// TODO: handle error and retry
return
}
if err = stream.Send(resp); err != nil {
errc <- err
// TODO: handle error and retry
return
}
}
}()
select {
case err = <-errc:
case <-stream.Context().Done():
err = stream.Context().Err()
}
return err
} | |
c174689 | interruptHandlers = append(interruptHandlers, h)
} | |
c174690 | for _, h := range ihs {
h()
}
signal.Stop(notifier)
pid := syscall.Getpid()
// exit directly if it is the "init" process, since the kernel will not help to kill pid 1.
if pid == 1 {
os.Exit(0)
}
setDflSignal(sig.(syscall.Signal))
syscall.Kill(pid, sig.(syscall.Signal))
}()
} | |
c174691 | be set at the same time, choose one")
}
ret := Op{t: tRange, key: []byte(key)}
ret.applyOpts(opts)
return ret
} | |
c174692 |
panic("unexpected countOnly in delete")
case ret.minModRev != 0, ret.maxModRev != 0:
panic("unexpected mod revision filter in delete")
case ret.minCreateRev != 0, ret.maxCreateRev != 0:
panic("unexpected create revision filter in delete")
case ret.filterDelete, ret.filterPut:
panic("unexpected filter in delete")
case ret.createdNotify:
panic("unexpected createdNotify in delete")
}
return ret
} | |
c174693 | put")
case ret.minCreateRev != 0, ret.maxCreateRev != 0:
panic("unexpected create revision filter in put")
case ret.filterDelete, ret.filterPut:
panic("unexpected filter in put")
case ret.createdNotify:
panic("unexpected createdNotify in put")
}
return ret
} | |
c174694 | Op {
return Op{t: tTxn, cmps: cmps, thenOps: thenOps, elseOps: elseOps}
} | |
c174695 | op.key = []byte{0}
}
op.end = []byte("\x00")
}
} | |
c174696 | WithSort(target, order), WithLimit(1)}
} | |
c174697 | != nil {
return false
}
return len(names) != 0
} | |
c174698 | {
if lg != nil {
lg.Panic("failed to parse WAL file name", zap.String("path", name), zap.Error(err))
} else {
plog.Panicf("parse correct name should never fail: %v", err)
}
}
if index >= curIndex {
return i, true
}
}
return -1, false
} | |
c174699 | plog.Panicf("parse correct name should never fail: %v", err)
}
}
if lastSeq != 0 && lastSeq != curSeq-1 {
return false
}
lastSeq = curSeq
}
return true
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.