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
functional/rpcpb/member.go
CreateEtcdClient
func (m *Member) CreateEtcdClient(opts ...grpc.DialOption) (*clientv3.Client, error) { cfg, err := m.CreateEtcdClientConfig(opts...) if err != nil { return nil, err } return clientv3.New(*cfg) }
go
func (m *Member) CreateEtcdClient(opts ...grpc.DialOption) (*clientv3.Client, error) { cfg, err := m.CreateEtcdClientConfig(opts...) if err != nil { return nil, err } return clientv3.New(*cfg) }
[ "func", "(", "m", "*", "Member", ")", "CreateEtcdClient", "(", "opts", "...", "grpc", ".", "DialOption", ")", "(", "*", "clientv3", ".", "Client", ",", "error", ")", "{", "cfg", ",", "err", ":=", "m", ".", "CreateEtcdClientConfig", "(", "opts", "...", ...
// CreateEtcdClient creates a client from member.
[ "CreateEtcdClient", "creates", "a", "client", "from", "member", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/rpcpb/member.go#L124-L130
test
etcd-io/etcd
functional/rpcpb/member.go
CheckCompact
func (m *Member) CheckCompact(rev int64) error { cli, err := m.CreateEtcdClient() if err != nil { return fmt.Errorf("%v (%q)", err, m.EtcdClientEndpoint) } defer cli.Close() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) wch := cli.Watch(ctx, "\x00", clientv3.WithFromKey(), clientv3.Wi...
go
func (m *Member) CheckCompact(rev int64) error { cli, err := m.CreateEtcdClient() if err != nil { return fmt.Errorf("%v (%q)", err, m.EtcdClientEndpoint) } defer cli.Close() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) wch := cli.Watch(ctx, "\x00", clientv3.WithFromKey(), clientv3.Wi...
[ "func", "(", "m", "*", "Member", ")", "CheckCompact", "(", "rev", "int64", ")", "error", "{", "cli", ",", "err", ":=", "m", ".", "CreateEtcdClient", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"%v (%q)\"", ...
// CheckCompact ensures that historical data before given revision has been compacted.
[ "CheckCompact", "ensures", "that", "historical", "data", "before", "given", "revision", "has", "been", "compacted", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/rpcpb/member.go#L133-L153
test
etcd-io/etcd
functional/rpcpb/member.go
Defrag
func (m *Member) Defrag() error { cli, err := m.CreateEtcdClient() if err != nil { return fmt.Errorf("%v (%q)", err, m.EtcdClientEndpoint) } defer cli.Close() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) _, err = cli.Defragment(ctx, m.EtcdClientEndpoint) cancel() return err }
go
func (m *Member) Defrag() error { cli, err := m.CreateEtcdClient() if err != nil { return fmt.Errorf("%v (%q)", err, m.EtcdClientEndpoint) } defer cli.Close() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) _, err = cli.Defragment(ctx, m.EtcdClientEndpoint) cancel() return err }
[ "func", "(", "m", "*", "Member", ")", "Defrag", "(", ")", "error", "{", "cli", ",", "err", ":=", "m", ".", "CreateEtcdClient", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"%v (%q)\"", ",", "err", ",", "m"...
// Defrag runs defragmentation on this member.
[ "Defrag", "runs", "defragmentation", "on", "this", "member", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/rpcpb/member.go#L156-L167
test
etcd-io/etcd
functional/rpcpb/member.go
RevHash
func (m *Member) RevHash() (int64, int64, error) { conn, err := m.DialEtcdGRPCServer() if err != nil { return 0, 0, err } defer conn.Close() mt := pb.NewMaintenanceClient(conn) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) resp, err := mt.Hash(ctx, &pb.HashRequest{}, grpc.FailFast(fa...
go
func (m *Member) RevHash() (int64, int64, error) { conn, err := m.DialEtcdGRPCServer() if err != nil { return 0, 0, err } defer conn.Close() mt := pb.NewMaintenanceClient(conn) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) resp, err := mt.Hash(ctx, &pb.HashRequest{}, grpc.FailFast(fa...
[ "func", "(", "m", "*", "Member", ")", "RevHash", "(", ")", "(", "int64", ",", "int64", ",", "error", ")", "{", "conn", ",", "err", ":=", "m", ".", "DialEtcdGRPCServer", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "0", ","...
// RevHash fetches current revision and hash on this member.
[ "RevHash", "fetches", "current", "revision", "and", "hash", "on", "this", "member", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/rpcpb/member.go#L170-L187
test
etcd-io/etcd
functional/rpcpb/member.go
Rev
func (m *Member) Rev(ctx context.Context) (int64, error) { cli, err := m.CreateEtcdClient() if err != nil { return 0, fmt.Errorf("%v (%q)", err, m.EtcdClientEndpoint) } defer cli.Close() resp, err := cli.Status(ctx, m.EtcdClientEndpoint) if err != nil { return 0, err } return resp.Header.Revision, nil }
go
func (m *Member) Rev(ctx context.Context) (int64, error) { cli, err := m.CreateEtcdClient() if err != nil { return 0, fmt.Errorf("%v (%q)", err, m.EtcdClientEndpoint) } defer cli.Close() resp, err := cli.Status(ctx, m.EtcdClientEndpoint) if err != nil { return 0, err } return resp.Header.Revision, nil }
[ "func", "(", "m", "*", "Member", ")", "Rev", "(", "ctx", "context", ".", "Context", ")", "(", "int64", ",", "error", ")", "{", "cli", ",", "err", ":=", "m", ".", "CreateEtcdClient", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ...
// Rev fetches current revision on this member.
[ "Rev", "fetches", "current", "revision", "on", "this", "member", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/rpcpb/member.go#L190-L202
test
etcd-io/etcd
functional/rpcpb/member.go
Compact
func (m *Member) Compact(rev int64, timeout time.Duration) error { cli, err := m.CreateEtcdClient() if err != nil { return fmt.Errorf("%v (%q)", err, m.EtcdClientEndpoint) } defer cli.Close() ctx, cancel := context.WithTimeout(context.Background(), timeout) _, err = cli.Compact(ctx, rev, clientv3.WithCompactPh...
go
func (m *Member) Compact(rev int64, timeout time.Duration) error { cli, err := m.CreateEtcdClient() if err != nil { return fmt.Errorf("%v (%q)", err, m.EtcdClientEndpoint) } defer cli.Close() ctx, cancel := context.WithTimeout(context.Background(), timeout) _, err = cli.Compact(ctx, rev, clientv3.WithCompactPh...
[ "func", "(", "m", "*", "Member", ")", "Compact", "(", "rev", "int64", ",", "timeout", "time", ".", "Duration", ")", "error", "{", "cli", ",", "err", ":=", "m", ".", "CreateEtcdClient", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt",...
// Compact compacts member storage with given revision. // It blocks until it's physically done.
[ "Compact", "compacts", "member", "storage", "with", "given", "revision", ".", "It", "blocks", "until", "it", "s", "physically", "done", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/rpcpb/member.go#L206-L217
test
etcd-io/etcd
functional/rpcpb/member.go
IsLeader
func (m *Member) IsLeader() (bool, error) { cli, err := m.CreateEtcdClient() if err != nil { return false, fmt.Errorf("%v (%q)", err, m.EtcdClientEndpoint) } defer cli.Close() resp, err := cli.Status(context.Background(), m.EtcdClientEndpoint) if err != nil { return false, err } return resp.Header.MemberId...
go
func (m *Member) IsLeader() (bool, error) { cli, err := m.CreateEtcdClient() if err != nil { return false, fmt.Errorf("%v (%q)", err, m.EtcdClientEndpoint) } defer cli.Close() resp, err := cli.Status(context.Background(), m.EtcdClientEndpoint) if err != nil { return false, err } return resp.Header.MemberId...
[ "func", "(", "m", "*", "Member", ")", "IsLeader", "(", ")", "(", "bool", ",", "error", ")", "{", "cli", ",", "err", ":=", "m", ".", "CreateEtcdClient", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "fmt", ".", "Errorf", ...
// IsLeader returns true if this member is the current cluster leader.
[ "IsLeader", "returns", "true", "if", "this", "member", "is", "the", "current", "cluster", "leader", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/rpcpb/member.go#L220-L232
test
etcd-io/etcd
functional/rpcpb/member.go
WriteHealthKey
func (m *Member) WriteHealthKey() error { cli, err := m.CreateEtcdClient() if err != nil { return fmt.Errorf("%v (%q)", err, m.EtcdClientEndpoint) } defer cli.Close() // give enough time-out in case expensive requests (range/delete) are pending ctx, cancel := context.WithTimeout(context.Background(), 5*time.Se...
go
func (m *Member) WriteHealthKey() error { cli, err := m.CreateEtcdClient() if err != nil { return fmt.Errorf("%v (%q)", err, m.EtcdClientEndpoint) } defer cli.Close() // give enough time-out in case expensive requests (range/delete) are pending ctx, cancel := context.WithTimeout(context.Background(), 5*time.Se...
[ "func", "(", "m", "*", "Member", ")", "WriteHealthKey", "(", ")", "error", "{", "cli", ",", "err", ":=", "m", ".", "CreateEtcdClient", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"%v (%q)\"", ",", "err", ",...
// WriteHealthKey writes a health key to this member.
[ "WriteHealthKey", "writes", "a", "health", "key", "to", "this", "member", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/rpcpb/member.go#L235-L250
test
etcd-io/etcd
functional/rpcpb/member.go
SaveSnapshot
func (m *Member) SaveSnapshot(lg *zap.Logger) (err error) { // remove existing snapshot first if err = os.RemoveAll(m.SnapshotPath); err != nil { return err } var ccfg *clientv3.Config ccfg, err = m.CreateEtcdClientConfig() if err != nil { return fmt.Errorf("%v (%q)", err, m.EtcdClientEndpoint) } lg.Info(...
go
func (m *Member) SaveSnapshot(lg *zap.Logger) (err error) { // remove existing snapshot first if err = os.RemoveAll(m.SnapshotPath); err != nil { return err } var ccfg *clientv3.Config ccfg, err = m.CreateEtcdClientConfig() if err != nil { return fmt.Errorf("%v (%q)", err, m.EtcdClientEndpoint) } lg.Info(...
[ "func", "(", "m", "*", "Member", ")", "SaveSnapshot", "(", "lg", "*", "zap", ".", "Logger", ")", "(", "err", "error", ")", "{", "if", "err", "=", "os", ".", "RemoveAll", "(", "m", ".", "SnapshotPath", ")", ";", "err", "!=", "nil", "{", "return", ...
// SaveSnapshot downloads a snapshot file from this member, locally. // It's meant to requested remotely, so that local member can store // snapshot file on local disk.
[ "SaveSnapshot", "downloads", "a", "snapshot", "file", "from", "this", "member", "locally", ".", "It", "s", "meant", "to", "requested", "remotely", "so", "that", "local", "member", "can", "store", "snapshot", "file", "on", "local", "disk", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/rpcpb/member.go#L255-L314
test
etcd-io/etcd
functional/rpcpb/member.go
RestoreSnapshot
func (m *Member) RestoreSnapshot(lg *zap.Logger) (err error) { if err = os.RemoveAll(m.EtcdOnSnapshotRestore.DataDir); err != nil { return err } if err = os.RemoveAll(m.EtcdOnSnapshotRestore.WALDir); err != nil { return err } lg.Info( "snapshot restore START", zap.String("member-name", m.Etcd.Name), zap...
go
func (m *Member) RestoreSnapshot(lg *zap.Logger) (err error) { if err = os.RemoveAll(m.EtcdOnSnapshotRestore.DataDir); err != nil { return err } if err = os.RemoveAll(m.EtcdOnSnapshotRestore.WALDir); err != nil { return err } lg.Info( "snapshot restore START", zap.String("member-name", m.Etcd.Name), zap...
[ "func", "(", "m", "*", "Member", ")", "RestoreSnapshot", "(", "lg", "*", "zap", ".", "Logger", ")", "(", "err", "error", ")", "{", "if", "err", "=", "os", ".", "RemoveAll", "(", "m", ".", "EtcdOnSnapshotRestore", ".", "DataDir", ")", ";", "err", "!...
// RestoreSnapshot restores a cluster from a given snapshot file on disk. // It's meant to requested remotely, so that local member can load the // snapshot file from local disk.
[ "RestoreSnapshot", "restores", "a", "cluster", "from", "a", "given", "snapshot", "file", "on", "disk", ".", "It", "s", "meant", "to", "requested", "remotely", "so", "that", "local", "member", "can", "load", "the", "snapshot", "file", "from", "local", "disk",...
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/rpcpb/member.go#L319-L361
test
etcd-io/etcd
clientv3/namespace/watch.go
NewWatcher
func NewWatcher(w clientv3.Watcher, prefix string) clientv3.Watcher { return &watcherPrefix{Watcher: w, pfx: prefix, stopc: make(chan struct{})} }
go
func NewWatcher(w clientv3.Watcher, prefix string) clientv3.Watcher { return &watcherPrefix{Watcher: w, pfx: prefix, stopc: make(chan struct{})} }
[ "func", "NewWatcher", "(", "w", "clientv3", ".", "Watcher", ",", "prefix", "string", ")", "clientv3", ".", "Watcher", "{", "return", "&", "watcherPrefix", "{", "Watcher", ":", "w", ",", "pfx", ":", "prefix", ",", "stopc", ":", "make", "(", "chan", "str...
// NewWatcher wraps a Watcher instance so that all Watch requests // are prefixed with a given string and all Watch responses have // the prefix removed.
[ "NewWatcher", "wraps", "a", "Watcher", "instance", "so", "that", "all", "Watch", "requests", "are", "prefixed", "with", "a", "given", "string", "and", "all", "Watch", "responses", "have", "the", "prefix", "removed", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/namespace/watch.go#L36-L38
test
etcd-io/etcd
raft/rawnode.go
NewRawNode
func NewRawNode(config *Config, peers []Peer) (*RawNode, error) { if config.ID == 0 { panic("config.ID must not be zero") } r := newRaft(config) rn := &RawNode{ raft: r, } lastIndex, err := config.Storage.LastIndex() if err != nil { panic(err) // TODO(bdarnell) } // If the log is empty, this is a new Raw...
go
func NewRawNode(config *Config, peers []Peer) (*RawNode, error) { if config.ID == 0 { panic("config.ID must not be zero") } r := newRaft(config) rn := &RawNode{ raft: r, } lastIndex, err := config.Storage.LastIndex() if err != nil { panic(err) // TODO(bdarnell) } // If the log is empty, this is a new Raw...
[ "func", "NewRawNode", "(", "config", "*", "Config", ",", "peers", "[", "]", "Peer", ")", "(", "*", "RawNode", ",", "error", ")", "{", "if", "config", ".", "ID", "==", "0", "{", "panic", "(", "\"config.ID must not be zero\"", ")", "\n", "}", "\n", "r"...
// NewRawNode returns a new RawNode given configuration and a list of raft peers.
[ "NewRawNode", "returns", "a", "new", "RawNode", "given", "configuration", "and", "a", "list", "of", "raft", "peers", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/rawnode.go#L72-L116
test
etcd-io/etcd
raft/rawnode.go
Campaign
func (rn *RawNode) Campaign() error { return rn.raft.Step(pb.Message{ Type: pb.MsgHup, }) }
go
func (rn *RawNode) Campaign() error { return rn.raft.Step(pb.Message{ Type: pb.MsgHup, }) }
[ "func", "(", "rn", "*", "RawNode", ")", "Campaign", "(", ")", "error", "{", "return", "rn", ".", "raft", ".", "Step", "(", "pb", ".", "Message", "{", "Type", ":", "pb", ".", "MsgHup", ",", "}", ")", "\n", "}" ]
// Campaign causes this RawNode to transition to candidate state.
[ "Campaign", "causes", "this", "RawNode", "to", "transition", "to", "candidate", "state", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/rawnode.go#L136-L140
test
etcd-io/etcd
raft/rawnode.go
Propose
func (rn *RawNode) Propose(data []byte) error { return rn.raft.Step(pb.Message{ Type: pb.MsgProp, From: rn.raft.id, Entries: []pb.Entry{ {Data: data}, }}) }
go
func (rn *RawNode) Propose(data []byte) error { return rn.raft.Step(pb.Message{ Type: pb.MsgProp, From: rn.raft.id, Entries: []pb.Entry{ {Data: data}, }}) }
[ "func", "(", "rn", "*", "RawNode", ")", "Propose", "(", "data", "[", "]", "byte", ")", "error", "{", "return", "rn", ".", "raft", ".", "Step", "(", "pb", ".", "Message", "{", "Type", ":", "pb", ".", "MsgProp", ",", "From", ":", "rn", ".", "raft...
// Propose proposes data be appended to the raft log.
[ "Propose", "proposes", "data", "be", "appended", "to", "the", "raft", "log", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/rawnode.go#L143-L150
test
etcd-io/etcd
raft/rawnode.go
ProposeConfChange
func (rn *RawNode) ProposeConfChange(cc pb.ConfChange) error { data, err := cc.Marshal() if err != nil { return err } return rn.raft.Step(pb.Message{ Type: pb.MsgProp, Entries: []pb.Entry{ {Type: pb.EntryConfChange, Data: data}, }, }) }
go
func (rn *RawNode) ProposeConfChange(cc pb.ConfChange) error { data, err := cc.Marshal() if err != nil { return err } return rn.raft.Step(pb.Message{ Type: pb.MsgProp, Entries: []pb.Entry{ {Type: pb.EntryConfChange, Data: data}, }, }) }
[ "func", "(", "rn", "*", "RawNode", ")", "ProposeConfChange", "(", "cc", "pb", ".", "ConfChange", ")", "error", "{", "data", ",", "err", ":=", "cc", ".", "Marshal", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "...
// ProposeConfChange proposes a config change.
[ "ProposeConfChange", "proposes", "a", "config", "change", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/rawnode.go#L153-L164
test
etcd-io/etcd
raft/rawnode.go
ApplyConfChange
func (rn *RawNode) ApplyConfChange(cc pb.ConfChange) *pb.ConfState { if cc.NodeID == None { return &pb.ConfState{Nodes: rn.raft.nodes(), Learners: rn.raft.learnerNodes()} } switch cc.Type { case pb.ConfChangeAddNode: rn.raft.addNode(cc.NodeID) case pb.ConfChangeAddLearnerNode: rn.raft.addLearner(cc.NodeID) ...
go
func (rn *RawNode) ApplyConfChange(cc pb.ConfChange) *pb.ConfState { if cc.NodeID == None { return &pb.ConfState{Nodes: rn.raft.nodes(), Learners: rn.raft.learnerNodes()} } switch cc.Type { case pb.ConfChangeAddNode: rn.raft.addNode(cc.NodeID) case pb.ConfChangeAddLearnerNode: rn.raft.addLearner(cc.NodeID) ...
[ "func", "(", "rn", "*", "RawNode", ")", "ApplyConfChange", "(", "cc", "pb", ".", "ConfChange", ")", "*", "pb", ".", "ConfState", "{", "if", "cc", ".", "NodeID", "==", "None", "{", "return", "&", "pb", ".", "ConfState", "{", "Nodes", ":", "rn", ".",...
// ApplyConfChange applies a config change to the local node.
[ "ApplyConfChange", "applies", "a", "config", "change", "to", "the", "local", "node", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/rawnode.go#L167-L183
test
etcd-io/etcd
raft/rawnode.go
Step
func (rn *RawNode) Step(m pb.Message) error { // ignore unexpected local messages receiving over network if IsLocalMsg(m.Type) { return ErrStepLocalMsg } if pr := rn.raft.getProgress(m.From); pr != nil || !IsResponseMsg(m.Type) { return rn.raft.Step(m) } return ErrStepPeerNotFound }
go
func (rn *RawNode) Step(m pb.Message) error { // ignore unexpected local messages receiving over network if IsLocalMsg(m.Type) { return ErrStepLocalMsg } if pr := rn.raft.getProgress(m.From); pr != nil || !IsResponseMsg(m.Type) { return rn.raft.Step(m) } return ErrStepPeerNotFound }
[ "func", "(", "rn", "*", "RawNode", ")", "Step", "(", "m", "pb", ".", "Message", ")", "error", "{", "if", "IsLocalMsg", "(", "m", ".", "Type", ")", "{", "return", "ErrStepLocalMsg", "\n", "}", "\n", "if", "pr", ":=", "rn", ".", "raft", ".", "getPr...
// Step advances the state machine using the given message.
[ "Step", "advances", "the", "state", "machine", "using", "the", "given", "message", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/rawnode.go#L186-L195
test
etcd-io/etcd
raft/rawnode.go
Ready
func (rn *RawNode) Ready() Ready { rd := rn.newReady() rn.raft.msgs = nil rn.raft.reduceUncommittedSize(rd.CommittedEntries) return rd }
go
func (rn *RawNode) Ready() Ready { rd := rn.newReady() rn.raft.msgs = nil rn.raft.reduceUncommittedSize(rd.CommittedEntries) return rd }
[ "func", "(", "rn", "*", "RawNode", ")", "Ready", "(", ")", "Ready", "{", "rd", ":=", "rn", ".", "newReady", "(", ")", "\n", "rn", ".", "raft", ".", "msgs", "=", "nil", "\n", "rn", ".", "raft", ".", "reduceUncommittedSize", "(", "rd", ".", "Commit...
// Ready returns the current point-in-time state of this RawNode.
[ "Ready", "returns", "the", "current", "point", "-", "in", "-", "time", "state", "of", "this", "RawNode", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/rawnode.go#L198-L203
test
etcd-io/etcd
raft/rawnode.go
WithProgress
func (rn *RawNode) WithProgress(visitor func(id uint64, typ ProgressType, pr Progress)) { for id, pr := range rn.raft.prs { pr := *pr pr.ins = nil visitor(id, ProgressTypePeer, pr) } for id, pr := range rn.raft.learnerPrs { pr := *pr pr.ins = nil visitor(id, ProgressTypeLearner, pr) } }
go
func (rn *RawNode) WithProgress(visitor func(id uint64, typ ProgressType, pr Progress)) { for id, pr := range rn.raft.prs { pr := *pr pr.ins = nil visitor(id, ProgressTypePeer, pr) } for id, pr := range rn.raft.learnerPrs { pr := *pr pr.ins = nil visitor(id, ProgressTypeLearner, pr) } }
[ "func", "(", "rn", "*", "RawNode", ")", "WithProgress", "(", "visitor", "func", "(", "id", "uint64", ",", "typ", "ProgressType", ",", "pr", "Progress", ")", ")", "{", "for", "id", ",", "pr", ":=", "range", "rn", ".", "raft", ".", "prs", "{", "pr", ...
// WithProgress is a helper to introspect the Progress for this node and its // peers.
[ "WithProgress", "is", "a", "helper", "to", "introspect", "the", "Progress", "for", "this", "node", "and", "its", "peers", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/rawnode.go#L259-L270
test
etcd-io/etcd
raft/rawnode.go
ReportUnreachable
func (rn *RawNode) ReportUnreachable(id uint64) { _ = rn.raft.Step(pb.Message{Type: pb.MsgUnreachable, From: id}) }
go
func (rn *RawNode) ReportUnreachable(id uint64) { _ = rn.raft.Step(pb.Message{Type: pb.MsgUnreachable, From: id}) }
[ "func", "(", "rn", "*", "RawNode", ")", "ReportUnreachable", "(", "id", "uint64", ")", "{", "_", "=", "rn", ".", "raft", ".", "Step", "(", "pb", ".", "Message", "{", "Type", ":", "pb", ".", "MsgUnreachable", ",", "From", ":", "id", "}", ")", "\n"...
// ReportUnreachable reports the given node is not reachable for the last send.
[ "ReportUnreachable", "reports", "the", "given", "node", "is", "not", "reachable", "for", "the", "last", "send", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/rawnode.go#L273-L275
test
etcd-io/etcd
raft/rawnode.go
ReportSnapshot
func (rn *RawNode) ReportSnapshot(id uint64, status SnapshotStatus) { rej := status == SnapshotFailure _ = rn.raft.Step(pb.Message{Type: pb.MsgSnapStatus, From: id, Reject: rej}) }
go
func (rn *RawNode) ReportSnapshot(id uint64, status SnapshotStatus) { rej := status == SnapshotFailure _ = rn.raft.Step(pb.Message{Type: pb.MsgSnapStatus, From: id, Reject: rej}) }
[ "func", "(", "rn", "*", "RawNode", ")", "ReportSnapshot", "(", "id", "uint64", ",", "status", "SnapshotStatus", ")", "{", "rej", ":=", "status", "==", "SnapshotFailure", "\n", "_", "=", "rn", ".", "raft", ".", "Step", "(", "pb", ".", "Message", "{", ...
// ReportSnapshot reports the status of the sent snapshot.
[ "ReportSnapshot", "reports", "the", "status", "of", "the", "sent", "snapshot", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/rawnode.go#L278-L282
test
etcd-io/etcd
raft/rawnode.go
TransferLeader
func (rn *RawNode) TransferLeader(transferee uint64) { _ = rn.raft.Step(pb.Message{Type: pb.MsgTransferLeader, From: transferee}) }
go
func (rn *RawNode) TransferLeader(transferee uint64) { _ = rn.raft.Step(pb.Message{Type: pb.MsgTransferLeader, From: transferee}) }
[ "func", "(", "rn", "*", "RawNode", ")", "TransferLeader", "(", "transferee", "uint64", ")", "{", "_", "=", "rn", ".", "raft", ".", "Step", "(", "pb", ".", "Message", "{", "Type", ":", "pb", ".", "MsgTransferLeader", ",", "From", ":", "transferee", "}...
// TransferLeader tries to transfer leadership to the given transferee.
[ "TransferLeader", "tries", "to", "transfer", "leadership", "to", "the", "given", "transferee", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/rawnode.go#L285-L287
test
etcd-io/etcd
raft/rawnode.go
ReadIndex
func (rn *RawNode) ReadIndex(rctx []byte) { _ = rn.raft.Step(pb.Message{Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: rctx}}}) }
go
func (rn *RawNode) ReadIndex(rctx []byte) { _ = rn.raft.Step(pb.Message{Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: rctx}}}) }
[ "func", "(", "rn", "*", "RawNode", ")", "ReadIndex", "(", "rctx", "[", "]", "byte", ")", "{", "_", "=", "rn", ".", "raft", ".", "Step", "(", "pb", ".", "Message", "{", "Type", ":", "pb", ".", "MsgReadIndex", ",", "Entries", ":", "[", "]", "pb",...
// ReadIndex requests a read state. The read state will be set in ready. // Read State has a read index. Once the application advances further than the read // index, any linearizable read requests issued before the read request can be // processed safely. The read state will have the same rctx attached.
[ "ReadIndex", "requests", "a", "read", "state", ".", "The", "read", "state", "will", "be", "set", "in", "ready", ".", "Read", "State", "has", "a", "read", "index", ".", "Once", "the", "application", "advances", "further", "than", "the", "read", "index", "...
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/rawnode.go#L293-L295
test
etcd-io/etcd
client/curl.go
printcURL
func printcURL(req *http.Request) error { if !cURLDebug { return nil } var ( command string b []byte err error ) if req.URL != nil { command = fmt.Sprintf("curl -X %s %s", req.Method, req.URL.String()) } if req.Body != nil { b, err = ioutil.ReadAll(req.Body) if err != nil { return er...
go
func printcURL(req *http.Request) error { if !cURLDebug { return nil } var ( command string b []byte err error ) if req.URL != nil { command = fmt.Sprintf("curl -X %s %s", req.Method, req.URL.String()) } if req.Body != nil { b, err = ioutil.ReadAll(req.Body) if err != nil { return er...
[ "func", "printcURL", "(", "req", "*", "http", ".", "Request", ")", "error", "{", "if", "!", "cURLDebug", "{", "return", "nil", "\n", "}", "\n", "var", "(", "command", "string", "\n", "b", "[", "]", "byte", "\n", "err", "error", "\n", ")", "\n", "...
// printcURL prints the cURL equivalent request to stderr. // It returns an error if the body of the request cannot // be read. // The caller MUST cancel the request if there is an error.
[ "printcURL", "prints", "the", "cURL", "equivalent", "request", "to", "stderr", ".", "It", "returns", "an", "error", "if", "the", "body", "of", "the", "request", "cannot", "be", "read", ".", "The", "caller", "MUST", "cancel", "the", "request", "if", "there"...
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/client/curl.go#L41-L70
test
etcd-io/etcd
raft/node.go
StartNode
func StartNode(c *Config, peers []Peer) Node { r := newRaft(c) // become the follower at term 1 and apply initial configuration // entries of term 1 r.becomeFollower(1, None) for _, peer := range peers { cc := pb.ConfChange{Type: pb.ConfChangeAddNode, NodeID: peer.ID, Context: peer.Context} d, err := cc.Marsha...
go
func StartNode(c *Config, peers []Peer) Node { r := newRaft(c) // become the follower at term 1 and apply initial configuration // entries of term 1 r.becomeFollower(1, None) for _, peer := range peers { cc := pb.ConfChange{Type: pb.ConfChangeAddNode, NodeID: peer.ID, Context: peer.Context} d, err := cc.Marsha...
[ "func", "StartNode", "(", "c", "*", "Config", ",", "peers", "[", "]", "Peer", ")", "Node", "{", "r", ":=", "newRaft", "(", "c", ")", "\n", "r", ".", "becomeFollower", "(", "1", ",", "None", ")", "\n", "for", "_", ",", "peer", ":=", "range", "pe...
// StartNode returns a new Node given configuration and a list of raft peers. // It appends a ConfChangeAddNode entry for each given peer to the initial log.
[ "StartNode", "returns", "a", "new", "Node", "given", "configuration", "and", "a", "list", "of", "raft", "peers", ".", "It", "appends", "a", "ConfChangeAddNode", "entry", "for", "each", "given", "peer", "to", "the", "initial", "log", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/node.go#L200-L235
test
etcd-io/etcd
raft/node.go
RestartNode
func RestartNode(c *Config) Node { r := newRaft(c) n := newNode() n.logger = c.Logger go n.run(r) return &n }
go
func RestartNode(c *Config) Node { r := newRaft(c) n := newNode() n.logger = c.Logger go n.run(r) return &n }
[ "func", "RestartNode", "(", "c", "*", "Config", ")", "Node", "{", "r", ":=", "newRaft", "(", "c", ")", "\n", "n", ":=", "newNode", "(", ")", "\n", "n", ".", "logger", "=", "c", ".", "Logger", "\n", "go", "n", ".", "run", "(", "r", ")", "\n", ...
// RestartNode is similar to StartNode but does not take a list of peers. // The current membership of the cluster will be restored from the Storage. // If the caller has an existing state machine, pass in the last log index that // has been applied to it; otherwise use zero.
[ "RestartNode", "is", "similar", "to", "StartNode", "but", "does", "not", "take", "a", "list", "of", "peers", ".", "The", "current", "membership", "of", "the", "cluster", "will", "be", "restored", "from", "the", "Storage", ".", "If", "the", "caller", "has",...
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/node.go#L241-L248
test
etcd-io/etcd
raft/node.go
Tick
func (n *node) Tick() { select { case n.tickc <- struct{}{}: case <-n.done: default: n.logger.Warningf("A tick missed to fire. Node blocks too long!") } }
go
func (n *node) Tick() { select { case n.tickc <- struct{}{}: case <-n.done: default: n.logger.Warningf("A tick missed to fire. Node blocks too long!") } }
[ "func", "(", "n", "*", "node", ")", "Tick", "(", ")", "{", "select", "{", "case", "n", ".", "tickc", "<-", "struct", "{", "}", "{", "}", ":", "case", "<-", "n", ".", "done", ":", "default", ":", "n", ".", "logger", ".", "Warningf", "(", "\"A ...
// Tick increments the internal logical clock for this Node. Election timeouts // and heartbeat timeouts are in units of ticks.
[ "Tick", "increments", "the", "internal", "logical", "clock", "for", "this", "Node", ".", "Election", "timeouts", "and", "heartbeat", "timeouts", "are", "in", "units", "of", "ticks", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/node.go#L438-L445
test
etcd-io/etcd
raft/node.go
MustSync
func MustSync(st, prevst pb.HardState, entsnum int) bool { // Persistent state on all servers: // (Updated on stable storage before responding to RPCs) // currentTerm // votedFor // log entries[] return entsnum != 0 || st.Vote != prevst.Vote || st.Term != prevst.Term }
go
func MustSync(st, prevst pb.HardState, entsnum int) bool { // Persistent state on all servers: // (Updated on stable storage before responding to RPCs) // currentTerm // votedFor // log entries[] return entsnum != 0 || st.Vote != prevst.Vote || st.Term != prevst.Term }
[ "func", "MustSync", "(", "st", ",", "prevst", "pb", ".", "HardState", ",", "entsnum", "int", ")", "bool", "{", "return", "entsnum", "!=", "0", "||", "st", ".", "Vote", "!=", "prevst", ".", "Vote", "||", "st", ".", "Term", "!=", "prevst", ".", "Term...
// MustSync returns true if the hard state and count of Raft entries indicate // that a synchronous write to persistent storage is required.
[ "MustSync", "returns", "true", "if", "the", "hard", "state", "and", "count", "of", "Raft", "entries", "indicate", "that", "a", "synchronous", "write", "to", "persistent", "storage", "is", "required", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/node.go#L604-L611
test
etcd-io/etcd
clientv3/balancer/grpc1.7-health.go
NewGRPC17Health
func NewGRPC17Health( eps []string, timeout time.Duration, dialFunc DialFunc, ) *GRPC17Health { notifyCh := make(chan []grpc.Address) addrs := eps2addrs(eps) hb := &GRPC17Health{ addrs: addrs, eps: eps, notifyCh: notifyCh, readyc: make(chan struct{}), he...
go
func NewGRPC17Health( eps []string, timeout time.Duration, dialFunc DialFunc, ) *GRPC17Health { notifyCh := make(chan []grpc.Address) addrs := eps2addrs(eps) hb := &GRPC17Health{ addrs: addrs, eps: eps, notifyCh: notifyCh, readyc: make(chan struct{}), he...
[ "func", "NewGRPC17Health", "(", "eps", "[", "]", "string", ",", "timeout", "time", ".", "Duration", ",", "dialFunc", "DialFunc", ",", ")", "*", "GRPC17Health", "{", "notifyCh", ":=", "make", "(", "chan", "[", "]", "grpc", ".", "Address", ")", "\n", "ad...
// NewGRPC17Health returns a new health balancer with gRPC v1.7.
[ "NewGRPC17Health", "returns", "a", "new", "health", "balancer", "with", "gRPC", "v1", ".", "7", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/balancer/grpc1.7-health.go#L112-L146
test
etcd-io/etcd
clientv3/balancer/grpc1.7-health.go
NeedUpdate
func (b *GRPC17Health) NeedUpdate() bool { // updating notifyCh can trigger new connections, // need update addrs if all connections are down // or addrs does not include pinAddr. b.mu.RLock() update := !hasAddr(b.addrs, b.pinAddr) b.mu.RUnlock() return update }
go
func (b *GRPC17Health) NeedUpdate() bool { // updating notifyCh can trigger new connections, // need update addrs if all connections are down // or addrs does not include pinAddr. b.mu.RLock() update := !hasAddr(b.addrs, b.pinAddr) b.mu.RUnlock() return update }
[ "func", "(", "b", "*", "GRPC17Health", ")", "NeedUpdate", "(", ")", "bool", "{", "b", ".", "mu", ".", "RLock", "(", ")", "\n", "update", ":=", "!", "hasAddr", "(", "b", ".", "addrs", ",", "b", ".", "pinAddr", ")", "\n", "b", ".", "mu", ".", "...
// NeedUpdate returns true if all connections are down or // addresses do not include current pinned address.
[ "NeedUpdate", "returns", "true", "if", "all", "connections", "are", "down", "or", "addresses", "do", "not", "include", "current", "pinned", "address", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/balancer/grpc1.7-health.go#L269-L277
test
etcd-io/etcd
pkg/osutil/signal_linux.go
dflSignal
func dflSignal(sig syscall.Signal) { // clearing out the sigact sets the signal to SIG_DFL var sigactBuf [32]uint64 ptr := unsafe.Pointer(&sigactBuf) syscall.Syscall6(uintptr(syscall.SYS_RT_SIGACTION), uintptr(sig), uintptr(ptr), 0, 8, 0, 0) }
go
func dflSignal(sig syscall.Signal) { // clearing out the sigact sets the signal to SIG_DFL var sigactBuf [32]uint64 ptr := unsafe.Pointer(&sigactBuf) syscall.Syscall6(uintptr(syscall.SYS_RT_SIGACTION), uintptr(sig), uintptr(ptr), 0, 8, 0, 0) }
[ "func", "dflSignal", "(", "sig", "syscall", ".", "Signal", ")", "{", "var", "sigactBuf", "[", "32", "]", "uint64", "\n", "ptr", ":=", "unsafe", ".", "Pointer", "(", "&", "sigactBuf", ")", "\n", "syscall", ".", "Syscall6", "(", "uintptr", "(", "syscall"...
// dflSignal sets the given signal to SIG_DFL
[ "dflSignal", "sets", "the", "given", "signal", "to", "SIG_DFL" ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/osutil/signal_linux.go#L25-L30
test
etcd-io/etcd
etcdserver/api/v2store/store.go
New
func New(namespaces ...string) Store { s := newStore(namespaces...) s.clock = clockwork.NewRealClock() return s }
go
func New(namespaces ...string) Store { s := newStore(namespaces...) s.clock = clockwork.NewRealClock() return s }
[ "func", "New", "(", "namespaces", "...", "string", ")", "Store", "{", "s", ":=", "newStore", "(", "namespaces", "...", ")", "\n", "s", ".", "clock", "=", "clockwork", ".", "NewRealClock", "(", ")", "\n", "return", "s", "\n", "}" ]
// New creates a store where the given namespaces will be created as initial directories.
[ "New", "creates", "a", "store", "where", "the", "given", "namespaces", "will", "be", "created", "as", "initial", "directories", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/store.go#L87-L91
test
etcd-io/etcd
etcdserver/api/v2store/store.go
Index
func (s *store) Index() uint64 { s.worldLock.RLock() defer s.worldLock.RUnlock() return s.CurrentIndex }
go
func (s *store) Index() uint64 { s.worldLock.RLock() defer s.worldLock.RUnlock() return s.CurrentIndex }
[ "func", "(", "s", "*", "store", ")", "Index", "(", ")", "uint64", "{", "s", ".", "worldLock", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "worldLock", ".", "RUnlock", "(", ")", "\n", "return", "s", ".", "CurrentIndex", "\n", "}" ]
// Index retrieves the current index of the store.
[ "Index", "retrieves", "the", "current", "index", "of", "the", "store", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/store.go#L113-L117
test
etcd-io/etcd
etcdserver/api/v2store/store.go
Get
func (s *store) Get(nodePath string, recursive, sorted bool) (*Event, error) { var err *v2error.Error s.worldLock.RLock() defer s.worldLock.RUnlock() defer func() { if err == nil { s.Stats.Inc(GetSuccess) if recursive { reportReadSuccess(GetRecursive) } else { reportReadSuccess(Get) } ret...
go
func (s *store) Get(nodePath string, recursive, sorted bool) (*Event, error) { var err *v2error.Error s.worldLock.RLock() defer s.worldLock.RUnlock() defer func() { if err == nil { s.Stats.Inc(GetSuccess) if recursive { reportReadSuccess(GetRecursive) } else { reportReadSuccess(Get) } ret...
[ "func", "(", "s", "*", "store", ")", "Get", "(", "nodePath", "string", ",", "recursive", ",", "sorted", "bool", ")", "(", "*", "Event", ",", "error", ")", "{", "var", "err", "*", "v2error", ".", "Error", "\n", "s", ".", "worldLock", ".", "RLock", ...
// Get returns a get event. // If recursive is true, it will return all the content under the node path. // If sorted is true, it will sort the content by keys.
[ "Get", "returns", "a", "get", "event", ".", "If", "recursive", "is", "true", "it", "will", "return", "all", "the", "content", "under", "the", "node", "path", ".", "If", "sorted", "is", "true", "it", "will", "sort", "the", "content", "by", "keys", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/store.go#L122-L157
test
etcd-io/etcd
etcdserver/api/v2store/store.go
Create
func (s *store) Create(nodePath string, dir bool, value string, unique bool, expireOpts TTLOptionSet) (*Event, error) { var err *v2error.Error s.worldLock.Lock() defer s.worldLock.Unlock() defer func() { if err == nil { s.Stats.Inc(CreateSuccess) reportWriteSuccess(Create) return } s.Stats.Inc(Cre...
go
func (s *store) Create(nodePath string, dir bool, value string, unique bool, expireOpts TTLOptionSet) (*Event, error) { var err *v2error.Error s.worldLock.Lock() defer s.worldLock.Unlock() defer func() { if err == nil { s.Stats.Inc(CreateSuccess) reportWriteSuccess(Create) return } s.Stats.Inc(Cre...
[ "func", "(", "s", "*", "store", ")", "Create", "(", "nodePath", "string", ",", "dir", "bool", ",", "value", "string", ",", "unique", "bool", ",", "expireOpts", "TTLOptionSet", ")", "(", "*", "Event", ",", "error", ")", "{", "var", "err", "*", "v2erro...
// Create creates the node at nodePath. Create will help to create intermediate directories with no ttl. // If the node has already existed, create will fail. // If any node on the path is a file, create will fail.
[ "Create", "creates", "the", "node", "at", "nodePath", ".", "Create", "will", "help", "to", "create", "intermediate", "directories", "with", "no", "ttl", ".", "If", "the", "node", "has", "already", "existed", "create", "will", "fail", ".", "If", "any", "nod...
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/store.go#L162-L188
test
etcd-io/etcd
etcdserver/api/v2store/store.go
Set
func (s *store) Set(nodePath string, dir bool, value string, expireOpts TTLOptionSet) (*Event, error) { var err *v2error.Error s.worldLock.Lock() defer s.worldLock.Unlock() defer func() { if err == nil { s.Stats.Inc(SetSuccess) reportWriteSuccess(Set) return } s.Stats.Inc(SetFail) reportWriteFai...
go
func (s *store) Set(nodePath string, dir bool, value string, expireOpts TTLOptionSet) (*Event, error) { var err *v2error.Error s.worldLock.Lock() defer s.worldLock.Unlock() defer func() { if err == nil { s.Stats.Inc(SetSuccess) reportWriteSuccess(Set) return } s.Stats.Inc(SetFail) reportWriteFai...
[ "func", "(", "s", "*", "store", ")", "Set", "(", "nodePath", "string", ",", "dir", "bool", ",", "value", "string", ",", "expireOpts", "TTLOptionSet", ")", "(", "*", "Event", ",", "error", ")", "{", "var", "err", "*", "v2error", ".", "Error", "\n", ...
// Set creates or replace the node at nodePath.
[ "Set", "creates", "or", "replace", "the", "node", "at", "nodePath", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/store.go#L191-L245
test
etcd-io/etcd
etcdserver/api/v2store/store.go
getCompareFailCause
func getCompareFailCause(n *node, which int, prevValue string, prevIndex uint64) string { switch which { case CompareIndexNotMatch: return fmt.Sprintf("[%v != %v]", prevIndex, n.ModifiedIndex) case CompareValueNotMatch: return fmt.Sprintf("[%v != %v]", prevValue, n.Value) default: return fmt.Sprintf("[%v != %...
go
func getCompareFailCause(n *node, which int, prevValue string, prevIndex uint64) string { switch which { case CompareIndexNotMatch: return fmt.Sprintf("[%v != %v]", prevIndex, n.ModifiedIndex) case CompareValueNotMatch: return fmt.Sprintf("[%v != %v]", prevValue, n.Value) default: return fmt.Sprintf("[%v != %...
[ "func", "getCompareFailCause", "(", "n", "*", "node", ",", "which", "int", ",", "prevValue", "string", ",", "prevIndex", "uint64", ")", "string", "{", "switch", "which", "{", "case", "CompareIndexNotMatch", ":", "return", "fmt", ".", "Sprintf", "(", "\"[%v !...
// returns user-readable cause of failed comparison
[ "returns", "user", "-", "readable", "cause", "of", "failed", "comparison" ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/store.go#L248-L257
test
etcd-io/etcd
etcdserver/api/v2store/store.go
Delete
func (s *store) Delete(nodePath string, dir, recursive bool) (*Event, error) { var err *v2error.Error s.worldLock.Lock() defer s.worldLock.Unlock() defer func() { if err == nil { s.Stats.Inc(DeleteSuccess) reportWriteSuccess(Delete) return } s.Stats.Inc(DeleteFail) reportWriteFailure(Delete) }(...
go
func (s *store) Delete(nodePath string, dir, recursive bool) (*Event, error) { var err *v2error.Error s.worldLock.Lock() defer s.worldLock.Unlock() defer func() { if err == nil { s.Stats.Inc(DeleteSuccess) reportWriteSuccess(Delete) return } s.Stats.Inc(DeleteFail) reportWriteFailure(Delete) }(...
[ "func", "(", "s", "*", "store", ")", "Delete", "(", "nodePath", "string", ",", "dir", ",", "recursive", "bool", ")", "(", "*", "Event", ",", "error", ")", "{", "var", "err", "*", "v2error", ".", "Error", "\n", "s", ".", "worldLock", ".", "Lock", ...
// Delete deletes the node at the given path. // If the node is a directory, recursive must be true to delete it.
[ "Delete", "deletes", "the", "node", "at", "the", "given", "path", ".", "If", "the", "node", "is", "a", "directory", "recursive", "must", "be", "true", "to", "delete", "it", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/store.go#L334-L393
test
etcd-io/etcd
etcdserver/api/v2store/store.go
walk
func (s *store) walk(nodePath string, walkFunc func(prev *node, component string) (*node, *v2error.Error)) (*node, *v2error.Error) { components := strings.Split(nodePath, "/") curr := s.Root var err *v2error.Error for i := 1; i < len(components); i++ { if len(components[i]) == 0 { // ignore empty string retu...
go
func (s *store) walk(nodePath string, walkFunc func(prev *node, component string) (*node, *v2error.Error)) (*node, *v2error.Error) { components := strings.Split(nodePath, "/") curr := s.Root var err *v2error.Error for i := 1; i < len(components); i++ { if len(components[i]) == 0 { // ignore empty string retu...
[ "func", "(", "s", "*", "store", ")", "walk", "(", "nodePath", "string", ",", "walkFunc", "func", "(", "prev", "*", "node", ",", "component", "string", ")", "(", "*", "node", ",", "*", "v2error", ".", "Error", ")", ")", "(", "*", "node", ",", "*",...
// walk walks all the nodePath and apply the walkFunc on each directory
[ "walk", "walks", "all", "the", "nodePath", "and", "apply", "the", "walkFunc", "on", "each", "directory" ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/store.go#L469-L487
test
etcd-io/etcd
etcdserver/api/v2store/store.go
internalGet
func (s *store) internalGet(nodePath string) (*node, *v2error.Error) { nodePath = path.Clean(path.Join("/", nodePath)) walkFunc := func(parent *node, name string) (*node, *v2error.Error) { if !parent.IsDir() { err := v2error.NewError(v2error.EcodeNotDir, parent.Path, s.CurrentIndex) return nil, err } c...
go
func (s *store) internalGet(nodePath string) (*node, *v2error.Error) { nodePath = path.Clean(path.Join("/", nodePath)) walkFunc := func(parent *node, name string) (*node, *v2error.Error) { if !parent.IsDir() { err := v2error.NewError(v2error.EcodeNotDir, parent.Path, s.CurrentIndex) return nil, err } c...
[ "func", "(", "s", "*", "store", ")", "internalGet", "(", "nodePath", "string", ")", "(", "*", "node", ",", "*", "v2error", ".", "Error", ")", "{", "nodePath", "=", "path", ".", "Clean", "(", "path", ".", "Join", "(", "\"/\"", ",", "nodePath", ")", ...
// InternalGet gets the node of the given nodePath.
[ "InternalGet", "gets", "the", "node", "of", "the", "given", "nodePath", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/store.go#L644-L668
test
etcd-io/etcd
etcdserver/api/v2store/store.go
DeleteExpiredKeys
func (s *store) DeleteExpiredKeys(cutoff time.Time) { s.worldLock.Lock() defer s.worldLock.Unlock() for { node := s.ttlKeyHeap.top() if node == nil || node.ExpireTime.After(cutoff) { break } s.CurrentIndex++ e := newEvent(Expire, node.Path, s.CurrentIndex, node.CreatedIndex) e.EtcdIndex = s.CurrentI...
go
func (s *store) DeleteExpiredKeys(cutoff time.Time) { s.worldLock.Lock() defer s.worldLock.Unlock() for { node := s.ttlKeyHeap.top() if node == nil || node.ExpireTime.After(cutoff) { break } s.CurrentIndex++ e := newEvent(Expire, node.Path, s.CurrentIndex, node.CreatedIndex) e.EtcdIndex = s.CurrentI...
[ "func", "(", "s", "*", "store", ")", "DeleteExpiredKeys", "(", "cutoff", "time", ".", "Time", ")", "{", "s", ".", "worldLock", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "worldLock", ".", "Unlock", "(", ")", "\n", "for", "{", "node", ":=", "...
// DeleteExpiredKeys will delete all expired keys
[ "DeleteExpiredKeys", "will", "delete", "all", "expired", "keys" ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/store.go#L671-L703
test
etcd-io/etcd
etcdserver/api/v2store/store.go
checkDir
func (s *store) checkDir(parent *node, dirName string) (*node, *v2error.Error) { node, ok := parent.Children[dirName] if ok { if node.IsDir() { return node, nil } return nil, v2error.NewError(v2error.EcodeNotDir, node.Path, s.CurrentIndex) } n := newDir(s, path.Join(parent.Path, dirName), s.CurrentIndex...
go
func (s *store) checkDir(parent *node, dirName string) (*node, *v2error.Error) { node, ok := parent.Children[dirName] if ok { if node.IsDir() { return node, nil } return nil, v2error.NewError(v2error.EcodeNotDir, node.Path, s.CurrentIndex) } n := newDir(s, path.Join(parent.Path, dirName), s.CurrentIndex...
[ "func", "(", "s", "*", "store", ")", "checkDir", "(", "parent", "*", "node", ",", "dirName", "string", ")", "(", "*", "node", ",", "*", "v2error", ".", "Error", ")", "{", "node", ",", "ok", ":=", "parent", ".", "Children", "[", "dirName", "]", "\...
// checkDir will check whether the component is a directory under parent node. // If it is a directory, this function will return the pointer to that node. // If it does not exist, this function will create a new directory and return the pointer to that node. // If it is a file, this function will return error.
[ "checkDir", "will", "check", "whether", "the", "component", "is", "a", "directory", "under", "parent", "node", ".", "If", "it", "is", "a", "directory", "this", "function", "will", "return", "the", "pointer", "to", "that", "node", ".", "If", "it", "does", ...
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/store.go#L709-L725
test
etcd-io/etcd
etcdserver/api/v2store/store.go
Save
func (s *store) Save() ([]byte, error) { b, err := json.Marshal(s.Clone()) if err != nil { return nil, err } return b, nil }
go
func (s *store) Save() ([]byte, error) { b, err := json.Marshal(s.Clone()) if err != nil { return nil, err } return b, nil }
[ "func", "(", "s", "*", "store", ")", "Save", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "b", ",", "err", ":=", "json", ".", "Marshal", "(", "s", ".", "Clone", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil"...
// Save saves the static state of the store system. // It will not be able to save the state of watchers. // It will not save the parent field of the node. Or there will // be cyclic dependencies issue for the json package.
[ "Save", "saves", "the", "static", "state", "of", "the", "store", "system", ".", "It", "will", "not", "be", "able", "to", "save", "the", "state", "of", "watchers", ".", "It", "will", "not", "save", "the", "parent", "field", "of", "the", "node", ".", "...
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/store.go#L731-L738
test
etcd-io/etcd
etcdserver/api/v2store/store.go
Recovery
func (s *store) Recovery(state []byte) error { s.worldLock.Lock() defer s.worldLock.Unlock() err := json.Unmarshal(state, s) if err != nil { return err } s.ttlKeyHeap = newTtlKeyHeap() s.Root.recoverAndclean() return nil }
go
func (s *store) Recovery(state []byte) error { s.worldLock.Lock() defer s.worldLock.Unlock() err := json.Unmarshal(state, s) if err != nil { return err } s.ttlKeyHeap = newTtlKeyHeap() s.Root.recoverAndclean() return nil }
[ "func", "(", "s", "*", "store", ")", "Recovery", "(", "state", "[", "]", "byte", ")", "error", "{", "s", ".", "worldLock", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "worldLock", ".", "Unlock", "(", ")", "\n", "err", ":=", "json", ".", "Un...
// Recovery recovers the store system from a static state // It needs to recover the parent field of the nodes. // It needs to delete the expired nodes since the saved time and also // needs to create monitoring go routines.
[ "Recovery", "recovers", "the", "store", "system", "from", "a", "static", "state", "It", "needs", "to", "recover", "the", "parent", "field", "of", "the", "nodes", ".", "It", "needs", "to", "delete", "the", "expired", "nodes", "since", "the", "saved", "time"...
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/store.go#L767-L780
test
etcd-io/etcd
pkg/idutil/id.go
Next
func (g *Generator) Next() uint64 { suffix := atomic.AddUint64(&g.suffix, 1) id := g.prefix | lowbit(suffix, suffixLen) return id }
go
func (g *Generator) Next() uint64 { suffix := atomic.AddUint64(&g.suffix, 1) id := g.prefix | lowbit(suffix, suffixLen) return id }
[ "func", "(", "g", "*", "Generator", ")", "Next", "(", ")", "uint64", "{", "suffix", ":=", "atomic", ".", "AddUint64", "(", "&", "g", ".", "suffix", ",", "1", ")", "\n", "id", ":=", "g", ".", "prefix", "|", "lowbit", "(", "suffix", ",", "suffixLen...
// Next generates a id that is unique.
[ "Next", "generates", "a", "id", "that", "is", "unique", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/idutil/id.go#L67-L71
test
etcd-io/etcd
etcdctl/ctlv3/command/make_mirror_command.go
NewMakeMirrorCommand
func NewMakeMirrorCommand() *cobra.Command { c := &cobra.Command{ Use: "make-mirror [options] <destination>", Short: "Makes a mirror at the destination etcd cluster", Run: makeMirrorCommandFunc, } c.Flags().StringVar(&mmprefix, "prefix", "", "Key-value prefix to mirror") c.Flags().StringVar(&mmdestprefix...
go
func NewMakeMirrorCommand() *cobra.Command { c := &cobra.Command{ Use: "make-mirror [options] <destination>", Short: "Makes a mirror at the destination etcd cluster", Run: makeMirrorCommandFunc, } c.Flags().StringVar(&mmprefix, "prefix", "", "Key-value prefix to mirror") c.Flags().StringVar(&mmdestprefix...
[ "func", "NewMakeMirrorCommand", "(", ")", "*", "cobra", ".", "Command", "{", "c", ":=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"make-mirror [options] <destination>\"", ",", "Short", ":", "\"Makes a mirror at the destination etcd cluster\"", ",", "Run", ":"...
// NewMakeMirrorCommand returns the cobra command for "makeMirror".
[ "NewMakeMirrorCommand", "returns", "the", "cobra", "command", "for", "makeMirror", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/make_mirror_command.go#L44-L61
test
etcd-io/etcd
embed/config_logging.go
NewZapCoreLoggerBuilder
func NewZapCoreLoggerBuilder(lg *zap.Logger, cr zapcore.Core, syncer zapcore.WriteSyncer) func(*Config) error { return func(cfg *Config) error { cfg.loggerMu.Lock() defer cfg.loggerMu.Unlock() cfg.logger = lg cfg.loggerConfig = nil cfg.loggerCore = cr cfg.loggerWriteSyncer = syncer grpcLogOnce.Do(func()...
go
func NewZapCoreLoggerBuilder(lg *zap.Logger, cr zapcore.Core, syncer zapcore.WriteSyncer) func(*Config) error { return func(cfg *Config) error { cfg.loggerMu.Lock() defer cfg.loggerMu.Unlock() cfg.logger = lg cfg.loggerConfig = nil cfg.loggerCore = cr cfg.loggerWriteSyncer = syncer grpcLogOnce.Do(func()...
[ "func", "NewZapCoreLoggerBuilder", "(", "lg", "*", "zap", ".", "Logger", ",", "cr", "zapcore", ".", "Core", ",", "syncer", "zapcore", ".", "WriteSyncer", ")", "func", "(", "*", "Config", ")", "error", "{", "return", "func", "(", "cfg", "*", "Config", "...
// NewZapCoreLoggerBuilder generates a zap core logger builder.
[ "NewZapCoreLoggerBuilder", "generates", "a", "zap", "core", "logger", "builder", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/embed/config_logging.go#L277-L291
test
etcd-io/etcd
clientv3/mirror/syncer.go
NewSyncer
func NewSyncer(c *clientv3.Client, prefix string, rev int64) Syncer { return &syncer{c: c, prefix: prefix, rev: rev} }
go
func NewSyncer(c *clientv3.Client, prefix string, rev int64) Syncer { return &syncer{c: c, prefix: prefix, rev: rev} }
[ "func", "NewSyncer", "(", "c", "*", "clientv3", ".", "Client", ",", "prefix", "string", ",", "rev", "int64", ")", "Syncer", "{", "return", "&", "syncer", "{", "c", ":", "c", ",", "prefix", ":", "prefix", ",", "rev", ":", "rev", "}", "\n", "}" ]
// NewSyncer creates a Syncer.
[ "NewSyncer", "creates", "a", "Syncer", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/mirror/syncer.go#L39-L41
test
etcd-io/etcd
pkg/netutil/isolate_linux.go
DropPort
func DropPort(port int) error { cmdStr := fmt.Sprintf("sudo iptables -A OUTPUT -p tcp --destination-port %d -j DROP", port) if _, err := exec.Command("/bin/sh", "-c", cmdStr).Output(); err != nil { return err } cmdStr = fmt.Sprintf("sudo iptables -A INPUT -p tcp --destination-port %d -j DROP", port) _, err := ex...
go
func DropPort(port int) error { cmdStr := fmt.Sprintf("sudo iptables -A OUTPUT -p tcp --destination-port %d -j DROP", port) if _, err := exec.Command("/bin/sh", "-c", cmdStr).Output(); err != nil { return err } cmdStr = fmt.Sprintf("sudo iptables -A INPUT -p tcp --destination-port %d -j DROP", port) _, err := ex...
[ "func", "DropPort", "(", "port", "int", ")", "error", "{", "cmdStr", ":=", "fmt", ".", "Sprintf", "(", "\"sudo iptables -A OUTPUT -p tcp --destination-port %d -j DROP\"", ",", "port", ")", "\n", "if", "_", ",", "err", ":=", "exec", ".", "Command", "(", "\"/bin...
// DropPort drops all tcp packets that are received from the given port and sent to the given port.
[ "DropPort", "drops", "all", "tcp", "packets", "that", "are", "received", "from", "the", "given", "port", "and", "sent", "to", "the", "given", "port", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/netutil/isolate_linux.go#L23-L31
test
etcd-io/etcd
pkg/netutil/isolate_linux.go
SetLatency
func SetLatency(ms, rv int) error { ifces, err := GetDefaultInterfaces() if err != nil { return err } if rv > ms { rv = 1 } for ifce := range ifces { cmdStr := fmt.Sprintf("sudo tc qdisc add dev %s root netem delay %dms %dms distribution normal", ifce, ms, rv) _, err = exec.Command("/bin/sh", "-c", cmdSt...
go
func SetLatency(ms, rv int) error { ifces, err := GetDefaultInterfaces() if err != nil { return err } if rv > ms { rv = 1 } for ifce := range ifces { cmdStr := fmt.Sprintf("sudo tc qdisc add dev %s root netem delay %dms %dms distribution normal", ifce, ms, rv) _, err = exec.Command("/bin/sh", "-c", cmdSt...
[ "func", "SetLatency", "(", "ms", ",", "rv", "int", ")", "error", "{", "ifces", ",", "err", ":=", "GetDefaultInterfaces", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "rv", ">", "ms", "{", "rv", "=", "1", ...
// SetLatency adds latency in millisecond scale with random variations.
[ "SetLatency", "adds", "latency", "in", "millisecond", "scale", "with", "random", "variations", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/netutil/isolate_linux.go#L45-L67
test
etcd-io/etcd
pkg/netutil/isolate_linux.go
RemoveLatency
func RemoveLatency() error { ifces, err := GetDefaultInterfaces() if err != nil { return err } for ifce := range ifces { _, err = exec.Command("/bin/sh", "-c", fmt.Sprintf("sudo tc qdisc del dev %s root netem", ifce)).Output() if err != nil { return err } } return nil }
go
func RemoveLatency() error { ifces, err := GetDefaultInterfaces() if err != nil { return err } for ifce := range ifces { _, err = exec.Command("/bin/sh", "-c", fmt.Sprintf("sudo tc qdisc del dev %s root netem", ifce)).Output() if err != nil { return err } } return nil }
[ "func", "RemoveLatency", "(", ")", "error", "{", "ifces", ",", "err", ":=", "GetDefaultInterfaces", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "ifce", ":=", "range", "ifces", "{", "_", ",", "err", "=", "...
// RemoveLatency resets latency configurations.
[ "RemoveLatency", "resets", "latency", "configurations", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/netutil/isolate_linux.go#L70-L82
test
etcd-io/etcd
etcdctl/ctlv3/command/txn_command.go
NewTxnCommand
func NewTxnCommand() *cobra.Command { cmd := &cobra.Command{ Use: "txn [options]", Short: "Txn processes all the requests in one transaction", Run: txnCommandFunc, } cmd.Flags().BoolVarP(&txnInteractive, "interactive", "i", false, "Input transaction in interactive mode") return cmd }
go
func NewTxnCommand() *cobra.Command { cmd := &cobra.Command{ Use: "txn [options]", Short: "Txn processes all the requests in one transaction", Run: txnCommandFunc, } cmd.Flags().BoolVarP(&txnInteractive, "interactive", "i", false, "Input transaction in interactive mode") return cmd }
[ "func", "NewTxnCommand", "(", ")", "*", "cobra", ".", "Command", "{", "cmd", ":=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"txn [options]\"", ",", "Short", ":", "\"Txn processes all the requests in one transaction\"", ",", "Run", ":", "txnCommandFunc", ...
// NewTxnCommand returns the cobra command for "txn".
[ "NewTxnCommand", "returns", "the", "cobra", "command", "for", "txn", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/txn_command.go#L34-L42
test
etcd-io/etcd
etcdctl/ctlv3/command/txn_command.go
txnCommandFunc
func txnCommandFunc(cmd *cobra.Command, args []string) { if len(args) != 0 { ExitWithError(ExitBadArgs, fmt.Errorf("txn command does not accept argument")) } reader := bufio.NewReader(os.Stdin) txn := mustClientFromCmd(cmd).Txn(context.Background()) promptInteractive("compares:") txn.If(readCompares(reader).....
go
func txnCommandFunc(cmd *cobra.Command, args []string) { if len(args) != 0 { ExitWithError(ExitBadArgs, fmt.Errorf("txn command does not accept argument")) } reader := bufio.NewReader(os.Stdin) txn := mustClientFromCmd(cmd).Txn(context.Background()) promptInteractive("compares:") txn.If(readCompares(reader).....
[ "func", "txnCommandFunc", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "if", "len", "(", "args", ")", "!=", "0", "{", "ExitWithError", "(", "ExitBadArgs", ",", "fmt", ".", "Errorf", "(", "\"txn command does not acc...
// txnCommandFunc executes the "txn" command.
[ "txnCommandFunc", "executes", "the", "txn", "command", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/txn_command.go#L45-L66
test
etcd-io/etcd
etcdserver/api/v3compactor/compactor.go
New
func New( lg *zap.Logger, mode string, retention time.Duration, rg RevGetter, c Compactable, ) (Compactor, error) { switch mode { case ModePeriodic: return newPeriodic(lg, clockwork.NewRealClock(), retention, rg, c), nil case ModeRevision: return newRevision(lg, clockwork.NewRealClock(), int64(retention), r...
go
func New( lg *zap.Logger, mode string, retention time.Duration, rg RevGetter, c Compactable, ) (Compactor, error) { switch mode { case ModePeriodic: return newPeriodic(lg, clockwork.NewRealClock(), retention, rg, c), nil case ModeRevision: return newRevision(lg, clockwork.NewRealClock(), int64(retention), r...
[ "func", "New", "(", "lg", "*", "zap", ".", "Logger", ",", "mode", "string", ",", "retention", "time", ".", "Duration", ",", "rg", "RevGetter", ",", "c", "Compactable", ",", ")", "(", "Compactor", ",", "error", ")", "{", "switch", "mode", "{", "case",...
// New returns a new Compactor based on given "mode".
[ "New", "returns", "a", "new", "Compactor", "based", "on", "given", "mode", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v3compactor/compactor.go#L60-L75
test
etcd-io/etcd
etcdctl/ctlv2/command/format.go
printResponseKey
func printResponseKey(resp *client.Response, format string) { // Format the result. switch format { case "simple": if resp.Action != "delete" { fmt.Println(resp.Node.Value) } else { fmt.Println("PrevNode.Value:", resp.PrevNode.Value) } case "extended": // Extended prints in a rfc2822 style format fm...
go
func printResponseKey(resp *client.Response, format string) { // Format the result. switch format { case "simple": if resp.Action != "delete" { fmt.Println(resp.Node.Value) } else { fmt.Println("PrevNode.Value:", resp.PrevNode.Value) } case "extended": // Extended prints in a rfc2822 style format fm...
[ "func", "printResponseKey", "(", "resp", "*", "client", ".", "Response", ",", "format", "string", ")", "{", "switch", "format", "{", "case", "\"simple\"", ":", "if", "resp", ".", "Action", "!=", "\"delete\"", "{", "fmt", ".", "Println", "(", "resp", ".",...
// printResponseKey only supports to print key correctly.
[ "printResponseKey", "only", "supports", "to", "print", "key", "correctly", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv2/command/format.go#L26-L60
test
etcd-io/etcd
etcdserver/api/v3lock/v3lockpb/gw/v3lock.pb.gw.go
RegisterLockHandler
func RegisterLockHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { return RegisterLockHandlerClient(ctx, mux, v3lockpb.NewLockClient(conn)) }
go
func RegisterLockHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { return RegisterLockHandlerClient(ctx, mux, v3lockpb.NewLockClient(conn)) }
[ "func", "RegisterLockHandler", "(", "ctx", "context", ".", "Context", ",", "mux", "*", "runtime", ".", "ServeMux", ",", "conn", "*", "grpc", ".", "ClientConn", ")", "error", "{", "return", "RegisterLockHandlerClient", "(", "ctx", ",", "mux", ",", "v3lockpb",...
// RegisterLockHandler registers the http handlers for service Lock to "mux". // The handlers forward requests to the grpc endpoint over "conn".
[ "RegisterLockHandler", "registers", "the", "http", "handlers", "for", "service", "Lock", "to", "mux", ".", "The", "handlers", "forward", "requests", "to", "the", "grpc", "endpoint", "over", "conn", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v3lock/v3lockpb/gw/v3lock.pb.gw.go#L85-L87
test
etcd-io/etcd
embed/serve.go
grpcHandlerFunc
func grpcHandlerFunc(grpcServer *grpc.Server, otherHandler http.Handler) http.Handler { if otherHandler == nil { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { grpcServer.ServeHTTP(w, r) }) } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.ProtoMajor == 2 ...
go
func grpcHandlerFunc(grpcServer *grpc.Server, otherHandler http.Handler) http.Handler { if otherHandler == nil { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { grpcServer.ServeHTTP(w, r) }) } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.ProtoMajor == 2 ...
[ "func", "grpcHandlerFunc", "(", "grpcServer", "*", "grpc", ".", "Server", ",", "otherHandler", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "if", "otherHandler", "==", "nil", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", ...
// grpcHandlerFunc returns an http.Handler that delegates to grpcServer on incoming gRPC // connections or otherHandler otherwise. Given in gRPC docs.
[ "grpcHandlerFunc", "returns", "an", "http", ".", "Handler", "that", "delegates", "to", "grpcServer", "on", "incoming", "gRPC", "connections", "or", "otherHandler", "otherwise", ".", "Given", "in", "gRPC", "docs", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/embed/serve.go#L206-L219
test
etcd-io/etcd
embed/serve.go
addCORSHeader
func addCORSHeader(w http.ResponseWriter, origin string) { w.Header().Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE") w.Header().Add("Access-Control-Allow-Origin", origin) w.Header().Add("Access-Control-Allow-Headers", "accept, content-type, authorization") }
go
func addCORSHeader(w http.ResponseWriter, origin string) { w.Header().Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE") w.Header().Add("Access-Control-Allow-Origin", origin) w.Header().Add("Access-Control-Allow-Headers", "accept, content-type, authorization") }
[ "func", "addCORSHeader", "(", "w", "http", ".", "ResponseWriter", ",", "origin", "string", ")", "{", "w", ".", "Header", "(", ")", ".", "Add", "(", "\"Access-Control-Allow-Methods\"", ",", "\"POST, GET, OPTIONS, PUT, DELETE\"", ")", "\n", "w", ".", "Header", "...
// addCORSHeader adds the correct cors headers given an origin
[ "addCORSHeader", "adds", "the", "correct", "cors", "headers", "given", "an", "origin" ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/embed/serve.go#L363-L367
test
etcd-io/etcd
clientv3/leasing/txn.go
fallback
func (txn *txnLeasing) fallback(ops []v3.Op) (fbOps []v3.Op) { for _, op := range ops { if op.IsGet() { continue } lkey, lend := txn.lkv.pfx+string(op.KeyBytes()), "" if len(op.RangeBytes()) > 0 { lend = txn.lkv.pfx + string(op.RangeBytes()) } fbOps = append(fbOps, v3.OpGet(lkey, v3.WithRange(lend)))...
go
func (txn *txnLeasing) fallback(ops []v3.Op) (fbOps []v3.Op) { for _, op := range ops { if op.IsGet() { continue } lkey, lend := txn.lkv.pfx+string(op.KeyBytes()), "" if len(op.RangeBytes()) > 0 { lend = txn.lkv.pfx + string(op.RangeBytes()) } fbOps = append(fbOps, v3.OpGet(lkey, v3.WithRange(lend)))...
[ "func", "(", "txn", "*", "txnLeasing", ")", "fallback", "(", "ops", "[", "]", "v3", ".", "Op", ")", "(", "fbOps", "[", "]", "v3", ".", "Op", ")", "{", "for", "_", ",", "op", ":=", "range", "ops", "{", "if", "op", ".", "IsGet", "(", ")", "{"...
// fallback computes the ops to fetch all possible conflicting // leasing keys for a list of ops.
[ "fallback", "computes", "the", "ops", "to", "fetch", "all", "possible", "conflicting", "leasing", "keys", "for", "a", "list", "of", "ops", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/leasing/txn.go#L93-L105
test
etcd-io/etcd
pkg/types/id.go
IDFromString
func IDFromString(s string) (ID, error) { i, err := strconv.ParseUint(s, 16, 64) return ID(i), err }
go
func IDFromString(s string) (ID, error) { i, err := strconv.ParseUint(s, 16, 64) return ID(i), err }
[ "func", "IDFromString", "(", "s", "string", ")", "(", "ID", ",", "error", ")", "{", "i", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "s", ",", "16", ",", "64", ")", "\n", "return", "ID", "(", "i", ")", ",", "err", "\n", "}" ]
// IDFromString attempts to create an ID from a base-16 string.
[ "IDFromString", "attempts", "to", "create", "an", "ID", "from", "a", "base", "-", "16", "string", "." ]
616592d9ba993e3fe9798eef581316016df98906
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/types/id.go#L29-L32
test
dgraph-io/badger
dir_unix.go
release
func (guard *directoryLockGuard) release() error { var err error if !guard.readOnly { // It's important that we remove the pid file first. err = os.Remove(guard.path) } if closeErr := guard.f.Close(); err == nil { err = closeErr } guard.path = "" guard.f = nil return err }
go
func (guard *directoryLockGuard) release() error { var err error if !guard.readOnly { // It's important that we remove the pid file first. err = os.Remove(guard.path) } if closeErr := guard.f.Close(); err == nil { err = closeErr } guard.path = "" guard.f = nil return err }
[ "func", "(", "guard", "*", "directoryLockGuard", ")", "release", "(", ")", "error", "{", "var", "err", "error", "\n", "if", "!", "guard", ".", "readOnly", "{", "err", "=", "os", ".", "Remove", "(", "guard", ".", "path", ")", "\n", "}", "\n", "if", ...
// Release deletes the pid file and releases our lock on the directory.
[ "Release", "deletes", "the", "pid", "file", "and", "releases", "our", "lock", "on", "the", "directory", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/dir_unix.go#L83-L97
test
dgraph-io/badger
y/iterator.go
EncodedSize
func (v *ValueStruct) EncodedSize() uint16 { sz := len(v.Value) + 2 // meta, usermeta. if v.ExpiresAt == 0 { return uint16(sz + 1) } enc := sizeVarint(v.ExpiresAt) return uint16(sz + enc) }
go
func (v *ValueStruct) EncodedSize() uint16 { sz := len(v.Value) + 2 // meta, usermeta. if v.ExpiresAt == 0 { return uint16(sz + 1) } enc := sizeVarint(v.ExpiresAt) return uint16(sz + enc) }
[ "func", "(", "v", "*", "ValueStruct", ")", "EncodedSize", "(", ")", "uint16", "{", "sz", ":=", "len", "(", "v", ".", "Value", ")", "+", "2", "\n", "if", "v", ".", "ExpiresAt", "==", "0", "{", "return", "uint16", "(", "sz", "+", "1", ")", "\n", ...
// EncodedSize is the size of the ValueStruct when encoded
[ "EncodedSize", "is", "the", "size", "of", "the", "ValueStruct", "when", "encoded" ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/iterator.go#L50-L58
test
dgraph-io/badger
y/iterator.go
Decode
func (v *ValueStruct) Decode(b []byte) { v.Meta = b[0] v.UserMeta = b[1] var sz int v.ExpiresAt, sz = binary.Uvarint(b[2:]) v.Value = b[2+sz:] }
go
func (v *ValueStruct) Decode(b []byte) { v.Meta = b[0] v.UserMeta = b[1] var sz int v.ExpiresAt, sz = binary.Uvarint(b[2:]) v.Value = b[2+sz:] }
[ "func", "(", "v", "*", "ValueStruct", ")", "Decode", "(", "b", "[", "]", "byte", ")", "{", "v", ".", "Meta", "=", "b", "[", "0", "]", "\n", "v", ".", "UserMeta", "=", "b", "[", "1", "]", "\n", "var", "sz", "int", "\n", "v", ".", "ExpiresAt"...
// Decode uses the length of the slice to infer the length of the Value field.
[ "Decode", "uses", "the", "length", "of", "the", "slice", "to", "infer", "the", "length", "of", "the", "Value", "field", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/iterator.go#L61-L67
test
dgraph-io/badger
y/iterator.go
NewMergeIterator
func NewMergeIterator(iters []Iterator, reversed bool) *MergeIterator { m := &MergeIterator{all: iters, reversed: reversed} m.h = make(elemHeap, 0, len(iters)) m.initHeap() return m }
go
func NewMergeIterator(iters []Iterator, reversed bool) *MergeIterator { m := &MergeIterator{all: iters, reversed: reversed} m.h = make(elemHeap, 0, len(iters)) m.initHeap() return m }
[ "func", "NewMergeIterator", "(", "iters", "[", "]", "Iterator", ",", "reversed", "bool", ")", "*", "MergeIterator", "{", "m", ":=", "&", "MergeIterator", "{", "all", ":", "iters", ",", "reversed", ":", "reversed", "}", "\n", "m", ".", "h", "=", "make",...
// NewMergeIterator returns a new MergeIterator from a list of Iterators.
[ "NewMergeIterator", "returns", "a", "new", "MergeIterator", "from", "a", "list", "of", "Iterators", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/iterator.go#L144-L149
test
dgraph-io/badger
y/iterator.go
initHeap
func (s *MergeIterator) initHeap() { s.h = s.h[:0] for idx, itr := range s.all { if !itr.Valid() { continue } e := &elem{itr: itr, nice: idx, reversed: s.reversed} s.h = append(s.h, e) } heap.Init(&s.h) for len(s.h) > 0 { it := s.h[0].itr if it == nil || !it.Valid() { heap.Pop(&s.h) continue ...
go
func (s *MergeIterator) initHeap() { s.h = s.h[:0] for idx, itr := range s.all { if !itr.Valid() { continue } e := &elem{itr: itr, nice: idx, reversed: s.reversed} s.h = append(s.h, e) } heap.Init(&s.h) for len(s.h) > 0 { it := s.h[0].itr if it == nil || !it.Valid() { heap.Pop(&s.h) continue ...
[ "func", "(", "s", "*", "MergeIterator", ")", "initHeap", "(", ")", "{", "s", ".", "h", "=", "s", ".", "h", "[", ":", "0", "]", "\n", "for", "idx", ",", "itr", ":=", "range", "s", ".", "all", "{", "if", "!", "itr", ".", "Valid", "(", ")", ...
// initHeap checks all iterators and initializes our heap and array of keys. // Whenever we reverse direction, we need to run this.
[ "initHeap", "checks", "all", "iterators", "and", "initializes", "our", "heap", "and", "array", "of", "keys", ".", "Whenever", "we", "reverse", "direction", "we", "need", "to", "run", "this", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/iterator.go#L161-L180
test
dgraph-io/badger
y/iterator.go
Valid
func (s *MergeIterator) Valid() bool { if s == nil { return false } if len(s.h) == 0 { return false } return s.h[0].itr.Valid() }
go
func (s *MergeIterator) Valid() bool { if s == nil { return false } if len(s.h) == 0 { return false } return s.h[0].itr.Valid() }
[ "func", "(", "s", "*", "MergeIterator", ")", "Valid", "(", ")", "bool", "{", "if", "s", "==", "nil", "{", "return", "false", "\n", "}", "\n", "if", "len", "(", "s", ".", "h", ")", "==", "0", "{", "return", "false", "\n", "}", "\n", "return", ...
// Valid returns whether the MergeIterator is at a valid element.
[ "Valid", "returns", "whether", "the", "MergeIterator", "is", "at", "a", "valid", "element", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/iterator.go#L183-L191
test
dgraph-io/badger
y/iterator.go
Key
func (s *MergeIterator) Key() []byte { if len(s.h) == 0 { return nil } return s.h[0].itr.Key() }
go
func (s *MergeIterator) Key() []byte { if len(s.h) == 0 { return nil } return s.h[0].itr.Key() }
[ "func", "(", "s", "*", "MergeIterator", ")", "Key", "(", ")", "[", "]", "byte", "{", "if", "len", "(", "s", ".", "h", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "return", "s", ".", "h", "[", "0", "]", ".", "itr", ".", "Key", "...
// Key returns the key associated with the current iterator
[ "Key", "returns", "the", "key", "associated", "with", "the", "current", "iterator" ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/iterator.go#L194-L199
test
dgraph-io/badger
y/iterator.go
Value
func (s *MergeIterator) Value() ValueStruct { if len(s.h) == 0 { return ValueStruct{} } return s.h[0].itr.Value() }
go
func (s *MergeIterator) Value() ValueStruct { if len(s.h) == 0 { return ValueStruct{} } return s.h[0].itr.Value() }
[ "func", "(", "s", "*", "MergeIterator", ")", "Value", "(", ")", "ValueStruct", "{", "if", "len", "(", "s", ".", "h", ")", "==", "0", "{", "return", "ValueStruct", "{", "}", "\n", "}", "\n", "return", "s", ".", "h", "[", "0", "]", ".", "itr", ...
// Value returns the value associated with the iterator.
[ "Value", "returns", "the", "value", "associated", "with", "the", "iterator", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/iterator.go#L202-L207
test
dgraph-io/badger
y/iterator.go
Next
func (s *MergeIterator) Next() { if len(s.h) == 0 { return } smallest := s.h[0].itr smallest.Next() for len(s.h) > 0 { smallest = s.h[0].itr if !smallest.Valid() { heap.Pop(&s.h) continue } heap.Fix(&s.h, 0) smallest = s.h[0].itr if smallest.Valid() { if !bytes.Equal(smallest.Key(), s.cur...
go
func (s *MergeIterator) Next() { if len(s.h) == 0 { return } smallest := s.h[0].itr smallest.Next() for len(s.h) > 0 { smallest = s.h[0].itr if !smallest.Valid() { heap.Pop(&s.h) continue } heap.Fix(&s.h, 0) smallest = s.h[0].itr if smallest.Valid() { if !bytes.Equal(smallest.Key(), s.cur...
[ "func", "(", "s", "*", "MergeIterator", ")", "Next", "(", ")", "{", "if", "len", "(", "s", ".", "h", ")", "==", "0", "{", "return", "\n", "}", "\n", "smallest", ":=", "s", ".", "h", "[", "0", "]", ".", "itr", "\n", "smallest", ".", "Next", ...
// Next returns the next element. If it is the same as the current key, ignore it.
[ "Next", "returns", "the", "next", "element", ".", "If", "it", "is", "the", "same", "as", "the", "current", "key", "ignore", "it", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/iterator.go#L210-L238
test
dgraph-io/badger
y/iterator.go
Seek
func (s *MergeIterator) Seek(key []byte) { for _, itr := range s.all { itr.Seek(key) } s.initHeap() }
go
func (s *MergeIterator) Seek(key []byte) { for _, itr := range s.all { itr.Seek(key) } s.initHeap() }
[ "func", "(", "s", "*", "MergeIterator", ")", "Seek", "(", "key", "[", "]", "byte", ")", "{", "for", "_", ",", "itr", ":=", "range", "s", ".", "all", "{", "itr", ".", "Seek", "(", "key", ")", "\n", "}", "\n", "s", ".", "initHeap", "(", ")", ...
// Seek brings us to element with key >= given key.
[ "Seek", "brings", "us", "to", "element", "with", "key", ">", "=", "given", "key", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/iterator.go#L249-L254
test
dgraph-io/badger
y/iterator.go
Close
func (s *MergeIterator) Close() error { for _, itr := range s.all { if err := itr.Close(); err != nil { return errors.Wrap(err, "MergeIterator") } } return nil }
go
func (s *MergeIterator) Close() error { for _, itr := range s.all { if err := itr.Close(); err != nil { return errors.Wrap(err, "MergeIterator") } } return nil }
[ "func", "(", "s", "*", "MergeIterator", ")", "Close", "(", ")", "error", "{", "for", "_", ",", "itr", ":=", "range", "s", ".", "all", "{", "if", "err", ":=", "itr", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", ...
// Close implements y.Iterator
[ "Close", "implements", "y", ".", "Iterator" ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/iterator.go#L257-L264
test
dgraph-io/badger
structs.go
Encode
func (p valuePointer) Encode(b []byte) []byte { binary.BigEndian.PutUint32(b[:4], p.Fid) binary.BigEndian.PutUint32(b[4:8], p.Len) binary.BigEndian.PutUint32(b[8:12], p.Offset) return b[:vptrSize] }
go
func (p valuePointer) Encode(b []byte) []byte { binary.BigEndian.PutUint32(b[:4], p.Fid) binary.BigEndian.PutUint32(b[4:8], p.Len) binary.BigEndian.PutUint32(b[8:12], p.Offset) return b[:vptrSize] }
[ "func", "(", "p", "valuePointer", ")", "Encode", "(", "b", "[", "]", "byte", ")", "[", "]", "byte", "{", "binary", ".", "BigEndian", ".", "PutUint32", "(", "b", "[", ":", "4", "]", ",", "p", ".", "Fid", ")", "\n", "binary", ".", "BigEndian", "....
// Encode encodes Pointer into byte buffer.
[ "Encode", "encodes", "Pointer", "into", "byte", "buffer", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/structs.go#L35-L40
test
dgraph-io/badger
structs.go
Decode
func (h *header) Decode(buf []byte) { h.klen = binary.BigEndian.Uint32(buf[0:4]) h.vlen = binary.BigEndian.Uint32(buf[4:8]) h.expiresAt = binary.BigEndian.Uint64(buf[8:16]) h.meta = buf[16] h.userMeta = buf[17] }
go
func (h *header) Decode(buf []byte) { h.klen = binary.BigEndian.Uint32(buf[0:4]) h.vlen = binary.BigEndian.Uint32(buf[4:8]) h.expiresAt = binary.BigEndian.Uint64(buf[8:16]) h.meta = buf[16] h.userMeta = buf[17] }
[ "func", "(", "h", "*", "header", ")", "Decode", "(", "buf", "[", "]", "byte", ")", "{", "h", ".", "klen", "=", "binary", ".", "BigEndian", ".", "Uint32", "(", "buf", "[", "0", ":", "4", "]", ")", "\n", "h", ".", "vlen", "=", "binary", ".", ...
// Decodes h from buf.
[ "Decodes", "h", "from", "buf", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/structs.go#L71-L77
test
dgraph-io/badger
structs.go
encodeEntry
func encodeEntry(e *Entry, buf *bytes.Buffer) (int, error) { h := header{ klen: uint32(len(e.Key)), vlen: uint32(len(e.Value)), expiresAt: e.ExpiresAt, meta: e.meta, userMeta: e.UserMeta, } var headerEnc [headerBufSize]byte h.Encode(headerEnc[:]) hash := crc32.New(y.CastagnoliCrcTable) ...
go
func encodeEntry(e *Entry, buf *bytes.Buffer) (int, error) { h := header{ klen: uint32(len(e.Key)), vlen: uint32(len(e.Value)), expiresAt: e.ExpiresAt, meta: e.meta, userMeta: e.UserMeta, } var headerEnc [headerBufSize]byte h.Encode(headerEnc[:]) hash := crc32.New(y.CastagnoliCrcTable) ...
[ "func", "encodeEntry", "(", "e", "*", "Entry", ",", "buf", "*", "bytes", ".", "Buffer", ")", "(", "int", ",", "error", ")", "{", "h", ":=", "header", "{", "klen", ":", "uint32", "(", "len", "(", "e", ".", "Key", ")", ")", ",", "vlen", ":", "u...
// Encodes e to buf. Returns number of bytes written.
[ "Encodes", "e", "to", "buf", ".", "Returns", "number", "of", "bytes", "written", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/structs.go#L99-L127
test
dgraph-io/badger
batch.go
SetEntry
func (wb *WriteBatch) SetEntry(e *Entry) error { wb.Lock() defer wb.Unlock() if err := wb.txn.SetEntry(e); err != ErrTxnTooBig { return err } // Txn has reached it's zenith. Commit now. if cerr := wb.commit(); cerr != nil { return cerr } // This time the error must not be ErrTxnTooBig, otherwise, we make t...
go
func (wb *WriteBatch) SetEntry(e *Entry) error { wb.Lock() defer wb.Unlock() if err := wb.txn.SetEntry(e); err != ErrTxnTooBig { return err } // Txn has reached it's zenith. Commit now. if cerr := wb.commit(); cerr != nil { return cerr } // This time the error must not be ErrTxnTooBig, otherwise, we make t...
[ "func", "(", "wb", "*", "WriteBatch", ")", "SetEntry", "(", "e", "*", "Entry", ")", "error", "{", "wb", ".", "Lock", "(", ")", "\n", "defer", "wb", ".", "Unlock", "(", ")", "\n", "if", "err", ":=", "wb", ".", "txn", ".", "SetEntry", "(", "e", ...
// SetEntry is the equivalent of Txn.SetEntry.
[ "SetEntry", "is", "the", "equivalent", "of", "Txn", ".", "SetEntry", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/batch.go#L77-L95
test
dgraph-io/badger
batch.go
Set
func (wb *WriteBatch) Set(k, v []byte, meta byte) error { e := &Entry{Key: k, Value: v, UserMeta: meta} return wb.SetEntry(e) }
go
func (wb *WriteBatch) Set(k, v []byte, meta byte) error { e := &Entry{Key: k, Value: v, UserMeta: meta} return wb.SetEntry(e) }
[ "func", "(", "wb", "*", "WriteBatch", ")", "Set", "(", "k", ",", "v", "[", "]", "byte", ",", "meta", "byte", ")", "error", "{", "e", ":=", "&", "Entry", "{", "Key", ":", "k", ",", "Value", ":", "v", ",", "UserMeta", ":", "meta", "}", "\n", ...
// Set is equivalent of Txn.SetWithMeta.
[ "Set", "is", "equivalent", "of", "Txn", ".", "SetWithMeta", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/batch.go#L98-L101
test
dgraph-io/badger
batch.go
SetWithTTL
func (wb *WriteBatch) SetWithTTL(key, val []byte, dur time.Duration) error { expire := time.Now().Add(dur).Unix() e := &Entry{Key: key, Value: val, ExpiresAt: uint64(expire)} return wb.SetEntry(e) }
go
func (wb *WriteBatch) SetWithTTL(key, val []byte, dur time.Duration) error { expire := time.Now().Add(dur).Unix() e := &Entry{Key: key, Value: val, ExpiresAt: uint64(expire)} return wb.SetEntry(e) }
[ "func", "(", "wb", "*", "WriteBatch", ")", "SetWithTTL", "(", "key", ",", "val", "[", "]", "byte", ",", "dur", "time", ".", "Duration", ")", "error", "{", "expire", ":=", "time", ".", "Now", "(", ")", ".", "Add", "(", "dur", ")", ".", "Unix", "...
// SetWithTTL is equivalent of Txn.SetWithTTL.
[ "SetWithTTL", "is", "equivalent", "of", "Txn", ".", "SetWithTTL", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/batch.go#L104-L108
test
dgraph-io/badger
batch.go
Delete
func (wb *WriteBatch) Delete(k []byte) error { wb.Lock() defer wb.Unlock() if err := wb.txn.Delete(k); err != ErrTxnTooBig { return err } if err := wb.commit(); err != nil { return err } if err := wb.txn.Delete(k); err != nil { wb.err = err return err } return nil }
go
func (wb *WriteBatch) Delete(k []byte) error { wb.Lock() defer wb.Unlock() if err := wb.txn.Delete(k); err != ErrTxnTooBig { return err } if err := wb.commit(); err != nil { return err } if err := wb.txn.Delete(k); err != nil { wb.err = err return err } return nil }
[ "func", "(", "wb", "*", "WriteBatch", ")", "Delete", "(", "k", "[", "]", "byte", ")", "error", "{", "wb", ".", "Lock", "(", ")", "\n", "defer", "wb", ".", "Unlock", "(", ")", "\n", "if", "err", ":=", "wb", ".", "txn", ".", "Delete", "(", "k",...
// Delete is equivalent of Txn.Delete.
[ "Delete", "is", "equivalent", "of", "Txn", ".", "Delete", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/batch.go#L111-L126
test
dgraph-io/badger
batch.go
commit
func (wb *WriteBatch) commit() error { if wb.err != nil { return wb.err } // Get a new txn before we commit this one. So, the new txn doesn't need // to wait for this one to commit. wb.wg.Add(1) wb.txn.CommitWith(wb.callback) wb.txn = wb.db.newTransaction(true, true) // See comment about readTs in NewWriteBat...
go
func (wb *WriteBatch) commit() error { if wb.err != nil { return wb.err } // Get a new txn before we commit this one. So, the new txn doesn't need // to wait for this one to commit. wb.wg.Add(1) wb.txn.CommitWith(wb.callback) wb.txn = wb.db.newTransaction(true, true) // See comment about readTs in NewWriteBat...
[ "func", "(", "wb", "*", "WriteBatch", ")", "commit", "(", ")", "error", "{", "if", "wb", ".", "err", "!=", "nil", "{", "return", "wb", ".", "err", "\n", "}", "\n", "wb", ".", "wg", ".", "Add", "(", "1", ")", "\n", "wb", ".", "txn", ".", "Co...
// Caller to commit must hold a write lock.
[ "Caller", "to", "commit", "must", "hold", "a", "write", "lock", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/batch.go#L129-L141
test
dgraph-io/badger
batch.go
Flush
func (wb *WriteBatch) Flush() error { wb.Lock() _ = wb.commit() wb.txn.Discard() wb.Unlock() wb.wg.Wait() // Safe to access error without any synchronization here. return wb.err }
go
func (wb *WriteBatch) Flush() error { wb.Lock() _ = wb.commit() wb.txn.Discard() wb.Unlock() wb.wg.Wait() // Safe to access error without any synchronization here. return wb.err }
[ "func", "(", "wb", "*", "WriteBatch", ")", "Flush", "(", ")", "error", "{", "wb", ".", "Lock", "(", ")", "\n", "_", "=", "wb", ".", "commit", "(", ")", "\n", "wb", ".", "txn", ".", "Discard", "(", ")", "\n", "wb", ".", "Unlock", "(", ")", "...
// Flush must be called at the end to ensure that any pending writes get committed to Badger. Flush // returns any error stored by WriteBatch.
[ "Flush", "must", "be", "called", "at", "the", "end", "to", "ensure", "that", "any", "pending", "writes", "get", "committed", "to", "Badger", ".", "Flush", "returns", "any", "error", "stored", "by", "WriteBatch", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/batch.go#L145-L154
test
dgraph-io/badger
batch.go
Error
func (wb *WriteBatch) Error() error { wb.Lock() defer wb.Unlock() return wb.err }
go
func (wb *WriteBatch) Error() error { wb.Lock() defer wb.Unlock() return wb.err }
[ "func", "(", "wb", "*", "WriteBatch", ")", "Error", "(", ")", "error", "{", "wb", ".", "Lock", "(", ")", "\n", "defer", "wb", ".", "Unlock", "(", ")", "\n", "return", "wb", ".", "err", "\n", "}" ]
// Error returns any errors encountered so far. No commits would be run once an error is detected.
[ "Error", "returns", "any", "errors", "encountered", "so", "far", ".", "No", "commits", "would", "be", "run", "once", "an", "error", "is", "detected", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/batch.go#L157-L161
test
dgraph-io/badger
db.go
getMemTables
func (db *DB) getMemTables() ([]*skl.Skiplist, func()) { db.RLock() defer db.RUnlock() tables := make([]*skl.Skiplist, len(db.imm)+1) // Get mutable memtable. tables[0] = db.mt tables[0].IncrRef() // Get immutable memtables. last := len(db.imm) - 1 for i := range db.imm { tables[i+1] = db.imm[last-i] ta...
go
func (db *DB) getMemTables() ([]*skl.Skiplist, func()) { db.RLock() defer db.RUnlock() tables := make([]*skl.Skiplist, len(db.imm)+1) // Get mutable memtable. tables[0] = db.mt tables[0].IncrRef() // Get immutable memtables. last := len(db.imm) - 1 for i := range db.imm { tables[i+1] = db.imm[last-i] ta...
[ "func", "(", "db", "*", "DB", ")", "getMemTables", "(", ")", "(", "[", "]", "*", "skl", ".", "Skiplist", ",", "func", "(", ")", ")", "{", "db", ".", "RLock", "(", ")", "\n", "defer", "db", ".", "RUnlock", "(", ")", "\n", "tables", ":=", "make...
// getMemtables returns the current memtables and get references.
[ "getMemtables", "returns", "the", "current", "memtables", "and", "get", "references", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/db.go#L456-L477
test
dgraph-io/badger
db.go
writeRequests
func (db *DB) writeRequests(reqs []*request) error { if len(reqs) == 0 { return nil } done := func(err error) { for _, r := range reqs { r.Err = err r.Wg.Done() } } db.elog.Printf("writeRequests called. Writing to value log") err := db.vlog.write(reqs) if err != nil { done(err) return err } ...
go
func (db *DB) writeRequests(reqs []*request) error { if len(reqs) == 0 { return nil } done := func(err error) { for _, r := range reqs { r.Err = err r.Wg.Done() } } db.elog.Printf("writeRequests called. Writing to value log") err := db.vlog.write(reqs) if err != nil { done(err) return err } ...
[ "func", "(", "db", "*", "DB", ")", "writeRequests", "(", "reqs", "[", "]", "*", "request", ")", "error", "{", "if", "len", "(", "reqs", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "done", ":=", "func", "(", "err", "error", ")", "{", ...
// writeRequests is called serially by only one goroutine.
[ "writeRequests", "is", "called", "serially", "by", "only", "one", "goroutine", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/db.go#L589-L639
test
dgraph-io/badger
db.go
ensureRoomForWrite
func (db *DB) ensureRoomForWrite() error { var err error db.Lock() defer db.Unlock() if db.mt.MemSize() < db.opt.MaxTableSize { return nil } y.AssertTrue(db.mt != nil) // A nil mt indicates that DB is being closed. select { case db.flushChan <- flushTask{mt: db.mt, vptr: db.vhead}: db.elog.Printf("Flushing...
go
func (db *DB) ensureRoomForWrite() error { var err error db.Lock() defer db.Unlock() if db.mt.MemSize() < db.opt.MaxTableSize { return nil } y.AssertTrue(db.mt != nil) // A nil mt indicates that DB is being closed. select { case db.flushChan <- flushTask{mt: db.mt, vptr: db.vhead}: db.elog.Printf("Flushing...
[ "func", "(", "db", "*", "DB", ")", "ensureRoomForWrite", "(", ")", "error", "{", "var", "err", "error", "\n", "db", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "Unlock", "(", ")", "\n", "if", "db", ".", "mt", ".", "MemSize", "(", ")", "<",...
// ensureRoomForWrite is always called serially.
[ "ensureRoomForWrite", "is", "always", "called", "serially", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/db.go#L760-L789
test
dgraph-io/badger
db.go
writeLevel0Table
func writeLevel0Table(ft flushTask, f io.Writer) error { iter := ft.mt.NewIterator() defer iter.Close() b := table.NewTableBuilder() defer b.Close() for iter.SeekToFirst(); iter.Valid(); iter.Next() { if len(ft.dropPrefix) > 0 && bytes.HasPrefix(iter.Key(), ft.dropPrefix) { continue } if err := b.Add(iter...
go
func writeLevel0Table(ft flushTask, f io.Writer) error { iter := ft.mt.NewIterator() defer iter.Close() b := table.NewTableBuilder() defer b.Close() for iter.SeekToFirst(); iter.Valid(); iter.Next() { if len(ft.dropPrefix) > 0 && bytes.HasPrefix(iter.Key(), ft.dropPrefix) { continue } if err := b.Add(iter...
[ "func", "writeLevel0Table", "(", "ft", "flushTask", ",", "f", "io", ".", "Writer", ")", "error", "{", "iter", ":=", "ft", ".", "mt", ".", "NewIterator", "(", ")", "\n", "defer", "iter", ".", "Close", "(", ")", "\n", "b", ":=", "table", ".", "NewTab...
// WriteLevel0Table flushes memtable.
[ "WriteLevel0Table", "flushes", "memtable", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/db.go#L796-L811
test
dgraph-io/badger
db.go
handleFlushTask
func (db *DB) handleFlushTask(ft flushTask) error { if !ft.mt.Empty() { // Store badger head even if vptr is zero, need it for readTs db.opt.Debugf("Storing value log head: %+v\n", ft.vptr) db.elog.Printf("Storing offset: %+v\n", ft.vptr) offset := make([]byte, vptrSize) ft.vptr.Encode(offset) // Pick the...
go
func (db *DB) handleFlushTask(ft flushTask) error { if !ft.mt.Empty() { // Store badger head even if vptr is zero, need it for readTs db.opt.Debugf("Storing value log head: %+v\n", ft.vptr) db.elog.Printf("Storing offset: %+v\n", ft.vptr) offset := make([]byte, vptrSize) ft.vptr.Encode(offset) // Pick the...
[ "func", "(", "db", "*", "DB", ")", "handleFlushTask", "(", "ft", "flushTask", ")", "error", "{", "if", "!", "ft", ".", "mt", ".", "Empty", "(", ")", "{", "db", ".", "opt", ".", "Debugf", "(", "\"Storing value log head: %+v\\n\"", ",", "\\n", ")", "\n...
// handleFlushTask must be run serially.
[ "handleFlushTask", "must", "be", "run", "serially", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/db.go#L820-L869
test
dgraph-io/badger
db.go
flushMemtable
func (db *DB) flushMemtable(lc *y.Closer) error { defer lc.Done() for ft := range db.flushChan { if ft.mt == nil { // We close db.flushChan now, instead of sending a nil ft.mt. continue } for { err := db.handleFlushTask(ft) if err == nil { // Update s.imm. Need a lock. db.Lock() // This...
go
func (db *DB) flushMemtable(lc *y.Closer) error { defer lc.Done() for ft := range db.flushChan { if ft.mt == nil { // We close db.flushChan now, instead of sending a nil ft.mt. continue } for { err := db.handleFlushTask(ft) if err == nil { // Update s.imm. Need a lock. db.Lock() // This...
[ "func", "(", "db", "*", "DB", ")", "flushMemtable", "(", "lc", "*", "y", ".", "Closer", ")", "error", "{", "defer", "lc", ".", "Done", "(", ")", "\n", "for", "ft", ":=", "range", "db", ".", "flushChan", "{", "if", "ft", ".", "mt", "==", "nil", ...
// flushMemtable must keep running until we send it an empty flushTask. If there // are errors during handling the flush task, we'll retry indefinitely.
[ "flushMemtable", "must", "keep", "running", "until", "we", "send", "it", "an", "empty", "flushTask", ".", "If", "there", "are", "errors", "during", "handling", "the", "flush", "task", "we", "ll", "retry", "indefinitely", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/db.go#L873-L904
test
dgraph-io/badger
db.go
calculateSize
func (db *DB) calculateSize() { newInt := func(val int64) *expvar.Int { v := new(expvar.Int) v.Add(val) return v } totalSize := func(dir string) (int64, int64) { var lsmSize, vlogSize int64 err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { if err != nil { return err ...
go
func (db *DB) calculateSize() { newInt := func(val int64) *expvar.Int { v := new(expvar.Int) v.Add(val) return v } totalSize := func(dir string) (int64, int64) { var lsmSize, vlogSize int64 err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { if err != nil { return err ...
[ "func", "(", "db", "*", "DB", ")", "calculateSize", "(", ")", "{", "newInt", ":=", "func", "(", "val", "int64", ")", "*", "expvar", ".", "Int", "{", "v", ":=", "new", "(", "expvar", ".", "Int", ")", "\n", "v", ".", "Add", "(", "val", ")", "\n...
// This function does a filewalk, calculates the size of vlog and sst files and stores it in // y.LSMSize and y.VlogSize.
[ "This", "function", "does", "a", "filewalk", "calculates", "the", "size", "of", "vlog", "and", "sst", "files", "and", "stores", "it", "in", "y", ".", "LSMSize", "and", "y", ".", "VlogSize", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/db.go#L919-L953
test
dgraph-io/badger
db.go
Size
func (db *DB) Size() (lsm, vlog int64) { if y.LSMSize.Get(db.opt.Dir) == nil { lsm, vlog = 0, 0 return } lsm = y.LSMSize.Get(db.opt.Dir).(*expvar.Int).Value() vlog = y.VlogSize.Get(db.opt.Dir).(*expvar.Int).Value() return }
go
func (db *DB) Size() (lsm, vlog int64) { if y.LSMSize.Get(db.opt.Dir) == nil { lsm, vlog = 0, 0 return } lsm = y.LSMSize.Get(db.opt.Dir).(*expvar.Int).Value() vlog = y.VlogSize.Get(db.opt.Dir).(*expvar.Int).Value() return }
[ "func", "(", "db", "*", "DB", ")", "Size", "(", ")", "(", "lsm", ",", "vlog", "int64", ")", "{", "if", "y", ".", "LSMSize", ".", "Get", "(", "db", ".", "opt", ".", "Dir", ")", "==", "nil", "{", "lsm", ",", "vlog", "=", "0", ",", "0", "\n"...
// Size returns the size of lsm and value log files in bytes. It can be used to decide how often to // call RunValueLogGC.
[ "Size", "returns", "the", "size", "of", "lsm", "and", "value", "log", "files", "in", "bytes", ".", "It", "can", "be", "used", "to", "decide", "how", "often", "to", "call", "RunValueLogGC", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/db.go#L1022-L1030
test
dgraph-io/badger
db.go
Next
func (seq *Sequence) Next() (uint64, error) { seq.Lock() defer seq.Unlock() if seq.next >= seq.leased { if err := seq.updateLease(); err != nil { return 0, err } } val := seq.next seq.next++ return val, nil }
go
func (seq *Sequence) Next() (uint64, error) { seq.Lock() defer seq.Unlock() if seq.next >= seq.leased { if err := seq.updateLease(); err != nil { return 0, err } } val := seq.next seq.next++ return val, nil }
[ "func", "(", "seq", "*", "Sequence", ")", "Next", "(", ")", "(", "uint64", ",", "error", ")", "{", "seq", ".", "Lock", "(", ")", "\n", "defer", "seq", ".", "Unlock", "(", ")", "\n", "if", "seq", ".", "next", ">=", "seq", ".", "leased", "{", "...
// Next would return the next integer in the sequence, updating the lease by running a transaction // if needed.
[ "Next", "would", "return", "the", "next", "integer", "in", "the", "sequence", "updating", "the", "lease", "by", "running", "a", "transaction", "if", "needed", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/db.go#L1044-L1055
test
dgraph-io/badger
db.go
Release
func (seq *Sequence) Release() error { seq.Lock() defer seq.Unlock() err := seq.db.Update(func(txn *Txn) error { var buf [8]byte binary.BigEndian.PutUint64(buf[:], seq.next) return txn.Set(seq.key, buf[:]) }) if err != nil { return err } seq.leased = seq.next return nil }
go
func (seq *Sequence) Release() error { seq.Lock() defer seq.Unlock() err := seq.db.Update(func(txn *Txn) error { var buf [8]byte binary.BigEndian.PutUint64(buf[:], seq.next) return txn.Set(seq.key, buf[:]) }) if err != nil { return err } seq.leased = seq.next return nil }
[ "func", "(", "seq", "*", "Sequence", ")", "Release", "(", ")", "error", "{", "seq", ".", "Lock", "(", ")", "\n", "defer", "seq", ".", "Unlock", "(", ")", "\n", "err", ":=", "seq", ".", "db", ".", "Update", "(", "func", "(", "txn", "*", "Txn", ...
// Release the leased sequence to avoid wasted integers. This should be done right // before closing the associated DB. However it is valid to use the sequence after // it was released, causing a new lease with full bandwidth.
[ "Release", "the", "leased", "sequence", "to", "avoid", "wasted", "integers", ".", "This", "should", "be", "done", "right", "before", "closing", "the", "associated", "DB", ".", "However", "it", "is", "valid", "to", "use", "the", "sequence", "after", "it", "...
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/db.go#L1060-L1073
test
dgraph-io/badger
db.go
KeySplits
func (db *DB) KeySplits(prefix []byte) []string { var splits []string for _, ti := range db.Tables() { // We don't use ti.Left, because that has a tendency to store !badger // keys. if bytes.HasPrefix(ti.Right, prefix) { splits = append(splits, string(ti.Right)) } } sort.Strings(splits) return splits }
go
func (db *DB) KeySplits(prefix []byte) []string { var splits []string for _, ti := range db.Tables() { // We don't use ti.Left, because that has a tendency to store !badger // keys. if bytes.HasPrefix(ti.Right, prefix) { splits = append(splits, string(ti.Right)) } } sort.Strings(splits) return splits }
[ "func", "(", "db", "*", "DB", ")", "KeySplits", "(", "prefix", "[", "]", "byte", ")", "[", "]", "string", "{", "var", "splits", "[", "]", "string", "\n", "for", "_", ",", "ti", ":=", "range", "db", ".", "Tables", "(", ")", "{", "if", "bytes", ...
// KeySplits can be used to get rough key ranges to divide up iteration over // the DB.
[ "KeySplits", "can", "be", "used", "to", "get", "rough", "key", "ranges", "to", "divide", "up", "iteration", "over", "the", "DB", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/db.go#L1139-L1150
test
dgraph-io/badger
db.go
Flatten
func (db *DB) Flatten(workers int) error { db.stopCompactions() defer db.startCompactions() compactAway := func(cp compactionPriority) error { db.opt.Infof("Attempting to compact with %+v\n", cp) errCh := make(chan error, 1) for i := 0; i < workers; i++ { go func() { errCh <- db.lc.doCompact(cp) }()...
go
func (db *DB) Flatten(workers int) error { db.stopCompactions() defer db.startCompactions() compactAway := func(cp compactionPriority) error { db.opt.Infof("Attempting to compact with %+v\n", cp) errCh := make(chan error, 1) for i := 0; i < workers; i++ { go func() { errCh <- db.lc.doCompact(cp) }()...
[ "func", "(", "db", "*", "DB", ")", "Flatten", "(", "workers", "int", ")", "error", "{", "db", ".", "stopCompactions", "(", ")", "\n", "defer", "db", ".", "startCompactions", "(", ")", "\n", "compactAway", ":=", "func", "(", "cp", "compactionPriority", ...
// Flatten can be used to force compactions on the LSM tree so all the tables fall on the same // level. This ensures that all the versions of keys are colocated and not split across multiple // levels, which is necessary after a restore from backup. During Flatten, live compactions are // stopped. Ideally, no writes a...
[ "Flatten", "can", "be", "used", "to", "force", "compactions", "on", "the", "LSM", "tree", "so", "all", "the", "tables", "fall", "on", "the", "same", "level", ".", "This", "ensures", "that", "all", "the", "versions", "of", "keys", "are", "colocated", "and...
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/db.go#L1192-L1256
test
dgraph-io/badger
y/mmap_unix.go
Mmap
func Mmap(fd *os.File, writable bool, size int64) ([]byte, error) { mtype := unix.PROT_READ if writable { mtype |= unix.PROT_WRITE } return unix.Mmap(int(fd.Fd()), 0, int(size), mtype, unix.MAP_SHARED) }
go
func Mmap(fd *os.File, writable bool, size int64) ([]byte, error) { mtype := unix.PROT_READ if writable { mtype |= unix.PROT_WRITE } return unix.Mmap(int(fd.Fd()), 0, int(size), mtype, unix.MAP_SHARED) }
[ "func", "Mmap", "(", "fd", "*", "os", ".", "File", ",", "writable", "bool", ",", "size", "int64", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "mtype", ":=", "unix", ".", "PROT_READ", "\n", "if", "writable", "{", "mtype", "|=", "unix", "."...
// Mmap uses the mmap system call to memory-map a file. If writable is true, // memory protection of the pages is set so that they may be written to as well.
[ "Mmap", "uses", "the", "mmap", "system", "call", "to", "memory", "-", "map", "a", "file", ".", "If", "writable", "is", "true", "memory", "protection", "of", "the", "pages", "is", "set", "so", "that", "they", "may", "be", "written", "to", "as", "well", ...
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/mmap_unix.go#L31-L37
test
dgraph-io/badger
y/mmap_unix.go
Madvise
func Madvise(b []byte, readahead bool) error { flags := unix.MADV_NORMAL if !readahead { flags = unix.MADV_RANDOM } return madvise(b, flags) }
go
func Madvise(b []byte, readahead bool) error { flags := unix.MADV_NORMAL if !readahead { flags = unix.MADV_RANDOM } return madvise(b, flags) }
[ "func", "Madvise", "(", "b", "[", "]", "byte", ",", "readahead", "bool", ")", "error", "{", "flags", ":=", "unix", ".", "MADV_NORMAL", "\n", "if", "!", "readahead", "{", "flags", "=", "unix", ".", "MADV_RANDOM", "\n", "}", "\n", "return", "madvise", ...
// Madvise uses the madvise system call to give advise about the use of memory // when using a slice that is memory-mapped to a file. Set the readahead flag to // false if page references are expected in random order.
[ "Madvise", "uses", "the", "madvise", "system", "call", "to", "give", "advise", "about", "the", "use", "of", "memory", "when", "using", "a", "slice", "that", "is", "memory", "-", "mapped", "to", "a", "file", ".", "Set", "the", "readahead", "flag", "to", ...
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/mmap_unix.go#L47-L53
test
dgraph-io/badger
txn.go
setDiscardTs
func (o *oracle) setDiscardTs(ts uint64) { o.Lock() defer o.Unlock() o.discardTs = ts }
go
func (o *oracle) setDiscardTs(ts uint64) { o.Lock() defer o.Unlock() o.discardTs = ts }
[ "func", "(", "o", "*", "oracle", ")", "setDiscardTs", "(", "ts", "uint64", ")", "{", "o", ".", "Lock", "(", ")", "\n", "defer", "o", ".", "Unlock", "(", ")", "\n", "o", ".", "discardTs", "=", "ts", "\n", "}" ]
// Any deleted or invalid versions at or below ts would be discarded during // compaction to reclaim disk space in LSM tree and thence value log.
[ "Any", "deleted", "or", "invalid", "versions", "at", "or", "below", "ts", "would", "be", "discarded", "during", "compaction", "to", "reclaim", "disk", "space", "in", "LSM", "tree", "and", "thence", "value", "log", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/txn.go#L132-L136
test
dgraph-io/badger
txn.go
hasConflict
func (o *oracle) hasConflict(txn *Txn) bool { if len(txn.reads) == 0 { return false } for _, ro := range txn.reads { // A commit at the read timestamp is expected. // But, any commit after the read timestamp should cause a conflict. if ts, has := o.commits[ro]; has && ts > txn.readTs { return true } } ...
go
func (o *oracle) hasConflict(txn *Txn) bool { if len(txn.reads) == 0 { return false } for _, ro := range txn.reads { // A commit at the read timestamp is expected. // But, any commit after the read timestamp should cause a conflict. if ts, has := o.commits[ro]; has && ts > txn.readTs { return true } } ...
[ "func", "(", "o", "*", "oracle", ")", "hasConflict", "(", "txn", "*", "Txn", ")", "bool", "{", "if", "len", "(", "txn", ".", "reads", ")", "==", "0", "{", "return", "false", "\n", "}", "\n", "for", "_", ",", "ro", ":=", "range", "txn", ".", "...
// hasConflict must be called while having a lock.
[ "hasConflict", "must", "be", "called", "while", "having", "a", "lock", "." ]
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/txn.go#L148-L160
test
dgraph-io/badger
txn.go
Set
func (txn *Txn) Set(key, val []byte) error { e := &Entry{ Key: key, Value: val, } return txn.SetEntry(e) }
go
func (txn *Txn) Set(key, val []byte) error { e := &Entry{ Key: key, Value: val, } return txn.SetEntry(e) }
[ "func", "(", "txn", "*", "Txn", ")", "Set", "(", "key", ",", "val", "[", "]", "byte", ")", "error", "{", "e", ":=", "&", "Entry", "{", "Key", ":", "key", ",", "Value", ":", "val", ",", "}", "\n", "return", "txn", ".", "SetEntry", "(", "e", ...
// Set adds a key-value pair to the database. // // It will return ErrReadOnlyTxn if update flag was set to false when creating the // transaction. // // The current transaction keeps a reference to the key and val byte slice // arguments. Users must not modify key and val until the end of the transaction.
[ "Set", "adds", "a", "key", "-", "value", "pair", "to", "the", "database", ".", "It", "will", "return", "ErrReadOnlyTxn", "if", "update", "flag", "was", "set", "to", "false", "when", "creating", "the", "transaction", ".", "The", "current", "transaction", "k...
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/txn.go#L308-L314
test
dgraph-io/badger
txn.go
SetWithMeta
func (txn *Txn) SetWithMeta(key, val []byte, meta byte) error { e := &Entry{Key: key, Value: val, UserMeta: meta} return txn.SetEntry(e) }
go
func (txn *Txn) SetWithMeta(key, val []byte, meta byte) error { e := &Entry{Key: key, Value: val, UserMeta: meta} return txn.SetEntry(e) }
[ "func", "(", "txn", "*", "Txn", ")", "SetWithMeta", "(", "key", ",", "val", "[", "]", "byte", ",", "meta", "byte", ")", "error", "{", "e", ":=", "&", "Entry", "{", "Key", ":", "key", ",", "Value", ":", "val", ",", "UserMeta", ":", "meta", "}", ...
// SetWithMeta adds a key-value pair to the database, along with a metadata // byte. // // This byte is stored alongside the key, and can be used as an aid to // interpret the value or store other contextual bits corresponding to the // key-value pair. // // The current transaction keeps a reference to the key and val ...
[ "SetWithMeta", "adds", "a", "key", "-", "value", "pair", "to", "the", "database", "along", "with", "a", "metadata", "byte", ".", "This", "byte", "is", "stored", "alongside", "the", "key", "and", "can", "be", "used", "as", "an", "aid", "to", "interpret", ...
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/txn.go#L325-L328
test
dgraph-io/badger
txn.go
Delete
func (txn *Txn) Delete(key []byte) error { e := &Entry{ Key: key, meta: bitDelete, } return txn.modify(e) }
go
func (txn *Txn) Delete(key []byte) error { e := &Entry{ Key: key, meta: bitDelete, } return txn.modify(e) }
[ "func", "(", "txn", "*", "Txn", ")", "Delete", "(", "key", "[", "]", "byte", ")", "error", "{", "e", ":=", "&", "Entry", "{", "Key", ":", "key", ",", "meta", ":", "bitDelete", ",", "}", "\n", "return", "txn", ".", "modify", "(", "e", ")", "\n...
// Delete deletes a key. // // This is done by adding a delete marker for the key at commit timestamp. Any // reads happening before this timestamp would be unaffected. Any reads after // this commit would see the deletion. // // The current transaction keeps a reference to the key byte slice argument. // Users must n...
[ "Delete", "deletes", "a", "key", ".", "This", "is", "done", "by", "adding", "a", "delete", "marker", "for", "the", "key", "at", "commit", "timestamp", ".", "Any", "reads", "happening", "before", "this", "timestamp", "would", "be", "unaffected", ".", "Any",...
6b796b3ebec3ff006fcb1b425836cd784651e9fd
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/txn.go#L419-L425
test