id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
146,200
kubernetes-incubator/reference-docs
gen-apidocs/generators/api/config.go
visitResourcesInToc
func (c *Config) visitResourcesInToc() { missing := false for _, cat := range c.ResourceCategories { for _, r := range cat.Resources { if d, ok := c.Definitions.GetByVersionKind(r.Group, r.Version, r.Name); ok { d.InToc = true // Mark as in Toc d.initExample(c) r.Definition = d } else { fmt.Printf("Could not find definition for resource in TOC: %s %s %s.\n", r.Group, r.Version, r.Name) missing = true } } } if missing { fmt.Printf("All known definitions: %v\n", c.Definitions.All) } }
go
func (c *Config) visitResourcesInToc() { missing := false for _, cat := range c.ResourceCategories { for _, r := range cat.Resources { if d, ok := c.Definitions.GetByVersionKind(r.Group, r.Version, r.Name); ok { d.InToc = true // Mark as in Toc d.initExample(c) r.Definition = d } else { fmt.Printf("Could not find definition for resource in TOC: %s %s %s.\n", r.Group, r.Version, r.Name) missing = true } } } if missing { fmt.Printf("All known definitions: %v\n", c.Definitions.All) } }
[ "func", "(", "c", "*", "Config", ")", "visitResourcesInToc", "(", ")", "{", "missing", ":=", "false", "\n", "for", "_", ",", "cat", ":=", "range", "c", ".", "ResourceCategories", "{", "for", "_", ",", "r", ":=", "range", "cat", ".", "Resources", "{", "if", "d", ",", "ok", ":=", "c", ".", "Definitions", ".", "GetByVersionKind", "(", "r", ".", "Group", ",", "r", ".", "Version", ",", "r", ".", "Name", ")", ";", "ok", "{", "d", ".", "InToc", "=", "true", "// Mark as in Toc", "\n", "d", ".", "initExample", "(", "c", ")", "\n", "r", ".", "Definition", "=", "d", "\n", "}", "else", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "r", ".", "Group", ",", "r", ".", "Version", ",", "r", ".", "Name", ")", "\n", "missing", "=", "true", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "missing", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "c", ".", "Definitions", ".", "All", ")", "\n", "}", "\n", "}" ]
// For each resource in the ToC, look up its definition and visit it.
[ "For", "each", "resource", "in", "the", "ToC", "look", "up", "its", "definition", "and", "visit", "it", "." ]
9642bd3f4de59e831d66fecfeb3b465681ba5711
https://github.com/kubernetes-incubator/reference-docs/blob/9642bd3f4de59e831d66fecfeb3b465681ba5711/gen-apidocs/generators/api/config.go#L524-L541
146,201
kubernetes-incubator/reference-docs
gen-apidocs/generators/api/operation.go
GetOperationId
func (ot OperationType) GetOperationId(d string) string { return strings.Replace(ot.Match, "${resource}", d, -1) }
go
func (ot OperationType) GetOperationId(d string) string { return strings.Replace(ot.Match, "${resource}", d, -1) }
[ "func", "(", "ot", "OperationType", ")", "GetOperationId", "(", "d", "string", ")", "string", "{", "return", "strings", ".", "Replace", "(", "ot", ".", "Match", ",", "\"", "\"", ",", "d", ",", "-", "1", ")", "\n", "}" ]
// GetOperationId returns the ID of the operation for the given definition
[ "GetOperationId", "returns", "the", "ID", "of", "the", "operation", "for", "the", "given", "definition" ]
9642bd3f4de59e831d66fecfeb3b465681ba5711
https://github.com/kubernetes-incubator/reference-docs/blob/9642bd3f4de59e831d66fecfeb3b465681ba5711/gen-apidocs/generators/api/operation.go#L35-L37
146,202
kubernetes-incubator/reference-docs
gen-apidocs/generators/api/operation.go
VisitOperations
func VisitOperations(specs []*loads.Document, fn func(operation Operation)) { for _, d := range specs { for path, item := range d.Spec().Paths.Paths { for method, operation := range getOperationsForItem(item) { if operation != nil && !IsBlacklistedOperation(operation) { fn(Operation{ item: item, op: operation, Path: path, HttpMethod: method, ID: operation.ID, }) } } } } }
go
func VisitOperations(specs []*loads.Document, fn func(operation Operation)) { for _, d := range specs { for path, item := range d.Spec().Paths.Paths { for method, operation := range getOperationsForItem(item) { if operation != nil && !IsBlacklistedOperation(operation) { fn(Operation{ item: item, op: operation, Path: path, HttpMethod: method, ID: operation.ID, }) } } } } }
[ "func", "VisitOperations", "(", "specs", "[", "]", "*", "loads", ".", "Document", ",", "fn", "func", "(", "operation", "Operation", ")", ")", "{", "for", "_", ",", "d", ":=", "range", "specs", "{", "for", "path", ",", "item", ":=", "range", "d", ".", "Spec", "(", ")", ".", "Paths", ".", "Paths", "{", "for", "method", ",", "operation", ":=", "range", "getOperationsForItem", "(", "item", ")", "{", "if", "operation", "!=", "nil", "&&", "!", "IsBlacklistedOperation", "(", "operation", ")", "{", "fn", "(", "Operation", "{", "item", ":", "item", ",", "op", ":", "operation", ",", "Path", ":", "path", ",", "HttpMethod", ":", "method", ",", "ID", ":", "operation", ".", "ID", ",", "}", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// VisitOperations calls fn once for each operation found in the collection of Documents // VisitOperations calls fn once for each operation found in the collection of Documents
[ "VisitOperations", "calls", "fn", "once", "for", "each", "operation", "found", "in", "the", "collection", "of", "Documents", "VisitOperations", "calls", "fn", "once", "for", "each", "operation", "found", "in", "the", "collection", "of", "Documents" ]
9642bd3f4de59e831d66fecfeb3b465681ba5711
https://github.com/kubernetes-incubator/reference-docs/blob/9642bd3f4de59e831d66fecfeb3b465681ba5711/gen-apidocs/generators/api/operation.go#L81-L97
146,203
kubernetes-incubator/reference-docs
gen-apidocs/generators/api/operation.go
getOperationsForItem
func getOperationsForItem(pathItem spec.PathItem) map[string]*spec.Operation { return map[string]*spec.Operation{ "GET": pathItem.Get, "DELETE": pathItem.Delete, "PATCH": pathItem.Patch, "PUT": pathItem.Put, "POST": pathItem.Post, "HEAD": pathItem.Head, } }
go
func getOperationsForItem(pathItem spec.PathItem) map[string]*spec.Operation { return map[string]*spec.Operation{ "GET": pathItem.Get, "DELETE": pathItem.Delete, "PATCH": pathItem.Patch, "PUT": pathItem.Put, "POST": pathItem.Post, "HEAD": pathItem.Head, } }
[ "func", "getOperationsForItem", "(", "pathItem", "spec", ".", "PathItem", ")", "map", "[", "string", "]", "*", "spec", ".", "Operation", "{", "return", "map", "[", "string", "]", "*", "spec", ".", "Operation", "{", "\"", "\"", ":", "pathItem", ".", "Get", ",", "\"", "\"", ":", "pathItem", ".", "Delete", ",", "\"", "\"", ":", "pathItem", ".", "Patch", ",", "\"", "\"", ":", "pathItem", ".", "Put", ",", "\"", "\"", ":", "pathItem", ".", "Post", ",", "\"", "\"", ":", "pathItem", ".", "Head", ",", "}", "\n", "}" ]
// Get all operations from the pathitem so we cacn iterate over them
[ "Get", "all", "operations", "from", "the", "pathitem", "so", "we", "cacn", "iterate", "over", "them" ]
9642bd3f4de59e831d66fecfeb3b465681ba5711
https://github.com/kubernetes-incubator/reference-docs/blob/9642bd3f4de59e831d66fecfeb3b465681ba5711/gen-apidocs/generators/api/operation.go#L108-L117
146,204
kubernetes-incubator/reference-docs
gen-apidocs/generators/api/operation.go
initExample
func (o *Operation) initExample(config *Config) { path := o.Type.Name + ".yaml" path = filepath.Join(*ConfigDir, config.ExampleLocation, o.Definition.Name, path) path = strings.Replace(path, " ", "_", -1) path = strings.ToLower(path) content, err := ioutil.ReadFile(path) if err != nil { return } err = yaml.Unmarshal(content, &o.ExampleConfig) if err != nil { panic(fmt.Sprintf("Could not Unmarshal ExampleConfig yaml: %s\n", content)) } }
go
func (o *Operation) initExample(config *Config) { path := o.Type.Name + ".yaml" path = filepath.Join(*ConfigDir, config.ExampleLocation, o.Definition.Name, path) path = strings.Replace(path, " ", "_", -1) path = strings.ToLower(path) content, err := ioutil.ReadFile(path) if err != nil { return } err = yaml.Unmarshal(content, &o.ExampleConfig) if err != nil { panic(fmt.Sprintf("Could not Unmarshal ExampleConfig yaml: %s\n", content)) } }
[ "func", "(", "o", "*", "Operation", ")", "initExample", "(", "config", "*", "Config", ")", "{", "path", ":=", "o", ".", "Type", ".", "Name", "+", "\"", "\"", "\n", "path", "=", "filepath", ".", "Join", "(", "*", "ConfigDir", ",", "config", ".", "ExampleLocation", ",", "o", ".", "Definition", ".", "Name", ",", "path", ")", "\n", "path", "=", "strings", ".", "Replace", "(", "path", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "path", "=", "strings", ".", "ToLower", "(", "path", ")", "\n", "content", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "err", "=", "yaml", ".", "Unmarshal", "(", "content", ",", "&", "o", ".", "ExampleConfig", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "content", ")", ")", "\n", "}", "\n", "}" ]
// initExample reads the example config for an operation
[ "initExample", "reads", "the", "example", "config", "for", "an", "operation" ]
9642bd3f4de59e831d66fecfeb3b465681ba5711
https://github.com/kubernetes-incubator/reference-docs/blob/9642bd3f4de59e831d66fecfeb3b465681ba5711/gen-apidocs/generators/api/operation.go#L174-L187
146,205
kubernetes-incubator/reference-docs
gen-kubectldocs/generators/read_cmd.go
NewOptions
func NewOptions(flags *pflag.FlagSet) Options { result := Options{} flags.VisitAll(func(flag *pflag.Flag) { opt := &Option{ Name: flag.Name, Shorthand: flag.Shorthand, DefaultValue: flag.DefValue, Usage: flag.Usage, } result = append(result, opt) }) return result }
go
func NewOptions(flags *pflag.FlagSet) Options { result := Options{} flags.VisitAll(func(flag *pflag.Flag) { opt := &Option{ Name: flag.Name, Shorthand: flag.Shorthand, DefaultValue: flag.DefValue, Usage: flag.Usage, } result = append(result, opt) }) return result }
[ "func", "NewOptions", "(", "flags", "*", "pflag", ".", "FlagSet", ")", "Options", "{", "result", ":=", "Options", "{", "}", "\n", "flags", ".", "VisitAll", "(", "func", "(", "flag", "*", "pflag", ".", "Flag", ")", "{", "opt", ":=", "&", "Option", "{", "Name", ":", "flag", ".", "Name", ",", "Shorthand", ":", "flag", ".", "Shorthand", ",", "DefaultValue", ":", "flag", ".", "DefValue", ",", "Usage", ":", "flag", ".", "Usage", ",", "}", "\n", "result", "=", "append", "(", "result", ",", "opt", ")", "\n", "}", ")", "\n", "return", "result", "\n", "}" ]
// Parse the Options
[ "Parse", "the", "Options" ]
9642bd3f4de59e831d66fecfeb3b465681ba5711
https://github.com/kubernetes-incubator/reference-docs/blob/9642bd3f4de59e831d66fecfeb3b465681ba5711/gen-kubectldocs/generators/read_cmd.go#L66-L78
146,206
kubernetes-incubator/reference-docs
gen-kubectldocs/generators/read_cmd.go
NewSubCommands
func NewSubCommands(c *cobra.Command, path string) Commands { subCommands := Commands{NewCommand(c, path+c.Name())} for _, subCommand := range c.Commands() { subCommands = append(subCommands, NewSubCommands(subCommand, path+c.Name()+" ")...) } return subCommands }
go
func NewSubCommands(c *cobra.Command, path string) Commands { subCommands := Commands{NewCommand(c, path+c.Name())} for _, subCommand := range c.Commands() { subCommands = append(subCommands, NewSubCommands(subCommand, path+c.Name()+" ")...) } return subCommands }
[ "func", "NewSubCommands", "(", "c", "*", "cobra", ".", "Command", ",", "path", "string", ")", "Commands", "{", "subCommands", ":=", "Commands", "{", "NewCommand", "(", "c", ",", "path", "+", "c", ".", "Name", "(", ")", ")", "}", "\n", "for", "_", ",", "subCommand", ":=", "range", "c", ".", "Commands", "(", ")", "{", "subCommands", "=", "append", "(", "subCommands", ",", "NewSubCommands", "(", "subCommand", ",", "path", "+", "c", ".", "Name", "(", ")", "+", "\"", "\"", ")", "...", ")", "\n", "}", "\n", "return", "subCommands", "\n", "}" ]
// Parse the Commands
[ "Parse", "the", "Commands" ]
9642bd3f4de59e831d66fecfeb3b465681ba5711
https://github.com/kubernetes-incubator/reference-docs/blob/9642bd3f4de59e831d66fecfeb3b465681ba5711/gen-kubectldocs/generators/read_cmd.go#L81-L87
146,207
kubernetes-incubator/reference-docs
gen-apidocs/generators/api/open_api.go
LoadOpenApiSpec
func LoadOpenApiSpec() []*loads.Document { dir := filepath.Join(*ConfigDir, "openapi-spec/") docs := []*loads.Document{} err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { ext := filepath.Ext(path) if ext != ".json" { return nil } var d *loads.Document d, err = loads.JSONSpec(path) if err != nil { return fmt.Errorf("Could not load json file %s as api-spec: %v\n", path, err) } docs = append(docs, d) return nil }) if err != nil { os.Stderr.WriteString(fmt.Sprintf("%v", err)) os.Exit(1) } return docs }
go
func LoadOpenApiSpec() []*loads.Document { dir := filepath.Join(*ConfigDir, "openapi-spec/") docs := []*loads.Document{} err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { ext := filepath.Ext(path) if ext != ".json" { return nil } var d *loads.Document d, err = loads.JSONSpec(path) if err != nil { return fmt.Errorf("Could not load json file %s as api-spec: %v\n", path, err) } docs = append(docs, d) return nil }) if err != nil { os.Stderr.WriteString(fmt.Sprintf("%v", err)) os.Exit(1) } return docs }
[ "func", "LoadOpenApiSpec", "(", ")", "[", "]", "*", "loads", ".", "Document", "{", "dir", ":=", "filepath", ".", "Join", "(", "*", "ConfigDir", ",", "\"", "\"", ")", "\n", "docs", ":=", "[", "]", "*", "loads", ".", "Document", "{", "}", "\n", "err", ":=", "filepath", ".", "Walk", "(", "dir", ",", "func", "(", "path", "string", ",", "info", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "ext", ":=", "filepath", ".", "Ext", "(", "path", ")", "\n", "if", "ext", "!=", "\"", "\"", "{", "return", "nil", "\n", "}", "\n", "var", "d", "*", "loads", ".", "Document", "\n", "d", ",", "err", "=", "loads", ".", "JSONSpec", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "path", ",", "err", ")", "\n", "}", "\n", "docs", "=", "append", "(", "docs", ",", "d", ")", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "os", ".", "Stderr", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "return", "docs", "\n", "}" ]
// Loads all of the open-api documents
[ "Loads", "all", "of", "the", "open", "-", "api", "documents" ]
9642bd3f4de59e831d66fecfeb3b465681ba5711
https://github.com/kubernetes-incubator/reference-docs/blob/9642bd3f4de59e831d66fecfeb3b465681ba5711/gen-apidocs/generators/api/open_api.go#L37-L58
146,208
kubernetes-incubator/reference-docs
gen-apidocs/generators/api/open_api.go
buildGroupMap
func buildGroupMap(specs []*loads.Document) map[string]string { mapping := map[string]string{} mapping["apiregistration"] = "apiregistration.k8s.io" mapping["apiextensions"] = "apiextensions.k8s.io" mapping["certificates"] = "certificates.k8s.io" mapping["meta"] = "meta" mapping["core"] = "core" mapping["extensions"] = "extensions" for _, spec := range specs { for name, spec := range spec.Spec().Definitions { group, _, _ := GuessGVK(name) if _, found := mapping[group]; found { continue } // special groups where group name from extension is empty! if group == "meta" || group == "core" { continue } // full group not exposed as x-kubernetes- openapi extensions // from kube-aggregator project or apiextensions-apiserver project if group == "apiregistration" || group == "apiextensions" { continue } if extension, found := spec.Extensions[typeKey]; found { gvks, ok := extension.([]interface{}) if ok { for _, item := range gvks { gvk, ok := item.(map[string]interface{}) if ok { mapping[group] = gvk["group"].(string) break } } } } } } return mapping }
go
func buildGroupMap(specs []*loads.Document) map[string]string { mapping := map[string]string{} mapping["apiregistration"] = "apiregistration.k8s.io" mapping["apiextensions"] = "apiextensions.k8s.io" mapping["certificates"] = "certificates.k8s.io" mapping["meta"] = "meta" mapping["core"] = "core" mapping["extensions"] = "extensions" for _, spec := range specs { for name, spec := range spec.Spec().Definitions { group, _, _ := GuessGVK(name) if _, found := mapping[group]; found { continue } // special groups where group name from extension is empty! if group == "meta" || group == "core" { continue } // full group not exposed as x-kubernetes- openapi extensions // from kube-aggregator project or apiextensions-apiserver project if group == "apiregistration" || group == "apiextensions" { continue } if extension, found := spec.Extensions[typeKey]; found { gvks, ok := extension.([]interface{}) if ok { for _, item := range gvks { gvk, ok := item.(map[string]interface{}) if ok { mapping[group] = gvk["group"].(string) break } } } } } } return mapping }
[ "func", "buildGroupMap", "(", "specs", "[", "]", "*", "loads", ".", "Document", ")", "map", "[", "string", "]", "string", "{", "mapping", ":=", "map", "[", "string", "]", "string", "{", "}", "\n", "mapping", "[", "\"", "\"", "]", "=", "\"", "\"", "\n", "mapping", "[", "\"", "\"", "]", "=", "\"", "\"", "\n", "mapping", "[", "\"", "\"", "]", "=", "\"", "\"", "\n", "mapping", "[", "\"", "\"", "]", "=", "\"", "\"", "\n", "mapping", "[", "\"", "\"", "]", "=", "\"", "\"", "\n", "mapping", "[", "\"", "\"", "]", "=", "\"", "\"", "\n\n", "for", "_", ",", "spec", ":=", "range", "specs", "{", "for", "name", ",", "spec", ":=", "range", "spec", ".", "Spec", "(", ")", ".", "Definitions", "{", "group", ",", "_", ",", "_", ":=", "GuessGVK", "(", "name", ")", "\n", "if", "_", ",", "found", ":=", "mapping", "[", "group", "]", ";", "found", "{", "continue", "\n", "}", "\n", "// special groups where group name from extension is empty!", "if", "group", "==", "\"", "\"", "||", "group", "==", "\"", "\"", "{", "continue", "\n", "}", "\n\n", "// full group not exposed as x-kubernetes- openapi extensions", "// from kube-aggregator project or apiextensions-apiserver project", "if", "group", "==", "\"", "\"", "||", "group", "==", "\"", "\"", "{", "continue", "\n", "}", "\n\n", "if", "extension", ",", "found", ":=", "spec", ".", "Extensions", "[", "typeKey", "]", ";", "found", "{", "gvks", ",", "ok", ":=", "extension", ".", "(", "[", "]", "interface", "{", "}", ")", "\n", "if", "ok", "{", "for", "_", ",", "item", ":=", "range", "gvks", "{", "gvk", ",", "ok", ":=", "item", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "if", "ok", "{", "mapping", "[", "group", "]", "=", "gvk", "[", "\"", "\"", "]", ".", "(", "string", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "mapping", "\n", "}" ]
// return the map from short group name to full group name
[ "return", "the", "map", "from", "short", "group", "name", "to", "full", "group", "name" ]
9642bd3f4de59e831d66fecfeb3b465681ba5711
https://github.com/kubernetes-incubator/reference-docs/blob/9642bd3f4de59e831d66fecfeb3b465681ba5711/gen-apidocs/generators/api/open_api.go#L61-L102
146,209
docker/go-connections
tlsconfig/certpool_go17.go
SystemCertPool
func SystemCertPool() (*x509.CertPool, error) { certpool, err := x509.SystemCertPool() if err != nil && runtime.GOOS == "windows" { return x509.NewCertPool(), nil } return certpool, err }
go
func SystemCertPool() (*x509.CertPool, error) { certpool, err := x509.SystemCertPool() if err != nil && runtime.GOOS == "windows" { return x509.NewCertPool(), nil } return certpool, err }
[ "func", "SystemCertPool", "(", ")", "(", "*", "x509", ".", "CertPool", ",", "error", ")", "{", "certpool", ",", "err", ":=", "x509", ".", "SystemCertPool", "(", ")", "\n", "if", "err", "!=", "nil", "&&", "runtime", ".", "GOOS", "==", "\"", "\"", "{", "return", "x509", ".", "NewCertPool", "(", ")", ",", "nil", "\n", "}", "\n", "return", "certpool", ",", "err", "\n", "}" ]
// SystemCertPool returns a copy of the system cert pool, // returns an error if failed to load or empty pool on windows.
[ "SystemCertPool", "returns", "a", "copy", "of", "the", "system", "cert", "pool", "returns", "an", "error", "if", "failed", "to", "load", "or", "empty", "pool", "on", "windows", "." ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/tlsconfig/certpool_go17.go#L12-L18
146,210
docker/go-connections
sockets/sockets_unix.go
DialPipe
func DialPipe(_ string, _ time.Duration) (net.Conn, error) { return nil, syscall.EAFNOSUPPORT }
go
func DialPipe(_ string, _ time.Duration) (net.Conn, error) { return nil, syscall.EAFNOSUPPORT }
[ "func", "DialPipe", "(", "_", "string", ",", "_", "time", ".", "Duration", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "return", "nil", ",", "syscall", ".", "EAFNOSUPPORT", "\n", "}" ]
// DialPipe connects to a Windows named pipe. // This is not supported on other OSes.
[ "DialPipe", "connects", "to", "a", "Windows", "named", "pipe", ".", "This", "is", "not", "supported", "on", "other", "OSes", "." ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/sockets/sockets_unix.go#L36-L38
146,211
docker/go-connections
proxy/udp_proxy.go
Run
func (proxy *UDPProxy) Run() { readBuf := make([]byte, UDPBufSize) for { read, from, err := proxy.listener.ReadFromUDP(readBuf) if err != nil { // NOTE: Apparently ReadFrom doesn't return // ECONNREFUSED like Read do (see comment in // UDPProxy.replyLoop) if !isClosedError(err) { proxy.Logger.Printf("Stopping proxy on udp/%v for udp/%v (%s)", proxy.frontendAddr, proxy.backendAddr, err) } break } fromKey := newConnTrackKey(from) proxy.connTrackLock.Lock() proxyConn, hit := proxy.connTrackTable[*fromKey] if !hit { proxyConn, err = net.DialUDP("udp", nil, proxy.backendAddr) if err != nil { proxy.Logger.Printf("Can't proxy a datagram to udp/%s: %s\n", proxy.backendAddr, err) proxy.connTrackLock.Unlock() continue } proxy.connTrackTable[*fromKey] = proxyConn go proxy.replyLoop(proxyConn, from, fromKey) } proxy.connTrackLock.Unlock() for i := 0; i != read; { written, err := proxyConn.Write(readBuf[i:read]) if err != nil { proxy.Logger.Printf("Can't proxy a datagram to udp/%s: %s\n", proxy.backendAddr, err) break } i += written } } }
go
func (proxy *UDPProxy) Run() { readBuf := make([]byte, UDPBufSize) for { read, from, err := proxy.listener.ReadFromUDP(readBuf) if err != nil { // NOTE: Apparently ReadFrom doesn't return // ECONNREFUSED like Read do (see comment in // UDPProxy.replyLoop) if !isClosedError(err) { proxy.Logger.Printf("Stopping proxy on udp/%v for udp/%v (%s)", proxy.frontendAddr, proxy.backendAddr, err) } break } fromKey := newConnTrackKey(from) proxy.connTrackLock.Lock() proxyConn, hit := proxy.connTrackTable[*fromKey] if !hit { proxyConn, err = net.DialUDP("udp", nil, proxy.backendAddr) if err != nil { proxy.Logger.Printf("Can't proxy a datagram to udp/%s: %s\n", proxy.backendAddr, err) proxy.connTrackLock.Unlock() continue } proxy.connTrackTable[*fromKey] = proxyConn go proxy.replyLoop(proxyConn, from, fromKey) } proxy.connTrackLock.Unlock() for i := 0; i != read; { written, err := proxyConn.Write(readBuf[i:read]) if err != nil { proxy.Logger.Printf("Can't proxy a datagram to udp/%s: %s\n", proxy.backendAddr, err) break } i += written } } }
[ "func", "(", "proxy", "*", "UDPProxy", ")", "Run", "(", ")", "{", "readBuf", ":=", "make", "(", "[", "]", "byte", ",", "UDPBufSize", ")", "\n", "for", "{", "read", ",", "from", ",", "err", ":=", "proxy", ".", "listener", ".", "ReadFromUDP", "(", "readBuf", ")", "\n", "if", "err", "!=", "nil", "{", "// NOTE: Apparently ReadFrom doesn't return", "// ECONNREFUSED like Read do (see comment in", "// UDPProxy.replyLoop)", "if", "!", "isClosedError", "(", "err", ")", "{", "proxy", ".", "Logger", ".", "Printf", "(", "\"", "\"", ",", "proxy", ".", "frontendAddr", ",", "proxy", ".", "backendAddr", ",", "err", ")", "\n", "}", "\n", "break", "\n", "}", "\n\n", "fromKey", ":=", "newConnTrackKey", "(", "from", ")", "\n", "proxy", ".", "connTrackLock", ".", "Lock", "(", ")", "\n", "proxyConn", ",", "hit", ":=", "proxy", ".", "connTrackTable", "[", "*", "fromKey", "]", "\n", "if", "!", "hit", "{", "proxyConn", ",", "err", "=", "net", ".", "DialUDP", "(", "\"", "\"", ",", "nil", ",", "proxy", ".", "backendAddr", ")", "\n", "if", "err", "!=", "nil", "{", "proxy", ".", "Logger", ".", "Printf", "(", "\"", "\\n", "\"", ",", "proxy", ".", "backendAddr", ",", "err", ")", "\n", "proxy", ".", "connTrackLock", ".", "Unlock", "(", ")", "\n", "continue", "\n", "}", "\n", "proxy", ".", "connTrackTable", "[", "*", "fromKey", "]", "=", "proxyConn", "\n", "go", "proxy", ".", "replyLoop", "(", "proxyConn", ",", "from", ",", "fromKey", ")", "\n", "}", "\n", "proxy", ".", "connTrackLock", ".", "Unlock", "(", ")", "\n", "for", "i", ":=", "0", ";", "i", "!=", "read", ";", "{", "written", ",", "err", ":=", "proxyConn", ".", "Write", "(", "readBuf", "[", "i", ":", "read", "]", ")", "\n", "if", "err", "!=", "nil", "{", "proxy", ".", "Logger", ".", "Printf", "(", "\"", "\\n", "\"", ",", "proxy", ".", "backendAddr", ",", "err", ")", "\n", "break", "\n", "}", "\n", "i", "+=", "written", "\n", "}", "\n", "}", "\n", "}" ]
// Run starts forwarding the traffic using UDP.
[ "Run", "starts", "forwarding", "the", "traffic", "using", "UDP", "." ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/proxy/udp_proxy.go#L113-L150
146,212
docker/go-connections
nat/nat.go
NewPort
func NewPort(proto, port string) (Port, error) { // Check for parsing issues on "port" now so we can avoid having // to check it later on. portStartInt, portEndInt, err := ParsePortRangeToInt(port) if err != nil { return "", err } if portStartInt == portEndInt { return Port(fmt.Sprintf("%d/%s", portStartInt, proto)), nil } return Port(fmt.Sprintf("%d-%d/%s", portStartInt, portEndInt, proto)), nil }
go
func NewPort(proto, port string) (Port, error) { // Check for parsing issues on "port" now so we can avoid having // to check it later on. portStartInt, portEndInt, err := ParsePortRangeToInt(port) if err != nil { return "", err } if portStartInt == portEndInt { return Port(fmt.Sprintf("%d/%s", portStartInt, proto)), nil } return Port(fmt.Sprintf("%d-%d/%s", portStartInt, portEndInt, proto)), nil }
[ "func", "NewPort", "(", "proto", ",", "port", "string", ")", "(", "Port", ",", "error", ")", "{", "// Check for parsing issues on \"port\" now so we can avoid having", "// to check it later on.", "portStartInt", ",", "portEndInt", ",", "err", ":=", "ParsePortRangeToInt", "(", "port", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "if", "portStartInt", "==", "portEndInt", "{", "return", "Port", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "portStartInt", ",", "proto", ")", ")", ",", "nil", "\n", "}", "\n", "return", "Port", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "portStartInt", ",", "portEndInt", ",", "proto", ")", ")", ",", "nil", "\n", "}" ]
// NewPort creates a new instance of a Port given a protocol and port number or port range
[ "NewPort", "creates", "a", "new", "instance", "of", "a", "Port", "given", "a", "protocol", "and", "port", "number", "or", "port", "range" ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/nat/nat.go#L34-L47
146,213
docker/go-connections
nat/nat.go
ParsePort
func ParsePort(rawPort string) (int, error) { if len(rawPort) == 0 { return 0, nil } port, err := strconv.ParseUint(rawPort, 10, 16) if err != nil { return 0, err } return int(port), nil }
go
func ParsePort(rawPort string) (int, error) { if len(rawPort) == 0 { return 0, nil } port, err := strconv.ParseUint(rawPort, 10, 16) if err != nil { return 0, err } return int(port), nil }
[ "func", "ParsePort", "(", "rawPort", "string", ")", "(", "int", ",", "error", ")", "{", "if", "len", "(", "rawPort", ")", "==", "0", "{", "return", "0", ",", "nil", "\n", "}", "\n", "port", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "rawPort", ",", "10", ",", "16", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "int", "(", "port", ")", ",", "nil", "\n", "}" ]
// ParsePort parses the port number string and returns an int
[ "ParsePort", "parses", "the", "port", "number", "string", "and", "returns", "an", "int" ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/nat/nat.go#L50-L59
146,214
docker/go-connections
nat/nat.go
Proto
func (p Port) Proto() string { proto, _ := SplitProtoPort(string(p)) return proto }
go
func (p Port) Proto() string { proto, _ := SplitProtoPort(string(p)) return proto }
[ "func", "(", "p", "Port", ")", "Proto", "(", ")", "string", "{", "proto", ",", "_", ":=", "SplitProtoPort", "(", "string", "(", "p", ")", ")", "\n", "return", "proto", "\n", "}" ]
// Proto returns the protocol of a Port
[ "Proto", "returns", "the", "protocol", "of", "a", "Port" ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/nat/nat.go#L74-L77
146,215
docker/go-connections
nat/nat.go
Port
func (p Port) Port() string { _, port := SplitProtoPort(string(p)) return port }
go
func (p Port) Port() string { _, port := SplitProtoPort(string(p)) return port }
[ "func", "(", "p", "Port", ")", "Port", "(", ")", "string", "{", "_", ",", "port", ":=", "SplitProtoPort", "(", "string", "(", "p", ")", ")", "\n", "return", "port", "\n", "}" ]
// Port returns the port number of a Port
[ "Port", "returns", "the", "port", "number", "of", "a", "Port" ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/nat/nat.go#L80-L83
146,216
docker/go-connections
nat/nat.go
Int
func (p Port) Int() int { portStr := p.Port() // We don't need to check for an error because we're going to // assume that any error would have been found, and reported, in NewPort() port, _ := ParsePort(portStr) return port }
go
func (p Port) Int() int { portStr := p.Port() // We don't need to check for an error because we're going to // assume that any error would have been found, and reported, in NewPort() port, _ := ParsePort(portStr) return port }
[ "func", "(", "p", "Port", ")", "Int", "(", ")", "int", "{", "portStr", ":=", "p", ".", "Port", "(", ")", "\n", "// We don't need to check for an error because we're going to", "// assume that any error would have been found, and reported, in NewPort()", "port", ",", "_", ":=", "ParsePort", "(", "portStr", ")", "\n", "return", "port", "\n", "}" ]
// Int returns the port number of a Port as an int
[ "Int", "returns", "the", "port", "number", "of", "a", "Port", "as", "an", "int" ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/nat/nat.go#L86-L92
146,217
docker/go-connections
nat/nat.go
ParsePortSpec
func ParsePortSpec(rawPort string) ([]PortMapping, error) { var proto string rawIP, hostPort, containerPort := splitParts(rawPort) proto, containerPort = SplitProtoPort(containerPort) // Strip [] from IPV6 addresses ip, _, err := net.SplitHostPort(rawIP + ":") if err != nil { return nil, fmt.Errorf("Invalid ip address %v: %s", rawIP, err) } if ip != "" && net.ParseIP(ip) == nil { return nil, fmt.Errorf("Invalid ip address: %s", ip) } if containerPort == "" { return nil, fmt.Errorf("No port specified: %s<empty>", rawPort) } startPort, endPort, err := ParsePortRange(containerPort) if err != nil { return nil, fmt.Errorf("Invalid containerPort: %s", containerPort) } var startHostPort, endHostPort uint64 = 0, 0 if len(hostPort) > 0 { startHostPort, endHostPort, err = ParsePortRange(hostPort) if err != nil { return nil, fmt.Errorf("Invalid hostPort: %s", hostPort) } } if hostPort != "" && (endPort-startPort) != (endHostPort-startHostPort) { // Allow host port range iff containerPort is not a range. // In this case, use the host port range as the dynamic // host port range to allocate into. if endPort != startPort { return nil, fmt.Errorf("Invalid ranges specified for container and host Ports: %s and %s", containerPort, hostPort) } } if !validateProto(strings.ToLower(proto)) { return nil, fmt.Errorf("Invalid proto: %s", proto) } ports := []PortMapping{} for i := uint64(0); i <= (endPort - startPort); i++ { containerPort = strconv.FormatUint(startPort+i, 10) if len(hostPort) > 0 { hostPort = strconv.FormatUint(startHostPort+i, 10) } // Set hostPort to a range only if there is a single container port // and a dynamic host port. if startPort == endPort && startHostPort != endHostPort { hostPort = fmt.Sprintf("%s-%s", hostPort, strconv.FormatUint(endHostPort, 10)) } port, err := NewPort(strings.ToLower(proto), containerPort) if err != nil { return nil, err } binding := PortBinding{ HostIP: ip, HostPort: hostPort, } ports = append(ports, PortMapping{Port: port, Binding: binding}) } return ports, nil }
go
func ParsePortSpec(rawPort string) ([]PortMapping, error) { var proto string rawIP, hostPort, containerPort := splitParts(rawPort) proto, containerPort = SplitProtoPort(containerPort) // Strip [] from IPV6 addresses ip, _, err := net.SplitHostPort(rawIP + ":") if err != nil { return nil, fmt.Errorf("Invalid ip address %v: %s", rawIP, err) } if ip != "" && net.ParseIP(ip) == nil { return nil, fmt.Errorf("Invalid ip address: %s", ip) } if containerPort == "" { return nil, fmt.Errorf("No port specified: %s<empty>", rawPort) } startPort, endPort, err := ParsePortRange(containerPort) if err != nil { return nil, fmt.Errorf("Invalid containerPort: %s", containerPort) } var startHostPort, endHostPort uint64 = 0, 0 if len(hostPort) > 0 { startHostPort, endHostPort, err = ParsePortRange(hostPort) if err != nil { return nil, fmt.Errorf("Invalid hostPort: %s", hostPort) } } if hostPort != "" && (endPort-startPort) != (endHostPort-startHostPort) { // Allow host port range iff containerPort is not a range. // In this case, use the host port range as the dynamic // host port range to allocate into. if endPort != startPort { return nil, fmt.Errorf("Invalid ranges specified for container and host Ports: %s and %s", containerPort, hostPort) } } if !validateProto(strings.ToLower(proto)) { return nil, fmt.Errorf("Invalid proto: %s", proto) } ports := []PortMapping{} for i := uint64(0); i <= (endPort - startPort); i++ { containerPort = strconv.FormatUint(startPort+i, 10) if len(hostPort) > 0 { hostPort = strconv.FormatUint(startHostPort+i, 10) } // Set hostPort to a range only if there is a single container port // and a dynamic host port. if startPort == endPort && startHostPort != endHostPort { hostPort = fmt.Sprintf("%s-%s", hostPort, strconv.FormatUint(endHostPort, 10)) } port, err := NewPort(strings.ToLower(proto), containerPort) if err != nil { return nil, err } binding := PortBinding{ HostIP: ip, HostPort: hostPort, } ports = append(ports, PortMapping{Port: port, Binding: binding}) } return ports, nil }
[ "func", "ParsePortSpec", "(", "rawPort", "string", ")", "(", "[", "]", "PortMapping", ",", "error", ")", "{", "var", "proto", "string", "\n", "rawIP", ",", "hostPort", ",", "containerPort", ":=", "splitParts", "(", "rawPort", ")", "\n", "proto", ",", "containerPort", "=", "SplitProtoPort", "(", "containerPort", ")", "\n\n", "// Strip [] from IPV6 addresses", "ip", ",", "_", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "rawIP", "+", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "rawIP", ",", "err", ")", "\n", "}", "\n", "if", "ip", "!=", "\"", "\"", "&&", "net", ".", "ParseIP", "(", "ip", ")", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ip", ")", "\n", "}", "\n", "if", "containerPort", "==", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "rawPort", ")", "\n", "}", "\n\n", "startPort", ",", "endPort", ",", "err", ":=", "ParsePortRange", "(", "containerPort", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "containerPort", ")", "\n", "}", "\n\n", "var", "startHostPort", ",", "endHostPort", "uint64", "=", "0", ",", "0", "\n", "if", "len", "(", "hostPort", ")", ">", "0", "{", "startHostPort", ",", "endHostPort", ",", "err", "=", "ParsePortRange", "(", "hostPort", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hostPort", ")", "\n", "}", "\n", "}", "\n\n", "if", "hostPort", "!=", "\"", "\"", "&&", "(", "endPort", "-", "startPort", ")", "!=", "(", "endHostPort", "-", "startHostPort", ")", "{", "// Allow host port range iff containerPort is not a range.", "// In this case, use the host port range as the dynamic", "// host port range to allocate into.", "if", "endPort", "!=", "startPort", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "containerPort", ",", "hostPort", ")", "\n", "}", "\n", "}", "\n\n", "if", "!", "validateProto", "(", "strings", ".", "ToLower", "(", "proto", ")", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "proto", ")", "\n", "}", "\n\n", "ports", ":=", "[", "]", "PortMapping", "{", "}", "\n", "for", "i", ":=", "uint64", "(", "0", ")", ";", "i", "<=", "(", "endPort", "-", "startPort", ")", ";", "i", "++", "{", "containerPort", "=", "strconv", ".", "FormatUint", "(", "startPort", "+", "i", ",", "10", ")", "\n", "if", "len", "(", "hostPort", ")", ">", "0", "{", "hostPort", "=", "strconv", ".", "FormatUint", "(", "startHostPort", "+", "i", ",", "10", ")", "\n", "}", "\n", "// Set hostPort to a range only if there is a single container port", "// and a dynamic host port.", "if", "startPort", "==", "endPort", "&&", "startHostPort", "!=", "endHostPort", "{", "hostPort", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "hostPort", ",", "strconv", ".", "FormatUint", "(", "endHostPort", ",", "10", ")", ")", "\n", "}", "\n", "port", ",", "err", ":=", "NewPort", "(", "strings", ".", "ToLower", "(", "proto", ")", ",", "containerPort", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "binding", ":=", "PortBinding", "{", "HostIP", ":", "ip", ",", "HostPort", ":", "hostPort", ",", "}", "\n", "ports", "=", "append", "(", "ports", ",", "PortMapping", "{", "Port", ":", "port", ",", "Binding", ":", "binding", "}", ")", "\n", "}", "\n", "return", "ports", ",", "nil", "\n", "}" ]
// ParsePortSpec parses a port specification string into a slice of PortMappings
[ "ParsePortSpec", "parses", "a", "port", "specification", "string", "into", "a", "slice", "of", "PortMappings" ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/nat/nat.go#L176-L242
146,218
docker/go-connections
tlsconfig/config.go
ServerDefault
func ServerDefault(ops ...func(*tls.Config)) *tls.Config { tlsconfig := &tls.Config{ // Avoid fallback by default to SSL protocols < TLS1.2 MinVersion: tls.VersionTLS12, PreferServerCipherSuites: true, CipherSuites: DefaultServerAcceptedCiphers, } for _, op := range ops { op(tlsconfig) } return tlsconfig }
go
func ServerDefault(ops ...func(*tls.Config)) *tls.Config { tlsconfig := &tls.Config{ // Avoid fallback by default to SSL protocols < TLS1.2 MinVersion: tls.VersionTLS12, PreferServerCipherSuites: true, CipherSuites: DefaultServerAcceptedCiphers, } for _, op := range ops { op(tlsconfig) } return tlsconfig }
[ "func", "ServerDefault", "(", "ops", "...", "func", "(", "*", "tls", ".", "Config", ")", ")", "*", "tls", ".", "Config", "{", "tlsconfig", ":=", "&", "tls", ".", "Config", "{", "// Avoid fallback by default to SSL protocols < TLS1.2", "MinVersion", ":", "tls", ".", "VersionTLS12", ",", "PreferServerCipherSuites", ":", "true", ",", "CipherSuites", ":", "DefaultServerAcceptedCiphers", ",", "}", "\n\n", "for", "_", ",", "op", ":=", "range", "ops", "{", "op", "(", "tlsconfig", ")", "\n", "}", "\n\n", "return", "tlsconfig", "\n", "}" ]
// ServerDefault returns a secure-enough TLS configuration for the server TLS configuration.
[ "ServerDefault", "returns", "a", "secure", "-", "enough", "TLS", "configuration", "for", "the", "server", "TLS", "configuration", "." ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/tlsconfig/config.go#L66-L79
146,219
docker/go-connections
tlsconfig/config.go
ClientDefault
func ClientDefault(ops ...func(*tls.Config)) *tls.Config { tlsconfig := &tls.Config{ // Prefer TLS1.2 as the client minimum MinVersion: tls.VersionTLS12, CipherSuites: clientCipherSuites, } for _, op := range ops { op(tlsconfig) } return tlsconfig }
go
func ClientDefault(ops ...func(*tls.Config)) *tls.Config { tlsconfig := &tls.Config{ // Prefer TLS1.2 as the client minimum MinVersion: tls.VersionTLS12, CipherSuites: clientCipherSuites, } for _, op := range ops { op(tlsconfig) } return tlsconfig }
[ "func", "ClientDefault", "(", "ops", "...", "func", "(", "*", "tls", ".", "Config", ")", ")", "*", "tls", ".", "Config", "{", "tlsconfig", ":=", "&", "tls", ".", "Config", "{", "// Prefer TLS1.2 as the client minimum", "MinVersion", ":", "tls", ".", "VersionTLS12", ",", "CipherSuites", ":", "clientCipherSuites", ",", "}", "\n\n", "for", "_", ",", "op", ":=", "range", "ops", "{", "op", "(", "tlsconfig", ")", "\n", "}", "\n\n", "return", "tlsconfig", "\n", "}" ]
// ClientDefault returns a secure-enough TLS configuration for the client TLS configuration.
[ "ClientDefault", "returns", "a", "secure", "-", "enough", "TLS", "configuration", "for", "the", "client", "TLS", "configuration", "." ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/tlsconfig/config.go#L82-L94
146,220
docker/go-connections
tlsconfig/config.go
certPool
func certPool(caFile string, exclusivePool bool) (*x509.CertPool, error) { // If we should verify the server, we need to load a trusted ca var ( certPool *x509.CertPool err error ) if exclusivePool { certPool = x509.NewCertPool() } else { certPool, err = SystemCertPool() if err != nil { return nil, fmt.Errorf("failed to read system certificates: %v", err) } } pem, err := ioutil.ReadFile(caFile) if err != nil { return nil, fmt.Errorf("could not read CA certificate %q: %v", caFile, err) } if !certPool.AppendCertsFromPEM(pem) { return nil, fmt.Errorf("failed to append certificates from PEM file: %q", caFile) } return certPool, nil }
go
func certPool(caFile string, exclusivePool bool) (*x509.CertPool, error) { // If we should verify the server, we need to load a trusted ca var ( certPool *x509.CertPool err error ) if exclusivePool { certPool = x509.NewCertPool() } else { certPool, err = SystemCertPool() if err != nil { return nil, fmt.Errorf("failed to read system certificates: %v", err) } } pem, err := ioutil.ReadFile(caFile) if err != nil { return nil, fmt.Errorf("could not read CA certificate %q: %v", caFile, err) } if !certPool.AppendCertsFromPEM(pem) { return nil, fmt.Errorf("failed to append certificates from PEM file: %q", caFile) } return certPool, nil }
[ "func", "certPool", "(", "caFile", "string", ",", "exclusivePool", "bool", ")", "(", "*", "x509", ".", "CertPool", ",", "error", ")", "{", "// If we should verify the server, we need to load a trusted ca", "var", "(", "certPool", "*", "x509", ".", "CertPool", "\n", "err", "error", "\n", ")", "\n", "if", "exclusivePool", "{", "certPool", "=", "x509", ".", "NewCertPool", "(", ")", "\n", "}", "else", "{", "certPool", ",", "err", "=", "SystemCertPool", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "pem", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "caFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "caFile", ",", "err", ")", "\n", "}", "\n", "if", "!", "certPool", ".", "AppendCertsFromPEM", "(", "pem", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "caFile", ")", "\n", "}", "\n", "return", "certPool", ",", "nil", "\n", "}" ]
// certPool returns an X.509 certificate pool from `caFile`, the certificate file.
[ "certPool", "returns", "an", "X", ".", "509", "certificate", "pool", "from", "caFile", "the", "certificate", "file", "." ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/tlsconfig/config.go#L97-L119
146,221
docker/go-connections
tlsconfig/config.go
adjustMinVersion
func adjustMinVersion(options Options, config *tls.Config) error { if options.MinVersion > 0 { if !isValidMinVersion(options.MinVersion) { return fmt.Errorf("Invalid minimum TLS version: %x", options.MinVersion) } if options.MinVersion < config.MinVersion { return fmt.Errorf("Requested minimum TLS version is too low. Should be at-least: %x", config.MinVersion) } config.MinVersion = options.MinVersion } return nil }
go
func adjustMinVersion(options Options, config *tls.Config) error { if options.MinVersion > 0 { if !isValidMinVersion(options.MinVersion) { return fmt.Errorf("Invalid minimum TLS version: %x", options.MinVersion) } if options.MinVersion < config.MinVersion { return fmt.Errorf("Requested minimum TLS version is too low. Should be at-least: %x", config.MinVersion) } config.MinVersion = options.MinVersion } return nil }
[ "func", "adjustMinVersion", "(", "options", "Options", ",", "config", "*", "tls", ".", "Config", ")", "error", "{", "if", "options", ".", "MinVersion", ">", "0", "{", "if", "!", "isValidMinVersion", "(", "options", ".", "MinVersion", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "options", ".", "MinVersion", ")", "\n", "}", "\n", "if", "options", ".", "MinVersion", "<", "config", ".", "MinVersion", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "config", ".", "MinVersion", ")", "\n", "}", "\n", "config", ".", "MinVersion", "=", "options", ".", "MinVersion", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// adjustMinVersion sets the MinVersion on `config`, the input configuration. // It assumes the current MinVersion on the `config` is the lowest allowed.
[ "adjustMinVersion", "sets", "the", "MinVersion", "on", "config", "the", "input", "configuration", ".", "It", "assumes", "the", "current", "MinVersion", "on", "the", "config", "is", "the", "lowest", "allowed", "." ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/tlsconfig/config.go#L129-L141
146,222
docker/go-connections
tlsconfig/config.go
getPrivateKey
func getPrivateKey(keyBytes []byte, passphrase string) ([]byte, error) { // this section makes some small changes to code from notary/tuf/utils/x509.go pemBlock, _ := pem.Decode(keyBytes) if pemBlock == nil { return nil, fmt.Errorf("no valid private key found") } var err error if x509.IsEncryptedPEMBlock(pemBlock) { keyBytes, err = x509.DecryptPEMBlock(pemBlock, []byte(passphrase)) if err != nil { return nil, errors.Wrap(err, "private key is encrypted, but could not decrypt it") } keyBytes = pem.EncodeToMemory(&pem.Block{Type: pemBlock.Type, Bytes: keyBytes}) } return keyBytes, nil }
go
func getPrivateKey(keyBytes []byte, passphrase string) ([]byte, error) { // this section makes some small changes to code from notary/tuf/utils/x509.go pemBlock, _ := pem.Decode(keyBytes) if pemBlock == nil { return nil, fmt.Errorf("no valid private key found") } var err error if x509.IsEncryptedPEMBlock(pemBlock) { keyBytes, err = x509.DecryptPEMBlock(pemBlock, []byte(passphrase)) if err != nil { return nil, errors.Wrap(err, "private key is encrypted, but could not decrypt it") } keyBytes = pem.EncodeToMemory(&pem.Block{Type: pemBlock.Type, Bytes: keyBytes}) } return keyBytes, nil }
[ "func", "getPrivateKey", "(", "keyBytes", "[", "]", "byte", ",", "passphrase", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// this section makes some small changes to code from notary/tuf/utils/x509.go", "pemBlock", ",", "_", ":=", "pem", ".", "Decode", "(", "keyBytes", ")", "\n", "if", "pemBlock", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var", "err", "error", "\n", "if", "x509", ".", "IsEncryptedPEMBlock", "(", "pemBlock", ")", "{", "keyBytes", ",", "err", "=", "x509", ".", "DecryptPEMBlock", "(", "pemBlock", ",", "[", "]", "byte", "(", "passphrase", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "keyBytes", "=", "pem", ".", "EncodeToMemory", "(", "&", "pem", ".", "Block", "{", "Type", ":", "pemBlock", ".", "Type", ",", "Bytes", ":", "keyBytes", "}", ")", "\n", "}", "\n\n", "return", "keyBytes", ",", "nil", "\n", "}" ]
// getPrivateKey returns the private key in 'keyBytes', in PEM-encoded format. // If the private key is encrypted, 'passphrase' is used to decrypted the // private key.
[ "getPrivateKey", "returns", "the", "private", "key", "in", "keyBytes", "in", "PEM", "-", "encoded", "format", ".", "If", "the", "private", "key", "is", "encrypted", "passphrase", "is", "used", "to", "decrypted", "the", "private", "key", "." ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/tlsconfig/config.go#L152-L169
146,223
docker/go-connections
tlsconfig/config.go
getCert
func getCert(options Options) ([]tls.Certificate, error) { if options.CertFile == "" && options.KeyFile == "" { return nil, nil } errMessage := "Could not load X509 key pair" cert, err := ioutil.ReadFile(options.CertFile) if err != nil { return nil, errors.Wrap(err, errMessage) } prKeyBytes, err := ioutil.ReadFile(options.KeyFile) if err != nil { return nil, errors.Wrap(err, errMessage) } prKeyBytes, err = getPrivateKey(prKeyBytes, options.Passphrase) if err != nil { return nil, errors.Wrap(err, errMessage) } tlsCert, err := tls.X509KeyPair(cert, prKeyBytes) if err != nil { return nil, errors.Wrap(err, errMessage) } return []tls.Certificate{tlsCert}, nil }
go
func getCert(options Options) ([]tls.Certificate, error) { if options.CertFile == "" && options.KeyFile == "" { return nil, nil } errMessage := "Could not load X509 key pair" cert, err := ioutil.ReadFile(options.CertFile) if err != nil { return nil, errors.Wrap(err, errMessage) } prKeyBytes, err := ioutil.ReadFile(options.KeyFile) if err != nil { return nil, errors.Wrap(err, errMessage) } prKeyBytes, err = getPrivateKey(prKeyBytes, options.Passphrase) if err != nil { return nil, errors.Wrap(err, errMessage) } tlsCert, err := tls.X509KeyPair(cert, prKeyBytes) if err != nil { return nil, errors.Wrap(err, errMessage) } return []tls.Certificate{tlsCert}, nil }
[ "func", "getCert", "(", "options", "Options", ")", "(", "[", "]", "tls", ".", "Certificate", ",", "error", ")", "{", "if", "options", ".", "CertFile", "==", "\"", "\"", "&&", "options", ".", "KeyFile", "==", "\"", "\"", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "errMessage", ":=", "\"", "\"", "\n\n", "cert", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "options", ".", "CertFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "errMessage", ")", "\n", "}", "\n\n", "prKeyBytes", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "options", ".", "KeyFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "errMessage", ")", "\n", "}", "\n\n", "prKeyBytes", ",", "err", "=", "getPrivateKey", "(", "prKeyBytes", ",", "options", ".", "Passphrase", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "errMessage", ")", "\n", "}", "\n\n", "tlsCert", ",", "err", ":=", "tls", ".", "X509KeyPair", "(", "cert", ",", "prKeyBytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "errMessage", ")", "\n", "}", "\n\n", "return", "[", "]", "tls", ".", "Certificate", "{", "tlsCert", "}", ",", "nil", "\n", "}" ]
// getCert returns a Certificate from the CertFile and KeyFile in 'options', // if the key is encrypted, the Passphrase in 'options' will be used to // decrypt it.
[ "getCert", "returns", "a", "Certificate", "from", "the", "CertFile", "and", "KeyFile", "in", "options", "if", "the", "key", "is", "encrypted", "the", "Passphrase", "in", "options", "will", "be", "used", "to", "decrypt", "it", "." ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/tlsconfig/config.go#L174-L202
146,224
docker/go-connections
tlsconfig/config.go
Client
func Client(options Options) (*tls.Config, error) { tlsConfig := ClientDefault() tlsConfig.InsecureSkipVerify = options.InsecureSkipVerify if !options.InsecureSkipVerify && options.CAFile != "" { CAs, err := certPool(options.CAFile, options.ExclusiveRootPools) if err != nil { return nil, err } tlsConfig.RootCAs = CAs } tlsCerts, err := getCert(options) if err != nil { return nil, err } tlsConfig.Certificates = tlsCerts if err := adjustMinVersion(options, tlsConfig); err != nil { return nil, err } return tlsConfig, nil }
go
func Client(options Options) (*tls.Config, error) { tlsConfig := ClientDefault() tlsConfig.InsecureSkipVerify = options.InsecureSkipVerify if !options.InsecureSkipVerify && options.CAFile != "" { CAs, err := certPool(options.CAFile, options.ExclusiveRootPools) if err != nil { return nil, err } tlsConfig.RootCAs = CAs } tlsCerts, err := getCert(options) if err != nil { return nil, err } tlsConfig.Certificates = tlsCerts if err := adjustMinVersion(options, tlsConfig); err != nil { return nil, err } return tlsConfig, nil }
[ "func", "Client", "(", "options", "Options", ")", "(", "*", "tls", ".", "Config", ",", "error", ")", "{", "tlsConfig", ":=", "ClientDefault", "(", ")", "\n", "tlsConfig", ".", "InsecureSkipVerify", "=", "options", ".", "InsecureSkipVerify", "\n", "if", "!", "options", ".", "InsecureSkipVerify", "&&", "options", ".", "CAFile", "!=", "\"", "\"", "{", "CAs", ",", "err", ":=", "certPool", "(", "options", ".", "CAFile", ",", "options", ".", "ExclusiveRootPools", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "tlsConfig", ".", "RootCAs", "=", "CAs", "\n", "}", "\n\n", "tlsCerts", ",", "err", ":=", "getCert", "(", "options", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "tlsConfig", ".", "Certificates", "=", "tlsCerts", "\n\n", "if", "err", ":=", "adjustMinVersion", "(", "options", ",", "tlsConfig", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "tlsConfig", ",", "nil", "\n", "}" ]
// Client returns a TLS configuration meant to be used by a client.
[ "Client", "returns", "a", "TLS", "configuration", "meant", "to", "be", "used", "by", "a", "client", "." ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/tlsconfig/config.go#L205-L227
146,225
docker/go-connections
tlsconfig/config.go
Server
func Server(options Options) (*tls.Config, error) { tlsConfig := ServerDefault() tlsConfig.ClientAuth = options.ClientAuth tlsCert, err := tls.LoadX509KeyPair(options.CertFile, options.KeyFile) if err != nil { if os.IsNotExist(err) { return nil, fmt.Errorf("Could not load X509 key pair (cert: %q, key: %q): %v", options.CertFile, options.KeyFile, err) } return nil, fmt.Errorf("Error reading X509 key pair (cert: %q, key: %q): %v. Make sure the key is not encrypted.", options.CertFile, options.KeyFile, err) } tlsConfig.Certificates = []tls.Certificate{tlsCert} if options.ClientAuth >= tls.VerifyClientCertIfGiven && options.CAFile != "" { CAs, err := certPool(options.CAFile, options.ExclusiveRootPools) if err != nil { return nil, err } tlsConfig.ClientCAs = CAs } if err := adjustMinVersion(options, tlsConfig); err != nil { return nil, err } return tlsConfig, nil }
go
func Server(options Options) (*tls.Config, error) { tlsConfig := ServerDefault() tlsConfig.ClientAuth = options.ClientAuth tlsCert, err := tls.LoadX509KeyPair(options.CertFile, options.KeyFile) if err != nil { if os.IsNotExist(err) { return nil, fmt.Errorf("Could not load X509 key pair (cert: %q, key: %q): %v", options.CertFile, options.KeyFile, err) } return nil, fmt.Errorf("Error reading X509 key pair (cert: %q, key: %q): %v. Make sure the key is not encrypted.", options.CertFile, options.KeyFile, err) } tlsConfig.Certificates = []tls.Certificate{tlsCert} if options.ClientAuth >= tls.VerifyClientCertIfGiven && options.CAFile != "" { CAs, err := certPool(options.CAFile, options.ExclusiveRootPools) if err != nil { return nil, err } tlsConfig.ClientCAs = CAs } if err := adjustMinVersion(options, tlsConfig); err != nil { return nil, err } return tlsConfig, nil }
[ "func", "Server", "(", "options", "Options", ")", "(", "*", "tls", ".", "Config", ",", "error", ")", "{", "tlsConfig", ":=", "ServerDefault", "(", ")", "\n", "tlsConfig", ".", "ClientAuth", "=", "options", ".", "ClientAuth", "\n", "tlsCert", ",", "err", ":=", "tls", ".", "LoadX509KeyPair", "(", "options", ".", "CertFile", ",", "options", ".", "KeyFile", ")", "\n", "if", "err", "!=", "nil", "{", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "options", ".", "CertFile", ",", "options", ".", "KeyFile", ",", "err", ")", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "options", ".", "CertFile", ",", "options", ".", "KeyFile", ",", "err", ")", "\n", "}", "\n", "tlsConfig", ".", "Certificates", "=", "[", "]", "tls", ".", "Certificate", "{", "tlsCert", "}", "\n", "if", "options", ".", "ClientAuth", ">=", "tls", ".", "VerifyClientCertIfGiven", "&&", "options", ".", "CAFile", "!=", "\"", "\"", "{", "CAs", ",", "err", ":=", "certPool", "(", "options", ".", "CAFile", ",", "options", ".", "ExclusiveRootPools", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "tlsConfig", ".", "ClientCAs", "=", "CAs", "\n", "}", "\n\n", "if", "err", ":=", "adjustMinVersion", "(", "options", ",", "tlsConfig", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "tlsConfig", ",", "nil", "\n", "}" ]
// Server returns a TLS configuration meant to be used by a server.
[ "Server", "returns", "a", "TLS", "configuration", "meant", "to", "be", "used", "by", "a", "server", "." ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/tlsconfig/config.go#L230-L254
146,226
docker/go-connections
sockets/unix_socket.go
WithChown
func WithChown(uid, gid int) SockOption { return func(path string) error { if err := os.Chown(path, uid, gid); err != nil { return err } return nil } }
go
func WithChown(uid, gid int) SockOption { return func(path string) error { if err := os.Chown(path, uid, gid); err != nil { return err } return nil } }
[ "func", "WithChown", "(", "uid", ",", "gid", "int", ")", "SockOption", "{", "return", "func", "(", "path", "string", ")", "error", "{", "if", "err", ":=", "os", ".", "Chown", "(", "path", ",", "uid", ",", "gid", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// WithChown modifies the socket file's uid and gid
[ "WithChown", "modifies", "the", "socket", "file", "s", "uid", "and", "gid" ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/sockets/unix_socket.go#L61-L68
146,227
docker/go-connections
sockets/unix_socket.go
WithChmod
func WithChmod(mask os.FileMode) SockOption { return func(path string) error { if err := os.Chmod(path, mask); err != nil { return err } return nil } }
go
func WithChmod(mask os.FileMode) SockOption { return func(path string) error { if err := os.Chmod(path, mask); err != nil { return err } return nil } }
[ "func", "WithChmod", "(", "mask", "os", ".", "FileMode", ")", "SockOption", "{", "return", "func", "(", "path", "string", ")", "error", "{", "if", "err", ":=", "os", ".", "Chmod", "(", "path", ",", "mask", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// WithChmod modifies socket file's access mode
[ "WithChmod", "modifies", "socket", "file", "s", "access", "mode" ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/sockets/unix_socket.go#L71-L78
146,228
docker/go-connections
sockets/unix_socket.go
NewUnixSocketWithOpts
func NewUnixSocketWithOpts(path string, opts ...SockOption) (net.Listener, error) { if err := syscall.Unlink(path); err != nil && !os.IsNotExist(err) { return nil, err } mask := syscall.Umask(0777) defer syscall.Umask(mask) l, err := net.Listen("unix", path) if err != nil { return nil, err } for _, op := range opts { if err := op(path); err != nil { l.Close() return nil, err } } return l, nil }
go
func NewUnixSocketWithOpts(path string, opts ...SockOption) (net.Listener, error) { if err := syscall.Unlink(path); err != nil && !os.IsNotExist(err) { return nil, err } mask := syscall.Umask(0777) defer syscall.Umask(mask) l, err := net.Listen("unix", path) if err != nil { return nil, err } for _, op := range opts { if err := op(path); err != nil { l.Close() return nil, err } } return l, nil }
[ "func", "NewUnixSocketWithOpts", "(", "path", "string", ",", "opts", "...", "SockOption", ")", "(", "net", ".", "Listener", ",", "error", ")", "{", "if", "err", ":=", "syscall", ".", "Unlink", "(", "path", ")", ";", "err", "!=", "nil", "&&", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "nil", ",", "err", "\n", "}", "\n", "mask", ":=", "syscall", ".", "Umask", "(", "0777", ")", "\n", "defer", "syscall", ".", "Umask", "(", "mask", ")", "\n\n", "l", ",", "err", ":=", "net", ".", "Listen", "(", "\"", "\"", ",", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "for", "_", ",", "op", ":=", "range", "opts", "{", "if", "err", ":=", "op", "(", "path", ")", ";", "err", "!=", "nil", "{", "l", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "l", ",", "nil", "\n", "}" ]
// NewUnixSocketWithOpts creates a unix socket with the specified options
[ "NewUnixSocketWithOpts", "creates", "a", "unix", "socket", "with", "the", "specified", "options" ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/sockets/unix_socket.go#L81-L101
146,229
docker/go-connections
sockets/unix_socket.go
NewUnixSocket
func NewUnixSocket(path string, gid int) (net.Listener, error) { return NewUnixSocketWithOpts(path, WithChown(0, gid), WithChmod(0660)) }
go
func NewUnixSocket(path string, gid int) (net.Listener, error) { return NewUnixSocketWithOpts(path, WithChown(0, gid), WithChmod(0660)) }
[ "func", "NewUnixSocket", "(", "path", "string", ",", "gid", "int", ")", "(", "net", ".", "Listener", ",", "error", ")", "{", "return", "NewUnixSocketWithOpts", "(", "path", ",", "WithChown", "(", "0", ",", "gid", ")", ",", "WithChmod", "(", "0660", ")", ")", "\n", "}" ]
// NewUnixSocket creates a unix socket with the specified path and group.
[ "NewUnixSocket", "creates", "a", "unix", "socket", "with", "the", "specified", "path", "and", "group", "." ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/sockets/unix_socket.go#L104-L106
146,230
docker/go-connections
sockets/sockets_windows.go
DialPipe
func DialPipe(addr string, timeout time.Duration) (net.Conn, error) { return winio.DialPipe(addr, &timeout) }
go
func DialPipe(addr string, timeout time.Duration) (net.Conn, error) { return winio.DialPipe(addr, &timeout) }
[ "func", "DialPipe", "(", "addr", "string", ",", "timeout", "time", ".", "Duration", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "return", "winio", ".", "DialPipe", "(", "addr", ",", "&", "timeout", ")", "\n", "}" ]
// DialPipe connects to a Windows named pipe.
[ "DialPipe", "connects", "to", "a", "Windows", "named", "pipe", "." ]
b44139defdac517e3f71df1e60826f8a262a2482
https://github.com/docker/go-connections/blob/b44139defdac517e3f71df1e60826f8a262a2482/sockets/sockets_windows.go#L33-L35
146,231
ipfs/go-dnslink
dnslink/main.go
printLink
func printLink(domain string) error { link, err := dnslink.Resolve(domain) if err != nil { return err } fmt.Println(link) return nil }
go
func printLink(domain string) error { link, err := dnslink.Resolve(domain) if err != nil { return err } fmt.Println(link) return nil }
[ "func", "printLink", "(", "domain", "string", ")", "error", "{", "link", ",", "err", ":=", "dnslink", ".", "Resolve", "(", "domain", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "fmt", ".", "Println", "(", "link", ")", "\n", "return", "nil", "\n", "}" ]
// print a single link
[ "print", "a", "single", "link" ]
47ab53fda3fac2f043084406e6da47232efa91d1
https://github.com/ipfs/go-dnslink/blob/47ab53fda3fac2f043084406e6da47232efa91d1/dnslink/main.go#L57-L64
146,232
ipfs/go-dnslink
dnslink/main.go
printLinks
func printLinks(domains []string) error { for _, domain := range domains { fmt.Print(domain, ": ") result, err := dnslink.Resolve(domain) if result != "" { fmt.Print(result) } if err != nil { fmt.Print("error: ", err) } fmt.Println() } return nil }
go
func printLinks(domains []string) error { for _, domain := range domains { fmt.Print(domain, ": ") result, err := dnslink.Resolve(domain) if result != "" { fmt.Print(result) } if err != nil { fmt.Print("error: ", err) } fmt.Println() } return nil }
[ "func", "printLinks", "(", "domains", "[", "]", "string", ")", "error", "{", "for", "_", ",", "domain", ":=", "range", "domains", "{", "fmt", ".", "Print", "(", "domain", ",", "\"", "\"", ")", "\n\n", "result", ",", "err", ":=", "dnslink", ".", "Resolve", "(", "domain", ")", "\n", "if", "result", "!=", "\"", "\"", "{", "fmt", ".", "Print", "(", "result", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Print", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "fmt", ".", "Println", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// print multiple links. // errors printed as output, and do not fail the entire process.
[ "print", "multiple", "links", ".", "errors", "printed", "as", "output", "and", "do", "not", "fail", "the", "entire", "process", "." ]
47ab53fda3fac2f043084406e6da47232efa91d1
https://github.com/ipfs/go-dnslink/blob/47ab53fda3fac2f043084406e6da47232efa91d1/dnslink/main.go#L68-L82
146,233
ipfs/go-dnslink
dnslink.go
Resolve
func (r *Resolver) Resolve(domain string) (string, error) { return r.ResolveN(domain, DefaultDepthLimit) }
go
func (r *Resolver) Resolve(domain string) (string, error) { return r.ResolveN(domain, DefaultDepthLimit) }
[ "func", "(", "r", "*", "Resolver", ")", "Resolve", "(", "domain", "string", ")", "(", "string", ",", "error", ")", "{", "return", "r", ".", "ResolveN", "(", "domain", ",", "DefaultDepthLimit", ")", "\n", "}" ]
// Resolve resolves the dnslink at a particular domain. It will recursively // keep resolving until reaching the defaultDepth of Resolver. If the depth // is reached, Resolve will return the last value retrieved, and ErrResolveLimit. // If TXT records are found but are not valid dnslink records, Resolve will // return ErrInvalidDnslink. Resolve will check every TXT record returned. // If resolution fails otherwise, Resolve will return ErrResolveFailed
[ "Resolve", "resolves", "the", "dnslink", "at", "a", "particular", "domain", ".", "It", "will", "recursively", "keep", "resolving", "until", "reaching", "the", "defaultDepth", "of", "Resolver", ".", "If", "the", "depth", "is", "reached", "Resolve", "will", "return", "the", "last", "value", "retrieved", "and", "ErrResolveLimit", ".", "If", "TXT", "records", "are", "found", "but", "are", "not", "valid", "dnslink", "records", "Resolve", "will", "return", "ErrInvalidDnslink", ".", "Resolve", "will", "check", "every", "TXT", "record", "returned", ".", "If", "resolution", "fails", "otherwise", "Resolve", "will", "return", "ErrResolveFailed" ]
47ab53fda3fac2f043084406e6da47232efa91d1
https://github.com/ipfs/go-dnslink/blob/47ab53fda3fac2f043084406e6da47232efa91d1/dnslink.go#L142-L144
146,234
Joker/jade
template.go
ParseFile
func ParseFile(filename string) (string, error) { bs, err := ioutil.ReadFile(filename) if err != nil { return "", err } return Parse(filepath.Base(filename), bs) }
go
func ParseFile(filename string) (string, error) { bs, err := ioutil.ReadFile(filename) if err != nil { return "", err } return Parse(filepath.Base(filename), bs) }
[ "func", "ParseFile", "(", "filename", "string", ")", "(", "string", ",", "error", ")", "{", "bs", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "Parse", "(", "filepath", ".", "Base", "(", "filename", ")", ",", "bs", ")", "\n", "}" ]
// ParseFile parse the jade template file in given filename
[ "ParseFile", "parse", "the", "jade", "template", "file", "in", "given", "filename" ]
9ffefa50b5f31416ac643e9d9ad6116f4688705f
https://github.com/Joker/jade/blob/9ffefa50b5f31416ac643e9d9ad6116f4688705f/template.go#L48-L54
146,235
Joker/jade
jade_node.go
filterString
func filterString(in string) string { var ( rs = []rune(in) flag, prev rune psn int ) for k, r := range rs { // fmt.Println(string(r), " ", r) switch r { case '"': if flag == '\'' && prev != '\\' { rs[k] = 0 // bookmark for replace } if flag == 0 { flag = '"' psn = k } else if r == flag && prev != '\\' { flag = 0 } case '\'': if flag == 0 { flag = '\'' psn = k } else if r == flag && prev != '\\' { // if k-(psn+1) != 1 { rs[psn] = '"' rs[k] = '"' // } flag = 0 } case '`': if flag == 0 { flag = '`' psn = k } else if r == flag { flag = 0 } } prev = r } filterPlus(rs) filterJsEsc(rs) out := strings.Replace(string(rs), string(rune(0)), `\"`, -1) out = strings.Replace(out, string(rune(1)), ``, -1) out = strings.Replace(out, string([]rune{2, 2}), "`+", -1) out = strings.Replace(out, string(rune(3)), "+`", -1) return out }
go
func filterString(in string) string { var ( rs = []rune(in) flag, prev rune psn int ) for k, r := range rs { // fmt.Println(string(r), " ", r) switch r { case '"': if flag == '\'' && prev != '\\' { rs[k] = 0 // bookmark for replace } if flag == 0 { flag = '"' psn = k } else if r == flag && prev != '\\' { flag = 0 } case '\'': if flag == 0 { flag = '\'' psn = k } else if r == flag && prev != '\\' { // if k-(psn+1) != 1 { rs[psn] = '"' rs[k] = '"' // } flag = 0 } case '`': if flag == 0 { flag = '`' psn = k } else if r == flag { flag = 0 } } prev = r } filterPlus(rs) filterJsEsc(rs) out := strings.Replace(string(rs), string(rune(0)), `\"`, -1) out = strings.Replace(out, string(rune(1)), ``, -1) out = strings.Replace(out, string([]rune{2, 2}), "`+", -1) out = strings.Replace(out, string(rune(3)), "+`", -1) return out }
[ "func", "filterString", "(", "in", "string", ")", "string", "{", "var", "(", "rs", "=", "[", "]", "rune", "(", "in", ")", "\n", "flag", ",", "prev", "rune", "\n", "psn", "int", "\n", ")", "\n", "for", "k", ",", "r", ":=", "range", "rs", "{", "// fmt.Println(string(r), \" \", r)", "switch", "r", "{", "case", "'\"'", ":", "if", "flag", "==", "'\\''", "&&", "prev", "!=", "'\\\\'", "{", "rs", "[", "k", "]", "=", "0", "// bookmark for replace", "\n", "}", "\n", "if", "flag", "==", "0", "{", "flag", "=", "'\"'", "\n", "psn", "=", "k", "\n", "}", "else", "if", "r", "==", "flag", "&&", "prev", "!=", "'\\\\'", "{", "flag", "=", "0", "\n", "}", "\n", "case", "'\\''", ":", "if", "flag", "==", "0", "{", "flag", "=", "'\\''", "\n", "psn", "=", "k", "\n", "}", "else", "if", "r", "==", "flag", "&&", "prev", "!=", "'\\\\'", "{", "// if k-(psn+1) != 1 {", "rs", "[", "psn", "]", "=", "'\"'", "\n", "rs", "[", "k", "]", "=", "'\"'", "\n", "// }", "flag", "=", "0", "\n", "}", "\n", "case", "'`'", ":", "if", "flag", "==", "0", "{", "flag", "=", "'`'", "\n", "psn", "=", "k", "\n", "}", "else", "if", "r", "==", "flag", "{", "flag", "=", "0", "\n", "}", "\n", "}", "\n", "prev", "=", "r", "\n", "}", "\n", "filterPlus", "(", "rs", ")", "\n", "filterJsEsc", "(", "rs", ")", "\n", "out", ":=", "strings", ".", "Replace", "(", "string", "(", "rs", ")", ",", "string", "(", "rune", "(", "0", ")", ")", ",", "`\\\"`", ",", "-", "1", ")", "\n", "out", "=", "strings", ".", "Replace", "(", "out", ",", "string", "(", "rune", "(", "1", ")", ")", ",", "``", ",", "-", "1", ")", "\n", "out", "=", "strings", ".", "Replace", "(", "out", ",", "string", "(", "[", "]", "rune", "{", "2", ",", "2", "}", ")", ",", "\"", "\"", ",", "-", "1", ")", "\n", "out", "=", "strings", ".", "Replace", "(", "out", ",", "string", "(", "rune", "(", "3", ")", ")", ",", "\"", "\"", ",", "-", "1", ")", "\n", "return", "out", "\n", "}" ]
// `"aaa'a" + 'b\"bb"b' + 'c'` >>> `"aaa'a" + "b\"bb\"b" + "c"`
[ "aaa", "a", "+", "b", "\\", "bb", "b", "+", "c", ">>>", "aaa", "a", "+", "b", "\\", "bb", "\\", "b", "+", "c" ]
9ffefa50b5f31416ac643e9d9ad6116f4688705f
https://github.com/Joker/jade/blob/9ffefa50b5f31416ac643e9d9ad6116f4688705f/jade_node.go#L65-L112
146,236
Joker/jade
jade_node.go
filterPlus
func filterPlus(rs []rune) { var ( flag, prev rune psn int ) for k, r := range rs { switch r { case '"': if flag == 0 { flag = '"' if psn > 0 { for i := psn; i < k+1; i++ { // fmt.Println(string(rs[i]), rs[i]) rs[i] = 1 } } } else if r == flag && prev != '\\' { psn = k flag = 0 } case '`': if flag == 0 { flag = '`' } else if r == flag { flag = 0 } case ' ', '+': default: psn = 0 } prev = r } }
go
func filterPlus(rs []rune) { var ( flag, prev rune psn int ) for k, r := range rs { switch r { case '"': if flag == 0 { flag = '"' if psn > 0 { for i := psn; i < k+1; i++ { // fmt.Println(string(rs[i]), rs[i]) rs[i] = 1 } } } else if r == flag && prev != '\\' { psn = k flag = 0 } case '`': if flag == 0 { flag = '`' } else if r == flag { flag = 0 } case ' ', '+': default: psn = 0 } prev = r } }
[ "func", "filterPlus", "(", "rs", "[", "]", "rune", ")", "{", "var", "(", "flag", ",", "prev", "rune", "\n", "psn", "int", "\n", ")", "\n", "for", "k", ",", "r", ":=", "range", "rs", "{", "switch", "r", "{", "case", "'\"'", ":", "if", "flag", "==", "0", "{", "flag", "=", "'\"'", "\n", "if", "psn", ">", "0", "{", "for", "i", ":=", "psn", ";", "i", "<", "k", "+", "1", ";", "i", "++", "{", "// fmt.Println(string(rs[i]), rs[i])", "rs", "[", "i", "]", "=", "1", "\n", "}", "\n", "}", "\n", "}", "else", "if", "r", "==", "flag", "&&", "prev", "!=", "'\\\\'", "{", "psn", "=", "k", "\n", "flag", "=", "0", "\n", "}", "\n", "case", "'`'", ":", "if", "flag", "==", "0", "{", "flag", "=", "'`'", "\n", "}", "else", "if", "r", "==", "flag", "{", "flag", "=", "0", "\n", "}", "\n", "case", "' '", ",", "'+'", ":", "default", ":", "psn", "=", "0", "\n", "}", "\n", "prev", "=", "r", "\n", "}", "\n", "}" ]
// "aaa" + "bbb" >>> "aaabbb"
[ "aaa", "+", "bbb", ">>>", "aaabbb" ]
9ffefa50b5f31416ac643e9d9ad6116f4688705f
https://github.com/Joker/jade/blob/9ffefa50b5f31416ac643e9d9ad6116f4688705f/jade_node.go#L115-L147
146,237
Joker/jade
parse.go
Copy
func (t *Tree) Copy() *Tree { if t == nil { return nil } return &Tree{ Name: t.Name, Root: t.Root.CopyList(), text: t.text, } }
go
func (t *Tree) Copy() *Tree { if t == nil { return nil } return &Tree{ Name: t.Name, Root: t.Root.CopyList(), text: t.text, } }
[ "func", "(", "t", "*", "Tree", ")", "Copy", "(", ")", "*", "Tree", "{", "if", "t", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "&", "Tree", "{", "Name", ":", "t", ".", "Name", ",", "Root", ":", "t", ".", "Root", ".", "CopyList", "(", ")", ",", "text", ":", "t", ".", "text", ",", "}", "\n", "}" ]
// Copy returns a copy of the Tree. Any parsing state is discarded.
[ "Copy", "returns", "a", "copy", "of", "the", "Tree", ".", "Any", "parsing", "state", "is", "discarded", "." ]
9ffefa50b5f31416ac643e9d9ad6116f4688705f
https://github.com/Joker/jade/blob/9ffefa50b5f31416ac643e9d9ad6116f4688705f/parse.go#L28-L37
146,238
Joker/jade
parse.go
New
func New(name string) *Tree { return &Tree{ Name: name, mixin: map[string]*MixinNode{}, block: map[string]*ListNode{}, } }
go
func New(name string) *Tree { return &Tree{ Name: name, mixin: map[string]*MixinNode{}, block: map[string]*ListNode{}, } }
[ "func", "New", "(", "name", "string", ")", "*", "Tree", "{", "return", "&", "Tree", "{", "Name", ":", "name", ",", "mixin", ":", "map", "[", "string", "]", "*", "MixinNode", "{", "}", ",", "block", ":", "map", "[", "string", "]", "*", "ListNode", "{", "}", ",", "}", "\n", "}" ]
// New allocates a new parse tree with the given name.
[ "New", "allocates", "a", "new", "parse", "tree", "with", "the", "given", "name", "." ]
9ffefa50b5f31416ac643e9d9ad6116f4688705f
https://github.com/Joker/jade/blob/9ffefa50b5f31416ac643e9d9ad6116f4688705f/parse.go#L139-L145
146,239
Joker/jade
lex.go
backup
func (l *lexer) backup() { l.pos -= l.width // Correct newline count. if l.width == 1 && l.input[l.pos] == '\n' { l.line-- } }
go
func (l *lexer) backup() { l.pos -= l.width // Correct newline count. if l.width == 1 && l.input[l.pos] == '\n' { l.line-- } }
[ "func", "(", "l", "*", "lexer", ")", "backup", "(", ")", "{", "l", ".", "pos", "-=", "l", ".", "width", "\n", "// Correct newline count.", "if", "l", ".", "width", "==", "1", "&&", "l", ".", "input", "[", "l", ".", "pos", "]", "==", "'\\n'", "{", "l", ".", "line", "--", "\n", "}", "\n", "}" ]
// backup steps back one rune. Can only be called once per call of next.
[ "backup", "steps", "back", "one", "rune", ".", "Can", "only", "be", "called", "once", "per", "call", "of", "next", "." ]
9ffefa50b5f31416ac643e9d9ad6116f4688705f
https://github.com/Joker/jade/blob/9ffefa50b5f31416ac643e9d9ad6116f4688705f/lex.go#L83-L89
146,240
couchbase/go-couchbase
conn_pool.go
Discard
func (cp *connectionPool) Discard(c *memcached.Client) { <-cp.createsem c.Close() }
go
func (cp *connectionPool) Discard(c *memcached.Client) { <-cp.createsem c.Close() }
[ "func", "(", "cp", "*", "connectionPool", ")", "Discard", "(", "c", "*", "memcached", ".", "Client", ")", "{", "<-", "cp", ".", "createsem", "\n", "c", ".", "Close", "(", ")", "\n", "}" ]
// give the ability to discard a connection from a pool // useful for ditching connections to the wrong node after a rebalance
[ "give", "the", "ability", "to", "discard", "a", "connection", "from", "a", "pool", "useful", "for", "ditching", "connections", "to", "the", "wrong", "node", "after", "a", "rebalance" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/conn_pool.go#L292-L295
146,241
couchbase/go-couchbase
conn_pool.go
connCloser
func (cp *connectionPool) connCloser() { var connCount uint64 t := time.NewTimer(ConnCloserInterval) defer t.Stop() for { connCount = cp.connCount // we don't exist anymore! bail out! select { case <-cp.bailOut: return case <-t.C: } t.Reset(ConnCloserInterval) // no overflow connections open or sustained requests for connections // nothing to do until the next cycle if len(cp.connections) <= cp.poolSize || ConnCloserInterval/ConnPoolAvailWaitTime < time.Duration(cp.connCount-connCount) { continue } // close overflow connections now that they are not needed for c := range cp.connections { select { case <-cp.bailOut: return default: } // bail out if close did not work out if !cp.connCleanup(c) { return } if len(cp.connections) <= cp.poolSize { break } } } }
go
func (cp *connectionPool) connCloser() { var connCount uint64 t := time.NewTimer(ConnCloserInterval) defer t.Stop() for { connCount = cp.connCount // we don't exist anymore! bail out! select { case <-cp.bailOut: return case <-t.C: } t.Reset(ConnCloserInterval) // no overflow connections open or sustained requests for connections // nothing to do until the next cycle if len(cp.connections) <= cp.poolSize || ConnCloserInterval/ConnPoolAvailWaitTime < time.Duration(cp.connCount-connCount) { continue } // close overflow connections now that they are not needed for c := range cp.connections { select { case <-cp.bailOut: return default: } // bail out if close did not work out if !cp.connCleanup(c) { return } if len(cp.connections) <= cp.poolSize { break } } } }
[ "func", "(", "cp", "*", "connectionPool", ")", "connCloser", "(", ")", "{", "var", "connCount", "uint64", "\n\n", "t", ":=", "time", ".", "NewTimer", "(", "ConnCloserInterval", ")", "\n", "defer", "t", ".", "Stop", "(", ")", "\n\n", "for", "{", "connCount", "=", "cp", ".", "connCount", "\n\n", "// we don't exist anymore! bail out!", "select", "{", "case", "<-", "cp", ".", "bailOut", ":", "return", "\n", "case", "<-", "t", ".", "C", ":", "}", "\n", "t", ".", "Reset", "(", "ConnCloserInterval", ")", "\n\n", "// no overflow connections open or sustained requests for connections", "// nothing to do until the next cycle", "if", "len", "(", "cp", ".", "connections", ")", "<=", "cp", ".", "poolSize", "||", "ConnCloserInterval", "/", "ConnPoolAvailWaitTime", "<", "time", ".", "Duration", "(", "cp", ".", "connCount", "-", "connCount", ")", "{", "continue", "\n", "}", "\n\n", "// close overflow connections now that they are not needed", "for", "c", ":=", "range", "cp", ".", "connections", "{", "select", "{", "case", "<-", "cp", ".", "bailOut", ":", "return", "\n", "default", ":", "}", "\n\n", "// bail out if close did not work out", "if", "!", "cp", ".", "connCleanup", "(", "c", ")", "{", "return", "\n", "}", "\n", "if", "len", "(", "cp", ".", "connections", ")", "<=", "cp", ".", "poolSize", "{", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// asynchronous connection closer
[ "asynchronous", "connection", "closer" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/conn_pool.go#L298-L339
146,242
couchbase/go-couchbase
conn_pool.go
connCleanup
func (cp *connectionPool) connCleanup(c *memcached.Client) (rv bool) { // just in case we are closing a connection after // bailOut has been sent but we haven't yet read it defer func() { if recover() != nil { rv = false } }() rv = true c.Close() <-cp.createsem return }
go
func (cp *connectionPool) connCleanup(c *memcached.Client) (rv bool) { // just in case we are closing a connection after // bailOut has been sent but we haven't yet read it defer func() { if recover() != nil { rv = false } }() rv = true c.Close() <-cp.createsem return }
[ "func", "(", "cp", "*", "connectionPool", ")", "connCleanup", "(", "c", "*", "memcached", ".", "Client", ")", "(", "rv", "bool", ")", "{", "// just in case we are closing a connection after", "// bailOut has been sent but we haven't yet read it", "defer", "func", "(", ")", "{", "if", "recover", "(", ")", "!=", "nil", "{", "rv", "=", "false", "\n", "}", "\n", "}", "(", ")", "\n", "rv", "=", "true", "\n\n", "c", ".", "Close", "(", ")", "\n", "<-", "cp", ".", "createsem", "\n", "return", "\n", "}" ]
// close connection with recovery on error
[ "close", "connection", "with", "recovery", "on", "error" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/conn_pool.go#L342-L356
146,243
couchbase/go-couchbase
trace/trace.go
ConsolidateByTitle
func ConsolidateByTitle(next *Msg, prev *Msg) *Msg { if prev == nil || prev.Title != next.Title { return next } prev.Repeats++ return nil }
go
func ConsolidateByTitle(next *Msg, prev *Msg) *Msg { if prev == nil || prev.Title != next.Title { return next } prev.Repeats++ return nil }
[ "func", "ConsolidateByTitle", "(", "next", "*", "Msg", ",", "prev", "*", "Msg", ")", "*", "Msg", "{", "if", "prev", "==", "nil", "||", "prev", ".", "Title", "!=", "next", ".", "Title", "{", "return", "next", "\n", "}", "\n\n", "prev", ".", "Repeats", "++", "\n", "return", "nil", "\n", "}" ]
// ConsolidateByTitle implements the MsgConsolidateFunc signature // by consolidating trace message when their titles are the same.
[ "ConsolidateByTitle", "implements", "the", "MsgConsolidateFunc", "signature", "by", "consolidating", "trace", "message", "when", "their", "titles", "are", "the", "same", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/trace/trace.go#L57-L64
146,244
couchbase/go-couchbase
trace/trace.go
NewRingBuffer
func NewRingBuffer( capacity int, consolidateFunc MsgConsolidateFunc) *RingBuffer { return &RingBuffer{ consolidateFunc: consolidateFunc, next: 0, msgs: make([]Msg, capacity), } }
go
func NewRingBuffer( capacity int, consolidateFunc MsgConsolidateFunc) *RingBuffer { return &RingBuffer{ consolidateFunc: consolidateFunc, next: 0, msgs: make([]Msg, capacity), } }
[ "func", "NewRingBuffer", "(", "capacity", "int", ",", "consolidateFunc", "MsgConsolidateFunc", ")", "*", "RingBuffer", "{", "return", "&", "RingBuffer", "{", "consolidateFunc", ":", "consolidateFunc", ",", "next", ":", "0", ",", "msgs", ":", "make", "(", "[", "]", "Msg", ",", "capacity", ")", ",", "}", "\n", "}" ]
// NewRingBuffer returns a RingBuffer initialized with the // given capacity and optional consolidateFunc.
[ "NewRingBuffer", "returns", "a", "RingBuffer", "initialized", "with", "the", "given", "capacity", "and", "optional", "consolidateFunc", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/trace/trace.go#L68-L76
146,245
couchbase/go-couchbase
trace/trace.go
Add
func (trb *RingBuffer) Add(title string, body []byte) { if len(trb.msgs) <= 0 { return } msg := &Msg{ Title: title, Body: body, Repeats: 1, } trb.m.Lock() if trb.consolidateFunc != nil { msg = trb.consolidateFunc(msg, trb.lastUNLOCKED()) if msg == nil { trb.m.Unlock() return } } trb.msgs[trb.next] = *msg trb.next++ if trb.next >= len(trb.msgs) { trb.next = 0 } trb.m.Unlock() }
go
func (trb *RingBuffer) Add(title string, body []byte) { if len(trb.msgs) <= 0 { return } msg := &Msg{ Title: title, Body: body, Repeats: 1, } trb.m.Lock() if trb.consolidateFunc != nil { msg = trb.consolidateFunc(msg, trb.lastUNLOCKED()) if msg == nil { trb.m.Unlock() return } } trb.msgs[trb.next] = *msg trb.next++ if trb.next >= len(trb.msgs) { trb.next = 0 } trb.m.Unlock() }
[ "func", "(", "trb", "*", "RingBuffer", ")", "Add", "(", "title", "string", ",", "body", "[", "]", "byte", ")", "{", "if", "len", "(", "trb", ".", "msgs", ")", "<=", "0", "{", "return", "\n", "}", "\n\n", "msg", ":=", "&", "Msg", "{", "Title", ":", "title", ",", "Body", ":", "body", ",", "Repeats", ":", "1", ",", "}", "\n\n", "trb", ".", "m", ".", "Lock", "(", ")", "\n\n", "if", "trb", ".", "consolidateFunc", "!=", "nil", "{", "msg", "=", "trb", ".", "consolidateFunc", "(", "msg", ",", "trb", ".", "lastUNLOCKED", "(", ")", ")", "\n", "if", "msg", "==", "nil", "{", "trb", ".", "m", ".", "Unlock", "(", ")", "\n\n", "return", "\n", "}", "\n", "}", "\n\n", "trb", ".", "msgs", "[", "trb", ".", "next", "]", "=", "*", "msg", "\n\n", "trb", ".", "next", "++", "\n", "if", "trb", ".", "next", ">=", "len", "(", "trb", ".", "msgs", ")", "{", "trb", ".", "next", "=", "0", "\n", "}", "\n\n", "trb", ".", "m", ".", "Unlock", "(", ")", "\n", "}" ]
// Add appens a trace message to the ring buffer, consolidating trace // messages based on the optional consolidation function.
[ "Add", "appens", "a", "trace", "message", "to", "the", "ring", "buffer", "consolidating", "trace", "messages", "based", "on", "the", "optional", "consolidation", "function", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/trace/trace.go#L80-L110
146,246
couchbase/go-couchbase
trace/trace.go
Last
func (trb *RingBuffer) Last() *Msg { trb.m.Lock() last := trb.lastUNLOCKED() trb.m.Unlock() return last }
go
func (trb *RingBuffer) Last() *Msg { trb.m.Lock() last := trb.lastUNLOCKED() trb.m.Unlock() return last }
[ "func", "(", "trb", "*", "RingBuffer", ")", "Last", "(", ")", "*", "Msg", "{", "trb", ".", "m", ".", "Lock", "(", ")", "\n", "last", ":=", "trb", ".", "lastUNLOCKED", "(", ")", "\n", "trb", ".", "m", ".", "Unlock", "(", ")", "\n", "return", "last", "\n", "}" ]
// Last returns the last trace in the ring buffer.
[ "Last", "returns", "the", "last", "trace", "in", "the", "ring", "buffer", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/trace/trace.go#L118-L123
146,247
couchbase/go-couchbase
trace/trace.go
Msgs
func (trb *RingBuffer) Msgs() []Msg { rv := make([]Msg, 0, len(trb.msgs)) trb.m.Lock() i := trb.next for { if trb.msgs[i].Title != "" { rv = append(rv, trb.msgs[i]) } i++ if i >= len(trb.msgs) { i = 0 } if i == trb.next { // We've returned to the beginning. break } } trb.m.Unlock() return rv }
go
func (trb *RingBuffer) Msgs() []Msg { rv := make([]Msg, 0, len(trb.msgs)) trb.m.Lock() i := trb.next for { if trb.msgs[i].Title != "" { rv = append(rv, trb.msgs[i]) } i++ if i >= len(trb.msgs) { i = 0 } if i == trb.next { // We've returned to the beginning. break } } trb.m.Unlock() return rv }
[ "func", "(", "trb", "*", "RingBuffer", ")", "Msgs", "(", ")", "[", "]", "Msg", "{", "rv", ":=", "make", "(", "[", "]", "Msg", ",", "0", ",", "len", "(", "trb", ".", "msgs", ")", ")", "\n\n", "trb", ".", "m", ".", "Lock", "(", ")", "\n\n", "i", ":=", "trb", ".", "next", "\n", "for", "{", "if", "trb", ".", "msgs", "[", "i", "]", ".", "Title", "!=", "\"", "\"", "{", "rv", "=", "append", "(", "rv", ",", "trb", ".", "msgs", "[", "i", "]", ")", "\n", "}", "\n\n", "i", "++", "\n", "if", "i", ">=", "len", "(", "trb", ".", "msgs", ")", "{", "i", "=", "0", "\n", "}", "\n\n", "if", "i", "==", "trb", ".", "next", "{", "// We've returned to the beginning.", "break", "\n", "}", "\n", "}", "\n\n", "trb", ".", "m", ".", "Unlock", "(", ")", "\n\n", "return", "rv", "\n", "}" ]
// Msgs returns a copy of all the trace messages, as an array with the // oldest trace message first.
[ "Msgs", "returns", "a", "copy", "of", "all", "the", "trace", "messages", "as", "an", "array", "with", "the", "oldest", "trace", "message", "first", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/trace/trace.go#L138-L162
146,248
couchbase/go-couchbase
perf/generate-json.go
generateRandomDocument
func generateRandomDocument() ([]byte, error) { c := &contacts{} c.Name = randomdata.FullName(randomdata.RandomGender) c.Email = randomdata.Email() c.Age = randomdata.Number(20, 50) c.Address = randomdata.Address() c.City = randomdata.City() c.State = randomdata.State(randomdata.Large) c.Country = randomdata.Country(randomdata.FullCountry) return json.Marshal(c) }
go
func generateRandomDocument() ([]byte, error) { c := &contacts{} c.Name = randomdata.FullName(randomdata.RandomGender) c.Email = randomdata.Email() c.Age = randomdata.Number(20, 50) c.Address = randomdata.Address() c.City = randomdata.City() c.State = randomdata.State(randomdata.Large) c.Country = randomdata.Country(randomdata.FullCountry) return json.Marshal(c) }
[ "func", "generateRandomDocument", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "c", ":=", "&", "contacts", "{", "}", "\n", "c", ".", "Name", "=", "randomdata", ".", "FullName", "(", "randomdata", ".", "RandomGender", ")", "\n", "c", ".", "Email", "=", "randomdata", ".", "Email", "(", ")", "\n", "c", ".", "Age", "=", "randomdata", ".", "Number", "(", "20", ",", "50", ")", "\n", "c", ".", "Address", "=", "randomdata", ".", "Address", "(", ")", "\n", "c", ".", "City", "=", "randomdata", ".", "City", "(", ")", "\n", "c", ".", "State", "=", "randomdata", ".", "State", "(", "randomdata", ".", "Large", ")", "\n", "c", ".", "Country", "=", "randomdata", ".", "Country", "(", "randomdata", ".", "FullCountry", ")", "\n\n", "return", "json", ".", "Marshal", "(", "c", ")", "\n", "}" ]
// return a json marshalled document
[ "return", "a", "json", "marshalled", "document" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/perf/generate-json.go#L19-L30
146,249
couchbase/go-couchbase
platform/platform_windows.go
HideConsole
func HideConsole(hide bool) { var k32 = syscall.NewLazyDLL("kernel32.dll") var cw = k32.NewProc("GetConsoleWindow") var u32 = syscall.NewLazyDLL("user32.dll") var sw = u32.NewProc("ShowWindow") hwnd, _, _ := cw.Call() if hwnd == 0 { return } if hide { var SW_HIDE uintptr = 0 sw.Call(hwnd, SW_HIDE) } else { var SW_RESTORE uintptr = 9 sw.Call(hwnd, SW_RESTORE) } }
go
func HideConsole(hide bool) { var k32 = syscall.NewLazyDLL("kernel32.dll") var cw = k32.NewProc("GetConsoleWindow") var u32 = syscall.NewLazyDLL("user32.dll") var sw = u32.NewProc("ShowWindow") hwnd, _, _ := cw.Call() if hwnd == 0 { return } if hide { var SW_HIDE uintptr = 0 sw.Call(hwnd, SW_HIDE) } else { var SW_RESTORE uintptr = 9 sw.Call(hwnd, SW_RESTORE) } }
[ "func", "HideConsole", "(", "hide", "bool", ")", "{", "var", "k32", "=", "syscall", ".", "NewLazyDLL", "(", "\"", "\"", ")", "\n", "var", "cw", "=", "k32", ".", "NewProc", "(", "\"", "\"", ")", "\n", "var", "u32", "=", "syscall", ".", "NewLazyDLL", "(", "\"", "\"", ")", "\n", "var", "sw", "=", "u32", ".", "NewProc", "(", "\"", "\"", ")", "\n", "hwnd", ",", "_", ",", "_", ":=", "cw", ".", "Call", "(", ")", "\n", "if", "hwnd", "==", "0", "{", "return", "\n", "}", "\n", "if", "hide", "{", "var", "SW_HIDE", "uintptr", "=", "0", "\n", "sw", ".", "Call", "(", "hwnd", ",", "SW_HIDE", ")", "\n", "}", "else", "{", "var", "SW_RESTORE", "uintptr", "=", "9", "\n", "sw", ".", "Call", "(", "hwnd", ",", "SW_RESTORE", ")", "\n", "}", "\n", "}" ]
// Hide console on windows without removing it unlike -H windowsgui.
[ "Hide", "console", "on", "windows", "without", "removing", "it", "unlike", "-", "H", "windowsgui", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/platform/platform_windows.go#L20-L36
146,250
couchbase/go-couchbase
ddocs.go
GetDDocs
func (b *Bucket) GetDDocs() (DDocsResult, error) { var ddocsResult DDocsResult b.RLock() pool := b.pool uri := b.DDocs.URI b.RUnlock() // MB-23555 ephemeral buckets have no ddocs if uri == "" { return DDocsResult{}, nil } err := pool.client.parseURLResponse(uri, &ddocsResult) if err != nil { return DDocsResult{}, err } return ddocsResult, nil }
go
func (b *Bucket) GetDDocs() (DDocsResult, error) { var ddocsResult DDocsResult b.RLock() pool := b.pool uri := b.DDocs.URI b.RUnlock() // MB-23555 ephemeral buckets have no ddocs if uri == "" { return DDocsResult{}, nil } err := pool.client.parseURLResponse(uri, &ddocsResult) if err != nil { return DDocsResult{}, err } return ddocsResult, nil }
[ "func", "(", "b", "*", "Bucket", ")", "GetDDocs", "(", ")", "(", "DDocsResult", ",", "error", ")", "{", "var", "ddocsResult", "DDocsResult", "\n", "b", ".", "RLock", "(", ")", "\n", "pool", ":=", "b", ".", "pool", "\n", "uri", ":=", "b", ".", "DDocs", ".", "URI", "\n", "b", ".", "RUnlock", "(", ")", "\n\n", "// MB-23555 ephemeral buckets have no ddocs", "if", "uri", "==", "\"", "\"", "{", "return", "DDocsResult", "{", "}", ",", "nil", "\n", "}", "\n\n", "err", ":=", "pool", ".", "client", ".", "parseURLResponse", "(", "uri", ",", "&", "ddocsResult", ")", "\n", "if", "err", "!=", "nil", "{", "return", "DDocsResult", "{", "}", ",", "err", "\n", "}", "\n", "return", "ddocsResult", ",", "nil", "\n", "}" ]
// GetDDocs lists all design documents
[ "GetDDocs", "lists", "all", "design", "documents" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/ddocs.go#L36-L53
146,251
couchbase/go-couchbase
ddocs.go
PutDDoc
func (b *Bucket) PutDDoc(docname string, value interface{}) error { var Err error maxRetries, err := b.getMaxRetries() if err != nil { return err } lastNode := START_NODE_ID for retryCount := 0; retryCount < maxRetries; retryCount++ { Err = nil ddocU, selectedNode, err := b.ddocURLNext(lastNode, docname) if err != nil { return err } lastNode = selectedNode logging.Infof(" Trying with selected node %d", selectedNode) j, err := json.Marshal(value) if err != nil { return err } req, err := http.NewRequest("PUT", ddocU, bytes.NewReader(j)) if err != nil { return err } req.Header.Set("Content-Type", "application/json") err = maybeAddAuth(req, b.authHandler(false /* bucket not yet locked */)) if err != nil { return err } res, err := doHTTPRequest(req) if err != nil { return err } if res.StatusCode != 201 { body, _ := ioutil.ReadAll(res.Body) Err = fmt.Errorf("error installing view: %v / %s", res.Status, body) logging.Errorf(" Error in PutDDOC %v. Retrying...", Err) res.Body.Close() b.Refresh() continue } res.Body.Close() break } return Err }
go
func (b *Bucket) PutDDoc(docname string, value interface{}) error { var Err error maxRetries, err := b.getMaxRetries() if err != nil { return err } lastNode := START_NODE_ID for retryCount := 0; retryCount < maxRetries; retryCount++ { Err = nil ddocU, selectedNode, err := b.ddocURLNext(lastNode, docname) if err != nil { return err } lastNode = selectedNode logging.Infof(" Trying with selected node %d", selectedNode) j, err := json.Marshal(value) if err != nil { return err } req, err := http.NewRequest("PUT", ddocU, bytes.NewReader(j)) if err != nil { return err } req.Header.Set("Content-Type", "application/json") err = maybeAddAuth(req, b.authHandler(false /* bucket not yet locked */)) if err != nil { return err } res, err := doHTTPRequest(req) if err != nil { return err } if res.StatusCode != 201 { body, _ := ioutil.ReadAll(res.Body) Err = fmt.Errorf("error installing view: %v / %s", res.Status, body) logging.Errorf(" Error in PutDDOC %v. Retrying...", Err) res.Body.Close() b.Refresh() continue } res.Body.Close() break } return Err }
[ "func", "(", "b", "*", "Bucket", ")", "PutDDoc", "(", "docname", "string", ",", "value", "interface", "{", "}", ")", "error", "{", "var", "Err", "error", "\n\n", "maxRetries", ",", "err", ":=", "b", ".", "getMaxRetries", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "lastNode", ":=", "START_NODE_ID", "\n\n", "for", "retryCount", ":=", "0", ";", "retryCount", "<", "maxRetries", ";", "retryCount", "++", "{", "Err", "=", "nil", "\n\n", "ddocU", ",", "selectedNode", ",", "err", ":=", "b", ".", "ddocURLNext", "(", "lastNode", ",", "docname", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "lastNode", "=", "selectedNode", "\n\n", "logging", ".", "Infof", "(", "\"", "\"", ",", "selectedNode", ")", "\n", "j", ",", "err", ":=", "json", ".", "Marshal", "(", "value", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "ddocU", ",", "bytes", ".", "NewReader", "(", "j", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "err", "=", "maybeAddAuth", "(", "req", ",", "b", ".", "authHandler", "(", "false", "/* bucket not yet locked */", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "res", ",", "err", ":=", "doHTTPRequest", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "res", ".", "StatusCode", "!=", "201", "{", "body", ",", "_", ":=", "ioutil", ".", "ReadAll", "(", "res", ".", "Body", ")", "\n", "Err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "res", ".", "Status", ",", "body", ")", "\n", "logging", ".", "Errorf", "(", "\"", "\"", ",", "Err", ")", "\n", "res", ".", "Body", ".", "Close", "(", ")", "\n", "b", ".", "Refresh", "(", ")", "\n", "continue", "\n", "}", "\n\n", "res", ".", "Body", ".", "Close", "(", ")", "\n", "break", "\n", "}", "\n\n", "return", "Err", "\n", "}" ]
// PutDDoc installs a design document.
[ "PutDDoc", "installs", "a", "design", "document", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/ddocs.go#L121-L179
146,252
couchbase/go-couchbase
util.go
CleanupHost
func CleanupHost(h, commonSuffix string) string { if strings.HasSuffix(h, commonSuffix) { return h[:len(h)-len(commonSuffix)] } return h }
go
func CleanupHost(h, commonSuffix string) string { if strings.HasSuffix(h, commonSuffix) { return h[:len(h)-len(commonSuffix)] } return h }
[ "func", "CleanupHost", "(", "h", ",", "commonSuffix", "string", ")", "string", "{", "if", "strings", ".", "HasSuffix", "(", "h", ",", "commonSuffix", ")", "{", "return", "h", "[", ":", "len", "(", "h", ")", "-", "len", "(", "commonSuffix", ")", "]", "\n", "}", "\n", "return", "h", "\n", "}" ]
// CleanupHost returns the hostname with the given suffix removed.
[ "CleanupHost", "returns", "the", "hostname", "with", "the", "given", "suffix", "removed", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/util.go#L10-L15
146,253
couchbase/go-couchbase
util.go
FindCommonSuffix
func FindCommonSuffix(input []string) string { rv := "" if len(input) < 2 { return "" } from := input for i := len(input[0]); i > 0; i-- { common := true suffix := input[0][i:] for _, s := range from { if !strings.HasSuffix(s, suffix) { common = false break } } if common { rv = suffix } } return rv }
go
func FindCommonSuffix(input []string) string { rv := "" if len(input) < 2 { return "" } from := input for i := len(input[0]); i > 0; i-- { common := true suffix := input[0][i:] for _, s := range from { if !strings.HasSuffix(s, suffix) { common = false break } } if common { rv = suffix } } return rv }
[ "func", "FindCommonSuffix", "(", "input", "[", "]", "string", ")", "string", "{", "rv", ":=", "\"", "\"", "\n", "if", "len", "(", "input", ")", "<", "2", "{", "return", "\"", "\"", "\n", "}", "\n", "from", ":=", "input", "\n", "for", "i", ":=", "len", "(", "input", "[", "0", "]", ")", ";", "i", ">", "0", ";", "i", "--", "{", "common", ":=", "true", "\n", "suffix", ":=", "input", "[", "0", "]", "[", "i", ":", "]", "\n", "for", "_", ",", "s", ":=", "range", "from", "{", "if", "!", "strings", ".", "HasSuffix", "(", "s", ",", "suffix", ")", "{", "common", "=", "false", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "common", "{", "rv", "=", "suffix", "\n", "}", "\n", "}", "\n", "return", "rv", "\n", "}" ]
// FindCommonSuffix returns the longest common suffix from the given // strings.
[ "FindCommonSuffix", "returns", "the", "longest", "common", "suffix", "from", "the", "given", "strings", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/util.go#L19-L39
146,254
couchbase/go-couchbase
util.go
ParseURL
func ParseURL(urlStr string) (result *url.URL, err error) { result, err = url.Parse(urlStr) if result != nil && result.Scheme == "" { result = nil err = fmt.Errorf("invalid URL <%s>", urlStr) } return }
go
func ParseURL(urlStr string) (result *url.URL, err error) { result, err = url.Parse(urlStr) if result != nil && result.Scheme == "" { result = nil err = fmt.Errorf("invalid URL <%s>", urlStr) } return }
[ "func", "ParseURL", "(", "urlStr", "string", ")", "(", "result", "*", "url", ".", "URL", ",", "err", "error", ")", "{", "result", ",", "err", "=", "url", ".", "Parse", "(", "urlStr", ")", "\n", "if", "result", "!=", "nil", "&&", "result", ".", "Scheme", "==", "\"", "\"", "{", "result", "=", "nil", "\n", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "urlStr", ")", "\n", "}", "\n", "return", "\n", "}" ]
// ParseURL is a wrapper around url.Parse with some sanity-checking
[ "ParseURL", "is", "a", "wrapper", "around", "url", ".", "Parse", "with", "some", "sanity", "-", "checking" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/util.go#L42-L49
146,255
couchbase/go-couchbase
vbmap.go
VBHash
func (b *Bucket) VBHash(key string) uint32 { crc := uint32(0xffffffff) for x := 0; x < len(key); x++ { crc = (crc >> 8) ^ crc32tab[(uint64(crc)^uint64(key[x]))&0xff] } vbm := b.VBServerMap() return ((^crc) >> 16) & 0x7fff & (uint32(len(vbm.VBucketMap)) - 1) }
go
func (b *Bucket) VBHash(key string) uint32 { crc := uint32(0xffffffff) for x := 0; x < len(key); x++ { crc = (crc >> 8) ^ crc32tab[(uint64(crc)^uint64(key[x]))&0xff] } vbm := b.VBServerMap() return ((^crc) >> 16) & 0x7fff & (uint32(len(vbm.VBucketMap)) - 1) }
[ "func", "(", "b", "*", "Bucket", ")", "VBHash", "(", "key", "string", ")", "uint32", "{", "crc", ":=", "uint32", "(", "0xffffffff", ")", "\n", "for", "x", ":=", "0", ";", "x", "<", "len", "(", "key", ")", ";", "x", "++", "{", "crc", "=", "(", "crc", ">>", "8", ")", "^", "crc32tab", "[", "(", "uint64", "(", "crc", ")", "^", "uint64", "(", "key", "[", "x", "]", ")", ")", "&", "0xff", "]", "\n", "}", "\n", "vbm", ":=", "b", ".", "VBServerMap", "(", ")", "\n", "return", "(", "(", "^", "crc", ")", ">>", "16", ")", "&", "0x7fff", "&", "(", "uint32", "(", "len", "(", "vbm", ".", "VBucketMap", ")", ")", "-", "1", ")", "\n", "}" ]
// VBHash finds the vbucket for the given key.
[ "VBHash", "finds", "the", "vbucket", "for", "the", "given", "key", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/vbmap.go#L70-L77
146,256
couchbase/go-couchbase
pools.go
SetConnectionPoolParams
func SetConnectionPoolParams(size, overflow int) { if size > 0 { PoolSize = size } if overflow > 0 { PoolOverflow = overflow } }
go
func SetConnectionPoolParams(size, overflow int) { if size > 0 { PoolSize = size } if overflow > 0 { PoolOverflow = overflow } }
[ "func", "SetConnectionPoolParams", "(", "size", ",", "overflow", "int", ")", "{", "if", "size", ">", "0", "{", "PoolSize", "=", "size", "\n", "}", "\n\n", "if", "overflow", ">", "0", "{", "PoolOverflow", "=", "overflow", "\n", "}", "\n", "}" ]
// Allow applications to speciify the Poolsize and Overflow
[ "Allow", "applications", "to", "speciify", "the", "Poolsize", "and", "Overflow" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L87-L96
146,257
couchbase/go-couchbase
pools.go
SetTcpKeepalive
func SetTcpKeepalive(enabled bool, interval int) { TCPKeepalive = enabled if interval > 0 { TCPKeepaliveInterval = interval } }
go
func SetTcpKeepalive(enabled bool, interval int) { TCPKeepalive = enabled if interval > 0 { TCPKeepaliveInterval = interval } }
[ "func", "SetTcpKeepalive", "(", "enabled", "bool", ",", "interval", "int", ")", "{", "TCPKeepalive", "=", "enabled", "\n\n", "if", "interval", ">", "0", "{", "TCPKeepaliveInterval", "=", "interval", "\n", "}", "\n", "}" ]
// Allow TCP keepalive parameters to be set by the application
[ "Allow", "TCP", "keepalive", "parameters", "to", "be", "set", "by", "the", "application" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L109-L116
146,258
couchbase/go-couchbase
pools.go
VBServerMap
func (b *Bucket) VBServerMap() *VBucketServerMap { b.RLock() defer b.RUnlock() ret := (*VBucketServerMap)(b.vBucketServerMap) return ret }
go
func (b *Bucket) VBServerMap() *VBucketServerMap { b.RLock() defer b.RUnlock() ret := (*VBucketServerMap)(b.vBucketServerMap) return ret }
[ "func", "(", "b", "*", "Bucket", ")", "VBServerMap", "(", ")", "*", "VBucketServerMap", "{", "b", ".", "RLock", "(", ")", "\n", "defer", "b", ".", "RUnlock", "(", ")", "\n", "ret", ":=", "(", "*", "VBucketServerMap", ")", "(", "b", ".", "vBucketServerMap", ")", "\n", "return", "ret", "\n", "}" ]
// VBServerMap returns the current VBucketServerMap.
[ "VBServerMap", "returns", "the", "current", "VBucketServerMap", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L288-L293
146,259
couchbase/go-couchbase
pools.go
checkVBmap
func (b *Bucket) checkVBmap(node string) bool { vbmap := b.VBServerMap() servers := vbmap.ServerList for _, idxs := range vbmap.VBucketMap { if len(idxs) == 0 { return true } else if idxs[0] < 0 || idxs[0] >= len(servers) { return true } if servers[idxs[0]] == node { return false } } return true }
go
func (b *Bucket) checkVBmap(node string) bool { vbmap := b.VBServerMap() servers := vbmap.ServerList for _, idxs := range vbmap.VBucketMap { if len(idxs) == 0 { return true } else if idxs[0] < 0 || idxs[0] >= len(servers) { return true } if servers[idxs[0]] == node { return false } } return true }
[ "func", "(", "b", "*", "Bucket", ")", "checkVBmap", "(", "node", "string", ")", "bool", "{", "vbmap", ":=", "b", ".", "VBServerMap", "(", ")", "\n", "servers", ":=", "vbmap", ".", "ServerList", "\n\n", "for", "_", ",", "idxs", ":=", "range", "vbmap", ".", "VBucketMap", "{", "if", "len", "(", "idxs", ")", "==", "0", "{", "return", "true", "\n", "}", "else", "if", "idxs", "[", "0", "]", "<", "0", "||", "idxs", "[", "0", "]", ">=", "len", "(", "servers", ")", "{", "return", "true", "\n", "}", "\n", "if", "servers", "[", "idxs", "[", "0", "]", "]", "==", "node", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// true if node is not on the bucket VBmap
[ "true", "if", "node", "is", "not", "on", "the", "bucket", "VBmap" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L321-L336
146,260
couchbase/go-couchbase
pools.go
Nodes
func (b *Bucket) Nodes() []Node { b.RLock() defer b.RUnlock() ret := *(*[]Node)(b.nodeList) return ret }
go
func (b *Bucket) Nodes() []Node { b.RLock() defer b.RUnlock() ret := *(*[]Node)(b.nodeList) return ret }
[ "func", "(", "b", "*", "Bucket", ")", "Nodes", "(", ")", "[", "]", "Node", "{", "b", ".", "RLock", "(", ")", "\n", "defer", "b", ".", "RUnlock", "(", ")", "\n", "ret", ":=", "*", "(", "*", "[", "]", "Node", ")", "(", "b", ".", "nodeList", ")", "\n", "return", "ret", "\n", "}" ]
// Nodes returns the current list of nodes servicing this bucket.
[ "Nodes", "returns", "the", "current", "list", "of", "nodes", "servicing", "this", "bucket", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L346-L351
146,261
couchbase/go-couchbase
pools.go
HealthyNodes
func (b *Bucket) HealthyNodes() []Node { nodes := []Node{} for _, n := range b.Nodes() { if n.Status == "healthy" && n.CouchAPIBase != "" { nodes = append(nodes, n) } if n.Status != "healthy" { // log non-healthy node logging.Infof("Non-healthy node; node details:") logging.Infof("Hostname=%v, Status=%v, CouchAPIBase=%v, ThisNode=%v", n.Hostname, n.Status, n.CouchAPIBase, n.ThisNode) } } return nodes }
go
func (b *Bucket) HealthyNodes() []Node { nodes := []Node{} for _, n := range b.Nodes() { if n.Status == "healthy" && n.CouchAPIBase != "" { nodes = append(nodes, n) } if n.Status != "healthy" { // log non-healthy node logging.Infof("Non-healthy node; node details:") logging.Infof("Hostname=%v, Status=%v, CouchAPIBase=%v, ThisNode=%v", n.Hostname, n.Status, n.CouchAPIBase, n.ThisNode) } } return nodes }
[ "func", "(", "b", "*", "Bucket", ")", "HealthyNodes", "(", ")", "[", "]", "Node", "{", "nodes", ":=", "[", "]", "Node", "{", "}", "\n\n", "for", "_", ",", "n", ":=", "range", "b", ".", "Nodes", "(", ")", "{", "if", "n", ".", "Status", "==", "\"", "\"", "&&", "n", ".", "CouchAPIBase", "!=", "\"", "\"", "{", "nodes", "=", "append", "(", "nodes", ",", "n", ")", "\n", "}", "\n", "if", "n", ".", "Status", "!=", "\"", "\"", "{", "// log non-healthy node", "logging", ".", "Infof", "(", "\"", "\"", ")", "\n", "logging", ".", "Infof", "(", "\"", "\"", ",", "n", ".", "Hostname", ",", "n", ".", "Status", ",", "n", ".", "CouchAPIBase", ",", "n", ".", "ThisNode", ")", "\n", "}", "\n", "}", "\n\n", "return", "nodes", "\n", "}" ]
// return the list of healthy nodes
[ "return", "the", "list", "of", "healthy", "nodes" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L354-L368
146,262
couchbase/go-couchbase
pools.go
getConnectionToVBucket
func (b *Bucket) getConnectionToVBucket(vb uint32) (*memcached.Client, *connectionPool, error) { for { vbm := b.VBServerMap() if len(vbm.VBucketMap) < int(vb) { return nil, nil, fmt.Errorf("go-couchbase: vbmap smaller than vbucket list: %v vs. %v", vb, vbm.VBucketMap) } masterId := vbm.VBucketMap[vb][0] if masterId < 0 { return nil, nil, fmt.Errorf("go-couchbase: No master for vbucket %d", vb) } pool := b.getConnPool(masterId) conn, err := pool.Get() if err != errClosedPool { return conn, pool, err } // If conn pool was closed, because another goroutine refreshed the vbucket map, retry... } }
go
func (b *Bucket) getConnectionToVBucket(vb uint32) (*memcached.Client, *connectionPool, error) { for { vbm := b.VBServerMap() if len(vbm.VBucketMap) < int(vb) { return nil, nil, fmt.Errorf("go-couchbase: vbmap smaller than vbucket list: %v vs. %v", vb, vbm.VBucketMap) } masterId := vbm.VBucketMap[vb][0] if masterId < 0 { return nil, nil, fmt.Errorf("go-couchbase: No master for vbucket %d", vb) } pool := b.getConnPool(masterId) conn, err := pool.Get() if err != errClosedPool { return conn, pool, err } // If conn pool was closed, because another goroutine refreshed the vbucket map, retry... } }
[ "func", "(", "b", "*", "Bucket", ")", "getConnectionToVBucket", "(", "vb", "uint32", ")", "(", "*", "memcached", ".", "Client", ",", "*", "connectionPool", ",", "error", ")", "{", "for", "{", "vbm", ":=", "b", ".", "VBServerMap", "(", ")", "\n", "if", "len", "(", "vbm", ".", "VBucketMap", ")", "<", "int", "(", "vb", ")", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "vb", ",", "vbm", ".", "VBucketMap", ")", "\n", "}", "\n", "masterId", ":=", "vbm", ".", "VBucketMap", "[", "vb", "]", "[", "0", "]", "\n", "if", "masterId", "<", "0", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "vb", ")", "\n", "}", "\n", "pool", ":=", "b", ".", "getConnPool", "(", "masterId", ")", "\n", "conn", ",", "err", ":=", "pool", ".", "Get", "(", ")", "\n", "if", "err", "!=", "errClosedPool", "{", "return", "conn", ",", "pool", ",", "err", "\n", "}", "\n", "// If conn pool was closed, because another goroutine refreshed the vbucket map, retry...", "}", "\n", "}" ]
// Given a vbucket number, returns a memcached connection to it. // The connection must be returned to its pool after use.
[ "Given", "a", "vbucket", "number", "returns", "a", "memcached", "connection", "to", "it", ".", "The", "connection", "must", "be", "returned", "to", "its", "pool", "after", "use", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L425-L443
146,263
couchbase/go-couchbase
pools.go
getRandomConnection
func (b *Bucket) getRandomConnection() (*memcached.Client, *connectionPool, error) { for { var currentPool = 0 pools := b.getConnPools(false /* not already locked */) if len(pools) == 0 { return nil, nil, fmt.Errorf("No connection pool found") } else if len(pools) > 1 { // choose a random connection currentPool = rand.Intn(len(pools)) } // if only one pool, currentPool defaults to 0, i.e., the only pool // get the pool pool := pools[currentPool] conn, err := pool.Get() if err != errClosedPool { return conn, pool, err } // If conn pool was closed, because another goroutine refreshed the vbucket map, retry... } }
go
func (b *Bucket) getRandomConnection() (*memcached.Client, *connectionPool, error) { for { var currentPool = 0 pools := b.getConnPools(false /* not already locked */) if len(pools) == 0 { return nil, nil, fmt.Errorf("No connection pool found") } else if len(pools) > 1 { // choose a random connection currentPool = rand.Intn(len(pools)) } // if only one pool, currentPool defaults to 0, i.e., the only pool // get the pool pool := pools[currentPool] conn, err := pool.Get() if err != errClosedPool { return conn, pool, err } // If conn pool was closed, because another goroutine refreshed the vbucket map, retry... } }
[ "func", "(", "b", "*", "Bucket", ")", "getRandomConnection", "(", ")", "(", "*", "memcached", ".", "Client", ",", "*", "connectionPool", ",", "error", ")", "{", "for", "{", "var", "currentPool", "=", "0", "\n", "pools", ":=", "b", ".", "getConnPools", "(", "false", "/* not already locked */", ")", "\n", "if", "len", "(", "pools", ")", "==", "0", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "else", "if", "len", "(", "pools", ")", ">", "1", "{", "// choose a random connection", "currentPool", "=", "rand", ".", "Intn", "(", "len", "(", "pools", ")", ")", "\n", "}", "// if only one pool, currentPool defaults to 0, i.e., the only pool", "\n\n", "// get the pool", "pool", ":=", "pools", "[", "currentPool", "]", "\n", "conn", ",", "err", ":=", "pool", ".", "Get", "(", ")", "\n", "if", "err", "!=", "errClosedPool", "{", "return", "conn", ",", "pool", ",", "err", "\n", "}", "\n\n", "// If conn pool was closed, because another goroutine refreshed the vbucket map, retry...", "}", "\n", "}" ]
// To get random documents, we need to cover all the nodes, so select // a connection at random.
[ "To", "get", "random", "documents", "we", "need", "to", "cover", "all", "the", "nodes", "so", "select", "a", "connection", "at", "random", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L448-L467
146,264
couchbase/go-couchbase
pools.go
ConnectWithAuth
func ConnectWithAuth(baseU string, ah AuthHandler) (c Client, err error) { c.BaseURL, err = ParseURL(baseU) if err != nil { return } c.ah = ah return c, c.parseURLResponse("/pools", &c.Info) }
go
func ConnectWithAuth(baseU string, ah AuthHandler) (c Client, err error) { c.BaseURL, err = ParseURL(baseU) if err != nil { return } c.ah = ah return c, c.parseURLResponse("/pools", &c.Info) }
[ "func", "ConnectWithAuth", "(", "baseU", "string", ",", "ah", "AuthHandler", ")", "(", "c", "Client", ",", "err", "error", ")", "{", "c", ".", "BaseURL", ",", "err", "=", "ParseURL", "(", "baseU", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "c", ".", "ah", "=", "ah", "\n\n", "return", "c", ",", "c", ".", "parseURLResponse", "(", "\"", "\"", ",", "&", "c", ".", "Info", ")", "\n", "}" ]
// ConnectWithAuth connects to a couchbase cluster with the given // authentication handler.
[ "ConnectWithAuth", "connects", "to", "a", "couchbase", "cluster", "with", "the", "given", "authentication", "handler", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L938-L946
146,265
couchbase/go-couchbase
pools.go
ConnectWithAuthCreds
func ConnectWithAuthCreds(baseU, username, password string) (c Client, err error) { c.BaseURL, err = ParseURL(baseU) if err != nil { return } c.ah = newBucketAuth(username, password, "") return c, c.parseURLResponse("/pools", &c.Info) }
go
func ConnectWithAuthCreds(baseU, username, password string) (c Client, err error) { c.BaseURL, err = ParseURL(baseU) if err != nil { return } c.ah = newBucketAuth(username, password, "") return c, c.parseURLResponse("/pools", &c.Info) }
[ "func", "ConnectWithAuthCreds", "(", "baseU", ",", "username", ",", "password", "string", ")", "(", "c", "Client", ",", "err", "error", ")", "{", "c", ".", "BaseURL", ",", "err", "=", "ParseURL", "(", "baseU", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "c", ".", "ah", "=", "newBucketAuth", "(", "username", ",", "password", ",", "\"", "\"", ")", "\n", "return", "c", ",", "c", ".", "parseURLResponse", "(", "\"", "\"", ",", "&", "c", ".", "Info", ")", "\n", "}" ]
// ConnectWithAuthCreds connects to a couchbase cluster with the give // authorization creds returned by cb_auth
[ "ConnectWithAuthCreds", "connects", "to", "a", "couchbase", "cluster", "with", "the", "give", "authorization", "creds", "returned", "by", "cb_auth" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L969-L977
146,266
couchbase/go-couchbase
pools.go
GetBucketList
func GetBucketList(baseU string) (bInfo []BucketInfo, err error) { c := &Client{} c.BaseURL, err = ParseURL(baseU) if err != nil { return } c.ah = basicAuthFromURL(baseU) var buckets []Bucket err = c.parseURLResponse("/pools/default/buckets", &buckets) if err != nil { return } bInfo = make([]BucketInfo, 0) for _, bucket := range buckets { bucketInfo := BucketInfo{Name: bucket.Name, Password: bucket.Password} bInfo = append(bInfo, bucketInfo) } return bInfo, err }
go
func GetBucketList(baseU string) (bInfo []BucketInfo, err error) { c := &Client{} c.BaseURL, err = ParseURL(baseU) if err != nil { return } c.ah = basicAuthFromURL(baseU) var buckets []Bucket err = c.parseURLResponse("/pools/default/buckets", &buckets) if err != nil { return } bInfo = make([]BucketInfo, 0) for _, bucket := range buckets { bucketInfo := BucketInfo{Name: bucket.Name, Password: bucket.Password} bInfo = append(bInfo, bucketInfo) } return bInfo, err }
[ "func", "GetBucketList", "(", "baseU", "string", ")", "(", "bInfo", "[", "]", "BucketInfo", ",", "err", "error", ")", "{", "c", ":=", "&", "Client", "{", "}", "\n", "c", ".", "BaseURL", ",", "err", "=", "ParseURL", "(", "baseU", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "c", ".", "ah", "=", "basicAuthFromURL", "(", "baseU", ")", "\n\n", "var", "buckets", "[", "]", "Bucket", "\n", "err", "=", "c", ".", "parseURLResponse", "(", "\"", "\"", ",", "&", "buckets", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "bInfo", "=", "make", "(", "[", "]", "BucketInfo", ",", "0", ")", "\n", "for", "_", ",", "bucket", ":=", "range", "buckets", "{", "bucketInfo", ":=", "BucketInfo", "{", "Name", ":", "bucket", ".", "Name", ",", "Password", ":", "bucket", ".", "Password", "}", "\n", "bInfo", "=", "append", "(", "bInfo", ",", "bucketInfo", ")", "\n", "}", "\n", "return", "bInfo", ",", "err", "\n", "}" ]
//Get SASL buckets
[ "Get", "SASL", "buckets" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L991-L1011
146,267
couchbase/go-couchbase
pools.go
GetCollectionsManifest
func (b *Bucket) GetCollectionsManifest() (*Manifest, error) { // Collections not used? if !EnableCollections { return nil, fmt.Errorf("Collections not enabled.") } b.RLock() pools := b.getConnPools(true /* already locked */) pool := pools[0] // Any pool will do, so use the first one. b.RUnlock() client, err := pool.Get() if err != nil { return nil, fmt.Errorf("Unable to get connection to retrieve collections manifest: %v. No collections access to bucket %s.", err, b.Name) } // We need to select the bucket before GetCollectionsManifest() // will work. This is sometimes done at startup (see defaultMkConn()) // but not always, depending on the auth type. // Doing this is safe because we collect the the connections // by bucket, so the bucket being selected will never change. _, err = client.SelectBucket(b.Name) if err != nil { pool.Return(client) return nil, fmt.Errorf("Unable to select bucket %s: %v. No collections access to bucket %s.", err, b.Name, b.Name) } res, err := client.GetCollectionsManifest() if err != nil { pool.Return(client) return nil, fmt.Errorf("Unable to retrieve collections manifest: %v. No collections access to bucket %s.", err, b.Name) } mani, err := parseCollectionsManifest(res) if err != nil { pool.Return(client) return nil, fmt.Errorf("Unable to parse collections manifest: %v. No collections access to bucket %s.", err, b.Name) } pool.Return(client) return mani, nil }
go
func (b *Bucket) GetCollectionsManifest() (*Manifest, error) { // Collections not used? if !EnableCollections { return nil, fmt.Errorf("Collections not enabled.") } b.RLock() pools := b.getConnPools(true /* already locked */) pool := pools[0] // Any pool will do, so use the first one. b.RUnlock() client, err := pool.Get() if err != nil { return nil, fmt.Errorf("Unable to get connection to retrieve collections manifest: %v. No collections access to bucket %s.", err, b.Name) } // We need to select the bucket before GetCollectionsManifest() // will work. This is sometimes done at startup (see defaultMkConn()) // but not always, depending on the auth type. // Doing this is safe because we collect the the connections // by bucket, so the bucket being selected will never change. _, err = client.SelectBucket(b.Name) if err != nil { pool.Return(client) return nil, fmt.Errorf("Unable to select bucket %s: %v. No collections access to bucket %s.", err, b.Name, b.Name) } res, err := client.GetCollectionsManifest() if err != nil { pool.Return(client) return nil, fmt.Errorf("Unable to retrieve collections manifest: %v. No collections access to bucket %s.", err, b.Name) } mani, err := parseCollectionsManifest(res) if err != nil { pool.Return(client) return nil, fmt.Errorf("Unable to parse collections manifest: %v. No collections access to bucket %s.", err, b.Name) } pool.Return(client) return mani, nil }
[ "func", "(", "b", "*", "Bucket", ")", "GetCollectionsManifest", "(", ")", "(", "*", "Manifest", ",", "error", ")", "{", "// Collections not used?", "if", "!", "EnableCollections", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "b", ".", "RLock", "(", ")", "\n", "pools", ":=", "b", ".", "getConnPools", "(", "true", "/* already locked */", ")", "\n", "pool", ":=", "pools", "[", "0", "]", "// Any pool will do, so use the first one.", "\n", "b", ".", "RUnlock", "(", ")", "\n", "client", ",", "err", ":=", "pool", ".", "Get", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ",", "b", ".", "Name", ")", "\n", "}", "\n\n", "// We need to select the bucket before GetCollectionsManifest()", "// will work. This is sometimes done at startup (see defaultMkConn())", "// but not always, depending on the auth type.", "// Doing this is safe because we collect the the connections", "// by bucket, so the bucket being selected will never change.", "_", ",", "err", "=", "client", ".", "SelectBucket", "(", "b", ".", "Name", ")", "\n", "if", "err", "!=", "nil", "{", "pool", ".", "Return", "(", "client", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ",", "b", ".", "Name", ",", "b", ".", "Name", ")", "\n", "}", "\n\n", "res", ",", "err", ":=", "client", ".", "GetCollectionsManifest", "(", ")", "\n", "if", "err", "!=", "nil", "{", "pool", ".", "Return", "(", "client", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ",", "b", ".", "Name", ")", "\n", "}", "\n", "mani", ",", "err", ":=", "parseCollectionsManifest", "(", "res", ")", "\n", "if", "err", "!=", "nil", "{", "pool", ".", "Return", "(", "client", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ",", "b", ".", "Name", ")", "\n", "}", "\n\n", "pool", ".", "Return", "(", "client", ")", "\n", "return", "mani", ",", "nil", "\n", "}" ]
// This function assumes the bucket is locked.
[ "This", "function", "assumes", "the", "bucket", "is", "locked", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L1152-L1191
146,268
couchbase/go-couchbase
pools.go
Close
func (b *Bucket) Close() { b.Lock() defer b.Unlock() if b.connPools != nil { for _, c := range b.getConnPools(true /* already locked */) { if c != nil { c.Close() } } b.connPools = nil } }
go
func (b *Bucket) Close() { b.Lock() defer b.Unlock() if b.connPools != nil { for _, c := range b.getConnPools(true /* already locked */) { if c != nil { c.Close() } } b.connPools = nil } }
[ "func", "(", "b", "*", "Bucket", ")", "Close", "(", ")", "{", "b", ".", "Lock", "(", ")", "\n", "defer", "b", ".", "Unlock", "(", ")", "\n", "if", "b", ".", "connPools", "!=", "nil", "{", "for", "_", ",", "c", ":=", "range", "b", ".", "getConnPools", "(", "true", "/* already locked */", ")", "{", "if", "c", "!=", "nil", "{", "c", ".", "Close", "(", ")", "\n", "}", "\n", "}", "\n", "b", ".", "connPools", "=", "nil", "\n", "}", "\n", "}" ]
// Close marks this bucket as no longer needed, closing connections it // may have open.
[ "Close", "marks", "this", "bucket", "as", "no", "longer", "needed", "closing", "connections", "it", "may", "have", "open", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L1362-L1373
146,269
couchbase/go-couchbase
pools.go
GetPool
func (b *Bucket) GetPool() *Pool { b.RLock() defer b.RUnlock() ret := b.pool return ret }
go
func (b *Bucket) GetPool() *Pool { b.RLock() defer b.RUnlock() ret := b.pool return ret }
[ "func", "(", "b", "*", "Bucket", ")", "GetPool", "(", ")", "*", "Pool", "{", "b", ".", "RLock", "(", ")", "\n", "defer", "b", ".", "RUnlock", "(", ")", "\n", "ret", ":=", "b", ".", "pool", "\n", "return", "ret", "\n", "}" ]
// GetPool gets the pool to which this bucket belongs.
[ "GetPool", "gets", "the", "pool", "to", "which", "this", "bucket", "belongs", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L1414-L1419
146,270
couchbase/go-couchbase
pools.go
Close
func (p *Pool) Close() { // fine to loop through the buckets unlocked // locking happens at the bucket level for b, _ := range p.BucketMap { // MB-33208 defer closing connection pools until the bucket is no longer used bucket := p.BucketMap[b] bucket.Lock() bucket.closed = true bucket.Unlock() } }
go
func (p *Pool) Close() { // fine to loop through the buckets unlocked // locking happens at the bucket level for b, _ := range p.BucketMap { // MB-33208 defer closing connection pools until the bucket is no longer used bucket := p.BucketMap[b] bucket.Lock() bucket.closed = true bucket.Unlock() } }
[ "func", "(", "p", "*", "Pool", ")", "Close", "(", ")", "{", "// fine to loop through the buckets unlocked", "// locking happens at the bucket level", "for", "b", ",", "_", ":=", "range", "p", ".", "BucketMap", "{", "// MB-33208 defer closing connection pools until the bucket is no longer used", "bucket", ":=", "p", ".", "BucketMap", "[", "b", "]", "\n", "bucket", ".", "Lock", "(", ")", "\n", "bucket", ".", "closed", "=", "true", "\n", "bucket", ".", "Unlock", "(", ")", "\n", "}", "\n", "}" ]
// Release bucket connections when the pool is no longer in use
[ "Release", "bucket", "connections", "when", "the", "pool", "is", "no", "longer", "in", "use" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L1427-L1438
146,271
couchbase/go-couchbase
pools.go
GetBucket
func GetBucket(endpoint, poolname, bucketname string) (*Bucket, error) { var err error client, err := Connect(endpoint) if err != nil { return nil, err } pool, err := client.GetPool(poolname) if err != nil { return nil, err } return pool.GetBucket(bucketname) }
go
func GetBucket(endpoint, poolname, bucketname string) (*Bucket, error) { var err error client, err := Connect(endpoint) if err != nil { return nil, err } pool, err := client.GetPool(poolname) if err != nil { return nil, err } return pool.GetBucket(bucketname) }
[ "func", "GetBucket", "(", "endpoint", ",", "poolname", ",", "bucketname", "string", ")", "(", "*", "Bucket", ",", "error", ")", "{", "var", "err", "error", "\n", "client", ",", "err", ":=", "Connect", "(", "endpoint", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "pool", ",", "err", ":=", "client", ".", "GetPool", "(", "poolname", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "pool", ".", "GetBucket", "(", "bucketname", ")", "\n", "}" ]
// GetBucket is a convenience function for getting a named bucket from // a URL
[ "GetBucket", "is", "a", "convenience", "function", "for", "getting", "a", "named", "bucket", "from", "a", "URL" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L1442-L1455
146,272
couchbase/go-couchbase
pools.go
ConnectWithAuthAndGetBucket
func ConnectWithAuthAndGetBucket(endpoint, poolname, bucketname string, ah AuthHandler) (*Bucket, error) { client, err := ConnectWithAuth(endpoint, ah) if err != nil { return nil, err } pool, err := client.GetPool(poolname) if err != nil { return nil, err } return pool.GetBucket(bucketname) }
go
func ConnectWithAuthAndGetBucket(endpoint, poolname, bucketname string, ah AuthHandler) (*Bucket, error) { client, err := ConnectWithAuth(endpoint, ah) if err != nil { return nil, err } pool, err := client.GetPool(poolname) if err != nil { return nil, err } return pool.GetBucket(bucketname) }
[ "func", "ConnectWithAuthAndGetBucket", "(", "endpoint", ",", "poolname", ",", "bucketname", "string", ",", "ah", "AuthHandler", ")", "(", "*", "Bucket", ",", "error", ")", "{", "client", ",", "err", ":=", "ConnectWithAuth", "(", "endpoint", ",", "ah", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "pool", ",", "err", ":=", "client", ".", "GetPool", "(", "poolname", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "pool", ".", "GetBucket", "(", "bucketname", ")", "\n", "}" ]
// ConnectWithAuthAndGetBucket is a convenience function for // getting a named bucket from a given URL and an auth callback
[ "ConnectWithAuthAndGetBucket", "is", "a", "convenience", "function", "for", "getting", "a", "named", "bucket", "from", "a", "given", "URL", "and", "an", "auth", "callback" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/pools.go#L1459-L1472
146,273
couchbase/go-couchbase
observe.go
Get
func (p *OPpool) Get() *ObservePersistJob { var o *ObservePersistJob select { case o = <-p.pool: default: o = &ObservePersistJob{} } return o }
go
func (p *OPpool) Get() *ObservePersistJob { var o *ObservePersistJob select { case o = <-p.pool: default: o = &ObservePersistJob{} } return o }
[ "func", "(", "p", "*", "OPpool", ")", "Get", "(", ")", "*", "ObservePersistJob", "{", "var", "o", "*", "ObservePersistJob", "\n", "select", "{", "case", "o", "=", "<-", "p", ".", "pool", ":", "default", ":", "o", "=", "&", "ObservePersistJob", "{", "}", "\n", "}", "\n", "return", "o", "\n", "}" ]
// Borrow a Client from the pool.
[ "Borrow", "a", "Client", "from", "the", "pool", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/observe.go#L283-L291
146,274
couchbase/go-couchbase
cbdatasource/cbdatasource.go
workerStart
func (d *bucketDataSource) workerStart(server string, workerCh chan []uint16, tlsConfig *tls.Config) { backoffFactor := d.options.DataManagerBackoffFactor if backoffFactor <= 0.0 { backoffFactor = DefaultBucketDataSourceOptions.DataManagerBackoffFactor } sleepInitMS := d.options.DataManagerSleepInitMS if sleepInitMS <= 0 { sleepInitMS = DefaultBucketDataSourceOptions.DataManagerSleepInitMS } sleepMaxMS := d.options.DataManagerSleepMaxMS if sleepMaxMS <= 0 { sleepMaxMS = DefaultBucketDataSourceOptions.DataManagerSleepMaxMS } // Use exponential backoff loop to handle connect retries to the server. go func() { atomic.AddUint64(&d.stats.TotWorkerStart, 1) ExponentialBackoffLoop("cbdatasource.worker-"+server, func() int { return d.worker(server, workerCh, tlsConfig) }, sleepInitMS, backoffFactor, sleepMaxMS) atomic.AddUint64(&d.stats.TotWorkerDone, 1) }() }
go
func (d *bucketDataSource) workerStart(server string, workerCh chan []uint16, tlsConfig *tls.Config) { backoffFactor := d.options.DataManagerBackoffFactor if backoffFactor <= 0.0 { backoffFactor = DefaultBucketDataSourceOptions.DataManagerBackoffFactor } sleepInitMS := d.options.DataManagerSleepInitMS if sleepInitMS <= 0 { sleepInitMS = DefaultBucketDataSourceOptions.DataManagerSleepInitMS } sleepMaxMS := d.options.DataManagerSleepMaxMS if sleepMaxMS <= 0 { sleepMaxMS = DefaultBucketDataSourceOptions.DataManagerSleepMaxMS } // Use exponential backoff loop to handle connect retries to the server. go func() { atomic.AddUint64(&d.stats.TotWorkerStart, 1) ExponentialBackoffLoop("cbdatasource.worker-"+server, func() int { return d.worker(server, workerCh, tlsConfig) }, sleepInitMS, backoffFactor, sleepMaxMS) atomic.AddUint64(&d.stats.TotWorkerDone, 1) }() }
[ "func", "(", "d", "*", "bucketDataSource", ")", "workerStart", "(", "server", "string", ",", "workerCh", "chan", "[", "]", "uint16", ",", "tlsConfig", "*", "tls", ".", "Config", ")", "{", "backoffFactor", ":=", "d", ".", "options", ".", "DataManagerBackoffFactor", "\n", "if", "backoffFactor", "<=", "0.0", "{", "backoffFactor", "=", "DefaultBucketDataSourceOptions", ".", "DataManagerBackoffFactor", "\n", "}", "\n", "sleepInitMS", ":=", "d", ".", "options", ".", "DataManagerSleepInitMS", "\n", "if", "sleepInitMS", "<=", "0", "{", "sleepInitMS", "=", "DefaultBucketDataSourceOptions", ".", "DataManagerSleepInitMS", "\n", "}", "\n", "sleepMaxMS", ":=", "d", ".", "options", ".", "DataManagerSleepMaxMS", "\n", "if", "sleepMaxMS", "<=", "0", "{", "sleepMaxMS", "=", "DefaultBucketDataSourceOptions", ".", "DataManagerSleepMaxMS", "\n", "}", "\n\n", "// Use exponential backoff loop to handle connect retries to the server.", "go", "func", "(", ")", "{", "atomic", ".", "AddUint64", "(", "&", "d", ".", "stats", ".", "TotWorkerStart", ",", "1", ")", "\n\n", "ExponentialBackoffLoop", "(", "\"", "\"", "+", "server", ",", "func", "(", ")", "int", "{", "return", "d", ".", "worker", "(", "server", ",", "workerCh", ",", "tlsConfig", ")", "}", ",", "sleepInitMS", ",", "backoffFactor", ",", "sleepMaxMS", ")", "\n\n", "atomic", ".", "AddUint64", "(", "&", "d", ".", "stats", ".", "TotWorkerDone", ",", "1", ")", "\n", "}", "(", ")", "\n", "}" ]
// A worker connects to one data manager server.
[ "A", "worker", "connects", "to", "one", "data", "manager", "server", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/cbdatasource/cbdatasource.go#L927-L951
146,275
couchbase/go-couchbase
cbdatasource/cbdatasource.go
ConnectBucket
func ConnectBucket(serverURL, poolName, bucketName string, auth couchbase.AuthHandler) (Bucket, error) { var bucket *couchbase.Bucket var err error if auth != nil { bucket, err = couchbase.ConnectWithAuthAndGetBucket(serverURL, poolName, bucketName, auth) } else { bucket, err = couchbase.GetBucket(serverURL, poolName, bucketName) } if err != nil { return nil, err } if bucket == nil { return nil, fmt.Errorf("unknown bucket,"+ " serverURL: %s, bucketName: %s", serverURL, bucketName) } return &bucketWrapper{b: bucket}, nil }
go
func ConnectBucket(serverURL, poolName, bucketName string, auth couchbase.AuthHandler) (Bucket, error) { var bucket *couchbase.Bucket var err error if auth != nil { bucket, err = couchbase.ConnectWithAuthAndGetBucket(serverURL, poolName, bucketName, auth) } else { bucket, err = couchbase.GetBucket(serverURL, poolName, bucketName) } if err != nil { return nil, err } if bucket == nil { return nil, fmt.Errorf("unknown bucket,"+ " serverURL: %s, bucketName: %s", serverURL, bucketName) } return &bucketWrapper{b: bucket}, nil }
[ "func", "ConnectBucket", "(", "serverURL", ",", "poolName", ",", "bucketName", "string", ",", "auth", "couchbase", ".", "AuthHandler", ")", "(", "Bucket", ",", "error", ")", "{", "var", "bucket", "*", "couchbase", ".", "Bucket", "\n", "var", "err", "error", "\n\n", "if", "auth", "!=", "nil", "{", "bucket", ",", "err", "=", "couchbase", ".", "ConnectWithAuthAndGetBucket", "(", "serverURL", ",", "poolName", ",", "bucketName", ",", "auth", ")", "\n", "}", "else", "{", "bucket", ",", "err", "=", "couchbase", ".", "GetBucket", "(", "serverURL", ",", "poolName", ",", "bucketName", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "bucket", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "serverURL", ",", "bucketName", ")", "\n", "}", "\n\n", "return", "&", "bucketWrapper", "{", "b", ":", "bucket", "}", ",", "nil", "\n", "}" ]
// ConnectBucket is the default function used by BucketDataSource // to connect to a Couchbase cluster to retrieve Bucket information. // It is exposed for testability and to allow applications to // override or wrap via BucketDataSourceOptions.
[ "ConnectBucket", "is", "the", "default", "function", "used", "by", "BucketDataSource", "to", "connect", "to", "a", "Couchbase", "cluster", "to", "retrieve", "Bucket", "information", ".", "It", "is", "exposed", "for", "testability", "and", "to", "allow", "applications", "to", "override", "or", "wrap", "via", "BucketDataSourceOptions", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/cbdatasource/cbdatasource.go#L1959-L1978
146,276
couchbase/go-couchbase
cbdatasource/cbdatasource.go
UPROpen
func UPROpen(mc *memcached.Client, name string, option *BucketDataSourceOptions, openFlags uint32) error { rq := &gomemcached.MCRequest{ Opcode: gomemcached.UPR_OPEN, Key: []byte(name), Opaque: 0xf00d1234, Extras: make([]byte, 8), } bufSize := option.FeedBufferSizeBytes noopInterval := option.NoopTimeIntervalSecs binary.BigEndian.PutUint32(rq.Extras[:4], 0) // First 4 bytes are reserved. flags := FlagOpenProducer | openFlags // NOTE: 1 for producer, 0 for consumer. binary.BigEndian.PutUint32(rq.Extras[4:], flags) if err := mc.Transmit(rq); err != nil { return fmt.Errorf("UPROpen transmit, err: %v", err) } res, err := mc.Receive() if err != nil { return fmt.Errorf("UPROpen receive, err: %v", err) } if res.Opcode != gomemcached.UPR_OPEN { return fmt.Errorf("UPROpen unexpected #opcode %v", res.Opcode) } if res.Opaque != rq.Opaque { return fmt.Errorf("UPROpen opaque mismatch, %v over %v", res.Opaque, res.Opaque) } if res.Status != gomemcached.SUCCESS { return fmt.Errorf("UPROpen failed, status: %v, %#v", res.Status, res) } if bufSize > 0 { rq := &gomemcached.MCRequest{ Opcode: gomemcached.UPR_CONTROL, Key: []byte("connection_buffer_size"), Body: []byte(strconv.Itoa(int(bufSize))), } if err = mc.Transmit(rq); err != nil { return fmt.Errorf("UPROpen transmit UPR_CONTROL"+ " (connection_buffer_size), err: %v", err) } } if noopInterval > 0 { rq := &gomemcached.MCRequest{ Opcode: gomemcached.UPR_CONTROL, Key: []byte("enable_noop"), Body: []byte("true"), } if err = mc.Transmit(rq); err != nil { return fmt.Errorf("UPROpen transmit UPR_CONTROL"+ " (enable_noop), err: %v", err) } rq = &gomemcached.MCRequest{ Opcode: gomemcached.UPR_CONTROL, Key: []byte("set_noop_interval"), Body: []byte(strconv.Itoa(int(noopInterval))), } if err = mc.Transmit(rq); err != nil { return fmt.Errorf("UPROpen transmit UPR_CONTROL"+ " (set_noop_interval), err: %v", err) } } return nil }
go
func UPROpen(mc *memcached.Client, name string, option *BucketDataSourceOptions, openFlags uint32) error { rq := &gomemcached.MCRequest{ Opcode: gomemcached.UPR_OPEN, Key: []byte(name), Opaque: 0xf00d1234, Extras: make([]byte, 8), } bufSize := option.FeedBufferSizeBytes noopInterval := option.NoopTimeIntervalSecs binary.BigEndian.PutUint32(rq.Extras[:4], 0) // First 4 bytes are reserved. flags := FlagOpenProducer | openFlags // NOTE: 1 for producer, 0 for consumer. binary.BigEndian.PutUint32(rq.Extras[4:], flags) if err := mc.Transmit(rq); err != nil { return fmt.Errorf("UPROpen transmit, err: %v", err) } res, err := mc.Receive() if err != nil { return fmt.Errorf("UPROpen receive, err: %v", err) } if res.Opcode != gomemcached.UPR_OPEN { return fmt.Errorf("UPROpen unexpected #opcode %v", res.Opcode) } if res.Opaque != rq.Opaque { return fmt.Errorf("UPROpen opaque mismatch, %v over %v", res.Opaque, res.Opaque) } if res.Status != gomemcached.SUCCESS { return fmt.Errorf("UPROpen failed, status: %v, %#v", res.Status, res) } if bufSize > 0 { rq := &gomemcached.MCRequest{ Opcode: gomemcached.UPR_CONTROL, Key: []byte("connection_buffer_size"), Body: []byte(strconv.Itoa(int(bufSize))), } if err = mc.Transmit(rq); err != nil { return fmt.Errorf("UPROpen transmit UPR_CONTROL"+ " (connection_buffer_size), err: %v", err) } } if noopInterval > 0 { rq := &gomemcached.MCRequest{ Opcode: gomemcached.UPR_CONTROL, Key: []byte("enable_noop"), Body: []byte("true"), } if err = mc.Transmit(rq); err != nil { return fmt.Errorf("UPROpen transmit UPR_CONTROL"+ " (enable_noop), err: %v", err) } rq = &gomemcached.MCRequest{ Opcode: gomemcached.UPR_CONTROL, Key: []byte("set_noop_interval"), Body: []byte(strconv.Itoa(int(noopInterval))), } if err = mc.Transmit(rq); err != nil { return fmt.Errorf("UPROpen transmit UPR_CONTROL"+ " (set_noop_interval), err: %v", err) } } return nil }
[ "func", "UPROpen", "(", "mc", "*", "memcached", ".", "Client", ",", "name", "string", ",", "option", "*", "BucketDataSourceOptions", ",", "openFlags", "uint32", ")", "error", "{", "rq", ":=", "&", "gomemcached", ".", "MCRequest", "{", "Opcode", ":", "gomemcached", ".", "UPR_OPEN", ",", "Key", ":", "[", "]", "byte", "(", "name", ")", ",", "Opaque", ":", "0xf00d1234", ",", "Extras", ":", "make", "(", "[", "]", "byte", ",", "8", ")", ",", "}", "\n", "bufSize", ":=", "option", ".", "FeedBufferSizeBytes", "\n", "noopInterval", ":=", "option", ".", "NoopTimeIntervalSecs", "\n\n", "binary", ".", "BigEndian", ".", "PutUint32", "(", "rq", ".", "Extras", "[", ":", "4", "]", ",", "0", ")", "// First 4 bytes are reserved.", "\n", "flags", ":=", "FlagOpenProducer", "|", "openFlags", "// NOTE: 1 for producer, 0 for consumer.", "\n", "binary", ".", "BigEndian", ".", "PutUint32", "(", "rq", ".", "Extras", "[", "4", ":", "]", ",", "flags", ")", "\n\n", "if", "err", ":=", "mc", ".", "Transmit", "(", "rq", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "res", ",", "err", ":=", "mc", ".", "Receive", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "res", ".", "Opcode", "!=", "gomemcached", ".", "UPR_OPEN", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "res", ".", "Opcode", ")", "\n", "}", "\n", "if", "res", ".", "Opaque", "!=", "rq", ".", "Opaque", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "res", ".", "Opaque", ",", "res", ".", "Opaque", ")", "\n", "}", "\n", "if", "res", ".", "Status", "!=", "gomemcached", ".", "SUCCESS", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "res", ".", "Status", ",", "res", ")", "\n", "}", "\n\n", "if", "bufSize", ">", "0", "{", "rq", ":=", "&", "gomemcached", ".", "MCRequest", "{", "Opcode", ":", "gomemcached", ".", "UPR_CONTROL", ",", "Key", ":", "[", "]", "byte", "(", "\"", "\"", ")", ",", "Body", ":", "[", "]", "byte", "(", "strconv", ".", "Itoa", "(", "int", "(", "bufSize", ")", ")", ")", ",", "}", "\n", "if", "err", "=", "mc", ".", "Transmit", "(", "rq", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "if", "noopInterval", ">", "0", "{", "rq", ":=", "&", "gomemcached", ".", "MCRequest", "{", "Opcode", ":", "gomemcached", ".", "UPR_CONTROL", ",", "Key", ":", "[", "]", "byte", "(", "\"", "\"", ")", ",", "Body", ":", "[", "]", "byte", "(", "\"", "\"", ")", ",", "}", "\n", "if", "err", "=", "mc", ".", "Transmit", "(", "rq", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "rq", "=", "&", "gomemcached", ".", "MCRequest", "{", "Opcode", ":", "gomemcached", ".", "UPR_CONTROL", ",", "Key", ":", "[", "]", "byte", "(", "\"", "\"", ")", ",", "Body", ":", "[", "]", "byte", "(", "strconv", ".", "Itoa", "(", "int", "(", "noopInterval", ")", ")", ")", ",", "}", "\n", "if", "err", "=", "mc", ".", "Transmit", "(", "rq", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// UPROpen starts a UPR_OPEN stream on a memcached client connection. // It is exposed for testability.
[ "UPROpen", "starts", "a", "UPR_OPEN", "stream", "on", "a", "memcached", "client", "connection", ".", "It", "is", "exposed", "for", "testability", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/cbdatasource/cbdatasource.go#L2037-L2105
146,277
couchbase/go-couchbase
upr.go
GetFailoverLogs
func (b *Bucket) GetFailoverLogs(vBuckets []uint16) (FailoverLog, error) { // map vbids to their corresponding hosts vbHostList := make(map[string][]uint16) vbm := b.VBServerMap() if len(vbm.VBucketMap) < len(vBuckets) { return nil, fmt.Errorf("vbmap smaller than vbucket list: %v vs. %v", vbm.VBucketMap, vBuckets) } for _, vb := range vBuckets { masterID := vbm.VBucketMap[vb][0] master := b.getMasterNode(masterID) if master == "" { return nil, fmt.Errorf("No master found for vb %d", vb) } vbList := vbHostList[master] if vbList == nil { vbList = make([]uint16, 0) } vbList = append(vbList, vb) vbHostList[master] = vbList } failoverLogMap := make(FailoverLog) for _, serverConn := range b.getConnPools(false /* not already locked */) { vbList := vbHostList[serverConn.host] if vbList == nil { continue } mc, err := serverConn.Get() if err != nil { logging.Infof("No Free connections for vblist %v", vbList) return nil, fmt.Errorf("No Free connections for host %s", serverConn.host) } // close the connection so that it doesn't get reused for upr data // connection defer mc.Close() failoverlogs, err := mc.UprGetFailoverLog(vbList) if err != nil { return nil, fmt.Errorf("Error getting failover log %s host %s", err.Error(), serverConn.host) } for vb, log := range failoverlogs { failoverLogMap[vb] = *log } } return failoverLogMap, nil }
go
func (b *Bucket) GetFailoverLogs(vBuckets []uint16) (FailoverLog, error) { // map vbids to their corresponding hosts vbHostList := make(map[string][]uint16) vbm := b.VBServerMap() if len(vbm.VBucketMap) < len(vBuckets) { return nil, fmt.Errorf("vbmap smaller than vbucket list: %v vs. %v", vbm.VBucketMap, vBuckets) } for _, vb := range vBuckets { masterID := vbm.VBucketMap[vb][0] master := b.getMasterNode(masterID) if master == "" { return nil, fmt.Errorf("No master found for vb %d", vb) } vbList := vbHostList[master] if vbList == nil { vbList = make([]uint16, 0) } vbList = append(vbList, vb) vbHostList[master] = vbList } failoverLogMap := make(FailoverLog) for _, serverConn := range b.getConnPools(false /* not already locked */) { vbList := vbHostList[serverConn.host] if vbList == nil { continue } mc, err := serverConn.Get() if err != nil { logging.Infof("No Free connections for vblist %v", vbList) return nil, fmt.Errorf("No Free connections for host %s", serverConn.host) } // close the connection so that it doesn't get reused for upr data // connection defer mc.Close() failoverlogs, err := mc.UprGetFailoverLog(vbList) if err != nil { return nil, fmt.Errorf("Error getting failover log %s host %s", err.Error(), serverConn.host) } for vb, log := range failoverlogs { failoverLogMap[vb] = *log } } return failoverLogMap, nil }
[ "func", "(", "b", "*", "Bucket", ")", "GetFailoverLogs", "(", "vBuckets", "[", "]", "uint16", ")", "(", "FailoverLog", ",", "error", ")", "{", "// map vbids to their corresponding hosts", "vbHostList", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "uint16", ")", "\n", "vbm", ":=", "b", ".", "VBServerMap", "(", ")", "\n", "if", "len", "(", "vbm", ".", "VBucketMap", ")", "<", "len", "(", "vBuckets", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "vbm", ".", "VBucketMap", ",", "vBuckets", ")", "\n", "}", "\n\n", "for", "_", ",", "vb", ":=", "range", "vBuckets", "{", "masterID", ":=", "vbm", ".", "VBucketMap", "[", "vb", "]", "[", "0", "]", "\n", "master", ":=", "b", ".", "getMasterNode", "(", "masterID", ")", "\n", "if", "master", "==", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "vb", ")", "\n", "}", "\n\n", "vbList", ":=", "vbHostList", "[", "master", "]", "\n", "if", "vbList", "==", "nil", "{", "vbList", "=", "make", "(", "[", "]", "uint16", ",", "0", ")", "\n", "}", "\n", "vbList", "=", "append", "(", "vbList", ",", "vb", ")", "\n", "vbHostList", "[", "master", "]", "=", "vbList", "\n", "}", "\n\n", "failoverLogMap", ":=", "make", "(", "FailoverLog", ")", "\n", "for", "_", ",", "serverConn", ":=", "range", "b", ".", "getConnPools", "(", "false", "/* not already locked */", ")", "{", "vbList", ":=", "vbHostList", "[", "serverConn", ".", "host", "]", "\n", "if", "vbList", "==", "nil", "{", "continue", "\n", "}", "\n\n", "mc", ",", "err", ":=", "serverConn", ".", "Get", "(", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "Infof", "(", "\"", "\"", ",", "vbList", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "serverConn", ".", "host", ")", "\n\n", "}", "\n", "// close the connection so that it doesn't get reused for upr data", "// connection", "defer", "mc", ".", "Close", "(", ")", "\n", "failoverlogs", ",", "err", ":=", "mc", ".", "UprGetFailoverLog", "(", "vbList", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ",", "serverConn", ".", "host", ")", "\n\n", "}", "\n\n", "for", "vb", ",", "log", ":=", "range", "failoverlogs", "{", "failoverLogMap", "[", "vb", "]", "=", "*", "log", "\n", "}", "\n", "}", "\n\n", "return", "failoverLogMap", ",", "nil", "\n", "}" ]
// GetFailoverLogs, get the failover logs for a set of vbucket ids
[ "GetFailoverLogs", "get", "the", "failover", "logs", "for", "a", "set", "of", "vbucket", "ids" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/upr.go#L48-L104
146,278
couchbase/go-couchbase
upr.go
StartUprFeedWithConfig
func (b *Bucket) StartUprFeedWithConfig(name string, sequence uint32, data_chan_size int, dcp_buffer_size uint32) (*UprFeed, error) { feed := &UprFeed{ bucket: b, output: make(chan *memcached.UprEvent, data_chan_size), quit: make(chan bool), nodeFeeds: make(map[string]*FeedInfo, 0), name: name, sequence: sequence, killSwitch: make(chan bool), dcp_buffer_size: dcp_buffer_size, data_chan_size: data_chan_size, } err := feed.connectToNodes() if err != nil { return nil, fmt.Errorf("Cannot connect to bucket %s", err.Error()) } feed.connected = true go feed.run() feed.C = feed.output return feed, nil }
go
func (b *Bucket) StartUprFeedWithConfig(name string, sequence uint32, data_chan_size int, dcp_buffer_size uint32) (*UprFeed, error) { feed := &UprFeed{ bucket: b, output: make(chan *memcached.UprEvent, data_chan_size), quit: make(chan bool), nodeFeeds: make(map[string]*FeedInfo, 0), name: name, sequence: sequence, killSwitch: make(chan bool), dcp_buffer_size: dcp_buffer_size, data_chan_size: data_chan_size, } err := feed.connectToNodes() if err != nil { return nil, fmt.Errorf("Cannot connect to bucket %s", err.Error()) } feed.connected = true go feed.run() feed.C = feed.output return feed, nil }
[ "func", "(", "b", "*", "Bucket", ")", "StartUprFeedWithConfig", "(", "name", "string", ",", "sequence", "uint32", ",", "data_chan_size", "int", ",", "dcp_buffer_size", "uint32", ")", "(", "*", "UprFeed", ",", "error", ")", "{", "feed", ":=", "&", "UprFeed", "{", "bucket", ":", "b", ",", "output", ":", "make", "(", "chan", "*", "memcached", ".", "UprEvent", ",", "data_chan_size", ")", ",", "quit", ":", "make", "(", "chan", "bool", ")", ",", "nodeFeeds", ":", "make", "(", "map", "[", "string", "]", "*", "FeedInfo", ",", "0", ")", ",", "name", ":", "name", ",", "sequence", ":", "sequence", ",", "killSwitch", ":", "make", "(", "chan", "bool", ")", ",", "dcp_buffer_size", ":", "dcp_buffer_size", ",", "data_chan_size", ":", "data_chan_size", ",", "}", "\n\n", "err", ":=", "feed", ".", "connectToNodes", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "feed", ".", "connected", "=", "true", "\n", "go", "feed", ".", "run", "(", ")", "\n\n", "feed", ".", "C", "=", "feed", ".", "output", "\n", "return", "feed", ",", "nil", "\n", "}" ]
// StartUprFeed creates and starts a new Upr feed // No data will be sent on the channel unless vbuckets streams are requested
[ "StartUprFeed", "creates", "and", "starts", "a", "new", "Upr", "feed", "No", "data", "will", "be", "sent", "on", "the", "channel", "unless", "vbuckets", "streams", "are", "requested" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/upr.go#L112-L135
146,279
couchbase/go-couchbase
upr.go
UprRequestStream
func (feed *UprFeed) UprRequestStream(vb uint16, opaque uint16, flags uint32, vuuid, startSequence, endSequence, snapStart, snapEnd uint64) error { defer func() { if r := recover(); r != nil { log.Panicf("Panic in UprRequestStream. Feed %v Bucket %v", feed, feed.bucket) } }() vbm := feed.bucket.VBServerMap() if len(vbm.VBucketMap) < int(vb) { return fmt.Errorf("vbmap smaller than vbucket list: %v vs. %v", vb, vbm.VBucketMap) } if int(vb) >= len(vbm.VBucketMap) { return fmt.Errorf("Invalid vbucket id %d", vb) } masterID := vbm.VBucketMap[vb][0] master := feed.bucket.getMasterNode(masterID) if master == "" { return fmt.Errorf("Master node not found for vbucket %d", vb) } singleFeed := feed.nodeFeeds[master] if singleFeed == nil { return fmt.Errorf("UprFeed for this host not found") } if err := singleFeed.uprFeed.UprRequestStream(vb, opaque, flags, vuuid, startSequence, endSequence, snapStart, snapEnd); err != nil { return err } return nil }
go
func (feed *UprFeed) UprRequestStream(vb uint16, opaque uint16, flags uint32, vuuid, startSequence, endSequence, snapStart, snapEnd uint64) error { defer func() { if r := recover(); r != nil { log.Panicf("Panic in UprRequestStream. Feed %v Bucket %v", feed, feed.bucket) } }() vbm := feed.bucket.VBServerMap() if len(vbm.VBucketMap) < int(vb) { return fmt.Errorf("vbmap smaller than vbucket list: %v vs. %v", vb, vbm.VBucketMap) } if int(vb) >= len(vbm.VBucketMap) { return fmt.Errorf("Invalid vbucket id %d", vb) } masterID := vbm.VBucketMap[vb][0] master := feed.bucket.getMasterNode(masterID) if master == "" { return fmt.Errorf("Master node not found for vbucket %d", vb) } singleFeed := feed.nodeFeeds[master] if singleFeed == nil { return fmt.Errorf("UprFeed for this host not found") } if err := singleFeed.uprFeed.UprRequestStream(vb, opaque, flags, vuuid, startSequence, endSequence, snapStart, snapEnd); err != nil { return err } return nil }
[ "func", "(", "feed", "*", "UprFeed", ")", "UprRequestStream", "(", "vb", "uint16", ",", "opaque", "uint16", ",", "flags", "uint32", ",", "vuuid", ",", "startSequence", ",", "endSequence", ",", "snapStart", ",", "snapEnd", "uint64", ")", "error", "{", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "log", ".", "Panicf", "(", "\"", "\"", ",", "feed", ",", "feed", ".", "bucket", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "vbm", ":=", "feed", ".", "bucket", ".", "VBServerMap", "(", ")", "\n", "if", "len", "(", "vbm", ".", "VBucketMap", ")", "<", "int", "(", "vb", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "vb", ",", "vbm", ".", "VBucketMap", ")", "\n", "}", "\n\n", "if", "int", "(", "vb", ")", ">=", "len", "(", "vbm", ".", "VBucketMap", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "vb", ")", "\n", "}", "\n\n", "masterID", ":=", "vbm", ".", "VBucketMap", "[", "vb", "]", "[", "0", "]", "\n", "master", ":=", "feed", ".", "bucket", ".", "getMasterNode", "(", "masterID", ")", "\n", "if", "master", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "vb", ")", "\n", "}", "\n", "singleFeed", ":=", "feed", ".", "nodeFeeds", "[", "master", "]", "\n", "if", "singleFeed", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "err", ":=", "singleFeed", ".", "uprFeed", ".", "UprRequestStream", "(", "vb", ",", "opaque", ",", "flags", ",", "vuuid", ",", "startSequence", ",", "endSequence", ",", "snapStart", ",", "snapEnd", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// UprRequestStream starts a stream for a vb on a feed
[ "UprRequestStream", "starts", "a", "stream", "for", "a", "vb", "on", "a", "feed" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/upr.go#L138-L173
146,280
couchbase/go-couchbase
upr.go
UprCloseStream
func (feed *UprFeed) UprCloseStream(vb, opaqueMSB uint16) error { defer func() { if r := recover(); r != nil { log.Panicf("Panic in UprCloseStream. Feed %v Bucket %v ", feed, feed.bucket) } }() vbm := feed.bucket.VBServerMap() if len(vbm.VBucketMap) < int(vb) { return fmt.Errorf("vbmap smaller than vbucket list: %v vs. %v", vb, vbm.VBucketMap) } if int(vb) >= len(vbm.VBucketMap) { return fmt.Errorf("Invalid vbucket id %d", vb) } masterID := vbm.VBucketMap[vb][0] master := feed.bucket.getMasterNode(masterID) if master == "" { return fmt.Errorf("Master node not found for vbucket %d", vb) } singleFeed := feed.nodeFeeds[master] if singleFeed == nil { return fmt.Errorf("UprFeed for this host not found") } if err := singleFeed.uprFeed.CloseStream(vb, opaqueMSB); err != nil { return err } return nil }
go
func (feed *UprFeed) UprCloseStream(vb, opaqueMSB uint16) error { defer func() { if r := recover(); r != nil { log.Panicf("Panic in UprCloseStream. Feed %v Bucket %v ", feed, feed.bucket) } }() vbm := feed.bucket.VBServerMap() if len(vbm.VBucketMap) < int(vb) { return fmt.Errorf("vbmap smaller than vbucket list: %v vs. %v", vb, vbm.VBucketMap) } if int(vb) >= len(vbm.VBucketMap) { return fmt.Errorf("Invalid vbucket id %d", vb) } masterID := vbm.VBucketMap[vb][0] master := feed.bucket.getMasterNode(masterID) if master == "" { return fmt.Errorf("Master node not found for vbucket %d", vb) } singleFeed := feed.nodeFeeds[master] if singleFeed == nil { return fmt.Errorf("UprFeed for this host not found") } if err := singleFeed.uprFeed.CloseStream(vb, opaqueMSB); err != nil { return err } return nil }
[ "func", "(", "feed", "*", "UprFeed", ")", "UprCloseStream", "(", "vb", ",", "opaqueMSB", "uint16", ")", "error", "{", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "log", ".", "Panicf", "(", "\"", "\"", ",", "feed", ",", "feed", ".", "bucket", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "vbm", ":=", "feed", ".", "bucket", ".", "VBServerMap", "(", ")", "\n", "if", "len", "(", "vbm", ".", "VBucketMap", ")", "<", "int", "(", "vb", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "vb", ",", "vbm", ".", "VBucketMap", ")", "\n", "}", "\n\n", "if", "int", "(", "vb", ")", ">=", "len", "(", "vbm", ".", "VBucketMap", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "vb", ")", "\n", "}", "\n\n", "masterID", ":=", "vbm", ".", "VBucketMap", "[", "vb", "]", "[", "0", "]", "\n", "master", ":=", "feed", ".", "bucket", ".", "getMasterNode", "(", "masterID", ")", "\n", "if", "master", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "vb", ")", "\n", "}", "\n", "singleFeed", ":=", "feed", ".", "nodeFeeds", "[", "master", "]", "\n", "if", "singleFeed", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "err", ":=", "singleFeed", ".", "uprFeed", ".", "CloseStream", "(", "vb", ",", "opaqueMSB", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// UprCloseStream ends a vbucket stream.
[ "UprCloseStream", "ends", "a", "vbucket", "stream", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/upr.go#L176-L208
146,281
couchbase/go-couchbase
upr.go
forwardUprEvents
func (feed *UprFeed) forwardUprEvents(nodeFeed *FeedInfo, killSwitch chan bool, host string) { singleFeed := nodeFeed.uprFeed defer func() { feed.wg.Done() if r := recover(); r != nil { //if feed is not closing, re-throw the panic if feed.outputClosed != true && feed.closing != true { panic(r) } else { logging.Errorf("Panic is recovered. Since feed is closed, exit gracefully") } } }() for { select { case <-nodeFeed.quit: nodeFeed.connected = false return case event, ok := <-singleFeed.C: if !ok { if singleFeed.Error != nil { logging.Errorf("go-couchbase: Upr feed from %s failed: %v", host, singleFeed.Error) } killSwitch <- true return } if feed.outputClosed == true { // someone closed the node feed logging.Infof("Node need closed, returning from forwardUprEvent") return } feed.output <- event if event.Status == gomemcached.NOT_MY_VBUCKET { logging.Infof(" Got a not my vbucket error !! ") if err := feed.bucket.Refresh(); err != nil { logging.Errorf("Unable to refresh bucket %s ", err.Error()) feed.closeNodeFeeds() return } // this will only connect to nodes that are not connected or changed // user will have to reconnect the stream if err := feed.connectToNodes(); err != nil { logging.Errorf("Unable to connect to nodes %s", err.Error()) return } } } } }
go
func (feed *UprFeed) forwardUprEvents(nodeFeed *FeedInfo, killSwitch chan bool, host string) { singleFeed := nodeFeed.uprFeed defer func() { feed.wg.Done() if r := recover(); r != nil { //if feed is not closing, re-throw the panic if feed.outputClosed != true && feed.closing != true { panic(r) } else { logging.Errorf("Panic is recovered. Since feed is closed, exit gracefully") } } }() for { select { case <-nodeFeed.quit: nodeFeed.connected = false return case event, ok := <-singleFeed.C: if !ok { if singleFeed.Error != nil { logging.Errorf("go-couchbase: Upr feed from %s failed: %v", host, singleFeed.Error) } killSwitch <- true return } if feed.outputClosed == true { // someone closed the node feed logging.Infof("Node need closed, returning from forwardUprEvent") return } feed.output <- event if event.Status == gomemcached.NOT_MY_VBUCKET { logging.Infof(" Got a not my vbucket error !! ") if err := feed.bucket.Refresh(); err != nil { logging.Errorf("Unable to refresh bucket %s ", err.Error()) feed.closeNodeFeeds() return } // this will only connect to nodes that are not connected or changed // user will have to reconnect the stream if err := feed.connectToNodes(); err != nil { logging.Errorf("Unable to connect to nodes %s", err.Error()) return } } } } }
[ "func", "(", "feed", "*", "UprFeed", ")", "forwardUprEvents", "(", "nodeFeed", "*", "FeedInfo", ",", "killSwitch", "chan", "bool", ",", "host", "string", ")", "{", "singleFeed", ":=", "nodeFeed", ".", "uprFeed", "\n\n", "defer", "func", "(", ")", "{", "feed", ".", "wg", ".", "Done", "(", ")", "\n", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "//if feed is not closing, re-throw the panic", "if", "feed", ".", "outputClosed", "!=", "true", "&&", "feed", ".", "closing", "!=", "true", "{", "panic", "(", "r", ")", "\n", "}", "else", "{", "logging", ".", "Errorf", "(", "\"", "\"", ")", "\n\n", "}", "\n", "}", "\n", "}", "(", ")", "\n\n", "for", "{", "select", "{", "case", "<-", "nodeFeed", ".", "quit", ":", "nodeFeed", ".", "connected", "=", "false", "\n", "return", "\n\n", "case", "event", ",", "ok", ":=", "<-", "singleFeed", ".", "C", ":", "if", "!", "ok", "{", "if", "singleFeed", ".", "Error", "!=", "nil", "{", "logging", ".", "Errorf", "(", "\"", "\"", ",", "host", ",", "singleFeed", ".", "Error", ")", "\n", "}", "\n", "killSwitch", "<-", "true", "\n", "return", "\n", "}", "\n", "if", "feed", ".", "outputClosed", "==", "true", "{", "// someone closed the node feed", "logging", ".", "Infof", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "feed", ".", "output", "<-", "event", "\n", "if", "event", ".", "Status", "==", "gomemcached", ".", "NOT_MY_VBUCKET", "{", "logging", ".", "Infof", "(", "\"", "\"", ")", "\n", "if", "err", ":=", "feed", ".", "bucket", ".", "Refresh", "(", ")", ";", "err", "!=", "nil", "{", "logging", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "feed", ".", "closeNodeFeeds", "(", ")", "\n", "return", "\n", "}", "\n", "// this will only connect to nodes that are not connected or changed", "// user will have to reconnect the stream", "if", "err", ":=", "feed", ".", "connectToNodes", "(", ")", ";", "err", "!=", "nil", "{", "logging", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "return", "\n", "}", "\n\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// Goroutine that forwards Upr events from a single node's feed to the aggregate feed.
[ "Goroutine", "that", "forwards", "Upr", "events", "from", "a", "single", "node", "s", "feed", "to", "the", "aggregate", "feed", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/upr.go#L315-L368
146,282
couchbase/go-couchbase
upr.go
Close
func (feed *UprFeed) Close() error { select { case <-feed.quit: return nil default: } feed.closing = true feed.closeNodeFeeds() close(feed.quit) feed.wg.Wait() if feed.outputClosed == false { feed.outputClosed = true close(feed.output) } return nil }
go
func (feed *UprFeed) Close() error { select { case <-feed.quit: return nil default: } feed.closing = true feed.closeNodeFeeds() close(feed.quit) feed.wg.Wait() if feed.outputClosed == false { feed.outputClosed = true close(feed.output) } return nil }
[ "func", "(", "feed", "*", "UprFeed", ")", "Close", "(", ")", "error", "{", "select", "{", "case", "<-", "feed", ".", "quit", ":", "return", "nil", "\n", "default", ":", "}", "\n\n", "feed", ".", "closing", "=", "true", "\n", "feed", ".", "closeNodeFeeds", "(", ")", "\n", "close", "(", "feed", ".", "quit", ")", "\n\n", "feed", ".", "wg", ".", "Wait", "(", ")", "\n", "if", "feed", ".", "outputClosed", "==", "false", "{", "feed", ".", "outputClosed", "=", "true", "\n", "close", "(", "feed", ".", "output", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Close a Upr feed.
[ "Close", "a", "Upr", "feed", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/upr.go#L380-L398
146,283
couchbase/go-couchbase
client.go
IsRefreshRequired
func IsRefreshRequired(err error) bool { res, ok := err.(*gomemcached.MCResponse) if ok && (res.Status == gomemcached.NO_BUCKET || res.Status == gomemcached.NOT_MY_VBUCKET) { return true } return false }
go
func IsRefreshRequired(err error) bool { res, ok := err.(*gomemcached.MCResponse) if ok && (res.Status == gomemcached.NO_BUCKET || res.Status == gomemcached.NOT_MY_VBUCKET) { return true } return false }
[ "func", "IsRefreshRequired", "(", "err", "error", ")", "bool", "{", "res", ",", "ok", ":=", "err", ".", "(", "*", "gomemcached", ".", "MCResponse", ")", "\n", "if", "ok", "&&", "(", "res", ".", "Status", "==", "gomemcached", ".", "NO_BUCKET", "||", "res", ".", "Status", "==", "gomemcached", ".", "NOT_MY_VBUCKET", ")", "{", "return", "true", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// Return true if error suggests a bucket refresh is required. Required by cbq-engine
[ "Return", "true", "if", "error", "suggests", "a", "bucket", "refresh", "is", "required", ".", "Required", "by", "cbq", "-", "engine" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/client.go#L91-L99
146,284
couchbase/go-couchbase
client.go
Do
func (b *Bucket) Do(k string, f func(mc *memcached.Client, vb uint16) error) (err error) { return b.Do2(k, f, true) }
go
func (b *Bucket) Do(k string, f func(mc *memcached.Client, vb uint16) error) (err error) { return b.Do2(k, f, true) }
[ "func", "(", "b", "*", "Bucket", ")", "Do", "(", "k", "string", ",", "f", "func", "(", "mc", "*", "memcached", ".", "Client", ",", "vb", "uint16", ")", "error", ")", "(", "err", "error", ")", "{", "return", "b", ".", "Do2", "(", "k", ",", "f", ",", "true", ")", "\n", "}" ]
// Do executes a function on a memcached connection to the node owning key "k" // // Note that this automatically handles transient errors by replaying // your function on a "not-my-vbucket" error, so don't assume // your command will only be executed only once.
[ "Do", "executes", "a", "function", "on", "a", "memcached", "connection", "to", "the", "node", "owning", "key", "k", "Note", "that", "this", "automatically", "handles", "transient", "errors", "by", "replaying", "your", "function", "on", "a", "not", "-", "my", "-", "vbucket", "error", "so", "don", "t", "assume", "your", "command", "will", "only", "be", "executed", "only", "once", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/client.go#L109-L111
146,285
couchbase/go-couchbase
client.go
GetStats
func (b *Bucket) GetStats(which string) map[string]map[string]string { rv := map[string]map[string]string{} for server, gs := range b.GatherStats(which) { if len(gs.Stats) > 0 { rv[server] = gs.Stats } } return rv }
go
func (b *Bucket) GetStats(which string) map[string]map[string]string { rv := map[string]map[string]string{} for server, gs := range b.GatherStats(which) { if len(gs.Stats) > 0 { rv[server] = gs.Stats } } return rv }
[ "func", "(", "b", "*", "Bucket", ")", "GetStats", "(", "which", "string", ")", "map", "[", "string", "]", "map", "[", "string", "]", "string", "{", "rv", ":=", "map", "[", "string", "]", "map", "[", "string", "]", "string", "{", "}", "\n", "for", "server", ",", "gs", ":=", "range", "b", ".", "GatherStats", "(", "which", ")", "{", "if", "len", "(", "gs", ".", "Stats", ")", ">", "0", "{", "rv", "[", "server", "]", "=", "gs", ".", "Stats", "\n", "}", "\n", "}", "\n", "return", "rv", "\n", "}" ]
// GetStats gets a set of stats from all servers. // // Returns a map of server ID -> map of stat key to map value.
[ "GetStats", "gets", "a", "set", "of", "stats", "from", "all", "servers", ".", "Returns", "a", "map", "of", "server", "ID", "-", ">", "map", "of", "stat", "key", "to", "map", "value", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/client.go#L206-L214
146,286
couchbase/go-couchbase
client.go
GatherStats
func (b *Bucket) GatherStats(which string) map[string]GatheredStats { vsm := b.VBServerMap() if vsm.ServerList == nil { return nil } // Go grab all the things at once. ch := make(chan GatheredStats, len(vsm.ServerList)) for i, sn := range vsm.ServerList { go getStatsParallel(sn, b, i, which, ch) } // Gather the results rv := map[string]GatheredStats{} for range vsm.ServerList { gs := <-ch rv[gs.Server] = gs } return rv }
go
func (b *Bucket) GatherStats(which string) map[string]GatheredStats { vsm := b.VBServerMap() if vsm.ServerList == nil { return nil } // Go grab all the things at once. ch := make(chan GatheredStats, len(vsm.ServerList)) for i, sn := range vsm.ServerList { go getStatsParallel(sn, b, i, which, ch) } // Gather the results rv := map[string]GatheredStats{} for range vsm.ServerList { gs := <-ch rv[gs.Server] = gs } return rv }
[ "func", "(", "b", "*", "Bucket", ")", "GatherStats", "(", "which", "string", ")", "map", "[", "string", "]", "GatheredStats", "{", "vsm", ":=", "b", ".", "VBServerMap", "(", ")", "\n", "if", "vsm", ".", "ServerList", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "// Go grab all the things at once.", "ch", ":=", "make", "(", "chan", "GatheredStats", ",", "len", "(", "vsm", ".", "ServerList", ")", ")", "\n", "for", "i", ",", "sn", ":=", "range", "vsm", ".", "ServerList", "{", "go", "getStatsParallel", "(", "sn", ",", "b", ",", "i", ",", "which", ",", "ch", ")", "\n", "}", "\n\n", "// Gather the results", "rv", ":=", "map", "[", "string", "]", "GatheredStats", "{", "}", "\n", "for", "range", "vsm", ".", "ServerList", "{", "gs", ":=", "<-", "ch", "\n", "rv", "[", "gs", ".", "Server", "]", "=", "gs", "\n", "}", "\n", "return", "rv", "\n", "}" ]
// GatherStats returns a map of server ID -> GatheredStats from all servers.
[ "GatherStats", "returns", "a", "map", "of", "server", "ID", "-", ">", "GatheredStats", "from", "all", "servers", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/client.go#L217-L236
146,287
couchbase/go-couchbase
client.go
GetCount
func (b *Bucket) GetCount(refresh bool) (count int64, err error) { if refresh { b.Refresh() } var cnt int64 for _, gs := range b.GatherStats("") { if len(gs.Stats) > 0 { cnt, err = strconv.ParseInt(gs.Stats["curr_items"], 10, 64) if err != nil { return 0, err } count += cnt } } return count, nil }
go
func (b *Bucket) GetCount(refresh bool) (count int64, err error) { if refresh { b.Refresh() } var cnt int64 for _, gs := range b.GatherStats("") { if len(gs.Stats) > 0 { cnt, err = strconv.ParseInt(gs.Stats["curr_items"], 10, 64) if err != nil { return 0, err } count += cnt } } return count, nil }
[ "func", "(", "b", "*", "Bucket", ")", "GetCount", "(", "refresh", "bool", ")", "(", "count", "int64", ",", "err", "error", ")", "{", "if", "refresh", "{", "b", ".", "Refresh", "(", ")", "\n", "}", "\n\n", "var", "cnt", "int64", "\n", "for", "_", ",", "gs", ":=", "range", "b", ".", "GatherStats", "(", "\"", "\"", ")", "{", "if", "len", "(", "gs", ".", "Stats", ")", ">", "0", "{", "cnt", ",", "err", "=", "strconv", ".", "ParseInt", "(", "gs", ".", "Stats", "[", "\"", "\"", "]", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "count", "+=", "cnt", "\n", "}", "\n", "}", "\n\n", "return", "count", ",", "nil", "\n", "}" ]
// Get bucket count through the bucket stats
[ "Get", "bucket", "count", "through", "the", "bucket", "stats" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/client.go#L239-L256
146,288
couchbase/go-couchbase
client.go
GetSize
func (b *Bucket) GetSize(refresh bool) (size int64, err error) { if refresh { b.Refresh() } var sz int64 for _, gs := range b.GatherStats("") { if len(gs.Stats) > 0 { sz, err = strconv.ParseInt(gs.Stats["ep_value_size"], 10, 64) if err != nil { return 0, err } size += sz } } return size, nil }
go
func (b *Bucket) GetSize(refresh bool) (size int64, err error) { if refresh { b.Refresh() } var sz int64 for _, gs := range b.GatherStats("") { if len(gs.Stats) > 0 { sz, err = strconv.ParseInt(gs.Stats["ep_value_size"], 10, 64) if err != nil { return 0, err } size += sz } } return size, nil }
[ "func", "(", "b", "*", "Bucket", ")", "GetSize", "(", "refresh", "bool", ")", "(", "size", "int64", ",", "err", "error", ")", "{", "if", "refresh", "{", "b", ".", "Refresh", "(", ")", "\n", "}", "\n\n", "var", "sz", "int64", "\n", "for", "_", ",", "gs", ":=", "range", "b", ".", "GatherStats", "(", "\"", "\"", ")", "{", "if", "len", "(", "gs", ".", "Stats", ")", ">", "0", "{", "sz", ",", "err", "=", "strconv", ".", "ParseInt", "(", "gs", ".", "Stats", "[", "\"", "\"", "]", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "size", "+=", "sz", "\n", "}", "\n", "}", "\n\n", "return", "size", ",", "nil", "\n", "}" ]
// Get bucket document size through the bucket stats
[ "Get", "bucket", "document", "size", "through", "the", "bucket", "stats" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/client.go#L259-L276
146,289
couchbase/go-couchbase
client.go
isConnError
func isConnError(err error) bool { if err == io.EOF { return true } estr := err.Error() return strings.Contains(estr, "broken pipe") || strings.Contains(estr, "connection reset") || strings.Contains(estr, "connection refused") || strings.Contains(estr, "connection pool is closed") }
go
func isConnError(err error) bool { if err == io.EOF { return true } estr := err.Error() return strings.Contains(estr, "broken pipe") || strings.Contains(estr, "connection reset") || strings.Contains(estr, "connection refused") || strings.Contains(estr, "connection pool is closed") }
[ "func", "isConnError", "(", "err", "error", ")", "bool", "{", "if", "err", "==", "io", ".", "EOF", "{", "return", "true", "\n", "}", "\n", "estr", ":=", "err", ".", "Error", "(", ")", "\n", "return", "strings", ".", "Contains", "(", "estr", ",", "\"", "\"", ")", "||", "strings", ".", "Contains", "(", "estr", ",", "\"", "\"", ")", "||", "strings", ".", "Contains", "(", "estr", ",", "\"", "\"", ")", "||", "strings", ".", "Contains", "(", "estr", ",", "\"", "\"", ")", "\n", "}" ]
// Errors that are not considered fatal for our fetch loop
[ "Errors", "that", "are", "not", "considered", "fatal", "for", "our", "fetch", "loop" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/client.go#L297-L306
146,290
couchbase/go-couchbase
client.go
GetBulk
func (b *Bucket) GetBulk(keys []string, reqDeadline time.Time, subPaths []string) (map[string]*gomemcached.MCResponse, error) { return b.getBulk(keys, reqDeadline, subPaths) }
go
func (b *Bucket) GetBulk(keys []string, reqDeadline time.Time, subPaths []string) (map[string]*gomemcached.MCResponse, error) { return b.getBulk(keys, reqDeadline, subPaths) }
[ "func", "(", "b", "*", "Bucket", ")", "GetBulk", "(", "keys", "[", "]", "string", ",", "reqDeadline", "time", ".", "Time", ",", "subPaths", "[", "]", "string", ")", "(", "map", "[", "string", "]", "*", "gomemcached", ".", "MCResponse", ",", "error", ")", "{", "return", "b", ".", "getBulk", "(", "keys", ",", "reqDeadline", ",", "subPaths", ")", "\n", "}" ]
// GetBulk fetches multiple keys concurrently. // // Unlike more convenient GETs, the entire response is returned in the // map array for each key. Keys that were not found will not be included in // the map.
[ "GetBulk", "fetches", "multiple", "keys", "concurrently", ".", "Unlike", "more", "convenient", "GETs", "the", "entire", "response", "is", "returned", "in", "the", "map", "array", "for", "each", "key", ".", "Keys", "that", "were", "not", "found", "will", "not", "be", "included", "in", "the", "map", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/client.go#L635-L637
146,291
couchbase/go-couchbase
client.go
String
func (w WriteOptions) String() string { f := []string{} for _, on := range optNames { if w&on.opt != 0 { f = append(f, on.name) w &= ^on.opt } } if len(f) == 0 || w != 0 { f = append(f, fmt.Sprintf("0x%x", int(w))) } return strings.Join(f, "|") }
go
func (w WriteOptions) String() string { f := []string{} for _, on := range optNames { if w&on.opt != 0 { f = append(f, on.name) w &= ^on.opt } } if len(f) == 0 || w != 0 { f = append(f, fmt.Sprintf("0x%x", int(w))) } return strings.Join(f, "|") }
[ "func", "(", "w", "WriteOptions", ")", "String", "(", ")", "string", "{", "f", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "on", ":=", "range", "optNames", "{", "if", "w", "&", "on", ".", "opt", "!=", "0", "{", "f", "=", "append", "(", "f", ",", "on", ".", "name", ")", "\n", "w", "&=", "^", "on", ".", "opt", "\n", "}", "\n", "}", "\n", "if", "len", "(", "f", ")", "==", "0", "||", "w", "!=", "0", "{", "f", "=", "append", "(", "f", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "int", "(", "w", ")", ")", ")", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "f", ",", "\"", "\"", ")", "\n", "}" ]
// String representation of WriteOptions
[ "String", "representation", "of", "WriteOptions" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/client.go#L716-L728
146,292
couchbase/go-couchbase
client.go
Cas
func (b *Bucket) Cas(k string, exp int, cas uint64, v interface{}) (uint64, error) { return b.WriteCas(k, 0, exp, cas, v, 0) }
go
func (b *Bucket) Cas(k string, exp int, cas uint64, v interface{}) (uint64, error) { return b.WriteCas(k, 0, exp, cas, v, 0) }
[ "func", "(", "b", "*", "Bucket", ")", "Cas", "(", "k", "string", ",", "exp", "int", ",", "cas", "uint64", ",", "v", "interface", "{", "}", ")", "(", "uint64", ",", "error", ")", "{", "return", "b", ".", "WriteCas", "(", "k", ",", "0", ",", "exp", ",", "cas", ",", "v", ",", "0", ")", "\n", "}" ]
// Set a value in this bucket with Cas and return the new Cas value
[ "Set", "a", "value", "in", "this", "bucket", "with", "Cas", "and", "return", "the", "new", "Cas", "value" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/client.go#L846-L848
146,293
couchbase/go-couchbase
client.go
CasRaw
func (b *Bucket) CasRaw(k string, exp int, cas uint64, v interface{}) (uint64, error) { return b.WriteCas(k, 0, exp, cas, v, Raw) }
go
func (b *Bucket) CasRaw(k string, exp int, cas uint64, v interface{}) (uint64, error) { return b.WriteCas(k, 0, exp, cas, v, Raw) }
[ "func", "(", "b", "*", "Bucket", ")", "CasRaw", "(", "k", "string", ",", "exp", "int", ",", "cas", "uint64", ",", "v", "interface", "{", "}", ")", "(", "uint64", ",", "error", ")", "{", "return", "b", ".", "WriteCas", "(", "k", ",", "0", ",", "exp", ",", "cas", ",", "v", ",", "Raw", ")", "\n", "}" ]
// Set a value in this bucket with Cas without json encoding it
[ "Set", "a", "value", "in", "this", "bucket", "with", "Cas", "without", "json", "encoding", "it" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/client.go#L851-L853
146,294
couchbase/go-couchbase
client.go
CasWithMeta
func (b *Bucket) CasWithMeta(k string, flags int, exp int, cas uint64, v interface{}) (uint64, *MutationToken, error) { return b.WriteCasWithMT(k, flags, exp, cas, v, 0) }
go
func (b *Bucket) CasWithMeta(k string, flags int, exp int, cas uint64, v interface{}) (uint64, *MutationToken, error) { return b.WriteCasWithMT(k, flags, exp, cas, v, 0) }
[ "func", "(", "b", "*", "Bucket", ")", "CasWithMeta", "(", "k", "string", ",", "flags", "int", ",", "exp", "int", ",", "cas", "uint64", ",", "v", "interface", "{", "}", ")", "(", "uint64", ",", "*", "MutationToken", ",", "error", ")", "{", "return", "b", ".", "WriteCasWithMT", "(", "k", ",", "flags", ",", "exp", ",", "cas", ",", "v", ",", "0", ")", "\n", "}" ]
// Extended CAS operation. These functions will return the mutation token, i.e vbuuid & guard
[ "Extended", "CAS", "operation", ".", "These", "functions", "will", "return", "the", "mutation", "token", "i", ".", "e", "vbuuid", "&", "guard" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/client.go#L888-L890
146,295
couchbase/go-couchbase
client.go
Set
func (b *Bucket) Set(k string, exp int, v interface{}) error { return b.Write(k, 0, exp, v, 0) }
go
func (b *Bucket) Set(k string, exp int, v interface{}) error { return b.Write(k, 0, exp, v, 0) }
[ "func", "(", "b", "*", "Bucket", ")", "Set", "(", "k", "string", ",", "exp", "int", ",", "v", "interface", "{", "}", ")", "error", "{", "return", "b", ".", "Write", "(", "k", ",", "0", ",", "exp", ",", "v", ",", "0", ")", "\n", "}" ]
// Set a value in this bucket. // The value will be serialized into a JSON document.
[ "Set", "a", "value", "in", "this", "bucket", ".", "The", "value", "will", "be", "serialized", "into", "a", "JSON", "document", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/client.go#L942-L944
146,296
couchbase/go-couchbase
client.go
SetWithMeta
func (b *Bucket) SetWithMeta(k string, flags int, exp int, v interface{}) (*MutationToken, error) { return b.WriteWithMT(k, flags, exp, v, 0) }
go
func (b *Bucket) SetWithMeta(k string, flags int, exp int, v interface{}) (*MutationToken, error) { return b.WriteWithMT(k, flags, exp, v, 0) }
[ "func", "(", "b", "*", "Bucket", ")", "SetWithMeta", "(", "k", "string", ",", "flags", "int", ",", "exp", "int", ",", "v", "interface", "{", "}", ")", "(", "*", "MutationToken", ",", "error", ")", "{", "return", "b", ".", "WriteWithMT", "(", "k", ",", "flags", ",", "exp", ",", "v", ",", "0", ")", "\n", "}" ]
// Set a value in this bucket with with flags
[ "Set", "a", "value", "in", "this", "bucket", "with", "with", "flags" ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/client.go#L947-L949
146,297
couchbase/go-couchbase
client.go
SetRaw
func (b *Bucket) SetRaw(k string, exp int, v []byte) error { return b.Write(k, 0, exp, v, Raw) }
go
func (b *Bucket) SetRaw(k string, exp int, v []byte) error { return b.Write(k, 0, exp, v, Raw) }
[ "func", "(", "b", "*", "Bucket", ")", "SetRaw", "(", "k", "string", ",", "exp", "int", ",", "v", "[", "]", "byte", ")", "error", "{", "return", "b", ".", "Write", "(", "k", ",", "0", ",", "exp", ",", "v", ",", "Raw", ")", "\n", "}" ]
// SetRaw sets a value in this bucket without JSON encoding it.
[ "SetRaw", "sets", "a", "value", "in", "this", "bucket", "without", "JSON", "encoding", "it", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/client.go#L952-L954
146,298
couchbase/go-couchbase
client.go
Append
func (b *Bucket) Append(k string, data []byte) error { return b.Write(k, 0, 0, data, Append|Raw) }
go
func (b *Bucket) Append(k string, data []byte) error { return b.Write(k, 0, 0, data, Append|Raw) }
[ "func", "(", "b", "*", "Bucket", ")", "Append", "(", "k", "string", ",", "data", "[", "]", "byte", ")", "error", "{", "return", "b", ".", "Write", "(", "k", ",", "0", ",", "0", ",", "data", ",", "Append", "|", "Raw", ")", "\n", "}" ]
// Append appends raw data to an existing item.
[ "Append", "appends", "raw", "data", "to", "an", "existing", "item", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/client.go#L999-L1001
146,299
couchbase/go-couchbase
client.go
GetCollectionCID
func (b *Bucket) GetCollectionCID(scope string, collection string, reqDeadline time.Time) (uint32, uint32, error) { var err error var response *gomemcached.MCResponse if ClientOpCallback != nil { defer func(t time.Time) { ClientOpCallback("GetCollectionCID", scope+"."+collection, t, err) }(time.Now()) } var key = "DUMMY" // Contact any server. var manifestUid uint32 var collUid uint32 err = b.Do2(key, func(mc *memcached.Client, vb uint16) error { var err1 error mc.SetDeadline(getDeadline(reqDeadline, DefaultTimeout)) _, err1 = mc.SelectBucket(b.Name) if err1 != nil { mc.SetDeadline(noDeadline) return err1 } response, err1 = mc.CollectionsGetCID(scope, collection) if err1 != nil { mc.SetDeadline(noDeadline) return err1 } manifestUid = binary.BigEndian.Uint32(response.Extras[4:8]) collUid = binary.BigEndian.Uint32(response.Extras[8:12]) return nil }, false) return collUid, manifestUid, err }
go
func (b *Bucket) GetCollectionCID(scope string, collection string, reqDeadline time.Time) (uint32, uint32, error) { var err error var response *gomemcached.MCResponse if ClientOpCallback != nil { defer func(t time.Time) { ClientOpCallback("GetCollectionCID", scope+"."+collection, t, err) }(time.Now()) } var key = "DUMMY" // Contact any server. var manifestUid uint32 var collUid uint32 err = b.Do2(key, func(mc *memcached.Client, vb uint16) error { var err1 error mc.SetDeadline(getDeadline(reqDeadline, DefaultTimeout)) _, err1 = mc.SelectBucket(b.Name) if err1 != nil { mc.SetDeadline(noDeadline) return err1 } response, err1 = mc.CollectionsGetCID(scope, collection) if err1 != nil { mc.SetDeadline(noDeadline) return err1 } manifestUid = binary.BigEndian.Uint32(response.Extras[4:8]) collUid = binary.BigEndian.Uint32(response.Extras[8:12]) return nil }, false) return collUid, manifestUid, err }
[ "func", "(", "b", "*", "Bucket", ")", "GetCollectionCID", "(", "scope", "string", ",", "collection", "string", ",", "reqDeadline", "time", ".", "Time", ")", "(", "uint32", ",", "uint32", ",", "error", ")", "{", "var", "err", "error", "\n", "var", "response", "*", "gomemcached", ".", "MCResponse", "\n\n", "if", "ClientOpCallback", "!=", "nil", "{", "defer", "func", "(", "t", "time", ".", "Time", ")", "{", "ClientOpCallback", "(", "\"", "\"", ",", "scope", "+", "\"", "\"", "+", "collection", ",", "t", ",", "err", ")", "}", "(", "time", ".", "Now", "(", ")", ")", "\n", "}", "\n\n", "var", "key", "=", "\"", "\"", "// Contact any server.", "\n", "var", "manifestUid", "uint32", "\n", "var", "collUid", "uint32", "\n", "err", "=", "b", ".", "Do2", "(", "key", ",", "func", "(", "mc", "*", "memcached", ".", "Client", ",", "vb", "uint16", ")", "error", "{", "var", "err1", "error", "\n\n", "mc", ".", "SetDeadline", "(", "getDeadline", "(", "reqDeadline", ",", "DefaultTimeout", ")", ")", "\n", "_", ",", "err1", "=", "mc", ".", "SelectBucket", "(", "b", ".", "Name", ")", "\n", "if", "err1", "!=", "nil", "{", "mc", ".", "SetDeadline", "(", "noDeadline", ")", "\n", "return", "err1", "\n", "}", "\n\n", "response", ",", "err1", "=", "mc", ".", "CollectionsGetCID", "(", "scope", ",", "collection", ")", "\n", "if", "err1", "!=", "nil", "{", "mc", ".", "SetDeadline", "(", "noDeadline", ")", "\n", "return", "err1", "\n", "}", "\n\n", "manifestUid", "=", "binary", ".", "BigEndian", ".", "Uint32", "(", "response", ".", "Extras", "[", "4", ":", "8", "]", ")", "\n", "collUid", "=", "binary", ".", "BigEndian", ".", "Uint32", "(", "response", ".", "Extras", "[", "8", ":", "12", "]", ")", "\n\n", "return", "nil", "\n", "}", ",", "false", ")", "\n\n", "return", "collUid", ",", "manifestUid", ",", "err", "\n", "}" ]
// Returns collectionUid, manifestUid, error.
[ "Returns", "collectionUid", "manifestUid", "error", "." ]
6aeabeae85e5645306382779e3ee55a330ec558c
https://github.com/couchbase/go-couchbase/blob/6aeabeae85e5645306382779e3ee55a330ec558c/client.go#L1039-L1073