id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequencelengths 21
1.41k
| docstring
stringlengths 6
2.61k
| docstring_tokens
sequencelengths 3
215
| sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
147,900 | goraft/raft | snapshot.go | Encode | func (req *SnapshotRecoveryRequest) Encode(w io.Writer) (int, error) {
protoPeers := make([]*protobuf.SnapshotRecoveryRequest_Peer, len(req.Peers))
for i, peer := range req.Peers {
protoPeers[i] = &protobuf.SnapshotRecoveryRequest_Peer{
Name: proto.String(peer.Name),
ConnectionString: proto.String(peer.ConnectionString),
}
}
pb := &protobuf.SnapshotRecoveryRequest{
LeaderName: proto.String(req.LeaderName),
LastIndex: proto.Uint64(req.LastIndex),
LastTerm: proto.Uint64(req.LastTerm),
Peers: protoPeers,
State: req.State,
}
p, err := proto.Marshal(pb)
if err != nil {
return -1, err
}
return w.Write(p)
} | go | func (req *SnapshotRecoveryRequest) Encode(w io.Writer) (int, error) {
protoPeers := make([]*protobuf.SnapshotRecoveryRequest_Peer, len(req.Peers))
for i, peer := range req.Peers {
protoPeers[i] = &protobuf.SnapshotRecoveryRequest_Peer{
Name: proto.String(peer.Name),
ConnectionString: proto.String(peer.ConnectionString),
}
}
pb := &protobuf.SnapshotRecoveryRequest{
LeaderName: proto.String(req.LeaderName),
LastIndex: proto.Uint64(req.LastIndex),
LastTerm: proto.Uint64(req.LastTerm),
Peers: protoPeers,
State: req.State,
}
p, err := proto.Marshal(pb)
if err != nil {
return -1, err
}
return w.Write(p)
} | [
"func",
"(",
"req",
"*",
"SnapshotRecoveryRequest",
")",
"Encode",
"(",
"w",
"io",
".",
"Writer",
")",
"(",
"int",
",",
"error",
")",
"{",
"protoPeers",
":=",
"make",
"(",
"[",
"]",
"*",
"protobuf",
".",
"SnapshotRecoveryRequest_Peer",
",",
"len",
"(",
"req",
".",
"Peers",
")",
")",
"\n\n",
"for",
"i",
",",
"peer",
":=",
"range",
"req",
".",
"Peers",
"{",
"protoPeers",
"[",
"i",
"]",
"=",
"&",
"protobuf",
".",
"SnapshotRecoveryRequest_Peer",
"{",
"Name",
":",
"proto",
".",
"String",
"(",
"peer",
".",
"Name",
")",
",",
"ConnectionString",
":",
"proto",
".",
"String",
"(",
"peer",
".",
"ConnectionString",
")",
",",
"}",
"\n",
"}",
"\n\n",
"pb",
":=",
"&",
"protobuf",
".",
"SnapshotRecoveryRequest",
"{",
"LeaderName",
":",
"proto",
".",
"String",
"(",
"req",
".",
"LeaderName",
")",
",",
"LastIndex",
":",
"proto",
".",
"Uint64",
"(",
"req",
".",
"LastIndex",
")",
",",
"LastTerm",
":",
"proto",
".",
"Uint64",
"(",
"req",
".",
"LastTerm",
")",
",",
"Peers",
":",
"protoPeers",
",",
"State",
":",
"req",
".",
"State",
",",
"}",
"\n",
"p",
",",
"err",
":=",
"proto",
".",
"Marshal",
"(",
"pb",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"w",
".",
"Write",
"(",
"p",
")",
"\n",
"}"
] | // Encodes the SnapshotRecoveryRequest to a buffer. Returns the number of bytes
// written and any error that may have occurred. | [
"Encodes",
"the",
"SnapshotRecoveryRequest",
"to",
"a",
"buffer",
".",
"Returns",
"the",
"number",
"of",
"bytes",
"written",
"and",
"any",
"error",
"that",
"may",
"have",
"occurred",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/snapshot.go#L109-L133 |
147,901 | goraft/raft | snapshot.go | Decode | func (req *SnapshotRecoveryRequest) Decode(r io.Reader) (int, error) {
data, err := ioutil.ReadAll(r)
if err != nil {
return 0, err
}
totalBytes := len(data)
pb := &protobuf.SnapshotRecoveryRequest{}
if err = proto.Unmarshal(data, pb); err != nil {
return -1, err
}
req.LeaderName = pb.GetLeaderName()
req.LastIndex = pb.GetLastIndex()
req.LastTerm = pb.GetLastTerm()
req.State = pb.GetState()
req.Peers = make([]*Peer, len(pb.Peers))
for i, peer := range pb.Peers {
req.Peers[i] = &Peer{
Name: peer.GetName(),
ConnectionString: peer.GetConnectionString(),
}
}
return totalBytes, nil
} | go | func (req *SnapshotRecoveryRequest) Decode(r io.Reader) (int, error) {
data, err := ioutil.ReadAll(r)
if err != nil {
return 0, err
}
totalBytes := len(data)
pb := &protobuf.SnapshotRecoveryRequest{}
if err = proto.Unmarshal(data, pb); err != nil {
return -1, err
}
req.LeaderName = pb.GetLeaderName()
req.LastIndex = pb.GetLastIndex()
req.LastTerm = pb.GetLastTerm()
req.State = pb.GetState()
req.Peers = make([]*Peer, len(pb.Peers))
for i, peer := range pb.Peers {
req.Peers[i] = &Peer{
Name: peer.GetName(),
ConnectionString: peer.GetConnectionString(),
}
}
return totalBytes, nil
} | [
"func",
"(",
"req",
"*",
"SnapshotRecoveryRequest",
")",
"Decode",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"int",
",",
"error",
")",
"{",
"data",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"totalBytes",
":=",
"len",
"(",
"data",
")",
"\n\n",
"pb",
":=",
"&",
"protobuf",
".",
"SnapshotRecoveryRequest",
"{",
"}",
"\n",
"if",
"err",
"=",
"proto",
".",
"Unmarshal",
"(",
"data",
",",
"pb",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"err",
"\n",
"}",
"\n\n",
"req",
".",
"LeaderName",
"=",
"pb",
".",
"GetLeaderName",
"(",
")",
"\n",
"req",
".",
"LastIndex",
"=",
"pb",
".",
"GetLastIndex",
"(",
")",
"\n",
"req",
".",
"LastTerm",
"=",
"pb",
".",
"GetLastTerm",
"(",
")",
"\n",
"req",
".",
"State",
"=",
"pb",
".",
"GetState",
"(",
")",
"\n\n",
"req",
".",
"Peers",
"=",
"make",
"(",
"[",
"]",
"*",
"Peer",
",",
"len",
"(",
"pb",
".",
"Peers",
")",
")",
"\n\n",
"for",
"i",
",",
"peer",
":=",
"range",
"pb",
".",
"Peers",
"{",
"req",
".",
"Peers",
"[",
"i",
"]",
"=",
"&",
"Peer",
"{",
"Name",
":",
"peer",
".",
"GetName",
"(",
")",
",",
"ConnectionString",
":",
"peer",
".",
"GetConnectionString",
"(",
")",
",",
"}",
"\n",
"}",
"\n\n",
"return",
"totalBytes",
",",
"nil",
"\n",
"}"
] | // Decodes the SnapshotRecoveryRequest from a buffer. Returns the number of bytes read and
// any error that occurs. | [
"Decodes",
"the",
"SnapshotRecoveryRequest",
"from",
"a",
"buffer",
".",
"Returns",
"the",
"number",
"of",
"bytes",
"read",
"and",
"any",
"error",
"that",
"occurs",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/snapshot.go#L137-L166 |
147,902 | goraft/raft | snapshot.go | newSnapshotRecoveryResponse | func newSnapshotRecoveryResponse(term uint64, success bool, commitIndex uint64) *SnapshotRecoveryResponse {
return &SnapshotRecoveryResponse{
Term: term,
Success: success,
CommitIndex: commitIndex,
}
} | go | func newSnapshotRecoveryResponse(term uint64, success bool, commitIndex uint64) *SnapshotRecoveryResponse {
return &SnapshotRecoveryResponse{
Term: term,
Success: success,
CommitIndex: commitIndex,
}
} | [
"func",
"newSnapshotRecoveryResponse",
"(",
"term",
"uint64",
",",
"success",
"bool",
",",
"commitIndex",
"uint64",
")",
"*",
"SnapshotRecoveryResponse",
"{",
"return",
"&",
"SnapshotRecoveryResponse",
"{",
"Term",
":",
"term",
",",
"Success",
":",
"success",
",",
"CommitIndex",
":",
"commitIndex",
",",
"}",
"\n",
"}"
] | // Creates a new Snapshot response. | [
"Creates",
"a",
"new",
"Snapshot",
"response",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/snapshot.go#L169-L175 |
147,903 | goraft/raft | snapshot.go | Encode | func (req *SnapshotRecoveryResponse) Encode(w io.Writer) (int, error) {
pb := &protobuf.SnapshotRecoveryResponse{
Term: proto.Uint64(req.Term),
Success: proto.Bool(req.Success),
CommitIndex: proto.Uint64(req.CommitIndex),
}
p, err := proto.Marshal(pb)
if err != nil {
return -1, err
}
return w.Write(p)
} | go | func (req *SnapshotRecoveryResponse) Encode(w io.Writer) (int, error) {
pb := &protobuf.SnapshotRecoveryResponse{
Term: proto.Uint64(req.Term),
Success: proto.Bool(req.Success),
CommitIndex: proto.Uint64(req.CommitIndex),
}
p, err := proto.Marshal(pb)
if err != nil {
return -1, err
}
return w.Write(p)
} | [
"func",
"(",
"req",
"*",
"SnapshotRecoveryResponse",
")",
"Encode",
"(",
"w",
"io",
".",
"Writer",
")",
"(",
"int",
",",
"error",
")",
"{",
"pb",
":=",
"&",
"protobuf",
".",
"SnapshotRecoveryResponse",
"{",
"Term",
":",
"proto",
".",
"Uint64",
"(",
"req",
".",
"Term",
")",
",",
"Success",
":",
"proto",
".",
"Bool",
"(",
"req",
".",
"Success",
")",
",",
"CommitIndex",
":",
"proto",
".",
"Uint64",
"(",
"req",
".",
"CommitIndex",
")",
",",
"}",
"\n",
"p",
",",
"err",
":=",
"proto",
".",
"Marshal",
"(",
"pb",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"w",
".",
"Write",
"(",
"p",
")",
"\n",
"}"
] | // Encode writes the response to a writer.
// Returns the number of bytes written and any error that occurs. | [
"Encode",
"writes",
"the",
"response",
"to",
"a",
"writer",
".",
"Returns",
"the",
"number",
"of",
"bytes",
"written",
"and",
"any",
"error",
"that",
"occurs",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/snapshot.go#L179-L191 |
147,904 | goraft/raft | snapshot.go | Decode | func (req *SnapshotRecoveryResponse) Decode(r io.Reader) (int, error) {
data, err := ioutil.ReadAll(r)
if err != nil {
return 0, err
}
totalBytes := len(data)
pb := &protobuf.SnapshotRecoveryResponse{}
if err := proto.Unmarshal(data, pb); err != nil {
return -1, err
}
req.Term = pb.GetTerm()
req.Success = pb.GetSuccess()
req.CommitIndex = pb.GetCommitIndex()
return totalBytes, nil
} | go | func (req *SnapshotRecoveryResponse) Decode(r io.Reader) (int, error) {
data, err := ioutil.ReadAll(r)
if err != nil {
return 0, err
}
totalBytes := len(data)
pb := &protobuf.SnapshotRecoveryResponse{}
if err := proto.Unmarshal(data, pb); err != nil {
return -1, err
}
req.Term = pb.GetTerm()
req.Success = pb.GetSuccess()
req.CommitIndex = pb.GetCommitIndex()
return totalBytes, nil
} | [
"func",
"(",
"req",
"*",
"SnapshotRecoveryResponse",
")",
"Decode",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"int",
",",
"error",
")",
"{",
"data",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"totalBytes",
":=",
"len",
"(",
"data",
")",
"\n\n",
"pb",
":=",
"&",
"protobuf",
".",
"SnapshotRecoveryResponse",
"{",
"}",
"\n",
"if",
"err",
":=",
"proto",
".",
"Unmarshal",
"(",
"data",
",",
"pb",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"err",
"\n",
"}",
"\n\n",
"req",
".",
"Term",
"=",
"pb",
".",
"GetTerm",
"(",
")",
"\n",
"req",
".",
"Success",
"=",
"pb",
".",
"GetSuccess",
"(",
")",
"\n",
"req",
".",
"CommitIndex",
"=",
"pb",
".",
"GetCommitIndex",
"(",
")",
"\n\n",
"return",
"totalBytes",
",",
"nil",
"\n",
"}"
] | // Decodes the SnapshotRecoveryResponse from a buffer. | [
"Decodes",
"the",
"SnapshotRecoveryResponse",
"from",
"a",
"buffer",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/snapshot.go#L194-L213 |
147,905 | goraft/raft | snapshot.go | Encode | func (req *SnapshotRequest) Encode(w io.Writer) (int, error) {
pb := &protobuf.SnapshotRequest{
LeaderName: proto.String(req.LeaderName),
LastIndex: proto.Uint64(req.LastIndex),
LastTerm: proto.Uint64(req.LastTerm),
}
p, err := proto.Marshal(pb)
if err != nil {
return -1, err
}
return w.Write(p)
} | go | func (req *SnapshotRequest) Encode(w io.Writer) (int, error) {
pb := &protobuf.SnapshotRequest{
LeaderName: proto.String(req.LeaderName),
LastIndex: proto.Uint64(req.LastIndex),
LastTerm: proto.Uint64(req.LastTerm),
}
p, err := proto.Marshal(pb)
if err != nil {
return -1, err
}
return w.Write(p)
} | [
"func",
"(",
"req",
"*",
"SnapshotRequest",
")",
"Encode",
"(",
"w",
"io",
".",
"Writer",
")",
"(",
"int",
",",
"error",
")",
"{",
"pb",
":=",
"&",
"protobuf",
".",
"SnapshotRequest",
"{",
"LeaderName",
":",
"proto",
".",
"String",
"(",
"req",
".",
"LeaderName",
")",
",",
"LastIndex",
":",
"proto",
".",
"Uint64",
"(",
"req",
".",
"LastIndex",
")",
",",
"LastTerm",
":",
"proto",
".",
"Uint64",
"(",
"req",
".",
"LastTerm",
")",
",",
"}",
"\n",
"p",
",",
"err",
":=",
"proto",
".",
"Marshal",
"(",
"pb",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"w",
".",
"Write",
"(",
"p",
")",
"\n",
"}"
] | // Encodes the SnapshotRequest to a buffer. Returns the number of bytes
// written and any error that may have occurred. | [
"Encodes",
"the",
"SnapshotRequest",
"to",
"a",
"buffer",
".",
"Returns",
"the",
"number",
"of",
"bytes",
"written",
"and",
"any",
"error",
"that",
"may",
"have",
"occurred",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/snapshot.go#L226-L238 |
147,906 | goraft/raft | snapshot.go | Decode | func (req *SnapshotRequest) Decode(r io.Reader) (int, error) {
data, err := ioutil.ReadAll(r)
if err != nil {
return 0, err
}
totalBytes := len(data)
pb := &protobuf.SnapshotRequest{}
if err := proto.Unmarshal(data, pb); err != nil {
return -1, err
}
req.LeaderName = pb.GetLeaderName()
req.LastIndex = pb.GetLastIndex()
req.LastTerm = pb.GetLastTerm()
return totalBytes, nil
} | go | func (req *SnapshotRequest) Decode(r io.Reader) (int, error) {
data, err := ioutil.ReadAll(r)
if err != nil {
return 0, err
}
totalBytes := len(data)
pb := &protobuf.SnapshotRequest{}
if err := proto.Unmarshal(data, pb); err != nil {
return -1, err
}
req.LeaderName = pb.GetLeaderName()
req.LastIndex = pb.GetLastIndex()
req.LastTerm = pb.GetLastTerm()
return totalBytes, nil
} | [
"func",
"(",
"req",
"*",
"SnapshotRequest",
")",
"Decode",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"int",
",",
"error",
")",
"{",
"data",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"totalBytes",
":=",
"len",
"(",
"data",
")",
"\n\n",
"pb",
":=",
"&",
"protobuf",
".",
"SnapshotRequest",
"{",
"}",
"\n\n",
"if",
"err",
":=",
"proto",
".",
"Unmarshal",
"(",
"data",
",",
"pb",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"err",
"\n",
"}",
"\n\n",
"req",
".",
"LeaderName",
"=",
"pb",
".",
"GetLeaderName",
"(",
")",
"\n",
"req",
".",
"LastIndex",
"=",
"pb",
".",
"GetLastIndex",
"(",
")",
"\n",
"req",
".",
"LastTerm",
"=",
"pb",
".",
"GetLastTerm",
"(",
")",
"\n\n",
"return",
"totalBytes",
",",
"nil",
"\n",
"}"
] | // Decodes the SnapshotRequest from a buffer. Returns the number of bytes read and
// any error that occurs. | [
"Decodes",
"the",
"SnapshotRequest",
"from",
"a",
"buffer",
".",
"Returns",
"the",
"number",
"of",
"bytes",
"read",
"and",
"any",
"error",
"that",
"occurs",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/snapshot.go#L242-L262 |
147,907 | goraft/raft | snapshot.go | Encode | func (resp *SnapshotResponse) Encode(w io.Writer) (int, error) {
pb := &protobuf.SnapshotResponse{
Success: proto.Bool(resp.Success),
}
p, err := proto.Marshal(pb)
if err != nil {
return -1, err
}
return w.Write(p)
} | go | func (resp *SnapshotResponse) Encode(w io.Writer) (int, error) {
pb := &protobuf.SnapshotResponse{
Success: proto.Bool(resp.Success),
}
p, err := proto.Marshal(pb)
if err != nil {
return -1, err
}
return w.Write(p)
} | [
"func",
"(",
"resp",
"*",
"SnapshotResponse",
")",
"Encode",
"(",
"w",
"io",
".",
"Writer",
")",
"(",
"int",
",",
"error",
")",
"{",
"pb",
":=",
"&",
"protobuf",
".",
"SnapshotResponse",
"{",
"Success",
":",
"proto",
".",
"Bool",
"(",
"resp",
".",
"Success",
")",
",",
"}",
"\n",
"p",
",",
"err",
":=",
"proto",
".",
"Marshal",
"(",
"pb",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"w",
".",
"Write",
"(",
"p",
")",
"\n",
"}"
] | // Encodes the SnapshotResponse to a buffer. Returns the number of bytes
// written and any error that may have occurred. | [
"Encodes",
"the",
"SnapshotResponse",
"to",
"a",
"buffer",
".",
"Returns",
"the",
"number",
"of",
"bytes",
"written",
"and",
"any",
"error",
"that",
"may",
"have",
"occurred",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/snapshot.go#L273-L283 |
147,908 | goraft/raft | snapshot.go | Decode | func (resp *SnapshotResponse) Decode(r io.Reader) (int, error) {
data, err := ioutil.ReadAll(r)
if err != nil {
return 0, err
}
totalBytes := len(data)
pb := &protobuf.SnapshotResponse{}
if err := proto.Unmarshal(data, pb); err != nil {
return -1, err
}
resp.Success = pb.GetSuccess()
return totalBytes, nil
} | go | func (resp *SnapshotResponse) Decode(r io.Reader) (int, error) {
data, err := ioutil.ReadAll(r)
if err != nil {
return 0, err
}
totalBytes := len(data)
pb := &protobuf.SnapshotResponse{}
if err := proto.Unmarshal(data, pb); err != nil {
return -1, err
}
resp.Success = pb.GetSuccess()
return totalBytes, nil
} | [
"func",
"(",
"resp",
"*",
"SnapshotResponse",
")",
"Decode",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"int",
",",
"error",
")",
"{",
"data",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"totalBytes",
":=",
"len",
"(",
"data",
")",
"\n\n",
"pb",
":=",
"&",
"protobuf",
".",
"SnapshotResponse",
"{",
"}",
"\n",
"if",
"err",
":=",
"proto",
".",
"Unmarshal",
"(",
"data",
",",
"pb",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"err",
"\n",
"}",
"\n\n",
"resp",
".",
"Success",
"=",
"pb",
".",
"GetSuccess",
"(",
")",
"\n\n",
"return",
"totalBytes",
",",
"nil",
"\n",
"}"
] | // Decodes the SnapshotResponse from a buffer. Returns the number of bytes read and
// any error that occurs. | [
"Decodes",
"the",
"SnapshotResponse",
"from",
"a",
"buffer",
".",
"Returns",
"the",
"number",
"of",
"bytes",
"read",
"and",
"any",
"error",
"that",
"occurs",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/snapshot.go#L287-L304 |
147,909 | goraft/raft | log_entry.go | newLogEntry | func newLogEntry(log *Log, event *ev, index uint64, term uint64, command Command) (*LogEntry, error) {
var buf bytes.Buffer
var commandName string
if command != nil {
commandName = command.CommandName()
if encoder, ok := command.(CommandEncoder); ok {
if err := encoder.Encode(&buf); err != nil {
return nil, err
}
} else {
if err := json.NewEncoder(&buf).Encode(command); err != nil {
return nil, err
}
}
}
pb := &protobuf.LogEntry{
Index: proto.Uint64(index),
Term: proto.Uint64(term),
CommandName: proto.String(commandName),
Command: buf.Bytes(),
}
e := &LogEntry{
pb: pb,
log: log,
event: event,
}
return e, nil
} | go | func newLogEntry(log *Log, event *ev, index uint64, term uint64, command Command) (*LogEntry, error) {
var buf bytes.Buffer
var commandName string
if command != nil {
commandName = command.CommandName()
if encoder, ok := command.(CommandEncoder); ok {
if err := encoder.Encode(&buf); err != nil {
return nil, err
}
} else {
if err := json.NewEncoder(&buf).Encode(command); err != nil {
return nil, err
}
}
}
pb := &protobuf.LogEntry{
Index: proto.Uint64(index),
Term: proto.Uint64(term),
CommandName: proto.String(commandName),
Command: buf.Bytes(),
}
e := &LogEntry{
pb: pb,
log: log,
event: event,
}
return e, nil
} | [
"func",
"newLogEntry",
"(",
"log",
"*",
"Log",
",",
"event",
"*",
"ev",
",",
"index",
"uint64",
",",
"term",
"uint64",
",",
"command",
"Command",
")",
"(",
"*",
"LogEntry",
",",
"error",
")",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"var",
"commandName",
"string",
"\n",
"if",
"command",
"!=",
"nil",
"{",
"commandName",
"=",
"command",
".",
"CommandName",
"(",
")",
"\n",
"if",
"encoder",
",",
"ok",
":=",
"command",
".",
"(",
"CommandEncoder",
")",
";",
"ok",
"{",
"if",
"err",
":=",
"encoder",
".",
"Encode",
"(",
"&",
"buf",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"else",
"{",
"if",
"err",
":=",
"json",
".",
"NewEncoder",
"(",
"&",
"buf",
")",
".",
"Encode",
"(",
"command",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"pb",
":=",
"&",
"protobuf",
".",
"LogEntry",
"{",
"Index",
":",
"proto",
".",
"Uint64",
"(",
"index",
")",
",",
"Term",
":",
"proto",
".",
"Uint64",
"(",
"term",
")",
",",
"CommandName",
":",
"proto",
".",
"String",
"(",
"commandName",
")",
",",
"Command",
":",
"buf",
".",
"Bytes",
"(",
")",
",",
"}",
"\n\n",
"e",
":=",
"&",
"LogEntry",
"{",
"pb",
":",
"pb",
",",
"log",
":",
"log",
",",
"event",
":",
"event",
",",
"}",
"\n\n",
"return",
"e",
",",
"nil",
"\n",
"}"
] | // Creates a new log entry associated with a log. | [
"Creates",
"a",
"new",
"log",
"entry",
"associated",
"with",
"a",
"log",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/log_entry.go#L22-L52 |
147,910 | goraft/raft | log_entry.go | Encode | func (e *LogEntry) Encode(w io.Writer) (int, error) {
b, err := proto.Marshal(e.pb)
if err != nil {
return -1, err
}
if _, err = fmt.Fprintf(w, "%8x\n", len(b)); err != nil {
return -1, err
}
return w.Write(b)
} | go | func (e *LogEntry) Encode(w io.Writer) (int, error) {
b, err := proto.Marshal(e.pb)
if err != nil {
return -1, err
}
if _, err = fmt.Fprintf(w, "%8x\n", len(b)); err != nil {
return -1, err
}
return w.Write(b)
} | [
"func",
"(",
"e",
"*",
"LogEntry",
")",
"Encode",
"(",
"w",
"io",
".",
"Writer",
")",
"(",
"int",
",",
"error",
")",
"{",
"b",
",",
"err",
":=",
"proto",
".",
"Marshal",
"(",
"e",
".",
"pb",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"err",
"=",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\n",
"\"",
",",
"len",
"(",
"b",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"w",
".",
"Write",
"(",
"b",
")",
"\n",
"}"
] | // Encodes the log entry to a buffer. Returns the number of bytes
// written and any error that may have occurred. | [
"Encodes",
"the",
"log",
"entry",
"to",
"a",
"buffer",
".",
"Returns",
"the",
"number",
"of",
"bytes",
"written",
"and",
"any",
"error",
"that",
"may",
"have",
"occurred",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/log_entry.go#L72-L83 |
147,911 | goraft/raft | log_entry.go | Decode | func (e *LogEntry) Decode(r io.Reader) (int, error) {
var length int
_, err := fmt.Fscanf(r, "%8x\n", &length)
if err != nil {
return -1, err
}
data := make([]byte, length)
_, err = io.ReadFull(r, data)
if err != nil {
return -1, err
}
if err = proto.Unmarshal(data, e.pb); err != nil {
return -1, err
}
return length + 8 + 1, nil
} | go | func (e *LogEntry) Decode(r io.Reader) (int, error) {
var length int
_, err := fmt.Fscanf(r, "%8x\n", &length)
if err != nil {
return -1, err
}
data := make([]byte, length)
_, err = io.ReadFull(r, data)
if err != nil {
return -1, err
}
if err = proto.Unmarshal(data, e.pb); err != nil {
return -1, err
}
return length + 8 + 1, nil
} | [
"func",
"(",
"e",
"*",
"LogEntry",
")",
"Decode",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"int",
",",
"error",
")",
"{",
"var",
"length",
"int",
"\n",
"_",
",",
"err",
":=",
"fmt",
".",
"Fscanf",
"(",
"r",
",",
"\"",
"\\n",
"\"",
",",
"&",
"length",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"err",
"\n",
"}",
"\n\n",
"data",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"length",
")",
"\n",
"_",
",",
"err",
"=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"data",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
"=",
"proto",
".",
"Unmarshal",
"(",
"data",
",",
"e",
".",
"pb",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"length",
"+",
"8",
"+",
"1",
",",
"nil",
"\n",
"}"
] | // Decodes the log entry from a buffer. Returns the number of bytes read and
// any error that occurs. | [
"Decodes",
"the",
"log",
"entry",
"from",
"a",
"buffer",
".",
"Returns",
"the",
"number",
"of",
"bytes",
"read",
"and",
"any",
"error",
"that",
"occurs",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/log_entry.go#L87-L107 |
147,912 | goraft/raft | util.go | afterBetween | func afterBetween(min time.Duration, max time.Duration) <-chan time.Time {
rand := rand.New(rand.NewSource(time.Now().UnixNano()))
d, delta := min, (max - min)
if delta > 0 {
d += time.Duration(rand.Int63n(int64(delta)))
}
return time.After(d)
} | go | func afterBetween(min time.Duration, max time.Duration) <-chan time.Time {
rand := rand.New(rand.NewSource(time.Now().UnixNano()))
d, delta := min, (max - min)
if delta > 0 {
d += time.Duration(rand.Int63n(int64(delta)))
}
return time.After(d)
} | [
"func",
"afterBetween",
"(",
"min",
"time",
".",
"Duration",
",",
"max",
"time",
".",
"Duration",
")",
"<-",
"chan",
"time",
".",
"Time",
"{",
"rand",
":=",
"rand",
".",
"New",
"(",
"rand",
".",
"NewSource",
"(",
"time",
".",
"Now",
"(",
")",
".",
"UnixNano",
"(",
")",
")",
")",
"\n",
"d",
",",
"delta",
":=",
"min",
",",
"(",
"max",
"-",
"min",
")",
"\n",
"if",
"delta",
">",
"0",
"{",
"d",
"+=",
"time",
".",
"Duration",
"(",
"rand",
".",
"Int63n",
"(",
"int64",
"(",
"delta",
")",
")",
")",
"\n",
"}",
"\n",
"return",
"time",
".",
"After",
"(",
"d",
")",
"\n",
"}"
] | // Waits for a random time between two durations and sends the current time on
// the returned channel. | [
"Waits",
"for",
"a",
"random",
"time",
"between",
"two",
"durations",
"and",
"sends",
"the",
"current",
"time",
"on",
"the",
"returned",
"channel",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/util.go#L46-L53 |
147,913 | goraft/raft | command.go | newCommand | func newCommand(name string, data []byte) (Command, error) {
// Find the registered command.
command := commandTypes[name]
if command == nil {
return nil, fmt.Errorf("raft.Command: Unregistered command type: %s", name)
}
// Make a copy of the command.
v := reflect.New(reflect.Indirect(reflect.ValueOf(command)).Type()).Interface()
copy, ok := v.(Command)
if !ok {
panic(fmt.Sprintf("raft: Unable to copy command: %s (%v)", command.CommandName(), reflect.ValueOf(v).Kind().String()))
}
// If data for the command was passed in the decode it.
if data != nil {
if encoder, ok := copy.(CommandEncoder); ok {
if err := encoder.Decode(bytes.NewReader(data)); err != nil {
return nil, err
}
} else {
if err := json.NewDecoder(bytes.NewReader(data)).Decode(copy); err != nil {
return nil, err
}
}
}
return copy, nil
} | go | func newCommand(name string, data []byte) (Command, error) {
// Find the registered command.
command := commandTypes[name]
if command == nil {
return nil, fmt.Errorf("raft.Command: Unregistered command type: %s", name)
}
// Make a copy of the command.
v := reflect.New(reflect.Indirect(reflect.ValueOf(command)).Type()).Interface()
copy, ok := v.(Command)
if !ok {
panic(fmt.Sprintf("raft: Unable to copy command: %s (%v)", command.CommandName(), reflect.ValueOf(v).Kind().String()))
}
// If data for the command was passed in the decode it.
if data != nil {
if encoder, ok := copy.(CommandEncoder); ok {
if err := encoder.Decode(bytes.NewReader(data)); err != nil {
return nil, err
}
} else {
if err := json.NewDecoder(bytes.NewReader(data)).Decode(copy); err != nil {
return nil, err
}
}
}
return copy, nil
} | [
"func",
"newCommand",
"(",
"name",
"string",
",",
"data",
"[",
"]",
"byte",
")",
"(",
"Command",
",",
"error",
")",
"{",
"// Find the registered command.",
"command",
":=",
"commandTypes",
"[",
"name",
"]",
"\n",
"if",
"command",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n\n",
"// Make a copy of the command.",
"v",
":=",
"reflect",
".",
"New",
"(",
"reflect",
".",
"Indirect",
"(",
"reflect",
".",
"ValueOf",
"(",
"command",
")",
")",
".",
"Type",
"(",
")",
")",
".",
"Interface",
"(",
")",
"\n",
"copy",
",",
"ok",
":=",
"v",
".",
"(",
"Command",
")",
"\n",
"if",
"!",
"ok",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"command",
".",
"CommandName",
"(",
")",
",",
"reflect",
".",
"ValueOf",
"(",
"v",
")",
".",
"Kind",
"(",
")",
".",
"String",
"(",
")",
")",
")",
"\n",
"}",
"\n\n",
"// If data for the command was passed in the decode it.",
"if",
"data",
"!=",
"nil",
"{",
"if",
"encoder",
",",
"ok",
":=",
"copy",
".",
"(",
"CommandEncoder",
")",
";",
"ok",
"{",
"if",
"err",
":=",
"encoder",
".",
"Decode",
"(",
"bytes",
".",
"NewReader",
"(",
"data",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"else",
"{",
"if",
"err",
":=",
"json",
".",
"NewDecoder",
"(",
"bytes",
".",
"NewReader",
"(",
"data",
")",
")",
".",
"Decode",
"(",
"copy",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"copy",
",",
"nil",
"\n",
"}"
] | // Creates a new instance of a command by name. | [
"Creates",
"a",
"new",
"instance",
"of",
"a",
"command",
"by",
"name",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/command.go#L38-L66 |
147,914 | goraft/raft | command.go | RegisterCommand | func RegisterCommand(command Command) {
if command == nil {
panic(fmt.Sprintf("raft: Cannot register nil"))
} else if commandTypes[command.CommandName()] != nil {
panic(fmt.Sprintf("raft: Duplicate registration: %s", command.CommandName()))
}
commandTypes[command.CommandName()] = command
} | go | func RegisterCommand(command Command) {
if command == nil {
panic(fmt.Sprintf("raft: Cannot register nil"))
} else if commandTypes[command.CommandName()] != nil {
panic(fmt.Sprintf("raft: Duplicate registration: %s", command.CommandName()))
}
commandTypes[command.CommandName()] = command
} | [
"func",
"RegisterCommand",
"(",
"command",
"Command",
")",
"{",
"if",
"command",
"==",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
")",
")",
"\n",
"}",
"else",
"if",
"commandTypes",
"[",
"command",
".",
"CommandName",
"(",
")",
"]",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"command",
".",
"CommandName",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"commandTypes",
"[",
"command",
".",
"CommandName",
"(",
")",
"]",
"=",
"command",
"\n",
"}"
] | // Registers a command by storing a reference to an instance of it. | [
"Registers",
"a",
"command",
"by",
"storing",
"a",
"reference",
"to",
"an",
"instance",
"of",
"it",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/command.go#L69-L76 |
147,915 | goraft/raft | http_transporter.go | SendVoteRequest | func (t *HTTPTransporter) SendVoteRequest(server Server, peer *Peer, req *RequestVoteRequest) *RequestVoteResponse {
var b bytes.Buffer
if _, err := req.Encode(&b); err != nil {
traceln("transporter.rv.encoding.error:", err)
return nil
}
url := fmt.Sprintf("%s%s", peer.ConnectionString, t.RequestVotePath())
traceln(server.Name(), "POST", url)
httpResp, err := t.httpClient.Post(url, "application/protobuf", &b)
if httpResp == nil || err != nil {
traceln("transporter.rv.response.error:", err)
return nil
}
defer httpResp.Body.Close()
resp := &RequestVoteResponse{}
if _, err = resp.Decode(httpResp.Body); err != nil && err != io.EOF {
traceln("transporter.rv.decoding.error:", err)
return nil
}
return resp
} | go | func (t *HTTPTransporter) SendVoteRequest(server Server, peer *Peer, req *RequestVoteRequest) *RequestVoteResponse {
var b bytes.Buffer
if _, err := req.Encode(&b); err != nil {
traceln("transporter.rv.encoding.error:", err)
return nil
}
url := fmt.Sprintf("%s%s", peer.ConnectionString, t.RequestVotePath())
traceln(server.Name(), "POST", url)
httpResp, err := t.httpClient.Post(url, "application/protobuf", &b)
if httpResp == nil || err != nil {
traceln("transporter.rv.response.error:", err)
return nil
}
defer httpResp.Body.Close()
resp := &RequestVoteResponse{}
if _, err = resp.Decode(httpResp.Body); err != nil && err != io.EOF {
traceln("transporter.rv.decoding.error:", err)
return nil
}
return resp
} | [
"func",
"(",
"t",
"*",
"HTTPTransporter",
")",
"SendVoteRequest",
"(",
"server",
"Server",
",",
"peer",
"*",
"Peer",
",",
"req",
"*",
"RequestVoteRequest",
")",
"*",
"RequestVoteResponse",
"{",
"var",
"b",
"bytes",
".",
"Buffer",
"\n",
"if",
"_",
",",
"err",
":=",
"req",
".",
"Encode",
"(",
"&",
"b",
")",
";",
"err",
"!=",
"nil",
"{",
"traceln",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"url",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"peer",
".",
"ConnectionString",
",",
"t",
".",
"RequestVotePath",
"(",
")",
")",
"\n",
"traceln",
"(",
"server",
".",
"Name",
"(",
")",
",",
"\"",
"\"",
",",
"url",
")",
"\n\n",
"httpResp",
",",
"err",
":=",
"t",
".",
"httpClient",
".",
"Post",
"(",
"url",
",",
"\"",
"\"",
",",
"&",
"b",
")",
"\n",
"if",
"httpResp",
"==",
"nil",
"||",
"err",
"!=",
"nil",
"{",
"traceln",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"defer",
"httpResp",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"resp",
":=",
"&",
"RequestVoteResponse",
"{",
"}",
"\n",
"if",
"_",
",",
"err",
"=",
"resp",
".",
"Decode",
"(",
"httpResp",
".",
"Body",
")",
";",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"io",
".",
"EOF",
"{",
"traceln",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"resp",
"\n",
"}"
] | // Sends a RequestVote RPC to a peer. | [
"Sends",
"a",
"RequestVote",
"RPC",
"to",
"a",
"peer",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/http_transporter.go#L142-L166 |
147,916 | goraft/raft | append_entries.go | newAppendEntriesRequest | func newAppendEntriesRequest(term uint64, prevLogIndex uint64, prevLogTerm uint64,
commitIndex uint64, leaderName string, entries []*LogEntry) *AppendEntriesRequest {
pbEntries := make([]*protobuf.LogEntry, len(entries))
for i := range entries {
pbEntries[i] = entries[i].pb
}
return &AppendEntriesRequest{
Term: term,
PrevLogIndex: prevLogIndex,
PrevLogTerm: prevLogTerm,
CommitIndex: commitIndex,
LeaderName: leaderName,
Entries: pbEntries,
}
} | go | func newAppendEntriesRequest(term uint64, prevLogIndex uint64, prevLogTerm uint64,
commitIndex uint64, leaderName string, entries []*LogEntry) *AppendEntriesRequest {
pbEntries := make([]*protobuf.LogEntry, len(entries))
for i := range entries {
pbEntries[i] = entries[i].pb
}
return &AppendEntriesRequest{
Term: term,
PrevLogIndex: prevLogIndex,
PrevLogTerm: prevLogTerm,
CommitIndex: commitIndex,
LeaderName: leaderName,
Entries: pbEntries,
}
} | [
"func",
"newAppendEntriesRequest",
"(",
"term",
"uint64",
",",
"prevLogIndex",
"uint64",
",",
"prevLogTerm",
"uint64",
",",
"commitIndex",
"uint64",
",",
"leaderName",
"string",
",",
"entries",
"[",
"]",
"*",
"LogEntry",
")",
"*",
"AppendEntriesRequest",
"{",
"pbEntries",
":=",
"make",
"(",
"[",
"]",
"*",
"protobuf",
".",
"LogEntry",
",",
"len",
"(",
"entries",
")",
")",
"\n\n",
"for",
"i",
":=",
"range",
"entries",
"{",
"pbEntries",
"[",
"i",
"]",
"=",
"entries",
"[",
"i",
"]",
".",
"pb",
"\n",
"}",
"\n\n",
"return",
"&",
"AppendEntriesRequest",
"{",
"Term",
":",
"term",
",",
"PrevLogIndex",
":",
"prevLogIndex",
",",
"PrevLogTerm",
":",
"prevLogTerm",
",",
"CommitIndex",
":",
"commitIndex",
",",
"LeaderName",
":",
"leaderName",
",",
"Entries",
":",
"pbEntries",
",",
"}",
"\n",
"}"
] | // Creates a new AppendEntries request. | [
"Creates",
"a",
"new",
"AppendEntries",
"request",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/append_entries.go#L29-L45 |
147,917 | goraft/raft | append_entries.go | Encode | func (req *AppendEntriesRequest) Encode(w io.Writer) (int, error) {
pb := &protobuf.AppendEntriesRequest{
Term: proto.Uint64(req.Term),
PrevLogIndex: proto.Uint64(req.PrevLogIndex),
PrevLogTerm: proto.Uint64(req.PrevLogTerm),
CommitIndex: proto.Uint64(req.CommitIndex),
LeaderName: proto.String(req.LeaderName),
Entries: req.Entries,
}
p, err := proto.Marshal(pb)
if err != nil {
return -1, err
}
return w.Write(p)
} | go | func (req *AppendEntriesRequest) Encode(w io.Writer) (int, error) {
pb := &protobuf.AppendEntriesRequest{
Term: proto.Uint64(req.Term),
PrevLogIndex: proto.Uint64(req.PrevLogIndex),
PrevLogTerm: proto.Uint64(req.PrevLogTerm),
CommitIndex: proto.Uint64(req.CommitIndex),
LeaderName: proto.String(req.LeaderName),
Entries: req.Entries,
}
p, err := proto.Marshal(pb)
if err != nil {
return -1, err
}
return w.Write(p)
} | [
"func",
"(",
"req",
"*",
"AppendEntriesRequest",
")",
"Encode",
"(",
"w",
"io",
".",
"Writer",
")",
"(",
"int",
",",
"error",
")",
"{",
"pb",
":=",
"&",
"protobuf",
".",
"AppendEntriesRequest",
"{",
"Term",
":",
"proto",
".",
"Uint64",
"(",
"req",
".",
"Term",
")",
",",
"PrevLogIndex",
":",
"proto",
".",
"Uint64",
"(",
"req",
".",
"PrevLogIndex",
")",
",",
"PrevLogTerm",
":",
"proto",
".",
"Uint64",
"(",
"req",
".",
"PrevLogTerm",
")",
",",
"CommitIndex",
":",
"proto",
".",
"Uint64",
"(",
"req",
".",
"CommitIndex",
")",
",",
"LeaderName",
":",
"proto",
".",
"String",
"(",
"req",
".",
"LeaderName",
")",
",",
"Entries",
":",
"req",
".",
"Entries",
",",
"}",
"\n\n",
"p",
",",
"err",
":=",
"proto",
".",
"Marshal",
"(",
"pb",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"w",
".",
"Write",
"(",
"p",
")",
"\n",
"}"
] | // Encodes the AppendEntriesRequest to a buffer. Returns the number of bytes
// written and any error that may have occurred. | [
"Encodes",
"the",
"AppendEntriesRequest",
"to",
"a",
"buffer",
".",
"Returns",
"the",
"number",
"of",
"bytes",
"written",
"and",
"any",
"error",
"that",
"may",
"have",
"occurred",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/append_entries.go#L49-L65 |
147,918 | goraft/raft | append_entries.go | Decode | func (req *AppendEntriesRequest) Decode(r io.Reader) (int, error) {
data, err := ioutil.ReadAll(r)
if err != nil {
return -1, err
}
pb := new(protobuf.AppendEntriesRequest)
if err := proto.Unmarshal(data, pb); err != nil {
return -1, err
}
req.Term = pb.GetTerm()
req.PrevLogIndex = pb.GetPrevLogIndex()
req.PrevLogTerm = pb.GetPrevLogTerm()
req.CommitIndex = pb.GetCommitIndex()
req.LeaderName = pb.GetLeaderName()
req.Entries = pb.GetEntries()
return len(data), nil
} | go | func (req *AppendEntriesRequest) Decode(r io.Reader) (int, error) {
data, err := ioutil.ReadAll(r)
if err != nil {
return -1, err
}
pb := new(protobuf.AppendEntriesRequest)
if err := proto.Unmarshal(data, pb); err != nil {
return -1, err
}
req.Term = pb.GetTerm()
req.PrevLogIndex = pb.GetPrevLogIndex()
req.PrevLogTerm = pb.GetPrevLogTerm()
req.CommitIndex = pb.GetCommitIndex()
req.LeaderName = pb.GetLeaderName()
req.Entries = pb.GetEntries()
return len(data), nil
} | [
"func",
"(",
"req",
"*",
"AppendEntriesRequest",
")",
"Decode",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"int",
",",
"error",
")",
"{",
"data",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"err",
"\n",
"}",
"\n\n",
"pb",
":=",
"new",
"(",
"protobuf",
".",
"AppendEntriesRequest",
")",
"\n",
"if",
"err",
":=",
"proto",
".",
"Unmarshal",
"(",
"data",
",",
"pb",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"err",
"\n",
"}",
"\n\n",
"req",
".",
"Term",
"=",
"pb",
".",
"GetTerm",
"(",
")",
"\n",
"req",
".",
"PrevLogIndex",
"=",
"pb",
".",
"GetPrevLogIndex",
"(",
")",
"\n",
"req",
".",
"PrevLogTerm",
"=",
"pb",
".",
"GetPrevLogTerm",
"(",
")",
"\n",
"req",
".",
"CommitIndex",
"=",
"pb",
".",
"GetCommitIndex",
"(",
")",
"\n",
"req",
".",
"LeaderName",
"=",
"pb",
".",
"GetLeaderName",
"(",
")",
"\n",
"req",
".",
"Entries",
"=",
"pb",
".",
"GetEntries",
"(",
")",
"\n\n",
"return",
"len",
"(",
"data",
")",
",",
"nil",
"\n",
"}"
] | // Decodes the AppendEntriesRequest from a buffer. Returns the number of bytes read and
// any error that occurs. | [
"Decodes",
"the",
"AppendEntriesRequest",
"from",
"a",
"buffer",
".",
"Returns",
"the",
"number",
"of",
"bytes",
"read",
"and",
"any",
"error",
"that",
"occurs",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/append_entries.go#L69-L89 |
147,919 | goraft/raft | append_entries.go | newAppendEntriesResponse | func newAppendEntriesResponse(term uint64, success bool, index uint64, commitIndex uint64) *AppendEntriesResponse {
pb := &protobuf.AppendEntriesResponse{
Term: proto.Uint64(term),
Index: proto.Uint64(index),
Success: proto.Bool(success),
CommitIndex: proto.Uint64(commitIndex),
}
return &AppendEntriesResponse{
pb: pb,
}
} | go | func newAppendEntriesResponse(term uint64, success bool, index uint64, commitIndex uint64) *AppendEntriesResponse {
pb := &protobuf.AppendEntriesResponse{
Term: proto.Uint64(term),
Index: proto.Uint64(index),
Success: proto.Bool(success),
CommitIndex: proto.Uint64(commitIndex),
}
return &AppendEntriesResponse{
pb: pb,
}
} | [
"func",
"newAppendEntriesResponse",
"(",
"term",
"uint64",
",",
"success",
"bool",
",",
"index",
"uint64",
",",
"commitIndex",
"uint64",
")",
"*",
"AppendEntriesResponse",
"{",
"pb",
":=",
"&",
"protobuf",
".",
"AppendEntriesResponse",
"{",
"Term",
":",
"proto",
".",
"Uint64",
"(",
"term",
")",
",",
"Index",
":",
"proto",
".",
"Uint64",
"(",
"index",
")",
",",
"Success",
":",
"proto",
".",
"Bool",
"(",
"success",
")",
",",
"CommitIndex",
":",
"proto",
".",
"Uint64",
"(",
"commitIndex",
")",
",",
"}",
"\n\n",
"return",
"&",
"AppendEntriesResponse",
"{",
"pb",
":",
"pb",
",",
"}",
"\n",
"}"
] | // Creates a new AppendEntries response. | [
"Creates",
"a",
"new",
"AppendEntries",
"response",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/append_entries.go#L92-L103 |
147,920 | goraft/raft | append_entries.go | Encode | func (resp *AppendEntriesResponse) Encode(w io.Writer) (int, error) {
b, err := proto.Marshal(resp.pb)
if err != nil {
return -1, err
}
return w.Write(b)
} | go | func (resp *AppendEntriesResponse) Encode(w io.Writer) (int, error) {
b, err := proto.Marshal(resp.pb)
if err != nil {
return -1, err
}
return w.Write(b)
} | [
"func",
"(",
"resp",
"*",
"AppendEntriesResponse",
")",
"Encode",
"(",
"w",
"io",
".",
"Writer",
")",
"(",
"int",
",",
"error",
")",
"{",
"b",
",",
"err",
":=",
"proto",
".",
"Marshal",
"(",
"resp",
".",
"pb",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"w",
".",
"Write",
"(",
"b",
")",
"\n",
"}"
] | // Encodes the AppendEntriesResponse to a buffer. Returns the number of bytes
// written and any error that may have occurred. | [
"Encodes",
"the",
"AppendEntriesResponse",
"to",
"a",
"buffer",
".",
"Returns",
"the",
"number",
"of",
"bytes",
"written",
"and",
"any",
"error",
"that",
"may",
"have",
"occurred",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/append_entries.go#L123-L130 |
147,921 | goraft/raft | append_entries.go | Decode | func (resp *AppendEntriesResponse) Decode(r io.Reader) (int, error) {
data, err := ioutil.ReadAll(r)
if err != nil {
return -1, err
}
resp.pb = new(protobuf.AppendEntriesResponse)
if err := proto.Unmarshal(data, resp.pb); err != nil {
return -1, err
}
return len(data), nil
} | go | func (resp *AppendEntriesResponse) Decode(r io.Reader) (int, error) {
data, err := ioutil.ReadAll(r)
if err != nil {
return -1, err
}
resp.pb = new(protobuf.AppendEntriesResponse)
if err := proto.Unmarshal(data, resp.pb); err != nil {
return -1, err
}
return len(data), nil
} | [
"func",
"(",
"resp",
"*",
"AppendEntriesResponse",
")",
"Decode",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"int",
",",
"error",
")",
"{",
"data",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"err",
"\n",
"}",
"\n\n",
"resp",
".",
"pb",
"=",
"new",
"(",
"protobuf",
".",
"AppendEntriesResponse",
")",
"\n",
"if",
"err",
":=",
"proto",
".",
"Unmarshal",
"(",
"data",
",",
"resp",
".",
"pb",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"-",
"1",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"len",
"(",
"data",
")",
",",
"nil",
"\n",
"}"
] | // Decodes the AppendEntriesResponse from a buffer. Returns the number of bytes read and
// any error that occurs. | [
"Decodes",
"the",
"AppendEntriesResponse",
"from",
"a",
"buffer",
".",
"Returns",
"the",
"number",
"of",
"bytes",
"read",
"and",
"any",
"error",
"that",
"occurs",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/append_entries.go#L134-L146 |
147,922 | goraft/raft | server.go | Peers | func (s *server) Peers() map[string]*Peer {
s.mutex.Lock()
defer s.mutex.Unlock()
peers := make(map[string]*Peer)
for name, peer := range s.peers {
peers[name] = peer.clone()
}
return peers
} | go | func (s *server) Peers() map[string]*Peer {
s.mutex.Lock()
defer s.mutex.Unlock()
peers := make(map[string]*Peer)
for name, peer := range s.peers {
peers[name] = peer.clone()
}
return peers
} | [
"func",
"(",
"s",
"*",
"server",
")",
"Peers",
"(",
")",
"map",
"[",
"string",
"]",
"*",
"Peer",
"{",
"s",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n\n",
"peers",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"Peer",
")",
"\n",
"for",
"name",
",",
"peer",
":=",
"range",
"s",
".",
"peers",
"{",
"peers",
"[",
"name",
"]",
"=",
"peer",
".",
"clone",
"(",
")",
"\n",
"}",
"\n",
"return",
"peers",
"\n",
"}"
] | // Retrieves a copy of the peer data. | [
"Retrieves",
"a",
"copy",
"of",
"the",
"peer",
"data",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L241-L250 |
147,923 | goraft/raft | server.go | Transporter | func (s *server) Transporter() Transporter {
s.mutex.RLock()
defer s.mutex.RUnlock()
return s.transporter
} | go | func (s *server) Transporter() Transporter {
s.mutex.RLock()
defer s.mutex.RUnlock()
return s.transporter
} | [
"func",
"(",
"s",
"*",
"server",
")",
"Transporter",
"(",
")",
"Transporter",
"{",
"s",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"s",
".",
"transporter",
"\n",
"}"
] | // Retrieves the object that transports requests. | [
"Retrieves",
"the",
"object",
"that",
"transports",
"requests",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L253-L257 |
147,924 | goraft/raft | server.go | State | func (s *server) State() string {
s.mutex.RLock()
defer s.mutex.RUnlock()
return s.state
} | go | func (s *server) State() string {
s.mutex.RLock()
defer s.mutex.RUnlock()
return s.state
} | [
"func",
"(",
"s",
"*",
"server",
")",
"State",
"(",
")",
"string",
"{",
"s",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"s",
".",
"state",
"\n",
"}"
] | // Retrieves the current state of the server. | [
"Retrieves",
"the",
"current",
"state",
"of",
"the",
"server",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L281-L285 |
147,925 | goraft/raft | server.go | setState | func (s *server) setState(state string) {
s.mutex.Lock()
defer s.mutex.Unlock()
// Temporarily store previous values.
prevState := s.state
prevLeader := s.leader
// Update state and leader.
s.state = state
if state == Leader {
s.leader = s.Name()
s.syncedPeer = make(map[string]bool)
}
// Dispatch state and leader change events.
s.DispatchEvent(newEvent(StateChangeEventType, s.state, prevState))
if prevLeader != s.leader {
s.DispatchEvent(newEvent(LeaderChangeEventType, s.leader, prevLeader))
}
} | go | func (s *server) setState(state string) {
s.mutex.Lock()
defer s.mutex.Unlock()
// Temporarily store previous values.
prevState := s.state
prevLeader := s.leader
// Update state and leader.
s.state = state
if state == Leader {
s.leader = s.Name()
s.syncedPeer = make(map[string]bool)
}
// Dispatch state and leader change events.
s.DispatchEvent(newEvent(StateChangeEventType, s.state, prevState))
if prevLeader != s.leader {
s.DispatchEvent(newEvent(LeaderChangeEventType, s.leader, prevLeader))
}
} | [
"func",
"(",
"s",
"*",
"server",
")",
"setState",
"(",
"state",
"string",
")",
"{",
"s",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n\n",
"// Temporarily store previous values.",
"prevState",
":=",
"s",
".",
"state",
"\n",
"prevLeader",
":=",
"s",
".",
"leader",
"\n\n",
"// Update state and leader.",
"s",
".",
"state",
"=",
"state",
"\n",
"if",
"state",
"==",
"Leader",
"{",
"s",
".",
"leader",
"=",
"s",
".",
"Name",
"(",
")",
"\n",
"s",
".",
"syncedPeer",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"bool",
")",
"\n",
"}",
"\n\n",
"// Dispatch state and leader change events.",
"s",
".",
"DispatchEvent",
"(",
"newEvent",
"(",
"StateChangeEventType",
",",
"s",
".",
"state",
",",
"prevState",
")",
")",
"\n\n",
"if",
"prevLeader",
"!=",
"s",
".",
"leader",
"{",
"s",
".",
"DispatchEvent",
"(",
"newEvent",
"(",
"LeaderChangeEventType",
",",
"s",
".",
"leader",
",",
"prevLeader",
")",
")",
"\n",
"}",
"\n",
"}"
] | // Sets the state of the server. | [
"Sets",
"the",
"state",
"of",
"the",
"server",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L288-L309 |
147,926 | goraft/raft | server.go | Term | func (s *server) Term() uint64 {
s.mutex.RLock()
defer s.mutex.RUnlock()
return s.currentTerm
} | go | func (s *server) Term() uint64 {
s.mutex.RLock()
defer s.mutex.RUnlock()
return s.currentTerm
} | [
"func",
"(",
"s",
"*",
"server",
")",
"Term",
"(",
")",
"uint64",
"{",
"s",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"s",
".",
"currentTerm",
"\n",
"}"
] | // Retrieves the current term of the server. | [
"Retrieves",
"the",
"current",
"term",
"of",
"the",
"server",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L312-L316 |
147,927 | goraft/raft | server.go | CommitIndex | func (s *server) CommitIndex() uint64 {
s.log.mutex.RLock()
defer s.log.mutex.RUnlock()
return s.log.commitIndex
} | go | func (s *server) CommitIndex() uint64 {
s.log.mutex.RLock()
defer s.log.mutex.RUnlock()
return s.log.commitIndex
} | [
"func",
"(",
"s",
"*",
"server",
")",
"CommitIndex",
"(",
")",
"uint64",
"{",
"s",
".",
"log",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"log",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"s",
".",
"log",
".",
"commitIndex",
"\n",
"}"
] | // Retrieves the current commit index of the server. | [
"Retrieves",
"the",
"current",
"commit",
"index",
"of",
"the",
"server",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L319-L323 |
147,928 | goraft/raft | server.go | LogEntries | func (s *server) LogEntries() []*LogEntry {
s.log.mutex.RLock()
defer s.log.mutex.RUnlock()
return s.log.entries
} | go | func (s *server) LogEntries() []*LogEntry {
s.log.mutex.RLock()
defer s.log.mutex.RUnlock()
return s.log.entries
} | [
"func",
"(",
"s",
"*",
"server",
")",
"LogEntries",
"(",
")",
"[",
"]",
"*",
"LogEntry",
"{",
"s",
".",
"log",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"log",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"s",
".",
"log",
".",
"entries",
"\n",
"}"
] | // A list of all the log entries. This should only be used for debugging purposes. | [
"A",
"list",
"of",
"all",
"the",
"log",
"entries",
".",
"This",
"should",
"only",
"be",
"used",
"for",
"debugging",
"purposes",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L336-L340 |
147,929 | goraft/raft | server.go | GetState | func (s *server) GetState() string {
s.mutex.RLock()
defer s.mutex.RUnlock()
return fmt.Sprintf("Name: %s, State: %s, Term: %v, CommitedIndex: %v ", s.name, s.state, s.currentTerm, s.log.commitIndex)
} | go | func (s *server) GetState() string {
s.mutex.RLock()
defer s.mutex.RUnlock()
return fmt.Sprintf("Name: %s, State: %s, Term: %v, CommitedIndex: %v ", s.name, s.state, s.currentTerm, s.log.commitIndex)
} | [
"func",
"(",
"s",
"*",
"server",
")",
"GetState",
"(",
")",
"string",
"{",
"s",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"s",
".",
"name",
",",
"s",
".",
"state",
",",
"s",
".",
"currentTerm",
",",
"s",
".",
"log",
".",
"commitIndex",
")",
"\n",
"}"
] | // Get the state of the server for debugging | [
"Get",
"the",
"state",
"of",
"the",
"server",
"for",
"debugging"
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L348-L352 |
147,930 | goraft/raft | server.go | SetElectionTimeout | func (s *server) SetElectionTimeout(duration time.Duration) {
s.mutex.Lock()
defer s.mutex.Unlock()
s.electionTimeout = duration
} | go | func (s *server) SetElectionTimeout(duration time.Duration) {
s.mutex.Lock()
defer s.mutex.Unlock()
s.electionTimeout = duration
} | [
"func",
"(",
"s",
"*",
"server",
")",
"SetElectionTimeout",
"(",
"duration",
"time",
".",
"Duration",
")",
"{",
"s",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"s",
".",
"electionTimeout",
"=",
"duration",
"\n",
"}"
] | // Sets the election timeout. | [
"Sets",
"the",
"election",
"timeout",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L387-L391 |
147,931 | goraft/raft | server.go | SetHeartbeatInterval | func (s *server) SetHeartbeatInterval(duration time.Duration) {
s.mutex.Lock()
defer s.mutex.Unlock()
s.heartbeatInterval = duration
for _, peer := range s.peers {
peer.setHeartbeatInterval(duration)
}
} | go | func (s *server) SetHeartbeatInterval(duration time.Duration) {
s.mutex.Lock()
defer s.mutex.Unlock()
s.heartbeatInterval = duration
for _, peer := range s.peers {
peer.setHeartbeatInterval(duration)
}
} | [
"func",
"(",
"s",
"*",
"server",
")",
"SetHeartbeatInterval",
"(",
"duration",
"time",
".",
"Duration",
")",
"{",
"s",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n\n",
"s",
".",
"heartbeatInterval",
"=",
"duration",
"\n",
"for",
"_",
",",
"peer",
":=",
"range",
"s",
".",
"peers",
"{",
"peer",
".",
"setHeartbeatInterval",
"(",
"duration",
")",
"\n",
"}",
"\n",
"}"
] | // Sets the heartbeat timeout. | [
"Sets",
"the",
"heartbeat",
"timeout",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L405-L413 |
147,932 | goraft/raft | server.go | Start | func (s *server) Start() error {
// Exit if the server is already running.
if s.Running() {
return fmt.Errorf("raft.Server: Server already running[%v]", s.state)
}
if err := s.Init(); err != nil {
return err
}
// stopped needs to be allocated each time server starts
// because it is closed at `Stop`.
s.stopped = make(chan bool)
s.setState(Follower)
// If no log entries exist then
// 1. wait for AEs from another node
// 2. wait for self-join command
// to set itself promotable
if !s.promotable() {
s.debugln("start as a new raft server")
// If log entries exist then allow promotion to candidate
// if no AEs received.
} else {
s.debugln("start from previous saved state")
}
debugln(s.GetState())
s.routineGroup.Add(1)
go func() {
defer s.routineGroup.Done()
s.loop()
}()
return nil
} | go | func (s *server) Start() error {
// Exit if the server is already running.
if s.Running() {
return fmt.Errorf("raft.Server: Server already running[%v]", s.state)
}
if err := s.Init(); err != nil {
return err
}
// stopped needs to be allocated each time server starts
// because it is closed at `Stop`.
s.stopped = make(chan bool)
s.setState(Follower)
// If no log entries exist then
// 1. wait for AEs from another node
// 2. wait for self-join command
// to set itself promotable
if !s.promotable() {
s.debugln("start as a new raft server")
// If log entries exist then allow promotion to candidate
// if no AEs received.
} else {
s.debugln("start from previous saved state")
}
debugln(s.GetState())
s.routineGroup.Add(1)
go func() {
defer s.routineGroup.Done()
s.loop()
}()
return nil
} | [
"func",
"(",
"s",
"*",
"server",
")",
"Start",
"(",
")",
"error",
"{",
"// Exit if the server is already running.",
"if",
"s",
".",
"Running",
"(",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"s",
".",
"state",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"s",
".",
"Init",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// stopped needs to be allocated each time server starts",
"// because it is closed at `Stop`.",
"s",
".",
"stopped",
"=",
"make",
"(",
"chan",
"bool",
")",
"\n",
"s",
".",
"setState",
"(",
"Follower",
")",
"\n\n",
"// If no log entries exist then",
"// 1. wait for AEs from another node",
"// 2. wait for self-join command",
"// to set itself promotable",
"if",
"!",
"s",
".",
"promotable",
"(",
")",
"{",
"s",
".",
"debugln",
"(",
"\"",
"\"",
")",
"\n\n",
"// If log entries exist then allow promotion to candidate",
"// if no AEs received.",
"}",
"else",
"{",
"s",
".",
"debugln",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"debugln",
"(",
"s",
".",
"GetState",
"(",
")",
")",
"\n\n",
"s",
".",
"routineGroup",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"defer",
"s",
".",
"routineGroup",
".",
"Done",
"(",
")",
"\n",
"s",
".",
"loop",
"(",
")",
"\n",
"}",
"(",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Start the raft server
// If log entries exist then allow promotion to candidate if no AEs received.
// If no log entries exist then wait for AEs from another node.
// If no log entries exist and a self-join command is issued then
// immediately become leader and commit entry. | [
"Start",
"the",
"raft",
"server",
"If",
"log",
"entries",
"exist",
"then",
"allow",
"promotion",
"to",
"candidate",
"if",
"no",
"AEs",
"received",
".",
"If",
"no",
"log",
"entries",
"exist",
"then",
"wait",
"for",
"AEs",
"from",
"another",
"node",
".",
"If",
"no",
"log",
"entries",
"exist",
"and",
"a",
"self",
"-",
"join",
"command",
"is",
"issued",
"then",
"immediately",
"become",
"leader",
"and",
"commit",
"entry",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L437-L474 |
147,933 | goraft/raft | server.go | Stop | func (s *server) Stop() {
if s.State() == Stopped {
return
}
close(s.stopped)
// make sure all goroutines have stopped before we close the log
s.routineGroup.Wait()
s.log.close()
s.setState(Stopped)
} | go | func (s *server) Stop() {
if s.State() == Stopped {
return
}
close(s.stopped)
// make sure all goroutines have stopped before we close the log
s.routineGroup.Wait()
s.log.close()
s.setState(Stopped)
} | [
"func",
"(",
"s",
"*",
"server",
")",
"Stop",
"(",
")",
"{",
"if",
"s",
".",
"State",
"(",
")",
"==",
"Stopped",
"{",
"return",
"\n",
"}",
"\n\n",
"close",
"(",
"s",
".",
"stopped",
")",
"\n\n",
"// make sure all goroutines have stopped before we close the log",
"s",
".",
"routineGroup",
".",
"Wait",
"(",
")",
"\n\n",
"s",
".",
"log",
".",
"close",
"(",
")",
"\n",
"s",
".",
"setState",
"(",
"Stopped",
")",
"\n",
"}"
] | // Shuts down the server. | [
"Shuts",
"down",
"the",
"server",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L518-L530 |
147,934 | goraft/raft | server.go | Running | func (s *server) Running() bool {
s.mutex.RLock()
defer s.mutex.RUnlock()
return (s.state != Stopped && s.state != Initialized)
} | go | func (s *server) Running() bool {
s.mutex.RLock()
defer s.mutex.RUnlock()
return (s.state != Stopped && s.state != Initialized)
} | [
"func",
"(",
"s",
"*",
"server",
")",
"Running",
"(",
")",
"bool",
"{",
"s",
".",
"mutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"mutex",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"(",
"s",
".",
"state",
"!=",
"Stopped",
"&&",
"s",
".",
"state",
"!=",
"Initialized",
")",
"\n",
"}"
] | // Checks if the server is currently running. | [
"Checks",
"if",
"the",
"server",
"is",
"currently",
"running",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L533-L537 |
147,935 | goraft/raft | server.go | send | func (s *server) send(value interface{}) (interface{}, error) {
if !s.Running() {
return nil, StopError
}
event := &ev{target: value, c: make(chan error, 1)}
select {
case s.c <- event:
case <-s.stopped:
return nil, StopError
}
select {
case <-s.stopped:
return nil, StopError
case err := <-event.c:
return event.returnValue, err
}
} | go | func (s *server) send(value interface{}) (interface{}, error) {
if !s.Running() {
return nil, StopError
}
event := &ev{target: value, c: make(chan error, 1)}
select {
case s.c <- event:
case <-s.stopped:
return nil, StopError
}
select {
case <-s.stopped:
return nil, StopError
case err := <-event.c:
return event.returnValue, err
}
} | [
"func",
"(",
"s",
"*",
"server",
")",
"send",
"(",
"value",
"interface",
"{",
"}",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"if",
"!",
"s",
".",
"Running",
"(",
")",
"{",
"return",
"nil",
",",
"StopError",
"\n",
"}",
"\n\n",
"event",
":=",
"&",
"ev",
"{",
"target",
":",
"value",
",",
"c",
":",
"make",
"(",
"chan",
"error",
",",
"1",
")",
"}",
"\n",
"select",
"{",
"case",
"s",
".",
"c",
"<-",
"event",
":",
"case",
"<-",
"s",
".",
"stopped",
":",
"return",
"nil",
",",
"StopError",
"\n",
"}",
"\n",
"select",
"{",
"case",
"<-",
"s",
".",
"stopped",
":",
"return",
"nil",
",",
"StopError",
"\n",
"case",
"err",
":=",
"<-",
"event",
".",
"c",
":",
"return",
"event",
".",
"returnValue",
",",
"err",
"\n",
"}",
"\n",
"}"
] | // Sends an event to the event loop to be processed. The function will wait
// until the event is actually processed before returning. | [
"Sends",
"an",
"event",
"to",
"the",
"event",
"loop",
"to",
"be",
"processed",
".",
"The",
"function",
"will",
"wait",
"until",
"the",
"event",
"is",
"actually",
"processed",
"before",
"returning",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L619-L636 |
147,936 | goraft/raft | server.go | candidateLoop | func (s *server) candidateLoop() {
// Clear leader value.
prevLeader := s.leader
s.leader = ""
if prevLeader != s.leader {
s.DispatchEvent(newEvent(LeaderChangeEventType, s.leader, prevLeader))
}
lastLogIndex, lastLogTerm := s.log.lastInfo()
doVote := true
votesGranted := 0
var timeoutChan <-chan time.Time
var respChan chan *RequestVoteResponse
for s.State() == Candidate {
if doVote {
// Increment current term, vote for self.
s.currentTerm++
s.votedFor = s.name
// Send RequestVote RPCs to all other servers.
respChan = make(chan *RequestVoteResponse, len(s.peers))
for _, peer := range s.peers {
s.routineGroup.Add(1)
go func(peer *Peer) {
defer s.routineGroup.Done()
peer.sendVoteRequest(newRequestVoteRequest(s.currentTerm, s.name, lastLogIndex, lastLogTerm), respChan)
}(peer)
}
// Wait for either:
// * Votes received from majority of servers: become leader
// * AppendEntries RPC received from new leader: step down.
// * Election timeout elapses without election resolution: increment term, start new election
// * Discover higher term: step down (§5.1)
votesGranted = 1
timeoutChan = afterBetween(s.ElectionTimeout(), s.ElectionTimeout()*2)
doVote = false
}
// If we received enough votes then stop waiting for more votes.
// And return from the candidate loop
if votesGranted == s.QuorumSize() {
s.debugln("server.candidate.recv.enough.votes")
s.setState(Leader)
return
}
// Collect votes from peers.
select {
case <-s.stopped:
s.setState(Stopped)
return
case resp := <-respChan:
if success := s.processVoteResponse(resp); success {
s.debugln("server.candidate.vote.granted: ", votesGranted)
votesGranted++
}
case e := <-s.c:
var err error
switch req := e.target.(type) {
case Command:
err = NotLeaderError
case *AppendEntriesRequest:
e.returnValue, _ = s.processAppendEntriesRequest(req)
case *RequestVoteRequest:
e.returnValue, _ = s.processRequestVoteRequest(req)
}
// Callback to event.
e.c <- err
case <-timeoutChan:
doVote = true
}
}
} | go | func (s *server) candidateLoop() {
// Clear leader value.
prevLeader := s.leader
s.leader = ""
if prevLeader != s.leader {
s.DispatchEvent(newEvent(LeaderChangeEventType, s.leader, prevLeader))
}
lastLogIndex, lastLogTerm := s.log.lastInfo()
doVote := true
votesGranted := 0
var timeoutChan <-chan time.Time
var respChan chan *RequestVoteResponse
for s.State() == Candidate {
if doVote {
// Increment current term, vote for self.
s.currentTerm++
s.votedFor = s.name
// Send RequestVote RPCs to all other servers.
respChan = make(chan *RequestVoteResponse, len(s.peers))
for _, peer := range s.peers {
s.routineGroup.Add(1)
go func(peer *Peer) {
defer s.routineGroup.Done()
peer.sendVoteRequest(newRequestVoteRequest(s.currentTerm, s.name, lastLogIndex, lastLogTerm), respChan)
}(peer)
}
// Wait for either:
// * Votes received from majority of servers: become leader
// * AppendEntries RPC received from new leader: step down.
// * Election timeout elapses without election resolution: increment term, start new election
// * Discover higher term: step down (§5.1)
votesGranted = 1
timeoutChan = afterBetween(s.ElectionTimeout(), s.ElectionTimeout()*2)
doVote = false
}
// If we received enough votes then stop waiting for more votes.
// And return from the candidate loop
if votesGranted == s.QuorumSize() {
s.debugln("server.candidate.recv.enough.votes")
s.setState(Leader)
return
}
// Collect votes from peers.
select {
case <-s.stopped:
s.setState(Stopped)
return
case resp := <-respChan:
if success := s.processVoteResponse(resp); success {
s.debugln("server.candidate.vote.granted: ", votesGranted)
votesGranted++
}
case e := <-s.c:
var err error
switch req := e.target.(type) {
case Command:
err = NotLeaderError
case *AppendEntriesRequest:
e.returnValue, _ = s.processAppendEntriesRequest(req)
case *RequestVoteRequest:
e.returnValue, _ = s.processRequestVoteRequest(req)
}
// Callback to event.
e.c <- err
case <-timeoutChan:
doVote = true
}
}
} | [
"func",
"(",
"s",
"*",
"server",
")",
"candidateLoop",
"(",
")",
"{",
"// Clear leader value.",
"prevLeader",
":=",
"s",
".",
"leader",
"\n",
"s",
".",
"leader",
"=",
"\"",
"\"",
"\n",
"if",
"prevLeader",
"!=",
"s",
".",
"leader",
"{",
"s",
".",
"DispatchEvent",
"(",
"newEvent",
"(",
"LeaderChangeEventType",
",",
"s",
".",
"leader",
",",
"prevLeader",
")",
")",
"\n",
"}",
"\n\n",
"lastLogIndex",
",",
"lastLogTerm",
":=",
"s",
".",
"log",
".",
"lastInfo",
"(",
")",
"\n",
"doVote",
":=",
"true",
"\n",
"votesGranted",
":=",
"0",
"\n",
"var",
"timeoutChan",
"<-",
"chan",
"time",
".",
"Time",
"\n",
"var",
"respChan",
"chan",
"*",
"RequestVoteResponse",
"\n\n",
"for",
"s",
".",
"State",
"(",
")",
"==",
"Candidate",
"{",
"if",
"doVote",
"{",
"// Increment current term, vote for self.",
"s",
".",
"currentTerm",
"++",
"\n",
"s",
".",
"votedFor",
"=",
"s",
".",
"name",
"\n\n",
"// Send RequestVote RPCs to all other servers.",
"respChan",
"=",
"make",
"(",
"chan",
"*",
"RequestVoteResponse",
",",
"len",
"(",
"s",
".",
"peers",
")",
")",
"\n",
"for",
"_",
",",
"peer",
":=",
"range",
"s",
".",
"peers",
"{",
"s",
".",
"routineGroup",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
"peer",
"*",
"Peer",
")",
"{",
"defer",
"s",
".",
"routineGroup",
".",
"Done",
"(",
")",
"\n",
"peer",
".",
"sendVoteRequest",
"(",
"newRequestVoteRequest",
"(",
"s",
".",
"currentTerm",
",",
"s",
".",
"name",
",",
"lastLogIndex",
",",
"lastLogTerm",
")",
",",
"respChan",
")",
"\n",
"}",
"(",
"peer",
")",
"\n",
"}",
"\n\n",
"// Wait for either:",
"// * Votes received from majority of servers: become leader",
"// * AppendEntries RPC received from new leader: step down.",
"// * Election timeout elapses without election resolution: increment term, start new election",
"// * Discover higher term: step down (§5.1)",
"votesGranted",
"=",
"1",
"\n",
"timeoutChan",
"=",
"afterBetween",
"(",
"s",
".",
"ElectionTimeout",
"(",
")",
",",
"s",
".",
"ElectionTimeout",
"(",
")",
"*",
"2",
")",
"\n",
"doVote",
"=",
"false",
"\n",
"}",
"\n\n",
"// If we received enough votes then stop waiting for more votes.",
"// And return from the candidate loop",
"if",
"votesGranted",
"==",
"s",
".",
"QuorumSize",
"(",
")",
"{",
"s",
".",
"debugln",
"(",
"\"",
"\"",
")",
"\n",
"s",
".",
"setState",
"(",
"Leader",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Collect votes from peers.",
"select",
"{",
"case",
"<-",
"s",
".",
"stopped",
":",
"s",
".",
"setState",
"(",
"Stopped",
")",
"\n",
"return",
"\n\n",
"case",
"resp",
":=",
"<-",
"respChan",
":",
"if",
"success",
":=",
"s",
".",
"processVoteResponse",
"(",
"resp",
")",
";",
"success",
"{",
"s",
".",
"debugln",
"(",
"\"",
"\"",
",",
"votesGranted",
")",
"\n",
"votesGranted",
"++",
"\n",
"}",
"\n\n",
"case",
"e",
":=",
"<-",
"s",
".",
"c",
":",
"var",
"err",
"error",
"\n",
"switch",
"req",
":=",
"e",
".",
"target",
".",
"(",
"type",
")",
"{",
"case",
"Command",
":",
"err",
"=",
"NotLeaderError",
"\n",
"case",
"*",
"AppendEntriesRequest",
":",
"e",
".",
"returnValue",
",",
"_",
"=",
"s",
".",
"processAppendEntriesRequest",
"(",
"req",
")",
"\n",
"case",
"*",
"RequestVoteRequest",
":",
"e",
".",
"returnValue",
",",
"_",
"=",
"s",
".",
"processRequestVoteRequest",
"(",
"req",
")",
"\n",
"}",
"\n\n",
"// Callback to event.",
"e",
".",
"c",
"<-",
"err",
"\n\n",
"case",
"<-",
"timeoutChan",
":",
"doVote",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // The event loop that is run when the server is in a Candidate state. | [
"The",
"event",
"loop",
"that",
"is",
"run",
"when",
"the",
"server",
"is",
"in",
"a",
"Candidate",
"state",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L730-L808 |
147,937 | goraft/raft | server.go | leaderLoop | func (s *server) leaderLoop() {
logIndex, _ := s.log.lastInfo()
// Update the peers prevLogIndex to leader's lastLogIndex and start heartbeat.
s.debugln("leaderLoop.set.PrevIndex to ", logIndex)
for _, peer := range s.peers {
peer.setPrevLogIndex(logIndex)
peer.startHeartbeat()
}
// Commit a NOP after the server becomes leader. From the Raft paper:
// "Upon election: send initial empty AppendEntries RPCs (heartbeat) to
// each server; repeat during idle periods to prevent election timeouts
// (§5.2)". The heartbeats started above do the "idle" period work.
s.routineGroup.Add(1)
go func() {
defer s.routineGroup.Done()
s.Do(NOPCommand{})
}()
// Begin to collect response from followers
for s.State() == Leader {
var err error
select {
case <-s.stopped:
// Stop all peers before stop
for _, peer := range s.peers {
peer.stopHeartbeat(false)
}
s.setState(Stopped)
return
case e := <-s.c:
switch req := e.target.(type) {
case Command:
s.processCommand(req, e)
continue
case *AppendEntriesRequest:
e.returnValue, _ = s.processAppendEntriesRequest(req)
case *AppendEntriesResponse:
s.processAppendEntriesResponse(req)
case *RequestVoteRequest:
e.returnValue, _ = s.processRequestVoteRequest(req)
}
// Callback to event.
e.c <- err
}
}
s.syncedPeer = nil
} | go | func (s *server) leaderLoop() {
logIndex, _ := s.log.lastInfo()
// Update the peers prevLogIndex to leader's lastLogIndex and start heartbeat.
s.debugln("leaderLoop.set.PrevIndex to ", logIndex)
for _, peer := range s.peers {
peer.setPrevLogIndex(logIndex)
peer.startHeartbeat()
}
// Commit a NOP after the server becomes leader. From the Raft paper:
// "Upon election: send initial empty AppendEntries RPCs (heartbeat) to
// each server; repeat during idle periods to prevent election timeouts
// (§5.2)". The heartbeats started above do the "idle" period work.
s.routineGroup.Add(1)
go func() {
defer s.routineGroup.Done()
s.Do(NOPCommand{})
}()
// Begin to collect response from followers
for s.State() == Leader {
var err error
select {
case <-s.stopped:
// Stop all peers before stop
for _, peer := range s.peers {
peer.stopHeartbeat(false)
}
s.setState(Stopped)
return
case e := <-s.c:
switch req := e.target.(type) {
case Command:
s.processCommand(req, e)
continue
case *AppendEntriesRequest:
e.returnValue, _ = s.processAppendEntriesRequest(req)
case *AppendEntriesResponse:
s.processAppendEntriesResponse(req)
case *RequestVoteRequest:
e.returnValue, _ = s.processRequestVoteRequest(req)
}
// Callback to event.
e.c <- err
}
}
s.syncedPeer = nil
} | [
"func",
"(",
"s",
"*",
"server",
")",
"leaderLoop",
"(",
")",
"{",
"logIndex",
",",
"_",
":=",
"s",
".",
"log",
".",
"lastInfo",
"(",
")",
"\n\n",
"// Update the peers prevLogIndex to leader's lastLogIndex and start heartbeat.",
"s",
".",
"debugln",
"(",
"\"",
"\"",
",",
"logIndex",
")",
"\n",
"for",
"_",
",",
"peer",
":=",
"range",
"s",
".",
"peers",
"{",
"peer",
".",
"setPrevLogIndex",
"(",
"logIndex",
")",
"\n",
"peer",
".",
"startHeartbeat",
"(",
")",
"\n",
"}",
"\n\n",
"// Commit a NOP after the server becomes leader. From the Raft paper:",
"// \"Upon election: send initial empty AppendEntries RPCs (heartbeat) to",
"// each server; repeat during idle periods to prevent election timeouts",
"// (§5.2)\". The heartbeats started above do the \"idle\" period work.",
"s",
".",
"routineGroup",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"defer",
"s",
".",
"routineGroup",
".",
"Done",
"(",
")",
"\n",
"s",
".",
"Do",
"(",
"NOPCommand",
"{",
"}",
")",
"\n",
"}",
"(",
")",
"\n\n",
"// Begin to collect response from followers",
"for",
"s",
".",
"State",
"(",
")",
"==",
"Leader",
"{",
"var",
"err",
"error",
"\n",
"select",
"{",
"case",
"<-",
"s",
".",
"stopped",
":",
"// Stop all peers before stop",
"for",
"_",
",",
"peer",
":=",
"range",
"s",
".",
"peers",
"{",
"peer",
".",
"stopHeartbeat",
"(",
"false",
")",
"\n",
"}",
"\n",
"s",
".",
"setState",
"(",
"Stopped",
")",
"\n",
"return",
"\n\n",
"case",
"e",
":=",
"<-",
"s",
".",
"c",
":",
"switch",
"req",
":=",
"e",
".",
"target",
".",
"(",
"type",
")",
"{",
"case",
"Command",
":",
"s",
".",
"processCommand",
"(",
"req",
",",
"e",
")",
"\n",
"continue",
"\n",
"case",
"*",
"AppendEntriesRequest",
":",
"e",
".",
"returnValue",
",",
"_",
"=",
"s",
".",
"processAppendEntriesRequest",
"(",
"req",
")",
"\n",
"case",
"*",
"AppendEntriesResponse",
":",
"s",
".",
"processAppendEntriesResponse",
"(",
"req",
")",
"\n",
"case",
"*",
"RequestVoteRequest",
":",
"e",
".",
"returnValue",
",",
"_",
"=",
"s",
".",
"processRequestVoteRequest",
"(",
"req",
")",
"\n",
"}",
"\n\n",
"// Callback to event.",
"e",
".",
"c",
"<-",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"s",
".",
"syncedPeer",
"=",
"nil",
"\n",
"}"
] | // The event loop that is run when the server is in a Leader state. | [
"The",
"event",
"loop",
"that",
"is",
"run",
"when",
"the",
"server",
"is",
"in",
"a",
"Leader",
"state",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L811-L862 |
147,938 | goraft/raft | server.go | processCommand | func (s *server) processCommand(command Command, e *ev) {
s.debugln("server.command.process")
// Create an entry for the command in the log.
entry, err := s.log.createEntry(s.currentTerm, command, e)
if err != nil {
s.debugln("server.command.log.entry.error:", err)
e.c <- err
return
}
if err := s.log.appendEntry(entry); err != nil {
s.debugln("server.command.log.error:", err)
e.c <- err
return
}
s.syncedPeer[s.Name()] = true
if len(s.peers) == 0 {
commitIndex := s.log.currentIndex()
s.log.setCommitIndex(commitIndex)
s.debugln("commit index ", commitIndex)
}
} | go | func (s *server) processCommand(command Command, e *ev) {
s.debugln("server.command.process")
// Create an entry for the command in the log.
entry, err := s.log.createEntry(s.currentTerm, command, e)
if err != nil {
s.debugln("server.command.log.entry.error:", err)
e.c <- err
return
}
if err := s.log.appendEntry(entry); err != nil {
s.debugln("server.command.log.error:", err)
e.c <- err
return
}
s.syncedPeer[s.Name()] = true
if len(s.peers) == 0 {
commitIndex := s.log.currentIndex()
s.log.setCommitIndex(commitIndex)
s.debugln("commit index ", commitIndex)
}
} | [
"func",
"(",
"s",
"*",
"server",
")",
"processCommand",
"(",
"command",
"Command",
",",
"e",
"*",
"ev",
")",
"{",
"s",
".",
"debugln",
"(",
"\"",
"\"",
")",
"\n\n",
"// Create an entry for the command in the log.",
"entry",
",",
"err",
":=",
"s",
".",
"log",
".",
"createEntry",
"(",
"s",
".",
"currentTerm",
",",
"command",
",",
"e",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"s",
".",
"debugln",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"e",
".",
"c",
"<-",
"err",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"s",
".",
"log",
".",
"appendEntry",
"(",
"entry",
")",
";",
"err",
"!=",
"nil",
"{",
"s",
".",
"debugln",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"e",
".",
"c",
"<-",
"err",
"\n",
"return",
"\n",
"}",
"\n\n",
"s",
".",
"syncedPeer",
"[",
"s",
".",
"Name",
"(",
")",
"]",
"=",
"true",
"\n",
"if",
"len",
"(",
"s",
".",
"peers",
")",
"==",
"0",
"{",
"commitIndex",
":=",
"s",
".",
"log",
".",
"currentIndex",
"(",
")",
"\n",
"s",
".",
"log",
".",
"setCommitIndex",
"(",
"commitIndex",
")",
"\n",
"s",
".",
"debugln",
"(",
"\"",
"\"",
",",
"commitIndex",
")",
"\n",
"}",
"\n",
"}"
] | // Processes a command. | [
"Processes",
"a",
"command",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L901-L925 |
147,939 | goraft/raft | server.go | processAppendEntriesRequest | func (s *server) processAppendEntriesRequest(req *AppendEntriesRequest) (*AppendEntriesResponse, bool) {
s.traceln("server.ae.process")
if req.Term < s.currentTerm {
s.debugln("server.ae.error: stale term")
return newAppendEntriesResponse(s.currentTerm, false, s.log.currentIndex(), s.log.CommitIndex()), false
}
if req.Term == s.currentTerm {
_assert(s.State() != Leader, "leader.elected.at.same.term.%d\n", s.currentTerm)
// step-down to follower when it is a candidate
if s.state == Candidate {
// change state to follower
s.setState(Follower)
}
// discover new leader when candidate
// save leader name when follower
s.leader = req.LeaderName
} else {
// Update term and leader.
s.updateCurrentTerm(req.Term, req.LeaderName)
}
// Reject if log doesn't contain a matching previous entry.
if err := s.log.truncate(req.PrevLogIndex, req.PrevLogTerm); err != nil {
s.debugln("server.ae.truncate.error: ", err)
return newAppendEntriesResponse(s.currentTerm, false, s.log.currentIndex(), s.log.CommitIndex()), true
}
// Append entries to the log.
if err := s.log.appendEntries(req.Entries); err != nil {
s.debugln("server.ae.append.error: ", err)
return newAppendEntriesResponse(s.currentTerm, false, s.log.currentIndex(), s.log.CommitIndex()), true
}
// Commit up to the commit index.
if err := s.log.setCommitIndex(req.CommitIndex); err != nil {
s.debugln("server.ae.commit.error: ", err)
return newAppendEntriesResponse(s.currentTerm, false, s.log.currentIndex(), s.log.CommitIndex()), true
}
// once the server appended and committed all the log entries from the leader
return newAppendEntriesResponse(s.currentTerm, true, s.log.currentIndex(), s.log.CommitIndex()), true
} | go | func (s *server) processAppendEntriesRequest(req *AppendEntriesRequest) (*AppendEntriesResponse, bool) {
s.traceln("server.ae.process")
if req.Term < s.currentTerm {
s.debugln("server.ae.error: stale term")
return newAppendEntriesResponse(s.currentTerm, false, s.log.currentIndex(), s.log.CommitIndex()), false
}
if req.Term == s.currentTerm {
_assert(s.State() != Leader, "leader.elected.at.same.term.%d\n", s.currentTerm)
// step-down to follower when it is a candidate
if s.state == Candidate {
// change state to follower
s.setState(Follower)
}
// discover new leader when candidate
// save leader name when follower
s.leader = req.LeaderName
} else {
// Update term and leader.
s.updateCurrentTerm(req.Term, req.LeaderName)
}
// Reject if log doesn't contain a matching previous entry.
if err := s.log.truncate(req.PrevLogIndex, req.PrevLogTerm); err != nil {
s.debugln("server.ae.truncate.error: ", err)
return newAppendEntriesResponse(s.currentTerm, false, s.log.currentIndex(), s.log.CommitIndex()), true
}
// Append entries to the log.
if err := s.log.appendEntries(req.Entries); err != nil {
s.debugln("server.ae.append.error: ", err)
return newAppendEntriesResponse(s.currentTerm, false, s.log.currentIndex(), s.log.CommitIndex()), true
}
// Commit up to the commit index.
if err := s.log.setCommitIndex(req.CommitIndex); err != nil {
s.debugln("server.ae.commit.error: ", err)
return newAppendEntriesResponse(s.currentTerm, false, s.log.currentIndex(), s.log.CommitIndex()), true
}
// once the server appended and committed all the log entries from the leader
return newAppendEntriesResponse(s.currentTerm, true, s.log.currentIndex(), s.log.CommitIndex()), true
} | [
"func",
"(",
"s",
"*",
"server",
")",
"processAppendEntriesRequest",
"(",
"req",
"*",
"AppendEntriesRequest",
")",
"(",
"*",
"AppendEntriesResponse",
",",
"bool",
")",
"{",
"s",
".",
"traceln",
"(",
"\"",
"\"",
")",
"\n\n",
"if",
"req",
".",
"Term",
"<",
"s",
".",
"currentTerm",
"{",
"s",
".",
"debugln",
"(",
"\"",
"\"",
")",
"\n",
"return",
"newAppendEntriesResponse",
"(",
"s",
".",
"currentTerm",
",",
"false",
",",
"s",
".",
"log",
".",
"currentIndex",
"(",
")",
",",
"s",
".",
"log",
".",
"CommitIndex",
"(",
")",
")",
",",
"false",
"\n",
"}",
"\n\n",
"if",
"req",
".",
"Term",
"==",
"s",
".",
"currentTerm",
"{",
"_assert",
"(",
"s",
".",
"State",
"(",
")",
"!=",
"Leader",
",",
"\"",
"\\n",
"\"",
",",
"s",
".",
"currentTerm",
")",
"\n\n",
"// step-down to follower when it is a candidate",
"if",
"s",
".",
"state",
"==",
"Candidate",
"{",
"// change state to follower",
"s",
".",
"setState",
"(",
"Follower",
")",
"\n",
"}",
"\n\n",
"// discover new leader when candidate",
"// save leader name when follower",
"s",
".",
"leader",
"=",
"req",
".",
"LeaderName",
"\n",
"}",
"else",
"{",
"// Update term and leader.",
"s",
".",
"updateCurrentTerm",
"(",
"req",
".",
"Term",
",",
"req",
".",
"LeaderName",
")",
"\n",
"}",
"\n\n",
"// Reject if log doesn't contain a matching previous entry.",
"if",
"err",
":=",
"s",
".",
"log",
".",
"truncate",
"(",
"req",
".",
"PrevLogIndex",
",",
"req",
".",
"PrevLogTerm",
")",
";",
"err",
"!=",
"nil",
"{",
"s",
".",
"debugln",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"newAppendEntriesResponse",
"(",
"s",
".",
"currentTerm",
",",
"false",
",",
"s",
".",
"log",
".",
"currentIndex",
"(",
")",
",",
"s",
".",
"log",
".",
"CommitIndex",
"(",
")",
")",
",",
"true",
"\n",
"}",
"\n\n",
"// Append entries to the log.",
"if",
"err",
":=",
"s",
".",
"log",
".",
"appendEntries",
"(",
"req",
".",
"Entries",
")",
";",
"err",
"!=",
"nil",
"{",
"s",
".",
"debugln",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"newAppendEntriesResponse",
"(",
"s",
".",
"currentTerm",
",",
"false",
",",
"s",
".",
"log",
".",
"currentIndex",
"(",
")",
",",
"s",
".",
"log",
".",
"CommitIndex",
"(",
")",
")",
",",
"true",
"\n",
"}",
"\n\n",
"// Commit up to the commit index.",
"if",
"err",
":=",
"s",
".",
"log",
".",
"setCommitIndex",
"(",
"req",
".",
"CommitIndex",
")",
";",
"err",
"!=",
"nil",
"{",
"s",
".",
"debugln",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"newAppendEntriesResponse",
"(",
"s",
".",
"currentTerm",
",",
"false",
",",
"s",
".",
"log",
".",
"currentIndex",
"(",
")",
",",
"s",
".",
"log",
".",
"CommitIndex",
"(",
")",
")",
",",
"true",
"\n",
"}",
"\n\n",
"// once the server appended and committed all the log entries from the leader",
"return",
"newAppendEntriesResponse",
"(",
"s",
".",
"currentTerm",
",",
"true",
",",
"s",
".",
"log",
".",
"currentIndex",
"(",
")",
",",
"s",
".",
"log",
".",
"CommitIndex",
"(",
")",
")",
",",
"true",
"\n",
"}"
] | // Processes the "append entries" request. | [
"Processes",
"the",
"append",
"entries",
"request",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L939-L985 |
147,940 | goraft/raft | server.go | processAppendEntriesResponse | func (s *server) processAppendEntriesResponse(resp *AppendEntriesResponse) {
// If we find a higher term then change to a follower and exit.
if resp.Term() > s.Term() {
s.updateCurrentTerm(resp.Term(), "")
return
}
// panic response if it's not successful.
if !resp.Success() {
return
}
// if one peer successfully append a log from the leader term,
// we add it to the synced list
if resp.append == true {
s.syncedPeer[resp.peer] = true
}
// Increment the commit count to make sure we have a quorum before committing.
if len(s.syncedPeer) < s.QuorumSize() {
return
}
// Determine the committed index that a majority has.
var indices []uint64
indices = append(indices, s.log.currentIndex())
for _, peer := range s.peers {
indices = append(indices, peer.getPrevLogIndex())
}
sort.Sort(sort.Reverse(uint64Slice(indices)))
// We can commit up to the index which the majority of the members have appended.
commitIndex := indices[s.QuorumSize()-1]
committedIndex := s.log.commitIndex
if commitIndex > committedIndex {
// leader needs to do a fsync before committing log entries
s.log.sync()
s.log.setCommitIndex(commitIndex)
s.debugln("commit index ", commitIndex)
}
} | go | func (s *server) processAppendEntriesResponse(resp *AppendEntriesResponse) {
// If we find a higher term then change to a follower and exit.
if resp.Term() > s.Term() {
s.updateCurrentTerm(resp.Term(), "")
return
}
// panic response if it's not successful.
if !resp.Success() {
return
}
// if one peer successfully append a log from the leader term,
// we add it to the synced list
if resp.append == true {
s.syncedPeer[resp.peer] = true
}
// Increment the commit count to make sure we have a quorum before committing.
if len(s.syncedPeer) < s.QuorumSize() {
return
}
// Determine the committed index that a majority has.
var indices []uint64
indices = append(indices, s.log.currentIndex())
for _, peer := range s.peers {
indices = append(indices, peer.getPrevLogIndex())
}
sort.Sort(sort.Reverse(uint64Slice(indices)))
// We can commit up to the index which the majority of the members have appended.
commitIndex := indices[s.QuorumSize()-1]
committedIndex := s.log.commitIndex
if commitIndex > committedIndex {
// leader needs to do a fsync before committing log entries
s.log.sync()
s.log.setCommitIndex(commitIndex)
s.debugln("commit index ", commitIndex)
}
} | [
"func",
"(",
"s",
"*",
"server",
")",
"processAppendEntriesResponse",
"(",
"resp",
"*",
"AppendEntriesResponse",
")",
"{",
"// If we find a higher term then change to a follower and exit.",
"if",
"resp",
".",
"Term",
"(",
")",
">",
"s",
".",
"Term",
"(",
")",
"{",
"s",
".",
"updateCurrentTerm",
"(",
"resp",
".",
"Term",
"(",
")",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// panic response if it's not successful.",
"if",
"!",
"resp",
".",
"Success",
"(",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"// if one peer successfully append a log from the leader term,",
"// we add it to the synced list",
"if",
"resp",
".",
"append",
"==",
"true",
"{",
"s",
".",
"syncedPeer",
"[",
"resp",
".",
"peer",
"]",
"=",
"true",
"\n",
"}",
"\n\n",
"// Increment the commit count to make sure we have a quorum before committing.",
"if",
"len",
"(",
"s",
".",
"syncedPeer",
")",
"<",
"s",
".",
"QuorumSize",
"(",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"// Determine the committed index that a majority has.",
"var",
"indices",
"[",
"]",
"uint64",
"\n",
"indices",
"=",
"append",
"(",
"indices",
",",
"s",
".",
"log",
".",
"currentIndex",
"(",
")",
")",
"\n",
"for",
"_",
",",
"peer",
":=",
"range",
"s",
".",
"peers",
"{",
"indices",
"=",
"append",
"(",
"indices",
",",
"peer",
".",
"getPrevLogIndex",
"(",
")",
")",
"\n",
"}",
"\n",
"sort",
".",
"Sort",
"(",
"sort",
".",
"Reverse",
"(",
"uint64Slice",
"(",
"indices",
")",
")",
")",
"\n\n",
"// We can commit up to the index which the majority of the members have appended.",
"commitIndex",
":=",
"indices",
"[",
"s",
".",
"QuorumSize",
"(",
")",
"-",
"1",
"]",
"\n",
"committedIndex",
":=",
"s",
".",
"log",
".",
"commitIndex",
"\n\n",
"if",
"commitIndex",
">",
"committedIndex",
"{",
"// leader needs to do a fsync before committing log entries",
"s",
".",
"log",
".",
"sync",
"(",
")",
"\n",
"s",
".",
"log",
".",
"setCommitIndex",
"(",
"commitIndex",
")",
"\n",
"s",
".",
"debugln",
"(",
"\"",
"\"",
",",
"commitIndex",
")",
"\n",
"}",
"\n",
"}"
] | // Processes the "append entries" response from the peer. This is only
// processed when the server is a leader. Responses received during other
// states are dropped. | [
"Processes",
"the",
"append",
"entries",
"response",
"from",
"the",
"peer",
".",
"This",
"is",
"only",
"processed",
"when",
"the",
"server",
"is",
"a",
"leader",
".",
"Responses",
"received",
"during",
"other",
"states",
"are",
"dropped",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L990-L1031 |
147,941 | goraft/raft | server.go | processRequestVoteRequest | func (s *server) processRequestVoteRequest(req *RequestVoteRequest) (*RequestVoteResponse, bool) {
// If the request is coming from an old term then reject it.
if req.Term < s.Term() {
s.debugln("server.rv.deny.vote: cause stale term")
return newRequestVoteResponse(s.currentTerm, false), false
}
// If the term of the request peer is larger than this node, update the term
// If the term is equal and we've already voted for a different candidate then
// don't vote for this candidate.
if req.Term > s.Term() {
s.updateCurrentTerm(req.Term, "")
} else if s.votedFor != "" && s.votedFor != req.CandidateName {
s.debugln("server.deny.vote: cause duplicate vote: ", req.CandidateName,
" already vote for ", s.votedFor)
return newRequestVoteResponse(s.currentTerm, false), false
}
// If the candidate's log is not at least as up-to-date as our last log then don't vote.
lastIndex, lastTerm := s.log.lastInfo()
if lastIndex > req.LastLogIndex || lastTerm > req.LastLogTerm {
s.debugln("server.deny.vote: cause out of date log: ", req.CandidateName,
"Index :[", lastIndex, "]", " [", req.LastLogIndex, "]",
"Term :[", lastTerm, "]", " [", req.LastLogTerm, "]")
return newRequestVoteResponse(s.currentTerm, false), false
}
// If we made it this far then cast a vote and reset our election time out.
s.debugln("server.rv.vote: ", s.name, " votes for", req.CandidateName, "at term", req.Term)
s.votedFor = req.CandidateName
return newRequestVoteResponse(s.currentTerm, true), true
} | go | func (s *server) processRequestVoteRequest(req *RequestVoteRequest) (*RequestVoteResponse, bool) {
// If the request is coming from an old term then reject it.
if req.Term < s.Term() {
s.debugln("server.rv.deny.vote: cause stale term")
return newRequestVoteResponse(s.currentTerm, false), false
}
// If the term of the request peer is larger than this node, update the term
// If the term is equal and we've already voted for a different candidate then
// don't vote for this candidate.
if req.Term > s.Term() {
s.updateCurrentTerm(req.Term, "")
} else if s.votedFor != "" && s.votedFor != req.CandidateName {
s.debugln("server.deny.vote: cause duplicate vote: ", req.CandidateName,
" already vote for ", s.votedFor)
return newRequestVoteResponse(s.currentTerm, false), false
}
// If the candidate's log is not at least as up-to-date as our last log then don't vote.
lastIndex, lastTerm := s.log.lastInfo()
if lastIndex > req.LastLogIndex || lastTerm > req.LastLogTerm {
s.debugln("server.deny.vote: cause out of date log: ", req.CandidateName,
"Index :[", lastIndex, "]", " [", req.LastLogIndex, "]",
"Term :[", lastTerm, "]", " [", req.LastLogTerm, "]")
return newRequestVoteResponse(s.currentTerm, false), false
}
// If we made it this far then cast a vote and reset our election time out.
s.debugln("server.rv.vote: ", s.name, " votes for", req.CandidateName, "at term", req.Term)
s.votedFor = req.CandidateName
return newRequestVoteResponse(s.currentTerm, true), true
} | [
"func",
"(",
"s",
"*",
"server",
")",
"processRequestVoteRequest",
"(",
"req",
"*",
"RequestVoteRequest",
")",
"(",
"*",
"RequestVoteResponse",
",",
"bool",
")",
"{",
"// If the request is coming from an old term then reject it.",
"if",
"req",
".",
"Term",
"<",
"s",
".",
"Term",
"(",
")",
"{",
"s",
".",
"debugln",
"(",
"\"",
"\"",
")",
"\n",
"return",
"newRequestVoteResponse",
"(",
"s",
".",
"currentTerm",
",",
"false",
")",
",",
"false",
"\n",
"}",
"\n\n",
"// If the term of the request peer is larger than this node, update the term",
"// If the term is equal and we've already voted for a different candidate then",
"// don't vote for this candidate.",
"if",
"req",
".",
"Term",
">",
"s",
".",
"Term",
"(",
")",
"{",
"s",
".",
"updateCurrentTerm",
"(",
"req",
".",
"Term",
",",
"\"",
"\"",
")",
"\n",
"}",
"else",
"if",
"s",
".",
"votedFor",
"!=",
"\"",
"\"",
"&&",
"s",
".",
"votedFor",
"!=",
"req",
".",
"CandidateName",
"{",
"s",
".",
"debugln",
"(",
"\"",
"\"",
",",
"req",
".",
"CandidateName",
",",
"\"",
"\"",
",",
"s",
".",
"votedFor",
")",
"\n",
"return",
"newRequestVoteResponse",
"(",
"s",
".",
"currentTerm",
",",
"false",
")",
",",
"false",
"\n",
"}",
"\n\n",
"// If the candidate's log is not at least as up-to-date as our last log then don't vote.",
"lastIndex",
",",
"lastTerm",
":=",
"s",
".",
"log",
".",
"lastInfo",
"(",
")",
"\n",
"if",
"lastIndex",
">",
"req",
".",
"LastLogIndex",
"||",
"lastTerm",
">",
"req",
".",
"LastLogTerm",
"{",
"s",
".",
"debugln",
"(",
"\"",
"\"",
",",
"req",
".",
"CandidateName",
",",
"\"",
"\"",
",",
"lastIndex",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"req",
".",
"LastLogIndex",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"lastTerm",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"req",
".",
"LastLogTerm",
",",
"\"",
"\"",
")",
"\n",
"return",
"newRequestVoteResponse",
"(",
"s",
".",
"currentTerm",
",",
"false",
")",
",",
"false",
"\n",
"}",
"\n\n",
"// If we made it this far then cast a vote and reset our election time out.",
"s",
".",
"debugln",
"(",
"\"",
"\"",
",",
"s",
".",
"name",
",",
"\"",
"\"",
",",
"req",
".",
"CandidateName",
",",
"\"",
"\"",
",",
"req",
".",
"Term",
")",
"\n",
"s",
".",
"votedFor",
"=",
"req",
".",
"CandidateName",
"\n\n",
"return",
"newRequestVoteResponse",
"(",
"s",
".",
"currentTerm",
",",
"true",
")",
",",
"true",
"\n",
"}"
] | // Processes a "request vote" request. | [
"Processes",
"a",
"request",
"vote",
"request",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L1066-L1099 |
147,942 | goraft/raft | server.go | RemovePeer | func (s *server) RemovePeer(name string) error {
s.debugln("server.peer.remove: ", name, len(s.peers))
// Skip the Peer if it has the same name as the Server
if name != s.Name() {
// Return error if peer doesn't exist.
peer := s.peers[name]
if peer == nil {
return fmt.Errorf("raft: Peer not found: %s", name)
}
// Stop peer and remove it.
if s.State() == Leader {
// We create a go routine here to avoid potential deadlock.
// We are holding log write lock when reach this line of code.
// Peer.stopHeartbeat can be blocked without go routine, if the
// target go routine (which we want to stop) is calling
// log.getEntriesAfter and waiting for log read lock.
// So we might be holding log lock and waiting for log lock,
// which lead to a deadlock.
// TODO(xiangli) refactor log lock
s.routineGroup.Add(1)
go func() {
defer s.routineGroup.Done()
peer.stopHeartbeat(true)
}()
}
delete(s.peers, name)
s.DispatchEvent(newEvent(RemovePeerEventType, name, nil))
}
// Write the configuration to file.
s.writeConf()
return nil
} | go | func (s *server) RemovePeer(name string) error {
s.debugln("server.peer.remove: ", name, len(s.peers))
// Skip the Peer if it has the same name as the Server
if name != s.Name() {
// Return error if peer doesn't exist.
peer := s.peers[name]
if peer == nil {
return fmt.Errorf("raft: Peer not found: %s", name)
}
// Stop peer and remove it.
if s.State() == Leader {
// We create a go routine here to avoid potential deadlock.
// We are holding log write lock when reach this line of code.
// Peer.stopHeartbeat can be blocked without go routine, if the
// target go routine (which we want to stop) is calling
// log.getEntriesAfter and waiting for log read lock.
// So we might be holding log lock and waiting for log lock,
// which lead to a deadlock.
// TODO(xiangli) refactor log lock
s.routineGroup.Add(1)
go func() {
defer s.routineGroup.Done()
peer.stopHeartbeat(true)
}()
}
delete(s.peers, name)
s.DispatchEvent(newEvent(RemovePeerEventType, name, nil))
}
// Write the configuration to file.
s.writeConf()
return nil
} | [
"func",
"(",
"s",
"*",
"server",
")",
"RemovePeer",
"(",
"name",
"string",
")",
"error",
"{",
"s",
".",
"debugln",
"(",
"\"",
"\"",
",",
"name",
",",
"len",
"(",
"s",
".",
"peers",
")",
")",
"\n\n",
"// Skip the Peer if it has the same name as the Server",
"if",
"name",
"!=",
"s",
".",
"Name",
"(",
")",
"{",
"// Return error if peer doesn't exist.",
"peer",
":=",
"s",
".",
"peers",
"[",
"name",
"]",
"\n",
"if",
"peer",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n\n",
"// Stop peer and remove it.",
"if",
"s",
".",
"State",
"(",
")",
"==",
"Leader",
"{",
"// We create a go routine here to avoid potential deadlock.",
"// We are holding log write lock when reach this line of code.",
"// Peer.stopHeartbeat can be blocked without go routine, if the",
"// target go routine (which we want to stop) is calling",
"// log.getEntriesAfter and waiting for log read lock.",
"// So we might be holding log lock and waiting for log lock,",
"// which lead to a deadlock.",
"// TODO(xiangli) refactor log lock",
"s",
".",
"routineGroup",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"defer",
"s",
".",
"routineGroup",
".",
"Done",
"(",
")",
"\n",
"peer",
".",
"stopHeartbeat",
"(",
"true",
")",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n\n",
"delete",
"(",
"s",
".",
"peers",
",",
"name",
")",
"\n\n",
"s",
".",
"DispatchEvent",
"(",
"newEvent",
"(",
"RemovePeerEventType",
",",
"name",
",",
"nil",
")",
")",
"\n",
"}",
"\n\n",
"// Write the configuration to file.",
"s",
".",
"writeConf",
"(",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Removes a peer from the server. | [
"Removes",
"a",
"peer",
"from",
"the",
"server",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L1134-L1171 |
147,943 | goraft/raft | server.go | LoadSnapshot | func (s *server) LoadSnapshot() error {
// Open snapshot/ directory.
dir, err := os.OpenFile(path.Join(s.path, "snapshot"), os.O_RDONLY, 0)
if err != nil {
s.debugln("cannot.open.snapshot: ", err)
return err
}
// Retrieve a list of all snapshots.
filenames, err := dir.Readdirnames(-1)
if err != nil {
dir.Close()
panic(err)
}
dir.Close()
if len(filenames) == 0 {
s.debugln("no.snapshot.to.load")
return nil
}
// Grab the latest snapshot.
sort.Strings(filenames)
snapshotPath := path.Join(s.path, "snapshot", filenames[len(filenames)-1])
// Read snapshot data.
file, err := os.OpenFile(snapshotPath, os.O_RDONLY, 0)
if err != nil {
return err
}
defer file.Close()
// Check checksum.
var checksum uint32
n, err := fmt.Fscanf(file, "%08x\n", &checksum)
if err != nil {
return err
} else if n != 1 {
return errors.New("checksum.err: bad.snapshot.file")
}
// Load remaining snapshot contents.
b, err := ioutil.ReadAll(file)
if err != nil {
return err
}
// Generate checksum.
byteChecksum := crc32.ChecksumIEEE(b)
if uint32(checksum) != byteChecksum {
s.debugln(checksum, " ", byteChecksum)
return errors.New("bad snapshot file")
}
// Decode snapshot.
if err = json.Unmarshal(b, &s.snapshot); err != nil {
s.debugln("unmarshal.snapshot.error: ", err)
return err
}
// Recover snapshot into state machine.
if err = s.stateMachine.Recovery(s.snapshot.State); err != nil {
s.debugln("recovery.snapshot.error: ", err)
return err
}
// Recover cluster configuration.
for _, peer := range s.snapshot.Peers {
s.AddPeer(peer.Name, peer.ConnectionString)
}
// Update log state.
s.log.startTerm = s.snapshot.LastTerm
s.log.startIndex = s.snapshot.LastIndex
s.log.updateCommitIndex(s.snapshot.LastIndex)
return err
} | go | func (s *server) LoadSnapshot() error {
// Open snapshot/ directory.
dir, err := os.OpenFile(path.Join(s.path, "snapshot"), os.O_RDONLY, 0)
if err != nil {
s.debugln("cannot.open.snapshot: ", err)
return err
}
// Retrieve a list of all snapshots.
filenames, err := dir.Readdirnames(-1)
if err != nil {
dir.Close()
panic(err)
}
dir.Close()
if len(filenames) == 0 {
s.debugln("no.snapshot.to.load")
return nil
}
// Grab the latest snapshot.
sort.Strings(filenames)
snapshotPath := path.Join(s.path, "snapshot", filenames[len(filenames)-1])
// Read snapshot data.
file, err := os.OpenFile(snapshotPath, os.O_RDONLY, 0)
if err != nil {
return err
}
defer file.Close()
// Check checksum.
var checksum uint32
n, err := fmt.Fscanf(file, "%08x\n", &checksum)
if err != nil {
return err
} else if n != 1 {
return errors.New("checksum.err: bad.snapshot.file")
}
// Load remaining snapshot contents.
b, err := ioutil.ReadAll(file)
if err != nil {
return err
}
// Generate checksum.
byteChecksum := crc32.ChecksumIEEE(b)
if uint32(checksum) != byteChecksum {
s.debugln(checksum, " ", byteChecksum)
return errors.New("bad snapshot file")
}
// Decode snapshot.
if err = json.Unmarshal(b, &s.snapshot); err != nil {
s.debugln("unmarshal.snapshot.error: ", err)
return err
}
// Recover snapshot into state machine.
if err = s.stateMachine.Recovery(s.snapshot.State); err != nil {
s.debugln("recovery.snapshot.error: ", err)
return err
}
// Recover cluster configuration.
for _, peer := range s.snapshot.Peers {
s.AddPeer(peer.Name, peer.ConnectionString)
}
// Update log state.
s.log.startTerm = s.snapshot.LastTerm
s.log.startIndex = s.snapshot.LastIndex
s.log.updateCommitIndex(s.snapshot.LastIndex)
return err
} | [
"func",
"(",
"s",
"*",
"server",
")",
"LoadSnapshot",
"(",
")",
"error",
"{",
"// Open snapshot/ directory.",
"dir",
",",
"err",
":=",
"os",
".",
"OpenFile",
"(",
"path",
".",
"Join",
"(",
"s",
".",
"path",
",",
"\"",
"\"",
")",
",",
"os",
".",
"O_RDONLY",
",",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"s",
".",
"debugln",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// Retrieve a list of all snapshots.",
"filenames",
",",
"err",
":=",
"dir",
".",
"Readdirnames",
"(",
"-",
"1",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"dir",
".",
"Close",
"(",
")",
"\n",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"dir",
".",
"Close",
"(",
")",
"\n\n",
"if",
"len",
"(",
"filenames",
")",
"==",
"0",
"{",
"s",
".",
"debugln",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Grab the latest snapshot.",
"sort",
".",
"Strings",
"(",
"filenames",
")",
"\n",
"snapshotPath",
":=",
"path",
".",
"Join",
"(",
"s",
".",
"path",
",",
"\"",
"\"",
",",
"filenames",
"[",
"len",
"(",
"filenames",
")",
"-",
"1",
"]",
")",
"\n\n",
"// Read snapshot data.",
"file",
",",
"err",
":=",
"os",
".",
"OpenFile",
"(",
"snapshotPath",
",",
"os",
".",
"O_RDONLY",
",",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"file",
".",
"Close",
"(",
")",
"\n\n",
"// Check checksum.",
"var",
"checksum",
"uint32",
"\n",
"n",
",",
"err",
":=",
"fmt",
".",
"Fscanf",
"(",
"file",
",",
"\"",
"\\n",
"\"",
",",
"&",
"checksum",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"else",
"if",
"n",
"!=",
"1",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Load remaining snapshot contents.",
"b",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"file",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Generate checksum.",
"byteChecksum",
":=",
"crc32",
".",
"ChecksumIEEE",
"(",
"b",
")",
"\n",
"if",
"uint32",
"(",
"checksum",
")",
"!=",
"byteChecksum",
"{",
"s",
".",
"debugln",
"(",
"checksum",
",",
"\"",
"\"",
",",
"byteChecksum",
")",
"\n",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Decode snapshot.",
"if",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"b",
",",
"&",
"s",
".",
"snapshot",
")",
";",
"err",
"!=",
"nil",
"{",
"s",
".",
"debugln",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// Recover snapshot into state machine.",
"if",
"err",
"=",
"s",
".",
"stateMachine",
".",
"Recovery",
"(",
"s",
".",
"snapshot",
".",
"State",
")",
";",
"err",
"!=",
"nil",
"{",
"s",
".",
"debugln",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// Recover cluster configuration.",
"for",
"_",
",",
"peer",
":=",
"range",
"s",
".",
"snapshot",
".",
"Peers",
"{",
"s",
".",
"AddPeer",
"(",
"peer",
".",
"Name",
",",
"peer",
".",
"ConnectionString",
")",
"\n",
"}",
"\n\n",
"// Update log state.",
"s",
".",
"log",
".",
"startTerm",
"=",
"s",
".",
"snapshot",
".",
"LastTerm",
"\n",
"s",
".",
"log",
".",
"startIndex",
"=",
"s",
".",
"snapshot",
".",
"LastIndex",
"\n",
"s",
".",
"log",
".",
"updateCommitIndex",
"(",
"s",
".",
"snapshot",
".",
"LastIndex",
")",
"\n\n",
"return",
"err",
"\n",
"}"
] | // Load a snapshot at restart | [
"Load",
"a",
"snapshot",
"at",
"restart"
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L1316-L1393 |
147,944 | goraft/raft | server.go | readConf | func (s *server) readConf() error {
confPath := path.Join(s.path, "conf")
s.debugln("readConf.open ", confPath)
// open conf file
b, err := ioutil.ReadFile(confPath)
if err != nil {
return nil
}
conf := &Config{}
if err = json.Unmarshal(b, conf); err != nil {
return err
}
s.log.updateCommitIndex(conf.CommitIndex)
return nil
} | go | func (s *server) readConf() error {
confPath := path.Join(s.path, "conf")
s.debugln("readConf.open ", confPath)
// open conf file
b, err := ioutil.ReadFile(confPath)
if err != nil {
return nil
}
conf := &Config{}
if err = json.Unmarshal(b, conf); err != nil {
return err
}
s.log.updateCommitIndex(conf.CommitIndex)
return nil
} | [
"func",
"(",
"s",
"*",
"server",
")",
"readConf",
"(",
")",
"error",
"{",
"confPath",
":=",
"path",
".",
"Join",
"(",
"s",
".",
"path",
",",
"\"",
"\"",
")",
"\n",
"s",
".",
"debugln",
"(",
"\"",
"\"",
",",
"confPath",
")",
"\n\n",
"// open conf file",
"b",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"confPath",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"conf",
":=",
"&",
"Config",
"{",
"}",
"\n\n",
"if",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"b",
",",
"conf",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"s",
".",
"log",
".",
"updateCommitIndex",
"(",
"conf",
".",
"CommitIndex",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Read the configuration for the server. | [
"Read",
"the",
"configuration",
"for",
"the",
"server",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/server.go#L1437-L1457 |
147,945 | goraft/raft | event.go | newEvent | func newEvent(typ string, value interface{}, prevValue interface{}) *event {
return &event{
typ: typ,
value: value,
prevValue: prevValue,
}
} | go | func newEvent(typ string, value interface{}, prevValue interface{}) *event {
return &event{
typ: typ,
value: value,
prevValue: prevValue,
}
} | [
"func",
"newEvent",
"(",
"typ",
"string",
",",
"value",
"interface",
"{",
"}",
",",
"prevValue",
"interface",
"{",
"}",
")",
"*",
"event",
"{",
"return",
"&",
"event",
"{",
"typ",
":",
"typ",
",",
"value",
":",
"value",
",",
"prevValue",
":",
"prevValue",
",",
"}",
"\n",
"}"
] | // newEvent creates a new event. | [
"newEvent",
"creates",
"a",
"new",
"event",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/event.go#L35-L41 |
147,946 | goraft/raft | peer.go | setPrevLogIndex | func (p *Peer) setPrevLogIndex(value uint64) {
p.Lock()
defer p.Unlock()
p.prevLogIndex = value
} | go | func (p *Peer) setPrevLogIndex(value uint64) {
p.Lock()
defer p.Unlock()
p.prevLogIndex = value
} | [
"func",
"(",
"p",
"*",
"Peer",
")",
"setPrevLogIndex",
"(",
"value",
"uint64",
")",
"{",
"p",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"Unlock",
"(",
")",
"\n",
"p",
".",
"prevLogIndex",
"=",
"value",
"\n",
"}"
] | // Sets the previous log index. | [
"Sets",
"the",
"previous",
"log",
"index",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/peer.go#L65-L69 |
147,947 | goraft/raft | peer.go | stopHeartbeat | func (p *Peer) stopHeartbeat(flush bool) {
p.setLastActivity(time.Time{})
p.stopChan <- flush
} | go | func (p *Peer) stopHeartbeat(flush bool) {
p.setLastActivity(time.Time{})
p.stopChan <- flush
} | [
"func",
"(",
"p",
"*",
"Peer",
")",
"stopHeartbeat",
"(",
"flush",
"bool",
")",
"{",
"p",
".",
"setLastActivity",
"(",
"time",
".",
"Time",
"{",
"}",
")",
"\n\n",
"p",
".",
"stopChan",
"<-",
"flush",
"\n",
"}"
] | // Stops the peer heartbeat. | [
"Stops",
"the",
"peer",
"heartbeat",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/peer.go#L103-L107 |
147,948 | goraft/raft | peer.go | LastActivity | func (p *Peer) LastActivity() time.Time {
p.RLock()
defer p.RUnlock()
return p.lastActivity
} | go | func (p *Peer) LastActivity() time.Time {
p.RLock()
defer p.RUnlock()
return p.lastActivity
} | [
"func",
"(",
"p",
"*",
"Peer",
")",
"LastActivity",
"(",
")",
"time",
".",
"Time",
"{",
"p",
".",
"RLock",
"(",
")",
"\n",
"defer",
"p",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"p",
".",
"lastActivity",
"\n",
"}"
] | // LastActivity returns the last time any response was received from the peer. | [
"LastActivity",
"returns",
"the",
"last",
"time",
"any",
"response",
"was",
"received",
"from",
"the",
"peer",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/peer.go#L110-L114 |
147,949 | goraft/raft | peer.go | sendSnapshotRequest | func (p *Peer) sendSnapshotRequest(req *SnapshotRequest) {
debugln("peer.snap.send: ", p.Name)
resp := p.server.Transporter().SendSnapshotRequest(p.server, p, req)
if resp == nil {
debugln("peer.snap.timeout: ", p.Name)
return
}
debugln("peer.snap.recv: ", p.Name)
// If successful, the peer should have been to snapshot state
// Send it the snapshot!
p.setLastActivity(time.Now())
if resp.Success {
p.sendSnapshotRecoveryRequest()
} else {
debugln("peer.snap.failed: ", p.Name)
return
}
} | go | func (p *Peer) sendSnapshotRequest(req *SnapshotRequest) {
debugln("peer.snap.send: ", p.Name)
resp := p.server.Transporter().SendSnapshotRequest(p.server, p, req)
if resp == nil {
debugln("peer.snap.timeout: ", p.Name)
return
}
debugln("peer.snap.recv: ", p.Name)
// If successful, the peer should have been to snapshot state
// Send it the snapshot!
p.setLastActivity(time.Now())
if resp.Success {
p.sendSnapshotRecoveryRequest()
} else {
debugln("peer.snap.failed: ", p.Name)
return
}
} | [
"func",
"(",
"p",
"*",
"Peer",
")",
"sendSnapshotRequest",
"(",
"req",
"*",
"SnapshotRequest",
")",
"{",
"debugln",
"(",
"\"",
"\"",
",",
"p",
".",
"Name",
")",
"\n\n",
"resp",
":=",
"p",
".",
"server",
".",
"Transporter",
"(",
")",
".",
"SendSnapshotRequest",
"(",
"p",
".",
"server",
",",
"p",
",",
"req",
")",
"\n",
"if",
"resp",
"==",
"nil",
"{",
"debugln",
"(",
"\"",
"\"",
",",
"p",
".",
"Name",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"debugln",
"(",
"\"",
"\"",
",",
"p",
".",
"Name",
")",
"\n\n",
"// If successful, the peer should have been to snapshot state",
"// Send it the snapshot!",
"p",
".",
"setLastActivity",
"(",
"time",
".",
"Now",
"(",
")",
")",
"\n\n",
"if",
"resp",
".",
"Success",
"{",
"p",
".",
"sendSnapshotRecoveryRequest",
"(",
")",
"\n",
"}",
"else",
"{",
"debugln",
"(",
"\"",
"\"",
",",
"p",
".",
"Name",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"}"
] | // Sends an Snapshot request to the peer through the transport. | [
"Sends",
"an",
"Snapshot",
"request",
"to",
"the",
"peer",
"through",
"the",
"transport",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/peer.go#L258-L280 |
147,950 | goraft/raft | peer.go | sendSnapshotRecoveryRequest | func (p *Peer) sendSnapshotRecoveryRequest() {
req := newSnapshotRecoveryRequest(p.server.name, p.server.snapshot)
debugln("peer.snap.recovery.send: ", p.Name)
resp := p.server.Transporter().SendSnapshotRecoveryRequest(p.server, p, req)
if resp == nil {
debugln("peer.snap.recovery.timeout: ", p.Name)
return
}
p.setLastActivity(time.Now())
if resp.Success {
p.prevLogIndex = req.LastIndex
} else {
debugln("peer.snap.recovery.failed: ", p.Name)
return
}
p.server.sendAsync(resp)
} | go | func (p *Peer) sendSnapshotRecoveryRequest() {
req := newSnapshotRecoveryRequest(p.server.name, p.server.snapshot)
debugln("peer.snap.recovery.send: ", p.Name)
resp := p.server.Transporter().SendSnapshotRecoveryRequest(p.server, p, req)
if resp == nil {
debugln("peer.snap.recovery.timeout: ", p.Name)
return
}
p.setLastActivity(time.Now())
if resp.Success {
p.prevLogIndex = req.LastIndex
} else {
debugln("peer.snap.recovery.failed: ", p.Name)
return
}
p.server.sendAsync(resp)
} | [
"func",
"(",
"p",
"*",
"Peer",
")",
"sendSnapshotRecoveryRequest",
"(",
")",
"{",
"req",
":=",
"newSnapshotRecoveryRequest",
"(",
"p",
".",
"server",
".",
"name",
",",
"p",
".",
"server",
".",
"snapshot",
")",
"\n",
"debugln",
"(",
"\"",
"\"",
",",
"p",
".",
"Name",
")",
"\n",
"resp",
":=",
"p",
".",
"server",
".",
"Transporter",
"(",
")",
".",
"SendSnapshotRecoveryRequest",
"(",
"p",
".",
"server",
",",
"p",
",",
"req",
")",
"\n\n",
"if",
"resp",
"==",
"nil",
"{",
"debugln",
"(",
"\"",
"\"",
",",
"p",
".",
"Name",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"p",
".",
"setLastActivity",
"(",
"time",
".",
"Now",
"(",
")",
")",
"\n",
"if",
"resp",
".",
"Success",
"{",
"p",
".",
"prevLogIndex",
"=",
"req",
".",
"LastIndex",
"\n",
"}",
"else",
"{",
"debugln",
"(",
"\"",
"\"",
",",
"p",
".",
"Name",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"p",
".",
"server",
".",
"sendAsync",
"(",
"resp",
")",
"\n",
"}"
] | // Sends an Snapshot Recovery request to the peer through the transport. | [
"Sends",
"an",
"Snapshot",
"Recovery",
"request",
"to",
"the",
"peer",
"through",
"the",
"transport",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/peer.go#L283-L302 |
147,951 | goraft/raft | debug.go | debugf | func debugf(format string, v ...interface{}) {
if logLevel >= Debug {
logger.Printf(format, v...)
}
} | go | func debugf(format string, v ...interface{}) {
if logLevel >= Debug {
logger.Printf(format, v...)
}
} | [
"func",
"debugf",
"(",
"format",
"string",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"if",
"logLevel",
">=",
"Debug",
"{",
"logger",
".",
"Printf",
"(",
"format",
",",
"v",
"...",
")",
"\n",
"}",
"\n",
"}"
] | // Prints to the standard logger if debug mode is enabled. Arguments
// are handled in the manner of fmt.Printf. | [
"Prints",
"to",
"the",
"standard",
"logger",
"if",
"debug",
"mode",
"is",
"enabled",
".",
"Arguments",
"are",
"handled",
"in",
"the",
"manner",
"of",
"fmt",
".",
"Printf",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/debug.go#L76-L80 |
147,952 | goraft/raft | debug.go | tracef | func tracef(format string, v ...interface{}) {
if logLevel >= Trace {
logger.Printf(format, v...)
}
} | go | func tracef(format string, v ...interface{}) {
if logLevel >= Trace {
logger.Printf(format, v...)
}
} | [
"func",
"tracef",
"(",
"format",
"string",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"if",
"logLevel",
">=",
"Trace",
"{",
"logger",
".",
"Printf",
"(",
"format",
",",
"v",
"...",
")",
"\n",
"}",
"\n",
"}"
] | // Prints to the standard logger if trace debugging is enabled. Arguments
// are handled in the manner of fmt.Printf. | [
"Prints",
"to",
"the",
"standard",
"logger",
"if",
"trace",
"debugging",
"is",
"enabled",
".",
"Arguments",
"are",
"handled",
"in",
"the",
"manner",
"of",
"fmt",
".",
"Printf",
"."
] | 0061b6c82526bd96292f41fa72358ec13ee3853c | https://github.com/goraft/raft/blob/0061b6c82526bd96292f41fa72358ec13ee3853c/debug.go#L104-L108 |
147,953 | tebeka/selenium | common.go | filteredURL | func filteredURL(u string) string {
// Hide password if set in URL
m, err := url.Parse(u)
if err != nil {
return ""
}
if m.User != nil {
if _, ok := m.User.Password(); ok {
m.User = url.UserPassword(m.User.Username(), "__password__")
}
}
return m.String()
} | go | func filteredURL(u string) string {
// Hide password if set in URL
m, err := url.Parse(u)
if err != nil {
return ""
}
if m.User != nil {
if _, ok := m.User.Password(); ok {
m.User = url.UserPassword(m.User.Username(), "__password__")
}
}
return m.String()
} | [
"func",
"filteredURL",
"(",
"u",
"string",
")",
"string",
"{",
"// Hide password if set in URL",
"m",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"u",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"m",
".",
"User",
"!=",
"nil",
"{",
"if",
"_",
",",
"ok",
":=",
"m",
".",
"User",
".",
"Password",
"(",
")",
";",
"ok",
"{",
"m",
".",
"User",
"=",
"url",
".",
"UserPassword",
"(",
"m",
".",
"User",
".",
"Username",
"(",
")",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"m",
".",
"String",
"(",
")",
"\n",
"}"
] | // filteredURL replaces existing password from the given URL. | [
"filteredURL",
"replaces",
"existing",
"password",
"from",
"the",
"given",
"URL",
"."
] | edf31bb7fd715ad505d9190f8d65d13f39a7c825 | https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/common.go#L23-L35 |
147,954 | tebeka/selenium | selenium.go | AddChrome | func (c Capabilities) AddChrome(f chrome.Capabilities) {
c[chrome.CapabilitiesKey] = f
c[chrome.DeprecatedCapabilitiesKey] = f
} | go | func (c Capabilities) AddChrome(f chrome.Capabilities) {
c[chrome.CapabilitiesKey] = f
c[chrome.DeprecatedCapabilitiesKey] = f
} | [
"func",
"(",
"c",
"Capabilities",
")",
"AddChrome",
"(",
"f",
"chrome",
".",
"Capabilities",
")",
"{",
"c",
"[",
"chrome",
".",
"CapabilitiesKey",
"]",
"=",
"f",
"\n",
"c",
"[",
"chrome",
".",
"DeprecatedCapabilitiesKey",
"]",
"=",
"f",
"\n",
"}"
] | // AddChrome adds Chrome-specific capabilities. | [
"AddChrome",
"adds",
"Chrome",
"-",
"specific",
"capabilities",
"."
] | edf31bb7fd715ad505d9190f8d65d13f39a7c825 | https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/selenium.go#L96-L99 |
147,955 | tebeka/selenium | selenium.go | AddFirefox | func (c Capabilities) AddFirefox(f firefox.Capabilities) {
c[firefox.CapabilitiesKey] = f
} | go | func (c Capabilities) AddFirefox(f firefox.Capabilities) {
c[firefox.CapabilitiesKey] = f
} | [
"func",
"(",
"c",
"Capabilities",
")",
"AddFirefox",
"(",
"f",
"firefox",
".",
"Capabilities",
")",
"{",
"c",
"[",
"firefox",
".",
"CapabilitiesKey",
"]",
"=",
"f",
"\n",
"}"
] | // AddFirefox adds Firefox-specific capabilities. | [
"AddFirefox",
"adds",
"Firefox",
"-",
"specific",
"capabilities",
"."
] | edf31bb7fd715ad505d9190f8d65d13f39a7c825 | https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/selenium.go#L102-L104 |
147,956 | tebeka/selenium | selenium.go | AddLogging | func (c Capabilities) AddLogging(l log.Capabilities) {
c[log.CapabilitiesKey] = l
} | go | func (c Capabilities) AddLogging(l log.Capabilities) {
c[log.CapabilitiesKey] = l
} | [
"func",
"(",
"c",
"Capabilities",
")",
"AddLogging",
"(",
"l",
"log",
".",
"Capabilities",
")",
"{",
"c",
"[",
"log",
".",
"CapabilitiesKey",
"]",
"=",
"l",
"\n",
"}"
] | // AddLogging adds logging configuration to the capabilities. | [
"AddLogging",
"adds",
"logging",
"configuration",
"to",
"the",
"capabilities",
"."
] | edf31bb7fd715ad505d9190f8d65d13f39a7c825 | https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/selenium.go#L112-L114 |
147,957 | tebeka/selenium | selenium.go | SetLogLevel | func (c Capabilities) SetLogLevel(typ log.Type, level log.Level) {
if _, ok := c[log.CapabilitiesKey]; !ok {
c[log.CapabilitiesKey] = make(log.Capabilities)
}
m := c[log.CapabilitiesKey].(log.Capabilities)
m[typ] = level
} | go | func (c Capabilities) SetLogLevel(typ log.Type, level log.Level) {
if _, ok := c[log.CapabilitiesKey]; !ok {
c[log.CapabilitiesKey] = make(log.Capabilities)
}
m := c[log.CapabilitiesKey].(log.Capabilities)
m[typ] = level
} | [
"func",
"(",
"c",
"Capabilities",
")",
"SetLogLevel",
"(",
"typ",
"log",
".",
"Type",
",",
"level",
"log",
".",
"Level",
")",
"{",
"if",
"_",
",",
"ok",
":=",
"c",
"[",
"log",
".",
"CapabilitiesKey",
"]",
";",
"!",
"ok",
"{",
"c",
"[",
"log",
".",
"CapabilitiesKey",
"]",
"=",
"make",
"(",
"log",
".",
"Capabilities",
")",
"\n",
"}",
"\n",
"m",
":=",
"c",
"[",
"log",
".",
"CapabilitiesKey",
"]",
".",
"(",
"log",
".",
"Capabilities",
")",
"\n",
"m",
"[",
"typ",
"]",
"=",
"level",
"\n",
"}"
] | // SetLogLevel sets the logging level of a component. It is a shortcut for
// passing a log.Capabilities instance to AddLogging. | [
"SetLogLevel",
"sets",
"the",
"logging",
"level",
"of",
"a",
"component",
".",
"It",
"is",
"a",
"shortcut",
"for",
"passing",
"a",
"log",
".",
"Capabilities",
"instance",
"to",
"AddLogging",
"."
] | edf31bb7fd715ad505d9190f8d65d13f39a7c825 | https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/selenium.go#L118-L124 |
147,958 | tebeka/selenium | service.go | Display | func Display(d, xauthPath string) ServiceOption {
return func(s *Service) error {
if s.display != "" {
return fmt.Errorf("service display already set: %v", s.display)
}
if s.xauthPath != "" {
return fmt.Errorf("service xauth path already set: %v", s.xauthPath)
}
if !isDisplay(d) {
return fmt.Errorf("supplied display %q must be of the format 'x' or 'x.y' where x and y are integers", d)
}
s.display = d
s.xauthPath = xauthPath
return nil
}
} | go | func Display(d, xauthPath string) ServiceOption {
return func(s *Service) error {
if s.display != "" {
return fmt.Errorf("service display already set: %v", s.display)
}
if s.xauthPath != "" {
return fmt.Errorf("service xauth path already set: %v", s.xauthPath)
}
if !isDisplay(d) {
return fmt.Errorf("supplied display %q must be of the format 'x' or 'x.y' where x and y are integers", d)
}
s.display = d
s.xauthPath = xauthPath
return nil
}
} | [
"func",
"Display",
"(",
"d",
",",
"xauthPath",
"string",
")",
"ServiceOption",
"{",
"return",
"func",
"(",
"s",
"*",
"Service",
")",
"error",
"{",
"if",
"s",
".",
"display",
"!=",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"s",
".",
"display",
")",
"\n",
"}",
"\n",
"if",
"s",
".",
"xauthPath",
"!=",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"s",
".",
"xauthPath",
")",
"\n",
"}",
"\n",
"if",
"!",
"isDisplay",
"(",
"d",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"d",
")",
"\n",
"}",
"\n",
"s",
".",
"display",
"=",
"d",
"\n",
"s",
".",
"xauthPath",
"=",
"xauthPath",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // Display specifies the value to which set the DISPLAY environment variable,
// as well as the path to the Xauthority file containing credentials needed to
// write to that X server. | [
"Display",
"specifies",
"the",
"value",
"to",
"which",
"set",
"the",
"DISPLAY",
"environment",
"variable",
"as",
"well",
"as",
"the",
"path",
"to",
"the",
"Xauthority",
"file",
"containing",
"credentials",
"needed",
"to",
"write",
"to",
"that",
"X",
"server",
"."
] | edf31bb7fd715ad505d9190f8d65d13f39a7c825 | https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/service.go#L24-L39 |
147,959 | tebeka/selenium | service.go | isDisplay | func isDisplay(disp string) bool {
ds := strings.Split(disp, ".")
if len(ds) > 2 {
return false
}
for _, d := range ds {
if _, err := strconv.Atoi(d); err != nil {
return false
}
}
return true
} | go | func isDisplay(disp string) bool {
ds := strings.Split(disp, ".")
if len(ds) > 2 {
return false
}
for _, d := range ds {
if _, err := strconv.Atoi(d); err != nil {
return false
}
}
return true
} | [
"func",
"isDisplay",
"(",
"disp",
"string",
")",
"bool",
"{",
"ds",
":=",
"strings",
".",
"Split",
"(",
"disp",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"ds",
")",
">",
"2",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"d",
":=",
"range",
"ds",
"{",
"if",
"_",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"d",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // isDisplay validates that the given disp is in the format "x" or "x.y", where
// x and y are both integers. | [
"isDisplay",
"validates",
"that",
"the",
"given",
"disp",
"is",
"in",
"the",
"format",
"x",
"or",
"x",
".",
"y",
"where",
"x",
"and",
"y",
"are",
"both",
"integers",
"."
] | edf31bb7fd715ad505d9190f8d65d13f39a7c825 | https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/service.go#L43-L55 |
147,960 | tebeka/selenium | service.go | StartFrameBufferWithOptions | func StartFrameBufferWithOptions(options FrameBufferOptions) ServiceOption {
return func(s *Service) error {
if s.display != "" {
return fmt.Errorf("service display already set: %v", s.display)
}
if s.xauthPath != "" {
return fmt.Errorf("service xauth path already set: %v", s.xauthPath)
}
if s.xvfb != nil {
return fmt.Errorf("service Xvfb instance already running")
}
fb, err := NewFrameBufferWithOptions(options)
if err != nil {
return fmt.Errorf("error starting frame buffer: %v", err)
}
s.xvfb = fb
return Display(fb.Display, fb.AuthPath)(s)
}
} | go | func StartFrameBufferWithOptions(options FrameBufferOptions) ServiceOption {
return func(s *Service) error {
if s.display != "" {
return fmt.Errorf("service display already set: %v", s.display)
}
if s.xauthPath != "" {
return fmt.Errorf("service xauth path already set: %v", s.xauthPath)
}
if s.xvfb != nil {
return fmt.Errorf("service Xvfb instance already running")
}
fb, err := NewFrameBufferWithOptions(options)
if err != nil {
return fmt.Errorf("error starting frame buffer: %v", err)
}
s.xvfb = fb
return Display(fb.Display, fb.AuthPath)(s)
}
} | [
"func",
"StartFrameBufferWithOptions",
"(",
"options",
"FrameBufferOptions",
")",
"ServiceOption",
"{",
"return",
"func",
"(",
"s",
"*",
"Service",
")",
"error",
"{",
"if",
"s",
".",
"display",
"!=",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"s",
".",
"display",
")",
"\n",
"}",
"\n",
"if",
"s",
".",
"xauthPath",
"!=",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"s",
".",
"xauthPath",
")",
"\n",
"}",
"\n",
"if",
"s",
".",
"xvfb",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"fb",
",",
"err",
":=",
"NewFrameBufferWithOptions",
"(",
"options",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"s",
".",
"xvfb",
"=",
"fb",
"\n",
"return",
"Display",
"(",
"fb",
".",
"Display",
",",
"fb",
".",
"AuthPath",
")",
"(",
"s",
")",
"\n",
"}",
"\n",
"}"
] | // StartFrameBufferWithOptions causes an X virtual frame buffer to start before
// the WebDriver service. The frame buffer process will be terminated when the
// service itself is stopped. | [
"StartFrameBufferWithOptions",
"causes",
"an",
"X",
"virtual",
"frame",
"buffer",
"to",
"start",
"before",
"the",
"WebDriver",
"service",
".",
"The",
"frame",
"buffer",
"process",
"will",
"be",
"terminated",
"when",
"the",
"service",
"itself",
"is",
"stopped",
"."
] | edf31bb7fd715ad505d9190f8d65d13f39a7c825 | https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/service.go#L77-L95 |
147,961 | tebeka/selenium | service.go | Output | func Output(w io.Writer) ServiceOption {
return func(s *Service) error {
s.output = w
return nil
}
} | go | func Output(w io.Writer) ServiceOption {
return func(s *Service) error {
s.output = w
return nil
}
} | [
"func",
"Output",
"(",
"w",
"io",
".",
"Writer",
")",
"ServiceOption",
"{",
"return",
"func",
"(",
"s",
"*",
"Service",
")",
"error",
"{",
"s",
".",
"output",
"=",
"w",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // Output specifies that the WebDriver service should log to the provided
// writer. | [
"Output",
"specifies",
"that",
"the",
"WebDriver",
"service",
"should",
"log",
"to",
"the",
"provided",
"writer",
"."
] | edf31bb7fd715ad505d9190f8d65d13f39a7c825 | https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/service.go#L99-L104 |
147,962 | tebeka/selenium | service.go | GeckoDriver | func GeckoDriver(path string) ServiceOption {
return func(s *Service) error {
s.geckoDriverPath = path
return nil
}
} | go | func GeckoDriver(path string) ServiceOption {
return func(s *Service) error {
s.geckoDriverPath = path
return nil
}
} | [
"func",
"GeckoDriver",
"(",
"path",
"string",
")",
"ServiceOption",
"{",
"return",
"func",
"(",
"s",
"*",
"Service",
")",
"error",
"{",
"s",
".",
"geckoDriverPath",
"=",
"path",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // GeckoDriver sets the path to the geckodriver binary for the Selenium Server.
// Unlike other drivers, Selenium Server does not support specifying the
// geckodriver path at runtime. This ServiceOption is only useful when calling
// NewSeleniumService. | [
"GeckoDriver",
"sets",
"the",
"path",
"to",
"the",
"geckodriver",
"binary",
"for",
"the",
"Selenium",
"Server",
".",
"Unlike",
"other",
"drivers",
"Selenium",
"Server",
"does",
"not",
"support",
"specifying",
"the",
"geckodriver",
"path",
"at",
"runtime",
".",
"This",
"ServiceOption",
"is",
"only",
"useful",
"when",
"calling",
"NewSeleniumService",
"."
] | edf31bb7fd715ad505d9190f8d65d13f39a7c825 | https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/service.go#L110-L115 |
147,963 | tebeka/selenium | service.go | JavaPath | func JavaPath(path string) ServiceOption {
return func(s *Service) error {
s.javaPath = path
return nil
}
} | go | func JavaPath(path string) ServiceOption {
return func(s *Service) error {
s.javaPath = path
return nil
}
} | [
"func",
"JavaPath",
"(",
"path",
"string",
")",
"ServiceOption",
"{",
"return",
"func",
"(",
"s",
"*",
"Service",
")",
"error",
"{",
"s",
".",
"javaPath",
"=",
"path",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // JavaPath specifies the path to the JRE for a Selenium service. | [
"JavaPath",
"specifies",
"the",
"path",
"to",
"the",
"JRE",
"for",
"a",
"Selenium",
"service",
"."
] | edf31bb7fd715ad505d9190f8d65d13f39a7c825 | https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/service.go#L125-L130 |
147,964 | tebeka/selenium | service.go | NewSeleniumService | func NewSeleniumService(jarPath string, port int, opts ...ServiceOption) (*Service, error) {
cmd := exec.Command("java", "-jar", jarPath, "-port", strconv.Itoa(port))
s, err := newService(cmd, "/wd/hub", port, opts...)
if err != nil {
return nil, err
}
if s.javaPath != "" {
s.cmd.Path = s.javaPath
}
if s.geckoDriverPath != "" {
s.cmd.Args = append([]string{"java", "-Dwebdriver.gecko.driver=" + s.geckoDriverPath}, cmd.Args[1:]...)
}
if s.chromeDriverPath != "" {
s.cmd.Args = append([]string{"java", "-Dwebdriver.chrome.driver=" + s.chromeDriverPath}, cmd.Args[1:]...)
}
if err := s.start(port); err != nil {
return nil, err
}
return s, nil
} | go | func NewSeleniumService(jarPath string, port int, opts ...ServiceOption) (*Service, error) {
cmd := exec.Command("java", "-jar", jarPath, "-port", strconv.Itoa(port))
s, err := newService(cmd, "/wd/hub", port, opts...)
if err != nil {
return nil, err
}
if s.javaPath != "" {
s.cmd.Path = s.javaPath
}
if s.geckoDriverPath != "" {
s.cmd.Args = append([]string{"java", "-Dwebdriver.gecko.driver=" + s.geckoDriverPath}, cmd.Args[1:]...)
}
if s.chromeDriverPath != "" {
s.cmd.Args = append([]string{"java", "-Dwebdriver.chrome.driver=" + s.chromeDriverPath}, cmd.Args[1:]...)
}
if err := s.start(port); err != nil {
return nil, err
}
return s, nil
} | [
"func",
"NewSeleniumService",
"(",
"jarPath",
"string",
",",
"port",
"int",
",",
"opts",
"...",
"ServiceOption",
")",
"(",
"*",
"Service",
",",
"error",
")",
"{",
"cmd",
":=",
"exec",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"jarPath",
",",
"\"",
"\"",
",",
"strconv",
".",
"Itoa",
"(",
"port",
")",
")",
"\n",
"s",
",",
"err",
":=",
"newService",
"(",
"cmd",
",",
"\"",
"\"",
",",
"port",
",",
"opts",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"s",
".",
"javaPath",
"!=",
"\"",
"\"",
"{",
"s",
".",
"cmd",
".",
"Path",
"=",
"s",
".",
"javaPath",
"\n",
"}",
"\n",
"if",
"s",
".",
"geckoDriverPath",
"!=",
"\"",
"\"",
"{",
"s",
".",
"cmd",
".",
"Args",
"=",
"append",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"+",
"s",
".",
"geckoDriverPath",
"}",
",",
"cmd",
".",
"Args",
"[",
"1",
":",
"]",
"...",
")",
"\n",
"}",
"\n",
"if",
"s",
".",
"chromeDriverPath",
"!=",
"\"",
"\"",
"{",
"s",
".",
"cmd",
".",
"Args",
"=",
"append",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"+",
"s",
".",
"chromeDriverPath",
"}",
",",
"cmd",
".",
"Args",
"[",
"1",
":",
"]",
"...",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"s",
".",
"start",
"(",
"port",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"s",
",",
"nil",
"\n",
"}"
] | // NewSeleniumService starts a Selenium instance in the background. | [
"NewSeleniumService",
"starts",
"a",
"Selenium",
"instance",
"in",
"the",
"background",
"."
] | edf31bb7fd715ad505d9190f8d65d13f39a7c825 | https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/service.go#L154-L173 |
147,965 | tebeka/selenium | service.go | NewChromeDriverService | func NewChromeDriverService(path string, port int, opts ...ServiceOption) (*Service, error) {
cmd := exec.Command(path, "--port="+strconv.Itoa(port), "--url-base=wd/hub", "--verbose")
s, err := newService(cmd, "/wd/hub", port, opts...)
if err != nil {
return nil, err
}
s.shutdownURLPath = "/shutdown"
if err := s.start(port); err != nil {
return nil, err
}
return s, nil
} | go | func NewChromeDriverService(path string, port int, opts ...ServiceOption) (*Service, error) {
cmd := exec.Command(path, "--port="+strconv.Itoa(port), "--url-base=wd/hub", "--verbose")
s, err := newService(cmd, "/wd/hub", port, opts...)
if err != nil {
return nil, err
}
s.shutdownURLPath = "/shutdown"
if err := s.start(port); err != nil {
return nil, err
}
return s, nil
} | [
"func",
"NewChromeDriverService",
"(",
"path",
"string",
",",
"port",
"int",
",",
"opts",
"...",
"ServiceOption",
")",
"(",
"*",
"Service",
",",
"error",
")",
"{",
"cmd",
":=",
"exec",
".",
"Command",
"(",
"path",
",",
"\"",
"\"",
"+",
"strconv",
".",
"Itoa",
"(",
"port",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"s",
",",
"err",
":=",
"newService",
"(",
"cmd",
",",
"\"",
"\"",
",",
"port",
",",
"opts",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"s",
".",
"shutdownURLPath",
"=",
"\"",
"\"",
"\n",
"if",
"err",
":=",
"s",
".",
"start",
"(",
"port",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"s",
",",
"nil",
"\n",
"}"
] | // NewChromeDriverService starts a ChromeDriver instance in the background. | [
"NewChromeDriverService",
"starts",
"a",
"ChromeDriver",
"instance",
"in",
"the",
"background",
"."
] | edf31bb7fd715ad505d9190f8d65d13f39a7c825 | https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/service.go#L176-L187 |
147,966 | tebeka/selenium | service.go | Stop | func (s *Service) Stop() error {
// Selenium 3 stopped supporting the shutdown URL by default.
// https://github.com/SeleniumHQ/selenium/issues/2852
if s.shutdownURLPath == "" {
if err := s.cmd.Process.Kill(); err != nil {
return err
}
} else {
resp, err := http.Get(s.addr + s.shutdownURLPath)
if err != nil {
return err
}
resp.Body.Close()
}
if err := s.cmd.Wait(); err != nil && err.Error() != "signal: killed" {
return err
}
if s.xvfb != nil {
return s.xvfb.Stop()
}
return nil
} | go | func (s *Service) Stop() error {
// Selenium 3 stopped supporting the shutdown URL by default.
// https://github.com/SeleniumHQ/selenium/issues/2852
if s.shutdownURLPath == "" {
if err := s.cmd.Process.Kill(); err != nil {
return err
}
} else {
resp, err := http.Get(s.addr + s.shutdownURLPath)
if err != nil {
return err
}
resp.Body.Close()
}
if err := s.cmd.Wait(); err != nil && err.Error() != "signal: killed" {
return err
}
if s.xvfb != nil {
return s.xvfb.Stop()
}
return nil
} | [
"func",
"(",
"s",
"*",
"Service",
")",
"Stop",
"(",
")",
"error",
"{",
"// Selenium 3 stopped supporting the shutdown URL by default.",
"// https://github.com/SeleniumHQ/selenium/issues/2852",
"if",
"s",
".",
"shutdownURLPath",
"==",
"\"",
"\"",
"{",
"if",
"err",
":=",
"s",
".",
"cmd",
".",
"Process",
".",
"Kill",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"else",
"{",
"resp",
",",
"err",
":=",
"http",
".",
"Get",
"(",
"s",
".",
"addr",
"+",
"s",
".",
"shutdownURLPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"s",
".",
"cmd",
".",
"Wait",
"(",
")",
";",
"err",
"!=",
"nil",
"&&",
"err",
".",
"Error",
"(",
")",
"!=",
"\"",
"\"",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"s",
".",
"xvfb",
"!=",
"nil",
"{",
"return",
"s",
".",
"xvfb",
".",
"Stop",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Stop shuts down the WebDriver service, and the X virtual frame buffer
// if one was started. | [
"Stop",
"shuts",
"down",
"the",
"WebDriver",
"service",
"and",
"the",
"X",
"virtual",
"frame",
"buffer",
"if",
"one",
"was",
"started",
"."
] | edf31bb7fd715ad505d9190f8d65d13f39a7c825 | https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/service.go#L250-L271 |
147,967 | tebeka/selenium | service.go | NewFrameBufferWithOptions | func NewFrameBufferWithOptions(options FrameBufferOptions) (*FrameBuffer, error) {
r, w, err := os.Pipe()
if err != nil {
return nil, err
}
defer r.Close()
auth, err := ioutil.TempFile("", "selenium-xvfb")
if err != nil {
return nil, err
}
authPath := auth.Name()
if err := auth.Close(); err != nil {
return nil, err
}
// Xvfb will print the display on which it is listening to file descriptor 3,
// for which we provide a pipe.
arguments := []string{"-displayfd", "3", "-nolisten", "tcp"}
if options.ScreenSize != "" {
var screenSizeExpression = regexp.MustCompile(`^\d+x\d+(?:x\d+)$`)
if !screenSizeExpression.MatchString(options.ScreenSize) {
return nil, fmt.Errorf("invalid screen size: expected 'WxH[xD]', got %q", options.ScreenSize)
}
arguments = append(arguments, "-screen", "0", options.ScreenSize)
}
xvfb := exec.Command("Xvfb", arguments...)
xvfb.ExtraFiles = []*os.File{w}
// TODO(minusnine): plumb a way to set xvfb.Std{err,out} conditionally.
// TODO(minusnine): Pdeathsig is only supported on Linux. Somehow, make sure
// process cleanup happens as gracefully as possible.
xvfb.Env = append(xvfb.Env, "XAUTHORITY="+authPath)
if err := xvfb.Start(); err != nil {
return nil, err
}
w.Close()
type resp struct {
display string
err error
}
ch := make(chan resp)
go func() {
bufr := bufio.NewReader(r)
s, err := bufr.ReadString('\n')
ch <- resp{s, err}
}()
var display string
select {
case resp := <-ch:
if resp.err != nil {
return nil, resp.err
}
display = strings.TrimSpace(resp.display)
if _, err := strconv.Atoi(display); err != nil {
return nil, errors.New("Xvfb did not print the display number")
}
case <-time.After(3 * time.Second):
return nil, errors.New("timeout waiting for Xvfb")
}
xauth := exec.Command("xauth", "generate", ":"+display, ".", "trusted")
xauth.Stderr = os.Stderr
xauth.Stdout = os.Stdout
xauth.Env = append(xauth.Env, "XAUTHORITY="+authPath)
if err := xauth.Run(); err != nil {
return nil, err
}
return &FrameBuffer{display, authPath, xvfb}, nil
} | go | func NewFrameBufferWithOptions(options FrameBufferOptions) (*FrameBuffer, error) {
r, w, err := os.Pipe()
if err != nil {
return nil, err
}
defer r.Close()
auth, err := ioutil.TempFile("", "selenium-xvfb")
if err != nil {
return nil, err
}
authPath := auth.Name()
if err := auth.Close(); err != nil {
return nil, err
}
// Xvfb will print the display on which it is listening to file descriptor 3,
// for which we provide a pipe.
arguments := []string{"-displayfd", "3", "-nolisten", "tcp"}
if options.ScreenSize != "" {
var screenSizeExpression = regexp.MustCompile(`^\d+x\d+(?:x\d+)$`)
if !screenSizeExpression.MatchString(options.ScreenSize) {
return nil, fmt.Errorf("invalid screen size: expected 'WxH[xD]', got %q", options.ScreenSize)
}
arguments = append(arguments, "-screen", "0", options.ScreenSize)
}
xvfb := exec.Command("Xvfb", arguments...)
xvfb.ExtraFiles = []*os.File{w}
// TODO(minusnine): plumb a way to set xvfb.Std{err,out} conditionally.
// TODO(minusnine): Pdeathsig is only supported on Linux. Somehow, make sure
// process cleanup happens as gracefully as possible.
xvfb.Env = append(xvfb.Env, "XAUTHORITY="+authPath)
if err := xvfb.Start(); err != nil {
return nil, err
}
w.Close()
type resp struct {
display string
err error
}
ch := make(chan resp)
go func() {
bufr := bufio.NewReader(r)
s, err := bufr.ReadString('\n')
ch <- resp{s, err}
}()
var display string
select {
case resp := <-ch:
if resp.err != nil {
return nil, resp.err
}
display = strings.TrimSpace(resp.display)
if _, err := strconv.Atoi(display); err != nil {
return nil, errors.New("Xvfb did not print the display number")
}
case <-time.After(3 * time.Second):
return nil, errors.New("timeout waiting for Xvfb")
}
xauth := exec.Command("xauth", "generate", ":"+display, ".", "trusted")
xauth.Stderr = os.Stderr
xauth.Stdout = os.Stdout
xauth.Env = append(xauth.Env, "XAUTHORITY="+authPath)
if err := xauth.Run(); err != nil {
return nil, err
}
return &FrameBuffer{display, authPath, xvfb}, nil
} | [
"func",
"NewFrameBufferWithOptions",
"(",
"options",
"FrameBufferOptions",
")",
"(",
"*",
"FrameBuffer",
",",
"error",
")",
"{",
"r",
",",
"w",
",",
"err",
":=",
"os",
".",
"Pipe",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"r",
".",
"Close",
"(",
")",
"\n\n",
"auth",
",",
"err",
":=",
"ioutil",
".",
"TempFile",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"authPath",
":=",
"auth",
".",
"Name",
"(",
")",
"\n",
"if",
"err",
":=",
"auth",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Xvfb will print the display on which it is listening to file descriptor 3,",
"// for which we provide a pipe.",
"arguments",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"\n",
"if",
"options",
".",
"ScreenSize",
"!=",
"\"",
"\"",
"{",
"var",
"screenSizeExpression",
"=",
"regexp",
".",
"MustCompile",
"(",
"`^\\d+x\\d+(?:x\\d+)$`",
")",
"\n",
"if",
"!",
"screenSizeExpression",
".",
"MatchString",
"(",
"options",
".",
"ScreenSize",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"options",
".",
"ScreenSize",
")",
"\n",
"}",
"\n",
"arguments",
"=",
"append",
"(",
"arguments",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"options",
".",
"ScreenSize",
")",
"\n",
"}",
"\n",
"xvfb",
":=",
"exec",
".",
"Command",
"(",
"\"",
"\"",
",",
"arguments",
"...",
")",
"\n",
"xvfb",
".",
"ExtraFiles",
"=",
"[",
"]",
"*",
"os",
".",
"File",
"{",
"w",
"}",
"\n\n",
"// TODO(minusnine): plumb a way to set xvfb.Std{err,out} conditionally.",
"// TODO(minusnine): Pdeathsig is only supported on Linux. Somehow, make sure",
"// process cleanup happens as gracefully as possible.",
"xvfb",
".",
"Env",
"=",
"append",
"(",
"xvfb",
".",
"Env",
",",
"\"",
"\"",
"+",
"authPath",
")",
"\n",
"if",
"err",
":=",
"xvfb",
".",
"Start",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"w",
".",
"Close",
"(",
")",
"\n\n",
"type",
"resp",
"struct",
"{",
"display",
"string",
"\n",
"err",
"error",
"\n",
"}",
"\n",
"ch",
":=",
"make",
"(",
"chan",
"resp",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"bufr",
":=",
"bufio",
".",
"NewReader",
"(",
"r",
")",
"\n",
"s",
",",
"err",
":=",
"bufr",
".",
"ReadString",
"(",
"'\\n'",
")",
"\n",
"ch",
"<-",
"resp",
"{",
"s",
",",
"err",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"var",
"display",
"string",
"\n",
"select",
"{",
"case",
"resp",
":=",
"<-",
"ch",
":",
"if",
"resp",
".",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"resp",
".",
"err",
"\n",
"}",
"\n",
"display",
"=",
"strings",
".",
"TrimSpace",
"(",
"resp",
".",
"display",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"display",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"case",
"<-",
"time",
".",
"After",
"(",
"3",
"*",
"time",
".",
"Second",
")",
":",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"xauth",
":=",
"exec",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"+",
"display",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"xauth",
".",
"Stderr",
"=",
"os",
".",
"Stderr",
"\n",
"xauth",
".",
"Stdout",
"=",
"os",
".",
"Stdout",
"\n",
"xauth",
".",
"Env",
"=",
"append",
"(",
"xauth",
".",
"Env",
",",
"\"",
"\"",
"+",
"authPath",
")",
"\n\n",
"if",
"err",
":=",
"xauth",
".",
"Run",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"FrameBuffer",
"{",
"display",
",",
"authPath",
",",
"xvfb",
"}",
",",
"nil",
"\n",
"}"
] | // NewFrameBufferWithOptions starts an X virtual frame buffer running in the background.
// FrameBufferOptions may be populated to change the behavior of the frame buffer. | [
"NewFrameBufferWithOptions",
"starts",
"an",
"X",
"virtual",
"frame",
"buffer",
"running",
"in",
"the",
"background",
".",
"FrameBufferOptions",
"may",
"be",
"populated",
"to",
"change",
"the",
"behavior",
"of",
"the",
"frame",
"buffer",
"."
] | edf31bb7fd715ad505d9190f8d65d13f39a7c825 | https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/service.go#L296-L369 |
147,968 | tebeka/selenium | service.go | Stop | func (f FrameBuffer) Stop() error {
if err := f.cmd.Process.Kill(); err != nil {
return err
}
os.Remove(f.AuthPath) // best effort removal; ignore error
if err := f.cmd.Wait(); err != nil && err.Error() != "signal: killed" {
return err
}
return nil
} | go | func (f FrameBuffer) Stop() error {
if err := f.cmd.Process.Kill(); err != nil {
return err
}
os.Remove(f.AuthPath) // best effort removal; ignore error
if err := f.cmd.Wait(); err != nil && err.Error() != "signal: killed" {
return err
}
return nil
} | [
"func",
"(",
"f",
"FrameBuffer",
")",
"Stop",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"f",
".",
"cmd",
".",
"Process",
".",
"Kill",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"os",
".",
"Remove",
"(",
"f",
".",
"AuthPath",
")",
"// best effort removal; ignore error",
"\n",
"if",
"err",
":=",
"f",
".",
"cmd",
".",
"Wait",
"(",
")",
";",
"err",
"!=",
"nil",
"&&",
"err",
".",
"Error",
"(",
")",
"!=",
"\"",
"\"",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Stop kills the background frame buffer process and removes the X
// authorization file. | [
"Stop",
"kills",
"the",
"background",
"frame",
"buffer",
"process",
"and",
"removes",
"the",
"X",
"authorization",
"file",
"."
] | edf31bb7fd715ad505d9190f8d65d13f39a7c825 | https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/service.go#L373-L382 |
147,969 | tebeka/selenium | sauce/connect.go | Start | func (c *Connect) Start() error {
c.cmd = exec.Command(c.Path, c.Args...)
if c.UserName != "" {
c.cmd.Args = append(c.cmd.Args, "--user", c.UserName)
}
if c.AccessKey != "" {
c.cmd.Args = append(c.cmd.Args, "--api-key", c.AccessKey)
}
if c.SeleniumPort > 0 {
c.cmd.Args = append(c.cmd.Args, "--se-port", strconv.Itoa(c.SeleniumPort))
}
if c.ExtraVerbose {
c.cmd.Args = append(c.cmd.Args, "-vv")
} else if c.Verbose {
c.cmd.Args = append(c.cmd.Args, "-v")
}
if c.ExtraVerbose || c.Verbose {
c.cmd.Stdout = os.Stdout
c.cmd.Stderr = os.Stderr
}
if c.LogFile != "" {
c.cmd.Args = append(c.cmd.Args, "--logfile", c.LogFile)
}
if c.QuitProcessUponExit && runtime.GOOS == "linux" {
c.cmd.SysProcAttr = &syscall.SysProcAttr{
// Deliver SIGTERM to process when we die.
Pdeathsig: syscall.SIGTERM,
}
}
dir, err := ioutil.TempDir("", "selenium-sauce-connect")
if err != nil {
return err
}
defer func() {
os.RemoveAll(dir) // ignore error.
}()
var pidFilePath string
if c.PIDFile != "" {
pidFilePath = c.PIDFile
} else {
f, err := ioutil.TempFile("", "selenium-sauce-connect-pid.")
if err != nil {
return err
}
pidFilePath = f.Name()
f.Close() // ignore the error.
}
// The path specified here will be touched by the proxy process when it is
// ready to accept connections.
readyPath := filepath.Join(dir, "ready")
c.cmd.Args = append(c.cmd.Args, "--readyfile", readyPath)
c.cmd.Args = append(c.cmd.Args, "--pidfile", pidFilePath)
if err := c.cmd.Start(); err != nil {
return err
}
// Wait for the Proxy to accept connections.
var started bool
for i := 0; i < 60; i++ {
time.Sleep(time.Second)
if _, err := os.Stat(readyPath); err == nil {
started = true
break
}
}
if !started {
c.Stop() // ignore error.
return fmt.Errorf("proxy process did not become ready before the timeout")
}
return nil
} | go | func (c *Connect) Start() error {
c.cmd = exec.Command(c.Path, c.Args...)
if c.UserName != "" {
c.cmd.Args = append(c.cmd.Args, "--user", c.UserName)
}
if c.AccessKey != "" {
c.cmd.Args = append(c.cmd.Args, "--api-key", c.AccessKey)
}
if c.SeleniumPort > 0 {
c.cmd.Args = append(c.cmd.Args, "--se-port", strconv.Itoa(c.SeleniumPort))
}
if c.ExtraVerbose {
c.cmd.Args = append(c.cmd.Args, "-vv")
} else if c.Verbose {
c.cmd.Args = append(c.cmd.Args, "-v")
}
if c.ExtraVerbose || c.Verbose {
c.cmd.Stdout = os.Stdout
c.cmd.Stderr = os.Stderr
}
if c.LogFile != "" {
c.cmd.Args = append(c.cmd.Args, "--logfile", c.LogFile)
}
if c.QuitProcessUponExit && runtime.GOOS == "linux" {
c.cmd.SysProcAttr = &syscall.SysProcAttr{
// Deliver SIGTERM to process when we die.
Pdeathsig: syscall.SIGTERM,
}
}
dir, err := ioutil.TempDir("", "selenium-sauce-connect")
if err != nil {
return err
}
defer func() {
os.RemoveAll(dir) // ignore error.
}()
var pidFilePath string
if c.PIDFile != "" {
pidFilePath = c.PIDFile
} else {
f, err := ioutil.TempFile("", "selenium-sauce-connect-pid.")
if err != nil {
return err
}
pidFilePath = f.Name()
f.Close() // ignore the error.
}
// The path specified here will be touched by the proxy process when it is
// ready to accept connections.
readyPath := filepath.Join(dir, "ready")
c.cmd.Args = append(c.cmd.Args, "--readyfile", readyPath)
c.cmd.Args = append(c.cmd.Args, "--pidfile", pidFilePath)
if err := c.cmd.Start(); err != nil {
return err
}
// Wait for the Proxy to accept connections.
var started bool
for i := 0; i < 60; i++ {
time.Sleep(time.Second)
if _, err := os.Stat(readyPath); err == nil {
started = true
break
}
}
if !started {
c.Stop() // ignore error.
return fmt.Errorf("proxy process did not become ready before the timeout")
}
return nil
} | [
"func",
"(",
"c",
"*",
"Connect",
")",
"Start",
"(",
")",
"error",
"{",
"c",
".",
"cmd",
"=",
"exec",
".",
"Command",
"(",
"c",
".",
"Path",
",",
"c",
".",
"Args",
"...",
")",
"\n",
"if",
"c",
".",
"UserName",
"!=",
"\"",
"\"",
"{",
"c",
".",
"cmd",
".",
"Args",
"=",
"append",
"(",
"c",
".",
"cmd",
".",
"Args",
",",
"\"",
"\"",
",",
"c",
".",
"UserName",
")",
"\n",
"}",
"\n",
"if",
"c",
".",
"AccessKey",
"!=",
"\"",
"\"",
"{",
"c",
".",
"cmd",
".",
"Args",
"=",
"append",
"(",
"c",
".",
"cmd",
".",
"Args",
",",
"\"",
"\"",
",",
"c",
".",
"AccessKey",
")",
"\n",
"}",
"\n",
"if",
"c",
".",
"SeleniumPort",
">",
"0",
"{",
"c",
".",
"cmd",
".",
"Args",
"=",
"append",
"(",
"c",
".",
"cmd",
".",
"Args",
",",
"\"",
"\"",
",",
"strconv",
".",
"Itoa",
"(",
"c",
".",
"SeleniumPort",
")",
")",
"\n",
"}",
"\n",
"if",
"c",
".",
"ExtraVerbose",
"{",
"c",
".",
"cmd",
".",
"Args",
"=",
"append",
"(",
"c",
".",
"cmd",
".",
"Args",
",",
"\"",
"\"",
")",
"\n",
"}",
"else",
"if",
"c",
".",
"Verbose",
"{",
"c",
".",
"cmd",
".",
"Args",
"=",
"append",
"(",
"c",
".",
"cmd",
".",
"Args",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"c",
".",
"ExtraVerbose",
"||",
"c",
".",
"Verbose",
"{",
"c",
".",
"cmd",
".",
"Stdout",
"=",
"os",
".",
"Stdout",
"\n",
"c",
".",
"cmd",
".",
"Stderr",
"=",
"os",
".",
"Stderr",
"\n",
"}",
"\n",
"if",
"c",
".",
"LogFile",
"!=",
"\"",
"\"",
"{",
"c",
".",
"cmd",
".",
"Args",
"=",
"append",
"(",
"c",
".",
"cmd",
".",
"Args",
",",
"\"",
"\"",
",",
"c",
".",
"LogFile",
")",
"\n",
"}",
"\n",
"if",
"c",
".",
"QuitProcessUponExit",
"&&",
"runtime",
".",
"GOOS",
"==",
"\"",
"\"",
"{",
"c",
".",
"cmd",
".",
"SysProcAttr",
"=",
"&",
"syscall",
".",
"SysProcAttr",
"{",
"// Deliver SIGTERM to process when we die.",
"Pdeathsig",
":",
"syscall",
".",
"SIGTERM",
",",
"}",
"\n",
"}",
"\n\n",
"dir",
",",
"err",
":=",
"ioutil",
".",
"TempDir",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"func",
"(",
")",
"{",
"os",
".",
"RemoveAll",
"(",
"dir",
")",
"// ignore error.",
"\n",
"}",
"(",
")",
"\n\n",
"var",
"pidFilePath",
"string",
"\n",
"if",
"c",
".",
"PIDFile",
"!=",
"\"",
"\"",
"{",
"pidFilePath",
"=",
"c",
".",
"PIDFile",
"\n",
"}",
"else",
"{",
"f",
",",
"err",
":=",
"ioutil",
".",
"TempFile",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"pidFilePath",
"=",
"f",
".",
"Name",
"(",
")",
"\n",
"f",
".",
"Close",
"(",
")",
"// ignore the error.",
"\n",
"}",
"\n\n",
"// The path specified here will be touched by the proxy process when it is",
"// ready to accept connections.",
"readyPath",
":=",
"filepath",
".",
"Join",
"(",
"dir",
",",
"\"",
"\"",
")",
"\n",
"c",
".",
"cmd",
".",
"Args",
"=",
"append",
"(",
"c",
".",
"cmd",
".",
"Args",
",",
"\"",
"\"",
",",
"readyPath",
")",
"\n",
"c",
".",
"cmd",
".",
"Args",
"=",
"append",
"(",
"c",
".",
"cmd",
".",
"Args",
",",
"\"",
"\"",
",",
"pidFilePath",
")",
"\n\n",
"if",
"err",
":=",
"c",
".",
"cmd",
".",
"Start",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Wait for the Proxy to accept connections.",
"var",
"started",
"bool",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"60",
";",
"i",
"++",
"{",
"time",
".",
"Sleep",
"(",
"time",
".",
"Second",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"readyPath",
")",
";",
"err",
"==",
"nil",
"{",
"started",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"started",
"{",
"c",
".",
"Stop",
"(",
")",
"// ignore error.",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Start starts the Sauce Connect Proxy. | [
"Start",
"starts",
"the",
"Sauce",
"Connect",
"Proxy",
"."
] | edf31bb7fd715ad505d9190f8d65d13f39a7c825 | https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/sauce/connect.go#L47-L121 |
147,970 | tebeka/selenium | sauce/connect.go | Addr | func (c *Connect) Addr() string {
return fmt.Sprintf("http://%s:%s@localhost:%d/wd/hub", c.UserName, c.AccessKey, c.SeleniumPort)
} | go | func (c *Connect) Addr() string {
return fmt.Sprintf("http://%s:%s@localhost:%d/wd/hub", c.UserName, c.AccessKey, c.SeleniumPort)
} | [
"func",
"(",
"c",
"*",
"Connect",
")",
"Addr",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"c",
".",
"UserName",
",",
"c",
".",
"AccessKey",
",",
"c",
".",
"SeleniumPort",
")",
"\n",
"}"
] | // Addr returns the URL of the WebDriver endpoint to use for driving the
// browser. | [
"Addr",
"returns",
"the",
"URL",
"of",
"the",
"WebDriver",
"endpoint",
"to",
"use",
"for",
"driving",
"the",
"browser",
"."
] | edf31bb7fd715ad505d9190f8d65d13f39a7c825 | https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/sauce/connect.go#L125-L127 |
147,971 | tebeka/selenium | chrome/capabilities.go | AddExtension | func (c *Capabilities) AddExtension(path string) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
return c.addExtension(f)
} | go | func (c *Capabilities) AddExtension(path string) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
return c.addExtension(f)
} | [
"func",
"(",
"c",
"*",
"Capabilities",
")",
"AddExtension",
"(",
"path",
"string",
")",
"error",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n",
"return",
"c",
".",
"addExtension",
"(",
"f",
")",
"\n",
"}"
] | // AddExtension adds an extension for the browser to load at startup. The path
// parameter should be a path to an extension file (which typically has a
// `.crx` file extension. Note that the contents of the file will be loaded
// into memory, as required by the protocol. | [
"AddExtension",
"adds",
"an",
"extension",
"for",
"the",
"browser",
"to",
"load",
"at",
"startup",
".",
"The",
"path",
"parameter",
"should",
"be",
"a",
"path",
"to",
"an",
"extension",
"file",
"(",
"which",
"typically",
"has",
"a",
".",
"crx",
"file",
"extension",
".",
"Note",
"that",
"the",
"contents",
"of",
"the",
"file",
"will",
"be",
"loaded",
"into",
"memory",
"as",
"required",
"by",
"the",
"protocol",
"."
] | edf31bb7fd715ad505d9190f8d65d13f39a7c825 | https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/chrome/capabilities.go#L128-L135 |
147,972 | tebeka/selenium | chrome/capabilities.go | addExtension | func (c *Capabilities) addExtension(r io.Reader) error {
var buf bytes.Buffer
encoder := base64.NewEncoder(base64.StdEncoding, &buf)
if _, err := io.Copy(encoder, bufio.NewReader(r)); err != nil {
return err
}
encoder.Close()
c.Extensions = append(c.Extensions, buf.String())
return nil
} | go | func (c *Capabilities) addExtension(r io.Reader) error {
var buf bytes.Buffer
encoder := base64.NewEncoder(base64.StdEncoding, &buf)
if _, err := io.Copy(encoder, bufio.NewReader(r)); err != nil {
return err
}
encoder.Close()
c.Extensions = append(c.Extensions, buf.String())
return nil
} | [
"func",
"(",
"c",
"*",
"Capabilities",
")",
"addExtension",
"(",
"r",
"io",
".",
"Reader",
")",
"error",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"encoder",
":=",
"base64",
".",
"NewEncoder",
"(",
"base64",
".",
"StdEncoding",
",",
"&",
"buf",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"io",
".",
"Copy",
"(",
"encoder",
",",
"bufio",
".",
"NewReader",
"(",
"r",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"encoder",
".",
"Close",
"(",
")",
"\n",
"c",
".",
"Extensions",
"=",
"append",
"(",
"c",
".",
"Extensions",
",",
"buf",
".",
"String",
"(",
")",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // addExtension reads a Chrome extension's data from r, base64-encodes it, and
// attaches it to the Capabilities instance. | [
"addExtension",
"reads",
"a",
"Chrome",
"extension",
"s",
"data",
"from",
"r",
"base64",
"-",
"encodes",
"it",
"and",
"attaches",
"it",
"to",
"the",
"Capabilities",
"instance",
"."
] | edf31bb7fd715ad505d9190f8d65d13f39a7c825 | https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/chrome/capabilities.go#L139-L148 |
147,973 | tebeka/selenium | chrome/capabilities.go | AddUnpackedExtension | func (c *Capabilities) AddUnpackedExtension(basePath string) error {
buf, _, err := NewExtension(basePath)
if err != nil {
return err
}
return c.addExtension(bytes.NewBuffer(buf))
} | go | func (c *Capabilities) AddUnpackedExtension(basePath string) error {
buf, _, err := NewExtension(basePath)
if err != nil {
return err
}
return c.addExtension(bytes.NewBuffer(buf))
} | [
"func",
"(",
"c",
"*",
"Capabilities",
")",
"AddUnpackedExtension",
"(",
"basePath",
"string",
")",
"error",
"{",
"buf",
",",
"_",
",",
"err",
":=",
"NewExtension",
"(",
"basePath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"c",
".",
"addExtension",
"(",
"bytes",
".",
"NewBuffer",
"(",
"buf",
")",
")",
"\n",
"}"
] | // AddUnpackedExtension creates a packaged Chrome extension with the files
// below the provided directory path and causes the browser to load that
// extension at startup. | [
"AddUnpackedExtension",
"creates",
"a",
"packaged",
"Chrome",
"extension",
"with",
"the",
"files",
"below",
"the",
"provided",
"directory",
"path",
"and",
"causes",
"the",
"browser",
"to",
"load",
"that",
"extension",
"at",
"startup",
"."
] | edf31bb7fd715ad505d9190f8d65d13f39a7c825 | https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/chrome/capabilities.go#L153-L159 |
147,974 | tebeka/selenium | chrome/capabilities.go | NewExtension | func NewExtension(basePath string) ([]byte, *rsa.PrivateKey, error) {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, nil, err
}
data, err := NewExtensionWithKey(basePath, key)
if err != nil {
return nil, nil, err
}
return data, key, nil
} | go | func NewExtension(basePath string) ([]byte, *rsa.PrivateKey, error) {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, nil, err
}
data, err := NewExtensionWithKey(basePath, key)
if err != nil {
return nil, nil, err
}
return data, key, nil
} | [
"func",
"NewExtension",
"(",
"basePath",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"*",
"rsa",
".",
"PrivateKey",
",",
"error",
")",
"{",
"key",
",",
"err",
":=",
"rsa",
".",
"GenerateKey",
"(",
"rand",
".",
"Reader",
",",
"2048",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"data",
",",
"err",
":=",
"NewExtensionWithKey",
"(",
"basePath",
",",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"data",
",",
"key",
",",
"nil",
"\n",
"}"
] | // NewExtension creates the payload of a Chrome extension file which is signed
// using the returned private key. | [
"NewExtension",
"creates",
"the",
"payload",
"of",
"a",
"Chrome",
"extension",
"file",
"which",
"is",
"signed",
"using",
"the",
"returned",
"private",
"key",
"."
] | edf31bb7fd715ad505d9190f8d65d13f39a7c825 | https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/chrome/capabilities.go#L163-L173 |
147,975 | tebeka/selenium | chrome/capabilities.go | NewExtensionWithKey | func NewExtensionWithKey(basePath string, key *rsa.PrivateKey) ([]byte, error) {
zip, err := zip.New(basePath)
if err != nil {
return nil, err
}
h := sha1.New()
if _, err := io.Copy(h, bytes.NewReader(zip.Bytes())); err != nil {
return nil, err
}
hashed := h.Sum(nil)
signature, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA1, hashed[:])
if err != nil {
return nil, err
}
pubKey, err := x509.MarshalPKIXPublicKey(key.Public())
if err != nil {
return nil, err
}
// This format is documented at https://developer.chrome.com/extensions/crx .
buf := new(bytes.Buffer)
if _, err := buf.Write([]byte("Cr24")); err != nil { // Magic number.
return nil, err
}
// Version.
if err := binary.Write(buf, binary.LittleEndian, uint32(2)); err != nil {
return nil, err
}
// Public key length.
if err := binary.Write(buf, binary.LittleEndian, uint32(len(pubKey))); err != nil {
return nil, err
}
// Signature length.
if err := binary.Write(buf, binary.LittleEndian, uint32(len(signature))); err != nil {
return nil, err
}
// Public key payload.
if err := binary.Write(buf, binary.LittleEndian, pubKey); err != nil {
return nil, err
}
// Signature payload.
if err := binary.Write(buf, binary.LittleEndian, signature); err != nil {
return nil, err
}
// Zipped extension directory payload.
if err := binary.Write(buf, binary.LittleEndian, zip.Bytes()); err != nil {
return nil, err
}
return buf.Bytes(), nil
} | go | func NewExtensionWithKey(basePath string, key *rsa.PrivateKey) ([]byte, error) {
zip, err := zip.New(basePath)
if err != nil {
return nil, err
}
h := sha1.New()
if _, err := io.Copy(h, bytes.NewReader(zip.Bytes())); err != nil {
return nil, err
}
hashed := h.Sum(nil)
signature, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA1, hashed[:])
if err != nil {
return nil, err
}
pubKey, err := x509.MarshalPKIXPublicKey(key.Public())
if err != nil {
return nil, err
}
// This format is documented at https://developer.chrome.com/extensions/crx .
buf := new(bytes.Buffer)
if _, err := buf.Write([]byte("Cr24")); err != nil { // Magic number.
return nil, err
}
// Version.
if err := binary.Write(buf, binary.LittleEndian, uint32(2)); err != nil {
return nil, err
}
// Public key length.
if err := binary.Write(buf, binary.LittleEndian, uint32(len(pubKey))); err != nil {
return nil, err
}
// Signature length.
if err := binary.Write(buf, binary.LittleEndian, uint32(len(signature))); err != nil {
return nil, err
}
// Public key payload.
if err := binary.Write(buf, binary.LittleEndian, pubKey); err != nil {
return nil, err
}
// Signature payload.
if err := binary.Write(buf, binary.LittleEndian, signature); err != nil {
return nil, err
}
// Zipped extension directory payload.
if err := binary.Write(buf, binary.LittleEndian, zip.Bytes()); err != nil {
return nil, err
}
return buf.Bytes(), nil
} | [
"func",
"NewExtensionWithKey",
"(",
"basePath",
"string",
",",
"key",
"*",
"rsa",
".",
"PrivateKey",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"zip",
",",
"err",
":=",
"zip",
".",
"New",
"(",
"basePath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"h",
":=",
"sha1",
".",
"New",
"(",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"io",
".",
"Copy",
"(",
"h",
",",
"bytes",
".",
"NewReader",
"(",
"zip",
".",
"Bytes",
"(",
")",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"hashed",
":=",
"h",
".",
"Sum",
"(",
"nil",
")",
"\n\n",
"signature",
",",
"err",
":=",
"rsa",
".",
"SignPKCS1v15",
"(",
"rand",
".",
"Reader",
",",
"key",
",",
"crypto",
".",
"SHA1",
",",
"hashed",
"[",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"pubKey",
",",
"err",
":=",
"x509",
".",
"MarshalPKIXPublicKey",
"(",
"key",
".",
"Public",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// This format is documented at https://developer.chrome.com/extensions/crx .",
"buf",
":=",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"buf",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"// Magic number.",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Version.",
"if",
"err",
":=",
"binary",
".",
"Write",
"(",
"buf",
",",
"binary",
".",
"LittleEndian",
",",
"uint32",
"(",
"2",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Public key length.",
"if",
"err",
":=",
"binary",
".",
"Write",
"(",
"buf",
",",
"binary",
".",
"LittleEndian",
",",
"uint32",
"(",
"len",
"(",
"pubKey",
")",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// Signature length.",
"if",
"err",
":=",
"binary",
".",
"Write",
"(",
"buf",
",",
"binary",
".",
"LittleEndian",
",",
"uint32",
"(",
"len",
"(",
"signature",
")",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Public key payload.",
"if",
"err",
":=",
"binary",
".",
"Write",
"(",
"buf",
",",
"binary",
".",
"LittleEndian",
",",
"pubKey",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Signature payload.",
"if",
"err",
":=",
"binary",
".",
"Write",
"(",
"buf",
",",
"binary",
".",
"LittleEndian",
",",
"signature",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Zipped extension directory payload.",
"if",
"err",
":=",
"binary",
".",
"Write",
"(",
"buf",
",",
"binary",
".",
"LittleEndian",
",",
"zip",
".",
"Bytes",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"buf",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"}"
] | // NewExtensionWithKey creates the payload of a Chrome extension file which is
// signed by the provided private key. | [
"NewExtensionWithKey",
"creates",
"the",
"payload",
"of",
"a",
"Chrome",
"extension",
"file",
"which",
"is",
"signed",
"by",
"the",
"provided",
"private",
"key",
"."
] | edf31bb7fd715ad505d9190f8d65d13f39a7c825 | https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/chrome/capabilities.go#L177-L235 |
147,976 | tebeka/selenium | remote.go | execute | func (wd *remoteWD) execute(method, url string, data []byte) (json.RawMessage, error) {
debugLog("-> %s %s\n%s", method, filteredURL(url), data)
request, err := newRequest(method, url, data)
if err != nil {
return nil, err
}
response, err := HTTPClient.Do(request)
if err != nil {
return nil, err
}
buf, err := ioutil.ReadAll(response.Body)
if debugFlag {
if err == nil {
// Pretty print the JSON response
var prettyBuf bytes.Buffer
if err = json.Indent(&prettyBuf, buf, "", " "); err == nil && prettyBuf.Len() > 0 {
buf = prettyBuf.Bytes()
}
}
debugLog("<- %s [%s]\n%s", response.Status, response.Header["Content-Type"], buf)
}
if err != nil {
return nil, errors.New(response.Status)
}
fullCType := response.Header.Get("Content-Type")
cType, _, err := mime.ParseMediaType(fullCType)
if err != nil {
return nil, fmt.Errorf("got content type header %q, expected %q", fullCType, jsonContentType)
}
if cType != jsonContentType {
return nil, fmt.Errorf("got content type %q, expected %q", cType, jsonContentType)
}
reply := new(serverReply)
if err := json.Unmarshal(buf, reply); err != nil {
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("bad server reply status: %s", response.Status)
}
return nil, err
}
if reply.Err != "" {
return nil, &reply.Error
}
// Handle the W3C-compliant error format. In the W3C spec, the error is
// embedded in the 'value' field.
if len(reply.Value) > 0 {
respErr := new(Error)
if err := json.Unmarshal(reply.Value, respErr); err == nil && respErr.Err != "" {
respErr.HTTPCode = response.StatusCode
return nil, respErr
}
}
// Handle the legacy error format.
const success = 0
if reply.Status != success {
shortMsg, ok := remoteErrors[reply.Status]
if !ok {
shortMsg = fmt.Sprintf("unknown error - %d", reply.Status)
}
longMsg := new(struct {
Message string
})
if err := json.Unmarshal(reply.Value, longMsg); err != nil {
return nil, errors.New(shortMsg)
}
return nil, &Error{
Err: shortMsg,
Message: longMsg.Message,
HTTPCode: response.StatusCode,
LegacyCode: reply.Status,
}
}
return buf, nil
} | go | func (wd *remoteWD) execute(method, url string, data []byte) (json.RawMessage, error) {
debugLog("-> %s %s\n%s", method, filteredURL(url), data)
request, err := newRequest(method, url, data)
if err != nil {
return nil, err
}
response, err := HTTPClient.Do(request)
if err != nil {
return nil, err
}
buf, err := ioutil.ReadAll(response.Body)
if debugFlag {
if err == nil {
// Pretty print the JSON response
var prettyBuf bytes.Buffer
if err = json.Indent(&prettyBuf, buf, "", " "); err == nil && prettyBuf.Len() > 0 {
buf = prettyBuf.Bytes()
}
}
debugLog("<- %s [%s]\n%s", response.Status, response.Header["Content-Type"], buf)
}
if err != nil {
return nil, errors.New(response.Status)
}
fullCType := response.Header.Get("Content-Type")
cType, _, err := mime.ParseMediaType(fullCType)
if err != nil {
return nil, fmt.Errorf("got content type header %q, expected %q", fullCType, jsonContentType)
}
if cType != jsonContentType {
return nil, fmt.Errorf("got content type %q, expected %q", cType, jsonContentType)
}
reply := new(serverReply)
if err := json.Unmarshal(buf, reply); err != nil {
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("bad server reply status: %s", response.Status)
}
return nil, err
}
if reply.Err != "" {
return nil, &reply.Error
}
// Handle the W3C-compliant error format. In the W3C spec, the error is
// embedded in the 'value' field.
if len(reply.Value) > 0 {
respErr := new(Error)
if err := json.Unmarshal(reply.Value, respErr); err == nil && respErr.Err != "" {
respErr.HTTPCode = response.StatusCode
return nil, respErr
}
}
// Handle the legacy error format.
const success = 0
if reply.Status != success {
shortMsg, ok := remoteErrors[reply.Status]
if !ok {
shortMsg = fmt.Sprintf("unknown error - %d", reply.Status)
}
longMsg := new(struct {
Message string
})
if err := json.Unmarshal(reply.Value, longMsg); err != nil {
return nil, errors.New(shortMsg)
}
return nil, &Error{
Err: shortMsg,
Message: longMsg.Message,
HTTPCode: response.StatusCode,
LegacyCode: reply.Status,
}
}
return buf, nil
} | [
"func",
"(",
"wd",
"*",
"remoteWD",
")",
"execute",
"(",
"method",
",",
"url",
"string",
",",
"data",
"[",
"]",
"byte",
")",
"(",
"json",
".",
"RawMessage",
",",
"error",
")",
"{",
"debugLog",
"(",
"\"",
"\\n",
"\"",
",",
"method",
",",
"filteredURL",
"(",
"url",
")",
",",
"data",
")",
"\n",
"request",
",",
"err",
":=",
"newRequest",
"(",
"method",
",",
"url",
",",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"response",
",",
"err",
":=",
"HTTPClient",
".",
"Do",
"(",
"request",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"buf",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"response",
".",
"Body",
")",
"\n",
"if",
"debugFlag",
"{",
"if",
"err",
"==",
"nil",
"{",
"// Pretty print the JSON response",
"var",
"prettyBuf",
"bytes",
".",
"Buffer",
"\n",
"if",
"err",
"=",
"json",
".",
"Indent",
"(",
"&",
"prettyBuf",
",",
"buf",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
";",
"err",
"==",
"nil",
"&&",
"prettyBuf",
".",
"Len",
"(",
")",
">",
"0",
"{",
"buf",
"=",
"prettyBuf",
".",
"Bytes",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"debugLog",
"(",
"\"",
"\\n",
"\"",
",",
"response",
".",
"Status",
",",
"response",
".",
"Header",
"[",
"\"",
"\"",
"]",
",",
"buf",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"response",
".",
"Status",
")",
"\n",
"}",
"\n\n",
"fullCType",
":=",
"response",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"cType",
",",
"_",
",",
"err",
":=",
"mime",
".",
"ParseMediaType",
"(",
"fullCType",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"fullCType",
",",
"jsonContentType",
")",
"\n",
"}",
"\n",
"if",
"cType",
"!=",
"jsonContentType",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"cType",
",",
"jsonContentType",
")",
"\n",
"}",
"\n\n",
"reply",
":=",
"new",
"(",
"serverReply",
")",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"buf",
",",
"reply",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"response",
".",
"StatusCode",
"!=",
"http",
".",
"StatusOK",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"response",
".",
"Status",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"reply",
".",
"Err",
"!=",
"\"",
"\"",
"{",
"return",
"nil",
",",
"&",
"reply",
".",
"Error",
"\n",
"}",
"\n\n",
"// Handle the W3C-compliant error format. In the W3C spec, the error is",
"// embedded in the 'value' field.",
"if",
"len",
"(",
"reply",
".",
"Value",
")",
">",
"0",
"{",
"respErr",
":=",
"new",
"(",
"Error",
")",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"reply",
".",
"Value",
",",
"respErr",
")",
";",
"err",
"==",
"nil",
"&&",
"respErr",
".",
"Err",
"!=",
"\"",
"\"",
"{",
"respErr",
".",
"HTTPCode",
"=",
"response",
".",
"StatusCode",
"\n",
"return",
"nil",
",",
"respErr",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Handle the legacy error format.",
"const",
"success",
"=",
"0",
"\n",
"if",
"reply",
".",
"Status",
"!=",
"success",
"{",
"shortMsg",
",",
"ok",
":=",
"remoteErrors",
"[",
"reply",
".",
"Status",
"]",
"\n",
"if",
"!",
"ok",
"{",
"shortMsg",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"reply",
".",
"Status",
")",
"\n",
"}",
"\n\n",
"longMsg",
":=",
"new",
"(",
"struct",
"{",
"Message",
"string",
"\n",
"}",
")",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"reply",
".",
"Value",
",",
"longMsg",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"shortMsg",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"&",
"Error",
"{",
"Err",
":",
"shortMsg",
",",
"Message",
":",
"longMsg",
".",
"Message",
",",
"HTTPCode",
":",
"response",
".",
"StatusCode",
",",
"LegacyCode",
":",
"reply",
".",
"Status",
",",
"}",
"\n",
"}",
"\n\n",
"return",
"buf",
",",
"nil",
"\n",
"}"
] | // execute performs an HTTP request and inspects the returned data for an error
// encoded by the remote end in a JSON structure. If no error is present, the
// entire, raw request payload is returned. | [
"execute",
"performs",
"an",
"HTTP",
"request",
"and",
"inspects",
"the",
"returned",
"data",
"for",
"an",
"error",
"encoded",
"by",
"the",
"remote",
"end",
"in",
"a",
"JSON",
"structure",
".",
"If",
"no",
"error",
"is",
"present",
"the",
"entire",
"raw",
"request",
"payload",
"is",
"returned",
"."
] | edf31bb7fd715ad505d9190f8d65d13f39a7c825 | https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/remote.go#L124-L204 |
147,977 | tebeka/selenium | remote.go | parseVersion | func parseVersion(v string) (semver.Version, error) {
parts := strings.Split(v, ".")
var err error
for i := len(parts); i > 0; i-- {
var ver semver.Version
ver, err = semver.ParseTolerant(strings.Join(parts[:i], "."))
if err == nil {
return ver, nil
}
}
return semver.Version{}, err
} | go | func parseVersion(v string) (semver.Version, error) {
parts := strings.Split(v, ".")
var err error
for i := len(parts); i > 0; i-- {
var ver semver.Version
ver, err = semver.ParseTolerant(strings.Join(parts[:i], "."))
if err == nil {
return ver, nil
}
}
return semver.Version{}, err
} | [
"func",
"parseVersion",
"(",
"v",
"string",
")",
"(",
"semver",
".",
"Version",
",",
"error",
")",
"{",
"parts",
":=",
"strings",
".",
"Split",
"(",
"v",
",",
"\"",
"\"",
")",
"\n",
"var",
"err",
"error",
"\n",
"for",
"i",
":=",
"len",
"(",
"parts",
")",
";",
"i",
">",
"0",
";",
"i",
"--",
"{",
"var",
"ver",
"semver",
".",
"Version",
"\n",
"ver",
",",
"err",
"=",
"semver",
".",
"ParseTolerant",
"(",
"strings",
".",
"Join",
"(",
"parts",
"[",
":",
"i",
"]",
",",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"ver",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"semver",
".",
"Version",
"{",
"}",
",",
"err",
"\n",
"}"
] | // parseVersion sanitizes the browser version enough for semver.ParseTolerant
// to parse it. | [
"parseVersion",
"sanitizes",
"the",
"browser",
"version",
"enough",
"for",
"semver",
".",
"ParseTolerant",
"to",
"parse",
"it",
"."
] | edf31bb7fd715ad505d9190f8d65d13f39a7c825 | https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/remote.go#L311-L322 |
147,978 | tebeka/selenium | remote.go | newW3CCapabilities | func newW3CCapabilities(caps Capabilities) Capabilities {
alwaysMatch := make(Capabilities)
for name, value := range caps {
if isValidW3CCapability[name] || strings.Contains(name, ":") {
alwaysMatch[name] = value
}
}
// Move the Firefox profile setting from the old location to the new
// location.
if prof, ok := caps["firefox_profile"]; ok {
if c, ok := alwaysMatch[firefox.CapabilitiesKey]; ok {
firefoxCaps := c.(firefox.Capabilities)
if firefoxCaps.Profile == "" {
firefoxCaps.Profile = prof.(string)
}
} else {
alwaysMatch[firefox.CapabilitiesKey] = firefox.Capabilities{
Profile: prof.(string),
}
}
}
return Capabilities{
"alwaysMatch": alwaysMatch,
}
} | go | func newW3CCapabilities(caps Capabilities) Capabilities {
alwaysMatch := make(Capabilities)
for name, value := range caps {
if isValidW3CCapability[name] || strings.Contains(name, ":") {
alwaysMatch[name] = value
}
}
// Move the Firefox profile setting from the old location to the new
// location.
if prof, ok := caps["firefox_profile"]; ok {
if c, ok := alwaysMatch[firefox.CapabilitiesKey]; ok {
firefoxCaps := c.(firefox.Capabilities)
if firefoxCaps.Profile == "" {
firefoxCaps.Profile = prof.(string)
}
} else {
alwaysMatch[firefox.CapabilitiesKey] = firefox.Capabilities{
Profile: prof.(string),
}
}
}
return Capabilities{
"alwaysMatch": alwaysMatch,
}
} | [
"func",
"newW3CCapabilities",
"(",
"caps",
"Capabilities",
")",
"Capabilities",
"{",
"alwaysMatch",
":=",
"make",
"(",
"Capabilities",
")",
"\n",
"for",
"name",
",",
"value",
":=",
"range",
"caps",
"{",
"if",
"isValidW3CCapability",
"[",
"name",
"]",
"||",
"strings",
".",
"Contains",
"(",
"name",
",",
"\"",
"\"",
")",
"{",
"alwaysMatch",
"[",
"name",
"]",
"=",
"value",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Move the Firefox profile setting from the old location to the new",
"// location.",
"if",
"prof",
",",
"ok",
":=",
"caps",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"if",
"c",
",",
"ok",
":=",
"alwaysMatch",
"[",
"firefox",
".",
"CapabilitiesKey",
"]",
";",
"ok",
"{",
"firefoxCaps",
":=",
"c",
".",
"(",
"firefox",
".",
"Capabilities",
")",
"\n",
"if",
"firefoxCaps",
".",
"Profile",
"==",
"\"",
"\"",
"{",
"firefoxCaps",
".",
"Profile",
"=",
"prof",
".",
"(",
"string",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"alwaysMatch",
"[",
"firefox",
".",
"CapabilitiesKey",
"]",
"=",
"firefox",
".",
"Capabilities",
"{",
"Profile",
":",
"prof",
".",
"(",
"string",
")",
",",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"Capabilities",
"{",
"\"",
"\"",
":",
"alwaysMatch",
",",
"}",
"\n",
"}"
] | // Create a W3C-compatible capabilities instance. | [
"Create",
"a",
"W3C",
"-",
"compatible",
"capabilities",
"instance",
"."
] | edf31bb7fd715ad505d9190f8d65d13f39a7c825 | https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/remote.go#L350-L376 |
147,979 | tebeka/selenium | remote.go | rect | func (elem *remoteWE) rect() (*rect, error) {
wd := elem.parent
url := wd.requestURL("/session/%s/element/%s/rect", wd.id, elem.id)
response, err := wd.execute("GET", url, nil)
if err != nil {
return nil, err
}
r := new(struct{ Value rect })
if err := json.Unmarshal(response, r); err != nil {
return nil, err
}
return &r.Value, nil
} | go | func (elem *remoteWE) rect() (*rect, error) {
wd := elem.parent
url := wd.requestURL("/session/%s/element/%s/rect", wd.id, elem.id)
response, err := wd.execute("GET", url, nil)
if err != nil {
return nil, err
}
r := new(struct{ Value rect })
if err := json.Unmarshal(response, r); err != nil {
return nil, err
}
return &r.Value, nil
} | [
"func",
"(",
"elem",
"*",
"remoteWE",
")",
"rect",
"(",
")",
"(",
"*",
"rect",
",",
"error",
")",
"{",
"wd",
":=",
"elem",
".",
"parent",
"\n",
"url",
":=",
"wd",
".",
"requestURL",
"(",
"\"",
"\"",
",",
"wd",
".",
"id",
",",
"elem",
".",
"id",
")",
"\n",
"response",
",",
"err",
":=",
"wd",
".",
"execute",
"(",
"\"",
"\"",
",",
"url",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"r",
":=",
"new",
"(",
"struct",
"{",
"Value",
"rect",
"}",
")",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"response",
",",
"r",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"r",
".",
"Value",
",",
"nil",
"\n",
"}"
] | // rect implements the "Get Element Rect" method of the W3C standard. | [
"rect",
"implements",
"the",
"Get",
"Element",
"Rect",
"method",
"of",
"the",
"W3C",
"standard",
"."
] | edf31bb7fd715ad505d9190f8d65d13f39a7c825 | https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/remote.go#L1416-L1428 |
147,980 | tebeka/selenium | internal/zip/zip.go | New | func New(basePath string) (*bytes.Buffer, error) {
fi, err := os.Stat(basePath)
if err != nil {
return nil, err
}
if !fi.IsDir() {
return nil, fmt.Errorf("path %q is not a directory, which is required for a Firefox profile", basePath)
}
buf := new(bytes.Buffer)
w := zip.NewWriter(buf)
err = filepath.Walk(basePath, func(filePath string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.Mode().IsRegular() {
return nil
}
zipFI, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
// Strip the prefix from the filename (and the trailing directory
// separator) so that the files are at the root of the zip file.
zipFI.Name = filePath[len(basePath)+1:]
// Without this, the Java zip reader throws a java.util.zip.ZipException:
// "only DEFLATED entries can have EXT descriptor".
zipFI.Method = zip.Deflate
w, err := w.CreateHeader(zipFI)
if err != nil {
return err
}
f, err := os.Open(filePath)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(w, bufio.NewReader(f))
return err
})
if err != nil {
return nil, err
}
if err := w.Close(); err != nil {
return nil, err
}
return buf, nil
} | go | func New(basePath string) (*bytes.Buffer, error) {
fi, err := os.Stat(basePath)
if err != nil {
return nil, err
}
if !fi.IsDir() {
return nil, fmt.Errorf("path %q is not a directory, which is required for a Firefox profile", basePath)
}
buf := new(bytes.Buffer)
w := zip.NewWriter(buf)
err = filepath.Walk(basePath, func(filePath string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.Mode().IsRegular() {
return nil
}
zipFI, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
// Strip the prefix from the filename (and the trailing directory
// separator) so that the files are at the root of the zip file.
zipFI.Name = filePath[len(basePath)+1:]
// Without this, the Java zip reader throws a java.util.zip.ZipException:
// "only DEFLATED entries can have EXT descriptor".
zipFI.Method = zip.Deflate
w, err := w.CreateHeader(zipFI)
if err != nil {
return err
}
f, err := os.Open(filePath)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(w, bufio.NewReader(f))
return err
})
if err != nil {
return nil, err
}
if err := w.Close(); err != nil {
return nil, err
}
return buf, nil
} | [
"func",
"New",
"(",
"basePath",
"string",
")",
"(",
"*",
"bytes",
".",
"Buffer",
",",
"error",
")",
"{",
"fi",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"basePath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"!",
"fi",
".",
"IsDir",
"(",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"basePath",
")",
"\n",
"}",
"\n\n",
"buf",
":=",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"\n",
"w",
":=",
"zip",
".",
"NewWriter",
"(",
"buf",
")",
"\n",
"err",
"=",
"filepath",
".",
"Walk",
"(",
"basePath",
",",
"func",
"(",
"filePath",
"string",
",",
"info",
"os",
".",
"FileInfo",
",",
"err",
"error",
")",
"error",
"{",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"!",
"info",
".",
"Mode",
"(",
")",
".",
"IsRegular",
"(",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"zipFI",
",",
"err",
":=",
"zip",
".",
"FileInfoHeader",
"(",
"info",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Strip the prefix from the filename (and the trailing directory",
"// separator) so that the files are at the root of the zip file.",
"zipFI",
".",
"Name",
"=",
"filePath",
"[",
"len",
"(",
"basePath",
")",
"+",
"1",
":",
"]",
"\n\n",
"// Without this, the Java zip reader throws a java.util.zip.ZipException:",
"// \"only DEFLATED entries can have EXT descriptor\".",
"zipFI",
".",
"Method",
"=",
"zip",
".",
"Deflate",
"\n\n",
"w",
",",
"err",
":=",
"w",
".",
"CreateHeader",
"(",
"zipFI",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"filePath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n\n",
"_",
",",
"err",
"=",
"io",
".",
"Copy",
"(",
"w",
",",
"bufio",
".",
"NewReader",
"(",
"f",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"w",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"buf",
",",
"nil",
"\n",
"}"
] | // New returns a buffer that contains the payload of a Zip file. | [
"New",
"returns",
"a",
"buffer",
"that",
"contains",
"the",
"payload",
"of",
"a",
"Zip",
"file",
"."
] | edf31bb7fd715ad505d9190f8d65d13f39a7c825 | https://github.com/tebeka/selenium/blob/edf31bb7fd715ad505d9190f8d65d13f39a7c825/internal/zip/zip.go#L15-L68 |
147,981 | cheggaaa/pb | pool.go | NewPool | func NewPool(pbs ...*ProgressBar) (pool *Pool) {
pool = new(Pool)
pool.Add(pbs...)
return
} | go | func NewPool(pbs ...*ProgressBar) (pool *Pool) {
pool = new(Pool)
pool.Add(pbs...)
return
} | [
"func",
"NewPool",
"(",
"pbs",
"...",
"*",
"ProgressBar",
")",
"(",
"pool",
"*",
"Pool",
")",
"{",
"pool",
"=",
"new",
"(",
"Pool",
")",
"\n",
"pool",
".",
"Add",
"(",
"pbs",
"...",
")",
"\n",
"return",
"\n",
"}"
] | // NewPool initialises a pool with progress bars, but
// doesn't start it. You need to call Start manually | [
"NewPool",
"initialises",
"a",
"pool",
"with",
"progress",
"bars",
"but",
"doesn",
"t",
"start",
"it",
".",
"You",
"need",
"to",
"call",
"Start",
"manually"
] | f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11 | https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pool.go#L24-L28 |
147,982 | cheggaaa/pb | pool.go | Add | func (p *Pool) Add(pbs ...*ProgressBar) {
p.m.Lock()
defer p.m.Unlock()
for _, bar := range pbs {
bar.ManualUpdate = true
bar.NotPrint = true
bar.Start()
p.bars = append(p.bars, bar)
}
} | go | func (p *Pool) Add(pbs ...*ProgressBar) {
p.m.Lock()
defer p.m.Unlock()
for _, bar := range pbs {
bar.ManualUpdate = true
bar.NotPrint = true
bar.Start()
p.bars = append(p.bars, bar)
}
} | [
"func",
"(",
"p",
"*",
"Pool",
")",
"Add",
"(",
"pbs",
"...",
"*",
"ProgressBar",
")",
"{",
"p",
".",
"m",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"m",
".",
"Unlock",
"(",
")",
"\n",
"for",
"_",
",",
"bar",
":=",
"range",
"pbs",
"{",
"bar",
".",
"ManualUpdate",
"=",
"true",
"\n",
"bar",
".",
"NotPrint",
"=",
"true",
"\n",
"bar",
".",
"Start",
"(",
")",
"\n",
"p",
".",
"bars",
"=",
"append",
"(",
"p",
".",
"bars",
",",
"bar",
")",
"\n",
"}",
"\n",
"}"
] | // Add progress bars. | [
"Add",
"progress",
"bars",
"."
] | f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11 | https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pool.go#L42-L51 |
147,983 | cheggaaa/pb | pool.go | Stop | func (p *Pool) Stop() error {
p.finishOnce.Do(func() {
if p.shutdownCh != nil {
close(p.shutdownCh)
}
})
// Wait for the worker to complete
select {
case <-p.workerCh:
}
return unlockEcho()
} | go | func (p *Pool) Stop() error {
p.finishOnce.Do(func() {
if p.shutdownCh != nil {
close(p.shutdownCh)
}
})
// Wait for the worker to complete
select {
case <-p.workerCh:
}
return unlockEcho()
} | [
"func",
"(",
"p",
"*",
"Pool",
")",
"Stop",
"(",
")",
"error",
"{",
"p",
".",
"finishOnce",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"if",
"p",
".",
"shutdownCh",
"!=",
"nil",
"{",
"close",
"(",
"p",
".",
"shutdownCh",
")",
"\n",
"}",
"\n",
"}",
")",
"\n\n",
"// Wait for the worker to complete",
"select",
"{",
"case",
"<-",
"p",
".",
"workerCh",
":",
"}",
"\n\n",
"return",
"unlockEcho",
"(",
")",
"\n",
"}"
] | // Restore terminal state and close pool | [
"Restore",
"terminal",
"state",
"and",
"close",
"pool"
] | f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11 | https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pool.go#L91-L104 |
147,984 | cheggaaa/pb | format.go | formatBytes | func formatBytes(i int64) (result string) {
switch {
case i >= TiB:
result = fmt.Sprintf("%.02f TiB", float64(i)/TiB)
case i >= GiB:
result = fmt.Sprintf("%.02f GiB", float64(i)/GiB)
case i >= MiB:
result = fmt.Sprintf("%.02f MiB", float64(i)/MiB)
case i >= KiB:
result = fmt.Sprintf("%.02f KiB", float64(i)/KiB)
default:
result = fmt.Sprintf("%d B", i)
}
return
} | go | func formatBytes(i int64) (result string) {
switch {
case i >= TiB:
result = fmt.Sprintf("%.02f TiB", float64(i)/TiB)
case i >= GiB:
result = fmt.Sprintf("%.02f GiB", float64(i)/GiB)
case i >= MiB:
result = fmt.Sprintf("%.02f MiB", float64(i)/MiB)
case i >= KiB:
result = fmt.Sprintf("%.02f KiB", float64(i)/KiB)
default:
result = fmt.Sprintf("%d B", i)
}
return
} | [
"func",
"formatBytes",
"(",
"i",
"int64",
")",
"(",
"result",
"string",
")",
"{",
"switch",
"{",
"case",
"i",
">=",
"TiB",
":",
"result",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"float64",
"(",
"i",
")",
"/",
"TiB",
")",
"\n",
"case",
"i",
">=",
"GiB",
":",
"result",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"float64",
"(",
"i",
")",
"/",
"GiB",
")",
"\n",
"case",
"i",
">=",
"MiB",
":",
"result",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"float64",
"(",
"i",
")",
"/",
"MiB",
")",
"\n",
"case",
"i",
">=",
"KiB",
":",
"result",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"float64",
"(",
"i",
")",
"/",
"KiB",
")",
"\n",
"default",
":",
"result",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"i",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Convert bytes to human readable string. Like 2 MiB, 64.2 KiB, 52 B | [
"Convert",
"bytes",
"to",
"human",
"readable",
"string",
".",
"Like",
"2",
"MiB",
"64",
".",
"2",
"KiB",
"52",
"B"
] | f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11 | https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/format.go#L77-L91 |
147,985 | cheggaaa/pb | format.go | formatBytesDec | func formatBytesDec(i int64) (result string) {
switch {
case i >= TB:
result = fmt.Sprintf("%.02f TB", float64(i)/TB)
case i >= GB:
result = fmt.Sprintf("%.02f GB", float64(i)/GB)
case i >= MB:
result = fmt.Sprintf("%.02f MB", float64(i)/MB)
case i >= KB:
result = fmt.Sprintf("%.02f KB", float64(i)/KB)
default:
result = fmt.Sprintf("%d B", i)
}
return
} | go | func formatBytesDec(i int64) (result string) {
switch {
case i >= TB:
result = fmt.Sprintf("%.02f TB", float64(i)/TB)
case i >= GB:
result = fmt.Sprintf("%.02f GB", float64(i)/GB)
case i >= MB:
result = fmt.Sprintf("%.02f MB", float64(i)/MB)
case i >= KB:
result = fmt.Sprintf("%.02f KB", float64(i)/KB)
default:
result = fmt.Sprintf("%d B", i)
}
return
} | [
"func",
"formatBytesDec",
"(",
"i",
"int64",
")",
"(",
"result",
"string",
")",
"{",
"switch",
"{",
"case",
"i",
">=",
"TB",
":",
"result",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"float64",
"(",
"i",
")",
"/",
"TB",
")",
"\n",
"case",
"i",
">=",
"GB",
":",
"result",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"float64",
"(",
"i",
")",
"/",
"GB",
")",
"\n",
"case",
"i",
">=",
"MB",
":",
"result",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"float64",
"(",
"i",
")",
"/",
"MB",
")",
"\n",
"case",
"i",
">=",
"KB",
":",
"result",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"float64",
"(",
"i",
")",
"/",
"KB",
")",
"\n",
"default",
":",
"result",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"i",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Convert bytes to base-10 human readable string. Like 2 MB, 64.2 KB, 52 B | [
"Convert",
"bytes",
"to",
"base",
"-",
"10",
"human",
"readable",
"string",
".",
"Like",
"2",
"MB",
"64",
".",
"2",
"KB",
"52",
"B"
] | f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11 | https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/format.go#L94-L108 |
147,986 | cheggaaa/pb | pb.go | Get | func (pb *ProgressBar) Get() int64 {
c := atomic.LoadInt64(&pb.current)
return c
} | go | func (pb *ProgressBar) Get() int64 {
c := atomic.LoadInt64(&pb.current)
return c
} | [
"func",
"(",
"pb",
"*",
"ProgressBar",
")",
"Get",
"(",
")",
"int64",
"{",
"c",
":=",
"atomic",
".",
"LoadInt64",
"(",
"&",
"pb",
".",
"current",
")",
"\n",
"return",
"c",
"\n",
"}"
] | // Get current value | [
"Get",
"current",
"value"
] | f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11 | https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pb.go#L135-L138 |
147,987 | cheggaaa/pb | pb.go | Set | func (pb *ProgressBar) Set(current int) *ProgressBar {
return pb.Set64(int64(current))
} | go | func (pb *ProgressBar) Set(current int) *ProgressBar {
return pb.Set64(int64(current))
} | [
"func",
"(",
"pb",
"*",
"ProgressBar",
")",
"Set",
"(",
"current",
"int",
")",
"*",
"ProgressBar",
"{",
"return",
"pb",
".",
"Set64",
"(",
"int64",
"(",
"current",
")",
")",
"\n",
"}"
] | // Set current value | [
"Set",
"current",
"value"
] | f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11 | https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pb.go#L141-L143 |
147,988 | cheggaaa/pb | pb.go | Add | func (pb *ProgressBar) Add(add int) int {
return int(pb.Add64(int64(add)))
} | go | func (pb *ProgressBar) Add(add int) int {
return int(pb.Add64(int64(add)))
} | [
"func",
"(",
"pb",
"*",
"ProgressBar",
")",
"Add",
"(",
"add",
"int",
")",
"int",
"{",
"return",
"int",
"(",
"pb",
".",
"Add64",
"(",
"int64",
"(",
"add",
")",
")",
")",
"\n",
"}"
] | // Add to current value | [
"Add",
"to",
"current",
"value"
] | f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11 | https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pb.go#L152-L154 |
147,989 | cheggaaa/pb | pb.go | IsFinished | func (pb *ProgressBar) IsFinished() bool {
pb.mu.Lock()
defer pb.mu.Unlock()
return pb.isFinish
} | go | func (pb *ProgressBar) IsFinished() bool {
pb.mu.Lock()
defer pb.mu.Unlock()
return pb.isFinish
} | [
"func",
"(",
"pb",
"*",
"ProgressBar",
")",
"IsFinished",
"(",
")",
"bool",
"{",
"pb",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"pb",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"pb",
".",
"isFinish",
"\n",
"}"
] | // IsFinished return boolean | [
"IsFinished",
"return",
"boolean"
] | f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11 | https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pb.go#L243-L247 |
147,990 | cheggaaa/pb | pb.go | FinishPrint | func (pb *ProgressBar) FinishPrint(str string) {
pb.Finish()
if pb.Output != nil {
fmt.Fprintln(pb.Output, str)
} else {
fmt.Println(str)
}
} | go | func (pb *ProgressBar) FinishPrint(str string) {
pb.Finish()
if pb.Output != nil {
fmt.Fprintln(pb.Output, str)
} else {
fmt.Println(str)
}
} | [
"func",
"(",
"pb",
"*",
"ProgressBar",
")",
"FinishPrint",
"(",
"str",
"string",
")",
"{",
"pb",
".",
"Finish",
"(",
")",
"\n",
"if",
"pb",
".",
"Output",
"!=",
"nil",
"{",
"fmt",
".",
"Fprintln",
"(",
"pb",
".",
"Output",
",",
"str",
")",
"\n",
"}",
"else",
"{",
"fmt",
".",
"Println",
"(",
"str",
")",
"\n",
"}",
"\n",
"}"
] | // End print and write string 'str' | [
"End",
"print",
"and",
"write",
"string",
"str"
] | f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11 | https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pb.go#L250-L257 |
147,991 | cheggaaa/pb | pb.go | Write | func (pb *ProgressBar) Write(p []byte) (n int, err error) {
n = len(p)
pb.Add(n)
return
} | go | func (pb *ProgressBar) Write(p []byte) (n int, err error) {
n = len(p)
pb.Add(n)
return
} | [
"func",
"(",
"pb",
"*",
"ProgressBar",
")",
"Write",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"n",
"=",
"len",
"(",
"p",
")",
"\n",
"pb",
".",
"Add",
"(",
"n",
")",
"\n",
"return",
"\n",
"}"
] | // implement io.Writer | [
"implement",
"io",
".",
"Writer"
] | f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11 | https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pb.go#L260-L264 |
147,992 | cheggaaa/pb | pb.go | NewProxyReader | func (pb *ProgressBar) NewProxyReader(r io.Reader) *Reader {
return &Reader{r, pb}
} | go | func (pb *ProgressBar) NewProxyReader(r io.Reader) *Reader {
return &Reader{r, pb}
} | [
"func",
"(",
"pb",
"*",
"ProgressBar",
")",
"NewProxyReader",
"(",
"r",
"io",
".",
"Reader",
")",
"*",
"Reader",
"{",
"return",
"&",
"Reader",
"{",
"r",
",",
"pb",
"}",
"\n",
"}"
] | // Create new proxy reader over bar
// Takes io.Reader or io.ReadCloser | [
"Create",
"new",
"proxy",
"reader",
"over",
"bar",
"Takes",
"io",
".",
"Reader",
"or",
"io",
".",
"ReadCloser"
] | f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11 | https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pb.go#L275-L277 |
147,993 | cheggaaa/pb | pb.go | String | func (pb *ProgressBar) String() string {
pb.mu.Lock()
defer pb.mu.Unlock()
return pb.lastPrint
} | go | func (pb *ProgressBar) String() string {
pb.mu.Lock()
defer pb.mu.Unlock()
return pb.lastPrint
} | [
"func",
"(",
"pb",
"*",
"ProgressBar",
")",
"String",
"(",
")",
"string",
"{",
"pb",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"pb",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"pb",
".",
"lastPrint",
"\n",
"}"
] | // String return the last bar print | [
"String",
"return",
"the",
"last",
"bar",
"print"
] | f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11 | https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pb.go#L461-L465 |
147,994 | cheggaaa/pb | pb.go | SetTotal | func (pb *ProgressBar) SetTotal(total int) *ProgressBar {
return pb.SetTotal64(int64(total))
} | go | func (pb *ProgressBar) SetTotal(total int) *ProgressBar {
return pb.SetTotal64(int64(total))
} | [
"func",
"(",
"pb",
"*",
"ProgressBar",
")",
"SetTotal",
"(",
"total",
"int",
")",
"*",
"ProgressBar",
"{",
"return",
"pb",
".",
"SetTotal64",
"(",
"int64",
"(",
"total",
")",
")",
"\n",
"}"
] | // SetTotal atomically sets new total count | [
"SetTotal",
"atomically",
"sets",
"new",
"total",
"count"
] | f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11 | https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pb.go#L468-L470 |
147,995 | cheggaaa/pb | pb.go | SetTotal64 | func (pb *ProgressBar) SetTotal64(total int64) *ProgressBar {
atomic.StoreInt64(&pb.Total, total)
return pb
} | go | func (pb *ProgressBar) SetTotal64(total int64) *ProgressBar {
atomic.StoreInt64(&pb.Total, total)
return pb
} | [
"func",
"(",
"pb",
"*",
"ProgressBar",
")",
"SetTotal64",
"(",
"total",
"int64",
")",
"*",
"ProgressBar",
"{",
"atomic",
".",
"StoreInt64",
"(",
"&",
"pb",
".",
"Total",
",",
"total",
")",
"\n",
"return",
"pb",
"\n",
"}"
] | // SetTotal64 atomically sets new total count | [
"SetTotal64",
"atomically",
"sets",
"new",
"total",
"count"
] | f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11 | https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pb.go#L473-L476 |
147,996 | cheggaaa/pb | pb.go | Reset | func (pb *ProgressBar) Reset(total int) *ProgressBar {
pb.mu.Lock()
defer pb.mu.Unlock()
if pb.isFinish {
pb.SetTotal(total).Set(0)
atomic.StoreInt64(&pb.previous, 0)
}
return pb
} | go | func (pb *ProgressBar) Reset(total int) *ProgressBar {
pb.mu.Lock()
defer pb.mu.Unlock()
if pb.isFinish {
pb.SetTotal(total).Set(0)
atomic.StoreInt64(&pb.previous, 0)
}
return pb
} | [
"func",
"(",
"pb",
"*",
"ProgressBar",
")",
"Reset",
"(",
"total",
"int",
")",
"*",
"ProgressBar",
"{",
"pb",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"pb",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"pb",
".",
"isFinish",
"{",
"pb",
".",
"SetTotal",
"(",
"total",
")",
".",
"Set",
"(",
"0",
")",
"\n",
"atomic",
".",
"StoreInt64",
"(",
"&",
"pb",
".",
"previous",
",",
"0",
")",
"\n",
"}",
"\n",
"return",
"pb",
"\n",
"}"
] | // Reset bar and set new total count
// Does effect only on finished bar | [
"Reset",
"bar",
"and",
"set",
"new",
"total",
"count",
"Does",
"effect",
"only",
"on",
"finished",
"bar"
] | f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11 | https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pb.go#L480-L488 |
147,997 | cheggaaa/pb | pb.go | refresher | func (pb *ProgressBar) refresher() {
for {
select {
case <-pb.finish:
return
case <-time.After(pb.RefreshRate):
pb.Update()
}
}
} | go | func (pb *ProgressBar) refresher() {
for {
select {
case <-pb.finish:
return
case <-time.After(pb.RefreshRate):
pb.Update()
}
}
} | [
"func",
"(",
"pb",
"*",
"ProgressBar",
")",
"refresher",
"(",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"<-",
"pb",
".",
"finish",
":",
"return",
"\n",
"case",
"<-",
"time",
".",
"After",
"(",
"pb",
".",
"RefreshRate",
")",
":",
"pb",
".",
"Update",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Internal loop for refreshing the progressbar | [
"Internal",
"loop",
"for",
"refreshing",
"the",
"progressbar"
] | f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11 | https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pb.go#L491-L500 |
147,998 | cheggaaa/pb | pb_x.go | catchTerminate | func catchTerminate(shutdownCh chan struct{}) {
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGKILL)
defer signal.Stop(sig)
select {
case <-shutdownCh:
unlockEcho()
case <-sig:
unlockEcho()
}
} | go | func catchTerminate(shutdownCh chan struct{}) {
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGKILL)
defer signal.Stop(sig)
select {
case <-shutdownCh:
unlockEcho()
case <-sig:
unlockEcho()
}
} | [
"func",
"catchTerminate",
"(",
"shutdownCh",
"chan",
"struct",
"{",
"}",
")",
"{",
"sig",
":=",
"make",
"(",
"chan",
"os",
".",
"Signal",
",",
"1",
")",
"\n",
"signal",
".",
"Notify",
"(",
"sig",
",",
"os",
".",
"Interrupt",
",",
"syscall",
".",
"SIGQUIT",
",",
"syscall",
".",
"SIGTERM",
",",
"syscall",
".",
"SIGKILL",
")",
"\n",
"defer",
"signal",
".",
"Stop",
"(",
"sig",
")",
"\n",
"select",
"{",
"case",
"<-",
"shutdownCh",
":",
"unlockEcho",
"(",
")",
"\n",
"case",
"<-",
"sig",
":",
"unlockEcho",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // listen exit signals and restore terminal state | [
"listen",
"exit",
"signals",
"and",
"restore",
"terminal",
"state"
] | f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11 | https://github.com/cheggaaa/pb/blob/f907f6f5dd81f77c2bbc1cde92e4c5a04720cb11/pb_x.go#L108-L118 |
147,999 | coocood/freecache | iterator.go | Next | func (it *Iterator) Next() *Entry {
for it.segmentIdx < 256 {
entry := it.nextForSegment(it.segmentIdx)
if entry != nil {
return entry
}
it.segmentIdx++
it.slotIdx = 0
it.entryIdx = 0
}
return nil
} | go | func (it *Iterator) Next() *Entry {
for it.segmentIdx < 256 {
entry := it.nextForSegment(it.segmentIdx)
if entry != nil {
return entry
}
it.segmentIdx++
it.slotIdx = 0
it.entryIdx = 0
}
return nil
} | [
"func",
"(",
"it",
"*",
"Iterator",
")",
"Next",
"(",
")",
"*",
"Entry",
"{",
"for",
"it",
".",
"segmentIdx",
"<",
"256",
"{",
"entry",
":=",
"it",
".",
"nextForSegment",
"(",
"it",
".",
"segmentIdx",
")",
"\n",
"if",
"entry",
"!=",
"nil",
"{",
"return",
"entry",
"\n",
"}",
"\n",
"it",
".",
"segmentIdx",
"++",
"\n",
"it",
".",
"slotIdx",
"=",
"0",
"\n",
"it",
".",
"entryIdx",
"=",
"0",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Next returns the next entry for the iterator.
// The order of the entries is not guaranteed.
// If there is no more entries to return, nil will be returned. | [
"Next",
"returns",
"the",
"next",
"entry",
"for",
"the",
"iterator",
".",
"The",
"order",
"of",
"the",
"entries",
"is",
"not",
"guaranteed",
".",
"If",
"there",
"is",
"no",
"more",
"entries",
"to",
"return",
"nil",
"will",
"be",
"returned",
"."
] | 142b9e1225b0ecdbe420d8fe6cef33f268670c42 | https://github.com/coocood/freecache/blob/142b9e1225b0ecdbe420d8fe6cef33f268670c42/iterator.go#L25-L36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.