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,800
cilium/cilium
pkg/kafka/correlation_cache.go
HandleRequest
func (cc *CorrelationCache) HandleRequest(req *RequestMessage, finishFunc FinishFunc) { cc.mutex.Lock() defer cc.mutex.Unlock() // save the original correlation ID origCorrelationID := req.GetCorrelationID() // Use a sequence number to generate a correlation ID that is // guaranteed to be unique newCorrelationID := cc.nextSequenceNumber cc.nextSequenceNumber++ // Overwrite the correlation ID in the request to allow correlating the // response later on. The original correlation ID will be restored when // forwarding the response req.SetCorrelationID(newCorrelationID) if _, ok := cc.cache[newCorrelationID]; ok { log.Warning("BUG: Overwriting Kafka request message in correlation cache") } cc.cache[newCorrelationID] = &correlationEntry{ request: req, created: time.Now(), origCorrelationID: origCorrelationID, finishFunc: finishFunc, } }
go
func (cc *CorrelationCache) HandleRequest(req *RequestMessage, finishFunc FinishFunc) { cc.mutex.Lock() defer cc.mutex.Unlock() // save the original correlation ID origCorrelationID := req.GetCorrelationID() // Use a sequence number to generate a correlation ID that is // guaranteed to be unique newCorrelationID := cc.nextSequenceNumber cc.nextSequenceNumber++ // Overwrite the correlation ID in the request to allow correlating the // response later on. The original correlation ID will be restored when // forwarding the response req.SetCorrelationID(newCorrelationID) if _, ok := cc.cache[newCorrelationID]; ok { log.Warning("BUG: Overwriting Kafka request message in correlation cache") } cc.cache[newCorrelationID] = &correlationEntry{ request: req, created: time.Now(), origCorrelationID: origCorrelationID, finishFunc: finishFunc, } }
[ "func", "(", "cc", "*", "CorrelationCache", ")", "HandleRequest", "(", "req", "*", "RequestMessage", ",", "finishFunc", "FinishFunc", ")", "{", "cc", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "cc", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "// save the original correlation ID", "origCorrelationID", ":=", "req", ".", "GetCorrelationID", "(", ")", "\n\n", "// Use a sequence number to generate a correlation ID that is", "// guaranteed to be unique", "newCorrelationID", ":=", "cc", ".", "nextSequenceNumber", "\n", "cc", ".", "nextSequenceNumber", "++", "\n\n", "// Overwrite the correlation ID in the request to allow correlating the", "// response later on. The original correlation ID will be restored when", "// forwarding the response", "req", ".", "SetCorrelationID", "(", "newCorrelationID", ")", "\n\n", "if", "_", ",", "ok", ":=", "cc", ".", "cache", "[", "newCorrelationID", "]", ";", "ok", "{", "log", ".", "Warning", "(", "\"", "\"", ")", "\n", "}", "\n\n", "cc", ".", "cache", "[", "newCorrelationID", "]", "=", "&", "correlationEntry", "{", "request", ":", "req", ",", "created", ":", "time", ".", "Now", "(", ")", ",", "origCorrelationID", ":", "origCorrelationID", ",", "finishFunc", ":", "finishFunc", ",", "}", "\n", "}" ]
// HandleRequest must be called when a request is forwarded to the broker, will // keep track of the request and rewrite the correlation ID inside of the // request to a sequence number. This sequence number is guaranteed to be // unique within the connection covered by the cache.
[ "HandleRequest", "must", "be", "called", "when", "a", "request", "is", "forwarded", "to", "the", "broker", "will", "keep", "track", "of", "the", "request", "and", "rewrite", "the", "correlation", "ID", "inside", "of", "the", "request", "to", "a", "sequence", "number", ".", "This", "sequence", "number", "is", "guaranteed", "to", "be", "unique", "within", "the", "connection", "covered", "by", "the", "cache", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/kafka/correlation_cache.go#L120-L147
162,801
cilium/cilium
pkg/kafka/correlation_cache.go
correlate
func (cc *CorrelationCache) correlate(id CorrelationID) *correlationEntry { cc.mutex.RLock() defer cc.mutex.RUnlock() entry, _ := cc.cache[id] return entry }
go
func (cc *CorrelationCache) correlate(id CorrelationID) *correlationEntry { cc.mutex.RLock() defer cc.mutex.RUnlock() entry, _ := cc.cache[id] return entry }
[ "func", "(", "cc", "*", "CorrelationCache", ")", "correlate", "(", "id", "CorrelationID", ")", "*", "correlationEntry", "{", "cc", ".", "mutex", ".", "RLock", "(", ")", "\n", "defer", "cc", ".", "mutex", ".", "RUnlock", "(", ")", "\n\n", "entry", ",", "_", ":=", "cc", ".", "cache", "[", "id", "]", "\n", "return", "entry", "\n", "}" ]
// correlate returns the request message with the matching correlation ID
[ "correlate", "returns", "the", "request", "message", "with", "the", "matching", "correlation", "ID" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/kafka/correlation_cache.go#L150-L156
162,802
cilium/cilium
pkg/kafka/correlation_cache.go
CorrelateResponse
func (cc *CorrelationCache) CorrelateResponse(res *ResponseMessage) *RequestMessage { cc.mutex.Lock() defer cc.mutex.Unlock() correlationID := res.GetCorrelationID() if entry := cc.cache[correlationID]; entry != nil { res.SetCorrelationID(entry.origCorrelationID) if entry.finishFunc != nil { entry.finishFunc(entry.request) } delete(cc.cache, correlationID) return entry.request } return nil }
go
func (cc *CorrelationCache) CorrelateResponse(res *ResponseMessage) *RequestMessage { cc.mutex.Lock() defer cc.mutex.Unlock() correlationID := res.GetCorrelationID() if entry := cc.cache[correlationID]; entry != nil { res.SetCorrelationID(entry.origCorrelationID) if entry.finishFunc != nil { entry.finishFunc(entry.request) } delete(cc.cache, correlationID) return entry.request } return nil }
[ "func", "(", "cc", "*", "CorrelationCache", ")", "CorrelateResponse", "(", "res", "*", "ResponseMessage", ")", "*", "RequestMessage", "{", "cc", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "cc", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "correlationID", ":=", "res", ".", "GetCorrelationID", "(", ")", "\n", "if", "entry", ":=", "cc", ".", "cache", "[", "correlationID", "]", ";", "entry", "!=", "nil", "{", "res", ".", "SetCorrelationID", "(", "entry", ".", "origCorrelationID", ")", "\n\n", "if", "entry", ".", "finishFunc", "!=", "nil", "{", "entry", ".", "finishFunc", "(", "entry", ".", "request", ")", "\n", "}", "\n\n", "delete", "(", "cc", ".", "cache", ",", "correlationID", ")", "\n", "return", "entry", ".", "request", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// CorrelateResponse extracts the correlation ID from the response message, // correlates the corresponding request, restores the original correlation ID // in the response and returns the original request
[ "CorrelateResponse", "extracts", "the", "correlation", "ID", "from", "the", "response", "message", "correlates", "the", "corresponding", "request", "restores", "the", "original", "correlation", "ID", "in", "the", "response", "and", "returns", "the", "original", "request" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/kafka/correlation_cache.go#L161-L178
162,803
cilium/cilium
pkg/option/map_options.go
NewNamedMapOptions
func NewNamedMapOptions(name string, values *map[string]string, validator Validator) *NamedMapOptions { return &NamedMapOptions{ name: name, MapOptions: *NewMapOpts(*values, validator), } }
go
func NewNamedMapOptions(name string, values *map[string]string, validator Validator) *NamedMapOptions { return &NamedMapOptions{ name: name, MapOptions: *NewMapOpts(*values, validator), } }
[ "func", "NewNamedMapOptions", "(", "name", "string", ",", "values", "*", "map", "[", "string", "]", "string", ",", "validator", "Validator", ")", "*", "NamedMapOptions", "{", "return", "&", "NamedMapOptions", "{", "name", ":", "name", ",", "MapOptions", ":", "*", "NewMapOpts", "(", "*", "values", ",", "validator", ")", ",", "}", "\n", "}" ]
// NewNamedMapOptions creates a reference to a new NamedMapOpts struct.
[ "NewNamedMapOptions", "creates", "a", "reference", "to", "a", "new", "NamedMapOpts", "struct", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/option/map_options.go#L40-L45
162,804
cilium/cilium
pkg/option/map_options.go
NewMapOpts
func NewMapOpts(values map[string]string, validator Validator) *MapOptions { if values == nil { values = make(map[string]string) } return &MapOptions{ vals: values, validator: validator, } }
go
func NewMapOpts(values map[string]string, validator Validator) *MapOptions { if values == nil { values = make(map[string]string) } return &MapOptions{ vals: values, validator: validator, } }
[ "func", "NewMapOpts", "(", "values", "map", "[", "string", "]", "string", ",", "validator", "Validator", ")", "*", "MapOptions", "{", "if", "values", "==", "nil", "{", "values", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "}", "\n", "return", "&", "MapOptions", "{", "vals", ":", "values", ",", "validator", ":", "validator", ",", "}", "\n", "}" ]
// NewMapOpts creates a new MapOpts with the specified map of values and an // optional validator.
[ "NewMapOpts", "creates", "a", "new", "MapOpts", "with", "the", "specified", "map", "of", "values", "and", "an", "optional", "validator", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/option/map_options.go#L49-L57
162,805
cilium/cilium
pkg/option/map_options.go
Set
func (opts *MapOptions) Set(value string) error { if opts.validator != nil { v, err := opts.validator(value) if err != nil { return err } value = v } vals := strings.SplitN(value, "=", 2) if len(vals) == 1 { (opts.vals)[vals[0]] = "" } else { (opts.vals)[vals[0]] = vals[1] } return nil }
go
func (opts *MapOptions) Set(value string) error { if opts.validator != nil { v, err := opts.validator(value) if err != nil { return err } value = v } vals := strings.SplitN(value, "=", 2) if len(vals) == 1 { (opts.vals)[vals[0]] = "" } else { (opts.vals)[vals[0]] = vals[1] } return nil }
[ "func", "(", "opts", "*", "MapOptions", ")", "Set", "(", "value", "string", ")", "error", "{", "if", "opts", ".", "validator", "!=", "nil", "{", "v", ",", "err", ":=", "opts", ".", "validator", "(", "value", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "value", "=", "v", "\n", "}", "\n", "vals", ":=", "strings", ".", "SplitN", "(", "value", ",", "\"", "\"", ",", "2", ")", "\n", "if", "len", "(", "vals", ")", "==", "1", "{", "(", "opts", ".", "vals", ")", "[", "vals", "[", "0", "]", "]", "=", "\"", "\"", "\n", "}", "else", "{", "(", "opts", ".", "vals", ")", "[", "vals", "[", "0", "]", "]", "=", "vals", "[", "1", "]", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Set validates, if needed, the input value and adds it to the internal map, // by splitting on '='.
[ "Set", "validates", "if", "needed", "the", "input", "value", "and", "adds", "it", "to", "the", "internal", "map", "by", "splitting", "on", "=", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/option/map_options.go#L70-L85
162,806
cilium/cilium
api/v1/server/restapi/endpoint/get_endpoint_responses.go
WithPayload
func (o *GetEndpointOK) WithPayload(payload []*models.Endpoint) *GetEndpointOK { o.Payload = payload return o }
go
func (o *GetEndpointOK) WithPayload(payload []*models.Endpoint) *GetEndpointOK { o.Payload = payload return o }
[ "func", "(", "o", "*", "GetEndpointOK", ")", "WithPayload", "(", "payload", "[", "]", "*", "models", ".", "Endpoint", ")", "*", "GetEndpointOK", "{", "o", ".", "Payload", "=", "payload", "\n", "return", "o", "\n", "}" ]
// WithPayload adds the payload to the get endpoint o k response
[ "WithPayload", "adds", "the", "payload", "to", "the", "get", "endpoint", "o", "k", "response" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/api/v1/server/restapi/endpoint/get_endpoint_responses.go#L38-L41
162,807
cilium/cilium
pkg/option/monitor.go
ParseMonitorAggregationLevel
func ParseMonitorAggregationLevel(value string) (OptionSetting, error) { // First, attempt the string representation. if level, ok := monitorAggregationOption[strings.ToLower(value)]; ok { return level, nil } // If it's not a valid string option, attempt to parse an integer. valueParsed, err := strconv.Atoi(value) if err != nil { err = fmt.Errorf("Invalid monitor aggregation level %q", value) return MonitorAggregationLevelNone, err } parsed := OptionSetting(valueParsed) if parsed < MonitorAggregationLevelNone || parsed > MonitorAggregationLevelMax { err = fmt.Errorf("Monitor aggregation level must be between %d and %d", MonitorAggregationLevelNone, MonitorAggregationLevelMax) return MonitorAggregationLevelNone, err } return parsed, nil }
go
func ParseMonitorAggregationLevel(value string) (OptionSetting, error) { // First, attempt the string representation. if level, ok := monitorAggregationOption[strings.ToLower(value)]; ok { return level, nil } // If it's not a valid string option, attempt to parse an integer. valueParsed, err := strconv.Atoi(value) if err != nil { err = fmt.Errorf("Invalid monitor aggregation level %q", value) return MonitorAggregationLevelNone, err } parsed := OptionSetting(valueParsed) if parsed < MonitorAggregationLevelNone || parsed > MonitorAggregationLevelMax { err = fmt.Errorf("Monitor aggregation level must be between %d and %d", MonitorAggregationLevelNone, MonitorAggregationLevelMax) return MonitorAggregationLevelNone, err } return parsed, nil }
[ "func", "ParseMonitorAggregationLevel", "(", "value", "string", ")", "(", "OptionSetting", ",", "error", ")", "{", "// First, attempt the string representation.", "if", "level", ",", "ok", ":=", "monitorAggregationOption", "[", "strings", ".", "ToLower", "(", "value", ")", "]", ";", "ok", "{", "return", "level", ",", "nil", "\n", "}", "\n\n", "// If it's not a valid string option, attempt to parse an integer.", "valueParsed", ",", "err", ":=", "strconv", ".", "Atoi", "(", "value", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "value", ")", "\n", "return", "MonitorAggregationLevelNone", ",", "err", "\n", "}", "\n", "parsed", ":=", "OptionSetting", "(", "valueParsed", ")", "\n", "if", "parsed", "<", "MonitorAggregationLevelNone", "||", "parsed", ">", "MonitorAggregationLevelMax", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "MonitorAggregationLevelNone", ",", "MonitorAggregationLevelMax", ")", "\n", "return", "MonitorAggregationLevelNone", ",", "err", "\n", "}", "\n", "return", "parsed", ",", "nil", "\n", "}" ]
// ParseMonitorAggregationLevel turns a string into a monitor aggregation // level. The string may contain an integer value or a string representation of // a particular monitor aggregation level.
[ "ParseMonitorAggregationLevel", "turns", "a", "string", "into", "a", "monitor", "aggregation", "level", ".", "The", "string", "may", "contain", "an", "integer", "value", "or", "a", "string", "representation", "of", "a", "particular", "monitor", "aggregation", "level", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/option/monitor.go#L96-L115
162,808
cilium/cilium
api/v1/server/restapi/daemon/patch_config_responses.go
WithPayload
func (o *PatchConfigBadRequest) WithPayload(payload models.Error) *PatchConfigBadRequest { o.Payload = payload return o }
go
func (o *PatchConfigBadRequest) WithPayload(payload models.Error) *PatchConfigBadRequest { o.Payload = payload return o }
[ "func", "(", "o", "*", "PatchConfigBadRequest", ")", "WithPayload", "(", "payload", "models", ".", "Error", ")", "*", "PatchConfigBadRequest", "{", "o", ".", "Payload", "=", "payload", "\n", "return", "o", "\n", "}" ]
// WithPayload adds the payload to the patch config bad request response
[ "WithPayload", "adds", "the", "payload", "to", "the", "patch", "config", "bad", "request", "response" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/api/v1/server/restapi/daemon/patch_config_responses.go#L62-L65
162,809
cilium/cilium
api/v1/server/restapi/daemon/patch_config_responses.go
WithPayload
func (o *PatchConfigFailure) WithPayload(payload models.Error) *PatchConfigFailure { o.Payload = payload return o }
go
func (o *PatchConfigFailure) WithPayload(payload models.Error) *PatchConfigFailure { o.Payload = payload return o }
[ "func", "(", "o", "*", "PatchConfigFailure", ")", "WithPayload", "(", "payload", "models", ".", "Error", ")", "*", "PatchConfigFailure", "{", "o", ".", "Payload", "=", "payload", "\n", "return", "o", "\n", "}" ]
// WithPayload adds the payload to the patch config failure response
[ "WithPayload", "adds", "the", "payload", "to", "the", "patch", "config", "failure", "response" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/api/v1/server/restapi/daemon/patch_config_responses.go#L104-L107
162,810
cilium/cilium
pkg/client/config.go
ConfigGet
func (c *Client) ConfigGet() (*models.DaemonConfiguration, error) { resp, err := c.Daemon.GetConfig(nil) if err != nil { return nil, Hint(err) } return resp.Payload, nil }
go
func (c *Client) ConfigGet() (*models.DaemonConfiguration, error) { resp, err := c.Daemon.GetConfig(nil) if err != nil { return nil, Hint(err) } return resp.Payload, nil }
[ "func", "(", "c", "*", "Client", ")", "ConfigGet", "(", ")", "(", "*", "models", ".", "DaemonConfiguration", ",", "error", ")", "{", "resp", ",", "err", ":=", "c", ".", "Daemon", ".", "GetConfig", "(", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "Hint", "(", "err", ")", "\n", "}", "\n", "return", "resp", ".", "Payload", ",", "nil", "\n", "}" ]
// ConfigGet returns a daemon configuration.
[ "ConfigGet", "returns", "a", "daemon", "configuration", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/client/config.go#L24-L30
162,811
cilium/cilium
pkg/client/config.go
ConfigPatch
func (c *Client) ConfigPatch(cfg models.DaemonConfigurationSpec) error { fullCfg, err := c.ConfigGet() if err != nil { return err } for opt, value := range cfg.Options { fullCfg.Spec.Options[opt] = value } if cfg.PolicyEnforcement != "" { fullCfg.Spec.PolicyEnforcement = cfg.PolicyEnforcement } params := daemon.NewPatchConfigParams().WithConfiguration(fullCfg.Spec).WithTimeout(api.ClientTimeout) _, err = c.Daemon.PatchConfig(params) return Hint(err) }
go
func (c *Client) ConfigPatch(cfg models.DaemonConfigurationSpec) error { fullCfg, err := c.ConfigGet() if err != nil { return err } for opt, value := range cfg.Options { fullCfg.Spec.Options[opt] = value } if cfg.PolicyEnforcement != "" { fullCfg.Spec.PolicyEnforcement = cfg.PolicyEnforcement } params := daemon.NewPatchConfigParams().WithConfiguration(fullCfg.Spec).WithTimeout(api.ClientTimeout) _, err = c.Daemon.PatchConfig(params) return Hint(err) }
[ "func", "(", "c", "*", "Client", ")", "ConfigPatch", "(", "cfg", "models", ".", "DaemonConfigurationSpec", ")", "error", "{", "fullCfg", ",", "err", ":=", "c", ".", "ConfigGet", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "for", "opt", ",", "value", ":=", "range", "cfg", ".", "Options", "{", "fullCfg", ".", "Spec", ".", "Options", "[", "opt", "]", "=", "value", "\n", "}", "\n", "if", "cfg", ".", "PolicyEnforcement", "!=", "\"", "\"", "{", "fullCfg", ".", "Spec", ".", "PolicyEnforcement", "=", "cfg", ".", "PolicyEnforcement", "\n", "}", "\n\n", "params", ":=", "daemon", ".", "NewPatchConfigParams", "(", ")", ".", "WithConfiguration", "(", "fullCfg", ".", "Spec", ")", ".", "WithTimeout", "(", "api", ".", "ClientTimeout", ")", "\n", "_", ",", "err", "=", "c", ".", "Daemon", ".", "PatchConfig", "(", "params", ")", "\n", "return", "Hint", "(", "err", ")", "\n", "}" ]
// ConfigPatch modifies the daemon configuration.
[ "ConfigPatch", "modifies", "the", "daemon", "configuration", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/client/config.go#L33-L49
162,812
cilium/cilium
api/v1/models/trace_from.go
Validate
func (m *TraceFrom) Validate(formats strfmt.Registry) error { var res []error if err := m.validateLabels(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil }
go
func (m *TraceFrom) Validate(formats strfmt.Registry) error { var res []error if err := m.validateLabels(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil }
[ "func", "(", "m", "*", "TraceFrom", ")", "Validate", "(", "formats", "strfmt", ".", "Registry", ")", "error", "{", "var", "res", "[", "]", "error", "\n\n", "if", "err", ":=", "m", ".", "validateLabels", "(", "formats", ")", ";", "err", "!=", "nil", "{", "res", "=", "append", "(", "res", ",", "err", ")", "\n", "}", "\n\n", "if", "len", "(", "res", ")", ">", "0", "{", "return", "errors", ".", "CompositeValidationError", "(", "res", "...", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate validates this trace from
[ "Validate", "validates", "this", "trace", "from" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/api/v1/models/trace_from.go#L24-L35
162,813
cilium/cilium
pkg/command/output.go
DumpJSONToSlice
func DumpJSONToSlice(data interface{}, jsonPath string) ([]byte, error) { if len(jsonPath) == 0 { result, err := json.MarshalIndent(data, "", " ") if err != nil { fmt.Fprintf(os.Stderr, "Couldn't marshal to json: '%s'\n", err) return nil, err } fmt.Println(string(result)) return nil, nil } parser := jsonpath.New("").AllowMissingKeys(true) if err := parser.Parse(jsonPath); err != nil { fmt.Fprintf(os.Stderr, "Couldn't parse jsonpath expression: '%s'\n", err) return nil, err } buf := new(bytes.Buffer) if err := parser.Execute(buf, data); err != nil { fmt.Fprintf(os.Stderr, "Couldn't parse jsonpath expression: '%s'\n", err) return nil, err } return buf.Bytes(), nil }
go
func DumpJSONToSlice(data interface{}, jsonPath string) ([]byte, error) { if len(jsonPath) == 0 { result, err := json.MarshalIndent(data, "", " ") if err != nil { fmt.Fprintf(os.Stderr, "Couldn't marshal to json: '%s'\n", err) return nil, err } fmt.Println(string(result)) return nil, nil } parser := jsonpath.New("").AllowMissingKeys(true) if err := parser.Parse(jsonPath); err != nil { fmt.Fprintf(os.Stderr, "Couldn't parse jsonpath expression: '%s'\n", err) return nil, err } buf := new(bytes.Buffer) if err := parser.Execute(buf, data); err != nil { fmt.Fprintf(os.Stderr, "Couldn't parse jsonpath expression: '%s'\n", err) return nil, err } return buf.Bytes(), nil }
[ "func", "DumpJSONToSlice", "(", "data", "interface", "{", "}", ",", "jsonPath", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "len", "(", "jsonPath", ")", "==", "0", "{", "result", ",", "err", ":=", "json", ".", "MarshalIndent", "(", "data", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\n", "\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "fmt", ".", "Println", "(", "string", "(", "result", ")", ")", "\n", "return", "nil", ",", "nil", "\n", "}", "\n\n", "parser", ":=", "jsonpath", ".", "New", "(", "\"", "\"", ")", ".", "AllowMissingKeys", "(", "true", ")", "\n", "if", "err", ":=", "parser", ".", "Parse", "(", "jsonPath", ")", ";", "err", "!=", "nil", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\n", "\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "buf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "if", "err", ":=", "parser", ".", "Execute", "(", "buf", ",", "data", ")", ";", "err", "!=", "nil", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\n", "\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n\n", "}", "\n", "return", "buf", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// DumpJSONToSlice dumps the contents of data into a byte slice. If jsonpath // is non-empty, will attempt to do jsonpath filtering using said string. // Returns byte array containing the JSON in data, or an error if any JSON // marshaling, parsing operations fail.
[ "DumpJSONToSlice", "dumps", "the", "contents", "of", "data", "into", "a", "byte", "slice", ".", "If", "jsonpath", "is", "non", "-", "empty", "will", "attempt", "to", "do", "jsonpath", "filtering", "using", "said", "string", ".", "Returns", "byte", "array", "containing", "the", "JSON", "in", "data", "or", "an", "error", "if", "any", "JSON", "marshaling", "parsing", "operations", "fail", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/command/output.go#L67-L91
162,814
cilium/cilium
pkg/command/output.go
dumpJSON
func dumpJSON(data interface{}, jsonPath string) error { jsonBytes, err := DumpJSONToSlice(data, jsonPath) if err != nil { return err } fmt.Println(string(jsonBytes[:])) return nil }
go
func dumpJSON(data interface{}, jsonPath string) error { jsonBytes, err := DumpJSONToSlice(data, jsonPath) if err != nil { return err } fmt.Println(string(jsonBytes[:])) return nil }
[ "func", "dumpJSON", "(", "data", "interface", "{", "}", ",", "jsonPath", "string", ")", "error", "{", "jsonBytes", ",", "err", ":=", "DumpJSONToSlice", "(", "data", ",", "jsonPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "fmt", ".", "Println", "(", "string", "(", "jsonBytes", "[", ":", "]", ")", ")", "\n", "return", "nil", "\n", "}" ]
// dumpJSON dump the data variable to the stdout as json. // If somethings fail, it'll return an error // If jsonPath is passed, it'll run the json query over data var.
[ "dumpJSON", "dump", "the", "data", "variable", "to", "the", "stdout", "as", "json", ".", "If", "somethings", "fail", "it", "ll", "return", "an", "error", "If", "jsonPath", "is", "passed", "it", "ll", "run", "the", "json", "query", "over", "data", "var", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/command/output.go#L96-L103
162,815
cilium/cilium
pkg/kvstore/consul.go
Disconnected
func (c *consulClient) Disconnected() <-chan struct{} { c.disconnectedMu.RLock() ch := c.disconnected c.disconnectedMu.RUnlock() return ch }
go
func (c *consulClient) Disconnected() <-chan struct{} { c.disconnectedMu.RLock() ch := c.disconnected c.disconnectedMu.RUnlock() return ch }
[ "func", "(", "c", "*", "consulClient", ")", "Disconnected", "(", ")", "<-", "chan", "struct", "{", "}", "{", "c", ".", "disconnectedMu", ".", "RLock", "(", ")", "\n", "ch", ":=", "c", ".", "disconnected", "\n", "c", ".", "disconnectedMu", ".", "RUnlock", "(", ")", "\n", "return", "ch", "\n", "}" ]
// Disconnected closes the returned channel when consul detects the client // is disconnected from the server.
[ "Disconnected", "closes", "the", "returned", "channel", "when", "consul", "detects", "the", "client", "is", "disconnected", "from", "the", "server", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/kvstore/consul.go#L395-L400
162,816
cilium/cilium
pkg/kvstore/consul.go
Update
func (c *consulClient) Update(ctx context.Context, key string, value []byte, lease bool) error { k := &consulAPI.KVPair{Key: key, Value: value} if lease { k.Session = c.lease } opts := &consulAPI.WriteOptions{} duration := spanstat.Start() _, err := c.KV().Put(k, opts.WithContext(ctx)) increaseMetric(key, metricSet, "Update", duration.EndError(err).Total(), err) return err }
go
func (c *consulClient) Update(ctx context.Context, key string, value []byte, lease bool) error { k := &consulAPI.KVPair{Key: key, Value: value} if lease { k.Session = c.lease } opts := &consulAPI.WriteOptions{} duration := spanstat.Start() _, err := c.KV().Put(k, opts.WithContext(ctx)) increaseMetric(key, metricSet, "Update", duration.EndError(err).Total(), err) return err }
[ "func", "(", "c", "*", "consulClient", ")", "Update", "(", "ctx", "context", ".", "Context", ",", "key", "string", ",", "value", "[", "]", "byte", ",", "lease", "bool", ")", "error", "{", "k", ":=", "&", "consulAPI", ".", "KVPair", "{", "Key", ":", "key", ",", "Value", ":", "value", "}", "\n\n", "if", "lease", "{", "k", ".", "Session", "=", "c", ".", "lease", "\n", "}", "\n\n", "opts", ":=", "&", "consulAPI", ".", "WriteOptions", "{", "}", "\n\n", "duration", ":=", "spanstat", ".", "Start", "(", ")", "\n", "_", ",", "err", ":=", "c", ".", "KV", "(", ")", ".", "Put", "(", "k", ",", "opts", ".", "WithContext", "(", "ctx", ")", ")", "\n", "increaseMetric", "(", "key", ",", "metricSet", ",", "\"", "\"", ",", "duration", ".", "EndError", "(", "err", ")", ".", "Total", "(", ")", ",", "err", ")", "\n", "return", "err", "\n", "}" ]
// Update creates or updates a key with the value
[ "Update", "creates", "or", "updates", "a", "key", "with", "the", "value" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/kvstore/consul.go#L462-L475
162,817
cilium/cilium
pkg/kvstore/consul.go
createIfExists
func (c *consulClient) createIfExists(condKey, key string, value []byte, lease bool) error { // Consul does not support transactions which would allow to check for // the presence of a conditional key if the key is not the key being // manipulated // // Lock the conditional key to serialize all CreateIfExists() calls l, err := LockPath(context.Background(), condKey) if err != nil { return fmt.Errorf("unable to lock condKey for CreateIfExists: %s", err) } defer l.Unlock() // Create the key if it does not exist if _, err := c.CreateOnly(context.TODO(), key, value, lease); err != nil { return err } // Consul does not support transactions which would allow to check for // the presence of another key masterKey, err := c.Get(condKey) if err != nil || masterKey == nil { c.Delete(key) return fmt.Errorf("conditional key not present") } return nil }
go
func (c *consulClient) createIfExists(condKey, key string, value []byte, lease bool) error { // Consul does not support transactions which would allow to check for // the presence of a conditional key if the key is not the key being // manipulated // // Lock the conditional key to serialize all CreateIfExists() calls l, err := LockPath(context.Background(), condKey) if err != nil { return fmt.Errorf("unable to lock condKey for CreateIfExists: %s", err) } defer l.Unlock() // Create the key if it does not exist if _, err := c.CreateOnly(context.TODO(), key, value, lease); err != nil { return err } // Consul does not support transactions which would allow to check for // the presence of another key masterKey, err := c.Get(condKey) if err != nil || masterKey == nil { c.Delete(key) return fmt.Errorf("conditional key not present") } return nil }
[ "func", "(", "c", "*", "consulClient", ")", "createIfExists", "(", "condKey", ",", "key", "string", ",", "value", "[", "]", "byte", ",", "lease", "bool", ")", "error", "{", "// Consul does not support transactions which would allow to check for", "// the presence of a conditional key if the key is not the key being", "// manipulated", "//", "// Lock the conditional key to serialize all CreateIfExists() calls", "l", ",", "err", ":=", "LockPath", "(", "context", ".", "Background", "(", ")", ",", "condKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "defer", "l", ".", "Unlock", "(", ")", "\n\n", "// Create the key if it does not exist", "if", "_", ",", "err", ":=", "c", ".", "CreateOnly", "(", "context", ".", "TODO", "(", ")", ",", "key", ",", "value", ",", "lease", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Consul does not support transactions which would allow to check for", "// the presence of another key", "masterKey", ",", "err", ":=", "c", ".", "Get", "(", "condKey", ")", "\n", "if", "err", "!=", "nil", "||", "masterKey", "==", "nil", "{", "c", ".", "Delete", "(", "key", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// createIfExists creates a key with the value only if key condKey exists
[ "createIfExists", "creates", "a", "key", "with", "the", "value", "only", "if", "key", "condKey", "exists" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/kvstore/consul.go#L513-L541
162,818
cilium/cilium
pkg/kvstore/consul.go
ListPrefix
func (c *consulClient) ListPrefix(prefix string) (KeyValuePairs, error) { duration := spanstat.Start() pairs, _, err := c.KV().List(prefix, nil) increaseMetric(prefix, metricRead, "ListPrefix", duration.EndError(err).Total(), err) if err != nil { return nil, err } p := KeyValuePairs(make(map[string][]byte, len(pairs))) for i := 0; i < len(pairs); i++ { p[pairs[i].Key] = pairs[i].Value } return p, nil }
go
func (c *consulClient) ListPrefix(prefix string) (KeyValuePairs, error) { duration := spanstat.Start() pairs, _, err := c.KV().List(prefix, nil) increaseMetric(prefix, metricRead, "ListPrefix", duration.EndError(err).Total(), err) if err != nil { return nil, err } p := KeyValuePairs(make(map[string][]byte, len(pairs))) for i := 0; i < len(pairs); i++ { p[pairs[i].Key] = pairs[i].Value } return p, nil }
[ "func", "(", "c", "*", "consulClient", ")", "ListPrefix", "(", "prefix", "string", ")", "(", "KeyValuePairs", ",", "error", ")", "{", "duration", ":=", "spanstat", ".", "Start", "(", ")", "\n", "pairs", ",", "_", ",", "err", ":=", "c", ".", "KV", "(", ")", ".", "List", "(", "prefix", ",", "nil", ")", "\n", "increaseMetric", "(", "prefix", ",", "metricRead", ",", "\"", "\"", ",", "duration", ".", "EndError", "(", "err", ")", ".", "Total", "(", ")", ",", "err", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "p", ":=", "KeyValuePairs", "(", "make", "(", "map", "[", "string", "]", "[", "]", "byte", ",", "len", "(", "pairs", ")", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "pairs", ")", ";", "i", "++", "{", "p", "[", "pairs", "[", "i", "]", ".", "Key", "]", "=", "pairs", "[", "i", "]", ".", "Value", "\n", "}", "\n\n", "return", "p", ",", "nil", "\n", "}" ]
// ListPrefix returns a map of matching keys
[ "ListPrefix", "returns", "a", "map", "of", "matching", "keys" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/kvstore/consul.go#L552-L566
162,819
cilium/cilium
pkg/kvstore/consul.go
Close
func (c *consulClient) Close() { if c.controllers != nil { c.controllers.RemoveAll() } if c.lease != "" { c.Session().Destroy(c.lease, nil) } }
go
func (c *consulClient) Close() { if c.controllers != nil { c.controllers.RemoveAll() } if c.lease != "" { c.Session().Destroy(c.lease, nil) } }
[ "func", "(", "c", "*", "consulClient", ")", "Close", "(", ")", "{", "if", "c", ".", "controllers", "!=", "nil", "{", "c", ".", "controllers", ".", "RemoveAll", "(", ")", "\n", "}", "\n", "if", "c", ".", "lease", "!=", "\"", "\"", "{", "c", ".", "Session", "(", ")", ".", "Destroy", "(", "c", ".", "lease", ",", "nil", ")", "\n", "}", "\n", "}" ]
// Close closes the consul session
[ "Close", "closes", "the", "consul", "session" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/kvstore/consul.go#L569-L576
162,820
cilium/cilium
pkg/kvstore/consul.go
ListAndWatch
func (c *consulClient) ListAndWatch(name, prefix string, chanSize int) *Watcher { w := newWatcher(name, prefix, chanSize) log.WithField(fieldWatcher, w).Debug("Starting watcher...") go c.Watch(w) return w }
go
func (c *consulClient) ListAndWatch(name, prefix string, chanSize int) *Watcher { w := newWatcher(name, prefix, chanSize) log.WithField(fieldWatcher, w).Debug("Starting watcher...") go c.Watch(w) return w }
[ "func", "(", "c", "*", "consulClient", ")", "ListAndWatch", "(", "name", ",", "prefix", "string", ",", "chanSize", "int", ")", "*", "Watcher", "{", "w", ":=", "newWatcher", "(", "name", ",", "prefix", ",", "chanSize", ")", "\n\n", "log", ".", "WithField", "(", "fieldWatcher", ",", "w", ")", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "go", "c", ".", "Watch", "(", "w", ")", "\n\n", "return", "w", "\n", "}" ]
// ListAndWatch implements the BackendOperations.ListAndWatch using consul
[ "ListAndWatch", "implements", "the", "BackendOperations", ".", "ListAndWatch", "using", "consul" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/kvstore/consul.go#L594-L602
162,821
cilium/cilium
pkg/endpoint/id/allocator.go
Allocate
func Allocate() uint16 { id := pool.AllocateID() // Out of endpoint IDs if id == idpool.NoID { return uint16(0) } return uint16(id) }
go
func Allocate() uint16 { id := pool.AllocateID() // Out of endpoint IDs if id == idpool.NoID { return uint16(0) } return uint16(id) }
[ "func", "Allocate", "(", ")", "uint16", "{", "id", ":=", "pool", ".", "AllocateID", "(", ")", "\n\n", "// Out of endpoint IDs", "if", "id", "==", "idpool", ".", "NoID", "{", "return", "uint16", "(", "0", ")", "\n", "}", "\n\n", "return", "uint16", "(", "id", ")", "\n", "}" ]
// Allocate returns a new random ID from the pool
[ "Allocate", "returns", "a", "new", "random", "ID", "from", "the", "pool" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/endpoint/id/allocator.go#L41-L50
162,822
cilium/cilium
pkg/endpoint/id/allocator.go
Reuse
func Reuse(id uint16) error { if idpool.ID(id) < minID { return fmt.Errorf("unable to reuse endpoint: %d < %d", id, minID) } // When restoring endpoints, the existing endpoint ID can be outside of // the range. This is fine (tm) and we can just skip to reserve the ID // from the pool as the pool will not cover it. if idpool.ID(id) > maxID { return nil } if !pool.Remove(idpool.ID(id)) { return fmt.Errorf("endpoint ID %d is already in use", id) } return nil }
go
func Reuse(id uint16) error { if idpool.ID(id) < minID { return fmt.Errorf("unable to reuse endpoint: %d < %d", id, minID) } // When restoring endpoints, the existing endpoint ID can be outside of // the range. This is fine (tm) and we can just skip to reserve the ID // from the pool as the pool will not cover it. if idpool.ID(id) > maxID { return nil } if !pool.Remove(idpool.ID(id)) { return fmt.Errorf("endpoint ID %d is already in use", id) } return nil }
[ "func", "Reuse", "(", "id", "uint16", ")", "error", "{", "if", "idpool", ".", "ID", "(", "id", ")", "<", "minID", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "id", ",", "minID", ")", "\n", "}", "\n\n", "// When restoring endpoints, the existing endpoint ID can be outside of", "// the range. This is fine (tm) and we can just skip to reserve the ID", "// from the pool as the pool will not cover it.", "if", "idpool", ".", "ID", "(", "id", ")", ">", "maxID", "{", "return", "nil", "\n", "}", "\n\n", "if", "!", "pool", ".", "Remove", "(", "idpool", ".", "ID", "(", "id", ")", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "id", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Reuse grabs a specific endpoint ID for reuse. This can be used when // restoring endpoints.
[ "Reuse", "grabs", "a", "specific", "endpoint", "ID", "for", "reuse", ".", "This", "can", "be", "used", "when", "restoring", "endpoints", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/endpoint/id/allocator.go#L54-L71
162,823
cilium/cilium
pkg/endpoint/id/allocator.go
Release
func Release(id uint16) error { if !pool.Insert(idpool.ID(id)) { return fmt.Errorf("Unable to release endpoint ID %d", id) } return nil }
go
func Release(id uint16) error { if !pool.Insert(idpool.ID(id)) { return fmt.Errorf("Unable to release endpoint ID %d", id) } return nil }
[ "func", "Release", "(", "id", "uint16", ")", "error", "{", "if", "!", "pool", ".", "Insert", "(", "idpool", ".", "ID", "(", "id", ")", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "id", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Release releases an endpoint ID that was previously allocated or reused
[ "Release", "releases", "an", "endpoint", "ID", "that", "was", "previously", "allocated", "or", "reused" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/endpoint/id/allocator.go#L74-L80
162,824
cilium/cilium
api/v1/server/restapi/daemon/get_map_name_parameters.go
bindName
func (o *GetMapNameParams) bindName(rawData []string, hasKey bool, formats strfmt.Registry) error { var raw string if len(rawData) > 0 { raw = rawData[len(rawData)-1] } // Required: true // Parameter is provided by construction from the route o.Name = raw return nil }
go
func (o *GetMapNameParams) bindName(rawData []string, hasKey bool, formats strfmt.Registry) error { var raw string if len(rawData) > 0 { raw = rawData[len(rawData)-1] } // Required: true // Parameter is provided by construction from the route o.Name = raw return nil }
[ "func", "(", "o", "*", "GetMapNameParams", ")", "bindName", "(", "rawData", "[", "]", "string", ",", "hasKey", "bool", ",", "formats", "strfmt", ".", "Registry", ")", "error", "{", "var", "raw", "string", "\n", "if", "len", "(", "rawData", ")", ">", "0", "{", "raw", "=", "rawData", "[", "len", "(", "rawData", ")", "-", "1", "]", "\n", "}", "\n\n", "// Required: true", "// Parameter is provided by construction from the route", "o", ".", "Name", "=", "raw", "\n\n", "return", "nil", "\n", "}" ]
// bindName binds and validates parameter Name from path.
[ "bindName", "binds", "and", "validates", "parameter", "Name", "from", "path", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/api/v1/server/restapi/daemon/get_map_name_parameters.go#L61-L73
162,825
cilium/cilium
cilium/cmd/bpf_ipcache_get.go
getLPMValue
func getLPMValue(ip net.IP, entries map[string][]string) (interface{}, bool) { type lpmEntry struct { prefix []byte identity []string } isV4 := isIPV4(ip) // Convert ip to 4-byte representation if IPv4. if isV4 { ip = ip.To4() } var lpmEntries []lpmEntry for cidr, identity := range entries { currIP, subnet, err := net.ParseCIDR(cidr) if err != nil { log.Warnf("unable to parse ipcache entry '%s' as a CIDR: %s", cidr, err) continue } // No need to include IPv6 addresses if the argument is // IPv4 and vice versa. if isIPV4(currIP) != isV4 { continue } // Convert ip to 4-byte representation if IPv4. if isV4 { currIP = currIP.To4() } ones, _ := subnet.Mask.Size() prefix := getPrefix(currIP, ones) lpmEntries = append(lpmEntries, lpmEntry{prefix, identity}) } r := iradix.New() for _, e := range lpmEntries { r, _, _ = r.Insert(e.prefix, e.identity) } // Look-up using all bits in the argument ip var mask int if isV4 { mask = 8 * net.IPv4len } else { mask = 8 * net.IPv6len } _, v, exists := r.Root().LongestPrefix(getPrefix(ip, mask)) return v, exists }
go
func getLPMValue(ip net.IP, entries map[string][]string) (interface{}, bool) { type lpmEntry struct { prefix []byte identity []string } isV4 := isIPV4(ip) // Convert ip to 4-byte representation if IPv4. if isV4 { ip = ip.To4() } var lpmEntries []lpmEntry for cidr, identity := range entries { currIP, subnet, err := net.ParseCIDR(cidr) if err != nil { log.Warnf("unable to parse ipcache entry '%s' as a CIDR: %s", cidr, err) continue } // No need to include IPv6 addresses if the argument is // IPv4 and vice versa. if isIPV4(currIP) != isV4 { continue } // Convert ip to 4-byte representation if IPv4. if isV4 { currIP = currIP.To4() } ones, _ := subnet.Mask.Size() prefix := getPrefix(currIP, ones) lpmEntries = append(lpmEntries, lpmEntry{prefix, identity}) } r := iradix.New() for _, e := range lpmEntries { r, _, _ = r.Insert(e.prefix, e.identity) } // Look-up using all bits in the argument ip var mask int if isV4 { mask = 8 * net.IPv4len } else { mask = 8 * net.IPv6len } _, v, exists := r.Root().LongestPrefix(getPrefix(ip, mask)) return v, exists }
[ "func", "getLPMValue", "(", "ip", "net", ".", "IP", ",", "entries", "map", "[", "string", "]", "[", "]", "string", ")", "(", "interface", "{", "}", ",", "bool", ")", "{", "type", "lpmEntry", "struct", "{", "prefix", "[", "]", "byte", "\n", "identity", "[", "]", "string", "\n", "}", "\n\n", "isV4", ":=", "isIPV4", "(", "ip", ")", "\n\n", "// Convert ip to 4-byte representation if IPv4.", "if", "isV4", "{", "ip", "=", "ip", ".", "To4", "(", ")", "\n", "}", "\n\n", "var", "lpmEntries", "[", "]", "lpmEntry", "\n", "for", "cidr", ",", "identity", ":=", "range", "entries", "{", "currIP", ",", "subnet", ",", "err", ":=", "net", ".", "ParseCIDR", "(", "cidr", ")", "\n\n", "if", "err", "!=", "nil", "{", "log", ".", "Warnf", "(", "\"", "\"", ",", "cidr", ",", "err", ")", "\n", "continue", "\n", "}", "\n\n", "// No need to include IPv6 addresses if the argument is", "// IPv4 and vice versa.", "if", "isIPV4", "(", "currIP", ")", "!=", "isV4", "{", "continue", "\n", "}", "\n\n", "// Convert ip to 4-byte representation if IPv4.", "if", "isV4", "{", "currIP", "=", "currIP", ".", "To4", "(", ")", "\n", "}", "\n\n", "ones", ",", "_", ":=", "subnet", ".", "Mask", ".", "Size", "(", ")", "\n", "prefix", ":=", "getPrefix", "(", "currIP", ",", "ones", ")", "\n\n", "lpmEntries", "=", "append", "(", "lpmEntries", ",", "lpmEntry", "{", "prefix", ",", "identity", "}", ")", "\n", "}", "\n\n", "r", ":=", "iradix", ".", "New", "(", ")", "\n", "for", "_", ",", "e", ":=", "range", "lpmEntries", "{", "r", ",", "_", ",", "_", "=", "r", ".", "Insert", "(", "e", ".", "prefix", ",", "e", ".", "identity", ")", "\n", "}", "\n\n", "// Look-up using all bits in the argument ip", "var", "mask", "int", "\n", "if", "isV4", "{", "mask", "=", "8", "*", "net", ".", "IPv4len", "\n", "}", "else", "{", "mask", "=", "8", "*", "net", ".", "IPv6len", "\n", "}", "\n\n", "_", ",", "v", ",", "exists", ":=", "r", ".", "Root", "(", ")", ".", "LongestPrefix", "(", "getPrefix", "(", "ip", ",", "mask", ")", ")", "\n", "return", "v", ",", "exists", "\n", "}" ]
// getLPMValue calculates the longest prefix matching ip amongst the // keys in entries. The keys in entries must be specified in CIDR notation. // If LPM is found, the value associated with that entry is returned // along with boolean true. Otherwise, false is returned.
[ "getLPMValue", "calculates", "the", "longest", "prefix", "matching", "ip", "amongst", "the", "keys", "in", "entries", ".", "The", "keys", "in", "entries", "must", "be", "specified", "in", "CIDR", "notation", ".", "If", "LPM", "is", "found", "the", "value", "associated", "with", "that", "entry", "is", "returned", "along", "with", "boolean", "true", ".", "Otherwise", "false", "is", "returned", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/cilium/cmd/bpf_ipcache_get.go#L92-L146
162,826
cilium/cilium
cilium/cmd/bpf_ipcache_get.go
getPrefix
func getPrefix(ip net.IP, maskSize int) []byte { bytes := make([]byte, maskSize) var i, j uint8 var n int for n < maskSize { for j = 0; j < 8 && n < maskSize; j++ { mask := uint8(128) >> uint8(j) if mask&ip[i] == 0 { bytes[i*8+j] = 0x0 } else { bytes[i*8+j] = 0x1 } n++ } i++ } return bytes }
go
func getPrefix(ip net.IP, maskSize int) []byte { bytes := make([]byte, maskSize) var i, j uint8 var n int for n < maskSize { for j = 0; j < 8 && n < maskSize; j++ { mask := uint8(128) >> uint8(j) if mask&ip[i] == 0 { bytes[i*8+j] = 0x0 } else { bytes[i*8+j] = 0x1 } n++ } i++ } return bytes }
[ "func", "getPrefix", "(", "ip", "net", ".", "IP", ",", "maskSize", "int", ")", "[", "]", "byte", "{", "bytes", ":=", "make", "(", "[", "]", "byte", ",", "maskSize", ")", "\n", "var", "i", ",", "j", "uint8", "\n", "var", "n", "int", "\n\n", "for", "n", "<", "maskSize", "{", "for", "j", "=", "0", ";", "j", "<", "8", "&&", "n", "<", "maskSize", ";", "j", "++", "{", "mask", ":=", "uint8", "(", "128", ")", ">>", "uint8", "(", "j", ")", "\n\n", "if", "mask", "&", "ip", "[", "i", "]", "==", "0", "{", "bytes", "[", "i", "*", "8", "+", "j", "]", "=", "0x0", "\n", "}", "else", "{", "bytes", "[", "i", "*", "8", "+", "j", "]", "=", "0x1", "\n", "}", "\n", "n", "++", "\n", "}", "\n", "i", "++", "\n", "}", "\n\n", "return", "bytes", "\n", "}" ]
// getPrefix converts the most significant maskSize bits in ip // into a byte slice - each bit is represented using one byte.
[ "getPrefix", "converts", "the", "most", "significant", "maskSize", "bits", "in", "ip", "into", "a", "byte", "slice", "-", "each", "bit", "is", "represented", "using", "one", "byte", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/cilium/cmd/bpf_ipcache_get.go#L150-L170
162,827
cilium/cilium
pkg/service/id_kvstore.go
getMaxID
func getMaxID(key string, firstID uint32) (uint32, error) { client := kvstore.Client() k, err := client.Get(key) if err != nil { return 0, err } if k == nil { // FreeID is empty? We should set it out! if err := initializeFreeID(key, firstID); err != nil { return 0, err } // Due other goroutine can take the ID, still need to get the key from the kvstore. k, err = client.Get(key) if err != nil { return 0, err } if k == nil { // Something is really wrong errMsg := "Unable to retrieve last free ID because the key is always empty\n" log.Error(errMsg) return 0, fmt.Errorf(errMsg) } } var freeID uint32 if err := json.Unmarshal(k, &freeID); err != nil { return 0, err } return freeID, nil }
go
func getMaxID(key string, firstID uint32) (uint32, error) { client := kvstore.Client() k, err := client.Get(key) if err != nil { return 0, err } if k == nil { // FreeID is empty? We should set it out! if err := initializeFreeID(key, firstID); err != nil { return 0, err } // Due other goroutine can take the ID, still need to get the key from the kvstore. k, err = client.Get(key) if err != nil { return 0, err } if k == nil { // Something is really wrong errMsg := "Unable to retrieve last free ID because the key is always empty\n" log.Error(errMsg) return 0, fmt.Errorf(errMsg) } } var freeID uint32 if err := json.Unmarshal(k, &freeID); err != nil { return 0, err } return freeID, nil }
[ "func", "getMaxID", "(", "key", "string", ",", "firstID", "uint32", ")", "(", "uint32", ",", "error", ")", "{", "client", ":=", "kvstore", ".", "Client", "(", ")", "\n", "k", ",", "err", ":=", "client", ".", "Get", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "if", "k", "==", "nil", "{", "// FreeID is empty? We should set it out!", "if", "err", ":=", "initializeFreeID", "(", "key", ",", "firstID", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "// Due other goroutine can take the ID, still need to get the key from the kvstore.", "k", ",", "err", "=", "client", ".", "Get", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "if", "k", "==", "nil", "{", "// Something is really wrong", "errMsg", ":=", "\"", "\\n", "\"", "\n", "log", ".", "Error", "(", "errMsg", ")", "\n", "return", "0", ",", "fmt", ".", "Errorf", "(", "errMsg", ")", "\n", "}", "\n", "}", "\n", "var", "freeID", "uint32", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "k", ",", "&", "freeID", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "freeID", ",", "nil", "\n", "}" ]
// getMaxID returns the maximum possible free UUID stored.
[ "getMaxID", "returns", "the", "maximum", "possible", "free", "UUID", "stored", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/service/id_kvstore.go#L72-L100
162,828
cilium/cilium
pkg/service/id_kvstore.go
gasNewL3n4AddrID
func gasNewL3n4AddrID(l3n4AddrID *loadbalancer.L3n4AddrID, baseID uint32) error { client := kvstore.Client() if baseID == 0 { var err error baseID, err = getGlobalMaxServiceID() if err != nil { return err } } setIDtoL3n4Addr := func(id uint32) error { l3n4AddrID.ID = loadbalancer.ID(id) marshaledL3n4AddrID, err := json.Marshal(l3n4AddrID) if err != nil { return err } keyPath := path.Join(ServiceIDKeyPath, strconv.FormatUint(uint64(l3n4AddrID.ID), 10)) if err := client.Set(keyPath, marshaledL3n4AddrID); err != nil { return err } return setMaxID(LastFreeServiceIDKeyPath, FirstFreeServiceID, id+1) } acquireFreeID := func(firstID uint32, incID *uint32) (bool, error) { keyPath := path.Join(ServiceIDKeyPath, strconv.FormatUint(uint64(*incID), 10)) locker, err := client.LockPath(context.Background(), keyPath) if err != nil { return false, err } defer locker.Unlock() value, err := client.Get(keyPath) if err != nil { return false, err } if value == nil { return false, setIDtoL3n4Addr(*incID) } var kvstoreL3n4AddrID loadbalancer.L3n4AddrID if err := json.Unmarshal(value, &kvstoreL3n4AddrID); err != nil { return false, err } if kvstoreL3n4AddrID.ID == 0 { log.WithField(logfields.Identity, *incID).Info("Recycling Service ID") return false, setIDtoL3n4Addr(*incID) } *incID++ if *incID > MaxSetOfServiceID { *incID = FirstFreeServiceID } if firstID == *incID { return false, fmt.Errorf("reached maximum set of serviceIDs available") } // Only retry if we have incremented the service ID return true, nil } beginning := baseID for { retry, err := acquireFreeID(beginning, &baseID) if err != nil { return err } else if !retry { return nil } } }
go
func gasNewL3n4AddrID(l3n4AddrID *loadbalancer.L3n4AddrID, baseID uint32) error { client := kvstore.Client() if baseID == 0 { var err error baseID, err = getGlobalMaxServiceID() if err != nil { return err } } setIDtoL3n4Addr := func(id uint32) error { l3n4AddrID.ID = loadbalancer.ID(id) marshaledL3n4AddrID, err := json.Marshal(l3n4AddrID) if err != nil { return err } keyPath := path.Join(ServiceIDKeyPath, strconv.FormatUint(uint64(l3n4AddrID.ID), 10)) if err := client.Set(keyPath, marshaledL3n4AddrID); err != nil { return err } return setMaxID(LastFreeServiceIDKeyPath, FirstFreeServiceID, id+1) } acquireFreeID := func(firstID uint32, incID *uint32) (bool, error) { keyPath := path.Join(ServiceIDKeyPath, strconv.FormatUint(uint64(*incID), 10)) locker, err := client.LockPath(context.Background(), keyPath) if err != nil { return false, err } defer locker.Unlock() value, err := client.Get(keyPath) if err != nil { return false, err } if value == nil { return false, setIDtoL3n4Addr(*incID) } var kvstoreL3n4AddrID loadbalancer.L3n4AddrID if err := json.Unmarshal(value, &kvstoreL3n4AddrID); err != nil { return false, err } if kvstoreL3n4AddrID.ID == 0 { log.WithField(logfields.Identity, *incID).Info("Recycling Service ID") return false, setIDtoL3n4Addr(*incID) } *incID++ if *incID > MaxSetOfServiceID { *incID = FirstFreeServiceID } if firstID == *incID { return false, fmt.Errorf("reached maximum set of serviceIDs available") } // Only retry if we have incremented the service ID return true, nil } beginning := baseID for { retry, err := acquireFreeID(beginning, &baseID) if err != nil { return err } else if !retry { return nil } } }
[ "func", "gasNewL3n4AddrID", "(", "l3n4AddrID", "*", "loadbalancer", ".", "L3n4AddrID", ",", "baseID", "uint32", ")", "error", "{", "client", ":=", "kvstore", ".", "Client", "(", ")", "\n\n", "if", "baseID", "==", "0", "{", "var", "err", "error", "\n", "baseID", ",", "err", "=", "getGlobalMaxServiceID", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "setIDtoL3n4Addr", ":=", "func", "(", "id", "uint32", ")", "error", "{", "l3n4AddrID", ".", "ID", "=", "loadbalancer", ".", "ID", "(", "id", ")", "\n", "marshaledL3n4AddrID", ",", "err", ":=", "json", ".", "Marshal", "(", "l3n4AddrID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "keyPath", ":=", "path", ".", "Join", "(", "ServiceIDKeyPath", ",", "strconv", ".", "FormatUint", "(", "uint64", "(", "l3n4AddrID", ".", "ID", ")", ",", "10", ")", ")", "\n", "if", "err", ":=", "client", ".", "Set", "(", "keyPath", ",", "marshaledL3n4AddrID", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "setMaxID", "(", "LastFreeServiceIDKeyPath", ",", "FirstFreeServiceID", ",", "id", "+", "1", ")", "\n", "}", "\n\n", "acquireFreeID", ":=", "func", "(", "firstID", "uint32", ",", "incID", "*", "uint32", ")", "(", "bool", ",", "error", ")", "{", "keyPath", ":=", "path", ".", "Join", "(", "ServiceIDKeyPath", ",", "strconv", ".", "FormatUint", "(", "uint64", "(", "*", "incID", ")", ",", "10", ")", ")", "\n\n", "locker", ",", "err", ":=", "client", ".", "LockPath", "(", "context", ".", "Background", "(", ")", ",", "keyPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "defer", "locker", ".", "Unlock", "(", ")", "\n\n", "value", ",", "err", ":=", "client", ".", "Get", "(", "keyPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "if", "value", "==", "nil", "{", "return", "false", ",", "setIDtoL3n4Addr", "(", "*", "incID", ")", "\n", "}", "\n", "var", "kvstoreL3n4AddrID", "loadbalancer", ".", "L3n4AddrID", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "value", ",", "&", "kvstoreL3n4AddrID", ")", ";", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "if", "kvstoreL3n4AddrID", ".", "ID", "==", "0", "{", "log", ".", "WithField", "(", "logfields", ".", "Identity", ",", "*", "incID", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "return", "false", ",", "setIDtoL3n4Addr", "(", "*", "incID", ")", "\n", "}", "\n\n", "*", "incID", "++", "\n", "if", "*", "incID", ">", "MaxSetOfServiceID", "{", "*", "incID", "=", "FirstFreeServiceID", "\n", "}", "\n", "if", "firstID", "==", "*", "incID", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "// Only retry if we have incremented the service ID", "return", "true", ",", "nil", "\n", "}", "\n\n", "beginning", ":=", "baseID", "\n", "for", "{", "retry", ",", "err", ":=", "acquireFreeID", "(", "beginning", ",", "&", "baseID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "else", "if", "!", "retry", "{", "return", "nil", "\n", "}", "\n", "}", "\n", "}" ]
// gasNewL3n4AddrID gets and sets a new L3n4Addr ID. If baseID is different than zero, // KVStore tries to assign that ID first.
[ "gasNewL3n4AddrID", "gets", "and", "sets", "a", "new", "L3n4Addr", "ID", ".", "If", "baseID", "is", "different", "than", "zero", "KVStore", "tries", "to", "assign", "that", "ID", "first", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/service/id_kvstore.go#L133-L203
162,829
cilium/cilium
pkg/service/id_kvstore.go
acquireGlobalID
func acquireGlobalID(l3n4Addr loadbalancer.L3n4Addr, baseID uint32) (*loadbalancer.L3n4AddrID, error) { // Retrieve unique SHA256Sum for service sha256Sum := l3n4Addr.SHA256Sum() svcPath := path.Join(common.ServicesKeyPath, sha256Sum) // Lock that sha256Sum lockKey, err := kvstore.LockPath(context.Background(), svcPath) if err != nil { return nil, err } defer lockKey.Unlock() // After lock complete, get svc's path rmsg, err := kvstore.Client().Get(svcPath) if err != nil { return nil, err } sl4KV := loadbalancer.L3n4AddrID{} if rmsg != nil { if err := json.Unmarshal(rmsg, &sl4KV); err != nil { return nil, err } } if sl4KV.ID == 0 { sl4KV.L3n4Addr = l3n4Addr if err := gasNewL3n4AddrID(&sl4KV, baseID); err != nil { return nil, err } marshaledSl4Kv, err := json.Marshal(sl4KV) if err != nil { return nil, err } err = kvstore.Client().Set(svcPath, marshaledSl4Kv) if err != nil { return nil, err } } return &sl4KV, err }
go
func acquireGlobalID(l3n4Addr loadbalancer.L3n4Addr, baseID uint32) (*loadbalancer.L3n4AddrID, error) { // Retrieve unique SHA256Sum for service sha256Sum := l3n4Addr.SHA256Sum() svcPath := path.Join(common.ServicesKeyPath, sha256Sum) // Lock that sha256Sum lockKey, err := kvstore.LockPath(context.Background(), svcPath) if err != nil { return nil, err } defer lockKey.Unlock() // After lock complete, get svc's path rmsg, err := kvstore.Client().Get(svcPath) if err != nil { return nil, err } sl4KV := loadbalancer.L3n4AddrID{} if rmsg != nil { if err := json.Unmarshal(rmsg, &sl4KV); err != nil { return nil, err } } if sl4KV.ID == 0 { sl4KV.L3n4Addr = l3n4Addr if err := gasNewL3n4AddrID(&sl4KV, baseID); err != nil { return nil, err } marshaledSl4Kv, err := json.Marshal(sl4KV) if err != nil { return nil, err } err = kvstore.Client().Set(svcPath, marshaledSl4Kv) if err != nil { return nil, err } } return &sl4KV, err }
[ "func", "acquireGlobalID", "(", "l3n4Addr", "loadbalancer", ".", "L3n4Addr", ",", "baseID", "uint32", ")", "(", "*", "loadbalancer", ".", "L3n4AddrID", ",", "error", ")", "{", "// Retrieve unique SHA256Sum for service", "sha256Sum", ":=", "l3n4Addr", ".", "SHA256Sum", "(", ")", "\n", "svcPath", ":=", "path", ".", "Join", "(", "common", ".", "ServicesKeyPath", ",", "sha256Sum", ")", "\n\n", "// Lock that sha256Sum", "lockKey", ",", "err", ":=", "kvstore", ".", "LockPath", "(", "context", ".", "Background", "(", ")", ",", "svcPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "lockKey", ".", "Unlock", "(", ")", "\n\n", "// After lock complete, get svc's path", "rmsg", ",", "err", ":=", "kvstore", ".", "Client", "(", ")", ".", "Get", "(", "svcPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "sl4KV", ":=", "loadbalancer", ".", "L3n4AddrID", "{", "}", "\n", "if", "rmsg", "!=", "nil", "{", "if", "err", ":=", "json", ".", "Unmarshal", "(", "rmsg", ",", "&", "sl4KV", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "if", "sl4KV", ".", "ID", "==", "0", "{", "sl4KV", ".", "L3n4Addr", "=", "l3n4Addr", "\n", "if", "err", ":=", "gasNewL3n4AddrID", "(", "&", "sl4KV", ",", "baseID", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "marshaledSl4Kv", ",", "err", ":=", "json", ".", "Marshal", "(", "sl4KV", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "err", "=", "kvstore", ".", "Client", "(", ")", ".", "Set", "(", "svcPath", ",", "marshaledSl4Kv", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "&", "sl4KV", ",", "err", "\n", "}" ]
// acquireGlobalID stores the given service in the kvstore and returns the L3n4AddrID // created for the given l3n4Addr. If baseID is different than 0, it tries to acquire that // ID to the l3n4Addr.
[ "acquireGlobalID", "stores", "the", "given", "service", "in", "the", "kvstore", "and", "returns", "the", "L3n4AddrID", "created", "for", "the", "given", "l3n4Addr", ".", "If", "baseID", "is", "different", "than", "0", "it", "tries", "to", "acquire", "that", "ID", "to", "the", "l3n4Addr", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/service/id_kvstore.go#L208-L248
162,830
cilium/cilium
pkg/service/id_kvstore.go
getGlobalID
func getGlobalID(id uint32) (*loadbalancer.L3n4AddrID, error) { strID := strconv.FormatUint(uint64(id), 10) log.WithField(logfields.L3n4AddrID, strID).Debug("getting L3n4AddrID for ID") return getL3n4AddrID(path.Join(ServiceIDKeyPath, strID)) }
go
func getGlobalID(id uint32) (*loadbalancer.L3n4AddrID, error) { strID := strconv.FormatUint(uint64(id), 10) log.WithField(logfields.L3n4AddrID, strID).Debug("getting L3n4AddrID for ID") return getL3n4AddrID(path.Join(ServiceIDKeyPath, strID)) }
[ "func", "getGlobalID", "(", "id", "uint32", ")", "(", "*", "loadbalancer", ".", "L3n4AddrID", ",", "error", ")", "{", "strID", ":=", "strconv", ".", "FormatUint", "(", "uint64", "(", "id", ")", ",", "10", ")", "\n", "log", ".", "WithField", "(", "logfields", ".", "L3n4AddrID", ",", "strID", ")", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "return", "getL3n4AddrID", "(", "path", ".", "Join", "(", "ServiceIDKeyPath", ",", "strID", ")", ")", "\n", "}" ]
// getGlobalID returns the L3n4AddrID that belongs to the given id.
[ "getGlobalID", "returns", "the", "L3n4AddrID", "that", "belongs", "to", "the", "given", "id", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/service/id_kvstore.go#L268-L273
162,831
cilium/cilium
pkg/service/id_kvstore.go
deleteGlobalID
func deleteGlobalID(id uint32) error { l3n4AddrID, err := getGlobalID(id) if err != nil { return err } if l3n4AddrID == nil { return nil } return deleteL3n4AddrIDBySHA256(l3n4AddrID.SHA256Sum()) }
go
func deleteGlobalID(id uint32) error { l3n4AddrID, err := getGlobalID(id) if err != nil { return err } if l3n4AddrID == nil { return nil } return deleteL3n4AddrIDBySHA256(l3n4AddrID.SHA256Sum()) }
[ "func", "deleteGlobalID", "(", "id", "uint32", ")", "error", "{", "l3n4AddrID", ",", "err", ":=", "getGlobalID", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "l3n4AddrID", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "return", "deleteL3n4AddrIDBySHA256", "(", "l3n4AddrID", ".", "SHA256Sum", "(", ")", ")", "\n", "}" ]
// deleteGlobalID deletes the L3n4AddrID belonging to the given id from the kvstore.
[ "deleteGlobalID", "deletes", "the", "L3n4AddrID", "belonging", "to", "the", "given", "id", "from", "the", "kvstore", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/service/id_kvstore.go#L276-L286
162,832
cilium/cilium
pkg/service/id_kvstore.go
deleteL3n4AddrIDBySHA256
func deleteL3n4AddrIDBySHA256(sha256Sum string) error { log.WithField(logfields.SHA, sha256Sum).Debug("deleting L3n4AddrID with SHA256") if sha256Sum == "" { return nil } svcPath := path.Join(common.ServicesKeyPath, sha256Sum) // Lock that sha256Sum lockKey, err := kvstore.LockPath(context.Background(), svcPath) if err != nil { return err } defer lockKey.Unlock() // After lock complete, get label's path rmsg, err := kvstore.Client().Get(svcPath) if err != nil { return err } if rmsg == nil { return nil } var l3n4AddrID loadbalancer.L3n4AddrID if err := json.Unmarshal(rmsg, &l3n4AddrID); err != nil { return err } oldL3n4ID := l3n4AddrID.ID l3n4AddrID.ID = 0 // update the value in the kvstore if err := updateL3n4AddrIDRef(oldL3n4ID, l3n4AddrID); err != nil { return err } marshaledL3n4AddrID, err := json.Marshal(l3n4AddrID) if err != nil { return err } return kvstore.Client().Set(svcPath, marshaledL3n4AddrID) }
go
func deleteL3n4AddrIDBySHA256(sha256Sum string) error { log.WithField(logfields.SHA, sha256Sum).Debug("deleting L3n4AddrID with SHA256") if sha256Sum == "" { return nil } svcPath := path.Join(common.ServicesKeyPath, sha256Sum) // Lock that sha256Sum lockKey, err := kvstore.LockPath(context.Background(), svcPath) if err != nil { return err } defer lockKey.Unlock() // After lock complete, get label's path rmsg, err := kvstore.Client().Get(svcPath) if err != nil { return err } if rmsg == nil { return nil } var l3n4AddrID loadbalancer.L3n4AddrID if err := json.Unmarshal(rmsg, &l3n4AddrID); err != nil { return err } oldL3n4ID := l3n4AddrID.ID l3n4AddrID.ID = 0 // update the value in the kvstore if err := updateL3n4AddrIDRef(oldL3n4ID, l3n4AddrID); err != nil { return err } marshaledL3n4AddrID, err := json.Marshal(l3n4AddrID) if err != nil { return err } return kvstore.Client().Set(svcPath, marshaledL3n4AddrID) }
[ "func", "deleteL3n4AddrIDBySHA256", "(", "sha256Sum", "string", ")", "error", "{", "log", ".", "WithField", "(", "logfields", ".", "SHA", ",", "sha256Sum", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "if", "sha256Sum", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n", "svcPath", ":=", "path", ".", "Join", "(", "common", ".", "ServicesKeyPath", ",", "sha256Sum", ")", "\n", "// Lock that sha256Sum", "lockKey", ",", "err", ":=", "kvstore", ".", "LockPath", "(", "context", ".", "Background", "(", ")", ",", "svcPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "lockKey", ".", "Unlock", "(", ")", "\n\n", "// After lock complete, get label's path", "rmsg", ",", "err", ":=", "kvstore", ".", "Client", "(", ")", ".", "Get", "(", "svcPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "rmsg", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "var", "l3n4AddrID", "loadbalancer", ".", "L3n4AddrID", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "rmsg", ",", "&", "l3n4AddrID", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "oldL3n4ID", ":=", "l3n4AddrID", ".", "ID", "\n", "l3n4AddrID", ".", "ID", "=", "0", "\n\n", "// update the value in the kvstore", "if", "err", ":=", "updateL3n4AddrIDRef", "(", "oldL3n4ID", ",", "l3n4AddrID", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "marshaledL3n4AddrID", ",", "err", ":=", "json", ".", "Marshal", "(", "l3n4AddrID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "kvstore", ".", "Client", "(", ")", ".", "Set", "(", "svcPath", ",", "marshaledL3n4AddrID", ")", "\n", "}" ]
// deleteL3n4AddrIDBySHA256 deletes the L3n4AddrID from the kvstore corresponding to the service's // sha256Sum.
[ "deleteL3n4AddrIDBySHA256", "deletes", "the", "L3n4AddrID", "from", "the", "kvstore", "corresponding", "to", "the", "service", "s", "sha256Sum", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/service/id_kvstore.go#L290-L328
162,833
cilium/cilium
pkg/bpf/map_register_linux.go
GetMap
func GetMap(name string) *Map { mutex.RLock() defer mutex.RUnlock() if !path.IsAbs(name) { name = MapPath(name) } return mapRegister[name] }
go
func GetMap(name string) *Map { mutex.RLock() defer mutex.RUnlock() if !path.IsAbs(name) { name = MapPath(name) } return mapRegister[name] }
[ "func", "GetMap", "(", "name", "string", ")", "*", "Map", "{", "mutex", ".", "RLock", "(", ")", "\n", "defer", "mutex", ".", "RUnlock", "(", ")", "\n\n", "if", "!", "path", ".", "IsAbs", "(", "name", ")", "{", "name", "=", "MapPath", "(", "name", ")", "\n", "}", "\n\n", "return", "mapRegister", "[", "name", "]", "\n", "}" ]
// GetMap returns the registered map with the given name or absolute path
[ "GetMap", "returns", "the", "registered", "map", "with", "the", "given", "name", "or", "absolute", "path" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/bpf/map_register_linux.go#L48-L57
162,834
cilium/cilium
api/v1/server/restapi/policy/get_fqdn_cache_id.go
NewGetFqdnCacheID
func NewGetFqdnCacheID(ctx *middleware.Context, handler GetFqdnCacheIDHandler) *GetFqdnCacheID { return &GetFqdnCacheID{Context: ctx, Handler: handler} }
go
func NewGetFqdnCacheID(ctx *middleware.Context, handler GetFqdnCacheIDHandler) *GetFqdnCacheID { return &GetFqdnCacheID{Context: ctx, Handler: handler} }
[ "func", "NewGetFqdnCacheID", "(", "ctx", "*", "middleware", ".", "Context", ",", "handler", "GetFqdnCacheIDHandler", ")", "*", "GetFqdnCacheID", "{", "return", "&", "GetFqdnCacheID", "{", "Context", ":", "ctx", ",", "Handler", ":", "handler", "}", "\n", "}" ]
// NewGetFqdnCacheID creates a new http.Handler for the get fqdn cache ID operation
[ "NewGetFqdnCacheID", "creates", "a", "new", "http", ".", "Handler", "for", "the", "get", "fqdn", "cache", "ID", "operation" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/api/v1/server/restapi/policy/get_fqdn_cache_id.go#L28-L30
162,835
cilium/cilium
api/v1/client/policy/get_fqdn_cache_parameters.go
WithTimeout
func (o *GetFqdnCacheParams) WithTimeout(timeout time.Duration) *GetFqdnCacheParams { o.SetTimeout(timeout) return o }
go
func (o *GetFqdnCacheParams) WithTimeout(timeout time.Duration) *GetFqdnCacheParams { o.SetTimeout(timeout) return o }
[ "func", "(", "o", "*", "GetFqdnCacheParams", ")", "WithTimeout", "(", "timeout", "time", ".", "Duration", ")", "*", "GetFqdnCacheParams", "{", "o", ".", "SetTimeout", "(", "timeout", ")", "\n", "return", "o", "\n", "}" ]
// WithTimeout adds the timeout to the get fqdn cache params
[ "WithTimeout", "adds", "the", "timeout", "to", "the", "get", "fqdn", "cache", "params" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/api/v1/client/policy/get_fqdn_cache_parameters.go#L81-L84
162,836
cilium/cilium
api/v1/client/policy/get_fqdn_cache_parameters.go
WithContext
func (o *GetFqdnCacheParams) WithContext(ctx context.Context) *GetFqdnCacheParams { o.SetContext(ctx) return o }
go
func (o *GetFqdnCacheParams) WithContext(ctx context.Context) *GetFqdnCacheParams { o.SetContext(ctx) return o }
[ "func", "(", "o", "*", "GetFqdnCacheParams", ")", "WithContext", "(", "ctx", "context", ".", "Context", ")", "*", "GetFqdnCacheParams", "{", "o", ".", "SetContext", "(", "ctx", ")", "\n", "return", "o", "\n", "}" ]
// WithContext adds the context to the get fqdn cache params
[ "WithContext", "adds", "the", "context", "to", "the", "get", "fqdn", "cache", "params" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/api/v1/client/policy/get_fqdn_cache_parameters.go#L92-L95
162,837
cilium/cilium
api/v1/client/policy/get_fqdn_cache_parameters.go
WithHTTPClient
func (o *GetFqdnCacheParams) WithHTTPClient(client *http.Client) *GetFqdnCacheParams { o.SetHTTPClient(client) return o }
go
func (o *GetFqdnCacheParams) WithHTTPClient(client *http.Client) *GetFqdnCacheParams { o.SetHTTPClient(client) return o }
[ "func", "(", "o", "*", "GetFqdnCacheParams", ")", "WithHTTPClient", "(", "client", "*", "http", ".", "Client", ")", "*", "GetFqdnCacheParams", "{", "o", ".", "SetHTTPClient", "(", "client", ")", "\n", "return", "o", "\n", "}" ]
// WithHTTPClient adds the HTTPClient to the get fqdn cache params
[ "WithHTTPClient", "adds", "the", "HTTPClient", "to", "the", "get", "fqdn", "cache", "params" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/api/v1/client/policy/get_fqdn_cache_parameters.go#L103-L106
162,838
cilium/cilium
api/v1/client/policy/get_fqdn_cache_parameters.go
WithCidr
func (o *GetFqdnCacheParams) WithCidr(cidr *string) *GetFqdnCacheParams { o.SetCidr(cidr) return o }
go
func (o *GetFqdnCacheParams) WithCidr(cidr *string) *GetFqdnCacheParams { o.SetCidr(cidr) return o }
[ "func", "(", "o", "*", "GetFqdnCacheParams", ")", "WithCidr", "(", "cidr", "*", "string", ")", "*", "GetFqdnCacheParams", "{", "o", ".", "SetCidr", "(", "cidr", ")", "\n", "return", "o", "\n", "}" ]
// WithCidr adds the cidr to the get fqdn cache params
[ "WithCidr", "adds", "the", "cidr", "to", "the", "get", "fqdn", "cache", "params" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/api/v1/client/policy/get_fqdn_cache_parameters.go#L114-L117
162,839
cilium/cilium
api/v1/client/policy/get_fqdn_cache_parameters.go
WithMatchpattern
func (o *GetFqdnCacheParams) WithMatchpattern(matchpattern *string) *GetFqdnCacheParams { o.SetMatchpattern(matchpattern) return o }
go
func (o *GetFqdnCacheParams) WithMatchpattern(matchpattern *string) *GetFqdnCacheParams { o.SetMatchpattern(matchpattern) return o }
[ "func", "(", "o", "*", "GetFqdnCacheParams", ")", "WithMatchpattern", "(", "matchpattern", "*", "string", ")", "*", "GetFqdnCacheParams", "{", "o", ".", "SetMatchpattern", "(", "matchpattern", ")", "\n", "return", "o", "\n", "}" ]
// WithMatchpattern adds the matchpattern to the get fqdn cache params
[ "WithMatchpattern", "adds", "the", "matchpattern", "to", "the", "get", "fqdn", "cache", "params" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/api/v1/client/policy/get_fqdn_cache_parameters.go#L125-L128
162,840
cilium/cilium
pkg/metrics/logging_hook.go
NewLoggingHook
func NewLoggingHook(component string) *LoggingHook { // NOTE(mrostecki): For now errors and warning metric exists only for Cilium // daemon, but support of Prometheus metrics in some other components (i.e. // cilium-health - GH-4268) is planned. // Pick a metric for the component. var metric *prometheus.CounterVec switch component { case components.CiliumAgentName: metric = ErrorsWarnings default: panic(fmt.Sprintf("component %s is unsupported by LoggingHook", component)) } return &LoggingHook{metric: metric} }
go
func NewLoggingHook(component string) *LoggingHook { // NOTE(mrostecki): For now errors and warning metric exists only for Cilium // daemon, but support of Prometheus metrics in some other components (i.e. // cilium-health - GH-4268) is planned. // Pick a metric for the component. var metric *prometheus.CounterVec switch component { case components.CiliumAgentName: metric = ErrorsWarnings default: panic(fmt.Sprintf("component %s is unsupported by LoggingHook", component)) } return &LoggingHook{metric: metric} }
[ "func", "NewLoggingHook", "(", "component", "string", ")", "*", "LoggingHook", "{", "// NOTE(mrostecki): For now errors and warning metric exists only for Cilium", "// daemon, but support of Prometheus metrics in some other components (i.e.", "// cilium-health - GH-4268) is planned.", "// Pick a metric for the component.", "var", "metric", "*", "prometheus", ".", "CounterVec", "\n", "switch", "component", "{", "case", "components", ".", "CiliumAgentName", ":", "metric", "=", "ErrorsWarnings", "\n", "default", ":", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "component", ")", ")", "\n", "}", "\n\n", "return", "&", "LoggingHook", "{", "metric", ":", "metric", "}", "\n", "}" ]
// NewLoggingHook returns a new instance of LoggingHook for the given Cilium // component.
[ "NewLoggingHook", "returns", "a", "new", "instance", "of", "LoggingHook", "for", "the", "given", "Cilium", "component", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/metrics/logging_hook.go#L36-L51
162,841
cilium/cilium
pkg/metrics/logging_hook.go
Levels
func (h *LoggingHook) Levels() []logrus.Level { return []logrus.Level{ logrus.ErrorLevel, logrus.WarnLevel, } }
go
func (h *LoggingHook) Levels() []logrus.Level { return []logrus.Level{ logrus.ErrorLevel, logrus.WarnLevel, } }
[ "func", "(", "h", "*", "LoggingHook", ")", "Levels", "(", ")", "[", "]", "logrus", ".", "Level", "{", "return", "[", "]", "logrus", ".", "Level", "{", "logrus", ".", "ErrorLevel", ",", "logrus", ".", "WarnLevel", ",", "}", "\n", "}" ]
// Levels returns the list of logging levels on which the hook is triggered.
[ "Levels", "returns", "the", "list", "of", "logging", "levels", "on", "which", "the", "hook", "is", "triggered", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/metrics/logging_hook.go#L54-L59
162,842
cilium/cilium
pkg/metrics/logging_hook.go
Fire
func (h *LoggingHook) Fire(entry *logrus.Entry) error { // Get information about subsystem from logging entry field. iSubsystem, ok := entry.Data[logfields.LogSubsys] if !ok { serializedEntry, err := entry.String() if err != nil { return fmt.Errorf("log entry cannot be serialized and doesn't contain 'subsys' field") } return fmt.Errorf("log entry doesn't contain 'subsys' field: %s", serializedEntry) } subsystem, ok := iSubsystem.(string) if !ok { return fmt.Errorf("type of the 'subsystem' log entry field is not string but %s", reflect.TypeOf(iSubsystem)) } // Increment the metric. h.metric.WithLabelValues(entry.Level.String(), subsystem).Inc() return nil }
go
func (h *LoggingHook) Fire(entry *logrus.Entry) error { // Get information about subsystem from logging entry field. iSubsystem, ok := entry.Data[logfields.LogSubsys] if !ok { serializedEntry, err := entry.String() if err != nil { return fmt.Errorf("log entry cannot be serialized and doesn't contain 'subsys' field") } return fmt.Errorf("log entry doesn't contain 'subsys' field: %s", serializedEntry) } subsystem, ok := iSubsystem.(string) if !ok { return fmt.Errorf("type of the 'subsystem' log entry field is not string but %s", reflect.TypeOf(iSubsystem)) } // Increment the metric. h.metric.WithLabelValues(entry.Level.String(), subsystem).Inc() return nil }
[ "func", "(", "h", "*", "LoggingHook", ")", "Fire", "(", "entry", "*", "logrus", ".", "Entry", ")", "error", "{", "// Get information about subsystem from logging entry field.", "iSubsystem", ",", "ok", ":=", "entry", ".", "Data", "[", "logfields", ".", "LogSubsys", "]", "\n", "if", "!", "ok", "{", "serializedEntry", ",", "err", ":=", "entry", ".", "String", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "serializedEntry", ")", "\n", "}", "\n", "subsystem", ",", "ok", ":=", "iSubsystem", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "iSubsystem", ")", ")", "\n", "}", "\n\n", "// Increment the metric.", "h", ".", "metric", ".", "WithLabelValues", "(", "entry", ".", "Level", ".", "String", "(", ")", ",", "subsystem", ")", ".", "Inc", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// Fire is the main method which is called every time when logger has an error // or warning message.
[ "Fire", "is", "the", "main", "method", "which", "is", "called", "every", "time", "when", "logger", "has", "an", "error", "or", "warning", "message", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/metrics/logging_hook.go#L63-L82
162,843
cilium/cilium
api/v1/server/restapi/policy/get_policy.go
NewGetPolicy
func NewGetPolicy(ctx *middleware.Context, handler GetPolicyHandler) *GetPolicy { return &GetPolicy{Context: ctx, Handler: handler} }
go
func NewGetPolicy(ctx *middleware.Context, handler GetPolicyHandler) *GetPolicy { return &GetPolicy{Context: ctx, Handler: handler} }
[ "func", "NewGetPolicy", "(", "ctx", "*", "middleware", ".", "Context", ",", "handler", "GetPolicyHandler", ")", "*", "GetPolicy", "{", "return", "&", "GetPolicy", "{", "Context", ":", "ctx", ",", "Handler", ":", "handler", "}", "\n", "}" ]
// NewGetPolicy creates a new http.Handler for the get policy operation
[ "NewGetPolicy", "creates", "a", "new", "http", ".", "Handler", "for", "the", "get", "policy", "operation" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/api/v1/server/restapi/policy/get_policy.go#L28-L30
162,844
cilium/cilium
api/v1/server/restapi/endpoint/put_endpoint_id_responses.go
WithPayload
func (o *PutEndpointIDInvalid) WithPayload(payload models.Error) *PutEndpointIDInvalid { o.Payload = payload return o }
go
func (o *PutEndpointIDInvalid) WithPayload(payload models.Error) *PutEndpointIDInvalid { o.Payload = payload return o }
[ "func", "(", "o", "*", "PutEndpointIDInvalid", ")", "WithPayload", "(", "payload", "models", ".", "Error", ")", "*", "PutEndpointIDInvalid", "{", "o", ".", "Payload", "=", "payload", "\n", "return", "o", "\n", "}" ]
// WithPayload adds the payload to the put endpoint Id invalid response
[ "WithPayload", "adds", "the", "payload", "to", "the", "put", "endpoint", "Id", "invalid", "response" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/api/v1/server/restapi/endpoint/put_endpoint_id_responses.go#L62-L65
162,845
cilium/cilium
api/v1/server/restapi/endpoint/put_endpoint_id_responses.go
WithPayload
func (o *PutEndpointIDFailed) WithPayload(payload models.Error) *PutEndpointIDFailed { o.Payload = payload return o }
go
func (o *PutEndpointIDFailed) WithPayload(payload models.Error) *PutEndpointIDFailed { o.Payload = payload return o }
[ "func", "(", "o", "*", "PutEndpointIDFailed", ")", "WithPayload", "(", "payload", "models", ".", "Error", ")", "*", "PutEndpointIDFailed", "{", "o", ".", "Payload", "=", "payload", "\n", "return", "o", "\n", "}" ]
// WithPayload adds the payload to the put endpoint Id failed response
[ "WithPayload", "adds", "the", "payload", "to", "the", "put", "endpoint", "Id", "failed", "response" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/api/v1/server/restapi/endpoint/put_endpoint_id_responses.go#L128-L131
162,846
cilium/cilium
pkg/health/server/server.go
getNodes
func (s *Server) getNodes() (nodeMap, error) { scopedLog := log if s.CiliumURI != "" { scopedLog = log.WithField("URI", s.CiliumURI) } scopedLog.Debug("Sending request for /healthz ...") resp, err := s.Daemon.GetHealthz(nil) if err != nil { return nil, fmt.Errorf("unable to get agent health: %s", err) } log.Debug("Got cilium /healthz") if resp == nil || resp.Payload == nil || resp.Payload.Cluster == nil { return nil, fmt.Errorf("received nil health response") } if resp.Payload.Cluster.Self != "" { s.RWMutex.Lock() s.localStatus = &healthModels.SelfStatus{ Name: resp.Payload.Cluster.Self, } s.RWMutex.Unlock() } nodes := make(nodeMap) for _, n := range resp.Payload.Cluster.Nodes { if n.PrimaryAddress != nil { if n.PrimaryAddress.IPV4 != nil { nodes[ipString(n.PrimaryAddress.IPV4.IP)] = NewHealthNode(n) } if n.PrimaryAddress.IPV6 != nil { nodes[ipString(n.PrimaryAddress.IPV6.IP)] = NewHealthNode(n) } } for _, addr := range n.SecondaryAddresses { nodes[ipString(addr.IP)] = NewHealthNode(n) } if n.HealthEndpointAddress != nil { if n.HealthEndpointAddress.IPV4 != nil { nodes[ipString(n.HealthEndpointAddress.IPV4.IP)] = NewHealthNode(n) } if n.HealthEndpointAddress.IPV6 != nil { nodes[ipString(n.HealthEndpointAddress.IPV6.IP)] = NewHealthNode(n) } } } return nodes, nil }
go
func (s *Server) getNodes() (nodeMap, error) { scopedLog := log if s.CiliumURI != "" { scopedLog = log.WithField("URI", s.CiliumURI) } scopedLog.Debug("Sending request for /healthz ...") resp, err := s.Daemon.GetHealthz(nil) if err != nil { return nil, fmt.Errorf("unable to get agent health: %s", err) } log.Debug("Got cilium /healthz") if resp == nil || resp.Payload == nil || resp.Payload.Cluster == nil { return nil, fmt.Errorf("received nil health response") } if resp.Payload.Cluster.Self != "" { s.RWMutex.Lock() s.localStatus = &healthModels.SelfStatus{ Name: resp.Payload.Cluster.Self, } s.RWMutex.Unlock() } nodes := make(nodeMap) for _, n := range resp.Payload.Cluster.Nodes { if n.PrimaryAddress != nil { if n.PrimaryAddress.IPV4 != nil { nodes[ipString(n.PrimaryAddress.IPV4.IP)] = NewHealthNode(n) } if n.PrimaryAddress.IPV6 != nil { nodes[ipString(n.PrimaryAddress.IPV6.IP)] = NewHealthNode(n) } } for _, addr := range n.SecondaryAddresses { nodes[ipString(addr.IP)] = NewHealthNode(n) } if n.HealthEndpointAddress != nil { if n.HealthEndpointAddress.IPV4 != nil { nodes[ipString(n.HealthEndpointAddress.IPV4.IP)] = NewHealthNode(n) } if n.HealthEndpointAddress.IPV6 != nil { nodes[ipString(n.HealthEndpointAddress.IPV6.IP)] = NewHealthNode(n) } } } return nodes, nil }
[ "func", "(", "s", "*", "Server", ")", "getNodes", "(", ")", "(", "nodeMap", ",", "error", ")", "{", "scopedLog", ":=", "log", "\n", "if", "s", ".", "CiliumURI", "!=", "\"", "\"", "{", "scopedLog", "=", "log", ".", "WithField", "(", "\"", "\"", ",", "s", ".", "CiliumURI", ")", "\n", "}", "\n", "scopedLog", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "resp", ",", "err", ":=", "s", ".", "Daemon", ".", "GetHealthz", "(", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "log", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "if", "resp", "==", "nil", "||", "resp", ".", "Payload", "==", "nil", "||", "resp", ".", "Payload", ".", "Cluster", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "resp", ".", "Payload", ".", "Cluster", ".", "Self", "!=", "\"", "\"", "{", "s", ".", "RWMutex", ".", "Lock", "(", ")", "\n", "s", ".", "localStatus", "=", "&", "healthModels", ".", "SelfStatus", "{", "Name", ":", "resp", ".", "Payload", ".", "Cluster", ".", "Self", ",", "}", "\n", "s", ".", "RWMutex", ".", "Unlock", "(", ")", "\n", "}", "\n\n", "nodes", ":=", "make", "(", "nodeMap", ")", "\n", "for", "_", ",", "n", ":=", "range", "resp", ".", "Payload", ".", "Cluster", ".", "Nodes", "{", "if", "n", ".", "PrimaryAddress", "!=", "nil", "{", "if", "n", ".", "PrimaryAddress", ".", "IPV4", "!=", "nil", "{", "nodes", "[", "ipString", "(", "n", ".", "PrimaryAddress", ".", "IPV4", ".", "IP", ")", "]", "=", "NewHealthNode", "(", "n", ")", "\n", "}", "\n", "if", "n", ".", "PrimaryAddress", ".", "IPV6", "!=", "nil", "{", "nodes", "[", "ipString", "(", "n", ".", "PrimaryAddress", ".", "IPV6", ".", "IP", ")", "]", "=", "NewHealthNode", "(", "n", ")", "\n", "}", "\n", "}", "\n", "for", "_", ",", "addr", ":=", "range", "n", ".", "SecondaryAddresses", "{", "nodes", "[", "ipString", "(", "addr", ".", "IP", ")", "]", "=", "NewHealthNode", "(", "n", ")", "\n", "}", "\n", "if", "n", ".", "HealthEndpointAddress", "!=", "nil", "{", "if", "n", ".", "HealthEndpointAddress", ".", "IPV4", "!=", "nil", "{", "nodes", "[", "ipString", "(", "n", ".", "HealthEndpointAddress", ".", "IPV4", ".", "IP", ")", "]", "=", "NewHealthNode", "(", "n", ")", "\n", "}", "\n", "if", "n", ".", "HealthEndpointAddress", ".", "IPV6", "!=", "nil", "{", "nodes", "[", "ipString", "(", "n", ".", "HealthEndpointAddress", ".", "IPV6", ".", "IP", ")", "]", "=", "NewHealthNode", "(", "n", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nodes", ",", "nil", "\n", "}" ]
// getNodes fetches the latest set of nodes in the cluster from the Cilium // daemon, and updates the Server's 'nodes' map.
[ "getNodes", "fetches", "the", "latest", "set", "of", "nodes", "in", "the", "cluster", "from", "the", "Cilium", "daemon", "and", "updates", "the", "Server", "s", "nodes", "map", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/health/server/server.go#L104-L152
162,847
cilium/cilium
pkg/health/server/server.go
updateCluster
func (s *Server) updateCluster(report *healthReport) { s.Lock() defer s.Unlock() if s.connectivity.startTime.Before(report.startTime) { s.connectivity = report } }
go
func (s *Server) updateCluster(report *healthReport) { s.Lock() defer s.Unlock() if s.connectivity.startTime.Before(report.startTime) { s.connectivity = report } }
[ "func", "(", "s", "*", "Server", ")", "updateCluster", "(", "report", "*", "healthReport", ")", "{", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n\n", "if", "s", ".", "connectivity", ".", "startTime", ".", "Before", "(", "report", ".", "startTime", ")", "{", "s", ".", "connectivity", "=", "report", "\n", "}", "\n", "}" ]
// updateCluster makes the specified health report visible to the API. // // It only updates the server's API-visible health report if the provided // report started after the current report.
[ "updateCluster", "makes", "the", "specified", "health", "report", "visible", "to", "the", "API", ".", "It", "only", "updates", "the", "server", "s", "API", "-", "visible", "health", "report", "if", "the", "provided", "report", "started", "after", "the", "current", "report", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/health/server/server.go#L158-L165
162,848
cilium/cilium
pkg/health/server/server.go
GetStatusResponse
func (s *Server) GetStatusResponse() *healthModels.HealthStatusResponse { s.RLock() defer s.RUnlock() var name string // Check if localStatus is populated already. If not, the name is empty if s.localStatus != nil { name = s.localStatus.Name } return &healthModels.HealthStatusResponse{ Local: &healthModels.SelfStatus{ Name: name, }, Nodes: s.connectivity.nodes, Timestamp: s.connectivity.startTime.Format(time.RFC3339), } }
go
func (s *Server) GetStatusResponse() *healthModels.HealthStatusResponse { s.RLock() defer s.RUnlock() var name string // Check if localStatus is populated already. If not, the name is empty if s.localStatus != nil { name = s.localStatus.Name } return &healthModels.HealthStatusResponse{ Local: &healthModels.SelfStatus{ Name: name, }, Nodes: s.connectivity.nodes, Timestamp: s.connectivity.startTime.Format(time.RFC3339), } }
[ "func", "(", "s", "*", "Server", ")", "GetStatusResponse", "(", ")", "*", "healthModels", ".", "HealthStatusResponse", "{", "s", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "RUnlock", "(", ")", "\n\n", "var", "name", "string", "\n", "// Check if localStatus is populated already. If not, the name is empty", "if", "s", ".", "localStatus", "!=", "nil", "{", "name", "=", "s", ".", "localStatus", ".", "Name", "\n", "}", "\n\n", "return", "&", "healthModels", ".", "HealthStatusResponse", "{", "Local", ":", "&", "healthModels", ".", "SelfStatus", "{", "Name", ":", "name", ",", "}", ",", "Nodes", ":", "s", ".", "connectivity", ".", "nodes", ",", "Timestamp", ":", "s", ".", "connectivity", ".", "startTime", ".", "Format", "(", "time", ".", "RFC3339", ")", ",", "}", "\n", "}" ]
// GetStatusResponse returns the most recent cluster connectivity status.
[ "GetStatusResponse", "returns", "the", "most", "recent", "cluster", "connectivity", "status", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/health/server/server.go#L168-L185
162,849
cilium/cilium
pkg/health/server/server.go
FetchStatusResponse
func (s *Server) FetchStatusResponse() (*healthModels.HealthStatusResponse, error) { nodes, err := s.getNodes() if err != nil { return nil, err } prober := newProber(s, nodes) if err := prober.Run(); err != nil { log.WithError(err).Info("Failed to run ping") return nil, err } log.Debug("Run complete") s.updateCluster(prober.getResults()) return s.GetStatusResponse(), nil }
go
func (s *Server) FetchStatusResponse() (*healthModels.HealthStatusResponse, error) { nodes, err := s.getNodes() if err != nil { return nil, err } prober := newProber(s, nodes) if err := prober.Run(); err != nil { log.WithError(err).Info("Failed to run ping") return nil, err } log.Debug("Run complete") s.updateCluster(prober.getResults()) return s.GetStatusResponse(), nil }
[ "func", "(", "s", "*", "Server", ")", "FetchStatusResponse", "(", ")", "(", "*", "healthModels", ".", "HealthStatusResponse", ",", "error", ")", "{", "nodes", ",", "err", ":=", "s", ".", "getNodes", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "prober", ":=", "newProber", "(", "s", ",", "nodes", ")", "\n", "if", "err", ":=", "prober", ".", "Run", "(", ")", ";", "err", "!=", "nil", "{", "log", ".", "WithError", "(", "err", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "log", ".", "Debug", "(", "\"", "\"", ")", "\n", "s", ".", "updateCluster", "(", "prober", ".", "getResults", "(", ")", ")", "\n\n", "return", "s", ".", "GetStatusResponse", "(", ")", ",", "nil", "\n", "}" ]
// FetchStatusResponse updates the cluster with the latest set of nodes, // runs a synchronous probe across the cluster, updates the connectivity cache // and returns the results.
[ "FetchStatusResponse", "updates", "the", "cluster", "with", "the", "latest", "set", "of", "nodes", "runs", "a", "synchronous", "probe", "across", "the", "cluster", "updates", "the", "connectivity", "cache", "and", "returns", "the", "results", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/health/server/server.go#L190-L205
162,850
cilium/cilium
pkg/health/server/server.go
NewServer
func NewServer(config Config) (*Server, error) { server := &Server{ startTime: time.Now(), Config: config, tcpServers: []*healthApi.Server{}, connectivity: &healthReport{}, } swaggerSpec, err := loads.Analyzed(healthApi.SwaggerJSON, "") if err != nil { return nil, err } if !config.Passive { cl, err := ciliumPkg.NewClient(config.CiliumURI) if err != nil { return nil, err } server.Client = cl server.Server = *server.newServer(swaggerSpec, 0) } for port := range PortToPaths { srv := server.newServer(swaggerSpec, port) server.tcpServers = append(server.tcpServers, srv) } return server, nil }
go
func NewServer(config Config) (*Server, error) { server := &Server{ startTime: time.Now(), Config: config, tcpServers: []*healthApi.Server{}, connectivity: &healthReport{}, } swaggerSpec, err := loads.Analyzed(healthApi.SwaggerJSON, "") if err != nil { return nil, err } if !config.Passive { cl, err := ciliumPkg.NewClient(config.CiliumURI) if err != nil { return nil, err } server.Client = cl server.Server = *server.newServer(swaggerSpec, 0) } for port := range PortToPaths { srv := server.newServer(swaggerSpec, port) server.tcpServers = append(server.tcpServers, srv) } return server, nil }
[ "func", "NewServer", "(", "config", "Config", ")", "(", "*", "Server", ",", "error", ")", "{", "server", ":=", "&", "Server", "{", "startTime", ":", "time", ".", "Now", "(", ")", ",", "Config", ":", "config", ",", "tcpServers", ":", "[", "]", "*", "healthApi", ".", "Server", "{", "}", ",", "connectivity", ":", "&", "healthReport", "{", "}", ",", "}", "\n\n", "swaggerSpec", ",", "err", ":=", "loads", ".", "Analyzed", "(", "healthApi", ".", "SwaggerJSON", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "!", "config", ".", "Passive", "{", "cl", ",", "err", ":=", "ciliumPkg", ".", "NewClient", "(", "config", ".", "CiliumURI", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "server", ".", "Client", "=", "cl", "\n", "server", ".", "Server", "=", "*", "server", ".", "newServer", "(", "swaggerSpec", ",", "0", ")", "\n", "}", "\n", "for", "port", ":=", "range", "PortToPaths", "{", "srv", ":=", "server", ".", "newServer", "(", "swaggerSpec", ",", "port", ")", "\n", "server", ".", "tcpServers", "=", "append", "(", "server", ".", "tcpServers", ",", "srv", ")", "\n", "}", "\n\n", "return", "server", ",", "nil", "\n", "}" ]
// NewServer creates a server to handle health requests.
[ "NewServer", "creates", "a", "server", "to", "handle", "health", "requests", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/health/server/server.go#L315-L343
162,851
cilium/cilium
pkg/policy/groups/controllers.go
UpdateCNPInformation
func UpdateCNPInformation() { cnpToUpdate := groupsCNPCache.GetAllCNP() sem := make(chan bool, maxConcurrentUpdates) for _, cnp := range cnpToUpdate { sem <- true go func(cnp *cilium_v2.CiliumNetworkPolicy) { defer func() { <-sem }() addDerivativeCNP(cnp) }(cnp) } }
go
func UpdateCNPInformation() { cnpToUpdate := groupsCNPCache.GetAllCNP() sem := make(chan bool, maxConcurrentUpdates) for _, cnp := range cnpToUpdate { sem <- true go func(cnp *cilium_v2.CiliumNetworkPolicy) { defer func() { <-sem }() addDerivativeCNP(cnp) }(cnp) } }
[ "func", "UpdateCNPInformation", "(", ")", "{", "cnpToUpdate", ":=", "groupsCNPCache", ".", "GetAllCNP", "(", ")", "\n", "sem", ":=", "make", "(", "chan", "bool", ",", "maxConcurrentUpdates", ")", "\n", "for", "_", ",", "cnp", ":=", "range", "cnpToUpdate", "{", "sem", "<-", "true", "\n", "go", "func", "(", "cnp", "*", "cilium_v2", ".", "CiliumNetworkPolicy", ")", "{", "defer", "func", "(", ")", "{", "<-", "sem", "}", "(", ")", "\n", "addDerivativeCNP", "(", "cnp", ")", "\n\n", "}", "(", "cnp", ")", "\n", "}", "\n", "}" ]
// UpdateCNPInformation retrieves all the CNP that has currently a derivative // policy and creates the new derivatives policies with the latest information // from providers. To avoid issues with rate-limiting this function will // execute the addDerivative function with a max number of concurrent calls, // defined on maxConcurrentUpdates.
[ "UpdateCNPInformation", "retrieves", "all", "the", "CNP", "that", "has", "currently", "a", "derivative", "policy", "and", "creates", "the", "new", "derivatives", "policies", "with", "the", "latest", "information", "from", "providers", ".", "To", "avoid", "issues", "with", "rate", "-", "limiting", "this", "function", "will", "execute", "the", "addDerivative", "function", "with", "a", "max", "number", "of", "concurrent", "calls", "defined", "on", "maxConcurrentUpdates", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/policy/groups/controllers.go#L30-L42
162,852
cilium/cilium
pkg/fqdn/cache.go
isExpiredBy
func (entry *cacheEntry) isExpiredBy(pointInTime time.Time) bool { return pointInTime.After(entry.ExpirationTime) }
go
func (entry *cacheEntry) isExpiredBy(pointInTime time.Time) bool { return pointInTime.After(entry.ExpirationTime) }
[ "func", "(", "entry", "*", "cacheEntry", ")", "isExpiredBy", "(", "pointInTime", "time", ".", "Time", ")", "bool", "{", "return", "pointInTime", ".", "After", "(", "entry", ".", "ExpirationTime", ")", "\n", "}" ]
// isExpiredBy returns true if entry is no longer valid at pointInTime
[ "isExpiredBy", "returns", "true", "if", "entry", "is", "no", "longer", "valid", "at", "pointInTime" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/fqdn/cache.go#L58-L60
162,853
cilium/cilium
pkg/fqdn/cache.go
getIPs
func (s ipEntries) getIPs(now time.Time) []net.IP { ips := make([]net.IP, 0, len(s)) // worst case size for ip, entry := range s { if entry != nil && !entry.isExpiredBy(now) { ips = append(ips, net.ParseIP(ip)) } } return ip.KeepUniqueIPs(ips) // sorts IPs }
go
func (s ipEntries) getIPs(now time.Time) []net.IP { ips := make([]net.IP, 0, len(s)) // worst case size for ip, entry := range s { if entry != nil && !entry.isExpiredBy(now) { ips = append(ips, net.ParseIP(ip)) } } return ip.KeepUniqueIPs(ips) // sorts IPs }
[ "func", "(", "s", "ipEntries", ")", "getIPs", "(", "now", "time", ".", "Time", ")", "[", "]", "net", ".", "IP", "{", "ips", ":=", "make", "(", "[", "]", "net", ".", "IP", ",", "0", ",", "len", "(", "s", ")", ")", "// worst case size", "\n", "for", "ip", ",", "entry", ":=", "range", "s", "{", "if", "entry", "!=", "nil", "&&", "!", "entry", ".", "isExpiredBy", "(", "now", ")", "{", "ips", "=", "append", "(", "ips", ",", "net", ".", "ParseIP", "(", "ip", ")", ")", "\n", "}", "\n", "}", "\n\n", "return", "ip", ".", "KeepUniqueIPs", "(", "ips", ")", "// sorts IPs", "\n", "}" ]
// getIPs returns a sorted list of non-expired unique IPs. // This needs a read-lock
[ "getIPs", "returns", "a", "sorted", "list", "of", "non", "-", "expired", "unique", "IPs", ".", "This", "needs", "a", "read", "-", "lock" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/fqdn/cache.go#L80-L89
162,854
cilium/cilium
pkg/fqdn/cache.go
NewDNSCache
func NewDNSCache(minTTL int) *DNSCache { c := &DNSCache{ forward: make(map[string]ipEntries), reverse: make(map[string]nameEntries), lastCleanup: time.Now(), cleanup: map[int64][]string{}, overLimit: map[string]bool{}, perHostLimit: 0, minTTL: minTTL, } return c }
go
func NewDNSCache(minTTL int) *DNSCache { c := &DNSCache{ forward: make(map[string]ipEntries), reverse: make(map[string]nameEntries), lastCleanup: time.Now(), cleanup: map[int64][]string{}, overLimit: map[string]bool{}, perHostLimit: 0, minTTL: minTTL, } return c }
[ "func", "NewDNSCache", "(", "minTTL", "int", ")", "*", "DNSCache", "{", "c", ":=", "&", "DNSCache", "{", "forward", ":", "make", "(", "map", "[", "string", "]", "ipEntries", ")", ",", "reverse", ":", "make", "(", "map", "[", "string", "]", "nameEntries", ")", ",", "lastCleanup", ":", "time", ".", "Now", "(", ")", ",", "cleanup", ":", "map", "[", "int64", "]", "[", "]", "string", "{", "}", ",", "overLimit", ":", "map", "[", "string", "]", "bool", "{", "}", ",", "perHostLimit", ":", "0", ",", "minTTL", ":", "minTTL", ",", "}", "\n", "return", "c", "\n", "}" ]
// NewDNSCache returns an initialized DNSCache
[ "NewDNSCache", "returns", "an", "initialized", "DNSCache" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/fqdn/cache.go#L143-L154
162,855
cilium/cilium
pkg/fqdn/cache.go
NewDNSCacheWithLimit
func NewDNSCacheWithLimit(minTTL int, limit int) *DNSCache { c := NewDNSCache(minTTL) c.perHostLimit = limit return c }
go
func NewDNSCacheWithLimit(minTTL int, limit int) *DNSCache { c := NewDNSCache(minTTL) c.perHostLimit = limit return c }
[ "func", "NewDNSCacheWithLimit", "(", "minTTL", "int", ",", "limit", "int", ")", "*", "DNSCache", "{", "c", ":=", "NewDNSCache", "(", "minTTL", ")", "\n", "c", ".", "perHostLimit", "=", "limit", "\n", "return", "c", "\n", "}" ]
// NewDNSCache returns an initialized DNSCache and set the max host limit to // the given argument
[ "NewDNSCache", "returns", "an", "initialized", "DNSCache", "and", "set", "the", "max", "host", "limit", "to", "the", "given", "argument" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/fqdn/cache.go#L158-L162
162,856
cilium/cilium
pkg/fqdn/cache.go
updateWithEntry
func (c *DNSCache) updateWithEntry(entry *cacheEntry) bool { changed := false entries, exists := c.forward[entry.Name] if !exists { changed = true entries = make(map[string]*cacheEntry) c.forward[entry.Name] = entries } if c.updateWithEntryIPs(entries, entry) { changed = true } // When lookupTime is much earlier than time.Now(), we may not expire all // entries that should be expired, leaving more work for .Lookup. if c.removeExpired(entries, time.Now(), time.Time{}) { changed = true } if c.perHostLimit > 0 && len(entries) > c.perHostLimit { c.overLimit[entry.Name] = true } return changed }
go
func (c *DNSCache) updateWithEntry(entry *cacheEntry) bool { changed := false entries, exists := c.forward[entry.Name] if !exists { changed = true entries = make(map[string]*cacheEntry) c.forward[entry.Name] = entries } if c.updateWithEntryIPs(entries, entry) { changed = true } // When lookupTime is much earlier than time.Now(), we may not expire all // entries that should be expired, leaving more work for .Lookup. if c.removeExpired(entries, time.Now(), time.Time{}) { changed = true } if c.perHostLimit > 0 && len(entries) > c.perHostLimit { c.overLimit[entry.Name] = true } return changed }
[ "func", "(", "c", "*", "DNSCache", ")", "updateWithEntry", "(", "entry", "*", "cacheEntry", ")", "bool", "{", "changed", ":=", "false", "\n", "entries", ",", "exists", ":=", "c", ".", "forward", "[", "entry", ".", "Name", "]", "\n", "if", "!", "exists", "{", "changed", "=", "true", "\n", "entries", "=", "make", "(", "map", "[", "string", "]", "*", "cacheEntry", ")", "\n", "c", ".", "forward", "[", "entry", ".", "Name", "]", "=", "entries", "\n", "}", "\n\n", "if", "c", ".", "updateWithEntryIPs", "(", "entries", ",", "entry", ")", "{", "changed", "=", "true", "\n", "}", "\n\n", "// When lookupTime is much earlier than time.Now(), we may not expire all", "// entries that should be expired, leaving more work for .Lookup.", "if", "c", ".", "removeExpired", "(", "entries", ",", "time", ".", "Now", "(", ")", ",", "time", ".", "Time", "{", "}", ")", "{", "changed", "=", "true", "\n", "}", "\n\n", "if", "c", ".", "perHostLimit", ">", "0", "&&", "len", "(", "entries", ")", ">", "c", ".", "perHostLimit", "{", "c", ".", "overLimit", "[", "entry", ".", "Name", "]", "=", "true", "\n", "}", "\n", "return", "changed", "\n", "}" ]
// updateWithEntry implements the insertion of a cacheEntry. It is used by // DNSCache.Update and DNSCache.UpdateWithEntry. // This needs a write lock
[ "updateWithEntry", "implements", "the", "insertion", "of", "a", "cacheEntry", ".", "It", "is", "used", "by", "DNSCache", ".", "Update", "and", "DNSCache", ".", "UpdateWithEntry", ".", "This", "needs", "a", "write", "lock" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/fqdn/cache.go#L194-L217
162,857
cilium/cilium
pkg/fqdn/cache.go
addNameToCleanup
func (c *DNSCache) addNameToCleanup(entry *cacheEntry) { if entry.ExpirationTime.Before(c.lastCleanup) { // ExpirationTime can be before the lastCleanup don't add that value to // prevent leaks on the map. return } expiration := entry.ExpirationTime.Unix() expiredEntries, exists := c.cleanup[expiration] if !exists { expiredEntries = []string{} } c.cleanup[expiration] = append(expiredEntries, entry.Name) }
go
func (c *DNSCache) addNameToCleanup(entry *cacheEntry) { if entry.ExpirationTime.Before(c.lastCleanup) { // ExpirationTime can be before the lastCleanup don't add that value to // prevent leaks on the map. return } expiration := entry.ExpirationTime.Unix() expiredEntries, exists := c.cleanup[expiration] if !exists { expiredEntries = []string{} } c.cleanup[expiration] = append(expiredEntries, entry.Name) }
[ "func", "(", "c", "*", "DNSCache", ")", "addNameToCleanup", "(", "entry", "*", "cacheEntry", ")", "{", "if", "entry", ".", "ExpirationTime", ".", "Before", "(", "c", ".", "lastCleanup", ")", "{", "// ExpirationTime can be before the lastCleanup don't add that value to", "// prevent leaks on the map.", "return", "\n", "}", "\n", "expiration", ":=", "entry", ".", "ExpirationTime", ".", "Unix", "(", ")", "\n", "expiredEntries", ",", "exists", ":=", "c", ".", "cleanup", "[", "expiration", "]", "\n", "if", "!", "exists", "{", "expiredEntries", "=", "[", "]", "string", "{", "}", "\n", "}", "\n", "c", ".", "cleanup", "[", "expiration", "]", "=", "append", "(", "expiredEntries", ",", "entry", ".", "Name", ")", "\n", "}" ]
// AddNameToCleanup adds the IP with the given TTL to the the cleanup map to // delete the entry from the policy when it expires. // Need to be called with a write lock
[ "AddNameToCleanup", "adds", "the", "IP", "with", "the", "given", "TTL", "to", "the", "the", "cleanup", "map", "to", "delete", "the", "entry", "from", "the", "policy", "when", "it", "expires", ".", "Need", "to", "be", "called", "with", "a", "write", "lock" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/fqdn/cache.go#L222-L234
162,858
cilium/cilium
pkg/fqdn/cache.go
cleanupExpiredEntries
func (c *DNSCache) cleanupExpiredEntries(expires time.Time) ([]string, time.Time) { timediff := int(expires.Sub(c.lastCleanup).Seconds()) startTime := c.lastCleanup expiredEntries := []string{} for i := 0; i < int(timediff); i++ { expiredTime := c.lastCleanup.Add(time.Second) key := expiredTime.Unix() c.lastCleanup = expiredTime entries, exists := c.cleanup[key] if !exists { continue } expiredEntries = append(expiredEntries, entries...) delete(c.cleanup, key) } result := []string{} for _, name := range KeepUniqueNames(expiredEntries) { if entries, exists := c.forward[name]; exists { if !c.removeExpired(entries, c.lastCleanup, time.Time{}) { continue } result = append(result, name) } } return result, startTime }
go
func (c *DNSCache) cleanupExpiredEntries(expires time.Time) ([]string, time.Time) { timediff := int(expires.Sub(c.lastCleanup).Seconds()) startTime := c.lastCleanup expiredEntries := []string{} for i := 0; i < int(timediff); i++ { expiredTime := c.lastCleanup.Add(time.Second) key := expiredTime.Unix() c.lastCleanup = expiredTime entries, exists := c.cleanup[key] if !exists { continue } expiredEntries = append(expiredEntries, entries...) delete(c.cleanup, key) } result := []string{} for _, name := range KeepUniqueNames(expiredEntries) { if entries, exists := c.forward[name]; exists { if !c.removeExpired(entries, c.lastCleanup, time.Time{}) { continue } result = append(result, name) } } return result, startTime }
[ "func", "(", "c", "*", "DNSCache", ")", "cleanupExpiredEntries", "(", "expires", "time", ".", "Time", ")", "(", "[", "]", "string", ",", "time", ".", "Time", ")", "{", "timediff", ":=", "int", "(", "expires", ".", "Sub", "(", "c", ".", "lastCleanup", ")", ".", "Seconds", "(", ")", ")", "\n", "startTime", ":=", "c", ".", "lastCleanup", "\n", "expiredEntries", ":=", "[", "]", "string", "{", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "int", "(", "timediff", ")", ";", "i", "++", "{", "expiredTime", ":=", "c", ".", "lastCleanup", ".", "Add", "(", "time", ".", "Second", ")", "\n", "key", ":=", "expiredTime", ".", "Unix", "(", ")", "\n", "c", ".", "lastCleanup", "=", "expiredTime", "\n", "entries", ",", "exists", ":=", "c", ".", "cleanup", "[", "key", "]", "\n", "if", "!", "exists", "{", "continue", "\n", "}", "\n", "expiredEntries", "=", "append", "(", "expiredEntries", ",", "entries", "...", ")", "\n", "delete", "(", "c", ".", "cleanup", ",", "key", ")", "\n", "}", "\n\n", "result", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "name", ":=", "range", "KeepUniqueNames", "(", "expiredEntries", ")", "{", "if", "entries", ",", "exists", ":=", "c", ".", "forward", "[", "name", "]", ";", "exists", "{", "if", "!", "c", ".", "removeExpired", "(", "entries", ",", "c", ".", "lastCleanup", ",", "time", ".", "Time", "{", "}", ")", "{", "continue", "\n", "}", "\n", "result", "=", "append", "(", "result", ",", "name", ")", "\n", "}", "\n", "}", "\n", "return", "result", ",", "startTime", "\n", "}" ]
// cleanupExpiredEntries cleans all the expired entries from the lastTime that // runs to the give time. It will lock the struct until retrieves all the data. // It returns the list of names that need to be deleted from the policies.
[ "cleanupExpiredEntries", "cleans", "all", "the", "expired", "entries", "from", "the", "lastTime", "that", "runs", "to", "the", "give", "time", ".", "It", "will", "lock", "the", "struct", "until", "retrieves", "all", "the", "data", ".", "It", "returns", "the", "list", "of", "names", "that", "need", "to", "be", "deleted", "from", "the", "policies", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/fqdn/cache.go#L239-L265
162,859
cilium/cilium
pkg/fqdn/cache.go
cleanupOverLimitEntries
func (c *DNSCache) cleanupOverLimitEntries() []string { type IPEntry struct { ip string entry *cacheEntry } affectedNames := []string{} // For global cache the limit maybe is not used at all. if c.perHostLimit == 0 { return affectedNames } for dnsName := range c.overLimit { entries, ok := c.forward[dnsName] if !ok { continue } overlimit := len(entries) - c.perHostLimit if overlimit <= 0 { continue } sortedEntries := []IPEntry{} for ip, entry := range entries { sortedEntries = append(sortedEntries, IPEntry{ip, entry}) } sort.Slice(sortedEntries, func(i, j int) bool { return sortedEntries[i].entry.ExpirationTime.Before(sortedEntries[j].entry.ExpirationTime) }) for i := 0; i < overlimit; i++ { key := sortedEntries[i] delete(entries, key.ip) c.removeReverse(key.ip, key.entry) } affectedNames = append(affectedNames, dnsName) } c.overLimit = map[string]bool{} return affectedNames }
go
func (c *DNSCache) cleanupOverLimitEntries() []string { type IPEntry struct { ip string entry *cacheEntry } affectedNames := []string{} // For global cache the limit maybe is not used at all. if c.perHostLimit == 0 { return affectedNames } for dnsName := range c.overLimit { entries, ok := c.forward[dnsName] if !ok { continue } overlimit := len(entries) - c.perHostLimit if overlimit <= 0 { continue } sortedEntries := []IPEntry{} for ip, entry := range entries { sortedEntries = append(sortedEntries, IPEntry{ip, entry}) } sort.Slice(sortedEntries, func(i, j int) bool { return sortedEntries[i].entry.ExpirationTime.Before(sortedEntries[j].entry.ExpirationTime) }) for i := 0; i < overlimit; i++ { key := sortedEntries[i] delete(entries, key.ip) c.removeReverse(key.ip, key.entry) } affectedNames = append(affectedNames, dnsName) } c.overLimit = map[string]bool{} return affectedNames }
[ "func", "(", "c", "*", "DNSCache", ")", "cleanupOverLimitEntries", "(", ")", "[", "]", "string", "{", "type", "IPEntry", "struct", "{", "ip", "string", "\n", "entry", "*", "cacheEntry", "\n", "}", "\n", "affectedNames", ":=", "[", "]", "string", "{", "}", "\n\n", "// For global cache the limit maybe is not used at all.", "if", "c", ".", "perHostLimit", "==", "0", "{", "return", "affectedNames", "\n", "}", "\n\n", "for", "dnsName", ":=", "range", "c", ".", "overLimit", "{", "entries", ",", "ok", ":=", "c", ".", "forward", "[", "dnsName", "]", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n", "overlimit", ":=", "len", "(", "entries", ")", "-", "c", ".", "perHostLimit", "\n", "if", "overlimit", "<=", "0", "{", "continue", "\n", "}", "\n", "sortedEntries", ":=", "[", "]", "IPEntry", "{", "}", "\n", "for", "ip", ",", "entry", ":=", "range", "entries", "{", "sortedEntries", "=", "append", "(", "sortedEntries", ",", "IPEntry", "{", "ip", ",", "entry", "}", ")", "\n", "}", "\n\n", "sort", ".", "Slice", "(", "sortedEntries", ",", "func", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "sortedEntries", "[", "i", "]", ".", "entry", ".", "ExpirationTime", ".", "Before", "(", "sortedEntries", "[", "j", "]", ".", "entry", ".", "ExpirationTime", ")", "\n", "}", ")", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "overlimit", ";", "i", "++", "{", "key", ":=", "sortedEntries", "[", "i", "]", "\n", "delete", "(", "entries", ",", "key", ".", "ip", ")", "\n", "c", ".", "removeReverse", "(", "key", ".", "ip", ",", "key", ".", "entry", ")", "\n", "}", "\n", "affectedNames", "=", "append", "(", "affectedNames", ",", "dnsName", ")", "\n", "}", "\n", "c", ".", "overLimit", "=", "map", "[", "string", "]", "bool", "{", "}", "\n", "return", "affectedNames", "\n", "}" ]
// cleanupOverLimitEntries returns the names that has reached the max number of // IP per host. Internally the function sort the entries by the expiration // time.
[ "cleanupOverLimitEntries", "returns", "the", "names", "that", "has", "reached", "the", "max", "number", "of", "IP", "per", "host", ".", "Internally", "the", "function", "sort", "the", "entries", "by", "the", "expiration", "time", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/fqdn/cache.go#L270-L309
162,860
cilium/cilium
pkg/fqdn/cache.go
GC
func (c *DNSCache) GC() []string { c.Lock() expiredEntries, _ := c.cleanupExpiredEntries(time.Now()) overLimitEntries := c.cleanupOverLimitEntries() c.Unlock() return KeepUniqueNames(append(expiredEntries, overLimitEntries...)) }
go
func (c *DNSCache) GC() []string { c.Lock() expiredEntries, _ := c.cleanupExpiredEntries(time.Now()) overLimitEntries := c.cleanupOverLimitEntries() c.Unlock() return KeepUniqueNames(append(expiredEntries, overLimitEntries...)) }
[ "func", "(", "c", "*", "DNSCache", ")", "GC", "(", ")", "[", "]", "string", "{", "c", ".", "Lock", "(", ")", "\n", "expiredEntries", ",", "_", ":=", "c", ".", "cleanupExpiredEntries", "(", "time", ".", "Now", "(", ")", ")", "\n", "overLimitEntries", ":=", "c", ".", "cleanupOverLimitEntries", "(", ")", "\n", "c", ".", "Unlock", "(", ")", "\n", "return", "KeepUniqueNames", "(", "append", "(", "expiredEntries", ",", "overLimitEntries", "...", ")", ")", "\n", "}" ]
// GC garbage collector function that clean expired entries and return the // entries that are deleted.
[ "GC", "garbage", "collector", "function", "that", "clean", "expired", "entries", "and", "return", "the", "entries", "that", "are", "deleted", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/fqdn/cache.go#L313-L319
162,861
cilium/cilium
pkg/fqdn/cache.go
UpdateFromCache
func (c *DNSCache) UpdateFromCache(update *DNSCache, namesToUpdate []string) { if update == nil { return } update.RLock() defer update.RUnlock() c.Lock() defer c.Unlock() if len(namesToUpdate) == 0 { for name := range update.forward { namesToUpdate = append(namesToUpdate, name) } } for _, name := range namesToUpdate { newEntries, exists := update.forward[name] if !exists { continue } for _, newEntry := range newEntries { c.updateWithEntry(newEntry) } } }
go
func (c *DNSCache) UpdateFromCache(update *DNSCache, namesToUpdate []string) { if update == nil { return } update.RLock() defer update.RUnlock() c.Lock() defer c.Unlock() if len(namesToUpdate) == 0 { for name := range update.forward { namesToUpdate = append(namesToUpdate, name) } } for _, name := range namesToUpdate { newEntries, exists := update.forward[name] if !exists { continue } for _, newEntry := range newEntries { c.updateWithEntry(newEntry) } } }
[ "func", "(", "c", "*", "DNSCache", ")", "UpdateFromCache", "(", "update", "*", "DNSCache", ",", "namesToUpdate", "[", "]", "string", ")", "{", "if", "update", "==", "nil", "{", "return", "\n", "}", "\n\n", "update", ".", "RLock", "(", ")", "\n", "defer", "update", ".", "RUnlock", "(", ")", "\n\n", "c", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "Unlock", "(", ")", "\n", "if", "len", "(", "namesToUpdate", ")", "==", "0", "{", "for", "name", ":=", "range", "update", ".", "forward", "{", "namesToUpdate", "=", "append", "(", "namesToUpdate", ",", "name", ")", "\n", "}", "\n", "}", "\n", "for", "_", ",", "name", ":=", "range", "namesToUpdate", "{", "newEntries", ",", "exists", ":=", "update", ".", "forward", "[", "name", "]", "\n", "if", "!", "exists", "{", "continue", "\n", "}", "\n", "for", "_", ",", "newEntry", ":=", "range", "newEntries", "{", "c", ".", "updateWithEntry", "(", "newEntry", ")", "\n", "}", "\n", "}", "\n", "}" ]
// UpdateFromCache is a utility function that allows updating a DNSCache // instance with all the internal entries of another. Latest-Expiration still // applies, thus the merged outcome is consistent with adding the entries // individually. // When namesToUpdate has non-zero length only those names are updated from // update, otherwise all DNS names in update are used.
[ "UpdateFromCache", "is", "a", "utility", "function", "that", "allows", "updating", "a", "DNSCache", "instance", "with", "all", "the", "internal", "entries", "of", "another", ".", "Latest", "-", "Expiration", "still", "applies", "thus", "the", "merged", "outcome", "is", "consistent", "with", "adding", "the", "entries", "individually", ".", "When", "namesToUpdate", "has", "non", "-", "zero", "length", "only", "those", "names", "are", "updated", "from", "update", "otherwise", "all", "DNS", "names", "in", "update", "are", "used", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/fqdn/cache.go#L327-L351
162,862
cilium/cilium
pkg/fqdn/cache.go
Lookup
func (c *DNSCache) Lookup(name string) (ips []net.IP) { c.RLock() defer c.RUnlock() return c.lookupByTime(time.Now(), name) }
go
func (c *DNSCache) Lookup(name string) (ips []net.IP) { c.RLock() defer c.RUnlock() return c.lookupByTime(time.Now(), name) }
[ "func", "(", "c", "*", "DNSCache", ")", "Lookup", "(", "name", "string", ")", "(", "ips", "[", "]", "net", ".", "IP", ")", "{", "c", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "RUnlock", "(", ")", "\n\n", "return", "c", ".", "lookupByTime", "(", "time", ".", "Now", "(", ")", ",", "name", ")", "\n", "}" ]
// Lookup returns a set of unique IPs that are currently unexpired for name, if // any exist. An empty list indicates no valid records exist. The IPs are // returned sorted.
[ "Lookup", "returns", "a", "set", "of", "unique", "IPs", "that", "are", "currently", "unexpired", "for", "name", "if", "any", "exist", ".", "An", "empty", "list", "indicates", "no", "valid", "records", "exist", ".", "The", "IPs", "are", "returned", "sorted", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/fqdn/cache.go#L356-L361
162,863
cilium/cilium
pkg/fqdn/cache.go
lookupByTime
func (c *DNSCache) lookupByTime(now time.Time, name string) (ips []net.IP) { entries, found := c.forward[name] if !found { return nil } return entries.getIPs(now) }
go
func (c *DNSCache) lookupByTime(now time.Time, name string) (ips []net.IP) { entries, found := c.forward[name] if !found { return nil } return entries.getIPs(now) }
[ "func", "(", "c", "*", "DNSCache", ")", "lookupByTime", "(", "now", "time", ".", "Time", ",", "name", "string", ")", "(", "ips", "[", "]", "net", ".", "IP", ")", "{", "entries", ",", "found", ":=", "c", ".", "forward", "[", "name", "]", "\n", "if", "!", "found", "{", "return", "nil", "\n", "}", "\n\n", "return", "entries", ".", "getIPs", "(", "now", ")", "\n", "}" ]
// lookupByTime takes a timestamp for expiration comparisions, and is only // intended for testing.
[ "lookupByTime", "takes", "a", "timestamp", "for", "expiration", "comparisions", "and", "is", "only", "intended", "for", "testing", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/fqdn/cache.go#L365-L372
162,864
cilium/cilium
pkg/fqdn/cache.go
LookupByRegexp
func (c *DNSCache) LookupByRegexp(re *regexp.Regexp) (matches map[string][]net.IP) { return c.lookupByRegexpByTime(time.Now(), re) }
go
func (c *DNSCache) LookupByRegexp(re *regexp.Regexp) (matches map[string][]net.IP) { return c.lookupByRegexpByTime(time.Now(), re) }
[ "func", "(", "c", "*", "DNSCache", ")", "LookupByRegexp", "(", "re", "*", "regexp", ".", "Regexp", ")", "(", "matches", "map", "[", "string", "]", "[", "]", "net", ".", "IP", ")", "{", "return", "c", ".", "lookupByRegexpByTime", "(", "time", ".", "Now", "(", ")", ",", "re", ")", "\n", "}" ]
// LookupByRegexp returns all non-expired cache entries that match re as a map // of name -> IPs
[ "LookupByRegexp", "returns", "all", "non", "-", "expired", "cache", "entries", "that", "match", "re", "as", "a", "map", "of", "name", "-", ">", "IPs" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/fqdn/cache.go#L376-L378
162,865
cilium/cilium
pkg/fqdn/cache.go
lookupByRegexpByTime
func (c *DNSCache) lookupByRegexpByTime(now time.Time, re *regexp.Regexp) (matches map[string][]net.IP) { matches = make(map[string][]net.IP) c.RLock() defer c.RUnlock() for name, entry := range c.forward { if re.MatchString(name) { matches[name] = append(matches[name], entry.getIPs(now)...) } } return matches }
go
func (c *DNSCache) lookupByRegexpByTime(now time.Time, re *regexp.Regexp) (matches map[string][]net.IP) { matches = make(map[string][]net.IP) c.RLock() defer c.RUnlock() for name, entry := range c.forward { if re.MatchString(name) { matches[name] = append(matches[name], entry.getIPs(now)...) } } return matches }
[ "func", "(", "c", "*", "DNSCache", ")", "lookupByRegexpByTime", "(", "now", "time", ".", "Time", ",", "re", "*", "regexp", ".", "Regexp", ")", "(", "matches", "map", "[", "string", "]", "[", "]", "net", ".", "IP", ")", "{", "matches", "=", "make", "(", "map", "[", "string", "]", "[", "]", "net", ".", "IP", ")", "\n\n", "c", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "RUnlock", "(", ")", "\n\n", "for", "name", ",", "entry", ":=", "range", "c", ".", "forward", "{", "if", "re", ".", "MatchString", "(", "name", ")", "{", "matches", "[", "name", "]", "=", "append", "(", "matches", "[", "name", "]", ",", "entry", ".", "getIPs", "(", "now", ")", "...", ")", "\n", "}", "\n", "}", "\n\n", "return", "matches", "\n", "}" ]
// lookupByRegexpByTime takes a timestamp for expiration comparisions, and is // only intended for testing.
[ "lookupByRegexpByTime", "takes", "a", "timestamp", "for", "expiration", "comparisions", "and", "is", "only", "intended", "for", "testing", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/fqdn/cache.go#L382-L395
162,866
cilium/cilium
pkg/fqdn/cache.go
LookupIP
func (c *DNSCache) LookupIP(ip net.IP) (names []string) { c.RLock() defer c.RUnlock() return c.lookupIPByTime(time.Now(), ip) }
go
func (c *DNSCache) LookupIP(ip net.IP) (names []string) { c.RLock() defer c.RUnlock() return c.lookupIPByTime(time.Now(), ip) }
[ "func", "(", "c", "*", "DNSCache", ")", "LookupIP", "(", "ip", "net", ".", "IP", ")", "(", "names", "[", "]", "string", ")", "{", "c", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "RUnlock", "(", ")", "\n\n", "return", "c", ".", "lookupIPByTime", "(", "time", ".", "Now", "(", ")", ",", "ip", ")", "\n", "}" ]
// LookupIP returns all DNS names in entries that include that IP. The cache // maintains the latest-expiring entry per-name per-IP. This means that multiple // names referrring to the same IP will expire from the cache at different times, // and only 1 entry for each name-IP pair is internally retained.
[ "LookupIP", "returns", "all", "DNS", "names", "in", "entries", "that", "include", "that", "IP", ".", "The", "cache", "maintains", "the", "latest", "-", "expiring", "entry", "per", "-", "name", "per", "-", "IP", ".", "This", "means", "that", "multiple", "names", "referrring", "to", "the", "same", "IP", "will", "expire", "from", "the", "cache", "at", "different", "times", "and", "only", "1", "entry", "for", "each", "name", "-", "IP", "pair", "is", "internally", "retained", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/fqdn/cache.go#L401-L406
162,867
cilium/cilium
pkg/fqdn/cache.go
lookupIPByTime
func (c *DNSCache) lookupIPByTime(now time.Time, ip net.IP) (names []string) { ipKey := ip.String() cacheEntries, found := c.reverse[ipKey] if !found { return nil } for name, entry := range cacheEntries { if entry != nil && !entry.isExpiredBy(now) { names = append(names, name) } } sort.Strings(names) return names }
go
func (c *DNSCache) lookupIPByTime(now time.Time, ip net.IP) (names []string) { ipKey := ip.String() cacheEntries, found := c.reverse[ipKey] if !found { return nil } for name, entry := range cacheEntries { if entry != nil && !entry.isExpiredBy(now) { names = append(names, name) } } sort.Strings(names) return names }
[ "func", "(", "c", "*", "DNSCache", ")", "lookupIPByTime", "(", "now", "time", ".", "Time", ",", "ip", "net", ".", "IP", ")", "(", "names", "[", "]", "string", ")", "{", "ipKey", ":=", "ip", ".", "String", "(", ")", "\n", "cacheEntries", ",", "found", ":=", "c", ".", "reverse", "[", "ipKey", "]", "\n", "if", "!", "found", "{", "return", "nil", "\n", "}", "\n\n", "for", "name", ",", "entry", ":=", "range", "cacheEntries", "{", "if", "entry", "!=", "nil", "&&", "!", "entry", ".", "isExpiredBy", "(", "now", ")", "{", "names", "=", "append", "(", "names", ",", "name", ")", "\n", "}", "\n", "}", "\n\n", "sort", ".", "Strings", "(", "names", ")", "\n", "return", "names", "\n", "}" ]
// lookupIPByTime takes a timestamp for expiration comparisions, and is // only intended for testing.
[ "lookupIPByTime", "takes", "a", "timestamp", "for", "expiration", "comparisions", "and", "is", "only", "intended", "for", "testing", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/fqdn/cache.go#L410-L425
162,868
cilium/cilium
pkg/fqdn/cache.go
upsertReverse
func (c *DNSCache) upsertReverse(ip string, entry *cacheEntry) { entries, exists := c.reverse[ip] if entries == nil || !exists { entries = make(map[string]*cacheEntry) c.reverse[ip] = entries } entries[entry.Name] = entry }
go
func (c *DNSCache) upsertReverse(ip string, entry *cacheEntry) { entries, exists := c.reverse[ip] if entries == nil || !exists { entries = make(map[string]*cacheEntry) c.reverse[ip] = entries } entries[entry.Name] = entry }
[ "func", "(", "c", "*", "DNSCache", ")", "upsertReverse", "(", "ip", "string", ",", "entry", "*", "cacheEntry", ")", "{", "entries", ",", "exists", ":=", "c", ".", "reverse", "[", "ip", "]", "\n", "if", "entries", "==", "nil", "||", "!", "exists", "{", "entries", "=", "make", "(", "map", "[", "string", "]", "*", "cacheEntry", ")", "\n", "c", ".", "reverse", "[", "ip", "]", "=", "entries", "\n", "}", "\n", "entries", "[", "entry", ".", "Name", "]", "=", "entry", "\n", "}" ]
// upsertReverse updates the reverse DNS cache for ip with entry, if it expires // later than the already-stored entry. // It is assumed that entry includes ip. // This needs a write lock
[ "upsertReverse", "updates", "the", "reverse", "DNS", "cache", "for", "ip", "with", "entry", "if", "it", "expires", "later", "than", "the", "already", "-", "stored", "entry", ".", "It", "is", "assumed", "that", "entry", "includes", "ip", ".", "This", "needs", "a", "write", "lock" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/fqdn/cache.go#L473-L480
162,869
cilium/cilium
pkg/fqdn/cache.go
removeReverse
func (c *DNSCache) removeReverse(ip string, entry *cacheEntry) { entries, exists := c.reverse[ip] if entries == nil || !exists { return } delete(entries, entry.Name) if len(entries) == 0 { delete(c.reverse, ip) } }
go
func (c *DNSCache) removeReverse(ip string, entry *cacheEntry) { entries, exists := c.reverse[ip] if entries == nil || !exists { return } delete(entries, entry.Name) if len(entries) == 0 { delete(c.reverse, ip) } }
[ "func", "(", "c", "*", "DNSCache", ")", "removeReverse", "(", "ip", "string", ",", "entry", "*", "cacheEntry", ")", "{", "entries", ",", "exists", ":=", "c", ".", "reverse", "[", "ip", "]", "\n", "if", "entries", "==", "nil", "||", "!", "exists", "{", "return", "\n", "}", "\n", "delete", "(", "entries", ",", "entry", ".", "Name", ")", "\n", "if", "len", "(", "entries", ")", "==", "0", "{", "delete", "(", "c", ".", "reverse", ",", "ip", ")", "\n", "}", "\n", "}" ]
// removeReverse removes the reference between ip and the name stored in entry. // When no more refrences from ip to any name exist, the map entry is deleted // outright. // It is assumed that entry includes ip. // This needs a write lock
[ "removeReverse", "removes", "the", "reference", "between", "ip", "and", "the", "name", "stored", "in", "entry", ".", "When", "no", "more", "refrences", "from", "ip", "to", "any", "name", "exist", "the", "map", "entry", "is", "deleted", "outright", ".", "It", "is", "assumed", "that", "entry", "includes", "ip", ".", "This", "needs", "a", "write", "lock" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/fqdn/cache.go#L487-L496
162,870
cilium/cilium
pkg/fqdn/cache.go
ForceExpireByNames
func (c *DNSCache) ForceExpireByNames(expireLookupsBefore time.Time, names []string) (namesAffected []string) { c.Lock() defer c.Unlock() for _, name := range names { entries, exists := c.forward[name] if !exists { continue } // We pass expireLookupsBefore as the `now` parameter but it is redundant // because LookupTime must be before ExpirationTime. // The second expireLookupsBefore actually matches lookup times, and will // delete the entries completely. nameNeedsRegen := c.removeExpired(entries, expireLookupsBefore, expireLookupsBefore) if nameNeedsRegen { namesAffected = append(namesAffected, name) } } return namesAffected }
go
func (c *DNSCache) ForceExpireByNames(expireLookupsBefore time.Time, names []string) (namesAffected []string) { c.Lock() defer c.Unlock() for _, name := range names { entries, exists := c.forward[name] if !exists { continue } // We pass expireLookupsBefore as the `now` parameter but it is redundant // because LookupTime must be before ExpirationTime. // The second expireLookupsBefore actually matches lookup times, and will // delete the entries completely. nameNeedsRegen := c.removeExpired(entries, expireLookupsBefore, expireLookupsBefore) if nameNeedsRegen { namesAffected = append(namesAffected, name) } } return namesAffected }
[ "func", "(", "c", "*", "DNSCache", ")", "ForceExpireByNames", "(", "expireLookupsBefore", "time", ".", "Time", ",", "names", "[", "]", "string", ")", "(", "namesAffected", "[", "]", "string", ")", "{", "c", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "Unlock", "(", ")", "\n", "for", "_", ",", "name", ":=", "range", "names", "{", "entries", ",", "exists", ":=", "c", ".", "forward", "[", "name", "]", "\n", "if", "!", "exists", "{", "continue", "\n", "}", "\n\n", "// We pass expireLookupsBefore as the `now` parameter but it is redundant", "// because LookupTime must be before ExpirationTime.", "// The second expireLookupsBefore actually matches lookup times, and will", "// delete the entries completely.", "nameNeedsRegen", ":=", "c", ".", "removeExpired", "(", "entries", ",", "expireLookupsBefore", ",", "expireLookupsBefore", ")", "\n", "if", "nameNeedsRegen", "{", "namesAffected", "=", "append", "(", "namesAffected", ",", "name", ")", "\n", "}", "\n", "}", "\n\n", "return", "namesAffected", "\n", "}" ]
// ForceExpireByNames is the same function as ForceExpire but uses the exact // names to delete the entries.
[ "ForceExpireByNames", "is", "the", "same", "function", "as", "ForceExpire", "but", "uses", "the", "exact", "names", "to", "delete", "the", "entries", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/fqdn/cache.go#L530-L550
162,871
cilium/cilium
pkg/fqdn/cache.go
Dump
func (c *DNSCache) Dump() (lookups []*cacheEntry) { c.RLock() defer c.RUnlock() now := time.Now() // Collect all the still-valid entries lookups = make([]*cacheEntry, 0, len(c.forward)) for _, entries := range c.forward { for _, entry := range entries { if !entry.isExpiredBy(now) { lookups = append(lookups, entry) } } } // Dedup the entries. They are created once and are immutable so the address // is a unique identifier. // We iterate through the list, keeping unique pointers. This is correct // because the list is sorted and, if two consecutive entries are the same, // it is safe to overwrite the second duplicate. sort.Slice(lookups, func(i, j int) bool { return uintptr(unsafe.Pointer(lookups[i])) < uintptr(unsafe.Pointer(lookups[j])) }) deduped := lookups[:0] // len==0 but cap==cap(lookups) for readIdx, lookup := range lookups { if readIdx == 0 || deduped[len(deduped)-1] != lookups[readIdx] { deduped = append(deduped, lookup) } } return deduped }
go
func (c *DNSCache) Dump() (lookups []*cacheEntry) { c.RLock() defer c.RUnlock() now := time.Now() // Collect all the still-valid entries lookups = make([]*cacheEntry, 0, len(c.forward)) for _, entries := range c.forward { for _, entry := range entries { if !entry.isExpiredBy(now) { lookups = append(lookups, entry) } } } // Dedup the entries. They are created once and are immutable so the address // is a unique identifier. // We iterate through the list, keeping unique pointers. This is correct // because the list is sorted and, if two consecutive entries are the same, // it is safe to overwrite the second duplicate. sort.Slice(lookups, func(i, j int) bool { return uintptr(unsafe.Pointer(lookups[i])) < uintptr(unsafe.Pointer(lookups[j])) }) deduped := lookups[:0] // len==0 but cap==cap(lookups) for readIdx, lookup := range lookups { if readIdx == 0 || deduped[len(deduped)-1] != lookups[readIdx] { deduped = append(deduped, lookup) } } return deduped }
[ "func", "(", "c", "*", "DNSCache", ")", "Dump", "(", ")", "(", "lookups", "[", "]", "*", "cacheEntry", ")", "{", "c", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "RUnlock", "(", ")", "\n\n", "now", ":=", "time", ".", "Now", "(", ")", "\n\n", "// Collect all the still-valid entries", "lookups", "=", "make", "(", "[", "]", "*", "cacheEntry", ",", "0", ",", "len", "(", "c", ".", "forward", ")", ")", "\n", "for", "_", ",", "entries", ":=", "range", "c", ".", "forward", "{", "for", "_", ",", "entry", ":=", "range", "entries", "{", "if", "!", "entry", ".", "isExpiredBy", "(", "now", ")", "{", "lookups", "=", "append", "(", "lookups", ",", "entry", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Dedup the entries. They are created once and are immutable so the address", "// is a unique identifier.", "// We iterate through the list, keeping unique pointers. This is correct", "// because the list is sorted and, if two consecutive entries are the same,", "// it is safe to overwrite the second duplicate.", "sort", ".", "Slice", "(", "lookups", ",", "func", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "uintptr", "(", "unsafe", ".", "Pointer", "(", "lookups", "[", "i", "]", ")", ")", "<", "uintptr", "(", "unsafe", ".", "Pointer", "(", "lookups", "[", "j", "]", ")", ")", "\n", "}", ")", "\n\n", "deduped", ":=", "lookups", "[", ":", "0", "]", "// len==0 but cap==cap(lookups)", "\n", "for", "readIdx", ",", "lookup", ":=", "range", "lookups", "{", "if", "readIdx", "==", "0", "||", "deduped", "[", "len", "(", "deduped", ")", "-", "1", "]", "!=", "lookups", "[", "readIdx", "]", "{", "deduped", "=", "append", "(", "deduped", ",", "lookup", ")", "\n", "}", "\n", "}", "\n\n", "return", "deduped", "\n", "}" ]
// Dump returns unexpired cache entries in the cache. They are deduplicated, // but not usefully sorted. These objects should not be modified.
[ "Dump", "returns", "unexpired", "cache", "entries", "in", "the", "cache", ".", "They", "are", "deduplicated", "but", "not", "usefully", "sorted", ".", "These", "objects", "should", "not", "be", "modified", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/fqdn/cache.go#L554-L587
162,872
cilium/cilium
pkg/fqdn/dnsproxy/proxy.go
IsTimeout
func (proxyStat *ProxyRequestContext) IsTimeout() bool { netErr, isNetErr := proxyStat.Err.(net.Error) if isNetErr && netErr.Timeout() { return true } return false }
go
func (proxyStat *ProxyRequestContext) IsTimeout() bool { netErr, isNetErr := proxyStat.Err.(net.Error) if isNetErr && netErr.Timeout() { return true } return false }
[ "func", "(", "proxyStat", "*", "ProxyRequestContext", ")", "IsTimeout", "(", ")", "bool", "{", "netErr", ",", "isNetErr", ":=", "proxyStat", ".", "Err", ".", "(", "net", ".", "Error", ")", "\n", "if", "isNetErr", "&&", "netErr", ".", "Timeout", "(", ")", "{", "return", "true", "\n\n", "}", "\n", "return", "false", "\n", "}" ]
// IsTimeout return true if the ProxyRequest timeout
[ "IsTimeout", "return", "true", "if", "the", "ProxyRequest", "timeout" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/fqdn/dnsproxy/proxy.go#L136-L143
162,873
cilium/cilium
pkg/fqdn/dnsproxy/proxy.go
StartDNSProxy
func StartDNSProxy(address string, port uint16, lookupEPFunc LookupEndpointIDByIPFunc, notifyFunc NotifyOnDNSMsgFunc) (*DNSProxy, error) { if port == 0 { log.Debug("DNS Proxy port is configured to 0. A random port will be assigned by the OS.") } if lookupEPFunc == nil || notifyFunc == nil { return nil, errors.New("DNS proxy must have lookupEPFunc and notifyFunc provided") } p := &DNSProxy{ LookupEndpointIDByIP: lookupEPFunc, NotifyOnDNSMsg: notifyFunc, lookupTargetDNSServer: lookupTargetDNSServer, allowed: regexpmap.NewRegexpMap(), rejectReply: dns.RcodeRefused, } // Start the DNS listeners on UDP and TCP var ( UDPConn *net.UDPConn TCPListener *net.TCPListener err error ) start := time.Now() for time.Since(start) < ProxyBindTimeout { UDPConn, TCPListener, err = bindToAddr(address, port) if err == nil { break } log.WithError(err).Warnf("Attempt to bind DNS Proxy failed, retrying in %v", ProxyBindRetryInterval) time.Sleep(ProxyBindRetryInterval) } if err != nil { return nil, err } p.BindAddr = UDPConn.LocalAddr().String() p.BindPort = uint16(UDPConn.LocalAddr().(*net.UDPAddr).Port) p.UDPServer = &dns.Server{PacketConn: UDPConn, Addr: p.BindAddr, Net: "udp", Handler: p, SessionUDPFactory: ciliumSessionUDPFactory, } p.TCPServer = &dns.Server{Listener: TCPListener, Addr: p.BindAddr, Net: "tcp", Handler: p} log.WithField("address", p.BindAddr).Debug("DNS Proxy bound to address") for _, s := range []*dns.Server{p.UDPServer, p.TCPServer} { go func(server *dns.Server) { // try 5 times during a single ProxyBindTimeout period. We fatal here // because we have no other way to indicate failure this late. start := time.Now() for time.Since(start) < ProxyBindTimeout { if err := server.ActivateAndServe(); err != nil { log.WithError(err).Errorf("Failed to start the %s DNS proxy on %s", server.Net, server.Addr) } time.Sleep(ProxyBindRetryInterval) } log.Fatalf("Failed to start %s DNS Proxy on %s", server.Net, server.Addr) }(s) } // Bind the DNS forwarding clients on UDP and TCP p.UDPClient = &dns.Client{Net: "udp", Timeout: ProxyForwardTimeout, SingleInflight: true} p.TCPClient = &dns.Client{Net: "tcp", Timeout: ProxyForwardTimeout, SingleInflight: true} return p, nil }
go
func StartDNSProxy(address string, port uint16, lookupEPFunc LookupEndpointIDByIPFunc, notifyFunc NotifyOnDNSMsgFunc) (*DNSProxy, error) { if port == 0 { log.Debug("DNS Proxy port is configured to 0. A random port will be assigned by the OS.") } if lookupEPFunc == nil || notifyFunc == nil { return nil, errors.New("DNS proxy must have lookupEPFunc and notifyFunc provided") } p := &DNSProxy{ LookupEndpointIDByIP: lookupEPFunc, NotifyOnDNSMsg: notifyFunc, lookupTargetDNSServer: lookupTargetDNSServer, allowed: regexpmap.NewRegexpMap(), rejectReply: dns.RcodeRefused, } // Start the DNS listeners on UDP and TCP var ( UDPConn *net.UDPConn TCPListener *net.TCPListener err error ) start := time.Now() for time.Since(start) < ProxyBindTimeout { UDPConn, TCPListener, err = bindToAddr(address, port) if err == nil { break } log.WithError(err).Warnf("Attempt to bind DNS Proxy failed, retrying in %v", ProxyBindRetryInterval) time.Sleep(ProxyBindRetryInterval) } if err != nil { return nil, err } p.BindAddr = UDPConn.LocalAddr().String() p.BindPort = uint16(UDPConn.LocalAddr().(*net.UDPAddr).Port) p.UDPServer = &dns.Server{PacketConn: UDPConn, Addr: p.BindAddr, Net: "udp", Handler: p, SessionUDPFactory: ciliumSessionUDPFactory, } p.TCPServer = &dns.Server{Listener: TCPListener, Addr: p.BindAddr, Net: "tcp", Handler: p} log.WithField("address", p.BindAddr).Debug("DNS Proxy bound to address") for _, s := range []*dns.Server{p.UDPServer, p.TCPServer} { go func(server *dns.Server) { // try 5 times during a single ProxyBindTimeout period. We fatal here // because we have no other way to indicate failure this late. start := time.Now() for time.Since(start) < ProxyBindTimeout { if err := server.ActivateAndServe(); err != nil { log.WithError(err).Errorf("Failed to start the %s DNS proxy on %s", server.Net, server.Addr) } time.Sleep(ProxyBindRetryInterval) } log.Fatalf("Failed to start %s DNS Proxy on %s", server.Net, server.Addr) }(s) } // Bind the DNS forwarding clients on UDP and TCP p.UDPClient = &dns.Client{Net: "udp", Timeout: ProxyForwardTimeout, SingleInflight: true} p.TCPClient = &dns.Client{Net: "tcp", Timeout: ProxyForwardTimeout, SingleInflight: true} return p, nil }
[ "func", "StartDNSProxy", "(", "address", "string", ",", "port", "uint16", ",", "lookupEPFunc", "LookupEndpointIDByIPFunc", ",", "notifyFunc", "NotifyOnDNSMsgFunc", ")", "(", "*", "DNSProxy", ",", "error", ")", "{", "if", "port", "==", "0", "{", "log", ".", "Debug", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "lookupEPFunc", "==", "nil", "||", "notifyFunc", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "p", ":=", "&", "DNSProxy", "{", "LookupEndpointIDByIP", ":", "lookupEPFunc", ",", "NotifyOnDNSMsg", ":", "notifyFunc", ",", "lookupTargetDNSServer", ":", "lookupTargetDNSServer", ",", "allowed", ":", "regexpmap", ".", "NewRegexpMap", "(", ")", ",", "rejectReply", ":", "dns", ".", "RcodeRefused", ",", "}", "\n\n", "// Start the DNS listeners on UDP and TCP", "var", "(", "UDPConn", "*", "net", ".", "UDPConn", "\n", "TCPListener", "*", "net", ".", "TCPListener", "\n", "err", "error", "\n", ")", "\n\n", "start", ":=", "time", ".", "Now", "(", ")", "\n", "for", "time", ".", "Since", "(", "start", ")", "<", "ProxyBindTimeout", "{", "UDPConn", ",", "TCPListener", ",", "err", "=", "bindToAddr", "(", "address", ",", "port", ")", "\n", "if", "err", "==", "nil", "{", "break", "\n", "}", "\n", "log", ".", "WithError", "(", "err", ")", ".", "Warnf", "(", "\"", "\"", ",", "ProxyBindRetryInterval", ")", "\n", "time", ".", "Sleep", "(", "ProxyBindRetryInterval", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "p", ".", "BindAddr", "=", "UDPConn", ".", "LocalAddr", "(", ")", ".", "String", "(", ")", "\n", "p", ".", "BindPort", "=", "uint16", "(", "UDPConn", ".", "LocalAddr", "(", ")", ".", "(", "*", "net", ".", "UDPAddr", ")", ".", "Port", ")", "\n", "p", ".", "UDPServer", "=", "&", "dns", ".", "Server", "{", "PacketConn", ":", "UDPConn", ",", "Addr", ":", "p", ".", "BindAddr", ",", "Net", ":", "\"", "\"", ",", "Handler", ":", "p", ",", "SessionUDPFactory", ":", "ciliumSessionUDPFactory", ",", "}", "\n", "p", ".", "TCPServer", "=", "&", "dns", ".", "Server", "{", "Listener", ":", "TCPListener", ",", "Addr", ":", "p", ".", "BindAddr", ",", "Net", ":", "\"", "\"", ",", "Handler", ":", "p", "}", "\n", "log", ".", "WithField", "(", "\"", "\"", ",", "p", ".", "BindAddr", ")", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "for", "_", ",", "s", ":=", "range", "[", "]", "*", "dns", ".", "Server", "{", "p", ".", "UDPServer", ",", "p", ".", "TCPServer", "}", "{", "go", "func", "(", "server", "*", "dns", ".", "Server", ")", "{", "// try 5 times during a single ProxyBindTimeout period. We fatal here", "// because we have no other way to indicate failure this late.", "start", ":=", "time", ".", "Now", "(", ")", "\n", "for", "time", ".", "Since", "(", "start", ")", "<", "ProxyBindTimeout", "{", "if", "err", ":=", "server", ".", "ActivateAndServe", "(", ")", ";", "err", "!=", "nil", "{", "log", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "\"", "\"", ",", "server", ".", "Net", ",", "server", ".", "Addr", ")", "\n", "}", "\n", "time", ".", "Sleep", "(", "ProxyBindRetryInterval", ")", "\n", "}", "\n", "log", ".", "Fatalf", "(", "\"", "\"", ",", "server", ".", "Net", ",", "server", ".", "Addr", ")", "\n", "}", "(", "s", ")", "\n", "}", "\n\n", "// Bind the DNS forwarding clients on UDP and TCP", "p", ".", "UDPClient", "=", "&", "dns", ".", "Client", "{", "Net", ":", "\"", "\"", ",", "Timeout", ":", "ProxyForwardTimeout", ",", "SingleInflight", ":", "true", "}", "\n", "p", ".", "TCPClient", "=", "&", "dns", ".", "Client", "{", "Net", ":", "\"", "\"", ",", "Timeout", ":", "ProxyForwardTimeout", ",", "SingleInflight", ":", "true", "}", "\n\n", "return", "p", ",", "nil", "\n", "}" ]
// address and port. // address is the bind address to listen on. Empty binds to all local // addresses. // port is the port to bind to for both UDP and TCP. 0 causes the kernel to // select a free port. // lookupEPFunc will be called with the source IP of DNS requests, and expects // a unique identifier for the endpoint that made the request. // notifyFunc will be called with DNS response data that is returned to a // requesting endpoint. Note that denied requests will not trigger this // callback.
[ "address", "and", "port", ".", "address", "is", "the", "bind", "address", "to", "listen", "on", ".", "Empty", "binds", "to", "all", "local", "addresses", ".", "port", "is", "the", "port", "to", "bind", "to", "for", "both", "UDP", "and", "TCP", ".", "0", "causes", "the", "kernel", "to", "select", "a", "free", "port", ".", "lookupEPFunc", "will", "be", "called", "with", "the", "source", "IP", "of", "DNS", "requests", "and", "expects", "a", "unique", "identifier", "for", "the", "endpoint", "that", "made", "the", "request", ".", "notifyFunc", "will", "be", "called", "with", "DNS", "response", "data", "that", "is", "returned", "to", "a", "requesting", "endpoint", ".", "Note", "that", "denied", "requests", "will", "not", "trigger", "this", "callback", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/fqdn/dnsproxy/proxy.go#L155-L220
162,874
cilium/cilium
pkg/fqdn/dnsproxy/proxy.go
AddAllowed
func (p *DNSProxy) AddAllowed(reStr, endpointID string) { log.WithField(logfields.DNSName, reStr).Debug("Adding allowed DNS FQDN pattern") p.UpdateAllowed([]string{reStr}, nil, endpointID) }
go
func (p *DNSProxy) AddAllowed(reStr, endpointID string) { log.WithField(logfields.DNSName, reStr).Debug("Adding allowed DNS FQDN pattern") p.UpdateAllowed([]string{reStr}, nil, endpointID) }
[ "func", "(", "p", "*", "DNSProxy", ")", "AddAllowed", "(", "reStr", ",", "endpointID", "string", ")", "{", "log", ".", "WithField", "(", "logfields", ".", "DNSName", ",", "reStr", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "p", ".", "UpdateAllowed", "(", "[", "]", "string", "{", "reStr", "}", ",", "nil", ",", "endpointID", ")", "\n", "}" ]
// AddAllowed adds reStr, a regexp, to the DNS lookups the proxy allows.
[ "AddAllowed", "adds", "reStr", "a", "regexp", "to", "the", "DNS", "lookups", "the", "proxy", "allows", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/fqdn/dnsproxy/proxy.go#L223-L226
162,875
cilium/cilium
pkg/fqdn/dnsproxy/proxy.go
UpdateAllowed
func (p *DNSProxy) UpdateAllowed(reStrToAdd, reStrToRemove []string, endpointID string) { for i := range reStrToAdd { reStrToAdd[i] = prepareNameMatch(reStrToAdd[i]) } for i := range reStrToRemove { reStrToRemove[i] = prepareNameMatch(reStrToRemove[i]) } p.Lock() defer p.Unlock() for _, reStr := range reStrToRemove { p.allowed.Remove(reStr, endpointID) } for _, reStr := range reStrToAdd { p.allowed.Add(reStr, endpointID) } }
go
func (p *DNSProxy) UpdateAllowed(reStrToAdd, reStrToRemove []string, endpointID string) { for i := range reStrToAdd { reStrToAdd[i] = prepareNameMatch(reStrToAdd[i]) } for i := range reStrToRemove { reStrToRemove[i] = prepareNameMatch(reStrToRemove[i]) } p.Lock() defer p.Unlock() for _, reStr := range reStrToRemove { p.allowed.Remove(reStr, endpointID) } for _, reStr := range reStrToAdd { p.allowed.Add(reStr, endpointID) } }
[ "func", "(", "p", "*", "DNSProxy", ")", "UpdateAllowed", "(", "reStrToAdd", ",", "reStrToRemove", "[", "]", "string", ",", "endpointID", "string", ")", "{", "for", "i", ":=", "range", "reStrToAdd", "{", "reStrToAdd", "[", "i", "]", "=", "prepareNameMatch", "(", "reStrToAdd", "[", "i", "]", ")", "\n", "}", "\n", "for", "i", ":=", "range", "reStrToRemove", "{", "reStrToRemove", "[", "i", "]", "=", "prepareNameMatch", "(", "reStrToRemove", "[", "i", "]", ")", "\n", "}", "\n\n", "p", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "Unlock", "(", ")", "\n", "for", "_", ",", "reStr", ":=", "range", "reStrToRemove", "{", "p", ".", "allowed", ".", "Remove", "(", "reStr", ",", "endpointID", ")", "\n", "}", "\n", "for", "_", ",", "reStr", ":=", "range", "reStrToAdd", "{", "p", ".", "allowed", ".", "Add", "(", "reStr", ",", "endpointID", ")", "\n", "}", "\n", "}" ]
// UpdateAllowed adds and removes reStr while holding the lock. This is a bit // of a hack to ensure atomic updates of rules until we replace the tracking // with something better.
[ "UpdateAllowed", "adds", "and", "removes", "reStr", "while", "holding", "the", "lock", ".", "This", "is", "a", "bit", "of", "a", "hack", "to", "ensure", "atomic", "updates", "of", "rules", "until", "we", "replace", "the", "tracking", "with", "something", "better", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/fqdn/dnsproxy/proxy.go#L239-L255
162,876
cilium/cilium
pkg/fqdn/dnsproxy/proxy.go
sendRefused
func (p *DNSProxy) sendRefused(scopedLog *logrus.Entry, w dns.ResponseWriter, request *dns.Msg) (err error) { refused := new(dns.Msg) refused.SetRcode(request, p.rejectReply) if err = w.WriteMsg(refused); err != nil { scopedLog.WithError(err).Error("Cannot send REFUSED response") err = fmt.Errorf("cannot send REFUSED response: %s", err) } return err }
go
func (p *DNSProxy) sendRefused(scopedLog *logrus.Entry, w dns.ResponseWriter, request *dns.Msg) (err error) { refused := new(dns.Msg) refused.SetRcode(request, p.rejectReply) if err = w.WriteMsg(refused); err != nil { scopedLog.WithError(err).Error("Cannot send REFUSED response") err = fmt.Errorf("cannot send REFUSED response: %s", err) } return err }
[ "func", "(", "p", "*", "DNSProxy", ")", "sendRefused", "(", "scopedLog", "*", "logrus", ".", "Entry", ",", "w", "dns", ".", "ResponseWriter", ",", "request", "*", "dns", ".", "Msg", ")", "(", "err", "error", ")", "{", "refused", ":=", "new", "(", "dns", ".", "Msg", ")", "\n", "refused", ".", "SetRcode", "(", "request", ",", "p", ".", "rejectReply", ")", "\n\n", "if", "err", "=", "w", ".", "WriteMsg", "(", "refused", ")", ";", "err", "!=", "nil", "{", "scopedLog", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// sendRefused creates and sends a REFUSED response for request to w // The returned error is logged with scopedLog and is returned for convenience
[ "sendRefused", "creates", "and", "sends", "a", "REFUSED", "response", "for", "request", "to", "w", "The", "returned", "error", "is", "logged", "with", "scopedLog", "and", "is", "returned", "for", "convenience" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/fqdn/dnsproxy/proxy.go#L392-L401
162,877
cilium/cilium
pkg/fqdn/dnsproxy/proxy.go
SetRejectReply
func (p *DNSProxy) SetRejectReply(opt string) { switch strings.ToLower(opt) { case strings.ToLower(option.FQDNProxyDenyWithNameError): p.rejectReply = dns.RcodeNameError case strings.ToLower(option.FQDNProxyDenyWithRefused): p.rejectReply = dns.RcodeRefused default: log.Infof("DNS reject response '%s' is not valid, available options are '%v'", opt, option.FQDNRejectOptions) return } }
go
func (p *DNSProxy) SetRejectReply(opt string) { switch strings.ToLower(opt) { case strings.ToLower(option.FQDNProxyDenyWithNameError): p.rejectReply = dns.RcodeNameError case strings.ToLower(option.FQDNProxyDenyWithRefused): p.rejectReply = dns.RcodeRefused default: log.Infof("DNS reject response '%s' is not valid, available options are '%v'", opt, option.FQDNRejectOptions) return } }
[ "func", "(", "p", "*", "DNSProxy", ")", "SetRejectReply", "(", "opt", "string", ")", "{", "switch", "strings", ".", "ToLower", "(", "opt", ")", "{", "case", "strings", ".", "ToLower", "(", "option", ".", "FQDNProxyDenyWithNameError", ")", ":", "p", ".", "rejectReply", "=", "dns", ".", "RcodeNameError", "\n", "case", "strings", ".", "ToLower", "(", "option", ".", "FQDNProxyDenyWithRefused", ")", ":", "p", ".", "rejectReply", "=", "dns", ".", "RcodeRefused", "\n", "default", ":", "log", ".", "Infof", "(", "\"", "\"", ",", "opt", ",", "option", ".", "FQDNRejectOptions", ")", "\n", "return", "\n", "}", "\n", "}" ]
// SetRejectReply sets the default reject reply on denied dns responses.
[ "SetRejectReply", "sets", "the", "default", "reject", "reply", "on", "denied", "dns", "responses", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/fqdn/dnsproxy/proxy.go#L404-L415
162,878
cilium/cilium
pkg/fqdn/dnsproxy/proxy.go
ExtractMsgDetails
func ExtractMsgDetails(msg *dns.Msg) (qname string, responseIPs []net.IP, TTL uint32, CNAMEs []string, rcode int, answerTypes []uint16, qTypes []uint16, err error) { if len(msg.Question) == 0 { return "", nil, 0, nil, 0, nil, nil, errors.New("Invalid DNS message") } qname = strings.ToLower(string(msg.Question[0].Name)) // rrName is the name the next RR should include. // This will change when we see CNAMEs. rrName := strings.ToLower(qname) TTL = math.MaxUint32 // a TTL must exist in the RRs answerTypes = make([]uint16, 0, len(msg.Answer)) for _, ans := range msg.Answer { // Ensure we have records for DNS names we expect if strings.ToLower(ans.Header().Name) != rrName { return qname, nil, 0, nil, 0, nil, nil, fmt.Errorf("Unexpected name (%s) in RRs for %s (query for %s)", ans, rrName, qname) } // Handle A, AAAA and CNAME records by accumulating IPs and lowest TTL switch ans := ans.(type) { case *dns.A: responseIPs = append(responseIPs, ans.A) if TTL > ans.Hdr.Ttl { TTL = ans.Hdr.Ttl } case *dns.AAAA: responseIPs = append(responseIPs, ans.AAAA) if TTL > ans.Hdr.Ttl { TTL = ans.Hdr.Ttl } case *dns.CNAME: // We still track the TTL because the lowest TTL in the chain // determines the valid caching time for the whole response. if TTL > ans.Hdr.Ttl { TTL = ans.Hdr.Ttl } rrName = strings.ToLower(ans.Target) CNAMEs = append(CNAMEs, ans.Target) } answerTypes = append(answerTypes, ans.Header().Rrtype) } qTypes = make([]uint16, 0, len(msg.Question)) for _, q := range msg.Question { qTypes = append(qTypes, q.Qtype) } return qname, responseIPs, TTL, CNAMEs, msg.Rcode, answerTypes, qTypes, nil }
go
func ExtractMsgDetails(msg *dns.Msg) (qname string, responseIPs []net.IP, TTL uint32, CNAMEs []string, rcode int, answerTypes []uint16, qTypes []uint16, err error) { if len(msg.Question) == 0 { return "", nil, 0, nil, 0, nil, nil, errors.New("Invalid DNS message") } qname = strings.ToLower(string(msg.Question[0].Name)) // rrName is the name the next RR should include. // This will change when we see CNAMEs. rrName := strings.ToLower(qname) TTL = math.MaxUint32 // a TTL must exist in the RRs answerTypes = make([]uint16, 0, len(msg.Answer)) for _, ans := range msg.Answer { // Ensure we have records for DNS names we expect if strings.ToLower(ans.Header().Name) != rrName { return qname, nil, 0, nil, 0, nil, nil, fmt.Errorf("Unexpected name (%s) in RRs for %s (query for %s)", ans, rrName, qname) } // Handle A, AAAA and CNAME records by accumulating IPs and lowest TTL switch ans := ans.(type) { case *dns.A: responseIPs = append(responseIPs, ans.A) if TTL > ans.Hdr.Ttl { TTL = ans.Hdr.Ttl } case *dns.AAAA: responseIPs = append(responseIPs, ans.AAAA) if TTL > ans.Hdr.Ttl { TTL = ans.Hdr.Ttl } case *dns.CNAME: // We still track the TTL because the lowest TTL in the chain // determines the valid caching time for the whole response. if TTL > ans.Hdr.Ttl { TTL = ans.Hdr.Ttl } rrName = strings.ToLower(ans.Target) CNAMEs = append(CNAMEs, ans.Target) } answerTypes = append(answerTypes, ans.Header().Rrtype) } qTypes = make([]uint16, 0, len(msg.Question)) for _, q := range msg.Question { qTypes = append(qTypes, q.Qtype) } return qname, responseIPs, TTL, CNAMEs, msg.Rcode, answerTypes, qTypes, nil }
[ "func", "ExtractMsgDetails", "(", "msg", "*", "dns", ".", "Msg", ")", "(", "qname", "string", ",", "responseIPs", "[", "]", "net", ".", "IP", ",", "TTL", "uint32", ",", "CNAMEs", "[", "]", "string", ",", "rcode", "int", ",", "answerTypes", "[", "]", "uint16", ",", "qTypes", "[", "]", "uint16", ",", "err", "error", ")", "{", "if", "len", "(", "msg", ".", "Question", ")", "==", "0", "{", "return", "\"", "\"", ",", "nil", ",", "0", ",", "nil", ",", "0", ",", "nil", ",", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "qname", "=", "strings", ".", "ToLower", "(", "string", "(", "msg", ".", "Question", "[", "0", "]", ".", "Name", ")", ")", "\n\n", "// rrName is the name the next RR should include.", "// This will change when we see CNAMEs.", "rrName", ":=", "strings", ".", "ToLower", "(", "qname", ")", "\n\n", "TTL", "=", "math", ".", "MaxUint32", "// a TTL must exist in the RRs", "\n\n", "answerTypes", "=", "make", "(", "[", "]", "uint16", ",", "0", ",", "len", "(", "msg", ".", "Answer", ")", ")", "\n", "for", "_", ",", "ans", ":=", "range", "msg", ".", "Answer", "{", "// Ensure we have records for DNS names we expect", "if", "strings", ".", "ToLower", "(", "ans", ".", "Header", "(", ")", ".", "Name", ")", "!=", "rrName", "{", "return", "qname", ",", "nil", ",", "0", ",", "nil", ",", "0", ",", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ans", ",", "rrName", ",", "qname", ")", "\n", "}", "\n\n", "// Handle A, AAAA and CNAME records by accumulating IPs and lowest TTL", "switch", "ans", ":=", "ans", ".", "(", "type", ")", "{", "case", "*", "dns", ".", "A", ":", "responseIPs", "=", "append", "(", "responseIPs", ",", "ans", ".", "A", ")", "\n", "if", "TTL", ">", "ans", ".", "Hdr", ".", "Ttl", "{", "TTL", "=", "ans", ".", "Hdr", ".", "Ttl", "\n", "}", "\n", "case", "*", "dns", ".", "AAAA", ":", "responseIPs", "=", "append", "(", "responseIPs", ",", "ans", ".", "AAAA", ")", "\n", "if", "TTL", ">", "ans", ".", "Hdr", ".", "Ttl", "{", "TTL", "=", "ans", ".", "Hdr", ".", "Ttl", "\n", "}", "\n", "case", "*", "dns", ".", "CNAME", ":", "// We still track the TTL because the lowest TTL in the chain", "// determines the valid caching time for the whole response.", "if", "TTL", ">", "ans", ".", "Hdr", ".", "Ttl", "{", "TTL", "=", "ans", ".", "Hdr", ".", "Ttl", "\n", "}", "\n", "rrName", "=", "strings", ".", "ToLower", "(", "ans", ".", "Target", ")", "\n", "CNAMEs", "=", "append", "(", "CNAMEs", ",", "ans", ".", "Target", ")", "\n", "}", "\n", "answerTypes", "=", "append", "(", "answerTypes", ",", "ans", ".", "Header", "(", ")", ".", "Rrtype", ")", "\n", "}", "\n\n", "qTypes", "=", "make", "(", "[", "]", "uint16", ",", "0", ",", "len", "(", "msg", ".", "Question", ")", ")", "\n", "for", "_", ",", "q", ":=", "range", "msg", ".", "Question", "{", "qTypes", "=", "append", "(", "qTypes", ",", "q", ".", "Qtype", ")", "\n", "}", "\n\n", "return", "qname", ",", "responseIPs", ",", "TTL", ",", "CNAMEs", ",", "msg", ".", "Rcode", ",", "answerTypes", ",", "qTypes", ",", "nil", "\n", "}" ]
// ExtractMsgDetails extracts a canonical query name, any IPs in a response, // the lowest applicable TTL, rcode, anwer rr types and question types // When a CNAME is returned the chain is collapsed down, keeping the lowest TTL, // and CNAME targets are returned.
[ "ExtractMsgDetails", "extracts", "a", "canonical", "query", "name", "any", "IPs", "in", "a", "response", "the", "lowest", "applicable", "TTL", "rcode", "anwer", "rr", "types", "and", "question", "types", "When", "a", "CNAME", "is", "returned", "the", "chain", "is", "collapsed", "down", "keeping", "the", "lowest", "TTL", "and", "CNAME", "targets", "are", "returned", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/fqdn/dnsproxy/proxy.go#L421-L470
162,879
cilium/cilium
monitor/launch/launcher.go
NewNodeMonitor
func NewNodeMonitor(queueSize int) *NodeMonitor { nm := &NodeMonitor{ queue: make(chan []byte, queueSize), } go nm.eventDrainer() return nm }
go
func NewNodeMonitor(queueSize int) *NodeMonitor { nm := &NodeMonitor{ queue: make(chan []byte, queueSize), } go nm.eventDrainer() return nm }
[ "func", "NewNodeMonitor", "(", "queueSize", "int", ")", "*", "NodeMonitor", "{", "nm", ":=", "&", "NodeMonitor", "{", "queue", ":", "make", "(", "chan", "[", "]", "byte", ",", "queueSize", ")", ",", "}", "\n\n", "go", "nm", ".", "eventDrainer", "(", ")", "\n\n", "return", "nm", "\n", "}" ]
// NewNodeMonitor returns a new node monitor
[ "NewNodeMonitor", "returns", "a", "new", "node", "monitor" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/monitor/launch/launcher.go#L60-L68
162,880
cilium/cilium
monitor/launch/launcher.go
run
func (nm *NodeMonitor) run(sockPath, bpfRoot string) error { os.Remove(sockPath) if err := syscall.Mkfifo(sockPath, 0600); err != nil { return fmt.Errorf("Unable to create named pipe %s: %s", sockPath, err) } defer os.Remove(sockPath) pipe, err := os.OpenFile(sockPath, os.O_RDWR, 0600) if err != nil { return fmt.Errorf("Unable to open named pipe for writing: %s", err) } defer pipe.Close() nm.pipeLock.Lock() nm.pipe = pipe nm.pipeLock.Unlock() nm.Launcher.SetArgs([]string{"--bpf-root", bpfRoot}) if err := nm.Launcher.Run(); err != nil { return err } metrics.SubprocessStart.WithLabelValues(targetName).Inc() r := bufio.NewReader(nm.GetStdout()) for nm.GetProcess() != nil { l, err := r.ReadBytes('\n') // this is a blocking read if err != nil { return fmt.Errorf("Unable to read stdout from monitor: %s", err) } var tmp *models.MonitorStatus if err := json.Unmarshal(l, &tmp); err != nil { return fmt.Errorf("Unable to unmarshal stdout from monitor: %s", err) } nm.setState(tmp) } return fmt.Errorf("Monitor process quit unexepctedly") }
go
func (nm *NodeMonitor) run(sockPath, bpfRoot string) error { os.Remove(sockPath) if err := syscall.Mkfifo(sockPath, 0600); err != nil { return fmt.Errorf("Unable to create named pipe %s: %s", sockPath, err) } defer os.Remove(sockPath) pipe, err := os.OpenFile(sockPath, os.O_RDWR, 0600) if err != nil { return fmt.Errorf("Unable to open named pipe for writing: %s", err) } defer pipe.Close() nm.pipeLock.Lock() nm.pipe = pipe nm.pipeLock.Unlock() nm.Launcher.SetArgs([]string{"--bpf-root", bpfRoot}) if err := nm.Launcher.Run(); err != nil { return err } metrics.SubprocessStart.WithLabelValues(targetName).Inc() r := bufio.NewReader(nm.GetStdout()) for nm.GetProcess() != nil { l, err := r.ReadBytes('\n') // this is a blocking read if err != nil { return fmt.Errorf("Unable to read stdout from monitor: %s", err) } var tmp *models.MonitorStatus if err := json.Unmarshal(l, &tmp); err != nil { return fmt.Errorf("Unable to unmarshal stdout from monitor: %s", err) } nm.setState(tmp) } return fmt.Errorf("Monitor process quit unexepctedly") }
[ "func", "(", "nm", "*", "NodeMonitor", ")", "run", "(", "sockPath", ",", "bpfRoot", "string", ")", "error", "{", "os", ".", "Remove", "(", "sockPath", ")", "\n", "if", "err", ":=", "syscall", ".", "Mkfifo", "(", "sockPath", ",", "0600", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "sockPath", ",", "err", ")", "\n", "}", "\n\n", "defer", "os", ".", "Remove", "(", "sockPath", ")", "\n\n", "pipe", ",", "err", ":=", "os", ".", "OpenFile", "(", "sockPath", ",", "os", ".", "O_RDWR", ",", "0600", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "defer", "pipe", ".", "Close", "(", ")", "\n\n", "nm", ".", "pipeLock", ".", "Lock", "(", ")", "\n", "nm", ".", "pipe", "=", "pipe", "\n", "nm", ".", "pipeLock", ".", "Unlock", "(", ")", "\n\n", "nm", ".", "Launcher", ".", "SetArgs", "(", "[", "]", "string", "{", "\"", "\"", ",", "bpfRoot", "}", ")", "\n", "if", "err", ":=", "nm", ".", "Launcher", ".", "Run", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "metrics", ".", "SubprocessStart", ".", "WithLabelValues", "(", "targetName", ")", ".", "Inc", "(", ")", "\n\n", "r", ":=", "bufio", ".", "NewReader", "(", "nm", ".", "GetStdout", "(", ")", ")", "\n", "for", "nm", ".", "GetProcess", "(", ")", "!=", "nil", "{", "l", ",", "err", ":=", "r", ".", "ReadBytes", "(", "'\\n'", ")", "// this is a blocking read", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "var", "tmp", "*", "models", ".", "MonitorStatus", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "l", ",", "&", "tmp", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "nm", ".", "setState", "(", "tmp", ")", "\n", "}", "\n\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}" ]
// run creates a FIFO at sockPath, launches the monitor as sub process and then // reads stdout from the monitor and updates nm.state accordingly. The function // returns with an error if the FIFO cannot be created, opened or if the an // error was encountered while reading stdout from the monitor. The FIFO is always // removed again when the function returns.
[ "run", "creates", "a", "FIFO", "at", "sockPath", "launches", "the", "monitor", "as", "sub", "process", "and", "then", "reads", "stdout", "from", "the", "monitor", "and", "updates", "nm", ".", "state", "accordingly", ".", "The", "function", "returns", "with", "an", "error", "if", "the", "FIFO", "cannot", "be", "created", "opened", "or", "if", "the", "an", "error", "was", "encountered", "while", "reading", "stdout", "from", "the", "monitor", ".", "The", "FIFO", "is", "always", "removed", "again", "when", "the", "function", "returns", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/monitor/launch/launcher.go#L80-L121
162,881
cilium/cilium
monitor/launch/launcher.go
Run
func (nm *NodeMonitor) Run(sockPath, bpfRoot string) { backoffConfig := backoff.Exponential{Min: time.Second, Max: 2 * time.Minute} nm.SetTarget(targetName) for { if err := nm.run(sockPath, bpfRoot); err != nil { log.WithError(err).Warning("Error while running monitor") } backoffConfig.Wait(context.TODO()) } }
go
func (nm *NodeMonitor) Run(sockPath, bpfRoot string) { backoffConfig := backoff.Exponential{Min: time.Second, Max: 2 * time.Minute} nm.SetTarget(targetName) for { if err := nm.run(sockPath, bpfRoot); err != nil { log.WithError(err).Warning("Error while running monitor") } backoffConfig.Wait(context.TODO()) } }
[ "func", "(", "nm", "*", "NodeMonitor", ")", "Run", "(", "sockPath", ",", "bpfRoot", "string", ")", "{", "backoffConfig", ":=", "backoff", ".", "Exponential", "{", "Min", ":", "time", ".", "Second", ",", "Max", ":", "2", "*", "time", ".", "Minute", "}", "\n\n", "nm", ".", "SetTarget", "(", "targetName", ")", "\n", "for", "{", "if", "err", ":=", "nm", ".", "run", "(", "sockPath", ",", "bpfRoot", ")", ";", "err", "!=", "nil", "{", "log", ".", "WithError", "(", "err", ")", ".", "Warning", "(", "\"", "\"", ")", "\n", "}", "\n\n", "backoffConfig", ".", "Wait", "(", "context", ".", "TODO", "(", ")", ")", "\n", "}", "\n", "}" ]
// Run starts the node monitor and keeps on restarting it. The function will // never return.
[ "Run", "starts", "the", "node", "monitor", "and", "keeps", "on", "restarting", "it", ".", "The", "function", "will", "never", "return", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/monitor/launch/launcher.go#L125-L136
162,882
cilium/cilium
monitor/launch/launcher.go
State
func (nm *NodeMonitor) State() *models.MonitorStatus { nm.Mutex.RLock() state := nm.state nm.Mutex.RUnlock() return state }
go
func (nm *NodeMonitor) State() *models.MonitorStatus { nm.Mutex.RLock() state := nm.state nm.Mutex.RUnlock() return state }
[ "func", "(", "nm", "*", "NodeMonitor", ")", "State", "(", ")", "*", "models", ".", "MonitorStatus", "{", "nm", ".", "Mutex", ".", "RLock", "(", ")", "\n", "state", ":=", "nm", ".", "state", "\n", "nm", ".", "Mutex", ".", "RUnlock", "(", ")", "\n", "return", "state", "\n", "}" ]
// State returns the monitor status.
[ "State", "returns", "the", "monitor", "status", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/monitor/launch/launcher.go#L139-L144
162,883
cilium/cilium
monitor/launch/launcher.go
setState
func (nm *NodeMonitor) setState(state *models.MonitorStatus) { nm.Mutex.Lock() nm.state = state nm.Mutex.Unlock() }
go
func (nm *NodeMonitor) setState(state *models.MonitorStatus) { nm.Mutex.Lock() nm.state = state nm.Mutex.Unlock() }
[ "func", "(", "nm", "*", "NodeMonitor", ")", "setState", "(", "state", "*", "models", ".", "MonitorStatus", ")", "{", "nm", ".", "Mutex", ".", "Lock", "(", ")", "\n", "nm", ".", "state", "=", "state", "\n", "nm", ".", "Mutex", ".", "Unlock", "(", ")", "\n", "}" ]
// setState sets the internal state monitor with the given state.
[ "setState", "sets", "the", "internal", "state", "monitor", "with", "the", "given", "state", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/monitor/launch/launcher.go#L147-L151
162,884
cilium/cilium
monitor/launch/launcher.go
SendEvent
func (nm *NodeMonitor) SendEvent(typ int, event interface{}) error { var buf bytes.Buffer if err := gob.NewEncoder(&buf).Encode(event); err != nil { nm.bumpLost() return fmt.Errorf("Unable to gob encode: %s", err) } select { case nm.queue <- append([]byte{byte(typ)}, buf.Bytes()...): default: nm.bumpLost() return fmt.Errorf("Monitor queue is full, discarding notification") } return nil }
go
func (nm *NodeMonitor) SendEvent(typ int, event interface{}) error { var buf bytes.Buffer if err := gob.NewEncoder(&buf).Encode(event); err != nil { nm.bumpLost() return fmt.Errorf("Unable to gob encode: %s", err) } select { case nm.queue <- append([]byte{byte(typ)}, buf.Bytes()...): default: nm.bumpLost() return fmt.Errorf("Monitor queue is full, discarding notification") } return nil }
[ "func", "(", "nm", "*", "NodeMonitor", ")", "SendEvent", "(", "typ", "int", ",", "event", "interface", "{", "}", ")", "error", "{", "var", "buf", "bytes", ".", "Buffer", "\n\n", "if", "err", ":=", "gob", ".", "NewEncoder", "(", "&", "buf", ")", ".", "Encode", "(", "event", ")", ";", "err", "!=", "nil", "{", "nm", ".", "bumpLost", "(", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "select", "{", "case", "nm", ".", "queue", "<-", "append", "(", "[", "]", "byte", "{", "byte", "(", "typ", ")", "}", ",", "buf", ".", "Bytes", "(", ")", "...", ")", ":", "default", ":", "nm", ".", "bumpLost", "(", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// SendEvent sends an event to the node monitor which will then distribute to // all monitor listeners
[ "SendEvent", "sends", "an", "event", "to", "the", "node", "monitor", "which", "will", "then", "distribute", "to", "all", "monitor", "listeners" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/monitor/launch/launcher.go#L155-L171
162,885
cilium/cilium
monitor/launch/launcher.go
bumpLost
func (nm *NodeMonitor) bumpLost() { nm.pipeLock.Lock() nm.lost++ nm.pipeLock.Unlock() }
go
func (nm *NodeMonitor) bumpLost() { nm.pipeLock.Lock() nm.lost++ nm.pipeLock.Unlock() }
[ "func", "(", "nm", "*", "NodeMonitor", ")", "bumpLost", "(", ")", "{", "nm", ".", "pipeLock", ".", "Lock", "(", ")", "\n", "nm", ".", "lost", "++", "\n", "nm", ".", "pipeLock", ".", "Unlock", "(", ")", "\n", "}" ]
// bumpLost accounts for a lost notification
[ "bumpLost", "accounts", "for", "a", "lost", "notification" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/monitor/launch/launcher.go#L174-L178
162,886
cilium/cilium
api/v1/health/client/connectivity/put_status_probe_parameters.go
WithTimeout
func (o *PutStatusProbeParams) WithTimeout(timeout time.Duration) *PutStatusProbeParams { o.SetTimeout(timeout) return o }
go
func (o *PutStatusProbeParams) WithTimeout(timeout time.Duration) *PutStatusProbeParams { o.SetTimeout(timeout) return o }
[ "func", "(", "o", "*", "PutStatusProbeParams", ")", "WithTimeout", "(", "timeout", "time", ".", "Duration", ")", "*", "PutStatusProbeParams", "{", "o", ".", "SetTimeout", "(", "timeout", ")", "\n", "return", "o", "\n", "}" ]
// WithTimeout adds the timeout to the put status probe params
[ "WithTimeout", "adds", "the", "timeout", "to", "the", "put", "status", "probe", "params" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/api/v1/health/client/connectivity/put_status_probe_parameters.go#L69-L72
162,887
cilium/cilium
api/v1/health/client/connectivity/put_status_probe_parameters.go
WithContext
func (o *PutStatusProbeParams) WithContext(ctx context.Context) *PutStatusProbeParams { o.SetContext(ctx) return o }
go
func (o *PutStatusProbeParams) WithContext(ctx context.Context) *PutStatusProbeParams { o.SetContext(ctx) return o }
[ "func", "(", "o", "*", "PutStatusProbeParams", ")", "WithContext", "(", "ctx", "context", ".", "Context", ")", "*", "PutStatusProbeParams", "{", "o", ".", "SetContext", "(", "ctx", ")", "\n", "return", "o", "\n", "}" ]
// WithContext adds the context to the put status probe params
[ "WithContext", "adds", "the", "context", "to", "the", "put", "status", "probe", "params" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/api/v1/health/client/connectivity/put_status_probe_parameters.go#L80-L83
162,888
cilium/cilium
api/v1/health/client/connectivity/put_status_probe_parameters.go
WithHTTPClient
func (o *PutStatusProbeParams) WithHTTPClient(client *http.Client) *PutStatusProbeParams { o.SetHTTPClient(client) return o }
go
func (o *PutStatusProbeParams) WithHTTPClient(client *http.Client) *PutStatusProbeParams { o.SetHTTPClient(client) return o }
[ "func", "(", "o", "*", "PutStatusProbeParams", ")", "WithHTTPClient", "(", "client", "*", "http", ".", "Client", ")", "*", "PutStatusProbeParams", "{", "o", ".", "SetHTTPClient", "(", "client", ")", "\n", "return", "o", "\n", "}" ]
// WithHTTPClient adds the HTTPClient to the put status probe params
[ "WithHTTPClient", "adds", "the", "HTTPClient", "to", "the", "put", "status", "probe", "params" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/api/v1/health/client/connectivity/put_status_probe_parameters.go#L91-L94
162,889
cilium/cilium
pkg/envoy/envoy.go
GetEnvoyVersion
func GetEnvoyVersion() string { out, err := exec.Command(ciliumEnvoy, "--version").Output() if err != nil { log.WithError(err).Fatalf("Envoy: Binary %q cannot be executed", ciliumEnvoy) } return strings.TrimSpace(string(out)) }
go
func GetEnvoyVersion() string { out, err := exec.Command(ciliumEnvoy, "--version").Output() if err != nil { log.WithError(err).Fatalf("Envoy: Binary %q cannot be executed", ciliumEnvoy) } return strings.TrimSpace(string(out)) }
[ "func", "GetEnvoyVersion", "(", ")", "string", "{", "out", ",", "err", ":=", "exec", ".", "Command", "(", "ciliumEnvoy", ",", "\"", "\"", ")", ".", "Output", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "WithError", "(", "err", ")", ".", "Fatalf", "(", "\"", "\"", ",", "ciliumEnvoy", ")", "\n", "}", "\n", "return", "strings", ".", "TrimSpace", "(", "string", "(", "out", ")", ")", "\n", "}" ]
// GetEnvoyVersion returns the envoy binary version string
[ "GetEnvoyVersion", "returns", "the", "envoy", "binary", "version", "string" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/envoy/envoy.go#L141-L147
162,890
cilium/cilium
pkg/envoy/envoy.go
newEnvoyLogPiper
func newEnvoyLogPiper() io.WriteCloser { reader, writer := io.Pipe() scanner := bufio.NewScanner(reader) go func() { scopedLog := log.WithFields(logrus.Fields{ logfields.LogSubsys: "unknown", logfields.ThreadID: "unknown", }) level := "debug" for scanner.Scan() { line := scanner.Text() var msg string parts := strings.SplitN(line, "|", 4) // Parse the line as a log message written by Envoy, assuming it // uses the configured format: "%t|%l|%n|%v". if len(parts) == 4 { threadID := parts[0] level = parts[1] loggerName := parts[2] // TODO: Parse msg to extract the source filename, line number, etc. msg = fmt.Sprintf("[%s", parts[3]) scopedLog = log.WithFields(logrus.Fields{ logfields.LogSubsys: fmt.Sprintf("envoy-%s", loggerName), logfields.ThreadID: threadID, }) } else { // If this line can't be parsed, it continues a multi-line log // message. In this case, log it at the same level and with the // same fields as the previous line. msg = line } if len(msg) == 0 { continue } // Map the Envoy log level to a logrus level. switch level { case "off", "critical", "error": scopedLog.Error(msg) case "warning": scopedLog.Warn(msg) case "info": scopedLog.Info(msg) case "debug", "trace": scopedLog.Debug(msg) default: scopedLog.Debug(msg) } } if err := scanner.Err(); err != nil { log.WithError(err).Error("Error while parsing Envoy logs") } reader.Close() }() return writer }
go
func newEnvoyLogPiper() io.WriteCloser { reader, writer := io.Pipe() scanner := bufio.NewScanner(reader) go func() { scopedLog := log.WithFields(logrus.Fields{ logfields.LogSubsys: "unknown", logfields.ThreadID: "unknown", }) level := "debug" for scanner.Scan() { line := scanner.Text() var msg string parts := strings.SplitN(line, "|", 4) // Parse the line as a log message written by Envoy, assuming it // uses the configured format: "%t|%l|%n|%v". if len(parts) == 4 { threadID := parts[0] level = parts[1] loggerName := parts[2] // TODO: Parse msg to extract the source filename, line number, etc. msg = fmt.Sprintf("[%s", parts[3]) scopedLog = log.WithFields(logrus.Fields{ logfields.LogSubsys: fmt.Sprintf("envoy-%s", loggerName), logfields.ThreadID: threadID, }) } else { // If this line can't be parsed, it continues a multi-line log // message. In this case, log it at the same level and with the // same fields as the previous line. msg = line } if len(msg) == 0 { continue } // Map the Envoy log level to a logrus level. switch level { case "off", "critical", "error": scopedLog.Error(msg) case "warning": scopedLog.Warn(msg) case "info": scopedLog.Info(msg) case "debug", "trace": scopedLog.Debug(msg) default: scopedLog.Debug(msg) } } if err := scanner.Err(); err != nil { log.WithError(err).Error("Error while parsing Envoy logs") } reader.Close() }() return writer }
[ "func", "newEnvoyLogPiper", "(", ")", "io", ".", "WriteCloser", "{", "reader", ",", "writer", ":=", "io", ".", "Pipe", "(", ")", "\n", "scanner", ":=", "bufio", ".", "NewScanner", "(", "reader", ")", "\n", "go", "func", "(", ")", "{", "scopedLog", ":=", "log", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "logfields", ".", "LogSubsys", ":", "\"", "\"", ",", "logfields", ".", "ThreadID", ":", "\"", "\"", ",", "}", ")", "\n", "level", ":=", "\"", "\"", "\n\n", "for", "scanner", ".", "Scan", "(", ")", "{", "line", ":=", "scanner", ".", "Text", "(", ")", "\n", "var", "msg", "string", "\n\n", "parts", ":=", "strings", ".", "SplitN", "(", "line", ",", "\"", "\"", ",", "4", ")", "\n", "// Parse the line as a log message written by Envoy, assuming it", "// uses the configured format: \"%t|%l|%n|%v\".", "if", "len", "(", "parts", ")", "==", "4", "{", "threadID", ":=", "parts", "[", "0", "]", "\n", "level", "=", "parts", "[", "1", "]", "\n", "loggerName", ":=", "parts", "[", "2", "]", "\n", "// TODO: Parse msg to extract the source filename, line number, etc.", "msg", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "parts", "[", "3", "]", ")", "\n\n", "scopedLog", "=", "log", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "logfields", ".", "LogSubsys", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "loggerName", ")", ",", "logfields", ".", "ThreadID", ":", "threadID", ",", "}", ")", "\n", "}", "else", "{", "// If this line can't be parsed, it continues a multi-line log", "// message. In this case, log it at the same level and with the", "// same fields as the previous line.", "msg", "=", "line", "\n", "}", "\n\n", "if", "len", "(", "msg", ")", "==", "0", "{", "continue", "\n", "}", "\n\n", "// Map the Envoy log level to a logrus level.", "switch", "level", "{", "case", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ":", "scopedLog", ".", "Error", "(", "msg", ")", "\n", "case", "\"", "\"", ":", "scopedLog", ".", "Warn", "(", "msg", ")", "\n", "case", "\"", "\"", ":", "scopedLog", ".", "Info", "(", "msg", ")", "\n", "case", "\"", "\"", ",", "\"", "\"", ":", "scopedLog", ".", "Debug", "(", "msg", ")", "\n", "default", ":", "scopedLog", ".", "Debug", "(", "msg", ")", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "scanner", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "log", ".", "WithError", "(", "err", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "}", "\n", "reader", ".", "Close", "(", ")", "\n", "}", "(", ")", "\n", "return", "writer", "\n", "}" ]
// newEnvoyLogPiper creates a writer that parses and logs log messages written by Envoy.
[ "newEnvoyLogPiper", "creates", "a", "writer", "that", "parses", "and", "logs", "log", "messages", "written", "by", "Envoy", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/envoy/envoy.go#L283-L342
162,891
cilium/cilium
pkg/envoy/envoy.go
isEOF
func isEOF(err error) bool { strerr := err.Error() errlen := len(strerr) return errlen >= 3 && strerr[errlen-3:] == io.EOF.Error() }
go
func isEOF(err error) bool { strerr := err.Error() errlen := len(strerr) return errlen >= 3 && strerr[errlen-3:] == io.EOF.Error() }
[ "func", "isEOF", "(", "err", "error", ")", "bool", "{", "strerr", ":=", "err", ".", "Error", "(", ")", "\n", "errlen", ":=", "len", "(", "strerr", ")", "\n", "return", "errlen", ">=", "3", "&&", "strerr", "[", "errlen", "-", "3", ":", "]", "==", "io", ".", "EOF", ".", "Error", "(", ")", "\n", "}" ]
// isEOF returns true if the error message ends in "EOF". ReadMsgUnix returns extra info in the beginning.
[ "isEOF", "returns", "true", "if", "the", "error", "message", "ends", "in", "EOF", ".", "ReadMsgUnix", "returns", "extra", "info", "in", "the", "beginning", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/envoy/envoy.go#L345-L349
162,892
cilium/cilium
pkg/envoy/envoy.go
StopEnvoy
func (e *Envoy) StopEnvoy() error { close(e.stopCh) err, ok := <-e.errCh if ok { return err } return nil }
go
func (e *Envoy) StopEnvoy() error { close(e.stopCh) err, ok := <-e.errCh if ok { return err } return nil }
[ "func", "(", "e", "*", "Envoy", ")", "StopEnvoy", "(", ")", "error", "{", "close", "(", "e", ".", "stopCh", ")", "\n", "err", ",", "ok", ":=", "<-", "e", ".", "errCh", "\n", "if", "ok", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// StopEnvoy kills the Envoy process started with StartEnvoy. The gRPC API streams are terminated // first.
[ "StopEnvoy", "kills", "the", "Envoy", "process", "started", "with", "StartEnvoy", ".", "The", "gRPC", "API", "streams", "are", "terminated", "first", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/envoy/envoy.go#L353-L360
162,893
cilium/cilium
pkg/envoy/envoy.go
ChangeLogLevel
func (e *Envoy) ChangeLogLevel(level logrus.Level) { e.admin.changeLogLevel(level) }
go
func (e *Envoy) ChangeLogLevel(level logrus.Level) { e.admin.changeLogLevel(level) }
[ "func", "(", "e", "*", "Envoy", ")", "ChangeLogLevel", "(", "level", "logrus", ".", "Level", ")", "{", "e", ".", "admin", ".", "changeLogLevel", "(", "level", ")", "\n", "}" ]
// ChangeLogLevel changes Envoy log level to correspond to the logrus log level 'level'.
[ "ChangeLogLevel", "changes", "Envoy", "log", "level", "to", "correspond", "to", "the", "logrus", "log", "level", "level", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/envoy/envoy.go#L363-L365
162,894
cilium/cilium
pkg/api/apierror.go
New
func New(code int, msg string, args ...interface{}) *APIError { if code <= 0 { code = 500 } if len(args) > 0 { return &APIError{code: code, msg: fmt.Sprintf(msg, args...)} } return &APIError{code: code, msg: msg} }
go
func New(code int, msg string, args ...interface{}) *APIError { if code <= 0 { code = 500 } if len(args) > 0 { return &APIError{code: code, msg: fmt.Sprintf(msg, args...)} } return &APIError{code: code, msg: msg} }
[ "func", "New", "(", "code", "int", ",", "msg", "string", ",", "args", "...", "interface", "{", "}", ")", "*", "APIError", "{", "if", "code", "<=", "0", "{", "code", "=", "500", "\n", "}", "\n\n", "if", "len", "(", "args", ")", ">", "0", "{", "return", "&", "APIError", "{", "code", ":", "code", ",", "msg", ":", "fmt", ".", "Sprintf", "(", "msg", ",", "args", "...", ")", "}", "\n", "}", "\n", "return", "&", "APIError", "{", "code", ":", "code", ",", "msg", ":", "msg", "}", "\n", "}" ]
// New creates a API error from the code, msg and extra arguments.
[ "New", "creates", "a", "API", "error", "from", "the", "code", "msg", "and", "extra", "arguments", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/api/apierror.go#L33-L42
162,895
cilium/cilium
pkg/api/apierror.go
Error
func Error(code int, err error) *APIError { if err == nil { err = fmt.Errorf("Error pointer was nil") } return New(code, err.Error()) }
go
func Error(code int, err error) *APIError { if err == nil { err = fmt.Errorf("Error pointer was nil") } return New(code, err.Error()) }
[ "func", "Error", "(", "code", "int", ",", "err", "error", ")", "*", "APIError", "{", "if", "err", "==", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "New", "(", "code", ",", "err", ".", "Error", "(", ")", ")", "\n", "}" ]
// Error creates a new API error from the code and error.
[ "Error", "creates", "a", "new", "API", "error", "from", "the", "code", "and", "error", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/api/apierror.go#L45-L51
162,896
cilium/cilium
pkg/api/apierror.go
GetModel
func (a *APIError) GetModel() *models.Error { m := models.Error(a.msg) return &m }
go
func (a *APIError) GetModel() *models.Error { m := models.Error(a.msg) return &m }
[ "func", "(", "a", "*", "APIError", ")", "GetModel", "(", ")", "*", "models", ".", "Error", "{", "m", ":=", "models", ".", "Error", "(", "a", ".", "msg", ")", "\n", "return", "&", "m", "\n", "}" ]
// GetModel returns model error.
[ "GetModel", "returns", "model", "error", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/api/apierror.go#L59-L62
162,897
cilium/cilium
pkg/api/apierror.go
WriteResponse
func (a *APIError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { rw.WriteHeader(a.code) m := a.GetModel() if err := producer.Produce(rw, m); err != nil { panic(err) } }
go
func (a *APIError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { rw.WriteHeader(a.code) m := a.GetModel() if err := producer.Produce(rw, m); err != nil { panic(err) } }
[ "func", "(", "a", "*", "APIError", ")", "WriteResponse", "(", "rw", "http", ".", "ResponseWriter", ",", "producer", "runtime", ".", "Producer", ")", "{", "rw", ".", "WriteHeader", "(", "a", ".", "code", ")", "\n", "m", ":=", "a", ".", "GetModel", "(", ")", "\n", "if", "err", ":=", "producer", ".", "Produce", "(", "rw", ",", "m", ")", ";", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n\n", "}" ]
// WriteResponse to the client.
[ "WriteResponse", "to", "the", "client", "." ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/pkg/api/apierror.go#L65-L72
162,898
cilium/cilium
api/v1/health/server/restapi/connectivity/put_status_probe_responses.go
WithPayload
func (o *PutStatusProbeOK) WithPayload(payload *models.HealthStatusResponse) *PutStatusProbeOK { o.Payload = payload return o }
go
func (o *PutStatusProbeOK) WithPayload(payload *models.HealthStatusResponse) *PutStatusProbeOK { o.Payload = payload return o }
[ "func", "(", "o", "*", "PutStatusProbeOK", ")", "WithPayload", "(", "payload", "*", "models", ".", "HealthStatusResponse", ")", "*", "PutStatusProbeOK", "{", "o", ".", "Payload", "=", "payload", "\n", "return", "o", "\n", "}" ]
// WithPayload adds the payload to the put status probe o k response
[ "WithPayload", "adds", "the", "payload", "to", "the", "put", "status", "probe", "o", "k", "response" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/api/v1/health/server/restapi/connectivity/put_status_probe_responses.go#L38-L41
162,899
cilium/cilium
api/v1/health/server/restapi/connectivity/put_status_probe_responses.go
WithPayload
func (o *PutStatusProbeFailed) WithPayload(payload models.Error) *PutStatusProbeFailed { o.Payload = payload return o }
go
func (o *PutStatusProbeFailed) WithPayload(payload models.Error) *PutStatusProbeFailed { o.Payload = payload return o }
[ "func", "(", "o", "*", "PutStatusProbeFailed", ")", "WithPayload", "(", "payload", "models", ".", "Error", ")", "*", "PutStatusProbeFailed", "{", "o", ".", "Payload", "=", "payload", "\n", "return", "o", "\n", "}" ]
// WithPayload adds the payload to the put status probe failed response
[ "WithPayload", "adds", "the", "payload", "to", "the", "put", "status", "probe", "failed", "response" ]
6ecfff82c2314dd9d847645361b57e2646eed64b
https://github.com/cilium/cilium/blob/6ecfff82c2314dd9d847645361b57e2646eed64b/api/v1/health/server/restapi/connectivity/put_status_probe_responses.go#L82-L85