id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequencelengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
sequencelengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
162,200
blevesearch/bleve
index/scorch/segment/zap/posting.go
PostingsIteratorFrom1Hit
func PostingsIteratorFrom1Hit(docNum1Hit, normBits1Hit uint64, includeFreqNorm, includeLocs bool) (*PostingsIterator, error) { return &PostingsIterator{ docNum1Hit: docNum1Hit, normBits1Hit: normBits1Hit, includeFreqNorm: includeFreqNorm, includeLocs: includeLocs, }, nil }
go
func PostingsIteratorFrom1Hit(docNum1Hit, normBits1Hit uint64, includeFreqNorm, includeLocs bool) (*PostingsIterator, error) { return &PostingsIterator{ docNum1Hit: docNum1Hit, normBits1Hit: normBits1Hit, includeFreqNorm: includeFreqNorm, includeLocs: includeLocs, }, nil }
[ "func", "PostingsIteratorFrom1Hit", "(", "docNum1Hit", ",", "normBits1Hit", "uint64", ",", "includeFreqNorm", ",", "includeLocs", "bool", ")", "(", "*", "PostingsIterator", ",", "error", ")", "{", "return", "&", "PostingsIterator", "{", "docNum1Hit", ":", "docNum1Hit", ",", "normBits1Hit", ":", "normBits1Hit", ",", "includeFreqNorm", ":", "includeFreqNorm", ",", "includeLocs", ":", "includeLocs", ",", "}", ",", "nil", "\n", "}" ]
// PostingsIteratorFrom1Hit constructs a PostingsIterator given a // 1-hit docNum.
[ "PostingsIteratorFrom1Hit", "constructs", "a", "PostingsIterator", "given", "a", "1", "-", "hit", "docNum", "." ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/index/scorch/segment/zap/posting.go#L813-L821
162,201
blevesearch/bleve
numeric/prefix_coded.go
Shift
func (p PrefixCoded) Shift() (uint, error) { if len(p) > 0 { shift := p[0] - ShiftStartInt64 if shift < 0 || shift < 63 { return uint(shift), nil } } return 0, fmt.Errorf("invalid prefix coded value") }
go
func (p PrefixCoded) Shift() (uint, error) { if len(p) > 0 { shift := p[0] - ShiftStartInt64 if shift < 0 || shift < 63 { return uint(shift), nil } } return 0, fmt.Errorf("invalid prefix coded value") }
[ "func", "(", "p", "PrefixCoded", ")", "Shift", "(", ")", "(", "uint", ",", "error", ")", "{", "if", "len", "(", "p", ")", ">", "0", "{", "shift", ":=", "p", "[", "0", "]", "-", "ShiftStartInt64", "\n", "if", "shift", "<", "0", "||", "shift", "<", "63", "{", "return", "uint", "(", "shift", ")", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}" ]
// Shift returns the number of bits shifted // returns 0 if in uninitialized state
[ "Shift", "returns", "the", "number", "of", "bits", "shifted", "returns", "0", "if", "in", "uninitialized", "state" ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/numeric/prefix_coded.go#L71-L79
162,202
blevesearch/bleve
analysis/token/ngram/ngram.go
convertToInt
func convertToInt(val interface{}) (int, error) { var intVal int var floatVal float64 var ok bool intVal, ok = val.(int) if ok { return intVal, nil } floatVal, ok = val.(float64) if ok { return int(floatVal), nil } return 0, fmt.Errorf("failed to convert to int value") }
go
func convertToInt(val interface{}) (int, error) { var intVal int var floatVal float64 var ok bool intVal, ok = val.(int) if ok { return intVal, nil } floatVal, ok = val.(float64) if ok { return int(floatVal), nil } return 0, fmt.Errorf("failed to convert to int value") }
[ "func", "convertToInt", "(", "val", "interface", "{", "}", ")", "(", "int", ",", "error", ")", "{", "var", "intVal", "int", "\n", "var", "floatVal", "float64", "\n", "var", "ok", "bool", "\n\n", "intVal", ",", "ok", "=", "val", ".", "(", "int", ")", "\n", "if", "ok", "{", "return", "intVal", ",", "nil", "\n", "}", "\n\n", "floatVal", ",", "ok", "=", "val", ".", "(", "float64", ")", "\n", "if", "ok", "{", "return", "int", "(", "floatVal", ")", ",", "nil", "\n", "}", "\n\n", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}" ]
// Expects either an int or a flaot64 value
[ "Expects", "either", "an", "int", "or", "a", "flaot64", "value" ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/analysis/token/ngram/ngram.go#L97-L113
162,203
blevesearch/bleve
search/pool.go
NewDocumentMatchPool
func NewDocumentMatchPool(size, sortsize int) *DocumentMatchPool { avail := make(DocumentMatchCollection, size) // pre-allocate the expected number of instances startBlock := make([]DocumentMatch, size) startSorts := make([]string, size*sortsize) // make these initial instances available i, j := 0, 0 for i < size { avail[i] = &startBlock[i] avail[i].Sort = startSorts[j:j] i += 1 j += sortsize } return &DocumentMatchPool{ avail: avail, TooSmall: defaultDocumentMatchPoolTooSmall, } }
go
func NewDocumentMatchPool(size, sortsize int) *DocumentMatchPool { avail := make(DocumentMatchCollection, size) // pre-allocate the expected number of instances startBlock := make([]DocumentMatch, size) startSorts := make([]string, size*sortsize) // make these initial instances available i, j := 0, 0 for i < size { avail[i] = &startBlock[i] avail[i].Sort = startSorts[j:j] i += 1 j += sortsize } return &DocumentMatchPool{ avail: avail, TooSmall: defaultDocumentMatchPoolTooSmall, } }
[ "func", "NewDocumentMatchPool", "(", "size", ",", "sortsize", "int", ")", "*", "DocumentMatchPool", "{", "avail", ":=", "make", "(", "DocumentMatchCollection", ",", "size", ")", "\n", "// pre-allocate the expected number of instances", "startBlock", ":=", "make", "(", "[", "]", "DocumentMatch", ",", "size", ")", "\n", "startSorts", ":=", "make", "(", "[", "]", "string", ",", "size", "*", "sortsize", ")", "\n", "// make these initial instances available", "i", ",", "j", ":=", "0", ",", "0", "\n", "for", "i", "<", "size", "{", "avail", "[", "i", "]", "=", "&", "startBlock", "[", "i", "]", "\n", "avail", "[", "i", "]", ".", "Sort", "=", "startSorts", "[", "j", ":", "j", "]", "\n", "i", "+=", "1", "\n", "j", "+=", "sortsize", "\n", "}", "\n", "return", "&", "DocumentMatchPool", "{", "avail", ":", "avail", ",", "TooSmall", ":", "defaultDocumentMatchPoolTooSmall", ",", "}", "\n", "}" ]
// NewDocumentMatchPool will build a DocumentMatchPool with memory // pre-allocated to accommodate the requested number of DocumentMatch // instances
[ "NewDocumentMatchPool", "will", "build", "a", "DocumentMatchPool", "with", "memory", "pre", "-", "allocated", "to", "accommodate", "the", "requested", "number", "of", "DocumentMatch", "instances" ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/search/pool.go#L50-L67
162,204
blevesearch/bleve
search/pool.go
Get
func (p *DocumentMatchPool) Get() *DocumentMatch { var rv *DocumentMatch if len(p.avail) > 0 { rv, p.avail = p.avail[len(p.avail)-1], p.avail[:len(p.avail)-1] } else { rv = p.TooSmall(p) } return rv }
go
func (p *DocumentMatchPool) Get() *DocumentMatch { var rv *DocumentMatch if len(p.avail) > 0 { rv, p.avail = p.avail[len(p.avail)-1], p.avail[:len(p.avail)-1] } else { rv = p.TooSmall(p) } return rv }
[ "func", "(", "p", "*", "DocumentMatchPool", ")", "Get", "(", ")", "*", "DocumentMatch", "{", "var", "rv", "*", "DocumentMatch", "\n", "if", "len", "(", "p", ".", "avail", ")", ">", "0", "{", "rv", ",", "p", ".", "avail", "=", "p", ".", "avail", "[", "len", "(", "p", ".", "avail", ")", "-", "1", "]", ",", "p", ".", "avail", "[", ":", "len", "(", "p", ".", "avail", ")", "-", "1", "]", "\n", "}", "else", "{", "rv", "=", "p", ".", "TooSmall", "(", "p", ")", "\n", "}", "\n", "return", "rv", "\n", "}" ]
// Get returns an available DocumentMatch from the pool // if the pool was not allocated with sufficient size, an allocation will // occur to satisfy this request. As a side-effect this will grow the size // of the pool.
[ "Get", "returns", "an", "available", "DocumentMatch", "from", "the", "pool", "if", "the", "pool", "was", "not", "allocated", "with", "sufficient", "size", "an", "allocation", "will", "occur", "to", "satisfy", "this", "request", ".", "As", "a", "side", "-", "effect", "this", "will", "grow", "the", "size", "of", "the", "pool", "." ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/search/pool.go#L73-L81
162,205
blevesearch/bleve
search/pool.go
Put
func (p *DocumentMatchPool) Put(d *DocumentMatch) { if d == nil { return } // reset DocumentMatch before returning it to available pool d.Reset() p.avail = append(p.avail, d) }
go
func (p *DocumentMatchPool) Put(d *DocumentMatch) { if d == nil { return } // reset DocumentMatch before returning it to available pool d.Reset() p.avail = append(p.avail, d) }
[ "func", "(", "p", "*", "DocumentMatchPool", ")", "Put", "(", "d", "*", "DocumentMatch", ")", "{", "if", "d", "==", "nil", "{", "return", "\n", "}", "\n", "// reset DocumentMatch before returning it to available pool", "d", ".", "Reset", "(", ")", "\n", "p", ".", "avail", "=", "append", "(", "p", ".", "avail", ",", "d", ")", "\n", "}" ]
// Put returns a DocumentMatch to the pool
[ "Put", "returns", "a", "DocumentMatch", "to", "the", "pool" ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/search/pool.go#L84-L91
162,206
blevesearch/bleve
search/query/multi_phrase.go
NewMultiPhraseQuery
func NewMultiPhraseQuery(terms [][]string, field string) *MultiPhraseQuery { return &MultiPhraseQuery{ Terms: terms, Field: field, } }
go
func NewMultiPhraseQuery(terms [][]string, field string) *MultiPhraseQuery { return &MultiPhraseQuery{ Terms: terms, Field: field, } }
[ "func", "NewMultiPhraseQuery", "(", "terms", "[", "]", "[", "]", "string", ",", "field", "string", ")", "*", "MultiPhraseQuery", "{", "return", "&", "MultiPhraseQuery", "{", "Terms", ":", "terms", ",", "Field", ":", "field", ",", "}", "\n", "}" ]
// NewMultiPhraseQuery creates a new Query for finding // term phrases in the index. // It is like PhraseQuery, but each position in the // phrase may be satisfied by a list of terms // as opposed to just one. // At least one of the terms must exist in the correct // order, at the correct index offsets, in the // specified field. Queried field must have been indexed with // IncludeTermVectors set to true.
[ "NewMultiPhraseQuery", "creates", "a", "new", "Query", "for", "finding", "term", "phrases", "in", "the", "index", ".", "It", "is", "like", "PhraseQuery", "but", "each", "position", "in", "the", "phrase", "may", "be", "satisfied", "by", "a", "list", "of", "terms", "as", "opposed", "to", "just", "one", ".", "At", "least", "one", "of", "the", "terms", "must", "exist", "in", "the", "correct", "order", "at", "the", "correct", "index", "offsets", "in", "the", "specified", "field", ".", "Queried", "field", "must", "have", "been", "indexed", "with", "IncludeTermVectors", "set", "to", "true", "." ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/search/query/multi_phrase.go#L42-L47
162,207
blevesearch/bleve
mapping/reflect.go
parseTagName
func parseTagName(tag string) string { if idx := strings.Index(tag, ","); idx != -1 { return tag[:idx] } return tag }
go
func parseTagName(tag string) string { if idx := strings.Index(tag, ","); idx != -1 { return tag[:idx] } return tag }
[ "func", "parseTagName", "(", "tag", "string", ")", "string", "{", "if", "idx", ":=", "strings", ".", "Index", "(", "tag", ",", "\"", "\"", ")", ";", "idx", "!=", "-", "1", "{", "return", "tag", "[", ":", "idx", "]", "\n", "}", "\n", "return", "tag", "\n", "}" ]
// parseTagName extracts the field name from a struct tag
[ "parseTagName", "extracts", "the", "field", "name", "from", "a", "struct", "tag" ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/mapping/reflect.go#L87-L92
162,208
blevesearch/bleve
search/searcher/search_regexp.go
NewRegexpStringSearcher
func NewRegexpStringSearcher(indexReader index.IndexReader, pattern string, field string, boost float64, options search.SearcherOptions) ( search.Searcher, error) { ir, ok := indexReader.(index.IndexReaderRegexp) if !ok { r, err := regexp.Compile(pattern) if err != nil { return nil, err } return NewRegexpSearcher(indexReader, r, field, boost, options) } fieldDict, err := ir.FieldDictRegexp(field, pattern) if err != nil { return nil, err } defer func() { if cerr := fieldDict.Close(); cerr != nil && err == nil { err = cerr } }() var candidateTerms []string tfd, err := fieldDict.Next() for err == nil && tfd != nil { candidateTerms = append(candidateTerms, tfd.Term) tfd, err = fieldDict.Next() } if err != nil { return nil, err } return NewMultiTermSearcher(indexReader, candidateTerms, field, boost, options, true) }
go
func NewRegexpStringSearcher(indexReader index.IndexReader, pattern string, field string, boost float64, options search.SearcherOptions) ( search.Searcher, error) { ir, ok := indexReader.(index.IndexReaderRegexp) if !ok { r, err := regexp.Compile(pattern) if err != nil { return nil, err } return NewRegexpSearcher(indexReader, r, field, boost, options) } fieldDict, err := ir.FieldDictRegexp(field, pattern) if err != nil { return nil, err } defer func() { if cerr := fieldDict.Close(); cerr != nil && err == nil { err = cerr } }() var candidateTerms []string tfd, err := fieldDict.Next() for err == nil && tfd != nil { candidateTerms = append(candidateTerms, tfd.Term) tfd, err = fieldDict.Next() } if err != nil { return nil, err } return NewMultiTermSearcher(indexReader, candidateTerms, field, boost, options, true) }
[ "func", "NewRegexpStringSearcher", "(", "indexReader", "index", ".", "IndexReader", ",", "pattern", "string", ",", "field", "string", ",", "boost", "float64", ",", "options", "search", ".", "SearcherOptions", ")", "(", "search", ".", "Searcher", ",", "error", ")", "{", "ir", ",", "ok", ":=", "indexReader", ".", "(", "index", ".", "IndexReaderRegexp", ")", "\n", "if", "!", "ok", "{", "r", ",", "err", ":=", "regexp", ".", "Compile", "(", "pattern", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "NewRegexpSearcher", "(", "indexReader", ",", "r", ",", "field", ",", "boost", ",", "options", ")", "\n", "}", "\n\n", "fieldDict", ",", "err", ":=", "ir", ".", "FieldDictRegexp", "(", "field", ",", "pattern", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "func", "(", ")", "{", "if", "cerr", ":=", "fieldDict", ".", "Close", "(", ")", ";", "cerr", "!=", "nil", "&&", "err", "==", "nil", "{", "err", "=", "cerr", "\n", "}", "\n", "}", "(", ")", "\n\n", "var", "candidateTerms", "[", "]", "string", "\n\n", "tfd", ",", "err", ":=", "fieldDict", ".", "Next", "(", ")", "\n", "for", "err", "==", "nil", "&&", "tfd", "!=", "nil", "{", "candidateTerms", "=", "append", "(", "candidateTerms", ",", "tfd", ".", "Term", ")", "\n", "tfd", ",", "err", "=", "fieldDict", ".", "Next", "(", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "NewMultiTermSearcher", "(", "indexReader", ",", "candidateTerms", ",", "field", ",", "boost", ",", "options", ",", "true", ")", "\n", "}" ]
// NewRegexpStringSearcher is similar to NewRegexpSearcher, but // additionally optimizes for index readers that handle regexp's.
[ "NewRegexpStringSearcher", "is", "similar", "to", "NewRegexpSearcher", "but", "additionally", "optimizes", "for", "index", "readers", "that", "handle", "regexp", "s", "." ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/search/searcher/search_regexp.go#L26-L62
162,209
blevesearch/bleve
index/scorch/stats.go
ToMap
func (s *Stats) ToMap() map[string]interface{} { m := map[string]interface{}{} sve := reflect.ValueOf(s).Elem() svet := sve.Type() for i := 0; i < svet.NumField(); i++ { svef := sve.Field(i) if svef.CanAddr() { svefp := svef.Addr().Interface() m[svet.Field(i).Name] = atomic.LoadUint64(svefp.(*uint64)) } } return m }
go
func (s *Stats) ToMap() map[string]interface{} { m := map[string]interface{}{} sve := reflect.ValueOf(s).Elem() svet := sve.Type() for i := 0; i < svet.NumField(); i++ { svef := sve.Field(i) if svef.CanAddr() { svefp := svef.Addr().Interface() m[svet.Field(i).Name] = atomic.LoadUint64(svefp.(*uint64)) } } return m }
[ "func", "(", "s", "*", "Stats", ")", "ToMap", "(", ")", "map", "[", "string", "]", "interface", "{", "}", "{", "m", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "}", "\n", "sve", ":=", "reflect", ".", "ValueOf", "(", "s", ")", ".", "Elem", "(", ")", "\n", "svet", ":=", "sve", ".", "Type", "(", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "svet", ".", "NumField", "(", ")", ";", "i", "++", "{", "svef", ":=", "sve", ".", "Field", "(", "i", ")", "\n", "if", "svef", ".", "CanAddr", "(", ")", "{", "svefp", ":=", "svef", ".", "Addr", "(", ")", ".", "Interface", "(", ")", "\n", "m", "[", "svet", ".", "Field", "(", "i", ")", ".", "Name", "]", "=", "atomic", ".", "LoadUint64", "(", "svefp", ".", "(", "*", "uint64", ")", ")", "\n", "}", "\n", "}", "\n", "return", "m", "\n", "}" ]
// atomically populates the returned map
[ "atomically", "populates", "the", "returned", "map" ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/index/scorch/stats.go#L122-L134
162,210
blevesearch/bleve
index.go
Size
func (b *Batch) Size() int { return len(b.internal.IndexOps) + len(b.internal.InternalOps) }
go
func (b *Batch) Size() int { return len(b.internal.IndexOps) + len(b.internal.InternalOps) }
[ "func", "(", "b", "*", "Batch", ")", "Size", "(", ")", "int", "{", "return", "len", "(", "b", ".", "internal", ".", "IndexOps", ")", "+", "len", "(", "b", ".", "internal", ".", "InternalOps", ")", "\n", "}" ]
// Size returns the total number of operations inside the batch // including normal index operations and internal operations.
[ "Size", "returns", "the", "total", "number", "of", "operations", "inside", "the", "batch", "including", "normal", "index", "operations", "and", "internal", "operations", "." ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/index.go#L106-L108
162,211
blevesearch/bleve
index.go
Reset
func (b *Batch) Reset() { b.internal.Reset() b.lastDocSize = 0 b.totalSize = 0 }
go
func (b *Batch) Reset() { b.internal.Reset() b.lastDocSize = 0 b.totalSize = 0 }
[ "func", "(", "b", "*", "Batch", ")", "Reset", "(", ")", "{", "b", ".", "internal", ".", "Reset", "(", ")", "\n", "b", ".", "lastDocSize", "=", "0", "\n", "b", ".", "totalSize", "=", "0", "\n", "}" ]
// Reset returns a Batch to the empty state so that it can // be re-used in the future.
[ "Reset", "returns", "a", "Batch", "to", "the", "empty", "state", "so", "that", "it", "can", "be", "re", "-", "used", "in", "the", "future", "." ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/index.go#L118-L122
162,212
blevesearch/bleve
index/scorch/segment/zap/count.go
Write
func (c *CountHashWriter) Write(b []byte) (int, error) { n, err := c.w.Write(b) c.crc = crc32.Update(c.crc, crc32.IEEETable, b[:n]) c.n += n if c.s != nil { c.s.ReportBytesWritten(uint64(n)) } return n, err }
go
func (c *CountHashWriter) Write(b []byte) (int, error) { n, err := c.w.Write(b) c.crc = crc32.Update(c.crc, crc32.IEEETable, b[:n]) c.n += n if c.s != nil { c.s.ReportBytesWritten(uint64(n)) } return n, err }
[ "func", "(", "c", "*", "CountHashWriter", ")", "Write", "(", "b", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "n", ",", "err", ":=", "c", ".", "w", ".", "Write", "(", "b", ")", "\n", "c", ".", "crc", "=", "crc32", ".", "Update", "(", "c", ".", "crc", ",", "crc32", ".", "IEEETable", ",", "b", "[", ":", "n", "]", ")", "\n", "c", ".", "n", "+=", "n", "\n", "if", "c", ".", "s", "!=", "nil", "{", "c", ".", "s", ".", "ReportBytesWritten", "(", "uint64", "(", "n", ")", ")", "\n", "}", "\n", "return", "n", ",", "err", "\n", "}" ]
// Write writes the provided bytes to the wrapped writer and counts the bytes
[ "Write", "writes", "the", "provided", "bytes", "to", "the", "wrapped", "writer", "and", "counts", "the", "bytes" ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/index/scorch/segment/zap/count.go#L43-L51
162,213
blevesearch/bleve
index/scorch/snapshot_segment.go
DocNumbersLive
func (s *SegmentSnapshot) DocNumbersLive() *roaring.Bitmap { rv := roaring.NewBitmap() rv.AddRange(0, s.segment.Count()) if s.deleted != nil { rv.AndNot(s.deleted) } return rv }
go
func (s *SegmentSnapshot) DocNumbersLive() *roaring.Bitmap { rv := roaring.NewBitmap() rv.AddRange(0, s.segment.Count()) if s.deleted != nil { rv.AndNot(s.deleted) } return rv }
[ "func", "(", "s", "*", "SegmentSnapshot", ")", "DocNumbersLive", "(", ")", "*", "roaring", ".", "Bitmap", "{", "rv", ":=", "roaring", ".", "NewBitmap", "(", ")", "\n", "rv", ".", "AddRange", "(", "0", ",", "s", ".", "segment", ".", "Count", "(", ")", ")", "\n", "if", "s", ".", "deleted", "!=", "nil", "{", "rv", ".", "AndNot", "(", "s", ".", "deleted", ")", "\n", "}", "\n", "return", "rv", "\n", "}" ]
// DocNumbersLive returns a bitmap containing doc numbers for all live docs
[ "DocNumbersLive", "returns", "a", "bitmap", "containing", "doc", "numbers", "for", "all", "live", "docs" ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/index/scorch/snapshot_segment.go#L93-L100
162,214
blevesearch/bleve
index/scorch/snapshot_segment.go
hasFields
func (c *cachedDocs) hasFields(fields []string) bool { c.m.Lock() for _, field := range fields { if _, exists := c.cache[field]; !exists { c.m.Unlock() return false // found a field not in cache } } c.m.Unlock() return true }
go
func (c *cachedDocs) hasFields(fields []string) bool { c.m.Lock() for _, field := range fields { if _, exists := c.cache[field]; !exists { c.m.Unlock() return false // found a field not in cache } } c.m.Unlock() return true }
[ "func", "(", "c", "*", "cachedDocs", ")", "hasFields", "(", "fields", "[", "]", "string", ")", "bool", "{", "c", ".", "m", ".", "Lock", "(", ")", "\n", "for", "_", ",", "field", ":=", "range", "fields", "{", "if", "_", ",", "exists", ":=", "c", ".", "cache", "[", "field", "]", ";", "!", "exists", "{", "c", ".", "m", ".", "Unlock", "(", ")", "\n", "return", "false", "// found a field not in cache", "\n", "}", "\n", "}", "\n", "c", ".", "m", ".", "Unlock", "(", ")", "\n", "return", "true", "\n", "}" ]
// hasFields returns true if the cache has all the given fields
[ "hasFields", "returns", "true", "if", "the", "cache", "has", "all", "the", "given", "fields" ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/index/scorch/snapshot_segment.go#L228-L238
162,215
blevesearch/bleve
index/scorch/segment/zap/dict.go
PostingsList
func (d *Dictionary) PostingsList(term []byte, except *roaring.Bitmap, prealloc segment.PostingsList) (segment.PostingsList, error) { var preallocPL *PostingsList pl, ok := prealloc.(*PostingsList) if ok && pl != nil { preallocPL = pl } return d.postingsList(term, except, preallocPL) }
go
func (d *Dictionary) PostingsList(term []byte, except *roaring.Bitmap, prealloc segment.PostingsList) (segment.PostingsList, error) { var preallocPL *PostingsList pl, ok := prealloc.(*PostingsList) if ok && pl != nil { preallocPL = pl } return d.postingsList(term, except, preallocPL) }
[ "func", "(", "d", "*", "Dictionary", ")", "PostingsList", "(", "term", "[", "]", "byte", ",", "except", "*", "roaring", ".", "Bitmap", ",", "prealloc", "segment", ".", "PostingsList", ")", "(", "segment", ".", "PostingsList", ",", "error", ")", "{", "var", "preallocPL", "*", "PostingsList", "\n", "pl", ",", "ok", ":=", "prealloc", ".", "(", "*", "PostingsList", ")", "\n", "if", "ok", "&&", "pl", "!=", "nil", "{", "preallocPL", "=", "pl", "\n", "}", "\n", "return", "d", ".", "postingsList", "(", "term", ",", "except", ",", "preallocPL", ")", "\n", "}" ]
// PostingsList returns the postings list for the specified term
[ "PostingsList", "returns", "the", "postings", "list", "for", "the", "specified", "term" ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/index/scorch/segment/zap/dict.go#L37-L45
162,216
blevesearch/bleve
index/scorch/segment/zap/dict.go
Iterator
func (d *Dictionary) Iterator() segment.DictionaryIterator { rv := &DictionaryIterator{ d: d, } if d.fst != nil { itr, err := d.fst.Iterator(nil, nil) if err == nil { rv.itr = itr } else if err != vellum.ErrIteratorDone { rv.err = err } } return rv }
go
func (d *Dictionary) Iterator() segment.DictionaryIterator { rv := &DictionaryIterator{ d: d, } if d.fst != nil { itr, err := d.fst.Iterator(nil, nil) if err == nil { rv.itr = itr } else if err != vellum.ErrIteratorDone { rv.err = err } } return rv }
[ "func", "(", "d", "*", "Dictionary", ")", "Iterator", "(", ")", "segment", ".", "DictionaryIterator", "{", "rv", ":=", "&", "DictionaryIterator", "{", "d", ":", "d", ",", "}", "\n\n", "if", "d", ".", "fst", "!=", "nil", "{", "itr", ",", "err", ":=", "d", ".", "fst", ".", "Iterator", "(", "nil", ",", "nil", ")", "\n", "if", "err", "==", "nil", "{", "rv", ".", "itr", "=", "itr", "\n", "}", "else", "if", "err", "!=", "vellum", ".", "ErrIteratorDone", "{", "rv", ".", "err", "=", "err", "\n", "}", "\n", "}", "\n\n", "return", "rv", "\n", "}" ]
// Iterator returns an iterator for this dictionary
[ "Iterator", "returns", "an", "iterator", "for", "this", "dictionary" ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/index/scorch/segment/zap/dict.go#L99-L114
162,217
blevesearch/bleve
index/scorch/segment/zap/dict.go
PrefixIterator
func (d *Dictionary) PrefixIterator(prefix string) segment.DictionaryIterator { rv := &DictionaryIterator{ d: d, } kBeg := []byte(prefix) kEnd := segment.IncrementBytes(kBeg) if d.fst != nil { itr, err := d.fst.Iterator(kBeg, kEnd) if err == nil { rv.itr = itr } else if err != vellum.ErrIteratorDone { rv.err = err } } return rv }
go
func (d *Dictionary) PrefixIterator(prefix string) segment.DictionaryIterator { rv := &DictionaryIterator{ d: d, } kBeg := []byte(prefix) kEnd := segment.IncrementBytes(kBeg) if d.fst != nil { itr, err := d.fst.Iterator(kBeg, kEnd) if err == nil { rv.itr = itr } else if err != vellum.ErrIteratorDone { rv.err = err } } return rv }
[ "func", "(", "d", "*", "Dictionary", ")", "PrefixIterator", "(", "prefix", "string", ")", "segment", ".", "DictionaryIterator", "{", "rv", ":=", "&", "DictionaryIterator", "{", "d", ":", "d", ",", "}", "\n\n", "kBeg", ":=", "[", "]", "byte", "(", "prefix", ")", "\n", "kEnd", ":=", "segment", ".", "IncrementBytes", "(", "kBeg", ")", "\n\n", "if", "d", ".", "fst", "!=", "nil", "{", "itr", ",", "err", ":=", "d", ".", "fst", ".", "Iterator", "(", "kBeg", ",", "kEnd", ")", "\n", "if", "err", "==", "nil", "{", "rv", ".", "itr", "=", "itr", "\n", "}", "else", "if", "err", "!=", "vellum", ".", "ErrIteratorDone", "{", "rv", ".", "err", "=", "err", "\n", "}", "\n", "}", "\n\n", "return", "rv", "\n", "}" ]
// PrefixIterator returns an iterator which only visits terms having the // the specified prefix
[ "PrefixIterator", "returns", "an", "iterator", "which", "only", "visits", "terms", "having", "the", "the", "specified", "prefix" ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/index/scorch/segment/zap/dict.go#L118-L136
162,218
blevesearch/bleve
index/scorch/segment/zap/dict.go
Next
func (i *DictionaryIterator) Next() (*index.DictEntry, error) { if i.err != nil && i.err != vellum.ErrIteratorDone { return nil, i.err } else if i.itr == nil || i.err == vellum.ErrIteratorDone { return nil, nil } term, postingsOffset := i.itr.Current() i.entry.Term = string(term) if !i.omitCount { i.err = i.tmp.read(postingsOffset, i.d) if i.err != nil { return nil, i.err } i.entry.Count = i.tmp.Count() } i.err = i.itr.Next() return &i.entry, nil }
go
func (i *DictionaryIterator) Next() (*index.DictEntry, error) { if i.err != nil && i.err != vellum.ErrIteratorDone { return nil, i.err } else if i.itr == nil || i.err == vellum.ErrIteratorDone { return nil, nil } term, postingsOffset := i.itr.Current() i.entry.Term = string(term) if !i.omitCount { i.err = i.tmp.read(postingsOffset, i.d) if i.err != nil { return nil, i.err } i.entry.Count = i.tmp.Count() } i.err = i.itr.Next() return &i.entry, nil }
[ "func", "(", "i", "*", "DictionaryIterator", ")", "Next", "(", ")", "(", "*", "index", ".", "DictEntry", ",", "error", ")", "{", "if", "i", ".", "err", "!=", "nil", "&&", "i", ".", "err", "!=", "vellum", ".", "ErrIteratorDone", "{", "return", "nil", ",", "i", ".", "err", "\n", "}", "else", "if", "i", ".", "itr", "==", "nil", "||", "i", ".", "err", "==", "vellum", ".", "ErrIteratorDone", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "term", ",", "postingsOffset", ":=", "i", ".", "itr", ".", "Current", "(", ")", "\n", "i", ".", "entry", ".", "Term", "=", "string", "(", "term", ")", "\n", "if", "!", "i", ".", "omitCount", "{", "i", ".", "err", "=", "i", ".", "tmp", ".", "read", "(", "postingsOffset", ",", "i", ".", "d", ")", "\n", "if", "i", ".", "err", "!=", "nil", "{", "return", "nil", ",", "i", ".", "err", "\n", "}", "\n", "i", ".", "entry", ".", "Count", "=", "i", ".", "tmp", ".", "Count", "(", ")", "\n", "}", "\n", "i", ".", "err", "=", "i", ".", "itr", ".", "Next", "(", ")", "\n", "return", "&", "i", ".", "entry", ",", "nil", "\n", "}" ]
// Next returns the next entry in the dictionary
[ "Next", "returns", "the", "next", "entry", "in", "the", "dictionary" ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/index/scorch/segment/zap/dict.go#L242-L259
162,219
blevesearch/bleve
mapping/field.go
NewTextFieldMapping
func NewTextFieldMapping() *FieldMapping { return &FieldMapping{ Type: "text", Store: true, Index: true, IncludeTermVectors: true, IncludeInAll: true, DocValues: true, } }
go
func NewTextFieldMapping() *FieldMapping { return &FieldMapping{ Type: "text", Store: true, Index: true, IncludeTermVectors: true, IncludeInAll: true, DocValues: true, } }
[ "func", "NewTextFieldMapping", "(", ")", "*", "FieldMapping", "{", "return", "&", "FieldMapping", "{", "Type", ":", "\"", "\"", ",", "Store", ":", "true", ",", "Index", ":", "true", ",", "IncludeTermVectors", ":", "true", ",", "IncludeInAll", ":", "true", ",", "DocValues", ":", "true", ",", "}", "\n", "}" ]
// NewTextFieldMapping returns a default field mapping for text
[ "NewTextFieldMapping", "returns", "a", "default", "field", "mapping", "for", "text" ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/mapping/field.go#L65-L74
162,220
blevesearch/bleve
mapping/field.go
NewNumericFieldMapping
func NewNumericFieldMapping() *FieldMapping { return &FieldMapping{ Type: "number", Store: true, Index: true, IncludeInAll: true, DocValues: true, } }
go
func NewNumericFieldMapping() *FieldMapping { return &FieldMapping{ Type: "number", Store: true, Index: true, IncludeInAll: true, DocValues: true, } }
[ "func", "NewNumericFieldMapping", "(", ")", "*", "FieldMapping", "{", "return", "&", "FieldMapping", "{", "Type", ":", "\"", "\"", ",", "Store", ":", "true", ",", "Index", ":", "true", ",", "IncludeInAll", ":", "true", ",", "DocValues", ":", "true", ",", "}", "\n", "}" ]
// NewNumericFieldMapping returns a default field mapping for numbers
[ "NewNumericFieldMapping", "returns", "a", "default", "field", "mapping", "for", "numbers" ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/mapping/field.go#L85-L93
162,221
blevesearch/bleve
mapping/field.go
NewDateTimeFieldMapping
func NewDateTimeFieldMapping() *FieldMapping { return &FieldMapping{ Type: "datetime", Store: true, Index: true, IncludeInAll: true, DocValues: true, } }
go
func NewDateTimeFieldMapping() *FieldMapping { return &FieldMapping{ Type: "datetime", Store: true, Index: true, IncludeInAll: true, DocValues: true, } }
[ "func", "NewDateTimeFieldMapping", "(", ")", "*", "FieldMapping", "{", "return", "&", "FieldMapping", "{", "Type", ":", "\"", "\"", ",", "Store", ":", "true", ",", "Index", ":", "true", ",", "IncludeInAll", ":", "true", ",", "DocValues", ":", "true", ",", "}", "\n", "}" ]
// NewDateTimeFieldMapping returns a default field mapping for dates
[ "NewDateTimeFieldMapping", "returns", "a", "default", "field", "mapping", "for", "dates" ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/mapping/field.go#L104-L112
162,222
blevesearch/bleve
mapping/field.go
NewBooleanFieldMapping
func NewBooleanFieldMapping() *FieldMapping { return &FieldMapping{ Type: "boolean", Store: true, Index: true, IncludeInAll: true, DocValues: true, } }
go
func NewBooleanFieldMapping() *FieldMapping { return &FieldMapping{ Type: "boolean", Store: true, Index: true, IncludeInAll: true, DocValues: true, } }
[ "func", "NewBooleanFieldMapping", "(", ")", "*", "FieldMapping", "{", "return", "&", "FieldMapping", "{", "Type", ":", "\"", "\"", ",", "Store", ":", "true", ",", "Index", ":", "true", ",", "IncludeInAll", ":", "true", ",", "DocValues", ":", "true", ",", "}", "\n", "}" ]
// NewBooleanFieldMapping returns a default field mapping for booleans
[ "NewBooleanFieldMapping", "returns", "a", "default", "field", "mapping", "for", "booleans" ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/mapping/field.go#L123-L131
162,223
blevesearch/bleve
mapping/field.go
NewGeoPointFieldMapping
func NewGeoPointFieldMapping() *FieldMapping { return &FieldMapping{ Type: "geopoint", Store: true, Index: true, IncludeInAll: true, DocValues: true, } }
go
func NewGeoPointFieldMapping() *FieldMapping { return &FieldMapping{ Type: "geopoint", Store: true, Index: true, IncludeInAll: true, DocValues: true, } }
[ "func", "NewGeoPointFieldMapping", "(", ")", "*", "FieldMapping", "{", "return", "&", "FieldMapping", "{", "Type", ":", "\"", "\"", ",", "Store", ":", "true", ",", "Index", ":", "true", ",", "IncludeInAll", ":", "true", ",", "DocValues", ":", "true", ",", "}", "\n", "}" ]
// NewGeoPointFieldMapping returns a default field mapping for geo points
[ "NewGeoPointFieldMapping", "returns", "a", "default", "field", "mapping", "for", "geo", "points" ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/mapping/field.go#L142-L150
162,224
blevesearch/bleve
mapping/field.go
Options
func (fm *FieldMapping) Options() document.IndexingOptions { var rv document.IndexingOptions if fm.Store { rv |= document.StoreField } if fm.Index { rv |= document.IndexField } if fm.IncludeTermVectors { rv |= document.IncludeTermVectors } if fm.DocValues { rv |= document.DocValues } return rv }
go
func (fm *FieldMapping) Options() document.IndexingOptions { var rv document.IndexingOptions if fm.Store { rv |= document.StoreField } if fm.Index { rv |= document.IndexField } if fm.IncludeTermVectors { rv |= document.IncludeTermVectors } if fm.DocValues { rv |= document.DocValues } return rv }
[ "func", "(", "fm", "*", "FieldMapping", ")", "Options", "(", ")", "document", ".", "IndexingOptions", "{", "var", "rv", "document", ".", "IndexingOptions", "\n", "if", "fm", ".", "Store", "{", "rv", "|=", "document", ".", "StoreField", "\n", "}", "\n", "if", "fm", ".", "Index", "{", "rv", "|=", "document", ".", "IndexField", "\n", "}", "\n", "if", "fm", ".", "IncludeTermVectors", "{", "rv", "|=", "document", ".", "IncludeTermVectors", "\n", "}", "\n", "if", "fm", ".", "DocValues", "{", "rv", "|=", "document", ".", "DocValues", "\n", "}", "\n", "return", "rv", "\n", "}" ]
// Options returns the indexing options for this field.
[ "Options", "returns", "the", "indexing", "options", "for", "this", "field", "." ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/mapping/field.go#L153-L168
162,225
blevesearch/bleve
index/scorch/segment/zap/docvalues.go
VisitDocumentFieldTerms
func (s *Segment) VisitDocumentFieldTerms(localDocNum uint64, fields []string, visitor index.DocumentFieldTermVisitor, dvsIn segment.DocVisitState) ( segment.DocVisitState, error) { dvs, ok := dvsIn.(*docVisitState) if !ok || dvs == nil { dvs = &docVisitState{} } else { if dvs.segment != s { dvs.segment = s dvs.dvrs = nil } } var fieldIDPlus1 uint16 if dvs.dvrs == nil { dvs.dvrs = make(map[uint16]*docValueReader, len(fields)) for _, field := range fields { if fieldIDPlus1, ok = s.fieldsMap[field]; !ok { continue } fieldID := fieldIDPlus1 - 1 if dvIter, exists := s.fieldDvReaders[fieldID]; exists && dvIter != nil { dvs.dvrs[fieldID] = dvIter.cloneInto(dvs.dvrs[fieldID]) } } } // find the chunkNumber where the docValues are stored docInChunk := localDocNum / uint64(s.chunkFactor) var dvr *docValueReader for _, field := range fields { if fieldIDPlus1, ok = s.fieldsMap[field]; !ok { continue } fieldID := fieldIDPlus1 - 1 if dvr, ok = dvs.dvrs[fieldID]; ok && dvr != nil { // check if the chunk is already loaded if docInChunk != dvr.curChunkNumber() { err := dvr.loadDvChunk(docInChunk, &s.SegmentBase) if err != nil { return dvs, err } } _ = dvr.visitDocValues(localDocNum, visitor) } } return dvs, nil }
go
func (s *Segment) VisitDocumentFieldTerms(localDocNum uint64, fields []string, visitor index.DocumentFieldTermVisitor, dvsIn segment.DocVisitState) ( segment.DocVisitState, error) { dvs, ok := dvsIn.(*docVisitState) if !ok || dvs == nil { dvs = &docVisitState{} } else { if dvs.segment != s { dvs.segment = s dvs.dvrs = nil } } var fieldIDPlus1 uint16 if dvs.dvrs == nil { dvs.dvrs = make(map[uint16]*docValueReader, len(fields)) for _, field := range fields { if fieldIDPlus1, ok = s.fieldsMap[field]; !ok { continue } fieldID := fieldIDPlus1 - 1 if dvIter, exists := s.fieldDvReaders[fieldID]; exists && dvIter != nil { dvs.dvrs[fieldID] = dvIter.cloneInto(dvs.dvrs[fieldID]) } } } // find the chunkNumber where the docValues are stored docInChunk := localDocNum / uint64(s.chunkFactor) var dvr *docValueReader for _, field := range fields { if fieldIDPlus1, ok = s.fieldsMap[field]; !ok { continue } fieldID := fieldIDPlus1 - 1 if dvr, ok = dvs.dvrs[fieldID]; ok && dvr != nil { // check if the chunk is already loaded if docInChunk != dvr.curChunkNumber() { err := dvr.loadDvChunk(docInChunk, &s.SegmentBase) if err != nil { return dvs, err } } _ = dvr.visitDocValues(localDocNum, visitor) } } return dvs, nil }
[ "func", "(", "s", "*", "Segment", ")", "VisitDocumentFieldTerms", "(", "localDocNum", "uint64", ",", "fields", "[", "]", "string", ",", "visitor", "index", ".", "DocumentFieldTermVisitor", ",", "dvsIn", "segment", ".", "DocVisitState", ")", "(", "segment", ".", "DocVisitState", ",", "error", ")", "{", "dvs", ",", "ok", ":=", "dvsIn", ".", "(", "*", "docVisitState", ")", "\n", "if", "!", "ok", "||", "dvs", "==", "nil", "{", "dvs", "=", "&", "docVisitState", "{", "}", "\n", "}", "else", "{", "if", "dvs", ".", "segment", "!=", "s", "{", "dvs", ".", "segment", "=", "s", "\n", "dvs", ".", "dvrs", "=", "nil", "\n", "}", "\n", "}", "\n\n", "var", "fieldIDPlus1", "uint16", "\n", "if", "dvs", ".", "dvrs", "==", "nil", "{", "dvs", ".", "dvrs", "=", "make", "(", "map", "[", "uint16", "]", "*", "docValueReader", ",", "len", "(", "fields", ")", ")", "\n", "for", "_", ",", "field", ":=", "range", "fields", "{", "if", "fieldIDPlus1", ",", "ok", "=", "s", ".", "fieldsMap", "[", "field", "]", ";", "!", "ok", "{", "continue", "\n", "}", "\n", "fieldID", ":=", "fieldIDPlus1", "-", "1", "\n", "if", "dvIter", ",", "exists", ":=", "s", ".", "fieldDvReaders", "[", "fieldID", "]", ";", "exists", "&&", "dvIter", "!=", "nil", "{", "dvs", ".", "dvrs", "[", "fieldID", "]", "=", "dvIter", ".", "cloneInto", "(", "dvs", ".", "dvrs", "[", "fieldID", "]", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// find the chunkNumber where the docValues are stored", "docInChunk", ":=", "localDocNum", "/", "uint64", "(", "s", ".", "chunkFactor", ")", "\n", "var", "dvr", "*", "docValueReader", "\n", "for", "_", ",", "field", ":=", "range", "fields", "{", "if", "fieldIDPlus1", ",", "ok", "=", "s", ".", "fieldsMap", "[", "field", "]", ";", "!", "ok", "{", "continue", "\n", "}", "\n", "fieldID", ":=", "fieldIDPlus1", "-", "1", "\n", "if", "dvr", ",", "ok", "=", "dvs", ".", "dvrs", "[", "fieldID", "]", ";", "ok", "&&", "dvr", "!=", "nil", "{", "// check if the chunk is already loaded", "if", "docInChunk", "!=", "dvr", ".", "curChunkNumber", "(", ")", "{", "err", ":=", "dvr", ".", "loadDvChunk", "(", "docInChunk", ",", "&", "s", ".", "SegmentBase", ")", "\n", "if", "err", "!=", "nil", "{", "return", "dvs", ",", "err", "\n", "}", "\n", "}", "\n\n", "_", "=", "dvr", ".", "visitDocValues", "(", "localDocNum", ",", "visitor", ")", "\n", "}", "\n", "}", "\n", "return", "dvs", ",", "nil", "\n", "}" ]
// VisitDocumentFieldTerms is an implementation of the // DocumentFieldTermVisitable interface
[ "VisitDocumentFieldTerms", "is", "an", "implementation", "of", "the", "DocumentFieldTermVisitable", "interface" ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/index/scorch/segment/zap/docvalues.go#L255-L304
162,226
blevesearch/bleve
geo/geohash.go
newEncoding
func newEncoding(encoder string) *encoding { e := new(encoding) e.enc = encoder for i := 0; i < len(e.dec); i++ { e.dec[i] = 0xff } for i := 0; i < len(encoder); i++ { e.dec[encoder[i]] = byte(i) } return e }
go
func newEncoding(encoder string) *encoding { e := new(encoding) e.enc = encoder for i := 0; i < len(e.dec); i++ { e.dec[i] = 0xff } for i := 0; i < len(encoder); i++ { e.dec[encoder[i]] = byte(i) } return e }
[ "func", "newEncoding", "(", "encoder", "string", ")", "*", "encoding", "{", "e", ":=", "new", "(", "encoding", ")", "\n", "e", ".", "enc", "=", "encoder", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "e", ".", "dec", ")", ";", "i", "++", "{", "e", ".", "dec", "[", "i", "]", "=", "0xff", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "encoder", ")", ";", "i", "++", "{", "e", ".", "dec", "[", "encoder", "[", "i", "]", "]", "=", "byte", "(", "i", ")", "\n", "}", "\n", "return", "e", "\n", "}" ]
// newEncoding constructs a new encoding defined by the given alphabet, // which must be a 32-byte string.
[ "newEncoding", "constructs", "a", "new", "encoding", "defined", "by", "the", "given", "alphabet", "which", "must", "be", "a", "32", "-", "byte", "string", "." ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/geo/geohash.go#L38-L48
162,227
blevesearch/bleve
geo/geohash.go
decode
func (e *encoding) decode(s string) uint64 { x := uint64(0) for i := 0; i < len(s); i++ { x = (x << 5) | uint64(e.dec[s[i]]) } return x }
go
func (e *encoding) decode(s string) uint64 { x := uint64(0) for i := 0; i < len(s); i++ { x = (x << 5) | uint64(e.dec[s[i]]) } return x }
[ "func", "(", "e", "*", "encoding", ")", "decode", "(", "s", "string", ")", "uint64", "{", "x", ":=", "uint64", "(", "0", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "s", ")", ";", "i", "++", "{", "x", "=", "(", "x", "<<", "5", ")", "|", "uint64", "(", "e", ".", "dec", "[", "s", "[", "i", "]", "]", ")", "\n", "}", "\n", "return", "x", "\n", "}" ]
// Decode string into bits of a 64-bit word. The string s may be at most 12 // characters.
[ "Decode", "string", "into", "bits", "of", "a", "64", "-", "bit", "word", ".", "The", "string", "s", "may", "be", "at", "most", "12", "characters", "." ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/geo/geohash.go#L52-L58
162,228
blevesearch/bleve
geo/geohash.go
geoBoundingBox
func geoBoundingBox(hash string) geoBox { bits := uint(5 * len(hash)) inthash := base32encoding.decode(hash) return geoBoundingBoxIntWithPrecision(inthash, bits) }
go
func geoBoundingBox(hash string) geoBox { bits := uint(5 * len(hash)) inthash := base32encoding.decode(hash) return geoBoundingBoxIntWithPrecision(inthash, bits) }
[ "func", "geoBoundingBox", "(", "hash", "string", ")", "geoBox", "{", "bits", ":=", "uint", "(", "5", "*", "len", "(", "hash", ")", ")", "\n", "inthash", ":=", "base32encoding", ".", "decode", "(", "hash", ")", "\n", "return", "geoBoundingBoxIntWithPrecision", "(", "inthash", ",", "bits", ")", "\n", "}" ]
// BoundingBox returns the region encoded by the given string geohash.
[ "BoundingBox", "returns", "the", "region", "encoded", "by", "the", "given", "string", "geohash", "." ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/geo/geohash.go#L74-L78
162,229
blevesearch/bleve
geo/geohash.go
round
func (b geoBox) round() (lat, lng float64) { x := maxDecimalPower(b.maxLat - b.minLat) lat = math.Ceil(b.minLat/x) * x x = maxDecimalPower(b.maxLng - b.minLng) lng = math.Ceil(b.minLng/x) * x return }
go
func (b geoBox) round() (lat, lng float64) { x := maxDecimalPower(b.maxLat - b.minLat) lat = math.Ceil(b.minLat/x) * x x = maxDecimalPower(b.maxLng - b.minLng) lng = math.Ceil(b.minLng/x) * x return }
[ "func", "(", "b", "geoBox", ")", "round", "(", ")", "(", "lat", ",", "lng", "float64", ")", "{", "x", ":=", "maxDecimalPower", "(", "b", ".", "maxLat", "-", "b", ".", "minLat", ")", "\n", "lat", "=", "math", ".", "Ceil", "(", "b", ".", "minLat", "/", "x", ")", "*", "x", "\n", "x", "=", "maxDecimalPower", "(", "b", ".", "maxLng", "-", "b", ".", "minLng", ")", "\n", "lng", "=", "math", ".", "Ceil", "(", "b", ".", "minLng", "/", "x", ")", "*", "x", "\n", "return", "\n", "}" ]
// Round returns a point inside the box, making an effort to round to minimal // precision.
[ "Round", "returns", "a", "point", "inside", "the", "box", "making", "an", "effort", "to", "round", "to", "minimal", "precision", "." ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/geo/geohash.go#L90-L96
162,230
blevesearch/bleve
geo/geohash.go
errorWithPrecision
func errorWithPrecision(bits uint) (latErr, lngErr float64) { b := int(bits) latBits := b / 2 lngBits := b - latBits latErr = math.Ldexp(180.0, -latBits) lngErr = math.Ldexp(360.0, -lngBits) return }
go
func errorWithPrecision(bits uint) (latErr, lngErr float64) { b := int(bits) latBits := b / 2 lngBits := b - latBits latErr = math.Ldexp(180.0, -latBits) lngErr = math.Ldexp(360.0, -lngBits) return }
[ "func", "errorWithPrecision", "(", "bits", "uint", ")", "(", "latErr", ",", "lngErr", "float64", ")", "{", "b", ":=", "int", "(", "bits", ")", "\n", "latBits", ":=", "b", "/", "2", "\n", "lngBits", ":=", "b", "-", "latBits", "\n", "latErr", "=", "math", ".", "Ldexp", "(", "180.0", ",", "-", "latBits", ")", "\n", "lngErr", "=", "math", ".", "Ldexp", "(", "360.0", ",", "-", "lngBits", ")", "\n", "return", "\n", "}" ]
// errorWithPrecision returns the error range in latitude and longitude for in // integer geohash with bits of precision.
[ "errorWithPrecision", "returns", "the", "error", "range", "in", "latitude", "and", "longitude", "for", "in", "integer", "geohash", "with", "bits", "of", "precision", "." ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/geo/geohash.go#L103-L110
162,231
blevesearch/bleve
geo/geohash.go
maxDecimalPower
func maxDecimalPower(r float64) float64 { m := int(math.Floor(math.Log10(r))) return math.Pow10(m) }
go
func maxDecimalPower(r float64) float64 { m := int(math.Floor(math.Log10(r))) return math.Pow10(m) }
[ "func", "maxDecimalPower", "(", "r", "float64", ")", "float64", "{", "m", ":=", "int", "(", "math", ".", "Floor", "(", "math", ".", "Log10", "(", "r", ")", ")", ")", "\n", "return", "math", ".", "Pow10", "(", "m", ")", "\n", "}" ]
// minDecimalPlaces returns the minimum number of decimal places such that // there must exist an number with that many places within any range of width // r. This is intended for returning minimal precision coordinates inside a // box.
[ "minDecimalPlaces", "returns", "the", "minimum", "number", "of", "decimal", "places", "such", "that", "there", "must", "exist", "an", "number", "with", "that", "many", "places", "within", "any", "range", "of", "width", "r", ".", "This", "is", "intended", "for", "returning", "minimal", "precision", "coordinates", "inside", "a", "box", "." ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/geo/geohash.go#L116-L119
162,232
blevesearch/bleve
geo/geohash.go
encodeRange
func encodeRange(x, r float64) uint32 { p := (x + r) / (2 * r) return uint32(p * exp232) }
go
func encodeRange(x, r float64) uint32 { p := (x + r) / (2 * r) return uint32(p * exp232) }
[ "func", "encodeRange", "(", "x", ",", "r", "float64", ")", "uint32", "{", "p", ":=", "(", "x", "+", "r", ")", "/", "(", "2", "*", "r", ")", "\n", "return", "uint32", "(", "p", "*", "exp232", ")", "\n", "}" ]
// Encode the position of x within the range -r to +r as a 32-bit integer.
[ "Encode", "the", "position", "of", "x", "within", "the", "range", "-", "r", "to", "+", "r", "as", "a", "32", "-", "bit", "integer", "." ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/geo/geohash.go#L122-L125
162,233
blevesearch/bleve
geo/geohash.go
decodeRange
func decodeRange(X uint32, r float64) float64 { p := float64(X) / exp232 x := 2*r*p - r return x }
go
func decodeRange(X uint32, r float64) float64 { p := float64(X) / exp232 x := 2*r*p - r return x }
[ "func", "decodeRange", "(", "X", "uint32", ",", "r", "float64", ")", "float64", "{", "p", ":=", "float64", "(", "X", ")", "/", "exp232", "\n", "x", ":=", "2", "*", "r", "*", "p", "-", "r", "\n", "return", "x", "\n", "}" ]
// Decode the 32-bit range encoding X back to a value in the range -r to +r.
[ "Decode", "the", "32", "-", "bit", "range", "encoding", "X", "back", "to", "a", "value", "in", "the", "range", "-", "r", "to", "+", "r", "." ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/geo/geohash.go#L128-L132
162,234
blevesearch/bleve
geo/geohash.go
squash
func squash(X uint64) uint32 { X &= 0x5555555555555555 X = (X | (X >> 1)) & 0x3333333333333333 X = (X | (X >> 2)) & 0x0f0f0f0f0f0f0f0f X = (X | (X >> 4)) & 0x00ff00ff00ff00ff X = (X | (X >> 8)) & 0x0000ffff0000ffff X = (X | (X >> 16)) & 0x00000000ffffffff return uint32(X) }
go
func squash(X uint64) uint32 { X &= 0x5555555555555555 X = (X | (X >> 1)) & 0x3333333333333333 X = (X | (X >> 2)) & 0x0f0f0f0f0f0f0f0f X = (X | (X >> 4)) & 0x00ff00ff00ff00ff X = (X | (X >> 8)) & 0x0000ffff0000ffff X = (X | (X >> 16)) & 0x00000000ffffffff return uint32(X) }
[ "func", "squash", "(", "X", "uint64", ")", "uint32", "{", "X", "&=", "0x5555555555555555", "\n", "X", "=", "(", "X", "|", "(", "X", ">>", "1", ")", ")", "&", "0x3333333333333333", "\n", "X", "=", "(", "X", "|", "(", "X", ">>", "2", ")", ")", "&", "0x0f0f0f0f0f0f0f0f", "\n", "X", "=", "(", "X", "|", "(", "X", ">>", "4", ")", ")", "&", "0x00ff00ff00ff00ff", "\n", "X", "=", "(", "X", "|", "(", "X", ">>", "8", ")", ")", "&", "0x0000ffff0000ffff", "\n", "X", "=", "(", "X", "|", "(", "X", ">>", "16", ")", ")", "&", "0x00000000ffffffff", "\n", "return", "uint32", "(", "X", ")", "\n", "}" ]
// Squash the even bitlevels of X into a 32-bit word. Odd bitlevels of X are // ignored, and may take any value.
[ "Squash", "the", "even", "bitlevels", "of", "X", "into", "a", "32", "-", "bit", "word", ".", "Odd", "bitlevels", "of", "X", "are", "ignored", "and", "may", "take", "any", "value", "." ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/geo/geohash.go#L136-L144
162,235
blevesearch/bleve
geo/geohash.go
geoBoundingBoxIntWithPrecision
func geoBoundingBoxIntWithPrecision(hash uint64, bits uint) geoBox { fullHash := hash << (64 - bits) latInt, lngInt := deinterleave(fullHash) lat := decodeRange(latInt, 90) lng := decodeRange(lngInt, 180) latErr, lngErr := errorWithPrecision(bits) return geoBox{ minLat: lat, maxLat: lat + latErr, minLng: lng, maxLng: lng + lngErr, } }
go
func geoBoundingBoxIntWithPrecision(hash uint64, bits uint) geoBox { fullHash := hash << (64 - bits) latInt, lngInt := deinterleave(fullHash) lat := decodeRange(latInt, 90) lng := decodeRange(lngInt, 180) latErr, lngErr := errorWithPrecision(bits) return geoBox{ minLat: lat, maxLat: lat + latErr, minLng: lng, maxLng: lng + lngErr, } }
[ "func", "geoBoundingBoxIntWithPrecision", "(", "hash", "uint64", ",", "bits", "uint", ")", "geoBox", "{", "fullHash", ":=", "hash", "<<", "(", "64", "-", "bits", ")", "\n", "latInt", ",", "lngInt", ":=", "deinterleave", "(", "fullHash", ")", "\n", "lat", ":=", "decodeRange", "(", "latInt", ",", "90", ")", "\n", "lng", ":=", "decodeRange", "(", "lngInt", ",", "180", ")", "\n", "latErr", ",", "lngErr", ":=", "errorWithPrecision", "(", "bits", ")", "\n", "return", "geoBox", "{", "minLat", ":", "lat", ",", "maxLat", ":", "lat", "+", "latErr", ",", "minLng", ":", "lng", ",", "maxLng", ":", "lng", "+", "lngErr", ",", "}", "\n", "}" ]
// BoundingBoxIntWithPrecision returns the region encoded by the integer // geohash with the specified precision.
[ "BoundingBoxIntWithPrecision", "returns", "the", "region", "encoded", "by", "the", "integer", "geohash", "with", "the", "specified", "precision", "." ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/geo/geohash.go#L154-L166
162,236
blevesearch/bleve
index/scorch/segment/zap/write.go
writeRoaringWithLen
func writeRoaringWithLen(r *roaring.Bitmap, w io.Writer, reuseBufVarint []byte) (int, error) { buf, err := r.ToBytes() if err != nil { return 0, err } var tw int // write out the length n := binary.PutUvarint(reuseBufVarint, uint64(len(buf))) nw, err := w.Write(reuseBufVarint[:n]) tw += nw if err != nil { return tw, err } // write out the roaring bytes nw, err = w.Write(buf) tw += nw if err != nil { return tw, err } return tw, nil }
go
func writeRoaringWithLen(r *roaring.Bitmap, w io.Writer, reuseBufVarint []byte) (int, error) { buf, err := r.ToBytes() if err != nil { return 0, err } var tw int // write out the length n := binary.PutUvarint(reuseBufVarint, uint64(len(buf))) nw, err := w.Write(reuseBufVarint[:n]) tw += nw if err != nil { return tw, err } // write out the roaring bytes nw, err = w.Write(buf) tw += nw if err != nil { return tw, err } return tw, nil }
[ "func", "writeRoaringWithLen", "(", "r", "*", "roaring", ".", "Bitmap", ",", "w", "io", ".", "Writer", ",", "reuseBufVarint", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "buf", ",", "err", ":=", "r", ".", "ToBytes", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "var", "tw", "int", "\n\n", "// write out the length", "n", ":=", "binary", ".", "PutUvarint", "(", "reuseBufVarint", ",", "uint64", "(", "len", "(", "buf", ")", ")", ")", "\n", "nw", ",", "err", ":=", "w", ".", "Write", "(", "reuseBufVarint", "[", ":", "n", "]", ")", "\n", "tw", "+=", "nw", "\n", "if", "err", "!=", "nil", "{", "return", "tw", ",", "err", "\n", "}", "\n\n", "// write out the roaring bytes", "nw", ",", "err", "=", "w", ".", "Write", "(", "buf", ")", "\n", "tw", "+=", "nw", "\n", "if", "err", "!=", "nil", "{", "return", "tw", ",", "err", "\n", "}", "\n\n", "return", "tw", ",", "nil", "\n", "}" ]
// writes out the length of the roaring bitmap in bytes as varint // then writes out the roaring bitmap itself
[ "writes", "out", "the", "length", "of", "the", "roaring", "bitmap", "in", "bytes", "as", "varint", "then", "writes", "out", "the", "roaring", "bitmap", "itself" ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/index/scorch/segment/zap/write.go#L26-L51
162,237
blevesearch/bleve
analysis/token/camelcase/parser.go
NewState
func (p *Parser) NewState(sym rune) State { var found State found = &LowerCaseState{} if found.StartSym(sym) { return found } found = &UpperCaseState{} if found.StartSym(sym) { return found } found = &NumberCaseState{} if found.StartSym(sym) { return found } return &NonAlphaNumericCaseState{} }
go
func (p *Parser) NewState(sym rune) State { var found State found = &LowerCaseState{} if found.StartSym(sym) { return found } found = &UpperCaseState{} if found.StartSym(sym) { return found } found = &NumberCaseState{} if found.StartSym(sym) { return found } return &NonAlphaNumericCaseState{} }
[ "func", "(", "p", "*", "Parser", ")", "NewState", "(", "sym", "rune", ")", "State", "{", "var", "found", "State", "\n\n", "found", "=", "&", "LowerCaseState", "{", "}", "\n", "if", "found", ".", "StartSym", "(", "sym", ")", "{", "return", "found", "\n", "}", "\n\n", "found", "=", "&", "UpperCaseState", "{", "}", "\n", "if", "found", ".", "StartSym", "(", "sym", ")", "{", "return", "found", "\n", "}", "\n\n", "found", "=", "&", "NumberCaseState", "{", "}", "\n", "if", "found", ".", "StartSym", "(", "sym", ")", "{", "return", "found", "\n", "}", "\n\n", "return", "&", "NonAlphaNumericCaseState", "{", "}", "\n", "}" ]
// Note. States have to have different starting symbols.
[ "Note", ".", "States", "have", "to", "have", "different", "starting", "symbols", "." ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/analysis/token/camelcase/parser.go#L81-L100
162,238
blevesearch/bleve
index/scorch/segment/int.go
DecodeUvarintAscending
func DecodeUvarintAscending(b []byte) ([]byte, uint64, error) { if len(b) == 0 { return nil, 0, fmt.Errorf("insufficient bytes to decode uvarint value") } length := int(b[0]) - intZero b = b[1:] // skip length byte if length <= intSmall { return b, uint64(length), nil } length -= intSmall if length < 0 || length > 8 { return nil, 0, fmt.Errorf("invalid uvarint length of %d", length) } else if len(b) < length { return nil, 0, fmt.Errorf("insufficient bytes to decode uvarint value: %q", b) } var v uint64 // It is faster to range over the elements in a slice than to index // into the slice on each loop iteration. for _, t := range b[:length] { v = (v << 8) | uint64(t) } return b[length:], v, nil }
go
func DecodeUvarintAscending(b []byte) ([]byte, uint64, error) { if len(b) == 0 { return nil, 0, fmt.Errorf("insufficient bytes to decode uvarint value") } length := int(b[0]) - intZero b = b[1:] // skip length byte if length <= intSmall { return b, uint64(length), nil } length -= intSmall if length < 0 || length > 8 { return nil, 0, fmt.Errorf("invalid uvarint length of %d", length) } else if len(b) < length { return nil, 0, fmt.Errorf("insufficient bytes to decode uvarint value: %q", b) } var v uint64 // It is faster to range over the elements in a slice than to index // into the slice on each loop iteration. for _, t := range b[:length] { v = (v << 8) | uint64(t) } return b[length:], v, nil }
[ "func", "DecodeUvarintAscending", "(", "b", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "uint64", ",", "error", ")", "{", "if", "len", "(", "b", ")", "==", "0", "{", "return", "nil", ",", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "length", ":=", "int", "(", "b", "[", "0", "]", ")", "-", "intZero", "\n", "b", "=", "b", "[", "1", ":", "]", "// skip length byte", "\n", "if", "length", "<=", "intSmall", "{", "return", "b", ",", "uint64", "(", "length", ")", ",", "nil", "\n", "}", "\n", "length", "-=", "intSmall", "\n", "if", "length", "<", "0", "||", "length", ">", "8", "{", "return", "nil", ",", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "length", ")", "\n", "}", "else", "if", "len", "(", "b", ")", "<", "length", "{", "return", "nil", ",", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "b", ")", "\n", "}", "\n", "var", "v", "uint64", "\n", "// It is faster to range over the elements in a slice than to index", "// into the slice on each loop iteration.", "for", "_", ",", "t", ":=", "range", "b", "[", ":", "length", "]", "{", "v", "=", "(", "v", "<<", "8", ")", "|", "uint64", "(", "t", ")", "\n", "}", "\n", "return", "b", "[", "length", ":", "]", ",", "v", ",", "nil", "\n", "}" ]
// DecodeUvarintAscending decodes a varint encoded uint64 from the input // buffer. The remainder of the input buffer and the decoded uint64 // are returned.
[ "DecodeUvarintAscending", "decodes", "a", "varint", "encoded", "uint64", "from", "the", "input", "buffer", ".", "The", "remainder", "of", "the", "input", "buffer", "and", "the", "decoded", "uint64", "are", "returned", "." ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/index/scorch/segment/int.go#L75-L97
162,239
blevesearch/bleve
index/scorch/segment/int.go
Len
func (r *MemUvarintReader) Len() int { n := len(r.S) - r.C if n < 0 { return 0 } return n }
go
func (r *MemUvarintReader) Len() int { n := len(r.S) - r.C if n < 0 { return 0 } return n }
[ "func", "(", "r", "*", "MemUvarintReader", ")", "Len", "(", ")", "int", "{", "n", ":=", "len", "(", "r", ".", "S", ")", "-", "r", ".", "C", "\n", "if", "n", "<", "0", "{", "return", "0", "\n", "}", "\n", "return", "n", "\n", "}" ]
// Len returns the number of unread bytes.
[ "Len", "returns", "the", "number", "of", "unread", "bytes", "." ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/index/scorch/segment/int.go#L111-L117
162,240
blevesearch/bleve
index/scorch/segment/int.go
SkipUvarint
func (r *MemUvarintReader) SkipUvarint() { for { b := r.S[r.C] r.C++ if b < 0x80 { return } } }
go
func (r *MemUvarintReader) SkipUvarint() { for { b := r.S[r.C] r.C++ if b < 0x80 { return } } }
[ "func", "(", "r", "*", "MemUvarintReader", ")", "SkipUvarint", "(", ")", "{", "for", "{", "b", ":=", "r", ".", "S", "[", "r", ".", "C", "]", "\n", "r", ".", "C", "++", "\n\n", "if", "b", "<", "0x80", "{", "return", "\n", "}", "\n", "}", "\n", "}" ]
// SkipUvarint skips ahead one encoded uint64.
[ "SkipUvarint", "skips", "ahead", "one", "encoded", "uint64", "." ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/index/scorch/segment/int.go#L157-L166
162,241
blevesearch/bleve
index/scorch/segment/int.go
SkipBytes
func (r *MemUvarintReader) SkipBytes(count int) { r.C = r.C + count }
go
func (r *MemUvarintReader) SkipBytes(count int) { r.C = r.C + count }
[ "func", "(", "r", "*", "MemUvarintReader", ")", "SkipBytes", "(", "count", "int", ")", "{", "r", ".", "C", "=", "r", ".", "C", "+", "count", "\n", "}" ]
// SkipBytes skips a count number of bytes.
[ "SkipBytes", "skips", "a", "count", "number", "of", "bytes", "." ]
7f3a218ae72960bb4841254833a52a5f088a9928
https://github.com/blevesearch/bleve/blob/7f3a218ae72960bb4841254833a52a5f088a9928/index/scorch/segment/int.go#L169-L171
162,242
fsnotify/fsnotify
inotify.go
readEvents
func (w *Watcher) readEvents() { var ( buf [unix.SizeofInotifyEvent * 4096]byte // Buffer for a maximum of 4096 raw events n int // Number of bytes read with read() errno error // Syscall errno ok bool // For poller.wait ) defer close(w.doneResp) defer close(w.Errors) defer close(w.Events) defer unix.Close(w.fd) defer w.poller.close() for { // See if we have been closed. if w.isClosed() { return } ok, errno = w.poller.wait() if errno != nil { select { case w.Errors <- errno: case <-w.done: return } continue } if !ok { continue } n, errno = unix.Read(w.fd, buf[:]) // If a signal interrupted execution, see if we've been asked to close, and try again. // http://man7.org/linux/man-pages/man7/signal.7.html : // "Before Linux 3.8, reads from an inotify(7) file descriptor were not restartable" if errno == unix.EINTR { continue } // unix.Read might have been woken up by Close. If so, we're done. if w.isClosed() { return } if n < unix.SizeofInotifyEvent { var err error if n == 0 { // If EOF is received. This should really never happen. err = io.EOF } else if n < 0 { // If an error occurred while reading. err = errno } else { // Read was too short. err = errors.New("notify: short read in readEvents()") } select { case w.Errors <- err: case <-w.done: return } continue } var offset uint32 // We don't know how many events we just read into the buffer // While the offset points to at least one whole event... for offset <= uint32(n-unix.SizeofInotifyEvent) { // Point "raw" to the event in the buffer raw := (*unix.InotifyEvent)(unsafe.Pointer(&buf[offset])) mask := uint32(raw.Mask) nameLen := uint32(raw.Len) if mask&unix.IN_Q_OVERFLOW != 0 { select { case w.Errors <- ErrEventOverflow: case <-w.done: return } } // If the event happened to the watched directory or the watched file, the kernel // doesn't append the filename to the event, but we would like to always fill the // the "Name" field with a valid filename. We retrieve the path of the watch from // the "paths" map. w.mu.Lock() name, ok := w.paths[int(raw.Wd)] // IN_DELETE_SELF occurs when the file/directory being watched is removed. // This is a sign to clean up the maps, otherwise we are no longer in sync // with the inotify kernel state which has already deleted the watch // automatically. if ok && mask&unix.IN_DELETE_SELF == unix.IN_DELETE_SELF { delete(w.paths, int(raw.Wd)) delete(w.watches, name) } w.mu.Unlock() if nameLen > 0 { // Point "bytes" at the first byte of the filename bytes := (*[unix.PathMax]byte)(unsafe.Pointer(&buf[offset+unix.SizeofInotifyEvent])) // The filename is padded with NULL bytes. TrimRight() gets rid of those. name += "/" + strings.TrimRight(string(bytes[0:nameLen]), "\000") } event := newEvent(name, mask) // Send the events that are not ignored on the events channel if !event.ignoreLinux(mask) { select { case w.Events <- event: case <-w.done: return } } // Move to the next event in the buffer offset += unix.SizeofInotifyEvent + nameLen } } }
go
func (w *Watcher) readEvents() { var ( buf [unix.SizeofInotifyEvent * 4096]byte // Buffer for a maximum of 4096 raw events n int // Number of bytes read with read() errno error // Syscall errno ok bool // For poller.wait ) defer close(w.doneResp) defer close(w.Errors) defer close(w.Events) defer unix.Close(w.fd) defer w.poller.close() for { // See if we have been closed. if w.isClosed() { return } ok, errno = w.poller.wait() if errno != nil { select { case w.Errors <- errno: case <-w.done: return } continue } if !ok { continue } n, errno = unix.Read(w.fd, buf[:]) // If a signal interrupted execution, see if we've been asked to close, and try again. // http://man7.org/linux/man-pages/man7/signal.7.html : // "Before Linux 3.8, reads from an inotify(7) file descriptor were not restartable" if errno == unix.EINTR { continue } // unix.Read might have been woken up by Close. If so, we're done. if w.isClosed() { return } if n < unix.SizeofInotifyEvent { var err error if n == 0 { // If EOF is received. This should really never happen. err = io.EOF } else if n < 0 { // If an error occurred while reading. err = errno } else { // Read was too short. err = errors.New("notify: short read in readEvents()") } select { case w.Errors <- err: case <-w.done: return } continue } var offset uint32 // We don't know how many events we just read into the buffer // While the offset points to at least one whole event... for offset <= uint32(n-unix.SizeofInotifyEvent) { // Point "raw" to the event in the buffer raw := (*unix.InotifyEvent)(unsafe.Pointer(&buf[offset])) mask := uint32(raw.Mask) nameLen := uint32(raw.Len) if mask&unix.IN_Q_OVERFLOW != 0 { select { case w.Errors <- ErrEventOverflow: case <-w.done: return } } // If the event happened to the watched directory or the watched file, the kernel // doesn't append the filename to the event, but we would like to always fill the // the "Name" field with a valid filename. We retrieve the path of the watch from // the "paths" map. w.mu.Lock() name, ok := w.paths[int(raw.Wd)] // IN_DELETE_SELF occurs when the file/directory being watched is removed. // This is a sign to clean up the maps, otherwise we are no longer in sync // with the inotify kernel state which has already deleted the watch // automatically. if ok && mask&unix.IN_DELETE_SELF == unix.IN_DELETE_SELF { delete(w.paths, int(raw.Wd)) delete(w.watches, name) } w.mu.Unlock() if nameLen > 0 { // Point "bytes" at the first byte of the filename bytes := (*[unix.PathMax]byte)(unsafe.Pointer(&buf[offset+unix.SizeofInotifyEvent])) // The filename is padded with NULL bytes. TrimRight() gets rid of those. name += "/" + strings.TrimRight(string(bytes[0:nameLen]), "\000") } event := newEvent(name, mask) // Send the events that are not ignored on the events channel if !event.ignoreLinux(mask) { select { case w.Events <- event: case <-w.done: return } } // Move to the next event in the buffer offset += unix.SizeofInotifyEvent + nameLen } } }
[ "func", "(", "w", "*", "Watcher", ")", "readEvents", "(", ")", "{", "var", "(", "buf", "[", "unix", ".", "SizeofInotifyEvent", "*", "4096", "]", "byte", "// Buffer for a maximum of 4096 raw events", "\n", "n", "int", "// Number of bytes read with read()", "\n", "errno", "error", "// Syscall errno", "\n", "ok", "bool", "// For poller.wait", "\n", ")", "\n\n", "defer", "close", "(", "w", ".", "doneResp", ")", "\n", "defer", "close", "(", "w", ".", "Errors", ")", "\n", "defer", "close", "(", "w", ".", "Events", ")", "\n", "defer", "unix", ".", "Close", "(", "w", ".", "fd", ")", "\n", "defer", "w", ".", "poller", ".", "close", "(", ")", "\n\n", "for", "{", "// See if we have been closed.", "if", "w", ".", "isClosed", "(", ")", "{", "return", "\n", "}", "\n\n", "ok", ",", "errno", "=", "w", ".", "poller", ".", "wait", "(", ")", "\n", "if", "errno", "!=", "nil", "{", "select", "{", "case", "w", ".", "Errors", "<-", "errno", ":", "case", "<-", "w", ".", "done", ":", "return", "\n", "}", "\n", "continue", "\n", "}", "\n\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n\n", "n", ",", "errno", "=", "unix", ".", "Read", "(", "w", ".", "fd", ",", "buf", "[", ":", "]", ")", "\n", "// If a signal interrupted execution, see if we've been asked to close, and try again.", "// http://man7.org/linux/man-pages/man7/signal.7.html :", "// \"Before Linux 3.8, reads from an inotify(7) file descriptor were not restartable\"", "if", "errno", "==", "unix", ".", "EINTR", "{", "continue", "\n", "}", "\n\n", "// unix.Read might have been woken up by Close. If so, we're done.", "if", "w", ".", "isClosed", "(", ")", "{", "return", "\n", "}", "\n\n", "if", "n", "<", "unix", ".", "SizeofInotifyEvent", "{", "var", "err", "error", "\n", "if", "n", "==", "0", "{", "// If EOF is received. This should really never happen.", "err", "=", "io", ".", "EOF", "\n", "}", "else", "if", "n", "<", "0", "{", "// If an error occurred while reading.", "err", "=", "errno", "\n", "}", "else", "{", "// Read was too short.", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "select", "{", "case", "w", ".", "Errors", "<-", "err", ":", "case", "<-", "w", ".", "done", ":", "return", "\n", "}", "\n", "continue", "\n", "}", "\n\n", "var", "offset", "uint32", "\n", "// We don't know how many events we just read into the buffer", "// While the offset points to at least one whole event...", "for", "offset", "<=", "uint32", "(", "n", "-", "unix", ".", "SizeofInotifyEvent", ")", "{", "// Point \"raw\" to the event in the buffer", "raw", ":=", "(", "*", "unix", ".", "InotifyEvent", ")", "(", "unsafe", ".", "Pointer", "(", "&", "buf", "[", "offset", "]", ")", ")", "\n\n", "mask", ":=", "uint32", "(", "raw", ".", "Mask", ")", "\n", "nameLen", ":=", "uint32", "(", "raw", ".", "Len", ")", "\n\n", "if", "mask", "&", "unix", ".", "IN_Q_OVERFLOW", "!=", "0", "{", "select", "{", "case", "w", ".", "Errors", "<-", "ErrEventOverflow", ":", "case", "<-", "w", ".", "done", ":", "return", "\n", "}", "\n", "}", "\n\n", "// If the event happened to the watched directory or the watched file, the kernel", "// doesn't append the filename to the event, but we would like to always fill the", "// the \"Name\" field with a valid filename. We retrieve the path of the watch from", "// the \"paths\" map.", "w", ".", "mu", ".", "Lock", "(", ")", "\n", "name", ",", "ok", ":=", "w", ".", "paths", "[", "int", "(", "raw", ".", "Wd", ")", "]", "\n", "// IN_DELETE_SELF occurs when the file/directory being watched is removed.", "// This is a sign to clean up the maps, otherwise we are no longer in sync", "// with the inotify kernel state which has already deleted the watch", "// automatically.", "if", "ok", "&&", "mask", "&", "unix", ".", "IN_DELETE_SELF", "==", "unix", ".", "IN_DELETE_SELF", "{", "delete", "(", "w", ".", "paths", ",", "int", "(", "raw", ".", "Wd", ")", ")", "\n", "delete", "(", "w", ".", "watches", ",", "name", ")", "\n", "}", "\n", "w", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "nameLen", ">", "0", "{", "// Point \"bytes\" at the first byte of the filename", "bytes", ":=", "(", "*", "[", "unix", ".", "PathMax", "]", "byte", ")", "(", "unsafe", ".", "Pointer", "(", "&", "buf", "[", "offset", "+", "unix", ".", "SizeofInotifyEvent", "]", ")", ")", "\n", "// The filename is padded with NULL bytes. TrimRight() gets rid of those.", "name", "+=", "\"", "\"", "+", "strings", ".", "TrimRight", "(", "string", "(", "bytes", "[", "0", ":", "nameLen", "]", ")", ",", "\"", "\\000", "\"", ")", "\n", "}", "\n\n", "event", ":=", "newEvent", "(", "name", ",", "mask", ")", "\n\n", "// Send the events that are not ignored on the events channel", "if", "!", "event", ".", "ignoreLinux", "(", "mask", ")", "{", "select", "{", "case", "w", ".", "Events", "<-", "event", ":", "case", "<-", "w", ".", "done", ":", "return", "\n", "}", "\n", "}", "\n\n", "// Move to the next event in the buffer", "offset", "+=", "unix", ".", "SizeofInotifyEvent", "+", "nameLen", "\n", "}", "\n", "}", "\n", "}" ]
// readEvents reads from the inotify file descriptor, converts the // received events into Event objects and sends them via the Events channel
[ "readEvents", "reads", "from", "the", "inotify", "file", "descriptor", "converts", "the", "received", "events", "into", "Event", "objects", "and", "sends", "them", "via", "the", "Events", "channel" ]
1485a34d5d5723fea214f5710708e19a831720e4
https://github.com/fsnotify/fsnotify/blob/1485a34d5d5723fea214f5710708e19a831720e4/inotify.go#L172-L295
162,243
fsnotify/fsnotify
inotify.go
ignoreLinux
func (e *Event) ignoreLinux(mask uint32) bool { // Ignore anything the inotify API says to ignore if mask&unix.IN_IGNORED == unix.IN_IGNORED { return true } // If the event is not a DELETE or RENAME, the file must exist. // Otherwise the event is ignored. // *Note*: this was put in place because it was seen that a MODIFY // event was sent after the DELETE. This ignores that MODIFY and // assumes a DELETE will come or has come if the file doesn't exist. if !(e.Op&Remove == Remove || e.Op&Rename == Rename) { _, statErr := os.Lstat(e.Name) return os.IsNotExist(statErr) } return false }
go
func (e *Event) ignoreLinux(mask uint32) bool { // Ignore anything the inotify API says to ignore if mask&unix.IN_IGNORED == unix.IN_IGNORED { return true } // If the event is not a DELETE or RENAME, the file must exist. // Otherwise the event is ignored. // *Note*: this was put in place because it was seen that a MODIFY // event was sent after the DELETE. This ignores that MODIFY and // assumes a DELETE will come or has come if the file doesn't exist. if !(e.Op&Remove == Remove || e.Op&Rename == Rename) { _, statErr := os.Lstat(e.Name) return os.IsNotExist(statErr) } return false }
[ "func", "(", "e", "*", "Event", ")", "ignoreLinux", "(", "mask", "uint32", ")", "bool", "{", "// Ignore anything the inotify API says to ignore", "if", "mask", "&", "unix", ".", "IN_IGNORED", "==", "unix", ".", "IN_IGNORED", "{", "return", "true", "\n", "}", "\n\n", "// If the event is not a DELETE or RENAME, the file must exist.", "// Otherwise the event is ignored.", "// *Note*: this was put in place because it was seen that a MODIFY", "// event was sent after the DELETE. This ignores that MODIFY and", "// assumes a DELETE will come or has come if the file doesn't exist.", "if", "!", "(", "e", ".", "Op", "&", "Remove", "==", "Remove", "||", "e", ".", "Op", "&", "Rename", "==", "Rename", ")", "{", "_", ",", "statErr", ":=", "os", ".", "Lstat", "(", "e", ".", "Name", ")", "\n", "return", "os", ".", "IsNotExist", "(", "statErr", ")", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Certain types of events can be "ignored" and not sent over the Events // channel. Such as events marked ignore by the kernel, or MODIFY events // against files that do not exist.
[ "Certain", "types", "of", "events", "can", "be", "ignored", "and", "not", "sent", "over", "the", "Events", "channel", ".", "Such", "as", "events", "marked", "ignore", "by", "the", "kernel", "or", "MODIFY", "events", "against", "files", "that", "do", "not", "exist", "." ]
1485a34d5d5723fea214f5710708e19a831720e4
https://github.com/fsnotify/fsnotify/blob/1485a34d5d5723fea214f5710708e19a831720e4/inotify.go#L300-L316
162,244
fsnotify/fsnotify
inotify.go
newEvent
func newEvent(name string, mask uint32) Event { e := Event{Name: name} if mask&unix.IN_CREATE == unix.IN_CREATE || mask&unix.IN_MOVED_TO == unix.IN_MOVED_TO { e.Op |= Create } if mask&unix.IN_DELETE_SELF == unix.IN_DELETE_SELF || mask&unix.IN_DELETE == unix.IN_DELETE { e.Op |= Remove } if mask&unix.IN_MODIFY == unix.IN_MODIFY { e.Op |= Write } if mask&unix.IN_MOVE_SELF == unix.IN_MOVE_SELF || mask&unix.IN_MOVED_FROM == unix.IN_MOVED_FROM { e.Op |= Rename } if mask&unix.IN_ATTRIB == unix.IN_ATTRIB { e.Op |= Chmod } return e }
go
func newEvent(name string, mask uint32) Event { e := Event{Name: name} if mask&unix.IN_CREATE == unix.IN_CREATE || mask&unix.IN_MOVED_TO == unix.IN_MOVED_TO { e.Op |= Create } if mask&unix.IN_DELETE_SELF == unix.IN_DELETE_SELF || mask&unix.IN_DELETE == unix.IN_DELETE { e.Op |= Remove } if mask&unix.IN_MODIFY == unix.IN_MODIFY { e.Op |= Write } if mask&unix.IN_MOVE_SELF == unix.IN_MOVE_SELF || mask&unix.IN_MOVED_FROM == unix.IN_MOVED_FROM { e.Op |= Rename } if mask&unix.IN_ATTRIB == unix.IN_ATTRIB { e.Op |= Chmod } return e }
[ "func", "newEvent", "(", "name", "string", ",", "mask", "uint32", ")", "Event", "{", "e", ":=", "Event", "{", "Name", ":", "name", "}", "\n", "if", "mask", "&", "unix", ".", "IN_CREATE", "==", "unix", ".", "IN_CREATE", "||", "mask", "&", "unix", ".", "IN_MOVED_TO", "==", "unix", ".", "IN_MOVED_TO", "{", "e", ".", "Op", "|=", "Create", "\n", "}", "\n", "if", "mask", "&", "unix", ".", "IN_DELETE_SELF", "==", "unix", ".", "IN_DELETE_SELF", "||", "mask", "&", "unix", ".", "IN_DELETE", "==", "unix", ".", "IN_DELETE", "{", "e", ".", "Op", "|=", "Remove", "\n", "}", "\n", "if", "mask", "&", "unix", ".", "IN_MODIFY", "==", "unix", ".", "IN_MODIFY", "{", "e", ".", "Op", "|=", "Write", "\n", "}", "\n", "if", "mask", "&", "unix", ".", "IN_MOVE_SELF", "==", "unix", ".", "IN_MOVE_SELF", "||", "mask", "&", "unix", ".", "IN_MOVED_FROM", "==", "unix", ".", "IN_MOVED_FROM", "{", "e", ".", "Op", "|=", "Rename", "\n", "}", "\n", "if", "mask", "&", "unix", ".", "IN_ATTRIB", "==", "unix", ".", "IN_ATTRIB", "{", "e", ".", "Op", "|=", "Chmod", "\n", "}", "\n", "return", "e", "\n", "}" ]
// newEvent returns an platform-independent Event based on an inotify mask.
[ "newEvent", "returns", "an", "platform", "-", "independent", "Event", "based", "on", "an", "inotify", "mask", "." ]
1485a34d5d5723fea214f5710708e19a831720e4
https://github.com/fsnotify/fsnotify/blob/1485a34d5d5723fea214f5710708e19a831720e4/inotify.go#L319-L337
162,245
fsnotify/fsnotify
kqueue.go
readEvents
func (w *Watcher) readEvents() { eventBuffer := make([]unix.Kevent_t, 10) loop: for { // See if there is a message on the "done" channel select { case <-w.done: break loop default: } // Get new events kevents, err := read(w.kq, eventBuffer, &keventWaitTime) // EINTR is okay, the syscall was interrupted before timeout expired. if err != nil && err != unix.EINTR { select { case w.Errors <- err: case <-w.done: break loop } continue } // Flush the events we received to the Events channel for len(kevents) > 0 { kevent := &kevents[0] watchfd := int(kevent.Ident) mask := uint32(kevent.Fflags) w.mu.Lock() path := w.paths[watchfd] w.mu.Unlock() event := newEvent(path.name, mask) if path.isDir && !(event.Op&Remove == Remove) { // Double check to make sure the directory exists. This can happen when // we do a rm -fr on a recursively watched folders and we receive a // modification event first but the folder has been deleted and later // receive the delete event if _, err := os.Lstat(event.Name); os.IsNotExist(err) { // mark is as delete event event.Op |= Remove } } if event.Op&Rename == Rename || event.Op&Remove == Remove { w.Remove(event.Name) w.mu.Lock() delete(w.fileExists, event.Name) w.mu.Unlock() } if path.isDir && event.Op&Write == Write && !(event.Op&Remove == Remove) { w.sendDirectoryChangeEvents(event.Name) } else { // Send the event on the Events channel. select { case w.Events <- event: case <-w.done: break loop } } if event.Op&Remove == Remove { // Look for a file that may have overwritten this. // For example, mv f1 f2 will delete f2, then create f2. if path.isDir { fileDir := filepath.Clean(event.Name) w.mu.Lock() _, found := w.watches[fileDir] w.mu.Unlock() if found { // make sure the directory exists before we watch for changes. When we // do a recursive watch and perform rm -fr, the parent directory might // have gone missing, ignore the missing directory and let the // upcoming delete event remove the watch from the parent directory. if _, err := os.Lstat(fileDir); err == nil { w.sendDirectoryChangeEvents(fileDir) } } } else { filePath := filepath.Clean(event.Name) if fileInfo, err := os.Lstat(filePath); err == nil { w.sendFileCreatedEventIfNew(filePath, fileInfo) } } } // Move to next event kevents = kevents[1:] } } // cleanup err := unix.Close(w.kq) if err != nil { // only way the previous loop breaks is if w.done was closed so we need to async send to w.Errors. select { case w.Errors <- err: default: } } close(w.Events) close(w.Errors) }
go
func (w *Watcher) readEvents() { eventBuffer := make([]unix.Kevent_t, 10) loop: for { // See if there is a message on the "done" channel select { case <-w.done: break loop default: } // Get new events kevents, err := read(w.kq, eventBuffer, &keventWaitTime) // EINTR is okay, the syscall was interrupted before timeout expired. if err != nil && err != unix.EINTR { select { case w.Errors <- err: case <-w.done: break loop } continue } // Flush the events we received to the Events channel for len(kevents) > 0 { kevent := &kevents[0] watchfd := int(kevent.Ident) mask := uint32(kevent.Fflags) w.mu.Lock() path := w.paths[watchfd] w.mu.Unlock() event := newEvent(path.name, mask) if path.isDir && !(event.Op&Remove == Remove) { // Double check to make sure the directory exists. This can happen when // we do a rm -fr on a recursively watched folders and we receive a // modification event first but the folder has been deleted and later // receive the delete event if _, err := os.Lstat(event.Name); os.IsNotExist(err) { // mark is as delete event event.Op |= Remove } } if event.Op&Rename == Rename || event.Op&Remove == Remove { w.Remove(event.Name) w.mu.Lock() delete(w.fileExists, event.Name) w.mu.Unlock() } if path.isDir && event.Op&Write == Write && !(event.Op&Remove == Remove) { w.sendDirectoryChangeEvents(event.Name) } else { // Send the event on the Events channel. select { case w.Events <- event: case <-w.done: break loop } } if event.Op&Remove == Remove { // Look for a file that may have overwritten this. // For example, mv f1 f2 will delete f2, then create f2. if path.isDir { fileDir := filepath.Clean(event.Name) w.mu.Lock() _, found := w.watches[fileDir] w.mu.Unlock() if found { // make sure the directory exists before we watch for changes. When we // do a recursive watch and perform rm -fr, the parent directory might // have gone missing, ignore the missing directory and let the // upcoming delete event remove the watch from the parent directory. if _, err := os.Lstat(fileDir); err == nil { w.sendDirectoryChangeEvents(fileDir) } } } else { filePath := filepath.Clean(event.Name) if fileInfo, err := os.Lstat(filePath); err == nil { w.sendFileCreatedEventIfNew(filePath, fileInfo) } } } // Move to next event kevents = kevents[1:] } } // cleanup err := unix.Close(w.kq) if err != nil { // only way the previous loop breaks is if w.done was closed so we need to async send to w.Errors. select { case w.Errors <- err: default: } } close(w.Events) close(w.Errors) }
[ "func", "(", "w", "*", "Watcher", ")", "readEvents", "(", ")", "{", "eventBuffer", ":=", "make", "(", "[", "]", "unix", ".", "Kevent_t", ",", "10", ")", "\n\n", "loop", ":", "for", "{", "// See if there is a message on the \"done\" channel", "select", "{", "case", "<-", "w", ".", "done", ":", "break", "loop", "\n", "default", ":", "}", "\n\n", "// Get new events", "kevents", ",", "err", ":=", "read", "(", "w", ".", "kq", ",", "eventBuffer", ",", "&", "keventWaitTime", ")", "\n", "// EINTR is okay, the syscall was interrupted before timeout expired.", "if", "err", "!=", "nil", "&&", "err", "!=", "unix", ".", "EINTR", "{", "select", "{", "case", "w", ".", "Errors", "<-", "err", ":", "case", "<-", "w", ".", "done", ":", "break", "loop", "\n", "}", "\n", "continue", "\n", "}", "\n\n", "// Flush the events we received to the Events channel", "for", "len", "(", "kevents", ")", ">", "0", "{", "kevent", ":=", "&", "kevents", "[", "0", "]", "\n", "watchfd", ":=", "int", "(", "kevent", ".", "Ident", ")", "\n", "mask", ":=", "uint32", "(", "kevent", ".", "Fflags", ")", "\n", "w", ".", "mu", ".", "Lock", "(", ")", "\n", "path", ":=", "w", ".", "paths", "[", "watchfd", "]", "\n", "w", ".", "mu", ".", "Unlock", "(", ")", "\n", "event", ":=", "newEvent", "(", "path", ".", "name", ",", "mask", ")", "\n\n", "if", "path", ".", "isDir", "&&", "!", "(", "event", ".", "Op", "&", "Remove", "==", "Remove", ")", "{", "// Double check to make sure the directory exists. This can happen when", "// we do a rm -fr on a recursively watched folders and we receive a", "// modification event first but the folder has been deleted and later", "// receive the delete event", "if", "_", ",", "err", ":=", "os", ".", "Lstat", "(", "event", ".", "Name", ")", ";", "os", ".", "IsNotExist", "(", "err", ")", "{", "// mark is as delete event", "event", ".", "Op", "|=", "Remove", "\n", "}", "\n", "}", "\n\n", "if", "event", ".", "Op", "&", "Rename", "==", "Rename", "||", "event", ".", "Op", "&", "Remove", "==", "Remove", "{", "w", ".", "Remove", "(", "event", ".", "Name", ")", "\n", "w", ".", "mu", ".", "Lock", "(", ")", "\n", "delete", "(", "w", ".", "fileExists", ",", "event", ".", "Name", ")", "\n", "w", ".", "mu", ".", "Unlock", "(", ")", "\n", "}", "\n\n", "if", "path", ".", "isDir", "&&", "event", ".", "Op", "&", "Write", "==", "Write", "&&", "!", "(", "event", ".", "Op", "&", "Remove", "==", "Remove", ")", "{", "w", ".", "sendDirectoryChangeEvents", "(", "event", ".", "Name", ")", "\n", "}", "else", "{", "// Send the event on the Events channel.", "select", "{", "case", "w", ".", "Events", "<-", "event", ":", "case", "<-", "w", ".", "done", ":", "break", "loop", "\n", "}", "\n", "}", "\n\n", "if", "event", ".", "Op", "&", "Remove", "==", "Remove", "{", "// Look for a file that may have overwritten this.", "// For example, mv f1 f2 will delete f2, then create f2.", "if", "path", ".", "isDir", "{", "fileDir", ":=", "filepath", ".", "Clean", "(", "event", ".", "Name", ")", "\n", "w", ".", "mu", ".", "Lock", "(", ")", "\n", "_", ",", "found", ":=", "w", ".", "watches", "[", "fileDir", "]", "\n", "w", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "found", "{", "// make sure the directory exists before we watch for changes. When we", "// do a recursive watch and perform rm -fr, the parent directory might", "// have gone missing, ignore the missing directory and let the", "// upcoming delete event remove the watch from the parent directory.", "if", "_", ",", "err", ":=", "os", ".", "Lstat", "(", "fileDir", ")", ";", "err", "==", "nil", "{", "w", ".", "sendDirectoryChangeEvents", "(", "fileDir", ")", "\n", "}", "\n", "}", "\n", "}", "else", "{", "filePath", ":=", "filepath", ".", "Clean", "(", "event", ".", "Name", ")", "\n", "if", "fileInfo", ",", "err", ":=", "os", ".", "Lstat", "(", "filePath", ")", ";", "err", "==", "nil", "{", "w", ".", "sendFileCreatedEventIfNew", "(", "filePath", ",", "fileInfo", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Move to next event", "kevents", "=", "kevents", "[", "1", ":", "]", "\n", "}", "\n", "}", "\n\n", "// cleanup", "err", ":=", "unix", ".", "Close", "(", "w", ".", "kq", ")", "\n", "if", "err", "!=", "nil", "{", "// only way the previous loop breaks is if w.done was closed so we need to async send to w.Errors.", "select", "{", "case", "w", ".", "Errors", "<-", "err", ":", "default", ":", "}", "\n", "}", "\n", "close", "(", "w", ".", "Events", ")", "\n", "close", "(", "w", ".", "Errors", ")", "\n", "}" ]
// readEvents reads from kqueue and converts the received kevents into // Event values that it sends down the Events channel.
[ "readEvents", "reads", "from", "kqueue", "and", "converts", "the", "received", "kevents", "into", "Event", "values", "that", "it", "sends", "down", "the", "Events", "channel", "." ]
1485a34d5d5723fea214f5710708e19a831720e4
https://github.com/fsnotify/fsnotify/blob/1485a34d5d5723fea214f5710708e19a831720e4/kqueue.go#L261-L365
162,246
fsnotify/fsnotify
kqueue.go
newEvent
func newEvent(name string, mask uint32) Event { e := Event{Name: name} if mask&unix.NOTE_DELETE == unix.NOTE_DELETE { e.Op |= Remove } if mask&unix.NOTE_WRITE == unix.NOTE_WRITE { e.Op |= Write } if mask&unix.NOTE_RENAME == unix.NOTE_RENAME { e.Op |= Rename } if mask&unix.NOTE_ATTRIB == unix.NOTE_ATTRIB { e.Op |= Chmod } return e }
go
func newEvent(name string, mask uint32) Event { e := Event{Name: name} if mask&unix.NOTE_DELETE == unix.NOTE_DELETE { e.Op |= Remove } if mask&unix.NOTE_WRITE == unix.NOTE_WRITE { e.Op |= Write } if mask&unix.NOTE_RENAME == unix.NOTE_RENAME { e.Op |= Rename } if mask&unix.NOTE_ATTRIB == unix.NOTE_ATTRIB { e.Op |= Chmod } return e }
[ "func", "newEvent", "(", "name", "string", ",", "mask", "uint32", ")", "Event", "{", "e", ":=", "Event", "{", "Name", ":", "name", "}", "\n", "if", "mask", "&", "unix", ".", "NOTE_DELETE", "==", "unix", ".", "NOTE_DELETE", "{", "e", ".", "Op", "|=", "Remove", "\n", "}", "\n", "if", "mask", "&", "unix", ".", "NOTE_WRITE", "==", "unix", ".", "NOTE_WRITE", "{", "e", ".", "Op", "|=", "Write", "\n", "}", "\n", "if", "mask", "&", "unix", ".", "NOTE_RENAME", "==", "unix", ".", "NOTE_RENAME", "{", "e", ".", "Op", "|=", "Rename", "\n", "}", "\n", "if", "mask", "&", "unix", ".", "NOTE_ATTRIB", "==", "unix", ".", "NOTE_ATTRIB", "{", "e", ".", "Op", "|=", "Chmod", "\n", "}", "\n", "return", "e", "\n", "}" ]
// newEvent returns an platform-independent Event based on kqueue Fflags.
[ "newEvent", "returns", "an", "platform", "-", "independent", "Event", "based", "on", "kqueue", "Fflags", "." ]
1485a34d5d5723fea214f5710708e19a831720e4
https://github.com/fsnotify/fsnotify/blob/1485a34d5d5723fea214f5710708e19a831720e4/kqueue.go#L368-L383
162,247
fsnotify/fsnotify
kqueue.go
watchDirectoryFiles
func (w *Watcher) watchDirectoryFiles(dirPath string) error { // Get all files files, err := ioutil.ReadDir(dirPath) if err != nil { return err } for _, fileInfo := range files { filePath := filepath.Join(dirPath, fileInfo.Name()) filePath, err = w.internalWatch(filePath, fileInfo) if err != nil { return err } w.mu.Lock() w.fileExists[filePath] = true w.mu.Unlock() } return nil }
go
func (w *Watcher) watchDirectoryFiles(dirPath string) error { // Get all files files, err := ioutil.ReadDir(dirPath) if err != nil { return err } for _, fileInfo := range files { filePath := filepath.Join(dirPath, fileInfo.Name()) filePath, err = w.internalWatch(filePath, fileInfo) if err != nil { return err } w.mu.Lock() w.fileExists[filePath] = true w.mu.Unlock() } return nil }
[ "func", "(", "w", "*", "Watcher", ")", "watchDirectoryFiles", "(", "dirPath", "string", ")", "error", "{", "// Get all files", "files", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "dirPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "for", "_", ",", "fileInfo", ":=", "range", "files", "{", "filePath", ":=", "filepath", ".", "Join", "(", "dirPath", ",", "fileInfo", ".", "Name", "(", ")", ")", "\n", "filePath", ",", "err", "=", "w", ".", "internalWatch", "(", "filePath", ",", "fileInfo", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "w", ".", "mu", ".", "Lock", "(", ")", "\n", "w", ".", "fileExists", "[", "filePath", "]", "=", "true", "\n", "w", ".", "mu", ".", "Unlock", "(", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// watchDirectoryFiles to mimic inotify when adding a watch on a directory
[ "watchDirectoryFiles", "to", "mimic", "inotify", "when", "adding", "a", "watch", "on", "a", "directory" ]
1485a34d5d5723fea214f5710708e19a831720e4
https://github.com/fsnotify/fsnotify/blob/1485a34d5d5723fea214f5710708e19a831720e4/kqueue.go#L390-L410
162,248
fsnotify/fsnotify
kqueue.go
sendDirectoryChangeEvents
func (w *Watcher) sendDirectoryChangeEvents(dirPath string) { // Get all files files, err := ioutil.ReadDir(dirPath) if err != nil { select { case w.Errors <- err: case <-w.done: return } } // Search for new files for _, fileInfo := range files { filePath := filepath.Join(dirPath, fileInfo.Name()) err := w.sendFileCreatedEventIfNew(filePath, fileInfo) if err != nil { return } } }
go
func (w *Watcher) sendDirectoryChangeEvents(dirPath string) { // Get all files files, err := ioutil.ReadDir(dirPath) if err != nil { select { case w.Errors <- err: case <-w.done: return } } // Search for new files for _, fileInfo := range files { filePath := filepath.Join(dirPath, fileInfo.Name()) err := w.sendFileCreatedEventIfNew(filePath, fileInfo) if err != nil { return } } }
[ "func", "(", "w", "*", "Watcher", ")", "sendDirectoryChangeEvents", "(", "dirPath", "string", ")", "{", "// Get all files", "files", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "dirPath", ")", "\n", "if", "err", "!=", "nil", "{", "select", "{", "case", "w", ".", "Errors", "<-", "err", ":", "case", "<-", "w", ".", "done", ":", "return", "\n", "}", "\n", "}", "\n\n", "// Search for new files", "for", "_", ",", "fileInfo", ":=", "range", "files", "{", "filePath", ":=", "filepath", ".", "Join", "(", "dirPath", ",", "fileInfo", ".", "Name", "(", ")", ")", "\n", "err", ":=", "w", ".", "sendFileCreatedEventIfNew", "(", "filePath", ",", "fileInfo", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "\n", "}" ]
// sendDirectoryEvents searches the directory for newly created files // and sends them over the event channel. This functionality is to have // the BSD version of fsnotify match Linux inotify which provides a // create event for files created in a watched directory.
[ "sendDirectoryEvents", "searches", "the", "directory", "for", "newly", "created", "files", "and", "sends", "them", "over", "the", "event", "channel", ".", "This", "functionality", "is", "to", "have", "the", "BSD", "version", "of", "fsnotify", "match", "Linux", "inotify", "which", "provides", "a", "create", "event", "for", "files", "created", "in", "a", "watched", "directory", "." ]
1485a34d5d5723fea214f5710708e19a831720e4
https://github.com/fsnotify/fsnotify/blob/1485a34d5d5723fea214f5710708e19a831720e4/kqueue.go#L416-L436
162,249
fsnotify/fsnotify
kqueue.go
sendFileCreatedEventIfNew
func (w *Watcher) sendFileCreatedEventIfNew(filePath string, fileInfo os.FileInfo) (err error) { w.mu.Lock() _, doesExist := w.fileExists[filePath] w.mu.Unlock() if !doesExist { // Send create event select { case w.Events <- newCreateEvent(filePath): case <-w.done: return } } // like watchDirectoryFiles (but without doing another ReadDir) filePath, err = w.internalWatch(filePath, fileInfo) if err != nil { return err } w.mu.Lock() w.fileExists[filePath] = true w.mu.Unlock() return nil }
go
func (w *Watcher) sendFileCreatedEventIfNew(filePath string, fileInfo os.FileInfo) (err error) { w.mu.Lock() _, doesExist := w.fileExists[filePath] w.mu.Unlock() if !doesExist { // Send create event select { case w.Events <- newCreateEvent(filePath): case <-w.done: return } } // like watchDirectoryFiles (but without doing another ReadDir) filePath, err = w.internalWatch(filePath, fileInfo) if err != nil { return err } w.mu.Lock() w.fileExists[filePath] = true w.mu.Unlock() return nil }
[ "func", "(", "w", "*", "Watcher", ")", "sendFileCreatedEventIfNew", "(", "filePath", "string", ",", "fileInfo", "os", ".", "FileInfo", ")", "(", "err", "error", ")", "{", "w", ".", "mu", ".", "Lock", "(", ")", "\n", "_", ",", "doesExist", ":=", "w", ".", "fileExists", "[", "filePath", "]", "\n", "w", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "!", "doesExist", "{", "// Send create event", "select", "{", "case", "w", ".", "Events", "<-", "newCreateEvent", "(", "filePath", ")", ":", "case", "<-", "w", ".", "done", ":", "return", "\n", "}", "\n", "}", "\n\n", "// like watchDirectoryFiles (but without doing another ReadDir)", "filePath", ",", "err", "=", "w", ".", "internalWatch", "(", "filePath", ",", "fileInfo", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "w", ".", "mu", ".", "Lock", "(", ")", "\n", "w", ".", "fileExists", "[", "filePath", "]", "=", "true", "\n", "w", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// sendFileCreatedEvent sends a create event if the file isn't already being tracked.
[ "sendFileCreatedEvent", "sends", "a", "create", "event", "if", "the", "file", "isn", "t", "already", "being", "tracked", "." ]
1485a34d5d5723fea214f5710708e19a831720e4
https://github.com/fsnotify/fsnotify/blob/1485a34d5d5723fea214f5710708e19a831720e4/kqueue.go#L439-L463
162,250
fsnotify/fsnotify
kqueue.go
kqueue
func kqueue() (kq int, err error) { kq, err = unix.Kqueue() if kq == -1 { return kq, err } return kq, nil }
go
func kqueue() (kq int, err error) { kq, err = unix.Kqueue() if kq == -1 { return kq, err } return kq, nil }
[ "func", "kqueue", "(", ")", "(", "kq", "int", ",", "err", "error", ")", "{", "kq", ",", "err", "=", "unix", ".", "Kqueue", "(", ")", "\n", "if", "kq", "==", "-", "1", "{", "return", "kq", ",", "err", "\n", "}", "\n", "return", "kq", ",", "nil", "\n", "}" ]
// kqueue creates a new kernel event queue and returns a descriptor.
[ "kqueue", "creates", "a", "new", "kernel", "event", "queue", "and", "returns", "a", "descriptor", "." ]
1485a34d5d5723fea214f5710708e19a831720e4
https://github.com/fsnotify/fsnotify/blob/1485a34d5d5723fea214f5710708e19a831720e4/kqueue.go#L482-L488
162,251
fsnotify/fsnotify
kqueue.go
register
func register(kq int, fds []int, flags int, fflags uint32) error { changes := make([]unix.Kevent_t, len(fds)) for i, fd := range fds { // SetKevent converts int to the platform-specific types: unix.SetKevent(&changes[i], fd, unix.EVFILT_VNODE, flags) changes[i].Fflags = fflags } // register the events success, err := unix.Kevent(kq, changes, nil, nil) if success == -1 { return err } return nil }
go
func register(kq int, fds []int, flags int, fflags uint32) error { changes := make([]unix.Kevent_t, len(fds)) for i, fd := range fds { // SetKevent converts int to the platform-specific types: unix.SetKevent(&changes[i], fd, unix.EVFILT_VNODE, flags) changes[i].Fflags = fflags } // register the events success, err := unix.Kevent(kq, changes, nil, nil) if success == -1 { return err } return nil }
[ "func", "register", "(", "kq", "int", ",", "fds", "[", "]", "int", ",", "flags", "int", ",", "fflags", "uint32", ")", "error", "{", "changes", ":=", "make", "(", "[", "]", "unix", ".", "Kevent_t", ",", "len", "(", "fds", ")", ")", "\n\n", "for", "i", ",", "fd", ":=", "range", "fds", "{", "// SetKevent converts int to the platform-specific types:", "unix", ".", "SetKevent", "(", "&", "changes", "[", "i", "]", ",", "fd", ",", "unix", ".", "EVFILT_VNODE", ",", "flags", ")", "\n", "changes", "[", "i", "]", ".", "Fflags", "=", "fflags", "\n", "}", "\n\n", "// register the events", "success", ",", "err", ":=", "unix", ".", "Kevent", "(", "kq", ",", "changes", ",", "nil", ",", "nil", ")", "\n", "if", "success", "==", "-", "1", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// register events with the queue
[ "register", "events", "with", "the", "queue" ]
1485a34d5d5723fea214f5710708e19a831720e4
https://github.com/fsnotify/fsnotify/blob/1485a34d5d5723fea214f5710708e19a831720e4/kqueue.go#L491-L506
162,252
fsnotify/fsnotify
kqueue.go
read
func read(kq int, events []unix.Kevent_t, timeout *unix.Timespec) ([]unix.Kevent_t, error) { n, err := unix.Kevent(kq, nil, events, timeout) if err != nil { return nil, err } return events[0:n], nil }
go
func read(kq int, events []unix.Kevent_t, timeout *unix.Timespec) ([]unix.Kevent_t, error) { n, err := unix.Kevent(kq, nil, events, timeout) if err != nil { return nil, err } return events[0:n], nil }
[ "func", "read", "(", "kq", "int", ",", "events", "[", "]", "unix", ".", "Kevent_t", ",", "timeout", "*", "unix", ".", "Timespec", ")", "(", "[", "]", "unix", ".", "Kevent_t", ",", "error", ")", "{", "n", ",", "err", ":=", "unix", ".", "Kevent", "(", "kq", ",", "nil", ",", "events", ",", "timeout", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "events", "[", "0", ":", "n", "]", ",", "nil", "\n", "}" ]
// read retrieves pending events, or waits until an event occurs. // A timeout of nil blocks indefinitely, while 0 polls the queue.
[ "read", "retrieves", "pending", "events", "or", "waits", "until", "an", "event", "occurs", ".", "A", "timeout", "of", "nil", "blocks", "indefinitely", "while", "0", "polls", "the", "queue", "." ]
1485a34d5d5723fea214f5710708e19a831720e4
https://github.com/fsnotify/fsnotify/blob/1485a34d5d5723fea214f5710708e19a831720e4/kqueue.go#L510-L516
162,253
fsnotify/fsnotify
kqueue.go
durationToTimespec
func durationToTimespec(d time.Duration) unix.Timespec { return unix.NsecToTimespec(d.Nanoseconds()) }
go
func durationToTimespec(d time.Duration) unix.Timespec { return unix.NsecToTimespec(d.Nanoseconds()) }
[ "func", "durationToTimespec", "(", "d", "time", ".", "Duration", ")", "unix", ".", "Timespec", "{", "return", "unix", ".", "NsecToTimespec", "(", "d", ".", "Nanoseconds", "(", ")", ")", "\n", "}" ]
// durationToTimespec prepares a timeout value
[ "durationToTimespec", "prepares", "a", "timeout", "value" ]
1485a34d5d5723fea214f5710708e19a831720e4
https://github.com/fsnotify/fsnotify/blob/1485a34d5d5723fea214f5710708e19a831720e4/kqueue.go#L519-L521
162,254
fsnotify/fsnotify
inotify_poller.go
newFdPoller
func newFdPoller(fd int) (*fdPoller, error) { var errno error poller := emptyPoller(fd) defer func() { if errno != nil { poller.close() } }() poller.fd = fd // Create epoll fd poller.epfd, errno = unix.EpollCreate1(unix.EPOLL_CLOEXEC) if poller.epfd == -1 { return nil, errno } // Create pipe; pipe[0] is the read end, pipe[1] the write end. errno = unix.Pipe2(poller.pipe[:], unix.O_NONBLOCK|unix.O_CLOEXEC) if errno != nil { return nil, errno } // Register inotify fd with epoll event := unix.EpollEvent{ Fd: int32(poller.fd), Events: unix.EPOLLIN, } errno = unix.EpollCtl(poller.epfd, unix.EPOLL_CTL_ADD, poller.fd, &event) if errno != nil { return nil, errno } // Register pipe fd with epoll event = unix.EpollEvent{ Fd: int32(poller.pipe[0]), Events: unix.EPOLLIN, } errno = unix.EpollCtl(poller.epfd, unix.EPOLL_CTL_ADD, poller.pipe[0], &event) if errno != nil { return nil, errno } return poller, nil }
go
func newFdPoller(fd int) (*fdPoller, error) { var errno error poller := emptyPoller(fd) defer func() { if errno != nil { poller.close() } }() poller.fd = fd // Create epoll fd poller.epfd, errno = unix.EpollCreate1(unix.EPOLL_CLOEXEC) if poller.epfd == -1 { return nil, errno } // Create pipe; pipe[0] is the read end, pipe[1] the write end. errno = unix.Pipe2(poller.pipe[:], unix.O_NONBLOCK|unix.O_CLOEXEC) if errno != nil { return nil, errno } // Register inotify fd with epoll event := unix.EpollEvent{ Fd: int32(poller.fd), Events: unix.EPOLLIN, } errno = unix.EpollCtl(poller.epfd, unix.EPOLL_CTL_ADD, poller.fd, &event) if errno != nil { return nil, errno } // Register pipe fd with epoll event = unix.EpollEvent{ Fd: int32(poller.pipe[0]), Events: unix.EPOLLIN, } errno = unix.EpollCtl(poller.epfd, unix.EPOLL_CTL_ADD, poller.pipe[0], &event) if errno != nil { return nil, errno } return poller, nil }
[ "func", "newFdPoller", "(", "fd", "int", ")", "(", "*", "fdPoller", ",", "error", ")", "{", "var", "errno", "error", "\n", "poller", ":=", "emptyPoller", "(", "fd", ")", "\n", "defer", "func", "(", ")", "{", "if", "errno", "!=", "nil", "{", "poller", ".", "close", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n", "poller", ".", "fd", "=", "fd", "\n\n", "// Create epoll fd", "poller", ".", "epfd", ",", "errno", "=", "unix", ".", "EpollCreate1", "(", "unix", ".", "EPOLL_CLOEXEC", ")", "\n", "if", "poller", ".", "epfd", "==", "-", "1", "{", "return", "nil", ",", "errno", "\n", "}", "\n", "// Create pipe; pipe[0] is the read end, pipe[1] the write end.", "errno", "=", "unix", ".", "Pipe2", "(", "poller", ".", "pipe", "[", ":", "]", ",", "unix", ".", "O_NONBLOCK", "|", "unix", ".", "O_CLOEXEC", ")", "\n", "if", "errno", "!=", "nil", "{", "return", "nil", ",", "errno", "\n", "}", "\n\n", "// Register inotify fd with epoll", "event", ":=", "unix", ".", "EpollEvent", "{", "Fd", ":", "int32", "(", "poller", ".", "fd", ")", ",", "Events", ":", "unix", ".", "EPOLLIN", ",", "}", "\n", "errno", "=", "unix", ".", "EpollCtl", "(", "poller", ".", "epfd", ",", "unix", ".", "EPOLL_CTL_ADD", ",", "poller", ".", "fd", ",", "&", "event", ")", "\n", "if", "errno", "!=", "nil", "{", "return", "nil", ",", "errno", "\n", "}", "\n\n", "// Register pipe fd with epoll", "event", "=", "unix", ".", "EpollEvent", "{", "Fd", ":", "int32", "(", "poller", ".", "pipe", "[", "0", "]", ")", ",", "Events", ":", "unix", ".", "EPOLLIN", ",", "}", "\n", "errno", "=", "unix", ".", "EpollCtl", "(", "poller", ".", "epfd", ",", "unix", ".", "EPOLL_CTL_ADD", ",", "poller", ".", "pipe", "[", "0", "]", ",", "&", "event", ")", "\n", "if", "errno", "!=", "nil", "{", "return", "nil", ",", "errno", "\n", "}", "\n\n", "return", "poller", ",", "nil", "\n", "}" ]
// Create a new inotify poller. // This creates an inotify handler, and an epoll handler.
[ "Create", "a", "new", "inotify", "poller", ".", "This", "creates", "an", "inotify", "handler", "and", "an", "epoll", "handler", "." ]
1485a34d5d5723fea214f5710708e19a831720e4
https://github.com/fsnotify/fsnotify/blob/1485a34d5d5723fea214f5710708e19a831720e4/inotify_poller.go#L32-L74
162,255
fsnotify/fsnotify
inotify_poller.go
wait
func (poller *fdPoller) wait() (bool, error) { // 3 possible events per fd, and 2 fds, makes a maximum of 6 events. // I don't know whether epoll_wait returns the number of events returned, // or the total number of events ready. // I decided to catch both by making the buffer one larger than the maximum. events := make([]unix.EpollEvent, 7) for { n, errno := unix.EpollWait(poller.epfd, events, -1) if n == -1 { if errno == unix.EINTR { continue } return false, errno } if n == 0 { // If there are no events, try again. continue } if n > 6 { // This should never happen. More events were returned than should be possible. return false, errors.New("epoll_wait returned more events than I know what to do with") } ready := events[:n] epollhup := false epollerr := false epollin := false for _, event := range ready { if event.Fd == int32(poller.fd) { if event.Events&unix.EPOLLHUP != 0 { // This should not happen, but if it does, treat it as a wakeup. epollhup = true } if event.Events&unix.EPOLLERR != 0 { // If an error is waiting on the file descriptor, we should pretend // something is ready to read, and let unix.Read pick up the error. epollerr = true } if event.Events&unix.EPOLLIN != 0 { // There is data to read. epollin = true } } if event.Fd == int32(poller.pipe[0]) { if event.Events&unix.EPOLLHUP != 0 { // Write pipe descriptor was closed, by us. This means we're closing down the // watcher, and we should wake up. } if event.Events&unix.EPOLLERR != 0 { // If an error is waiting on the pipe file descriptor. // This is an absolute mystery, and should never ever happen. return false, errors.New("Error on the pipe descriptor.") } if event.Events&unix.EPOLLIN != 0 { // This is a regular wakeup, so we have to clear the buffer. err := poller.clearWake() if err != nil { return false, err } } } } if epollhup || epollerr || epollin { return true, nil } return false, nil } }
go
func (poller *fdPoller) wait() (bool, error) { // 3 possible events per fd, and 2 fds, makes a maximum of 6 events. // I don't know whether epoll_wait returns the number of events returned, // or the total number of events ready. // I decided to catch both by making the buffer one larger than the maximum. events := make([]unix.EpollEvent, 7) for { n, errno := unix.EpollWait(poller.epfd, events, -1) if n == -1 { if errno == unix.EINTR { continue } return false, errno } if n == 0 { // If there are no events, try again. continue } if n > 6 { // This should never happen. More events were returned than should be possible. return false, errors.New("epoll_wait returned more events than I know what to do with") } ready := events[:n] epollhup := false epollerr := false epollin := false for _, event := range ready { if event.Fd == int32(poller.fd) { if event.Events&unix.EPOLLHUP != 0 { // This should not happen, but if it does, treat it as a wakeup. epollhup = true } if event.Events&unix.EPOLLERR != 0 { // If an error is waiting on the file descriptor, we should pretend // something is ready to read, and let unix.Read pick up the error. epollerr = true } if event.Events&unix.EPOLLIN != 0 { // There is data to read. epollin = true } } if event.Fd == int32(poller.pipe[0]) { if event.Events&unix.EPOLLHUP != 0 { // Write pipe descriptor was closed, by us. This means we're closing down the // watcher, and we should wake up. } if event.Events&unix.EPOLLERR != 0 { // If an error is waiting on the pipe file descriptor. // This is an absolute mystery, and should never ever happen. return false, errors.New("Error on the pipe descriptor.") } if event.Events&unix.EPOLLIN != 0 { // This is a regular wakeup, so we have to clear the buffer. err := poller.clearWake() if err != nil { return false, err } } } } if epollhup || epollerr || epollin { return true, nil } return false, nil } }
[ "func", "(", "poller", "*", "fdPoller", ")", "wait", "(", ")", "(", "bool", ",", "error", ")", "{", "// 3 possible events per fd, and 2 fds, makes a maximum of 6 events.", "// I don't know whether epoll_wait returns the number of events returned,", "// or the total number of events ready.", "// I decided to catch both by making the buffer one larger than the maximum.", "events", ":=", "make", "(", "[", "]", "unix", ".", "EpollEvent", ",", "7", ")", "\n", "for", "{", "n", ",", "errno", ":=", "unix", ".", "EpollWait", "(", "poller", ".", "epfd", ",", "events", ",", "-", "1", ")", "\n", "if", "n", "==", "-", "1", "{", "if", "errno", "==", "unix", ".", "EINTR", "{", "continue", "\n", "}", "\n", "return", "false", ",", "errno", "\n", "}", "\n", "if", "n", "==", "0", "{", "// If there are no events, try again.", "continue", "\n", "}", "\n", "if", "n", ">", "6", "{", "// This should never happen. More events were returned than should be possible.", "return", "false", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "ready", ":=", "events", "[", ":", "n", "]", "\n", "epollhup", ":=", "false", "\n", "epollerr", ":=", "false", "\n", "epollin", ":=", "false", "\n", "for", "_", ",", "event", ":=", "range", "ready", "{", "if", "event", ".", "Fd", "==", "int32", "(", "poller", ".", "fd", ")", "{", "if", "event", ".", "Events", "&", "unix", ".", "EPOLLHUP", "!=", "0", "{", "// This should not happen, but if it does, treat it as a wakeup.", "epollhup", "=", "true", "\n", "}", "\n", "if", "event", ".", "Events", "&", "unix", ".", "EPOLLERR", "!=", "0", "{", "// If an error is waiting on the file descriptor, we should pretend", "// something is ready to read, and let unix.Read pick up the error.", "epollerr", "=", "true", "\n", "}", "\n", "if", "event", ".", "Events", "&", "unix", ".", "EPOLLIN", "!=", "0", "{", "// There is data to read.", "epollin", "=", "true", "\n", "}", "\n", "}", "\n", "if", "event", ".", "Fd", "==", "int32", "(", "poller", ".", "pipe", "[", "0", "]", ")", "{", "if", "event", ".", "Events", "&", "unix", ".", "EPOLLHUP", "!=", "0", "{", "// Write pipe descriptor was closed, by us. This means we're closing down the", "// watcher, and we should wake up.", "}", "\n", "if", "event", ".", "Events", "&", "unix", ".", "EPOLLERR", "!=", "0", "{", "// If an error is waiting on the pipe file descriptor.", "// This is an absolute mystery, and should never ever happen.", "return", "false", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "event", ".", "Events", "&", "unix", ".", "EPOLLIN", "!=", "0", "{", "// This is a regular wakeup, so we have to clear the buffer.", "err", ":=", "poller", ".", "clearWake", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "epollhup", "||", "epollerr", "||", "epollin", "{", "return", "true", ",", "nil", "\n", "}", "\n", "return", "false", ",", "nil", "\n", "}", "\n", "}" ]
// Wait using epoll. // Returns true if something is ready to be read, // false if there is not.
[ "Wait", "using", "epoll", ".", "Returns", "true", "if", "something", "is", "ready", "to", "be", "read", "false", "if", "there", "is", "not", "." ]
1485a34d5d5723fea214f5710708e19a831720e4
https://github.com/fsnotify/fsnotify/blob/1485a34d5d5723fea214f5710708e19a831720e4/inotify_poller.go#L79-L146
162,256
fsnotify/fsnotify
inotify_poller.go
wake
func (poller *fdPoller) wake() error { buf := make([]byte, 1) n, errno := unix.Write(poller.pipe[1], buf) if n == -1 { if errno == unix.EAGAIN { // Buffer is full, poller will wake. return nil } return errno } return nil }
go
func (poller *fdPoller) wake() error { buf := make([]byte, 1) n, errno := unix.Write(poller.pipe[1], buf) if n == -1 { if errno == unix.EAGAIN { // Buffer is full, poller will wake. return nil } return errno } return nil }
[ "func", "(", "poller", "*", "fdPoller", ")", "wake", "(", ")", "error", "{", "buf", ":=", "make", "(", "[", "]", "byte", ",", "1", ")", "\n", "n", ",", "errno", ":=", "unix", ".", "Write", "(", "poller", ".", "pipe", "[", "1", "]", ",", "buf", ")", "\n", "if", "n", "==", "-", "1", "{", "if", "errno", "==", "unix", ".", "EAGAIN", "{", "// Buffer is full, poller will wake.", "return", "nil", "\n", "}", "\n", "return", "errno", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close the write end of the poller.
[ "Close", "the", "write", "end", "of", "the", "poller", "." ]
1485a34d5d5723fea214f5710708e19a831720e4
https://github.com/fsnotify/fsnotify/blob/1485a34d5d5723fea214f5710708e19a831720e4/inotify_poller.go#L149-L160
162,257
fsnotify/fsnotify
inotify_poller.go
close
func (poller *fdPoller) close() { if poller.pipe[1] != -1 { unix.Close(poller.pipe[1]) } if poller.pipe[0] != -1 { unix.Close(poller.pipe[0]) } if poller.epfd != -1 { unix.Close(poller.epfd) } }
go
func (poller *fdPoller) close() { if poller.pipe[1] != -1 { unix.Close(poller.pipe[1]) } if poller.pipe[0] != -1 { unix.Close(poller.pipe[0]) } if poller.epfd != -1 { unix.Close(poller.epfd) } }
[ "func", "(", "poller", "*", "fdPoller", ")", "close", "(", ")", "{", "if", "poller", ".", "pipe", "[", "1", "]", "!=", "-", "1", "{", "unix", ".", "Close", "(", "poller", ".", "pipe", "[", "1", "]", ")", "\n", "}", "\n", "if", "poller", ".", "pipe", "[", "0", "]", "!=", "-", "1", "{", "unix", ".", "Close", "(", "poller", ".", "pipe", "[", "0", "]", ")", "\n", "}", "\n", "if", "poller", ".", "epfd", "!=", "-", "1", "{", "unix", ".", "Close", "(", "poller", ".", "epfd", ")", "\n", "}", "\n", "}" ]
// Close all poller file descriptors, but not the one passed to it.
[ "Close", "all", "poller", "file", "descriptors", "but", "not", "the", "one", "passed", "to", "it", "." ]
1485a34d5d5723fea214f5710708e19a831720e4
https://github.com/fsnotify/fsnotify/blob/1485a34d5d5723fea214f5710708e19a831720e4/inotify_poller.go#L177-L187
162,258
cilium/cilium
pkg/policy/groups/actions.go
AddDerivativeCNPIfNeeded
func AddDerivativeCNPIfNeeded(cnp *cilium_v2.CiliumNetworkPolicy) bool { if !cnp.RequiresDerivative() { log.WithFields(logrus.Fields{ logfields.CiliumNetworkPolicyName: cnp.ObjectMeta.Name, logfields.K8sNamespace: cnp.ObjectMeta.Namespace, }).Debug("CNP does not have derivative policies, skipped") return true } controllerManager.UpdateController(fmt.Sprintf("add-derivative-cnp-%s", cnp.ObjectMeta.Name), controller.ControllerParams{ DoFunc: func(ctx context.Context) error { return addDerivativeCNP(cnp) }, }) return true }
go
func AddDerivativeCNPIfNeeded(cnp *cilium_v2.CiliumNetworkPolicy) bool { if !cnp.RequiresDerivative() { log.WithFields(logrus.Fields{ logfields.CiliumNetworkPolicyName: cnp.ObjectMeta.Name, logfields.K8sNamespace: cnp.ObjectMeta.Namespace, }).Debug("CNP does not have derivative policies, skipped") return true } controllerManager.UpdateController(fmt.Sprintf("add-derivative-cnp-%s", cnp.ObjectMeta.Name), controller.ControllerParams{ DoFunc: func(ctx context.Context) error { return addDerivativeCNP(cnp) }, }) return true }
[ "func", "AddDerivativeCNPIfNeeded", "(", "cnp", "*", "cilium_v2", ".", "CiliumNetworkPolicy", ")", "bool", "{", "if", "!", "cnp", ".", "RequiresDerivative", "(", ")", "{", "log", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "logfields", ".", "CiliumNetworkPolicyName", ":", "cnp", ".", "ObjectMeta", ".", "Name", ",", "logfields", ".", "K8sNamespace", ":", "cnp", ".", "ObjectMeta", ".", "Namespace", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "return", "true", "\n", "}", "\n", "controllerManager", ".", "UpdateController", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cnp", ".", "ObjectMeta", ".", "Name", ")", ",", "controller", ".", "ControllerParams", "{", "DoFunc", ":", "func", "(", "ctx", "context", ".", "Context", ")", "error", "{", "return", "addDerivativeCNP", "(", "cnp", ")", "\n", "}", ",", "}", ")", "\n", "return", "true", "\n", "}" ]
// AddDerivativeCNPIfNeeded will create a new CNP if the given CNP has any rule // that need to create a new derivative policy. // It returns a boolean, true in case that all actions are correct, false if // something fails
[ "AddDerivativeCNPIfNeeded", "will", "create", "a", "new", "CNP", "if", "the", "given", "CNP", "has", "any", "rule", "that", "need", "to", "create", "a", "new", "derivative", "policy", ".", "It", "returns", "a", "boolean", "true", "in", "case", "that", "all", "actions", "are", "correct", "false", "if", "something", "fails" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/policy/groups/actions.go#L47-L62
162,259
cilium/cilium
pkg/policy/groups/actions.go
DeleteDerivativeCNP
func DeleteDerivativeCNP(cnp *cilium_v2.CiliumNetworkPolicy) error { scopedLog := log.WithFields(logrus.Fields{ logfields.CiliumNetworkPolicyName: cnp.ObjectMeta.Name, logfields.K8sNamespace: cnp.ObjectMeta.Namespace, }) if !cnp.RequiresDerivative() { scopedLog.Debug("CNP does not have derivative policies, skipped") return nil } err := k8s.CiliumClient().CiliumV2().CiliumNetworkPolicies(cnp.ObjectMeta.Namespace).DeleteCollection( &v1.DeleteOptions{}, v1.ListOptions{LabelSelector: fmt.Sprintf("%s=%s", parentCNP, cnp.ObjectMeta.UID)}) if err != nil { return err } DeleteDerivativeFromCache(cnp) return nil }
go
func DeleteDerivativeCNP(cnp *cilium_v2.CiliumNetworkPolicy) error { scopedLog := log.WithFields(logrus.Fields{ logfields.CiliumNetworkPolicyName: cnp.ObjectMeta.Name, logfields.K8sNamespace: cnp.ObjectMeta.Namespace, }) if !cnp.RequiresDerivative() { scopedLog.Debug("CNP does not have derivative policies, skipped") return nil } err := k8s.CiliumClient().CiliumV2().CiliumNetworkPolicies(cnp.ObjectMeta.Namespace).DeleteCollection( &v1.DeleteOptions{}, v1.ListOptions{LabelSelector: fmt.Sprintf("%s=%s", parentCNP, cnp.ObjectMeta.UID)}) if err != nil { return err } DeleteDerivativeFromCache(cnp) return nil }
[ "func", "DeleteDerivativeCNP", "(", "cnp", "*", "cilium_v2", ".", "CiliumNetworkPolicy", ")", "error", "{", "scopedLog", ":=", "log", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "logfields", ".", "CiliumNetworkPolicyName", ":", "cnp", ".", "ObjectMeta", ".", "Name", ",", "logfields", ".", "K8sNamespace", ":", "cnp", ".", "ObjectMeta", ".", "Namespace", ",", "}", ")", "\n\n", "if", "!", "cnp", ".", "RequiresDerivative", "(", ")", "{", "scopedLog", ".", "Debug", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n\n", "err", ":=", "k8s", ".", "CiliumClient", "(", ")", ".", "CiliumV2", "(", ")", ".", "CiliumNetworkPolicies", "(", "cnp", ".", "ObjectMeta", ".", "Namespace", ")", ".", "DeleteCollection", "(", "&", "v1", ".", "DeleteOptions", "{", "}", ",", "v1", ".", "ListOptions", "{", "LabelSelector", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "parentCNP", ",", "cnp", ".", "ObjectMeta", ".", "UID", ")", "}", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "DeleteDerivativeFromCache", "(", "cnp", ")", "\n", "return", "nil", "\n", "}" ]
// DeleteDerivativeCNP if the given policy has a derivative constraint,the // given CNP will be deleted from store and the cache.
[ "DeleteDerivativeCNP", "if", "the", "given", "policy", "has", "a", "derivative", "constraint", "the", "given", "CNP", "will", "be", "deleted", "from", "store", "and", "the", "cache", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/policy/groups/actions.go#L105-L127
162,260
cilium/cilium
pkg/command/exec/exec.go
combinedOutput
func combinedOutput(ctx context.Context, cmd *exec.Cmd, filters []string, scopedLog *logrus.Entry, verbose bool) ([]byte, error) { out, err := cmd.CombinedOutput() if ctx.Err() != nil { scopedLog.WithError(err).WithField("cmd", cmd.Args).Error("Command execution failed") return nil, fmt.Errorf("Command execution failed for %s: %s", cmd.Args, ctx.Err()) } if err != nil { if verbose { scopedLog.WithError(err).WithField("cmd", cmd.Args).Error("Command execution failed") scanner := bufio.NewScanner(bytes.NewReader(out)) scan: for scanner.Scan() { text := scanner.Text() for _, filter := range filters { if strings.Contains(text, filter) { continue scan } } scopedLog.Warn(text) } } } return out, err }
go
func combinedOutput(ctx context.Context, cmd *exec.Cmd, filters []string, scopedLog *logrus.Entry, verbose bool) ([]byte, error) { out, err := cmd.CombinedOutput() if ctx.Err() != nil { scopedLog.WithError(err).WithField("cmd", cmd.Args).Error("Command execution failed") return nil, fmt.Errorf("Command execution failed for %s: %s", cmd.Args, ctx.Err()) } if err != nil { if verbose { scopedLog.WithError(err).WithField("cmd", cmd.Args).Error("Command execution failed") scanner := bufio.NewScanner(bytes.NewReader(out)) scan: for scanner.Scan() { text := scanner.Text() for _, filter := range filters { if strings.Contains(text, filter) { continue scan } } scopedLog.Warn(text) } } } return out, err }
[ "func", "combinedOutput", "(", "ctx", "context", ".", "Context", ",", "cmd", "*", "exec", ".", "Cmd", ",", "filters", "[", "]", "string", ",", "scopedLog", "*", "logrus", ".", "Entry", ",", "verbose", "bool", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "out", ",", "err", ":=", "cmd", ".", "CombinedOutput", "(", ")", "\n", "if", "ctx", ".", "Err", "(", ")", "!=", "nil", "{", "scopedLog", ".", "WithError", "(", "err", ")", ".", "WithField", "(", "\"", "\"", ",", "cmd", ".", "Args", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "cmd", ".", "Args", ",", "ctx", ".", "Err", "(", ")", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "if", "verbose", "{", "scopedLog", ".", "WithError", "(", "err", ")", ".", "WithField", "(", "\"", "\"", ",", "cmd", ".", "Args", ")", ".", "Error", "(", "\"", "\"", ")", "\n\n", "scanner", ":=", "bufio", ".", "NewScanner", "(", "bytes", ".", "NewReader", "(", "out", ")", ")", "\n", "scan", ":", "for", "scanner", ".", "Scan", "(", ")", "{", "text", ":=", "scanner", ".", "Text", "(", ")", "\n", "for", "_", ",", "filter", ":=", "range", "filters", "{", "if", "strings", ".", "Contains", "(", "text", ",", "filter", ")", "{", "continue", "scan", "\n", "}", "\n", "}", "\n", "scopedLog", ".", "Warn", "(", "text", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "out", ",", "err", "\n", "}" ]
// combinedOutput is the core implementation of catching deadline exceeded // options and logging errors, with an optional set of filtered outputs.
[ "combinedOutput", "is", "the", "core", "implementation", "of", "catching", "deadline", "exceeded", "options", "and", "logging", "errors", "with", "an", "optional", "set", "of", "filtered", "outputs", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/command/exec/exec.go#L31-L55
162,261
cilium/cilium
pkg/command/exec/exec.go
CommandContext
func CommandContext(ctx context.Context, prog string, args ...string) *Cmd { return &Cmd{ Cmd: exec.CommandContext(ctx, prog, args...), ctx: ctx, } }
go
func CommandContext(ctx context.Context, prog string, args ...string) *Cmd { return &Cmd{ Cmd: exec.CommandContext(ctx, prog, args...), ctx: ctx, } }
[ "func", "CommandContext", "(", "ctx", "context", ".", "Context", ",", "prog", "string", ",", "args", "...", "string", ")", "*", "Cmd", "{", "return", "&", "Cmd", "{", "Cmd", ":", "exec", ".", "CommandContext", "(", "ctx", ",", "prog", ",", "args", "...", ")", ",", "ctx", ":", "ctx", ",", "}", "\n", "}" ]
// CommandContext wraps exec.CommandContext to allow this package to be used as // a drop-in replacement for the standard exec library.
[ "CommandContext", "wraps", "exec", ".", "CommandContext", "to", "allow", "this", "package", "to", "be", "used", "as", "a", "drop", "-", "in", "replacement", "for", "the", "standard", "exec", "library", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/command/exec/exec.go#L72-L77
162,262
cilium/cilium
pkg/command/exec/exec.go
WithTimeout
func WithTimeout(timeout time.Duration, prog string, args ...string) *Cmd { ctx, cancel := context.WithTimeout(context.Background(), timeout) cmd := CommandContext(ctx, prog, args...) cmd.cancelFn = cancel return cmd }
go
func WithTimeout(timeout time.Duration, prog string, args ...string) *Cmd { ctx, cancel := context.WithTimeout(context.Background(), timeout) cmd := CommandContext(ctx, prog, args...) cmd.cancelFn = cancel return cmd }
[ "func", "WithTimeout", "(", "timeout", "time", ".", "Duration", ",", "prog", "string", ",", "args", "...", "string", ")", "*", "Cmd", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "context", ".", "Background", "(", ")", ",", "timeout", ")", "\n", "cmd", ":=", "CommandContext", "(", "ctx", ",", "prog", ",", "args", "...", ")", "\n", "cmd", ".", "cancelFn", "=", "cancel", "\n", "return", "cmd", "\n", "}" ]
// WithTimeout creates a Cmd with a context that times out after the specified // duration.
[ "WithTimeout", "creates", "a", "Cmd", "with", "a", "context", "that", "times", "out", "after", "the", "specified", "duration", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/command/exec/exec.go#L81-L86
162,263
cilium/cilium
pkg/command/exec/exec.go
WithFilters
func (c *Cmd) WithFilters(filters ...string) *Cmd { c.filters = append(c.filters, filters...) return c }
go
func (c *Cmd) WithFilters(filters ...string) *Cmd { c.filters = append(c.filters, filters...) return c }
[ "func", "(", "c", "*", "Cmd", ")", "WithFilters", "(", "filters", "...", "string", ")", "*", "Cmd", "{", "c", ".", "filters", "=", "append", "(", "c", ".", "filters", ",", "filters", "...", ")", "\n", "return", "c", "\n", "}" ]
// WithFilters modifies the specified command to filter any output lines from // logs if they contain any of the substrings specified as arguments to this // function.
[ "WithFilters", "modifies", "the", "specified", "command", "to", "filter", "any", "output", "lines", "from", "logs", "if", "they", "contain", "any", "of", "the", "substrings", "specified", "as", "arguments", "to", "this", "function", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/command/exec/exec.go#L99-L102
162,264
cilium/cilium
pkg/command/exec/exec.go
CombinedOutput
func (c *Cmd) CombinedOutput(scopedLog *logrus.Entry, verbose bool) ([]byte, error) { out, err := combinedOutput(c.ctx, c.Cmd, c.filters, scopedLog, verbose) if c.cancelFn != nil { c.cancelFn() } return out, err }
go
func (c *Cmd) CombinedOutput(scopedLog *logrus.Entry, verbose bool) ([]byte, error) { out, err := combinedOutput(c.ctx, c.Cmd, c.filters, scopedLog, verbose) if c.cancelFn != nil { c.cancelFn() } return out, err }
[ "func", "(", "c", "*", "Cmd", ")", "CombinedOutput", "(", "scopedLog", "*", "logrus", ".", "Entry", ",", "verbose", "bool", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "out", ",", "err", ":=", "combinedOutput", "(", "c", ".", "ctx", ",", "c", ".", "Cmd", ",", "c", ".", "filters", ",", "scopedLog", ",", "verbose", ")", "\n", "if", "c", ".", "cancelFn", "!=", "nil", "{", "c", ".", "cancelFn", "(", ")", "\n", "}", "\n", "return", "out", ",", "err", "\n", "}" ]
// CombinedOutput runs the command and returns its combined standard output and // standard error. Unlike the standard library, if the context is exceeded, it // will return an error indicating so. // // Logs any errors that occur to the specified logger.
[ "CombinedOutput", "runs", "the", "command", "and", "returns", "its", "combined", "standard", "output", "and", "standard", "error", ".", "Unlike", "the", "standard", "library", "if", "the", "context", "is", "exceeded", "it", "will", "return", "an", "error", "indicating", "so", ".", "Logs", "any", "errors", "that", "occur", "to", "the", "specified", "logger", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/command/exec/exec.go#L109-L115
162,265
cilium/cilium
pkg/datapath/linux/node.go
NewNodeHandler
func NewNodeHandler(datapathConfig DatapathConfiguration, nodeAddressing datapath.NodeAddressing) datapath.NodeHandler { return &linuxNodeHandler{ nodeAddressing: nodeAddressing, datapathConfig: datapathConfig, nodes: map[node.Identity]*node.Node{}, } }
go
func NewNodeHandler(datapathConfig DatapathConfiguration, nodeAddressing datapath.NodeAddressing) datapath.NodeHandler { return &linuxNodeHandler{ nodeAddressing: nodeAddressing, datapathConfig: datapathConfig, nodes: map[node.Identity]*node.Node{}, } }
[ "func", "NewNodeHandler", "(", "datapathConfig", "DatapathConfiguration", ",", "nodeAddressing", "datapath", ".", "NodeAddressing", ")", "datapath", ".", "NodeHandler", "{", "return", "&", "linuxNodeHandler", "{", "nodeAddressing", ":", "nodeAddressing", ",", "datapathConfig", ":", "datapathConfig", ",", "nodes", ":", "map", "[", "node", ".", "Identity", "]", "*", "node", ".", "Node", "{", "}", ",", "}", "\n", "}" ]
// NewNodeHandler returns a new node handler to handle node events and // implement the implications in the Linux datapath
[ "NewNodeHandler", "returns", "a", "new", "node", "handler", "to", "handle", "node", "events", "and", "implement", "the", "implications", "in", "the", "Linux", "datapath" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/datapath/linux/node.go#L52-L58
162,266
cilium/cilium
pkg/datapath/linux/node.go
updateTunnelMapping
func updateTunnelMapping(oldCIDR, newCIDR *cidr.CIDR, oldIP, newIP net.IP, firstAddition, encapEnabled bool, oldEncryptKey, newEncryptKey uint8) { if !encapEnabled { // When the protocol family is disabled, the initial node addition will // trigger a deletion to clean up leftover entries. The deletion happens // in quiet mode as we don't know whether it exists or not if newCIDR != nil && firstAddition { deleteTunnelMapping(newCIDR, true) } return } if cidrNodeMappingUpdateRequired(oldCIDR, newCIDR, oldIP, newIP, oldEncryptKey, newEncryptKey) { log.WithFields(logrus.Fields{ logfields.IPAddr: newIP, "allocCIDR": newCIDR, }).Debug("Updating tunnel map entry") if err := tunnel.TunnelMap.SetTunnelEndpoint(newEncryptKey, newCIDR.IP, newIP); err != nil { log.WithError(err).WithFields(logrus.Fields{ "allocCIDR": newCIDR, }).Error("bpf: Unable to update in tunnel endpoint map") } } // Determine whether an old tunnel mapping must be cleaned up. The // below switch lists all conditions in which case the oldCIDR must be // removed from the tunnel mapping switch { // CIDR no longer announced case newCIDR == nil && oldCIDR != nil: fallthrough // Node allocation CIDR has changed case oldCIDR != nil && newCIDR != nil && !oldCIDR.IP.Equal(newCIDR.IP): deleteTunnelMapping(oldCIDR, false) } }
go
func updateTunnelMapping(oldCIDR, newCIDR *cidr.CIDR, oldIP, newIP net.IP, firstAddition, encapEnabled bool, oldEncryptKey, newEncryptKey uint8) { if !encapEnabled { // When the protocol family is disabled, the initial node addition will // trigger a deletion to clean up leftover entries. The deletion happens // in quiet mode as we don't know whether it exists or not if newCIDR != nil && firstAddition { deleteTunnelMapping(newCIDR, true) } return } if cidrNodeMappingUpdateRequired(oldCIDR, newCIDR, oldIP, newIP, oldEncryptKey, newEncryptKey) { log.WithFields(logrus.Fields{ logfields.IPAddr: newIP, "allocCIDR": newCIDR, }).Debug("Updating tunnel map entry") if err := tunnel.TunnelMap.SetTunnelEndpoint(newEncryptKey, newCIDR.IP, newIP); err != nil { log.WithError(err).WithFields(logrus.Fields{ "allocCIDR": newCIDR, }).Error("bpf: Unable to update in tunnel endpoint map") } } // Determine whether an old tunnel mapping must be cleaned up. The // below switch lists all conditions in which case the oldCIDR must be // removed from the tunnel mapping switch { // CIDR no longer announced case newCIDR == nil && oldCIDR != nil: fallthrough // Node allocation CIDR has changed case oldCIDR != nil && newCIDR != nil && !oldCIDR.IP.Equal(newCIDR.IP): deleteTunnelMapping(oldCIDR, false) } }
[ "func", "updateTunnelMapping", "(", "oldCIDR", ",", "newCIDR", "*", "cidr", ".", "CIDR", ",", "oldIP", ",", "newIP", "net", ".", "IP", ",", "firstAddition", ",", "encapEnabled", "bool", ",", "oldEncryptKey", ",", "newEncryptKey", "uint8", ")", "{", "if", "!", "encapEnabled", "{", "// When the protocol family is disabled, the initial node addition will", "// trigger a deletion to clean up leftover entries. The deletion happens", "// in quiet mode as we don't know whether it exists or not", "if", "newCIDR", "!=", "nil", "&&", "firstAddition", "{", "deleteTunnelMapping", "(", "newCIDR", ",", "true", ")", "\n", "}", "\n\n", "return", "\n", "}", "\n\n", "if", "cidrNodeMappingUpdateRequired", "(", "oldCIDR", ",", "newCIDR", ",", "oldIP", ",", "newIP", ",", "oldEncryptKey", ",", "newEncryptKey", ")", "{", "log", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "logfields", ".", "IPAddr", ":", "newIP", ",", "\"", "\"", ":", "newCIDR", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "if", "err", ":=", "tunnel", ".", "TunnelMap", ".", "SetTunnelEndpoint", "(", "newEncryptKey", ",", "newCIDR", ".", "IP", ",", "newIP", ")", ";", "err", "!=", "nil", "{", "log", ".", "WithError", "(", "err", ")", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "newCIDR", ",", "}", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "// Determine whether an old tunnel mapping must be cleaned up. The", "// below switch lists all conditions in which case the oldCIDR must be", "// removed from the tunnel mapping", "switch", "{", "// CIDR no longer announced", "case", "newCIDR", "==", "nil", "&&", "oldCIDR", "!=", "nil", ":", "fallthrough", "\n", "// Node allocation CIDR has changed", "case", "oldCIDR", "!=", "nil", "&&", "newCIDR", "!=", "nil", "&&", "!", "oldCIDR", ".", "IP", ".", "Equal", "(", "newCIDR", ".", "IP", ")", ":", "deleteTunnelMapping", "(", "oldCIDR", ",", "false", ")", "\n", "}", "\n", "}" ]
// updateTunnelMapping is called when a node update is received while running // with encapsulation mode enabled. The CIDR and IP of both the old and new // node are provided as context. The caller expects the tunnel mapping in the // datapath to be updated.
[ "updateTunnelMapping", "is", "called", "when", "a", "node", "update", "is", "received", "while", "running", "with", "encapsulation", "mode", "enabled", ".", "The", "CIDR", "and", "IP", "of", "both", "the", "old", "and", "new", "node", "are", "provided", "as", "context", ".", "The", "caller", "expects", "the", "tunnel", "mapping", "in", "the", "datapath", "to", "be", "updated", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/datapath/linux/node.go#L64-L100
162,267
cilium/cilium
pkg/datapath/linux/node.go
replaceNodeIPSecOutRoute
func (n *linuxNodeHandler) replaceNodeIPSecOutRoute(ip *net.IPNet) { if ip == nil { return } if ip.IP.To4() != nil { if !n.nodeConfig.EnableIPv4 { return } } else { if !n.nodeConfig.EnableIPv6 { return } } _, err := route.Upsert(n.createNodeIPSecOutRoute(ip), n.nodeConfig.MtuConfig) if err != nil { log.WithError(err).Error("Unable to replace the IPSec route OUT the host routing table") } }
go
func (n *linuxNodeHandler) replaceNodeIPSecOutRoute(ip *net.IPNet) { if ip == nil { return } if ip.IP.To4() != nil { if !n.nodeConfig.EnableIPv4 { return } } else { if !n.nodeConfig.EnableIPv6 { return } } _, err := route.Upsert(n.createNodeIPSecOutRoute(ip), n.nodeConfig.MtuConfig) if err != nil { log.WithError(err).Error("Unable to replace the IPSec route OUT the host routing table") } }
[ "func", "(", "n", "*", "linuxNodeHandler", ")", "replaceNodeIPSecOutRoute", "(", "ip", "*", "net", ".", "IPNet", ")", "{", "if", "ip", "==", "nil", "{", "return", "\n", "}", "\n\n", "if", "ip", ".", "IP", ".", "To4", "(", ")", "!=", "nil", "{", "if", "!", "n", ".", "nodeConfig", ".", "EnableIPv4", "{", "return", "\n", "}", "\n", "}", "else", "{", "if", "!", "n", ".", "nodeConfig", ".", "EnableIPv6", "{", "return", "\n", "}", "\n", "}", "\n\n", "_", ",", "err", ":=", "route", ".", "Upsert", "(", "n", ".", "createNodeIPSecOutRoute", "(", "ip", ")", ",", "n", ".", "nodeConfig", ".", "MtuConfig", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// replaceNodeIPSecOutRoute replace the out IPSec route in the host routing table // with the new route. If no route exists the route is installed on the host.
[ "replaceNodeIPSecOutRoute", "replace", "the", "out", "IPSec", "route", "in", "the", "host", "routing", "table", "with", "the", "new", "route", ".", "If", "no", "route", "exists", "the", "route", "is", "installed", "on", "the", "host", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/datapath/linux/node.go#L681-L700
162,268
cilium/cilium
pkg/datapath/linux/node.go
NodeConfigurationChanged
func (n *linuxNodeHandler) NodeConfigurationChanged(newConfig datapath.LocalNodeConfiguration) error { n.mutex.Lock() defer n.mutex.Unlock() prevConfig := n.nodeConfig n.nodeConfig = newConfig n.updateOrRemoveNodeRoutes(prevConfig.AuxiliaryPrefixes, newConfig.AuxiliaryPrefixes) if newConfig.UseSingleClusterRoute { n.updateOrRemoveClusterRoute(n.nodeAddressing.IPv4(), newConfig.EnableIPv4) n.updateOrRemoveClusterRoute(n.nodeAddressing.IPv6(), newConfig.EnableIPv6) } else if prevConfig.UseSingleClusterRoute { // single cluster route has been disabled, remove route n.deleteNodeRoute(n.nodeAddressing.IPv4().AllocationCIDR()) n.deleteNodeRoute(n.nodeAddressing.IPv6().AllocationCIDR()) } if !n.isInitialized { n.isInitialized = true if !n.nodeConfig.UseSingleClusterRoute { for _, unlinkedNode := range n.nodes { n.nodeUpdate(nil, unlinkedNode, true) } } } return nil }
go
func (n *linuxNodeHandler) NodeConfigurationChanged(newConfig datapath.LocalNodeConfiguration) error { n.mutex.Lock() defer n.mutex.Unlock() prevConfig := n.nodeConfig n.nodeConfig = newConfig n.updateOrRemoveNodeRoutes(prevConfig.AuxiliaryPrefixes, newConfig.AuxiliaryPrefixes) if newConfig.UseSingleClusterRoute { n.updateOrRemoveClusterRoute(n.nodeAddressing.IPv4(), newConfig.EnableIPv4) n.updateOrRemoveClusterRoute(n.nodeAddressing.IPv6(), newConfig.EnableIPv6) } else if prevConfig.UseSingleClusterRoute { // single cluster route has been disabled, remove route n.deleteNodeRoute(n.nodeAddressing.IPv4().AllocationCIDR()) n.deleteNodeRoute(n.nodeAddressing.IPv6().AllocationCIDR()) } if !n.isInitialized { n.isInitialized = true if !n.nodeConfig.UseSingleClusterRoute { for _, unlinkedNode := range n.nodes { n.nodeUpdate(nil, unlinkedNode, true) } } } return nil }
[ "func", "(", "n", "*", "linuxNodeHandler", ")", "NodeConfigurationChanged", "(", "newConfig", "datapath", ".", "LocalNodeConfiguration", ")", "error", "{", "n", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "n", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "prevConfig", ":=", "n", ".", "nodeConfig", "\n", "n", ".", "nodeConfig", "=", "newConfig", "\n\n", "n", ".", "updateOrRemoveNodeRoutes", "(", "prevConfig", ".", "AuxiliaryPrefixes", ",", "newConfig", ".", "AuxiliaryPrefixes", ")", "\n\n", "if", "newConfig", ".", "UseSingleClusterRoute", "{", "n", ".", "updateOrRemoveClusterRoute", "(", "n", ".", "nodeAddressing", ".", "IPv4", "(", ")", ",", "newConfig", ".", "EnableIPv4", ")", "\n", "n", ".", "updateOrRemoveClusterRoute", "(", "n", ".", "nodeAddressing", ".", "IPv6", "(", ")", ",", "newConfig", ".", "EnableIPv6", ")", "\n", "}", "else", "if", "prevConfig", ".", "UseSingleClusterRoute", "{", "// single cluster route has been disabled, remove route", "n", ".", "deleteNodeRoute", "(", "n", ".", "nodeAddressing", ".", "IPv4", "(", ")", ".", "AllocationCIDR", "(", ")", ")", "\n", "n", ".", "deleteNodeRoute", "(", "n", ".", "nodeAddressing", ".", "IPv6", "(", ")", ".", "AllocationCIDR", "(", ")", ")", "\n", "}", "\n\n", "if", "!", "n", ".", "isInitialized", "{", "n", ".", "isInitialized", "=", "true", "\n", "if", "!", "n", ".", "nodeConfig", ".", "UseSingleClusterRoute", "{", "for", "_", ",", "unlinkedNode", ":=", "range", "n", ".", "nodes", "{", "n", ".", "nodeUpdate", "(", "nil", ",", "unlinkedNode", ",", "true", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// NodeConfigurationChanged is called when the LocalNodeConfiguration has changed
[ "NodeConfigurationChanged", "is", "called", "when", "the", "LocalNodeConfiguration", "has", "changed" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/datapath/linux/node.go#L726-L754
162,269
cilium/cilium
pkg/datapath/linux/node.go
NodeValidateImplementation
func (n *linuxNodeHandler) NodeValidateImplementation(nodeToValidate node.Node) error { return n.nodeUpdate(nil, &nodeToValidate, false) }
go
func (n *linuxNodeHandler) NodeValidateImplementation(nodeToValidate node.Node) error { return n.nodeUpdate(nil, &nodeToValidate, false) }
[ "func", "(", "n", "*", "linuxNodeHandler", ")", "NodeValidateImplementation", "(", "nodeToValidate", "node", ".", "Node", ")", "error", "{", "return", "n", ".", "nodeUpdate", "(", "nil", ",", "&", "nodeToValidate", ",", "false", ")", "\n", "}" ]
// NodeValidateImplementation is called to validate the implementation of the // node in the datapath
[ "NodeValidateImplementation", "is", "called", "to", "validate", "the", "implementation", "of", "the", "node", "in", "the", "datapath" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/datapath/linux/node.go#L758-L760
162,270
cilium/cilium
api/v1/client/endpoint/get_endpoint_id_config_parameters.go
WithTimeout
func (o *GetEndpointIDConfigParams) WithTimeout(timeout time.Duration) *GetEndpointIDConfigParams { o.SetTimeout(timeout) return o }
go
func (o *GetEndpointIDConfigParams) WithTimeout(timeout time.Duration) *GetEndpointIDConfigParams { o.SetTimeout(timeout) return o }
[ "func", "(", "o", "*", "GetEndpointIDConfigParams", ")", "WithTimeout", "(", "timeout", "time", ".", "Duration", ")", "*", "GetEndpointIDConfigParams", "{", "o", ".", "SetTimeout", "(", "timeout", ")", "\n", "return", "o", "\n", "}" ]
// WithTimeout adds the timeout to the get endpoint ID config params
[ "WithTimeout", "adds", "the", "timeout", "to", "the", "get", "endpoint", "ID", "config", "params" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/api/v1/client/endpoint/get_endpoint_id_config_parameters.go#L88-L91
162,271
cilium/cilium
api/v1/client/endpoint/get_endpoint_id_config_parameters.go
WithContext
func (o *GetEndpointIDConfigParams) WithContext(ctx context.Context) *GetEndpointIDConfigParams { o.SetContext(ctx) return o }
go
func (o *GetEndpointIDConfigParams) WithContext(ctx context.Context) *GetEndpointIDConfigParams { o.SetContext(ctx) return o }
[ "func", "(", "o", "*", "GetEndpointIDConfigParams", ")", "WithContext", "(", "ctx", "context", ".", "Context", ")", "*", "GetEndpointIDConfigParams", "{", "o", ".", "SetContext", "(", "ctx", ")", "\n", "return", "o", "\n", "}" ]
// WithContext adds the context to the get endpoint ID config params
[ "WithContext", "adds", "the", "context", "to", "the", "get", "endpoint", "ID", "config", "params" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/api/v1/client/endpoint/get_endpoint_id_config_parameters.go#L99-L102
162,272
cilium/cilium
api/v1/client/endpoint/get_endpoint_id_config_parameters.go
WithHTTPClient
func (o *GetEndpointIDConfigParams) WithHTTPClient(client *http.Client) *GetEndpointIDConfigParams { o.SetHTTPClient(client) return o }
go
func (o *GetEndpointIDConfigParams) WithHTTPClient(client *http.Client) *GetEndpointIDConfigParams { o.SetHTTPClient(client) return o }
[ "func", "(", "o", "*", "GetEndpointIDConfigParams", ")", "WithHTTPClient", "(", "client", "*", "http", ".", "Client", ")", "*", "GetEndpointIDConfigParams", "{", "o", ".", "SetHTTPClient", "(", "client", ")", "\n", "return", "o", "\n", "}" ]
// WithHTTPClient adds the HTTPClient to the get endpoint ID config params
[ "WithHTTPClient", "adds", "the", "HTTPClient", "to", "the", "get", "endpoint", "ID", "config", "params" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/api/v1/client/endpoint/get_endpoint_id_config_parameters.go#L110-L113
162,273
cilium/cilium
api/v1/client/endpoint/get_endpoint_id_config_parameters.go
WithID
func (o *GetEndpointIDConfigParams) WithID(id string) *GetEndpointIDConfigParams { o.SetID(id) return o }
go
func (o *GetEndpointIDConfigParams) WithID(id string) *GetEndpointIDConfigParams { o.SetID(id) return o }
[ "func", "(", "o", "*", "GetEndpointIDConfigParams", ")", "WithID", "(", "id", "string", ")", "*", "GetEndpointIDConfigParams", "{", "o", ".", "SetID", "(", "id", ")", "\n", "return", "o", "\n", "}" ]
// WithID adds the id to the get endpoint ID config params
[ "WithID", "adds", "the", "id", "to", "the", "get", "endpoint", "ID", "config", "params" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/api/v1/client/endpoint/get_endpoint_id_config_parameters.go#L121-L124
162,274
cilium/cilium
pkg/k8s/config.go
Configure
func Configure(apiServer, kubeconfigPath string) { config.APIServer = apiServer config.KubeconfigPath = kubeconfigPath if IsEnabled() && config.APIServer != "" && !strings.HasPrefix(apiServer, "http") { config.APIServer = "http://" + apiServer } }
go
func Configure(apiServer, kubeconfigPath string) { config.APIServer = apiServer config.KubeconfigPath = kubeconfigPath if IsEnabled() && config.APIServer != "" && !strings.HasPrefix(apiServer, "http") { config.APIServer = "http://" + apiServer } }
[ "func", "Configure", "(", "apiServer", ",", "kubeconfigPath", "string", ")", "{", "config", ".", "APIServer", "=", "apiServer", "\n", "config", ".", "KubeconfigPath", "=", "kubeconfigPath", "\n\n", "if", "IsEnabled", "(", ")", "&&", "config", ".", "APIServer", "!=", "\"", "\"", "&&", "!", "strings", ".", "HasPrefix", "(", "apiServer", ",", "\"", "\"", ")", "{", "config", ".", "APIServer", "=", "\"", "\"", "+", "apiServer", "\n", "}", "\n", "}" ]
// Configure sets the parameters of the Kubernetes package
[ "Configure", "sets", "the", "parameters", "of", "the", "Kubernetes", "package" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/k8s/config.go#L49-L58
162,275
cilium/cilium
pkg/k8s/config.go
IsEnabled
func IsEnabled() bool { return config.APIServer != "" || config.KubeconfigPath != "" || (os.Getenv("KUBERNETES_SERVICE_HOST") != "" && os.Getenv("KUBERNETES_SERVICE_PORT") != "") }
go
func IsEnabled() bool { return config.APIServer != "" || config.KubeconfigPath != "" || (os.Getenv("KUBERNETES_SERVICE_HOST") != "" && os.Getenv("KUBERNETES_SERVICE_PORT") != "") }
[ "func", "IsEnabled", "(", ")", "bool", "{", "return", "config", ".", "APIServer", "!=", "\"", "\"", "||", "config", ".", "KubeconfigPath", "!=", "\"", "\"", "||", "(", "os", ".", "Getenv", "(", "\"", "\"", ")", "!=", "\"", "\"", "&&", "os", ".", "Getenv", "(", "\"", "\"", ")", "!=", "\"", "\"", ")", "\n", "}" ]
// IsEnabled checks if Cilium is being used in tandem with Kubernetes.
[ "IsEnabled", "checks", "if", "Cilium", "is", "being", "used", "in", "tandem", "with", "Kubernetes", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/k8s/config.go#L61-L66
162,276
cilium/cilium
pkg/api/socket.go
GetGroupIDByName
func GetGroupIDByName(grpName string) (int, error) { f, err := os.Open(GroupFilePath) if err != nil { return -1, err } defer f.Close() br := bufio.NewReader(f) for { s, err := br.ReadString('\n') if err == io.EOF { break } if err != nil { return -1, err } p := strings.Split(s, ":") if len(p) >= 3 && p[0] == grpName { return strconv.Atoi(p[2]) } } return -1, fmt.Errorf("group %q not found", grpName) }
go
func GetGroupIDByName(grpName string) (int, error) { f, err := os.Open(GroupFilePath) if err != nil { return -1, err } defer f.Close() br := bufio.NewReader(f) for { s, err := br.ReadString('\n') if err == io.EOF { break } if err != nil { return -1, err } p := strings.Split(s, ":") if len(p) >= 3 && p[0] == grpName { return strconv.Atoi(p[2]) } } return -1, fmt.Errorf("group %q not found", grpName) }
[ "func", "GetGroupIDByName", "(", "grpName", "string", ")", "(", "int", ",", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "GroupFilePath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "br", ":=", "bufio", ".", "NewReader", "(", "f", ")", "\n", "for", "{", "s", ",", "err", ":=", "br", ".", "ReadString", "(", "'\\n'", ")", "\n", "if", "err", "==", "io", ".", "EOF", "{", "break", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "err", "\n", "}", "\n", "p", ":=", "strings", ".", "Split", "(", "s", ",", "\"", "\"", ")", "\n", "if", "len", "(", "p", ")", ">=", "3", "&&", "p", "[", "0", "]", "==", "grpName", "{", "return", "strconv", ".", "Atoi", "(", "p", "[", "2", "]", ")", "\n", "}", "\n", "}", "\n", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "grpName", ")", "\n", "}" ]
// GetGroupIDByName returns the group ID for the given grpName.
[ "GetGroupIDByName", "returns", "the", "group", "ID", "for", "the", "given", "grpName", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/api/socket.go#L34-L55
162,277
cilium/cilium
pkg/api/socket.go
SetDefaultPermissions
func SetDefaultPermissions(socketPath string) error { gid, err := GetGroupIDByName(CiliumGroupName) if err != nil { log.WithError(err).WithFields(logrus.Fields{ logfields.Path: socketPath, "group": CiliumGroupName, }).Info("Group not found") } else { if err := os.Chown(socketPath, 0, gid); err != nil { return fmt.Errorf("failed while setting up %s's group ID"+ " in %q: %s", CiliumGroupName, socketPath, err) } } if err := os.Chmod(socketPath, SocketFileMode); err != nil { return fmt.Errorf("failed while setting up %s's file"+ " permissions in %q: %s", CiliumGroupName, socketPath, err) } return nil }
go
func SetDefaultPermissions(socketPath string) error { gid, err := GetGroupIDByName(CiliumGroupName) if err != nil { log.WithError(err).WithFields(logrus.Fields{ logfields.Path: socketPath, "group": CiliumGroupName, }).Info("Group not found") } else { if err := os.Chown(socketPath, 0, gid); err != nil { return fmt.Errorf("failed while setting up %s's group ID"+ " in %q: %s", CiliumGroupName, socketPath, err) } } if err := os.Chmod(socketPath, SocketFileMode); err != nil { return fmt.Errorf("failed while setting up %s's file"+ " permissions in %q: %s", CiliumGroupName, socketPath, err) } return nil }
[ "func", "SetDefaultPermissions", "(", "socketPath", "string", ")", "error", "{", "gid", ",", "err", ":=", "GetGroupIDByName", "(", "CiliumGroupName", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "WithError", "(", "err", ")", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "logfields", ".", "Path", ":", "socketPath", ",", "\"", "\"", ":", "CiliumGroupName", ",", "}", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "}", "else", "{", "if", "err", ":=", "os", ".", "Chown", "(", "socketPath", ",", "0", ",", "gid", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "CiliumGroupName", ",", "socketPath", ",", "err", ")", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "os", ".", "Chmod", "(", "socketPath", ",", "SocketFileMode", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "CiliumGroupName", ",", "socketPath", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SetDefaultPermissions sets the given socket to with cilium's default // group and mode permissions. Group `CiliumGroupName` and mode `0660`
[ "SetDefaultPermissions", "sets", "the", "given", "socket", "to", "with", "cilium", "s", "default", "group", "and", "mode", "permissions", ".", "Group", "CiliumGroupName", "and", "mode", "0660" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/api/socket.go#L59-L77
162,278
cilium/cilium
pkg/bpf/bpffs_linux.go
MapPath
func MapPath(name string) string { if components.IsCiliumAgent() { once.Do(lockDown) return filepath.Join(mapRoot, mapPrefix, name) } return mapPathFromMountInfo(name) }
go
func MapPath(name string) string { if components.IsCiliumAgent() { once.Do(lockDown) return filepath.Join(mapRoot, mapPrefix, name) } return mapPathFromMountInfo(name) }
[ "func", "MapPath", "(", "name", "string", ")", "string", "{", "if", "components", ".", "IsCiliumAgent", "(", ")", "{", "once", ".", "Do", "(", "lockDown", ")", "\n", "return", "filepath", ".", "Join", "(", "mapRoot", ",", "mapPrefix", ",", "name", ")", "\n", "}", "\n", "return", "mapPathFromMountInfo", "(", "name", ")", "\n", "}" ]
// MapPath returns a path for a BPF map with a given name.
[ "MapPath", "returns", "a", "path", "for", "a", "BPF", "map", "with", "a", "given", "name", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/bpf/bpffs_linux.go#L100-L106
162,279
cilium/cilium
pkg/bpf/bpffs_linux.go
LocalMapName
func LocalMapName(name string, id uint16) string { return fmt.Sprintf("%s%05d", name, id) }
go
func LocalMapName(name string, id uint16) string { return fmt.Sprintf("%s%05d", name, id) }
[ "func", "LocalMapName", "(", "name", "string", ",", "id", "uint16", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "name", ",", "id", ")", "\n", "}" ]
// LocalMapName returns the name for a BPF map that is local to the specified ID.
[ "LocalMapName", "returns", "the", "name", "for", "a", "BPF", "map", "that", "is", "local", "to", "the", "specified", "ID", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/bpf/bpffs_linux.go#L109-L111
162,280
cilium/cilium
pkg/bpf/bpffs_linux.go
LocalMapPath
func LocalMapPath(name string, id uint16) string { return MapPath(LocalMapName(name, id)) }
go
func LocalMapPath(name string, id uint16) string { return MapPath(LocalMapName(name, id)) }
[ "func", "LocalMapPath", "(", "name", "string", ",", "id", "uint16", ")", "string", "{", "return", "MapPath", "(", "LocalMapName", "(", "name", ",", "id", ")", ")", "\n", "}" ]
// LocalMapPath returns the path for a BPF map that is local to the specified ID.
[ "LocalMapPath", "returns", "the", "path", "for", "a", "BPF", "map", "that", "is", "local", "to", "the", "specified", "ID", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/bpf/bpffs_linux.go#L114-L116
162,281
cilium/cilium
pkg/bpf/bpffs_linux.go
Environment
func Environment() []string { return append( os.Environ(), fmt.Sprintf("CILIUM_BPF_MNT=%s", GetMapRoot()), fmt.Sprintf("TC_BPF_MNT=%s", GetMapRoot()), ) }
go
func Environment() []string { return append( os.Environ(), fmt.Sprintf("CILIUM_BPF_MNT=%s", GetMapRoot()), fmt.Sprintf("TC_BPF_MNT=%s", GetMapRoot()), ) }
[ "func", "Environment", "(", ")", "[", "]", "string", "{", "return", "append", "(", "os", ".", "Environ", "(", ")", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "GetMapRoot", "(", ")", ")", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "GetMapRoot", "(", ")", ")", ",", ")", "\n", "}" ]
// Environment returns a list of environment variables which are needed to make // BPF programs and tc aware of the actual BPFFS mount path.
[ "Environment", "returns", "a", "list", "of", "environment", "variables", "which", "are", "needed", "to", "make", "BPF", "programs", "and", "tc", "aware", "of", "the", "actual", "BPFFS", "mount", "path", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/bpf/bpffs_linux.go#L120-L126
162,282
cilium/cilium
pkg/bpf/bpffs_linux.go
mountFS
func mountFS() error { if k8s.IsEnabled() { log.Warning("================================= WARNING ==========================================") log.Warning("BPF filesystem is not mounted. This will lead to network disruption when Cilium pods") log.Warning("are restarted. Ensure that the BPF filesystem is mounted in the host.") log.Warning("https://docs.cilium.io/en/stable/kubernetes/requirements/#mounted-bpf-filesystem") log.Warning("====================================================================================") } log.Infof("Mounting BPF filesystem at %s", mapRoot) mapRootStat, err := os.Stat(mapRoot) if err != nil { if os.IsNotExist(err) { if err := os.MkdirAll(mapRoot, 0755); err != nil { return fmt.Errorf("unable to create bpf mount directory: %s", err) } } else { return fmt.Errorf("failed to stat the mount path %s: %s", mapRoot, err) } } else if !mapRootStat.IsDir() { return fmt.Errorf("%s is a file which is not a directory", mapRoot) } if err := syscall.Mount(mapRoot, mapRoot, "bpf", 0, ""); err != nil { return fmt.Errorf("failed to mount %s: %s", mapRoot, err) } return nil }
go
func mountFS() error { if k8s.IsEnabled() { log.Warning("================================= WARNING ==========================================") log.Warning("BPF filesystem is not mounted. This will lead to network disruption when Cilium pods") log.Warning("are restarted. Ensure that the BPF filesystem is mounted in the host.") log.Warning("https://docs.cilium.io/en/stable/kubernetes/requirements/#mounted-bpf-filesystem") log.Warning("====================================================================================") } log.Infof("Mounting BPF filesystem at %s", mapRoot) mapRootStat, err := os.Stat(mapRoot) if err != nil { if os.IsNotExist(err) { if err := os.MkdirAll(mapRoot, 0755); err != nil { return fmt.Errorf("unable to create bpf mount directory: %s", err) } } else { return fmt.Errorf("failed to stat the mount path %s: %s", mapRoot, err) } } else if !mapRootStat.IsDir() { return fmt.Errorf("%s is a file which is not a directory", mapRoot) } if err := syscall.Mount(mapRoot, mapRoot, "bpf", 0, ""); err != nil { return fmt.Errorf("failed to mount %s: %s", mapRoot, err) } return nil }
[ "func", "mountFS", "(", ")", "error", "{", "if", "k8s", ".", "IsEnabled", "(", ")", "{", "log", ".", "Warning", "(", "\"", "\"", ")", "\n", "log", ".", "Warning", "(", "\"", "\"", ")", "\n", "log", ".", "Warning", "(", "\"", "\"", ")", "\n", "log", ".", "Warning", "(", "\"", "\"", ")", "\n", "log", ".", "Warning", "(", "\"", "\"", ")", "\n", "}", "\n\n", "log", ".", "Infof", "(", "\"", "\"", ",", "mapRoot", ")", "\n\n", "mapRootStat", ",", "err", ":=", "os", ".", "Stat", "(", "mapRoot", ")", "\n", "if", "err", "!=", "nil", "{", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "if", "err", ":=", "os", ".", "MkdirAll", "(", "mapRoot", ",", "0755", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "else", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "mapRoot", ",", "err", ")", "\n\n", "}", "\n", "}", "else", "if", "!", "mapRootStat", ".", "IsDir", "(", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "mapRoot", ")", "\n", "}", "\n\n", "if", "err", ":=", "syscall", ".", "Mount", "(", "mapRoot", ",", "mapRoot", ",", "\"", "\"", ",", "0", ",", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "mapRoot", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// mountFS mounts the BPFFS filesystem into the desired mapRoot directory.
[ "mountFS", "mounts", "the", "BPFFS", "filesystem", "into", "the", "desired", "mapRoot", "directory", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/bpf/bpffs_linux.go#L133-L162
162,283
cilium/cilium
pkg/bpf/bpffs_linux.go
hasMultipleMounts
func hasMultipleMounts() (bool, error) { num := 0 mountInfos, err := mountinfo.GetMountInfo() if err != nil { return false, err } for _, mountInfo := range mountInfos { if mountInfo.Root == "/" && mountInfo.MountPoint == mapRoot { num++ } } return num > 1, nil }
go
func hasMultipleMounts() (bool, error) { num := 0 mountInfos, err := mountinfo.GetMountInfo() if err != nil { return false, err } for _, mountInfo := range mountInfos { if mountInfo.Root == "/" && mountInfo.MountPoint == mapRoot { num++ } } return num > 1, nil }
[ "func", "hasMultipleMounts", "(", ")", "(", "bool", ",", "error", ")", "{", "num", ":=", "0", "\n\n", "mountInfos", ",", "err", ":=", "mountinfo", ".", "GetMountInfo", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n\n", "for", "_", ",", "mountInfo", ":=", "range", "mountInfos", "{", "if", "mountInfo", ".", "Root", "==", "\"", "\"", "&&", "mountInfo", ".", "MountPoint", "==", "mapRoot", "{", "num", "++", "\n", "}", "\n", "}", "\n\n", "return", "num", ">", "1", ",", "nil", "\n", "}" ]
// hasMultipleMounts checks whether the current mapRoot has only one mount.
[ "hasMultipleMounts", "checks", "whether", "the", "current", "mapRoot", "has", "only", "one", "mount", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/bpf/bpffs_linux.go#L165-L180
162,284
cilium/cilium
pkg/k8s/endpoints.go
String
func (e *Endpoints) String() string { if e == nil { return "" } backends := []string{} for ip, ports := range e.Backends { for _, port := range ports { backends = append(backends, fmt.Sprintf("%s/%s", net.JoinHostPort(ip, strconv.Itoa(int(port.Port))), port.Protocol)) } } sort.Strings(backends) return strings.Join(backends, ",") }
go
func (e *Endpoints) String() string { if e == nil { return "" } backends := []string{} for ip, ports := range e.Backends { for _, port := range ports { backends = append(backends, fmt.Sprintf("%s/%s", net.JoinHostPort(ip, strconv.Itoa(int(port.Port))), port.Protocol)) } } sort.Strings(backends) return strings.Join(backends, ",") }
[ "func", "(", "e", "*", "Endpoints", ")", "String", "(", ")", "string", "{", "if", "e", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n\n", "backends", ":=", "[", "]", "string", "{", "}", "\n", "for", "ip", ",", "ports", ":=", "range", "e", ".", "Backends", "{", "for", "_", ",", "port", ":=", "range", "ports", "{", "backends", "=", "append", "(", "backends", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "net", ".", "JoinHostPort", "(", "ip", ",", "strconv", ".", "Itoa", "(", "int", "(", "port", ".", "Port", ")", ")", ")", ",", "port", ".", "Protocol", ")", ")", "\n", "}", "\n", "}", "\n\n", "sort", ".", "Strings", "(", "backends", ")", "\n\n", "return", "strings", ".", "Join", "(", "backends", ",", "\"", "\"", ")", "\n", "}" ]
// String returns the string representation of an endpoints resource, with // backends and ports sorted.
[ "String", "returns", "the", "string", "representation", "of", "an", "endpoints", "resource", "with", "backends", "and", "ports", "sorted", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/k8s/endpoints.go#L43-L58
162,285
cilium/cilium
pkg/k8s/endpoints.go
DeepEquals
func (e *Endpoints) DeepEquals(o *Endpoints) bool { switch { case (e == nil) != (o == nil): return false case (e == nil) && (o == nil): return true } if len(e.Backends) != len(o.Backends) { return false } for ip1, ports1 := range e.Backends { ports2, ok := o.Backends[ip1] if !ok { return false } if !ports1.DeepEquals(ports2) { return false } } return true }
go
func (e *Endpoints) DeepEquals(o *Endpoints) bool { switch { case (e == nil) != (o == nil): return false case (e == nil) && (o == nil): return true } if len(e.Backends) != len(o.Backends) { return false } for ip1, ports1 := range e.Backends { ports2, ok := o.Backends[ip1] if !ok { return false } if !ports1.DeepEquals(ports2) { return false } } return true }
[ "func", "(", "e", "*", "Endpoints", ")", "DeepEquals", "(", "o", "*", "Endpoints", ")", "bool", "{", "switch", "{", "case", "(", "e", "==", "nil", ")", "!=", "(", "o", "==", "nil", ")", ":", "return", "false", "\n", "case", "(", "e", "==", "nil", ")", "&&", "(", "o", "==", "nil", ")", ":", "return", "true", "\n", "}", "\n\n", "if", "len", "(", "e", ".", "Backends", ")", "!=", "len", "(", "o", ".", "Backends", ")", "{", "return", "false", "\n", "}", "\n\n", "for", "ip1", ",", "ports1", ":=", "range", "e", ".", "Backends", "{", "ports2", ",", "ok", ":=", "o", ".", "Backends", "[", "ip1", "]", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n\n", "if", "!", "ports1", ".", "DeepEquals", "(", "ports2", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n\n", "return", "true", "\n", "}" ]
// DeepEquals returns true if both endpoints are deep equal.
[ "DeepEquals", "returns", "true", "if", "both", "endpoints", "are", "deep", "equal", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/k8s/endpoints.go#L68-L92
162,286
cilium/cilium
pkg/k8s/endpoints.go
CIDRPrefixes
func (e *Endpoints) CIDRPrefixes() ([]*net.IPNet, error) { prefixes := make([]string, len(e.Backends)) index := 0 for ip := range e.Backends { prefixes[index] = ip index++ } valid, invalid := ip.ParseCIDRs(prefixes) if len(invalid) > 0 { return nil, fmt.Errorf("invalid IPs specified as backends: %+v", invalid) } return valid, nil }
go
func (e *Endpoints) CIDRPrefixes() ([]*net.IPNet, error) { prefixes := make([]string, len(e.Backends)) index := 0 for ip := range e.Backends { prefixes[index] = ip index++ } valid, invalid := ip.ParseCIDRs(prefixes) if len(invalid) > 0 { return nil, fmt.Errorf("invalid IPs specified as backends: %+v", invalid) } return valid, nil }
[ "func", "(", "e", "*", "Endpoints", ")", "CIDRPrefixes", "(", ")", "(", "[", "]", "*", "net", ".", "IPNet", ",", "error", ")", "{", "prefixes", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "e", ".", "Backends", ")", ")", "\n", "index", ":=", "0", "\n", "for", "ip", ":=", "range", "e", ".", "Backends", "{", "prefixes", "[", "index", "]", "=", "ip", "\n", "index", "++", "\n", "}", "\n\n", "valid", ",", "invalid", ":=", "ip", ".", "ParseCIDRs", "(", "prefixes", ")", "\n", "if", "len", "(", "invalid", ")", ">", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "invalid", ")", "\n", "}", "\n\n", "return", "valid", ",", "nil", "\n", "}" ]
// CIDRPrefixes returns the endpoint's backends as a slice of IPNets.
[ "CIDRPrefixes", "returns", "the", "endpoint", "s", "backends", "as", "a", "slice", "of", "IPNets", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/k8s/endpoints.go#L95-L109
162,287
cilium/cilium
pkg/k8s/endpoints.go
ParseEndpointsID
func ParseEndpointsID(svc *types.Endpoints) ServiceID { return ServiceID{ Name: svc.ObjectMeta.Name, Namespace: svc.ObjectMeta.Namespace, } }
go
func ParseEndpointsID(svc *types.Endpoints) ServiceID { return ServiceID{ Name: svc.ObjectMeta.Name, Namespace: svc.ObjectMeta.Namespace, } }
[ "func", "ParseEndpointsID", "(", "svc", "*", "types", ".", "Endpoints", ")", "ServiceID", "{", "return", "ServiceID", "{", "Name", ":", "svc", ".", "ObjectMeta", ".", "Name", ",", "Namespace", ":", "svc", ".", "ObjectMeta", ".", "Namespace", ",", "}", "\n", "}" ]
// ParseEndpointsID parses a Kubernetes endpoints and returns the ServiceID
[ "ParseEndpointsID", "parses", "a", "Kubernetes", "endpoints", "and", "returns", "the", "ServiceID" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/k8s/endpoints.go#L112-L117
162,288
cilium/cilium
pkg/k8s/endpoints.go
ParseEndpoints
func ParseEndpoints(ep *types.Endpoints) (ServiceID, *Endpoints) { endpoints := newEndpoints() for _, sub := range ep.Subsets { for _, addr := range sub.Addresses { backend, ok := endpoints.Backends[addr.IP] if !ok { backend = service.PortConfiguration{} endpoints.Backends[addr.IP] = backend } for _, port := range sub.Ports { lbPort := loadbalancer.NewL4Addr(loadbalancer.L4Type(port.Protocol), uint16(port.Port)) backend[port.Name] = lbPort } } } return ParseEndpointsID(ep), endpoints }
go
func ParseEndpoints(ep *types.Endpoints) (ServiceID, *Endpoints) { endpoints := newEndpoints() for _, sub := range ep.Subsets { for _, addr := range sub.Addresses { backend, ok := endpoints.Backends[addr.IP] if !ok { backend = service.PortConfiguration{} endpoints.Backends[addr.IP] = backend } for _, port := range sub.Ports { lbPort := loadbalancer.NewL4Addr(loadbalancer.L4Type(port.Protocol), uint16(port.Port)) backend[port.Name] = lbPort } } } return ParseEndpointsID(ep), endpoints }
[ "func", "ParseEndpoints", "(", "ep", "*", "types", ".", "Endpoints", ")", "(", "ServiceID", ",", "*", "Endpoints", ")", "{", "endpoints", ":=", "newEndpoints", "(", ")", "\n\n", "for", "_", ",", "sub", ":=", "range", "ep", ".", "Subsets", "{", "for", "_", ",", "addr", ":=", "range", "sub", ".", "Addresses", "{", "backend", ",", "ok", ":=", "endpoints", ".", "Backends", "[", "addr", ".", "IP", "]", "\n", "if", "!", "ok", "{", "backend", "=", "service", ".", "PortConfiguration", "{", "}", "\n", "endpoints", ".", "Backends", "[", "addr", ".", "IP", "]", "=", "backend", "\n", "}", "\n\n", "for", "_", ",", "port", ":=", "range", "sub", ".", "Ports", "{", "lbPort", ":=", "loadbalancer", ".", "NewL4Addr", "(", "loadbalancer", ".", "L4Type", "(", "port", ".", "Protocol", ")", ",", "uint16", "(", "port", ".", "Port", ")", ")", "\n", "backend", "[", "port", ".", "Name", "]", "=", "lbPort", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "ParseEndpointsID", "(", "ep", ")", ",", "endpoints", "\n", "}" ]
// ParseEndpoints parses a Kubernetes Endpoints resource
[ "ParseEndpoints", "parses", "a", "Kubernetes", "Endpoints", "resource" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/k8s/endpoints.go#L120-L139
162,289
cilium/cilium
pkg/k8s/utils/utils.go
ExtractNamespace
func ExtractNamespace(np metav1.Object) string { ns := np.GetNamespace() if ns == "" { return v1.NamespaceDefault } return ns }
go
func ExtractNamespace(np metav1.Object) string { ns := np.GetNamespace() if ns == "" { return v1.NamespaceDefault } return ns }
[ "func", "ExtractNamespace", "(", "np", "metav1", ".", "Object", ")", "string", "{", "ns", ":=", "np", ".", "GetNamespace", "(", ")", "\n", "if", "ns", "==", "\"", "\"", "{", "return", "v1", ".", "NamespaceDefault", "\n", "}", "\n", "return", "ns", "\n", "}" ]
// ExtractNamespace extracts the namespace of ObjectMeta.
[ "ExtractNamespace", "extracts", "the", "namespace", "of", "ObjectMeta", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/k8s/utils/utils.go#L24-L30
162,290
cilium/cilium
pkg/k8s/utils/utils.go
GetObjUID
func GetObjUID(obj metav1.Object) string { return GetObjNamespaceName(obj) + "/" + string(obj.GetUID()) }
go
func GetObjUID(obj metav1.Object) string { return GetObjNamespaceName(obj) + "/" + string(obj.GetUID()) }
[ "func", "GetObjUID", "(", "obj", "metav1", ".", "Object", ")", "string", "{", "return", "GetObjNamespaceName", "(", "obj", ")", "+", "\"", "\"", "+", "string", "(", "obj", ".", "GetUID", "(", ")", ")", "\n", "}" ]
// GetObjUID returns the object's namespace and name.
[ "GetObjUID", "returns", "the", "object", "s", "namespace", "and", "name", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/k8s/utils/utils.go#L38-L40
162,291
cilium/cilium
cilium/cmd/endpoint_labels.go
printEndpointLabels
func printEndpointLabels(lbls *labels.OpLabels) { log.WithField(logfields.Labels, logfields.Repr(*lbls)).Debug("All Labels") w := tabwriter.NewWriter(os.Stdout, 2, 0, 3, ' ', 0) for _, v := range lbls.IdentityLabels() { text := color.Green("Enabled") fmt.Fprintf(w, "%s\t%s\n", v, text) } for _, v := range lbls.Disabled { text := color.Red("Disabled") fmt.Fprintf(w, "%s\t%s\n", v, text) } w.Flush() }
go
func printEndpointLabels(lbls *labels.OpLabels) { log.WithField(logfields.Labels, logfields.Repr(*lbls)).Debug("All Labels") w := tabwriter.NewWriter(os.Stdout, 2, 0, 3, ' ', 0) for _, v := range lbls.IdentityLabels() { text := color.Green("Enabled") fmt.Fprintf(w, "%s\t%s\n", v, text) } for _, v := range lbls.Disabled { text := color.Red("Disabled") fmt.Fprintf(w, "%s\t%s\n", v, text) } w.Flush() }
[ "func", "printEndpointLabels", "(", "lbls", "*", "labels", ".", "OpLabels", ")", "{", "log", ".", "WithField", "(", "logfields", ".", "Labels", ",", "logfields", ".", "Repr", "(", "*", "lbls", ")", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "w", ":=", "tabwriter", ".", "NewWriter", "(", "os", ".", "Stdout", ",", "2", ",", "0", ",", "3", ",", "' '", ",", "0", ")", "\n\n", "for", "_", ",", "v", ":=", "range", "lbls", ".", "IdentityLabels", "(", ")", "{", "text", ":=", "color", ".", "Green", "(", "\"", "\"", ")", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\t", "\\n", "\"", ",", "v", ",", "text", ")", "\n", "}", "\n\n", "for", "_", ",", "v", ":=", "range", "lbls", ".", "Disabled", "{", "text", ":=", "color", ".", "Red", "(", "\"", "\"", ")", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\t", "\\n", "\"", ",", "v", ",", "text", ")", "\n", "}", "\n", "w", ".", "Flush", "(", ")", "\n", "}" ]
// printEndpointLabels pretty prints labels with tabs
[ "printEndpointLabels", "pretty", "prints", "labels", "with", "tabs" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/cilium/cmd/endpoint_labels.go#L72-L86
162,292
cilium/cilium
daemon/loadbalancer.go
SVCAdd
func (d *Daemon) SVCAdd(feL3n4Addr loadbalancer.L3n4AddrID, be []loadbalancer.LBBackEnd, addRevNAT bool) (bool, error) { log.WithField(logfields.ServiceID, feL3n4Addr.String()).Debug("adding service") if feL3n4Addr.ID == 0 { return false, fmt.Errorf("invalid service ID 0") } // Check if the service is already registered with this ID. feAddr, err := service.GetID(uint32(feL3n4Addr.ID)) if err != nil { return false, fmt.Errorf("unable to get service %d: %s", feL3n4Addr.ID, err) } if feAddr == nil { feAddr, err = service.AcquireID(feL3n4Addr.L3n4Addr, uint32(feL3n4Addr.ID)) if err != nil { return false, fmt.Errorf("unable to store service %s in kvstore: %s", feL3n4Addr.String(), err) } // This won't be atomic so we need to check if the baseID, feL3n4Addr.ID was given to the service if feAddr.ID != feL3n4Addr.ID { return false, fmt.Errorf("the service provided %s is already registered with ID %d, please use that ID instead of %d", feL3n4Addr.L3n4Addr.String(), feAddr.ID, feL3n4Addr.ID) } } feAddr256Sum := feAddr.L3n4Addr.SHA256Sum() feL3n4Addr256Sum := feL3n4Addr.L3n4Addr.SHA256Sum() if feAddr256Sum != feL3n4Addr256Sum { return false, fmt.Errorf("service ID %d is already registered to L3n4Addr %s, please choose a different ID", feL3n4Addr.ID, feAddr.String()) } return d.svcAdd(feL3n4Addr, be, addRevNAT) }
go
func (d *Daemon) SVCAdd(feL3n4Addr loadbalancer.L3n4AddrID, be []loadbalancer.LBBackEnd, addRevNAT bool) (bool, error) { log.WithField(logfields.ServiceID, feL3n4Addr.String()).Debug("adding service") if feL3n4Addr.ID == 0 { return false, fmt.Errorf("invalid service ID 0") } // Check if the service is already registered with this ID. feAddr, err := service.GetID(uint32(feL3n4Addr.ID)) if err != nil { return false, fmt.Errorf("unable to get service %d: %s", feL3n4Addr.ID, err) } if feAddr == nil { feAddr, err = service.AcquireID(feL3n4Addr.L3n4Addr, uint32(feL3n4Addr.ID)) if err != nil { return false, fmt.Errorf("unable to store service %s in kvstore: %s", feL3n4Addr.String(), err) } // This won't be atomic so we need to check if the baseID, feL3n4Addr.ID was given to the service if feAddr.ID != feL3n4Addr.ID { return false, fmt.Errorf("the service provided %s is already registered with ID %d, please use that ID instead of %d", feL3n4Addr.L3n4Addr.String(), feAddr.ID, feL3n4Addr.ID) } } feAddr256Sum := feAddr.L3n4Addr.SHA256Sum() feL3n4Addr256Sum := feL3n4Addr.L3n4Addr.SHA256Sum() if feAddr256Sum != feL3n4Addr256Sum { return false, fmt.Errorf("service ID %d is already registered to L3n4Addr %s, please choose a different ID", feL3n4Addr.ID, feAddr.String()) } return d.svcAdd(feL3n4Addr, be, addRevNAT) }
[ "func", "(", "d", "*", "Daemon", ")", "SVCAdd", "(", "feL3n4Addr", "loadbalancer", ".", "L3n4AddrID", ",", "be", "[", "]", "loadbalancer", ".", "LBBackEnd", ",", "addRevNAT", "bool", ")", "(", "bool", ",", "error", ")", "{", "log", ".", "WithField", "(", "logfields", ".", "ServiceID", ",", "feL3n4Addr", ".", "String", "(", ")", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "if", "feL3n4Addr", ".", "ID", "==", "0", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "// Check if the service is already registered with this ID.", "feAddr", ",", "err", ":=", "service", ".", "GetID", "(", "uint32", "(", "feL3n4Addr", ".", "ID", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "feL3n4Addr", ".", "ID", ",", "err", ")", "\n", "}", "\n", "if", "feAddr", "==", "nil", "{", "feAddr", ",", "err", "=", "service", ".", "AcquireID", "(", "feL3n4Addr", ".", "L3n4Addr", ",", "uint32", "(", "feL3n4Addr", ".", "ID", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "feL3n4Addr", ".", "String", "(", ")", ",", "err", ")", "\n", "}", "\n", "// This won't be atomic so we need to check if the baseID, feL3n4Addr.ID was given to the service", "if", "feAddr", ".", "ID", "!=", "feL3n4Addr", ".", "ID", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "feL3n4Addr", ".", "L3n4Addr", ".", "String", "(", ")", ",", "feAddr", ".", "ID", ",", "feL3n4Addr", ".", "ID", ")", "\n", "}", "\n", "}", "\n\n", "feAddr256Sum", ":=", "feAddr", ".", "L3n4Addr", ".", "SHA256Sum", "(", ")", "\n", "feL3n4Addr256Sum", ":=", "feL3n4Addr", ".", "L3n4Addr", ".", "SHA256Sum", "(", ")", "\n\n", "if", "feAddr256Sum", "!=", "feL3n4Addr256Sum", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "feL3n4Addr", ".", "ID", ",", "feAddr", ".", "String", "(", ")", ")", "\n", "}", "\n\n", "return", "d", ".", "svcAdd", "(", "feL3n4Addr", ",", "be", ",", "addRevNAT", ")", "\n", "}" ]
// SVCAdd is the public method to add services. We assume the ID provided is not in // sync with the KVStore. If that's the, case the service won't be used and an error is // returned to the caller. // // Returns true if service was created.
[ "SVCAdd", "is", "the", "public", "method", "to", "add", "services", ".", "We", "assume", "the", "ID", "provided", "is", "not", "in", "sync", "with", "the", "KVStore", ".", "If", "that", "s", "the", "case", "the", "service", "won", "t", "be", "used", "and", "an", "error", "is", "returned", "to", "the", "caller", ".", "Returns", "true", "if", "service", "was", "created", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/daemon/loadbalancer.go#L64-L93
162,293
cilium/cilium
daemon/loadbalancer.go
svcDeleteByFrontend
func (d *Daemon) svcDeleteByFrontend(frontend *loadbalancer.L3n4Addr) error { d.loadBalancer.BPFMapMU.Lock() defer d.loadBalancer.BPFMapMU.Unlock() return d.svcDeleteByFrontendLocked(frontend) }
go
func (d *Daemon) svcDeleteByFrontend(frontend *loadbalancer.L3n4Addr) error { d.loadBalancer.BPFMapMU.Lock() defer d.loadBalancer.BPFMapMU.Unlock() return d.svcDeleteByFrontendLocked(frontend) }
[ "func", "(", "d", "*", "Daemon", ")", "svcDeleteByFrontend", "(", "frontend", "*", "loadbalancer", ".", "L3n4Addr", ")", "error", "{", "d", ".", "loadBalancer", ".", "BPFMapMU", ".", "Lock", "(", ")", "\n", "defer", "d", ".", "loadBalancer", ".", "BPFMapMU", ".", "Unlock", "(", ")", "\n\n", "return", "d", ".", "svcDeleteByFrontendLocked", "(", "frontend", ")", "\n", "}" ]
// Deletes a service by the frontend address
[ "Deletes", "a", "service", "by", "the", "frontend", "address" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/daemon/loadbalancer.go#L249-L254
162,294
cilium/cilium
daemon/loadbalancer.go
svcGetBySHA256Sum
func (d *Daemon) svcGetBySHA256Sum(feL3n4SHA256Sum string) *loadbalancer.LBSVC { d.loadBalancer.BPFMapMU.RLock() defer d.loadBalancer.BPFMapMU.RUnlock() v, ok := d.loadBalancer.SVCMap[feL3n4SHA256Sum] if !ok { return nil } // We will move the slice from the loadbalancer map which has a mutex. If // we don't copy the slice we might risk changing memory that should be // locked. beCpy := []loadbalancer.LBBackEnd{} for _, v := range v.BES { beCpy = append(beCpy, v) } return &loadbalancer.LBSVC{ FE: *v.FE.DeepCopy(), BES: beCpy, } }
go
func (d *Daemon) svcGetBySHA256Sum(feL3n4SHA256Sum string) *loadbalancer.LBSVC { d.loadBalancer.BPFMapMU.RLock() defer d.loadBalancer.BPFMapMU.RUnlock() v, ok := d.loadBalancer.SVCMap[feL3n4SHA256Sum] if !ok { return nil } // We will move the slice from the loadbalancer map which has a mutex. If // we don't copy the slice we might risk changing memory that should be // locked. beCpy := []loadbalancer.LBBackEnd{} for _, v := range v.BES { beCpy = append(beCpy, v) } return &loadbalancer.LBSVC{ FE: *v.FE.DeepCopy(), BES: beCpy, } }
[ "func", "(", "d", "*", "Daemon", ")", "svcGetBySHA256Sum", "(", "feL3n4SHA256Sum", "string", ")", "*", "loadbalancer", ".", "LBSVC", "{", "d", ".", "loadBalancer", ".", "BPFMapMU", ".", "RLock", "(", ")", "\n", "defer", "d", ".", "loadBalancer", ".", "BPFMapMU", ".", "RUnlock", "(", ")", "\n\n", "v", ",", "ok", ":=", "d", ".", "loadBalancer", ".", "SVCMap", "[", "feL3n4SHA256Sum", "]", "\n", "if", "!", "ok", "{", "return", "nil", "\n", "}", "\n", "// We will move the slice from the loadbalancer map which has a mutex. If", "// we don't copy the slice we might risk changing memory that should be", "// locked.", "beCpy", ":=", "[", "]", "loadbalancer", ".", "LBBackEnd", "{", "}", "\n", "for", "_", ",", "v", ":=", "range", "v", ".", "BES", "{", "beCpy", "=", "append", "(", "beCpy", ",", "v", ")", "\n", "}", "\n", "return", "&", "loadbalancer", ".", "LBSVC", "{", "FE", ":", "*", "v", ".", "FE", ".", "DeepCopy", "(", ")", ",", "BES", ":", "beCpy", ",", "}", "\n", "}" ]
// SVCGetBySHA256Sum returns a DeepCopied frontend with its backends.
[ "SVCGetBySHA256Sum", "returns", "a", "DeepCopied", "frontend", "with", "its", "backends", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/daemon/loadbalancer.go#L356-L375
162,295
cilium/cilium
daemon/loadbalancer.go
RevNATAdd
func (d *Daemon) RevNATAdd(id loadbalancer.ServiceID, revNAT loadbalancer.L3n4Addr) error { revNATK, revNATV := lbmap.L3n4Addr2RevNatKeynValue(id, revNAT) d.loadBalancer.BPFMapMU.Lock() defer d.loadBalancer.BPFMapMU.Unlock() err := lbmap.UpdateRevNat(revNATK, revNATV) if err != nil { return err } d.loadBalancer.RevNATMap[id] = *revNAT.DeepCopy() return nil }
go
func (d *Daemon) RevNATAdd(id loadbalancer.ServiceID, revNAT loadbalancer.L3n4Addr) error { revNATK, revNATV := lbmap.L3n4Addr2RevNatKeynValue(id, revNAT) d.loadBalancer.BPFMapMU.Lock() defer d.loadBalancer.BPFMapMU.Unlock() err := lbmap.UpdateRevNat(revNATK, revNATV) if err != nil { return err } d.loadBalancer.RevNATMap[id] = *revNAT.DeepCopy() return nil }
[ "func", "(", "d", "*", "Daemon", ")", "RevNATAdd", "(", "id", "loadbalancer", ".", "ServiceID", ",", "revNAT", "loadbalancer", ".", "L3n4Addr", ")", "error", "{", "revNATK", ",", "revNATV", ":=", "lbmap", ".", "L3n4Addr2RevNatKeynValue", "(", "id", ",", "revNAT", ")", "\n\n", "d", ".", "loadBalancer", ".", "BPFMapMU", ".", "Lock", "(", ")", "\n", "defer", "d", ".", "loadBalancer", ".", "BPFMapMU", ".", "Unlock", "(", ")", "\n\n", "err", ":=", "lbmap", ".", "UpdateRevNat", "(", "revNATK", ",", "revNATV", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "d", ".", "loadBalancer", ".", "RevNATMap", "[", "id", "]", "=", "*", "revNAT", ".", "DeepCopy", "(", ")", "\n", "return", "nil", "\n", "}" ]
// RevNATAdd deep copies the given revNAT address to the cilium lbmap with the given id.
[ "RevNATAdd", "deep", "copies", "the", "given", "revNAT", "address", "to", "the", "cilium", "lbmap", "with", "the", "given", "id", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/daemon/loadbalancer.go#L392-L405
162,296
cilium/cilium
daemon/loadbalancer.go
RevNATDelete
func (d *Daemon) RevNATDelete(id loadbalancer.ServiceID) error { d.loadBalancer.BPFMapMU.Lock() defer d.loadBalancer.BPFMapMU.Unlock() revNAT, ok := d.loadBalancer.RevNATMap[id] if !ok { return nil } err := lbmap.DeleteRevNATBPF(id, revNAT.IsIPv6()) // TODO should we delete even if err is != nil? if err == nil { delete(d.loadBalancer.RevNATMap, id) } return err }
go
func (d *Daemon) RevNATDelete(id loadbalancer.ServiceID) error { d.loadBalancer.BPFMapMU.Lock() defer d.loadBalancer.BPFMapMU.Unlock() revNAT, ok := d.loadBalancer.RevNATMap[id] if !ok { return nil } err := lbmap.DeleteRevNATBPF(id, revNAT.IsIPv6()) // TODO should we delete even if err is != nil? if err == nil { delete(d.loadBalancer.RevNATMap, id) } return err }
[ "func", "(", "d", "*", "Daemon", ")", "RevNATDelete", "(", "id", "loadbalancer", ".", "ServiceID", ")", "error", "{", "d", ".", "loadBalancer", ".", "BPFMapMU", ".", "Lock", "(", ")", "\n", "defer", "d", ".", "loadBalancer", ".", "BPFMapMU", ".", "Unlock", "(", ")", "\n\n", "revNAT", ",", "ok", ":=", "d", ".", "loadBalancer", ".", "RevNATMap", "[", "id", "]", "\n", "if", "!", "ok", "{", "return", "nil", "\n", "}", "\n\n", "err", ":=", "lbmap", ".", "DeleteRevNATBPF", "(", "id", ",", "revNAT", ".", "IsIPv6", "(", ")", ")", "\n\n", "// TODO should we delete even if err is != nil?", "if", "err", "==", "nil", "{", "delete", "(", "d", ".", "loadBalancer", ".", "RevNATMap", ",", "id", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// RevNATDelete deletes the revNatKey from the local bpf map.
[ "RevNATDelete", "deletes", "the", "revNatKey", "from", "the", "local", "bpf", "map", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/daemon/loadbalancer.go#L408-L424
162,297
cilium/cilium
daemon/loadbalancer.go
RevNATDeleteAll
func (d *Daemon) RevNATDeleteAll() error { if option.Config.EnableIPv4 { if err := lbmap.RevNat4Map.DeleteAll(); err != nil { return err } } if option.Config.EnableIPv6 { if err := lbmap.RevNat6Map.DeleteAll(); err != nil { return err } } // TODO should we delete even if err is != nil? d.loadBalancer.RevNATMap = map[loadbalancer.ServiceID]loadbalancer.L3n4Addr{} return nil }
go
func (d *Daemon) RevNATDeleteAll() error { if option.Config.EnableIPv4 { if err := lbmap.RevNat4Map.DeleteAll(); err != nil { return err } } if option.Config.EnableIPv6 { if err := lbmap.RevNat6Map.DeleteAll(); err != nil { return err } } // TODO should we delete even if err is != nil? d.loadBalancer.RevNATMap = map[loadbalancer.ServiceID]loadbalancer.L3n4Addr{} return nil }
[ "func", "(", "d", "*", "Daemon", ")", "RevNATDeleteAll", "(", ")", "error", "{", "if", "option", ".", "Config", ".", "EnableIPv4", "{", "if", "err", ":=", "lbmap", ".", "RevNat4Map", ".", "DeleteAll", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "if", "option", ".", "Config", ".", "EnableIPv6", "{", "if", "err", ":=", "lbmap", ".", "RevNat6Map", ".", "DeleteAll", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "// TODO should we delete even if err is != nil?", "d", ".", "loadBalancer", ".", "RevNATMap", "=", "map", "[", "loadbalancer", ".", "ServiceID", "]", "loadbalancer", ".", "L3n4Addr", "{", "}", "\n", "return", "nil", "\n", "}" ]
// RevNATDeleteAll deletes all RevNAT4, if IPv4 is enabled on daemon, and all RevNAT6 // stored on the daemon and on the bpf maps. // // Must be called with d.loadBalancer.BPFMapMU locked.
[ "RevNATDeleteAll", "deletes", "all", "RevNAT4", "if", "IPv4", "is", "enabled", "on", "daemon", "and", "all", "RevNAT6", "stored", "on", "the", "daemon", "and", "on", "the", "bpf", "maps", ".", "Must", "be", "called", "with", "d", ".", "loadBalancer", ".", "BPFMapMU", "locked", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/daemon/loadbalancer.go#L430-L446
162,298
cilium/cilium
daemon/loadbalancer.go
RevNATGet
func (d *Daemon) RevNATGet(id loadbalancer.ServiceID) (*loadbalancer.L3n4Addr, error) { d.loadBalancer.BPFMapMU.RLock() defer d.loadBalancer.BPFMapMU.RUnlock() revNAT, ok := d.loadBalancer.RevNATMap[id] if !ok { return nil, nil } return revNAT.DeepCopy(), nil }
go
func (d *Daemon) RevNATGet(id loadbalancer.ServiceID) (*loadbalancer.L3n4Addr, error) { d.loadBalancer.BPFMapMU.RLock() defer d.loadBalancer.BPFMapMU.RUnlock() revNAT, ok := d.loadBalancer.RevNATMap[id] if !ok { return nil, nil } return revNAT.DeepCopy(), nil }
[ "func", "(", "d", "*", "Daemon", ")", "RevNATGet", "(", "id", "loadbalancer", ".", "ServiceID", ")", "(", "*", "loadbalancer", ".", "L3n4Addr", ",", "error", ")", "{", "d", ".", "loadBalancer", ".", "BPFMapMU", ".", "RLock", "(", ")", "\n", "defer", "d", ".", "loadBalancer", ".", "BPFMapMU", ".", "RUnlock", "(", ")", "\n\n", "revNAT", ",", "ok", ":=", "d", ".", "loadBalancer", ".", "RevNATMap", "[", "id", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "return", "revNAT", ".", "DeepCopy", "(", ")", ",", "nil", "\n", "}" ]
// RevNATGet returns a DeepCopy of the revNAT found with the given ID or nil if not found.
[ "RevNATGet", "returns", "a", "DeepCopy", "of", "the", "revNAT", "found", "with", "the", "given", "ID", "or", "nil", "if", "not", "found", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/daemon/loadbalancer.go#L449-L458
162,299
cilium/cilium
daemon/loadbalancer.go
RevNATDump
func (d *Daemon) RevNATDump() ([]loadbalancer.L3n4AddrID, error) { dump := []loadbalancer.L3n4AddrID{} d.loadBalancer.BPFMapMU.RLock() defer d.loadBalancer.BPFMapMU.RUnlock() for k, v := range d.loadBalancer.RevNATMap { dump = append(dump, loadbalancer.L3n4AddrID{ ID: loadbalancer.ID(k), L3n4Addr: *v.DeepCopy(), }) } return dump, nil }
go
func (d *Daemon) RevNATDump() ([]loadbalancer.L3n4AddrID, error) { dump := []loadbalancer.L3n4AddrID{} d.loadBalancer.BPFMapMU.RLock() defer d.loadBalancer.BPFMapMU.RUnlock() for k, v := range d.loadBalancer.RevNATMap { dump = append(dump, loadbalancer.L3n4AddrID{ ID: loadbalancer.ID(k), L3n4Addr: *v.DeepCopy(), }) } return dump, nil }
[ "func", "(", "d", "*", "Daemon", ")", "RevNATDump", "(", ")", "(", "[", "]", "loadbalancer", ".", "L3n4AddrID", ",", "error", ")", "{", "dump", ":=", "[", "]", "loadbalancer", ".", "L3n4AddrID", "{", "}", "\n\n", "d", ".", "loadBalancer", ".", "BPFMapMU", ".", "RLock", "(", ")", "\n", "defer", "d", ".", "loadBalancer", ".", "BPFMapMU", ".", "RUnlock", "(", ")", "\n\n", "for", "k", ",", "v", ":=", "range", "d", ".", "loadBalancer", ".", "RevNATMap", "{", "dump", "=", "append", "(", "dump", ",", "loadbalancer", ".", "L3n4AddrID", "{", "ID", ":", "loadbalancer", ".", "ID", "(", "k", ")", ",", "L3n4Addr", ":", "*", "v", ".", "DeepCopy", "(", ")", ",", "}", ")", "\n", "}", "\n\n", "return", "dump", ",", "nil", "\n", "}" ]
// RevNATDump dumps a DeepCopy of the cilium's loadbalancer.
[ "RevNATDump", "dumps", "a", "DeepCopy", "of", "the", "cilium", "s", "loadbalancer", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/daemon/loadbalancer.go#L461-L475