id
stringlengths 95
167
| text
stringlengths 69
15.9k
| title
stringclasses 1
value |
|---|---|---|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/embed/config.go#L798-L828
|
func (cfg *Config) UpdateDefaultClusterFromName(defaultInitialCluster string) (string, error) {
if defaultHostname == "" || defaultHostStatus != nil {
// update 'initial-cluster' when only the name is specified (e.g. 'etcd --name=abc')
if cfg.Name != DefaultName && cfg.InitialCluster == defaultInitialCluster {
cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name)
}
return "", defaultHostStatus
}
used := false
pip, pport := cfg.LPUrls[0].Hostname(), cfg.LPUrls[0].Port()
if cfg.defaultPeerHost() && pip == "0.0.0.0" {
cfg.APUrls[0] = url.URL{Scheme: cfg.APUrls[0].Scheme, Host: fmt.Sprintf("%s:%s", defaultHostname, pport)}
used = true
}
// update 'initial-cluster' when only the name is specified (e.g. 'etcd --name=abc')
if cfg.Name != DefaultName && cfg.InitialCluster == defaultInitialCluster {
cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name)
}
cip, cport := cfg.LCUrls[0].Hostname(), cfg.LCUrls[0].Port()
if cfg.defaultClientHost() && cip == "0.0.0.0" {
cfg.ACUrls[0] = url.URL{Scheme: cfg.ACUrls[0].Scheme, Host: fmt.Sprintf("%s:%s", defaultHostname, cport)}
used = true
}
dhost := defaultHostname
if !used {
dhost = ""
}
return dhost, defaultHostStatus
}
| |
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/raft.go#L122-L143
|
func (r *Raft) run() {
for {
// Check if we are doing a shutdown
select {
case <-r.shutdownCh:
// Clear the leader to prevent forwarding
r.setLeader("")
return
default:
}
// Enter into a sub-FSM
switch r.getState() {
case Follower:
r.runFollower()
case Candidate:
r.runCandidate()
case Leader:
r.runLeader()
}
}
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/expect/expect.go#L53-L71
|
func NewExpectWithEnv(name string, args []string, env []string) (ep *ExpectProcess, err error) {
cmd := exec.Command(name, args...)
cmd.Env = env
ep = &ExpectProcess{
cmd: cmd,
StopSignal: syscall.SIGKILL,
}
ep.cond = sync.NewCond(&ep.mu)
ep.cmd.Stderr = ep.cmd.Stdout
ep.cmd.Stdin = nil
if ep.fpty, err = pty.Start(ep.cmd); err != nil {
return nil, err
}
ep.wg.Add(1)
go ep.read()
return ep, nil
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/integration/cluster.go#L213-L215
|
func NewClusterByConfig(t testing.TB, cfg *ClusterConfig) *cluster {
return newCluster(t, cfg)
}
| |
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/genny/actions/build_actions.go#L14-L27
|
func buildActions(pres *presenter) genny.RunFn {
return func(r *genny.Runner) error {
fn := fmt.Sprintf("actions/%s.go", pres.Name.File())
xf, err := r.FindFile(fn)
if err != nil {
return buildNewActions(fn, pres)(r)
}
if err := appendActions(xf, pres)(r); err != nil {
return err
}
return nil
}
}
| |
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/golint/suggestion/golint_suggestion.go#L47-L57
|
func SuggestCodeChange(p lint.Problem) string {
var suggestion = ""
for regex, handler := range lintHandlersMap {
matches := regex.FindStringSubmatch(p.Text)
suggestion = handler(p, matches)
if suggestion != "" && suggestion != p.LineText {
return formatSuggestion(suggestion)
}
}
return ""
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/server.go#L1917-L1955
|
func (s *EtcdServer) apply(
es []raftpb.Entry,
confState *raftpb.ConfState,
) (appliedt uint64, appliedi uint64, shouldStop bool) {
for i := range es {
e := es[i]
switch e.Type {
case raftpb.EntryNormal:
s.applyEntryNormal(&e)
s.setAppliedIndex(e.Index)
s.setTerm(e.Term)
case raftpb.EntryConfChange:
// set the consistent index of current executing entry
if e.Index > s.consistIndex.ConsistentIndex() {
s.consistIndex.setConsistentIndex(e.Index)
}
var cc raftpb.ConfChange
pbutil.MustUnmarshal(&cc, e.Data)
removedSelf, err := s.applyConfChange(cc, confState)
s.setAppliedIndex(e.Index)
s.setTerm(e.Term)
shouldStop = shouldStop || removedSelf
s.w.Trigger(cc.ID, &confChangeResponse{s.cluster.Members(), err})
default:
if lg := s.getLogger(); lg != nil {
lg.Panic(
"unknown entry type; must be either EntryNormal or EntryConfChange",
zap.String("type", e.Type.String()),
)
} else {
plog.Panicf("entry type should be either EntryNormal or EntryConfChange")
}
}
appliedi, appliedt = e.Index, e.Term
}
return appliedt, appliedi, shouldStop
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/node.go#L57-L67
|
func newKV(store *store, nodePath string, value string, createdIndex uint64, parent *node, expireTime time.Time) *node {
return &node{
Path: nodePath,
CreatedIndex: createdIndex,
ModifiedIndex: createdIndex,
Parent: parent,
store: store,
ExpireTime: expireTime,
Value: value,
}
}
| |
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/fakegithub/fakegithub.go#L273-L286
|
func (f *FakeClient) GetIssueLabels(owner, repo string, number int) ([]github.Label, error) {
re := regexp.MustCompile(fmt.Sprintf(`^%s/%s#%d:(.*)$`, owner, repo, number))
la := []github.Label{}
allLabels := sets.NewString(f.IssueLabelsExisting...)
allLabels.Insert(f.IssueLabelsAdded...)
allLabels.Delete(f.IssueLabelsRemoved...)
for _, l := range allLabels.List() {
groups := re.FindStringSubmatch(l)
if groups != nil {
la = append(la, github.Label{Name: groups[1]})
}
}
return la, nil
}
| |
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/batch.go#L104-L108
|
func (wb *WriteBatch) SetWithTTL(key, val []byte, dur time.Duration) error {
expire := time.Now().Add(dur).Unix()
e := &Entry{Key: key, Value: val, ExpiresAt: uint64(expire)}
return wb.SetEntry(e)
}
| |
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/robots/coverage/cmd/downloader/downloader.go#L37-L52
|
func MakeCommand() *cobra.Command {
flags := &flags{}
cmd := &cobra.Command{
Use: "download [bucket] [prowjob]",
Short: "Finds and downloads the coverage profile file from the latest healthy build",
Long: `Finds and downloads the coverage profile file from the latest healthy build
stored in given gcs directory.`,
Run: func(cmd *cobra.Command, args []string) {
run(flags, cmd, args)
},
}
cmd.Flags().StringVarP(&flags.outputFile, "output", "o", "-", "output file")
cmd.Flags().StringVarP(&flags.artifactsDirName, "artifactsDir", "a", "artifacts", "artifact directory name in GCS")
cmd.Flags().StringVarP(&flags.profileName, "profile", "p", "coverage-profile", "code coverage profile file name in GCS")
return cmd
}
| |
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/file_snapshot.go#L296-L346
|
func (f *FileSnapshotStore) Open(id string) (*SnapshotMeta, io.ReadCloser, error) {
// Get the metadata
meta, err := f.readMeta(id)
if err != nil {
f.logger.Printf("[ERR] snapshot: Failed to get meta data to open snapshot: %v", err)
return nil, nil, err
}
// Open the state file
statePath := filepath.Join(f.path, id, stateFilePath)
fh, err := os.Open(statePath)
if err != nil {
f.logger.Printf("[ERR] snapshot: Failed to open state file: %v", err)
return nil, nil, err
}
// Create a CRC64 hash
stateHash := crc64.New(crc64.MakeTable(crc64.ECMA))
// Compute the hash
_, err = io.Copy(stateHash, fh)
if err != nil {
f.logger.Printf("[ERR] snapshot: Failed to read state file: %v", err)
fh.Close()
return nil, nil, err
}
// Verify the hash
computed := stateHash.Sum(nil)
if bytes.Compare(meta.CRC, computed) != 0 {
f.logger.Printf("[ERR] snapshot: CRC checksum failed (stored: %v computed: %v)",
meta.CRC, computed)
fh.Close()
return nil, nil, fmt.Errorf("CRC mismatch")
}
// Seek to the start
if _, err := fh.Seek(0, 0); err != nil {
f.logger.Printf("[ERR] snapshot: State file seek failed: %v", err)
fh.Close()
return nil, nil, err
}
// Return a buffered file
buffered := &bufferedFile{
bh: bufio.NewReader(fh),
fh: fh,
}
return &meta.SnapshotMeta, buffered, nil
}
| |
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/fakegithub/fakegithub.go#L410-L413
|
func (f *FakeClient) ClearMilestone(org, repo string, issueNum int) error {
f.Milestone = 0
return nil
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/watch.go#L282-L362
|
func (w *watcher) Watch(ctx context.Context, key string, opts ...OpOption) WatchChan {
ow := opWatch(key, opts...)
var filters []pb.WatchCreateRequest_FilterType
if ow.filterPut {
filters = append(filters, pb.WatchCreateRequest_NOPUT)
}
if ow.filterDelete {
filters = append(filters, pb.WatchCreateRequest_NODELETE)
}
wr := &watchRequest{
ctx: ctx,
createdNotify: ow.createdNotify,
key: string(ow.key),
end: string(ow.end),
rev: ow.rev,
progressNotify: ow.progressNotify,
fragment: ow.fragment,
filters: filters,
prevKV: ow.prevKV,
retc: make(chan chan WatchResponse, 1),
}
ok := false
ctxKey := streamKeyFromCtx(ctx)
// find or allocate appropriate grpc watch stream
w.mu.Lock()
if w.streams == nil {
// closed
w.mu.Unlock()
ch := make(chan WatchResponse)
close(ch)
return ch
}
wgs := w.streams[ctxKey]
if wgs == nil {
wgs = w.newWatcherGrpcStream(ctx)
w.streams[ctxKey] = wgs
}
donec := wgs.donec
reqc := wgs.reqc
w.mu.Unlock()
// couldn't create channel; return closed channel
closeCh := make(chan WatchResponse, 1)
// submit request
select {
case reqc <- wr:
ok = true
case <-wr.ctx.Done():
case <-donec:
if wgs.closeErr != nil {
closeCh <- WatchResponse{Canceled: true, closeErr: wgs.closeErr}
break
}
// retry; may have dropped stream from no ctxs
return w.Watch(ctx, key, opts...)
}
// receive channel
if ok {
select {
case ret := <-wr.retc:
return ret
case <-ctx.Done():
case <-donec:
if wgs.closeErr != nil {
closeCh <- WatchResponse{Canceled: true, closeErr: wgs.closeErr}
break
}
// retry; may have dropped stream from no ctxs
return w.Watch(ctx, key, opts...)
}
}
close(closeCh)
return closeCh
}
| |
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/file_snapshot.go#L375-L377
|
func (s *FileSnapshotSink) Write(b []byte) (int, error) {
return s.buffered.Write(b)
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2stats/queue.go#L52-L59
|
func (q *statsQueue) frontAndBack() (*RequestStats, *RequestStats) {
q.rwl.RLock()
defer q.rwl.RUnlock()
if q.size != 0 {
return q.items[q.front], q.items[q.back]
}
return nil, nil
}
| |
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/artifact-uploader/main.go#L86-L88
|
func (o *Options) LoadConfig(config string) error {
return json.Unmarshal([]byte(config), o)
}
| |
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/default_context.go#L265-L279
|
func (d *DefaultContext) MarshalJSON() ([]byte, error) {
m := map[string]interface{}{}
data := d.Data()
for k, v := range data {
// don't try and marshal ourself
if _, ok := v.(*DefaultContext); ok {
continue
}
if _, err := json.Marshal(v); err == nil {
// it can be marshaled, so add it:
m[k] = v
}
}
return json.Marshal(m)
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv2/command/ls_command.go#L80-L90
|
func rPrint(c *cli.Context, n *client.Node) {
if n.Dir && c.Bool("p") {
fmt.Println(fmt.Sprintf("%v/", n.Key))
} else {
fmt.Println(n.Key)
}
for _, node := range n.Nodes {
rPrint(c, node)
}
}
| |
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/inmem_store.go#L99-L104
|
func (i *InmemStore) Set(key []byte, val []byte) error {
i.l.Lock()
defer i.l.Unlock()
i.kv[string(key)] = val
return nil
}
| |
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/render/html.go#L16-L19
|
func HTML(names ...string) Renderer {
e := New(Options{})
return e.HTML(names...)
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/auth_command.go#L84-L97
|
func authDisableCommandFunc(cmd *cobra.Command, args []string) {
if len(args) != 0 {
ExitWithError(ExitBadArgs, fmt.Errorf("auth disable command does not accept any arguments"))
}
ctx, cancel := commandCtx(cmd)
_, err := mustClientFromCmd(cmd).Auth.AuthDisable(ctx)
cancel()
if err != nil {
ExitWithError(ExitError, err)
}
fmt.Println("Authentication Disabled")
}
| |
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/kube/dry_run_client.go#L50-L52
|
func (c *dryRunProwJobClient) Create(*prowapi.ProwJob) (*prowapi.ProwJob, error) {
return nil, nil
}
| |
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/secret/agent.go#L35-L49
|
func (a *Agent) Start(paths []string) error {
secretsMap, err := LoadSecrets(paths)
if err != nil {
return err
}
a.secretsMap = secretsMap
// Start one goroutine for each file to monitor and update the secret's values.
for secretPath := range secretsMap {
go a.reloadSecret(secretPath)
}
return nil
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2http/client.go#L370-L551
|
func parseKeyRequest(r *http.Request, clock clockwork.Clock) (etcdserverpb.Request, bool, error) {
var noValueOnSuccess bool
emptyReq := etcdserverpb.Request{}
err := r.ParseForm()
if err != nil {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeInvalidForm,
err.Error(),
)
}
if !strings.HasPrefix(r.URL.Path, keysPrefix) {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeInvalidForm,
"incorrect key prefix",
)
}
p := path.Join(etcdserver.StoreKeysPrefix, r.URL.Path[len(keysPrefix):])
var pIdx, wIdx uint64
if pIdx, err = getUint64(r.Form, "prevIndex"); err != nil {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeIndexNaN,
`invalid value for "prevIndex"`,
)
}
if wIdx, err = getUint64(r.Form, "waitIndex"); err != nil {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeIndexNaN,
`invalid value for "waitIndex"`,
)
}
var rec, sort, wait, dir, quorum, stream bool
if rec, err = getBool(r.Form, "recursive"); err != nil {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeInvalidField,
`invalid value for "recursive"`,
)
}
if sort, err = getBool(r.Form, "sorted"); err != nil {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeInvalidField,
`invalid value for "sorted"`,
)
}
if wait, err = getBool(r.Form, "wait"); err != nil {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeInvalidField,
`invalid value for "wait"`,
)
}
// TODO(jonboulle): define what parameters dir is/isn't compatible with?
if dir, err = getBool(r.Form, "dir"); err != nil {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeInvalidField,
`invalid value for "dir"`,
)
}
if quorum, err = getBool(r.Form, "quorum"); err != nil {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeInvalidField,
`invalid value for "quorum"`,
)
}
if stream, err = getBool(r.Form, "stream"); err != nil {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeInvalidField,
`invalid value for "stream"`,
)
}
if wait && r.Method != "GET" {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeInvalidField,
`"wait" can only be used with GET requests`,
)
}
pV := r.FormValue("prevValue")
if _, ok := r.Form["prevValue"]; ok && pV == "" {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodePrevValueRequired,
`"prevValue" cannot be empty`,
)
}
if noValueOnSuccess, err = getBool(r.Form, "noValueOnSuccess"); err != nil {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeInvalidField,
`invalid value for "noValueOnSuccess"`,
)
}
// TTL is nullable, so leave it null if not specified
// or an empty string
var ttl *uint64
if len(r.FormValue("ttl")) > 0 {
i, err := getUint64(r.Form, "ttl")
if err != nil {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeTTLNaN,
`invalid value for "ttl"`,
)
}
ttl = &i
}
// prevExist is nullable, so leave it null if not specified
var pe *bool
if _, ok := r.Form["prevExist"]; ok {
bv, err := getBool(r.Form, "prevExist")
if err != nil {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeInvalidField,
"invalid value for prevExist",
)
}
pe = &bv
}
// refresh is nullable, so leave it null if not specified
var refresh *bool
if _, ok := r.Form["refresh"]; ok {
bv, err := getBool(r.Form, "refresh")
if err != nil {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeInvalidField,
"invalid value for refresh",
)
}
refresh = &bv
if refresh != nil && *refresh {
val := r.FormValue("value")
if _, ok := r.Form["value"]; ok && val != "" {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeRefreshValue,
`A value was provided on a refresh`,
)
}
if ttl == nil {
return emptyReq, false, v2error.NewRequestError(
v2error.EcodeRefreshTTLRequired,
`No TTL value set`,
)
}
}
}
rr := etcdserverpb.Request{
Method: r.Method,
Path: p,
Val: r.FormValue("value"),
Dir: dir,
PrevValue: pV,
PrevIndex: pIdx,
PrevExist: pe,
Wait: wait,
Since: wIdx,
Recursive: rec,
Sorted: sort,
Quorum: quorum,
Stream: stream,
}
if pe != nil {
rr.PrevExist = pe
}
if refresh != nil {
rr.Refresh = refresh
}
// Null TTL is equivalent to unset Expiration
if ttl != nil {
expr := time.Duration(*ttl) * time.Second
rr.Expiration = clock.Now().Add(expr).UnixNano()
}
return rr, noValueOnSuccess, nil
}
| |
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/fakegithub/fakegithub.go#L588-L596
|
func (f *FakeClient) TeamHasMember(teamID int, memberLogin string) (bool, error) {
teamMembers, _ := f.ListTeamMembers(teamID, github.RoleAll)
for _, member := range teamMembers {
if member.Login == memberLogin {
return true, nil
}
}
return false, nil
}
| |
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/configuration.go#L280-L297
|
func encodePeers(configuration Configuration, trans Transport) []byte {
// Gather up all the voters, other suffrage types are not supported by
// this data format.
var encPeers [][]byte
for _, server := range configuration.Servers {
if server.Suffrage == Voter {
encPeers = append(encPeers, trans.EncodePeer(server.ID, server.Address))
}
}
// Encode the entire array.
buf, err := encodeMsgPack(encPeers)
if err != nil {
panic(fmt.Errorf("failed to encode peers: %v", err))
}
return buf.Bytes()
}
| |
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/servers/tls.go#L23-L26
|
func (s *TLS) Start(c context.Context, h http.Handler) error {
s.Handler = h
return s.ListenAndServeTLS(s.CertFile, s.KeyFile)
}
| |
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/peersjson.go#L64-L98
|
func ReadConfigJSON(path string) (Configuration, error) {
// Read in the file.
buf, err := ioutil.ReadFile(path)
if err != nil {
return Configuration{}, err
}
// Parse it as JSON.
var peers []configEntry
dec := json.NewDecoder(bytes.NewReader(buf))
if err := dec.Decode(&peers); err != nil {
return Configuration{}, err
}
// Map it into the new-style configuration structure.
var configuration Configuration
for _, peer := range peers {
suffrage := Voter
if peer.NonVoter {
suffrage = Nonvoter
}
server := Server{
Suffrage: suffrage,
ID: peer.ID,
Address: peer.Address,
}
configuration.Servers = append(configuration.Servers, server)
}
// We should only ingest valid configurations.
if err := checkConfiguration(configuration); err != nil {
return Configuration{}, err
}
return configuration, nil
}
| |
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/configuration.go#L327-L333
|
func encodeConfiguration(configuration Configuration) []byte {
buf, err := encodeMsgPack(configuration)
if err != nil {
panic(fmt.Errorf("failed to encode configuration: %v", err))
}
return buf.Bytes()
}
| |
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/transform/plugins/multiplexer_wrapper.go#L38-L46
|
func (m *MultiplexerPluginWrapper) ReceiveIssue(issue sql.Issue) []Point {
points := []Point{}
for _, plugin := range m.plugins {
points = append(points, plugin.ReceiveIssue(issue)...)
}
return points
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/server.go#L2218-L2223
|
func (s *EtcdServer) CutPeer(id types.ID) {
tr, ok := s.r.transport.(*rafthttp.Transport)
if ok {
tr.CutPeer(id)
}
}
| |
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/client/clientset/versioned/typed/prowjobs/v1/prowjob.go#L112-L122
|
func (c *prowJobs) Update(prowJob *v1.ProwJob) (result *v1.ProwJob, err error) {
result = &v1.ProwJob{}
err = c.client.Put().
Namespace(c.ns).
Resource("prowjobs").
Name(prowJob.Name).
Body(prowJob).
Do().
Into(result)
return
}
| |
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/render/sse.go#L64-L77
|
func NewEventSource(w http.ResponseWriter) (*EventSource, error) {
es := &EventSource{w: w}
var ok bool
es.fl, ok = w.(http.Flusher)
if !ok {
return es, errors.New("streaming is not supported")
}
es.w.Header().Set("Content-Type", "text/event-stream")
es.w.Header().Set("Cache-Control", "no-cache")
es.w.Header().Set("Connection", "keep-alive")
es.w.Header().Set("Access-Control-Allow-Origin", "*")
return es, nil
}
| |
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/iterator.go#L74-L76
|
func (item *Item) KeyCopy(dst []byte) []byte {
return y.SafeCopy(dst, item.key)
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2auth/auth.go#L468-L517
|
func (ou User) merge(lg *zap.Logger, nu User, s PasswordStore) (User, error) {
var out User
if ou.User != nu.User {
return out, authErr(http.StatusConflict, "Merging user data with conflicting usernames: %s %s", ou.User, nu.User)
}
out.User = ou.User
if nu.Password != "" {
hash, err := s.HashPassword(nu.Password)
if err != nil {
return ou, err
}
out.Password = hash
} else {
out.Password = ou.Password
}
currentRoles := types.NewUnsafeSet(ou.Roles...)
for _, g := range nu.Grant {
if currentRoles.Contains(g) {
if lg != nil {
lg.Warn(
"attempted to grant a duplicate role for a user",
zap.String("user-name", nu.User),
zap.String("role-name", g),
)
} else {
plog.Noticef("granting duplicate role %s for user %s", g, nu.User)
}
return User{}, authErr(http.StatusConflict, fmt.Sprintf("Granting duplicate role %s for user %s", g, nu.User))
}
currentRoles.Add(g)
}
for _, r := range nu.Revoke {
if !currentRoles.Contains(r) {
if lg != nil {
lg.Warn(
"attempted to revoke a ungranted role for a user",
zap.String("user-name", nu.User),
zap.String("role-name", r),
)
} else {
plog.Noticef("revoking ungranted role %s for user %s", r, nu.User)
}
return User{}, authErr(http.StatusConflict, fmt.Sprintf("Revoking ungranted role %s for user %s", r, nu.User))
}
currentRoles.Remove(r)
}
out.Roles = currentRoles.Values()
sort.Strings(out.Roles)
return out, nil
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/proxy/grpcproxy/cluster.go#L156-L177
|
func (cp *clusterProxy) MemberList(ctx context.Context, r *pb.MemberListRequest) (*pb.MemberListResponse, error) {
if cp.advaddr != "" {
if cp.prefix != "" {
mbs, err := cp.membersFromUpdates()
if err != nil {
return nil, err
}
if len(mbs) > 0 {
return &pb.MemberListResponse{Members: mbs}, nil
}
}
// prefix is empty or no grpc-proxy members haven't been registered
hostname, _ := os.Hostname()
return &pb.MemberListResponse{Members: []*pb.Member{{Name: hostname, ClientURLs: []string{cp.advaddr}}}}, nil
}
mresp, err := cp.clus.MemberList(ctx)
if err != nil {
return nil, err
}
resp := (pb.MemberListResponse)(*mresp)
return &resp, err
}
| |
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/server.go#L101-L108
|
func (a *App) Stop(err error) error {
a.cancel()
if err != nil && errors.Cause(err) != context.Canceled {
a.Logger.Error(err)
return err
}
return nil
}
| |
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/transform/plugins/multiplexer_wrapper.go#L60-L68
|
func (m *MultiplexerPluginWrapper) ReceiveComment(comment sql.Comment) []Point {
points := []Point{}
for _, plugin := range m.plugins {
points = append(points, plugin.ReceiveComment(comment)...)
}
return points
}
| |
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/artifact-uploader/main.go#L127-L151
|
func (o *Options) Run() error {
clusterConfig, err := loadClusterConfig()
if err != nil {
return fmt.Errorf("failed to load cluster config: %v", err)
}
client, err := kubernetes.NewForConfig(clusterConfig)
if err != nil {
return err
}
prowJobClient, err := kube.NewClientInCluster(o.ProwJobNamespace)
if err != nil {
return err
}
controller := artifact_uploader.NewController(client.CoreV1(), prowJobClient, o.Options)
stop := make(chan struct{})
defer close(stop)
go controller.Run(o.NumWorkers, stop)
// Wait forever
select {}
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/cluster_util.go#L231-L240
|
func isCompatibleWithCluster(lg *zap.Logger, cl *membership.RaftCluster, local types.ID, rt http.RoundTripper) bool {
vers := getVersions(lg, cl, local, rt)
minV := semver.Must(semver.NewVersion(version.MinClusterVersion))
maxV := semver.Must(semver.NewVersion(version.Version))
maxV = &semver.Version{
Major: maxV.Major,
Minor: maxV.Minor,
}
return isCompatibleWithVers(lg, vers, local, minV, maxV)
}
| |
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/mail/internal/mail/message.go#L135-L163
|
func (m *Message) FormatAddress(address, name string) string {
if name == "" {
return address
}
enc := m.encodeString(name)
if enc == name {
m.buf.WriteByte('"')
for i := 0; i < len(name); i++ {
b := name[i]
if b == '\\' || b == '"' {
m.buf.WriteByte('\\')
}
m.buf.WriteByte(b)
}
m.buf.WriteByte('"')
} else if hasSpecials(name) {
m.buf.WriteString(bEncoding.Encode(m.charset, name))
} else {
m.buf.WriteString(enc)
}
m.buf.WriteString(" <")
m.buf.WriteString(address)
m.buf.WriteByte('>')
addr := m.buf.String()
m.buf.Reset()
return addr
}
| |
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/batch.go#L38-L47
|
func (db *DB) NewWriteBatch() *WriteBatch {
txn := db.newTransaction(true, true)
// If we let it stay at zero, compactions would not allow older key versions to be deleted,
// because the read timestamps of pending txns, would be zero. Therefore, we set it to the
// maximum read timestamp that's done. This allows compactions to discard key versions below
// this read timestamp, while also not blocking on pending txns to finish before starting this
// one.
txn.readTs = db.orc.readMark.DoneUntil()
return &WriteBatch{db: db, txn: txn}
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/retry.go#L103-L107
|
func RetryKVClient(c *Client) pb.KVClient {
return &retryKVClient{
kc: pb.NewKVClient(c.conn),
}
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/rpcpb/member.go#L255-L314
|
func (m *Member) SaveSnapshot(lg *zap.Logger) (err error) {
// remove existing snapshot first
if err = os.RemoveAll(m.SnapshotPath); err != nil {
return err
}
var ccfg *clientv3.Config
ccfg, err = m.CreateEtcdClientConfig()
if err != nil {
return fmt.Errorf("%v (%q)", err, m.EtcdClientEndpoint)
}
lg.Info(
"snapshot save START",
zap.String("member-name", m.Etcd.Name),
zap.Strings("member-client-urls", m.Etcd.AdvertiseClientURLs),
zap.String("snapshot-path", m.SnapshotPath),
)
now := time.Now()
mgr := snapshot.NewV3(lg)
if err = mgr.Save(context.Background(), *ccfg, m.SnapshotPath); err != nil {
return err
}
took := time.Since(now)
var fi os.FileInfo
fi, err = os.Stat(m.SnapshotPath)
if err != nil {
return err
}
var st snapshot.Status
st, err = mgr.Status(m.SnapshotPath)
if err != nil {
return err
}
m.SnapshotInfo = &SnapshotInfo{
MemberName: m.Etcd.Name,
MemberClientURLs: m.Etcd.AdvertiseClientURLs,
SnapshotPath: m.SnapshotPath,
SnapshotFileSize: humanize.Bytes(uint64(fi.Size())),
SnapshotTotalSize: humanize.Bytes(uint64(st.TotalSize)),
SnapshotTotalKey: int64(st.TotalKey),
SnapshotHash: int64(st.Hash),
SnapshotRevision: st.Revision,
Took: fmt.Sprintf("%v", took),
}
lg.Info(
"snapshot save END",
zap.String("member-name", m.SnapshotInfo.MemberName),
zap.Strings("member-client-urls", m.SnapshotInfo.MemberClientURLs),
zap.String("snapshot-path", m.SnapshotPath),
zap.String("snapshot-file-size", m.SnapshotInfo.SnapshotFileSize),
zap.String("snapshot-total-size", m.SnapshotInfo.SnapshotTotalSize),
zap.Int64("snapshot-total-key", m.SnapshotInfo.SnapshotTotalKey),
zap.Int64("snapshot-hash", m.SnapshotInfo.SnapshotHash),
zap.Int64("snapshot-revision", m.SnapshotInfo.SnapshotRevision),
zap.String("took", m.SnapshotInfo.Took),
)
return nil
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/server.go#L2248-L2288
|
func (s *EtcdServer) monitorVersions() {
for {
select {
case <-s.forceVersionC:
case <-time.After(monitorVersionInterval):
case <-s.stopping:
return
}
if s.Leader() != s.ID() {
continue
}
v := decideClusterVersion(s.getLogger(), getVersions(s.getLogger(), s.cluster, s.id, s.peerRt))
if v != nil {
// only keep major.minor version for comparison
v = &semver.Version{
Major: v.Major,
Minor: v.Minor,
}
}
// if the current version is nil:
// 1. use the decided version if possible
// 2. or use the min cluster version
if s.cluster.Version() == nil {
verStr := version.MinClusterVersion
if v != nil {
verStr = v.String()
}
s.goAttach(func() { s.updateClusterVersion(verStr) })
continue
}
// update cluster version only if the decided version is greater than
// the current cluster version
if v != nil && s.cluster.Version().LessThan(*v) {
s.goAttach(func() { s.updateClusterVersion(v.String()) })
}
}
}
| |
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/mail/internal/mail/message.go#L304-L306
|
func (m *Message) Attach(filename string, settings ...FileSetting) {
m.attachments = m.appendFile(m.attachments, fileFromFilename(filename), settings)
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/check.go#L106-L116
|
func NewCheckCommand() *cobra.Command {
cc := &cobra.Command{
Use: "check <subcommand>",
Short: "commands for checking properties of the etcd cluster",
}
cc.AddCommand(NewCheckPerfCommand())
cc.AddCommand(NewCheckDatascaleCommand())
return cc
}
| |
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/fakegithub/fakegithub.go#L140-L149
|
func (f *FakeClient) CreateComment(owner, repo string, number int, comment string) error {
f.IssueCommentsAdded = append(f.IssueCommentsAdded, fmt.Sprintf("%s/%s#%d:%s", owner, repo, number, comment))
f.IssueComments[number] = append(f.IssueComments[number], github.IssueComment{
ID: f.IssueCommentID,
Body: comment,
User: github.User{Login: botName},
})
f.IssueCommentID++
return nil
}
| |
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/iterator.go#L241-L246
|
func (s *MergeIterator) Rewind() {
for _, itr := range s.all {
itr.Rewind()
}
s.initHeap()
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/etcdhttp/base.go#L87-L109
|
func logHandleFunc(w http.ResponseWriter, r *http.Request) {
if !allowMethod(w, r, "PUT") {
return
}
in := struct{ Level string }{}
d := json.NewDecoder(r.Body)
if err := d.Decode(&in); err != nil {
WriteError(nil, w, r, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid json body"))
return
}
logl, err := capnslog.ParseLevel(strings.ToUpper(in.Level))
if err != nil {
WriteError(nil, w, r, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid log level "+in.Level))
return
}
plog.Noticef("globalLogLevel set to %q", logl.String())
capnslog.SetGlobalLogLevel(logl)
w.WriteHeader(http.StatusNoContent)
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/retry_interceptor.go#L102-L131
|
func (c *Client) streamClientInterceptor(logger *zap.Logger, optFuncs ...retryOption) grpc.StreamClientInterceptor {
intOpts := reuseOrNewWithCallOptions(defaultOptions, optFuncs)
return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
grpcOpts, retryOpts := filterCallOptions(opts)
callOpts := reuseOrNewWithCallOptions(intOpts, retryOpts)
// short circuit for simplicity, and avoiding allocations.
if callOpts.max == 0 {
return streamer(ctx, desc, cc, method, grpcOpts...)
}
if desc.ClientStreams {
return nil, grpc.Errorf(codes.Unimplemented, "clientv3/retry_interceptor: cannot retry on ClientStreams, set Disable()")
}
newStreamer, err := streamer(ctx, desc, cc, method, grpcOpts...)
logger.Warn("retry stream intercept", zap.Error(err))
if err != nil {
// TODO(mwitkow): Maybe dial and transport errors should be retriable?
return nil, err
}
retryingStreamer := &serverStreamingRetryingStream{
client: c,
ClientStream: newStreamer,
callOpts: callOpts,
ctx: ctx,
streamerCall: func(ctx context.Context) (grpc.ClientStream, error) {
return streamer(ctx, desc, cc, method, grpcOpts...)
},
}
return retryingStreamer, nil
}
}
| |
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/genny/build/validate.go#L67-L73
|
func PlushValidator(f genny.File) error {
if !genny.HasExt(f, ".html", ".md", ".plush") {
return nil
}
_, err := plush.Parse(f.String())
return err
}
| |
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/fakegithub/fakegithub.go#L360-L371
|
func (f *FakeClient) ListTeams(org string) ([]github.Team, error) {
return []github.Team{
{
ID: 0,
Name: "Admins",
},
{
ID: 42,
Name: "Leads",
},
}, nil
}
| |
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/transport.go#L22-L24
|
func (r *RPC) Respond(resp interface{}, err error) {
r.RespChan <- RPCResponse{resp, err}
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/mock/mockserver/mockserver.go#L123-L143
|
func (ms *MockServers) StartAt(idx int) (err error) {
ms.mu.Lock()
defer ms.mu.Unlock()
if ms.Servers[idx].ln == nil {
ms.Servers[idx].ln, err = net.Listen(ms.Servers[idx].Network, ms.Servers[idx].Address)
if err != nil {
return fmt.Errorf("failed to listen %v", err)
}
}
svr := grpc.NewServer()
pb.RegisterKVServer(svr, &mockKVServer{})
ms.Servers[idx].GrpcServer = svr
ms.wg.Add(1)
go func(svr *grpc.Server, l net.Listener) {
svr.Serve(l)
}(ms.Servers[idx].GrpcServer, ms.Servers[idx].ln)
return nil
}
| |
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/runtime/build.go#L16-L18
|
func (b BuildInfo) String() string {
return fmt.Sprintf("%s (%s)", b.Version, b.Time)
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/event_history.go#L58-L109
|
func (eh *EventHistory) scan(key string, recursive bool, index uint64) (*Event, *v2error.Error) {
eh.rwl.RLock()
defer eh.rwl.RUnlock()
// index should be after the event history's StartIndex
if index < eh.StartIndex {
return nil,
v2error.NewError(v2error.EcodeEventIndexCleared,
fmt.Sprintf("the requested history has been cleared [%v/%v]",
eh.StartIndex, index), 0)
}
// the index should come before the size of the queue minus the duplicate count
if index > eh.LastIndex { // future index
return nil, nil
}
offset := index - eh.StartIndex
i := (eh.Queue.Front + int(offset)) % eh.Queue.Capacity
for {
e := eh.Queue.Events[i]
if !e.Refresh {
ok := e.Node.Key == key
if recursive {
// add tailing slash
nkey := path.Clean(key)
if nkey[len(nkey)-1] != '/' {
nkey = nkey + "/"
}
ok = ok || strings.HasPrefix(e.Node.Key, nkey)
}
if (e.Action == Delete || e.Action == Expire) && e.PrevNode != nil && e.PrevNode.Dir {
ok = ok || strings.HasPrefix(key, e.PrevNode.Key)
}
if ok {
return e, nil
}
}
i = (i + 1) % eh.Queue.Capacity
if i == eh.Queue.Back {
return nil, nil
}
}
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/etcdserverpb/rpc.pb.go#L1111-L1119
|
func (*Compare) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
return _Compare_OneofMarshaler, _Compare_OneofUnmarshaler, _Compare_OneofSizer, []interface{}{
(*Compare_Version)(nil),
(*Compare_CreateRevision)(nil),
(*Compare_ModRevision)(nil),
(*Compare_Value)(nil),
(*Compare_Lease)(nil),
}
}
| |
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/net_transport.go#L414-L449
|
func (n *NetworkTransport) InstallSnapshot(id ServerID, target ServerAddress, args *InstallSnapshotRequest, resp *InstallSnapshotResponse, data io.Reader) error {
// Get a conn, always close for InstallSnapshot
conn, err := n.getConnFromAddressProvider(id, target)
if err != nil {
return err
}
defer conn.Release()
// Set a deadline, scaled by request size
if n.timeout > 0 {
timeout := n.timeout * time.Duration(args.Size/int64(n.TimeoutScale))
if timeout < n.timeout {
timeout = n.timeout
}
conn.conn.SetDeadline(time.Now().Add(timeout))
}
// Send the RPC
if err = sendRPC(conn, rpcInstallSnapshot, args); err != nil {
return err
}
// Stream the state
if _, err = io.Copy(conn.w, data); err != nil {
return err
}
// Flush
if err = conn.w.Flush(); err != nil {
return err
}
// Decode the response, do not return conn
_, err = decodeResponse(conn, resp)
return err
}
| |
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/raft.go#L1164-L1251
|
func (r *Raft) requestVote(rpc RPC, req *RequestVoteRequest) {
defer metrics.MeasureSince([]string{"raft", "rpc", "requestVote"}, time.Now())
r.observe(*req)
// Setup a response
resp := &RequestVoteResponse{
RPCHeader: r.getRPCHeader(),
Term: r.getCurrentTerm(),
Granted: false,
}
var rpcErr error
defer func() {
rpc.Respond(resp, rpcErr)
}()
// Version 0 servers will panic unless the peers is present. It's only
// used on them to produce a warning message.
if r.protocolVersion < 2 {
resp.Peers = encodePeers(r.configurations.latest, r.trans)
}
// Check if we have an existing leader [who's not the candidate]
candidate := r.trans.DecodePeer(req.Candidate)
if leader := r.Leader(); leader != "" && leader != candidate {
r.logger.Warn(fmt.Sprintf("Rejecting vote request from %v since we have a leader: %v",
candidate, leader))
return
}
// Ignore an older term
if req.Term < r.getCurrentTerm() {
return
}
// Increase the term if we see a newer one
if req.Term > r.getCurrentTerm() {
// Ensure transition to follower
r.setState(Follower)
r.setCurrentTerm(req.Term)
resp.Term = req.Term
}
// Check if we have voted yet
lastVoteTerm, err := r.stable.GetUint64(keyLastVoteTerm)
if err != nil && err.Error() != "not found" {
r.logger.Error(fmt.Sprintf("Failed to get last vote term: %v", err))
return
}
lastVoteCandBytes, err := r.stable.Get(keyLastVoteCand)
if err != nil && err.Error() != "not found" {
r.logger.Error(fmt.Sprintf("Failed to get last vote candidate: %v", err))
return
}
// Check if we've voted in this election before
if lastVoteTerm == req.Term && lastVoteCandBytes != nil {
r.logger.Info(fmt.Sprintf("Duplicate RequestVote for same term: %d", req.Term))
if bytes.Compare(lastVoteCandBytes, req.Candidate) == 0 {
r.logger.Warn(fmt.Sprintf("Duplicate RequestVote from candidate: %s", req.Candidate))
resp.Granted = true
}
return
}
// Reject if their term is older
lastIdx, lastTerm := r.getLastEntry()
if lastTerm > req.LastLogTerm {
r.logger.Warn(fmt.Sprintf("Rejecting vote request from %v since our last term is greater (%d, %d)",
candidate, lastTerm, req.LastLogTerm))
return
}
if lastTerm == req.LastLogTerm && lastIdx > req.LastLogIndex {
r.logger.Warn(fmt.Sprintf("Rejecting vote request from %v since our last index is greater (%d, %d)",
candidate, lastIdx, req.LastLogIndex))
return
}
// Persist a vote for safety
if err := r.persistVote(req.Term, req.Candidate); err != nil {
r.logger.Error(fmt.Sprintf("Failed to persist vote: %v", err))
return
}
resp.Granted = true
r.setLastContact()
return
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv2/command/rmdir_command.go#L38-L54
|
func rmdirCommandFunc(c *cli.Context, ki client.KeysAPI) {
if len(c.Args()) == 0 {
handleError(c, ExitBadArgs, errors.New("key required"))
}
key := c.Args()[0]
ctx, cancel := contextWithTotalTimeout(c)
resp, err := ki.Delete(ctx, key, &client.DeleteOptions{Dir: true})
cancel()
if err != nil {
handleError(c, ExitServerError, err)
}
if !resp.Node.Dir || c.GlobalString("output") != "simple" {
printResponseKey(resp, c.GlobalString("output"))
}
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/progress.go#L183-L185
|
func (pr *Progress) needSnapshotAbort() bool {
return pr.State == ProgressStateSnapshot && pr.Match >= pr.PendingSnapshot
}
| |
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/flagutil/github.go#L119-L146
|
func (o *GitHubOptions) GitClient(secretAgent *secret.Agent, dryRun bool) (client *git.Client, err error) {
client, err = git.NewClient()
if err != nil {
return nil, err
}
// We must capture the value of client here to prevent issues related
// to the use of named return values when an error is encountered.
// Without this, we risk a nil pointer dereference.
defer func(client *git.Client) {
if err != nil {
client.Clean()
}
}(client)
// Get the bot's name in order to set credentials for the Git client.
githubClient, err := o.GitHubClient(secretAgent, dryRun)
if err != nil {
return nil, fmt.Errorf("error getting GitHub client: %v", err)
}
botName, err := githubClient.BotName()
if err != nil {
return nil, fmt.Errorf("error getting bot name: %v", err)
}
client.SetCredentials(botName, secretAgent.GetTokenGenerator(o.TokenPath))
return client, nil
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/proxy/grpcproxy/health.go#L28-L30
|
func HandleHealth(mux *http.ServeMux, c *clientv3.Client) {
mux.Handle(etcdhttp.PathHealth, etcdhttp.NewHealthHandler(func() etcdhttp.Health { return checkHealth(c) }))
}
| |
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/render/plain.go#L20-L27
|
func (e *Engine) Plain(names ...string) Renderer {
hr := &templateRenderer{
Engine: e,
contentType: "text/plain; charset=utf-8",
names: names,
}
return hr
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/lease.go#L558-L589
|
func (l *lessor) sendKeepAliveLoop(stream pb.Lease_LeaseKeepAliveClient) {
for {
var tosend []LeaseID
now := time.Now()
l.mu.Lock()
for id, ka := range l.keepAlives {
if ka.nextKeepAlive.Before(now) {
tosend = append(tosend, id)
}
}
l.mu.Unlock()
for _, id := range tosend {
r := &pb.LeaseKeepAliveRequest{ID: int64(id)}
if err := stream.Send(r); err != nil {
// TODO do something with this error?
return
}
}
select {
case <-time.After(retryConnWait):
case <-stream.Context().Done():
return
case <-l.donec:
return
case <-l.stopCtx.Done():
return
}
}
}
| |
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/batch.go#L145-L154
|
func (wb *WriteBatch) Flush() error {
wb.Lock()
_ = wb.commit()
wb.txn.Discard()
wb.Unlock()
wb.wg.Wait()
// Safe to access error without any synchronization here.
return wb.err
}
| |
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/y.go#L137-L144
|
func ParseKey(key []byte) []byte {
if key == nil {
return nil
}
AssertTrue(len(key) > 8)
return key[:len(key)-8]
}
| |
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/agent.go#L106-L110
|
func (ca *Agent) Subscribe(subscription DeltaChan) {
ca.mut.Lock()
defer ca.mut.Unlock()
ca.subscriptions = append(ca.subscriptions, subscription)
}
| |
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/genny/build/validate.go#L78-L85
|
func GoTemplateValidator(f genny.File) error {
if !genny.HasExt(f, ".tmpl") {
return nil
}
t := template.New(f.Name())
_, err := t.Parse(f.String())
return err
}
| |
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/mail/internal/mail/message.go#L130-L132
|
func (m *Message) SetAddressHeader(field, address, name string) {
m.header[field] = []string{m.FormatAddress(address, name)}
}
| |
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/net_transport.go#L506-L532
|
func (n *NetworkTransport) handleConn(connCtx context.Context, conn net.Conn) {
defer conn.Close()
r := bufio.NewReader(conn)
w := bufio.NewWriter(conn)
dec := codec.NewDecoder(r, &codec.MsgpackHandle{})
enc := codec.NewEncoder(w, &codec.MsgpackHandle{})
for {
select {
case <-connCtx.Done():
n.logger.Println("[DEBUG] raft-net: stream layer is closed")
return
default:
}
if err := n.handleCommand(r, dec, enc); err != nil {
if err != io.EOF {
n.logger.Printf("[ERR] raft-net: Failed to decode incoming command: %v", err)
}
return
}
if err := w.Flush(); err != nil {
n.logger.Printf("[ERR] raft-net: Failed to flush response: %v", err)
return
}
}
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/schedule/schedule.go#L63-L72
|
func NewFIFOScheduler() Scheduler {
f := &fifo{
resume: make(chan struct{}, 1),
donec: make(chan struct{}, 1),
}
f.finishCond = sync.NewCond(&f.mu)
f.ctx, f.cancel = context.WithCancel(context.Background())
go f.run()
return f
}
| |
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/genny/mail/options.go#L18-L27
|
func (opts *Options) Validate() error {
if opts.App.IsZero() {
opts.App = meta.New(".")
}
if len(opts.Name.String()) == 0 {
return errors.New("you must supply a name for your mailer")
}
return nil
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv2/command/set_command.go#L27-L48
|
func NewSetCommand() cli.Command {
return cli.Command{
Name: "set",
Usage: "set the value of a key",
ArgsUsage: "<key> <value>",
Description: `Set sets the value of a key.
When <value> begins with '-', <value> is interpreted as a flag.
Insert '--' for workaround:
$ set -- <key> <value>`,
Flags: []cli.Flag{
cli.IntFlag{Name: "ttl", Value: 0, Usage: "key time-to-live in seconds"},
cli.StringFlag{Name: "swap-with-value", Value: "", Usage: "previous value"},
cli.IntFlag{Name: "swap-with-index", Value: 0, Usage: "previous index"},
},
Action: func(c *cli.Context) error {
setCommandFunc(c, mustNewKeyAPI(c))
return nil
},
}
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/member_command.go#L171-L188
|
func memberRemoveCommandFunc(cmd *cobra.Command, args []string) {
if len(args) != 1 {
ExitWithError(ExitBadArgs, fmt.Errorf("member ID is not provided"))
}
id, err := strconv.ParseUint(args[0], 16, 64)
if err != nil {
ExitWithError(ExitBadArgs, fmt.Errorf("bad member ID arg (%v), expecting ID in Hex", err))
}
ctx, cancel := commandCtx(cmd)
resp, err := mustClientFromCmd(cmd).MemberRemove(ctx, id)
cancel()
if err != nil {
ExitWithError(ExitError, err)
}
display.MemberRemove(id, *resp)
}
| |
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/genny/assets/standard/standard.go#L13-L33
|
func New(opts *Options) (*genny.Generator, error) {
g := genny.New()
g.Box(packr.New("buffalo:genny:assets:standard", "../standard/templates"))
data := map[string]interface{}{}
h := template.FuncMap{}
t := gogen.TemplateTransformer(data, h)
g.Transformer(t)
g.RunFn(func(r *genny.Runner) error {
f, err := r.FindFile("templates/application.html")
if err != nil {
return err
}
s := strings.Replace(f.String(), "</title>", "</title>\n"+bs4, 1)
return r.File(genny.NewFileS(f.Name(), s))
})
return g, nil
}
| |
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/tide/history/history.go#L140-L153
|
func (h *History) Record(poolKey, action, baseSHA, err string, targets []prowapi.Pull) {
t := now()
sort.Sort(ByNum(targets))
h.addRecord(
poolKey,
&Record{
Time: t,
Action: action,
BaseSHA: baseSHA,
Target: targets,
Err: err,
},
)
}
| |
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/value.go#L902-L929
|
func (vlog *valueLog) sync(fid uint32) error {
if vlog.opt.SyncWrites {
return nil
}
vlog.filesLock.RLock()
maxFid := atomic.LoadUint32(&vlog.maxFid)
// During replay it is possible to get sync call with fid less than maxFid.
// Because older file has already been synced, we can return from here.
if fid < maxFid || len(vlog.filesMap) == 0 {
vlog.filesLock.RUnlock()
return nil
}
curlf := vlog.filesMap[maxFid]
// Sometimes it is possible that vlog.maxFid has been increased but file creation
// with same id is still in progress and this function is called. In those cases
// entry for the file might not be present in vlog.filesMap.
if curlf == nil {
vlog.filesLock.RUnlock()
return nil
}
curlf.lock.RLock()
vlog.filesLock.RUnlock()
err := curlf.sync()
curlf.lock.RUnlock()
return err
}
| |
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/fakegithub/fakegithub.go#L229-L231
|
func (f *FakeClient) GetSingleCommit(org, repo, SHA string) (github.SingleCommit, error) {
return f.Commits[SHA], nil
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/integration/cluster.go#L475-L492
|
func (c *cluster) waitNoLeader(membs []*member) {
noLeader := false
for !noLeader {
noLeader = true
for _, m := range membs {
select {
case <-m.s.StopNotify():
continue
default:
}
if m.s.Lead() != 0 {
noLeader = false
time.Sleep(10 * tickDuration)
break
}
}
}
}
| |
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/tide.go#L258-L284
|
func (tqs TideQueries) OrgExceptionsAndRepos() (map[string]sets.String, sets.String) {
orgs := make(map[string]sets.String)
for i := range tqs {
for _, org := range tqs[i].Orgs {
applicableRepos := sets.NewString(reposInOrg(org, tqs[i].ExcludedRepos)...)
if excepts, ok := orgs[org]; !ok {
// We have not seen this org so the exceptions are just applicable
// members of 'excludedRepos'.
orgs[org] = applicableRepos
} else {
// We have seen this org so the exceptions are the applicable
// members of 'excludedRepos' intersected with existing exceptions.
orgs[org] = excepts.Intersection(applicableRepos)
}
}
}
repos := sets.NewString()
for i := range tqs {
repos.Insert(tqs[i].Repos...)
}
// Remove any org exceptions that are explicitly included in a different query.
reposList := repos.UnsortedList()
for _, excepts := range orgs {
excepts.Delete(reposList...)
}
return orgs, repos
}
| |
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/servers/simple.go#L14-L18
|
func (s *Simple) SetAddr(addr string) {
if s.Server.Addr == "" {
s.Server.Addr = addr
}
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/watcher_hub.go#L180-L186
|
func (wh *watcherHub) clone() *watcherHub {
clonedHistory := wh.EventHistory.clone()
return &watcherHub{
EventHistory: clonedHistory,
}
}
| |
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/errorutil/aggregate.go#L60-L66
|
func (agg aggregate) Error() string {
if len(agg) == 0 {
// This should never happen, really.
return ""
}
return fmt.Sprintf("[%s]", strings.Join(agg.Strings(), ", "))
}
| |
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/tcp_transport.go#L100-L102
|
func (t *TCPStreamLayer) Accept() (c net.Conn, err error) {
return t.listener.Accept()
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2v3/store.go#L582-L586
|
func (s *v2v3Store) mkPathDepth(nodePath string, depth int) string {
normalForm := path.Clean(path.Join("/", nodePath))
n := strings.Count(normalForm, "/") + depth
return fmt.Sprintf("%s/%03d/k/%s", s.pfx, n, normalForm)
}
| |
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/skl/arena.go#L130-L136
|
func (s *Arena) getNodeOffset(nd *node) uint32 {
if nd == nil {
return 0
}
return uint32(uintptr(unsafe.Pointer(nd)) - uintptr(unsafe.Pointer(&s.buf[0])))
}
| |
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/genny/build/_fixtures/coke/actions/app.go#L72-L78
|
func translations() buffalo.MiddlewareFunc {
var err error
if T, err = i18n.New(packr.New("../locales", "../locales"), "en-US"); err != nil {
app.Stop(err)
}
return T.Middleware()
}
| |
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/tcp_transport.go#L38-L48
|
func NewTCPTransportWithLogger(
bindAddr string,
advertise net.Addr,
maxPool int,
timeout time.Duration,
logger *log.Logger,
) (*NetworkTransport, error) {
return newTCPTransport(bindAddr, advertise, func(stream StreamLayer) *NetworkTransport {
return NewNetworkTransportWithLogger(stream, maxPool, timeout, logger)
})
}
| |
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/file_snapshot.go#L227-L271
|
func (f *FileSnapshotStore) getSnapshots() ([]*fileSnapshotMeta, error) {
// Get the eligible snapshots
snapshots, err := ioutil.ReadDir(f.path)
if err != nil {
f.logger.Printf("[ERR] snapshot: Failed to scan snapshot dir: %v", err)
return nil, err
}
// Populate the metadata
var snapMeta []*fileSnapshotMeta
for _, snap := range snapshots {
// Ignore any files
if !snap.IsDir() {
continue
}
// Ignore any temporary snapshots
dirName := snap.Name()
if strings.HasSuffix(dirName, tmpSuffix) {
f.logger.Printf("[WARN] snapshot: Found temporary snapshot: %v", dirName)
continue
}
// Try to read the meta data
meta, err := f.readMeta(dirName)
if err != nil {
f.logger.Printf("[WARN] snapshot: Failed to read metadata for %v: %v", dirName, err)
continue
}
// Make sure we can understand this version.
if meta.Version < SnapshotVersionMin || meta.Version > SnapshotVersionMax {
f.logger.Printf("[WARN] snapshot: Snapshot version for %v not supported: %d", dirName, meta.Version)
continue
}
// Append, but only return up to the retain count
snapMeta = append(snapMeta, meta)
}
// Sort the snapshot, reverse so we get new -> old
sort.Sort(sort.Reverse(snapMetaSlice(snapMeta)))
return snapMeta, nil
}
| |
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/value.go#L74-L94
|
func (lf *logFile) openReadOnly() error {
var err error
lf.fd, err = os.OpenFile(lf.path, os.O_RDONLY, 0666)
if err != nil {
return errors.Wrapf(err, "Unable to open %q as RDONLY.", lf.path)
}
fi, err := lf.fd.Stat()
if err != nil {
return errors.Wrapf(err, "Unable to check stat for %q", lf.path)
}
y.AssertTrue(fi.Size() <= math.MaxUint32)
lf.size = uint32(fi.Size())
if err = lf.mmap(fi.Size()); err != nil {
_ = lf.fd.Close()
return y.Wrapf(err, "Unable to map file")
}
return nil
}
| |
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/stream.go#L114-L125
|
func (st *Stream) produceRanges(ctx context.Context) {
splits := st.db.KeySplits(st.Prefix)
start := y.SafeCopy(nil, st.Prefix)
for _, key := range splits {
st.rangeCh <- keyRange{left: start, right: y.SafeCopy(nil, []byte(key))}
start = y.SafeCopy(nil, []byte(key))
}
// Edge case: prefix is empty and no splits exist. In that case, we should have at least one
// keyRange output.
st.rangeCh <- keyRange{left: start}
close(st.rangeCh)
}
| |
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/route_mappings.go#L234-L241
|
func (a *App) RouteHelpers() map[string]RouteHelperFunc {
rh := map[string]RouteHelperFunc{}
for _, route := range a.Routes() {
cRoute := route
rh[cRoute.PathName] = cRoute.BuildPathHelper()
}
return rh
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/adt/interval_tree.go#L406-L408
|
func (ivt *IntervalTree) MaxHeight() int {
return int((2 * math.Log2(float64(ivt.Len()+1))) + 0.5)
}
| |
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/raft.go#L931-L965
|
func (r *Raft) processLog(l *Log, future *logFuture) {
switch l.Type {
case LogBarrier:
// Barrier is handled by the FSM
fallthrough
case LogCommand:
// Forward to the fsm handler
select {
case r.fsmMutateCh <- &commitTuple{l, future}:
case <-r.shutdownCh:
if future != nil {
future.respond(ErrRaftShutdown)
}
}
// Return so that the future is only responded to
// by the FSM handler when the application is done
return
case LogConfiguration:
case LogAddPeerDeprecated:
case LogRemovePeerDeprecated:
case LogNoop:
// Ignore the no-op
default:
panic(fmt.Errorf("unrecognized log type: %#v", l))
}
// Invoke the future if given
if future != nil {
future.respond(nil)
}
}
| |
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/render/template.go#L56-L64
|
func (s templateRenderer) partialFeeder(name string) (string, error) {
ct := strings.ToLower(s.contentType)
d, f := filepath.Split(name)
name = filepath.Join(d, "_"+f)
name = fixExtension(name, ct)
return s.TemplatesBox.FindString(name)
}
| |
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/config.go#L203-L252
|
func (c *ServerConfig) advertiseMatchesCluster() error {
urls, apurls := c.InitialPeerURLsMap[c.Name], c.PeerURLs.StringSlice()
urls.Sort()
sort.Strings(apurls)
ctx, cancel := context.WithTimeout(context.TODO(), 30*time.Second)
defer cancel()
ok, err := netutil.URLStringsEqual(ctx, c.Logger, apurls, urls.StringSlice())
if ok {
return nil
}
initMap, apMap := make(map[string]struct{}), make(map[string]struct{})
for _, url := range c.PeerURLs {
apMap[url.String()] = struct{}{}
}
for _, url := range c.InitialPeerURLsMap[c.Name] {
initMap[url.String()] = struct{}{}
}
missing := []string{}
for url := range initMap {
if _, ok := apMap[url]; !ok {
missing = append(missing, url)
}
}
if len(missing) > 0 {
for i := range missing {
missing[i] = c.Name + "=" + missing[i]
}
mstr := strings.Join(missing, ",")
apStr := strings.Join(apurls, ",")
return fmt.Errorf("--initial-cluster has %s but missing from --initial-advertise-peer-urls=%s (%v)", mstr, apStr, err)
}
for url := range apMap {
if _, ok := initMap[url]; !ok {
missing = append(missing, url)
}
}
if len(missing) > 0 {
mstr := strings.Join(missing, ",")
umap := types.URLsMap(map[string]types.URLs{c.Name: c.PeerURLs})
return fmt.Errorf("--initial-advertise-peer-urls has %s but missing from --initial-cluster=%s", mstr, umap.String())
}
// resolved URLs from "--initial-advertise-peer-urls" and "--initial-cluster" did not match or failed
apStr := strings.Join(apurls, ",")
umap := types.URLsMap(map[string]types.URLs{c.Name: c.PeerURLs})
return fmt.Errorf("failed to resolve %s to match --initial-cluster=%s (%v)", apStr, umap.String(), err)
}
| |
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/branch_protection.go#L184-L192
|
func (o Org) GetRepo(name string) *Repo {
r, ok := o.Repos[name]
if ok {
r.Policy = o.Apply(r.Policy)
} else {
r.Policy = o.Policy
}
return &r
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.