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
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
inverse-inc/packetfence
go/caddy/caddy/caddytls/certificates.go
cacheCertificate
func cacheCertificate(cert Certificate) { if cert.Config == nil { cert.Config = new(Config) } certCacheMu.Lock() if _, ok := certCache[""]; !ok { // use as default - must be *appended* to end of list, or bad things happen! cert.Names = append(cert.Names, "") certCache[""] = cert } for len(certCache)+len(c...
go
func cacheCertificate(cert Certificate) { if cert.Config == nil { cert.Config = new(Config) } certCacheMu.Lock() if _, ok := certCache[""]; !ok { // use as default - must be *appended* to end of list, or bad things happen! cert.Names = append(cert.Names, "") certCache[""] = cert } for len(certCache)+len(c...
[ "func", "cacheCertificate", "(", "cert", "Certificate", ")", "{", "if", "cert", ".", "Config", "==", "nil", "{", "cert", ".", "Config", "=", "new", "(", "Config", ")", "\n", "}", "\n", "certCacheMu", ".", "Lock", "(", ")", "\n", "if", "_", ",", "ok...
// cacheCertificate adds cert to the in-memory cache. If the cache is // empty, cert will be used as the default certificate. If the cache is // full, random entries are deleted until there is room to map all the // names on the certificate. // // This certificate will be keyed to the names in cert.Names. Any name // t...
[ "cacheCertificate", "adds", "cert", "to", "the", "in", "-", "memory", "cache", ".", "If", "the", "cache", "is", "empty", "cert", "will", "be", "used", "as", "the", "default", "certificate", ".", "If", "the", "cache", "is", "full", "random", "entries", "a...
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/certificates.go#L226-L250
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/certificates.go
uncacheCertificate
func uncacheCertificate(name string) { certCacheMu.Lock() delete(certCache, name) certCacheMu.Unlock() }
go
func uncacheCertificate(name string) { certCacheMu.Lock() delete(certCache, name) certCacheMu.Unlock() }
[ "func", "uncacheCertificate", "(", "name", "string", ")", "{", "certCacheMu", ".", "Lock", "(", ")", "\n", "delete", "(", "certCache", ",", "name", ")", "\n", "certCacheMu", ".", "Unlock", "(", ")", "\n", "}" ]
// uncacheCertificate deletes name's certificate from the // cache. If name is not a key in the certificate cache, // this function does nothing.
[ "uncacheCertificate", "deletes", "name", "s", "certificate", "from", "the", "cache", ".", "If", "name", "is", "not", "a", "key", "in", "the", "certificate", "cache", "this", "function", "does", "nothing", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/certificates.go#L255-L259
train
inverse-inc/packetfence
go/caddy/pfconfig/pool.go
setup
func setup(c *caddy.Controller) error { httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler { return PoolHandler{Next: next, refreshLauncher: &sync.Once{}} }) return nil }
go
func setup(c *caddy.Controller) error { httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler { return PoolHandler{Next: next, refreshLauncher: &sync.Once{}} }) return nil }
[ "func", "setup", "(", "c", "*", "caddy", ".", "Controller", ")", "error", "{", "httpserver", ".", "GetConfig", "(", "c", ")", ".", "AddMiddleware", "(", "func", "(", "next", "httpserver", ".", "Handler", ")", "httpserver", ".", "Handler", "{", "return", ...
// Setup an async goroutine that refreshes the pfconfig pool every second
[ "Setup", "an", "async", "goroutine", "that", "refreshes", "the", "pfconfig", "pool", "every", "second" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/pfconfig/pool.go#L22-L28
train
inverse-inc/packetfence
go/caddy/pfconfig/pool.go
ServeHTTP
func (h PoolHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) { id, err := pfconfigdriver.PfconfigPool.ReadLock(r.Context()) if err == nil { defer pfconfigdriver.PfconfigPool.ReadUnlock(r.Context(), id) // We launch the refresh job once, the first time a request comes in // This ensures t...
go
func (h PoolHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) { id, err := pfconfigdriver.PfconfigPool.ReadLock(r.Context()) if err == nil { defer pfconfigdriver.PfconfigPool.ReadUnlock(r.Context(), id) // We launch the refresh job once, the first time a request comes in // This ensures t...
[ "func", "(", "h", "PoolHandler", ")", "ServeHTTP", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "(", "int", ",", "error", ")", "{", "id", ",", "err", ":=", "pfconfigdriver", ".", "PfconfigPool", ".", "ReadLock", ...
// Middleware that ensures there is a read-lock on the pool during every request and released when the request is done
[ "Middleware", "that", "ensures", "there", "is", "a", "read", "-", "lock", "on", "the", "pool", "during", "every", "request", "and", "released", "when", "the", "request", "is", "done" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/pfconfig/pool.go#L36-L57
train
inverse-inc/packetfence
go/coredns/plugin/pkg/healthcheck/healthcheck.go
Down
func (uh *UpstreamHost) Down() bool { if uh.CheckDown == nil { fails := atomic.LoadInt32(&uh.Fails) return fails > 0 } return uh.CheckDown(uh) }
go
func (uh *UpstreamHost) Down() bool { if uh.CheckDown == nil { fails := atomic.LoadInt32(&uh.Fails) return fails > 0 } return uh.CheckDown(uh) }
[ "func", "(", "uh", "*", "UpstreamHost", ")", "Down", "(", ")", "bool", "{", "if", "uh", ".", "CheckDown", "==", "nil", "{", "fails", ":=", "atomic", ".", "LoadInt32", "(", "&", "uh", ".", "Fails", ")", "\n", "return", "fails", ">", "0", "\n", "}"...
// Down checks whether the upstream host is down or not. // Down will try to use uh.CheckDown first, and will fall // back to some default criteria if necessary.
[ "Down", "checks", "whether", "the", "upstream", "host", "is", "down", "or", "not", ".", "Down", "will", "try", "to", "use", "uh", ".", "CheckDown", "first", "and", "will", "fall", "back", "to", "some", "default", "criteria", "if", "necessary", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/pkg/healthcheck/healthcheck.go#L33-L39
train
inverse-inc/packetfence
go/coredns/plugin/pkg/healthcheck/healthcheck.go
Start
func (u *HealthCheck) Start() { for i, h := range u.Hosts { u.Hosts[i].CheckURL = u.normalizeCheckURL(h.Name) } u.stop = make(chan struct{}) if u.Path != "" { u.wg.Add(1) go func() { defer u.wg.Done() u.healthCheckWorker(u.stop) }() } }
go
func (u *HealthCheck) Start() { for i, h := range u.Hosts { u.Hosts[i].CheckURL = u.normalizeCheckURL(h.Name) } u.stop = make(chan struct{}) if u.Path != "" { u.wg.Add(1) go func() { defer u.wg.Done() u.healthCheckWorker(u.stop) }() } }
[ "func", "(", "u", "*", "HealthCheck", ")", "Start", "(", ")", "{", "for", "i", ",", "h", ":=", "range", "u", ".", "Hosts", "{", "u", ".", "Hosts", "[", "i", "]", ".", "CheckURL", "=", "u", ".", "normalizeCheckURL", "(", "h", ".", "Name", ")", ...
// Start starts the healthcheck
[ "Start", "starts", "the", "healthcheck" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/pkg/healthcheck/healthcheck.go#L61-L74
train
inverse-inc/packetfence
go/coredns/plugin/pkg/healthcheck/healthcheck.go
HealthCheckURL
func (uh *UpstreamHost) HealthCheckURL() { // Lock for our bool check. We don't just defer the unlock because // we don't want the lock held while http.Get runs. uh.Lock() // We call HealthCheckURL from proxy.go and lookup.go, bail out when nothing // is configured to healthcheck. Or we mid check? Don't run ano...
go
func (uh *UpstreamHost) HealthCheckURL() { // Lock for our bool check. We don't just defer the unlock because // we don't want the lock held while http.Get runs. uh.Lock() // We call HealthCheckURL from proxy.go and lookup.go, bail out when nothing // is configured to healthcheck. Or we mid check? Don't run ano...
[ "func", "(", "uh", "*", "UpstreamHost", ")", "HealthCheckURL", "(", ")", "{", "// Lock for our bool check. We don't just defer the unlock because", "// we don't want the lock held while http.Get runs.", "uh", ".", "Lock", "(", ")", "\n\n", "// We call HealthCheckURL from proxy.g...
// This was moved into a thread so that each host could throw a health // check at the same time. The reason for this is that if we are checking // 3 hosts, and the first one is gone, and we spend minutes timing out to // fail it, we would not have been doing any other health checks in that // time. So we now have a ...
[ "This", "was", "moved", "into", "a", "thread", "so", "that", "each", "host", "could", "throw", "a", "health", "check", "at", "the", "same", "time", ".", "The", "reason", "for", "this", "is", "that", "if", "we", "are", "checking", "3", "hosts", "and", ...
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/pkg/healthcheck/healthcheck.go#L100-L142
train
inverse-inc/packetfence
go/coredns/plugin/pkg/healthcheck/healthcheck.go
Select
func (u *HealthCheck) Select() *UpstreamHost { pool := u.Hosts if len(pool) == 1 { if pool[0].Down() && u.Spray == nil { return nil } return pool[0] } allDown := true for _, host := range pool { if !host.Down() { allDown = false break } } if allDown { if u.Spray == nil { return nil } ...
go
func (u *HealthCheck) Select() *UpstreamHost { pool := u.Hosts if len(pool) == 1 { if pool[0].Down() && u.Spray == nil { return nil } return pool[0] } allDown := true for _, host := range pool { if !host.Down() { allDown = false break } } if allDown { if u.Spray == nil { return nil } ...
[ "func", "(", "u", "*", "HealthCheck", ")", "Select", "(", ")", "*", "UpstreamHost", "{", "pool", ":=", "u", ".", "Hosts", "\n", "if", "len", "(", "pool", ")", "==", "1", "{", "if", "pool", "[", "0", "]", ".", "Down", "(", ")", "&&", "u", ".",...
// Select selects an upstream host based on the policy // and the healthcheck result.
[ "Select", "selects", "an", "upstream", "host", "based", "on", "the", "policy", "and", "the", "healthcheck", "result", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/pkg/healthcheck/healthcheck.go#L167-L209
train
inverse-inc/packetfence
go/coredns/plugin/pkg/healthcheck/healthcheck.go
normalizeCheckURL
func (u *HealthCheck) normalizeCheckURL(name string) string { // The DNS server might be an HTTP server. If so, extract its name. hostName := name ret, err := url.Parse(name) if err == nil && len(ret.Host) > 0 { hostName = ret.Host } // Extract the port number from the parsed server name. checkHostName, chec...
go
func (u *HealthCheck) normalizeCheckURL(name string) string { // The DNS server might be an HTTP server. If so, extract its name. hostName := name ret, err := url.Parse(name) if err == nil && len(ret.Host) > 0 { hostName = ret.Host } // Extract the port number from the parsed server name. checkHostName, chec...
[ "func", "(", "u", "*", "HealthCheck", ")", "normalizeCheckURL", "(", "name", "string", ")", "string", "{", "// The DNS server might be an HTTP server. If so, extract its name.", "hostName", ":=", "name", "\n", "ret", ",", "err", ":=", "url", ".", "Parse", "(", "n...
// normalizeCheckURL creates a proper URL for the health check.
[ "normalizeCheckURL", "creates", "a", "proper", "URL", "for", "the", "health", "check", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/pkg/healthcheck/healthcheck.go#L212-L232
train
inverse-inc/packetfence
go/caddy/job-status/job-status.go
buildJobStatusHandler
func buildJobStatusHandler(ctx context.Context) (JobStatusHandler, error) { jobStatus := JobStatusHandler{} pfconfigdriver.PfconfigPool.AddStruct(ctx, &redisclient.Config) var network string if redisclient.Config.RedisArgs.Server[0] == '/' { network = "unix" } else { network = "tcp" } jobStatus.redis = re...
go
func buildJobStatusHandler(ctx context.Context) (JobStatusHandler, error) { jobStatus := JobStatusHandler{} pfconfigdriver.PfconfigPool.AddStruct(ctx, &redisclient.Config) var network string if redisclient.Config.RedisArgs.Server[0] == '/' { network = "unix" } else { network = "tcp" } jobStatus.redis = re...
[ "func", "buildJobStatusHandler", "(", "ctx", "context", ".", "Context", ")", "(", "JobStatusHandler", ",", "error", ")", "{", "jobStatus", ":=", "JobStatusHandler", "{", "}", "\n\n", "pfconfigdriver", ".", "PfconfigPool", ".", "AddStruct", "(", "ctx", ",", "&"...
// Build the JobStatusHandler which will initialize the cache and instantiate the router along with its routes
[ "Build", "the", "JobStatusHandler", "which", "will", "initialize", "the", "cache", "and", "instantiate", "the", "router", "along", "with", "its", "routes" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/job-status/job-status.go#L66-L90
train
inverse-inc/packetfence
go/panichandler/panichandler.go
Http
func Http(ctx context.Context, w http.ResponseWriter) { if r := recover(); r != nil { outputPanic(ctx, r) http.Error(w, httpErrorMsg, http.StatusInternalServerError) } }
go
func Http(ctx context.Context, w http.ResponseWriter) { if r := recover(); r != nil { outputPanic(ctx, r) http.Error(w, httpErrorMsg, http.StatusInternalServerError) } }
[ "func", "Http", "(", "ctx", "context", ".", "Context", ",", "w", "http", ".", "ResponseWriter", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "outputPanic", "(", "ctx", ",", "r", ")", "\n", "http", ".", "Error", "(",...
// Defered panic handler that will write an error into the HTTP body and call outputPanic
[ "Defered", "panic", "handler", "that", "will", "write", "an", "error", "into", "the", "HTTP", "body", "and", "call", "outputPanic" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/panichandler/panichandler.go#L16-L21
train
inverse-inc/packetfence
go/panichandler/panichandler.go
Standard
func Standard(ctx context.Context) { if r := recover(); r != nil { outputPanic(ctx, r) } }
go
func Standard(ctx context.Context) { if r := recover(); r != nil { outputPanic(ctx, r) } }
[ "func", "Standard", "(", "ctx", "context", ".", "Context", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "outputPanic", "(", "ctx", ",", "r", ")", "\n", "}", "\n", "}" ]
// Defered panic handler that calls outputPanic
[ "Defered", "panic", "handler", "that", "calls", "outputPanic" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/panichandler/panichandler.go#L24-L28
train
inverse-inc/packetfence
go/panichandler/panichandler.go
outputPanic
func outputPanic(ctx context.Context, recovered interface{}) { msg := fmt.Sprintf("Recovered panic: %s.", recovered) log.LoggerWContext(ctx).Error(msg) fmt.Fprintln(os.Stderr, msg) debug.PrintStack() }
go
func outputPanic(ctx context.Context, recovered interface{}) { msg := fmt.Sprintf("Recovered panic: %s.", recovered) log.LoggerWContext(ctx).Error(msg) fmt.Fprintln(os.Stderr, msg) debug.PrintStack() }
[ "func", "outputPanic", "(", "ctx", "context", ".", "Context", ",", "recovered", "interface", "{", "}", ")", "{", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "recovered", ")", "\n", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Er...
// Output a panic error message along with its stacktrace // The stacktrace will start from this function up to where the panic was initially called // The stack and message are outputted in STDERR and a log line is added in Error
[ "Output", "a", "panic", "error", "message", "along", "with", "its", "stacktrace", "The", "stacktrace", "will", "start", "from", "this", "function", "up", "to", "where", "the", "panic", "was", "initially", "called", "The", "stack", "and", "message", "are", "o...
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/panichandler/panichandler.go#L33-L38
train
inverse-inc/packetfence
go/coredns/plugin/etcd/stub_handler.go
hasStubEdns0
func hasStubEdns0(m *dns.Msg) bool { option := m.IsEdns0() if option == nil { return false } for _, o := range option.Option { if o.Option() == ednsStubCode && len(o.(*dns.EDNS0_LOCAL).Data) == 1 && o.(*dns.EDNS0_LOCAL).Data[0] == 1 { return true } } return false }
go
func hasStubEdns0(m *dns.Msg) bool { option := m.IsEdns0() if option == nil { return false } for _, o := range option.Option { if o.Option() == ednsStubCode && len(o.(*dns.EDNS0_LOCAL).Data) == 1 && o.(*dns.EDNS0_LOCAL).Data[0] == 1 { return true } } return false }
[ "func", "hasStubEdns0", "(", "m", "*", "dns", ".", "Msg", ")", "bool", "{", "option", ":=", "m", ".", "IsEdns0", "(", ")", "\n", "if", "option", "==", "nil", "{", "return", "false", "\n", "}", "\n", "for", "_", ",", "o", ":=", "range", "option", ...
// hasStubEdns0 checks if the message is carrying our special edns0 zero option.
[ "hasStubEdns0", "checks", "if", "the", "message", "is", "carrying", "our", "special", "edns0", "zero", "option", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/etcd/stub_handler.go#L43-L55
train
inverse-inc/packetfence
go/coredns/plugin/etcd/stub_handler.go
addStubEdns0
func addStubEdns0(m *dns.Msg) *dns.Msg { option := m.IsEdns0() // Add a custom EDNS0 option to the packet, so we can detect loops when 2 stubs are forwarding to each other. if option != nil { option.Option = append(option.Option, &dns.EDNS0_LOCAL{Code: ednsStubCode, Data: []byte{1}}) return m } m.Extra = appe...
go
func addStubEdns0(m *dns.Msg) *dns.Msg { option := m.IsEdns0() // Add a custom EDNS0 option to the packet, so we can detect loops when 2 stubs are forwarding to each other. if option != nil { option.Option = append(option.Option, &dns.EDNS0_LOCAL{Code: ednsStubCode, Data: []byte{1}}) return m } m.Extra = appe...
[ "func", "addStubEdns0", "(", "m", "*", "dns", ".", "Msg", ")", "*", "dns", ".", "Msg", "{", "option", ":=", "m", ".", "IsEdns0", "(", ")", "\n", "// Add a custom EDNS0 option to the packet, so we can detect loops when 2 stubs are forwarding to each other.", "if", "opt...
// addStubEdns0 adds our special option to the message's OPT record.
[ "addStubEdns0", "adds", "our", "special", "option", "to", "the", "message", "s", "OPT", "record", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/etcd/stub_handler.go#L58-L68
train
inverse-inc/packetfence
go/coredns/plugin/dnstap/msg/wrapper.go
Wrap
func Wrap(m *lib.Message) lib.Dnstap { t := lib.Dnstap_MESSAGE return lib.Dnstap{ Type: &t, Message: m, } }
go
func Wrap(m *lib.Message) lib.Dnstap { t := lib.Dnstap_MESSAGE return lib.Dnstap{ Type: &t, Message: m, } }
[ "func", "Wrap", "(", "m", "*", "lib", ".", "Message", ")", "lib", ".", "Dnstap", "{", "t", ":=", "lib", ".", "Dnstap_MESSAGE", "\n", "return", "lib", ".", "Dnstap", "{", "Type", ":", "&", "t", ",", "Message", ":", "m", ",", "}", "\n", "}" ]
// Wrap a dnstap message in the top-level dnstap type.
[ "Wrap", "a", "dnstap", "message", "in", "the", "top", "-", "level", "dnstap", "type", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/dnstap/msg/wrapper.go#L11-L17
train
inverse-inc/packetfence
go/coredns/plugin/dnstap/msg/wrapper.go
Marshal
func Marshal(m *lib.Message) (data []byte, err error) { payload := Wrap(m) data, err = proto.Marshal(&payload) if err != nil { err = fmt.Errorf("proto: %s", err) return } return }
go
func Marshal(m *lib.Message) (data []byte, err error) { payload := Wrap(m) data, err = proto.Marshal(&payload) if err != nil { err = fmt.Errorf("proto: %s", err) return } return }
[ "func", "Marshal", "(", "m", "*", "lib", ".", "Message", ")", "(", "data", "[", "]", "byte", ",", "err", "error", ")", "{", "payload", ":=", "Wrap", "(", "m", ")", "\n", "data", ",", "err", "=", "proto", ".", "Marshal", "(", "&", "payload", ")"...
// Marshal encodes the message to a binary dnstap payload.
[ "Marshal", "encodes", "the", "message", "to", "a", "binary", "dnstap", "payload", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/dnstap/msg/wrapper.go#L20-L28
train
inverse-inc/packetfence
go/coredns/plugin/pkg/dnsutil/dedup.go
Dedup
func Dedup(m *dns.Msg) *dns.Msg { // TODO(miek): expensive! m.Answer = dns.Dedup(m.Answer, nil) m.Ns = dns.Dedup(m.Ns, nil) m.Extra = dns.Dedup(m.Extra, nil) return m }
go
func Dedup(m *dns.Msg) *dns.Msg { // TODO(miek): expensive! m.Answer = dns.Dedup(m.Answer, nil) m.Ns = dns.Dedup(m.Ns, nil) m.Extra = dns.Dedup(m.Extra, nil) return m }
[ "func", "Dedup", "(", "m", "*", "dns", ".", "Msg", ")", "*", "dns", ".", "Msg", "{", "// TODO(miek): expensive!", "m", ".", "Answer", "=", "dns", ".", "Dedup", "(", "m", ".", "Answer", ",", "nil", ")", "\n", "m", ".", "Ns", "=", "dns", ".", "De...
// Dedup de-duplicates a message.
[ "Dedup", "de", "-", "duplicates", "a", "message", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/pkg/dnsutil/dedup.go#L6-L12
train
inverse-inc/packetfence
go/coredns/core/dnsserver/register.go
init
func init() { flag.StringVar(&Port, serverType+".port", DefaultPort, "Default port") caddy.RegisterServerType(serverType, caddy.ServerType{ Directives: func() []string { return directives }, DefaultInput: func() caddy.Input { return caddy.CaddyfileInput{ Filepath: "Corefile", Contents: []b...
go
func init() { flag.StringVar(&Port, serverType+".port", DefaultPort, "Default port") caddy.RegisterServerType(serverType, caddy.ServerType{ Directives: func() []string { return directives }, DefaultInput: func() caddy.Input { return caddy.CaddyfileInput{ Filepath: "Corefile", Contents: []b...
[ "func", "init", "(", ")", "{", "flag", ".", "StringVar", "(", "&", "Port", ",", "serverType", "+", "\"", "\"", ",", "DefaultPort", ",", "\"", "\"", ")", "\n\n", "caddy", ".", "RegisterServerType", "(", "serverType", ",", "caddy", ".", "ServerType", "{"...
// Any flags defined here, need to be namespaced to the serverType other // wise they potentially clash with other server types.
[ "Any", "flags", "defined", "here", "need", "to", "be", "namespaced", "to", "the", "serverType", "other", "wise", "they", "potentially", "clash", "with", "other", "server", "types", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/core/dnsserver/register.go#L21-L35
train
inverse-inc/packetfence
go/firewallsso/paloalto.go
initChild
func (fw *PaloAlto) initChild(ctx context.Context) error { // Set a default value for vsys if there is none if fw.Vsys == "" { log.LoggerWContext(ctx).Debug("Setting default value for vsys as it isn't defined") fw.Vsys = "1" } return nil }
go
func (fw *PaloAlto) initChild(ctx context.Context) error { // Set a default value for vsys if there is none if fw.Vsys == "" { log.LoggerWContext(ctx).Debug("Setting default value for vsys as it isn't defined") fw.Vsys = "1" } return nil }
[ "func", "(", "fw", "*", "PaloAlto", ")", "initChild", "(", "ctx", "context", ".", "Context", ")", "error", "{", "// Set a default value for vsys if there is none", "if", "fw", ".", "Vsys", "==", "\"", "\"", "{", "log", ".", "LoggerWContext", "(", "ctx", ")",...
// Firewall specific init
[ "Firewall", "specific", "init" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/paloalto.go#L22-L29
train
inverse-inc/packetfence
go/firewallsso/paloalto.go
Start
func (fw *PaloAlto) Start(ctx context.Context, info map[string]string, timeout int) (bool, error) { if fw.Transport == "syslog" { log.LoggerWContext(ctx).Info("Sending SSO to PaloAlto using syslog") return fw.startSyslog(ctx, info, timeout) } else { log.LoggerWContext(ctx).Info("Sending SSO to PaloAlto using HT...
go
func (fw *PaloAlto) Start(ctx context.Context, info map[string]string, timeout int) (bool, error) { if fw.Transport == "syslog" { log.LoggerWContext(ctx).Info("Sending SSO to PaloAlto using syslog") return fw.startSyslog(ctx, info, timeout) } else { log.LoggerWContext(ctx).Info("Sending SSO to PaloAlto using HT...
[ "func", "(", "fw", "*", "PaloAlto", ")", "Start", "(", "ctx", "context", ".", "Context", ",", "info", "map", "[", "string", "]", "string", ",", "timeout", "int", ")", "(", "bool", ",", "error", ")", "{", "if", "fw", ".", "Transport", "==", "\"", ...
// Send an SSO start to the PaloAlto using either syslog or HTTP depending on the Transport value of the struct // This will return any value from startSyslog or startHttp depending on the type of the transport
[ "Send", "an", "SSO", "start", "to", "the", "PaloAlto", "using", "either", "syslog", "or", "HTTP", "depending", "on", "the", "Transport", "value", "of", "the", "struct", "This", "will", "return", "any", "value", "from", "startSyslog", "or", "startHttp", "depe...
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/paloalto.go#L33-L41
train
inverse-inc/packetfence
go/firewallsso/paloalto.go
getSyslog
func (fw *PaloAlto) getSyslog(ctx context.Context) (*syslog.Writer, error) { writer, err := syslog.Dial("udp", fw.PfconfigHashNS+":514", syslog.LOG_ERR|syslog.LOG_LOCAL5, "pfsso") if err != nil { log.LoggerWContext(ctx).Error(fmt.Sprintf("Error connecting to PaloAlto: %s", err)) return nil, err } return write...
go
func (fw *PaloAlto) getSyslog(ctx context.Context) (*syslog.Writer, error) { writer, err := syslog.Dial("udp", fw.PfconfigHashNS+":514", syslog.LOG_ERR|syslog.LOG_LOCAL5, "pfsso") if err != nil { log.LoggerWContext(ctx).Error(fmt.Sprintf("Error connecting to PaloAlto: %s", err)) return nil, err } return write...
[ "func", "(", "fw", "*", "PaloAlto", ")", "getSyslog", "(", "ctx", "context", ".", "Context", ")", "(", "*", "syslog", ".", "Writer", ",", "error", ")", "{", "writer", ",", "err", ":=", "syslog", ".", "Dial", "(", "\"", "\"", ",", "fw", ".", "Pfco...
// Get a syslog writter connection to the PaloAlto // This will always connect to port 514 and ignore the Port parameter // Returns an error if it can't connect but given its UDP, this should never fail
[ "Get", "a", "syslog", "writter", "connection", "to", "the", "PaloAlto", "This", "will", "always", "connect", "to", "port", "514", "and", "ignore", "the", "Port", "parameter", "Returns", "an", "error", "if", "it", "can", "t", "connect", "but", "given", "its...
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/paloalto.go#L46-L55
train
inverse-inc/packetfence
go/firewallsso/paloalto.go
sendSyslog
func (fw *PaloAlto) sendSyslog(ctx context.Context, line string) error { writer, err := fw.getSyslog(ctx) if err != nil { return err } err = writer.Err(line) if err != nil { log.LoggerWContext(ctx).Error(fmt.Sprintf("Error sending message to PaloAlto: %s", err)) return err } return nil }
go
func (fw *PaloAlto) sendSyslog(ctx context.Context, line string) error { writer, err := fw.getSyslog(ctx) if err != nil { return err } err = writer.Err(line) if err != nil { log.LoggerWContext(ctx).Error(fmt.Sprintf("Error sending message to PaloAlto: %s", err)) return err } return nil }
[ "func", "(", "fw", "*", "PaloAlto", ")", "sendSyslog", "(", "ctx", "context", ".", "Context", ",", "line", "string", ")", "error", "{", "writer", ",", "err", ":=", "fw", ".", "getSyslog", "(", "ctx", ")", "\n\n", "if", "err", "!=", "nil", "{", "ret...
// Send a syslog line to the PaloAlto // Will return an error if it fails to send the message
[ "Send", "a", "syslog", "line", "to", "the", "PaloAlto", "Will", "return", "an", "error", "if", "it", "fails", "to", "send", "the", "message" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/paloalto.go#L59-L74
train
inverse-inc/packetfence
go/firewallsso/paloalto.go
startSyslog
func (fw *PaloAlto) startSyslog(ctx context.Context, info map[string]string, timeout int) (bool, error) { if err := fw.sendSyslog(ctx, fmt.Sprintf("Group <packetfence> User <%s> Address <%s> assigned to session", info["username"], info["ip"])); err != nil { return false, err } else { return true, nil } }
go
func (fw *PaloAlto) startSyslog(ctx context.Context, info map[string]string, timeout int) (bool, error) { if err := fw.sendSyslog(ctx, fmt.Sprintf("Group <packetfence> User <%s> Address <%s> assigned to session", info["username"], info["ip"])); err != nil { return false, err } else { return true, nil } }
[ "func", "(", "fw", "*", "PaloAlto", ")", "startSyslog", "(", "ctx", "context", ".", "Context", ",", "info", "map", "[", "string", "]", "string", ",", "timeout", "int", ")", "(", "bool", ",", "error", ")", "{", "if", "err", ":=", "fw", ".", "sendSys...
// Send a start to the PaloAlto using the syslog transport // Will return an error if it fails to send the message
[ "Send", "a", "start", "to", "the", "PaloAlto", "using", "the", "syslog", "transport", "Will", "return", "an", "error", "if", "it", "fails", "to", "send", "the", "message" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/paloalto.go#L78-L84
train
inverse-inc/packetfence
go/firewallsso/paloalto.go
startHttpPayload
func (fw *PaloAlto) startHttpPayload(ctx context.Context, info map[string]string, timeout int) string { // PaloAlto XML API expects the timeout in minutes timeout = timeout / 60 t := template.New("PaloAlto.startHttp") t.Parse(` <uid-message> <version>1.0</version> <type>update</type> <payload> <login> ...
go
func (fw *PaloAlto) startHttpPayload(ctx context.Context, info map[string]string, timeout int) string { // PaloAlto XML API expects the timeout in minutes timeout = timeout / 60 t := template.New("PaloAlto.startHttp") t.Parse(` <uid-message> <version>1.0</version> <type>update</type> <payload> <login> ...
[ "func", "(", "fw", "*", "PaloAlto", ")", "startHttpPayload", "(", "ctx", "context", ".", "Context", ",", "info", "map", "[", "string", "]", "string", ",", "timeout", "int", ")", "string", "{", "// PaloAlto XML API expects the timeout in minutes", "timeout", "=",...
// Get the SSO start payload for the firewall
[ "Get", "the", "SSO", "start", "payload", "for", "the", "firewall" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/paloalto.go#L105-L123
train
inverse-inc/packetfence
go/firewallsso/paloalto.go
Stop
func (fw *PaloAlto) Stop(ctx context.Context, info map[string]string) (bool, error) { if fw.Transport == "syslog" { log.LoggerWContext(ctx).Warn("SSO Stop isn't supported on PaloAlto when using the syslog transport. You should use the HTTP transport if you require it.") return false, nil } else { log.LoggerWCon...
go
func (fw *PaloAlto) Stop(ctx context.Context, info map[string]string) (bool, error) { if fw.Transport == "syslog" { log.LoggerWContext(ctx).Warn("SSO Stop isn't supported on PaloAlto when using the syslog transport. You should use the HTTP transport if you require it.") return false, nil } else { log.LoggerWCon...
[ "func", "(", "fw", "*", "PaloAlto", ")", "Stop", "(", "ctx", "context", ".", "Context", ",", "info", "map", "[", "string", "]", "string", ")", "(", "bool", ",", "error", ")", "{", "if", "fw", ".", "Transport", "==", "\"", "\"", "{", "log", ".", ...
// Send an SSO stop to the firewall if the transport mode is HTTP. Otherwise, this outputs a warning // Will return the values from stopHttp for HTTP and no error if its syslog
[ "Send", "an", "SSO", "stop", "to", "the", "firewall", "if", "the", "transport", "mode", "is", "HTTP", ".", "Otherwise", "this", "outputs", "a", "warning", "Will", "return", "the", "values", "from", "stopHttp", "for", "HTTP", "and", "no", "error", "if", "...
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/paloalto.go#L127-L135
train
inverse-inc/packetfence
go/firewallsso/paloalto.go
stopHttp
func (fw *PaloAlto) stopHttp(ctx context.Context, info map[string]string) (bool, error) { resp, err := fw.getHttpClient(ctx).PostForm("https://"+fw.PfconfigHashNS+":"+fw.Port+"/api/?type=user-id&vsys=vsys"+fw.Vsys+"&action=set&key="+fw.Password, url.Values{"cmd": {fw.stopHttpPayload(ctx, info)}}) if err != nil { ...
go
func (fw *PaloAlto) stopHttp(ctx context.Context, info map[string]string) (bool, error) { resp, err := fw.getHttpClient(ctx).PostForm("https://"+fw.PfconfigHashNS+":"+fw.Port+"/api/?type=user-id&vsys=vsys"+fw.Vsys+"&action=set&key="+fw.Password, url.Values{"cmd": {fw.stopHttpPayload(ctx, info)}}) if err != nil { ...
[ "func", "(", "fw", "*", "PaloAlto", ")", "stopHttp", "(", "ctx", "context", ".", "Context", ",", "info", "map", "[", "string", "]", "string", ")", "(", "bool", ",", "error", ")", "{", "resp", ",", "err", ":=", "fw", ".", "getHttpClient", "(", "ctx"...
// Send an SSO stop using HTTP to the PaloAlto firewall // Returns an error if it fails to get a valid reply from the firewall
[ "Send", "an", "SSO", "stop", "using", "HTTP", "to", "the", "PaloAlto", "firewall", "Returns", "an", "error", "if", "it", "fails", "to", "get", "a", "valid", "reply", "from", "the", "firewall" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/paloalto.go#L158-L171
train
inverse-inc/packetfence
go/api-frontend/aaa/authorization.go
BearerRequestIsAuthorized
func (tam *TokenAuthorizationMiddleware) BearerRequestIsAuthorized(ctx context.Context, r *http.Request) (bool, error) { token := tam.TokenFromBearerRequest(ctx, r) xptid := r.Header.Get("X-PacketFence-Tenant-Id") tokenInfo, _ := tam.tokenBackend.TokenInfoForToken(token) if tokenInfo == nil { return false, erro...
go
func (tam *TokenAuthorizationMiddleware) BearerRequestIsAuthorized(ctx context.Context, r *http.Request) (bool, error) { token := tam.TokenFromBearerRequest(ctx, r) xptid := r.Header.Get("X-PacketFence-Tenant-Id") tokenInfo, _ := tam.tokenBackend.TokenInfoForToken(token) if tokenInfo == nil { return false, erro...
[ "func", "(", "tam", "*", "TokenAuthorizationMiddleware", ")", "BearerRequestIsAuthorized", "(", "ctx", "context", ".", "Context", ",", "r", "*", "http", ".", "Request", ")", "(", "bool", ",", "error", ")", "{", "token", ":=", "tam", ".", "TokenFromBearerRequ...
// Checks whether or not that request is authorized based on the path and method // It will extract the token out of the Authorization header and call the appropriate method
[ "Checks", "whether", "or", "not", "that", "request", "is", "authorized", "based", "on", "the", "path", "and", "method", "It", "will", "extract", "the", "token", "out", "of", "the", "Authorization", "header", "and", "call", "the", "appropriate", "method" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/api-frontend/aaa/authorization.go#L112-L151
train
inverse-inc/packetfence
go/api-frontend/aaa/authorization.go
IsAuthorized
func (tam *TokenAuthorizationMiddleware) IsAuthorized(ctx context.Context, method, path string, tenantId int, tokenInfo *TokenInfo) (bool, error) { if tokenInfo == nil { return false, errors.New("Invalid token info") } authAdminRoles, err := tam.isAuthorizedAdminActions(ctx, method, path, tokenInfo.AdminActions()...
go
func (tam *TokenAuthorizationMiddleware) IsAuthorized(ctx context.Context, method, path string, tenantId int, tokenInfo *TokenInfo) (bool, error) { if tokenInfo == nil { return false, errors.New("Invalid token info") } authAdminRoles, err := tam.isAuthorizedAdminActions(ctx, method, path, tokenInfo.AdminActions()...
[ "func", "(", "tam", "*", "TokenAuthorizationMiddleware", ")", "IsAuthorized", "(", "ctx", "context", ".", "Context", ",", "method", ",", "path", "string", ",", "tenantId", "int", ",", "tokenInfo", "*", "TokenInfo", ")", "(", "bool", ",", "error", ")", "{",...
// Checks whether or not that request is authorized based on the path and method
[ "Checks", "whether", "or", "not", "that", "request", "is", "authorized", "based", "on", "the", "path", "and", "method" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/api-frontend/aaa/authorization.go#L154-L176
train
inverse-inc/packetfence
go/caddy/caddy/caddyhttp/header/header.go
ServeHTTP
func (h Headers) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) { replacer := httpserver.NewReplacer(r, nil, "") rww := &responseWriterWrapper{w: w} for _, rule := range h.Rules { if httpserver.Path(r.URL.Path).Matches(rule.Path) { for name := range rule.Headers { // One can either delete a...
go
func (h Headers) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) { replacer := httpserver.NewReplacer(r, nil, "") rww := &responseWriterWrapper{w: w} for _, rule := range h.Rules { if httpserver.Path(r.URL.Path).Matches(rule.Path) { for name := range rule.Headers { // One can either delete a...
[ "func", "(", "h", "Headers", ")", "ServeHTTP", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "(", "int", ",", "error", ")", "{", "replacer", ":=", "httpserver", ".", "NewReplacer", "(", "r", ",", "nil", ",", "...
// ServeHTTP implements the httpserver.Handler interface and serves requests, // setting headers on the response according to the configured rules.
[ "ServeHTTP", "implements", "the", "httpserver", ".", "Handler", "interface", "and", "serves", "requests", "setting", "headers", "on", "the", "response", "according", "to", "the", "configured", "rules", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddyhttp/header/header.go#L24-L49
train
inverse-inc/packetfence
go/coredns/plugin/etcd/msg/service.go
targetStrip
func targetStrip(name string, targetStrip int) string { if targetStrip == 0 { return name } offset, end := 0, false for i := 0; i < targetStrip; i++ { offset, end = dns.NextLabel(name, offset) } if end { // We overshot the name, use the orignal one. offset = 0 } name = name[offset:] return name }
go
func targetStrip(name string, targetStrip int) string { if targetStrip == 0 { return name } offset, end := 0, false for i := 0; i < targetStrip; i++ { offset, end = dns.NextLabel(name, offset) } if end { // We overshot the name, use the orignal one. offset = 0 } name = name[offset:] return name }
[ "func", "targetStrip", "(", "name", "string", ",", "targetStrip", "int", ")", "string", "{", "if", "targetStrip", "==", "0", "{", "return", "name", "\n", "}", "\n\n", "offset", ",", "end", ":=", "0", ",", "false", "\n", "for", "i", ":=", "0", ";", ...
// targetStrip strips "targetstrip" labels from the left side of the fully qualified name.
[ "targetStrip", "strips", "targetstrip", "labels", "from", "the", "left", "side", "of", "the", "fully", "qualified", "name", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/etcd/msg/service.go#L188-L203
train
inverse-inc/packetfence
go/firewallsso/mockfw.go
Start
func (mfw *MockFW) Start(ctx context.Context, info map[string]string, timeout int) (bool, error) { log.LoggerWContext(ctx).Info("Sending SSO through mocked Firewall SSO") return true, nil }
go
func (mfw *MockFW) Start(ctx context.Context, info map[string]string, timeout int) (bool, error) { log.LoggerWContext(ctx).Info("Sending SSO through mocked Firewall SSO") return true, nil }
[ "func", "(", "mfw", "*", "MockFW", ")", "Start", "(", "ctx", "context", ".", "Context", ",", "info", "map", "[", "string", "]", "string", ",", "timeout", "int", ")", "(", "bool", ",", "error", ")", "{", "log", ".", "LoggerWContext", "(", "ctx", ")"...
// Send a dummy SSO start // This will always succeed without any error
[ "Send", "a", "dummy", "SSO", "start", "This", "will", "always", "succeed", "without", "any", "error" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/mockfw.go#L15-L18
train
inverse-inc/packetfence
go/firewallsso/mockfw.go
Stop
func (mfw *MockFW) Stop(ctx context.Context, info map[string]string) (bool, error) { log.LoggerWContext(ctx).Info("Sending SSO through mocked Firewall SSO") return true, nil }
go
func (mfw *MockFW) Stop(ctx context.Context, info map[string]string) (bool, error) { log.LoggerWContext(ctx).Info("Sending SSO through mocked Firewall SSO") return true, nil }
[ "func", "(", "mfw", "*", "MockFW", ")", "Stop", "(", "ctx", "context", ".", "Context", ",", "info", "map", "[", "string", "]", "string", ")", "(", "bool", ",", "error", ")", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Info", "(", "\...
// Send a dummy SSO stop // This will always succeed without any error
[ "Send", "a", "dummy", "SSO", "stop", "This", "will", "always", "succeed", "without", "any", "error" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/mockfw.go#L22-L25
train
inverse-inc/packetfence
go/log/log.go
NewLogger
func (l LoggerStruct) NewLogger() LoggerStruct { new := LoggerStruct{} new.logger = l.logger.New() new.handler = l.handler new.inDebug = l.inDebug new.processPid = l.processPid return new }
go
func (l LoggerStruct) NewLogger() LoggerStruct { new := LoggerStruct{} new.logger = l.logger.New() new.handler = l.handler new.inDebug = l.inDebug new.processPid = l.processPid return new }
[ "func", "(", "l", "LoggerStruct", ")", "NewLogger", "(", ")", "LoggerStruct", "{", "new", ":=", "LoggerStruct", "{", "}", "\n", "new", ".", "logger", "=", "l", ".", "logger", ".", "New", "(", ")", "\n", "new", ".", "handler", "=", "l", ".", "handle...
// Create a new logger from an existing one with the same confiuration
[ "Create", "a", "new", "logger", "from", "an", "existing", "one", "with", "the", "same", "confiuration" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/log/log.go#L40-L48
train
inverse-inc/packetfence
go/log/log.go
LoggerAddHandler
func LoggerAddHandler(ctx context.Context, f func(*log.Record) error) context.Context { logger := loggerFromContext(ctx) loggerHandler := log.MultiHandler(logger.handler, log.FuncHandler(f)) logger.SetHandler(loggerHandler) return context.WithValue(ctx, LoggerKey, logger) }
go
func LoggerAddHandler(ctx context.Context, f func(*log.Record) error) context.Context { logger := loggerFromContext(ctx) loggerHandler := log.MultiHandler(logger.handler, log.FuncHandler(f)) logger.SetHandler(loggerHandler) return context.WithValue(ctx, LoggerKey, logger) }
[ "func", "LoggerAddHandler", "(", "ctx", "context", ".", "Context", ",", "f", "func", "(", "*", "log", ".", "Record", ")", "error", ")", "context", ".", "Context", "{", "logger", ":=", "loggerFromContext", "(", "ctx", ")", "\n", "loggerHandler", ":=", "lo...
// Add a handler to a logger in the context
[ "Add", "a", "handler", "to", "a", "logger", "in", "the", "context" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/log/log.go#L88-L94
train
inverse-inc/packetfence
go/log/log.go
initContextLogger
func initContextLogger(ctx context.Context) context.Context { logger := newLoggerStruct() output := sharedutils.EnvOrDefault("LOG_OUTPUT", "syslog") if output == "syslog" { syslogBackend, err := log.SyslogHandler(syslog.LOG_INFO, ProcessName, log.LogfmtFormat()) sharedutils.CheckError(err) logger.SetHandler(s...
go
func initContextLogger(ctx context.Context) context.Context { logger := newLoggerStruct() output := sharedutils.EnvOrDefault("LOG_OUTPUT", "syslog") if output == "syslog" { syslogBackend, err := log.SyslogHandler(syslog.LOG_INFO, ProcessName, log.LogfmtFormat()) sharedutils.CheckError(err) logger.SetHandler(s...
[ "func", "initContextLogger", "(", "ctx", "context", ".", "Context", ")", "context", ".", "Context", "{", "logger", ":=", "newLoggerStruct", "(", ")", "\n\n", "output", ":=", "sharedutils", ".", "EnvOrDefault", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", ...
// Initialize the logger in a context
[ "Initialize", "the", "logger", "in", "a", "context" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/log/log.go#L97-L121
train
inverse-inc/packetfence
go/log/log.go
loggerFromContext
func loggerFromContext(ctx context.Context) LoggerStruct { loggerInt := ctx.Value(LoggerKey) var logger LoggerStruct logger = loggerInt.(LoggerStruct) return logger }
go
func loggerFromContext(ctx context.Context) LoggerStruct { loggerInt := ctx.Value(LoggerKey) var logger LoggerStruct logger = loggerInt.(LoggerStruct) return logger }
[ "func", "loggerFromContext", "(", "ctx", "context", ".", "Context", ")", "LoggerStruct", "{", "loggerInt", ":=", "ctx", ".", "Value", "(", "LoggerKey", ")", "\n\n", "var", "logger", "LoggerStruct", "\n", "logger", "=", "loggerInt", ".", "(", "LoggerStruct", ...
// Get the logger from a context // If the logger isn't there this will panic so make sure its there before calling this
[ "Get", "the", "logger", "from", "a", "context", "If", "the", "logger", "isn", "t", "there", "this", "will", "panic", "so", "make", "sure", "its", "there", "before", "calling", "this" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/log/log.go#L125-L132
train
inverse-inc/packetfence
go/log/log.go
LoggerNewContext
func LoggerNewContext(ctx context.Context) context.Context { ctx = initContextLogger(ctx) ctx = context.WithValue(ctx, AdditionnalLogElementsKey, ordered_map.NewOrderedMap()) return ctx }
go
func LoggerNewContext(ctx context.Context) context.Context { ctx = initContextLogger(ctx) ctx = context.WithValue(ctx, AdditionnalLogElementsKey, ordered_map.NewOrderedMap()) return ctx }
[ "func", "LoggerNewContext", "(", "ctx", "context", ".", "Context", ")", "context", ".", "Context", "{", "ctx", "=", "initContextLogger", "(", "ctx", ")", "\n", "ctx", "=", "context", ".", "WithValue", "(", "ctx", ",", "AdditionnalLogElementsKey", ",", "order...
// Create a new logger in a context // Will ensure that its initialized with the PID of the current process
[ "Create", "a", "new", "logger", "in", "a", "context", "Will", "ensure", "that", "its", "initialized", "with", "the", "PID", "of", "the", "current", "process" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/log/log.go#L171-L175
train
inverse-inc/packetfence
go/log/log.go
TranferLogContext
func TranferLogContext(sourceCtx context.Context, destCtx context.Context) context.Context { destCtx = context.WithValue(destCtx, LoggerKey, sourceCtx.Value(LoggerKey)) destCtx = context.WithValue(destCtx, AdditionnalLogElementsKey, sharedutils.CopyOrderedMap(sourceCtx.Value(AdditionnalLogElementsKey).(*ordered_map.O...
go
func TranferLogContext(sourceCtx context.Context, destCtx context.Context) context.Context { destCtx = context.WithValue(destCtx, LoggerKey, sourceCtx.Value(LoggerKey)) destCtx = context.WithValue(destCtx, AdditionnalLogElementsKey, sharedutils.CopyOrderedMap(sourceCtx.Value(AdditionnalLogElementsKey).(*ordered_map.O...
[ "func", "TranferLogContext", "(", "sourceCtx", "context", ".", "Context", ",", "destCtx", "context", ".", "Context", ")", "context", ".", "Context", "{", "destCtx", "=", "context", ".", "WithValue", "(", "destCtx", ",", "LoggerKey", ",", "sourceCtx", ".", "V...
// Transfer the logger from a context to another
[ "Transfer", "the", "logger", "from", "a", "context", "to", "another" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/log/log.go#L178-L182
train
inverse-inc/packetfence
go/log/log.go
LoggerNewRequest
func LoggerNewRequest(ctx context.Context) context.Context { u, _ := uuid.NewUUID() uStr := u.String() ctx = context.WithValue(ctx, RequestUuidKey, uStr) return ctx }
go
func LoggerNewRequest(ctx context.Context) context.Context { u, _ := uuid.NewUUID() uStr := u.String() ctx = context.WithValue(ctx, RequestUuidKey, uStr) return ctx }
[ "func", "LoggerNewRequest", "(", "ctx", "context", ".", "Context", ")", "context", ".", "Context", "{", "u", ",", "_", ":=", "uuid", ".", "NewUUID", "(", ")", "\n", "uStr", ":=", "u", ".", "String", "(", ")", "\n", "ctx", "=", "context", ".", "With...
// Generate a new UUID for the current request and add it to the context
[ "Generate", "a", "new", "UUID", "for", "the", "current", "request", "and", "add", "it", "to", "the", "context" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/log/log.go#L185-L190
train
inverse-inc/packetfence
go/log/log.go
Die
func Die(msg string, args ...interface{}) { Logger().Crit(msg, args...) panic(msg) }
go
func Die(msg string, args ...interface{}) { Logger().Crit(msg, args...) panic(msg) }
[ "func", "Die", "(", "msg", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "Logger", "(", ")", ".", "Crit", "(", "msg", ",", "args", "...", ")", "\n", "panic", "(", "msg", ")", "\n", "}" ]
// panic while logging a problem as critical
[ "panic", "while", "logging", "a", "problem", "as", "critical" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/log/log.go#L230-L233
train
inverse-inc/packetfence
go/coredns/plugin/dnstap/out/tcp.go
NewTCP
func NewTCP(address string) *TCP { s := &TCP{address: address} s.frames = make([][]byte, 0, 13) // 13 messages buffer return s }
go
func NewTCP(address string) *TCP { s := &TCP{address: address} s.frames = make([][]byte, 0, 13) // 13 messages buffer return s }
[ "func", "NewTCP", "(", "address", "string", ")", "*", "TCP", "{", "s", ":=", "&", "TCP", "{", "address", ":", "address", "}", "\n", "s", ".", "frames", "=", "make", "(", "[", "]", "[", "]", "byte", ",", "0", ",", "13", ")", "// 13 messages buffer...
// NewTCP returns a TCP writer.
[ "NewTCP", "returns", "a", "TCP", "writer", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/dnstap/out/tcp.go#L17-L21
train
inverse-inc/packetfence
go/coredns/plugin/dnstap/out/tcp.go
Flush
func (s *TCP) Flush() error { defer func() { s.frames = s.frames[:0] }() c, err := net.DialTimeout("tcp", s.address, time.Second) if err != nil { return err } enc, err := fs.NewEncoder(c, &fs.EncoderOptions{ ContentType: []byte("protobuf:dnstap.Dnstap"), Bidirectional: true, }) if err != nil { retur...
go
func (s *TCP) Flush() error { defer func() { s.frames = s.frames[:0] }() c, err := net.DialTimeout("tcp", s.address, time.Second) if err != nil { return err } enc, err := fs.NewEncoder(c, &fs.EncoderOptions{ ContentType: []byte("protobuf:dnstap.Dnstap"), Bidirectional: true, }) if err != nil { retur...
[ "func", "(", "s", "*", "TCP", ")", "Flush", "(", ")", "error", "{", "defer", "func", "(", ")", "{", "s", ".", "frames", "=", "s", ".", "frames", "[", ":", "0", "]", "\n", "}", "(", ")", "\n", "c", ",", "err", ":=", "net", ".", "DialTimeout"...
// Flush the remaining frames.
[ "Flush", "the", "remaining", "frames", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/dnstap/out/tcp.go#L33-L54
train
inverse-inc/packetfence
go/coredns/plugin/etcd/etcd.go
get
func (e *Etcd) get(path string, recursive bool) (*etcdc.Response, error) { hash := cache.Hash([]byte(path)) resp, err := e.Inflight.Do(hash, func() (interface{}, error) { ctx, cancel := context.WithTimeout(e.Ctx, etcdTimeout) defer cancel() r, e := e.Client.Get(ctx, path, &etcdc.GetOptions{Sort: false, Recurs...
go
func (e *Etcd) get(path string, recursive bool) (*etcdc.Response, error) { hash := cache.Hash([]byte(path)) resp, err := e.Inflight.Do(hash, func() (interface{}, error) { ctx, cancel := context.WithTimeout(e.Ctx, etcdTimeout) defer cancel() r, e := e.Client.Get(ctx, path, &etcdc.GetOptions{Sort: false, Recurs...
[ "func", "(", "e", "*", "Etcd", ")", "get", "(", "path", "string", ",", "recursive", "bool", ")", "(", "*", "etcdc", ".", "Response", ",", "error", ")", "{", "hash", ":=", "cache", ".", "Hash", "(", "[", "]", "byte", "(", "path", ")", ")", "\n\n...
// get is a wrapper for client.Get that uses SingleInflight to suppress multiple outstanding queries.
[ "get", "is", "a", "wrapper", "for", "client", ".", "Get", "that", "uses", "SingleInflight", "to", "suppress", "multiple", "outstanding", "queries", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/etcd/etcd.go#L88-L105
train
inverse-inc/packetfence
go/firewallsso/jsonrpc.go
getRequestBody
func (fw *JSONRPC) getRequestBody(action string, info map[string]string, timeout int) ([]byte, error) { args := &JSONRPC_Args{ User: info["username"], MAC: info["mac"], IP: info["ip"], Role: info["role"], Timeout: timeout, } body, err := json2.EncodeClientRequest(action, args) return body, ...
go
func (fw *JSONRPC) getRequestBody(action string, info map[string]string, timeout int) ([]byte, error) { args := &JSONRPC_Args{ User: info["username"], MAC: info["mac"], IP: info["ip"], Role: info["role"], Timeout: timeout, } body, err := json2.EncodeClientRequest(action, args) return body, ...
[ "func", "(", "fw", "*", "JSONRPC", ")", "getRequestBody", "(", "action", "string", ",", "info", "map", "[", "string", "]", "string", ",", "timeout", "int", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "args", ":=", "&", "JSONRPC_Args", "{", ...
// Create JSON-RPC request body
[ "Create", "JSON", "-", "RPC", "request", "body" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/jsonrpc.go#L28-L38
train
inverse-inc/packetfence
go/firewallsso/jsonrpc.go
makeRpcRequest
func (fw *JSONRPC) makeRpcRequest(ctx context.Context, action string, info map[string]string, timeout int) error { body, err := fw.getRequestBody(action, info, timeout) if err != nil { log.LoggerWContext(ctx).Error(fmt.Sprintf("Cannot encode JSON-RPC call: %s", err)) return err } req, err := http.NewRequest("P...
go
func (fw *JSONRPC) makeRpcRequest(ctx context.Context, action string, info map[string]string, timeout int) error { body, err := fw.getRequestBody(action, info, timeout) if err != nil { log.LoggerWContext(ctx).Error(fmt.Sprintf("Cannot encode JSON-RPC call: %s", err)) return err } req, err := http.NewRequest("P...
[ "func", "(", "fw", "*", "JSONRPC", ")", "makeRpcRequest", "(", "ctx", "context", ".", "Context", ",", "action", "string", ",", "info", "map", "[", "string", "]", "string", ",", "timeout", "int", ")", "error", "{", "body", ",", "err", ":=", "fw", ".",...
// Make a JSON-RPC request // Returns an error unless the server acknowledges success
[ "Make", "a", "JSON", "-", "RPC", "request", "Returns", "an", "error", "unless", "the", "server", "acknowledges", "success" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/jsonrpc.go#L42-L76
train
inverse-inc/packetfence
go/firewallsso/jsonrpc.go
Start
func (fw *JSONRPC) Start(ctx context.Context, info map[string]string, timeout int) (bool, error) { err := fw.makeRpcRequest(ctx, "Start", info, timeout) return err == nil, err }
go
func (fw *JSONRPC) Start(ctx context.Context, info map[string]string, timeout int) (bool, error) { err := fw.makeRpcRequest(ctx, "Start", info, timeout) return err == nil, err }
[ "func", "(", "fw", "*", "JSONRPC", ")", "Start", "(", "ctx", "context", ".", "Context", ",", "info", "map", "[", "string", "]", "string", ",", "timeout", "int", ")", "(", "bool", ",", "error", ")", "{", "err", ":=", "fw", ".", "makeRpcRequest", "("...
// Send an SSO start to the JSON-RPC server
[ "Send", "an", "SSO", "start", "to", "the", "JSON", "-", "RPC", "server" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/jsonrpc.go#L79-L82
train
inverse-inc/packetfence
go/firewallsso/jsonrpc.go
Stop
func (fw *JSONRPC) Stop(ctx context.Context, info map[string]string) (bool, error) { err := fw.makeRpcRequest(ctx, "Stop", info, 0) return err == nil, err }
go
func (fw *JSONRPC) Stop(ctx context.Context, info map[string]string) (bool, error) { err := fw.makeRpcRequest(ctx, "Stop", info, 0) return err == nil, err }
[ "func", "(", "fw", "*", "JSONRPC", ")", "Stop", "(", "ctx", "context", ".", "Context", ",", "info", "map", "[", "string", "]", "string", ")", "(", "bool", ",", "error", ")", "{", "err", ":=", "fw", ".", "makeRpcRequest", "(", "ctx", ",", "\"", "\...
// Send an SSO stop to the JSON-RPC server
[ "Send", "an", "SSO", "stop", "to", "the", "JSON", "-", "RPC", "server" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/jsonrpc.go#L85-L88
train
inverse-inc/packetfence
go/httpdispatcher/proxy.go
NewProxy
func NewProxy(ctx context.Context) *Proxy { var p Proxy passThrough = newProxyPassthrough(ctx) passThrough.readConfig(ctx) return &p }
go
func NewProxy(ctx context.Context) *Proxy { var p Proxy passThrough = newProxyPassthrough(ctx) passThrough.readConfig(ctx) return &p }
[ "func", "NewProxy", "(", "ctx", "context", ".", "Context", ")", "*", "Proxy", "{", "var", "p", "Proxy", "\n\n", "passThrough", "=", "newProxyPassthrough", "(", "ctx", ")", "\n", "passThrough", ".", "readConfig", "(", "ctx", ")", "\n", "return", "&", "p",...
// NewProxy creates a new instance of proxy. // It sets request logger using rLogPath as output file or os.Stdout by default. // If whitePath of blackPath is not empty they are parsed to set endpoint lists.
[ "NewProxy", "creates", "a", "new", "instance", "of", "proxy", ".", "It", "sets", "request", "logger", "using", "rLogPath", "as", "output", "file", "or", "os", ".", "Stdout", "by", "default", ".", "If", "whitePath", "of", "blackPath", "is", "not", "empty", ...
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/httpdispatcher/proxy.go#L44-L50
train
inverse-inc/packetfence
go/httpdispatcher/proxy.go
checkEndpointList
func (p *Proxy) checkEndpointList(ctx context.Context, e string) bool { if p.endpointBlackList == nil && p.endpointWhiteList == nil { return true } for _, rgx := range p.endpointBlackList { if rgx.MatchString(e) { return false } } return true }
go
func (p *Proxy) checkEndpointList(ctx context.Context, e string) bool { if p.endpointBlackList == nil && p.endpointWhiteList == nil { return true } for _, rgx := range p.endpointBlackList { if rgx.MatchString(e) { return false } } return true }
[ "func", "(", "p", "*", "Proxy", ")", "checkEndpointList", "(", "ctx", "context", ".", "Context", ",", "e", "string", ")", "bool", "{", "if", "p", ".", "endpointBlackList", "==", "nil", "&&", "p", ".", "endpointWhiteList", "==", "nil", "{", "return", "t...
// checkEndpointList looks if r is in whitelist or blackllist // returns true if endpoint is allowed
[ "checkEndpointList", "looks", "if", "r", "is", "in", "whitelist", "or", "blackllist", "returns", "true", "if", "endpoint", "is", "allowed" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/httpdispatcher/proxy.go#L71-L83
train
inverse-inc/packetfence
go/httpdispatcher/proxy.go
Configure
func (p *Proxy) Configure(ctx context.Context, port string) { p.addToEndpointList(ctx, "localhost") p.addToEndpointList(ctx, "127.0.0.1") }
go
func (p *Proxy) Configure(ctx context.Context, port string) { p.addToEndpointList(ctx, "localhost") p.addToEndpointList(ctx, "127.0.0.1") }
[ "func", "(", "p", "*", "Proxy", ")", "Configure", "(", "ctx", "context", ".", "Context", ",", "port", "string", ")", "{", "p", ".", "addToEndpointList", "(", "ctx", ",", "\"", "\"", ")", "\n", "p", ".", "addToEndpointList", "(", "ctx", ",", "\"", "...
// Configure add default target in the deny list
[ "Configure", "add", "default", "target", "in", "the", "deny", "list" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/httpdispatcher/proxy.go#L215-L218
train
inverse-inc/packetfence
go/httpdispatcher/proxy.go
addFqdnToList
func (p *passthrough) addFqdnToList(ctx context.Context, r string) error { rgx, err := regexp.Compile(r) if err == nil { p.mutex.Lock() p.proxypassthrough = append(p.proxypassthrough, rgx) p.mutex.Unlock() } return err }
go
func (p *passthrough) addFqdnToList(ctx context.Context, r string) error { rgx, err := regexp.Compile(r) if err == nil { p.mutex.Lock() p.proxypassthrough = append(p.proxypassthrough, rgx) p.mutex.Unlock() } return err }
[ "func", "(", "p", "*", "passthrough", ")", "addFqdnToList", "(", "ctx", "context", ".", "Context", ",", "r", "string", ")", "error", "{", "rgx", ",", "err", ":=", "regexp", ".", "Compile", "(", "r", ")", "\n", "if", "err", "==", "nil", "{", "p", ...
// addFqdnToList add all the passthrough fqdn in a list
[ "addFqdnToList", "add", "all", "the", "passthrough", "fqdn", "in", "a", "list" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/httpdispatcher/proxy.go#L312-L320
train
inverse-inc/packetfence
go/httpdispatcher/proxy.go
checkProxyPassthrough
func (p *passthrough) checkProxyPassthrough(ctx context.Context, e string) bool { if p.proxypassthrough == nil { return false } for _, rgx := range p.proxypassthrough { if rgx.MatchString(e) { return true } } return false }
go
func (p *passthrough) checkProxyPassthrough(ctx context.Context, e string) bool { if p.proxypassthrough == nil { return false } for _, rgx := range p.proxypassthrough { if rgx.MatchString(e) { return true } } return false }
[ "func", "(", "p", "*", "passthrough", ")", "checkProxyPassthrough", "(", "ctx", "context", ".", "Context", ",", "e", "string", ")", "bool", "{", "if", "p", ".", "proxypassthrough", "==", "nil", "{", "return", "false", "\n", "}", "\n\n", "for", "_", ","...
// checkProxyPassthrough compare the host to the list of regex
[ "checkProxyPassthrough", "compare", "the", "host", "to", "the", "list", "of", "regex" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/httpdispatcher/proxy.go#L334-L345
train
natefinch/lumberjack
lumberjack.go
Write
func (l *Logger) Write(p []byte) (n int, err error) { l.mu.Lock() defer l.mu.Unlock() writeLen := int64(len(p)) if writeLen > l.max() { return 0, fmt.Errorf( "write length %d exceeds maximum file size %d", writeLen, l.max(), ) } if l.file == nil { if err = l.openExistingOrNew(len(p)); err != nil { r...
go
func (l *Logger) Write(p []byte) (n int, err error) { l.mu.Lock() defer l.mu.Unlock() writeLen := int64(len(p)) if writeLen > l.max() { return 0, fmt.Errorf( "write length %d exceeds maximum file size %d", writeLen, l.max(), ) } if l.file == nil { if err = l.openExistingOrNew(len(p)); err != nil { r...
[ "func", "(", "l", "*", "Logger", ")", "Write", "(", "p", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "l", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "writeLen...
// Write implements io.Writer. If a write would cause the log file to be larger // than MaxSize, the file is closed, renamed to include a timestamp of the // current time, and a new log file is created using the original log file name. // If the length of the write is greater than MaxSize, an error is returned.
[ "Write", "implements", "io", ".", "Writer", ".", "If", "a", "write", "would", "cause", "the", "log", "file", "to", "be", "larger", "than", "MaxSize", "the", "file", "is", "closed", "renamed", "to", "include", "a", "timestamp", "of", "the", "current", "ti...
94d9e492cc53c413571e9b40c0b39cee643ee516
https://github.com/natefinch/lumberjack/blob/94d9e492cc53c413571e9b40c0b39cee643ee516/lumberjack.go#L135-L162
train
natefinch/lumberjack
lumberjack.go
Rotate
func (l *Logger) Rotate() error { l.mu.Lock() defer l.mu.Unlock() return l.rotate() }
go
func (l *Logger) Rotate() error { l.mu.Lock() defer l.mu.Unlock() return l.rotate() }
[ "func", "(", "l", "*", "Logger", ")", "Rotate", "(", ")", "error", "{", "l", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "l", ".", "rotate", "(", ")", "\n", "}" ]
// Rotate causes Logger to close the existing log file and immediately create a // new one. This is a helper function for applications that want to initiate // rotations outside of the normal rotation rules, such as in response to // SIGHUP. After rotating, this initiates compression and removal of old log // files a...
[ "Rotate", "causes", "Logger", "to", "close", "the", "existing", "log", "file", "and", "immediately", "create", "a", "new", "one", ".", "This", "is", "a", "helper", "function", "for", "applications", "that", "want", "to", "initiate", "rotations", "outside", "...
94d9e492cc53c413571e9b40c0b39cee643ee516
https://github.com/natefinch/lumberjack/blob/94d9e492cc53c413571e9b40c0b39cee643ee516/lumberjack.go#L186-L190
train
natefinch/lumberjack
lumberjack.go
openExistingOrNew
func (l *Logger) openExistingOrNew(writeLen int) error { l.mill() filename := l.filename() info, err := os_Stat(filename) if os.IsNotExist(err) { return l.openNew() } if err != nil { return fmt.Errorf("error getting log file info: %s", err) } if info.Size()+int64(writeLen) >= l.max() { return l.rotate()...
go
func (l *Logger) openExistingOrNew(writeLen int) error { l.mill() filename := l.filename() info, err := os_Stat(filename) if os.IsNotExist(err) { return l.openNew() } if err != nil { return fmt.Errorf("error getting log file info: %s", err) } if info.Size()+int64(writeLen) >= l.max() { return l.rotate()...
[ "func", "(", "l", "*", "Logger", ")", "openExistingOrNew", "(", "writeLen", "int", ")", "error", "{", "l", ".", "mill", "(", ")", "\n\n", "filename", ":=", "l", ".", "filename", "(", ")", "\n", "info", ",", "err", ":=", "os_Stat", "(", "filename", ...
// openExistingOrNew opens the logfile if it exists and if the current write // would not put it over MaxSize. If there is no such file or the write would // put it over the MaxSize, a new file is created.
[ "openExistingOrNew", "opens", "the", "logfile", "if", "it", "exists", "and", "if", "the", "current", "write", "would", "not", "put", "it", "over", "MaxSize", ".", "If", "there", "is", "no", "such", "file", "or", "the", "write", "would", "put", "it", "ove...
94d9e492cc53c413571e9b40c0b39cee643ee516
https://github.com/natefinch/lumberjack/blob/94d9e492cc53c413571e9b40c0b39cee643ee516/lumberjack.go#L264-L289
train
natefinch/lumberjack
lumberjack.go
filename
func (l *Logger) filename() string { if l.Filename != "" { return l.Filename } name := filepath.Base(os.Args[0]) + "-lumberjack.log" return filepath.Join(os.TempDir(), name) }
go
func (l *Logger) filename() string { if l.Filename != "" { return l.Filename } name := filepath.Base(os.Args[0]) + "-lumberjack.log" return filepath.Join(os.TempDir(), name) }
[ "func", "(", "l", "*", "Logger", ")", "filename", "(", ")", "string", "{", "if", "l", ".", "Filename", "!=", "\"", "\"", "{", "return", "l", ".", "Filename", "\n", "}", "\n", "name", ":=", "filepath", ".", "Base", "(", "os", ".", "Args", "[", "...
// filename generates the name of the logfile from the current time.
[ "filename", "generates", "the", "name", "of", "the", "logfile", "from", "the", "current", "time", "." ]
94d9e492cc53c413571e9b40c0b39cee643ee516
https://github.com/natefinch/lumberjack/blob/94d9e492cc53c413571e9b40c0b39cee643ee516/lumberjack.go#L292-L298
train
natefinch/lumberjack
lumberjack.go
millRunOnce
func (l *Logger) millRunOnce() error { if l.MaxBackups == 0 && l.MaxAge == 0 && !l.Compress { return nil } files, err := l.oldLogFiles() if err != nil { return err } var compress, remove []logInfo if l.MaxBackups > 0 && l.MaxBackups < len(files) { preserved := make(map[string]bool) var remaining []log...
go
func (l *Logger) millRunOnce() error { if l.MaxBackups == 0 && l.MaxAge == 0 && !l.Compress { return nil } files, err := l.oldLogFiles() if err != nil { return err } var compress, remove []logInfo if l.MaxBackups > 0 && l.MaxBackups < len(files) { preserved := make(map[string]bool) var remaining []log...
[ "func", "(", "l", "*", "Logger", ")", "millRunOnce", "(", ")", "error", "{", "if", "l", ".", "MaxBackups", "==", "0", "&&", "l", ".", "MaxAge", "==", "0", "&&", "!", "l", ".", "Compress", "{", "return", "nil", "\n", "}", "\n\n", "files", ",", "...
// millRunOnce performs compression and removal of stale log files. // Log files are compressed if enabled via configuration and old log // files are removed, keeping at most l.MaxBackups files, as long as // none of them are older than MaxAge.
[ "millRunOnce", "performs", "compression", "and", "removal", "of", "stale", "log", "files", ".", "Log", "files", "are", "compressed", "if", "enabled", "via", "configuration", "and", "old", "log", "files", "are", "removed", "keeping", "at", "most", "l", ".", "...
94d9e492cc53c413571e9b40c0b39cee643ee516
https://github.com/natefinch/lumberjack/blob/94d9e492cc53c413571e9b40c0b39cee643ee516/lumberjack.go#L304-L374
train
natefinch/lumberjack
lumberjack.go
mill
func (l *Logger) mill() { l.startMill.Do(func() { l.millCh = make(chan bool, 1) go l.millRun() }) select { case l.millCh <- true: default: } }
go
func (l *Logger) mill() { l.startMill.Do(func() { l.millCh = make(chan bool, 1) go l.millRun() }) select { case l.millCh <- true: default: } }
[ "func", "(", "l", "*", "Logger", ")", "mill", "(", ")", "{", "l", ".", "startMill", ".", "Do", "(", "func", "(", ")", "{", "l", ".", "millCh", "=", "make", "(", "chan", "bool", ",", "1", ")", "\n", "go", "l", ".", "millRun", "(", ")", "\n",...
// mill performs post-rotation compression and removal of stale log files, // starting the mill goroutine if necessary.
[ "mill", "performs", "post", "-", "rotation", "compression", "and", "removal", "of", "stale", "log", "files", "starting", "the", "mill", "goroutine", "if", "necessary", "." ]
94d9e492cc53c413571e9b40c0b39cee643ee516
https://github.com/natefinch/lumberjack/blob/94d9e492cc53c413571e9b40c0b39cee643ee516/lumberjack.go#L387-L396
train
natefinch/lumberjack
lumberjack.go
oldLogFiles
func (l *Logger) oldLogFiles() ([]logInfo, error) { files, err := ioutil.ReadDir(l.dir()) if err != nil { return nil, fmt.Errorf("can't read log file directory: %s", err) } logFiles := []logInfo{} prefix, ext := l.prefixAndExt() for _, f := range files { if f.IsDir() { continue } if t, err := l.timeF...
go
func (l *Logger) oldLogFiles() ([]logInfo, error) { files, err := ioutil.ReadDir(l.dir()) if err != nil { return nil, fmt.Errorf("can't read log file directory: %s", err) } logFiles := []logInfo{} prefix, ext := l.prefixAndExt() for _, f := range files { if f.IsDir() { continue } if t, err := l.timeF...
[ "func", "(", "l", "*", "Logger", ")", "oldLogFiles", "(", ")", "(", "[", "]", "logInfo", ",", "error", ")", "{", "files", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "l", ".", "dir", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "r...
// oldLogFiles returns the list of backup log files stored in the same // directory as the current log file, sorted by ModTime
[ "oldLogFiles", "returns", "the", "list", "of", "backup", "log", "files", "stored", "in", "the", "same", "directory", "as", "the", "current", "log", "file", "sorted", "by", "ModTime" ]
94d9e492cc53c413571e9b40c0b39cee643ee516
https://github.com/natefinch/lumberjack/blob/94d9e492cc53c413571e9b40c0b39cee643ee516/lumberjack.go#L400-L428
train
natefinch/lumberjack
lumberjack.go
timeFromName
func (l *Logger) timeFromName(filename, prefix, ext string) (time.Time, error) { if !strings.HasPrefix(filename, prefix) { return time.Time{}, errors.New("mismatched prefix") } if !strings.HasSuffix(filename, ext) { return time.Time{}, errors.New("mismatched extension") } ts := filename[len(prefix) : len(filen...
go
func (l *Logger) timeFromName(filename, prefix, ext string) (time.Time, error) { if !strings.HasPrefix(filename, prefix) { return time.Time{}, errors.New("mismatched prefix") } if !strings.HasSuffix(filename, ext) { return time.Time{}, errors.New("mismatched extension") } ts := filename[len(prefix) : len(filen...
[ "func", "(", "l", "*", "Logger", ")", "timeFromName", "(", "filename", ",", "prefix", ",", "ext", "string", ")", "(", "time", ".", "Time", ",", "error", ")", "{", "if", "!", "strings", ".", "HasPrefix", "(", "filename", ",", "prefix", ")", "{", "re...
// timeFromName extracts the formatted time from the filename by stripping off // the filename's prefix and extension. This prevents someone's filename from // confusing time.parse.
[ "timeFromName", "extracts", "the", "formatted", "time", "from", "the", "filename", "by", "stripping", "off", "the", "filename", "s", "prefix", "and", "extension", ".", "This", "prevents", "someone", "s", "filename", "from", "confusing", "time", ".", "parse", "...
94d9e492cc53c413571e9b40c0b39cee643ee516
https://github.com/natefinch/lumberjack/blob/94d9e492cc53c413571e9b40c0b39cee643ee516/lumberjack.go#L433-L442
train
natefinch/lumberjack
lumberjack.go
max
func (l *Logger) max() int64 { if l.MaxSize == 0 { return int64(defaultMaxSize * megabyte) } return int64(l.MaxSize) * int64(megabyte) }
go
func (l *Logger) max() int64 { if l.MaxSize == 0 { return int64(defaultMaxSize * megabyte) } return int64(l.MaxSize) * int64(megabyte) }
[ "func", "(", "l", "*", "Logger", ")", "max", "(", ")", "int64", "{", "if", "l", ".", "MaxSize", "==", "0", "{", "return", "int64", "(", "defaultMaxSize", "*", "megabyte", ")", "\n", "}", "\n", "return", "int64", "(", "l", ".", "MaxSize", ")", "*"...
// max returns the maximum size in bytes of log files before rolling.
[ "max", "returns", "the", "maximum", "size", "in", "bytes", "of", "log", "files", "before", "rolling", "." ]
94d9e492cc53c413571e9b40c0b39cee643ee516
https://github.com/natefinch/lumberjack/blob/94d9e492cc53c413571e9b40c0b39cee643ee516/lumberjack.go#L445-L450
train
natefinch/lumberjack
lumberjack.go
prefixAndExt
func (l *Logger) prefixAndExt() (prefix, ext string) { filename := filepath.Base(l.filename()) ext = filepath.Ext(filename) prefix = filename[:len(filename)-len(ext)] + "-" return prefix, ext }
go
func (l *Logger) prefixAndExt() (prefix, ext string) { filename := filepath.Base(l.filename()) ext = filepath.Ext(filename) prefix = filename[:len(filename)-len(ext)] + "-" return prefix, ext }
[ "func", "(", "l", "*", "Logger", ")", "prefixAndExt", "(", ")", "(", "prefix", ",", "ext", "string", ")", "{", "filename", ":=", "filepath", ".", "Base", "(", "l", ".", "filename", "(", ")", ")", "\n", "ext", "=", "filepath", ".", "Ext", "(", "fi...
// prefixAndExt returns the filename part and extension part from the Logger's // filename.
[ "prefixAndExt", "returns", "the", "filename", "part", "and", "extension", "part", "from", "the", "Logger", "s", "filename", "." ]
94d9e492cc53c413571e9b40c0b39cee643ee516
https://github.com/natefinch/lumberjack/blob/94d9e492cc53c413571e9b40c0b39cee643ee516/lumberjack.go#L459-L464
train
natefinch/lumberjack
lumberjack.go
compressLogFile
func compressLogFile(src, dst string) (err error) { f, err := os.Open(src) if err != nil { return fmt.Errorf("failed to open log file: %v", err) } defer f.Close() fi, err := os_Stat(src) if err != nil { return fmt.Errorf("failed to stat log file: %v", err) } if err := chown(dst, fi); err != nil { return...
go
func compressLogFile(src, dst string) (err error) { f, err := os.Open(src) if err != nil { return fmt.Errorf("failed to open log file: %v", err) } defer f.Close() fi, err := os_Stat(src) if err != nil { return fmt.Errorf("failed to stat log file: %v", err) } if err := chown(dst, fi); err != nil { return...
[ "func", "compressLogFile", "(", "src", ",", "dst", "string", ")", "(", "err", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "src", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",...
// compressLogFile compresses the given log file, removing the // uncompressed log file if successful.
[ "compressLogFile", "compresses", "the", "given", "log", "file", "removing", "the", "uncompressed", "log", "file", "if", "successful", "." ]
94d9e492cc53c413571e9b40c0b39cee643ee516
https://github.com/natefinch/lumberjack/blob/94d9e492cc53c413571e9b40c0b39cee643ee516/lumberjack.go#L468-L519
train
allegro/bigcache
bigcache.go
Get
func (c *BigCache) Get(key string) ([]byte, error) { hashedKey := c.hash.Sum64(key) shard := c.getShard(hashedKey) return shard.get(key, hashedKey) }
go
func (c *BigCache) Get(key string) ([]byte, error) { hashedKey := c.hash.Sum64(key) shard := c.getShard(hashedKey) return shard.get(key, hashedKey) }
[ "func", "(", "c", "*", "BigCache", ")", "Get", "(", "key", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "hashedKey", ":=", "c", ".", "hash", ".", "Sum64", "(", "key", ")", "\n", "shard", ":=", "c", ".", "getShard", "(", "hashed...
// Get reads entry for the key. // It returns an ErrEntryNotFound when // no entry exists for the given key.
[ "Get", "reads", "entry", "for", "the", "key", ".", "It", "returns", "an", "ErrEntryNotFound", "when", "no", "entry", "exists", "for", "the", "given", "key", "." ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/bigcache.go#L107-L111
train
allegro/bigcache
bigcache.go
Set
func (c *BigCache) Set(key string, entry []byte) error { hashedKey := c.hash.Sum64(key) shard := c.getShard(hashedKey) return shard.set(key, hashedKey, entry) }
go
func (c *BigCache) Set(key string, entry []byte) error { hashedKey := c.hash.Sum64(key) shard := c.getShard(hashedKey) return shard.set(key, hashedKey, entry) }
[ "func", "(", "c", "*", "BigCache", ")", "Set", "(", "key", "string", ",", "entry", "[", "]", "byte", ")", "error", "{", "hashedKey", ":=", "c", ".", "hash", ".", "Sum64", "(", "key", ")", "\n", "shard", ":=", "c", ".", "getShard", "(", "hashedKey...
// Set saves entry under the key
[ "Set", "saves", "entry", "under", "the", "key" ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/bigcache.go#L114-L118
train
allegro/bigcache
bigcache.go
Delete
func (c *BigCache) Delete(key string) error { hashedKey := c.hash.Sum64(key) shard := c.getShard(hashedKey) return shard.del(key, hashedKey) }
go
func (c *BigCache) Delete(key string) error { hashedKey := c.hash.Sum64(key) shard := c.getShard(hashedKey) return shard.del(key, hashedKey) }
[ "func", "(", "c", "*", "BigCache", ")", "Delete", "(", "key", "string", ")", "error", "{", "hashedKey", ":=", "c", ".", "hash", ".", "Sum64", "(", "key", ")", "\n", "shard", ":=", "c", ".", "getShard", "(", "hashedKey", ")", "\n", "return", "shard"...
// Delete removes the key
[ "Delete", "removes", "the", "key" ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/bigcache.go#L121-L125
train
allegro/bigcache
bigcache.go
Reset
func (c *BigCache) Reset() error { for _, shard := range c.shards { shard.reset(c.config) } return nil }
go
func (c *BigCache) Reset() error { for _, shard := range c.shards { shard.reset(c.config) } return nil }
[ "func", "(", "c", "*", "BigCache", ")", "Reset", "(", ")", "error", "{", "for", "_", ",", "shard", ":=", "range", "c", ".", "shards", "{", "shard", ".", "reset", "(", "c", ".", "config", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Reset empties all cache shards
[ "Reset", "empties", "all", "cache", "shards" ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/bigcache.go#L128-L133
train
allegro/bigcache
bigcache.go
Len
func (c *BigCache) Len() int { var len int for _, shard := range c.shards { len += shard.len() } return len }
go
func (c *BigCache) Len() int { var len int for _, shard := range c.shards { len += shard.len() } return len }
[ "func", "(", "c", "*", "BigCache", ")", "Len", "(", ")", "int", "{", "var", "len", "int", "\n", "for", "_", ",", "shard", ":=", "range", "c", ".", "shards", "{", "len", "+=", "shard", ".", "len", "(", ")", "\n", "}", "\n", "return", "len", "\...
// Len computes number of entries in cache
[ "Len", "computes", "number", "of", "entries", "in", "cache" ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/bigcache.go#L136-L142
train
allegro/bigcache
bigcache.go
Capacity
func (c *BigCache) Capacity() int { var len int for _, shard := range c.shards { len += shard.capacity() } return len }
go
func (c *BigCache) Capacity() int { var len int for _, shard := range c.shards { len += shard.capacity() } return len }
[ "func", "(", "c", "*", "BigCache", ")", "Capacity", "(", ")", "int", "{", "var", "len", "int", "\n", "for", "_", ",", "shard", ":=", "range", "c", ".", "shards", "{", "len", "+=", "shard", ".", "capacity", "(", ")", "\n", "}", "\n", "return", "...
// Capacity returns amount of bytes store in the cache.
[ "Capacity", "returns", "amount", "of", "bytes", "store", "in", "the", "cache", "." ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/bigcache.go#L145-L151
train
allegro/bigcache
bigcache.go
Stats
func (c *BigCache) Stats() Stats { var s Stats for _, shard := range c.shards { tmp := shard.getStats() s.Hits += tmp.Hits s.Misses += tmp.Misses s.DelHits += tmp.DelHits s.DelMisses += tmp.DelMisses s.Collisions += tmp.Collisions } return s }
go
func (c *BigCache) Stats() Stats { var s Stats for _, shard := range c.shards { tmp := shard.getStats() s.Hits += tmp.Hits s.Misses += tmp.Misses s.DelHits += tmp.DelHits s.DelMisses += tmp.DelMisses s.Collisions += tmp.Collisions } return s }
[ "func", "(", "c", "*", "BigCache", ")", "Stats", "(", ")", "Stats", "{", "var", "s", "Stats", "\n", "for", "_", ",", "shard", ":=", "range", "c", ".", "shards", "{", "tmp", ":=", "shard", ".", "getStats", "(", ")", "\n", "s", ".", "Hits", "+=",...
// Stats returns cache's statistics
[ "Stats", "returns", "cache", "s", "statistics" ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/bigcache.go#L154-L165
train
allegro/bigcache
config.go
DefaultConfig
func DefaultConfig(eviction time.Duration) Config { return Config{ Shards: 1024, LifeWindow: eviction, CleanWindow: 0, MaxEntriesInWindow: 1000 * 10 * 60, MaxEntrySize: 500, Verbose: true, Hasher: newDefaultHasher(), HardMaxCacheSize: 0, Logge...
go
func DefaultConfig(eviction time.Duration) Config { return Config{ Shards: 1024, LifeWindow: eviction, CleanWindow: 0, MaxEntriesInWindow: 1000 * 10 * 60, MaxEntrySize: 500, Verbose: true, Hasher: newDefaultHasher(), HardMaxCacheSize: 0, Logge...
[ "func", "DefaultConfig", "(", "eviction", "time", ".", "Duration", ")", "Config", "{", "return", "Config", "{", "Shards", ":", "1024", ",", "LifeWindow", ":", "eviction", ",", "CleanWindow", ":", "0", ",", "MaxEntriesInWindow", ":", "1000", "*", "10", "*",...
// DefaultConfig initializes config with default values. // When load for BigCache can be predicted in advance then it is better to use custom config.
[ "DefaultConfig", "initializes", "config", "with", "default", "values", ".", "When", "load", "for", "BigCache", "can", "be", "predicted", "in", "advance", "then", "it", "is", "better", "to", "use", "custom", "config", "." ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/config.go#L47-L59
train
allegro/bigcache
config.go
initialShardSize
func (c Config) initialShardSize() int { return max(c.MaxEntriesInWindow/c.Shards, minimumEntriesInShard) }
go
func (c Config) initialShardSize() int { return max(c.MaxEntriesInWindow/c.Shards, minimumEntriesInShard) }
[ "func", "(", "c", "Config", ")", "initialShardSize", "(", ")", "int", "{", "return", "max", "(", "c", ".", "MaxEntriesInWindow", "/", "c", ".", "Shards", ",", "minimumEntriesInShard", ")", "\n", "}" ]
// initialShardSize computes initial shard size
[ "initialShardSize", "computes", "initial", "shard", "size" ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/config.go#L62-L64
train
allegro/bigcache
config.go
maximumShardSize
func (c Config) maximumShardSize() int { maxShardSize := 0 if c.HardMaxCacheSize > 0 { maxShardSize = convertMBToBytes(c.HardMaxCacheSize) / c.Shards } return maxShardSize }
go
func (c Config) maximumShardSize() int { maxShardSize := 0 if c.HardMaxCacheSize > 0 { maxShardSize = convertMBToBytes(c.HardMaxCacheSize) / c.Shards } return maxShardSize }
[ "func", "(", "c", "Config", ")", "maximumShardSize", "(", ")", "int", "{", "maxShardSize", ":=", "0", "\n\n", "if", "c", ".", "HardMaxCacheSize", ">", "0", "{", "maxShardSize", "=", "convertMBToBytes", "(", "c", ".", "HardMaxCacheSize", ")", "/", "c", "....
// maximumShardSize computes maximum shard size
[ "maximumShardSize", "computes", "maximum", "shard", "size" ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/config.go#L67-L75
train
allegro/bigcache
config.go
OnRemoveFilterSet
func (c Config) OnRemoveFilterSet(reasons ...RemoveReason) Config { c.onRemoveFilter = 0 for i := range reasons { c.onRemoveFilter |= 1 << uint(reasons[i]) } return c }
go
func (c Config) OnRemoveFilterSet(reasons ...RemoveReason) Config { c.onRemoveFilter = 0 for i := range reasons { c.onRemoveFilter |= 1 << uint(reasons[i]) } return c }
[ "func", "(", "c", "Config", ")", "OnRemoveFilterSet", "(", "reasons", "...", "RemoveReason", ")", "Config", "{", "c", ".", "onRemoveFilter", "=", "0", "\n", "for", "i", ":=", "range", "reasons", "{", "c", ".", "onRemoveFilter", "|=", "1", "<<", "uint", ...
// OnRemoveFilterSet sets which remove reasons will trigger a call to OnRemoveWithReason. // Filtering out reasons prevents bigcache from unwrapping them, which saves cpu.
[ "OnRemoveFilterSet", "sets", "which", "remove", "reasons", "will", "trigger", "a", "call", "to", "OnRemoveWithReason", ".", "Filtering", "out", "reasons", "prevents", "bigcache", "from", "unwrapping", "them", "which", "saves", "cpu", "." ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/config.go#L79-L86
train
allegro/bigcache
server/stats_handler.go
statsIndexHandler
func statsIndexHandler() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet: getCacheStatsHandler(w, r) default: w.WriteHeader(http.StatusMethodNotAllowed) } }) }
go
func statsIndexHandler() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet: getCacheStatsHandler(w, r) default: w.WriteHeader(http.StatusMethodNotAllowed) } }) }
[ "func", "statsIndexHandler", "(", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "switch", "r", ".", "Method", "{", "case", ...
// index for stats handle
[ "index", "for", "stats", "handle" ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/server/stats_handler.go#L10-L19
train
allegro/bigcache
server/stats_handler.go
getCacheStatsHandler
func getCacheStatsHandler(w http.ResponseWriter, r *http.Request) { target, err := json.Marshal(cache.Stats()) if err != nil { w.WriteHeader(http.StatusInternalServerError) log.Printf("cannot marshal cache stats. error: %s", err) return } // since we're sending a struct, make it easy for consumers to interfac...
go
func getCacheStatsHandler(w http.ResponseWriter, r *http.Request) { target, err := json.Marshal(cache.Stats()) if err != nil { w.WriteHeader(http.StatusInternalServerError) log.Printf("cannot marshal cache stats. error: %s", err) return } // since we're sending a struct, make it easy for consumers to interfac...
[ "func", "getCacheStatsHandler", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "target", ",", "err", ":=", "json", ".", "Marshal", "(", "cache", ".", "Stats", "(", ")", ")", "\n", "if", "err", "!=", "nil", ...
// returns the cache's statistics.
[ "returns", "the", "cache", "s", "statistics", "." ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/server/stats_handler.go#L22-L33
train
allegro/bigcache
server/middleware.go
serviceLoader
func serviceLoader(h http.Handler, svcs ...service) http.Handler { for _, svc := range svcs { h = svc(h) } return h }
go
func serviceLoader(h http.Handler, svcs ...service) http.Handler { for _, svc := range svcs { h = svc(h) } return h }
[ "func", "serviceLoader", "(", "h", "http", ".", "Handler", ",", "svcs", "...", "service", ")", "http", ".", "Handler", "{", "for", "_", ",", "svc", ":=", "range", "svcs", "{", "h", "=", "svc", "(", "h", ")", "\n", "}", "\n", "return", "h", "\n", ...
// chain load middleware services.
[ "chain", "load", "middleware", "services", "." ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/server/middleware.go#L13-L18
train
allegro/bigcache
server/middleware.go
requestMetrics
func requestMetrics(l *log.Logger) service { return func(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() h.ServeHTTP(w, r) l.Printf("%s request to %s took %vns.", r.Method, r.URL.Path, time.Now().Sub(start).Nanoseconds()) }) } }
go
func requestMetrics(l *log.Logger) service { return func(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() h.ServeHTTP(w, r) l.Printf("%s request to %s took %vns.", r.Method, r.URL.Path, time.Now().Sub(start).Nanoseconds()) }) } }
[ "func", "requestMetrics", "(", "l", "*", "log", ".", "Logger", ")", "service", "{", "return", "func", "(", "h", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "Respo...
// middleware for request length metrics.
[ "middleware", "for", "request", "length", "metrics", "." ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/server/middleware.go#L21-L29
train
allegro/bigcache
iterator.go
SetNext
func (it *EntryInfoIterator) SetNext() bool { it.mutex.Lock() it.valid = false it.currentIndex++ if it.elementsCount > it.currentIndex { it.valid = true it.mutex.Unlock() return true } for i := it.currentShard + 1; i < it.cache.config.Shards; i++ { it.elements, it.elementsCount = it.cache.shards[i].cop...
go
func (it *EntryInfoIterator) SetNext() bool { it.mutex.Lock() it.valid = false it.currentIndex++ if it.elementsCount > it.currentIndex { it.valid = true it.mutex.Unlock() return true } for i := it.currentShard + 1; i < it.cache.config.Shards; i++ { it.elements, it.elementsCount = it.cache.shards[i].cop...
[ "func", "(", "it", "*", "EntryInfoIterator", ")", "SetNext", "(", ")", "bool", "{", "it", ".", "mutex", ".", "Lock", "(", ")", "\n\n", "it", ".", "valid", "=", "false", "\n", "it", ".", "currentIndex", "++", "\n\n", "if", "it", ".", "elementsCount", ...
// SetNext moves to next element and returns true if it exists.
[ "SetNext", "moves", "to", "next", "element", "and", "returns", "true", "if", "it", "exists", "." ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/iterator.go#L59-L85
train
allegro/bigcache
iterator.go
Value
func (it *EntryInfoIterator) Value() (EntryInfo, error) { it.mutex.Lock() if !it.valid { it.mutex.Unlock() return emptyEntryInfo, ErrInvalidIteratorState } entry, err := it.cache.shards[it.currentShard].getEntry(int(it.elements[it.currentIndex])) if err != nil { it.mutex.Unlock() return emptyEntryInfo, ...
go
func (it *EntryInfoIterator) Value() (EntryInfo, error) { it.mutex.Lock() if !it.valid { it.mutex.Unlock() return emptyEntryInfo, ErrInvalidIteratorState } entry, err := it.cache.shards[it.currentShard].getEntry(int(it.elements[it.currentIndex])) if err != nil { it.mutex.Unlock() return emptyEntryInfo, ...
[ "func", "(", "it", "*", "EntryInfoIterator", ")", "Value", "(", ")", "(", "EntryInfo", ",", "error", ")", "{", "it", ".", "mutex", ".", "Lock", "(", ")", "\n\n", "if", "!", "it", ".", "valid", "{", "it", ".", "mutex", ".", "Unlock", "(", ")", "...
// Value returns current value from the iterator
[ "Value", "returns", "current", "value", "from", "the", "iterator" ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/iterator.go#L100-L122
train
allegro/bigcache
server/cache_handlers.go
getCacheHandler
func getCacheHandler(w http.ResponseWriter, r *http.Request) { target := r.URL.Path[len(cachePath):] if target == "" { w.WriteHeader(http.StatusBadRequest) w.Write([]byte("can't get a key if there is no key.")) log.Print("empty request.") return } entry, err := cache.Get(target) if err != nil { errMsg :=...
go
func getCacheHandler(w http.ResponseWriter, r *http.Request) { target := r.URL.Path[len(cachePath):] if target == "" { w.WriteHeader(http.StatusBadRequest) w.Write([]byte("can't get a key if there is no key.")) log.Print("empty request.") return } entry, err := cache.Get(target) if err != nil { errMsg :=...
[ "func", "getCacheHandler", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "target", ":=", "r", ".", "URL", ".", "Path", "[", "len", "(", "cachePath", ")", ":", "]", "\n", "if", "target", "==", "\"", "\"", ...
// handles get requests.
[ "handles", "get", "requests", "." ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/server/cache_handlers.go#L24-L45
train
allegro/bigcache
server/cache_handlers.go
deleteCacheHandler
func deleteCacheHandler(w http.ResponseWriter, r *http.Request) { target := r.URL.Path[len(cachePath):] if err := cache.Delete(target); err != nil { if strings.Contains((err).Error(), "not found") { w.WriteHeader(http.StatusNotFound) log.Printf("%s not found.", target) return } w.WriteHeader(http.Statu...
go
func deleteCacheHandler(w http.ResponseWriter, r *http.Request) { target := r.URL.Path[len(cachePath):] if err := cache.Delete(target); err != nil { if strings.Contains((err).Error(), "not found") { w.WriteHeader(http.StatusNotFound) log.Printf("%s not found.", target) return } w.WriteHeader(http.Statu...
[ "func", "deleteCacheHandler", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "target", ":=", "r", ".", "URL", ".", "Path", "[", "len", "(", "cachePath", ")", ":", "]", "\n", "if", "err", ":=", "cache", "."...
// delete cache objects.
[ "delete", "cache", "objects", "." ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/server/cache_handlers.go#L73-L87
train
allegro/bigcache
fnv.go
Sum64
func (f fnv64a) Sum64(key string) uint64 { var hash uint64 = offset64 for i := 0; i < len(key); i++ { hash ^= uint64(key[i]) hash *= prime64 } return hash }
go
func (f fnv64a) Sum64(key string) uint64 { var hash uint64 = offset64 for i := 0; i < len(key); i++ { hash ^= uint64(key[i]) hash *= prime64 } return hash }
[ "func", "(", "f", "fnv64a", ")", "Sum64", "(", "key", "string", ")", "uint64", "{", "var", "hash", "uint64", "=", "offset64", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "key", ")", ";", "i", "++", "{", "hash", "^=", "uint64", "(", ...
// Sum64 gets the string and returns its uint64 hash value.
[ "Sum64", "gets", "the", "string", "and", "returns", "its", "uint64", "hash", "value", "." ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/fnv.go#L20-L28
train
allegro/bigcache
queue/bytes_queue.go
NewBytesQueue
func NewBytesQueue(initialCapacity int, maxCapacity int, verbose bool) *BytesQueue { return &BytesQueue{ array: make([]byte, initialCapacity), capacity: initialCapacity, maxCapacity: maxCapacity, headerBuffer: make([]byte, headerEntrySize), tail: leftMarginIndex, head: ...
go
func NewBytesQueue(initialCapacity int, maxCapacity int, verbose bool) *BytesQueue { return &BytesQueue{ array: make([]byte, initialCapacity), capacity: initialCapacity, maxCapacity: maxCapacity, headerBuffer: make([]byte, headerEntrySize), tail: leftMarginIndex, head: ...
[ "func", "NewBytesQueue", "(", "initialCapacity", "int", ",", "maxCapacity", "int", ",", "verbose", "bool", ")", "*", "BytesQueue", "{", "return", "&", "BytesQueue", "{", "array", ":", "make", "(", "[", "]", "byte", ",", "initialCapacity", ")", ",", "capaci...
// NewBytesQueue initialize new bytes queue. // Initial capacity is used in bytes array allocation // When verbose flag is set then information about memory allocation are printed
[ "NewBytesQueue", "initialize", "new", "bytes", "queue", ".", "Initial", "capacity", "is", "used", "in", "bytes", "array", "allocation", "When", "verbose", "flag", "is", "set", "then", "information", "about", "memory", "allocation", "are", "printed" ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/queue/bytes_queue.go#L47-L59
train
allegro/bigcache
queue/bytes_queue.go
Reset
func (q *BytesQueue) Reset() { // Just reset indexes q.tail = leftMarginIndex q.head = leftMarginIndex q.rightMargin = leftMarginIndex q.count = 0 }
go
func (q *BytesQueue) Reset() { // Just reset indexes q.tail = leftMarginIndex q.head = leftMarginIndex q.rightMargin = leftMarginIndex q.count = 0 }
[ "func", "(", "q", "*", "BytesQueue", ")", "Reset", "(", ")", "{", "// Just reset indexes", "q", ".", "tail", "=", "leftMarginIndex", "\n", "q", ".", "head", "=", "leftMarginIndex", "\n", "q", ".", "rightMargin", "=", "leftMarginIndex", "\n", "q", ".", "c...
// Reset removes all entries from queue
[ "Reset", "removes", "all", "entries", "from", "queue" ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/queue/bytes_queue.go#L62-L68
train
allegro/bigcache
queue/bytes_queue.go
Push
func (q *BytesQueue) Push(data []byte) (int, error) { dataLen := len(data) if q.availableSpaceAfterTail() < dataLen+headerEntrySize { if q.availableSpaceBeforeHead() >= dataLen+headerEntrySize { q.tail = leftMarginIndex } else if q.capacity+headerEntrySize+dataLen >= q.maxCapacity && q.maxCapacity > 0 { re...
go
func (q *BytesQueue) Push(data []byte) (int, error) { dataLen := len(data) if q.availableSpaceAfterTail() < dataLen+headerEntrySize { if q.availableSpaceBeforeHead() >= dataLen+headerEntrySize { q.tail = leftMarginIndex } else if q.capacity+headerEntrySize+dataLen >= q.maxCapacity && q.maxCapacity > 0 { re...
[ "func", "(", "q", "*", "BytesQueue", ")", "Push", "(", "data", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "dataLen", ":=", "len", "(", "data", ")", "\n\n", "if", "q", ".", "availableSpaceAfterTail", "(", ")", "<", "dataLen", "+", ...
// Push copies entry at the end of queue and moves tail pointer. Allocates more space if needed. // Returns index for pushed data or error if maximum size queue limit is reached.
[ "Push", "copies", "entry", "at", "the", "end", "of", "queue", "and", "moves", "tail", "pointer", ".", "Allocates", "more", "space", "if", "needed", ".", "Returns", "index", "for", "pushed", "data", "or", "error", "if", "maximum", "size", "queue", "limit", ...
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/queue/bytes_queue.go#L72-L90
train
allegro/bigcache
queue/bytes_queue.go
Pop
func (q *BytesQueue) Pop() ([]byte, error) { data, size, err := q.peek(q.head) if err != nil { return nil, err } q.head += headerEntrySize + size q.count-- if q.head == q.rightMargin { q.head = leftMarginIndex if q.tail == q.rightMargin { q.tail = leftMarginIndex } q.rightMargin = q.tail } retur...
go
func (q *BytesQueue) Pop() ([]byte, error) { data, size, err := q.peek(q.head) if err != nil { return nil, err } q.head += headerEntrySize + size q.count-- if q.head == q.rightMargin { q.head = leftMarginIndex if q.tail == q.rightMargin { q.tail = leftMarginIndex } q.rightMargin = q.tail } retur...
[ "func", "(", "q", "*", "BytesQueue", ")", "Pop", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "data", ",", "size", ",", "err", ":=", "q", ".", "peek", "(", "q", ".", "head", ")", "\n", "if", "err", "!=", "nil", "{", "return", "n...
// Pop reads the oldest entry from queue and moves head pointer to the next one
[ "Pop", "reads", "the", "oldest", "entry", "from", "queue", "and", "moves", "head", "pointer", "to", "the", "next", "one" ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/queue/bytes_queue.go#L139-L157
train
allegro/bigcache
queue/bytes_queue.go
Peek
func (q *BytesQueue) Peek() ([]byte, error) { data, _, err := q.peek(q.head) return data, err }
go
func (q *BytesQueue) Peek() ([]byte, error) { data, _, err := q.peek(q.head) return data, err }
[ "func", "(", "q", "*", "BytesQueue", ")", "Peek", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "data", ",", "_", ",", "err", ":=", "q", ".", "peek", "(", "q", ".", "head", ")", "\n", "return", "data", ",", "err", "\n", "}" ]
// Peek reads the oldest entry from list without moving head pointer
[ "Peek", "reads", "the", "oldest", "entry", "from", "list", "without", "moving", "head", "pointer" ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/queue/bytes_queue.go#L160-L163
train
allegro/bigcache
queue/bytes_queue.go
Get
func (q *BytesQueue) Get(index int) ([]byte, error) { data, _, err := q.peek(index) return data, err }
go
func (q *BytesQueue) Get(index int) ([]byte, error) { data, _, err := q.peek(index) return data, err }
[ "func", "(", "q", "*", "BytesQueue", ")", "Get", "(", "index", "int", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "data", ",", "_", ",", "err", ":=", "q", ".", "peek", "(", "index", ")", "\n", "return", "data", ",", "err", "\n", "}" ]
// Get reads entry from index
[ "Get", "reads", "entry", "from", "index" ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/queue/bytes_queue.go#L166-L169
train
allegro/bigcache
queue/bytes_queue.go
peekCheckErr
func (q *BytesQueue) peekCheckErr(index int) error { if q.count == 0 { return errEmptyQueue } if index <= 0 { return errInvalidIndex } if index+headerEntrySize >= len(q.array) { return errIndexOutOfBounds } return nil }
go
func (q *BytesQueue) peekCheckErr(index int) error { if q.count == 0 { return errEmptyQueue } if index <= 0 { return errInvalidIndex } if index+headerEntrySize >= len(q.array) { return errIndexOutOfBounds } return nil }
[ "func", "(", "q", "*", "BytesQueue", ")", "peekCheckErr", "(", "index", "int", ")", "error", "{", "if", "q", ".", "count", "==", "0", "{", "return", "errEmptyQueue", "\n", "}", "\n\n", "if", "index", "<=", "0", "{", "return", "errInvalidIndex", "\n", ...
// peekCheckErr is identical to peek, but does not actually return any data
[ "peekCheckErr", "is", "identical", "to", "peek", "but", "does", "not", "actually", "return", "any", "data" ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/queue/bytes_queue.go#L192-L206
train
sevlyar/go-daemon
examples/cmd/gd-log-rotation/log_file.go
NewLogFile
func NewLogFile(name string, file *os.File) (*LogFile, error) { rw := &LogFile{ file: file, name: name, } if file == nil { if err := rw.Rotate(); err != nil { return nil, err } } return rw, nil }
go
func NewLogFile(name string, file *os.File) (*LogFile, error) { rw := &LogFile{ file: file, name: name, } if file == nil { if err := rw.Rotate(); err != nil { return nil, err } } return rw, nil }
[ "func", "NewLogFile", "(", "name", "string", ",", "file", "*", "os", ".", "File", ")", "(", "*", "LogFile", ",", "error", ")", "{", "rw", ":=", "&", "LogFile", "{", "file", ":", "file", ",", "name", ":", "name", ",", "}", "\n", "if", "file", "=...
// NewLogFile creates a new LogFile. The file is optional - it will be created if needed.
[ "NewLogFile", "creates", "a", "new", "LogFile", ".", "The", "file", "is", "optional", "-", "it", "will", "be", "created", "if", "needed", "." ]
fedf95d0cd0be92511436dbc84c290ff1c104f61
https://github.com/sevlyar/go-daemon/blob/fedf95d0cd0be92511436dbc84c290ff1c104f61/examples/cmd/gd-log-rotation/log_file.go#L16-L27
train
sevlyar/go-daemon
examples/cmd/gd-log-rotation/log_file.go
Rotate
func (l *LogFile) Rotate() error { // rename dest file if it already exists. if _, err := os.Stat(l.name); err == nil { name := l.name + "." + time.Now().Format(time.RFC3339) if err = os.Rename(l.name, name); err != nil { return err } } // create new file. file, err := os.Create(l.name) if err != nil { ...
go
func (l *LogFile) Rotate() error { // rename dest file if it already exists. if _, err := os.Stat(l.name); err == nil { name := l.name + "." + time.Now().Format(time.RFC3339) if err = os.Rename(l.name, name); err != nil { return err } } // create new file. file, err := os.Create(l.name) if err != nil { ...
[ "func", "(", "l", "*", "LogFile", ")", "Rotate", "(", ")", "error", "{", "// rename dest file if it already exists.", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "l", ".", "name", ")", ";", "err", "==", "nil", "{", "name", ":=", "l", ".", ...
// Rotate renames old log file, creates new one, switches log and closes the old file.
[ "Rotate", "renames", "old", "log", "file", "creates", "new", "one", "switches", "log", "and", "closes", "the", "old", "file", "." ]
fedf95d0cd0be92511436dbc84c290ff1c104f61
https://github.com/sevlyar/go-daemon/blob/fedf95d0cd0be92511436dbc84c290ff1c104f61/examples/cmd/gd-log-rotation/log_file.go#L37-L61
train
sevlyar/go-daemon
lock_file.go
CreatePidFile
func CreatePidFile(name string, perm os.FileMode) (lock *LockFile, err error) { if lock, err = OpenLockFile(name, perm); err != nil { return } if err = lock.Lock(); err != nil { lock.Remove() return } if err = lock.WritePid(); err != nil { lock.Remove() } return }
go
func CreatePidFile(name string, perm os.FileMode) (lock *LockFile, err error) { if lock, err = OpenLockFile(name, perm); err != nil { return } if err = lock.Lock(); err != nil { lock.Remove() return } if err = lock.WritePid(); err != nil { lock.Remove() } return }
[ "func", "CreatePidFile", "(", "name", "string", ",", "perm", "os", ".", "FileMode", ")", "(", "lock", "*", "LockFile", ",", "err", "error", ")", "{", "if", "lock", ",", "err", "=", "OpenLockFile", "(", "name", ",", "perm", ")", ";", "err", "!=", "n...
// CreatePidFile opens the named file, applies exclusive lock and writes // current process id to file.
[ "CreatePidFile", "opens", "the", "named", "file", "applies", "exclusive", "lock", "and", "writes", "current", "process", "id", "to", "file", "." ]
fedf95d0cd0be92511436dbc84c290ff1c104f61
https://github.com/sevlyar/go-daemon/blob/fedf95d0cd0be92511436dbc84c290ff1c104f61/lock_file.go#L26-L38
train
sevlyar/go-daemon
lock_file.go
OpenLockFile
func OpenLockFile(name string, perm os.FileMode) (lock *LockFile, err error) { var file *os.File if file, err = os.OpenFile(name, os.O_RDWR|os.O_CREATE, perm); err == nil { lock = &LockFile{file} } return }
go
func OpenLockFile(name string, perm os.FileMode) (lock *LockFile, err error) { var file *os.File if file, err = os.OpenFile(name, os.O_RDWR|os.O_CREATE, perm); err == nil { lock = &LockFile{file} } return }
[ "func", "OpenLockFile", "(", "name", "string", ",", "perm", "os", ".", "FileMode", ")", "(", "lock", "*", "LockFile", ",", "err", "error", ")", "{", "var", "file", "*", "os", ".", "File", "\n", "if", "file", ",", "err", "=", "os", ".", "OpenFile", ...
// OpenLockFile opens the named file with flags os.O_RDWR|os.O_CREATE and specified perm. // If successful, function returns LockFile for opened file.
[ "OpenLockFile", "opens", "the", "named", "file", "with", "flags", "os", ".", "O_RDWR|os", ".", "O_CREATE", "and", "specified", "perm", ".", "If", "successful", "function", "returns", "LockFile", "for", "opened", "file", "." ]
fedf95d0cd0be92511436dbc84c290ff1c104f61
https://github.com/sevlyar/go-daemon/blob/fedf95d0cd0be92511436dbc84c290ff1c104f61/lock_file.go#L42-L48
train
sevlyar/go-daemon
lock_file.go
ReadPidFile
func ReadPidFile(name string) (pid int, err error) { var file *os.File if file, err = os.OpenFile(name, os.O_RDONLY, 0640); err != nil { return } defer file.Close() lock := &LockFile{file} pid, err = lock.ReadPid() return }
go
func ReadPidFile(name string) (pid int, err error) { var file *os.File if file, err = os.OpenFile(name, os.O_RDONLY, 0640); err != nil { return } defer file.Close() lock := &LockFile{file} pid, err = lock.ReadPid() return }
[ "func", "ReadPidFile", "(", "name", "string", ")", "(", "pid", "int", ",", "err", "error", ")", "{", "var", "file", "*", "os", ".", "File", "\n", "if", "file", ",", "err", "=", "os", ".", "OpenFile", "(", "name", ",", "os", ".", "O_RDONLY", ",", ...
// ReadPidFile reads process id from file with give name and returns pid. // If unable read from a file, returns error.
[ "ReadPidFile", "reads", "process", "id", "from", "file", "with", "give", "name", "and", "returns", "pid", ".", "If", "unable", "read", "from", "a", "file", "returns", "error", "." ]
fedf95d0cd0be92511436dbc84c290ff1c104f61
https://github.com/sevlyar/go-daemon/blob/fedf95d0cd0be92511436dbc84c290ff1c104f61/lock_file.go#L62-L72
train
sevlyar/go-daemon
lock_file.go
WritePid
func (file *LockFile) WritePid() (err error) { if _, err = file.Seek(0, os.SEEK_SET); err != nil { return } var fileLen int if fileLen, err = fmt.Fprint(file, os.Getpid()); err != nil { return } if err = file.Truncate(int64(fileLen)); err != nil { return } err = file.Sync() return }
go
func (file *LockFile) WritePid() (err error) { if _, err = file.Seek(0, os.SEEK_SET); err != nil { return } var fileLen int if fileLen, err = fmt.Fprint(file, os.Getpid()); err != nil { return } if err = file.Truncate(int64(fileLen)); err != nil { return } err = file.Sync() return }
[ "func", "(", "file", "*", "LockFile", ")", "WritePid", "(", ")", "(", "err", "error", ")", "{", "if", "_", ",", "err", "=", "file", ".", "Seek", "(", "0", ",", "os", ".", "SEEK_SET", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n...
// WritePid writes current process id to an open file.
[ "WritePid", "writes", "current", "process", "id", "to", "an", "open", "file", "." ]
fedf95d0cd0be92511436dbc84c290ff1c104f61
https://github.com/sevlyar/go-daemon/blob/fedf95d0cd0be92511436dbc84c290ff1c104f61/lock_file.go#L75-L88
train
sevlyar/go-daemon
lock_file.go
ReadPid
func (file *LockFile) ReadPid() (pid int, err error) { if _, err = file.Seek(0, os.SEEK_SET); err != nil { return } _, err = fmt.Fscan(file, &pid) return }
go
func (file *LockFile) ReadPid() (pid int, err error) { if _, err = file.Seek(0, os.SEEK_SET); err != nil { return } _, err = fmt.Fscan(file, &pid) return }
[ "func", "(", "file", "*", "LockFile", ")", "ReadPid", "(", ")", "(", "pid", "int", ",", "err", "error", ")", "{", "if", "_", ",", "err", "=", "file", ".", "Seek", "(", "0", ",", "os", ".", "SEEK_SET", ")", ";", "err", "!=", "nil", "{", "retur...
// ReadPid reads process id from file and returns pid. // If unable read from a file, returns error.
[ "ReadPid", "reads", "process", "id", "from", "file", "and", "returns", "pid", ".", "If", "unable", "read", "from", "a", "file", "returns", "error", "." ]
fedf95d0cd0be92511436dbc84c290ff1c104f61
https://github.com/sevlyar/go-daemon/blob/fedf95d0cd0be92511436dbc84c290ff1c104f61/lock_file.go#L92-L98
train
sevlyar/go-daemon
lock_file.go
Remove
func (file *LockFile) Remove() error { defer file.Close() if err := file.Unlock(); err != nil { return err } return os.Remove(file.Name()) }
go
func (file *LockFile) Remove() error { defer file.Close() if err := file.Unlock(); err != nil { return err } return os.Remove(file.Name()) }
[ "func", "(", "file", "*", "LockFile", ")", "Remove", "(", ")", "error", "{", "defer", "file", ".", "Close", "(", ")", "\n\n", "if", "err", ":=", "file", ".", "Unlock", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", ...
// Remove removes lock, closes and removes an open file.
[ "Remove", "removes", "lock", "closes", "and", "removes", "an", "open", "file", "." ]
fedf95d0cd0be92511436dbc84c290ff1c104f61
https://github.com/sevlyar/go-daemon/blob/fedf95d0cd0be92511436dbc84c290ff1c104f61/lock_file.go#L101-L109
train
sevlyar/go-daemon
command.go
AddCommand
func AddCommand(f Flag, sig os.Signal, handler SignalHandlerFunc) { if f != nil { AddFlag(f, sig) } if handler != nil { SetSigHandler(handler, sig) } }
go
func AddCommand(f Flag, sig os.Signal, handler SignalHandlerFunc) { if f != nil { AddFlag(f, sig) } if handler != nil { SetSigHandler(handler, sig) } }
[ "func", "AddCommand", "(", "f", "Flag", ",", "sig", "os", ".", "Signal", ",", "handler", "SignalHandlerFunc", ")", "{", "if", "f", "!=", "nil", "{", "AddFlag", "(", "f", ",", "sig", ")", "\n", "}", "\n", "if", "handler", "!=", "nil", "{", "SetSigHa...
// AddCommand is wrapper on AddFlag and SetSigHandler functions.
[ "AddCommand", "is", "wrapper", "on", "AddFlag", "and", "SetSigHandler", "functions", "." ]
fedf95d0cd0be92511436dbc84c290ff1c104f61
https://github.com/sevlyar/go-daemon/blob/fedf95d0cd0be92511436dbc84c290ff1c104f61/command.go#L8-L15
train