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
15,200
zsais/go-gin-prometheus
middleware.go
SetListenAddress
func (p *Prometheus) SetListenAddress(address string) { p.listenAddress = address if p.listenAddress != "" { p.router = gin.Default() } }
go
func (p *Prometheus) SetListenAddress(address string) { p.listenAddress = address if p.listenAddress != "" { p.router = gin.Default() } }
[ "func", "(", "p", "*", "Prometheus", ")", "SetListenAddress", "(", "address", "string", ")", "{", "p", ".", "listenAddress", "=", "address", "\n", "if", "p", ".", "listenAddress", "!=", "\"", "\"", "{", "p", ".", "router", "=", "gin", ".", "Default", "(", ")", "\n", "}", "\n", "}" ]
// SetListenAddress for exposing metrics on address. If not set, it will be exposed at the // same address of the gin engine that is being used
[ "SetListenAddress", "for", "exposing", "metrics", "on", "address", ".", "If", "not", "set", "it", "will", "be", "exposed", "at", "the", "same", "address", "of", "the", "gin", "engine", "that", "is", "being", "used" ]
58963fb32f547bd98cc0150a6bcbdf181a430967
https://github.com/zsais/go-gin-prometheus/blob/58963fb32f547bd98cc0150a6bcbdf181a430967/middleware.go#L165-L170
15,201
zsais/go-gin-prometheus
middleware.go
SetMetricsPath
func (p *Prometheus) SetMetricsPath(e *gin.Engine) { if p.listenAddress != "" { p.router.GET(p.MetricsPath, prometheusHandler()) p.runServer() } else { e.GET(p.MetricsPath, prometheusHandler()) } }
go
func (p *Prometheus) SetMetricsPath(e *gin.Engine) { if p.listenAddress != "" { p.router.GET(p.MetricsPath, prometheusHandler()) p.runServer() } else { e.GET(p.MetricsPath, prometheusHandler()) } }
[ "func", "(", "p", "*", "Prometheus", ")", "SetMetricsPath", "(", "e", "*", "gin", ".", "Engine", ")", "{", "if", "p", ".", "listenAddress", "!=", "\"", "\"", "{", "p", ".", "router", ".", "GET", "(", "p", ".", "MetricsPath", ",", "prometheusHandler", "(", ")", ")", "\n", "p", ".", "runServer", "(", ")", "\n", "}", "else", "{", "e", ".", "GET", "(", "p", ".", "MetricsPath", ",", "prometheusHandler", "(", ")", ")", "\n", "}", "\n", "}" ]
// SetMetricsPath set metrics paths
[ "SetMetricsPath", "set", "metrics", "paths" ]
58963fb32f547bd98cc0150a6bcbdf181a430967
https://github.com/zsais/go-gin-prometheus/blob/58963fb32f547bd98cc0150a6bcbdf181a430967/middleware.go#L182-L190
15,202
zsais/go-gin-prometheus
middleware.go
SetMetricsPathWithAuth
func (p *Prometheus) SetMetricsPathWithAuth(e *gin.Engine, accounts gin.Accounts) { if p.listenAddress != "" { p.router.GET(p.MetricsPath, gin.BasicAuth(accounts), prometheusHandler()) p.runServer() } else { e.GET(p.MetricsPath, gin.BasicAuth(accounts), prometheusHandler()) } }
go
func (p *Prometheus) SetMetricsPathWithAuth(e *gin.Engine, accounts gin.Accounts) { if p.listenAddress != "" { p.router.GET(p.MetricsPath, gin.BasicAuth(accounts), prometheusHandler()) p.runServer() } else { e.GET(p.MetricsPath, gin.BasicAuth(accounts), prometheusHandler()) } }
[ "func", "(", "p", "*", "Prometheus", ")", "SetMetricsPathWithAuth", "(", "e", "*", "gin", ".", "Engine", ",", "accounts", "gin", ".", "Accounts", ")", "{", "if", "p", ".", "listenAddress", "!=", "\"", "\"", "{", "p", ".", "router", ".", "GET", "(", "p", ".", "MetricsPath", ",", "gin", ".", "BasicAuth", "(", "accounts", ")", ",", "prometheusHandler", "(", ")", ")", "\n", "p", ".", "runServer", "(", ")", "\n", "}", "else", "{", "e", ".", "GET", "(", "p", ".", "MetricsPath", ",", "gin", ".", "BasicAuth", "(", "accounts", ")", ",", "prometheusHandler", "(", ")", ")", "\n", "}", "\n\n", "}" ]
// SetMetricsPathWithAuth set metrics paths with authentication
[ "SetMetricsPathWithAuth", "set", "metrics", "paths", "with", "authentication" ]
58963fb32f547bd98cc0150a6bcbdf181a430967
https://github.com/zsais/go-gin-prometheus/blob/58963fb32f547bd98cc0150a6bcbdf181a430967/middleware.go#L193-L202
15,203
zsais/go-gin-prometheus
middleware.go
NewMetric
func NewMetric(m *Metric, subsystem string) prometheus.Collector { var metric prometheus.Collector switch m.Type { case "counter_vec": metric = prometheus.NewCounterVec( prometheus.CounterOpts{ Subsystem: subsystem, Name: m.Name, Help: m.Description, }, m.Args, ) case "counter": metric = prometheus.NewCounter( prometheus.CounterOpts{ Subsystem: subsystem, Name: m.Name, Help: m.Description, }, ) case "gauge_vec": metric = prometheus.NewGaugeVec( prometheus.GaugeOpts{ Subsystem: subsystem, Name: m.Name, Help: m.Description, }, m.Args, ) case "gauge": metric = prometheus.NewGauge( prometheus.GaugeOpts{ Subsystem: subsystem, Name: m.Name, Help: m.Description, }, ) case "histogram_vec": metric = prometheus.NewHistogramVec( prometheus.HistogramOpts{ Subsystem: subsystem, Name: m.Name, Help: m.Description, }, m.Args, ) case "histogram": metric = prometheus.NewHistogram( prometheus.HistogramOpts{ Subsystem: subsystem, Name: m.Name, Help: m.Description, }, ) case "summary_vec": metric = prometheus.NewSummaryVec( prometheus.SummaryOpts{ Subsystem: subsystem, Name: m.Name, Help: m.Description, }, m.Args, ) case "summary": metric = prometheus.NewSummary( prometheus.SummaryOpts{ Subsystem: subsystem, Name: m.Name, Help: m.Description, }, ) } return metric }
go
func NewMetric(m *Metric, subsystem string) prometheus.Collector { var metric prometheus.Collector switch m.Type { case "counter_vec": metric = prometheus.NewCounterVec( prometheus.CounterOpts{ Subsystem: subsystem, Name: m.Name, Help: m.Description, }, m.Args, ) case "counter": metric = prometheus.NewCounter( prometheus.CounterOpts{ Subsystem: subsystem, Name: m.Name, Help: m.Description, }, ) case "gauge_vec": metric = prometheus.NewGaugeVec( prometheus.GaugeOpts{ Subsystem: subsystem, Name: m.Name, Help: m.Description, }, m.Args, ) case "gauge": metric = prometheus.NewGauge( prometheus.GaugeOpts{ Subsystem: subsystem, Name: m.Name, Help: m.Description, }, ) case "histogram_vec": metric = prometheus.NewHistogramVec( prometheus.HistogramOpts{ Subsystem: subsystem, Name: m.Name, Help: m.Description, }, m.Args, ) case "histogram": metric = prometheus.NewHistogram( prometheus.HistogramOpts{ Subsystem: subsystem, Name: m.Name, Help: m.Description, }, ) case "summary_vec": metric = prometheus.NewSummaryVec( prometheus.SummaryOpts{ Subsystem: subsystem, Name: m.Name, Help: m.Description, }, m.Args, ) case "summary": metric = prometheus.NewSummary( prometheus.SummaryOpts{ Subsystem: subsystem, Name: m.Name, Help: m.Description, }, ) } return metric }
[ "func", "NewMetric", "(", "m", "*", "Metric", ",", "subsystem", "string", ")", "prometheus", ".", "Collector", "{", "var", "metric", "prometheus", ".", "Collector", "\n", "switch", "m", ".", "Type", "{", "case", "\"", "\"", ":", "metric", "=", "prometheus", ".", "NewCounterVec", "(", "prometheus", ".", "CounterOpts", "{", "Subsystem", ":", "subsystem", ",", "Name", ":", "m", ".", "Name", ",", "Help", ":", "m", ".", "Description", ",", "}", ",", "m", ".", "Args", ",", ")", "\n", "case", "\"", "\"", ":", "metric", "=", "prometheus", ".", "NewCounter", "(", "prometheus", ".", "CounterOpts", "{", "Subsystem", ":", "subsystem", ",", "Name", ":", "m", ".", "Name", ",", "Help", ":", "m", ".", "Description", ",", "}", ",", ")", "\n", "case", "\"", "\"", ":", "metric", "=", "prometheus", ".", "NewGaugeVec", "(", "prometheus", ".", "GaugeOpts", "{", "Subsystem", ":", "subsystem", ",", "Name", ":", "m", ".", "Name", ",", "Help", ":", "m", ".", "Description", ",", "}", ",", "m", ".", "Args", ",", ")", "\n", "case", "\"", "\"", ":", "metric", "=", "prometheus", ".", "NewGauge", "(", "prometheus", ".", "GaugeOpts", "{", "Subsystem", ":", "subsystem", ",", "Name", ":", "m", ".", "Name", ",", "Help", ":", "m", ".", "Description", ",", "}", ",", ")", "\n", "case", "\"", "\"", ":", "metric", "=", "prometheus", ".", "NewHistogramVec", "(", "prometheus", ".", "HistogramOpts", "{", "Subsystem", ":", "subsystem", ",", "Name", ":", "m", ".", "Name", ",", "Help", ":", "m", ".", "Description", ",", "}", ",", "m", ".", "Args", ",", ")", "\n", "case", "\"", "\"", ":", "metric", "=", "prometheus", ".", "NewHistogram", "(", "prometheus", ".", "HistogramOpts", "{", "Subsystem", ":", "subsystem", ",", "Name", ":", "m", ".", "Name", ",", "Help", ":", "m", ".", "Description", ",", "}", ",", ")", "\n", "case", "\"", "\"", ":", "metric", "=", "prometheus", ".", "NewSummaryVec", "(", "prometheus", ".", "SummaryOpts", "{", "Subsystem", ":", "subsystem", ",", "Name", ":", "m", ".", "Name", ",", "Help", ":", "m", ".", "Description", ",", "}", ",", "m", ".", "Args", ",", ")", "\n", "case", "\"", "\"", ":", "metric", "=", "prometheus", ".", "NewSummary", "(", "prometheus", ".", "SummaryOpts", "{", "Subsystem", ":", "subsystem", ",", "Name", ":", "m", ".", "Name", ",", "Help", ":", "m", ".", "Description", ",", "}", ",", ")", "\n", "}", "\n", "return", "metric", "\n", "}" ]
// NewMetric associates prometheus.Collector based on Metric.Type
[ "NewMetric", "associates", "prometheus", ".", "Collector", "based", "on", "Metric", ".", "Type" ]
58963fb32f547bd98cc0150a6bcbdf181a430967
https://github.com/zsais/go-gin-prometheus/blob/58963fb32f547bd98cc0150a6bcbdf181a430967/middleware.go#L245-L318
15,204
zsais/go-gin-prometheus
middleware.go
Use
func (p *Prometheus) Use(e *gin.Engine) { e.Use(p.HandlerFunc()) p.SetMetricsPath(e) }
go
func (p *Prometheus) Use(e *gin.Engine) { e.Use(p.HandlerFunc()) p.SetMetricsPath(e) }
[ "func", "(", "p", "*", "Prometheus", ")", "Use", "(", "e", "*", "gin", ".", "Engine", ")", "{", "e", ".", "Use", "(", "p", ".", "HandlerFunc", "(", ")", ")", "\n", "p", ".", "SetMetricsPath", "(", "e", ")", "\n", "}" ]
// Use adds the middleware to a gin engine.
[ "Use", "adds", "the", "middleware", "to", "a", "gin", "engine", "." ]
58963fb32f547bd98cc0150a6bcbdf181a430967
https://github.com/zsais/go-gin-prometheus/blob/58963fb32f547bd98cc0150a6bcbdf181a430967/middleware.go#L342-L345
15,205
zsais/go-gin-prometheus
middleware.go
UseWithAuth
func (p *Prometheus) UseWithAuth(e *gin.Engine, accounts gin.Accounts) { e.Use(p.HandlerFunc()) p.SetMetricsPathWithAuth(e, accounts) }
go
func (p *Prometheus) UseWithAuth(e *gin.Engine, accounts gin.Accounts) { e.Use(p.HandlerFunc()) p.SetMetricsPathWithAuth(e, accounts) }
[ "func", "(", "p", "*", "Prometheus", ")", "UseWithAuth", "(", "e", "*", "gin", ".", "Engine", ",", "accounts", "gin", ".", "Accounts", ")", "{", "e", ".", "Use", "(", "p", ".", "HandlerFunc", "(", ")", ")", "\n", "p", ".", "SetMetricsPathWithAuth", "(", "e", ",", "accounts", ")", "\n", "}" ]
// UseWithAuth adds the middleware to a gin engine with BasicAuth.
[ "UseWithAuth", "adds", "the", "middleware", "to", "a", "gin", "engine", "with", "BasicAuth", "." ]
58963fb32f547bd98cc0150a6bcbdf181a430967
https://github.com/zsais/go-gin-prometheus/blob/58963fb32f547bd98cc0150a6bcbdf181a430967/middleware.go#L348-L351
15,206
zsais/go-gin-prometheus
middleware.go
HandlerFunc
func (p *Prometheus) HandlerFunc() gin.HandlerFunc { return func(c *gin.Context) { if c.Request.URL.String() == p.MetricsPath { c.Next() return } start := time.Now() reqSz := computeApproximateRequestSize(c.Request) c.Next() status := strconv.Itoa(c.Writer.Status()) elapsed := float64(time.Since(start)) / float64(time.Second) resSz := float64(c.Writer.Size()) p.reqDur.Observe(elapsed) url := p.ReqCntURLLabelMappingFn(c) // jlambert Oct 2018 - sidecar specific mod if len(p.URLLabelFromContext) > 0 { u, found := c.Get(p.URLLabelFromContext) if !found { u = "unknown" } url = u.(string) } p.reqCnt.WithLabelValues(status, c.Request.Method, c.HandlerName(), c.Request.Host, url).Inc() p.reqSz.Observe(float64(reqSz)) p.resSz.Observe(resSz) } }
go
func (p *Prometheus) HandlerFunc() gin.HandlerFunc { return func(c *gin.Context) { if c.Request.URL.String() == p.MetricsPath { c.Next() return } start := time.Now() reqSz := computeApproximateRequestSize(c.Request) c.Next() status := strconv.Itoa(c.Writer.Status()) elapsed := float64(time.Since(start)) / float64(time.Second) resSz := float64(c.Writer.Size()) p.reqDur.Observe(elapsed) url := p.ReqCntURLLabelMappingFn(c) // jlambert Oct 2018 - sidecar specific mod if len(p.URLLabelFromContext) > 0 { u, found := c.Get(p.URLLabelFromContext) if !found { u = "unknown" } url = u.(string) } p.reqCnt.WithLabelValues(status, c.Request.Method, c.HandlerName(), c.Request.Host, url).Inc() p.reqSz.Observe(float64(reqSz)) p.resSz.Observe(resSz) } }
[ "func", "(", "p", "*", "Prometheus", ")", "HandlerFunc", "(", ")", "gin", ".", "HandlerFunc", "{", "return", "func", "(", "c", "*", "gin", ".", "Context", ")", "{", "if", "c", ".", "Request", ".", "URL", ".", "String", "(", ")", "==", "p", ".", "MetricsPath", "{", "c", ".", "Next", "(", ")", "\n", "return", "\n", "}", "\n\n", "start", ":=", "time", ".", "Now", "(", ")", "\n", "reqSz", ":=", "computeApproximateRequestSize", "(", "c", ".", "Request", ")", "\n\n", "c", ".", "Next", "(", ")", "\n\n", "status", ":=", "strconv", ".", "Itoa", "(", "c", ".", "Writer", ".", "Status", "(", ")", ")", "\n", "elapsed", ":=", "float64", "(", "time", ".", "Since", "(", "start", ")", ")", "/", "float64", "(", "time", ".", "Second", ")", "\n", "resSz", ":=", "float64", "(", "c", ".", "Writer", ".", "Size", "(", ")", ")", "\n\n", "p", ".", "reqDur", ".", "Observe", "(", "elapsed", ")", "\n", "url", ":=", "p", ".", "ReqCntURLLabelMappingFn", "(", "c", ")", "\n", "// jlambert Oct 2018 - sidecar specific mod", "if", "len", "(", "p", ".", "URLLabelFromContext", ")", ">", "0", "{", "u", ",", "found", ":=", "c", ".", "Get", "(", "p", ".", "URLLabelFromContext", ")", "\n", "if", "!", "found", "{", "u", "=", "\"", "\"", "\n", "}", "\n", "url", "=", "u", ".", "(", "string", ")", "\n", "}", "\n", "p", ".", "reqCnt", ".", "WithLabelValues", "(", "status", ",", "c", ".", "Request", ".", "Method", ",", "c", ".", "HandlerName", "(", ")", ",", "c", ".", "Request", ".", "Host", ",", "url", ")", ".", "Inc", "(", ")", "\n", "p", ".", "reqSz", ".", "Observe", "(", "float64", "(", "reqSz", ")", ")", "\n", "p", ".", "resSz", ".", "Observe", "(", "resSz", ")", "\n", "}", "\n", "}" ]
// HandlerFunc defines handler function for middleware
[ "HandlerFunc", "defines", "handler", "function", "for", "middleware" ]
58963fb32f547bd98cc0150a6bcbdf181a430967
https://github.com/zsais/go-gin-prometheus/blob/58963fb32f547bd98cc0150a6bcbdf181a430967/middleware.go#L354-L384
15,207
cloudflare/ahocorasick
ahocorasick.go
findBlice
func (m *Matcher) findBlice(b []byte) *node { n := &m.trie[0] for n != nil && len(b) > 0 { n = n.child[int(b[0])] b = b[1:] } return n }
go
func (m *Matcher) findBlice(b []byte) *node { n := &m.trie[0] for n != nil && len(b) > 0 { n = n.child[int(b[0])] b = b[1:] } return n }
[ "func", "(", "m", "*", "Matcher", ")", "findBlice", "(", "b", "[", "]", "byte", ")", "*", "node", "{", "n", ":=", "&", "m", ".", "trie", "[", "0", "]", "\n\n", "for", "n", "!=", "nil", "&&", "len", "(", "b", ")", ">", "0", "{", "n", "=", "n", ".", "child", "[", "int", "(", "b", "[", "0", "]", ")", "]", "\n", "b", "=", "b", "[", "1", ":", "]", "\n", "}", "\n\n", "return", "n", "\n", "}" ]
// finndBlice looks for a blice in the trie starting from the root and // returns a pointer to the node representing the end of the blice. If // the blice is not found it returns nil.
[ "finndBlice", "looks", "for", "a", "blice", "in", "the", "trie", "starting", "from", "the", "root", "and", "returns", "a", "pointer", "to", "the", "node", "representing", "the", "end", "of", "the", "blice", ".", "If", "the", "blice", "is", "not", "found", "it", "returns", "nil", "." ]
1ce46e42b741851faf33c1bf283eeae6676f70a8
https://github.com/cloudflare/ahocorasick/blob/1ce46e42b741851faf33c1bf283eeae6676f70a8/ahocorasick.go#L63-L72
15,208
cloudflare/ahocorasick
ahocorasick.go
buildTrie
func (m *Matcher) buildTrie(dictionary [][]byte) { // Work out the maximum size for the trie (all dictionary entries // are distinct plus the root). This is used to preallocate memory // for it. max := 1 for _, blice := range dictionary { max += len(blice) } m.trie = make([]node, max) // Calling this an ignoring its argument simply allocated // m.trie[0] which will be the root element m.getFreeNode() // This loop builds the nodes in the trie by following through // each dictionary entry building the children pointers. for i, blice := range dictionary { n := m.root var path []byte for _, b := range blice { path = append(path, b) c := n.child[int(b)] if c == nil { c = m.getFreeNode() n.child[int(b)] = c c.b = make([]byte, len(path)) copy(c.b, path) // Nodes directly under the root node will have the // root as their fail point as there are no suffixes // possible. if len(path) == 1 { c.fail = m.root } c.suffix = m.root } n = c } // The last value of n points to the node representing a // dictionary entry n.output = true n.index = i } l := new(list.List) l.PushBack(m.root) for l.Len() > 0 { n := l.Remove(l.Front()).(*node) for i := 0; i < 256; i++ { c := n.child[i] if c != nil { l.PushBack(c) for j := 1; j < len(c.b); j++ { c.fail = m.findBlice(c.b[j:]) if c.fail != nil { break } } if c.fail == nil { c.fail = m.root } for j := 1; j < len(c.b); j++ { s := m.findBlice(c.b[j:]) if s != nil && s.output { c.suffix = s break } } } } } for i := 0; i < m.extent; i++ { for c := 0; c < 256; c++ { n := &m.trie[i] for n.child[c] == nil && !n.root { n = n.fail } m.trie[i].fails[c] = n } } m.trie = m.trie[:m.extent] }
go
func (m *Matcher) buildTrie(dictionary [][]byte) { // Work out the maximum size for the trie (all dictionary entries // are distinct plus the root). This is used to preallocate memory // for it. max := 1 for _, blice := range dictionary { max += len(blice) } m.trie = make([]node, max) // Calling this an ignoring its argument simply allocated // m.trie[0] which will be the root element m.getFreeNode() // This loop builds the nodes in the trie by following through // each dictionary entry building the children pointers. for i, blice := range dictionary { n := m.root var path []byte for _, b := range blice { path = append(path, b) c := n.child[int(b)] if c == nil { c = m.getFreeNode() n.child[int(b)] = c c.b = make([]byte, len(path)) copy(c.b, path) // Nodes directly under the root node will have the // root as their fail point as there are no suffixes // possible. if len(path) == 1 { c.fail = m.root } c.suffix = m.root } n = c } // The last value of n points to the node representing a // dictionary entry n.output = true n.index = i } l := new(list.List) l.PushBack(m.root) for l.Len() > 0 { n := l.Remove(l.Front()).(*node) for i := 0; i < 256; i++ { c := n.child[i] if c != nil { l.PushBack(c) for j := 1; j < len(c.b); j++ { c.fail = m.findBlice(c.b[j:]) if c.fail != nil { break } } if c.fail == nil { c.fail = m.root } for j := 1; j < len(c.b); j++ { s := m.findBlice(c.b[j:]) if s != nil && s.output { c.suffix = s break } } } } } for i := 0; i < m.extent; i++ { for c := 0; c < 256; c++ { n := &m.trie[i] for n.child[c] == nil && !n.root { n = n.fail } m.trie[i].fails[c] = n } } m.trie = m.trie[:m.extent] }
[ "func", "(", "m", "*", "Matcher", ")", "buildTrie", "(", "dictionary", "[", "]", "[", "]", "byte", ")", "{", "// Work out the maximum size for the trie (all dictionary entries", "// are distinct plus the root). This is used to preallocate memory", "// for it.", "max", ":=", "1", "\n", "for", "_", ",", "blice", ":=", "range", "dictionary", "{", "max", "+=", "len", "(", "blice", ")", "\n", "}", "\n", "m", ".", "trie", "=", "make", "(", "[", "]", "node", ",", "max", ")", "\n\n", "// Calling this an ignoring its argument simply allocated", "// m.trie[0] which will be the root element", "m", ".", "getFreeNode", "(", ")", "\n\n", "// This loop builds the nodes in the trie by following through", "// each dictionary entry building the children pointers.", "for", "i", ",", "blice", ":=", "range", "dictionary", "{", "n", ":=", "m", ".", "root", "\n", "var", "path", "[", "]", "byte", "\n", "for", "_", ",", "b", ":=", "range", "blice", "{", "path", "=", "append", "(", "path", ",", "b", ")", "\n\n", "c", ":=", "n", ".", "child", "[", "int", "(", "b", ")", "]", "\n\n", "if", "c", "==", "nil", "{", "c", "=", "m", ".", "getFreeNode", "(", ")", "\n", "n", ".", "child", "[", "int", "(", "b", ")", "]", "=", "c", "\n", "c", ".", "b", "=", "make", "(", "[", "]", "byte", ",", "len", "(", "path", ")", ")", "\n", "copy", "(", "c", ".", "b", ",", "path", ")", "\n\n", "// Nodes directly under the root node will have the", "// root as their fail point as there are no suffixes", "// possible.", "if", "len", "(", "path", ")", "==", "1", "{", "c", ".", "fail", "=", "m", ".", "root", "\n", "}", "\n\n", "c", ".", "suffix", "=", "m", ".", "root", "\n", "}", "\n\n", "n", "=", "c", "\n", "}", "\n\n", "// The last value of n points to the node representing a", "// dictionary entry", "n", ".", "output", "=", "true", "\n", "n", ".", "index", "=", "i", "\n", "}", "\n\n", "l", ":=", "new", "(", "list", ".", "List", ")", "\n", "l", ".", "PushBack", "(", "m", ".", "root", ")", "\n\n", "for", "l", ".", "Len", "(", ")", ">", "0", "{", "n", ":=", "l", ".", "Remove", "(", "l", ".", "Front", "(", ")", ")", ".", "(", "*", "node", ")", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "256", ";", "i", "++", "{", "c", ":=", "n", ".", "child", "[", "i", "]", "\n", "if", "c", "!=", "nil", "{", "l", ".", "PushBack", "(", "c", ")", "\n\n", "for", "j", ":=", "1", ";", "j", "<", "len", "(", "c", ".", "b", ")", ";", "j", "++", "{", "c", ".", "fail", "=", "m", ".", "findBlice", "(", "c", ".", "b", "[", "j", ":", "]", ")", "\n", "if", "c", ".", "fail", "!=", "nil", "{", "break", "\n", "}", "\n", "}", "\n\n", "if", "c", ".", "fail", "==", "nil", "{", "c", ".", "fail", "=", "m", ".", "root", "\n", "}", "\n\n", "for", "j", ":=", "1", ";", "j", "<", "len", "(", "c", ".", "b", ")", ";", "j", "++", "{", "s", ":=", "m", ".", "findBlice", "(", "c", ".", "b", "[", "j", ":", "]", ")", "\n", "if", "s", "!=", "nil", "&&", "s", ".", "output", "{", "c", ".", "suffix", "=", "s", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "m", ".", "extent", ";", "i", "++", "{", "for", "c", ":=", "0", ";", "c", "<", "256", ";", "c", "++", "{", "n", ":=", "&", "m", ".", "trie", "[", "i", "]", "\n", "for", "n", ".", "child", "[", "c", "]", "==", "nil", "&&", "!", "n", ".", "root", "{", "n", "=", "n", ".", "fail", "\n", "}", "\n\n", "m", ".", "trie", "[", "i", "]", ".", "fails", "[", "c", "]", "=", "n", "\n", "}", "\n", "}", "\n\n", "m", ".", "trie", "=", "m", ".", "trie", "[", ":", "m", ".", "extent", "]", "\n", "}" ]
// buildTrie builds the fundamental trie structure from a set of // blices.
[ "buildTrie", "builds", "the", "fundamental", "trie", "structure", "from", "a", "set", "of", "blices", "." ]
1ce46e42b741851faf33c1bf283eeae6676f70a8
https://github.com/cloudflare/ahocorasick/blob/1ce46e42b741851faf33c1bf283eeae6676f70a8/ahocorasick.go#L89-L189
15,209
cloudflare/ahocorasick
ahocorasick.go
NewMatcher
func NewMatcher(dictionary [][]byte) *Matcher { m := new(Matcher) m.buildTrie(dictionary) return m }
go
func NewMatcher(dictionary [][]byte) *Matcher { m := new(Matcher) m.buildTrie(dictionary) return m }
[ "func", "NewMatcher", "(", "dictionary", "[", "]", "[", "]", "byte", ")", "*", "Matcher", "{", "m", ":=", "new", "(", "Matcher", ")", "\n\n", "m", ".", "buildTrie", "(", "dictionary", ")", "\n\n", "return", "m", "\n", "}" ]
// NewMatcher creates a new Matcher used to match against a set of // blices
[ "NewMatcher", "creates", "a", "new", "Matcher", "used", "to", "match", "against", "a", "set", "of", "blices" ]
1ce46e42b741851faf33c1bf283eeae6676f70a8
https://github.com/cloudflare/ahocorasick/blob/1ce46e42b741851faf33c1bf283eeae6676f70a8/ahocorasick.go#L193-L199
15,210
cloudflare/ahocorasick
ahocorasick.go
Match
func (m *Matcher) Match(in []byte) []int { m.counter += 1 var hits []int n := m.root for _, b := range in { c := int(b) if !n.root && n.child[c] == nil { n = n.fails[c] } if n.child[c] != nil { f := n.child[c] n = f if f.output && f.counter != m.counter { hits = append(hits, f.index) f.counter = m.counter } for !f.suffix.root { f = f.suffix if f.counter != m.counter { hits = append(hits, f.index) f.counter = m.counter } else { // There's no point working our way up the // suffixes if it's been done before for this call // to Match. The matches are already in hits. break } } } } return hits }
go
func (m *Matcher) Match(in []byte) []int { m.counter += 1 var hits []int n := m.root for _, b := range in { c := int(b) if !n.root && n.child[c] == nil { n = n.fails[c] } if n.child[c] != nil { f := n.child[c] n = f if f.output && f.counter != m.counter { hits = append(hits, f.index) f.counter = m.counter } for !f.suffix.root { f = f.suffix if f.counter != m.counter { hits = append(hits, f.index) f.counter = m.counter } else { // There's no point working our way up the // suffixes if it's been done before for this call // to Match. The matches are already in hits. break } } } } return hits }
[ "func", "(", "m", "*", "Matcher", ")", "Match", "(", "in", "[", "]", "byte", ")", "[", "]", "int", "{", "m", ".", "counter", "+=", "1", "\n", "var", "hits", "[", "]", "int", "\n\n", "n", ":=", "m", ".", "root", "\n\n", "for", "_", ",", "b", ":=", "range", "in", "{", "c", ":=", "int", "(", "b", ")", "\n\n", "if", "!", "n", ".", "root", "&&", "n", ".", "child", "[", "c", "]", "==", "nil", "{", "n", "=", "n", ".", "fails", "[", "c", "]", "\n", "}", "\n\n", "if", "n", ".", "child", "[", "c", "]", "!=", "nil", "{", "f", ":=", "n", ".", "child", "[", "c", "]", "\n", "n", "=", "f", "\n\n", "if", "f", ".", "output", "&&", "f", ".", "counter", "!=", "m", ".", "counter", "{", "hits", "=", "append", "(", "hits", ",", "f", ".", "index", ")", "\n", "f", ".", "counter", "=", "m", ".", "counter", "\n", "}", "\n\n", "for", "!", "f", ".", "suffix", ".", "root", "{", "f", "=", "f", ".", "suffix", "\n", "if", "f", ".", "counter", "!=", "m", ".", "counter", "{", "hits", "=", "append", "(", "hits", ",", "f", ".", "index", ")", "\n", "f", ".", "counter", "=", "m", ".", "counter", "\n", "}", "else", "{", "// There's no point working our way up the", "// suffixes if it's been done before for this call", "// to Match. The matches are already in hits.", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "hits", "\n", "}" ]
// Match searches in for blices and returns all the blices found as // indexes into the original dictionary
[ "Match", "searches", "in", "for", "blices", "and", "returns", "all", "the", "blices", "found", "as", "indexes", "into", "the", "original", "dictionary" ]
1ce46e42b741851faf33c1bf283eeae6676f70a8
https://github.com/cloudflare/ahocorasick/blob/1ce46e42b741851faf33c1bf283eeae6676f70a8/ahocorasick.go#L218-L258
15,211
PuerkitoBio/fetchbot
example/full/main.go
stopHandler
func stopHandler(stopurl string, cancel bool, wrapped fetchbot.Handler) fetchbot.Handler { return fetchbot.HandlerFunc(func(ctx *fetchbot.Context, res *http.Response, err error) { if ctx.Cmd.URL().String() == stopurl { fmt.Printf(">>>>> STOP URL %s\n", ctx.Cmd.URL()) // generally not a good idea to stop/block from a handler goroutine // so do it in a separate goroutine go func() { if cancel { ctx.Q.Cancel() } else { ctx.Q.Close() } }() return } wrapped.Handle(ctx, res, err) }) }
go
func stopHandler(stopurl string, cancel bool, wrapped fetchbot.Handler) fetchbot.Handler { return fetchbot.HandlerFunc(func(ctx *fetchbot.Context, res *http.Response, err error) { if ctx.Cmd.URL().String() == stopurl { fmt.Printf(">>>>> STOP URL %s\n", ctx.Cmd.URL()) // generally not a good idea to stop/block from a handler goroutine // so do it in a separate goroutine go func() { if cancel { ctx.Q.Cancel() } else { ctx.Q.Close() } }() return } wrapped.Handle(ctx, res, err) }) }
[ "func", "stopHandler", "(", "stopurl", "string", ",", "cancel", "bool", ",", "wrapped", "fetchbot", ".", "Handler", ")", "fetchbot", ".", "Handler", "{", "return", "fetchbot", ".", "HandlerFunc", "(", "func", "(", "ctx", "*", "fetchbot", ".", "Context", ",", "res", "*", "http", ".", "Response", ",", "err", "error", ")", "{", "if", "ctx", ".", "Cmd", ".", "URL", "(", ")", ".", "String", "(", ")", "==", "stopurl", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "ctx", ".", "Cmd", ".", "URL", "(", ")", ")", "\n", "// generally not a good idea to stop/block from a handler goroutine", "// so do it in a separate goroutine", "go", "func", "(", ")", "{", "if", "cancel", "{", "ctx", ".", "Q", ".", "Cancel", "(", ")", "\n", "}", "else", "{", "ctx", ".", "Q", ".", "Close", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n", "return", "\n", "}", "\n", "wrapped", ".", "Handle", "(", "ctx", ",", "res", ",", "err", ")", "\n", "}", ")", "\n", "}" ]
// stopHandler stops the fetcher if the stopurl is reached. Otherwise it dispatches // the call to the wrapped Handler.
[ "stopHandler", "stops", "the", "fetcher", "if", "the", "stopurl", "is", "reached", ".", "Otherwise", "it", "dispatches", "the", "call", "to", "the", "wrapped", "Handler", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/example/full/main.go#L169-L186
15,212
PuerkitoBio/fetchbot
example/full/main.go
logHandler
func logHandler(wrapped fetchbot.Handler) fetchbot.Handler { return fetchbot.HandlerFunc(func(ctx *fetchbot.Context, res *http.Response, err error) { if err == nil { fmt.Printf("[%d] %s %s - %s\n", res.StatusCode, ctx.Cmd.Method(), ctx.Cmd.URL(), res.Header.Get("Content-Type")) } wrapped.Handle(ctx, res, err) }) }
go
func logHandler(wrapped fetchbot.Handler) fetchbot.Handler { return fetchbot.HandlerFunc(func(ctx *fetchbot.Context, res *http.Response, err error) { if err == nil { fmt.Printf("[%d] %s %s - %s\n", res.StatusCode, ctx.Cmd.Method(), ctx.Cmd.URL(), res.Header.Get("Content-Type")) } wrapped.Handle(ctx, res, err) }) }
[ "func", "logHandler", "(", "wrapped", "fetchbot", ".", "Handler", ")", "fetchbot", ".", "Handler", "{", "return", "fetchbot", ".", "HandlerFunc", "(", "func", "(", "ctx", "*", "fetchbot", ".", "Context", ",", "res", "*", "http", ".", "Response", ",", "err", "error", ")", "{", "if", "err", "==", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "res", ".", "StatusCode", ",", "ctx", ".", "Cmd", ".", "Method", "(", ")", ",", "ctx", ".", "Cmd", ".", "URL", "(", ")", ",", "res", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "wrapped", ".", "Handle", "(", "ctx", ",", "res", ",", "err", ")", "\n", "}", ")", "\n", "}" ]
// logHandler prints the fetch information and dispatches the call to the wrapped Handler.
[ "logHandler", "prints", "the", "fetch", "information", "and", "dispatches", "the", "call", "to", "the", "wrapped", "Handler", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/example/full/main.go#L189-L196
15,213
PuerkitoBio/fetchbot
cmd.go
NewHandlerCmd
func NewHandlerCmd(method, rawURL string, fn func(*Context, *http.Response, error)) (*HandlerCmd, error) { parsedURL, err := url.Parse(rawURL) if err != nil { return nil, err } return &HandlerCmd{&Cmd{parsedURL, method}, HandlerFunc(fn)}, nil }
go
func NewHandlerCmd(method, rawURL string, fn func(*Context, *http.Response, error)) (*HandlerCmd, error) { parsedURL, err := url.Parse(rawURL) if err != nil { return nil, err } return &HandlerCmd{&Cmd{parsedURL, method}, HandlerFunc(fn)}, nil }
[ "func", "NewHandlerCmd", "(", "method", ",", "rawURL", "string", ",", "fn", "func", "(", "*", "Context", ",", "*", "http", ".", "Response", ",", "error", ")", ")", "(", "*", "HandlerCmd", ",", "error", ")", "{", "parsedURL", ",", "err", ":=", "url", ".", "Parse", "(", "rawURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "HandlerCmd", "{", "&", "Cmd", "{", "parsedURL", ",", "method", "}", ",", "HandlerFunc", "(", "fn", ")", "}", ",", "nil", "\n", "}" ]
// NewHandlerCmd creates a HandlerCmd for the provided request and callback // handler function.
[ "NewHandlerCmd", "creates", "a", "HandlerCmd", "for", "the", "provided", "request", "and", "callback", "handler", "function", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/cmd.go#L77-L83
15,214
PuerkitoBio/fetchbot
handler.go
Handle
func (h HandlerFunc) Handle(ctx *Context, res *http.Response, err error) { h(ctx, res, err) }
go
func (h HandlerFunc) Handle(ctx *Context, res *http.Response, err error) { h(ctx, res, err) }
[ "func", "(", "h", "HandlerFunc", ")", "Handle", "(", "ctx", "*", "Context", ",", "res", "*", "http", ".", "Response", ",", "err", "error", ")", "{", "h", "(", "ctx", ",", "res", ",", "err", ")", "\n", "}" ]
// Handle is the Handler interface implementation for the HandlerFunc type.
[ "Handle", "is", "the", "Handler", "interface", "implementation", "for", "the", "HandlerFunc", "type", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/handler.go#L31-L33
15,215
PuerkitoBio/fetchbot
handler.go
NewMux
func NewMux() *Mux { return &Mux{ // Default handler is a no-op DefaultHandler: HandlerFunc(func(ctx *Context, res *http.Response, err error) {}), errm: make(map[error]Handler), res: make(map[*ResponseMatcher]bool), } }
go
func NewMux() *Mux { return &Mux{ // Default handler is a no-op DefaultHandler: HandlerFunc(func(ctx *Context, res *http.Response, err error) {}), errm: make(map[error]Handler), res: make(map[*ResponseMatcher]bool), } }
[ "func", "NewMux", "(", ")", "*", "Mux", "{", "return", "&", "Mux", "{", "// Default handler is a no-op", "DefaultHandler", ":", "HandlerFunc", "(", "func", "(", "ctx", "*", "Context", ",", "res", "*", "http", ".", "Response", ",", "err", "error", ")", "{", "}", ")", ",", "errm", ":", "make", "(", "map", "[", "error", "]", "Handler", ")", ",", "res", ":", "make", "(", "map", "[", "*", "ResponseMatcher", "]", "bool", ")", ",", "}", "\n", "}" ]
// NewMux returns an initialized Mux.
[ "NewMux", "returns", "an", "initialized", "Mux", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/handler.go#L60-L67
15,216
PuerkitoBio/fetchbot
handler.go
Handle
func (mux *Mux) Handle(ctx *Context, res *http.Response, err error) { mux.mu.RLock() defer mux.mu.RUnlock() if err != nil { // Find a matching error handler if h, ok := mux.errm[err]; ok { h.Handle(ctx, res, err) return } if h, ok := mux.errm[nil]; ok { h.Handle(ctx, res, err) return } } else { // Find a matching response handler var h Handler var n = -1 for r := range mux.res { if ok, cnt := r.match(res); ok { if cnt > n { h, n = r.h, cnt } } } if h != nil { h.Handle(ctx, res, err) return } } mux.DefaultHandler.Handle(ctx, res, err) }
go
func (mux *Mux) Handle(ctx *Context, res *http.Response, err error) { mux.mu.RLock() defer mux.mu.RUnlock() if err != nil { // Find a matching error handler if h, ok := mux.errm[err]; ok { h.Handle(ctx, res, err) return } if h, ok := mux.errm[nil]; ok { h.Handle(ctx, res, err) return } } else { // Find a matching response handler var h Handler var n = -1 for r := range mux.res { if ok, cnt := r.match(res); ok { if cnt > n { h, n = r.h, cnt } } } if h != nil { h.Handle(ctx, res, err) return } } mux.DefaultHandler.Handle(ctx, res, err) }
[ "func", "(", "mux", "*", "Mux", ")", "Handle", "(", "ctx", "*", "Context", ",", "res", "*", "http", ".", "Response", ",", "err", "error", ")", "{", "mux", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "mux", ".", "mu", ".", "RUnlock", "(", ")", "\n", "if", "err", "!=", "nil", "{", "// Find a matching error handler", "if", "h", ",", "ok", ":=", "mux", ".", "errm", "[", "err", "]", ";", "ok", "{", "h", ".", "Handle", "(", "ctx", ",", "res", ",", "err", ")", "\n", "return", "\n", "}", "\n", "if", "h", ",", "ok", ":=", "mux", ".", "errm", "[", "nil", "]", ";", "ok", "{", "h", ".", "Handle", "(", "ctx", ",", "res", ",", "err", ")", "\n", "return", "\n", "}", "\n", "}", "else", "{", "// Find a matching response handler", "var", "h", "Handler", "\n", "var", "n", "=", "-", "1", "\n", "for", "r", ":=", "range", "mux", ".", "res", "{", "if", "ok", ",", "cnt", ":=", "r", ".", "match", "(", "res", ")", ";", "ok", "{", "if", "cnt", ">", "n", "{", "h", ",", "n", "=", "r", ".", "h", ",", "cnt", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "h", "!=", "nil", "{", "h", ".", "Handle", "(", "ctx", ",", "res", ",", "err", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "mux", ".", "DefaultHandler", ".", "Handle", "(", "ctx", ",", "res", ",", "err", ")", "\n", "}" ]
// Handle is the Handler interface implementation for Mux. It dispatches the calls // to the matching Handler.
[ "Handle", "is", "the", "Handler", "interface", "implementation", "for", "Mux", ".", "It", "dispatches", "the", "calls", "to", "the", "matching", "Handler", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/handler.go#L71-L101
15,217
PuerkitoBio/fetchbot
handler.go
HandleError
func (mux *Mux) HandleError(err error, h Handler) { mux.mu.Lock() defer mux.mu.Unlock() mux.errm[err] = h }
go
func (mux *Mux) HandleError(err error, h Handler) { mux.mu.Lock() defer mux.mu.Unlock() mux.errm[err] = h }
[ "func", "(", "mux", "*", "Mux", ")", "HandleError", "(", "err", "error", ",", "h", "Handler", ")", "{", "mux", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "mux", ".", "mu", ".", "Unlock", "(", ")", "\n", "mux", ".", "errm", "[", "err", "]", "=", "h", "\n", "}" ]
// HandleError registers a Handler for a specific error value. Multiple calls // with the same error value override previous calls. As a special case, a nil // error value registers a Handler for any error that doesn't have a specific // Handler.
[ "HandleError", "registers", "a", "Handler", "for", "a", "specific", "error", "value", ".", "Multiple", "calls", "with", "the", "same", "error", "value", "override", "previous", "calls", ".", "As", "a", "special", "case", "a", "nil", "error", "value", "registers", "a", "Handler", "for", "any", "error", "that", "doesn", "t", "have", "a", "specific", "Handler", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/handler.go#L107-L111
15,218
PuerkitoBio/fetchbot
handler.go
match
func (r *ResponseMatcher) match(res *http.Response) (bool, int) { if r.method != "" { if r.method != res.Request.Method { return false, 0 } } if r.contentType != "" { if r.contentType != getContentType(res.Header.Get("Content-Type")) { return false, 0 } } if r.minStatus != 0 || r.maxStatus != 0 { if res.StatusCode < r.minStatus || res.StatusCode > r.maxStatus { return false, 0 } } if r.scheme != "" { if res.Request.URL.Scheme != r.scheme { return false, 0 } } if r.host != "" { if res.Request.URL.Host != r.host { return false, 0 } } if r.predicate != nil { if !r.predicate(res) { return false, 0 } } if r.path != "" { if strings.HasPrefix(res.Request.URL.Path, r.path) { return true, len(r.path) } return false, 0 } return true, 0 }
go
func (r *ResponseMatcher) match(res *http.Response) (bool, int) { if r.method != "" { if r.method != res.Request.Method { return false, 0 } } if r.contentType != "" { if r.contentType != getContentType(res.Header.Get("Content-Type")) { return false, 0 } } if r.minStatus != 0 || r.maxStatus != 0 { if res.StatusCode < r.minStatus || res.StatusCode > r.maxStatus { return false, 0 } } if r.scheme != "" { if res.Request.URL.Scheme != r.scheme { return false, 0 } } if r.host != "" { if res.Request.URL.Host != r.host { return false, 0 } } if r.predicate != nil { if !r.predicate(res) { return false, 0 } } if r.path != "" { if strings.HasPrefix(res.Request.URL.Path, r.path) { return true, len(r.path) } return false, 0 } return true, 0 }
[ "func", "(", "r", "*", "ResponseMatcher", ")", "match", "(", "res", "*", "http", ".", "Response", ")", "(", "bool", ",", "int", ")", "{", "if", "r", ".", "method", "!=", "\"", "\"", "{", "if", "r", ".", "method", "!=", "res", ".", "Request", ".", "Method", "{", "return", "false", ",", "0", "\n", "}", "\n", "}", "\n", "if", "r", ".", "contentType", "!=", "\"", "\"", "{", "if", "r", ".", "contentType", "!=", "getContentType", "(", "res", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ")", "{", "return", "false", ",", "0", "\n", "}", "\n", "}", "\n", "if", "r", ".", "minStatus", "!=", "0", "||", "r", ".", "maxStatus", "!=", "0", "{", "if", "res", ".", "StatusCode", "<", "r", ".", "minStatus", "||", "res", ".", "StatusCode", ">", "r", ".", "maxStatus", "{", "return", "false", ",", "0", "\n", "}", "\n", "}", "\n", "if", "r", ".", "scheme", "!=", "\"", "\"", "{", "if", "res", ".", "Request", ".", "URL", ".", "Scheme", "!=", "r", ".", "scheme", "{", "return", "false", ",", "0", "\n", "}", "\n", "}", "\n", "if", "r", ".", "host", "!=", "\"", "\"", "{", "if", "res", ".", "Request", ".", "URL", ".", "Host", "!=", "r", ".", "host", "{", "return", "false", ",", "0", "\n", "}", "\n", "}", "\n", "if", "r", ".", "predicate", "!=", "nil", "{", "if", "!", "r", ".", "predicate", "(", "res", ")", "{", "return", "false", ",", "0", "\n", "}", "\n", "}", "\n", "if", "r", ".", "path", "!=", "\"", "\"", "{", "if", "strings", ".", "HasPrefix", "(", "res", ".", "Request", ".", "URL", ".", "Path", ",", "r", ".", "path", ")", "{", "return", "true", ",", "len", "(", "r", ".", "path", ")", "\n", "}", "\n", "return", "false", ",", "0", "\n", "}", "\n", "return", "true", ",", "0", "\n", "}" ]
// match indicates if the response Handler matches the provided response, and if so, // and if a path criteria is specified, it also indicates the length of the path match.
[ "match", "indicates", "if", "the", "response", "Handler", "matches", "the", "provided", "response", "and", "if", "so", "and", "if", "a", "path", "criteria", "is", "specified", "it", "also", "indicates", "the", "length", "of", "the", "path", "match", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/handler.go#L141-L179
15,219
PuerkitoBio/fetchbot
handler.go
Status
func (r *ResponseMatcher) Status(code int) *ResponseMatcher { r.mux.mu.Lock() defer r.mux.mu.Unlock() r.minStatus = code r.maxStatus = code return r }
go
func (r *ResponseMatcher) Status(code int) *ResponseMatcher { r.mux.mu.Lock() defer r.mux.mu.Unlock() r.minStatus = code r.maxStatus = code return r }
[ "func", "(", "r", "*", "ResponseMatcher", ")", "Status", "(", "code", "int", ")", "*", "ResponseMatcher", "{", "r", ".", "mux", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "mux", ".", "mu", ".", "Unlock", "(", ")", "\n", "r", ".", "minStatus", "=", "code", "\n", "r", ".", "maxStatus", "=", "code", "\n", "return", "r", "\n", "}" ]
// Status sets a criteria based on the Status code of the response for the Response Handler. // Its Handler will only be called if the response has this status code.
[ "Status", "sets", "a", "criteria", "based", "on", "the", "Status", "code", "of", "the", "response", "for", "the", "Response", "Handler", ".", "Its", "Handler", "will", "only", "be", "called", "if", "the", "response", "has", "this", "status", "code", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/handler.go#L211-L217
15,220
PuerkitoBio/fetchbot
handler.go
StatusRange
func (r *ResponseMatcher) StatusRange(min, max int) *ResponseMatcher { if min > max { min, max = max, min } r.mux.mu.Lock() defer r.mux.mu.Unlock() r.minStatus = min r.maxStatus = max return r }
go
func (r *ResponseMatcher) StatusRange(min, max int) *ResponseMatcher { if min > max { min, max = max, min } r.mux.mu.Lock() defer r.mux.mu.Unlock() r.minStatus = min r.maxStatus = max return r }
[ "func", "(", "r", "*", "ResponseMatcher", ")", "StatusRange", "(", "min", ",", "max", "int", ")", "*", "ResponseMatcher", "{", "if", "min", ">", "max", "{", "min", ",", "max", "=", "max", ",", "min", "\n", "}", "\n", "r", ".", "mux", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "mux", ".", "mu", ".", "Unlock", "(", ")", "\n", "r", ".", "minStatus", "=", "min", "\n", "r", ".", "maxStatus", "=", "max", "\n", "return", "r", "\n", "}" ]
// StatusRange sets a criteria based on the Status code of the response for the Response Handler. // Its Handler will only be called if the response has a status code between the min and max. // If min is greater than max, the values are switched.
[ "StatusRange", "sets", "a", "criteria", "based", "on", "the", "Status", "code", "of", "the", "response", "for", "the", "Response", "Handler", ".", "Its", "Handler", "will", "only", "be", "called", "if", "the", "response", "has", "a", "status", "code", "between", "the", "min", "and", "max", ".", "If", "min", "is", "greater", "than", "max", "the", "values", "are", "switched", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/handler.go#L222-L231
15,221
PuerkitoBio/fetchbot
handler.go
Scheme
func (r *ResponseMatcher) Scheme(scheme string) *ResponseMatcher { r.mux.mu.Lock() defer r.mux.mu.Unlock() r.scheme = scheme return r }
go
func (r *ResponseMatcher) Scheme(scheme string) *ResponseMatcher { r.mux.mu.Lock() defer r.mux.mu.Unlock() r.scheme = scheme return r }
[ "func", "(", "r", "*", "ResponseMatcher", ")", "Scheme", "(", "scheme", "string", ")", "*", "ResponseMatcher", "{", "r", ".", "mux", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "mux", ".", "mu", ".", "Unlock", "(", ")", "\n", "r", ".", "scheme", "=", "scheme", "\n", "return", "r", "\n", "}" ]
// Scheme sets a criteria based on the scheme of the URL for the Response Handler. Its Handler // will only be called if the scheme of the URL matches exactly the specified scheme.
[ "Scheme", "sets", "a", "criteria", "based", "on", "the", "scheme", "of", "the", "URL", "for", "the", "Response", "Handler", ".", "Its", "Handler", "will", "only", "be", "called", "if", "the", "scheme", "of", "the", "URL", "matches", "exactly", "the", "specified", "scheme", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/handler.go#L235-L240
15,222
PuerkitoBio/fetchbot
handler.go
Host
func (r *ResponseMatcher) Host(host string) *ResponseMatcher { r.mux.mu.Lock() defer r.mux.mu.Unlock() r.host = host return r }
go
func (r *ResponseMatcher) Host(host string) *ResponseMatcher { r.mux.mu.Lock() defer r.mux.mu.Unlock() r.host = host return r }
[ "func", "(", "r", "*", "ResponseMatcher", ")", "Host", "(", "host", "string", ")", "*", "ResponseMatcher", "{", "r", ".", "mux", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "mux", ".", "mu", ".", "Unlock", "(", ")", "\n", "r", ".", "host", "=", "host", "\n", "return", "r", "\n", "}" ]
// Host sets a criteria based on the host of the URL for the Response Handler. Its Handler // will only be called if the host of the URL matches exactly the specified host.
[ "Host", "sets", "a", "criteria", "based", "on", "the", "host", "of", "the", "URL", "for", "the", "Response", "Handler", ".", "Its", "Handler", "will", "only", "be", "called", "if", "the", "host", "of", "the", "URL", "matches", "exactly", "the", "specified", "host", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/handler.go#L244-L249
15,223
PuerkitoBio/fetchbot
handler.go
Path
func (r *ResponseMatcher) Path(p string) *ResponseMatcher { r.mux.mu.Lock() defer r.mux.mu.Unlock() r.path = p return r }
go
func (r *ResponseMatcher) Path(p string) *ResponseMatcher { r.mux.mu.Lock() defer r.mux.mu.Unlock() r.path = p return r }
[ "func", "(", "r", "*", "ResponseMatcher", ")", "Path", "(", "p", "string", ")", "*", "ResponseMatcher", "{", "r", ".", "mux", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "mux", ".", "mu", ".", "Unlock", "(", ")", "\n", "r", ".", "path", "=", "p", "\n", "return", "r", "\n", "}" ]
// Path sets a criteria based on the path of the URL for the Response Handler. Its Handler // will only be called if the path of the URL starts with this path. Longer matches // have priority over shorter ones.
[ "Path", "sets", "a", "criteria", "based", "on", "the", "path", "of", "the", "URL", "for", "the", "Response", "Handler", ".", "Its", "Handler", "will", "only", "be", "called", "if", "the", "path", "of", "the", "URL", "starts", "with", "this", "path", ".", "Longer", "matches", "have", "priority", "over", "shorter", "ones", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/handler.go#L254-L259
15,224
PuerkitoBio/fetchbot
handler.go
Custom
func (r *ResponseMatcher) Custom(predicate func(*http.Response) bool) *ResponseMatcher { r.mux.mu.Lock() defer r.mux.mu.Unlock() r.predicate = predicate return r }
go
func (r *ResponseMatcher) Custom(predicate func(*http.Response) bool) *ResponseMatcher { r.mux.mu.Lock() defer r.mux.mu.Unlock() r.predicate = predicate return r }
[ "func", "(", "r", "*", "ResponseMatcher", ")", "Custom", "(", "predicate", "func", "(", "*", "http", ".", "Response", ")", "bool", ")", "*", "ResponseMatcher", "{", "r", ".", "mux", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "mux", ".", "mu", ".", "Unlock", "(", ")", "\n", "r", ".", "predicate", "=", "predicate", "\n", "return", "r", "\n", "}" ]
// Custom sets a criteria based on a function that receives the HTTP response // and returns true if the matcher should be used to handle this response, // false otherwise.
[ "Custom", "sets", "a", "criteria", "based", "on", "a", "function", "that", "receives", "the", "HTTP", "response", "and", "returns", "true", "if", "the", "matcher", "should", "be", "used", "to", "handle", "this", "response", "false", "otherwise", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/handler.go#L264-L269
15,225
PuerkitoBio/fetchbot
handler.go
Handler
func (r *ResponseMatcher) Handler(h Handler) *ResponseMatcher { r.mux.mu.Lock() defer r.mux.mu.Unlock() r.h = h if !r.mux.res[r] { r.mux.res[r] = true } return r }
go
func (r *ResponseMatcher) Handler(h Handler) *ResponseMatcher { r.mux.mu.Lock() defer r.mux.mu.Unlock() r.h = h if !r.mux.res[r] { r.mux.res[r] = true } return r }
[ "func", "(", "r", "*", "ResponseMatcher", ")", "Handler", "(", "h", "Handler", ")", "*", "ResponseMatcher", "{", "r", ".", "mux", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "mux", ".", "mu", ".", "Unlock", "(", ")", "\n", "r", ".", "h", "=", "h", "\n", "if", "!", "r", ".", "mux", ".", "res", "[", "r", "]", "{", "r", ".", "mux", ".", "res", "[", "r", "]", "=", "true", "\n", "}", "\n", "return", "r", "\n", "}" ]
// Handler sets the Handler to be called when this Response Handler is the match for // a given response. It registers the Response Handler in its parent Mux.
[ "Handler", "sets", "the", "Handler", "to", "be", "called", "when", "this", "Response", "Handler", "is", "the", "match", "for", "a", "given", "response", ".", "It", "registers", "the", "Response", "Handler", "in", "its", "parent", "Mux", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/handler.go#L273-L281
15,226
PuerkitoBio/fetchbot
fetch.go
New
func New(h Handler) *Fetcher { return &Fetcher{ Handler: h, CrawlDelay: DefaultCrawlDelay, HttpClient: http.DefaultClient, UserAgent: DefaultUserAgent, WorkerIdleTTL: DefaultWorkerIdleTTL, dbg: make(chan *DebugInfo, 1), } }
go
func New(h Handler) *Fetcher { return &Fetcher{ Handler: h, CrawlDelay: DefaultCrawlDelay, HttpClient: http.DefaultClient, UserAgent: DefaultUserAgent, WorkerIdleTTL: DefaultWorkerIdleTTL, dbg: make(chan *DebugInfo, 1), } }
[ "func", "New", "(", "h", "Handler", ")", "*", "Fetcher", "{", "return", "&", "Fetcher", "{", "Handler", ":", "h", ",", "CrawlDelay", ":", "DefaultCrawlDelay", ",", "HttpClient", ":", "http", ".", "DefaultClient", ",", "UserAgent", ":", "DefaultUserAgent", ",", "WorkerIdleTTL", ":", "DefaultWorkerIdleTTL", ",", "dbg", ":", "make", "(", "chan", "*", "DebugInfo", ",", "1", ")", ",", "}", "\n", "}" ]
// New returns an initialized Fetcher.
[ "New", "returns", "an", "initialized", "Fetcher", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/fetch.go#L108-L117
15,227
PuerkitoBio/fetchbot
fetch.go
Close
func (q *Queue) Close() error { // Make sure it is not already closed, as this is a run-time panic select { case <-q.closed: // Already closed, no-op return nil default: // Close the signal-channel close(q.closed) // Send a nil Command to make sure the processQueue method sees the close signal. q.ch <- nil // Wait for the Fetcher to drain. q.wg.Wait() // Unblock any callers waiting on q.Block close(q.done) return nil } }
go
func (q *Queue) Close() error { // Make sure it is not already closed, as this is a run-time panic select { case <-q.closed: // Already closed, no-op return nil default: // Close the signal-channel close(q.closed) // Send a nil Command to make sure the processQueue method sees the close signal. q.ch <- nil // Wait for the Fetcher to drain. q.wg.Wait() // Unblock any callers waiting on q.Block close(q.done) return nil } }
[ "func", "(", "q", "*", "Queue", ")", "Close", "(", ")", "error", "{", "// Make sure it is not already closed, as this is a run-time panic", "select", "{", "case", "<-", "q", ".", "closed", ":", "// Already closed, no-op", "return", "nil", "\n", "default", ":", "// Close the signal-channel", "close", "(", "q", ".", "closed", ")", "\n", "// Send a nil Command to make sure the processQueue method sees the close signal.", "q", ".", "ch", "<-", "nil", "\n", "// Wait for the Fetcher to drain.", "q", ".", "wg", ".", "Wait", "(", ")", "\n", "// Unblock any callers waiting on q.Block", "close", "(", "q", ".", "done", ")", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Close closes the Queue so that no more Commands can be sent. It blocks until // the Fetcher drains all pending commands. After the call, the Fetcher is stopped. // Attempts to enqueue new URLs after Close has been called will always result in // a ErrQueueClosed error.
[ "Close", "closes", "the", "Queue", "so", "that", "no", "more", "Commands", "can", "be", "sent", ".", "It", "blocks", "until", "the", "Fetcher", "drains", "all", "pending", "commands", ".", "After", "the", "call", "the", "Fetcher", "is", "stopped", ".", "Attempts", "to", "enqueue", "new", "URLs", "after", "Close", "has", "been", "called", "will", "always", "result", "in", "a", "ErrQueueClosed", "error", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/fetch.go#L134-L151
15,228
PuerkitoBio/fetchbot
fetch.go
Cancel
func (q *Queue) Cancel() error { select { case <-q.cancelled: // already cancelled, no-op return nil default: // mark the queue as cancelled close(q.cancelled) // Close the Queue, that will wait for pending commands to drain // will unblock any callers waiting on q.Block return q.Close() } }
go
func (q *Queue) Cancel() error { select { case <-q.cancelled: // already cancelled, no-op return nil default: // mark the queue as cancelled close(q.cancelled) // Close the Queue, that will wait for pending commands to drain // will unblock any callers waiting on q.Block return q.Close() } }
[ "func", "(", "q", "*", "Queue", ")", "Cancel", "(", ")", "error", "{", "select", "{", "case", "<-", "q", ".", "cancelled", ":", "// already cancelled, no-op", "return", "nil", "\n", "default", ":", "// mark the queue as cancelled", "close", "(", "q", ".", "cancelled", ")", "\n", "// Close the Queue, that will wait for pending commands to drain", "// will unblock any callers waiting on q.Block", "return", "q", ".", "Close", "(", ")", "\n", "}", "\n", "}" ]
// Cancel closes the Queue and drains the pending commands without processing // them, allowing for a fast "stop immediately"-ish operation.
[ "Cancel", "closes", "the", "Queue", "and", "drains", "the", "pending", "commands", "without", "processing", "them", "allowing", "for", "a", "fast", "stop", "immediately", "-", "ish", "operation", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/fetch.go#L167-L179
15,229
PuerkitoBio/fetchbot
fetch.go
Send
func (q *Queue) Send(c Command) error { if c == nil { return ErrEmptyHost } if u := c.URL(); u == nil || u.Host == "" { return ErrEmptyHost } select { case <-q.closed: return ErrQueueClosed default: q.ch <- c } return nil }
go
func (q *Queue) Send(c Command) error { if c == nil { return ErrEmptyHost } if u := c.URL(); u == nil || u.Host == "" { return ErrEmptyHost } select { case <-q.closed: return ErrQueueClosed default: q.ch <- c } return nil }
[ "func", "(", "q", "*", "Queue", ")", "Send", "(", "c", "Command", ")", "error", "{", "if", "c", "==", "nil", "{", "return", "ErrEmptyHost", "\n", "}", "\n", "if", "u", ":=", "c", ".", "URL", "(", ")", ";", "u", "==", "nil", "||", "u", ".", "Host", "==", "\"", "\"", "{", "return", "ErrEmptyHost", "\n", "}", "\n", "select", "{", "case", "<-", "q", ".", "closed", ":", "return", "ErrQueueClosed", "\n", "default", ":", "q", ".", "ch", "<-", "c", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Send enqueues a Command into the Fetcher. If the Queue has been closed, it // returns ErrQueueClosed. The Command's URL must have a Host.
[ "Send", "enqueues", "a", "Command", "into", "the", "Fetcher", ".", "If", "the", "Queue", "has", "been", "closed", "it", "returns", "ErrQueueClosed", ".", "The", "Command", "s", "URL", "must", "have", "a", "Host", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/fetch.go#L183-L197
15,230
PuerkitoBio/fetchbot
fetch.go
SendString
func (q *Queue) SendString(method string, rawurl ...string) (int, error) { return q.sendWithMethod(method, rawurl) }
go
func (q *Queue) SendString(method string, rawurl ...string) (int, error) { return q.sendWithMethod(method, rawurl) }
[ "func", "(", "q", "*", "Queue", ")", "SendString", "(", "method", "string", ",", "rawurl", "...", "string", ")", "(", "int", ",", "error", ")", "{", "return", "q", ".", "sendWithMethod", "(", "method", ",", "rawurl", ")", "\n", "}" ]
// SendString enqueues a method and some URL strings into the Fetcher. It returns an error // if the URL string cannot be parsed, or if the Queue has been closed. // The first return value is the number of URLs successfully enqueued.
[ "SendString", "enqueues", "a", "method", "and", "some", "URL", "strings", "into", "the", "Fetcher", ".", "It", "returns", "an", "error", "if", "the", "URL", "string", "cannot", "be", "parsed", "or", "if", "the", "Queue", "has", "been", "closed", ".", "The", "first", "return", "value", "is", "the", "number", "of", "URLs", "successfully", "enqueued", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/fetch.go#L202-L204
15,231
PuerkitoBio/fetchbot
fetch.go
SendStringHead
func (q *Queue) SendStringHead(rawurl ...string) (int, error) { return q.sendWithMethod("HEAD", rawurl) }
go
func (q *Queue) SendStringHead(rawurl ...string) (int, error) { return q.sendWithMethod("HEAD", rawurl) }
[ "func", "(", "q", "*", "Queue", ")", "SendStringHead", "(", "rawurl", "...", "string", ")", "(", "int", ",", "error", ")", "{", "return", "q", ".", "sendWithMethod", "(", "\"", "\"", ",", "rawurl", ")", "\n", "}" ]
// SendStringHead enqueues the URL strings to be fetched with a HEAD method. // It returns an error if the URL string cannot be parsed, or if the Queue has been closed. // The first return value is the number of URLs successfully enqueued.
[ "SendStringHead", "enqueues", "the", "URL", "strings", "to", "be", "fetched", "with", "a", "HEAD", "method", ".", "It", "returns", "an", "error", "if", "the", "URL", "string", "cannot", "be", "parsed", "or", "if", "the", "Queue", "has", "been", "closed", ".", "The", "first", "return", "value", "is", "the", "number", "of", "URLs", "successfully", "enqueued", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/fetch.go#L209-L211
15,232
PuerkitoBio/fetchbot
fetch.go
SendStringGet
func (q *Queue) SendStringGet(rawurl ...string) (int, error) { return q.sendWithMethod("GET", rawurl) }
go
func (q *Queue) SendStringGet(rawurl ...string) (int, error) { return q.sendWithMethod("GET", rawurl) }
[ "func", "(", "q", "*", "Queue", ")", "SendStringGet", "(", "rawurl", "...", "string", ")", "(", "int", ",", "error", ")", "{", "return", "q", ".", "sendWithMethod", "(", "\"", "\"", ",", "rawurl", ")", "\n", "}" ]
// SendStringGet enqueues the URL strings to be fetched with a GET method. // It returns an error if the URL string cannot be parsed, or if the Queue has been closed. // The first return value is the number of URLs successfully enqueued.
[ "SendStringGet", "enqueues", "the", "URL", "strings", "to", "be", "fetched", "with", "a", "GET", "method", ".", "It", "returns", "an", "error", "if", "the", "URL", "string", "cannot", "be", "parsed", "or", "if", "the", "Queue", "has", "been", "closed", ".", "The", "first", "return", "value", "is", "the", "number", "of", "URLs", "successfully", "enqueued", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/fetch.go#L216-L218
15,233
PuerkitoBio/fetchbot
fetch.go
Start
func (f *Fetcher) Start() *Queue { f.hosts = make(map[string]chan Command) f.q = &Queue{ ch: make(chan Command, 1), closed: make(chan struct{}), cancelled: make(chan struct{}), done: make(chan struct{}), } // Start the one and only queue processing goroutine. f.q.wg.Add(1) go f.processQueue() return f.q }
go
func (f *Fetcher) Start() *Queue { f.hosts = make(map[string]chan Command) f.q = &Queue{ ch: make(chan Command, 1), closed: make(chan struct{}), cancelled: make(chan struct{}), done: make(chan struct{}), } // Start the one and only queue processing goroutine. f.q.wg.Add(1) go f.processQueue() return f.q }
[ "func", "(", "f", "*", "Fetcher", ")", "Start", "(", ")", "*", "Queue", "{", "f", ".", "hosts", "=", "make", "(", "map", "[", "string", "]", "chan", "Command", ")", "\n\n", "f", ".", "q", "=", "&", "Queue", "{", "ch", ":", "make", "(", "chan", "Command", ",", "1", ")", ",", "closed", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "cancelled", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "done", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n\n", "// Start the one and only queue processing goroutine.", "f", ".", "q", ".", "wg", ".", "Add", "(", "1", ")", "\n", "go", "f", ".", "processQueue", "(", ")", "\n\n", "return", "f", ".", "q", "\n", "}" ]
// Start starts the Fetcher, and returns the Queue to use to send Commands to be fetched.
[ "Start", "starts", "the", "Fetcher", "and", "returns", "the", "Queue", "to", "use", "to", "send", "Commands", "to", "be", "fetched", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/fetch.go#L237-L252
15,234
PuerkitoBio/fetchbot
fetch.go
Debug
func (f *Fetcher) Debug() <-chan *DebugInfo { f.dbgmu.Lock() defer f.dbgmu.Unlock() f.debugging = true return f.dbg }
go
func (f *Fetcher) Debug() <-chan *DebugInfo { f.dbgmu.Lock() defer f.dbgmu.Unlock() f.debugging = true return f.dbg }
[ "func", "(", "f", "*", "Fetcher", ")", "Debug", "(", ")", "<-", "chan", "*", "DebugInfo", "{", "f", ".", "dbgmu", ".", "Lock", "(", ")", "\n", "defer", "f", ".", "dbgmu", ".", "Unlock", "(", ")", "\n", "f", ".", "debugging", "=", "true", "\n", "return", "f", ".", "dbg", "\n", "}" ]
// Debug returns the channel to use to receive the debugging information. It is not intended // to be used by package users.
[ "Debug", "returns", "the", "channel", "to", "use", "to", "receive", "the", "debugging", "information", ".", "It", "is", "not", "intended", "to", "be", "used", "by", "package", "users", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/fetch.go#L256-L261
15,235
PuerkitoBio/fetchbot
fetch.go
processQueue
func (f *Fetcher) processQueue() { loop: for v := range f.q.ch { if v == nil { // Special case, when the Queue is closed, a nil command is sent, use this // indicator to check for the closed signal, instead of looking on every loop. select { case <-f.q.closed: // Close signal, exit loop break loop default: // Keep going } } select { case <-f.q.cancelled: // queue got cancelled, drain continue default: // go on } // Get the URL to enqueue u := v.URL() // Check if a channel is already started for this host f.mu.Lock() in, ok := f.hosts[u.Host] if !ok { // Start a new channel and goroutine for this host. var rob *url.URL if !f.DisablePoliteness { // Must send the robots.txt request. rob = u.ResolveReference(robotsTxtParsedPath) } // Create the infinite queue: the in channel to send on, and the out channel // to read from in the host's goroutine, and add to the hosts map var out chan Command in, out = make(chan Command, 1), make(chan Command, 1) f.hosts[u.Host] = in f.mu.Unlock() f.q.wg.Add(1) // Start the infinite queue goroutine for this host go sliceIQ(in, out) // Start the working goroutine for this host go f.processChan(out, u.Host) if !f.DisablePoliteness { // Enqueue the robots.txt request first. in <- robotCommand{&Cmd{U: rob, M: "GET"}} } } else { f.mu.Unlock() } // Send the request in <- v // Send debug info, but do not block if full f.dbgmu.Lock() if f.debugging { f.mu.Lock() select { case f.dbg <- &DebugInfo{len(f.hosts)}: default: } f.mu.Unlock() } f.dbgmu.Unlock() } // Close all host channels now that it is impossible to send on those. Those are the `in` // channels of the infinite queue. It will then drain any pending events, triggering the // handlers for each in the worker goro, and then the infinite queue goro will terminate // and close the `out` channel, which in turn will terminate the worker goro. f.mu.Lock() for _, ch := range f.hosts { close(ch) } f.hosts = make(map[string]chan Command) f.mu.Unlock() f.q.wg.Done() }
go
func (f *Fetcher) processQueue() { loop: for v := range f.q.ch { if v == nil { // Special case, when the Queue is closed, a nil command is sent, use this // indicator to check for the closed signal, instead of looking on every loop. select { case <-f.q.closed: // Close signal, exit loop break loop default: // Keep going } } select { case <-f.q.cancelled: // queue got cancelled, drain continue default: // go on } // Get the URL to enqueue u := v.URL() // Check if a channel is already started for this host f.mu.Lock() in, ok := f.hosts[u.Host] if !ok { // Start a new channel and goroutine for this host. var rob *url.URL if !f.DisablePoliteness { // Must send the robots.txt request. rob = u.ResolveReference(robotsTxtParsedPath) } // Create the infinite queue: the in channel to send on, and the out channel // to read from in the host's goroutine, and add to the hosts map var out chan Command in, out = make(chan Command, 1), make(chan Command, 1) f.hosts[u.Host] = in f.mu.Unlock() f.q.wg.Add(1) // Start the infinite queue goroutine for this host go sliceIQ(in, out) // Start the working goroutine for this host go f.processChan(out, u.Host) if !f.DisablePoliteness { // Enqueue the robots.txt request first. in <- robotCommand{&Cmd{U: rob, M: "GET"}} } } else { f.mu.Unlock() } // Send the request in <- v // Send debug info, but do not block if full f.dbgmu.Lock() if f.debugging { f.mu.Lock() select { case f.dbg <- &DebugInfo{len(f.hosts)}: default: } f.mu.Unlock() } f.dbgmu.Unlock() } // Close all host channels now that it is impossible to send on those. Those are the `in` // channels of the infinite queue. It will then drain any pending events, triggering the // handlers for each in the worker goro, and then the infinite queue goro will terminate // and close the `out` channel, which in turn will terminate the worker goro. f.mu.Lock() for _, ch := range f.hosts { close(ch) } f.hosts = make(map[string]chan Command) f.mu.Unlock() f.q.wg.Done() }
[ "func", "(", "f", "*", "Fetcher", ")", "processQueue", "(", ")", "{", "loop", ":", "for", "v", ":=", "range", "f", ".", "q", ".", "ch", "{", "if", "v", "==", "nil", "{", "// Special case, when the Queue is closed, a nil command is sent, use this", "// indicator to check for the closed signal, instead of looking on every loop.", "select", "{", "case", "<-", "f", ".", "q", ".", "closed", ":", "// Close signal, exit loop", "break", "loop", "\n", "default", ":", "// Keep going", "}", "\n", "}", "\n", "select", "{", "case", "<-", "f", ".", "q", ".", "cancelled", ":", "// queue got cancelled, drain", "continue", "\n", "default", ":", "// go on", "}", "\n\n", "// Get the URL to enqueue", "u", ":=", "v", ".", "URL", "(", ")", "\n\n", "// Check if a channel is already started for this host", "f", ".", "mu", ".", "Lock", "(", ")", "\n", "in", ",", "ok", ":=", "f", ".", "hosts", "[", "u", ".", "Host", "]", "\n", "if", "!", "ok", "{", "// Start a new channel and goroutine for this host.", "var", "rob", "*", "url", ".", "URL", "\n", "if", "!", "f", ".", "DisablePoliteness", "{", "// Must send the robots.txt request.", "rob", "=", "u", ".", "ResolveReference", "(", "robotsTxtParsedPath", ")", "\n", "}", "\n\n", "// Create the infinite queue: the in channel to send on, and the out channel", "// to read from in the host's goroutine, and add to the hosts map", "var", "out", "chan", "Command", "\n", "in", ",", "out", "=", "make", "(", "chan", "Command", ",", "1", ")", ",", "make", "(", "chan", "Command", ",", "1", ")", "\n", "f", ".", "hosts", "[", "u", ".", "Host", "]", "=", "in", "\n", "f", ".", "mu", ".", "Unlock", "(", ")", "\n", "f", ".", "q", ".", "wg", ".", "Add", "(", "1", ")", "\n", "// Start the infinite queue goroutine for this host", "go", "sliceIQ", "(", "in", ",", "out", ")", "\n", "// Start the working goroutine for this host", "go", "f", ".", "processChan", "(", "out", ",", "u", ".", "Host", ")", "\n\n", "if", "!", "f", ".", "DisablePoliteness", "{", "// Enqueue the robots.txt request first.", "in", "<-", "robotCommand", "{", "&", "Cmd", "{", "U", ":", "rob", ",", "M", ":", "\"", "\"", "}", "}", "\n", "}", "\n", "}", "else", "{", "f", ".", "mu", ".", "Unlock", "(", ")", "\n", "}", "\n", "// Send the request", "in", "<-", "v", "\n\n", "// Send debug info, but do not block if full", "f", ".", "dbgmu", ".", "Lock", "(", ")", "\n", "if", "f", ".", "debugging", "{", "f", ".", "mu", ".", "Lock", "(", ")", "\n", "select", "{", "case", "f", ".", "dbg", "<-", "&", "DebugInfo", "{", "len", "(", "f", ".", "hosts", ")", "}", ":", "default", ":", "}", "\n", "f", ".", "mu", ".", "Unlock", "(", ")", "\n", "}", "\n", "f", ".", "dbgmu", ".", "Unlock", "(", ")", "\n", "}", "\n\n", "// Close all host channels now that it is impossible to send on those. Those are the `in`", "// channels of the infinite queue. It will then drain any pending events, triggering the", "// handlers for each in the worker goro, and then the infinite queue goro will terminate", "// and close the `out` channel, which in turn will terminate the worker goro.", "f", ".", "mu", ".", "Lock", "(", ")", "\n", "for", "_", ",", "ch", ":=", "range", "f", ".", "hosts", "{", "close", "(", "ch", ")", "\n", "}", "\n", "f", ".", "hosts", "=", "make", "(", "map", "[", "string", "]", "chan", "Command", ")", "\n", "f", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "f", ".", "q", ".", "wg", ".", "Done", "(", ")", "\n", "}" ]
// processQueue runs the queue in its own goroutine.
[ "processQueue", "runs", "the", "queue", "in", "its", "own", "goroutine", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/fetch.go#L264-L348
15,236
PuerkitoBio/fetchbot
fetch.go
processChan
func (f *Fetcher) processChan(ch <-chan Command, hostKey string) { var ( agent *robotstxt.Group wait <-chan time.Time ttl <-chan time.Time delay = f.CrawlDelay ) loop: for { select { case <-f.q.cancelled: break loop case v, ok := <-ch: if !ok { // Terminate this goroutine, channel is closed break loop } // Wait for the prescribed delay if wait != nil { <-wait } // was it cancelled during the wait? check again select { case <-f.q.cancelled: break loop default: // go on } switch r, ok := v.(robotCommand); { case ok: // This is the robots.txt request agent = f.getRobotAgent(r) // Initialize the crawl delay if agent != nil && agent.CrawlDelay > 0 { delay = agent.CrawlDelay } wait = time.After(delay) case agent == nil || agent.Test(v.URL().Path): // Path allowed, process the request res, err := f.doRequest(v) f.visit(v, res, err) // No delay on error - the remote host was not reached if err == nil { wait = time.After(delay) } else { wait = nil } default: // Path disallowed by robots.txt f.visit(v, nil, ErrDisallowed) wait = nil } // Every time a command is received, reset the ttl channel ttl = time.After(f.WorkerIdleTTL) case <-ttl: // Worker has been idle for WorkerIdleTTL, terminate it f.mu.Lock() inch, ok := f.hosts[hostKey] delete(f.hosts, hostKey) // Close the queue if AutoClose is set and there are no more hosts. if f.AutoClose && len(f.hosts) == 0 { go f.q.Close() } f.mu.Unlock() if ok { close(inch) } break loop } } // need to drain ch until it is closed, to prevent the producer goroutine // from leaking. for _ = range ch { } f.q.wg.Done() }
go
func (f *Fetcher) processChan(ch <-chan Command, hostKey string) { var ( agent *robotstxt.Group wait <-chan time.Time ttl <-chan time.Time delay = f.CrawlDelay ) loop: for { select { case <-f.q.cancelled: break loop case v, ok := <-ch: if !ok { // Terminate this goroutine, channel is closed break loop } // Wait for the prescribed delay if wait != nil { <-wait } // was it cancelled during the wait? check again select { case <-f.q.cancelled: break loop default: // go on } switch r, ok := v.(robotCommand); { case ok: // This is the robots.txt request agent = f.getRobotAgent(r) // Initialize the crawl delay if agent != nil && agent.CrawlDelay > 0 { delay = agent.CrawlDelay } wait = time.After(delay) case agent == nil || agent.Test(v.URL().Path): // Path allowed, process the request res, err := f.doRequest(v) f.visit(v, res, err) // No delay on error - the remote host was not reached if err == nil { wait = time.After(delay) } else { wait = nil } default: // Path disallowed by robots.txt f.visit(v, nil, ErrDisallowed) wait = nil } // Every time a command is received, reset the ttl channel ttl = time.After(f.WorkerIdleTTL) case <-ttl: // Worker has been idle for WorkerIdleTTL, terminate it f.mu.Lock() inch, ok := f.hosts[hostKey] delete(f.hosts, hostKey) // Close the queue if AutoClose is set and there are no more hosts. if f.AutoClose && len(f.hosts) == 0 { go f.q.Close() } f.mu.Unlock() if ok { close(inch) } break loop } } // need to drain ch until it is closed, to prevent the producer goroutine // from leaking. for _ = range ch { } f.q.wg.Done() }
[ "func", "(", "f", "*", "Fetcher", ")", "processChan", "(", "ch", "<-", "chan", "Command", ",", "hostKey", "string", ")", "{", "var", "(", "agent", "*", "robotstxt", ".", "Group", "\n", "wait", "<-", "chan", "time", ".", "Time", "\n", "ttl", "<-", "chan", "time", ".", "Time", "\n", "delay", "=", "f", ".", "CrawlDelay", "\n", ")", "\n\n", "loop", ":", "for", "{", "select", "{", "case", "<-", "f", ".", "q", ".", "cancelled", ":", "break", "loop", "\n", "case", "v", ",", "ok", ":=", "<-", "ch", ":", "if", "!", "ok", "{", "// Terminate this goroutine, channel is closed", "break", "loop", "\n", "}", "\n\n", "// Wait for the prescribed delay", "if", "wait", "!=", "nil", "{", "<-", "wait", "\n", "}", "\n\n", "// was it cancelled during the wait? check again", "select", "{", "case", "<-", "f", ".", "q", ".", "cancelled", ":", "break", "loop", "\n", "default", ":", "// go on", "}", "\n\n", "switch", "r", ",", "ok", ":=", "v", ".", "(", "robotCommand", ")", ";", "{", "case", "ok", ":", "// This is the robots.txt request", "agent", "=", "f", ".", "getRobotAgent", "(", "r", ")", "\n", "// Initialize the crawl delay", "if", "agent", "!=", "nil", "&&", "agent", ".", "CrawlDelay", ">", "0", "{", "delay", "=", "agent", ".", "CrawlDelay", "\n", "}", "\n", "wait", "=", "time", ".", "After", "(", "delay", ")", "\n\n", "case", "agent", "==", "nil", "||", "agent", ".", "Test", "(", "v", ".", "URL", "(", ")", ".", "Path", ")", ":", "// Path allowed, process the request", "res", ",", "err", ":=", "f", ".", "doRequest", "(", "v", ")", "\n", "f", ".", "visit", "(", "v", ",", "res", ",", "err", ")", "\n", "// No delay on error - the remote host was not reached", "if", "err", "==", "nil", "{", "wait", "=", "time", ".", "After", "(", "delay", ")", "\n", "}", "else", "{", "wait", "=", "nil", "\n", "}", "\n\n", "default", ":", "// Path disallowed by robots.txt", "f", ".", "visit", "(", "v", ",", "nil", ",", "ErrDisallowed", ")", "\n", "wait", "=", "nil", "\n", "}", "\n", "// Every time a command is received, reset the ttl channel", "ttl", "=", "time", ".", "After", "(", "f", ".", "WorkerIdleTTL", ")", "\n\n", "case", "<-", "ttl", ":", "// Worker has been idle for WorkerIdleTTL, terminate it", "f", ".", "mu", ".", "Lock", "(", ")", "\n", "inch", ",", "ok", ":=", "f", ".", "hosts", "[", "hostKey", "]", "\n", "delete", "(", "f", ".", "hosts", ",", "hostKey", ")", "\n\n", "// Close the queue if AutoClose is set and there are no more hosts.", "if", "f", ".", "AutoClose", "&&", "len", "(", "f", ".", "hosts", ")", "==", "0", "{", "go", "f", ".", "q", ".", "Close", "(", ")", "\n", "}", "\n", "f", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "ok", "{", "close", "(", "inch", ")", "\n", "}", "\n", "break", "loop", "\n", "}", "\n", "}", "\n\n", "// need to drain ch until it is closed, to prevent the producer goroutine", "// from leaking.", "for", "_", "=", "range", "ch", "{", "}", "\n\n", "f", ".", "q", ".", "wg", ".", "Done", "(", ")", "\n", "}" ]
// Goroutine for a host's worker, processing requests for all its URLs.
[ "Goroutine", "for", "a", "host", "s", "worker", "processing", "requests", "for", "all", "its", "URLs", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/fetch.go#L351-L436
15,237
PuerkitoBio/fetchbot
fetch.go
getRobotAgent
func (f *Fetcher) getRobotAgent(r robotCommand) *robotstxt.Group { res, err := f.doRequest(r) if err != nil { // TODO: Ignore robots.txt request error? fmt.Fprintf(os.Stderr, "fetchbot: error fetching robots.txt: %s\n", err) return nil } if res.Body != nil { defer res.Body.Close() } robData, err := robotstxt.FromResponse(res) if err != nil { // TODO : Ignore robots.txt parse error? fmt.Fprintf(os.Stderr, "fetchbot: error parsing robots.txt: %s\n", err) return nil } return robData.FindGroup(f.UserAgent) }
go
func (f *Fetcher) getRobotAgent(r robotCommand) *robotstxt.Group { res, err := f.doRequest(r) if err != nil { // TODO: Ignore robots.txt request error? fmt.Fprintf(os.Stderr, "fetchbot: error fetching robots.txt: %s\n", err) return nil } if res.Body != nil { defer res.Body.Close() } robData, err := robotstxt.FromResponse(res) if err != nil { // TODO : Ignore robots.txt parse error? fmt.Fprintf(os.Stderr, "fetchbot: error parsing robots.txt: %s\n", err) return nil } return robData.FindGroup(f.UserAgent) }
[ "func", "(", "f", "*", "Fetcher", ")", "getRobotAgent", "(", "r", "robotCommand", ")", "*", "robotstxt", ".", "Group", "{", "res", ",", "err", ":=", "f", ".", "doRequest", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "// TODO: Ignore robots.txt request error?", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\n", "\"", ",", "err", ")", "\n", "return", "nil", "\n", "}", "\n", "if", "res", ".", "Body", "!=", "nil", "{", "defer", "res", ".", "Body", ".", "Close", "(", ")", "\n", "}", "\n", "robData", ",", "err", ":=", "robotstxt", ".", "FromResponse", "(", "res", ")", "\n", "if", "err", "!=", "nil", "{", "// TODO : Ignore robots.txt parse error?", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\n", "\"", ",", "err", ")", "\n", "return", "nil", "\n", "}", "\n", "return", "robData", ".", "FindGroup", "(", "f", ".", "UserAgent", ")", "\n", "}" ]
// Get the robots.txt User-Agent-specific group.
[ "Get", "the", "robots", ".", "txt", "User", "-", "Agent", "-", "specific", "group", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/fetch.go#L439-L456
15,238
PuerkitoBio/fetchbot
fetch.go
visit
func (f *Fetcher) visit(cmd Command, res *http.Response, err error) { if res != nil && res.Body != nil { defer res.Body.Close() } // if the Command implements Handler, call that handler, otherwise // dispatch to the Fetcher's Handler. if h, ok := cmd.(Handler); ok { h.Handle(&Context{Cmd: cmd, Q: f.q}, res, err) return } f.Handler.Handle(&Context{Cmd: cmd, Q: f.q}, res, err) }
go
func (f *Fetcher) visit(cmd Command, res *http.Response, err error) { if res != nil && res.Body != nil { defer res.Body.Close() } // if the Command implements Handler, call that handler, otherwise // dispatch to the Fetcher's Handler. if h, ok := cmd.(Handler); ok { h.Handle(&Context{Cmd: cmd, Q: f.q}, res, err) return } f.Handler.Handle(&Context{Cmd: cmd, Q: f.q}, res, err) }
[ "func", "(", "f", "*", "Fetcher", ")", "visit", "(", "cmd", "Command", ",", "res", "*", "http", ".", "Response", ",", "err", "error", ")", "{", "if", "res", "!=", "nil", "&&", "res", ".", "Body", "!=", "nil", "{", "defer", "res", ".", "Body", ".", "Close", "(", ")", "\n", "}", "\n", "// if the Command implements Handler, call that handler, otherwise", "// dispatch to the Fetcher's Handler.", "if", "h", ",", "ok", ":=", "cmd", ".", "(", "Handler", ")", ";", "ok", "{", "h", ".", "Handle", "(", "&", "Context", "{", "Cmd", ":", "cmd", ",", "Q", ":", "f", ".", "q", "}", ",", "res", ",", "err", ")", "\n", "return", "\n", "}", "\n", "f", ".", "Handler", ".", "Handle", "(", "&", "Context", "{", "Cmd", ":", "cmd", ",", "Q", ":", "f", ".", "q", "}", ",", "res", ",", "err", ")", "\n", "}" ]
// Call the Handler for this Command. Closes the response's body.
[ "Call", "the", "Handler", "for", "this", "Command", ".", "Closes", "the", "response", "s", "body", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/fetch.go#L459-L470
15,239
PuerkitoBio/fetchbot
fetch.go
doRequest
func (f *Fetcher) doRequest(cmd Command) (*http.Response, error) { req, err := http.NewRequest(cmd.Method(), cmd.URL().String(), nil) if err != nil { return nil, err } // If the Command implements some other recognized interfaces, set // the request accordingly (see cmd.go for the list of interfaces). // First, the Header values. if hd, ok := cmd.(HeaderProvider); ok { for k, v := range hd.Header() { req.Header[k] = v } } // BasicAuth has higher priority than an Authorization header set by // a HeaderProvider. if ba, ok := cmd.(BasicAuthProvider); ok { req.SetBasicAuth(ba.BasicAuth()) } // Cookies are added to the request, even if some cookies were set // by a HeaderProvider. if ck, ok := cmd.(CookiesProvider); ok { for _, c := range ck.Cookies() { req.AddCookie(c) } } // For the body of the request, ReaderProvider has higher priority // than ValuesProvider. if rd, ok := cmd.(ReaderProvider); ok { rdr := rd.Reader() rc, ok := rdr.(io.ReadCloser) if !ok { rc = ioutil.NopCloser(rdr) } req.Body = rc } else if val, ok := cmd.(ValuesProvider); ok { v := val.Values() req.Body = ioutil.NopCloser(strings.NewReader(v.Encode())) if req.Header.Get("Content-Type") == "" { req.Header.Set("Content-Type", "application/x-www-form-urlencoded") } } // If there was no User-Agent implicitly set by the HeaderProvider, // set it to the default value. if req.Header.Get("User-Agent") == "" { req.Header.Set("User-Agent", f.UserAgent) } // Do the request. res, err := f.HttpClient.Do(req) if err != nil { return nil, err } return res, nil }
go
func (f *Fetcher) doRequest(cmd Command) (*http.Response, error) { req, err := http.NewRequest(cmd.Method(), cmd.URL().String(), nil) if err != nil { return nil, err } // If the Command implements some other recognized interfaces, set // the request accordingly (see cmd.go for the list of interfaces). // First, the Header values. if hd, ok := cmd.(HeaderProvider); ok { for k, v := range hd.Header() { req.Header[k] = v } } // BasicAuth has higher priority than an Authorization header set by // a HeaderProvider. if ba, ok := cmd.(BasicAuthProvider); ok { req.SetBasicAuth(ba.BasicAuth()) } // Cookies are added to the request, even if some cookies were set // by a HeaderProvider. if ck, ok := cmd.(CookiesProvider); ok { for _, c := range ck.Cookies() { req.AddCookie(c) } } // For the body of the request, ReaderProvider has higher priority // than ValuesProvider. if rd, ok := cmd.(ReaderProvider); ok { rdr := rd.Reader() rc, ok := rdr.(io.ReadCloser) if !ok { rc = ioutil.NopCloser(rdr) } req.Body = rc } else if val, ok := cmd.(ValuesProvider); ok { v := val.Values() req.Body = ioutil.NopCloser(strings.NewReader(v.Encode())) if req.Header.Get("Content-Type") == "" { req.Header.Set("Content-Type", "application/x-www-form-urlencoded") } } // If there was no User-Agent implicitly set by the HeaderProvider, // set it to the default value. if req.Header.Get("User-Agent") == "" { req.Header.Set("User-Agent", f.UserAgent) } // Do the request. res, err := f.HttpClient.Do(req) if err != nil { return nil, err } return res, nil }
[ "func", "(", "f", "*", "Fetcher", ")", "doRequest", "(", "cmd", "Command", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "cmd", ".", "Method", "(", ")", ",", "cmd", ".", "URL", "(", ")", ".", "String", "(", ")", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// If the Command implements some other recognized interfaces, set", "// the request accordingly (see cmd.go for the list of interfaces).", "// First, the Header values.", "if", "hd", ",", "ok", ":=", "cmd", ".", "(", "HeaderProvider", ")", ";", "ok", "{", "for", "k", ",", "v", ":=", "range", "hd", ".", "Header", "(", ")", "{", "req", ".", "Header", "[", "k", "]", "=", "v", "\n", "}", "\n", "}", "\n", "// BasicAuth has higher priority than an Authorization header set by", "// a HeaderProvider.", "if", "ba", ",", "ok", ":=", "cmd", ".", "(", "BasicAuthProvider", ")", ";", "ok", "{", "req", ".", "SetBasicAuth", "(", "ba", ".", "BasicAuth", "(", ")", ")", "\n", "}", "\n", "// Cookies are added to the request, even if some cookies were set", "// by a HeaderProvider.", "if", "ck", ",", "ok", ":=", "cmd", ".", "(", "CookiesProvider", ")", ";", "ok", "{", "for", "_", ",", "c", ":=", "range", "ck", ".", "Cookies", "(", ")", "{", "req", ".", "AddCookie", "(", "c", ")", "\n", "}", "\n", "}", "\n", "// For the body of the request, ReaderProvider has higher priority", "// than ValuesProvider.", "if", "rd", ",", "ok", ":=", "cmd", ".", "(", "ReaderProvider", ")", ";", "ok", "{", "rdr", ":=", "rd", ".", "Reader", "(", ")", "\n", "rc", ",", "ok", ":=", "rdr", ".", "(", "io", ".", "ReadCloser", ")", "\n", "if", "!", "ok", "{", "rc", "=", "ioutil", ".", "NopCloser", "(", "rdr", ")", "\n", "}", "\n", "req", ".", "Body", "=", "rc", "\n", "}", "else", "if", "val", ",", "ok", ":=", "cmd", ".", "(", "ValuesProvider", ")", ";", "ok", "{", "v", ":=", "val", ".", "Values", "(", ")", "\n", "req", ".", "Body", "=", "ioutil", ".", "NopCloser", "(", "strings", ".", "NewReader", "(", "v", ".", "Encode", "(", ")", ")", ")", "\n", "if", "req", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "==", "\"", "\"", "{", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "// If there was no User-Agent implicitly set by the HeaderProvider,", "// set it to the default value.", "if", "req", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "==", "\"", "\"", "{", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "f", ".", "UserAgent", ")", "\n", "}", "\n", "// Do the request.", "res", ",", "err", ":=", "f", ".", "HttpClient", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "res", ",", "nil", "\n", "}" ]
// Prepare and execute the request for this Command.
[ "Prepare", "and", "execute", "the", "request", "for", "this", "Command", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/fetch.go#L473-L525
15,240
PuerkitoBio/fetchbot
iq_slice.go
sliceIQ
func sliceIQ(in <-chan Command, next chan<- Command) { defer close(next) // pending events (this is the "infinite" part) pending := []Command{} recv: for { // Ensure that pending always has values so the select can // multiplex between the receiver and sender properly if len(pending) == 0 { v, ok := <-in if !ok { // in is closed, flush values break } // We now have something to send pending = append(pending, v) } select { // Queue incoming values case v, ok := <-in: if !ok { // in is closed, flush values break recv } pending = append(pending, v) // Send queued values case next <- pending[0]: pending[0] = nil pending = pending[1:] } } // After in is closed, we may still have events to send for _, v := range pending { next <- v } }
go
func sliceIQ(in <-chan Command, next chan<- Command) { defer close(next) // pending events (this is the "infinite" part) pending := []Command{} recv: for { // Ensure that pending always has values so the select can // multiplex between the receiver and sender properly if len(pending) == 0 { v, ok := <-in if !ok { // in is closed, flush values break } // We now have something to send pending = append(pending, v) } select { // Queue incoming values case v, ok := <-in: if !ok { // in is closed, flush values break recv } pending = append(pending, v) // Send queued values case next <- pending[0]: pending[0] = nil pending = pending[1:] } } // After in is closed, we may still have events to send for _, v := range pending { next <- v } }
[ "func", "sliceIQ", "(", "in", "<-", "chan", "Command", ",", "next", "chan", "<-", "Command", ")", "{", "defer", "close", "(", "next", ")", "\n\n", "// pending events (this is the \"infinite\" part)", "pending", ":=", "[", "]", "Command", "{", "}", "\n\n", "recv", ":", "for", "{", "// Ensure that pending always has values so the select can", "// multiplex between the receiver and sender properly", "if", "len", "(", "pending", ")", "==", "0", "{", "v", ",", "ok", ":=", "<-", "in", "\n", "if", "!", "ok", "{", "// in is closed, flush values", "break", "\n", "}", "\n\n", "// We now have something to send", "pending", "=", "append", "(", "pending", ",", "v", ")", "\n", "}", "\n\n", "select", "{", "// Queue incoming values", "case", "v", ",", "ok", ":=", "<-", "in", ":", "if", "!", "ok", "{", "// in is closed, flush values", "break", "recv", "\n", "}", "\n", "pending", "=", "append", "(", "pending", ",", "v", ")", "\n\n", "// Send queued values", "case", "next", "<-", "pending", "[", "0", "]", ":", "pending", "[", "0", "]", "=", "nil", "\n", "pending", "=", "pending", "[", "1", ":", "]", "\n", "}", "\n", "}", "\n\n", "// After in is closed, we may still have events to send", "for", "_", ",", "v", ":=", "range", "pending", "{", "next", "<-", "v", "\n", "}", "\n", "}" ]
// sliceIQ creates an infinite buffered channel taking input on // in and sending output to next. SliceIQ should be run in its // own goroutine.
[ "sliceIQ", "creates", "an", "infinite", "buffered", "channel", "taking", "input", "on", "in", "and", "sending", "output", "to", "next", ".", "SliceIQ", "should", "be", "run", "in", "its", "own", "goroutine", "." ]
1f502d610659b899a007858812b601e715f531eb
https://github.com/PuerkitoBio/fetchbot/blob/1f502d610659b899a007858812b601e715f531eb/iq_slice.go#L28-L69
15,241
oleiade/lane
pqueue.go
NewPQueue
func NewPQueue(pqType PQType) *PQueue { var cmp func(int, int) bool if pqType == MAXPQ { cmp = max } else { cmp = min } items := make([]*item, 1) items[0] = nil // Heap queue first element should always be nil return &PQueue{ items: items, elemsCount: 0, comparator: cmp, } }
go
func NewPQueue(pqType PQType) *PQueue { var cmp func(int, int) bool if pqType == MAXPQ { cmp = max } else { cmp = min } items := make([]*item, 1) items[0] = nil // Heap queue first element should always be nil return &PQueue{ items: items, elemsCount: 0, comparator: cmp, } }
[ "func", "NewPQueue", "(", "pqType", "PQType", ")", "*", "PQueue", "{", "var", "cmp", "func", "(", "int", ",", "int", ")", "bool", "\n\n", "if", "pqType", "==", "MAXPQ", "{", "cmp", "=", "max", "\n", "}", "else", "{", "cmp", "=", "min", "\n", "}", "\n\n", "items", ":=", "make", "(", "[", "]", "*", "item", ",", "1", ")", "\n", "items", "[", "0", "]", "=", "nil", "// Heap queue first element should always be nil", "\n\n", "return", "&", "PQueue", "{", "items", ":", "items", ",", "elemsCount", ":", "0", ",", "comparator", ":", "cmp", ",", "}", "\n", "}" ]
// NewPQueue creates a new priority queue with the provided pqtype // ordering type
[ "NewPQueue", "creates", "a", "new", "priority", "queue", "with", "the", "provided", "pqtype", "ordering", "type" ]
3053869314bb02cb983dc2205da8ea2abe46fa96
https://github.com/oleiade/lane/blob/3053869314bb02cb983dc2205da8ea2abe46fa96/pqueue.go#L44-L61
15,242
oleiade/lane
pqueue.go
Push
func (pq *PQueue) Push(value interface{}, priority int) { item := newItem(value, priority) pq.Lock() pq.items = append(pq.items, item) pq.elemsCount += 1 pq.swim(pq.size()) pq.Unlock() }
go
func (pq *PQueue) Push(value interface{}, priority int) { item := newItem(value, priority) pq.Lock() pq.items = append(pq.items, item) pq.elemsCount += 1 pq.swim(pq.size()) pq.Unlock() }
[ "func", "(", "pq", "*", "PQueue", ")", "Push", "(", "value", "interface", "{", "}", ",", "priority", "int", ")", "{", "item", ":=", "newItem", "(", "value", ",", "priority", ")", "\n\n", "pq", ".", "Lock", "(", ")", "\n", "pq", ".", "items", "=", "append", "(", "pq", ".", "items", ",", "item", ")", "\n", "pq", ".", "elemsCount", "+=", "1", "\n", "pq", ".", "swim", "(", "pq", ".", "size", "(", ")", ")", "\n", "pq", ".", "Unlock", "(", ")", "\n", "}" ]
// Push the value item into the priority queue with provided priority.
[ "Push", "the", "value", "item", "into", "the", "priority", "queue", "with", "provided", "priority", "." ]
3053869314bb02cb983dc2205da8ea2abe46fa96
https://github.com/oleiade/lane/blob/3053869314bb02cb983dc2205da8ea2abe46fa96/pqueue.go#L64-L72
15,243
oleiade/lane
pqueue.go
Size
func (pq *PQueue) Size() int { pq.RLock() defer pq.RUnlock() return pq.size() }
go
func (pq *PQueue) Size() int { pq.RLock() defer pq.RUnlock() return pq.size() }
[ "func", "(", "pq", "*", "PQueue", ")", "Size", "(", ")", "int", "{", "pq", ".", "RLock", "(", ")", "\n", "defer", "pq", ".", "RUnlock", "(", ")", "\n", "return", "pq", ".", "size", "(", ")", "\n", "}" ]
// Size returns the elements present in the priority queue count
[ "Size", "returns", "the", "elements", "present", "in", "the", "priority", "queue", "count" ]
3053869314bb02cb983dc2205da8ea2abe46fa96
https://github.com/oleiade/lane/blob/3053869314bb02cb983dc2205da8ea2abe46fa96/pqueue.go#L111-L115
15,244
oleiade/lane
pqueue.go
Empty
func (pq *PQueue) Empty() bool { pq.RLock() defer pq.RUnlock() return pq.size() == 0 }
go
func (pq *PQueue) Empty() bool { pq.RLock() defer pq.RUnlock() return pq.size() == 0 }
[ "func", "(", "pq", "*", "PQueue", ")", "Empty", "(", ")", "bool", "{", "pq", ".", "RLock", "(", ")", "\n", "defer", "pq", ".", "RUnlock", "(", ")", "\n", "return", "pq", ".", "size", "(", ")", "==", "0", "\n", "}" ]
// Check queue is empty
[ "Check", "queue", "is", "empty" ]
3053869314bb02cb983dc2205da8ea2abe46fa96
https://github.com/oleiade/lane/blob/3053869314bb02cb983dc2205da8ea2abe46fa96/pqueue.go#L118-L122
15,245
oleiade/lane
deque.go
NewCappedDeque
func NewCappedDeque(capacity int) *Deque { return &Deque{ container: list.New(), capacity: capacity, } }
go
func NewCappedDeque(capacity int) *Deque { return &Deque{ container: list.New(), capacity: capacity, } }
[ "func", "NewCappedDeque", "(", "capacity", "int", ")", "*", "Deque", "{", "return", "&", "Deque", "{", "container", ":", "list", ".", "New", "(", ")", ",", "capacity", ":", "capacity", ",", "}", "\n", "}" ]
// NewCappedDeque creates a Deque with the specified capacity limit.
[ "NewCappedDeque", "creates", "a", "Deque", "with", "the", "specified", "capacity", "limit", "." ]
3053869314bb02cb983dc2205da8ea2abe46fa96
https://github.com/oleiade/lane/blob/3053869314bb02cb983dc2205da8ea2abe46fa96/deque.go#L26-L31
15,246
oleiade/lane
deque.go
Size
func (s *Deque) Size() int { s.RLock() defer s.RUnlock() return s.container.Len() }
go
func (s *Deque) Size() int { s.RLock() defer s.RUnlock() return s.container.Len() }
[ "func", "(", "s", "*", "Deque", ")", "Size", "(", ")", "int", "{", "s", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "RUnlock", "(", ")", "\n\n", "return", "s", ".", "container", ".", "Len", "(", ")", "\n", "}" ]
// Size returns the actual deque size
[ "Size", "returns", "the", "actual", "deque", "size" ]
3053869314bb02cb983dc2205da8ea2abe46fa96
https://github.com/oleiade/lane/blob/3053869314bb02cb983dc2205da8ea2abe46fa96/deque.go#L120-L125
15,247
oleiade/lane
deque.go
Capacity
func (s *Deque) Capacity() int { s.RLock() defer s.RUnlock() return s.capacity }
go
func (s *Deque) Capacity() int { s.RLock() defer s.RUnlock() return s.capacity }
[ "func", "(", "s", "*", "Deque", ")", "Capacity", "(", ")", "int", "{", "s", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "RUnlock", "(", ")", "\n", "return", "s", ".", "capacity", "\n", "}" ]
// Capacity returns the capacity of the deque, or -1 if unlimited
[ "Capacity", "returns", "the", "capacity", "of", "the", "deque", "or", "-", "1", "if", "unlimited" ]
3053869314bb02cb983dc2205da8ea2abe46fa96
https://github.com/oleiade/lane/blob/3053869314bb02cb983dc2205da8ea2abe46fa96/deque.go#L128-L132
15,248
oleiade/lane
deque.go
Empty
func (s *Deque) Empty() bool { s.RLock() defer s.RUnlock() return s.container.Len() == 0 }
go
func (s *Deque) Empty() bool { s.RLock() defer s.RUnlock() return s.container.Len() == 0 }
[ "func", "(", "s", "*", "Deque", ")", "Empty", "(", ")", "bool", "{", "s", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "RUnlock", "(", ")", "\n\n", "return", "s", ".", "container", ".", "Len", "(", ")", "==", "0", "\n", "}" ]
// Empty checks if the deque is empty
[ "Empty", "checks", "if", "the", "deque", "is", "empty" ]
3053869314bb02cb983dc2205da8ea2abe46fa96
https://github.com/oleiade/lane/blob/3053869314bb02cb983dc2205da8ea2abe46fa96/deque.go#L135-L140
15,249
oleiade/lane
deque.go
Full
func (s *Deque) Full() bool { s.RLock() defer s.RUnlock() return s.capacity >= 0 && s.container.Len() >= s.capacity }
go
func (s *Deque) Full() bool { s.RLock() defer s.RUnlock() return s.capacity >= 0 && s.container.Len() >= s.capacity }
[ "func", "(", "s", "*", "Deque", ")", "Full", "(", ")", "bool", "{", "s", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "RUnlock", "(", ")", "\n\n", "return", "s", ".", "capacity", ">=", "0", "&&", "s", ".", "container", ".", "Len", "(", ")", ">=", "s", ".", "capacity", "\n", "}" ]
// Full checks if the deque is full
[ "Full", "checks", "if", "the", "deque", "is", "full" ]
3053869314bb02cb983dc2205da8ea2abe46fa96
https://github.com/oleiade/lane/blob/3053869314bb02cb983dc2205da8ea2abe46fa96/deque.go#L143-L148
15,250
intelsdi-x/snap
mgmt/rest/v2/task.go
AddSchedulerTaskFromTask
func AddSchedulerTaskFromTask(t core.Task) Task { st := SchedulerTaskFromTask(t) (&st).assertSchedule(t.Schedule()) st.Workflow = t.WMap() return st }
go
func AddSchedulerTaskFromTask(t core.Task) Task { st := SchedulerTaskFromTask(t) (&st).assertSchedule(t.Schedule()) st.Workflow = t.WMap() return st }
[ "func", "AddSchedulerTaskFromTask", "(", "t", "core", ".", "Task", ")", "Task", "{", "st", ":=", "SchedulerTaskFromTask", "(", "t", ")", "\n", "(", "&", "st", ")", ".", "assertSchedule", "(", "t", ".", "Schedule", "(", ")", ")", "\n", "st", ".", "Workflow", "=", "t", ".", "WMap", "(", ")", "\n", "return", "st", "\n", "}" ]
// functions to convert a core.Task to a Task
[ "functions", "to", "convert", "a", "core", ".", "Task", "to", "a", "Task" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/mgmt/rest/v2/task.go#L236-L241
15,251
intelsdi-x/snap
control/plugin/client/grpc.go
SecurityTLSEnabled
func SecurityTLSEnabled(certPath, keyPath string, secureSide SecureSide) GRPCSecurity { return GRPCSecurity{ TLSEnabled: true, SecureSide: secureSide, TLSCertPath: certPath, TLSKeyPath: keyPath, } }
go
func SecurityTLSEnabled(certPath, keyPath string, secureSide SecureSide) GRPCSecurity { return GRPCSecurity{ TLSEnabled: true, SecureSide: secureSide, TLSCertPath: certPath, TLSKeyPath: keyPath, } }
[ "func", "SecurityTLSEnabled", "(", "certPath", ",", "keyPath", "string", ",", "secureSide", "SecureSide", ")", "GRPCSecurity", "{", "return", "GRPCSecurity", "{", "TLSEnabled", ":", "true", ",", "SecureSide", ":", "secureSide", ",", "TLSCertPath", ":", "certPath", ",", "TLSKeyPath", ":", "keyPath", ",", "}", "\n", "}" ]
// SecurityTLSEnabled generates security object for securing gRPC communication
[ "SecurityTLSEnabled", "generates", "security", "object", "for", "securing", "gRPC", "communication" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/client/grpc.go#L96-L103
15,252
intelsdi-x/snap
control/plugin/client/grpc.go
SecurityTLSExtended
func SecurityTLSExtended(certPath, keyPath string, secureSide SecureSide, caCertPaths []string) GRPCSecurity { return GRPCSecurity{ TLSEnabled: true, SecureSide: secureSide, TLSCertPath: certPath, TLSKeyPath: keyPath, CACertPaths: caCertPaths, } }
go
func SecurityTLSExtended(certPath, keyPath string, secureSide SecureSide, caCertPaths []string) GRPCSecurity { return GRPCSecurity{ TLSEnabled: true, SecureSide: secureSide, TLSCertPath: certPath, TLSKeyPath: keyPath, CACertPaths: caCertPaths, } }
[ "func", "SecurityTLSExtended", "(", "certPath", ",", "keyPath", "string", ",", "secureSide", "SecureSide", ",", "caCertPaths", "[", "]", "string", ")", "GRPCSecurity", "{", "return", "GRPCSecurity", "{", "TLSEnabled", ":", "true", ",", "SecureSide", ":", "secureSide", ",", "TLSCertPath", ":", "certPath", ",", "TLSKeyPath", ":", "keyPath", ",", "CACertPaths", ":", "caCertPaths", ",", "}", "\n", "}" ]
// SecurityTLSExtended generates security object for securing gRPC communication. // This function accepts also a list of CA cert paths for verifying TLS participant's // identity.
[ "SecurityTLSExtended", "generates", "security", "object", "for", "securing", "gRPC", "communication", ".", "This", "function", "accepts", "also", "a", "list", "of", "CA", "cert", "paths", "for", "verifying", "TLS", "participant", "s", "identity", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/client/grpc.go#L108-L116
15,253
intelsdi-x/snap
control/plugin/client/grpc.go
NewCollectorGrpcClient
func NewCollectorGrpcClient(address string, timeout time.Duration, security GRPCSecurity) (PluginCollectorClient, error) { ctx := context.Background() p, err := newPluginGrpcClient(ctx, address, timeout, security, plugin.CollectorPluginType) if err != nil { return nil, err } return p.(PluginCollectorClient), err }
go
func NewCollectorGrpcClient(address string, timeout time.Duration, security GRPCSecurity) (PluginCollectorClient, error) { ctx := context.Background() p, err := newPluginGrpcClient(ctx, address, timeout, security, plugin.CollectorPluginType) if err != nil { return nil, err } return p.(PluginCollectorClient), err }
[ "func", "NewCollectorGrpcClient", "(", "address", "string", ",", "timeout", "time", ".", "Duration", ",", "security", "GRPCSecurity", ")", "(", "PluginCollectorClient", ",", "error", ")", "{", "ctx", ":=", "context", ".", "Background", "(", ")", "\n", "p", ",", "err", ":=", "newPluginGrpcClient", "(", "ctx", ",", "address", ",", "timeout", ",", "security", ",", "plugin", ".", "CollectorPluginType", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "p", ".", "(", "PluginCollectorClient", ")", ",", "err", "\n", "}" ]
// NewCollectorGrpcClient returns a collector gRPC Client.
[ "NewCollectorGrpcClient", "returns", "a", "collector", "gRPC", "Client", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/client/grpc.go#L127-L134
15,254
intelsdi-x/snap
control/plugin/client/grpc.go
NewStreamCollectorGrpcClient
func NewStreamCollectorGrpcClient(address string, timeout time.Duration, security GRPCSecurity) (PluginStreamCollectorClient, error) { ctx := context.Background() p, err := newPluginGrpcClient(ctx, address, timeout, security, plugin.StreamCollectorPluginType) if err != nil { return nil, err } return p.(PluginStreamCollectorClient), nil }
go
func NewStreamCollectorGrpcClient(address string, timeout time.Duration, security GRPCSecurity) (PluginStreamCollectorClient, error) { ctx := context.Background() p, err := newPluginGrpcClient(ctx, address, timeout, security, plugin.StreamCollectorPluginType) if err != nil { return nil, err } return p.(PluginStreamCollectorClient), nil }
[ "func", "NewStreamCollectorGrpcClient", "(", "address", "string", ",", "timeout", "time", ".", "Duration", ",", "security", "GRPCSecurity", ")", "(", "PluginStreamCollectorClient", ",", "error", ")", "{", "ctx", ":=", "context", ".", "Background", "(", ")", "\n", "p", ",", "err", ":=", "newPluginGrpcClient", "(", "ctx", ",", "address", ",", "timeout", ",", "security", ",", "plugin", ".", "StreamCollectorPluginType", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "p", ".", "(", "PluginStreamCollectorClient", ")", ",", "nil", "\n", "}" ]
// NewStreamCollectorGrpcClient returns a stream collector gRPC client
[ "NewStreamCollectorGrpcClient", "returns", "a", "stream", "collector", "gRPC", "client" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/client/grpc.go#L137-L144
15,255
intelsdi-x/snap
control/plugin/client/grpc.go
NewProcessorGrpcClient
func NewProcessorGrpcClient(address string, timeout time.Duration, security GRPCSecurity) (PluginProcessorClient, error) { ctx := context.Background() p, err := newPluginGrpcClient(ctx, address, timeout, security, plugin.ProcessorPluginType) if err != nil { return nil, err } return p.(PluginProcessorClient), err }
go
func NewProcessorGrpcClient(address string, timeout time.Duration, security GRPCSecurity) (PluginProcessorClient, error) { ctx := context.Background() p, err := newPluginGrpcClient(ctx, address, timeout, security, plugin.ProcessorPluginType) if err != nil { return nil, err } return p.(PluginProcessorClient), err }
[ "func", "NewProcessorGrpcClient", "(", "address", "string", ",", "timeout", "time", ".", "Duration", ",", "security", "GRPCSecurity", ")", "(", "PluginProcessorClient", ",", "error", ")", "{", "ctx", ":=", "context", ".", "Background", "(", ")", "\n", "p", ",", "err", ":=", "newPluginGrpcClient", "(", "ctx", ",", "address", ",", "timeout", ",", "security", ",", "plugin", ".", "ProcessorPluginType", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "p", ".", "(", "PluginProcessorClient", ")", ",", "err", "\n", "}" ]
// NewProcessorGrpcClient returns a processor gRPC Client.
[ "NewProcessorGrpcClient", "returns", "a", "processor", "gRPC", "Client", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/client/grpc.go#L147-L154
15,256
intelsdi-x/snap
control/plugin/client/grpc.go
NewPublisherGrpcClient
func NewPublisherGrpcClient(address string, timeout time.Duration, security GRPCSecurity) (PluginPublisherClient, error) { ctx := context.Background() p, err := newPluginGrpcClient(ctx, address, timeout, security, plugin.PublisherPluginType) if err != nil { return nil, err } return p.(PluginPublisherClient), err }
go
func NewPublisherGrpcClient(address string, timeout time.Duration, security GRPCSecurity) (PluginPublisherClient, error) { ctx := context.Background() p, err := newPluginGrpcClient(ctx, address, timeout, security, plugin.PublisherPluginType) if err != nil { return nil, err } return p.(PluginPublisherClient), err }
[ "func", "NewPublisherGrpcClient", "(", "address", "string", ",", "timeout", "time", ".", "Duration", ",", "security", "GRPCSecurity", ")", "(", "PluginPublisherClient", ",", "error", ")", "{", "ctx", ":=", "context", ".", "Background", "(", ")", "\n", "p", ",", "err", ":=", "newPluginGrpcClient", "(", "ctx", ",", "address", ",", "timeout", ",", "security", ",", "plugin", ".", "PublisherPluginType", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "p", ".", "(", "PluginPublisherClient", ")", ",", "err", "\n", "}" ]
// NewPublisherGrpcClient returns a publisher gRPC Client.
[ "NewPublisherGrpcClient", "returns", "a", "publisher", "gRPC", "Client", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/client/grpc.go#L157-L164
15,257
intelsdi-x/snap
control/plugin/client/grpc.go
newPluginGrpcClient
func newPluginGrpcClient(ctx context.Context, address string, timeout time.Duration, security GRPCSecurity, typ plugin.PluginType) (interface{}, error) { address, port, err := parseAddress(address) if err != nil { return nil, err } var p *grpcClient var creds credentials.TransportCredentials if creds, err = buildCredentials(security); err != nil { return nil, err } p, err = newGrpcClient(ctx, address, int(port), timeout, typ, creds) if err != nil { return nil, err } return p, nil }
go
func newPluginGrpcClient(ctx context.Context, address string, timeout time.Duration, security GRPCSecurity, typ plugin.PluginType) (interface{}, error) { address, port, err := parseAddress(address) if err != nil { return nil, err } var p *grpcClient var creds credentials.TransportCredentials if creds, err = buildCredentials(security); err != nil { return nil, err } p, err = newGrpcClient(ctx, address, int(port), timeout, typ, creds) if err != nil { return nil, err } return p, nil }
[ "func", "newPluginGrpcClient", "(", "ctx", "context", ".", "Context", ",", "address", "string", ",", "timeout", "time", ".", "Duration", ",", "security", "GRPCSecurity", ",", "typ", "plugin", ".", "PluginType", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "address", ",", "port", ",", "err", ":=", "parseAddress", "(", "address", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "var", "p", "*", "grpcClient", "\n", "var", "creds", "credentials", ".", "TransportCredentials", "\n", "if", "creds", ",", "err", "=", "buildCredentials", "(", "security", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "p", ",", "err", "=", "newGrpcClient", "(", "ctx", ",", "address", ",", "int", "(", "port", ")", ",", "timeout", ",", "typ", ",", "creds", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "p", ",", "nil", "\n", "}" ]
// newPluginGrpcClient returns a configured gRPC Client.
[ "newPluginGrpcClient", "returns", "a", "configured", "gRPC", "Client", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/client/grpc.go#L258-L273
15,258
intelsdi-x/snap
plugin/collector/snap-plugin-collector-mock1/mock/mock.go
GetConfigPolicy
func (f *Mock) GetConfigPolicy() (*cpolicy.ConfigPolicy, error) { c := cpolicy.New() rule, _ := cpolicy.NewStringRule("name", false, "bob") rule2, _ := cpolicy.NewStringRule("password", true) p := cpolicy.NewPolicyNode() p.Add(rule) p.Add(rule2) c.Add([]string{"intel", "mock", "foo"}, p) return c, nil }
go
func (f *Mock) GetConfigPolicy() (*cpolicy.ConfigPolicy, error) { c := cpolicy.New() rule, _ := cpolicy.NewStringRule("name", false, "bob") rule2, _ := cpolicy.NewStringRule("password", true) p := cpolicy.NewPolicyNode() p.Add(rule) p.Add(rule2) c.Add([]string{"intel", "mock", "foo"}, p) return c, nil }
[ "func", "(", "f", "*", "Mock", ")", "GetConfigPolicy", "(", ")", "(", "*", "cpolicy", ".", "ConfigPolicy", ",", "error", ")", "{", "c", ":=", "cpolicy", ".", "New", "(", ")", "\n", "rule", ",", "_", ":=", "cpolicy", ".", "NewStringRule", "(", "\"", "\"", ",", "false", ",", "\"", "\"", ")", "\n", "rule2", ",", "_", ":=", "cpolicy", ".", "NewStringRule", "(", "\"", "\"", ",", "true", ")", "\n", "p", ":=", "cpolicy", ".", "NewPolicyNode", "(", ")", "\n", "p", ".", "Add", "(", "rule", ")", "\n", "p", ".", "Add", "(", "rule2", ")", "\n", "c", ".", "Add", "(", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", ",", "p", ")", "\n", "return", "c", ",", "nil", "\n", "}" ]
// GetConfigPolicy returns a ConfigPolicyTree for testing
[ "GetConfigPolicy", "returns", "a", "ConfigPolicyTree", "for", "testing" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/plugin/collector/snap-plugin-collector-mock1/mock/mock.go#L129-L138
15,259
intelsdi-x/snap
cmd/snaptel/main.go
beforeAction
func beforeAction(ctx *cli.Context) error { username, password := checkForAuth(ctx) pClient, err = client.New(ctx.String("url"), ctx.String("api-version"), ctx.Bool("insecure"), client.Timeout(ctx.Duration("timeout"))) if err != nil { return fmt.Errorf("%v", err) } pClient.Password = password pClient.Username = username if err = checkTribeCommand(ctx); err != nil { return fmt.Errorf("%v", err) } return nil }
go
func beforeAction(ctx *cli.Context) error { username, password := checkForAuth(ctx) pClient, err = client.New(ctx.String("url"), ctx.String("api-version"), ctx.Bool("insecure"), client.Timeout(ctx.Duration("timeout"))) if err != nil { return fmt.Errorf("%v", err) } pClient.Password = password pClient.Username = username if err = checkTribeCommand(ctx); err != nil { return fmt.Errorf("%v", err) } return nil }
[ "func", "beforeAction", "(", "ctx", "*", "cli", ".", "Context", ")", "error", "{", "username", ",", "password", ":=", "checkForAuth", "(", "ctx", ")", "\n", "pClient", ",", "err", "=", "client", ".", "New", "(", "ctx", ".", "String", "(", "\"", "\"", ")", ",", "ctx", ".", "String", "(", "\"", "\"", ")", ",", "ctx", ".", "Bool", "(", "\"", "\"", ")", ",", "client", ".", "Timeout", "(", "ctx", ".", "Duration", "(", "\"", "\"", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "pClient", ".", "Password", "=", "password", "\n", "pClient", ".", "Username", "=", "username", "\n", "if", "err", "=", "checkTribeCommand", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Run before every command
[ "Run", "before", "every", "command" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/cmd/snaptel/main.go#L80-L92
15,260
intelsdi-x/snap
cmd/snaptel/main.go
checkTribeCommand
func checkTribeCommand(ctx *cli.Context) error { tribe := false for _, a := range os.Args { for _, command := range tribeCommands { if strings.Contains(a, command.Name) { tribe = true break } } if tribe { break } } if !tribe { return nil } resp := pClient.ListAgreements() if resp.Err != nil { if resp.Err.Error() == "Invalid credentials" { return resp.Err } return fmt.Errorf("Tribe mode must be enabled in snapteld to use tribe command") } return nil }
go
func checkTribeCommand(ctx *cli.Context) error { tribe := false for _, a := range os.Args { for _, command := range tribeCommands { if strings.Contains(a, command.Name) { tribe = true break } } if tribe { break } } if !tribe { return nil } resp := pClient.ListAgreements() if resp.Err != nil { if resp.Err.Error() == "Invalid credentials" { return resp.Err } return fmt.Errorf("Tribe mode must be enabled in snapteld to use tribe command") } return nil }
[ "func", "checkTribeCommand", "(", "ctx", "*", "cli", ".", "Context", ")", "error", "{", "tribe", ":=", "false", "\n", "for", "_", ",", "a", ":=", "range", "os", ".", "Args", "{", "for", "_", ",", "command", ":=", "range", "tribeCommands", "{", "if", "strings", ".", "Contains", "(", "a", ",", "command", ".", "Name", ")", "{", "tribe", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "tribe", "{", "break", "\n", "}", "\n", "}", "\n", "if", "!", "tribe", "{", "return", "nil", "\n", "}", "\n", "resp", ":=", "pClient", ".", "ListAgreements", "(", ")", "\n", "if", "resp", ".", "Err", "!=", "nil", "{", "if", "resp", ".", "Err", ".", "Error", "(", ")", "==", "\"", "\"", "{", "return", "resp", ".", "Err", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Checks if a tribe command was issued when tribe mode was not // enabled on the specified snapteld instance.
[ "Checks", "if", "a", "tribe", "command", "was", "issued", "when", "tribe", "mode", "was", "not", "enabled", "on", "the", "specified", "snapteld", "instance", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/cmd/snaptel/main.go#L96-L120
15,261
intelsdi-x/snap
control/strategy/lru.go
Select
func (l *lru) Select(aps []AvailablePlugin, _ string) (AvailablePlugin, error) { t := time.Now() index := -1 for i, ap := range aps { // look for the least recently used if ap.LastHit().Before(t) || index == -1 { index = i t = ap.LastHit() } } if index > -1 { l.logger.WithFields(log.Fields{ "block": "select", "strategy": l.String(), "pool size": len(aps), "index": aps[index].String(), "hitcount": aps[index].HitCount(), }).Debug("plugin selected") return aps[index], nil } l.logger.WithFields(log.Fields{ "block": "select", "strategy": l.String(), "error": ErrCouldNotSelect, }).Error("error selecting") return nil, ErrCouldNotSelect }
go
func (l *lru) Select(aps []AvailablePlugin, _ string) (AvailablePlugin, error) { t := time.Now() index := -1 for i, ap := range aps { // look for the least recently used if ap.LastHit().Before(t) || index == -1 { index = i t = ap.LastHit() } } if index > -1 { l.logger.WithFields(log.Fields{ "block": "select", "strategy": l.String(), "pool size": len(aps), "index": aps[index].String(), "hitcount": aps[index].HitCount(), }).Debug("plugin selected") return aps[index], nil } l.logger.WithFields(log.Fields{ "block": "select", "strategy": l.String(), "error": ErrCouldNotSelect, }).Error("error selecting") return nil, ErrCouldNotSelect }
[ "func", "(", "l", "*", "lru", ")", "Select", "(", "aps", "[", "]", "AvailablePlugin", ",", "_", "string", ")", "(", "AvailablePlugin", ",", "error", ")", "{", "t", ":=", "time", ".", "Now", "(", ")", "\n", "index", ":=", "-", "1", "\n", "for", "i", ",", "ap", ":=", "range", "aps", "{", "// look for the least recently used", "if", "ap", ".", "LastHit", "(", ")", ".", "Before", "(", "t", ")", "||", "index", "==", "-", "1", "{", "index", "=", "i", "\n", "t", "=", "ap", ".", "LastHit", "(", ")", "\n", "}", "\n", "}", "\n", "if", "index", ">", "-", "1", "{", "l", ".", "logger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "l", ".", "String", "(", ")", ",", "\"", "\"", ":", "len", "(", "aps", ")", ",", "\"", "\"", ":", "aps", "[", "index", "]", ".", "String", "(", ")", ",", "\"", "\"", ":", "aps", "[", "index", "]", ".", "HitCount", "(", ")", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "return", "aps", "[", "index", "]", ",", "nil", "\n", "}", "\n", "l", ".", "logger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "l", ".", "String", "(", ")", ",", "\"", "\"", ":", "ErrCouldNotSelect", ",", "}", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "ErrCouldNotSelect", "\n", "}" ]
// Select selects an available plugin using the least-recently-used strategy.
[ "Select", "selects", "an", "available", "plugin", "using", "the", "least", "-", "recently", "-", "used", "strategy", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/strategy/lru.go#L55-L81
15,262
intelsdi-x/snap
control/strategy/lru.go
Remove
func (l *lru) Remove(aps []AvailablePlugin, taskID string) (AvailablePlugin, error) { ap, err := l.Select(aps, taskID) if err != nil { return nil, err } return ap, nil }
go
func (l *lru) Remove(aps []AvailablePlugin, taskID string) (AvailablePlugin, error) { ap, err := l.Select(aps, taskID) if err != nil { return nil, err } return ap, nil }
[ "func", "(", "l", "*", "lru", ")", "Remove", "(", "aps", "[", "]", "AvailablePlugin", ",", "taskID", "string", ")", "(", "AvailablePlugin", ",", "error", ")", "{", "ap", ",", "err", ":=", "l", ".", "Select", "(", "aps", ",", "taskID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "ap", ",", "nil", "\n", "}" ]
// Remove selects a plugin // Since there is no state to cleanup we only need to return the selected plugin
[ "Remove", "selects", "a", "plugin", "Since", "there", "is", "no", "state", "to", "cleanup", "we", "only", "need", "to", "return", "the", "selected", "plugin" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/strategy/lru.go#L85-L91
15,263
intelsdi-x/snap
mgmt/rest/client/tribe.go
ListMembers
func (c *Client) ListMembers() *ListMembersResult { resp, err := c.do("GET", "/tribe/members", ContentTypeJSON, nil) if err != nil { return &ListMembersResult{Err: err} } switch resp.Meta.Type { case rbody.TribeMemberListType: // Success return &ListMembersResult{resp.Body.(*rbody.TribeMemberList), nil} case rbody.ErrorType: return &ListMembersResult{Err: resp.Body.(*rbody.Error)} default: return &ListMembersResult{Err: ErrAPIResponseMetaType} } }
go
func (c *Client) ListMembers() *ListMembersResult { resp, err := c.do("GET", "/tribe/members", ContentTypeJSON, nil) if err != nil { return &ListMembersResult{Err: err} } switch resp.Meta.Type { case rbody.TribeMemberListType: // Success return &ListMembersResult{resp.Body.(*rbody.TribeMemberList), nil} case rbody.ErrorType: return &ListMembersResult{Err: resp.Body.(*rbody.Error)} default: return &ListMembersResult{Err: ErrAPIResponseMetaType} } }
[ "func", "(", "c", "*", "Client", ")", "ListMembers", "(", ")", "*", "ListMembersResult", "{", "resp", ",", "err", ":=", "c", ".", "do", "(", "\"", "\"", ",", "\"", "\"", ",", "ContentTypeJSON", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "ListMembersResult", "{", "Err", ":", "err", "}", "\n", "}", "\n", "switch", "resp", ".", "Meta", ".", "Type", "{", "case", "rbody", ".", "TribeMemberListType", ":", "// Success", "return", "&", "ListMembersResult", "{", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "TribeMemberList", ")", ",", "nil", "}", "\n", "case", "rbody", ".", "ErrorType", ":", "return", "&", "ListMembersResult", "{", "Err", ":", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "Error", ")", "}", "\n", "default", ":", "return", "&", "ListMembersResult", "{", "Err", ":", "ErrAPIResponseMetaType", "}", "\n", "}", "\n", "}" ]
// ListMembers retrieves a list of tribe members through an HTTP GET call. // A list of tribe member returns if it succeeds. Otherwise, an error is returned.
[ "ListMembers", "retrieves", "a", "list", "of", "tribe", "members", "through", "an", "HTTP", "GET", "call", ".", "A", "list", "of", "tribe", "member", "returns", "if", "it", "succeeds", ".", "Otherwise", "an", "error", "is", "returned", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/mgmt/rest/client/tribe.go#L31-L45
15,264
intelsdi-x/snap
mgmt/rest/client/tribe.go
GetMember
func (c *Client) GetMember(name string) *GetMemberResult { resp, err := c.do("GET", fmt.Sprintf("/tribe/member/%s", name), ContentTypeJSON, nil) if err != nil { return &GetMemberResult{Err: err} } switch resp.Meta.Type { case rbody.TribeMemberShowType: // Success return &GetMemberResult{resp.Body.(*rbody.TribeMemberShow), nil} case rbody.ErrorType: return &GetMemberResult{Err: resp.Body.(*rbody.Error)} default: return &GetMemberResult{Err: ErrAPIResponseMetaType} } }
go
func (c *Client) GetMember(name string) *GetMemberResult { resp, err := c.do("GET", fmt.Sprintf("/tribe/member/%s", name), ContentTypeJSON, nil) if err != nil { return &GetMemberResult{Err: err} } switch resp.Meta.Type { case rbody.TribeMemberShowType: // Success return &GetMemberResult{resp.Body.(*rbody.TribeMemberShow), nil} case rbody.ErrorType: return &GetMemberResult{Err: resp.Body.(*rbody.Error)} default: return &GetMemberResult{Err: ErrAPIResponseMetaType} } }
[ "func", "(", "c", "*", "Client", ")", "GetMember", "(", "name", "string", ")", "*", "GetMemberResult", "{", "resp", ",", "err", ":=", "c", ".", "do", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "name", ")", ",", "ContentTypeJSON", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "GetMemberResult", "{", "Err", ":", "err", "}", "\n", "}", "\n", "switch", "resp", ".", "Meta", ".", "Type", "{", "case", "rbody", ".", "TribeMemberShowType", ":", "// Success", "return", "&", "GetMemberResult", "{", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "TribeMemberShow", ")", ",", "nil", "}", "\n", "case", "rbody", ".", "ErrorType", ":", "return", "&", "GetMemberResult", "{", "Err", ":", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "Error", ")", "}", "\n", "default", ":", "return", "&", "GetMemberResult", "{", "Err", ":", "ErrAPIResponseMetaType", "}", "\n", "}", "\n", "}" ]
// GetMember retrieves the tribe member given a member name. // The request is an HTTP GET call. The corresponding tribe member object returns // if it succeeds. Otherwise, an error is returned.
[ "GetMember", "retrieves", "the", "tribe", "member", "given", "a", "member", "name", ".", "The", "request", "is", "an", "HTTP", "GET", "call", ".", "The", "corresponding", "tribe", "member", "object", "returns", "if", "it", "succeeds", ".", "Otherwise", "an", "error", "is", "returned", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/mgmt/rest/client/tribe.go#L50-L64
15,265
intelsdi-x/snap
mgmt/rest/client/tribe.go
ListAgreements
func (c *Client) ListAgreements() *ListAgreementResult { resp, err := c.do("GET", "/tribe/agreements", ContentTypeJSON, nil) if err != nil { return &ListAgreementResult{Err: err} } switch resp.Meta.Type { case rbody.TribeListAgreementType: return &ListAgreementResult{resp.Body.(*rbody.TribeListAgreement), nil} case rbody.ErrorType: return &ListAgreementResult{Err: resp.Body.(*rbody.Error)} default: return &ListAgreementResult{Err: ErrAPIResponseMetaType} } }
go
func (c *Client) ListAgreements() *ListAgreementResult { resp, err := c.do("GET", "/tribe/agreements", ContentTypeJSON, nil) if err != nil { return &ListAgreementResult{Err: err} } switch resp.Meta.Type { case rbody.TribeListAgreementType: return &ListAgreementResult{resp.Body.(*rbody.TribeListAgreement), nil} case rbody.ErrorType: return &ListAgreementResult{Err: resp.Body.(*rbody.Error)} default: return &ListAgreementResult{Err: ErrAPIResponseMetaType} } }
[ "func", "(", "c", "*", "Client", ")", "ListAgreements", "(", ")", "*", "ListAgreementResult", "{", "resp", ",", "err", ":=", "c", ".", "do", "(", "\"", "\"", ",", "\"", "\"", ",", "ContentTypeJSON", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "ListAgreementResult", "{", "Err", ":", "err", "}", "\n", "}", "\n", "switch", "resp", ".", "Meta", ".", "Type", "{", "case", "rbody", ".", "TribeListAgreementType", ":", "return", "&", "ListAgreementResult", "{", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "TribeListAgreement", ")", ",", "nil", "}", "\n", "case", "rbody", ".", "ErrorType", ":", "return", "&", "ListAgreementResult", "{", "Err", ":", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "Error", ")", "}", "\n", "default", ":", "return", "&", "ListAgreementResult", "{", "Err", ":", "ErrAPIResponseMetaType", "}", "\n", "}", "\n", "}" ]
// ListAgreements retrieves a list of a tribe agreements through an HTTP GET call. // A list of tribe agreement map returns if it succeeds. Otherwise, an error is returned.
[ "ListAgreements", "retrieves", "a", "list", "of", "a", "tribe", "agreements", "through", "an", "HTTP", "GET", "call", ".", "A", "list", "of", "tribe", "agreement", "map", "returns", "if", "it", "succeeds", ".", "Otherwise", "an", "error", "is", "returned", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/mgmt/rest/client/tribe.go#L68-L81
15,266
intelsdi-x/snap
mgmt/rest/client/tribe.go
AddAgreement
func (c *Client) AddAgreement(name string) *AddAgreementResult { b, err := json.Marshal(struct { Name string `json:"name"` }{Name: name}) if err != nil { return &AddAgreementResult{Err: err} } resp, err := c.do("POST", "/tribe/agreements", ContentTypeJSON, b) if err != nil { return &AddAgreementResult{Err: err} } switch resp.Meta.Type { case rbody.TribeAddAgreementType: return &AddAgreementResult{resp.Body.(*rbody.TribeAddAgreement), nil} case rbody.ErrorType: return &AddAgreementResult{Err: resp.Body.(*rbody.Error)} default: return &AddAgreementResult{Err: ErrAPIResponseMetaType} } }
go
func (c *Client) AddAgreement(name string) *AddAgreementResult { b, err := json.Marshal(struct { Name string `json:"name"` }{Name: name}) if err != nil { return &AddAgreementResult{Err: err} } resp, err := c.do("POST", "/tribe/agreements", ContentTypeJSON, b) if err != nil { return &AddAgreementResult{Err: err} } switch resp.Meta.Type { case rbody.TribeAddAgreementType: return &AddAgreementResult{resp.Body.(*rbody.TribeAddAgreement), nil} case rbody.ErrorType: return &AddAgreementResult{Err: resp.Body.(*rbody.Error)} default: return &AddAgreementResult{Err: ErrAPIResponseMetaType} } }
[ "func", "(", "c", "*", "Client", ")", "AddAgreement", "(", "name", "string", ")", "*", "AddAgreementResult", "{", "b", ",", "err", ":=", "json", ".", "Marshal", "(", "struct", "{", "Name", "string", "`json:\"name\"`", "\n", "}", "{", "Name", ":", "name", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "AddAgreementResult", "{", "Err", ":", "err", "}", "\n", "}", "\n", "resp", ",", "err", ":=", "c", ".", "do", "(", "\"", "\"", ",", "\"", "\"", ",", "ContentTypeJSON", ",", "b", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "AddAgreementResult", "{", "Err", ":", "err", "}", "\n", "}", "\n", "switch", "resp", ".", "Meta", ".", "Type", "{", "case", "rbody", ".", "TribeAddAgreementType", ":", "return", "&", "AddAgreementResult", "{", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "TribeAddAgreement", ")", ",", "nil", "}", "\n", "case", "rbody", ".", "ErrorType", ":", "return", "&", "AddAgreementResult", "{", "Err", ":", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "Error", ")", "}", "\n", "default", ":", "return", "&", "AddAgreementResult", "{", "Err", ":", "ErrAPIResponseMetaType", "}", "\n", "}", "\n", "}" ]
// AddAgreement adds a tribe agreement giving an agreement name into tribe agreement list // through an HTTP POST call. A map of tribe agreements with the newly added named agreement // returns if it succeeds. Otherwise, an error is returned. Note that the newly added agreement // has no effect unless members join the agreement.
[ "AddAgreement", "adds", "a", "tribe", "agreement", "giving", "an", "agreement", "name", "into", "tribe", "agreement", "list", "through", "an", "HTTP", "POST", "call", ".", "A", "map", "of", "tribe", "agreements", "with", "the", "newly", "added", "named", "agreement", "returns", "if", "it", "succeeds", ".", "Otherwise", "an", "error", "is", "returned", ".", "Note", "that", "the", "newly", "added", "agreement", "has", "no", "effect", "unless", "members", "join", "the", "agreement", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/mgmt/rest/client/tribe.go#L87-L106
15,267
intelsdi-x/snap
mgmt/rest/client/tribe.go
DeleteAgreement
func (c *Client) DeleteAgreement(name string) *DeleteAgreementResult { resp, err := c.do("DELETE", fmt.Sprintf("/tribe/agreements/%s", name), ContentTypeJSON, nil) if err != nil { return &DeleteAgreementResult{Err: err} } switch resp.Meta.Type { case rbody.TribeDeleteAgreementType: return &DeleteAgreementResult{resp.Body.(*rbody.TribeDeleteAgreement), nil} case rbody.ErrorType: return &DeleteAgreementResult{Err: resp.Body.(*rbody.Error)} default: return &DeleteAgreementResult{Err: ErrAPIResponseMetaType} } }
go
func (c *Client) DeleteAgreement(name string) *DeleteAgreementResult { resp, err := c.do("DELETE", fmt.Sprintf("/tribe/agreements/%s", name), ContentTypeJSON, nil) if err != nil { return &DeleteAgreementResult{Err: err} } switch resp.Meta.Type { case rbody.TribeDeleteAgreementType: return &DeleteAgreementResult{resp.Body.(*rbody.TribeDeleteAgreement), nil} case rbody.ErrorType: return &DeleteAgreementResult{Err: resp.Body.(*rbody.Error)} default: return &DeleteAgreementResult{Err: ErrAPIResponseMetaType} } }
[ "func", "(", "c", "*", "Client", ")", "DeleteAgreement", "(", "name", "string", ")", "*", "DeleteAgreementResult", "{", "resp", ",", "err", ":=", "c", ".", "do", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "name", ")", ",", "ContentTypeJSON", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "DeleteAgreementResult", "{", "Err", ":", "err", "}", "\n", "}", "\n", "switch", "resp", ".", "Meta", ".", "Type", "{", "case", "rbody", ".", "TribeDeleteAgreementType", ":", "return", "&", "DeleteAgreementResult", "{", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "TribeDeleteAgreement", ")", ",", "nil", "}", "\n", "case", "rbody", ".", "ErrorType", ":", "return", "&", "DeleteAgreementResult", "{", "Err", ":", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "Error", ")", "}", "\n", "default", ":", "return", "&", "DeleteAgreementResult", "{", "Err", ":", "ErrAPIResponseMetaType", "}", "\n", "}", "\n", "}" ]
// DeleteAgreement removes a tribe agreement giving an agreement name from the tribe agreement list // through an HTTP DELETE call. A map of tribe agreements with the specified agreement removed returns // if it succeeds. Otherwise, an error is returned. Note deleting an agreement removes the agreement // from the tribe entirely for all the members of the agreement.
[ "DeleteAgreement", "removes", "a", "tribe", "agreement", "giving", "an", "agreement", "name", "from", "the", "tribe", "agreement", "list", "through", "an", "HTTP", "DELETE", "call", ".", "A", "map", "of", "tribe", "agreements", "with", "the", "specified", "agreement", "removed", "returns", "if", "it", "succeeds", ".", "Otherwise", "an", "error", "is", "returned", ".", "Note", "deleting", "an", "agreement", "removes", "the", "agreement", "from", "the", "tribe", "entirely", "for", "all", "the", "members", "of", "the", "agreement", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/mgmt/rest/client/tribe.go#L112-L125
15,268
intelsdi-x/snap
mgmt/rest/client/tribe.go
GetAgreement
func (c *Client) GetAgreement(name string) *GetAgreementResult { resp, err := c.do("GET", fmt.Sprintf("/tribe/agreements/%s", name), ContentTypeJSON, nil) if err != nil { return &GetAgreementResult{Err: err} } switch resp.Meta.Type { case rbody.TribeGetAgreementType: return &GetAgreementResult{resp.Body.(*rbody.TribeGetAgreement), nil} case rbody.ErrorType: return &GetAgreementResult{Err: resp.Body.(*rbody.Error)} default: return &GetAgreementResult{Err: ErrAPIResponseMetaType} } }
go
func (c *Client) GetAgreement(name string) *GetAgreementResult { resp, err := c.do("GET", fmt.Sprintf("/tribe/agreements/%s", name), ContentTypeJSON, nil) if err != nil { return &GetAgreementResult{Err: err} } switch resp.Meta.Type { case rbody.TribeGetAgreementType: return &GetAgreementResult{resp.Body.(*rbody.TribeGetAgreement), nil} case rbody.ErrorType: return &GetAgreementResult{Err: resp.Body.(*rbody.Error)} default: return &GetAgreementResult{Err: ErrAPIResponseMetaType} } }
[ "func", "(", "c", "*", "Client", ")", "GetAgreement", "(", "name", "string", ")", "*", "GetAgreementResult", "{", "resp", ",", "err", ":=", "c", ".", "do", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "name", ")", ",", "ContentTypeJSON", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "GetAgreementResult", "{", "Err", ":", "err", "}", "\n", "}", "\n", "switch", "resp", ".", "Meta", ".", "Type", "{", "case", "rbody", ".", "TribeGetAgreementType", ":", "return", "&", "GetAgreementResult", "{", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "TribeGetAgreement", ")", ",", "nil", "}", "\n", "case", "rbody", ".", "ErrorType", ":", "return", "&", "GetAgreementResult", "{", "Err", ":", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "Error", ")", "}", "\n", "default", ":", "return", "&", "GetAgreementResult", "{", "Err", ":", "ErrAPIResponseMetaType", "}", "\n", "}", "\n", "}" ]
// GetAgreement retrieves a tribe agreement given an agreement name through an HTTP GET call. // A tribe agreement returns if it succeeded. Otherwise, an error is returned.
[ "GetAgreement", "retrieves", "a", "tribe", "agreement", "given", "an", "agreement", "name", "through", "an", "HTTP", "GET", "call", ".", "A", "tribe", "agreement", "returns", "if", "it", "succeeded", ".", "Otherwise", "an", "error", "is", "returned", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/mgmt/rest/client/tribe.go#L129-L142
15,269
intelsdi-x/snap
mgmt/rest/client/tribe.go
JoinAgreement
func (c *Client) JoinAgreement(agreementName, memberName string) *JoinAgreementResult { b, err := json.Marshal(struct { MemberName string `json:"member_name"` }{MemberName: memberName}) if err != nil { return &JoinAgreementResult{Err: err} } resp, err := c.do("PUT", fmt.Sprintf("/tribe/agreements/%s/join", agreementName), ContentTypeJSON, b) if err != nil { return &JoinAgreementResult{Err: err} } switch resp.Meta.Type { case rbody.TribeJoinAgreementType: return &JoinAgreementResult{resp.Body.(*rbody.TribeJoinAgreement), nil} case rbody.ErrorType: return &JoinAgreementResult{Err: resp.Body.(*rbody.Error)} default: return &JoinAgreementResult{Err: ErrAPIResponseMetaType} } }
go
func (c *Client) JoinAgreement(agreementName, memberName string) *JoinAgreementResult { b, err := json.Marshal(struct { MemberName string `json:"member_name"` }{MemberName: memberName}) if err != nil { return &JoinAgreementResult{Err: err} } resp, err := c.do("PUT", fmt.Sprintf("/tribe/agreements/%s/join", agreementName), ContentTypeJSON, b) if err != nil { return &JoinAgreementResult{Err: err} } switch resp.Meta.Type { case rbody.TribeJoinAgreementType: return &JoinAgreementResult{resp.Body.(*rbody.TribeJoinAgreement), nil} case rbody.ErrorType: return &JoinAgreementResult{Err: resp.Body.(*rbody.Error)} default: return &JoinAgreementResult{Err: ErrAPIResponseMetaType} } }
[ "func", "(", "c", "*", "Client", ")", "JoinAgreement", "(", "agreementName", ",", "memberName", "string", ")", "*", "JoinAgreementResult", "{", "b", ",", "err", ":=", "json", ".", "Marshal", "(", "struct", "{", "MemberName", "string", "`json:\"member_name\"`", "\n", "}", "{", "MemberName", ":", "memberName", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "JoinAgreementResult", "{", "Err", ":", "err", "}", "\n", "}", "\n", "resp", ",", "err", ":=", "c", ".", "do", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "agreementName", ")", ",", "ContentTypeJSON", ",", "b", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "JoinAgreementResult", "{", "Err", ":", "err", "}", "\n", "}", "\n", "switch", "resp", ".", "Meta", ".", "Type", "{", "case", "rbody", ".", "TribeJoinAgreementType", ":", "return", "&", "JoinAgreementResult", "{", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "TribeJoinAgreement", ")", ",", "nil", "}", "\n", "case", "rbody", ".", "ErrorType", ":", "return", "&", "JoinAgreementResult", "{", "Err", ":", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "Error", ")", "}", "\n", "default", ":", "return", "&", "JoinAgreementResult", "{", "Err", ":", "ErrAPIResponseMetaType", "}", "\n", "}", "\n", "}" ]
// JoinAgreement adds a tribe member into the agreement given the agreement name and the member name. // It is an HTTP PUT request. The agreement with the newly added member returns if it succeeds. // Otherwise, an error is returned. Note that dual directional agreement replication happens automatically // through the gossip protocol between a newly joined member and existing members within the same agreement.
[ "JoinAgreement", "adds", "a", "tribe", "member", "into", "the", "agreement", "given", "the", "agreement", "name", "and", "the", "member", "name", ".", "It", "is", "an", "HTTP", "PUT", "request", ".", "The", "agreement", "with", "the", "newly", "added", "member", "returns", "if", "it", "succeeds", ".", "Otherwise", "an", "error", "is", "returned", ".", "Note", "that", "dual", "directional", "agreement", "replication", "happens", "automatically", "through", "the", "gossip", "protocol", "between", "a", "newly", "joined", "member", "and", "existing", "members", "within", "the", "same", "agreement", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/mgmt/rest/client/tribe.go#L148-L167
15,270
intelsdi-x/snap
mgmt/rest/client/tribe.go
LeaveAgreement
func (c *Client) LeaveAgreement(agreementName, memberName string) *LeaveAgreementResult { b, err := json.Marshal(struct { MemberName string `json:"member_name"` }{MemberName: memberName}) if err != nil { return &LeaveAgreementResult{Err: err} } resp, err := c.do("DELETE", fmt.Sprintf("/tribe/agreements/%s/leave", agreementName), ContentTypeJSON, b) if err != nil { return &LeaveAgreementResult{Err: err} } switch resp.Meta.Type { case rbody.TribeLeaveAgreementType: return &LeaveAgreementResult{resp.Body.(*rbody.TribeLeaveAgreement), nil} case rbody.ErrorType: return &LeaveAgreementResult{Err: resp.Body.(*rbody.Error)} default: return &LeaveAgreementResult{Err: ErrAPIResponseMetaType} } }
go
func (c *Client) LeaveAgreement(agreementName, memberName string) *LeaveAgreementResult { b, err := json.Marshal(struct { MemberName string `json:"member_name"` }{MemberName: memberName}) if err != nil { return &LeaveAgreementResult{Err: err} } resp, err := c.do("DELETE", fmt.Sprintf("/tribe/agreements/%s/leave", agreementName), ContentTypeJSON, b) if err != nil { return &LeaveAgreementResult{Err: err} } switch resp.Meta.Type { case rbody.TribeLeaveAgreementType: return &LeaveAgreementResult{resp.Body.(*rbody.TribeLeaveAgreement), nil} case rbody.ErrorType: return &LeaveAgreementResult{Err: resp.Body.(*rbody.Error)} default: return &LeaveAgreementResult{Err: ErrAPIResponseMetaType} } }
[ "func", "(", "c", "*", "Client", ")", "LeaveAgreement", "(", "agreementName", ",", "memberName", "string", ")", "*", "LeaveAgreementResult", "{", "b", ",", "err", ":=", "json", ".", "Marshal", "(", "struct", "{", "MemberName", "string", "`json:\"member_name\"`", "\n", "}", "{", "MemberName", ":", "memberName", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "LeaveAgreementResult", "{", "Err", ":", "err", "}", "\n", "}", "\n", "resp", ",", "err", ":=", "c", ".", "do", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "agreementName", ")", ",", "ContentTypeJSON", ",", "b", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "LeaveAgreementResult", "{", "Err", ":", "err", "}", "\n", "}", "\n", "switch", "resp", ".", "Meta", ".", "Type", "{", "case", "rbody", ".", "TribeLeaveAgreementType", ":", "return", "&", "LeaveAgreementResult", "{", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "TribeLeaveAgreement", ")", ",", "nil", "}", "\n", "case", "rbody", ".", "ErrorType", ":", "return", "&", "LeaveAgreementResult", "{", "Err", ":", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "Error", ")", "}", "\n", "default", ":", "return", "&", "LeaveAgreementResult", "{", "Err", ":", "ErrAPIResponseMetaType", "}", "\n", "}", "\n", "}" ]
// LeaveAgreement removes a member from the agreement given the agreement and member names through // an HTTP DELETE call. The agreement with the removed member returns if it succeeds. // Otherwise, an error is returned. For example, it is useful to leave an agreement for a member node repair.
[ "LeaveAgreement", "removes", "a", "member", "from", "the", "agreement", "given", "the", "agreement", "and", "member", "names", "through", "an", "HTTP", "DELETE", "call", ".", "The", "agreement", "with", "the", "removed", "member", "returns", "if", "it", "succeeds", ".", "Otherwise", "an", "error", "is", "returned", ".", "For", "example", "it", "is", "useful", "to", "leave", "an", "agreement", "for", "a", "member", "node", "repair", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/mgmt/rest/client/tribe.go#L172-L191
15,271
intelsdi-x/snap
grpc/common/common.go
ToNamespace
func ToNamespace(n core.Namespace) []*NamespaceElement { elements := make([]*NamespaceElement, 0, len(n)) for _, value := range n { ne := &NamespaceElement{ Value: value.Value, Description: value.Description, Name: value.Name, } elements = append(elements, ne) } return elements }
go
func ToNamespace(n core.Namespace) []*NamespaceElement { elements := make([]*NamespaceElement, 0, len(n)) for _, value := range n { ne := &NamespaceElement{ Value: value.Value, Description: value.Description, Name: value.Name, } elements = append(elements, ne) } return elements }
[ "func", "ToNamespace", "(", "n", "core", ".", "Namespace", ")", "[", "]", "*", "NamespaceElement", "{", "elements", ":=", "make", "(", "[", "]", "*", "NamespaceElement", ",", "0", ",", "len", "(", "n", ")", ")", "\n", "for", "_", ",", "value", ":=", "range", "n", "{", "ne", ":=", "&", "NamespaceElement", "{", "Value", ":", "value", ".", "Value", ",", "Description", ":", "value", ".", "Description", ",", "Name", ":", "value", ".", "Name", ",", "}", "\n", "elements", "=", "append", "(", "elements", ",", "ne", ")", "\n", "}", "\n", "return", "elements", "\n", "}" ]
// Convert core.Namespace to common.Namespace protobuf message
[ "Convert", "core", ".", "Namespace", "to", "common", ".", "Namespace", "protobuf", "message" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/grpc/common/common.go#L83-L94
15,272
intelsdi-x/snap
grpc/common/common.go
ToCoreMetric
func ToCoreMetric(mt *Metric) core.Metric { var lastAdvertisedTime time.Time // if the lastAdvertisedTime is not set we handle. -62135596800 represents the // number of seconds from 0001-1970 and is the default value for time.Unix. if mt.LastAdvertisedTime.Sec == int64(-62135596800) { lastAdvertisedTime = time.Unix(time.Now().Unix(), int64(time.Now().Nanosecond())) } else { lastAdvertisedTime = time.Unix(mt.LastAdvertisedTime.Sec, mt.LastAdvertisedTime.Nsec) } ret := &metric{ namespace: ToCoreNamespace(mt.Namespace), version: int(mt.Version), tags: mt.Tags, timeStamp: time.Unix(mt.Timestamp.Sec, mt.Timestamp.Nsec), lastAdvertisedTime: lastAdvertisedTime, config: ConfigMapToConfig(mt.Config), description: mt.Description, unit: mt.Unit, } switch mt.Data.(type) { case *Metric_BytesData: ret.data = mt.GetBytesData() case *Metric_StringData: ret.data = mt.GetStringData() case *Metric_Float32Data: ret.data = mt.GetFloat32Data() case *Metric_Float64Data: ret.data = mt.GetFloat64Data() case *Metric_Int32Data: ret.data = mt.GetInt32Data() case *Metric_Int64Data: ret.data = mt.GetInt64Data() case *Metric_Uint32Data: ret.data = mt.GetUint32Data() case *Metric_Uint64Data: ret.data = mt.GetUint64Data() case *Metric_BoolData: ret.data = mt.GetBoolData() } return ret }
go
func ToCoreMetric(mt *Metric) core.Metric { var lastAdvertisedTime time.Time // if the lastAdvertisedTime is not set we handle. -62135596800 represents the // number of seconds from 0001-1970 and is the default value for time.Unix. if mt.LastAdvertisedTime.Sec == int64(-62135596800) { lastAdvertisedTime = time.Unix(time.Now().Unix(), int64(time.Now().Nanosecond())) } else { lastAdvertisedTime = time.Unix(mt.LastAdvertisedTime.Sec, mt.LastAdvertisedTime.Nsec) } ret := &metric{ namespace: ToCoreNamespace(mt.Namespace), version: int(mt.Version), tags: mt.Tags, timeStamp: time.Unix(mt.Timestamp.Sec, mt.Timestamp.Nsec), lastAdvertisedTime: lastAdvertisedTime, config: ConfigMapToConfig(mt.Config), description: mt.Description, unit: mt.Unit, } switch mt.Data.(type) { case *Metric_BytesData: ret.data = mt.GetBytesData() case *Metric_StringData: ret.data = mt.GetStringData() case *Metric_Float32Data: ret.data = mt.GetFloat32Data() case *Metric_Float64Data: ret.data = mt.GetFloat64Data() case *Metric_Int32Data: ret.data = mt.GetInt32Data() case *Metric_Int64Data: ret.data = mt.GetInt64Data() case *Metric_Uint32Data: ret.data = mt.GetUint32Data() case *Metric_Uint64Data: ret.data = mt.GetUint64Data() case *Metric_BoolData: ret.data = mt.GetBoolData() } return ret }
[ "func", "ToCoreMetric", "(", "mt", "*", "Metric", ")", "core", ".", "Metric", "{", "var", "lastAdvertisedTime", "time", ".", "Time", "\n", "// if the lastAdvertisedTime is not set we handle. -62135596800 represents the", "// number of seconds from 0001-1970 and is the default value for time.Unix.", "if", "mt", ".", "LastAdvertisedTime", ".", "Sec", "==", "int64", "(", "-", "62135596800", ")", "{", "lastAdvertisedTime", "=", "time", ".", "Unix", "(", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", ",", "int64", "(", "time", ".", "Now", "(", ")", ".", "Nanosecond", "(", ")", ")", ")", "\n", "}", "else", "{", "lastAdvertisedTime", "=", "time", ".", "Unix", "(", "mt", ".", "LastAdvertisedTime", ".", "Sec", ",", "mt", ".", "LastAdvertisedTime", ".", "Nsec", ")", "\n", "}", "\n", "ret", ":=", "&", "metric", "{", "namespace", ":", "ToCoreNamespace", "(", "mt", ".", "Namespace", ")", ",", "version", ":", "int", "(", "mt", ".", "Version", ")", ",", "tags", ":", "mt", ".", "Tags", ",", "timeStamp", ":", "time", ".", "Unix", "(", "mt", ".", "Timestamp", ".", "Sec", ",", "mt", ".", "Timestamp", ".", "Nsec", ")", ",", "lastAdvertisedTime", ":", "lastAdvertisedTime", ",", "config", ":", "ConfigMapToConfig", "(", "mt", ".", "Config", ")", ",", "description", ":", "mt", ".", "Description", ",", "unit", ":", "mt", ".", "Unit", ",", "}", "\n\n", "switch", "mt", ".", "Data", ".", "(", "type", ")", "{", "case", "*", "Metric_BytesData", ":", "ret", ".", "data", "=", "mt", ".", "GetBytesData", "(", ")", "\n", "case", "*", "Metric_StringData", ":", "ret", ".", "data", "=", "mt", ".", "GetStringData", "(", ")", "\n", "case", "*", "Metric_Float32Data", ":", "ret", ".", "data", "=", "mt", ".", "GetFloat32Data", "(", ")", "\n", "case", "*", "Metric_Float64Data", ":", "ret", ".", "data", "=", "mt", ".", "GetFloat64Data", "(", ")", "\n", "case", "*", "Metric_Int32Data", ":", "ret", ".", "data", "=", "mt", ".", "GetInt32Data", "(", ")", "\n", "case", "*", "Metric_Int64Data", ":", "ret", ".", "data", "=", "mt", ".", "GetInt64Data", "(", ")", "\n", "case", "*", "Metric_Uint32Data", ":", "ret", ".", "data", "=", "mt", ".", "GetUint32Data", "(", ")", "\n", "case", "*", "Metric_Uint64Data", ":", "ret", ".", "data", "=", "mt", ".", "GetUint64Data", "(", ")", "\n", "case", "*", "Metric_BoolData", ":", "ret", ".", "data", "=", "mt", ".", "GetBoolData", "(", ")", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// Convert common.Metric to core.Metric
[ "Convert", "common", ".", "Metric", "to", "core", ".", "Metric" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/grpc/common/common.go#L135-L176
15,273
intelsdi-x/snap
grpc/common/common.go
ToCoreNamespace
func ToCoreNamespace(n []*NamespaceElement) core.Namespace { var namespace core.Namespace for _, val := range n { ele := core.NamespaceElement{ Value: val.Value, Description: val.Description, Name: val.Name, } namespace = append(namespace, ele) } return namespace }
go
func ToCoreNamespace(n []*NamespaceElement) core.Namespace { var namespace core.Namespace for _, val := range n { ele := core.NamespaceElement{ Value: val.Value, Description: val.Description, Name: val.Name, } namespace = append(namespace, ele) } return namespace }
[ "func", "ToCoreNamespace", "(", "n", "[", "]", "*", "NamespaceElement", ")", "core", ".", "Namespace", "{", "var", "namespace", "core", ".", "Namespace", "\n", "for", "_", ",", "val", ":=", "range", "n", "{", "ele", ":=", "core", ".", "NamespaceElement", "{", "Value", ":", "val", ".", "Value", ",", "Description", ":", "val", ".", "Description", ",", "Name", ":", "val", ".", "Name", ",", "}", "\n", "namespace", "=", "append", "(", "namespace", ",", "ele", ")", "\n", "}", "\n", "return", "namespace", "\n", "}" ]
// Convert common.Namespace protobuf message to core.Namespace
[ "Convert", "common", ".", "Namespace", "protobuf", "message", "to", "core", ".", "Namespace" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/grpc/common/common.go#L191-L202
15,274
intelsdi-x/snap
grpc/common/common.go
ToSubPluginMsg
func ToSubPluginMsg(pl core.SubscribedPlugin) *SubscribedPlugin { return &SubscribedPlugin{ TypeName: pl.TypeName(), Name: pl.Name(), Version: int64(pl.Version()), Config: ConfigToConfigMap(pl.Config()), } }
go
func ToSubPluginMsg(pl core.SubscribedPlugin) *SubscribedPlugin { return &SubscribedPlugin{ TypeName: pl.TypeName(), Name: pl.Name(), Version: int64(pl.Version()), Config: ConfigToConfigMap(pl.Config()), } }
[ "func", "ToSubPluginMsg", "(", "pl", "core", ".", "SubscribedPlugin", ")", "*", "SubscribedPlugin", "{", "return", "&", "SubscribedPlugin", "{", "TypeName", ":", "pl", ".", "TypeName", "(", ")", ",", "Name", ":", "pl", ".", "Name", "(", ")", ",", "Version", ":", "int64", "(", "pl", ".", "Version", "(", ")", ")", ",", "Config", ":", "ConfigToConfigMap", "(", "pl", ".", "Config", "(", ")", ")", ",", "}", "\n", "}" ]
// Convert core.SubscribedPlugin to SubscribedPlugin protobuf message
[ "Convert", "core", ".", "SubscribedPlugin", "to", "SubscribedPlugin", "protobuf", "message" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/grpc/common/common.go#L283-L290
15,275
intelsdi-x/snap
grpc/common/common.go
ToSubPlugin
func ToSubPlugin(msg *SubscribedPlugin) core.SubscribedPlugin { return SubPlugin{ typeName: msg.TypeName, name: msg.Name, version: int(msg.Version), config: ConfigMapToConfig(msg.Config), } }
go
func ToSubPlugin(msg *SubscribedPlugin) core.SubscribedPlugin { return SubPlugin{ typeName: msg.TypeName, name: msg.Name, version: int(msg.Version), config: ConfigMapToConfig(msg.Config), } }
[ "func", "ToSubPlugin", "(", "msg", "*", "SubscribedPlugin", ")", "core", ".", "SubscribedPlugin", "{", "return", "SubPlugin", "{", "typeName", ":", "msg", ".", "TypeName", ",", "name", ":", "msg", ".", "Name", ",", "version", ":", "int", "(", "msg", ".", "Version", ")", ",", "config", ":", "ConfigMapToConfig", "(", "msg", ".", "Config", ")", ",", "}", "\n", "}" ]
// Convert from a SubscribedPlugin protobuf message to core.SubscribedPlugin
[ "Convert", "from", "a", "SubscribedPlugin", "protobuf", "message", "to", "core", ".", "SubscribedPlugin" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/grpc/common/common.go#L293-L300
15,276
intelsdi-x/snap
grpc/common/common.go
ToCorePluginMsg
func ToCorePluginMsg(pl core.Plugin) *Plugin { return &Plugin{ TypeName: pl.TypeName(), Name: pl.Name(), Version: int64(pl.Version()), } }
go
func ToCorePluginMsg(pl core.Plugin) *Plugin { return &Plugin{ TypeName: pl.TypeName(), Name: pl.Name(), Version: int64(pl.Version()), } }
[ "func", "ToCorePluginMsg", "(", "pl", "core", ".", "Plugin", ")", "*", "Plugin", "{", "return", "&", "Plugin", "{", "TypeName", ":", "pl", ".", "TypeName", "(", ")", ",", "Name", ":", "pl", ".", "Name", "(", ")", ",", "Version", ":", "int64", "(", "pl", ".", "Version", "(", ")", ")", ",", "}", "\n", "}" ]
// Convert from core.Plugin to Plugin protobuf message
[ "Convert", "from", "core", ".", "Plugin", "to", "Plugin", "protobuf", "message" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/grpc/common/common.go#L303-L309
15,277
intelsdi-x/snap
grpc/common/common.go
ToCorePluginsMsg
func ToCorePluginsMsg(pls []core.Plugin) []*Plugin { plugins := make([]*Plugin, len(pls)) for i, v := range pls { plugins[i] = ToCorePluginMsg(v) } return plugins }
go
func ToCorePluginsMsg(pls []core.Plugin) []*Plugin { plugins := make([]*Plugin, len(pls)) for i, v := range pls { plugins[i] = ToCorePluginMsg(v) } return plugins }
[ "func", "ToCorePluginsMsg", "(", "pls", "[", "]", "core", ".", "Plugin", ")", "[", "]", "*", "Plugin", "{", "plugins", ":=", "make", "(", "[", "]", "*", "Plugin", ",", "len", "(", "pls", ")", ")", "\n", "for", "i", ",", "v", ":=", "range", "pls", "{", "plugins", "[", "i", "]", "=", "ToCorePluginMsg", "(", "v", ")", "\n", "}", "\n", "return", "plugins", "\n", "}" ]
// Convert from Plugin protobuf message to core.Plugin
[ "Convert", "from", "Plugin", "protobuf", "message", "to", "core", ".", "Plugin" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/grpc/common/common.go#L312-L318
15,278
intelsdi-x/snap
grpc/common/common.go
MsgToCorePlugin
func MsgToCorePlugin(msg *Plugin) core.Plugin { pl := &SubPlugin{ typeName: msg.TypeName, name: msg.Name, version: int(msg.Version), } return core.Plugin(pl) }
go
func MsgToCorePlugin(msg *Plugin) core.Plugin { pl := &SubPlugin{ typeName: msg.TypeName, name: msg.Name, version: int(msg.Version), } return core.Plugin(pl) }
[ "func", "MsgToCorePlugin", "(", "msg", "*", "Plugin", ")", "core", ".", "Plugin", "{", "pl", ":=", "&", "SubPlugin", "{", "typeName", ":", "msg", ".", "TypeName", ",", "name", ":", "msg", ".", "Name", ",", "version", ":", "int", "(", "msg", ".", "Version", ")", ",", "}", "\n", "return", "core", ".", "Plugin", "(", "pl", ")", "\n", "}" ]
// Converts Plugin protobuf message to core.Plugin
[ "Converts", "Plugin", "protobuf", "message", "to", "core", ".", "Plugin" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/grpc/common/common.go#L321-L328
15,279
intelsdi-x/snap
grpc/common/common.go
MsgToCorePlugins
func MsgToCorePlugins(msg []*Plugin) []core.Plugin { plugins := make([]core.Plugin, len(msg)) for i, v := range msg { plugins[i] = MsgToCorePlugin(v) } return plugins }
go
func MsgToCorePlugins(msg []*Plugin) []core.Plugin { plugins := make([]core.Plugin, len(msg)) for i, v := range msg { plugins[i] = MsgToCorePlugin(v) } return plugins }
[ "func", "MsgToCorePlugins", "(", "msg", "[", "]", "*", "Plugin", ")", "[", "]", "core", ".", "Plugin", "{", "plugins", ":=", "make", "(", "[", "]", "core", ".", "Plugin", ",", "len", "(", "msg", ")", ")", "\n", "for", "i", ",", "v", ":=", "range", "msg", "{", "plugins", "[", "i", "]", "=", "MsgToCorePlugin", "(", "v", ")", "\n", "}", "\n", "return", "plugins", "\n", "}" ]
// Converts slice of plugin protobuf messages to core.Plugins
[ "Converts", "slice", "of", "plugin", "protobuf", "messages", "to", "core", ".", "Plugins" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/grpc/common/common.go#L331-L337
15,280
intelsdi-x/snap
grpc/common/common.go
ToSubPlugins
func ToSubPlugins(msg []*SubscribedPlugin) []core.SubscribedPlugin { plugins := make([]core.SubscribedPlugin, len(msg)) for i, v := range msg { plugins[i] = ToSubPlugin(v) } return plugins }
go
func ToSubPlugins(msg []*SubscribedPlugin) []core.SubscribedPlugin { plugins := make([]core.SubscribedPlugin, len(msg)) for i, v := range msg { plugins[i] = ToSubPlugin(v) } return plugins }
[ "func", "ToSubPlugins", "(", "msg", "[", "]", "*", "SubscribedPlugin", ")", "[", "]", "core", ".", "SubscribedPlugin", "{", "plugins", ":=", "make", "(", "[", "]", "core", ".", "SubscribedPlugin", ",", "len", "(", "msg", ")", ")", "\n", "for", "i", ",", "v", ":=", "range", "msg", "{", "plugins", "[", "i", "]", "=", "ToSubPlugin", "(", "v", ")", "\n", "}", "\n", "return", "plugins", "\n", "}" ]
// Converts slice of SubscribedPlugin Messages to core.SubscribedPlugins
[ "Converts", "slice", "of", "SubscribedPlugin", "Messages", "to", "core", ".", "SubscribedPlugins" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/grpc/common/common.go#L340-L346
15,281
intelsdi-x/snap
grpc/common/common.go
ToSubPluginsMsg
func ToSubPluginsMsg(sp []core.SubscribedPlugin) []*SubscribedPlugin { plugins := make([]*SubscribedPlugin, len(sp)) for i, v := range sp { plugins[i] = ToSubPluginMsg(v) } return plugins }
go
func ToSubPluginsMsg(sp []core.SubscribedPlugin) []*SubscribedPlugin { plugins := make([]*SubscribedPlugin, len(sp)) for i, v := range sp { plugins[i] = ToSubPluginMsg(v) } return plugins }
[ "func", "ToSubPluginsMsg", "(", "sp", "[", "]", "core", ".", "SubscribedPlugin", ")", "[", "]", "*", "SubscribedPlugin", "{", "plugins", ":=", "make", "(", "[", "]", "*", "SubscribedPlugin", ",", "len", "(", "sp", ")", ")", "\n", "for", "i", ",", "v", ":=", "range", "sp", "{", "plugins", "[", "i", "]", "=", "ToSubPluginMsg", "(", "v", ")", "\n", "}", "\n", "return", "plugins", "\n", "}" ]
// Converts core.SubscribedPlugins to protobuf messages
[ "Converts", "core", ".", "SubscribedPlugins", "to", "protobuf", "messages" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/grpc/common/common.go#L349-L355
15,282
intelsdi-x/snap
grpc/common/common.go
ConfigMapToConfig
func ConfigMapToConfig(cfg *ConfigMap) *cdata.ConfigDataNode { if cfg == nil { return nil } config := cdata.FromTable(ParseConfig(cfg)) return config }
go
func ConfigMapToConfig(cfg *ConfigMap) *cdata.ConfigDataNode { if cfg == nil { return nil } config := cdata.FromTable(ParseConfig(cfg)) return config }
[ "func", "ConfigMapToConfig", "(", "cfg", "*", "ConfigMap", ")", "*", "cdata", ".", "ConfigDataNode", "{", "if", "cfg", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "config", ":=", "cdata", ".", "FromTable", "(", "ParseConfig", "(", "cfg", ")", ")", "\n", "return", "config", "\n", "}" ]
// Converts configMaps to ConfigDataNode
[ "Converts", "configMaps", "to", "ConfigDataNode" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/grpc/common/common.go#L358-L364
15,283
intelsdi-x/snap
grpc/common/common.go
ConfigToConfigMap
func ConfigToConfigMap(cd *cdata.ConfigDataNode) *ConfigMap { if cd == nil { return nil } return ToConfigMap(cd.Table()) }
go
func ConfigToConfigMap(cd *cdata.ConfigDataNode) *ConfigMap { if cd == nil { return nil } return ToConfigMap(cd.Table()) }
[ "func", "ConfigToConfigMap", "(", "cd", "*", "cdata", ".", "ConfigDataNode", ")", "*", "ConfigMap", "{", "if", "cd", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "ToConfigMap", "(", "cd", ".", "Table", "(", ")", ")", "\n", "}" ]
// Converts ConfigDataNode to ConfigMap protobuf message
[ "Converts", "ConfigDataNode", "to", "ConfigMap", "protobuf", "message" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/grpc/common/common.go#L389-L394
15,284
intelsdi-x/snap
grpc/common/common.go
ConvertSnapErrors
func ConvertSnapErrors(s []*SnapError) []serror.SnapError { rerrs := make([]serror.SnapError, len(s)) for i, err := range s { rerrs[i] = serror.New(errors.New(err.ErrorString), GetFields(err)) } return rerrs }
go
func ConvertSnapErrors(s []*SnapError) []serror.SnapError { rerrs := make([]serror.SnapError, len(s)) for i, err := range s { rerrs[i] = serror.New(errors.New(err.ErrorString), GetFields(err)) } return rerrs }
[ "func", "ConvertSnapErrors", "(", "s", "[", "]", "*", "SnapError", ")", "[", "]", "serror", ".", "SnapError", "{", "rerrs", ":=", "make", "(", "[", "]", "serror", ".", "SnapError", ",", "len", "(", "s", ")", ")", "\n", "for", "i", ",", "err", ":=", "range", "s", "{", "rerrs", "[", "i", "]", "=", "serror", ".", "New", "(", "errors", ".", "New", "(", "err", ".", "ErrorString", ")", ",", "GetFields", "(", "err", ")", ")", "\n", "}", "\n", "return", "rerrs", "\n", "}" ]
// Converts SnapError protobuf messages to serror.Snaperrors
[ "Converts", "SnapError", "protobuf", "messages", "to", "serror", ".", "Snaperrors" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/grpc/common/common.go#L420-L426
15,285
intelsdi-x/snap
grpc/common/common.go
ToSnapError
func ToSnapError(e *SnapError) serror.SnapError { if e == nil { return nil } return serror.New(errors.New(e.ErrorString), GetFields(e)) }
go
func ToSnapError(e *SnapError) serror.SnapError { if e == nil { return nil } return serror.New(errors.New(e.ErrorString), GetFields(e)) }
[ "func", "ToSnapError", "(", "e", "*", "SnapError", ")", "serror", ".", "SnapError", "{", "if", "e", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "serror", ".", "New", "(", "errors", ".", "New", "(", "e", ".", "ErrorString", ")", ",", "GetFields", "(", "e", ")", ")", "\n", "}" ]
// Converts a single SnapError protobuf message to SnapError
[ "Converts", "a", "single", "SnapError", "protobuf", "message", "to", "SnapError" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/grpc/common/common.go#L429-L434
15,286
intelsdi-x/snap
grpc/common/common.go
GetFields
func GetFields(s *SnapError) map[string]interface{} { fields := make(map[string]interface{}, len(s.ErrorFields)) for key, value := range s.ErrorFields { fields[key] = value } return fields }
go
func GetFields(s *SnapError) map[string]interface{} { fields := make(map[string]interface{}, len(s.ErrorFields)) for key, value := range s.ErrorFields { fields[key] = value } return fields }
[ "func", "GetFields", "(", "s", "*", "SnapError", ")", "map", "[", "string", "]", "interface", "{", "}", "{", "fields", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "len", "(", "s", ".", "ErrorFields", ")", ")", "\n", "for", "key", ",", "value", ":=", "range", "s", ".", "ErrorFields", "{", "fields", "[", "key", "]", "=", "value", "\n", "}", "\n", "return", "fields", "\n", "}" ]
// Returns the fields from a SnapError protobuf message
[ "Returns", "the", "fields", "from", "a", "SnapError", "protobuf", "message" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/grpc/common/common.go#L464-L470
15,287
intelsdi-x/snap
scheduler/managers.go
Get
func (m *managers) Get(key string) (managesMetrics, error) { if key == "" { return m.local, nil } m.mutex.RLock() defer m.mutex.RUnlock() if val, ok := m.remoteManagers[key]; ok { return val, nil } else { return nil, errors.New(fmt.Sprintf("Client not found for: %v", key)) } }
go
func (m *managers) Get(key string) (managesMetrics, error) { if key == "" { return m.local, nil } m.mutex.RLock() defer m.mutex.RUnlock() if val, ok := m.remoteManagers[key]; ok { return val, nil } else { return nil, errors.New(fmt.Sprintf("Client not found for: %v", key)) } }
[ "func", "(", "m", "*", "managers", ")", "Get", "(", "key", "string", ")", "(", "managesMetrics", ",", "error", ")", "{", "if", "key", "==", "\"", "\"", "{", "return", "m", ".", "local", ",", "nil", "\n", "}", "\n", "m", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "m", ".", "mutex", ".", "RUnlock", "(", ")", "\n", "if", "val", ",", "ok", ":=", "m", ".", "remoteManagers", "[", "key", "]", ";", "ok", "{", "return", "val", ",", "nil", "\n", "}", "else", "{", "return", "nil", ",", "errors", ".", "New", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "key", ")", ")", "\n", "}", "\n", "}" ]
// Returns the managesMetric instance that maps to given // string. If an empty string is given, will instead return // the local instance passed in on initialization.
[ "Returns", "the", "managesMetric", "instance", "that", "maps", "to", "given", "string", ".", "If", "an", "empty", "string", "is", "given", "will", "instead", "return", "the", "local", "instance", "passed", "in", "on", "initialization", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/managers.go#L57-L68
15,288
intelsdi-x/snap
scheduler/workflow.go
wmapToWorkflow
func wmapToWorkflow(wfMap *wmap.WorkflowMap) (*schedulerWorkflow, error) { wf := &schedulerWorkflow{} err := convertCollectionNode(wfMap.Collect, wf) if err != nil { return nil, err } // *** // TODO validate workflow makes sense here // - flows that don't end in publishers? // - duplicate child nodes anywhere? //*** // Retain a copy of the original workflow map wf.workflowMap = wfMap return wf, nil }
go
func wmapToWorkflow(wfMap *wmap.WorkflowMap) (*schedulerWorkflow, error) { wf := &schedulerWorkflow{} err := convertCollectionNode(wfMap.Collect, wf) if err != nil { return nil, err } // *** // TODO validate workflow makes sense here // - flows that don't end in publishers? // - duplicate child nodes anywhere? //*** // Retain a copy of the original workflow map wf.workflowMap = wfMap return wf, nil }
[ "func", "wmapToWorkflow", "(", "wfMap", "*", "wmap", ".", "WorkflowMap", ")", "(", "*", "schedulerWorkflow", ",", "error", ")", "{", "wf", ":=", "&", "schedulerWorkflow", "{", "}", "\n", "err", ":=", "convertCollectionNode", "(", "wfMap", ".", "Collect", ",", "wf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// ***", "// TODO validate workflow makes sense here", "// - flows that don't end in publishers?", "// - duplicate child nodes anywhere?", "//***", "// Retain a copy of the original workflow map", "wf", ".", "workflowMap", "=", "wfMap", "\n", "return", "wf", ",", "nil", "\n", "}" ]
// WmapToWorkflow attempts to convert a wmap.WorkflowMap to a schedulerWorkflow instance.
[ "WmapToWorkflow", "attempts", "to", "convert", "a", "wmap", ".", "WorkflowMap", "to", "a", "schedulerWorkflow", "instance", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/workflow.go#L60-L74
15,289
intelsdi-x/snap
scheduler/workflow.go
Start
func (s *schedulerWorkflow) Start(t *task) { workflowLogger.WithFields(log.Fields{ "_block": "workflow-start", "task-id": t.id, "task-name": t.name, }).Debug("Starting workflow") s.state = WorkflowStarted j := newCollectorJob(s.metrics, t.deadlineDuration, t.metricsManager, t.workflow.configTree, t.id, s.tags) // dispatch 'collect' job to be worked // Block until the job has been either run or skipped. errors := t.manager.Work(j).Promise().Await() if len(errors) > 0 { t.RecordFailure(errors) event := new(scheduler_event.MetricCollectionFailedEvent) event.TaskID = t.id event.Errors = errors defer s.eventEmitter.Emit(event) return } // Send event event := new(scheduler_event.MetricCollectedEvent) event.TaskID = t.id event.Metrics = j.(*collectorJob).metrics defer s.eventEmitter.Emit(event) // walk through the tree and dispatch work workJobs(s.processNodes, s.publishNodes, t, j) }
go
func (s *schedulerWorkflow) Start(t *task) { workflowLogger.WithFields(log.Fields{ "_block": "workflow-start", "task-id": t.id, "task-name": t.name, }).Debug("Starting workflow") s.state = WorkflowStarted j := newCollectorJob(s.metrics, t.deadlineDuration, t.metricsManager, t.workflow.configTree, t.id, s.tags) // dispatch 'collect' job to be worked // Block until the job has been either run or skipped. errors := t.manager.Work(j).Promise().Await() if len(errors) > 0 { t.RecordFailure(errors) event := new(scheduler_event.MetricCollectionFailedEvent) event.TaskID = t.id event.Errors = errors defer s.eventEmitter.Emit(event) return } // Send event event := new(scheduler_event.MetricCollectedEvent) event.TaskID = t.id event.Metrics = j.(*collectorJob).metrics defer s.eventEmitter.Emit(event) // walk through the tree and dispatch work workJobs(s.processNodes, s.publishNodes, t, j) }
[ "func", "(", "s", "*", "schedulerWorkflow", ")", "Start", "(", "t", "*", "task", ")", "{", "workflowLogger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "t", ".", "id", ",", "\"", "\"", ":", "t", ".", "name", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "s", ".", "state", "=", "WorkflowStarted", "\n", "j", ":=", "newCollectorJob", "(", "s", ".", "metrics", ",", "t", ".", "deadlineDuration", ",", "t", ".", "metricsManager", ",", "t", ".", "workflow", ".", "configTree", ",", "t", ".", "id", ",", "s", ".", "tags", ")", "\n\n", "// dispatch 'collect' job to be worked", "// Block until the job has been either run or skipped.", "errors", ":=", "t", ".", "manager", ".", "Work", "(", "j", ")", ".", "Promise", "(", ")", ".", "Await", "(", ")", "\n\n", "if", "len", "(", "errors", ")", ">", "0", "{", "t", ".", "RecordFailure", "(", "errors", ")", "\n", "event", ":=", "new", "(", "scheduler_event", ".", "MetricCollectionFailedEvent", ")", "\n", "event", ".", "TaskID", "=", "t", ".", "id", "\n", "event", ".", "Errors", "=", "errors", "\n", "defer", "s", ".", "eventEmitter", ".", "Emit", "(", "event", ")", "\n", "return", "\n", "}", "\n\n", "// Send event", "event", ":=", "new", "(", "scheduler_event", ".", "MetricCollectedEvent", ")", "\n", "event", ".", "TaskID", "=", "t", ".", "id", "\n", "event", ".", "Metrics", "=", "j", ".", "(", "*", "collectorJob", ")", ".", "metrics", "\n", "defer", "s", ".", "eventEmitter", ".", "Emit", "(", "event", ")", "\n\n", "// walk through the tree and dispatch work", "workJobs", "(", "s", ".", "processNodes", ",", "s", ".", "publishNodes", ",", "t", ",", "j", ")", "\n", "}" ]
// Start starts a workflow
[ "Start", "starts", "a", "workflow" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/workflow.go#L243-L273
15,290
intelsdi-x/snap
scheduler/workflow.go
workJobs
func workJobs(prs []*processNode, pus []*publishNode, t *task, pj job) { // optimize for no jobs if len(prs) == 0 && len(pus) == 0 { return } // Create waitgroup to block until all jobs are submitted wg := &sync.WaitGroup{} workflowLogger.WithFields(log.Fields{ "_block": "work-jobs", "task-id": t.id, "task-name": t.name, "count-process-nodes": len(prs), "count-publish-nodes": len(pus), "parent-node-type": pj.TypeString(), }).Debug("Batch submission of process and publish nodes") // range over the process jobs and call submitProcessJob for _, pr := range prs { // increment the wait group (before starting goroutine to prevent a race condition) wg.Add(1) // Start goroutine to submit the process job go submitProcessJob(pj, t, wg, pr) } // range over the publish jobs and call submitPublishJob for _, pu := range pus { // increment the wait group (before starting goroutine to prevent a race condition) wg.Add(1) // Start goroutine to submit the process job go submitPublishJob(pj, t, wg, pu) } // Wait until all job submisson goroutines are done wg.Wait() workflowLogger.WithFields(log.Fields{ "_block": "work-jobs", "task-id": t.id, "task-name": t.name, "count-process-nodes": len(prs), "count-publish-nodes": len(pus), "parent-node-type": pj.TypeString(), }).Debug("Batch submission complete") }
go
func workJobs(prs []*processNode, pus []*publishNode, t *task, pj job) { // optimize for no jobs if len(prs) == 0 && len(pus) == 0 { return } // Create waitgroup to block until all jobs are submitted wg := &sync.WaitGroup{} workflowLogger.WithFields(log.Fields{ "_block": "work-jobs", "task-id": t.id, "task-name": t.name, "count-process-nodes": len(prs), "count-publish-nodes": len(pus), "parent-node-type": pj.TypeString(), }).Debug("Batch submission of process and publish nodes") // range over the process jobs and call submitProcessJob for _, pr := range prs { // increment the wait group (before starting goroutine to prevent a race condition) wg.Add(1) // Start goroutine to submit the process job go submitProcessJob(pj, t, wg, pr) } // range over the publish jobs and call submitPublishJob for _, pu := range pus { // increment the wait group (before starting goroutine to prevent a race condition) wg.Add(1) // Start goroutine to submit the process job go submitPublishJob(pj, t, wg, pu) } // Wait until all job submisson goroutines are done wg.Wait() workflowLogger.WithFields(log.Fields{ "_block": "work-jobs", "task-id": t.id, "task-name": t.name, "count-process-nodes": len(prs), "count-publish-nodes": len(pus), "parent-node-type": pj.TypeString(), }).Debug("Batch submission complete") }
[ "func", "workJobs", "(", "prs", "[", "]", "*", "processNode", ",", "pus", "[", "]", "*", "publishNode", ",", "t", "*", "task", ",", "pj", "job", ")", "{", "// optimize for no jobs", "if", "len", "(", "prs", ")", "==", "0", "&&", "len", "(", "pus", ")", "==", "0", "{", "return", "\n", "}", "\n", "// Create waitgroup to block until all jobs are submitted", "wg", ":=", "&", "sync", ".", "WaitGroup", "{", "}", "\n", "workflowLogger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "t", ".", "id", ",", "\"", "\"", ":", "t", ".", "name", ",", "\"", "\"", ":", "len", "(", "prs", ")", ",", "\"", "\"", ":", "len", "(", "pus", ")", ",", "\"", "\"", ":", "pj", ".", "TypeString", "(", ")", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "// range over the process jobs and call submitProcessJob", "for", "_", ",", "pr", ":=", "range", "prs", "{", "// increment the wait group (before starting goroutine to prevent a race condition)", "wg", ".", "Add", "(", "1", ")", "\n", "// Start goroutine to submit the process job", "go", "submitProcessJob", "(", "pj", ",", "t", ",", "wg", ",", "pr", ")", "\n", "}", "\n", "// range over the publish jobs and call submitPublishJob", "for", "_", ",", "pu", ":=", "range", "pus", "{", "// increment the wait group (before starting goroutine to prevent a race condition)", "wg", ".", "Add", "(", "1", ")", "\n", "// Start goroutine to submit the process job", "go", "submitPublishJob", "(", "pj", ",", "t", ",", "wg", ",", "pu", ")", "\n", "}", "\n", "// Wait until all job submisson goroutines are done", "wg", ".", "Wait", "(", ")", "\n", "workflowLogger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "t", ".", "id", ",", "\"", "\"", ":", "t", ".", "name", ",", "\"", "\"", ":", "len", "(", "prs", ")", ",", "\"", "\"", ":", "len", "(", "pus", ")", ",", "\"", "\"", ":", "pj", ".", "TypeString", "(", ")", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "}" ]
// workJobs takes a slice of process and publish nodes and submits jobs for each for a task. // It then iterates down any process nodes to submit their child node jobs for the task
[ "workJobs", "takes", "a", "slice", "of", "process", "and", "publish", "nodes", "and", "submits", "jobs", "for", "each", "for", "a", "task", ".", "It", "then", "iterates", "down", "any", "process", "nodes", "to", "submit", "their", "child", "node", "jobs", "for", "the", "task" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/workflow.go#L302-L341
15,291
intelsdi-x/snap
pkg/rpcutil/rpc.go
GetClientConnection
func GetClientConnection(ctx context.Context, addr string, port int) (*grpc.ClientConn, error) { return GetClientConnectionWithCreds(ctx, addr, port, nil) }
go
func GetClientConnection(ctx context.Context, addr string, port int) (*grpc.ClientConn, error) { return GetClientConnectionWithCreds(ctx, addr, port, nil) }
[ "func", "GetClientConnection", "(", "ctx", "context", ".", "Context", ",", "addr", "string", ",", "port", "int", ")", "(", "*", "grpc", ".", "ClientConn", ",", "error", ")", "{", "return", "GetClientConnectionWithCreds", "(", "ctx", ",", "addr", ",", "port", ",", "nil", ")", "\n", "}" ]
// GetClientConnection returns a grcp.ClientConn that is unsecured
[ "GetClientConnection", "returns", "a", "grcp", ".", "ClientConn", "that", "is", "unsecured" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/pkg/rpcutil/rpc.go#L35-L37
15,292
intelsdi-x/snap
control/config.go
IsTLSEnabled
func (p *Config) IsTLSEnabled() bool { if p.TLSCertPath != "" && p.TLSKeyPath != "" { return true } return false }
go
func (p *Config) IsTLSEnabled() bool { if p.TLSCertPath != "" && p.TLSKeyPath != "" { return true } return false }
[ "func", "(", "p", "*", "Config", ")", "IsTLSEnabled", "(", ")", "bool", "{", "if", "p", ".", "TLSCertPath", "!=", "\"", "\"", "&&", "p", ".", "TLSKeyPath", "!=", "\"", "\"", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsTLSEnabled returns true if config values enable TLS in plugin communication
[ "IsTLSEnabled", "returns", "true", "if", "config", "values", "enable", "TLS", "in", "plugin", "communication" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/config.go#L254-L259
15,293
intelsdi-x/snap
control/fixtures/tls_cert_util.go
WritePEMFile
func (u CertTestUtil) WritePEMFile(fn string, pemHeader string, b []byte) error { f, err := os.Create(fn) if err != nil { return err } defer f.Close() w := bufio.NewWriter(f) pem.Encode(w, &pem.Block{ Type: pemHeader, Bytes: b, }) w.Flush() return nil }
go
func (u CertTestUtil) WritePEMFile(fn string, pemHeader string, b []byte) error { f, err := os.Create(fn) if err != nil { return err } defer f.Close() w := bufio.NewWriter(f) pem.Encode(w, &pem.Block{ Type: pemHeader, Bytes: b, }) w.Flush() return nil }
[ "func", "(", "u", "CertTestUtil", ")", "WritePEMFile", "(", "fn", "string", ",", "pemHeader", "string", ",", "b", "[", "]", "byte", ")", "error", "{", "f", ",", "err", ":=", "os", ".", "Create", "(", "fn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "w", ":=", "bufio", ".", "NewWriter", "(", "f", ")", "\n", "pem", ".", "Encode", "(", "w", ",", "&", "pem", ".", "Block", "{", "Type", ":", "pemHeader", ",", "Bytes", ":", "b", ",", "}", ")", "\n", "w", ".", "Flush", "(", ")", "\n", "return", "nil", "\n", "}" ]
// WritePEMFile writes block of bytes into a PEM formatted file with given header.
[ "WritePEMFile", "writes", "block", "of", "bytes", "into", "a", "PEM", "formatted", "file", "with", "given", "header", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/fixtures/tls_cert_util.go#L63-L76
15,294
intelsdi-x/snap
control/fixtures/tls_cert_util.go
MakeCACertKeyPair
func (u CertTestUtil) MakeCACertKeyPair(caName, ouName string, keyValidPeriod time.Duration) (caCertTpl *x509.Certificate, caCertBytes []byte, caPrivKey *rsa.PrivateKey, err error) { caPrivKey, err = rsa.GenerateKey(rand.Reader, keyBitsDefault) if err != nil { return nil, nil, nil, err } caPubKey := caPrivKey.Public() caPubBytes, err := x509.MarshalPKIXPublicKey(caPubKey) if err != nil { return nil, nil, nil, err } caPubSha256 := sha256.Sum256(caPubBytes) caCertTpl = &x509.Certificate{ SignatureAlgorithm: defaultSignatureAlgorithm, PublicKeyAlgorithm: defaultPublicKeyAlgorithm, Version: 3, SerialNumber: big.NewInt(1), Subject: pkix.Name{ CommonName: caName, }, NotBefore: time.Now(), NotAfter: time.Now().Add(keyValidPeriod), KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign, BasicConstraintsValid: true, MaxPathLenZero: true, IsCA: true, SubjectKeyId: caPubSha256[:], } caCertBytes, err = x509.CreateCertificate(rand.Reader, caCertTpl, caCertTpl, caPubKey, caPrivKey) if err != nil { return nil, nil, nil, err } return caCertTpl, caCertBytes, caPrivKey, nil }
go
func (u CertTestUtil) MakeCACertKeyPair(caName, ouName string, keyValidPeriod time.Duration) (caCertTpl *x509.Certificate, caCertBytes []byte, caPrivKey *rsa.PrivateKey, err error) { caPrivKey, err = rsa.GenerateKey(rand.Reader, keyBitsDefault) if err != nil { return nil, nil, nil, err } caPubKey := caPrivKey.Public() caPubBytes, err := x509.MarshalPKIXPublicKey(caPubKey) if err != nil { return nil, nil, nil, err } caPubSha256 := sha256.Sum256(caPubBytes) caCertTpl = &x509.Certificate{ SignatureAlgorithm: defaultSignatureAlgorithm, PublicKeyAlgorithm: defaultPublicKeyAlgorithm, Version: 3, SerialNumber: big.NewInt(1), Subject: pkix.Name{ CommonName: caName, }, NotBefore: time.Now(), NotAfter: time.Now().Add(keyValidPeriod), KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign, BasicConstraintsValid: true, MaxPathLenZero: true, IsCA: true, SubjectKeyId: caPubSha256[:], } caCertBytes, err = x509.CreateCertificate(rand.Reader, caCertTpl, caCertTpl, caPubKey, caPrivKey) if err != nil { return nil, nil, nil, err } return caCertTpl, caCertBytes, caPrivKey, nil }
[ "func", "(", "u", "CertTestUtil", ")", "MakeCACertKeyPair", "(", "caName", ",", "ouName", "string", ",", "keyValidPeriod", "time", ".", "Duration", ")", "(", "caCertTpl", "*", "x509", ".", "Certificate", ",", "caCertBytes", "[", "]", "byte", ",", "caPrivKey", "*", "rsa", ".", "PrivateKey", ",", "err", "error", ")", "{", "caPrivKey", ",", "err", "=", "rsa", ".", "GenerateKey", "(", "rand", ".", "Reader", ",", "keyBitsDefault", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "caPubKey", ":=", "caPrivKey", ".", "Public", "(", ")", "\n", "caPubBytes", ",", "err", ":=", "x509", ".", "MarshalPKIXPublicKey", "(", "caPubKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "caPubSha256", ":=", "sha256", ".", "Sum256", "(", "caPubBytes", ")", "\n", "caCertTpl", "=", "&", "x509", ".", "Certificate", "{", "SignatureAlgorithm", ":", "defaultSignatureAlgorithm", ",", "PublicKeyAlgorithm", ":", "defaultPublicKeyAlgorithm", ",", "Version", ":", "3", ",", "SerialNumber", ":", "big", ".", "NewInt", "(", "1", ")", ",", "Subject", ":", "pkix", ".", "Name", "{", "CommonName", ":", "caName", ",", "}", ",", "NotBefore", ":", "time", ".", "Now", "(", ")", ",", "NotAfter", ":", "time", ".", "Now", "(", ")", ".", "Add", "(", "keyValidPeriod", ")", ",", "KeyUsage", ":", "x509", ".", "KeyUsageCertSign", "|", "x509", ".", "KeyUsageCRLSign", ",", "BasicConstraintsValid", ":", "true", ",", "MaxPathLenZero", ":", "true", ",", "IsCA", ":", "true", ",", "SubjectKeyId", ":", "caPubSha256", "[", ":", "]", ",", "}", "\n", "caCertBytes", ",", "err", "=", "x509", ".", "CreateCertificate", "(", "rand", ".", "Reader", ",", "caCertTpl", ",", "caCertTpl", ",", "caPubKey", ",", "caPrivKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "return", "caCertTpl", ",", "caCertBytes", ",", "caPrivKey", ",", "nil", "\n", "}" ]
// MakeCACertKeyPair generates asymmetric private key and certificate // for CA, suitable for signing certificates
[ "MakeCACertKeyPair", "generates", "asymmetric", "private", "key", "and", "certificate", "for", "CA", "suitable", "for", "signing", "certificates" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/fixtures/tls_cert_util.go#L80-L112
15,295
intelsdi-x/snap
control/fixtures/tls_cert_util.go
MakeSubjCertKeyPair
func (u CertTestUtil) MakeSubjCertKeyPair(cn, ou string, keyValidPeriod time.Duration, caCertTpl *x509.Certificate, caPrivKey *rsa.PrivateKey) (subjCertBytes []byte, subjPrivKey *rsa.PrivateKey, err error) { subjPrivKey, err = rsa.GenerateKey(rand.Reader, keyBitsDefault) if err != nil { return nil, nil, err } subjPubBytes, err := x509.MarshalPKIXPublicKey(subjPrivKey.Public()) if err != nil { return nil, nil, err } subjPubSha256 := sha256.Sum256(subjPubBytes) subjCertTpl := x509.Certificate{ SignatureAlgorithm: defaultSignatureAlgorithm, PublicKeyAlgorithm: defaultPublicKeyAlgorithm, Version: 3, SerialNumber: big.NewInt(1), Subject: pkix.Name{ OrganizationalUnit: []string{ou}, CommonName: cn, }, NotBefore: time.Now(), NotAfter: time.Now().Add(keyValidPeriod), KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageDataEncipherment | x509.KeyUsageKeyAgreement, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, SubjectKeyId: subjPubSha256[:], } subjCertTpl.DNSNames = []string{"localhost"} subjCertTpl.IPAddresses = []net.IP{net.ParseIP("127.0.0.1")} subjCertBytes, err = x509.CreateCertificate(rand.Reader, &subjCertTpl, caCertTpl, subjPrivKey.Public(), caPrivKey) return subjCertBytes, subjPrivKey, err }
go
func (u CertTestUtil) MakeSubjCertKeyPair(cn, ou string, keyValidPeriod time.Duration, caCertTpl *x509.Certificate, caPrivKey *rsa.PrivateKey) (subjCertBytes []byte, subjPrivKey *rsa.PrivateKey, err error) { subjPrivKey, err = rsa.GenerateKey(rand.Reader, keyBitsDefault) if err != nil { return nil, nil, err } subjPubBytes, err := x509.MarshalPKIXPublicKey(subjPrivKey.Public()) if err != nil { return nil, nil, err } subjPubSha256 := sha256.Sum256(subjPubBytes) subjCertTpl := x509.Certificate{ SignatureAlgorithm: defaultSignatureAlgorithm, PublicKeyAlgorithm: defaultPublicKeyAlgorithm, Version: 3, SerialNumber: big.NewInt(1), Subject: pkix.Name{ OrganizationalUnit: []string{ou}, CommonName: cn, }, NotBefore: time.Now(), NotAfter: time.Now().Add(keyValidPeriod), KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageDataEncipherment | x509.KeyUsageKeyAgreement, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, SubjectKeyId: subjPubSha256[:], } subjCertTpl.DNSNames = []string{"localhost"} subjCertTpl.IPAddresses = []net.IP{net.ParseIP("127.0.0.1")} subjCertBytes, err = x509.CreateCertificate(rand.Reader, &subjCertTpl, caCertTpl, subjPrivKey.Public(), caPrivKey) return subjCertBytes, subjPrivKey, err }
[ "func", "(", "u", "CertTestUtil", ")", "MakeSubjCertKeyPair", "(", "cn", ",", "ou", "string", ",", "keyValidPeriod", "time", ".", "Duration", ",", "caCertTpl", "*", "x509", ".", "Certificate", ",", "caPrivKey", "*", "rsa", ".", "PrivateKey", ")", "(", "subjCertBytes", "[", "]", "byte", ",", "subjPrivKey", "*", "rsa", ".", "PrivateKey", ",", "err", "error", ")", "{", "subjPrivKey", ",", "err", "=", "rsa", ".", "GenerateKey", "(", "rand", ".", "Reader", ",", "keyBitsDefault", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "subjPubBytes", ",", "err", ":=", "x509", ".", "MarshalPKIXPublicKey", "(", "subjPrivKey", ".", "Public", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "subjPubSha256", ":=", "sha256", ".", "Sum256", "(", "subjPubBytes", ")", "\n", "subjCertTpl", ":=", "x509", ".", "Certificate", "{", "SignatureAlgorithm", ":", "defaultSignatureAlgorithm", ",", "PublicKeyAlgorithm", ":", "defaultPublicKeyAlgorithm", ",", "Version", ":", "3", ",", "SerialNumber", ":", "big", ".", "NewInt", "(", "1", ")", ",", "Subject", ":", "pkix", ".", "Name", "{", "OrganizationalUnit", ":", "[", "]", "string", "{", "ou", "}", ",", "CommonName", ":", "cn", ",", "}", ",", "NotBefore", ":", "time", ".", "Now", "(", ")", ",", "NotAfter", ":", "time", ".", "Now", "(", ")", ".", "Add", "(", "keyValidPeriod", ")", ",", "KeyUsage", ":", "x509", ".", "KeyUsageDigitalSignature", "|", "x509", ".", "KeyUsageKeyEncipherment", "|", "x509", ".", "KeyUsageDataEncipherment", "|", "x509", ".", "KeyUsageKeyAgreement", ",", "ExtKeyUsage", ":", "[", "]", "x509", ".", "ExtKeyUsage", "{", "x509", ".", "ExtKeyUsageClientAuth", ",", "x509", ".", "ExtKeyUsageServerAuth", "}", ",", "SubjectKeyId", ":", "subjPubSha256", "[", ":", "]", ",", "}", "\n", "subjCertTpl", ".", "DNSNames", "=", "[", "]", "string", "{", "\"", "\"", "}", "\n", "subjCertTpl", ".", "IPAddresses", "=", "[", "]", "net", ".", "IP", "{", "net", ".", "ParseIP", "(", "\"", "\"", ")", "}", "\n", "subjCertBytes", ",", "err", "=", "x509", ".", "CreateCertificate", "(", "rand", ".", "Reader", ",", "&", "subjCertTpl", ",", "caCertTpl", ",", "subjPrivKey", ".", "Public", "(", ")", ",", "caPrivKey", ")", "\n", "return", "subjCertBytes", ",", "subjPrivKey", ",", "err", "\n", "}" ]
// MakeSubjCertKeyPair generates a private key and a certificate for subject // suitable for securing TLS communication
[ "MakeSubjCertKeyPair", "generates", "a", "private", "key", "and", "a", "certificate", "for", "subject", "suitable", "for", "securing", "TLS", "communication" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/fixtures/tls_cert_util.go#L116-L145
15,296
intelsdi-x/snap
scheduler/wmap/wmap.go
GetConfigTree
func (c *CollectWorkflowMapNode) GetConfigTree() (*cdata.ConfigDataTree, error) { cdt := cdata.NewTree() // Iterate over config and attempt to convert into data nodes in the tree for ns_, cmap := range c.Config { ns := strings.Split(ns_, "/")[1:] cdn, err := configtoConfigDataNode(cmap, ns_) if err != nil { return nil, err } cdt.Add(ns, cdn) } return cdt, nil }
go
func (c *CollectWorkflowMapNode) GetConfigTree() (*cdata.ConfigDataTree, error) { cdt := cdata.NewTree() // Iterate over config and attempt to convert into data nodes in the tree for ns_, cmap := range c.Config { ns := strings.Split(ns_, "/")[1:] cdn, err := configtoConfigDataNode(cmap, ns_) if err != nil { return nil, err } cdt.Add(ns, cdn) } return cdt, nil }
[ "func", "(", "c", "*", "CollectWorkflowMapNode", ")", "GetConfigTree", "(", ")", "(", "*", "cdata", ".", "ConfigDataTree", ",", "error", ")", "{", "cdt", ":=", "cdata", ".", "NewTree", "(", ")", "\n", "// Iterate over config and attempt to convert into data nodes in the tree", "for", "ns_", ",", "cmap", ":=", "range", "c", ".", "Config", "{", "ns", ":=", "strings", ".", "Split", "(", "ns_", ",", "\"", "\"", ")", "[", "1", ":", "]", "\n", "cdn", ",", "err", ":=", "configtoConfigDataNode", "(", "cmap", ",", "ns_", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "cdt", ".", "Add", "(", "ns", ",", "cdn", ")", "\n", "}", "\n", "return", "cdt", ",", "nil", "\n", "}" ]
// GetConfigTree converts config data for collection node in wmap into a proper cdata.ConfigDataTree
[ "GetConfigTree", "converts", "config", "data", "for", "collection", "node", "in", "wmap", "into", "a", "proper", "cdata", ".", "ConfigDataTree" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/wmap/wmap.go#L246-L259
15,297
intelsdi-x/snap
cmd/snaptel/task.go
mergeCliOptions
func (t *task) mergeCliOptions(ctx *cli.Context) error { // set the name of the task (if a 'name' was provided in the CLI options) name := ctx.String("name") if ctx.IsSet("name") || name != "" { t.Name = name } // set the deadline of the task (if a 'deadline' was provided in the CLI options) deadline := ctx.String("deadline") if ctx.IsSet("deadline") || deadline != "" { t.Deadline = deadline } // set the MaxFailures for the task (if a 'max-failures' value was provided in the CLI options) maxFailuresStrVal := ctx.String("max-failures") if ctx.IsSet("max-failures") || maxFailuresStrVal != "" { maxFailures, err := stringValToInt(maxFailuresStrVal) if err != nil { return err } t.MaxFailures = maxFailures } // set the schedule for the task from the CLI options (and return the results // of that method call, indicating whether or not an error was encountered while // setting up that schedule) return t.setScheduleFromCliOptions(ctx) }
go
func (t *task) mergeCliOptions(ctx *cli.Context) error { // set the name of the task (if a 'name' was provided in the CLI options) name := ctx.String("name") if ctx.IsSet("name") || name != "" { t.Name = name } // set the deadline of the task (if a 'deadline' was provided in the CLI options) deadline := ctx.String("deadline") if ctx.IsSet("deadline") || deadline != "" { t.Deadline = deadline } // set the MaxFailures for the task (if a 'max-failures' value was provided in the CLI options) maxFailuresStrVal := ctx.String("max-failures") if ctx.IsSet("max-failures") || maxFailuresStrVal != "" { maxFailures, err := stringValToInt(maxFailuresStrVal) if err != nil { return err } t.MaxFailures = maxFailures } // set the schedule for the task from the CLI options (and return the results // of that method call, indicating whether or not an error was encountered while // setting up that schedule) return t.setScheduleFromCliOptions(ctx) }
[ "func", "(", "t", "*", "task", ")", "mergeCliOptions", "(", "ctx", "*", "cli", ".", "Context", ")", "error", "{", "// set the name of the task (if a 'name' was provided in the CLI options)", "name", ":=", "ctx", ".", "String", "(", "\"", "\"", ")", "\n", "if", "ctx", ".", "IsSet", "(", "\"", "\"", ")", "||", "name", "!=", "\"", "\"", "{", "t", ".", "Name", "=", "name", "\n", "}", "\n", "// set the deadline of the task (if a 'deadline' was provided in the CLI options)", "deadline", ":=", "ctx", ".", "String", "(", "\"", "\"", ")", "\n", "if", "ctx", ".", "IsSet", "(", "\"", "\"", ")", "||", "deadline", "!=", "\"", "\"", "{", "t", ".", "Deadline", "=", "deadline", "\n", "}", "\n", "// set the MaxFailures for the task (if a 'max-failures' value was provided in the CLI options)", "maxFailuresStrVal", ":=", "ctx", ".", "String", "(", "\"", "\"", ")", "\n", "if", "ctx", ".", "IsSet", "(", "\"", "\"", ")", "||", "maxFailuresStrVal", "!=", "\"", "\"", "{", "maxFailures", ",", "err", ":=", "stringValToInt", "(", "maxFailuresStrVal", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "t", ".", "MaxFailures", "=", "maxFailures", "\n", "}", "\n", "// set the schedule for the task from the CLI options (and return the results", "// of that method call, indicating whether or not an error was encountered while", "// setting up that schedule)", "return", "t", ".", "setScheduleFromCliOptions", "(", "ctx", ")", "\n", "}" ]
// merge the command-line options into the current task
[ "merge", "the", "command", "-", "line", "options", "into", "the", "current", "task" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/cmd/snaptel/task.go#L321-L345
15,298
intelsdi-x/snap
pkg/cfgfile/cfgfile.go
validateSchema
func (r *schemaValidatorType) validateSchema(schema, cfg string) []serror.SnapError { schemaLoader := gojsonschema.NewStringLoader(schema) testDoc := gojsonschema.NewStringLoader(cfg) result, err := gojsonschema.Validate(schemaLoader, testDoc) var serrors []serror.SnapError // Check for invalid json if err != nil { serrors = append(serrors, serror.New(err)) return serrors } // check if result passes validation if result.Valid() { return nil } for _, err := range result.Errors() { serr := serror.New(errors.New("Validate schema error")) serr.SetFields(map[string]interface{}{ "value": err.Value(), "context": err.Context().String("::"), "description": err.Description(), }) serrors = append(serrors, serr) } return serrors }
go
func (r *schemaValidatorType) validateSchema(schema, cfg string) []serror.SnapError { schemaLoader := gojsonschema.NewStringLoader(schema) testDoc := gojsonschema.NewStringLoader(cfg) result, err := gojsonschema.Validate(schemaLoader, testDoc) var serrors []serror.SnapError // Check for invalid json if err != nil { serrors = append(serrors, serror.New(err)) return serrors } // check if result passes validation if result.Valid() { return nil } for _, err := range result.Errors() { serr := serror.New(errors.New("Validate schema error")) serr.SetFields(map[string]interface{}{ "value": err.Value(), "context": err.Context().String("::"), "description": err.Description(), }) serrors = append(serrors, serr) } return serrors }
[ "func", "(", "r", "*", "schemaValidatorType", ")", "validateSchema", "(", "schema", ",", "cfg", "string", ")", "[", "]", "serror", ".", "SnapError", "{", "schemaLoader", ":=", "gojsonschema", ".", "NewStringLoader", "(", "schema", ")", "\n", "testDoc", ":=", "gojsonschema", ".", "NewStringLoader", "(", "cfg", ")", "\n", "result", ",", "err", ":=", "gojsonschema", ".", "Validate", "(", "schemaLoader", ",", "testDoc", ")", "\n", "var", "serrors", "[", "]", "serror", ".", "SnapError", "\n", "// Check for invalid json", "if", "err", "!=", "nil", "{", "serrors", "=", "append", "(", "serrors", ",", "serror", ".", "New", "(", "err", ")", ")", "\n", "return", "serrors", "\n", "}", "\n", "// check if result passes validation", "if", "result", ".", "Valid", "(", ")", "{", "return", "nil", "\n", "}", "\n", "for", "_", ",", "err", ":=", "range", "result", ".", "Errors", "(", ")", "{", "serr", ":=", "serror", ".", "New", "(", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "serr", ".", "SetFields", "(", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "err", ".", "Value", "(", ")", ",", "\"", "\"", ":", "err", ".", "Context", "(", ")", ".", "String", "(", "\"", "\"", ")", ",", "\"", "\"", ":", "err", ".", "Description", "(", ")", ",", "}", ")", "\n", "serrors", "=", "append", "(", "serrors", ",", "serr", ")", "\n", "}", "\n", "return", "serrors", "\n", "}" ]
// and define an implementation for that type that performs the schema validation
[ "and", "define", "an", "implementation", "for", "that", "type", "that", "performs", "the", "schema", "validation" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/pkg/cfgfile/cfgfile.go#L65-L89
15,299
intelsdi-x/snap
scheduler/task.go
newTask
func newTask(s schedule.Schedule, wf *schedulerWorkflow, m *workManager, mm managesMetrics, emitter gomit.Emitter, opts ...core.TaskOption) (*task, error) { //Task would always be given a default name. //However if a user want to change this name, she can pass optional arguments, in form of core.TaskOption //The new name then get over written. taskID := uuid.New() name := fmt.Sprintf("Task-%s", taskID) wf.eventEmitter = emitter mgrs := newManagers(mm) err := createTaskClients(&mgrs, wf) if err != nil { return nil, err } _, stream := s.(*schedule.StreamingSchedule) task := &task{ id: taskID, name: name, schResponseChan: make(chan schedule.Response), schedule: s, state: core.TaskStopped, creationTime: time.Now(), workflow: wf, manager: m, metricsManager: mm, deadlineDuration: DefaultDeadlineDuration, stopOnFailure: DefaultStopOnFailure, eventEmitter: emitter, RemoteManagers: mgrs, isStream: stream, } //set options for _, opt := range opts { opt(task) } return task, nil }
go
func newTask(s schedule.Schedule, wf *schedulerWorkflow, m *workManager, mm managesMetrics, emitter gomit.Emitter, opts ...core.TaskOption) (*task, error) { //Task would always be given a default name. //However if a user want to change this name, she can pass optional arguments, in form of core.TaskOption //The new name then get over written. taskID := uuid.New() name := fmt.Sprintf("Task-%s", taskID) wf.eventEmitter = emitter mgrs := newManagers(mm) err := createTaskClients(&mgrs, wf) if err != nil { return nil, err } _, stream := s.(*schedule.StreamingSchedule) task := &task{ id: taskID, name: name, schResponseChan: make(chan schedule.Response), schedule: s, state: core.TaskStopped, creationTime: time.Now(), workflow: wf, manager: m, metricsManager: mm, deadlineDuration: DefaultDeadlineDuration, stopOnFailure: DefaultStopOnFailure, eventEmitter: emitter, RemoteManagers: mgrs, isStream: stream, } //set options for _, opt := range opts { opt(task) } return task, nil }
[ "func", "newTask", "(", "s", "schedule", ".", "Schedule", ",", "wf", "*", "schedulerWorkflow", ",", "m", "*", "workManager", ",", "mm", "managesMetrics", ",", "emitter", "gomit", ".", "Emitter", ",", "opts", "...", "core", ".", "TaskOption", ")", "(", "*", "task", ",", "error", ")", "{", "//Task would always be given a default name.", "//However if a user want to change this name, she can pass optional arguments, in form of core.TaskOption", "//The new name then get over written.", "taskID", ":=", "uuid", ".", "New", "(", ")", "\n", "name", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "taskID", ")", "\n", "wf", ".", "eventEmitter", "=", "emitter", "\n", "mgrs", ":=", "newManagers", "(", "mm", ")", "\n", "err", ":=", "createTaskClients", "(", "&", "mgrs", ",", "wf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "_", ",", "stream", ":=", "s", ".", "(", "*", "schedule", ".", "StreamingSchedule", ")", "\n", "task", ":=", "&", "task", "{", "id", ":", "taskID", ",", "name", ":", "name", ",", "schResponseChan", ":", "make", "(", "chan", "schedule", ".", "Response", ")", ",", "schedule", ":", "s", ",", "state", ":", "core", ".", "TaskStopped", ",", "creationTime", ":", "time", ".", "Now", "(", ")", ",", "workflow", ":", "wf", ",", "manager", ":", "m", ",", "metricsManager", ":", "mm", ",", "deadlineDuration", ":", "DefaultDeadlineDuration", ",", "stopOnFailure", ":", "DefaultStopOnFailure", ",", "eventEmitter", ":", "emitter", ",", "RemoteManagers", ":", "mgrs", ",", "isStream", ":", "stream", ",", "}", "\n", "//set options", "for", "_", ",", "opt", ":=", "range", "opts", "{", "opt", "(", "task", ")", "\n", "}", "\n", "return", "task", ",", "nil", "\n", "}" ]
//NewTask creates a Task
[ "NewTask", "creates", "a", "Task" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/task.go#L95-L131