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
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | 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(cert.Names) > 10000 {
// for simplicity, just remove random elements
for key := range certCache {
if key == "" { // ... but not the default cert
continue
}
delete(certCache, key)
break
}
}
for _, name := range cert.Names {
certCache[name] = cert
}
certCacheMu.Unlock()
} | 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(cert.Names) > 10000 {
// for simplicity, just remove random elements
for key := range certCache {
if key == "" { // ... but not the default cert
continue
}
delete(certCache, key)
break
}
}
for _, name := range cert.Names {
certCache[name] = cert
}
certCacheMu.Unlock()
} | [
"func",
"cacheCertificate",
"(",
"cert",
"Certificate",
")",
"{",
"if",
"cert",
".",
"Config",
"==",
"nil",
"{",
"cert",
".",
"Config",
"=",
"new",
"(",
"Config",
")",
"\n",
"}",
"\n",
"certCacheMu",
".",
"Lock",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"certCache",
"[",
"\"",
"\"",
"]",
";",
"!",
"ok",
"{",
"// use as default - must be *appended* to end of list, or bad things happen!",
"cert",
".",
"Names",
"=",
"append",
"(",
"cert",
".",
"Names",
",",
"\"",
"\"",
")",
"\n",
"certCache",
"[",
"\"",
"\"",
"]",
"=",
"cert",
"\n",
"}",
"\n",
"for",
"len",
"(",
"certCache",
")",
"+",
"len",
"(",
"cert",
".",
"Names",
")",
">",
"10000",
"{",
"// for simplicity, just remove random elements",
"for",
"key",
":=",
"range",
"certCache",
"{",
"if",
"key",
"==",
"\"",
"\"",
"{",
"// ... but not the default cert",
"continue",
"\n",
"}",
"\n",
"delete",
"(",
"certCache",
",",
"key",
")",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"cert",
".",
"Names",
"{",
"certCache",
"[",
"name",
"]",
"=",
"cert",
"\n",
"}",
"\n",
"certCacheMu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // 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
// that is already a key in the cache will be replaced with this cert.
//
// This function is safe for concurrent use. | [
"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",
"that",
"is",
"already",
"a",
"key",
"in",
"the",
"cache",
"will",
"be",
"replaced",
"with",
"this",
"cert",
".",
"This",
"function",
"is",
"safe",
"for",
"concurrent",
"use",
"."
] | 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",
"PoolHandler",
"{",
"Next",
":",
"next",
",",
"refreshLauncher",
":",
"&",
"sync",
".",
"Once",
"{",
"}",
"}",
"\n",
"}",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // 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 that the pool will run with a context that represents a request (log level for instance)
h.refreshLauncher.Do(func() {
ctx := r.Context()
go func(ctx context.Context) {
for {
pfconfigdriver.PfconfigPool.Refresh(ctx)
time.Sleep(1 * time.Second)
}
}(ctx)
})
return h.Next.ServeHTTP(w, r)
} else {
panic("Unable to obtain pfconfigpool lock in caddy middleware")
}
} | 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 that the pool will run with a context that represents a request (log level for instance)
h.refreshLauncher.Do(func() {
ctx := r.Context()
go func(ctx context.Context) {
for {
pfconfigdriver.PfconfigPool.Refresh(ctx)
time.Sleep(1 * time.Second)
}
}(ctx)
})
return h.Next.ServeHTTP(w, r)
} else {
panic("Unable to obtain pfconfigpool lock in caddy middleware")
}
} | [
"func",
"(",
"h",
"PoolHandler",
")",
"ServeHTTP",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"int",
",",
"error",
")",
"{",
"id",
",",
"err",
":=",
"pfconfigdriver",
".",
"PfconfigPool",
".",
"ReadLock",
"(",
"r",
".",
"Context",
"(",
")",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"defer",
"pfconfigdriver",
".",
"PfconfigPool",
".",
"ReadUnlock",
"(",
"r",
".",
"Context",
"(",
")",
",",
"id",
")",
"\n\n",
"// We launch the refresh job once, the first time a request comes in",
"// This ensures that the pool will run with a context that represents a request (log level for instance)",
"h",
".",
"refreshLauncher",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"ctx",
":=",
"r",
".",
"Context",
"(",
")",
"\n",
"go",
"func",
"(",
"ctx",
"context",
".",
"Context",
")",
"{",
"for",
"{",
"pfconfigdriver",
".",
"PfconfigPool",
".",
"Refresh",
"(",
"ctx",
")",
"\n",
"time",
".",
"Sleep",
"(",
"1",
"*",
"time",
".",
"Second",
")",
"\n",
"}",
"\n",
"}",
"(",
"ctx",
")",
"\n",
"}",
")",
"\n\n",
"return",
"h",
".",
"Next",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"}",
"else",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}"
] | // 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",
"}",
"\n",
"return",
"uh",
".",
"CheckDown",
"(",
"uh",
")",
"\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",
")",
"\n",
"}",
"\n\n",
"u",
".",
"stop",
"=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"if",
"u",
".",
"Path",
"!=",
"\"",
"\"",
"{",
"u",
".",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"defer",
"u",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"u",
".",
"healthCheckWorker",
"(",
"u",
".",
"stop",
")",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // 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 another one.
if uh.CheckURL == "" || uh.Checking { // nothing configured
uh.Unlock()
return
}
uh.Checking = true
uh.Unlock()
// default timeout (5s)
r, err := healthClient.Get(uh.CheckURL)
defer func() {
uh.Lock()
uh.Checking = false
uh.Unlock()
}()
if err != nil {
log.Printf("[WARNING] Host %s health check probe failed: %v", uh.Name, err)
return
}
if err == nil {
io.Copy(ioutil.Discard, r.Body)
r.Body.Close()
if r.StatusCode < 200 || r.StatusCode >= 400 {
log.Printf("[WARNING] Host %s health check returned HTTP code %d", uh.Name, r.StatusCode)
return
}
// We are healthy again, reset fails.
atomic.StoreInt32(&uh.Fails, 0)
return
}
} | 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 another one.
if uh.CheckURL == "" || uh.Checking { // nothing configured
uh.Unlock()
return
}
uh.Checking = true
uh.Unlock()
// default timeout (5s)
r, err := healthClient.Get(uh.CheckURL)
defer func() {
uh.Lock()
uh.Checking = false
uh.Unlock()
}()
if err != nil {
log.Printf("[WARNING] Host %s health check probe failed: %v", uh.Name, err)
return
}
if err == nil {
io.Copy(ioutil.Discard, r.Body)
r.Body.Close()
if r.StatusCode < 200 || r.StatusCode >= 400 {
log.Printf("[WARNING] Host %s health check returned HTTP code %d", uh.Name, r.StatusCode)
return
}
// We are healthy again, reset fails.
atomic.StoreInt32(&uh.Fails, 0)
return
}
} | [
"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.go and lookup.go, bail out when nothing",
"// is configured to healthcheck. Or we mid check? Don't run another one.",
"if",
"uh",
".",
"CheckURL",
"==",
"\"",
"\"",
"||",
"uh",
".",
"Checking",
"{",
"// nothing configured",
"uh",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"uh",
".",
"Checking",
"=",
"true",
"\n",
"uh",
".",
"Unlock",
"(",
")",
"\n\n",
"// default timeout (5s)",
"r",
",",
"err",
":=",
"healthClient",
".",
"Get",
"(",
"uh",
".",
"CheckURL",
")",
"\n\n",
"defer",
"func",
"(",
")",
"{",
"uh",
".",
"Lock",
"(",
")",
"\n",
"uh",
".",
"Checking",
"=",
"false",
"\n",
"uh",
".",
"Unlock",
"(",
")",
"\n",
"}",
"(",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"uh",
".",
"Name",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"err",
"==",
"nil",
"{",
"io",
".",
"Copy",
"(",
"ioutil",
".",
"Discard",
",",
"r",
".",
"Body",
")",
"\n",
"r",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"if",
"r",
".",
"StatusCode",
"<",
"200",
"||",
"r",
".",
"StatusCode",
">=",
"400",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"uh",
".",
"Name",
",",
"r",
".",
"StatusCode",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// We are healthy again, reset fails.",
"atomic",
".",
"StoreInt32",
"(",
"&",
"uh",
".",
"Fails",
",",
"0",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}"
] | // 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 per-host lock and a threaded health check.
//
// We use the Checking bool to avoid concurrent checks against the same
// host; if one is taking a long time, the next one will find a check in
// progress and simply return before trying.
//
// We are carefully avoiding having the mutex locked while we check,
// otherwise checks will back up, potentially a lot of them if a host is
// absent for a long time. This arrangement makes checks quickly see if
// they are the only one running and abort otherwise.
// HealthCheckURL performs the http.Get that implements healthcheck. | [
"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",
"per",
"-",
"host",
"lock",
"and",
"a",
"threaded",
"health",
"check",
".",
"We",
"use",
"the",
"Checking",
"bool",
"to",
"avoid",
"concurrent",
"checks",
"against",
"the",
"same",
"host",
";",
"if",
"one",
"is",
"taking",
"a",
"long",
"time",
"the",
"next",
"one",
"will",
"find",
"a",
"check",
"in",
"progress",
"and",
"simply",
"return",
"before",
"trying",
".",
"We",
"are",
"carefully",
"avoiding",
"having",
"the",
"mutex",
"locked",
"while",
"we",
"check",
"otherwise",
"checks",
"will",
"back",
"up",
"potentially",
"a",
"lot",
"of",
"them",
"if",
"a",
"host",
"is",
"absent",
"for",
"a",
"long",
"time",
".",
"This",
"arrangement",
"makes",
"checks",
"quickly",
"see",
"if",
"they",
"are",
"the",
"only",
"one",
"running",
"and",
"abort",
"otherwise",
".",
"HealthCheckURL",
"performs",
"the",
"http",
".",
"Get",
"that",
"implements",
"healthcheck",
"."
] | 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
}
return u.Spray.Select(pool)
}
if u.Policy == nil {
h := (&Random{}).Select(pool)
if h != nil {
return h
}
if h == nil && u.Spray == nil {
return nil
}
return u.Spray.Select(pool)
}
h := u.Policy.Select(pool)
if h != nil {
return h
}
if u.Spray == nil {
return nil
}
return u.Spray.Select(pool)
} | 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
}
return u.Spray.Select(pool)
}
if u.Policy == nil {
h := (&Random{}).Select(pool)
if h != nil {
return h
}
if h == nil && u.Spray == nil {
return nil
}
return u.Spray.Select(pool)
}
h := u.Policy.Select(pool)
if h != nil {
return h
}
if u.Spray == nil {
return nil
}
return u.Spray.Select(pool)
} | [
"func",
"(",
"u",
"*",
"HealthCheck",
")",
"Select",
"(",
")",
"*",
"UpstreamHost",
"{",
"pool",
":=",
"u",
".",
"Hosts",
"\n",
"if",
"len",
"(",
"pool",
")",
"==",
"1",
"{",
"if",
"pool",
"[",
"0",
"]",
".",
"Down",
"(",
")",
"&&",
"u",
".",
"Spray",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"pool",
"[",
"0",
"]",
"\n",
"}",
"\n",
"allDown",
":=",
"true",
"\n",
"for",
"_",
",",
"host",
":=",
"range",
"pool",
"{",
"if",
"!",
"host",
".",
"Down",
"(",
")",
"{",
"allDown",
"=",
"false",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"allDown",
"{",
"if",
"u",
".",
"Spray",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"u",
".",
"Spray",
".",
"Select",
"(",
"pool",
")",
"\n",
"}",
"\n\n",
"if",
"u",
".",
"Policy",
"==",
"nil",
"{",
"h",
":=",
"(",
"&",
"Random",
"{",
"}",
")",
".",
"Select",
"(",
"pool",
")",
"\n",
"if",
"h",
"!=",
"nil",
"{",
"return",
"h",
"\n",
"}",
"\n",
"if",
"h",
"==",
"nil",
"&&",
"u",
".",
"Spray",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"u",
".",
"Spray",
".",
"Select",
"(",
"pool",
")",
"\n",
"}",
"\n\n",
"h",
":=",
"u",
".",
"Policy",
".",
"Select",
"(",
"pool",
")",
"\n",
"if",
"h",
"!=",
"nil",
"{",
"return",
"h",
"\n",
"}",
"\n\n",
"if",
"u",
".",
"Spray",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"u",
".",
"Spray",
".",
"Select",
"(",
"pool",
")",
"\n",
"}"
] | // 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, checkPort, err := net.SplitHostPort(hostName)
if err != nil {
checkHostName = hostName
}
if u.Port != "" {
checkPort = u.Port
}
checkURL := "http://" + net.JoinHostPort(checkHostName, checkPort) + u.Path
return checkURL
} | 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, checkPort, err := net.SplitHostPort(hostName)
if err != nil {
checkHostName = hostName
}
if u.Port != "" {
checkPort = u.Port
}
checkURL := "http://" + net.JoinHostPort(checkHostName, checkPort) + u.Path
return checkURL
} | [
"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",
"(",
"name",
")",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"len",
"(",
"ret",
".",
"Host",
")",
">",
"0",
"{",
"hostName",
"=",
"ret",
".",
"Host",
"\n",
"}",
"\n\n",
"// Extract the port number from the parsed server name.",
"checkHostName",
",",
"checkPort",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"hostName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"checkHostName",
"=",
"hostName",
"\n",
"}",
"\n\n",
"if",
"u",
".",
"Port",
"!=",
"\"",
"\"",
"{",
"checkPort",
"=",
"u",
".",
"Port",
"\n",
"}",
"\n\n",
"checkURL",
":=",
"\"",
"\"",
"+",
"net",
".",
"JoinHostPort",
"(",
"checkHostName",
",",
"checkPort",
")",
"+",
"u",
".",
"Path",
"\n",
"return",
"checkURL",
"\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 = redis.NewClient(&redis.Options{
Addr: redisclient.Config.RedisArgs.Server,
Network: network,
})
router := httprouter.New()
router.GET("/api/v1/pfqueue/task/:job_id/status", jobStatus.handleStatus)
router.GET("/api/v1/pfqueue/task/:job_id/status/poll", jobStatus.handleStatusPoll)
jobStatus.router = router
return jobStatus, nil
} | 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 = redis.NewClient(&redis.Options{
Addr: redisclient.Config.RedisArgs.Server,
Network: network,
})
router := httprouter.New()
router.GET("/api/v1/pfqueue/task/:job_id/status", jobStatus.handleStatus)
router.GET("/api/v1/pfqueue/task/:job_id/status/poll", jobStatus.handleStatusPoll)
jobStatus.router = router
return jobStatus, nil
} | [
"func",
"buildJobStatusHandler",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"JobStatusHandler",
",",
"error",
")",
"{",
"jobStatus",
":=",
"JobStatusHandler",
"{",
"}",
"\n\n",
"pfconfigdriver",
".",
"PfconfigPool",
".",
"AddStruct",
"(",
"ctx",
",",
"&",
"redisclient",
".",
"Config",
")",
"\n",
"var",
"network",
"string",
"\n",
"if",
"redisclient",
".",
"Config",
".",
"RedisArgs",
".",
"Server",
"[",
"0",
"]",
"==",
"'/'",
"{",
"network",
"=",
"\"",
"\"",
"\n",
"}",
"else",
"{",
"network",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"jobStatus",
".",
"redis",
"=",
"redis",
".",
"NewClient",
"(",
"&",
"redis",
".",
"Options",
"{",
"Addr",
":",
"redisclient",
".",
"Config",
".",
"RedisArgs",
".",
"Server",
",",
"Network",
":",
"network",
",",
"}",
")",
"\n\n",
"router",
":=",
"httprouter",
".",
"New",
"(",
")",
"\n",
"router",
".",
"GET",
"(",
"\"",
"\"",
",",
"jobStatus",
".",
"handleStatus",
")",
"\n",
"router",
".",
"GET",
"(",
"\"",
"\"",
",",
"jobStatus",
".",
"handleStatusPoll",
")",
"\n\n",
"jobStatus",
".",
"router",
"=",
"router",
"\n\n",
"return",
"jobStatus",
",",
"nil",
"\n",
"}"
] | // 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",
"(",
"w",
",",
"httpErrorMsg",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"}",
"\n",
"}"
] | // 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",
")",
".",
"Error",
"(",
"msg",
")",
"\n",
"fmt",
".",
"Fprintln",
"(",
"os",
".",
"Stderr",
",",
"msg",
")",
"\n",
"debug",
".",
"PrintStack",
"(",
")",
"\n",
"}"
] | // 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",
"outputted",
"in",
"STDERR",
"and",
"a",
"log",
"line",
"is",
"added",
"in",
"Error"
] | 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",
".",
"Option",
"{",
"if",
"o",
".",
"Option",
"(",
")",
"==",
"ednsStubCode",
"&&",
"len",
"(",
"o",
".",
"(",
"*",
"dns",
".",
"EDNS0_LOCAL",
")",
".",
"Data",
")",
"==",
"1",
"&&",
"o",
".",
"(",
"*",
"dns",
".",
"EDNS0_LOCAL",
")",
".",
"Data",
"[",
"0",
"]",
"==",
"1",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // 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 = append(m.Extra, ednsStub)
return m
} | 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 = append(m.Extra, ednsStub)
return m
} | [
"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",
"option",
"!=",
"nil",
"{",
"option",
".",
"Option",
"=",
"append",
"(",
"option",
".",
"Option",
",",
"&",
"dns",
".",
"EDNS0_LOCAL",
"{",
"Code",
":",
"ednsStubCode",
",",
"Data",
":",
"[",
"]",
"byte",
"{",
"1",
"}",
"}",
")",
"\n",
"return",
"m",
"\n",
"}",
"\n\n",
"m",
".",
"Extra",
"=",
"append",
"(",
"m",
".",
"Extra",
",",
"ednsStub",
")",
"\n",
"return",
"m",
"\n",
"}"
] | // 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",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // 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",
".",
"Dedup",
"(",
"m",
".",
"Ns",
",",
"nil",
")",
"\n",
"m",
".",
"Extra",
"=",
"dns",
".",
"Dedup",
"(",
"m",
".",
"Extra",
",",
"nil",
")",
"\n",
"return",
"m",
"\n",
"}"
] | // 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: []byte(".:" + Port + " {\nwhoami\n}\n"),
ServerTypeName: serverType,
}
},
NewContext: newContext,
})
} | 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: []byte(".:" + Port + " {\nwhoami\n}\n"),
ServerTypeName: serverType,
}
},
NewContext: newContext,
})
} | [
"func",
"init",
"(",
")",
"{",
"flag",
".",
"StringVar",
"(",
"&",
"Port",
",",
"serverType",
"+",
"\"",
"\"",
",",
"DefaultPort",
",",
"\"",
"\"",
")",
"\n\n",
"caddy",
".",
"RegisterServerType",
"(",
"serverType",
",",
"caddy",
".",
"ServerType",
"{",
"Directives",
":",
"func",
"(",
")",
"[",
"]",
"string",
"{",
"return",
"directives",
"}",
",",
"DefaultInput",
":",
"func",
"(",
")",
"caddy",
".",
"Input",
"{",
"return",
"caddy",
".",
"CaddyfileInput",
"{",
"Filepath",
":",
"\"",
"\"",
",",
"Contents",
":",
"[",
"]",
"byte",
"(",
"\"",
"\"",
"+",
"Port",
"+",
"\"",
"\\n",
"\\n",
"\\n",
"\"",
")",
",",
"ServerTypeName",
":",
"serverType",
",",
"}",
"\n",
"}",
",",
"NewContext",
":",
"newContext",
",",
"}",
")",
"\n",
"}"
] | // 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",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"fw",
".",
"Vsys",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // 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 HTTP")
return fw.startHttp(ctx, info, timeout)
}
} | 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 HTTP")
return fw.startHttp(ctx, info, timeout)
}
} | [
"func",
"(",
"fw",
"*",
"PaloAlto",
")",
"Start",
"(",
"ctx",
"context",
".",
"Context",
",",
"info",
"map",
"[",
"string",
"]",
"string",
",",
"timeout",
"int",
")",
"(",
"bool",
",",
"error",
")",
"{",
"if",
"fw",
".",
"Transport",
"==",
"\"",
"\"",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"return",
"fw",
".",
"startSyslog",
"(",
"ctx",
",",
"info",
",",
"timeout",
")",
"\n",
"}",
"else",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"return",
"fw",
".",
"startHttp",
"(",
"ctx",
",",
"info",
",",
"timeout",
")",
"\n",
"}",
"\n",
"}"
] | // 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",
"depending",
"on",
"the",
"type",
"of",
"the",
"transport"
] | 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 writer, err
} | 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 writer, err
} | [
"func",
"(",
"fw",
"*",
"PaloAlto",
")",
"getSyslog",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"*",
"syslog",
".",
"Writer",
",",
"error",
")",
"{",
"writer",
",",
"err",
":=",
"syslog",
".",
"Dial",
"(",
"\"",
"\"",
",",
"fw",
".",
"PfconfigHashNS",
"+",
"\"",
"\"",
",",
"syslog",
".",
"LOG_ERR",
"|",
"syslog",
".",
"LOG_LOCAL5",
",",
"\"",
"\"",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Error",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"writer",
",",
"err",
"\n",
"}"
] | // 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",
"UDP",
"this",
"should",
"never",
"fail"
] | 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",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"err",
"=",
"writer",
".",
"Err",
"(",
"line",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Error",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // 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",
".",
"sendSyslog",
"(",
"ctx",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"info",
"[",
"\"",
"\"",
"]",
",",
"info",
"[",
"\"",
"\"",
"]",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"else",
"{",
"return",
"true",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // 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>
<entry name="{{.Username}}" ip="{{.Ip}}" timeout="{{.Timeout}}"/>
</login>
</payload>
</uid-message>
`)
b := new(bytes.Buffer)
t.Execute(b, fw.InfoToTemplateCtx(ctx, info, timeout))
return b.String()
} | 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>
<entry name="{{.Username}}" ip="{{.Ip}}" timeout="{{.Timeout}}"/>
</login>
</payload>
</uid-message>
`)
b := new(bytes.Buffer)
t.Execute(b, fw.InfoToTemplateCtx(ctx, info, timeout))
return b.String()
} | [
"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",
"\n",
"t",
":=",
"template",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"t",
".",
"Parse",
"(",
"`\n<uid-message>\n\t\t<version>1.0</version>\n\t\t<type>update</type>\n\t\t<payload>\n\t\t\t\t<login>\n\t\t\t\t\t\t<entry name=\"{{.Username}}\" ip=\"{{.Ip}}\" timeout=\"{{.Timeout}}\"/>\n\t\t\t\t</login>\n\t\t</payload>\n</uid-message>\n`",
")",
"\n",
"b",
":=",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"\n",
"t",
".",
"Execute",
"(",
"b",
",",
"fw",
".",
"InfoToTemplateCtx",
"(",
"ctx",
",",
"info",
",",
"timeout",
")",
")",
"\n",
"return",
"b",
".",
"String",
"(",
")",
"\n",
"}"
] | // 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.LoggerWContext(ctx).Info("Sending SSO to PaloAlto using HTTP")
return fw.stopHttp(ctx, info)
}
} | 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.LoggerWContext(ctx).Info("Sending SSO to PaloAlto using HTTP")
return fw.stopHttp(ctx, info)
}
} | [
"func",
"(",
"fw",
"*",
"PaloAlto",
")",
"Stop",
"(",
"ctx",
"context",
".",
"Context",
",",
"info",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"if",
"fw",
".",
"Transport",
"==",
"\"",
"\"",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"return",
"false",
",",
"nil",
"\n",
"}",
"else",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"return",
"fw",
".",
"stopHttp",
"(",
"ctx",
",",
"info",
")",
"\n",
"}",
"\n",
"}"
] | // 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",
"its",
"syslog"
] | 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 {
log.LoggerWContext(ctx).Error(fmt.Sprintf("Error contacting PaloAlto: %s", err))
//Not returning now so that body closes below
}
if resp != nil && resp.Body != nil {
resp.Body.Close()
}
return err == nil, err
} | 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 {
log.LoggerWContext(ctx).Error(fmt.Sprintf("Error contacting PaloAlto: %s", err))
//Not returning now so that body closes below
}
if resp != nil && resp.Body != nil {
resp.Body.Close()
}
return err == nil, err
} | [
"func",
"(",
"fw",
"*",
"PaloAlto",
")",
"stopHttp",
"(",
"ctx",
"context",
".",
"Context",
",",
"info",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"resp",
",",
"err",
":=",
"fw",
".",
"getHttpClient",
"(",
"ctx",
")",
".",
"PostForm",
"(",
"\"",
"\"",
"+",
"fw",
".",
"PfconfigHashNS",
"+",
"\"",
"\"",
"+",
"fw",
".",
"Port",
"+",
"\"",
"\"",
"+",
"fw",
".",
"Vsys",
"+",
"\"",
"\"",
"+",
"fw",
".",
"Password",
",",
"url",
".",
"Values",
"{",
"\"",
"\"",
":",
"{",
"fw",
".",
"stopHttpPayload",
"(",
"ctx",
",",
"info",
")",
"}",
"}",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Error",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"//Not returning now so that body closes below",
"}",
"\n\n",
"if",
"resp",
"!=",
"nil",
"&&",
"resp",
".",
"Body",
"!=",
"nil",
"{",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"return",
"err",
"==",
"nil",
",",
"err",
"\n",
"}"
] | // 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, errors.New("Invalid token info")
}
var tenantId int
if tokenInfo.TenantId == AccessAllTenants && xptid == "" {
log.LoggerWContext(ctx).Debug("Token wasn't issued for a particular tenant and no X-PacketFence-Tenant-Id was provided. Request will use the default PacketFence tenant")
} else if xptid == "" {
log.LoggerWContext(ctx).Debug("Empty X-PacketFence-Tenant-Id, defaulting to token tenant ID")
tenantId = tokenInfo.TenantId
r.Header.Set("X-PacketFence-Tenant-Id", strconv.Itoa(tenantId))
} else {
var err error
tenantId, err = strconv.Atoi(xptid)
if err != nil {
msg := fmt.Sprintf("Impossible to parse X-PacketFence-Tenant-Id %s into a valid number, error: %s", xptid, err)
log.LoggerWContext(ctx).Warn(msg)
return false, errors.New(msg)
}
}
roles := make([]string, len(tokenInfo.AdminRoles))
i := 0
for r, _ := range tokenInfo.AdminRoles {
roles[i] = r
i++
}
r.Header.Set("X-PacketFence-Admin-Roles", strings.Join(roles, ","))
r.Header.Set("X-PacketFence-Username", tokenInfo.Username)
return tam.IsAuthorized(ctx, r.Method, r.URL.Path, tenantId, tokenInfo)
} | 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, errors.New("Invalid token info")
}
var tenantId int
if tokenInfo.TenantId == AccessAllTenants && xptid == "" {
log.LoggerWContext(ctx).Debug("Token wasn't issued for a particular tenant and no X-PacketFence-Tenant-Id was provided. Request will use the default PacketFence tenant")
} else if xptid == "" {
log.LoggerWContext(ctx).Debug("Empty X-PacketFence-Tenant-Id, defaulting to token tenant ID")
tenantId = tokenInfo.TenantId
r.Header.Set("X-PacketFence-Tenant-Id", strconv.Itoa(tenantId))
} else {
var err error
tenantId, err = strconv.Atoi(xptid)
if err != nil {
msg := fmt.Sprintf("Impossible to parse X-PacketFence-Tenant-Id %s into a valid number, error: %s", xptid, err)
log.LoggerWContext(ctx).Warn(msg)
return false, errors.New(msg)
}
}
roles := make([]string, len(tokenInfo.AdminRoles))
i := 0
for r, _ := range tokenInfo.AdminRoles {
roles[i] = r
i++
}
r.Header.Set("X-PacketFence-Admin-Roles", strings.Join(roles, ","))
r.Header.Set("X-PacketFence-Username", tokenInfo.Username)
return tam.IsAuthorized(ctx, r.Method, r.URL.Path, tenantId, tokenInfo)
} | [
"func",
"(",
"tam",
"*",
"TokenAuthorizationMiddleware",
")",
"BearerRequestIsAuthorized",
"(",
"ctx",
"context",
".",
"Context",
",",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"bool",
",",
"error",
")",
"{",
"token",
":=",
"tam",
".",
"TokenFromBearerRequest",
"(",
"ctx",
",",
"r",
")",
"\n",
"xptid",
":=",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n\n",
"tokenInfo",
",",
"_",
":=",
"tam",
".",
"tokenBackend",
".",
"TokenInfoForToken",
"(",
"token",
")",
"\n\n",
"if",
"tokenInfo",
"==",
"nil",
"{",
"return",
"false",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"tenantId",
"int",
"\n\n",
"if",
"tokenInfo",
".",
"TenantId",
"==",
"AccessAllTenants",
"&&",
"xptid",
"==",
"\"",
"\"",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"if",
"xptid",
"==",
"\"",
"\"",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"tenantId",
"=",
"tokenInfo",
".",
"TenantId",
"\n",
"r",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"strconv",
".",
"Itoa",
"(",
"tenantId",
")",
")",
"\n",
"}",
"else",
"{",
"var",
"err",
"error",
"\n",
"tenantId",
",",
"err",
"=",
"strconv",
".",
"Atoi",
"(",
"xptid",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"msg",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"xptid",
",",
"err",
")",
"\n",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Warn",
"(",
"msg",
")",
"\n",
"return",
"false",
",",
"errors",
".",
"New",
"(",
"msg",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"roles",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"tokenInfo",
".",
"AdminRoles",
")",
")",
"\n",
"i",
":=",
"0",
"\n",
"for",
"r",
",",
"_",
":=",
"range",
"tokenInfo",
".",
"AdminRoles",
"{",
"roles",
"[",
"i",
"]",
"=",
"r",
"\n",
"i",
"++",
"\n",
"}",
"\n",
"r",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"strings",
".",
"Join",
"(",
"roles",
",",
"\"",
"\"",
")",
")",
"\n\n",
"r",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"tokenInfo",
".",
"Username",
")",
"\n\n",
"return",
"tam",
".",
"IsAuthorized",
"(",
"ctx",
",",
"r",
".",
"Method",
",",
"r",
".",
"URL",
".",
"Path",
",",
"tenantId",
",",
"tokenInfo",
")",
"\n",
"}"
] | // 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())
if !authAdminRoles || err != nil {
return authAdminRoles, err
}
authTenant, err := tam.isAuthorizedTenantId(ctx, tenantId, tokenInfo.TenantId)
if !authTenant || err != nil {
return authTenant, err
}
authConfig, err := tam.isAuthorizedConfigNamespace(ctx, path, tokenInfo.TenantId)
if !authConfig || err != nil {
return authConfig, err
}
// If we're here, then we passed all the tests above and we're good to go
return true, nil
} | 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())
if !authAdminRoles || err != nil {
return authAdminRoles, err
}
authTenant, err := tam.isAuthorizedTenantId(ctx, tenantId, tokenInfo.TenantId)
if !authTenant || err != nil {
return authTenant, err
}
authConfig, err := tam.isAuthorizedConfigNamespace(ctx, path, tokenInfo.TenantId)
if !authConfig || err != nil {
return authConfig, err
}
// If we're here, then we passed all the tests above and we're good to go
return true, nil
} | [
"func",
"(",
"tam",
"*",
"TokenAuthorizationMiddleware",
")",
"IsAuthorized",
"(",
"ctx",
"context",
".",
"Context",
",",
"method",
",",
"path",
"string",
",",
"tenantId",
"int",
",",
"tokenInfo",
"*",
"TokenInfo",
")",
"(",
"bool",
",",
"error",
")",
"{",
"if",
"tokenInfo",
"==",
"nil",
"{",
"return",
"false",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"authAdminRoles",
",",
"err",
":=",
"tam",
".",
"isAuthorizedAdminActions",
"(",
"ctx",
",",
"method",
",",
"path",
",",
"tokenInfo",
".",
"AdminActions",
"(",
")",
")",
"\n",
"if",
"!",
"authAdminRoles",
"||",
"err",
"!=",
"nil",
"{",
"return",
"authAdminRoles",
",",
"err",
"\n",
"}",
"\n\n",
"authTenant",
",",
"err",
":=",
"tam",
".",
"isAuthorizedTenantId",
"(",
"ctx",
",",
"tenantId",
",",
"tokenInfo",
".",
"TenantId",
")",
"\n",
"if",
"!",
"authTenant",
"||",
"err",
"!=",
"nil",
"{",
"return",
"authTenant",
",",
"err",
"\n",
"}",
"\n\n",
"authConfig",
",",
"err",
":=",
"tam",
".",
"isAuthorizedConfigNamespace",
"(",
"ctx",
",",
"path",
",",
"tokenInfo",
".",
"TenantId",
")",
"\n",
"if",
"!",
"authConfig",
"||",
"err",
"!=",
"nil",
"{",
"return",
"authConfig",
",",
"err",
"\n",
"}",
"\n\n",
"// If we're here, then we passed all the tests above and we're good to go",
"return",
"true",
",",
"nil",
"\n",
"}"
] | // 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 header, add multiple values to a header, or simply
// set a header.
if strings.HasPrefix(name, "-") {
rww.delHeader(strings.TrimLeft(name, "-"))
} else if strings.HasPrefix(name, "+") {
for _, value := range rule.Headers[name] {
rww.Header().Add(strings.TrimLeft(name, "+"), replacer.Replace(value))
}
} else {
for _, value := range rule.Headers[name] {
rww.Header().Set(name, replacer.Replace(value))
}
}
}
}
}
return h.Next.ServeHTTP(rww, r)
} | 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 header, add multiple values to a header, or simply
// set a header.
if strings.HasPrefix(name, "-") {
rww.delHeader(strings.TrimLeft(name, "-"))
} else if strings.HasPrefix(name, "+") {
for _, value := range rule.Headers[name] {
rww.Header().Add(strings.TrimLeft(name, "+"), replacer.Replace(value))
}
} else {
for _, value := range rule.Headers[name] {
rww.Header().Set(name, replacer.Replace(value))
}
}
}
}
}
return h.Next.ServeHTTP(rww, r)
} | [
"func",
"(",
"h",
"Headers",
")",
"ServeHTTP",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"int",
",",
"error",
")",
"{",
"replacer",
":=",
"httpserver",
".",
"NewReplacer",
"(",
"r",
",",
"nil",
",",
"\"",
"\"",
")",
"\n",
"rww",
":=",
"&",
"responseWriterWrapper",
"{",
"w",
":",
"w",
"}",
"\n",
"for",
"_",
",",
"rule",
":=",
"range",
"h",
".",
"Rules",
"{",
"if",
"httpserver",
".",
"Path",
"(",
"r",
".",
"URL",
".",
"Path",
")",
".",
"Matches",
"(",
"rule",
".",
"Path",
")",
"{",
"for",
"name",
":=",
"range",
"rule",
".",
"Headers",
"{",
"// One can either delete a header, add multiple values to a header, or simply",
"// set a header.",
"if",
"strings",
".",
"HasPrefix",
"(",
"name",
",",
"\"",
"\"",
")",
"{",
"rww",
".",
"delHeader",
"(",
"strings",
".",
"TrimLeft",
"(",
"name",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"else",
"if",
"strings",
".",
"HasPrefix",
"(",
"name",
",",
"\"",
"\"",
")",
"{",
"for",
"_",
",",
"value",
":=",
"range",
"rule",
".",
"Headers",
"[",
"name",
"]",
"{",
"rww",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"strings",
".",
"TrimLeft",
"(",
"name",
",",
"\"",
"\"",
")",
",",
"replacer",
".",
"Replace",
"(",
"value",
")",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"for",
"_",
",",
"value",
":=",
"range",
"rule",
".",
"Headers",
"[",
"name",
"]",
"{",
"rww",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"name",
",",
"replacer",
".",
"Replace",
"(",
"value",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"h",
".",
"Next",
".",
"ServeHTTP",
"(",
"rww",
",",
"r",
")",
"\n",
"}"
] | // 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",
";",
"i",
"<",
"targetStrip",
";",
"i",
"++",
"{",
"offset",
",",
"end",
"=",
"dns",
".",
"NextLabel",
"(",
"name",
",",
"offset",
")",
"\n",
"}",
"\n",
"if",
"end",
"{",
"// We overshot the name, use the orignal one.",
"offset",
"=",
"0",
"\n",
"}",
"\n",
"name",
"=",
"name",
"[",
"offset",
":",
"]",
"\n",
"return",
"name",
"\n",
"}"
] | // 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",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"return",
"true",
",",
"nil",
"\n",
"}"
] | // 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",
"(",
"\"",
"\"",
")",
"\n",
"return",
"true",
",",
"nil",
"\n",
"}"
] | // 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",
".",
"handler",
"\n",
"new",
".",
"inDebug",
"=",
"l",
".",
"inDebug",
"\n",
"new",
".",
"processPid",
"=",
"l",
".",
"processPid",
"\n\n",
"return",
"new",
"\n",
"}"
] | // 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",
":=",
"log",
".",
"MultiHandler",
"(",
"logger",
".",
"handler",
",",
"log",
".",
"FuncHandler",
"(",
"f",
")",
")",
"\n",
"logger",
".",
"SetHandler",
"(",
"loggerHandler",
")",
"\n\n",
"return",
"context",
".",
"WithValue",
"(",
"ctx",
",",
"LoggerKey",
",",
"logger",
")",
"\n",
"}"
] | // 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(syslogBackend)
} else {
stdoutBackend := log.StreamHandler(os.Stdout, log.LogfmtFormat())
logger.SetHandler(stdoutBackend)
}
logger.processPid = strconv.Itoa(os.Getpid())
ctx = context.WithValue(ctx, LoggerKey, logger)
level := sharedutils.EnvOrDefault("LOG_LEVEL", "")
if level != "" {
logger.logger.Info("Setting log level to " + level)
ctx = LoggerSetLevel(ctx, level)
}
return ctx
} | 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(syslogBackend)
} else {
stdoutBackend := log.StreamHandler(os.Stdout, log.LogfmtFormat())
logger.SetHandler(stdoutBackend)
}
logger.processPid = strconv.Itoa(os.Getpid())
ctx = context.WithValue(ctx, LoggerKey, logger)
level := sharedutils.EnvOrDefault("LOG_LEVEL", "")
if level != "" {
logger.logger.Info("Setting log level to " + level)
ctx = LoggerSetLevel(ctx, level)
}
return ctx
} | [
"func",
"initContextLogger",
"(",
"ctx",
"context",
".",
"Context",
")",
"context",
".",
"Context",
"{",
"logger",
":=",
"newLoggerStruct",
"(",
")",
"\n\n",
"output",
":=",
"sharedutils",
".",
"EnvOrDefault",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"output",
"==",
"\"",
"\"",
"{",
"syslogBackend",
",",
"err",
":=",
"log",
".",
"SyslogHandler",
"(",
"syslog",
".",
"LOG_INFO",
",",
"ProcessName",
",",
"log",
".",
"LogfmtFormat",
"(",
")",
")",
"\n",
"sharedutils",
".",
"CheckError",
"(",
"err",
")",
"\n",
"logger",
".",
"SetHandler",
"(",
"syslogBackend",
")",
"\n",
"}",
"else",
"{",
"stdoutBackend",
":=",
"log",
".",
"StreamHandler",
"(",
"os",
".",
"Stdout",
",",
"log",
".",
"LogfmtFormat",
"(",
")",
")",
"\n",
"logger",
".",
"SetHandler",
"(",
"stdoutBackend",
")",
"\n",
"}",
"\n\n",
"logger",
".",
"processPid",
"=",
"strconv",
".",
"Itoa",
"(",
"os",
".",
"Getpid",
"(",
")",
")",
"\n\n",
"ctx",
"=",
"context",
".",
"WithValue",
"(",
"ctx",
",",
"LoggerKey",
",",
"logger",
")",
"\n\n",
"level",
":=",
"sharedutils",
".",
"EnvOrDefault",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"level",
"!=",
"\"",
"\"",
"{",
"logger",
".",
"logger",
".",
"Info",
"(",
"\"",
"\"",
"+",
"level",
")",
"\n",
"ctx",
"=",
"LoggerSetLevel",
"(",
"ctx",
",",
"level",
")",
"\n",
"}",
"\n\n",
"return",
"ctx",
"\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",
")",
"\n\n",
"return",
"logger",
"\n",
"}"
] | // 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",
",",
"ordered_map",
".",
"NewOrderedMap",
"(",
")",
")",
"\n",
"return",
"ctx",
"\n",
"}"
] | // 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.OrderedMap)))
return destCtx
} | 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.OrderedMap)))
return destCtx
} | [
"func",
"TranferLogContext",
"(",
"sourceCtx",
"context",
".",
"Context",
",",
"destCtx",
"context",
".",
"Context",
")",
"context",
".",
"Context",
"{",
"destCtx",
"=",
"context",
".",
"WithValue",
"(",
"destCtx",
",",
"LoggerKey",
",",
"sourceCtx",
".",
"Value",
"(",
"LoggerKey",
")",
")",
"\n",
"destCtx",
"=",
"context",
".",
"WithValue",
"(",
"destCtx",
",",
"AdditionnalLogElementsKey",
",",
"sharedutils",
".",
"CopyOrderedMap",
"(",
"sourceCtx",
".",
"Value",
"(",
"AdditionnalLogElementsKey",
")",
".",
"(",
"*",
"ordered_map",
".",
"OrderedMap",
")",
")",
")",
"\n",
"return",
"destCtx",
"\n",
"}"
] | // 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",
".",
"WithValue",
"(",
"ctx",
",",
"RequestUuidKey",
",",
"uStr",
")",
"\n",
"return",
"ctx",
"\n",
"}"
] | // 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",
"\n",
"return",
"s",
"\n",
"}"
] | // 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 {
return err
}
for _, frame := range s.frames {
if _, err = enc.Write(frame); err != nil {
return err
}
}
return enc.Flush()
} | 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 {
return err
}
for _, frame := range s.frames {
if _, err = enc.Write(frame); err != nil {
return err
}
}
return enc.Flush()
} | [
"func",
"(",
"s",
"*",
"TCP",
")",
"Flush",
"(",
")",
"error",
"{",
"defer",
"func",
"(",
")",
"{",
"s",
".",
"frames",
"=",
"s",
".",
"frames",
"[",
":",
"0",
"]",
"\n",
"}",
"(",
")",
"\n",
"c",
",",
"err",
":=",
"net",
".",
"DialTimeout",
"(",
"\"",
"\"",
",",
"s",
".",
"address",
",",
"time",
".",
"Second",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"enc",
",",
"err",
":=",
"fs",
".",
"NewEncoder",
"(",
"c",
",",
"&",
"fs",
".",
"EncoderOptions",
"{",
"ContentType",
":",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
",",
"Bidirectional",
":",
"true",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"frame",
":=",
"range",
"s",
".",
"frames",
"{",
"if",
"_",
",",
"err",
"=",
"enc",
".",
"Write",
"(",
"frame",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"enc",
".",
"Flush",
"(",
")",
"\n",
"}"
] | // 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, Recursive: recursive})
if e != nil {
return nil, e
}
return r, e
})
if err != nil {
return nil, err
}
return resp.(*etcdc.Response), err
} | 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, Recursive: recursive})
if e != nil {
return nil, e
}
return r, e
})
if err != nil {
return nil, err
}
return resp.(*etcdc.Response), err
} | [
"func",
"(",
"e",
"*",
"Etcd",
")",
"get",
"(",
"path",
"string",
",",
"recursive",
"bool",
")",
"(",
"*",
"etcdc",
".",
"Response",
",",
"error",
")",
"{",
"hash",
":=",
"cache",
".",
"Hash",
"(",
"[",
"]",
"byte",
"(",
"path",
")",
")",
"\n\n",
"resp",
",",
"err",
":=",
"e",
".",
"Inflight",
".",
"Do",
"(",
"hash",
",",
"func",
"(",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"ctx",
",",
"cancel",
":=",
"context",
".",
"WithTimeout",
"(",
"e",
".",
"Ctx",
",",
"etcdTimeout",
")",
"\n",
"defer",
"cancel",
"(",
")",
"\n",
"r",
",",
"e",
":=",
"e",
".",
"Client",
".",
"Get",
"(",
"ctx",
",",
"path",
",",
"&",
"etcdc",
".",
"GetOptions",
"{",
"Sort",
":",
"false",
",",
"Recursive",
":",
"recursive",
"}",
")",
"\n",
"if",
"e",
"!=",
"nil",
"{",
"return",
"nil",
",",
"e",
"\n",
"}",
"\n",
"return",
"r",
",",
"e",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"resp",
".",
"(",
"*",
"etcdc",
".",
"Response",
")",
",",
"err",
"\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, err
} | 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, err
} | [
"func",
"(",
"fw",
"*",
"JSONRPC",
")",
"getRequestBody",
"(",
"action",
"string",
",",
"info",
"map",
"[",
"string",
"]",
"string",
",",
"timeout",
"int",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"args",
":=",
"&",
"JSONRPC_Args",
"{",
"User",
":",
"info",
"[",
"\"",
"\"",
"]",
",",
"MAC",
":",
"info",
"[",
"\"",
"\"",
"]",
",",
"IP",
":",
"info",
"[",
"\"",
"\"",
"]",
",",
"Role",
":",
"info",
"[",
"\"",
"\"",
"]",
",",
"Timeout",
":",
"timeout",
",",
"}",
"\n",
"body",
",",
"err",
":=",
"json2",
".",
"EncodeClientRequest",
"(",
"action",
",",
"args",
")",
"\n",
"return",
"body",
",",
"err",
"\n",
"}"
] | // 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("POST", "https://"+fw.PfconfigHashNS+":"+fw.Port, bytes.NewBuffer(body))
if err != nil {
log.LoggerWContext(ctx).Error(fmt.Sprintf("Cannot create HTTP request for JSON-RPC call: %s", err))
return err
}
req.Header.Set("Content-Type", "application/json")
req.SetBasicAuth(fw.Username, fw.Password)
resp, err := fw.getHttpClient(ctx).Do(req)
if err != nil {
log.LoggerWContext(ctx).Error(fmt.Sprintf("Cannot make HTTP request for JSON-RPC call: %s", err))
return err
}
defer resp.Body.Close()
var result [1]string
err = json2.DecodeClientResponse(resp.Body, &result)
if err != nil {
log.LoggerWContext(ctx).Error(fmt.Sprintf("Cannot decode JSON-RPC response: %s", err))
return err
}
if result[0] == "OK" {
return nil
} else {
return fmt.Errorf("JSON-RPC call returned an error: %s", result[0])
}
} | 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("POST", "https://"+fw.PfconfigHashNS+":"+fw.Port, bytes.NewBuffer(body))
if err != nil {
log.LoggerWContext(ctx).Error(fmt.Sprintf("Cannot create HTTP request for JSON-RPC call: %s", err))
return err
}
req.Header.Set("Content-Type", "application/json")
req.SetBasicAuth(fw.Username, fw.Password)
resp, err := fw.getHttpClient(ctx).Do(req)
if err != nil {
log.LoggerWContext(ctx).Error(fmt.Sprintf("Cannot make HTTP request for JSON-RPC call: %s", err))
return err
}
defer resp.Body.Close()
var result [1]string
err = json2.DecodeClientResponse(resp.Body, &result)
if err != nil {
log.LoggerWContext(ctx).Error(fmt.Sprintf("Cannot decode JSON-RPC response: %s", err))
return err
}
if result[0] == "OK" {
return nil
} else {
return fmt.Errorf("JSON-RPC call returned an error: %s", result[0])
}
} | [
"func",
"(",
"fw",
"*",
"JSONRPC",
")",
"makeRpcRequest",
"(",
"ctx",
"context",
".",
"Context",
",",
"action",
"string",
",",
"info",
"map",
"[",
"string",
"]",
"string",
",",
"timeout",
"int",
")",
"error",
"{",
"body",
",",
"err",
":=",
"fw",
".",
"getRequestBody",
"(",
"action",
",",
"info",
",",
"timeout",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Error",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"\"",
"\"",
",",
"\"",
"\"",
"+",
"fw",
".",
"PfconfigHashNS",
"+",
"\"",
"\"",
"+",
"fw",
".",
"Port",
",",
"bytes",
".",
"NewBuffer",
"(",
"body",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Error",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"req",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"req",
".",
"SetBasicAuth",
"(",
"fw",
".",
"Username",
",",
"fw",
".",
"Password",
")",
"\n\n",
"resp",
",",
"err",
":=",
"fw",
".",
"getHttpClient",
"(",
"ctx",
")",
".",
"Do",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Error",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"var",
"result",
"[",
"1",
"]",
"string",
"\n",
"err",
"=",
"json2",
".",
"DecodeClientResponse",
"(",
"resp",
".",
"Body",
",",
"&",
"result",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"LoggerWContext",
"(",
"ctx",
")",
".",
"Error",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"result",
"[",
"0",
"]",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"else",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"result",
"[",
"0",
"]",
")",
"\n",
"}",
"\n",
"}"
] | // 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",
"(",
"ctx",
",",
"\"",
"\"",
",",
"info",
",",
"timeout",
")",
"\n",
"return",
"err",
"==",
"nil",
",",
"err",
"\n",
"}"
] | // 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",
",",
"\"",
"\"",
",",
"info",
",",
"0",
")",
"\n",
"return",
"err",
"==",
"nil",
",",
"err",
"\n",
"}"
] | // 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",
"\n",
"}"
] | // 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",
"they",
"are",
"parsed",
"to",
"set",
"endpoint",
"lists",
"."
] | 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",
"true",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"rgx",
":=",
"range",
"p",
".",
"endpointBlackList",
"{",
"if",
"rgx",
".",
"MatchString",
"(",
"e",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"true",
"\n",
"}"
] | // 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",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // 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",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"p",
".",
"proxypassthrough",
"=",
"append",
"(",
"p",
".",
"proxypassthrough",
",",
"rgx",
")",
"\n",
"p",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // 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",
"_",
",",
"rgx",
":=",
"range",
"p",
".",
"proxypassthrough",
"{",
"if",
"rgx",
".",
"MatchString",
"(",
"e",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // 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 {
return 0, err
}
}
if l.size+writeLen > l.max() {
if err := l.rotate(); err != nil {
return 0, err
}
}
n, err = l.file.Write(p)
l.size += int64(n)
return n, err
} | 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 {
return 0, err
}
}
if l.size+writeLen > l.max() {
if err := l.rotate(); err != nil {
return 0, err
}
}
n, err = l.file.Write(p)
l.size += int64(n)
return n, err
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"Write",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"l",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"l",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"writeLen",
":=",
"int64",
"(",
"len",
"(",
"p",
")",
")",
"\n",
"if",
"writeLen",
">",
"l",
".",
"max",
"(",
")",
"{",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"writeLen",
",",
"l",
".",
"max",
"(",
")",
",",
")",
"\n",
"}",
"\n\n",
"if",
"l",
".",
"file",
"==",
"nil",
"{",
"if",
"err",
"=",
"l",
".",
"openExistingOrNew",
"(",
"len",
"(",
"p",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"l",
".",
"size",
"+",
"writeLen",
">",
"l",
".",
"max",
"(",
")",
"{",
"if",
"err",
":=",
"l",
".",
"rotate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"n",
",",
"err",
"=",
"l",
".",
"file",
".",
"Write",
"(",
"p",
")",
"\n",
"l",
".",
"size",
"+=",
"int64",
"(",
"n",
")",
"\n\n",
"return",
"n",
",",
"err",
"\n",
"}"
] | // 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",
"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",
"."
] | 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 according to the configuration. | [
"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",
"according",
"to",
"the",
"configuration",
"."
] | 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()
}
file, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
// if we fail to open the old log file for some reason, just ignore
// it and open a new log file.
return l.openNew()
}
l.file = file
l.size = info.Size()
return nil
} | 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()
}
file, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
// if we fail to open the old log file for some reason, just ignore
// it and open a new log file.
return l.openNew()
}
l.file = file
l.size = info.Size()
return nil
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"openExistingOrNew",
"(",
"writeLen",
"int",
")",
"error",
"{",
"l",
".",
"mill",
"(",
")",
"\n\n",
"filename",
":=",
"l",
".",
"filename",
"(",
")",
"\n",
"info",
",",
"err",
":=",
"os_Stat",
"(",
"filename",
")",
"\n",
"if",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"l",
".",
"openNew",
"(",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"info",
".",
"Size",
"(",
")",
"+",
"int64",
"(",
"writeLen",
")",
">=",
"l",
".",
"max",
"(",
")",
"{",
"return",
"l",
".",
"rotate",
"(",
")",
"\n",
"}",
"\n\n",
"file",
",",
"err",
":=",
"os",
".",
"OpenFile",
"(",
"filename",
",",
"os",
".",
"O_APPEND",
"|",
"os",
".",
"O_WRONLY",
",",
"0644",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// if we fail to open the old log file for some reason, just ignore",
"// it and open a new log file.",
"return",
"l",
".",
"openNew",
"(",
")",
"\n",
"}",
"\n",
"l",
".",
"file",
"=",
"file",
"\n",
"l",
".",
"size",
"=",
"info",
".",
"Size",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // 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",
"over",
"the",
"MaxSize",
"a",
"new",
"file",
"is",
"created",
"."
] | 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",
"[",
"0",
"]",
")",
"+",
"\"",
"\"",
"\n",
"return",
"filepath",
".",
"Join",
"(",
"os",
".",
"TempDir",
"(",
")",
",",
"name",
")",
"\n",
"}"
] | // 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 []logInfo
for _, f := range files {
// Only count the uncompressed log file or the
// compressed log file, not both.
fn := f.Name()
if strings.HasSuffix(fn, compressSuffix) {
fn = fn[:len(fn)-len(compressSuffix)]
}
preserved[fn] = true
if len(preserved) > l.MaxBackups {
remove = append(remove, f)
} else {
remaining = append(remaining, f)
}
}
files = remaining
}
if l.MaxAge > 0 {
diff := time.Duration(int64(24*time.Hour) * int64(l.MaxAge))
cutoff := currentTime().Add(-1 * diff)
var remaining []logInfo
for _, f := range files {
if f.timestamp.Before(cutoff) {
remove = append(remove, f)
} else {
remaining = append(remaining, f)
}
}
files = remaining
}
if l.Compress {
for _, f := range files {
if !strings.HasSuffix(f.Name(), compressSuffix) {
compress = append(compress, f)
}
}
}
for _, f := range remove {
errRemove := os.Remove(filepath.Join(l.dir(), f.Name()))
if err == nil && errRemove != nil {
err = errRemove
}
}
for _, f := range compress {
fn := filepath.Join(l.dir(), f.Name())
errCompress := compressLogFile(fn, fn+compressSuffix)
if err == nil && errCompress != nil {
err = errCompress
}
}
return err
} | 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 []logInfo
for _, f := range files {
// Only count the uncompressed log file or the
// compressed log file, not both.
fn := f.Name()
if strings.HasSuffix(fn, compressSuffix) {
fn = fn[:len(fn)-len(compressSuffix)]
}
preserved[fn] = true
if len(preserved) > l.MaxBackups {
remove = append(remove, f)
} else {
remaining = append(remaining, f)
}
}
files = remaining
}
if l.MaxAge > 0 {
diff := time.Duration(int64(24*time.Hour) * int64(l.MaxAge))
cutoff := currentTime().Add(-1 * diff)
var remaining []logInfo
for _, f := range files {
if f.timestamp.Before(cutoff) {
remove = append(remove, f)
} else {
remaining = append(remaining, f)
}
}
files = remaining
}
if l.Compress {
for _, f := range files {
if !strings.HasSuffix(f.Name(), compressSuffix) {
compress = append(compress, f)
}
}
}
for _, f := range remove {
errRemove := os.Remove(filepath.Join(l.dir(), f.Name()))
if err == nil && errRemove != nil {
err = errRemove
}
}
for _, f := range compress {
fn := filepath.Join(l.dir(), f.Name())
errCompress := compressLogFile(fn, fn+compressSuffix)
if err == nil && errCompress != nil {
err = errCompress
}
}
return err
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"millRunOnce",
"(",
")",
"error",
"{",
"if",
"l",
".",
"MaxBackups",
"==",
"0",
"&&",
"l",
".",
"MaxAge",
"==",
"0",
"&&",
"!",
"l",
".",
"Compress",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"files",
",",
"err",
":=",
"l",
".",
"oldLogFiles",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"var",
"compress",
",",
"remove",
"[",
"]",
"logInfo",
"\n\n",
"if",
"l",
".",
"MaxBackups",
">",
"0",
"&&",
"l",
".",
"MaxBackups",
"<",
"len",
"(",
"files",
")",
"{",
"preserved",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"bool",
")",
"\n",
"var",
"remaining",
"[",
"]",
"logInfo",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"files",
"{",
"// Only count the uncompressed log file or the",
"// compressed log file, not both.",
"fn",
":=",
"f",
".",
"Name",
"(",
")",
"\n",
"if",
"strings",
".",
"HasSuffix",
"(",
"fn",
",",
"compressSuffix",
")",
"{",
"fn",
"=",
"fn",
"[",
":",
"len",
"(",
"fn",
")",
"-",
"len",
"(",
"compressSuffix",
")",
"]",
"\n",
"}",
"\n",
"preserved",
"[",
"fn",
"]",
"=",
"true",
"\n\n",
"if",
"len",
"(",
"preserved",
")",
">",
"l",
".",
"MaxBackups",
"{",
"remove",
"=",
"append",
"(",
"remove",
",",
"f",
")",
"\n",
"}",
"else",
"{",
"remaining",
"=",
"append",
"(",
"remaining",
",",
"f",
")",
"\n",
"}",
"\n",
"}",
"\n",
"files",
"=",
"remaining",
"\n",
"}",
"\n",
"if",
"l",
".",
"MaxAge",
">",
"0",
"{",
"diff",
":=",
"time",
".",
"Duration",
"(",
"int64",
"(",
"24",
"*",
"time",
".",
"Hour",
")",
"*",
"int64",
"(",
"l",
".",
"MaxAge",
")",
")",
"\n",
"cutoff",
":=",
"currentTime",
"(",
")",
".",
"Add",
"(",
"-",
"1",
"*",
"diff",
")",
"\n\n",
"var",
"remaining",
"[",
"]",
"logInfo",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"files",
"{",
"if",
"f",
".",
"timestamp",
".",
"Before",
"(",
"cutoff",
")",
"{",
"remove",
"=",
"append",
"(",
"remove",
",",
"f",
")",
"\n",
"}",
"else",
"{",
"remaining",
"=",
"append",
"(",
"remaining",
",",
"f",
")",
"\n",
"}",
"\n",
"}",
"\n",
"files",
"=",
"remaining",
"\n",
"}",
"\n\n",
"if",
"l",
".",
"Compress",
"{",
"for",
"_",
",",
"f",
":=",
"range",
"files",
"{",
"if",
"!",
"strings",
".",
"HasSuffix",
"(",
"f",
".",
"Name",
"(",
")",
",",
"compressSuffix",
")",
"{",
"compress",
"=",
"append",
"(",
"compress",
",",
"f",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"f",
":=",
"range",
"remove",
"{",
"errRemove",
":=",
"os",
".",
"Remove",
"(",
"filepath",
".",
"Join",
"(",
"l",
".",
"dir",
"(",
")",
",",
"f",
".",
"Name",
"(",
")",
")",
")",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"errRemove",
"!=",
"nil",
"{",
"err",
"=",
"errRemove",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"compress",
"{",
"fn",
":=",
"filepath",
".",
"Join",
"(",
"l",
".",
"dir",
"(",
")",
",",
"f",
".",
"Name",
"(",
")",
")",
"\n",
"errCompress",
":=",
"compressLogFile",
"(",
"fn",
",",
"fn",
"+",
"compressSuffix",
")",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"errCompress",
"!=",
"nil",
"{",
"err",
"=",
"errCompress",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"err",
"\n",
"}"
] | // 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",
".",
"MaxBackups",
"files",
"as",
"long",
"as",
"none",
"of",
"them",
"are",
"older",
"than",
"MaxAge",
"."
] | 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",
"}",
")",
"\n",
"select",
"{",
"case",
"l",
".",
"millCh",
"<-",
"true",
":",
"default",
":",
"}",
"\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.timeFromName(f.Name(), prefix, ext); err == nil {
logFiles = append(logFiles, logInfo{t, f})
continue
}
if t, err := l.timeFromName(f.Name(), prefix, ext+compressSuffix); err == nil {
logFiles = append(logFiles, logInfo{t, f})
continue
}
// error parsing means that the suffix at the end was not generated
// by lumberjack, and therefore it's not a backup file.
}
sort.Sort(byFormatTime(logFiles))
return logFiles, nil
} | 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.timeFromName(f.Name(), prefix, ext); err == nil {
logFiles = append(logFiles, logInfo{t, f})
continue
}
if t, err := l.timeFromName(f.Name(), prefix, ext+compressSuffix); err == nil {
logFiles = append(logFiles, logInfo{t, f})
continue
}
// error parsing means that the suffix at the end was not generated
// by lumberjack, and therefore it's not a backup file.
}
sort.Sort(byFormatTime(logFiles))
return logFiles, nil
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"oldLogFiles",
"(",
")",
"(",
"[",
"]",
"logInfo",
",",
"error",
")",
"{",
"files",
",",
"err",
":=",
"ioutil",
".",
"ReadDir",
"(",
"l",
".",
"dir",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"logFiles",
":=",
"[",
"]",
"logInfo",
"{",
"}",
"\n\n",
"prefix",
",",
"ext",
":=",
"l",
".",
"prefixAndExt",
"(",
")",
"\n\n",
"for",
"_",
",",
"f",
":=",
"range",
"files",
"{",
"if",
"f",
".",
"IsDir",
"(",
")",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"t",
",",
"err",
":=",
"l",
".",
"timeFromName",
"(",
"f",
".",
"Name",
"(",
")",
",",
"prefix",
",",
"ext",
")",
";",
"err",
"==",
"nil",
"{",
"logFiles",
"=",
"append",
"(",
"logFiles",
",",
"logInfo",
"{",
"t",
",",
"f",
"}",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"t",
",",
"err",
":=",
"l",
".",
"timeFromName",
"(",
"f",
".",
"Name",
"(",
")",
",",
"prefix",
",",
"ext",
"+",
"compressSuffix",
")",
";",
"err",
"==",
"nil",
"{",
"logFiles",
"=",
"append",
"(",
"logFiles",
",",
"logInfo",
"{",
"t",
",",
"f",
"}",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"// error parsing means that the suffix at the end was not generated",
"// by lumberjack, and therefore it's not a backup file.",
"}",
"\n\n",
"sort",
".",
"Sort",
"(",
"byFormatTime",
"(",
"logFiles",
")",
")",
"\n\n",
"return",
"logFiles",
",",
"nil",
"\n",
"}"
] | // 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(filename)-len(ext)]
return time.Parse(backupTimeFormat, ts)
} | 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(filename)-len(ext)]
return time.Parse(backupTimeFormat, ts)
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"timeFromName",
"(",
"filename",
",",
"prefix",
",",
"ext",
"string",
")",
"(",
"time",
".",
"Time",
",",
"error",
")",
"{",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"filename",
",",
"prefix",
")",
"{",
"return",
"time",
".",
"Time",
"{",
"}",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"!",
"strings",
".",
"HasSuffix",
"(",
"filename",
",",
"ext",
")",
"{",
"return",
"time",
".",
"Time",
"{",
"}",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"ts",
":=",
"filename",
"[",
"len",
"(",
"prefix",
")",
":",
"len",
"(",
"filename",
")",
"-",
"len",
"(",
"ext",
")",
"]",
"\n",
"return",
"time",
".",
"Parse",
"(",
"backupTimeFormat",
",",
"ts",
")",
"\n",
"}"
] | // 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",
")",
"*",
"int64",
"(",
"megabyte",
")",
"\n",
"}"
] | // 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",
"(",
"filename",
")",
"\n",
"prefix",
"=",
"filename",
"[",
":",
"len",
"(",
"filename",
")",
"-",
"len",
"(",
"ext",
")",
"]",
"+",
"\"",
"\"",
"\n",
"return",
"prefix",
",",
"ext",
"\n",
"}"
] | // 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 fmt.Errorf("failed to chown compressed log file: %v", err)
}
// If this file already exists, we presume it was created by
// a previous attempt to compress the log file.
gzf, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, fi.Mode())
if err != nil {
return fmt.Errorf("failed to open compressed log file: %v", err)
}
defer gzf.Close()
gz := gzip.NewWriter(gzf)
defer func() {
if err != nil {
os.Remove(dst)
err = fmt.Errorf("failed to compress log file: %v", err)
}
}()
if _, err := io.Copy(gz, f); err != nil {
return err
}
if err := gz.Close(); err != nil {
return err
}
if err := gzf.Close(); err != nil {
return err
}
if err := f.Close(); err != nil {
return err
}
if err := os.Remove(src); err != nil {
return err
}
return nil
} | 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 fmt.Errorf("failed to chown compressed log file: %v", err)
}
// If this file already exists, we presume it was created by
// a previous attempt to compress the log file.
gzf, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, fi.Mode())
if err != nil {
return fmt.Errorf("failed to open compressed log file: %v", err)
}
defer gzf.Close()
gz := gzip.NewWriter(gzf)
defer func() {
if err != nil {
os.Remove(dst)
err = fmt.Errorf("failed to compress log file: %v", err)
}
}()
if _, err := io.Copy(gz, f); err != nil {
return err
}
if err := gz.Close(); err != nil {
return err
}
if err := gzf.Close(); err != nil {
return err
}
if err := f.Close(); err != nil {
return err
}
if err := os.Remove(src); err != nil {
return err
}
return nil
} | [
"func",
"compressLogFile",
"(",
"src",
",",
"dst",
"string",
")",
"(",
"err",
"error",
")",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"src",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n\n",
"fi",
",",
"err",
":=",
"os_Stat",
"(",
"src",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"chown",
"(",
"dst",
",",
"fi",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// If this file already exists, we presume it was created by",
"// a previous attempt to compress the log file.",
"gzf",
",",
"err",
":=",
"os",
".",
"OpenFile",
"(",
"dst",
",",
"os",
".",
"O_CREATE",
"|",
"os",
".",
"O_TRUNC",
"|",
"os",
".",
"O_WRONLY",
",",
"fi",
".",
"Mode",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"gzf",
".",
"Close",
"(",
")",
"\n\n",
"gz",
":=",
"gzip",
".",
"NewWriter",
"(",
"gzf",
")",
"\n\n",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
"!=",
"nil",
"{",
"os",
".",
"Remove",
"(",
"dst",
")",
"\n",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"if",
"_",
",",
"err",
":=",
"io",
".",
"Copy",
"(",
"gz",
",",
"f",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"gz",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"gzf",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"f",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"os",
".",
"Remove",
"(",
"src",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // 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",
"(",
"hashedKey",
")",
"\n",
"return",
"shard",
".",
"get",
"(",
"key",
",",
"hashedKey",
")",
"\n",
"}"
] | // 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",
")",
"\n",
"return",
"shard",
".",
"set",
"(",
"key",
",",
"hashedKey",
",",
"entry",
")",
"\n",
"}"
] | // 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",
".",
"del",
"(",
"key",
",",
"hashedKey",
")",
"\n",
"}"
] | // 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",
"\n",
"}"
] | // 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",
"len",
"\n",
"}"
] | // 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",
"+=",
"tmp",
".",
"Hits",
"\n",
"s",
".",
"Misses",
"+=",
"tmp",
".",
"Misses",
"\n",
"s",
".",
"DelHits",
"+=",
"tmp",
".",
"DelHits",
"\n",
"s",
".",
"DelMisses",
"+=",
"tmp",
".",
"DelMisses",
"\n",
"s",
".",
"Collisions",
"+=",
"tmp",
".",
"Collisions",
"\n",
"}",
"\n",
"return",
"s",
"\n",
"}"
] | // 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,
Logger: DefaultLogger(),
}
} | 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,
Logger: DefaultLogger(),
}
} | [
"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",
",",
"Logger",
":",
"DefaultLogger",
"(",
")",
",",
"}",
"\n",
"}"
] | // 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",
".",
"Shards",
"\n",
"}",
"\n\n",
"return",
"maxShardSize",
"\n",
"}"
] | // 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",
"(",
"reasons",
"[",
"i",
"]",
")",
"\n",
"}",
"\n\n",
"return",
"c",
"\n",
"}"
] | // 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",
"http",
".",
"MethodGet",
":",
"getCacheStatsHandler",
"(",
"w",
",",
"r",
")",
"\n",
"default",
":",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusMethodNotAllowed",
")",
"\n",
"}",
"\n",
"}",
")",
"\n",
"}"
] | // 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 interface.
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Write(target)
return
} | 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 interface.
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Write(target)
return
} | [
"func",
"getCacheStatsHandler",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"target",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"cache",
".",
"Stats",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"// since we're sending a struct, make it easy for consumers to interface.",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Write",
"(",
"target",
")",
"\n",
"return",
"\n",
"}"
] | // 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",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"h",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"l",
".",
"Printf",
"(",
"\"",
"\"",
",",
"r",
".",
"Method",
",",
"r",
".",
"URL",
".",
"Path",
",",
"time",
".",
"Now",
"(",
")",
".",
"Sub",
"(",
"start",
")",
".",
"Nanoseconds",
"(",
")",
")",
"\n",
"}",
")",
"\n",
"}",
"\n",
"}"
] | // 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].copyKeys()
// Non empty shard - stick with it
if it.elementsCount > 0 {
it.currentIndex = 0
it.currentShard = i
it.valid = true
it.mutex.Unlock()
return true
}
}
it.mutex.Unlock()
return false
} | 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].copyKeys()
// Non empty shard - stick with it
if it.elementsCount > 0 {
it.currentIndex = 0
it.currentShard = i
it.valid = true
it.mutex.Unlock()
return true
}
}
it.mutex.Unlock()
return false
} | [
"func",
"(",
"it",
"*",
"EntryInfoIterator",
")",
"SetNext",
"(",
")",
"bool",
"{",
"it",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n\n",
"it",
".",
"valid",
"=",
"false",
"\n",
"it",
".",
"currentIndex",
"++",
"\n\n",
"if",
"it",
".",
"elementsCount",
">",
"it",
".",
"currentIndex",
"{",
"it",
".",
"valid",
"=",
"true",
"\n",
"it",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"return",
"true",
"\n",
"}",
"\n\n",
"for",
"i",
":=",
"it",
".",
"currentShard",
"+",
"1",
";",
"i",
"<",
"it",
".",
"cache",
".",
"config",
".",
"Shards",
";",
"i",
"++",
"{",
"it",
".",
"elements",
",",
"it",
".",
"elementsCount",
"=",
"it",
".",
"cache",
".",
"shards",
"[",
"i",
"]",
".",
"copyKeys",
"(",
")",
"\n\n",
"// Non empty shard - stick with it",
"if",
"it",
".",
"elementsCount",
">",
"0",
"{",
"it",
".",
"currentIndex",
"=",
"0",
"\n",
"it",
".",
"currentShard",
"=",
"i",
"\n",
"it",
".",
"valid",
"=",
"true",
"\n",
"it",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"it",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"return",
"false",
"\n",
"}"
] | // 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, ErrCannotRetrieveEntry
}
it.mutex.Unlock()
return EntryInfo{
timestamp: readTimestampFromEntry(entry),
hash: readHashFromEntry(entry),
key: readKeyFromEntry(entry),
value: readEntry(entry),
}, nil
} | 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, ErrCannotRetrieveEntry
}
it.mutex.Unlock()
return EntryInfo{
timestamp: readTimestampFromEntry(entry),
hash: readHashFromEntry(entry),
key: readKeyFromEntry(entry),
value: readEntry(entry),
}, nil
} | [
"func",
"(",
"it",
"*",
"EntryInfoIterator",
")",
"Value",
"(",
")",
"(",
"EntryInfo",
",",
"error",
")",
"{",
"it",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n\n",
"if",
"!",
"it",
".",
"valid",
"{",
"it",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"return",
"emptyEntryInfo",
",",
"ErrInvalidIteratorState",
"\n",
"}",
"\n\n",
"entry",
",",
"err",
":=",
"it",
".",
"cache",
".",
"shards",
"[",
"it",
".",
"currentShard",
"]",
".",
"getEntry",
"(",
"int",
"(",
"it",
".",
"elements",
"[",
"it",
".",
"currentIndex",
"]",
")",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"it",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"return",
"emptyEntryInfo",
",",
"ErrCannotRetrieveEntry",
"\n",
"}",
"\n",
"it",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"EntryInfo",
"{",
"timestamp",
":",
"readTimestampFromEntry",
"(",
"entry",
")",
",",
"hash",
":",
"readHashFromEntry",
"(",
"entry",
")",
",",
"key",
":",
"readKeyFromEntry",
"(",
"entry",
")",
",",
"value",
":",
"readEntry",
"(",
"entry",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] | // 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 := (err).Error()
if strings.Contains(errMsg, "not found") {
log.Print(err)
w.WriteHeader(http.StatusNotFound)
return
}
log.Print(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(entry)
} | 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 := (err).Error()
if strings.Contains(errMsg, "not found") {
log.Print(err)
w.WriteHeader(http.StatusNotFound)
return
}
log.Print(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(entry)
} | [
"func",
"getCacheHandler",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"target",
":=",
"r",
".",
"URL",
".",
"Path",
"[",
"len",
"(",
"cachePath",
")",
":",
"]",
"\n",
"if",
"target",
"==",
"\"",
"\"",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusBadRequest",
")",
"\n",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
"\n",
"log",
".",
"Print",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"entry",
",",
"err",
":=",
"cache",
".",
"Get",
"(",
"target",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"errMsg",
":=",
"(",
"err",
")",
".",
"Error",
"(",
")",
"\n",
"if",
"strings",
".",
"Contains",
"(",
"errMsg",
",",
"\"",
"\"",
")",
"{",
"log",
".",
"Print",
"(",
"err",
")",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusNotFound",
")",
"\n",
"return",
"\n",
"}",
"\n",
"log",
".",
"Print",
"(",
"err",
")",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"Write",
"(",
"entry",
")",
"\n",
"}"
] | // 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.StatusInternalServerError)
log.Printf("internal cache error: %s", err)
}
// this is what the RFC says to use when calling DELETE.
w.WriteHeader(http.StatusOK)
return
} | 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.StatusInternalServerError)
log.Printf("internal cache error: %s", err)
}
// this is what the RFC says to use when calling DELETE.
w.WriteHeader(http.StatusOK)
return
} | [
"func",
"deleteCacheHandler",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"target",
":=",
"r",
".",
"URL",
".",
"Path",
"[",
"len",
"(",
"cachePath",
")",
":",
"]",
"\n",
"if",
"err",
":=",
"cache",
".",
"Delete",
"(",
"target",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"strings",
".",
"Contains",
"(",
"(",
"err",
")",
".",
"Error",
"(",
")",
",",
"\"",
"\"",
")",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusNotFound",
")",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"target",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"// this is what the RFC says to use when calling DELETE.",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n",
"return",
"\n",
"}"
] | // 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",
"(",
"key",
"[",
"i",
"]",
")",
"\n",
"hash",
"*=",
"prime64",
"\n",
"}",
"\n\n",
"return",
"hash",
"\n",
"}"
] | // 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: leftMarginIndex,
rightMargin: leftMarginIndex,
verbose: verbose,
initialCapacity: initialCapacity,
}
} | 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: leftMarginIndex,
rightMargin: leftMarginIndex,
verbose: verbose,
initialCapacity: initialCapacity,
}
} | [
"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",
":",
"leftMarginIndex",
",",
"rightMargin",
":",
"leftMarginIndex",
",",
"verbose",
":",
"verbose",
",",
"initialCapacity",
":",
"initialCapacity",
",",
"}",
"\n",
"}"
] | // 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",
".",
"count",
"=",
"0",
"\n",
"}"
] | // 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 {
return -1, &queueError{"Full queue. Maximum size limit reached."}
} else {
q.allocateAdditionalMemory(dataLen + headerEntrySize)
}
}
index := q.tail
q.push(data, dataLen)
return index, nil
} | 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 {
return -1, &queueError{"Full queue. Maximum size limit reached."}
} else {
q.allocateAdditionalMemory(dataLen + headerEntrySize)
}
}
index := q.tail
q.push(data, dataLen)
return index, nil
} | [
"func",
"(",
"q",
"*",
"BytesQueue",
")",
"Push",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"dataLen",
":=",
"len",
"(",
"data",
")",
"\n\n",
"if",
"q",
".",
"availableSpaceAfterTail",
"(",
")",
"<",
"dataLen",
"+",
"headerEntrySize",
"{",
"if",
"q",
".",
"availableSpaceBeforeHead",
"(",
")",
">=",
"dataLen",
"+",
"headerEntrySize",
"{",
"q",
".",
"tail",
"=",
"leftMarginIndex",
"\n",
"}",
"else",
"if",
"q",
".",
"capacity",
"+",
"headerEntrySize",
"+",
"dataLen",
">=",
"q",
".",
"maxCapacity",
"&&",
"q",
".",
"maxCapacity",
">",
"0",
"{",
"return",
"-",
"1",
",",
"&",
"queueError",
"{",
"\"",
"\"",
"}",
"\n",
"}",
"else",
"{",
"q",
".",
"allocateAdditionalMemory",
"(",
"dataLen",
"+",
"headerEntrySize",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"index",
":=",
"q",
".",
"tail",
"\n\n",
"q",
".",
"push",
"(",
"data",
",",
"dataLen",
")",
"\n\n",
"return",
"index",
",",
"nil",
"\n",
"}"
] | // 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",
"is",
"reached",
"."
] | 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
}
return data, nil
} | 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
}
return data, nil
} | [
"func",
"(",
"q",
"*",
"BytesQueue",
")",
"Pop",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"data",
",",
"size",
",",
"err",
":=",
"q",
".",
"peek",
"(",
"q",
".",
"head",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"q",
".",
"head",
"+=",
"headerEntrySize",
"+",
"size",
"\n",
"q",
".",
"count",
"--",
"\n\n",
"if",
"q",
".",
"head",
"==",
"q",
".",
"rightMargin",
"{",
"q",
".",
"head",
"=",
"leftMarginIndex",
"\n",
"if",
"q",
".",
"tail",
"==",
"q",
".",
"rightMargin",
"{",
"q",
".",
"tail",
"=",
"leftMarginIndex",
"\n",
"}",
"\n",
"q",
".",
"rightMargin",
"=",
"q",
".",
"tail",
"\n",
"}",
"\n\n",
"return",
"data",
",",
"nil",
"\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",
"}",
"\n\n",
"if",
"index",
"+",
"headerEntrySize",
">=",
"len",
"(",
"q",
".",
"array",
")",
"{",
"return",
"errIndexOutOfBounds",
"\n",
"}",
"\n",
"return",
"nil",
"\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",
"==",
"nil",
"{",
"if",
"err",
":=",
"rw",
".",
"Rotate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"rw",
",",
"nil",
"\n",
"}"
] | // 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 {
return err
}
// switch dest file safely.
l.mu.Lock()
file, l.file = l.file, file
l.mu.Unlock()
// close old file if open.
if file != nil {
if err := file.Close(); err != nil {
return err
}
}
return 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 {
return err
}
// switch dest file safely.
l.mu.Lock()
file, l.file = l.file, file
l.mu.Unlock()
// close old file if open.
if file != nil {
if err := file.Close(); err != nil {
return err
}
}
return nil
} | [
"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",
")",
"\n",
"if",
"err",
"=",
"os",
".",
"Rename",
"(",
"l",
".",
"name",
",",
"name",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"// create new file.",
"file",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"l",
".",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"// switch dest file safely.",
"l",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"file",
",",
"l",
".",
"file",
"=",
"l",
".",
"file",
",",
"file",
"\n",
"l",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"// close old file if open.",
"if",
"file",
"!=",
"nil",
"{",
"if",
"err",
":=",
"file",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // 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",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"err",
"=",
"lock",
".",
"Lock",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"lock",
".",
"Remove",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"err",
"=",
"lock",
".",
"WritePid",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"lock",
".",
"Remove",
"(",
")",
"\n",
"}",
"\n",
"return",
"\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",
"(",
"name",
",",
"os",
".",
"O_RDWR",
"|",
"os",
".",
"O_CREATE",
",",
"perm",
")",
";",
"err",
"==",
"nil",
"{",
"lock",
"=",
"&",
"LockFile",
"{",
"file",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // 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",
",",
"0640",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"defer",
"file",
".",
"Close",
"(",
")",
"\n\n",
"lock",
":=",
"&",
"LockFile",
"{",
"file",
"}",
"\n",
"pid",
",",
"err",
"=",
"lock",
".",
"ReadPid",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // 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",
"var",
"fileLen",
"int",
"\n",
"if",
"fileLen",
",",
"err",
"=",
"fmt",
".",
"Fprint",
"(",
"file",
",",
"os",
".",
"Getpid",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"err",
"=",
"file",
".",
"Truncate",
"(",
"int64",
"(",
"fileLen",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"err",
"=",
"file",
".",
"Sync",
"(",
")",
"\n",
"return",
"\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",
"{",
"return",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"fmt",
".",
"Fscan",
"(",
"file",
",",
"&",
"pid",
")",
"\n",
"return",
"\n",
"}"
] | // 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",
"return",
"os",
".",
"Remove",
"(",
"file",
".",
"Name",
"(",
")",
")",
"\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",
"{",
"SetSigHandler",
"(",
"handler",
",",
"sig",
")",
"\n",
"}",
"\n",
"}"
] | // 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.