repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
etcd-io/etcd | clientv3/concurrency/stm.go | NewSTM | func NewSTM(c *v3.Client, apply func(STM) error, so ...stmOption) (*v3.TxnResponse, error) {
opts := &stmOptions{ctx: c.Ctx()}
for _, f := range so {
f(opts)
}
if len(opts.prefetch) != 0 {
f := apply
apply = func(s STM) error {
s.Get(opts.prefetch...)
return f(s)
}
}
return runSTM(mkSTM(c, opts), apply)
} | go | func NewSTM(c *v3.Client, apply func(STM) error, so ...stmOption) (*v3.TxnResponse, error) {
opts := &stmOptions{ctx: c.Ctx()}
for _, f := range so {
f(opts)
}
if len(opts.prefetch) != 0 {
f := apply
apply = func(s STM) error {
s.Get(opts.prefetch...)
return f(s)
}
}
return runSTM(mkSTM(c, opts), apply)
} | [
"func",
"NewSTM",
"(",
"c",
"*",
"v3",
".",
"Client",
",",
"apply",
"func",
"(",
"STM",
")",
"error",
",",
"so",
"...",
"stmOption",
")",
"(",
"*",
"v3",
".",
"TxnResponse",
",",
"error",
")",
"{",
"opts",
":=",
"&",
"stmOptions",
"{",
"ctx",
":"... | // NewSTM initiates a new STM instance, using serializable snapshot isolation by default. | [
"NewSTM",
"initiates",
"a",
"new",
"STM",
"instance",
"using",
"serializable",
"snapshot",
"isolation",
"by",
"default",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/concurrency/stm.go#L89-L102 | test |
etcd-io/etcd | clientv3/concurrency/stm.go | first | func (rs readSet) first() int64 {
ret := int64(math.MaxInt64 - 1)
for _, resp := range rs {
if rev := resp.Header.Revision; rev < ret {
ret = rev
}
}
return ret
} | go | func (rs readSet) first() int64 {
ret := int64(math.MaxInt64 - 1)
for _, resp := range rs {
if rev := resp.Header.Revision; rev < ret {
ret = rev
}
}
return ret
} | [
"func",
"(",
"rs",
"readSet",
")",
"first",
"(",
")",
"int64",
"{",
"ret",
":=",
"int64",
"(",
"math",
".",
"MaxInt64",
"-",
"1",
")",
"\n",
"for",
"_",
",",
"resp",
":=",
"range",
"rs",
"{",
"if",
"rev",
":=",
"resp",
".",
"Header",
".",
"Revi... | // first returns the store revision from the first fetch | [
"first",
"returns",
"the",
"store",
"revision",
"from",
"the",
"first",
"fetch"
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/concurrency/stm.go#L197-L205 | test |
etcd-io/etcd | clientv3/concurrency/stm.go | cmps | func (ws writeSet) cmps(rev int64) []v3.Cmp {
cmps := make([]v3.Cmp, 0, len(ws))
for key := range ws {
cmps = append(cmps, v3.Compare(v3.ModRevision(key), "<", rev))
}
return cmps
} | go | func (ws writeSet) cmps(rev int64) []v3.Cmp {
cmps := make([]v3.Cmp, 0, len(ws))
for key := range ws {
cmps = append(cmps, v3.Compare(v3.ModRevision(key), "<", rev))
}
return cmps
} | [
"func",
"(",
"ws",
"writeSet",
")",
"cmps",
"(",
"rev",
"int64",
")",
"[",
"]",
"v3",
".",
"Cmp",
"{",
"cmps",
":=",
"make",
"(",
"[",
"]",
"v3",
".",
"Cmp",
",",
"0",
",",
"len",
"(",
"ws",
")",
")",
"\n",
"for",
"key",
":=",
"range",
"ws"... | // cmps returns a cmp list testing no writes have happened past rev | [
"cmps",
"returns",
"a",
"cmp",
"list",
"testing",
"no",
"writes",
"have",
"happened",
"past",
"rev"
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/concurrency/stm.go#L228-L234 | test |
etcd-io/etcd | clientv3/concurrency/stm.go | NewSTMRepeatable | func NewSTMRepeatable(ctx context.Context, c *v3.Client, apply func(STM) error) (*v3.TxnResponse, error) {
return NewSTM(c, apply, WithAbortContext(ctx), WithIsolation(RepeatableReads))
} | go | func NewSTMRepeatable(ctx context.Context, c *v3.Client, apply func(STM) error) (*v3.TxnResponse, error) {
return NewSTM(c, apply, WithAbortContext(ctx), WithIsolation(RepeatableReads))
} | [
"func",
"NewSTMRepeatable",
"(",
"ctx",
"context",
".",
"Context",
",",
"c",
"*",
"v3",
".",
"Client",
",",
"apply",
"func",
"(",
"STM",
")",
"error",
")",
"(",
"*",
"v3",
".",
"TxnResponse",
",",
"error",
")",
"{",
"return",
"NewSTM",
"(",
"c",
",... | // NewSTMRepeatable is deprecated. | [
"NewSTMRepeatable",
"is",
"deprecated",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/concurrency/stm.go#L375-L377 | test |
etcd-io/etcd | clientv3/concurrency/stm.go | NewSTMSerializable | func NewSTMSerializable(ctx context.Context, c *v3.Client, apply func(STM) error) (*v3.TxnResponse, error) {
return NewSTM(c, apply, WithAbortContext(ctx), WithIsolation(Serializable))
} | go | func NewSTMSerializable(ctx context.Context, c *v3.Client, apply func(STM) error) (*v3.TxnResponse, error) {
return NewSTM(c, apply, WithAbortContext(ctx), WithIsolation(Serializable))
} | [
"func",
"NewSTMSerializable",
"(",
"ctx",
"context",
".",
"Context",
",",
"c",
"*",
"v3",
".",
"Client",
",",
"apply",
"func",
"(",
"STM",
")",
"error",
")",
"(",
"*",
"v3",
".",
"TxnResponse",
",",
"error",
")",
"{",
"return",
"NewSTM",
"(",
"c",
... | // NewSTMSerializable is deprecated. | [
"NewSTMSerializable",
"is",
"deprecated",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/concurrency/stm.go#L380-L382 | test |
etcd-io/etcd | clientv3/concurrency/stm.go | NewSTMReadCommitted | func NewSTMReadCommitted(ctx context.Context, c *v3.Client, apply func(STM) error) (*v3.TxnResponse, error) {
return NewSTM(c, apply, WithAbortContext(ctx), WithIsolation(ReadCommitted))
} | go | func NewSTMReadCommitted(ctx context.Context, c *v3.Client, apply func(STM) error) (*v3.TxnResponse, error) {
return NewSTM(c, apply, WithAbortContext(ctx), WithIsolation(ReadCommitted))
} | [
"func",
"NewSTMReadCommitted",
"(",
"ctx",
"context",
".",
"Context",
",",
"c",
"*",
"v3",
".",
"Client",
",",
"apply",
"func",
"(",
"STM",
")",
"error",
")",
"(",
"*",
"v3",
".",
"TxnResponse",
",",
"error",
")",
"{",
"return",
"NewSTM",
"(",
"c",
... | // NewSTMReadCommitted is deprecated. | [
"NewSTMReadCommitted",
"is",
"deprecated",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/concurrency/stm.go#L385-L387 | test |
etcd-io/etcd | pkg/tlsutil/tlsutil.go | NewCertPool | func NewCertPool(CAFiles []string) (*x509.CertPool, error) {
certPool := x509.NewCertPool()
for _, CAFile := range CAFiles {
pemByte, err := ioutil.ReadFile(CAFile)
if err != nil {
return nil, err
}
for {
var block *pem.Block
block, pemByte = pem.Decode(pemByte)
if block == nil {
break
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, err
}
certPool.AddCert(cert)
}
}
return certPool, nil
} | go | func NewCertPool(CAFiles []string) (*x509.CertPool, error) {
certPool := x509.NewCertPool()
for _, CAFile := range CAFiles {
pemByte, err := ioutil.ReadFile(CAFile)
if err != nil {
return nil, err
}
for {
var block *pem.Block
block, pemByte = pem.Decode(pemByte)
if block == nil {
break
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, err
}
certPool.AddCert(cert)
}
}
return certPool, nil
} | [
"func",
"NewCertPool",
"(",
"CAFiles",
"[",
"]",
"string",
")",
"(",
"*",
"x509",
".",
"CertPool",
",",
"error",
")",
"{",
"certPool",
":=",
"x509",
".",
"NewCertPool",
"(",
")",
"\n",
"for",
"_",
",",
"CAFile",
":=",
"range",
"CAFiles",
"{",
"pemByt... | // NewCertPool creates x509 certPool with provided CA files. | [
"NewCertPool",
"creates",
"x509",
"certPool",
"with",
"provided",
"CA",
"files",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/tlsutil/tlsutil.go#L25-L50 | test |
etcd-io/etcd | pkg/tlsutil/tlsutil.go | NewCert | func NewCert(certfile, keyfile string, parseFunc func([]byte, []byte) (tls.Certificate, error)) (*tls.Certificate, error) {
cert, err := ioutil.ReadFile(certfile)
if err != nil {
return nil, err
}
key, err := ioutil.ReadFile(keyfile)
if err != nil {
return nil, err
}
if parseFunc == nil {
parseFunc = tls.X509KeyPair
}
tlsCert, err := parseFunc(cert, key)
if err != nil {
return nil, err
}
return &tlsCert, nil
} | go | func NewCert(certfile, keyfile string, parseFunc func([]byte, []byte) (tls.Certificate, error)) (*tls.Certificate, error) {
cert, err := ioutil.ReadFile(certfile)
if err != nil {
return nil, err
}
key, err := ioutil.ReadFile(keyfile)
if err != nil {
return nil, err
}
if parseFunc == nil {
parseFunc = tls.X509KeyPair
}
tlsCert, err := parseFunc(cert, key)
if err != nil {
return nil, err
}
return &tlsCert, nil
} | [
"func",
"NewCert",
"(",
"certfile",
",",
"keyfile",
"string",
",",
"parseFunc",
"func",
"(",
"[",
"]",
"byte",
",",
"[",
"]",
"byte",
")",
"(",
"tls",
".",
"Certificate",
",",
"error",
")",
")",
"(",
"*",
"tls",
".",
"Certificate",
",",
"error",
")... | // NewCert generates TLS cert by using the given cert,key and parse function. | [
"NewCert",
"generates",
"TLS",
"cert",
"by",
"using",
"the",
"given",
"cert",
"key",
"and",
"parse",
"function",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/tlsutil/tlsutil.go#L53-L73 | test |
etcd-io/etcd | etcdserver/api/rafthttp/peer.go | Pause | func (p *peer) Pause() {
p.mu.Lock()
defer p.mu.Unlock()
p.paused = true
p.msgAppReader.pause()
p.msgAppV2Reader.pause()
} | go | func (p *peer) Pause() {
p.mu.Lock()
defer p.mu.Unlock()
p.paused = true
p.msgAppReader.pause()
p.msgAppV2Reader.pause()
} | [
"func",
"(",
"p",
"*",
"peer",
")",
"Pause",
"(",
")",
"{",
"p",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"p",
".",
"paused",
"=",
"true",
"\n",
"p",
".",
"msgAppReader",
".",
"pause",
... | // Pause pauses the peer. The peer will simply drops all incoming
// messages without returning an error. | [
"Pause",
"pauses",
"the",
"peer",
".",
"The",
"peer",
"will",
"simply",
"drops",
"all",
"incoming",
"messages",
"without",
"returning",
"an",
"error",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/rafthttp/peer.go#L314-L320 | test |
etcd-io/etcd | etcdserver/api/rafthttp/peer.go | Resume | func (p *peer) Resume() {
p.mu.Lock()
defer p.mu.Unlock()
p.paused = false
p.msgAppReader.resume()
p.msgAppV2Reader.resume()
} | go | func (p *peer) Resume() {
p.mu.Lock()
defer p.mu.Unlock()
p.paused = false
p.msgAppReader.resume()
p.msgAppV2Reader.resume()
} | [
"func",
"(",
"p",
"*",
"peer",
")",
"Resume",
"(",
")",
"{",
"p",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"p",
".",
"paused",
"=",
"false",
"\n",
"p",
".",
"msgAppReader",
".",
"resume",... | // Resume resumes a paused peer. | [
"Resume",
"resumes",
"a",
"paused",
"peer",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/rafthttp/peer.go#L323-L329 | test |
etcd-io/etcd | etcdserver/api/rafthttp/peer.go | pick | func (p *peer) pick(m raftpb.Message) (writec chan<- raftpb.Message, picked string) {
var ok bool
// Considering MsgSnap may have a big size, e.g., 1G, and will block
// stream for a long time, only use one of the N pipelines to send MsgSnap.
if isMsgSnap(m) {
return p.pipeline.msgc, pipelineMsg
} 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
} | go | func (p *peer) pick(m raftpb.Message) (writec chan<- raftpb.Message, picked string) {
var ok bool
// Considering MsgSnap may have a big size, e.g., 1G, and will block
// stream for a long time, only use one of the N pipelines to send MsgSnap.
if isMsgSnap(m) {
return p.pipeline.msgc, pipelineMsg
} 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
} | [
"func",
"(",
"p",
"*",
"peer",
")",
"pick",
"(",
"m",
"raftpb",
".",
"Message",
")",
"(",
"writec",
"chan",
"<-",
"raftpb",
".",
"Message",
",",
"picked",
"string",
")",
"{",
"var",
"ok",
"bool",
"\n",
"if",
"isMsgSnap",
"(",
"m",
")",
"{",
"retu... | // pick picks a chan for sending the given message. The picked chan and the picked chan
// string name are returned. | [
"pick",
"picks",
"a",
"chan",
"for",
"sending",
"the",
"given",
"message",
".",
"The",
"picked",
"chan",
"and",
"the",
"picked",
"chan",
"string",
"name",
"are",
"returned",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/rafthttp/peer.go#L358-L370 | test |
etcd-io/etcd | etcdserver/api/rafthttp/snapshot_sender.go | post | func (s *snapshotSender) post(req *http.Request) (err error) {
ctx, cancel := context.WithCancel(context.Background())
req = req.WithContext(ctx)
defer cancel()
type responseAndError struct {
resp *http.Response
body []byte
err error
}
result := make(chan responseAndError, 1)
go func() {
resp, err := s.tr.pipelineRt.RoundTrip(req)
if err != nil {
result <- responseAndError{resp, nil, err}
return
}
// close the response body when timeouts.
// prevents from reading the body forever when the other side dies right 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)
}
} | go | func (s *snapshotSender) post(req *http.Request) (err error) {
ctx, cancel := context.WithCancel(context.Background())
req = req.WithContext(ctx)
defer cancel()
type responseAndError struct {
resp *http.Response
body []byte
err error
}
result := make(chan responseAndError, 1)
go func() {
resp, err := s.tr.pipelineRt.RoundTrip(req)
if err != nil {
result <- responseAndError{resp, nil, err}
return
}
// close the response body when timeouts.
// prevents from reading the body forever when the other side dies right 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)
}
} | [
"func",
"(",
"s",
"*",
"snapshotSender",
")",
"post",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"err",
"error",
")",
"{",
"ctx",
",",
"cancel",
":=",
"context",
".",
"WithCancel",
"(",
"context",
".",
"Background",
"(",
")",
")",
"\n",
"re... | // post posts the given request.
// It returns nil when request is sent out and processed successfully. | [
"post",
"posts",
"the",
"given",
"request",
".",
"It",
"returns",
"nil",
"when",
"request",
"is",
"sent",
"out",
"and",
"processed",
"successfully",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/rafthttp/snapshot_sender.go#L149-L185 | test |
etcd-io/etcd | etcdserver/apply.go | newTxnResp | func newTxnResp(rt *pb.TxnRequest, txnPath []bool) (txnResp *pb.TxnResponse, txnCount int) {
reqs := rt.Success
if !txnPath[0] {
reqs = rt.Failure
}
resps := make([]*pb.ResponseOp, len(reqs))
txnResp = &pb.TxnResponse{
Responses: resps,
Succeeded: txnPath[0],
Header: &pb.ResponseHeader{},
}
for i, req := range reqs {
switch tv := req.Request.(type) {
case *pb.RequestOp_RequestRange:
resps[i] = &pb.ResponseOp{Response: &pb.ResponseOp_ResponseRange{}}
case *pb.RequestOp_RequestPut:
resps[i] = &pb.ResponseOp{Response: &pb.ResponseOp_ResponsePut{}}
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
} | go | func newTxnResp(rt *pb.TxnRequest, txnPath []bool) (txnResp *pb.TxnResponse, txnCount int) {
reqs := rt.Success
if !txnPath[0] {
reqs = rt.Failure
}
resps := make([]*pb.ResponseOp, len(reqs))
txnResp = &pb.TxnResponse{
Responses: resps,
Succeeded: txnPath[0],
Header: &pb.ResponseHeader{},
}
for i, req := range reqs {
switch tv := req.Request.(type) {
case *pb.RequestOp_RequestRange:
resps[i] = &pb.ResponseOp{Response: &pb.ResponseOp_ResponseRange{}}
case *pb.RequestOp_RequestPut:
resps[i] = &pb.ResponseOp{Response: &pb.ResponseOp_ResponsePut{}}
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
} | [
"func",
"newTxnResp",
"(",
"rt",
"*",
"pb",
".",
"TxnRequest",
",",
"txnPath",
"[",
"]",
"bool",
")",
"(",
"txnResp",
"*",
"pb",
".",
"TxnResponse",
",",
"txnCount",
"int",
")",
"{",
"reqs",
":=",
"rt",
".",
"Success",
"\n",
"if",
"!",
"txnPath",
"... | // newTxnResp allocates a txn response for a txn request given a path. | [
"newTxnResp",
"allocates",
"a",
"txn",
"response",
"for",
"a",
"txn",
"request",
"given",
"a",
"path",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/apply.go#L381-L409 | test |
etcd-io/etcd | etcdserver/apply.go | applyCompare | func applyCompare(rv mvcc.ReadView, c *pb.Compare) bool {
// TODO: possible optimizations
// * chunk reads for large ranges to conserve memory
// * rewrite rules for common patterns:
// ex. "[a, b) createrev > 0" => "limit 1 /\ kvs > 0"
// * caching
rr, err := rv.Range(c.Key, mkGteRange(c.RangeEnd), mvcc.RangeOptions{})
if err != nil {
return false
}
if len(rr.KVs) == 0 {
if c.Target == pb.Compare_VALUE {
// Always fail if comparing a value 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
} | go | func applyCompare(rv mvcc.ReadView, c *pb.Compare) bool {
// TODO: possible optimizations
// * chunk reads for large ranges to conserve memory
// * rewrite rules for common patterns:
// ex. "[a, b) createrev > 0" => "limit 1 /\ kvs > 0"
// * caching
rr, err := rv.Range(c.Key, mkGteRange(c.RangeEnd), mvcc.RangeOptions{})
if err != nil {
return false
}
if len(rr.KVs) == 0 {
if c.Target == pb.Compare_VALUE {
// Always fail if comparing a value 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
} | [
"func",
"applyCompare",
"(",
"rv",
"mvcc",
".",
"ReadView",
",",
"c",
"*",
"pb",
".",
"Compare",
")",
"bool",
"{",
"rr",
",",
"err",
":=",
"rv",
".",
"Range",
"(",
"c",
".",
"Key",
",",
"mkGteRange",
"(",
"c",
".",
"RangeEnd",
")",
",",
"mvcc",
... | // applyCompare applies the compare request.
// If the comparison succeeds, it returns true. Otherwise, returns false. | [
"applyCompare",
"applies",
"the",
"compare",
"request",
".",
"If",
"the",
"comparison",
"succeeds",
"it",
"returns",
"true",
".",
"Otherwise",
"returns",
"false",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/apply.go#L438-L462 | test |
etcd-io/etcd | clientv3/compact_op.go | OpCompact | func OpCompact(rev int64, opts ...CompactOption) CompactOp {
ret := CompactOp{revision: rev}
ret.applyCompactOpts(opts)
return ret
} | go | func OpCompact(rev int64, opts ...CompactOption) CompactOp {
ret := CompactOp{revision: rev}
ret.applyCompactOpts(opts)
return ret
} | [
"func",
"OpCompact",
"(",
"rev",
"int64",
",",
"opts",
"...",
"CompactOption",
")",
"CompactOp",
"{",
"ret",
":=",
"CompactOp",
"{",
"revision",
":",
"rev",
"}",
"\n",
"ret",
".",
"applyCompactOpts",
"(",
"opts",
")",
"\n",
"return",
"ret",
"\n",
"}"
] | // OpCompact wraps slice CompactOption to create a CompactOp. | [
"OpCompact",
"wraps",
"slice",
"CompactOption",
"to",
"create",
"a",
"CompactOp",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/compact_op.go#L37-L41 | test |
etcd-io/etcd | contrib/recipes/priority_queue.go | NewPriorityQueue | func NewPriorityQueue(client *v3.Client, key string) *PriorityQueue {
return &PriorityQueue{client, context.TODO(), key + "/"}
} | go | func NewPriorityQueue(client *v3.Client, key string) *PriorityQueue {
return &PriorityQueue{client, context.TODO(), key + "/"}
} | [
"func",
"NewPriorityQueue",
"(",
"client",
"*",
"v3",
".",
"Client",
",",
"key",
"string",
")",
"*",
"PriorityQueue",
"{",
"return",
"&",
"PriorityQueue",
"{",
"client",
",",
"context",
".",
"TODO",
"(",
")",
",",
"key",
"+",
"\"/\"",
"}",
"\n",
"}"
] | // NewPriorityQueue creates an etcd priority queue. | [
"NewPriorityQueue",
"creates",
"an",
"etcd",
"priority",
"queue",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/contrib/recipes/priority_queue.go#L33-L35 | test |
etcd-io/etcd | contrib/recipes/priority_queue.go | Enqueue | func (q *PriorityQueue) Enqueue(val string, pr uint16) error {
prefix := fmt.Sprintf("%s%05d", q.key, pr)
_, err := newSequentialKV(q.client, prefix, val)
return err
} | go | func (q *PriorityQueue) Enqueue(val string, pr uint16) error {
prefix := fmt.Sprintf("%s%05d", q.key, pr)
_, err := newSequentialKV(q.client, prefix, val)
return err
} | [
"func",
"(",
"q",
"*",
"PriorityQueue",
")",
"Enqueue",
"(",
"val",
"string",
",",
"pr",
"uint16",
")",
"error",
"{",
"prefix",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%s%05d\"",
",",
"q",
".",
"key",
",",
"pr",
")",
"\n",
"_",
",",
"err",
":=",
"ne... | // Enqueue puts a value into a queue with a given priority. | [
"Enqueue",
"puts",
"a",
"value",
"into",
"a",
"queue",
"with",
"a",
"given",
"priority",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/contrib/recipes/priority_queue.go#L38-L42 | test |
etcd-io/etcd | etcdserver/api/v2stats/leader.go | NewLeaderStats | func NewLeaderStats(id string) *LeaderStats {
return &LeaderStats{
leaderStats: leaderStats{
Leader: id,
Followers: make(map[string]*FollowerStats),
},
}
} | go | func NewLeaderStats(id string) *LeaderStats {
return &LeaderStats{
leaderStats: leaderStats{
Leader: id,
Followers: make(map[string]*FollowerStats),
},
}
} | [
"func",
"NewLeaderStats",
"(",
"id",
"string",
")",
"*",
"LeaderStats",
"{",
"return",
"&",
"LeaderStats",
"{",
"leaderStats",
":",
"leaderStats",
"{",
"Leader",
":",
"id",
",",
"Followers",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"FollowerStats"... | // NewLeaderStats generates a new LeaderStats with the given id as leader | [
"NewLeaderStats",
"generates",
"a",
"new",
"LeaderStats",
"with",
"the",
"given",
"id",
"as",
"leader"
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2stats/leader.go#L39-L46 | test |
etcd-io/etcd | etcdserver/api/v2stats/leader.go | Succ | func (fs *FollowerStats) Succ(d time.Duration) {
fs.Lock()
defer fs.Unlock()
total := float64(fs.Counts.Success) * fs.Latency.Average
totalSquare := float64(fs.Counts.Success) * fs.Latency.averageSquare
fs.Counts.Success++
fs.Latency.Current = float64(d) / (1000000.0)
if fs.Latency.Current > fs.Latency.Maximum {
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)
} | go | func (fs *FollowerStats) Succ(d time.Duration) {
fs.Lock()
defer fs.Unlock()
total := float64(fs.Counts.Success) * fs.Latency.Average
totalSquare := float64(fs.Counts.Success) * fs.Latency.averageSquare
fs.Counts.Success++
fs.Latency.Current = float64(d) / (1000000.0)
if fs.Latency.Current > fs.Latency.Maximum {
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)
} | [
"func",
"(",
"fs",
"*",
"FollowerStats",
")",
"Succ",
"(",
"d",
"time",
".",
"Duration",
")",
"{",
"fs",
".",
"Lock",
"(",
")",
"\n",
"defer",
"fs",
".",
"Unlock",
"(",
")",
"\n",
"total",
":=",
"float64",
"(",
"fs",
".",
"Counts",
".",
"Success"... | // Succ updates the FollowerStats with a successful send | [
"Succ",
"updates",
"the",
"FollowerStats",
"with",
"a",
"successful",
"send"
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2stats/leader.go#L97-L121 | test |
etcd-io/etcd | etcdserver/api/v2stats/leader.go | Fail | func (fs *FollowerStats) Fail() {
fs.Lock()
defer fs.Unlock()
fs.Counts.Fail++
} | go | func (fs *FollowerStats) Fail() {
fs.Lock()
defer fs.Unlock()
fs.Counts.Fail++
} | [
"func",
"(",
"fs",
"*",
"FollowerStats",
")",
"Fail",
"(",
")",
"{",
"fs",
".",
"Lock",
"(",
")",
"\n",
"defer",
"fs",
".",
"Unlock",
"(",
")",
"\n",
"fs",
".",
"Counts",
".",
"Fail",
"++",
"\n",
"}"
] | // Fail updates the FollowerStats with an unsuccessful send | [
"Fail",
"updates",
"the",
"FollowerStats",
"with",
"an",
"unsuccessful",
"send"
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2stats/leader.go#L124-L128 | test |
etcd-io/etcd | proxy/grpcproxy/watch_broadcasts.go | delete | func (wbs *watchBroadcasts) delete(w *watcher) int {
wbs.mu.Lock()
defer wbs.mu.Unlock()
wb, ok := wbs.watchers[w]
if !ok {
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)
} | go | func (wbs *watchBroadcasts) delete(w *watcher) int {
wbs.mu.Lock()
defer wbs.mu.Unlock()
wb, ok := wbs.watchers[w]
if !ok {
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)
} | [
"func",
"(",
"wbs",
"*",
"watchBroadcasts",
")",
"delete",
"(",
"w",
"*",
"watcher",
")",
"int",
"{",
"wbs",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"wbs",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"wb",
",",
"ok",
":=",
"wbs",
".",
... | // delete removes a watcher and returns the number of remaining watchers. | [
"delete",
"removes",
"a",
"watcher",
"and",
"returns",
"the",
"number",
"of",
"remaining",
"watchers",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/proxy/grpcproxy/watch_broadcasts.go#L102-L117 | test |
etcd-io/etcd | etcdserver/api/rafthttp/stream.go | startStreamWriter | func startStreamWriter(lg *zap.Logger, local, id types.ID, status *peerStatus, fs *stats.FollowerStats, r Raft) *streamWriter {
w := &streamWriter{
lg: lg,
localID: local,
peerID: id,
status: status,
fs: fs,
r: r,
msgc: make(chan raftpb.Message, streamBufSize),
connc: make(chan *outgoingConn),
stopc: make(chan struct{}),
done: make(chan struct{}),
}
go w.run()
return w
} | go | func startStreamWriter(lg *zap.Logger, local, id types.ID, status *peerStatus, fs *stats.FollowerStats, r Raft) *streamWriter {
w := &streamWriter{
lg: lg,
localID: local,
peerID: id,
status: status,
fs: fs,
r: r,
msgc: make(chan raftpb.Message, streamBufSize),
connc: make(chan *outgoingConn),
stopc: make(chan struct{}),
done: make(chan struct{}),
}
go w.run()
return w
} | [
"func",
"startStreamWriter",
"(",
"lg",
"*",
"zap",
".",
"Logger",
",",
"local",
",",
"id",
"types",
".",
"ID",
",",
"status",
"*",
"peerStatus",
",",
"fs",
"*",
"stats",
".",
"FollowerStats",
",",
"r",
"Raft",
")",
"*",
"streamWriter",
"{",
"w",
":=... | // startStreamWriter creates a streamWrite and starts a long running go-routine that accepts
// messages and writes to the attached outgoing connection. | [
"startStreamWriter",
"creates",
"a",
"streamWrite",
"and",
"starts",
"a",
"long",
"running",
"go",
"-",
"routine",
"that",
"accepts",
"messages",
"and",
"writes",
"to",
"the",
"attached",
"outgoing",
"connection",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/rafthttp/stream.go#L132-L149 | test |
etcd-io/etcd | etcdserver/api/rafthttp/stream.go | checkStreamSupport | func checkStreamSupport(v *semver.Version, t streamType) bool {
nv := &semver.Version{Major: v.Major, Minor: v.Minor}
for _, s := range supportedStream[nv.String()] {
if s == t {
return true
}
}
return false
} | go | func checkStreamSupport(v *semver.Version, t streamType) bool {
nv := &semver.Version{Major: v.Major, Minor: v.Minor}
for _, s := range supportedStream[nv.String()] {
if s == t {
return true
}
}
return false
} | [
"func",
"checkStreamSupport",
"(",
"v",
"*",
"semver",
".",
"Version",
",",
"t",
"streamType",
")",
"bool",
"{",
"nv",
":=",
"&",
"semver",
".",
"Version",
"{",
"Major",
":",
"v",
".",
"Major",
",",
"Minor",
":",
"v",
".",
"Minor",
"}",
"\n",
"for"... | // checkStreamSupport checks whether the stream type is supported in the
// given version. | [
"checkStreamSupport",
"checks",
"whether",
"the",
"stream",
"type",
"is",
"supported",
"in",
"the",
"given",
"version",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/rafthttp/stream.go#L738-L746 | test |
etcd-io/etcd | raft/progress.go | maybeUpdate | func (pr *Progress) maybeUpdate(n uint64) bool {
var updated bool
if pr.Match < n {
pr.Match = n
updated = true
pr.resume()
}
if pr.Next < n+1 {
pr.Next = n + 1
}
return updated
} | go | func (pr *Progress) maybeUpdate(n uint64) bool {
var updated bool
if pr.Match < n {
pr.Match = n
updated = true
pr.resume()
}
if pr.Next < n+1 {
pr.Next = n + 1
}
return updated
} | [
"func",
"(",
"pr",
"*",
"Progress",
")",
"maybeUpdate",
"(",
"n",
"uint64",
")",
"bool",
"{",
"var",
"updated",
"bool",
"\n",
"if",
"pr",
".",
"Match",
"<",
"n",
"{",
"pr",
".",
"Match",
"=",
"n",
"\n",
"updated",
"=",
"true",
"\n",
"pr",
".",
... | // maybeUpdate returns false if the given n index comes from an outdated message.
// Otherwise it updates the progress and returns true. | [
"maybeUpdate",
"returns",
"false",
"if",
"the",
"given",
"n",
"index",
"comes",
"from",
"an",
"outdated",
"message",
".",
"Otherwise",
"it",
"updates",
"the",
"progress",
"and",
"returns",
"true",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/progress.go#L118-L129 | test |
etcd-io/etcd | raft/progress.go | IsPaused | func (pr *Progress) IsPaused() bool {
switch pr.State {
case ProgressStateProbe:
return pr.Paused
case ProgressStateReplicate:
return pr.ins.full()
case ProgressStateSnapshot:
return true
default:
panic("unexpected state")
}
} | go | func (pr *Progress) IsPaused() bool {
switch pr.State {
case ProgressStateProbe:
return pr.Paused
case ProgressStateReplicate:
return pr.ins.full()
case ProgressStateSnapshot:
return true
default:
panic("unexpected state")
}
} | [
"func",
"(",
"pr",
"*",
"Progress",
")",
"IsPaused",
"(",
")",
"bool",
"{",
"switch",
"pr",
".",
"State",
"{",
"case",
"ProgressStateProbe",
":",
"return",
"pr",
".",
"Paused",
"\n",
"case",
"ProgressStateReplicate",
":",
"return",
"pr",
".",
"ins",
".",... | // IsPaused returns whether sending log entries to this node has been
// paused. A node may be paused because it has rejected recent
// MsgApps, is currently waiting for a snapshot, or has reached the
// MaxInflightMsgs limit. | [
"IsPaused",
"returns",
"whether",
"sending",
"log",
"entries",
"to",
"this",
"node",
"has",
"been",
"paused",
".",
"A",
"node",
"may",
"be",
"paused",
"because",
"it",
"has",
"rejected",
"recent",
"MsgApps",
"is",
"currently",
"waiting",
"for",
"a",
"snapsho... | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/progress.go#L166-L177 | test |
etcd-io/etcd | raft/progress.go | needSnapshotAbort | func (pr *Progress) needSnapshotAbort() bool {
return pr.State == ProgressStateSnapshot && pr.Match >= pr.PendingSnapshot
} | go | func (pr *Progress) needSnapshotAbort() bool {
return pr.State == ProgressStateSnapshot && pr.Match >= pr.PendingSnapshot
} | [
"func",
"(",
"pr",
"*",
"Progress",
")",
"needSnapshotAbort",
"(",
")",
"bool",
"{",
"return",
"pr",
".",
"State",
"==",
"ProgressStateSnapshot",
"&&",
"pr",
".",
"Match",
">=",
"pr",
".",
"PendingSnapshot",
"\n",
"}"
] | // needSnapshotAbort returns true if snapshot progress's Match
// is equal or higher than the pendingSnapshot. | [
"needSnapshotAbort",
"returns",
"true",
"if",
"snapshot",
"progress",
"s",
"Match",
"is",
"equal",
"or",
"higher",
"than",
"the",
"pendingSnapshot",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/progress.go#L183-L185 | test |
etcd-io/etcd | raft/progress.go | add | func (in *inflights) add(inflight uint64) {
if in.full() {
panic("cannot add into a full inflights")
}
next := in.start + in.count
size := in.size
if next >= size {
next -= size
}
if next >= len(in.buffer) {
in.growBuf()
}
in.buffer[next] = inflight
in.count++
} | go | func (in *inflights) add(inflight uint64) {
if in.full() {
panic("cannot add into a full inflights")
}
next := in.start + in.count
size := in.size
if next >= size {
next -= size
}
if next >= len(in.buffer) {
in.growBuf()
}
in.buffer[next] = inflight
in.count++
} | [
"func",
"(",
"in",
"*",
"inflights",
")",
"add",
"(",
"inflight",
"uint64",
")",
"{",
"if",
"in",
".",
"full",
"(",
")",
"{",
"panic",
"(",
"\"cannot add into a full inflights\"",
")",
"\n",
"}",
"\n",
"next",
":=",
"in",
".",
"start",
"+",
"in",
"."... | // add adds an inflight into inflights | [
"add",
"adds",
"an",
"inflight",
"into",
"inflights"
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/progress.go#L213-L227 | test |
etcd-io/etcd | raft/progress.go | growBuf | func (in *inflights) growBuf() {
newSize := len(in.buffer) * 2
if newSize == 0 {
newSize = 1
} else if newSize > in.size {
newSize = in.size
}
newBuffer := make([]uint64, newSize)
copy(newBuffer, in.buffer)
in.buffer = newBuffer
} | go | func (in *inflights) growBuf() {
newSize := len(in.buffer) * 2
if newSize == 0 {
newSize = 1
} else if newSize > in.size {
newSize = in.size
}
newBuffer := make([]uint64, newSize)
copy(newBuffer, in.buffer)
in.buffer = newBuffer
} | [
"func",
"(",
"in",
"*",
"inflights",
")",
"growBuf",
"(",
")",
"{",
"newSize",
":=",
"len",
"(",
"in",
".",
"buffer",
")",
"*",
"2",
"\n",
"if",
"newSize",
"==",
"0",
"{",
"newSize",
"=",
"1",
"\n",
"}",
"else",
"if",
"newSize",
">",
"in",
".",... | // grow the inflight buffer by doubling up to inflights.size. We grow on demand
// instead of preallocating to inflights.size to handle systems which have
// thousands of Raft groups per process. | [
"grow",
"the",
"inflight",
"buffer",
"by",
"doubling",
"up",
"to",
"inflights",
".",
"size",
".",
"We",
"grow",
"on",
"demand",
"instead",
"of",
"preallocating",
"to",
"inflights",
".",
"size",
"to",
"handle",
"systems",
"which",
"have",
"thousands",
"of",
... | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/progress.go#L232-L242 | test |
etcd-io/etcd | raft/progress.go | freeTo | func (in *inflights) freeTo(to uint64) {
if in.count == 0 || to < in.buffer[in.start] {
// out of the left side of the window
return
}
idx := in.start
var i int
for i = 0; i < in.count; i++ {
if to < in.buffer[idx] { // found the first large inflight
break
}
// increase index and maybe rotate
size := in.size
if idx++; idx >= size {
idx -= 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
}
} | go | func (in *inflights) freeTo(to uint64) {
if in.count == 0 || to < in.buffer[in.start] {
// out of the left side of the window
return
}
idx := in.start
var i int
for i = 0; i < in.count; i++ {
if to < in.buffer[idx] { // found the first large inflight
break
}
// increase index and maybe rotate
size := in.size
if idx++; idx >= size {
idx -= 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
}
} | [
"func",
"(",
"in",
"*",
"inflights",
")",
"freeTo",
"(",
"to",
"uint64",
")",
"{",
"if",
"in",
".",
"count",
"==",
"0",
"||",
"to",
"<",
"in",
".",
"buffer",
"[",
"in",
".",
"start",
"]",
"{",
"return",
"\n",
"}",
"\n",
"idx",
":=",
"in",
"."... | // freeTo frees the inflights smaller or equal to the given `to` flight. | [
"freeTo",
"frees",
"the",
"inflights",
"smaller",
"or",
"equal",
"to",
"the",
"given",
"to",
"flight",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/progress.go#L245-L272 | test |
etcd-io/etcd | etcdserver/api/snap/db.go | SaveDBFrom | func (s *Snapshotter) SaveDBFrom(r io.Reader, id uint64) (int64, error) {
start := time.Now()
f, err := ioutil.TempFile(s.dir, "tmp")
if err != nil {
return 0, err
}
var n int64
n, err = io.Copy(f, r)
if err == nil {
fsyncStart := time.Now()
err = fileutil.Fsync(f)
snapDBFsyncSec.Observe(time.Since(fsyncStart).Seconds())
}
f.Close()
if err != nil {
os.Remove(f.Name())
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
} | go | func (s *Snapshotter) SaveDBFrom(r io.Reader, id uint64) (int64, error) {
start := time.Now()
f, err := ioutil.TempFile(s.dir, "tmp")
if err != nil {
return 0, err
}
var n int64
n, err = io.Copy(f, r)
if err == nil {
fsyncStart := time.Now()
err = fileutil.Fsync(f)
snapDBFsyncSec.Observe(time.Since(fsyncStart).Seconds())
}
f.Close()
if err != nil {
os.Remove(f.Name())
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
} | [
"func",
"(",
"s",
"*",
"Snapshotter",
")",
"SaveDBFrom",
"(",
"r",
"io",
".",
"Reader",
",",
"id",
"uint64",
")",
"(",
"int64",
",",
"error",
")",
"{",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"f",
",",
"err",
":=",
"ioutil",
".",
"Te... | // SaveDBFrom saves snapshot of the database from the given reader. It
// guarantees the save operation is atomic. | [
"SaveDBFrom",
"saves",
"snapshot",
"of",
"the",
"database",
"from",
"the",
"given",
"reader",
".",
"It",
"guarantees",
"the",
"save",
"operation",
"is",
"atomic",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/snap/db.go#L36-L79 | test |
etcd-io/etcd | etcdserver/api/snap/db.go | DBFilePath | func (s *Snapshotter) DBFilePath(id uint64) (string, error) {
if _, err := fileutil.ReadDir(s.dir); err != nil {
return "", err
}
fn := s.dbFilePath(id)
if fileutil.Exist(fn) {
return fn, nil
}
if s.lg != nil {
s.lg.Warn(
"failed to find [SNAPSHOT-INDEX].snap.db",
zap.Uint64("snapshot-index", id),
zap.String("snapshot-file-path", fn),
zap.Error(ErrNoDBSnapshot),
)
}
return "", ErrNoDBSnapshot
} | go | func (s *Snapshotter) DBFilePath(id uint64) (string, error) {
if _, err := fileutil.ReadDir(s.dir); err != nil {
return "", err
}
fn := s.dbFilePath(id)
if fileutil.Exist(fn) {
return fn, nil
}
if s.lg != nil {
s.lg.Warn(
"failed to find [SNAPSHOT-INDEX].snap.db",
zap.Uint64("snapshot-index", id),
zap.String("snapshot-file-path", fn),
zap.Error(ErrNoDBSnapshot),
)
}
return "", ErrNoDBSnapshot
} | [
"func",
"(",
"s",
"*",
"Snapshotter",
")",
"DBFilePath",
"(",
"id",
"uint64",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"_",
",",
"err",
":=",
"fileutil",
".",
"ReadDir",
"(",
"s",
".",
"dir",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
... | // DBFilePath returns the file path for the snapshot of the database with
// given id. If the snapshot does not exist, it returns error. | [
"DBFilePath",
"returns",
"the",
"file",
"path",
"for",
"the",
"snapshot",
"of",
"the",
"database",
"with",
"given",
"id",
".",
"If",
"the",
"snapshot",
"does",
"not",
"exist",
"it",
"returns",
"error",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/snap/db.go#L83-L100 | test |
etcd-io/etcd | pkg/flags/unique_strings.go | Set | func (us *UniqueStringsValue) Set(s string) error {
us.Values = make(map[string]struct{})
for _, v := range strings.Split(s, ",") {
us.Values[v] = struct{}{}
}
return nil
} | go | func (us *UniqueStringsValue) Set(s string) error {
us.Values = make(map[string]struct{})
for _, v := range strings.Split(s, ",") {
us.Values[v] = struct{}{}
}
return nil
} | [
"func",
"(",
"us",
"*",
"UniqueStringsValue",
")",
"Set",
"(",
"s",
"string",
")",
"error",
"{",
"us",
".",
"Values",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"strings",
".",... | // Set parses a command line set of strings, separated by comma.
// Implements "flag.Value" interface.
// The values are set in order. | [
"Set",
"parses",
"a",
"command",
"line",
"set",
"of",
"strings",
"separated",
"by",
"comma",
".",
"Implements",
"flag",
".",
"Value",
"interface",
".",
"The",
"values",
"are",
"set",
"in",
"order",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/flags/unique_strings.go#L32-L38 | test |
etcd-io/etcd | pkg/flags/unique_strings.go | NewUniqueStringsValue | func NewUniqueStringsValue(s string) (us *UniqueStringsValue) {
us = &UniqueStringsValue{Values: make(map[string]struct{})}
if s == "" {
return us
}
if err := us.Set(s); err != nil {
plog.Panicf("new UniqueStringsValue should never fail: %v", err)
}
return us
} | go | func NewUniqueStringsValue(s string) (us *UniqueStringsValue) {
us = &UniqueStringsValue{Values: make(map[string]struct{})}
if s == "" {
return us
}
if err := us.Set(s); err != nil {
plog.Panicf("new UniqueStringsValue should never fail: %v", err)
}
return us
} | [
"func",
"NewUniqueStringsValue",
"(",
"s",
"string",
")",
"(",
"us",
"*",
"UniqueStringsValue",
")",
"{",
"us",
"=",
"&",
"UniqueStringsValue",
"{",
"Values",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
"}",
"\n",
"if",
"s",
... | // NewUniqueStringsValue implements string slice as "flag.Value" interface.
// Given value is to be separated by comma.
// The values are set in order. | [
"NewUniqueStringsValue",
"implements",
"string",
"slice",
"as",
"flag",
".",
"Value",
"interface",
".",
"Given",
"value",
"is",
"to",
"be",
"separated",
"by",
"comma",
".",
"The",
"values",
"are",
"set",
"in",
"order",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/flags/unique_strings.go#L57-L66 | test |
etcd-io/etcd | pkg/flags/unique_strings.go | UniqueStringsFromFlag | func UniqueStringsFromFlag(fs *flag.FlagSet, flagName string) []string {
return (*fs.Lookup(flagName).Value.(*UniqueStringsValue)).stringSlice()
} | go | func UniqueStringsFromFlag(fs *flag.FlagSet, flagName string) []string {
return (*fs.Lookup(flagName).Value.(*UniqueStringsValue)).stringSlice()
} | [
"func",
"UniqueStringsFromFlag",
"(",
"fs",
"*",
"flag",
".",
"FlagSet",
",",
"flagName",
"string",
")",
"[",
"]",
"string",
"{",
"return",
"(",
"*",
"fs",
".",
"Lookup",
"(",
"flagName",
")",
".",
"Value",
".",
"(",
"*",
"UniqueStringsValue",
")",
")"... | // UniqueStringsFromFlag returns a string slice from the flag. | [
"UniqueStringsFromFlag",
"returns",
"a",
"string",
"slice",
"from",
"the",
"flag",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/flags/unique_strings.go#L69-L71 | test |
etcd-io/etcd | pkg/flags/unique_strings.go | UniqueStringsMapFromFlag | func UniqueStringsMapFromFlag(fs *flag.FlagSet, flagName string) map[string]struct{} {
return (*fs.Lookup(flagName).Value.(*UniqueStringsValue)).Values
} | go | func UniqueStringsMapFromFlag(fs *flag.FlagSet, flagName string) map[string]struct{} {
return (*fs.Lookup(flagName).Value.(*UniqueStringsValue)).Values
} | [
"func",
"UniqueStringsMapFromFlag",
"(",
"fs",
"*",
"flag",
".",
"FlagSet",
",",
"flagName",
"string",
")",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
"{",
"return",
"(",
"*",
"fs",
".",
"Lookup",
"(",
"flagName",
")",
".",
"Value",
".",
"(",
"*"... | // UniqueStringsMapFromFlag returns a map of strings from the flag. | [
"UniqueStringsMapFromFlag",
"returns",
"a",
"map",
"of",
"strings",
"from",
"the",
"flag",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/flags/unique_strings.go#L74-L76 | test |
etcd-io/etcd | pkg/report/report.go | Percentiles | func Percentiles(nums []float64) (pcs []float64, data []float64) {
return pctls, percentiles(nums)
} | go | func Percentiles(nums []float64) (pcs []float64, data []float64) {
return pctls, percentiles(nums)
} | [
"func",
"Percentiles",
"(",
"nums",
"[",
"]",
"float64",
")",
"(",
"pcs",
"[",
"]",
"float64",
",",
"data",
"[",
"]",
"float64",
")",
"{",
"return",
"pctls",
",",
"percentiles",
"(",
"nums",
")",
"\n",
"}"
] | // Percentiles returns percentile distribution of float64 slice. | [
"Percentiles",
"returns",
"percentile",
"distribution",
"of",
"float64",
"slice",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/report/report.go#L209-L211 | test |
etcd-io/etcd | etcdserver/config.go | VerifyBootstrap | func (c *ServerConfig) VerifyBootstrap() error {
if err := c.hasLocalMember(); err != nil {
return err
}
if err := c.advertiseMatchesCluster(); err != nil {
return err
}
if checkDuplicateURL(c.InitialPeerURLsMap) {
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
} | go | func (c *ServerConfig) VerifyBootstrap() error {
if err := c.hasLocalMember(); err != nil {
return err
}
if err := c.advertiseMatchesCluster(); err != nil {
return err
}
if checkDuplicateURL(c.InitialPeerURLsMap) {
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
} | [
"func",
"(",
"c",
"*",
"ServerConfig",
")",
"VerifyBootstrap",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"c",
".",
"hasLocalMember",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"c",
".",
"advertiseM... | // VerifyBootstrap sanity-checks the initial config for bootstrap case
// and returns an error for things that should never happen. | [
"VerifyBootstrap",
"sanity",
"-",
"checks",
"the",
"initial",
"config",
"for",
"bootstrap",
"case",
"and",
"returns",
"an",
"error",
"for",
"things",
"that",
"should",
"never",
"happen",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/config.go#L161-L175 | test |
etcd-io/etcd | etcdserver/config.go | VerifyJoinExisting | func (c *ServerConfig) VerifyJoinExisting() error {
// The member has announced its peer urls to the cluster before starting; no need to
// set the configuration again.
if err := c.hasLocalMember(); err != nil {
return err
}
if checkDuplicateURL(c.InitialPeerURLsMap) {
return fmt.Errorf("initial 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
} | go | func (c *ServerConfig) VerifyJoinExisting() error {
// The member has announced its peer urls to the cluster before starting; no need to
// set the configuration again.
if err := c.hasLocalMember(); err != nil {
return err
}
if checkDuplicateURL(c.InitialPeerURLsMap) {
return fmt.Errorf("initial 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
} | [
"func",
"(",
"c",
"*",
"ServerConfig",
")",
"VerifyJoinExisting",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"c",
".",
"hasLocalMember",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"checkDuplicateURL",
"(",
"c",
".... | // VerifyJoinExisting sanity-checks the initial config for join existing cluster
// case and returns an error for things that should never happen. | [
"VerifyJoinExisting",
"sanity",
"-",
"checks",
"the",
"initial",
"config",
"for",
"join",
"existing",
"cluster",
"case",
"and",
"returns",
"an",
"error",
"for",
"things",
"that",
"should",
"never",
"happen",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/config.go#L179-L192 | test |
etcd-io/etcd | etcdserver/config.go | hasLocalMember | func (c *ServerConfig) hasLocalMember() error {
if urls := c.InitialPeerURLsMap[c.Name]; urls == nil {
return fmt.Errorf("couldn't find local name %q in the initial cluster configuration", c.Name)
}
return nil
} | go | func (c *ServerConfig) hasLocalMember() error {
if urls := c.InitialPeerURLsMap[c.Name]; urls == nil {
return fmt.Errorf("couldn't find local name %q in the initial cluster configuration", c.Name)
}
return nil
} | [
"func",
"(",
"c",
"*",
"ServerConfig",
")",
"hasLocalMember",
"(",
")",
"error",
"{",
"if",
"urls",
":=",
"c",
".",
"InitialPeerURLsMap",
"[",
"c",
".",
"Name",
"]",
";",
"urls",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"couldn't find l... | // hasLocalMember checks that the cluster at least contains the local server. | [
"hasLocalMember",
"checks",
"that",
"the",
"cluster",
"at",
"least",
"contains",
"the",
"local",
"server",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/config.go#L195-L200 | test |
etcd-io/etcd | etcdserver/config.go | advertiseMatchesCluster | func (c *ServerConfig) advertiseMatchesCluster() error {
urls, apurls := c.InitialPeerURLsMap[c.Name], c.PeerURLs.StringSlice()
urls.Sort()
sort.Strings(apurls)
ctx, cancel := context.WithTimeout(context.TODO(), 30*time.Second)
defer cancel()
ok, err := netutil.URLStringsEqual(ctx, c.Logger, apurls, urls.StringSlice())
if ok {
return nil
}
initMap, apMap := make(map[string]struct{}), make(map[string]struct{})
for _, url := range c.PeerURLs {
apMap[url.String()] = struct{}{}
}
for _, url := range c.InitialPeerURLsMap[c.Name] {
initMap[url.String()] = struct{}{}
}
missing := []string{}
for url := range initMap {
if _, ok := apMap[url]; !ok {
missing = append(missing, url)
}
}
if len(missing) > 0 {
for i := range missing {
missing[i] = c.Name + "=" + missing[i]
}
mstr := strings.Join(missing, ",")
apStr := strings.Join(apurls, ",")
return fmt.Errorf("--initial-cluster has %s but missing from --initial-advertise-peer-urls=%s (%v)", mstr, apStr, err)
}
for url := 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)
} | go | func (c *ServerConfig) advertiseMatchesCluster() error {
urls, apurls := c.InitialPeerURLsMap[c.Name], c.PeerURLs.StringSlice()
urls.Sort()
sort.Strings(apurls)
ctx, cancel := context.WithTimeout(context.TODO(), 30*time.Second)
defer cancel()
ok, err := netutil.URLStringsEqual(ctx, c.Logger, apurls, urls.StringSlice())
if ok {
return nil
}
initMap, apMap := make(map[string]struct{}), make(map[string]struct{})
for _, url := range c.PeerURLs {
apMap[url.String()] = struct{}{}
}
for _, url := range c.InitialPeerURLsMap[c.Name] {
initMap[url.String()] = struct{}{}
}
missing := []string{}
for url := range initMap {
if _, ok := apMap[url]; !ok {
missing = append(missing, url)
}
}
if len(missing) > 0 {
for i := range missing {
missing[i] = c.Name + "=" + missing[i]
}
mstr := strings.Join(missing, ",")
apStr := strings.Join(apurls, ",")
return fmt.Errorf("--initial-cluster has %s but missing from --initial-advertise-peer-urls=%s (%v)", mstr, apStr, err)
}
for url := 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)
} | [
"func",
"(",
"c",
"*",
"ServerConfig",
")",
"advertiseMatchesCluster",
"(",
")",
"error",
"{",
"urls",
",",
"apurls",
":=",
"c",
".",
"InitialPeerURLsMap",
"[",
"c",
".",
"Name",
"]",
",",
"c",
".",
"PeerURLs",
".",
"StringSlice",
"(",
")",
"\n",
"urls... | // advertiseMatchesCluster confirms peer URLs match those in the cluster peer list. | [
"advertiseMatchesCluster",
"confirms",
"peer",
"URLs",
"match",
"those",
"in",
"the",
"cluster",
"peer",
"list",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/config.go#L203-L252 | test |
etcd-io/etcd | etcdserver/config.go | ReqTimeout | func (c *ServerConfig) ReqTimeout() time.Duration {
// 5s for queue waiting, computation and disk IO delay
// + 2 * election timeout for possible leader election
return 5*time.Second + 2*time.Duration(c.ElectionTicks*int(c.TickMs))*time.Millisecond
} | go | func (c *ServerConfig) ReqTimeout() time.Duration {
// 5s for queue waiting, computation and disk IO delay
// + 2 * election timeout for possible leader election
return 5*time.Second + 2*time.Duration(c.ElectionTicks*int(c.TickMs))*time.Millisecond
} | [
"func",
"(",
"c",
"*",
"ServerConfig",
")",
"ReqTimeout",
"(",
")",
"time",
".",
"Duration",
"{",
"return",
"5",
"*",
"time",
".",
"Second",
"+",
"2",
"*",
"time",
".",
"Duration",
"(",
"c",
".",
"ElectionTicks",
"*",
"int",
"(",
"c",
".",
"TickMs"... | // ReqTimeout returns timeout for request to finish. | [
"ReqTimeout",
"returns",
"timeout",
"for",
"request",
"to",
"finish",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/config.go#L268-L272 | test |
etcd-io/etcd | raft/status.go | getStatus | func getStatus(r *raft) Status {
s := getStatusWithoutProgress(r)
if s.RaftState == StateLeader {
s.Progress = getProgressCopy(r)
}
return s
} | go | func getStatus(r *raft) Status {
s := getStatusWithoutProgress(r)
if s.RaftState == StateLeader {
s.Progress = getProgressCopy(r)
}
return s
} | [
"func",
"getStatus",
"(",
"r",
"*",
"raft",
")",
"Status",
"{",
"s",
":=",
"getStatusWithoutProgress",
"(",
"r",
")",
"\n",
"if",
"s",
".",
"RaftState",
"==",
"StateLeader",
"{",
"s",
".",
"Progress",
"=",
"getProgressCopy",
"(",
"r",
")",
"\n",
"}",
... | // getStatus gets a copy of the current raft status. | [
"getStatus",
"gets",
"a",
"copy",
"of",
"the",
"current",
"raft",
"status",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/status.go#L59-L65 | test |
etcd-io/etcd | pkg/netutil/routes_linux.go | GetDefaultHost | func GetDefaultHost() (string, error) {
rmsgs, rerr := getDefaultRoutes()
if rerr != nil {
return "", rerr
}
// prioritize IPv4
if rmsg, ok := rmsgs[syscall.AF_INET]; ok {
if host, err := chooseHost(syscall.AF_INET, rmsg); host != "" || err != nil {
return host, err
}
delete(rmsgs, syscall.AF_INET)
}
// sort so choice is deterministic
var families []int
for family := range rmsgs {
families = append(families, int(family))
}
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
} | go | func GetDefaultHost() (string, error) {
rmsgs, rerr := getDefaultRoutes()
if rerr != nil {
return "", rerr
}
// prioritize IPv4
if rmsg, ok := rmsgs[syscall.AF_INET]; ok {
if host, err := chooseHost(syscall.AF_INET, rmsg); host != "" || err != nil {
return host, err
}
delete(rmsgs, syscall.AF_INET)
}
// sort so choice is deterministic
var families []int
for family := range rmsgs {
families = append(families, int(family))
}
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
} | [
"func",
"GetDefaultHost",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"rmsgs",
",",
"rerr",
":=",
"getDefaultRoutes",
"(",
")",
"\n",
"if",
"rerr",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"rerr",
"\n",
"}",
"\n",
"if",
"rmsg",
",",
"ok",
":="... | // GetDefaultHost obtains the first IP address of machine from the routing table and returns the IP address as string.
// An IPv4 address is preferred to an IPv6 address for backward compatibility. | [
"GetDefaultHost",
"obtains",
"the",
"first",
"IP",
"address",
"of",
"machine",
"from",
"the",
"routing",
"table",
"and",
"returns",
"the",
"IP",
"address",
"as",
"string",
".",
"An",
"IPv4",
"address",
"is",
"preferred",
"to",
"an",
"IPv6",
"address",
"for",... | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/netutil/routes_linux.go#L36-L65 | test |
etcd-io/etcd | pkg/netutil/routes_linux.go | getIfaceAddr | func getIfaceAddr(idx uint32, family uint8) (*syscall.NetlinkMessage, error) {
dat, err := syscall.NetlinkRIB(syscall.RTM_GETADDR, int(family))
if err != nil {
return nil, err
}
msgs, msgErr := syscall.ParseNetlinkMessage(dat)
if msgErr != nil {
return nil, msgErr
}
ifaddrmsg := syscall.IfAddrmsg{}
for _, m := range msgs {
if m.Header.Type != syscall.RTM_NEWADDR {
continue
}
buf := bytes.NewBuffer(m.Data[:syscall.SizeofIfAddrmsg])
if 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)
} | go | func getIfaceAddr(idx uint32, family uint8) (*syscall.NetlinkMessage, error) {
dat, err := syscall.NetlinkRIB(syscall.RTM_GETADDR, int(family))
if err != nil {
return nil, err
}
msgs, msgErr := syscall.ParseNetlinkMessage(dat)
if msgErr != nil {
return nil, msgErr
}
ifaddrmsg := syscall.IfAddrmsg{}
for _, m := range msgs {
if m.Header.Type != syscall.RTM_NEWADDR {
continue
}
buf := bytes.NewBuffer(m.Data[:syscall.SizeofIfAddrmsg])
if 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)
} | [
"func",
"getIfaceAddr",
"(",
"idx",
"uint32",
",",
"family",
"uint8",
")",
"(",
"*",
"syscall",
".",
"NetlinkMessage",
",",
"error",
")",
"{",
"dat",
",",
"err",
":=",
"syscall",
".",
"NetlinkRIB",
"(",
"syscall",
".",
"RTM_GETADDR",
",",
"int",
"(",
"... | // Used to get an address of interface. | [
"Used",
"to",
"get",
"an",
"address",
"of",
"interface",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/netutil/routes_linux.go#L130-L157 | test |
etcd-io/etcd | pkg/netutil/routes_linux.go | getIfaceLink | func getIfaceLink(idx uint32) (*syscall.NetlinkMessage, error) {
dat, err := syscall.NetlinkRIB(syscall.RTM_GETLINK, syscall.AF_UNSPEC)
if err != nil {
return nil, err
}
msgs, msgErr := syscall.ParseNetlinkMessage(dat)
if msgErr != nil {
return nil, msgErr
}
ifinfomsg := syscall.IfInfomsg{}
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)
} | go | func getIfaceLink(idx uint32) (*syscall.NetlinkMessage, error) {
dat, err := syscall.NetlinkRIB(syscall.RTM_GETLINK, syscall.AF_UNSPEC)
if err != nil {
return nil, err
}
msgs, msgErr := syscall.ParseNetlinkMessage(dat)
if msgErr != nil {
return nil, msgErr
}
ifinfomsg := syscall.IfInfomsg{}
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)
} | [
"func",
"getIfaceLink",
"(",
"idx",
"uint32",
")",
"(",
"*",
"syscall",
".",
"NetlinkMessage",
",",
"error",
")",
"{",
"dat",
",",
"err",
":=",
"syscall",
".",
"NetlinkRIB",
"(",
"syscall",
".",
"RTM_GETLINK",
",",
"syscall",
".",
"AF_UNSPEC",
")",
"\n",... | // Used to get a name of interface. | [
"Used",
"to",
"get",
"a",
"name",
"of",
"interface",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/netutil/routes_linux.go#L160-L186 | test |
etcd-io/etcd | etcdctl/ctlv2/command/ls_command.go | lsCommandFunc | func lsCommandFunc(c *cli.Context, ki client.KeysAPI) {
key := "/"
if len(c.Args()) != 0 {
key = c.Args()[0]
}
sort := c.Bool("sort")
recursive := c.Bool("recursive")
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)
} | go | func lsCommandFunc(c *cli.Context, ki client.KeysAPI) {
key := "/"
if len(c.Args()) != 0 {
key = c.Args()[0]
}
sort := c.Bool("sort")
recursive := c.Bool("recursive")
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)
} | [
"func",
"lsCommandFunc",
"(",
"c",
"*",
"cli",
".",
"Context",
",",
"ki",
"client",
".",
"KeysAPI",
")",
"{",
"key",
":=",
"\"/\"",
"\n",
"if",
"len",
"(",
"c",
".",
"Args",
"(",
")",
")",
"!=",
"0",
"{",
"key",
"=",
"c",
".",
"Args",
"(",
")... | // lsCommandFunc executes the "ls" command. | [
"lsCommandFunc",
"executes",
"the",
"ls",
"command",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv2/command/ls_command.go#L43-L61 | test |
etcd-io/etcd | etcdctl/ctlv2/command/ls_command.go | printLs | func printLs(c *cli.Context, resp *client.Response) {
if c.GlobalString("output") == "simple" {
if !resp.Node.Dir {
fmt.Println(resp.Node.Key)
}
for _, node := range resp.Node.Nodes {
rPrint(c, node)
}
} else {
// user wants JSON or extended output
printResponseKey(resp, c.GlobalString("output"))
}
} | go | func printLs(c *cli.Context, resp *client.Response) {
if c.GlobalString("output") == "simple" {
if !resp.Node.Dir {
fmt.Println(resp.Node.Key)
}
for _, node := range resp.Node.Nodes {
rPrint(c, node)
}
} else {
// user wants JSON or extended output
printResponseKey(resp, c.GlobalString("output"))
}
} | [
"func",
"printLs",
"(",
"c",
"*",
"cli",
".",
"Context",
",",
"resp",
"*",
"client",
".",
"Response",
")",
"{",
"if",
"c",
".",
"GlobalString",
"(",
"\"output\"",
")",
"==",
"\"simple\"",
"{",
"if",
"!",
"resp",
".",
"Node",
".",
"Dir",
"{",
"fmt",... | // printLs writes a response out in a manner similar to the `ls` command in unix.
// Non-empty directories list their contents and files list their name. | [
"printLs",
"writes",
"a",
"response",
"out",
"in",
"a",
"manner",
"similar",
"to",
"the",
"ls",
"command",
"in",
"unix",
".",
"Non",
"-",
"empty",
"directories",
"list",
"their",
"contents",
"and",
"files",
"list",
"their",
"name",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv2/command/ls_command.go#L65-L77 | test |
etcd-io/etcd | etcdctl/ctlv2/command/ls_command.go | rPrint | func rPrint(c *cli.Context, n *client.Node) {
if n.Dir && c.Bool("p") {
fmt.Println(fmt.Sprintf("%v/", n.Key))
} else {
fmt.Println(n.Key)
}
for _, node := range n.Nodes {
rPrint(c, node)
}
} | go | func rPrint(c *cli.Context, n *client.Node) {
if n.Dir && c.Bool("p") {
fmt.Println(fmt.Sprintf("%v/", n.Key))
} else {
fmt.Println(n.Key)
}
for _, node := range n.Nodes {
rPrint(c, node)
}
} | [
"func",
"rPrint",
"(",
"c",
"*",
"cli",
".",
"Context",
",",
"n",
"*",
"client",
".",
"Node",
")",
"{",
"if",
"n",
".",
"Dir",
"&&",
"c",
".",
"Bool",
"(",
"\"p\"",
")",
"{",
"fmt",
".",
"Println",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"%v/\"",
... | // rPrint recursively prints out the nodes in the node structure. | [
"rPrint",
"recursively",
"prints",
"out",
"the",
"nodes",
"in",
"the",
"node",
"structure",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv2/command/ls_command.go#L80-L90 | test |
etcd-io/etcd | functional/runner/lease_renewer_command.go | NewLeaseRenewerCommand | func NewLeaseRenewerCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "lease-renewer",
Short: "Performs lease renew operation",
Run: runLeaseRenewerFunc,
}
cmd.Flags().Int64Var(&leaseTTL, "ttl", 5, "lease's ttl")
return cmd
} | go | func NewLeaseRenewerCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "lease-renewer",
Short: "Performs lease renew operation",
Run: runLeaseRenewerFunc,
}
cmd.Flags().Int64Var(&leaseTTL, "ttl", 5, "lease's ttl")
return cmd
} | [
"func",
"NewLeaseRenewerCommand",
"(",
")",
"*",
"cobra",
".",
"Command",
"{",
"cmd",
":=",
"&",
"cobra",
".",
"Command",
"{",
"Use",
":",
"\"lease-renewer\"",
",",
"Short",
":",
"\"Performs lease renew operation\"",
",",
"Run",
":",
"runLeaseRenewerFunc",
",",
... | // NewLeaseRenewerCommand returns the cobra command for "lease-renewer runner". | [
"NewLeaseRenewerCommand",
"returns",
"the",
"cobra",
"command",
"for",
"lease",
"-",
"renewer",
"runner",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/runner/lease_renewer_command.go#L36-L44 | test |
etcd-io/etcd | etcdserver/api/snap/snapshotter.go | Read | func Read(lg *zap.Logger, snapname string) (*raftpb.Snapshot, error) {
b, err := ioutil.ReadFile(snapname)
if err != nil {
if lg != nil {
lg.Warn("failed to read a snap file", zap.String("path", snapname), zap.Error(err))
} else {
plog.Errorf("cannot read file %v: %v", snapname, err)
}
return nil, err
}
if len(b) == 0 {
if lg != nil {
lg.Warn("failed to read empty snapshot file", zap.String("path", snapname))
} else {
plog.Errorf("unexpected empty snapshot")
}
return nil, ErrEmptySnapshot
}
var serializedSnap snappb.Snapshot
if err = serializedSnap.Unmarshal(b); err != nil {
if lg != nil {
lg.Warn("failed to unmarshal snappb.Snapshot", zap.String("path", snapname), zap.Error(err))
} else {
plog.Errorf("corrupted snapshot file %v: %v", snapname, err)
}
return nil, err
}
if len(serializedSnap.Data) == 0 || serializedSnap.Crc == 0 {
if lg != nil {
lg.Warn("failed to read empty snapshot data", zap.String("path", snapname))
} else {
plog.Errorf("unexpected empty snapshot")
}
return nil, 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
} | go | func Read(lg *zap.Logger, snapname string) (*raftpb.Snapshot, error) {
b, err := ioutil.ReadFile(snapname)
if err != nil {
if lg != nil {
lg.Warn("failed to read a snap file", zap.String("path", snapname), zap.Error(err))
} else {
plog.Errorf("cannot read file %v: %v", snapname, err)
}
return nil, err
}
if len(b) == 0 {
if lg != nil {
lg.Warn("failed to read empty snapshot file", zap.String("path", snapname))
} else {
plog.Errorf("unexpected empty snapshot")
}
return nil, ErrEmptySnapshot
}
var serializedSnap snappb.Snapshot
if err = serializedSnap.Unmarshal(b); err != nil {
if lg != nil {
lg.Warn("failed to unmarshal snappb.Snapshot", zap.String("path", snapname), zap.Error(err))
} else {
plog.Errorf("corrupted snapshot file %v: %v", snapname, err)
}
return nil, err
}
if len(serializedSnap.Data) == 0 || serializedSnap.Crc == 0 {
if lg != nil {
lg.Warn("failed to read empty snapshot data", zap.String("path", snapname))
} else {
plog.Errorf("unexpected empty snapshot")
}
return nil, 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
} | [
"func",
"Read",
"(",
"lg",
"*",
"zap",
".",
"Logger",
",",
"snapname",
"string",
")",
"(",
"*",
"raftpb",
".",
"Snapshot",
",",
"error",
")",
"{",
"b",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"snapname",
")",
"\n",
"if",
"err",
"!=",
"n... | // Read reads the snapshot named by snapname and returns the snapshot. | [
"Read",
"reads",
"the",
"snapshot",
"named",
"by",
"snapname",
"and",
"returns",
"the",
"snapshot",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/snap/snapshotter.go#L152-L215 | test |
etcd-io/etcd | pkg/tlsutil/cipher_suites.go | GetCipherSuite | func GetCipherSuite(s string) (uint16, bool) {
v, ok := cipherSuites[s]
return v, ok
} | go | func GetCipherSuite(s string) (uint16, bool) {
v, ok := cipherSuites[s]
return v, ok
} | [
"func",
"GetCipherSuite",
"(",
"s",
"string",
")",
"(",
"uint16",
",",
"bool",
")",
"{",
"v",
",",
"ok",
":=",
"cipherSuites",
"[",
"s",
"]",
"\n",
"return",
"v",
",",
"ok",
"\n",
"}"
] | // GetCipherSuite returns the corresponding cipher suite,
// and boolean value if it is supported. | [
"GetCipherSuite",
"returns",
"the",
"corresponding",
"cipher",
"suite",
"and",
"boolean",
"value",
"if",
"it",
"is",
"supported",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/tlsutil/cipher_suites.go#L48-L51 | test |
etcd-io/etcd | etcdserver/api/rafthttp/pipeline.go | post | func (p *pipeline) post(data []byte) (err error) {
u := p.picker.pick()
req := createPostRequest(u, RaftPrefix, bytes.NewBuffer(data), "application/protobuf", p.tr.URLs, p.tr.ID, p.tr.ClusterID)
done := make(chan struct{}, 1)
ctx, cancel := context.WithCancel(context.Background())
req = req.WithContext(ctx)
go func() {
select {
case <-done:
case <-p.stopc:
waitSchedule()
cancel()
}
}()
resp, err := p.tr.pipelineRt.RoundTrip(req)
done <- struct{}{}
if err != nil {
p.picker.unreachable(u)
return err
}
defer resp.Body.Close()
b, err := 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
} | go | func (p *pipeline) post(data []byte) (err error) {
u := p.picker.pick()
req := createPostRequest(u, RaftPrefix, bytes.NewBuffer(data), "application/protobuf", p.tr.URLs, p.tr.ID, p.tr.ClusterID)
done := make(chan struct{}, 1)
ctx, cancel := context.WithCancel(context.Background())
req = req.WithContext(ctx)
go func() {
select {
case <-done:
case <-p.stopc:
waitSchedule()
cancel()
}
}()
resp, err := p.tr.pipelineRt.RoundTrip(req)
done <- struct{}{}
if err != nil {
p.picker.unreachable(u)
return err
}
defer resp.Body.Close()
b, err := 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
} | [
"func",
"(",
"p",
"*",
"pipeline",
")",
"post",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"err",
"error",
")",
"{",
"u",
":=",
"p",
".",
"picker",
".",
"pick",
"(",
")",
"\n",
"req",
":=",
"createPostRequest",
"(",
"u",
",",
"RaftPrefix",
",",
"... | // post POSTs a data payload to a url. Returns nil if the POST succeeds,
// error on any failure. | [
"post",
"POSTs",
"a",
"data",
"payload",
"to",
"a",
"url",
".",
"Returns",
"nil",
"if",
"the",
"POST",
"succeeds",
"error",
"on",
"any",
"failure",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/rafthttp/pipeline.go#L136-L177 | test |
etcd-io/etcd | raft/raft.go | send | func (r *raft) send(m pb.Message) {
m.From = r.id
if m.Type == pb.MsgVote || m.Type == pb.MsgVoteResp || m.Type == pb.MsgPreVote || m.Type == pb.MsgPreVoteResp {
if m.Term == 0 {
// All {pre-,}campaign messages need to have the term set when
// sending.
// - MsgVote: m.Term is the term the node is campaigning for,
// non-zero as we increment the term when campaigning.
// - MsgVoteResp: m.Term is the new r.Term if the MsgVote was
// granted, non-zero for the same reason MsgVote is
// - MsgPreVote: m.Term is the term the node will campaign,
// non-zero as we use m.Term to indicate the next term we'll be
// campaigning for
// - MsgPreVoteResp: m.Term is the term received in the original
// MsgPreVote if the pre-vote was granted, non-zero for the
// same reasons MsgPreVote is
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)
} | go | func (r *raft) send(m pb.Message) {
m.From = r.id
if m.Type == pb.MsgVote || m.Type == pb.MsgVoteResp || m.Type == pb.MsgPreVote || m.Type == pb.MsgPreVoteResp {
if m.Term == 0 {
// All {pre-,}campaign messages need to have the term set when
// sending.
// - MsgVote: m.Term is the term the node is campaigning for,
// non-zero as we increment the term when campaigning.
// - MsgVoteResp: m.Term is the new r.Term if the MsgVote was
// granted, non-zero for the same reason MsgVote is
// - MsgPreVote: m.Term is the term the node will campaign,
// non-zero as we use m.Term to indicate the next term we'll be
// campaigning for
// - MsgPreVoteResp: m.Term is the term received in the original
// MsgPreVote if the pre-vote was granted, non-zero for the
// same reasons MsgPreVote is
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)
} | [
"func",
"(",
"r",
"*",
"raft",
")",
"send",
"(",
"m",
"pb",
".",
"Message",
")",
"{",
"m",
".",
"From",
"=",
"r",
".",
"id",
"\n",
"if",
"m",
".",
"Type",
"==",
"pb",
".",
"MsgVote",
"||",
"m",
".",
"Type",
"==",
"pb",
".",
"MsgVoteResp",
"... | // send persists state to stable storage and then sends to its mailbox. | [
"send",
"persists",
"state",
"to",
"stable",
"storage",
"and",
"then",
"sends",
"to",
"its",
"mailbox",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/raft.go#L427-L458 | test |
etcd-io/etcd | raft/raft.go | sendHeartbeat | func (r *raft) sendHeartbeat(to uint64, ctx []byte) {
// Attach the commit as min(to.matched, r.committed).
// When the leader sends out heartbeat message,
// the receiver(follower) might not be matched with the leader
// 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)
} | go | func (r *raft) sendHeartbeat(to uint64, ctx []byte) {
// Attach the commit as min(to.matched, r.committed).
// When the leader sends out heartbeat message,
// the receiver(follower) might not be matched with the leader
// 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)
} | [
"func",
"(",
"r",
"*",
"raft",
")",
"sendHeartbeat",
"(",
"to",
"uint64",
",",
"ctx",
"[",
"]",
"byte",
")",
"{",
"commit",
":=",
"min",
"(",
"r",
".",
"getProgress",
"(",
"to",
")",
".",
"Match",
",",
"r",
".",
"raftLog",
".",
"committed",
")",
... | // sendHeartbeat sends a heartbeat RPC to the given peer. | [
"sendHeartbeat",
"sends",
"a",
"heartbeat",
"RPC",
"to",
"the",
"given",
"peer",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/raft.go#L542-L558 | test |
etcd-io/etcd | raft/raft.go | bcastAppend | func (r *raft) bcastAppend() {
r.forEachProgress(func(id uint64, _ *Progress) {
if id == r.id {
return
}
r.sendAppend(id)
})
} | go | func (r *raft) bcastAppend() {
r.forEachProgress(func(id uint64, _ *Progress) {
if id == r.id {
return
}
r.sendAppend(id)
})
} | [
"func",
"(",
"r",
"*",
"raft",
")",
"bcastAppend",
"(",
")",
"{",
"r",
".",
"forEachProgress",
"(",
"func",
"(",
"id",
"uint64",
",",
"_",
"*",
"Progress",
")",
"{",
"if",
"id",
"==",
"r",
".",
"id",
"{",
"return",
"\n",
"}",
"\n",
"r",
".",
... | // bcastAppend sends RPC, with entries to all peers that are not up-to-date
// according to the progress recorded in r.prs. | [
"bcastAppend",
"sends",
"RPC",
"with",
"entries",
"to",
"all",
"peers",
"that",
"are",
"not",
"up",
"-",
"to",
"-",
"date",
"according",
"to",
"the",
"progress",
"recorded",
"in",
"r",
".",
"prs",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/raft.go#L572-L580 | test |
etcd-io/etcd | raft/raft.go | bcastHeartbeat | func (r *raft) bcastHeartbeat() {
lastCtx := r.readOnly.lastPendingRequestCtx()
if len(lastCtx) == 0 {
r.bcastHeartbeatWithCtx(nil)
} else {
r.bcastHeartbeatWithCtx([]byte(lastCtx))
}
} | go | func (r *raft) bcastHeartbeat() {
lastCtx := r.readOnly.lastPendingRequestCtx()
if len(lastCtx) == 0 {
r.bcastHeartbeatWithCtx(nil)
} else {
r.bcastHeartbeatWithCtx([]byte(lastCtx))
}
} | [
"func",
"(",
"r",
"*",
"raft",
")",
"bcastHeartbeat",
"(",
")",
"{",
"lastCtx",
":=",
"r",
".",
"readOnly",
".",
"lastPendingRequestCtx",
"(",
")",
"\n",
"if",
"len",
"(",
"lastCtx",
")",
"==",
"0",
"{",
"r",
".",
"bcastHeartbeatWithCtx",
"(",
"nil",
... | // bcastHeartbeat sends RPC, without entries to all the peers. | [
"bcastHeartbeat",
"sends",
"RPC",
"without",
"entries",
"to",
"all",
"the",
"peers",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/raft.go#L583-L590 | test |
etcd-io/etcd | raft/raft.go | tickElection | func (r *raft) tickElection() {
r.electionElapsed++
if r.promotable() && r.pastElectionTimeout() {
r.electionElapsed = 0
r.Step(pb.Message{From: r.id, Type: pb.MsgHup})
}
} | go | func (r *raft) tickElection() {
r.electionElapsed++
if r.promotable() && r.pastElectionTimeout() {
r.electionElapsed = 0
r.Step(pb.Message{From: r.id, Type: pb.MsgHup})
}
} | [
"func",
"(",
"r",
"*",
"raft",
")",
"tickElection",
"(",
")",
"{",
"r",
".",
"electionElapsed",
"++",
"\n",
"if",
"r",
".",
"promotable",
"(",
")",
"&&",
"r",
".",
"pastElectionTimeout",
"(",
")",
"{",
"r",
".",
"electionElapsed",
"=",
"0",
"\n",
"... | // tickElection is run by followers and candidates after r.electionTimeout. | [
"tickElection",
"is",
"run",
"by",
"followers",
"and",
"candidates",
"after",
"r",
".",
"electionTimeout",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/raft.go#L671-L678 | test |
etcd-io/etcd | raft/raft.go | tickHeartbeat | func (r *raft) tickHeartbeat() {
r.heartbeatElapsed++
r.electionElapsed++
if r.electionElapsed >= r.electionTimeout {
r.electionElapsed = 0
if r.checkQuorum {
r.Step(pb.Message{From: r.id, Type: pb.MsgCheckQuorum})
}
// If current leader cannot transfer leadership in electionTimeout, it becomes leader again.
if r.state == StateLeader && 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})
}
} | go | func (r *raft) tickHeartbeat() {
r.heartbeatElapsed++
r.electionElapsed++
if r.electionElapsed >= r.electionTimeout {
r.electionElapsed = 0
if r.checkQuorum {
r.Step(pb.Message{From: r.id, Type: pb.MsgCheckQuorum})
}
// If current leader cannot transfer leadership in electionTimeout, it becomes leader again.
if r.state == StateLeader && 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})
}
} | [
"func",
"(",
"r",
"*",
"raft",
")",
"tickHeartbeat",
"(",
")",
"{",
"r",
".",
"heartbeatElapsed",
"++",
"\n",
"r",
".",
"electionElapsed",
"++",
"\n",
"if",
"r",
".",
"electionElapsed",
">=",
"r",
".",
"electionTimeout",
"{",
"r",
".",
"electionElapsed",... | // tickHeartbeat is run by leaders to send a MsgBeat after r.heartbeatTimeout. | [
"tickHeartbeat",
"is",
"run",
"by",
"leaders",
"to",
"send",
"a",
"MsgBeat",
"after",
"r",
".",
"heartbeatTimeout",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/raft.go#L681-L704 | test |
etcd-io/etcd | raft/raft.go | stepCandidate | func stepCandidate(r *raft, m pb.Message) error {
// Only handle vote responses corresponding to our candidacy (while in
// StateCandidate, we may get stale MsgPreVoteResp messages in this term from
// our pre-candidate state).
var myVoteRespType pb.MessageType
if r.state == StatePreCandidate {
myVoteRespType = pb.MsgPreVoteResp
} else {
myVoteRespType = pb.MsgVoteResp
}
switch m.Type {
case pb.MsgProp:
r.logger.Infof("%x no leader at term %d; dropping proposal", r.id, r.Term)
return ErrProposalDropped
case pb.MsgApp:
r.becomeFollower(m.Term, m.From) // always m.Term == r.Term
r.handleAppendEntries(m)
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
} | go | func stepCandidate(r *raft, m pb.Message) error {
// Only handle vote responses corresponding to our candidacy (while in
// StateCandidate, we may get stale MsgPreVoteResp messages in this term from
// our pre-candidate state).
var myVoteRespType pb.MessageType
if r.state == StatePreCandidate {
myVoteRespType = pb.MsgPreVoteResp
} else {
myVoteRespType = pb.MsgVoteResp
}
switch m.Type {
case pb.MsgProp:
r.logger.Infof("%x no leader at term %d; dropping proposal", r.id, r.Term)
return ErrProposalDropped
case pb.MsgApp:
r.becomeFollower(m.Term, m.From) // always m.Term == r.Term
r.handleAppendEntries(m)
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
} | [
"func",
"stepCandidate",
"(",
"r",
"*",
"raft",
",",
"m",
"pb",
".",
"Message",
")",
"error",
"{",
"var",
"myVoteRespType",
"pb",
".",
"MessageType",
"\n",
"if",
"r",
".",
"state",
"==",
"StatePreCandidate",
"{",
"myVoteRespType",
"=",
"pb",
".",
"MsgPre... | // stepCandidate is shared by StateCandidate and StatePreCandidate; the difference is
// whether they respond to MsgVoteResp or MsgPreVoteResp. | [
"stepCandidate",
"is",
"shared",
"by",
"StateCandidate",
"and",
"StatePreCandidate",
";",
"the",
"difference",
"is",
"whether",
"they",
"respond",
"to",
"MsgVoteResp",
"or",
"MsgPreVoteResp",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/raft.go#L1210-L1253 | test |
etcd-io/etcd | raft/raft.go | restore | func (r *raft) restore(s pb.Snapshot) bool {
if s.Metadata.Index <= r.raftLog.committed {
return false
}
if r.raftLog.matchTerm(s.Metadata.Index, s.Metadata.Term) {
r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] fast-forwarded commit to snapshot [index: %d, term: %d]",
r.id, r.raftLog.committed, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
r.raftLog.commitTo(s.Metadata.Index)
return false
}
// The normal peer can't become learner.
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
} | go | func (r *raft) restore(s pb.Snapshot) bool {
if s.Metadata.Index <= r.raftLog.committed {
return false
}
if r.raftLog.matchTerm(s.Metadata.Index, s.Metadata.Term) {
r.logger.Infof("%x [commit: %d, lastindex: %d, lastterm: %d] fast-forwarded commit to snapshot [index: %d, term: %d]",
r.id, r.raftLog.committed, r.raftLog.lastIndex(), r.raftLog.lastTerm(), s.Metadata.Index, s.Metadata.Term)
r.raftLog.commitTo(s.Metadata.Index)
return false
}
// The normal peer can't become learner.
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
} | [
"func",
"(",
"r",
"*",
"raft",
")",
"restore",
"(",
"s",
"pb",
".",
"Snapshot",
")",
"bool",
"{",
"if",
"s",
".",
"Metadata",
".",
"Index",
"<=",
"r",
".",
"raftLog",
".",
"committed",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"r",
".",
"r... | // restore recovers the state machine from a snapshot. It restores the log and the
// configuration of state machine. | [
"restore",
"recovers",
"the",
"state",
"machine",
"from",
"a",
"snapshot",
".",
"It",
"restores",
"the",
"log",
"and",
"the",
"configuration",
"of",
"state",
"machine",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/raft.go#L1348-L1378 | test |
etcd-io/etcd | raft/raft.go | promotable | func (r *raft) promotable() bool {
_, ok := r.prs[r.id]
return ok
} | go | func (r *raft) promotable() bool {
_, ok := r.prs[r.id]
return ok
} | [
"func",
"(",
"r",
"*",
"raft",
")",
"promotable",
"(",
")",
"bool",
"{",
"_",
",",
"ok",
":=",
"r",
".",
"prs",
"[",
"r",
".",
"id",
"]",
"\n",
"return",
"ok",
"\n",
"}"
] | // promotable indicates whether state machine can be promoted to leader,
// which is true when its own id is in progress list. | [
"promotable",
"indicates",
"whether",
"state",
"machine",
"can",
"be",
"promoted",
"to",
"leader",
"which",
"is",
"true",
"when",
"its",
"own",
"id",
"is",
"in",
"progress",
"list",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/raft.go#L1394-L1397 | test |
etcd-io/etcd | raft/raft.go | checkQuorumActive | func (r *raft) checkQuorumActive() bool {
var act int
r.forEachProgress(func(id uint64, pr *Progress) {
if id == r.id { // self is always active
act++
return
}
if pr.RecentActive && !pr.IsLearner {
act++
}
pr.RecentActive = false
})
return act >= r.quorum()
} | go | func (r *raft) checkQuorumActive() bool {
var act int
r.forEachProgress(func(id uint64, pr *Progress) {
if id == r.id { // self is always active
act++
return
}
if pr.RecentActive && !pr.IsLearner {
act++
}
pr.RecentActive = false
})
return act >= r.quorum()
} | [
"func",
"(",
"r",
"*",
"raft",
")",
"checkQuorumActive",
"(",
")",
"bool",
"{",
"var",
"act",
"int",
"\n",
"r",
".",
"forEachProgress",
"(",
"func",
"(",
"id",
"uint64",
",",
"pr",
"*",
"Progress",
")",
"{",
"if",
"id",
"==",
"r",
".",
"id",
"{",... | // checkQuorumActive returns true if the quorum is active from
// the view of the local raft state machine. Otherwise, it returns
// false.
// checkQuorumActive also resets all RecentActive to false. | [
"checkQuorumActive",
"returns",
"true",
"if",
"the",
"quorum",
"is",
"active",
"from",
"the",
"view",
"of",
"the",
"local",
"raft",
"state",
"machine",
".",
"Otherwise",
"it",
"returns",
"false",
".",
"checkQuorumActive",
"also",
"resets",
"all",
"RecentActive",... | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/raft.go#L1502-L1519 | test |
etcd-io/etcd | raft/raft.go | increaseUncommittedSize | func (r *raft) increaseUncommittedSize(ents []pb.Entry) bool {
var s uint64
for _, e := range ents {
s += uint64(PayloadSize(e))
}
if r.uncommittedSize > 0 && r.uncommittedSize+s > r.maxUncommittedSize {
// If the uncommitted tail of the Raft log is empty, allow any size
// 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
} | go | func (r *raft) increaseUncommittedSize(ents []pb.Entry) bool {
var s uint64
for _, e := range ents {
s += uint64(PayloadSize(e))
}
if r.uncommittedSize > 0 && r.uncommittedSize+s > r.maxUncommittedSize {
// If the uncommitted tail of the Raft log is empty, allow any size
// 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
} | [
"func",
"(",
"r",
"*",
"raft",
")",
"increaseUncommittedSize",
"(",
"ents",
"[",
"]",
"pb",
".",
"Entry",
")",
"bool",
"{",
"var",
"s",
"uint64",
"\n",
"for",
"_",
",",
"e",
":=",
"range",
"ents",
"{",
"s",
"+=",
"uint64",
"(",
"PayloadSize",
"(",
... | // increaseUncommittedSize computes the size of the proposed entries and
// determines whether they would push leader over its maxUncommittedSize limit.
// If the new entries would exceed the limit, the method returns false. If not,
// the increase in uncommitted entry size is recorded and the method returns
// true. | [
"increaseUncommittedSize",
"computes",
"the",
"size",
"of",
"the",
"proposed",
"entries",
"and",
"determines",
"whether",
"they",
"would",
"push",
"leader",
"over",
"its",
"maxUncommittedSize",
"limit",
".",
"If",
"the",
"new",
"entries",
"would",
"exceed",
"the",... | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/raft.go#L1534-L1548 | test |
etcd-io/etcd | raft/raft.go | reduceUncommittedSize | func (r *raft) reduceUncommittedSize(ents []pb.Entry) {
if r.uncommittedSize == 0 {
// Fast-path for followers, who do not track or enforce the limit.
return
}
var s uint64
for _, e := range ents {
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
}
} | go | func (r *raft) reduceUncommittedSize(ents []pb.Entry) {
if r.uncommittedSize == 0 {
// Fast-path for followers, who do not track or enforce the limit.
return
}
var s uint64
for _, e := range ents {
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
}
} | [
"func",
"(",
"r",
"*",
"raft",
")",
"reduceUncommittedSize",
"(",
"ents",
"[",
"]",
"pb",
".",
"Entry",
")",
"{",
"if",
"r",
".",
"uncommittedSize",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n",
"var",
"s",
"uint64",
"\n",
"for",
"_",
",",
"e",
":="... | // reduceUncommittedSize accounts for the newly committed entries by decreasing
// the uncommitted entry size limit. | [
"reduceUncommittedSize",
"accounts",
"for",
"the",
"newly",
"committed",
"entries",
"by",
"decreasing",
"the",
"uncommitted",
"entry",
"size",
"limit",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/raft.go#L1552-L1570 | test |
etcd-io/etcd | etcdserver/api/v3compactor/periodic.go | newPeriodic | func newPeriodic(lg *zap.Logger, clock clockwork.Clock, h time.Duration, rg RevGetter, c Compactable) *Periodic {
pc := &Periodic{
lg: lg,
clock: clock,
period: h,
rg: rg,
c: c,
revs: make([]int64, 0),
}
pc.ctx, pc.cancel = context.WithCancel(context.Background())
return pc
} | go | func newPeriodic(lg *zap.Logger, clock clockwork.Clock, h time.Duration, rg RevGetter, c Compactable) *Periodic {
pc := &Periodic{
lg: lg,
clock: clock,
period: h,
rg: rg,
c: c,
revs: make([]int64, 0),
}
pc.ctx, pc.cancel = context.WithCancel(context.Background())
return pc
} | [
"func",
"newPeriodic",
"(",
"lg",
"*",
"zap",
".",
"Logger",
",",
"clock",
"clockwork",
".",
"Clock",
",",
"h",
"time",
".",
"Duration",
",",
"rg",
"RevGetter",
",",
"c",
"Compactable",
")",
"*",
"Periodic",
"{",
"pc",
":=",
"&",
"Periodic",
"{",
"lg... | // newPeriodic creates a new instance of Periodic compactor that purges
// the log older than h Duration. | [
"newPeriodic",
"creates",
"a",
"new",
"instance",
"of",
"Periodic",
"compactor",
"that",
"purges",
"the",
"log",
"older",
"than",
"h",
"Duration",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v3compactor/periodic.go#L50-L61 | test |
etcd-io/etcd | etcdserver/api/v3compactor/periodic.go | Pause | func (pc *Periodic) Pause() {
pc.mu.Lock()
pc.paused = true
pc.mu.Unlock()
} | go | func (pc *Periodic) Pause() {
pc.mu.Lock()
pc.paused = true
pc.mu.Unlock()
} | [
"func",
"(",
"pc",
"*",
"Periodic",
")",
"Pause",
"(",
")",
"{",
"pc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"pc",
".",
"paused",
"=",
"true",
"\n",
"pc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // Pause pauses periodic compactor. | [
"Pause",
"pauses",
"periodic",
"compactor",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v3compactor/periodic.go#L206-L210 | test |
etcd-io/etcd | etcdserver/api/v3compactor/periodic.go | Resume | func (pc *Periodic) Resume() {
pc.mu.Lock()
pc.paused = false
pc.mu.Unlock()
} | go | func (pc *Periodic) Resume() {
pc.mu.Lock()
pc.paused = false
pc.mu.Unlock()
} | [
"func",
"(",
"pc",
"*",
"Periodic",
")",
"Resume",
"(",
")",
"{",
"pc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"pc",
".",
"paused",
"=",
"false",
"\n",
"pc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // Resume resumes periodic compactor. | [
"Resume",
"resumes",
"periodic",
"compactor",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v3compactor/periodic.go#L213-L217 | test |
etcd-io/etcd | clientv3/concurrency/mutex.go | Lock | func (m *Mutex) Lock(ctx context.Context) error {
s := m.s
client := m.s.Client()
m.myKey = fmt.Sprintf("%s%x", m.pfx, s.Lease())
cmp := v3.Compare(v3.CreateRevision(m.myKey), "=", 0)
// put self in lock waiters via myKey; oldest waiter holds lock
put := v3.OpPut(m.myKey, "", v3.WithLease(s.Lease()))
// reuse key in case this session already holds the lock
get := v3.OpGet(m.myKey)
// fetch current holder to complete uncontended path with only one RPC
getOwner := v3.OpGet(m.pfx, v3.WithFirstCreate()...)
resp, err := client.Txn(ctx).If(cmp).Then(put, getOwner).Else(get, getOwner).Commit()
if err != nil {
return err
}
m.myRev = resp.Header.Revision
if !resp.Succeeded {
m.myRev = resp.Responses[0].GetResponseRange().Kvs[0].CreateRevision
}
// 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
} | go | func (m *Mutex) Lock(ctx context.Context) error {
s := m.s
client := m.s.Client()
m.myKey = fmt.Sprintf("%s%x", m.pfx, s.Lease())
cmp := v3.Compare(v3.CreateRevision(m.myKey), "=", 0)
// put self in lock waiters via myKey; oldest waiter holds lock
put := v3.OpPut(m.myKey, "", v3.WithLease(s.Lease()))
// reuse key in case this session already holds the lock
get := v3.OpGet(m.myKey)
// fetch current holder to complete uncontended path with only one RPC
getOwner := v3.OpGet(m.pfx, v3.WithFirstCreate()...)
resp, err := client.Txn(ctx).If(cmp).Then(put, getOwner).Else(get, getOwner).Commit()
if err != nil {
return err
}
m.myRev = resp.Header.Revision
if !resp.Succeeded {
m.myRev = resp.Responses[0].GetResponseRange().Kvs[0].CreateRevision
}
// 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
} | [
"func",
"(",
"m",
"*",
"Mutex",
")",
"Lock",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"s",
":=",
"m",
".",
"s",
"\n",
"client",
":=",
"m",
".",
"s",
".",
"Client",
"(",
")",
"\n",
"m",
".",
"myKey",
"=",
"fmt",
".",
"Sprintf"... | // Lock locks the mutex with a cancelable context. If the context is canceled
// while trying to acquire the lock, the mutex tries to clean its stale lock entry. | [
"Lock",
"locks",
"the",
"mutex",
"with",
"a",
"cancelable",
"context",
".",
"If",
"the",
"context",
"is",
"canceled",
"while",
"trying",
"to",
"acquire",
"the",
"lock",
"the",
"mutex",
"tries",
"to",
"clean",
"its",
"stale",
"lock",
"entry",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/concurrency/mutex.go#L42-L78 | test |
etcd-io/etcd | clientv3/concurrency/mutex.go | NewLocker | func NewLocker(s *Session, pfx string) sync.Locker {
return &lockerMutex{NewMutex(s, pfx)}
} | go | func NewLocker(s *Session, pfx string) sync.Locker {
return &lockerMutex{NewMutex(s, pfx)}
} | [
"func",
"NewLocker",
"(",
"s",
"*",
"Session",
",",
"pfx",
"string",
")",
"sync",
".",
"Locker",
"{",
"return",
"&",
"lockerMutex",
"{",
"NewMutex",
"(",
"s",
",",
"pfx",
")",
"}",
"\n",
"}"
] | // NewLocker creates a sync.Locker backed by an etcd mutex. | [
"NewLocker",
"creates",
"a",
"sync",
".",
"Locker",
"backed",
"by",
"an",
"etcd",
"mutex",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/concurrency/mutex.go#L115-L117 | test |
etcd-io/etcd | pkg/schedule/schedule.go | NewFIFOScheduler | func NewFIFOScheduler() Scheduler {
f := &fifo{
resume: make(chan struct{}, 1),
donec: make(chan struct{}, 1),
}
f.finishCond = sync.NewCond(&f.mu)
f.ctx, f.cancel = context.WithCancel(context.Background())
go f.run()
return f
} | go | func NewFIFOScheduler() Scheduler {
f := &fifo{
resume: make(chan struct{}, 1),
donec: make(chan struct{}, 1),
}
f.finishCond = sync.NewCond(&f.mu)
f.ctx, f.cancel = context.WithCancel(context.Background())
go f.run()
return f
} | [
"func",
"NewFIFOScheduler",
"(",
")",
"Scheduler",
"{",
"f",
":=",
"&",
"fifo",
"{",
"resume",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"1",
")",
",",
"donec",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"1",
")",
",",
"}",
"\n... | // NewFIFOScheduler returns a Scheduler that schedules jobs in FIFO
// order sequentially | [
"NewFIFOScheduler",
"returns",
"a",
"Scheduler",
"that",
"schedules",
"jobs",
"in",
"FIFO",
"order",
"sequentially"
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/schedule/schedule.go#L63-L72 | test |
etcd-io/etcd | pkg/schedule/schedule.go | Schedule | func (f *fifo) Schedule(j Job) {
f.mu.Lock()
defer f.mu.Unlock()
if f.cancel == nil {
panic("schedule: schedule to stopped scheduler")
}
if len(f.pendings) == 0 {
select {
case f.resume <- struct{}{}:
default:
}
}
f.pendings = append(f.pendings, j)
} | go | func (f *fifo) Schedule(j Job) {
f.mu.Lock()
defer f.mu.Unlock()
if f.cancel == nil {
panic("schedule: schedule to stopped scheduler")
}
if len(f.pendings) == 0 {
select {
case f.resume <- struct{}{}:
default:
}
}
f.pendings = append(f.pendings, j)
} | [
"func",
"(",
"f",
"*",
"fifo",
")",
"Schedule",
"(",
"j",
"Job",
")",
"{",
"f",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"f",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"f",
".",
"cancel",
"==",
"nil",
"{",
"panic",
"(",
"\"sch... | // Schedule schedules a job that will be ran in FIFO order sequentially. | [
"Schedule",
"schedules",
"a",
"job",
"that",
"will",
"be",
"ran",
"in",
"FIFO",
"order",
"sequentially",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/schedule/schedule.go#L75-L90 | test |
etcd-io/etcd | pkg/schedule/schedule.go | Stop | func (f *fifo) Stop() {
f.mu.Lock()
f.cancel()
f.cancel = nil
f.mu.Unlock()
<-f.donec
} | go | func (f *fifo) Stop() {
f.mu.Lock()
f.cancel()
f.cancel = nil
f.mu.Unlock()
<-f.donec
} | [
"func",
"(",
"f",
"*",
"fifo",
")",
"Stop",
"(",
")",
"{",
"f",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"f",
".",
"cancel",
"(",
")",
"\n",
"f",
".",
"cancel",
"=",
"nil",
"\n",
"f",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"<-",
"f",
... | // Stop stops the scheduler and cancels all pending jobs. | [
"Stop",
"stops",
"the",
"scheduler",
"and",
"cancels",
"all",
"pending",
"jobs",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/schedule/schedule.go#L119-L125 | test |
etcd-io/etcd | functional/agent/server.go | NewServer | func NewServer(
lg *zap.Logger,
network string,
address string,
) *Server {
return &Server{
lg: lg,
network: network,
address: address,
last: rpcpb.Operation_NOT_STARTED,
advertiseClientPortToProxy: make(map[int]proxy.Server),
advertisePeerPortToProxy: make(map[int]proxy.Server),
}
} | go | func NewServer(
lg *zap.Logger,
network string,
address string,
) *Server {
return &Server{
lg: lg,
network: network,
address: address,
last: rpcpb.Operation_NOT_STARTED,
advertiseClientPortToProxy: make(map[int]proxy.Server),
advertisePeerPortToProxy: make(map[int]proxy.Server),
}
} | [
"func",
"NewServer",
"(",
"lg",
"*",
"zap",
".",
"Logger",
",",
"network",
"string",
",",
"address",
"string",
",",
")",
"*",
"Server",
"{",
"return",
"&",
"Server",
"{",
"lg",
":",
"lg",
",",
"network",
":",
"network",
",",
"address",
":",
"address"... | // NewServer returns a new agent server. | [
"NewServer",
"returns",
"a",
"new",
"agent",
"server",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/agent/server.go#L61-L74 | test |
etcd-io/etcd | functional/agent/server.go | StartServe | func (srv *Server) StartServe() error {
var err error
srv.ln, err = net.Listen(srv.network, srv.address)
if err != nil {
return err
}
var opts []grpc.ServerOption
opts = append(opts, grpc.MaxRecvMsgSize(int(maxRequestBytes+grpcOverheadBytes)))
opts = append(opts, grpc.MaxSendMsgSize(maxSendBytes))
opts = append(opts, grpc.MaxConcurrentStreams(maxStreams))
srv.grpcServer = grpc.NewServer(opts...)
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
} | go | func (srv *Server) StartServe() error {
var err error
srv.ln, err = net.Listen(srv.network, srv.address)
if err != nil {
return err
}
var opts []grpc.ServerOption
opts = append(opts, grpc.MaxRecvMsgSize(int(maxRequestBytes+grpcOverheadBytes)))
opts = append(opts, grpc.MaxSendMsgSize(maxSendBytes))
opts = append(opts, grpc.MaxConcurrentStreams(maxStreams))
srv.grpcServer = grpc.NewServer(opts...)
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
} | [
"func",
"(",
"srv",
"*",
"Server",
")",
"StartServe",
"(",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"srv",
".",
"ln",
",",
"err",
"=",
"net",
".",
"Listen",
"(",
"srv",
".",
"network",
",",
"srv",
".",
"address",
")",
"\n",
"if",
"err",
... | // StartServe starts serving agent server. | [
"StartServe",
"starts",
"serving",
"agent",
"server",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/agent/server.go#L84-L119 | test |
etcd-io/etcd | functional/agent/server.go | Stop | func (srv *Server) Stop() {
srv.lg.Info("gRPC server stopping", zap.String("address", srv.address))
srv.grpcServer.Stop()
srv.lg.Info("gRPC server stopped", zap.String("address", srv.address))
} | go | func (srv *Server) Stop() {
srv.lg.Info("gRPC server stopping", zap.String("address", srv.address))
srv.grpcServer.Stop()
srv.lg.Info("gRPC server stopped", zap.String("address", srv.address))
} | [
"func",
"(",
"srv",
"*",
"Server",
")",
"Stop",
"(",
")",
"{",
"srv",
".",
"lg",
".",
"Info",
"(",
"\"gRPC server stopping\"",
",",
"zap",
".",
"String",
"(",
"\"address\"",
",",
"srv",
".",
"address",
")",
")",
"\n",
"srv",
".",
"grpcServer",
".",
... | // Stop stops serving gRPC server. | [
"Stop",
"stops",
"serving",
"gRPC",
"server",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/agent/server.go#L122-L126 | test |
etcd-io/etcd | functional/agent/server.go | Transport | func (srv *Server) Transport(stream rpcpb.Transport_TransportServer) (err error) {
errc := make(chan error)
go func() {
for {
var req *rpcpb.Request
req, err = stream.Recv()
if err != nil {
errc <- err
// TODO: handle error and retry
return
}
if req.Member != nil {
srv.Member = req.Member
}
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
} | go | func (srv *Server) Transport(stream rpcpb.Transport_TransportServer) (err error) {
errc := make(chan error)
go func() {
for {
var req *rpcpb.Request
req, err = stream.Recv()
if err != nil {
errc <- err
// TODO: handle error and retry
return
}
if req.Member != nil {
srv.Member = req.Member
}
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
} | [
"func",
"(",
"srv",
"*",
"Server",
")",
"Transport",
"(",
"stream",
"rpcpb",
".",
"Transport_TransportServer",
")",
"(",
"err",
"error",
")",
"{",
"errc",
":=",
"make",
"(",
"chan",
"error",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"for",
"{",
"var",
... | // Transport communicates with etcd tester. | [
"Transport",
"communicates",
"with",
"etcd",
"tester",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/agent/server.go#L129-L169 | test |
etcd-io/etcd | pkg/osutil/interrupt_unix.go | RegisterInterruptHandler | func RegisterInterruptHandler(h InterruptHandler) {
interruptRegisterMu.Lock()
defer interruptRegisterMu.Unlock()
interruptHandlers = append(interruptHandlers, h)
} | go | func RegisterInterruptHandler(h InterruptHandler) {
interruptRegisterMu.Lock()
defer interruptRegisterMu.Unlock()
interruptHandlers = append(interruptHandlers, h)
} | [
"func",
"RegisterInterruptHandler",
"(",
"h",
"InterruptHandler",
")",
"{",
"interruptRegisterMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"interruptRegisterMu",
".",
"Unlock",
"(",
")",
"\n",
"interruptHandlers",
"=",
"append",
"(",
"interruptHandlers",
",",
"h",
... | // RegisterInterruptHandler registers a new InterruptHandler. Handlers registered
// after interrupt handing was initiated will not be executed. | [
"RegisterInterruptHandler",
"registers",
"a",
"new",
"InterruptHandler",
".",
"Handlers",
"registered",
"after",
"interrupt",
"handing",
"was",
"initiated",
"will",
"not",
"be",
"executed",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/osutil/interrupt_unix.go#L41-L45 | test |
etcd-io/etcd | pkg/osutil/interrupt_unix.go | HandleInterrupts | func HandleInterrupts(lg *zap.Logger) {
notifier := make(chan os.Signal, 1)
signal.Notify(notifier, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-notifier
interruptRegisterMu.Lock()
ihs := make([]InterruptHandler, len(interruptHandlers))
copy(ihs, interruptHandlers)
interruptRegisterMu.Unlock()
interruptExitMu.Lock()
if lg != nil {
lg.Info("received signal; shutting down", zap.String("signal", sig.String()))
} else {
plog.Noticef("received %v signal, shutting down...", sig)
}
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))
}()
} | go | func HandleInterrupts(lg *zap.Logger) {
notifier := make(chan os.Signal, 1)
signal.Notify(notifier, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-notifier
interruptRegisterMu.Lock()
ihs := make([]InterruptHandler, len(interruptHandlers))
copy(ihs, interruptHandlers)
interruptRegisterMu.Unlock()
interruptExitMu.Lock()
if lg != nil {
lg.Info("received signal; shutting down", zap.String("signal", sig.String()))
} else {
plog.Noticef("received %v signal, shutting down...", sig)
}
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))
}()
} | [
"func",
"HandleInterrupts",
"(",
"lg",
"*",
"zap",
".",
"Logger",
")",
"{",
"notifier",
":=",
"make",
"(",
"chan",
"os",
".",
"Signal",
",",
"1",
")",
"\n",
"signal",
".",
"Notify",
"(",
"notifier",
",",
"syscall",
".",
"SIGINT",
",",
"syscall",
".",... | // HandleInterrupts calls the handler functions on receiving a SIGINT or SIGTERM. | [
"HandleInterrupts",
"calls",
"the",
"handler",
"functions",
"on",
"receiving",
"a",
"SIGINT",
"or",
"SIGTERM",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/osutil/interrupt_unix.go#L48-L80 | test |
etcd-io/etcd | clientv3/op.go | OpGet | func OpGet(key string, opts ...OpOption) Op {
// WithPrefix and WithFromKey are not supported together
if isWithPrefix(opts) && isWithFromKey(opts) {
panic("`WithPrefix` and `WithFromKey` cannot be set at the same time, choose one")
}
ret := Op{t: tRange, key: []byte(key)}
ret.applyOpts(opts)
return ret
} | go | func OpGet(key string, opts ...OpOption) Op {
// WithPrefix and WithFromKey are not supported together
if isWithPrefix(opts) && isWithFromKey(opts) {
panic("`WithPrefix` and `WithFromKey` cannot be set at the same time, choose one")
}
ret := Op{t: tRange, key: []byte(key)}
ret.applyOpts(opts)
return ret
} | [
"func",
"OpGet",
"(",
"key",
"string",
",",
"opts",
"...",
"OpOption",
")",
"Op",
"{",
"if",
"isWithPrefix",
"(",
"opts",
")",
"&&",
"isWithFromKey",
"(",
"opts",
")",
"{",
"panic",
"(",
"\"`WithPrefix` and `WithFromKey` cannot be set at the same time, choose one\""... | // OpGet returns "get" operation based on given key and operation options. | [
"OpGet",
"returns",
"get",
"operation",
"based",
"on",
"given",
"key",
"and",
"operation",
"options",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/op.go#L220-L228 | test |
etcd-io/etcd | clientv3/op.go | OpDelete | func OpDelete(key string, opts ...OpOption) Op {
// WithPrefix and WithFromKey are not supported together
if isWithPrefix(opts) && isWithFromKey(opts) {
panic("`WithPrefix` and `WithFromKey` cannot be set at the same time, choose one")
}
ret := Op{t: tDeleteRange, key: []byte(key)}
ret.applyOpts(opts)
switch {
case ret.leaseID != 0:
panic("unexpected lease in delete")
case ret.limit != 0:
panic("unexpected limit in delete")
case ret.rev != 0:
panic("unexpected revision in delete")
case ret.sort != nil:
panic("unexpected sort in delete")
case ret.serializable:
panic("unexpected serializable in delete")
case ret.countOnly:
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
} | go | func OpDelete(key string, opts ...OpOption) Op {
// WithPrefix and WithFromKey are not supported together
if isWithPrefix(opts) && isWithFromKey(opts) {
panic("`WithPrefix` and `WithFromKey` cannot be set at the same time, choose one")
}
ret := Op{t: tDeleteRange, key: []byte(key)}
ret.applyOpts(opts)
switch {
case ret.leaseID != 0:
panic("unexpected lease in delete")
case ret.limit != 0:
panic("unexpected limit in delete")
case ret.rev != 0:
panic("unexpected revision in delete")
case ret.sort != nil:
panic("unexpected sort in delete")
case ret.serializable:
panic("unexpected serializable in delete")
case ret.countOnly:
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
} | [
"func",
"OpDelete",
"(",
"key",
"string",
",",
"opts",
"...",
"OpOption",
")",
"Op",
"{",
"if",
"isWithPrefix",
"(",
"opts",
")",
"&&",
"isWithFromKey",
"(",
"opts",
")",
"{",
"panic",
"(",
"\"`WithPrefix` and `WithFromKey` cannot be set at the same time, choose one... | // OpDelete returns "delete" operation based on given key and operation options. | [
"OpDelete",
"returns",
"delete",
"operation",
"based",
"on",
"given",
"key",
"and",
"operation",
"options",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/op.go#L231-L261 | test |
etcd-io/etcd | clientv3/op.go | OpPut | func OpPut(key, val string, opts ...OpOption) Op {
ret := Op{t: tPut, key: []byte(key), val: []byte(val)}
ret.applyOpts(opts)
switch {
case ret.end != nil:
panic("unexpected range in put")
case ret.limit != 0:
panic("unexpected limit in put")
case ret.rev != 0:
panic("unexpected revision in put")
case ret.sort != nil:
panic("unexpected sort in put")
case ret.serializable:
panic("unexpected serializable in put")
case ret.countOnly:
panic("unexpected countOnly in put")
case ret.minModRev != 0, ret.maxModRev != 0:
panic("unexpected mod revision filter in 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
} | go | func OpPut(key, val string, opts ...OpOption) Op {
ret := Op{t: tPut, key: []byte(key), val: []byte(val)}
ret.applyOpts(opts)
switch {
case ret.end != nil:
panic("unexpected range in put")
case ret.limit != 0:
panic("unexpected limit in put")
case ret.rev != 0:
panic("unexpected revision in put")
case ret.sort != nil:
panic("unexpected sort in put")
case ret.serializable:
panic("unexpected serializable in put")
case ret.countOnly:
panic("unexpected countOnly in put")
case ret.minModRev != 0, ret.maxModRev != 0:
panic("unexpected mod revision filter in 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
} | [
"func",
"OpPut",
"(",
"key",
",",
"val",
"string",
",",
"opts",
"...",
"OpOption",
")",
"Op",
"{",
"ret",
":=",
"Op",
"{",
"t",
":",
"tPut",
",",
"key",
":",
"[",
"]",
"byte",
"(",
"key",
")",
",",
"val",
":",
"[",
"]",
"byte",
"(",
"val",
... | // OpPut returns "put" operation based on given key-value and operation options. | [
"OpPut",
"returns",
"put",
"operation",
"based",
"on",
"given",
"key",
"-",
"value",
"and",
"operation",
"options",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/op.go#L264-L290 | test |
etcd-io/etcd | clientv3/op.go | OpTxn | func OpTxn(cmps []Cmp, thenOps []Op, elseOps []Op) Op {
return Op{t: tTxn, cmps: cmps, thenOps: thenOps, elseOps: elseOps}
} | go | func OpTxn(cmps []Cmp, thenOps []Op, elseOps []Op) Op {
return Op{t: tTxn, cmps: cmps, thenOps: thenOps, elseOps: elseOps}
} | [
"func",
"OpTxn",
"(",
"cmps",
"[",
"]",
"Cmp",
",",
"thenOps",
"[",
"]",
"Op",
",",
"elseOps",
"[",
"]",
"Op",
")",
"Op",
"{",
"return",
"Op",
"{",
"t",
":",
"tTxn",
",",
"cmps",
":",
"cmps",
",",
"thenOps",
":",
"thenOps",
",",
"elseOps",
":",... | // OpTxn returns "txn" operation based on given transaction conditions. | [
"OpTxn",
"returns",
"txn",
"operation",
"based",
"on",
"given",
"transaction",
"conditions",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/op.go#L293-L295 | test |
etcd-io/etcd | clientv3/op.go | WithFromKey | func WithFromKey() OpOption {
return func(op *Op) {
if len(op.key) == 0 {
op.key = []byte{0}
}
op.end = []byte("\x00")
}
} | go | func WithFromKey() OpOption {
return func(op *Op) {
if len(op.key) == 0 {
op.key = []byte{0}
}
op.end = []byte("\x00")
}
} | [
"func",
"WithFromKey",
"(",
")",
"OpOption",
"{",
"return",
"func",
"(",
"op",
"*",
"Op",
")",
"{",
"if",
"len",
"(",
"op",
".",
"key",
")",
"==",
"0",
"{",
"op",
".",
"key",
"=",
"[",
"]",
"byte",
"{",
"0",
"}",
"\n",
"}",
"\n",
"op",
".",... | // WithFromKey specifies the range of 'Get', 'Delete', 'Watch' requests
// to be equal or greater than the key in the argument. | [
"WithFromKey",
"specifies",
"the",
"range",
"of",
"Get",
"Delete",
"Watch",
"requests",
"to",
"be",
"equal",
"or",
"greater",
"than",
"the",
"key",
"in",
"the",
"argument",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/op.go#L403-L410 | test |
etcd-io/etcd | clientv3/op.go | withTop | func withTop(target SortTarget, order SortOrder) []OpOption {
return []OpOption{WithPrefix(), WithSort(target, order), WithLimit(1)}
} | go | func withTop(target SortTarget, order SortOrder) []OpOption {
return []OpOption{WithPrefix(), WithSort(target, order), WithLimit(1)}
} | [
"func",
"withTop",
"(",
"target",
"SortTarget",
",",
"order",
"SortOrder",
")",
"[",
"]",
"OpOption",
"{",
"return",
"[",
"]",
"OpOption",
"{",
"WithPrefix",
"(",
")",
",",
"WithSort",
"(",
"target",
",",
"order",
")",
",",
"WithLimit",
"(",
"1",
")",
... | // withTop gets the first key over the get's prefix given a sort order | [
"withTop",
"gets",
"the",
"first",
"key",
"over",
"the",
"get",
"s",
"prefix",
"given",
"a",
"sort",
"order"
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/op.go#L461-L463 | test |
etcd-io/etcd | wal/util.go | Exist | func Exist(dir string) bool {
names, err := fileutil.ReadDir(dir, fileutil.WithExt(".wal"))
if err != nil {
return false
}
return len(names) != 0
} | go | func Exist(dir string) bool {
names, err := fileutil.ReadDir(dir, fileutil.WithExt(".wal"))
if err != nil {
return false
}
return len(names) != 0
} | [
"func",
"Exist",
"(",
"dir",
"string",
")",
"bool",
"{",
"names",
",",
"err",
":=",
"fileutil",
".",
"ReadDir",
"(",
"dir",
",",
"fileutil",
".",
"WithExt",
"(",
"\".wal\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}... | // Exist returns true if there are any files in a given directory. | [
"Exist",
"returns",
"true",
"if",
"there",
"are",
"any",
"files",
"in",
"a",
"given",
"directory",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/wal/util.go#L30-L36 | test |
etcd-io/etcd | wal/util.go | searchIndex | func searchIndex(lg *zap.Logger, names []string, index uint64) (int, bool) {
for i := len(names) - 1; i >= 0; i-- {
name := names[i]
_, curIndex, err := parseWALName(name)
if err != nil {
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
} | go | func searchIndex(lg *zap.Logger, names []string, index uint64) (int, bool) {
for i := len(names) - 1; i >= 0; i-- {
name := names[i]
_, curIndex, err := parseWALName(name)
if err != nil {
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
} | [
"func",
"searchIndex",
"(",
"lg",
"*",
"zap",
".",
"Logger",
",",
"names",
"[",
"]",
"string",
",",
"index",
"uint64",
")",
"(",
"int",
",",
"bool",
")",
"{",
"for",
"i",
":=",
"len",
"(",
"names",
")",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i"... | // searchIndex returns the last array index of names whose raft index section is
// equal to or smaller than the given index.
// The given names MUST be sorted. | [
"searchIndex",
"returns",
"the",
"last",
"array",
"index",
"of",
"names",
"whose",
"raft",
"index",
"section",
"is",
"equal",
"to",
"or",
"smaller",
"than",
"the",
"given",
"index",
".",
"The",
"given",
"names",
"MUST",
"be",
"sorted",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/wal/util.go#L41-L57 | test |
etcd-io/etcd | wal/util.go | isValidSeq | func isValidSeq(lg *zap.Logger, names []string) bool {
var lastSeq uint64
for _, name := range names {
curSeq, _, err := parseWALName(name)
if err != nil {
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 lastSeq != 0 && lastSeq != curSeq-1 {
return false
}
lastSeq = curSeq
}
return true
} | go | func isValidSeq(lg *zap.Logger, names []string) bool {
var lastSeq uint64
for _, name := range names {
curSeq, _, err := parseWALName(name)
if err != nil {
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 lastSeq != 0 && lastSeq != curSeq-1 {
return false
}
lastSeq = curSeq
}
return true
} | [
"func",
"isValidSeq",
"(",
"lg",
"*",
"zap",
".",
"Logger",
",",
"names",
"[",
"]",
"string",
")",
"bool",
"{",
"var",
"lastSeq",
"uint64",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"names",
"{",
"curSeq",
",",
"_",
",",
"err",
":=",
"parseWALN... | // names should have been sorted based on sequence number.
// isValidSeq checks whether seq increases continuously. | [
"names",
"should",
"have",
"been",
"sorted",
"based",
"on",
"sequence",
"number",
".",
"isValidSeq",
"checks",
"whether",
"seq",
"increases",
"continuously",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/wal/util.go#L61-L78 | test |
etcd-io/etcd | pkg/transport/listener.go | NewListener | func NewListener(addr, scheme string, tlsinfo *TLSInfo) (l net.Listener, err error) {
if l, err = newListener(addr, scheme); err != nil {
return nil, err
}
return wrapTLS(scheme, tlsinfo, l)
} | go | func NewListener(addr, scheme string, tlsinfo *TLSInfo) (l net.Listener, err error) {
if l, err = newListener(addr, scheme); err != nil {
return nil, err
}
return wrapTLS(scheme, tlsinfo, l)
} | [
"func",
"NewListener",
"(",
"addr",
",",
"scheme",
"string",
",",
"tlsinfo",
"*",
"TLSInfo",
")",
"(",
"l",
"net",
".",
"Listener",
",",
"err",
"error",
")",
"{",
"if",
"l",
",",
"err",
"=",
"newListener",
"(",
"addr",
",",
"scheme",
")",
";",
"err... | // NewListener creates a new listner. | [
"NewListener",
"creates",
"a",
"new",
"listner",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/transport/listener.go#L40-L45 | test |
etcd-io/etcd | pkg/transport/listener.go | cafiles | func (info TLSInfo) cafiles() []string {
cs := make([]string, 0)
if info.TrustedCAFile != "" {
cs = append(cs, info.TrustedCAFile)
}
return cs
} | go | func (info TLSInfo) cafiles() []string {
cs := make([]string, 0)
if info.TrustedCAFile != "" {
cs = append(cs, info.TrustedCAFile)
}
return cs
} | [
"func",
"(",
"info",
"TLSInfo",
")",
"cafiles",
"(",
")",
"[",
"]",
"string",
"{",
"cs",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
")",
"\n",
"if",
"info",
".",
"TrustedCAFile",
"!=",
"\"\"",
"{",
"cs",
"=",
"append",
"(",
"cs",
",",
"in... | // cafiles returns a list of CA file paths. | [
"cafiles",
"returns",
"a",
"list",
"of",
"CA",
"file",
"paths",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/transport/listener.go#L324-L330 | test |
etcd-io/etcd | pkg/transport/listener.go | ServerConfig | func (info TLSInfo) ServerConfig() (*tls.Config, error) {
cfg, err := info.baseConfig()
if err != nil {
return nil, err
}
cfg.ClientAuth = tls.NoClientCert
if info.TrustedCAFile != "" || info.ClientCertAuth {
cfg.ClientAuth = tls.RequireAndVerifyClientCert
}
cs := info.cafiles()
if len(cs) > 0 {
cp, err := tlsutil.NewCertPool(cs)
if err != nil {
return nil, err
}
cfg.ClientCAs = cp
}
// "h2" NextProtos is necessary for enabling HTTP2 for go's HTTP server
cfg.NextProtos = []string{"h2"}
return cfg, nil
} | go | func (info TLSInfo) ServerConfig() (*tls.Config, error) {
cfg, err := info.baseConfig()
if err != nil {
return nil, err
}
cfg.ClientAuth = tls.NoClientCert
if info.TrustedCAFile != "" || info.ClientCertAuth {
cfg.ClientAuth = tls.RequireAndVerifyClientCert
}
cs := info.cafiles()
if len(cs) > 0 {
cp, err := tlsutil.NewCertPool(cs)
if err != nil {
return nil, err
}
cfg.ClientCAs = cp
}
// "h2" NextProtos is necessary for enabling HTTP2 for go's HTTP server
cfg.NextProtos = []string{"h2"}
return cfg, nil
} | [
"func",
"(",
"info",
"TLSInfo",
")",
"ServerConfig",
"(",
")",
"(",
"*",
"tls",
".",
"Config",
",",
"error",
")",
"{",
"cfg",
",",
"err",
":=",
"info",
".",
"baseConfig",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",... | // ServerConfig generates a tls.Config object for use by an HTTP server. | [
"ServerConfig",
"generates",
"a",
"tls",
".",
"Config",
"object",
"for",
"use",
"by",
"an",
"HTTP",
"server",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/transport/listener.go#L333-L357 | test |
etcd-io/etcd | pkg/transport/listener.go | ClientConfig | func (info TLSInfo) ClientConfig() (*tls.Config, error) {
var cfg *tls.Config
var err error
if !info.Empty() {
cfg, err = info.baseConfig()
if err != nil {
return nil, err
}
} else {
cfg = &tls.Config{ServerName: info.ServerName}
}
cfg.InsecureSkipVerify = info.InsecureSkipVerify
cs := info.cafiles()
if len(cs) > 0 {
cfg.RootCAs, err = tlsutil.NewCertPool(cs)
if err != nil {
return nil, err
}
}
if info.selfCert {
cfg.InsecureSkipVerify = true
}
if info.EmptyCN {
hasNonEmptyCN := false
cn := ""
tlsutil.NewCert(info.CertFile, info.KeyFile, func(certPEMBlock []byte, keyPEMBlock []byte) (tls.Certificate, error) {
var block *pem.Block
block, _ = pem.Decode(certPEMBlock)
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return tls.Certificate{}, err
}
if len(cert.Subject.CommonName) != 0 {
hasNonEmptyCN = true
cn = cert.Subject.CommonName
}
return tls.X509KeyPair(certPEMBlock, keyPEMBlock)
})
if hasNonEmptyCN {
return nil, fmt.Errorf("cert has non empty Common Name (%s)", cn)
}
}
return cfg, nil
} | go | func (info TLSInfo) ClientConfig() (*tls.Config, error) {
var cfg *tls.Config
var err error
if !info.Empty() {
cfg, err = info.baseConfig()
if err != nil {
return nil, err
}
} else {
cfg = &tls.Config{ServerName: info.ServerName}
}
cfg.InsecureSkipVerify = info.InsecureSkipVerify
cs := info.cafiles()
if len(cs) > 0 {
cfg.RootCAs, err = tlsutil.NewCertPool(cs)
if err != nil {
return nil, err
}
}
if info.selfCert {
cfg.InsecureSkipVerify = true
}
if info.EmptyCN {
hasNonEmptyCN := false
cn := ""
tlsutil.NewCert(info.CertFile, info.KeyFile, func(certPEMBlock []byte, keyPEMBlock []byte) (tls.Certificate, error) {
var block *pem.Block
block, _ = pem.Decode(certPEMBlock)
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return tls.Certificate{}, err
}
if len(cert.Subject.CommonName) != 0 {
hasNonEmptyCN = true
cn = cert.Subject.CommonName
}
return tls.X509KeyPair(certPEMBlock, keyPEMBlock)
})
if hasNonEmptyCN {
return nil, fmt.Errorf("cert has non empty Common Name (%s)", cn)
}
}
return cfg, nil
} | [
"func",
"(",
"info",
"TLSInfo",
")",
"ClientConfig",
"(",
")",
"(",
"*",
"tls",
".",
"Config",
",",
"error",
")",
"{",
"var",
"cfg",
"*",
"tls",
".",
"Config",
"\n",
"var",
"err",
"error",
"\n",
"if",
"!",
"info",
".",
"Empty",
"(",
")",
"{",
"... | // ClientConfig generates a tls.Config object for use by an HTTP client. | [
"ClientConfig",
"generates",
"a",
"tls",
".",
"Config",
"object",
"for",
"use",
"by",
"an",
"HTTP",
"client",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/transport/listener.go#L360-L408 | test |
etcd-io/etcd | pkg/transport/keepalive_listener.go | newTLSKeepaliveListener | func newTLSKeepaliveListener(inner net.Listener, config *tls.Config) net.Listener {
l := &tlsKeepaliveListener{}
l.Listener = inner
l.config = config
return l
} | go | func newTLSKeepaliveListener(inner net.Listener, config *tls.Config) net.Listener {
l := &tlsKeepaliveListener{}
l.Listener = inner
l.config = config
return l
} | [
"func",
"newTLSKeepaliveListener",
"(",
"inner",
"net",
".",
"Listener",
",",
"config",
"*",
"tls",
".",
"Config",
")",
"net",
".",
"Listener",
"{",
"l",
":=",
"&",
"tlsKeepaliveListener",
"{",
"}",
"\n",
"l",
".",
"Listener",
"=",
"inner",
"\n",
"l",
... | // NewListener creates a Listener which accepts connections from an inner
// Listener and wraps each connection with Server.
// The configuration config must be non-nil and must have
// at least one certificate. | [
"NewListener",
"creates",
"a",
"Listener",
"which",
"accepts",
"connections",
"from",
"an",
"inner",
"Listener",
"and",
"wraps",
"each",
"connection",
"with",
"Server",
".",
"The",
"configuration",
"config",
"must",
"be",
"non",
"-",
"nil",
"and",
"must",
"hav... | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/transport/keepalive_listener.go#L89-L94 | test |
etcd-io/etcd | etcdserver/apply_v2.go | applyV2Request | func (s *EtcdServer) applyV2Request(r *RequestV2) Response {
defer warnOfExpensiveRequest(s.getLogger(), time.Now(), r, nil, nil)
switch r.Method {
case "POST":
return s.applyV2.Post(r)
case "PUT":
return s.applyV2.Put(r)
case "DELETE":
return s.applyV2.Delete(r)
case "QGET":
return s.applyV2.QGet(r)
case "SYNC":
return s.applyV2.Sync(r)
default:
// This should never be reached, but just in case:
return Response{Err: ErrUnknownMethod}
}
} | go | func (s *EtcdServer) applyV2Request(r *RequestV2) Response {
defer warnOfExpensiveRequest(s.getLogger(), time.Now(), r, nil, nil)
switch r.Method {
case "POST":
return s.applyV2.Post(r)
case "PUT":
return s.applyV2.Put(r)
case "DELETE":
return s.applyV2.Delete(r)
case "QGET":
return s.applyV2.QGet(r)
case "SYNC":
return s.applyV2.Sync(r)
default:
// This should never be reached, but just in case:
return Response{Err: ErrUnknownMethod}
}
} | [
"func",
"(",
"s",
"*",
"EtcdServer",
")",
"applyV2Request",
"(",
"r",
"*",
"RequestV2",
")",
"Response",
"{",
"defer",
"warnOfExpensiveRequest",
"(",
"s",
".",
"getLogger",
"(",
")",
",",
"time",
".",
"Now",
"(",
")",
",",
"r",
",",
"nil",
",",
"nil"... | // applyV2Request interprets r as a call to v2store.X
// and returns a Response interpreted from v2store.Event | [
"applyV2Request",
"interprets",
"r",
"as",
"a",
"call",
"to",
"v2store",
".",
"X",
"and",
"returns",
"a",
"Response",
"interpreted",
"from",
"v2store",
".",
"Event"
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/apply_v2.go#L116-L134 | test |
etcd-io/etcd | etcdctl/ctlv3/command/role_command.go | NewRoleCommand | func NewRoleCommand() *cobra.Command {
ac := &cobra.Command{
Use: "role <subcommand>",
Short: "Role related commands",
}
ac.AddCommand(newRoleAddCommand())
ac.AddCommand(newRoleDeleteCommand())
ac.AddCommand(newRoleGetCommand())
ac.AddCommand(newRoleListCommand())
ac.AddCommand(newRoleGrantPermissionCommand())
ac.AddCommand(newRoleRevokePermissionCommand())
return ac
} | go | func NewRoleCommand() *cobra.Command {
ac := &cobra.Command{
Use: "role <subcommand>",
Short: "Role related commands",
}
ac.AddCommand(newRoleAddCommand())
ac.AddCommand(newRoleDeleteCommand())
ac.AddCommand(newRoleGetCommand())
ac.AddCommand(newRoleListCommand())
ac.AddCommand(newRoleGrantPermissionCommand())
ac.AddCommand(newRoleRevokePermissionCommand())
return ac
} | [
"func",
"NewRoleCommand",
"(",
")",
"*",
"cobra",
".",
"Command",
"{",
"ac",
":=",
"&",
"cobra",
".",
"Command",
"{",
"Use",
":",
"\"role <subcommand>\"",
",",
"Short",
":",
"\"Role related commands\"",
",",
"}",
"\n",
"ac",
".",
"AddCommand",
"(",
"newRol... | // NewRoleCommand returns the cobra command for "role". | [
"NewRoleCommand",
"returns",
"the",
"cobra",
"command",
"for",
"role",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/role_command.go#L31-L45 | test |
etcd-io/etcd | etcdctl/ctlv3/command/role_command.go | roleAddCommandFunc | func roleAddCommandFunc(cmd *cobra.Command, args []string) {
if len(args) != 1 {
ExitWithError(ExitBadArgs, fmt.Errorf("role add command requires role name as its argument"))
}
resp, err := mustClientFromCmd(cmd).Auth.RoleAdd(context.TODO(), args[0])
if err != nil {
ExitWithError(ExitError, err)
}
display.RoleAdd(args[0], *resp)
} | go | func roleAddCommandFunc(cmd *cobra.Command, args []string) {
if len(args) != 1 {
ExitWithError(ExitBadArgs, fmt.Errorf("role add command requires role name as its argument"))
}
resp, err := mustClientFromCmd(cmd).Auth.RoleAdd(context.TODO(), args[0])
if err != nil {
ExitWithError(ExitError, err)
}
display.RoleAdd(args[0], *resp)
} | [
"func",
"roleAddCommandFunc",
"(",
"cmd",
"*",
"cobra",
".",
"Command",
",",
"args",
"[",
"]",
"string",
")",
"{",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
"{",
"ExitWithError",
"(",
"ExitBadArgs",
",",
"fmt",
".",
"Errorf",
"(",
"\"role add command req... | // roleAddCommandFunc executes the "role add" command. | [
"roleAddCommandFunc",
"executes",
"the",
"role",
"add",
"command",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/role_command.go#L106-L117 | test |
etcd-io/etcd | etcdctl/ctlv3/command/role_command.go | roleGetCommandFunc | func roleGetCommandFunc(cmd *cobra.Command, args []string) {
if len(args) != 1 {
ExitWithError(ExitBadArgs, fmt.Errorf("role get command requires role name as its argument"))
}
name := args[0]
resp, err := mustClientFromCmd(cmd).Auth.RoleGet(context.TODO(), name)
if err != nil {
ExitWithError(ExitError, err)
}
display.RoleGet(name, *resp)
} | go | func roleGetCommandFunc(cmd *cobra.Command, args []string) {
if len(args) != 1 {
ExitWithError(ExitBadArgs, fmt.Errorf("role get command requires role name as its argument"))
}
name := args[0]
resp, err := mustClientFromCmd(cmd).Auth.RoleGet(context.TODO(), name)
if err != nil {
ExitWithError(ExitError, err)
}
display.RoleGet(name, *resp)
} | [
"func",
"roleGetCommandFunc",
"(",
"cmd",
"*",
"cobra",
".",
"Command",
",",
"args",
"[",
"]",
"string",
")",
"{",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
"{",
"ExitWithError",
"(",
"ExitBadArgs",
",",
"fmt",
".",
"Errorf",
"(",
"\"role get command req... | // roleGetCommandFunc executes the "role get" command. | [
"roleGetCommandFunc",
"executes",
"the",
"role",
"get",
"command",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/role_command.go#L134-L146 | test |
etcd-io/etcd | etcdctl/ctlv3/command/role_command.go | roleGrantPermissionCommandFunc | func roleGrantPermissionCommandFunc(cmd *cobra.Command, args []string) {
if len(args) < 3 {
ExitWithError(ExitBadArgs, fmt.Errorf("role grant command requires role name, permission type, and key [endkey] as its argument"))
}
perm, err := clientv3.StrToPermissionType(args[1])
if err != nil {
ExitWithError(ExitBadArgs, err)
}
key, rangeEnd := permRange(args[2:])
resp, err := mustClientFromCmd(cmd).Auth.RoleGrantPermission(context.TODO(), args[0], key, rangeEnd, perm)
if err != nil {
ExitWithError(ExitError, err)
}
display.RoleGrantPermission(args[0], *resp)
} | go | func roleGrantPermissionCommandFunc(cmd *cobra.Command, args []string) {
if len(args) < 3 {
ExitWithError(ExitBadArgs, fmt.Errorf("role grant command requires role name, permission type, and key [endkey] as its argument"))
}
perm, err := clientv3.StrToPermissionType(args[1])
if err != nil {
ExitWithError(ExitBadArgs, err)
}
key, rangeEnd := permRange(args[2:])
resp, err := mustClientFromCmd(cmd).Auth.RoleGrantPermission(context.TODO(), args[0], key, rangeEnd, perm)
if err != nil {
ExitWithError(ExitError, err)
}
display.RoleGrantPermission(args[0], *resp)
} | [
"func",
"roleGrantPermissionCommandFunc",
"(",
"cmd",
"*",
"cobra",
".",
"Command",
",",
"args",
"[",
"]",
"string",
")",
"{",
"if",
"len",
"(",
"args",
")",
"<",
"3",
"{",
"ExitWithError",
"(",
"ExitBadArgs",
",",
"fmt",
".",
"Errorf",
"(",
"\"role gran... | // roleGrantPermissionCommandFunc executes the "role grant-permission" command. | [
"roleGrantPermissionCommandFunc",
"executes",
"the",
"role",
"grant",
"-",
"permission",
"command",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/role_command.go#L163-L180 | test |
etcd-io/etcd | etcdctl/ctlv3/command/role_command.go | roleRevokePermissionCommandFunc | func roleRevokePermissionCommandFunc(cmd *cobra.Command, args []string) {
if len(args) < 2 {
ExitWithError(ExitBadArgs, fmt.Errorf("role revoke-permission command requires role name and key [endkey] as its argument"))
}
key, rangeEnd := permRange(args[1:])
resp, err := mustClientFromCmd(cmd).Auth.RoleRevokePermission(context.TODO(), args[0], key, rangeEnd)
if err != nil {
ExitWithError(ExitError, err)
}
display.RoleRevokePermission(args[0], args[1], rangeEnd, *resp)
} | go | func roleRevokePermissionCommandFunc(cmd *cobra.Command, args []string) {
if len(args) < 2 {
ExitWithError(ExitBadArgs, fmt.Errorf("role revoke-permission command requires role name and key [endkey] as its argument"))
}
key, rangeEnd := permRange(args[1:])
resp, err := mustClientFromCmd(cmd).Auth.RoleRevokePermission(context.TODO(), args[0], key, rangeEnd)
if err != nil {
ExitWithError(ExitError, err)
}
display.RoleRevokePermission(args[0], args[1], rangeEnd, *resp)
} | [
"func",
"roleRevokePermissionCommandFunc",
"(",
"cmd",
"*",
"cobra",
".",
"Command",
",",
"args",
"[",
"]",
"string",
")",
"{",
"if",
"len",
"(",
"args",
")",
"<",
"2",
"{",
"ExitWithError",
"(",
"ExitBadArgs",
",",
"fmt",
".",
"Errorf",
"(",
"\"role rev... | // roleRevokePermissionCommandFunc executes the "role revoke-permission" command. | [
"roleRevokePermissionCommandFunc",
"executes",
"the",
"role",
"revoke",
"-",
"permission",
"command",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/role_command.go#L183-L194 | test |
etcd-io/etcd | integration/cluster.go | NewCluster | func NewCluster(t testing.TB, size int) *cluster {
return newCluster(t, &ClusterConfig{Size: size})
} | go | func NewCluster(t testing.TB, size int) *cluster {
return newCluster(t, &ClusterConfig{Size: size})
} | [
"func",
"NewCluster",
"(",
"t",
"testing",
".",
"TB",
",",
"size",
"int",
")",
"*",
"cluster",
"{",
"return",
"newCluster",
"(",
"t",
",",
"&",
"ClusterConfig",
"{",
"Size",
":",
"size",
"}",
")",
"\n",
"}"
] | // NewCluster returns an unlaunched cluster of the given size which has been
// set to use static bootstrap. | [
"NewCluster",
"returns",
"an",
"unlaunched",
"cluster",
"of",
"the",
"given",
"size",
"which",
"has",
"been",
"set",
"to",
"use",
"static",
"bootstrap",
"."
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/integration/cluster.go#L208-L210 | test |
etcd-io/etcd | integration/cluster.go | NewClusterByConfig | func NewClusterByConfig(t testing.TB, cfg *ClusterConfig) *cluster {
return newCluster(t, cfg)
} | go | func NewClusterByConfig(t testing.TB, cfg *ClusterConfig) *cluster {
return newCluster(t, cfg)
} | [
"func",
"NewClusterByConfig",
"(",
"t",
"testing",
".",
"TB",
",",
"cfg",
"*",
"ClusterConfig",
")",
"*",
"cluster",
"{",
"return",
"newCluster",
"(",
"t",
",",
"cfg",
")",
"\n",
"}"
] | // NewClusterByConfig returns an unlaunched cluster defined by a cluster configuration | [
"NewClusterByConfig",
"returns",
"an",
"unlaunched",
"cluster",
"defined",
"by",
"a",
"cluster",
"configuration"
] | 616592d9ba993e3fe9798eef581316016df98906 | https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/integration/cluster.go#L213-L215 | test |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.