_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/connection.go#L446-L458
func (c *Connection) recvMessage(ctx context.Context, msg message, mex *messageExchange) error { frame, err := mex.recvPeerFrameOfType(msg.messageType()) if err != nil { if err, ok := err.(errorMessage); ok { return err.AsSystemError() } return err } err = frame.read(msg) c.opts.FramePool.Release(frame) return err }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cron/cron.go#L73-L85
func (c *Cron) QueuedJobs() []string { c.lock.Lock() defer c.lock.Unlock() res := []string{} for k, v := range c.jobs { if v.triggered { res = append(res, k) } c.jobs[k].triggered = false } return res }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/merger/merger.go#L198-L250
func Match(rules []*rule.Rule, x *rule.Rule, info rule.KindInfo) (*rule.Rule, error) { xname := x.Name() xkind := x.Kind() var nameMatches []*rule.Rule var kindMatches []*rule.Rule for _, y := range rules { if xname == y.Name() { nameMatches = append(nameMatches, y) } if xkind == y.Kind() { kindMatches = append(kindMatches, y) } } if len(nameMatches) == 1 { y := nameMatches[0] if xkind != y.Kind() { return nil, fmt.Errorf("could not merge %s(%s): a rule of the same name has kind %s", xkind, xname, y.Kind()) } return y, nil } if len(nameMatches) > 1 { return nil, fmt.Errorf("could not merge %s(%s): multiple rules have the same name", xkind, xname) } for _, key := range info.MatchAttrs { var attrMatches []*rule.Rule xvalue := x.AttrString(key) if xvalue == "" { continue } for _, y := range kindMatches { if xvalue == y.AttrString(key) { attrMatches = append(attrMatches, y) } } if len(attrMatches) == 1 { return attrMatches[0], nil } else if len(attrMatches) > 1 { return nil, fmt.Errorf("could not merge %s(%s): multiple rules have the same attribute %s = %q", xkind, xname, key, xvalue) } } if info.MatchAny { if len(kindMatches) == 1 { return kindMatches[0], nil } else if len(kindMatches) > 1 { return nil, fmt.Errorf("could not merge %s(%s): multiple rules have the same kind but different names", xkind, xname) } } return nil, nil }
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/context.go#L154-L160
func (ctx *Context) Next() { // Call the next handler only if there is one and the response hasn't been written. if !ctx.Written() && ctx.index < len(ctx.handlersStack.Handlers)-1 { ctx.index++ ctx.handlersStack.Handlers[ctx.index](ctx) } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_pools.go#L122-L178
func (c *ClusterTx) StoragePoolNodeJoinCeph(poolID, nodeID int64) error { // Get the IDs of the other nodes (they should be all linked to // the pool). stmt := "SELECT node_id FROM storage_pools_nodes WHERE storage_pool_id=?" nodeIDs, err := query.SelectIntegers(c.tx, stmt, poolID) if err != nil { return errors.Wrap(err, "failed to fetch IDs of nodes with ceph pool") } if len(nodeIDs) == 0 { return fmt.Errorf("ceph pool is not linked to any node") } otherNodeID := nodeIDs[0] // Create entries of all the ceph volumes for the new node. _, err = c.tx.Exec(` INSERT INTO storage_volumes(name, storage_pool_id, node_id, type, description, project_id) SELECT name, storage_pool_id, ?, type, description, 1 FROM storage_volumes WHERE storage_pool_id=? AND node_id=? `, nodeID, poolID, otherNodeID) if err != nil { return errors.Wrap(err, "failed to create node ceph volumes") } // Create entries of all the ceph volumes configs for the new node. stmt = ` SELECT id FROM storage_volumes WHERE storage_pool_id=? AND node_id=? ORDER BY name, type ` volumeIDs, err := query.SelectIntegers(c.tx, stmt, poolID, nodeID) if err != nil { return errors.Wrap(err, "failed to get joining node's ceph volume IDs") } otherVolumeIDs, err := query.SelectIntegers(c.tx, stmt, poolID, otherNodeID) if err != nil { return errors.Wrap(err, "failed to get other node's ceph volume IDs") } if len(volumeIDs) != len(otherVolumeIDs) { // Sanity check return fmt.Errorf("not all ceph volumes were copied") } for i, otherVolumeID := range otherVolumeIDs { config, err := query.SelectConfig( c.tx, "storage_volumes_config", "storage_volume_id=?", otherVolumeID) if err != nil { return errors.Wrap(err, "failed to get storage volume config") } for key, value := range config { _, err := c.tx.Exec(` INSERT INTO storage_volumes_config(storage_volume_id, key, value) VALUES(?, ?, ?) `, volumeIDs[i], key, value) if err != nil { return errors.Wrap(err, "failed to copy volume config") } } } return nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_images.go#L309-L319
func (r *ProtocolLXD) GetImageAlias(name string) (*api.ImageAliasesEntry, string, error) { alias := api.ImageAliasesEntry{} // Fetch the raw value etag, err := r.queryStruct("GET", fmt.Sprintf("/images/aliases/%s", url.QueryEscape(name)), nil, "", &alias) if err != nil { return nil, "", err } return &alias, etag, nil }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/transaction.go#L200-L208
func (m ManageDataBuilder) MutateTransaction(o *TransactionBuilder) error { if m.Err != nil { return m.Err } m.O.Body, m.Err = xdr.NewOperationBody(xdr.OperationTypeManageData, m.MD) o.TX.Operations = append(o.TX.Operations, m.O) return m.Err }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/blobinfocache/memory/memory.go#L74-L88
func (mem *cache) RecordDigestUncompressedPair(anyDigest digest.Digest, uncompressed digest.Digest) { mem.mutex.Lock() defer mem.mutex.Unlock() if previous, ok := mem.uncompressedDigests[anyDigest]; ok && previous != uncompressed { logrus.Warnf("Uncompressed digest for blob %s previously recorded as %s, now %s", anyDigest, previous, uncompressed) } mem.uncompressedDigests[anyDigest] = uncompressed anyDigestSet, ok := mem.digestsByUncompressed[uncompressed] if !ok { anyDigestSet = map[digest.Digest]struct{}{} mem.digestsByUncompressed[uncompressed] = anyDigestSet } anyDigestSet[anyDigest] = struct{}{} // Possibly writing the same struct{}{} presence marker again. }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L486-L550
func (q *Query) GetAll(c context.Context, dst interface{}) ([]*Key, error) { var ( dv reflect.Value mat multiArgType elemType reflect.Type errFieldMismatch error ) if !q.keysOnly { dv = reflect.ValueOf(dst) if dv.Kind() != reflect.Ptr || dv.IsNil() { return nil, ErrInvalidEntityType } dv = dv.Elem() mat, elemType = checkMultiArg(dv) if mat == multiArgTypeInvalid || mat == multiArgTypeInterface { return nil, ErrInvalidEntityType } } var keys []*Key for t := q.Run(c); ; { k, e, err := t.next() if err == Done { break } if err != nil { return keys, err } if !q.keysOnly { ev := reflect.New(elemType) if elemType.Kind() == reflect.Map { // This is a special case. The zero values of a map type are // not immediately useful; they have to be make'd. // // Funcs and channels are similar, in that a zero value is not useful, // but even a freshly make'd channel isn't useful: there's no fixed // channel buffer size that is always going to be large enough, and // there's no goroutine to drain the other end. Theoretically, these // types could be supported, for example by sniffing for a constructor // method or requiring prior registration, but for now it's not a // frequent enough concern to be worth it. Programmers can work around // it by explicitly using Iterator.Next instead of the Query.GetAll // convenience method. x := reflect.MakeMap(elemType) ev.Elem().Set(x) } if err = loadEntity(ev.Interface(), e); err != nil { if _, ok := err.(*ErrFieldMismatch); ok { // We continue loading entities even in the face of field mismatch errors. // If we encounter any other error, that other error is returned. Otherwise, // an ErrFieldMismatch is returned. errFieldMismatch = err } else { return keys, err } } if mat != multiArgTypeStructPtr { ev = ev.Elem() } dv.Set(reflect.Append(dv, ev)) } keys = append(keys, k) } return keys, errFieldMismatch }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/secret/agent.go#L88-L92
func (a *Agent) GetSecret(secretPath string) []byte { a.RLock() defer a.RUnlock() return a.secretsMap[secretPath] }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/httpclient/http.go#L213-L230
func newRawClient( noRedirect, noCertCheck, disableKeepAlives bool, responseHeaderTimeout time.Duration) *http.Client { tr := http.Transport{ DisableKeepAlives: disableKeepAlives, ResponseHeaderTimeout: responseHeaderTimeout, Proxy: http.ProxyFromEnvironment, } tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: noCertCheck} c := http.Client{Transport: &tr} if noRedirect { c.CheckRedirect = func(*http.Request, []*http.Request) error { return fmt.Errorf(noRedirectError) } } return &c }
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/analyzer.go#L53-L107
func Preview(sql string) int { trimmed := StripLeadingComments(sql) firstWord := trimmed if end := strings.IndexFunc(trimmed, unicode.IsSpace); end != -1 { firstWord = trimmed[:end] } firstWord = strings.TrimLeftFunc(firstWord, func(r rune) bool { return !unicode.IsLetter(r) }) // Comparison is done in order of priority. loweredFirstWord := strings.ToLower(firstWord) switch loweredFirstWord { case "select": return StmtSelect case "stream": return StmtStream case "insert": return StmtInsert case "replace": return StmtReplace case "update": return StmtUpdate case "delete": return StmtDelete } // For the following statements it is not sufficient to rely // on loweredFirstWord. This is because they are not statements // in the grammar and we are relying on Preview to parse them. // For instance, we don't want: "BEGIN JUNK" to be parsed // as StmtBegin. trimmedNoComments, _ := SplitMarginComments(trimmed) switch strings.ToLower(trimmedNoComments) { case "begin", "start transaction": return StmtBegin case "commit": return StmtCommit case "rollback": return StmtRollback } switch loweredFirstWord { case "create", "alter", "rename", "drop", "truncate": return StmtDDL case "set": return StmtSet case "show": return StmtShow case "use": return StmtUse case "analyze", "describe", "desc", "explain", "repair", "optimize": return StmtOther } if strings.Index(trimmed, "/*!") == 0 { return StmtComment } return StmtUnknown }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pkg/discovery/etcd_client.go#L186-L207
func nodeToMap(node *etcd.Node, out map[string]string) bool { key := strings.TrimPrefix(node.Key, "/") if !node.Dir { if node.Value == "" { if _, ok := out[key]; ok { delete(out, key) return true } return false } if value, ok := out[key]; !ok || value != node.Value { out[key] = node.Value return true } return false } changed := false for _, node := range node.Nodes { changed = nodeToMap(node, out) || changed } return changed }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/db.go#L274-L285
func ForLocalInspectionWithPreparedStmts(db *sql.DB) (*Cluster, error) { c := ForLocalInspection(db) stmts, err := cluster.PrepareStmts(c.db) if err != nil { return nil, errors.Wrap(err, "Prepare database statements") } c.stmts = stmts return c, nil }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L222-L226
func (q *Query) KeysOnly() *Query { q = q.clone() q.keysOnly = true return q }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/easyjson.go#L850-L854
func (v *GetWindowBoundsParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoBrowser8(&r, v) return r.Error() }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/obj/amazon_client.go#L74-L80
func (v *vaultCredentialsProvider) updateLease(secret *vault.Secret) { v.leaseMu.Lock() defer v.leaseMu.Unlock() v.leaseID = secret.LeaseID v.leaseLastRenew = time.Now() v.leaseDuration = time.Duration(secret.LeaseDuration) * time.Second }
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/skiplist/stats.go#L134-L138
func (s *Skiplist) GetStats() StatsReport { var report StatsReport report.Apply(&s.Stats) return report }
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/static_files.go#L15-L26
func NewStaticFilesHandler(h http.Handler, prefix string, fs http.FileSystem) http.Handler { fileserver := http.StripPrefix(prefix, http.FileServer(fs)) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { filename := strings.TrimPrefix(r.URL.Path, prefix) _, err := fs.Open(filename) if err != nil { h.ServeHTTP(w, r) return } fileserver.ServeHTTP(w, r) }) }
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/trie/impl.go#L359-L363
func (t *Trie) printDebug() { fmt.Print("<trie>\n") t.root.printDebug(0) fmt.Print("</trie>\n") }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/exec/exec.go#L323-L397
func (c *Cmd) Start() error { if c.lookPathErr != nil { c.closeDescriptors(c.closeAfterStart) c.closeDescriptors(c.closeAfterWait) return c.lookPathErr } if runtime.GOOS == "windows" { lp, err := lookExtensions(c.Path, c.Dir) if err != nil { c.closeDescriptors(c.closeAfterStart) c.closeDescriptors(c.closeAfterWait) return err } c.Path = lp } if c.Process != nil { return errors.New("exec: already started") } if c.ctx != nil { select { case <-c.ctx.Done(): c.closeDescriptors(c.closeAfterStart) c.closeDescriptors(c.closeAfterWait) return c.ctx.Err() default: } } type F func(*Cmd) (*os.File, error) for _, setupFd := range []F{(*Cmd).stdin, (*Cmd).stdout, (*Cmd).stderr} { fd, err := setupFd(c) if err != nil { c.closeDescriptors(c.closeAfterStart) c.closeDescriptors(c.closeAfterWait) return err } c.childFiles = append(c.childFiles, fd) } c.childFiles = append(c.childFiles, c.ExtraFiles...) var err error c.Process, err = os.StartProcess(c.Path, c.argv(), &os.ProcAttr{ Dir: c.Dir, Files: c.childFiles, Env: dedupEnv(c.envv()), Sys: c.SysProcAttr, }) if err != nil { c.closeDescriptors(c.closeAfterStart) c.closeDescriptors(c.closeAfterWait) return err } c.closeDescriptors(c.closeAfterStart) c.errch = make(chan error, len(c.goroutine)) for _, fn := range c.goroutine { go func(fn func() error) { c.errch <- fn() }(fn) } if c.ctx != nil { c.waitDone = make(chan struct{}) go func() { select { case <-c.ctx.Done(): c.Process.Kill() case <-c.waitDone: } }() } return nil }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm16/codegen_client.go#L1878-L1880
func (r *ServerTemplate) Locator(api *API) *ServerTemplateLocator { return api.ServerTemplateLocator(r.Href) }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/data_types.go#L141-L165
func (d *APIDescriptor) uniqueTypeName(prefix string) string { u := fmt.Sprintf("%s%d", prefix, 2) taken := false for _, tn := range d.TypeNames { if tn == u { taken = true break } } idx := 3 for taken { u = fmt.Sprintf("%s%d", prefix, idx) taken = false for _, tn := range d.TypeNames { if tn == u { taken = true break } } if taken { idx++ } } return u }
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/type.go#L22-L26
func NewRat(a, b int64) *Rat { return &Rat{ Rat: big.NewRat(a, b), } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/easyjson.go#L582-L586
func (v SynthesizePinchGestureParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoInput3(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L292-L294
func (api *API) AlertLocator(href string) *AlertLocator { return &AlertLocator{Href(href), api} }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L4313-L4317
func (v EventBreakpointResolved) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDebugger41(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/archive/oci_transport.go#L162-L174
func createOCIRef(image string) (tempDirOCIRef, error) { dir, err := ioutil.TempDir(tmpdir.TemporaryDirectoryForBigFiles(), "oci") if err != nil { return tempDirOCIRef{}, errors.Wrapf(err, "error creating temp directory") } ociRef, err := ocilayout.NewReference(dir, image) if err != nil { return tempDirOCIRef{}, err } tempDirRef := tempDirOCIRef{tempDirectory: dir, ociRefExtracted: ociRef} return tempDirRef, nil }
https://github.com/antlinker/go-dirtyfilter/blob/533f538ffaa112776b1258c3db63e6f55648e18b/store/mongo.go#L20-L41
func NewMongoStore(config MongoConfig) (*MongoStore, error) { var session *mgo.Session if config.URL != "" { s, err := mgo.Dial(config.URL) if err != nil { return nil, err } session = s } else if config.Session != nil { session = config.Session } else { return nil, errors.New("未知的MongoDB连接") } if config.Collection == "" { config.Collection = DefaultCollection } return &MongoStore{ config: config, session: session, lg: log.New(os.Stdout, "[Mongo-Store]", log.LstdFlags), }, nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd-benchmark/benchmark/report.go#L30-L53
func (r *CSVReport) Load() error { file, err := os.Open(r.Filename) if err != nil { return err } defer file.Close() reader := csv.NewReader(file) for line := 1; err != io.EOF; line++ { record, err := reader.Read() if err == io.EOF { break } else if err != nil { return err } err = r.addRecord(record) if err != nil { return err } } logf("Loaded report file %s", r.Filename) return nil }
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/response.go#L40-L46
func Error(w ResponseWriter, error string, code int) { w.WriteHeader(code) err := w.WriteJson(map[string]string{ErrorFieldName: error}) if err != nil { panic(err) } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domdebugger/domdebugger.go#L199-L201
func (p *SetDOMBreakpointParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetDOMBreakpoint, p, nil) }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/context.go#L216-L250
func (c *Context) Original() (coal.Model, error) { // begin trace c.Tracer.Push("fire/Context.Original") // check operation if c.Operation != Update { panic("fire: the original can only be loaded during an update operation") } // return cached model if c.original != nil { c.Tracer.Pop() return c.original, nil } // create a new model m := c.Model.Meta().Make() // read original document c.Tracer.Push("mgo/Query.One") c.Tracer.Tag("id", c.Model.ID()) err := c.Store.C(c.Model).FindId(c.Model.ID()).One(m) if err != nil { return nil, err } c.Tracer.Pop() // cache model c.original = coal.Init(m) // finish trace c.Tracer.Pop() return c.original, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/fetch/types.go#L171-L173
func (t AuthChallengeResponseResponse) MarshalEasyJSON(out *jwriter.Writer) { out.String(string(t)) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/animation/easyjson.go#L648-L652
func (v ReleaseAnimationsParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoAnimation6(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/qor/roles/blob/d6375609fe3e5da46ad3a574fae244fb633e79c1/global.go#L44-L46
func HasRole(req *http.Request, user interface{}, roles ...string) bool { return Global.HasRole(req, user) }
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/compare.go#L609-L616
func makeAddressable(v reflect.Value) reflect.Value { if v.CanAddr() { return v } vc := reflect.New(v.Type()).Elem() vc.Set(v) return vc }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/introspection.go#L268-L274
func (ch *Channel) ReportInfo(opts *IntrospectionOptions) ChannelInfo { return ChannelInfo{ ID: ch.chID, CreatedStack: ch.createdStack, LocalPeer: ch.PeerInfo(), } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/pprof.go#L46-L109
func (e *Endpoints) PprofUpdateAddress(address string) error { if address != "" { address = util.CanonicalNetworkAddress(address) } oldAddress := e.NetworkAddress() if address == oldAddress { return nil } logger.Infof("Update pprof address") e.mu.Lock() defer e.mu.Unlock() // Close the previous socket e.closeListener(pprof) // If turning off listening, we're done if address == "" { return nil } // Attempt to setup the new listening socket getListener := func(address string) (*net.Listener, error) { var err error var listener net.Listener for i := 0; i < 10; i++ { // Ten retries over a second seems reasonable. listener, err = net.Listen("tcp", address) if err == nil { break } time.Sleep(100 * time.Millisecond) } if err != nil { return nil, fmt.Errorf("Cannot listen on http socket: %v", err) } return &listener, nil } // If setting a new address, setup the listener if address != "" { listener, err := getListener(address) if err != nil { // Attempt to revert to the previous address listener, err1 := getListener(oldAddress) if err1 == nil { e.listeners[pprof] = *listener e.serveHTTP(pprof) } return err } e.listeners[pprof] = *listener e.serveHTTP(pprof) } return nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_pools.go#L501-L507
func storagePoolClusterFillWithNodeConfig(dbConfig, reqConfig map[string]string) map[string]string { config := util.CopyConfig(reqConfig) for _, key := range db.StoragePoolNodeConfigKeys { config[key] = dbConfig[key] } return config }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/contrib/raftexample/raft.go#L81-L108
func newRaftNode(id int, peers []string, join bool, getSnapshot func() ([]byte, error), proposeC <-chan string, confChangeC <-chan raftpb.ConfChange) (<-chan *string, <-chan error, <-chan *snap.Snapshotter) { commitC := make(chan *string) errorC := make(chan error) rc := &raftNode{ proposeC: proposeC, confChangeC: confChangeC, commitC: commitC, errorC: errorC, id: id, peers: peers, join: join, waldir: fmt.Sprintf("raftexample-%d", id), snapdir: fmt.Sprintf("raftexample-%d-snap", id), getSnapshot: getSnapshot, snapCount: defaultSnapshotCount, stopc: make(chan struct{}), httpstopc: make(chan struct{}), httpdonec: make(chan struct{}), snapshotterReady: make(chan *snap.Snapshotter, 1), // rest of structure populated after WAL replay } go rc.startRaft() return commitC, errorC, rc.snapshotterReady }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift.go#L222-L227
func (s *openshiftImageSource) GetBlob(ctx context.Context, info types.BlobInfo, cache types.BlobInfoCache) (io.ReadCloser, int64, error) { if err := s.ensureImageIsResolved(ctx); err != nil { return nil, 0, err } return s.docker.GetBlob(ctx, info, cache) }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift-copies.go#L465-L480
func newAggregate(errlist []error) error { if len(errlist) == 0 { return nil } // In case of input error list contains nil var errs []error for _, e := range errlist { if e != nil { errs = append(errs, e) } } if len(errs) == 0 { return nil } return aggregateErr(errs) }
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/header.go#L306-L448
func consumeParam(s string) (consumed, rest string) { i := strings.IndexByte(s, '=') if i < 0 { return "", s } param := strings.Builder{} param.WriteString(s[:i+1]) s = s[i+1:] value := strings.Builder{} valueQuotedOriginally := false valueQuoteAdded := false valueQuoteNeeded := false var r rune findValueStart: for i, r = range s { switch r { case ' ', '\t': param.WriteRune(r) case '"': valueQuotedOriginally = true valueQuoteAdded = true value.WriteRune(r) break findValueStart default: valueQuotedOriginally = false valueQuoteAdded = false value.WriteRune(r) break findValueStart } } if len(s)-i < 1 { // parameter value starts at the end of the string, make empty // quoted string to play nice with mime.ParseMediaType param.WriteString(`""`) } else { // The beginning of the value is not at the end of the string s = s[i+1:] quoteIfUnquoted := func() { if !valueQuoteNeeded { if !valueQuoteAdded { param.WriteByte('"') valueQuoteAdded = true } valueQuoteNeeded = true } } findValueEnd: for len(s) > 0 { switch s[0] { case ';', ' ', '\t': if valueQuotedOriginally { // We're in a quoted string, so whitespace is allowed. value.WriteByte(s[0]) s = s[1:] break } // Otherwise, we've reached the end of an unquoted value. param.WriteString(value.String()) value.Reset() if valueQuoteNeeded { param.WriteByte('"') } param.WriteByte(s[0]) s = s[1:] break findValueEnd case '"': if valueQuotedOriginally { // We're in a quoted value. This is the end of that value. param.WriteString(value.String()) value.Reset() param.WriteByte(s[0]) s = s[1:] break findValueEnd } quoteIfUnquoted() value.WriteByte('\\') value.WriteByte(s[0]) s = s[1:] case '\\': if len(s) > 1 { value.WriteByte(s[0]) s = s[1:] // Backslash escapes the next char. Consume that next char. value.WriteByte(s[0]) quoteIfUnquoted() } // Else there is no next char to consume. s = s[1:] case '(', ')', '<', '>', '@', ',', ':', '/', '[', ']', '?', '=': quoteIfUnquoted() fallthrough default: value.WriteByte(s[0]) s = s[1:] } } } if value.Len() > 0 { // There is a value that ends with the string. Capture it. param.WriteString(value.String()) if valueQuotedOriginally || valueQuoteNeeded { // If valueQuotedOriginally is true and we got here, // that means there was no closing quote. So we'll add one. // Otherwise, we're here because it was an unquoted value // with a special char in it, and we had to quote it. param.WriteByte('"') } } return param.String(), s }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/log.go#L347-L361
func (l *raftLog) mustCheckOutOfBounds(lo, hi uint64) error { if lo > hi { l.logger.Panicf("invalid slice %d > %d", lo, hi) } fi := l.firstIndex() if lo < fi { return ErrCompacted } length := l.lastIndex() + 1 - fi if lo < fi || hi > fi+length { l.logger.Panicf("slice[%d,%d) out of bound [%d,%d]", lo, hi, fi, l.lastIndex()) } return nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/spyglass/gcsartifact.go#L140-L189
func (a *GCSArtifact) ReadAtMost(n int64) ([]byte, error) { var reader io.ReadCloser var p []byte gzipped, err := a.gzipped() if err != nil { return nil, fmt.Errorf("error checking artifact for gzip compression: %v", err) } if gzipped { reader, err = a.handle.NewReader(a.ctx) if err != nil { return nil, fmt.Errorf("error getting artifact reader: %v", err) } defer reader.Close() p, err = ioutil.ReadAll(reader) // Must readall for gzipped files if err != nil { return nil, fmt.Errorf("error reading all from artifact: %v", err) } artifactSize := int64(len(p)) readRange := n if n > artifactSize { readRange = artifactSize return p[:readRange], io.EOF } return p[:readRange], nil } artifactSize, err := a.Size() if err != nil { return nil, fmt.Errorf("error getting artifact size: %v", err) } readRange := n var gotEOF bool if n > artifactSize { gotEOF = true readRange = artifactSize } reader, err = a.handle.NewRangeReader(a.ctx, 0, readRange) if err != nil { return nil, fmt.Errorf("error getting artifact reader: %v", err) } defer reader.Close() p, err = ioutil.ReadAll(reader) if err != nil { return nil, fmt.Errorf("error reading all from artifact: %v", err) } if gotEOF { return p, io.EOF } return p, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L425-L444
func (p *GetResponseBodyParams) Do(ctx context.Context) (body []byte, err error) { // execute var res GetResponseBodyReturns err = cdp.Execute(ctx, CommandGetResponseBody, p, &res) if err != nil { return nil, err } // decode var dec []byte if res.Base64encoded { dec, err = base64.StdEncoding.DecodeString(res.Body) if err != nil { return nil, err } } else { dec = []byte(res.Body) } return dec, nil }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/y.go#L57-L67
func OpenExistingFile(filename string, flags uint32) (*os.File, error) { openFlags := os.O_RDWR if flags&ReadOnly != 0 { openFlags = os.O_RDONLY } if flags&Sync != 0 { openFlags |= datasyncFileFlag } return os.OpenFile(filename, openFlags, 0) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/termios/termios_unix.go#L54-L76
func MakeRaw(fd int) (*State, error) { var err error var oldState, newState *State oldState, err = GetState(fd) if err != nil { return nil, err } err = shared.DeepCopy(&oldState, &newState) if err != nil { return nil, err } C.cfmakeraw((*C.struct_termios)(unsafe.Pointer(&newState.Termios))) err = Restore(fd, newState) if err != nil { return nil, err } return oldState, nil }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/status.go#L116-L125
func makeUnicastRouteStatusSlice(r *routes) []unicastRouteStatus { r.RLock() defer r.RUnlock() var slice []unicastRouteStatus for dest, via := range r.unicast { slice = append(slice, unicastRouteStatus{dest.String(), via.String()}) } return slice }
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/decode.go#L1371-L1380
func (d *StreamDecoder) Encoder(e Emitter) (enc *StreamEncoder, err error) { var typ Type if typ, err = d.Parser.ParseType(); err == nil { enc = NewStreamEncoder(e) enc.oneshot = typ != Array } return }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/txn.go#L493-L507
func (txn *Txn) Discard() { if txn.discarded { // Avoid a re-run. return } if atomic.LoadInt32(&txn.numIterators) > 0 { panic("Unclosed iterator at time of Txn.Discard.") } txn.discarded = true if !txn.db.orc.isManaged { txn.db.orc.readMark.Done(txn.readTs) } if txn.update { txn.db.orc.decrRef() } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domdebugger/easyjson.go#L1030-L1034
func (v *EventListener) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDomdebugger10(&r, v) return r.Error() }
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/matchers.go#L181-L186
func ContainSubstring(substr string, args ...interface{}) types.GomegaMatcher { return &matchers.ContainSubstringMatcher{ Substr: substr, Args: args, } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/easyjson.go#L1047-L1051
func (v *GetObjectByHeapObjectIDReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoHeapprofiler11(&r, v) return r.Error() }
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/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L251-L266
func List(rs []io.ReadCloser, pattern string, f func(string, *NodeProto) error) (retErr error) { pattern = clean(pattern) if pattern == "" { pattern = "/" } g, err := globlib.Compile(pattern, '/') if err != nil { return errorf(MalformedGlob, err.Error()) } return nodes(rs, func(path string, node *NodeProto) error { if (g.Match(path) && node.DirNode == nil) || (g.Match(pathlib.Dir(path))) { return f(path, node) } return nil }) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L1377-L1387
func (r *ProtocolLXD) GetContainerState(name string) (*api.ContainerState, string, error) { state := api.ContainerState{} // Fetch the raw value etag, err := r.queryStruct("GET", fmt.Sprintf("/containers/%s/state", url.QueryEscape(name)), nil, "", &state) if err != nil { return nil, "", err } return &state, etag, nil }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/iaas.go#L179-L205
func templateDestroy(w http.ResponseWriter, r *http.Request, token auth.Token) (err error) { templateName := r.URL.Query().Get(":template_name") t, err := iaas.FindTemplate(templateName) if err != nil { if err == mgo.ErrNotFound { return &errors.HTTP{Code: http.StatusNotFound, Message: "template not found"} } return err } iaasCtx := permission.Context(permTypes.CtxIaaS, t.IaaSName) allowed := permission.Check(token, permission.PermMachineTemplateDelete, iaasCtx) if !allowed { return permission.ErrUnauthorized } evt, err := event.New(&event.Opts{ Target: event.Target{Type: event.TargetTypeIaas, Value: t.IaaSName}, Kind: permission.PermMachineTemplateDelete, Owner: token, CustomData: event.FormToCustomData(InputFields(r)), Allowed: event.Allowed(permission.PermMachineReadEvents, iaasCtx), }) if err != nil { return err } defer func() { evt.Done(err) }() return iaas.DestroyTemplate(templateName) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L4061-L4065
func (v GenerateTestReportParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage44(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pps/server/api_server.go#L2692-L2716
func (a *apiServer) incrementGCGeneration(ctx context.Context) error { resp, err := a.env.GetEtcdClient().Get(ctx, client.GCGenerationKey) if err != nil { return err } if resp.Count == 0 { // If the generation number does not exist, create it. // It's important that the new generation is 1, as the first // generation is assumed to be 0. if _, err := a.env.GetEtcdClient().Put(ctx, client.GCGenerationKey, "1"); err != nil { return err } } else { oldGen, err := strconv.Atoi(string(resp.Kvs[0].Value)) if err != nil { return err } newGen := oldGen + 1 if _, err := a.env.GetEtcdClient().Put(ctx, client.GCGenerationKey, strconv.Itoa(newGen)); err != nil { return err } } return nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/flags/urls.go#L63-L65
func URLsFromFlag(fs *flag.FlagSet, urlsFlagName string) []url.URL { return []url.URL(*fs.Lookup(urlsFlagName).Value.(*URLsValue)) }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selectable.go#L90-L92
func (s *selectable) FindByButton(text string) *Selection { return newSelection(s.session, s.selectors.Append(target.Button, text).Single()) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/config/map.go#L147-L179
func (m *Map) update(values map[string]string) ([]string, error) { // Detect if this is the first time we're setting values. This happens // when Load is called. initial := m.values == nil if initial { m.values = make(map[string]string, len(values)) } // Update our keys with the values from the given map, and keep track // of which keys actually changed their value. errors := ErrorList{} names := []string{} for name, value := range values { changed, err := m.set(name, value, initial) if err != nil { errors.add(name, value, err.Error()) continue } if changed { names = append(names, name) } } sort.Strings(names) var err error if errors.Len() > 0 { errors.sort() err = errors } return names, err }
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/skus/m1small/m1small.go#L73-L96
func (s *SkuM1Small) Procurement() *taskmanager.Task { agent := taskmanager.NewAgent(s.TaskManager, SkuName) task := agent.GetTask() agent.Run(func(ag *taskmanager.Agent) (err error) { if clnt, err := s.GetInnkeeperClient(); err == nil { if phinfo, err := clnt.ProvisionHost(ClientSkuName, s.UserIdentifier); err == nil { lo.G.Debug("provisionhost response: ", phinfo) ag.GetTask().Update(func(t *taskmanager.Task) interface{} { t.Status = taskmanager.AgentTaskStatusComplete t.SetPublicMeta(ProvisionHostInfoMetaName, phinfo) return t }) go s.StartPoller(phinfo.Data[0].RequestID, task) } else { return err } } return err }) return task }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L352-L355
func (p EvaluateParams) WithReturnByValue(returnByValue bool) *EvaluateParams { p.ReturnByValue = returnByValue return &p }
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/lan.go#L59-L64
func (c *Client) ListLans(dcid string) (*Lans, error) { url := lanColPath(dcid) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty) ret := &Lans{} err := c.client.Get(url, ret, http.StatusOK) return ret, err }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L373-L380
func (f *File) HasDefaultVisibility() bool { for _, r := range f.Rules { if r.Kind() == "package" && r.Attr("default_visibility") != nil { return true } } return false }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/key.go#L134-L146
func (k *Key) marshal(b *bytes.Buffer) { if k.parent != nil { k.parent.marshal(b) } b.WriteByte('/') b.WriteString(k.kind) b.WriteByte(',') if k.stringID != "" { b.WriteString(k.stringID) } else { b.WriteString(strconv.FormatInt(k.intID, 10)) } }
https://github.com/omniscale/go-mapnik/blob/710dfcc5e486e5760d0a5c46be909d91968e1ffb/mapnik.go#L146-L148
func (m *Map) SRS() string { return C.GoString(C.mapnik_map_get_srs(m.m)) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/deploy/cmds/cmds.go#L149-L661
func deployCmds(noMetrics *bool, noPortForwarding *bool) []*cobra.Command { var commands []*cobra.Command var opts *assets.AssetOpts var dryRun bool var outputFormat string var dev bool var hostPath string deployLocal := &cobra.Command{ Short: "Deploy a single-node Pachyderm cluster with local metadata storage.", Long: "Deploy a single-node Pachyderm cluster with local metadata storage.", Run: cmdutil.RunFixedArgs(0, func(args []string) (retErr error) { metrics := !*noMetrics if metrics && !dev { start := time.Now() startMetricsWait := _metrics.StartReportAndFlushUserAction("Deploy", start) defer startMetricsWait() defer func() { finishMetricsWait := _metrics.FinishReportAndFlushUserAction("Deploy", retErr, start) finishMetricsWait() }() } manifest := getEncoder(outputFormat) if dev { // Use dev build instead of release build opts.Version = deploy.DevVersionTag // we turn metrics off this is a dev cluster. The default is set by // deploy.PersistentPreRun, below. opts.Metrics = false // Disable authentication, for tests opts.DisableAuthentication = true // Serve the Pachyderm object/block API locally, as this is needed by // our tests (and authentication is disabled anyway) opts.ExposeObjectAPI = true } if err := assets.WriteLocalAssets(manifest, opts, hostPath); err != nil { return err } return kubectlCreate(dryRun, manifest, opts, metrics) }), } deployLocal.Flags().StringVar(&hostPath, "host-path", "/var/pachyderm", "Location on the host machine where PFS metadata will be stored.") deployLocal.Flags().BoolVarP(&dev, "dev", "d", false, "Deploy pachd with local version tags, disable metrics, expose Pachyderm's object/block API, and use an insecure authentication mechanism (do not set on any cluster with sensitive data)") commands = append(commands, cmdutil.CreateAlias(deployLocal, "deploy local")) deployGoogle := &cobra.Command{ Use: "{{alias}} <bucket-name> <disk-size> [<credentials-file>]", Short: "Deploy a Pachyderm cluster running on Google Cloud Platform.", Long: `Deploy a Pachyderm cluster running on Google Cloud Platform. <bucket-name>: A Google Cloud Storage bucket where Pachyderm will store PFS data. <disk-size>: Size of Google Compute Engine persistent disks in GB (assumed to all be the same). <credentials-file>: A file containing the private key for the account (downloaded from Google Compute Engine).`, Run: cmdutil.RunBoundedArgs(2, 3, func(args []string) (retErr error) { metrics := !*noMetrics if metrics { start := time.Now() startMetricsWait := _metrics.StartReportAndFlushUserAction("Deploy", start) defer startMetricsWait() defer func() { finishMetricsWait := _metrics.FinishReportAndFlushUserAction("Deploy", retErr, start) finishMetricsWait() }() } volumeSize, err := strconv.Atoi(args[1]) if err != nil { return fmt.Errorf("volume size needs to be an integer; instead got %v", args[1]) } manifest := getEncoder(outputFormat) opts.BlockCacheSize = "0G" // GCS is fast so we want to disable the block cache. See issue #1650 var cred string if len(args) == 3 { credBytes, err := ioutil.ReadFile(args[2]) if err != nil { return fmt.Errorf("error reading creds file %s: %v", args[2], err) } cred = string(credBytes) } bucket := strings.TrimPrefix(args[0], "gs://") if err = assets.WriteGoogleAssets(manifest, opts, bucket, cred, volumeSize); err != nil { return err } return kubectlCreate(dryRun, manifest, opts, metrics) }), } commands = append(commands, cmdutil.CreateAlias(deployGoogle, "deploy google")) var objectStoreBackend string var persistentDiskBackend string var secure bool var isS3V2 bool deployCustom := &cobra.Command{ Use: "{{alias}} --persistent-disk <persistent disk backend> --object-store <object store backend> <persistent disk args> <object store args>", Short: "Deploy a custom Pachyderm cluster configuration", Long: `Deploy a custom Pachyderm cluster configuration. If <object store backend> is \"s3\", then the arguments are: <volumes> <size of volumes (in GB)> <bucket> <id> <secret> <endpoint>`, Run: cmdutil.RunBoundedArgs(4, 7, func(args []string) (retErr error) { metrics := !*noMetrics if metrics { start := time.Now() startMetricsWait := _metrics.StartReportAndFlushUserAction("Deploy", start) defer startMetricsWait() defer func() { finishMetricsWait := _metrics.FinishReportAndFlushUserAction("Deploy", retErr, start) finishMetricsWait() }() } manifest := getEncoder(outputFormat) err := assets.WriteCustomAssets(manifest, opts, args, objectStoreBackend, persistentDiskBackend, secure, isS3V2) if err != nil { return err } return kubectlCreate(dryRun, manifest, opts, metrics) }), } deployCustom.Flags().BoolVarP(&secure, "secure", "s", false, "Enable secure access to a Minio server.") deployCustom.Flags().StringVar(&persistentDiskBackend, "persistent-disk", "aws", "(required) Backend providing persistent local volumes to stateful pods. "+ "One of: aws, google, or azure.") deployCustom.Flags().StringVar(&objectStoreBackend, "object-store", "s3", "(required) Backend providing an object-storage API to pachyderm. One of: "+ "s3, gcs, or azure-blob.") deployCustom.Flags().BoolVar(&isS3V2, "isS3V2", false, "Enable S3V2 client") commands = append(commands, cmdutil.CreateAlias(deployCustom, "deploy custom")) var cloudfrontDistribution string var creds string var iamRole string var vault string deployAmazon := &cobra.Command{ Use: "{{alias}} <bucket-name> <region> <disk-size>", Short: "Deploy a Pachyderm cluster running on AWS.", Long: `Deploy a Pachyderm cluster running on AWS. <bucket-name>: An S3 bucket where Pachyderm will store PFS data. <region>: The AWS region where Pachyderm is being deployed (e.g. us-west-1) <disk-size>: Size of EBS volumes, in GB (assumed to all be the same).`, Run: cmdutil.RunFixedArgs(3, func(args []string) (retErr error) { metrics := !*noMetrics if metrics { start := time.Now() startMetricsWait := _metrics.StartReportAndFlushUserAction("Deploy", start) defer startMetricsWait() defer func() { finishMetricsWait := _metrics.FinishReportAndFlushUserAction("Deploy", retErr, start) finishMetricsWait() }() } if creds == "" && vault == "" && iamRole == "" { return fmt.Errorf("One of --credentials, --vault, or --iam-role needs to be provided") } // populate 'amazonCreds' & validate var amazonCreds *assets.AmazonCreds s := bufio.NewScanner(os.Stdin) if creds != "" { parts := strings.Split(creds, ",") if len(parts) < 2 || len(parts) > 3 || containsEmpty(parts[:2]) { return fmt.Errorf("Incorrect format of --credentials") } amazonCreds = &assets.AmazonCreds{ID: parts[0], Secret: parts[1]} if len(parts) > 2 { amazonCreds.Token = parts[2] } if !awsAccessKeyIDRE.MatchString(amazonCreds.ID) { fmt.Printf("The AWS Access Key seems invalid (does not match %q). "+ "Do you want to continue deploying? [yN]\n", awsAccessKeyIDRE) if s.Scan(); s.Text()[0] != 'y' && s.Text()[0] != 'Y' { os.Exit(1) } } if !awsSecretRE.MatchString(amazonCreds.Secret) { fmt.Printf("The AWS Secret seems invalid (does not match %q). "+ "Do you want to continue deploying? [yN]\n", awsSecretRE) if s.Scan(); s.Text()[0] != 'y' && s.Text()[0] != 'Y' { os.Exit(1) } } } if vault != "" { if amazonCreds != nil { return fmt.Errorf("Only one of --credentials, --vault, or --iam-role needs to be provided") } parts := strings.Split(vault, ",") if len(parts) != 3 || containsEmpty(parts) { return fmt.Errorf("Incorrect format of --vault") } amazonCreds = &assets.AmazonCreds{VaultAddress: parts[0], VaultRole: parts[1], VaultToken: parts[2]} } if iamRole != "" { if amazonCreds != nil { return fmt.Errorf("Only one of --credentials, --vault, or --iam-role needs to be provided") } opts.IAMRole = iamRole } volumeSize, err := strconv.Atoi(args[2]) if err != nil { return fmt.Errorf("volume size needs to be an integer; instead got %v", args[2]) } if strings.TrimSpace(cloudfrontDistribution) != "" { fmt.Printf("WARNING: You specified a cloudfront distribution. Deploying on AWS with cloudfront is currently " + "an alpha feature. No security restrictions have been applied to cloudfront, making all data public (obscured but not secured)\n") } bucket, region := strings.TrimPrefix(args[0], "s3://"), args[1] if !awsRegionRE.MatchString(region) { fmt.Printf("The AWS region seems invalid (does not match %q). "+ "Do you want to continue deploying? [yN]\n", awsRegionRE) if s.Scan(); s.Text()[0] != 'y' && s.Text()[0] != 'Y' { os.Exit(1) } } // generate manifest and write assets manifest := getEncoder(outputFormat) if err = assets.WriteAmazonAssets(manifest, opts, region, bucket, volumeSize, amazonCreds, cloudfrontDistribution); err != nil { return err } return kubectlCreate(dryRun, manifest, opts, metrics) }), } deployAmazon.Flags().StringVar(&cloudfrontDistribution, "cloudfront-distribution", "", "Deploying on AWS with cloudfront is currently "+ "an alpha feature. No security restrictions have been"+ "applied to cloudfront, making all data public (obscured but not secured)") deployAmazon.Flags().StringVar(&creds, "credentials", "", "Use the format \"<id>,<secret>[,<token>]\". You can get a token by running \"aws sts get-session-token\".") deployAmazon.Flags().StringVar(&vault, "vault", "", "Use the format \"<address/hostport>,<role>,<token>\".") deployAmazon.Flags().StringVar(&iamRole, "iam-role", "", fmt.Sprintf("Use the given IAM role for authorization, as opposed to using static credentials. The given role will be applied as the annotation %s, this used with a Kubernetes IAM role management system such as kube2iam allows you to give pachd credentials in a more secure way.", assets.IAMAnnotation)) commands = append(commands, cmdutil.CreateAlias(deployAmazon, "deploy amazon")) deployMicrosoft := &cobra.Command{ Use: "{{alias}} <container> <account-name> <account-key> <disk-size>", Short: "Deploy a Pachyderm cluster running on Microsoft Azure.", Long: `Deploy a Pachyderm cluster running on Microsoft Azure. <container>: An Azure container where Pachyderm will store PFS data. <disk-size>: Size of persistent volumes, in GB (assumed to all be the same).`, Run: cmdutil.RunFixedArgs(4, func(args []string) (retErr error) { metrics := !*noMetrics if metrics { start := time.Now() startMetricsWait := _metrics.StartReportAndFlushUserAction("Deploy", start) defer startMetricsWait() defer func() { finishMetricsWait := _metrics.FinishReportAndFlushUserAction("Deploy", retErr, start) finishMetricsWait() }() } if _, err := base64.StdEncoding.DecodeString(args[2]); err != nil { return fmt.Errorf("storage-account-key needs to be base64 encoded; instead got '%v'", args[2]) } if opts.EtcdVolume != "" { tempURI, err := url.ParseRequestURI(opts.EtcdVolume) if err != nil { return fmt.Errorf("Volume URI needs to be a well-formed URI; instead got '%v'", opts.EtcdVolume) } opts.EtcdVolume = tempURI.String() } volumeSize, err := strconv.Atoi(args[3]) if err != nil { return fmt.Errorf("volume size needs to be an integer; instead got %v", args[3]) } manifest := getEncoder(outputFormat) container := strings.TrimPrefix(args[0], "wasb://") accountName, accountKey := args[1], args[2] if err = assets.WriteMicrosoftAssets(manifest, opts, container, accountName, accountKey, volumeSize); err != nil { return err } return kubectlCreate(dryRun, manifest, opts, metrics) }), } commands = append(commands, cmdutil.CreateAlias(deployMicrosoft, "deploy microsoft")) deployStorageSecrets := func(data map[string][]byte) error { c, err := client.NewOnUserMachine(!*noMetrics, !*noPortForwarding, "user") if err != nil { return fmt.Errorf("error constructing pachyderm client: %v", err) } defer c.Close() _, err = c.DeployStorageSecret(context.Background(), &deployclient.DeployStorageSecretRequest{ Secrets: data, }) if err != nil { return fmt.Errorf("error deploying storage secret to pachd: %v", err) } return nil } deployStorageAmazon := &cobra.Command{ Use: "{{alias}} <region> <bucket-id> <secret> [<token>]", Short: "Deploy credentials for the Amazon S3 storage provider.", Long: "Deploy credentials for the Amazon S3 storage provider, so that Pachyderm can ingress data from and egress data to it.", Run: cmdutil.RunBoundedArgs(3, 4, func(args []string) error { var token string if len(args) == 4 { token = args[3] } return deployStorageSecrets(assets.AmazonSecret(args[0], "", args[1], args[2], token, "")) }), } commands = append(commands, cmdutil.CreateAlias(deployStorageAmazon, "deploy storage amazon")) deployStorageGoogle := &cobra.Command{ Use: "{{alias}} <credentials-file>", Short: "Deploy credentials for the Google Cloud storage provider.", Long: "Deploy credentials for the Google Cloud storage provider, so that Pachyderm can ingress data from and egress data to it.", Run: cmdutil.RunFixedArgs(1, func(args []string) error { credBytes, err := ioutil.ReadFile(args[0]) if err != nil { return fmt.Errorf("error reading credentials file %s: %v", args[0], err) } return deployStorageSecrets(assets.GoogleSecret("", string(credBytes))) }), } commands = append(commands, cmdutil.CreateAlias(deployStorageGoogle, "deploy storage google")) deployStorageAzure := &cobra.Command{ Use: "{{alias}} <account-name> <account-key>", Short: "Deploy credentials for the Azure storage provider.", Long: "Deploy credentials for the Azure storage provider, so that Pachyderm can ingress data from and egress data to it.", Run: cmdutil.RunFixedArgs(2, func(args []string) error { return deployStorageSecrets(assets.MicrosoftSecret("", args[0], args[1])) }), } commands = append(commands, cmdutil.CreateAlias(deployStorageAzure, "deploy storage microsoft")) deployStorage := &cobra.Command{ Short: "Deploy credentials for a particular storage provider.", Long: "Deploy credentials for a particular storage provider, so that Pachyderm can ingress data from and egress data to it.", } commands = append(commands, cmdutil.CreateAlias(deployStorage, "deploy storage")) listImages := &cobra.Command{ Short: "Output the list of images in a deployment.", Long: "Output the list of images in a deployment.", Run: cmdutil.RunFixedArgs(0, func(args []string) error { for _, image := range assets.Images(opts) { fmt.Println(image) } return nil }), } commands = append(commands, cmdutil.CreateAlias(listImages, "deploy list-images")) exportImages := &cobra.Command{ Use: "{{alias}} <output-file>", Short: "Export a tarball (to stdout) containing all of the images in a deployment.", Long: "Export a tarball (to stdout) containing all of the images in a deployment.", Run: cmdutil.RunFixedArgs(1, func(args []string) (retErr error) { file, err := os.Create(args[0]) if err != nil { return err } defer func() { if err := file.Close(); err != nil && retErr == nil { retErr = err } }() return images.Export(opts, file) }), } commands = append(commands, cmdutil.CreateAlias(exportImages, "deploy export-images")) importImages := &cobra.Command{ Use: "{{alias}} <input-file>", Short: "Import a tarball (from stdin) containing all of the images in a deployment and push them to a private registry.", Long: "Import a tarball (from stdin) containing all of the images in a deployment and push them to a private registry.", Run: cmdutil.RunFixedArgs(1, func(args []string) (retErr error) { file, err := os.Open(args[0]) if err != nil { return err } defer func() { if err := file.Close(); err != nil && retErr == nil { retErr = err } }() return images.Import(opts, file) }), } commands = append(commands, cmdutil.CreateAlias(importImages, "deploy import-images")) var blockCacheSize string var dashImage string var dashOnly bool var etcdCPURequest string var etcdMemRequest string var etcdNodes int var etcdStorageClassName string var etcdVolume string var exposeObjectAPI bool var imagePullSecret string var localRoles bool var logLevel string var namespace string var newHashTree bool var noDash bool var noExposeDockerSocket bool var noGuaranteed bool var noRBAC bool var pachdCPURequest string var pachdNonCacheMemRequest string var pachdShards int var registry string var tlsCertKey string deploy := &cobra.Command{ Short: "Deploy a Pachyderm cluster.", Long: "Deploy a Pachyderm cluster.", PersistentPreRun: cmdutil.Run(func([]string) error { dashImage = getDefaultOrLatestDashImage(dashImage, dryRun) opts = &assets.AssetOpts{ FeatureFlags: assets.FeatureFlags{ NewHashTree: newHashTree, }, PachdShards: uint64(pachdShards), Version: version.PrettyPrintVersion(version.Version), LogLevel: logLevel, Metrics: !*noMetrics, PachdCPURequest: pachdCPURequest, PachdNonCacheMemRequest: pachdNonCacheMemRequest, BlockCacheSize: blockCacheSize, EtcdCPURequest: etcdCPURequest, EtcdMemRequest: etcdMemRequest, EtcdNodes: etcdNodes, EtcdVolume: etcdVolume, EtcdStorageClassName: etcdStorageClassName, DashOnly: dashOnly, NoDash: noDash, DashImage: dashImage, Registry: registry, ImagePullSecret: imagePullSecret, NoGuaranteed: noGuaranteed, NoRBAC: noRBAC, LocalRoles: localRoles, Namespace: namespace, NoExposeDockerSocket: noExposeDockerSocket, ExposeObjectAPI: exposeObjectAPI, } if tlsCertKey != "" { // TODO(msteffen): If either the cert path or the key path contains a // comma, this doesn't work certKey := strings.Split(tlsCertKey, ",") if len(certKey) != 2 { return fmt.Errorf("could not split TLS certificate and key correctly; must have two parts but got: %#v", certKey) } opts.TLS = &assets.TLSOpts{ ServerCert: certKey[0], ServerKey: certKey[1], } } return nil }), } deploy.PersistentFlags().IntVar(&pachdShards, "shards", 16, "(rarely set) The maximum number of pachd nodes allowed in the cluster; increasing this number blindly can result in degraded performance.") deploy.PersistentFlags().IntVar(&etcdNodes, "dynamic-etcd-nodes", 0, "Deploy etcd as a StatefulSet with the given number of pods. The persistent volumes used by these pods are provisioned dynamically. Note that StatefulSet is currently a beta kubernetes feature, which might be unavailable in older versions of kubernetes.") deploy.PersistentFlags().StringVar(&etcdVolume, "static-etcd-volume", "", "Deploy etcd as a ReplicationController with one pod. The pod uses the given persistent volume.") deploy.PersistentFlags().StringVar(&etcdStorageClassName, "etcd-storage-class", "", "If set, the name of an existing StorageClass to use for etcd storage. Ignored if --static-etcd-volume is set.") deploy.PersistentFlags().BoolVar(&dryRun, "dry-run", false, "Don't actually deploy pachyderm to Kubernetes, instead just print the manifest.") deploy.PersistentFlags().StringVarP(&outputFormat, "output", "o", "json", "Output formmat. One of: json|yaml") deploy.PersistentFlags().StringVar(&logLevel, "log-level", "info", "The level of log messages to print options are, from least to most verbose: \"error\", \"info\", \"debug\".") deploy.PersistentFlags().BoolVar(&dashOnly, "dashboard-only", false, "Only deploy the Pachyderm UI (experimental), without the rest of pachyderm. This is for launching the UI adjacent to an existing Pachyderm cluster. After deployment, run \"pachctl port-forward\" to connect") deploy.PersistentFlags().BoolVar(&noDash, "no-dashboard", false, "Don't deploy the Pachyderm UI alongside Pachyderm (experimental).") deploy.PersistentFlags().StringVar(&registry, "registry", "", "The registry to pull images from.") deploy.PersistentFlags().StringVar(&imagePullSecret, "image-pull-secret", "", "A secret in Kubernetes that's needed to pull from your private registry.") deploy.PersistentFlags().StringVar(&dashImage, "dash-image", "", "Image URL for pachyderm dashboard") deploy.PersistentFlags().BoolVar(&noGuaranteed, "no-guaranteed", false, "Don't use guaranteed QoS for etcd and pachd deployments. Turning this on (turning guaranteed QoS off) can lead to more stable local clusters (such as a on Minikube), it should normally be used for production clusters.") deploy.PersistentFlags().BoolVar(&noRBAC, "no-rbac", false, "Don't deploy RBAC roles for Pachyderm. (for k8s versions prior to 1.8)") deploy.PersistentFlags().BoolVar(&localRoles, "local-roles", false, "Use namespace-local roles instead of cluster roles. Ignored if --no-rbac is set.") deploy.PersistentFlags().StringVar(&namespace, "namespace", "default", "Kubernetes namespace to deploy Pachyderm to.") deploy.PersistentFlags().BoolVar(&noExposeDockerSocket, "no-expose-docker-socket", false, "Don't expose the Docker socket to worker containers. This limits the privileges of workers which prevents them from automatically setting the container's working dir and user.") deploy.PersistentFlags().BoolVar(&exposeObjectAPI, "expose-object-api", false, "If set, instruct pachd to serve its object/block API on its public port (not safe with auth enabled, do not set in production).") deploy.PersistentFlags().StringVar(&tlsCertKey, "tls", "", "string of the form \"<cert path>,<key path>\" of the signed TLS certificate and private key that Pachd should use for TLS authentication (enables TLS-encrypted communication with Pachd)") deploy.PersistentFlags().BoolVar(&newHashTree, "new-hash-tree-flag", false, "(feature flag) Do not set, used for testing") // Flags for setting pachd resource requests. These should rarely be set -- // only if we get the defaults wrong, or users have an unusual access pattern // // All of these are empty by default, because the actual default values depend // on the backend to which we're. The defaults are set in // s/s/pkg/deploy/assets/assets.go deploy.PersistentFlags().StringVar(&pachdCPURequest, "pachd-cpu-request", "", "(rarely set) The size of Pachd's CPU "+ "request, which we give to Kubernetes. Size is in cores (with partial "+ "cores allowed and encouraged).") deploy.PersistentFlags().StringVar(&blockCacheSize, "block-cache-size", "", "Size of pachd's in-memory cache for PFS files. Size is specified in "+ "bytes, with allowed SI suffixes (M, K, G, Mi, Ki, Gi, etc).") deploy.PersistentFlags().StringVar(&pachdNonCacheMemRequest, "pachd-memory-request", "", "(rarely set) The size of PachD's memory "+ "request in addition to its block cache (set via --block-cache-size). "+ "Size is in bytes, with SI suffixes (M, K, G, Mi, Ki, Gi, etc).") deploy.PersistentFlags().StringVar(&etcdCPURequest, "etcd-cpu-request", "", "(rarely set) The size of etcd's CPU request, "+ "which we give to Kubernetes. Size is in cores (with partial cores "+ "allowed and encouraged).") deploy.PersistentFlags().StringVar(&etcdMemRequest, "etcd-memory-request", "", "(rarely set) The size of etcd's memory "+ "request. Size is in bytes, with SI suffixes (M, K, G, Mi, Ki, Gi, "+ "etc).") commands = append(commands, cmdutil.CreateAlias(deploy, "deploy")) return commands }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcauth/tcauth.go#L240-L244
func (auth *Auth) DeleteClient(clientId string) error { cd := tcclient.Client(*auth) _, _, err := (&cd).APICall(nil, "DELETE", "/clients/"+url.QueryEscape(clientId), nil, nil) return err }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/meta/bundle.go#L44-L71
func (b *Bundle) StateAfter(key xdr.LedgerKey, opidx int) (*xdr.LedgerEntry, error) { all := b.changes(key, opidx) if len(all) == 0 { return nil, ErrMetaNotFound } change := all[len(all)-1] switch change.Type { case xdr.LedgerEntryChangeTypeLedgerEntryCreated: entry := change.MustCreated() return &entry, nil case xdr.LedgerEntryChangeTypeLedgerEntryRemoved: return nil, nil case xdr.LedgerEntryChangeTypeLedgerEntryUpdated: entry := change.MustUpdated() return &entry, nil case xdr.LedgerEntryChangeTypeLedgerEntryState: // scott: stellar-core should not emit a lone state entry, and we are // retrieving changes from the end of the collection. If this situation // occurs, it means that I didn't understand something correctly or there is // a bug in stellar-core. panic(fmt.Errorf("Unexpected 'state' entry")) default: panic(fmt.Errorf("Unknown change type: %v", change.Type)) } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/memory/memory.go#L151-L154
func (p StartSamplingParams) WithSuppressRandomness(suppressRandomness bool) *StartSamplingParams { p.SuppressRandomness = suppressRandomness return &p }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/maintenance/aws-janitor/resources/dhcp_options.go#L125-L159
func defaultLookingDHCPOptions(dhcp *ec2.DhcpOptions, region string) bool { if len(dhcp.Tags) != 0 { return false } for _, conf := range dhcp.DhcpConfigurations { switch *conf.Key { case "domain-name": var domain string // TODO(akutz): Should this be updated to regions.Default, or is // this relying on the default region for EC2 for North America? // Because EC2's default region changed from us-east-1 to us-east-2 // depending on when the account was created. if region == "us-east-1" { domain = "ec2.internal" } else { domain = region + ".compute.internal" } // TODO(vincepri): Investigate this line, seems it might segfault if conf.Values is 0? if len(conf.Values) != 1 || *conf.Values[0].Value != domain { return false } case "domain-name-servers": // TODO(vincepri): Same as above. if len(conf.Values) != 1 || *conf.Values[0].Value != "AmazonProvidedDNS" { return false } default: return false } } return true }
https://github.com/coryb/figtree/blob/e5fa026ccd54e0a6a99b6d81f73bfcc8e6fe6a6b/gen-rawoption.go#L601-L610
func (o *MapComplex128Option) Set(value string) error { parts := stringMapRegex.Split(value, 2) if len(parts) != 2 { return fmt.Errorf("expected KEY=VALUE got '%s'", value) } val := Complex128Option{} val.Set(parts[1]) (*o)[parts[0]] = val return nil }
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/mock_client.go#L72-L74
func (p *mockClient) ReifyMessage(request *types.PactReificationRequest) (res *types.ReificationResponse, err error) { return p.ReifyMessageResponse, p.ReifyMessageError }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/tnet/listener.go#L32-L34
func Wrap(l net.Listener) net.Listener { return &listener{Listener: l, cond: sync.NewCond(&sync.Mutex{})} }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cachestorage/cachestorage.go#L58-L60
func (p *DeleteEntryParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandDeleteEntry, p, nil) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/pretty/pretty.go#L31-L35
func TimeDifference(from *types.Timestamp, to *types.Timestamp) string { tFrom, _ := types.TimestampFromProto(from) tTo, _ := types.TimestampFromProto(to) return units.HumanDuration(tTo.Sub(tFrom)) }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/httpclient/http.go#L567-L582
func ctxhttpDo(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { if client == nil { client = http.DefaultClient } resp, err := client.Do(req.WithContext(ctx)) // If we got an error, and the context has been canceled, // the context's error is probably more useful. if err != nil { select { case <-ctx.Done(): err = ctx.Err() default: } } return resp, err }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/auth/server/api_server.go#L625-L650
func GitHubTokenToUsername(ctx context.Context, oauthToken string) (string, error) { if !githubTokenRegex.MatchString(oauthToken) && os.Getenv(DisableAuthenticationEnvVar) == "true" { logrus.Warnf("Pachyderm is deployed in DEV mode. The provided auth token "+ "will NOT be verified with GitHub; the caller is automatically "+ "authenticated as the GitHub user \"%s\"", oauthToken) return authclient.GitHubPrefix + oauthToken, nil } // Initialize GitHub client with 'oauthToken' ts := oauth2.StaticTokenSource( &oauth2.Token{ AccessToken: oauthToken, }, ) tc := oauth2.NewClient(ctx, ts) gclient := github.NewClient(tc) // Retrieve the caller's GitHub Username (the empty string gets us the // authenticated user) user, _, err := gclient.Users.Get(ctx, "") if err != nil { return "", fmt.Errorf("error getting the authenticated user: %v", err) } verifiedUsername := user.GetLogin() return authclient.GitHubPrefix + verifiedUsername, nil }
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mocktracer.go#L54-L58
func (t *MockTracer) Reset() { t.Lock() defer t.Unlock() t.finishedSpans = []*MockSpan{} }
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/code.go#L23-L29
func parseCode(str string) Code { code, err := strconv.Atoi(str) if err != nil { return Code(0) } return Code(code) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/agent/handler.go#L321-L392
func (srv *Server) saveTLSAssets() error { if srv.Member.PeerCertPath != "" { if srv.Member.PeerCertData == "" { return fmt.Errorf("got empty data for %q", srv.Member.PeerCertPath) } if err := ioutil.WriteFile(srv.Member.PeerCertPath, []byte(srv.Member.PeerCertData), 0644); err != nil { return err } } if srv.Member.PeerKeyPath != "" { if srv.Member.PeerKeyData == "" { return fmt.Errorf("got empty data for %q", srv.Member.PeerKeyPath) } if err := ioutil.WriteFile(srv.Member.PeerKeyPath, []byte(srv.Member.PeerKeyData), 0644); err != nil { return err } } if srv.Member.PeerTrustedCAPath != "" { if srv.Member.PeerTrustedCAData == "" { return fmt.Errorf("got empty data for %q", srv.Member.PeerTrustedCAPath) } if err := ioutil.WriteFile(srv.Member.PeerTrustedCAPath, []byte(srv.Member.PeerTrustedCAData), 0644); err != nil { return err } } if srv.Member.PeerCertPath != "" && srv.Member.PeerKeyPath != "" && srv.Member.PeerTrustedCAPath != "" { srv.lg.Info( "wrote", zap.String("peer-cert", srv.Member.PeerCertPath), zap.String("peer-key", srv.Member.PeerKeyPath), zap.String("peer-trusted-ca", srv.Member.PeerTrustedCAPath), ) } if srv.Member.ClientCertPath != "" { if srv.Member.ClientCertData == "" { return fmt.Errorf("got empty data for %q", srv.Member.ClientCertPath) } if err := ioutil.WriteFile(srv.Member.ClientCertPath, []byte(srv.Member.ClientCertData), 0644); err != nil { return err } } if srv.Member.ClientKeyPath != "" { if srv.Member.ClientKeyData == "" { return fmt.Errorf("got empty data for %q", srv.Member.ClientKeyPath) } if err := ioutil.WriteFile(srv.Member.ClientKeyPath, []byte(srv.Member.ClientKeyData), 0644); err != nil { return err } } if srv.Member.ClientTrustedCAPath != "" { if srv.Member.ClientTrustedCAData == "" { return fmt.Errorf("got empty data for %q", srv.Member.ClientTrustedCAPath) } if err := ioutil.WriteFile(srv.Member.ClientTrustedCAPath, []byte(srv.Member.ClientTrustedCAData), 0644); err != nil { return err } } if srv.Member.ClientCertPath != "" && srv.Member.ClientKeyPath != "" && srv.Member.ClientTrustedCAPath != "" { srv.lg.Info( "wrote", zap.String("client-cert", srv.Member.ClientCertPath), zap.String("client-key", srv.Member.ClientKeyPath), zap.String("client-trusted-ca", srv.Member.ClientTrustedCAPath), ) } return nil }
https://github.com/rlmcpherson/s3gof3r/blob/864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14/auth.go#L82-L92
func EnvKeys() (keys Keys, err error) { keys = Keys{ AccessKey: os.Getenv("AWS_ACCESS_KEY_ID"), SecretKey: os.Getenv("AWS_SECRET_ACCESS_KEY"), SecurityToken: os.Getenv("AWS_SECURITY_TOKEN"), } if keys.AccessKey == "" || keys.SecretKey == "" { err = fmt.Errorf("keys not set in environment: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY") } return }
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/client.go#L401-L414
func sanitiseRubyResponse(response string) string { log.Println("[TRACE] response from Ruby process pre-sanitisation:", response) r := regexp.MustCompile("(?m)^\\s*#.*$") s := r.ReplaceAllString(response, "") r = regexp.MustCompile("(?m).*bundle exec rake pact:verify.*$") s = r.ReplaceAllString(s, "") r = regexp.MustCompile("\\n+") s = r.ReplaceAllString(s, "\n") return s }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/util.go#L38-L50
func URLEncode(path string, query map[string]string) (string, error) { u, err := url.Parse(path) if err != nil { return "", err } params := url.Values{} for key, value := range query { params.Add(key, value) } u.RawQuery = params.Encode() return u.String(), nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/api/container.go#L95-L104
func (c Container) IsActive() bool { switch c.StatusCode { case Stopped: return false case Error: return false default: return true } }
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/service/lease.go#L49-L67
func (s *Lease) Post(logger *log.Logger, req *http.Request) (statusCode int, response interface{}) { var ( err error ) statusCode = http.StatusNotFound s.taskCollection.Wake() logger.Println("collection dialed successfully") if err = s.InitFromHTTPRequest(req); err == nil { logger.Println("obtaining lease...", s) s.Procurement() statusCode = http.StatusCreated response = s.Task } else { response = map[string]string{"error": err.Error()} } return }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/approve/approvers/owners.go#L675-L681
func getGubernatorMetadata(toBeAssigned []string) string { bytes, err := json.Marshal(map[string][]string{"approvers": toBeAssigned}) if err == nil { return fmt.Sprintf("\n<!-- META=%s -->", bytes) } return "" }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/types.go#L94-L126
func (t *TransitionType) UnmarshalEasyJSON(in *jlexer.Lexer) { switch TransitionType(in.String()) { case TransitionTypeLink: *t = TransitionTypeLink case TransitionTypeTyped: *t = TransitionTypeTyped case TransitionTypeAddressBar: *t = TransitionTypeAddressBar case TransitionTypeAutoBookmark: *t = TransitionTypeAutoBookmark case TransitionTypeAutoSubframe: *t = TransitionTypeAutoSubframe case TransitionTypeManualSubframe: *t = TransitionTypeManualSubframe case TransitionTypeGenerated: *t = TransitionTypeGenerated case TransitionTypeAutoToplevel: *t = TransitionTypeAutoToplevel case TransitionTypeFormSubmit: *t = TransitionTypeFormSubmit case TransitionTypeReload: *t = TransitionTypeReload case TransitionTypeKeyword: *t = TransitionTypeKeyword case TransitionTypeKeywordGenerated: *t = TransitionTypeKeywordGenerated case TransitionTypeOther: *t = TransitionTypeOther default: in.AddError(errors.New("unknown TransitionType value")) } }
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/ext/tags.go#L141-L143
func (tag spanKindTagName) Set(span opentracing.Span, value SpanKindEnum) { span.SetTag(string(tag), value) }
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/log/field.go#L81-L87
func Int64(key string, val int64) Field { return Field{ key: key, fieldType: int64Type, numericVal: val, } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L1980-L1984
func (v *QuerySelectorAllReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom21(&r, v) return r.Error() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L1458-L1463
func SetOuterHTML(nodeID cdp.NodeID, outerHTML string) *SetOuterHTMLParams { return &SetOuterHTMLParams{ NodeID: nodeID, OuterHTML: outerHTML, } }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcec2manager/tcec2manager.go#L178-L182
func (eC2Manager *EC2Manager) EnsureKeyPair(name string, payload *SSHPublicKey) error { cd := tcclient.Client(*eC2Manager) _, _, err := (&cd).APICall(payload, "GET", "/key-pairs/"+url.QueryEscape(name), nil, nil) return err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/performance/easyjson.go#L69-L73
func (v SetTimeDomainParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoPerformance(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/gateway.go#L640-L644
func dqliteMemoryDial(listener net.Listener) dqlite.DialFunc { return func(ctx context.Context, address string) (net.Conn, error) { return net.Dial("unix", listener.Addr().String()) } }
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/handler.go#L22-L24
func (hs *HandlersStack) Use(h RouterHandler) { hs.Handlers = append(hs.Handlers, h) }