repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
inverse-inc/packetfence
go/firewallsso/junipersrx.go
Start
func (fw *JuniperSRX) Start(ctx context.Context, info map[string]string, timeout int) (bool, error) { log.LoggerWContext(ctx).Info("Sending SSO to JuniperSRX using HTTP") return fw.startHttp(ctx, info, timeout) }
go
func (fw *JuniperSRX) Start(ctx context.Context, info map[string]string, timeout int) (bool, error) { log.LoggerWContext(ctx).Info("Sending SSO to JuniperSRX using HTTP") return fw.startHttp(ctx, info, timeout) }
[ "func", "(", "fw", "*", "JuniperSRX", ")", "Start", "(", "ctx", "context", ".", "Context", ",", "info", "map", "[", "string", "]", "string", ",", "timeout", "int", ")", "(", "bool", ",", "error", ")", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Info", "(", "\"Sending SSO to JuniperSRX using HTTP\"", ")", "\n", "return", "fw", ".", "startHttp", "(", "ctx", ",", "info", ",", "timeout", ")", "\n", "}" ]
// Send an SSO start to the JuniperSRX using HTTP // This will return any value from startSyslog or startHttp depending on the type of the transport
[ "Send", "an", "SSO", "start", "to", "the", "JuniperSRX", "using", "HTTP", "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/junipersrx.go#L23-L27
train
inverse-inc/packetfence
go/firewallsso/junipersrx.go
startHttp
func (fw *JuniperSRX) startHttp(ctx context.Context, info map[string]string, timeout int) (bool, error) { req, err := http.NewRequest("POST", "https://"+fw.PfconfigHashNS+":"+fw.Port+"/api/userfw/v1/post-entry", bytes.NewBuffer([]byte(fw.startHttpPayload(ctx, info)))) req.SetBasicAuth(fw.Username, fw.Password) client := fw.getHttpClient(ctx) resp, err := client.Do(req) if err != nil { log.LoggerWContext(ctx).Error(fmt.Sprintf("Error contacting JuniperSRX: %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 *JuniperSRX) startHttp(ctx context.Context, info map[string]string, timeout int) (bool, error) { req, err := http.NewRequest("POST", "https://"+fw.PfconfigHashNS+":"+fw.Port+"/api/userfw/v1/post-entry", bytes.NewBuffer([]byte(fw.startHttpPayload(ctx, info)))) req.SetBasicAuth(fw.Username, fw.Password) client := fw.getHttpClient(ctx) resp, err := client.Do(req) if err != nil { log.LoggerWContext(ctx).Error(fmt.Sprintf("Error contacting JuniperSRX: %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", "*", "JuniperSRX", ")", "startHttp", "(", "ctx", "context", ".", "Context", ",", "info", "map", "[", "string", "]", "string", ",", "timeout", "int", ")", "(", "bool", ",", "error", ")", "{", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"POST\"", ",", "\"https://\"", "+", "fw", ".", "PfconfigHashNS", "+", "\":\"", "+", "fw", ".", "Port", "+", "\"/api/userfw/v1/post-entry\"", ",", "bytes", ".", "NewBuffer", "(", "[", "]", "byte", "(", "fw", ".", "startHttpPayload", "(", "ctx", ",", "info", ")", ")", ")", ")", "\n", "req", ".", "SetBasicAuth", "(", "fw", ".", "Username", ",", "fw", ".", "Password", ")", "\n", "client", ":=", "fw", ".", "getHttpClient", "(", "ctx", ")", "\n", "resp", ",", "err", ":=", "client", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Error", "(", "fmt", ".", "Sprintf", "(", "\"Error contacting JuniperSRX: %s\"", ",", "err", ")", ")", "\n", "}", "\n", "if", "resp", "!=", "nil", "&&", "resp", ".", "Body", "!=", "nil", "{", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "}", "\n", "return", "err", "==", "nil", ",", "err", "\n", "}" ]
// Send a start to the JuniperSRX using the HTTP transport // Will return an error if it fails to get a valid reply from it
[ "Send", "a", "start", "to", "the", "JuniperSRX", "using", "the", "HTTP", "transport", "Will", "return", "an", "error", "if", "it", "fails", "to", "get", "a", "valid", "reply", "from", "it" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/junipersrx.go#L31-L48
train
inverse-inc/packetfence
go/firewallsso/junipersrx.go
Stop
func (fw *JuniperSRX) Stop(ctx context.Context, info map[string]string) (bool, error) { log.LoggerWContext(ctx).Info("Sending SSO to JuniperSRX using HTTP") return fw.stopHttp(ctx, info) }
go
func (fw *JuniperSRX) Stop(ctx context.Context, info map[string]string) (bool, error) { log.LoggerWContext(ctx).Info("Sending SSO to JuniperSRX using HTTP") return fw.stopHttp(ctx, info) }
[ "func", "(", "fw", "*", "JuniperSRX", ")", "Stop", "(", "ctx", "context", ".", "Context", ",", "info", "map", "[", "string", "]", "string", ")", "(", "bool", ",", "error", ")", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Info", "(", "\"Sending SSO to JuniperSRX using HTTP\"", ")", "\n", "return", "fw", ".", "stopHttp", "(", "ctx", ",", "info", ")", "\n", "}" ]
// Send an SSO stop to the firewall by using HTTP transport.
[ "Send", "an", "SSO", "stop", "to", "the", "firewall", "by", "using", "HTTP", "transport", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/junipersrx.go#L103-L107
train
inverse-inc/packetfence
go/firewallsso/barracudang.go
getSshSession
func (fw *BarracudaNG) getSshSession(ctx context.Context) (*ssh.Session, error) { sshConfig := &ssh.ClientConfig{ User: fw.Username, Auth: []ssh.AuthMethod{ ssh.Password(fw.Password), }, } connection, err := ssh.Dial("tcp", fw.PfconfigHashNS+":"+fw.Port, sshConfig) if err != nil { return nil, err } session, err := connection.NewSession() return session, err }
go
func (fw *BarracudaNG) getSshSession(ctx context.Context) (*ssh.Session, error) { sshConfig := &ssh.ClientConfig{ User: fw.Username, Auth: []ssh.AuthMethod{ ssh.Password(fw.Password), }, } connection, err := ssh.Dial("tcp", fw.PfconfigHashNS+":"+fw.Port, sshConfig) if err != nil { return nil, err } session, err := connection.NewSession() return session, err }
[ "func", "(", "fw", "*", "BarracudaNG", ")", "getSshSession", "(", "ctx", "context", ".", "Context", ")", "(", "*", "ssh", ".", "Session", ",", "error", ")", "{", "sshConfig", ":=", "&", "ssh", ".", "ClientConfig", "{", "User", ":", "fw", ".", "Username", ",", "Auth", ":", "[", "]", "ssh", ".", "AuthMethod", "{", "ssh", ".", "Password", "(", "fw", ".", "Password", ")", ",", "}", ",", "}", "\n", "connection", ",", "err", ":=", "ssh", ".", "Dial", "(", "\"tcp\"", ",", "fw", ".", "PfconfigHashNS", "+", "\":\"", "+", "fw", ".", "Port", ",", "sshConfig", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "session", ",", "err", ":=", "connection", ".", "NewSession", "(", ")", "\n", "return", "session", ",", "err", "\n", "}" ]
// Get an SSH session to the firewall
[ "Get", "an", "SSH", "session", "to", "the", "firewall" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/barracudang.go#L18-L34
train
inverse-inc/packetfence
go/firewallsso/barracudang.go
Start
func (fw *BarracudaNG) Start(ctx context.Context, info map[string]string, timeout int) (bool, error) { session, err := fw.getSshSession(ctx) if err != nil { log.LoggerWContext(ctx).Error(fmt.Sprintf("Cannot connect to BarracudaNG: %s", err)) return false, err } cmd := "phibstest 127.0.0.1 l peer=" + info["ip"] + " origin=PacketFence service=PacketFence user=" + info["username"] session.Run(cmd) return true, nil }
go
func (fw *BarracudaNG) Start(ctx context.Context, info map[string]string, timeout int) (bool, error) { session, err := fw.getSshSession(ctx) if err != nil { log.LoggerWContext(ctx).Error(fmt.Sprintf("Cannot connect to BarracudaNG: %s", err)) return false, err } cmd := "phibstest 127.0.0.1 l peer=" + info["ip"] + " origin=PacketFence service=PacketFence user=" + info["username"] session.Run(cmd) return true, nil }
[ "func", "(", "fw", "*", "BarracudaNG", ")", "Start", "(", "ctx", "context", ".", "Context", ",", "info", "map", "[", "string", "]", "string", ",", "timeout", "int", ")", "(", "bool", ",", "error", ")", "{", "session", ",", "err", ":=", "fw", ".", "getSshSession", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Error", "(", "fmt", ".", "Sprintf", "(", "\"Cannot connect to BarracudaNG: %s\"", ",", "err", ")", ")", "\n", "return", "false", ",", "err", "\n", "}", "\n", "cmd", ":=", "\"phibstest 127.0.0.1 l peer=\"", "+", "info", "[", "\"ip\"", "]", "+", "\" origin=PacketFence service=PacketFence user=\"", "+", "info", "[", "\"username\"", "]", "\n", "session", ".", "Run", "(", "cmd", ")", "\n", "return", "true", ",", "nil", "\n", "}" ]
// Send an SSO start to the BarracudaNG Firewall // Will return an error if it can't connect
[ "Send", "an", "SSO", "start", "to", "the", "BarracudaNG", "Firewall", "Will", "return", "an", "error", "if", "it", "can", "t", "connect" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/barracudang.go#L38-L50
train
inverse-inc/packetfence
go/stats/main.go
detectVIP
func detectVIP(management pfconfigdriver.ManagementNetwork) { if pfconfigdriver.GetClusterSummary(ctx).ClusterEnabled == 1 { var keyConfCluster pfconfigdriver.NetInterface keyConfCluster.PfconfigNS = "config::Pf(CLUSTER," + pfconfigdriver.FindClusterName(ctx) + ")" keyConfCluster.PfconfigHashNS = "interface " + management.Int pfconfigdriver.FetchDecodeSocket(ctx, &keyConfCluster) // Nothing in keyConfCluster.Ip so we are not in cluster mode if keyConfCluster.Ip == "" { VIP[management.Int] = true return } eth, _ := net.InterfaceByName(management.Int) adresses, _ := eth.Addrs() for _, adresse := range adresses { IP, _, _ := net.ParseCIDR(adresse.String()) VIPIp[management.Int] = net.ParseIP(keyConfCluster.Ip) if IP.Equal(VIPIp[management.Int]) { VIP[management.Int] = true return } } VIP[management.Int] = false return } else { VIP[management.Int] = true } }
go
func detectVIP(management pfconfigdriver.ManagementNetwork) { if pfconfigdriver.GetClusterSummary(ctx).ClusterEnabled == 1 { var keyConfCluster pfconfigdriver.NetInterface keyConfCluster.PfconfigNS = "config::Pf(CLUSTER," + pfconfigdriver.FindClusterName(ctx) + ")" keyConfCluster.PfconfigHashNS = "interface " + management.Int pfconfigdriver.FetchDecodeSocket(ctx, &keyConfCluster) // Nothing in keyConfCluster.Ip so we are not in cluster mode if keyConfCluster.Ip == "" { VIP[management.Int] = true return } eth, _ := net.InterfaceByName(management.Int) adresses, _ := eth.Addrs() for _, adresse := range adresses { IP, _, _ := net.ParseCIDR(adresse.String()) VIPIp[management.Int] = net.ParseIP(keyConfCluster.Ip) if IP.Equal(VIPIp[management.Int]) { VIP[management.Int] = true return } } VIP[management.Int] = false return } else { VIP[management.Int] = true } }
[ "func", "detectVIP", "(", "management", "pfconfigdriver", ".", "ManagementNetwork", ")", "{", "if", "pfconfigdriver", ".", "GetClusterSummary", "(", "ctx", ")", ".", "ClusterEnabled", "==", "1", "{", "var", "keyConfCluster", "pfconfigdriver", ".", "NetInterface", "\n", "keyConfCluster", ".", "PfconfigNS", "=", "\"config::Pf(CLUSTER,\"", "+", "pfconfigdriver", ".", "FindClusterName", "(", "ctx", ")", "+", "\")\"", "\n", "keyConfCluster", ".", "PfconfigHashNS", "=", "\"interface \"", "+", "management", ".", "Int", "\n", "pfconfigdriver", ".", "FetchDecodeSocket", "(", "ctx", ",", "&", "keyConfCluster", ")", "\n", "if", "keyConfCluster", ".", "Ip", "==", "\"\"", "{", "VIP", "[", "management", ".", "Int", "]", "=", "true", "\n", "return", "\n", "}", "\n", "eth", ",", "_", ":=", "net", ".", "InterfaceByName", "(", "management", ".", "Int", ")", "\n", "adresses", ",", "_", ":=", "eth", ".", "Addrs", "(", ")", "\n", "for", "_", ",", "adresse", ":=", "range", "adresses", "{", "IP", ",", "_", ",", "_", ":=", "net", ".", "ParseCIDR", "(", "adresse", ".", "String", "(", ")", ")", "\n", "VIPIp", "[", "management", ".", "Int", "]", "=", "net", ".", "ParseIP", "(", "keyConfCluster", ".", "Ip", ")", "\n", "if", "IP", ".", "Equal", "(", "VIPIp", "[", "management", ".", "Int", "]", ")", "{", "VIP", "[", "management", ".", "Int", "]", "=", "true", "\n", "return", "\n", "}", "\n", "}", "\n", "VIP", "[", "management", ".", "Int", "]", "=", "false", "\n", "return", "\n", "}", "else", "{", "VIP", "[", "management", ".", "Int", "]", "=", "true", "\n", "}", "\n", "}" ]
// Detect the vip on management
[ "Detect", "the", "vip", "on", "management" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/stats/main.go#L1791-L1820
train
inverse-inc/packetfence
go/coredns/plugin/proxy/upstream.go
NewStaticUpstreams
func NewStaticUpstreams(c *caddyfile.Dispenser) ([]Upstream, error) { var upstreams []Upstream for c.Next() { upstream := &staticUpstream{ from: ".", HealthCheck: healthcheck.HealthCheck{ FailTimeout: 5 * time.Second, MaxFails: 3, }, ex: newDNSEx(), } if !c.Args(&upstream.netsource) { return upstreams, c.ArgErr() } _, _, err := net.ParseCIDR(upstream.netsource) if err != nil { upstream.from = upstream.netsource upstream.netsource = "" } upstream.from = plugin.Host(upstream.from).Normalize() to := c.RemainingArgs() if len(to) == 0 { return upstreams, c.ArgErr() } // process the host list, substituting in any nameservers in files toHosts, err := dnsutil.ParseHostPortOrFile(to...) if err != nil { return upstreams, err } for c.NextBlock() { if err := parseBlock(c, upstream); err != nil { return upstreams, err } } upstream.Hosts = make([]*healthcheck.UpstreamHost, len(toHosts)) for i, host := range toHosts { uh := &healthcheck.UpstreamHost{ Name: host, FailTimeout: upstream.FailTimeout, CheckDown: checkDownFunc(upstream), } upstream.Hosts[i] = uh } upstream.Start() upstreams = append(upstreams, upstream) } return upstreams, nil }
go
func NewStaticUpstreams(c *caddyfile.Dispenser) ([]Upstream, error) { var upstreams []Upstream for c.Next() { upstream := &staticUpstream{ from: ".", HealthCheck: healthcheck.HealthCheck{ FailTimeout: 5 * time.Second, MaxFails: 3, }, ex: newDNSEx(), } if !c.Args(&upstream.netsource) { return upstreams, c.ArgErr() } _, _, err := net.ParseCIDR(upstream.netsource) if err != nil { upstream.from = upstream.netsource upstream.netsource = "" } upstream.from = plugin.Host(upstream.from).Normalize() to := c.RemainingArgs() if len(to) == 0 { return upstreams, c.ArgErr() } // process the host list, substituting in any nameservers in files toHosts, err := dnsutil.ParseHostPortOrFile(to...) if err != nil { return upstreams, err } for c.NextBlock() { if err := parseBlock(c, upstream); err != nil { return upstreams, err } } upstream.Hosts = make([]*healthcheck.UpstreamHost, len(toHosts)) for i, host := range toHosts { uh := &healthcheck.UpstreamHost{ Name: host, FailTimeout: upstream.FailTimeout, CheckDown: checkDownFunc(upstream), } upstream.Hosts[i] = uh } upstream.Start() upstreams = append(upstreams, upstream) } return upstreams, nil }
[ "func", "NewStaticUpstreams", "(", "c", "*", "caddyfile", ".", "Dispenser", ")", "(", "[", "]", "Upstream", ",", "error", ")", "{", "var", "upstreams", "[", "]", "Upstream", "\n", "for", "c", ".", "Next", "(", ")", "{", "upstream", ":=", "&", "staticUpstream", "{", "from", ":", "\".\"", ",", "HealthCheck", ":", "healthcheck", ".", "HealthCheck", "{", "FailTimeout", ":", "5", "*", "time", ".", "Second", ",", "MaxFails", ":", "3", ",", "}", ",", "ex", ":", "newDNSEx", "(", ")", ",", "}", "\n", "if", "!", "c", ".", "Args", "(", "&", "upstream", ".", "netsource", ")", "{", "return", "upstreams", ",", "c", ".", "ArgErr", "(", ")", "\n", "}", "\n", "_", ",", "_", ",", "err", ":=", "net", ".", "ParseCIDR", "(", "upstream", ".", "netsource", ")", "\n", "if", "err", "!=", "nil", "{", "upstream", ".", "from", "=", "upstream", ".", "netsource", "\n", "upstream", ".", "netsource", "=", "\"\"", "\n", "}", "\n", "upstream", ".", "from", "=", "plugin", ".", "Host", "(", "upstream", ".", "from", ")", ".", "Normalize", "(", ")", "\n", "to", ":=", "c", ".", "RemainingArgs", "(", ")", "\n", "if", "len", "(", "to", ")", "==", "0", "{", "return", "upstreams", ",", "c", ".", "ArgErr", "(", ")", "\n", "}", "\n", "toHosts", ",", "err", ":=", "dnsutil", ".", "ParseHostPortOrFile", "(", "to", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "upstreams", ",", "err", "\n", "}", "\n", "for", "c", ".", "NextBlock", "(", ")", "{", "if", "err", ":=", "parseBlock", "(", "c", ",", "upstream", ")", ";", "err", "!=", "nil", "{", "return", "upstreams", ",", "err", "\n", "}", "\n", "}", "\n", "upstream", ".", "Hosts", "=", "make", "(", "[", "]", "*", "healthcheck", ".", "UpstreamHost", ",", "len", "(", "toHosts", ")", ")", "\n", "for", "i", ",", "host", ":=", "range", "toHosts", "{", "uh", ":=", "&", "healthcheck", ".", "UpstreamHost", "{", "Name", ":", "host", ",", "FailTimeout", ":", "upstream", ".", "FailTimeout", ",", "CheckDown", ":", "checkDownFunc", "(", "upstream", ")", ",", "}", "\n", "upstream", ".", "Hosts", "[", "i", "]", "=", "uh", "\n", "}", "\n", "upstream", ".", "Start", "(", ")", "\n", "upstreams", "=", "append", "(", "upstreams", ",", "upstream", ")", "\n", "}", "\n", "return", "upstreams", ",", "nil", "\n", "}" ]
// NewStaticUpstreams parses the configuration input and sets up // static upstreams for the proxy plugin.
[ "NewStaticUpstreams", "parses", "the", "configuration", "input", "and", "sets", "up", "static", "upstreams", "for", "the", "proxy", "plugin", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/proxy/upstream.go#L29-L86
train
inverse-inc/packetfence
go/coredns/plugin/proxy/fuzz.go
Fuzz
func Fuzz(data []byte) int { c := caddy.NewTestController("dns", "proxy . 8.8.8.8:53") up, err := NewStaticUpstreams(&c.Dispenser) if err != nil { return 0 } p := &Proxy{Upstreams: &up} return fuzz.Do(p, data) }
go
func Fuzz(data []byte) int { c := caddy.NewTestController("dns", "proxy . 8.8.8.8:53") up, err := NewStaticUpstreams(&c.Dispenser) if err != nil { return 0 } p := &Proxy{Upstreams: &up} return fuzz.Do(p, data) }
[ "func", "Fuzz", "(", "data", "[", "]", "byte", ")", "int", "{", "c", ":=", "caddy", ".", "NewTestController", "(", "\"dns\"", ",", "\"proxy . 8.8.8.8:53\"", ")", "\n", "up", ",", "err", ":=", "NewStaticUpstreams", "(", "&", "c", ".", "Dispenser", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", "\n", "}", "\n", "p", ":=", "&", "Proxy", "{", "Upstreams", ":", "&", "up", "}", "\n", "return", "fuzz", ".", "Do", "(", "p", ",", "data", ")", "\n", "}" ]
// Fuzz fuzzes proxy.
[ "Fuzz", "fuzzes", "proxy", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/proxy/fuzz.go#L10-L19
train
inverse-inc/packetfence
go/unifiedapiclient/client.go
ensureRequestComplete
func (c *Client) ensureRequestComplete(ctx context.Context, resp *http.Response) { if resp == nil { return } defer resp.Body.Close() io.Copy(ioutil.Discard, resp.Body) }
go
func (c *Client) ensureRequestComplete(ctx context.Context, resp *http.Response) { if resp == nil { return } defer resp.Body.Close() io.Copy(ioutil.Discard, resp.Body) }
[ "func", "(", "c", "*", "Client", ")", "ensureRequestComplete", "(", "ctx", "context", ".", "Context", ",", "resp", "*", "http", ".", "Response", ")", "{", "if", "resp", "==", "nil", "{", "return", "\n", "}", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "io", ".", "Copy", "(", "ioutil", ".", "Discard", ",", "resp", ".", "Body", ")", "\n", "}" ]
// Ensures that the full body is read and closes the reader so that the connection can be reused
[ "Ensures", "that", "the", "full", "body", "is", "read", "and", "closes", "the", "reader", "so", "that", "the", "connection", "can", "be", "reused" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/unifiedapiclient/client.go#L128-L135
train
inverse-inc/packetfence
go/coredns/plugin/proxy/google_rr.go
toMsg
func toMsg(g *googleMsg) (*dns.Msg, error) { m := new(dns.Msg) m.Response = true m.Rcode = g.Status m.Truncated = g.TC m.RecursionDesired = g.RD m.RecursionAvailable = g.RA m.AuthenticatedData = g.AD m.CheckingDisabled = g.CD m.Question = make([]dns.Question, 1) m.Answer = make([]dns.RR, len(g.Answer)) m.Ns = make([]dns.RR, len(g.Authority)) m.Extra = make([]dns.RR, len(g.Additional)) m.Question[0] = dns.Question{Name: g.Question[0].Name, Qtype: g.Question[0].Type, Qclass: dns.ClassINET} var err error for i := 0; i < len(m.Answer); i++ { m.Answer[i], err = toRR(g.Answer[i]) if err != nil { return nil, err } } for i := 0; i < len(m.Ns); i++ { m.Ns[i], err = toRR(g.Authority[i]) if err != nil { return nil, err } } for i := 0; i < len(m.Extra); i++ { m.Extra[i], err = toRR(g.Additional[i]) if err != nil { return nil, err } } return m, nil }
go
func toMsg(g *googleMsg) (*dns.Msg, error) { m := new(dns.Msg) m.Response = true m.Rcode = g.Status m.Truncated = g.TC m.RecursionDesired = g.RD m.RecursionAvailable = g.RA m.AuthenticatedData = g.AD m.CheckingDisabled = g.CD m.Question = make([]dns.Question, 1) m.Answer = make([]dns.RR, len(g.Answer)) m.Ns = make([]dns.RR, len(g.Authority)) m.Extra = make([]dns.RR, len(g.Additional)) m.Question[0] = dns.Question{Name: g.Question[0].Name, Qtype: g.Question[0].Type, Qclass: dns.ClassINET} var err error for i := 0; i < len(m.Answer); i++ { m.Answer[i], err = toRR(g.Answer[i]) if err != nil { return nil, err } } for i := 0; i < len(m.Ns); i++ { m.Ns[i], err = toRR(g.Authority[i]) if err != nil { return nil, err } } for i := 0; i < len(m.Extra); i++ { m.Extra[i], err = toRR(g.Additional[i]) if err != nil { return nil, err } } return m, nil }
[ "func", "toMsg", "(", "g", "*", "googleMsg", ")", "(", "*", "dns", ".", "Msg", ",", "error", ")", "{", "m", ":=", "new", "(", "dns", ".", "Msg", ")", "\n", "m", ".", "Response", "=", "true", "\n", "m", ".", "Rcode", "=", "g", ".", "Status", "\n", "m", ".", "Truncated", "=", "g", ".", "TC", "\n", "m", ".", "RecursionDesired", "=", "g", ".", "RD", "\n", "m", ".", "RecursionAvailable", "=", "g", ".", "RA", "\n", "m", ".", "AuthenticatedData", "=", "g", ".", "AD", "\n", "m", ".", "CheckingDisabled", "=", "g", ".", "CD", "\n", "m", ".", "Question", "=", "make", "(", "[", "]", "dns", ".", "Question", ",", "1", ")", "\n", "m", ".", "Answer", "=", "make", "(", "[", "]", "dns", ".", "RR", ",", "len", "(", "g", ".", "Answer", ")", ")", "\n", "m", ".", "Ns", "=", "make", "(", "[", "]", "dns", ".", "RR", ",", "len", "(", "g", ".", "Authority", ")", ")", "\n", "m", ".", "Extra", "=", "make", "(", "[", "]", "dns", ".", "RR", ",", "len", "(", "g", ".", "Additional", ")", ")", "\n", "m", ".", "Question", "[", "0", "]", "=", "dns", ".", "Question", "{", "Name", ":", "g", ".", "Question", "[", "0", "]", ".", "Name", ",", "Qtype", ":", "g", ".", "Question", "[", "0", "]", ".", "Type", ",", "Qclass", ":", "dns", ".", "ClassINET", "}", "\n", "var", "err", "error", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "m", ".", "Answer", ")", ";", "i", "++", "{", "m", ".", "Answer", "[", "i", "]", ",", "err", "=", "toRR", "(", "g", ".", "Answer", "[", "i", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "m", ".", "Ns", ")", ";", "i", "++", "{", "m", ".", "Ns", "[", "i", "]", ",", "err", "=", "toRR", "(", "g", ".", "Authority", "[", "i", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "m", ".", "Extra", ")", ";", "i", "++", "{", "m", ".", "Extra", "[", "i", "]", ",", "err", "=", "toRR", "(", "g", ".", "Additional", "[", "i", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "return", "m", ",", "nil", "\n", "}" ]
// toMsg converts a googleMsg into the dns message.
[ "toMsg", "converts", "a", "googleMsg", "into", "the", "dns", "message", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/proxy/google_rr.go#L10-L48
train
inverse-inc/packetfence
go/coredns/plugin/proxy/google_rr.go
toRR
func toRR(g googleRR) (dns.RR, error) { typ, ok := dns.TypeToString[g.Type] if !ok { return nil, fmt.Errorf("failed to convert type %q", g.Type) } str := fmt.Sprintf("%s %d %s %s", g.Name, g.TTL, typ, g.Data) rr, err := dns.NewRR(str) if err != nil { return nil, fmt.Errorf("failed to parse %q: %s", str, err) } return rr, nil }
go
func toRR(g googleRR) (dns.RR, error) { typ, ok := dns.TypeToString[g.Type] if !ok { return nil, fmt.Errorf("failed to convert type %q", g.Type) } str := fmt.Sprintf("%s %d %s %s", g.Name, g.TTL, typ, g.Data) rr, err := dns.NewRR(str) if err != nil { return nil, fmt.Errorf("failed to parse %q: %s", str, err) } return rr, nil }
[ "func", "toRR", "(", "g", "googleRR", ")", "(", "dns", ".", "RR", ",", "error", ")", "{", "typ", ",", "ok", ":=", "dns", ".", "TypeToString", "[", "g", ".", "Type", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"failed to convert type %q\"", ",", "g", ".", "Type", ")", "\n", "}", "\n", "str", ":=", "fmt", ".", "Sprintf", "(", "\"%s %d %s %s\"", ",", "g", ".", "Name", ",", "g", ".", "TTL", ",", "typ", ",", "g", ".", "Data", ")", "\n", "rr", ",", "err", ":=", "dns", ".", "NewRR", "(", "str", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"failed to parse %q: %s\"", ",", "str", ",", "err", ")", "\n", "}", "\n", "return", "rr", ",", "nil", "\n", "}" ]
// toRR transforms a "google" RR to a dns.RR.
[ "toRR", "transforms", "a", "google", "RR", "to", "a", "dns", ".", "RR", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/proxy/google_rr.go#L51-L63
train
inverse-inc/packetfence
go/coredns/plugin/dnstap/taprw/writer.go
WriteMsg
func (w *ResponseWriter) WriteMsg(resp *dns.Msg) (writeErr error) { writeErr = w.ResponseWriter.WriteMsg(resp) writeEpoch := uint64(time.Now().Unix()) b := w.TapBuilder() b.TimeSec = w.queryEpoch if w.Send == nil || w.Send.Cq { if err := func() (err error) { err = b.AddrMsg(w.ResponseWriter.RemoteAddr(), w.Query) if err != nil { return } return w.TapMessage(b.ToClientQuery()) }(); err != nil { w.err = fmt.Errorf("client query: %s", err) // don't forget to call DnstapError later } } if w.Send == nil || w.Send.Cr { if writeErr == nil { if err := func() (err error) { b.TimeSec = writeEpoch if err = b.Msg(resp); err != nil { return } return w.TapMessage(b.ToClientResponse()) }(); err != nil { w.err = fmt.Errorf("client response: %s", err) } } } return }
go
func (w *ResponseWriter) WriteMsg(resp *dns.Msg) (writeErr error) { writeErr = w.ResponseWriter.WriteMsg(resp) writeEpoch := uint64(time.Now().Unix()) b := w.TapBuilder() b.TimeSec = w.queryEpoch if w.Send == nil || w.Send.Cq { if err := func() (err error) { err = b.AddrMsg(w.ResponseWriter.RemoteAddr(), w.Query) if err != nil { return } return w.TapMessage(b.ToClientQuery()) }(); err != nil { w.err = fmt.Errorf("client query: %s", err) // don't forget to call DnstapError later } } if w.Send == nil || w.Send.Cr { if writeErr == nil { if err := func() (err error) { b.TimeSec = writeEpoch if err = b.Msg(resp); err != nil { return } return w.TapMessage(b.ToClientResponse()) }(); err != nil { w.err = fmt.Errorf("client response: %s", err) } } } return }
[ "func", "(", "w", "*", "ResponseWriter", ")", "WriteMsg", "(", "resp", "*", "dns", ".", "Msg", ")", "(", "writeErr", "error", ")", "{", "writeErr", "=", "w", ".", "ResponseWriter", ".", "WriteMsg", "(", "resp", ")", "\n", "writeEpoch", ":=", "uint64", "(", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", ")", "\n", "b", ":=", "w", ".", "TapBuilder", "(", ")", "\n", "b", ".", "TimeSec", "=", "w", ".", "queryEpoch", "\n", "if", "w", ".", "Send", "==", "nil", "||", "w", ".", "Send", ".", "Cq", "{", "if", "err", ":=", "func", "(", ")", "(", "err", "error", ")", "{", "err", "=", "b", ".", "AddrMsg", "(", "w", ".", "ResponseWriter", ".", "RemoteAddr", "(", ")", ",", "w", ".", "Query", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "return", "w", ".", "TapMessage", "(", "b", ".", "ToClientQuery", "(", ")", ")", "\n", "}", "(", ")", ";", "err", "!=", "nil", "{", "w", ".", "err", "=", "fmt", ".", "Errorf", "(", "\"client query: %s\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "if", "w", ".", "Send", "==", "nil", "||", "w", ".", "Send", ".", "Cr", "{", "if", "writeErr", "==", "nil", "{", "if", "err", ":=", "func", "(", ")", "(", "err", "error", ")", "{", "b", ".", "TimeSec", "=", "writeEpoch", "\n", "if", "err", "=", "b", ".", "Msg", "(", "resp", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "return", "w", ".", "TapMessage", "(", "b", ".", "ToClientResponse", "(", ")", ")", "\n", "}", "(", ")", ";", "err", "!=", "nil", "{", "w", ".", "err", "=", "fmt", ".", "Errorf", "(", "\"client response: %s\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// WriteMsg writes back the response to the client and THEN works on logging the request // and response to dnstap. // Dnstap errors are to be checked by DnstapError.
[ "WriteMsg", "writes", "back", "the", "response", "to", "the", "client", "and", "THEN", "works", "on", "logging", "the", "request", "and", "response", "to", "dnstap", ".", "Dnstap", "errors", "are", "to", "be", "checked", "by", "DnstapError", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/coredns/plugin/dnstap/taprw/writer.go#L53-L87
train
inverse-inc/packetfence
go/firewallsso/iboss.go
Start
func (fw *Iboss) Start(ctx context.Context, info map[string]string, timeout int) (bool, error) { req, err := fw.getRequest(ctx, "login", info) if err != nil { return false, err } resp, err := fw.getHttpClient(ctx).Do(req) if err != nil { log.LoggerWContext(ctx).Error(fmt.Sprintf("Error contacting Iboss: %s", err)) //Not returning now so that body can be closed if necessary } if resp != nil && resp.Body != nil { resp.Body.Close() } return err == nil, err }
go
func (fw *Iboss) Start(ctx context.Context, info map[string]string, timeout int) (bool, error) { req, err := fw.getRequest(ctx, "login", info) if err != nil { return false, err } resp, err := fw.getHttpClient(ctx).Do(req) if err != nil { log.LoggerWContext(ctx).Error(fmt.Sprintf("Error contacting Iboss: %s", err)) //Not returning now so that body can be closed if necessary } if resp != nil && resp.Body != nil { resp.Body.Close() } return err == nil, err }
[ "func", "(", "fw", "*", "Iboss", ")", "Start", "(", "ctx", "context", ".", "Context", ",", "info", "map", "[", "string", "]", "string", ",", "timeout", "int", ")", "(", "bool", ",", "error", ")", "{", "req", ",", "err", ":=", "fw", ".", "getRequest", "(", "ctx", ",", "\"login\"", ",", "info", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "resp", ",", "err", ":=", "fw", ".", "getHttpClient", "(", "ctx", ")", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Error", "(", "fmt", ".", "Sprintf", "(", "\"Error contacting Iboss: %s\"", ",", "err", ")", ")", "\n", "}", "\n", "if", "resp", "!=", "nil", "&&", "resp", ".", "Body", "!=", "nil", "{", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "}", "\n", "return", "err", "==", "nil", ",", "err", "\n", "}" ]
// Send an SSO start to the Iboss firewall // Returns an error unless there is a valid reply from the firewall or if the HTTP request fails to be built
[ "Send", "an", "SSO", "start", "to", "the", "Iboss", "firewall", "Returns", "an", "error", "unless", "there", "is", "a", "valid", "reply", "from", "the", "firewall", "or", "if", "the", "HTTP", "request", "fails", "to", "be", "built" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/iboss.go#L20-L39
train
inverse-inc/packetfence
go/firewallsso/iboss.go
getRequest
func (fw *Iboss) getRequest(ctx context.Context, action string, info map[string]string) (*http.Request, error) { req, err := http.NewRequest( "GET", fmt.Sprintf( "http://%s:%s/nacAgent?action=%s&user=%s&dc=%s&key=%s&ip=%s&cn=%s&g=%s", fw.PfconfigHashNS, fw.Port, action, info["username"], fw.NacName, fw.Password, info["ip"], info["username"], info["role"], ), bytes.NewBufferString("query=libwww-perl&mode=dist"), ) req.Header.Add("Content-Type", "application/x-www-form-urlencoded") if err != nil { return nil, err } return req, nil }
go
func (fw *Iboss) getRequest(ctx context.Context, action string, info map[string]string) (*http.Request, error) { req, err := http.NewRequest( "GET", fmt.Sprintf( "http://%s:%s/nacAgent?action=%s&user=%s&dc=%s&key=%s&ip=%s&cn=%s&g=%s", fw.PfconfigHashNS, fw.Port, action, info["username"], fw.NacName, fw.Password, info["ip"], info["username"], info["role"], ), bytes.NewBufferString("query=libwww-perl&mode=dist"), ) req.Header.Add("Content-Type", "application/x-www-form-urlencoded") if err != nil { return nil, err } return req, nil }
[ "func", "(", "fw", "*", "Iboss", ")", "getRequest", "(", "ctx", "context", ".", "Context", ",", "action", "string", ",", "info", "map", "[", "string", "]", "string", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"GET\"", ",", "fmt", ".", "Sprintf", "(", "\"http://%s:%s/nacAgent?action=%s&user=%s&dc=%s&key=%s&ip=%s&cn=%s&g=%s\"", ",", "fw", ".", "PfconfigHashNS", ",", "fw", ".", "Port", ",", "action", ",", "info", "[", "\"username\"", "]", ",", "fw", ".", "NacName", ",", "fw", ".", "Password", ",", "info", "[", "\"ip\"", "]", ",", "info", "[", "\"username\"", "]", ",", "info", "[", "\"role\"", "]", ",", ")", ",", "bytes", ".", "NewBufferString", "(", "\"query=libwww-perl&mode=dist\"", ")", ",", ")", "\n", "req", ".", "Header", ".", "Add", "(", "\"Content-Type\"", ",", "\"application/x-www-form-urlencoded\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "req", ",", "nil", "\n", "}" ]
// Build an HTTP request to send to the Iboss firewall // This builds the request for start+stop and is controlled by the action parameter // This will return an error if the request cannot be built
[ "Build", "an", "HTTP", "request", "to", "send", "to", "the", "Iboss", "firewall", "This", "builds", "the", "request", "for", "start", "+", "stop", "and", "is", "controlled", "by", "the", "action", "parameter", "This", "will", "return", "an", "error", "if", "the", "request", "cannot", "be", "built" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/firewallsso/iboss.go#L67-L90
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/maintain.go
RenewManagedCertificates
func RenewManagedCertificates(allowPrompts bool) (err error) { var renewQueue, deleteQueue []Certificate visitedNames := make(map[string]struct{}) certCacheMu.RLock() for name, cert := range certCache { if !cert.Config.Managed || cert.Config.SelfSigned { continue } // the list of names on this cert should never be empty... if cert.Names == nil || len(cert.Names) == 0 { log.Printf("[WARNING] Certificate keyed by '%s' has no names: %v - removing from cache", name, cert.Names) deleteQueue = append(deleteQueue, cert) continue } // skip names whose certificate we've already renewed if _, ok := visitedNames[name]; ok { continue } for _, name := range cert.Names { visitedNames[name] = struct{}{} } // if its time is up or ending soon, we need to try to renew it timeLeft := cert.NotAfter.Sub(time.Now().UTC()) if timeLeft < RenewDurationBefore { log.Printf("[INFO] Certificate for %v expires in %v; attempting renewal", cert.Names, timeLeft) if cert.Config == nil { log.Printf("[ERROR] %s: No associated TLS config; unable to renew", name) continue } // queue for renewal when we aren't in a read lock anymore // (the TLS-SNI challenge will need a write lock in order to // present the certificate, so we renew outside of read lock) renewQueue = append(renewQueue, cert) } } certCacheMu.RUnlock() // Perform renewals that are queued for _, cert := range renewQueue { // Get the name which we should use to renew this certificate; // we only support managing certificates with one name per cert, // so this should be easy. We can't rely on cert.Config.Hostname // because it may be a wildcard value from the Caddyfile (e.g. // *.something.com) which, as of Jan. 2017, is not supported by ACME. var renewName string for _, name := range cert.Names { if name != "" { renewName = name break } } // perform renewal err := cert.Config.RenewCert(renewName, allowPrompts) if err != nil { if allowPrompts { // Certificate renewal failed and the operator is present; we should stop // immediately and return the error. See a discussion in issue 642 // about this. For a while, we only stopped if the certificate was // expired, but in reality, there is no difference between reporting // it now versus later, except that there's somebody present to deal // with it now, so require it. return err } log.Printf("[ERROR] %v", err) if cert.Config.OnDemand { deleteQueue = append(deleteQueue, cert) } } else { // successful renewal, so update in-memory cache by loading // renewed certificate so it will be used with handshakes // TODO: Not until CA has valid OCSP response ready for the new cert... sigh. if cert.Names[len(cert.Names)-1] == "" { // Special case: This is the default certificate. We must // flush it out of the cache so that we no longer point to // the old, un-renewed certificate. Otherwise it will be // renewed on every scan, which is too often. The next cert // to be cached (probably this one) will become the default. certCacheMu.Lock() delete(certCache, "") certCacheMu.Unlock() } _, err := CacheManagedCertificate(cert.Names[0], cert.Config) if err != nil { if allowPrompts { return err // operator is present, so report error immediately } log.Printf("[ERROR] %v", err) } } } // Apply queued deletion changes to the cache for _, cert := range deleteQueue { certCacheMu.Lock() for _, name := range cert.Names { delete(certCache, name) } certCacheMu.Unlock() } return nil }
go
func RenewManagedCertificates(allowPrompts bool) (err error) { var renewQueue, deleteQueue []Certificate visitedNames := make(map[string]struct{}) certCacheMu.RLock() for name, cert := range certCache { if !cert.Config.Managed || cert.Config.SelfSigned { continue } // the list of names on this cert should never be empty... if cert.Names == nil || len(cert.Names) == 0 { log.Printf("[WARNING] Certificate keyed by '%s' has no names: %v - removing from cache", name, cert.Names) deleteQueue = append(deleteQueue, cert) continue } // skip names whose certificate we've already renewed if _, ok := visitedNames[name]; ok { continue } for _, name := range cert.Names { visitedNames[name] = struct{}{} } // if its time is up or ending soon, we need to try to renew it timeLeft := cert.NotAfter.Sub(time.Now().UTC()) if timeLeft < RenewDurationBefore { log.Printf("[INFO] Certificate for %v expires in %v; attempting renewal", cert.Names, timeLeft) if cert.Config == nil { log.Printf("[ERROR] %s: No associated TLS config; unable to renew", name) continue } // queue for renewal when we aren't in a read lock anymore // (the TLS-SNI challenge will need a write lock in order to // present the certificate, so we renew outside of read lock) renewQueue = append(renewQueue, cert) } } certCacheMu.RUnlock() // Perform renewals that are queued for _, cert := range renewQueue { // Get the name which we should use to renew this certificate; // we only support managing certificates with one name per cert, // so this should be easy. We can't rely on cert.Config.Hostname // because it may be a wildcard value from the Caddyfile (e.g. // *.something.com) which, as of Jan. 2017, is not supported by ACME. var renewName string for _, name := range cert.Names { if name != "" { renewName = name break } } // perform renewal err := cert.Config.RenewCert(renewName, allowPrompts) if err != nil { if allowPrompts { // Certificate renewal failed and the operator is present; we should stop // immediately and return the error. See a discussion in issue 642 // about this. For a while, we only stopped if the certificate was // expired, but in reality, there is no difference between reporting // it now versus later, except that there's somebody present to deal // with it now, so require it. return err } log.Printf("[ERROR] %v", err) if cert.Config.OnDemand { deleteQueue = append(deleteQueue, cert) } } else { // successful renewal, so update in-memory cache by loading // renewed certificate so it will be used with handshakes // TODO: Not until CA has valid OCSP response ready for the new cert... sigh. if cert.Names[len(cert.Names)-1] == "" { // Special case: This is the default certificate. We must // flush it out of the cache so that we no longer point to // the old, un-renewed certificate. Otherwise it will be // renewed on every scan, which is too often. The next cert // to be cached (probably this one) will become the default. certCacheMu.Lock() delete(certCache, "") certCacheMu.Unlock() } _, err := CacheManagedCertificate(cert.Names[0], cert.Config) if err != nil { if allowPrompts { return err // operator is present, so report error immediately } log.Printf("[ERROR] %v", err) } } } // Apply queued deletion changes to the cache for _, cert := range deleteQueue { certCacheMu.Lock() for _, name := range cert.Names { delete(certCache, name) } certCacheMu.Unlock() } return nil }
[ "func", "RenewManagedCertificates", "(", "allowPrompts", "bool", ")", "(", "err", "error", ")", "{", "var", "renewQueue", ",", "deleteQueue", "[", "]", "Certificate", "\n", "visitedNames", ":=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", "\n", "certCacheMu", ".", "RLock", "(", ")", "\n", "for", "name", ",", "cert", ":=", "range", "certCache", "{", "if", "!", "cert", ".", "Config", ".", "Managed", "||", "cert", ".", "Config", ".", "SelfSigned", "{", "continue", "\n", "}", "\n", "if", "cert", ".", "Names", "==", "nil", "||", "len", "(", "cert", ".", "Names", ")", "==", "0", "{", "log", ".", "Printf", "(", "\"[WARNING] Certificate keyed by '%s' has no names: %v - removing from cache\"", ",", "name", ",", "cert", ".", "Names", ")", "\n", "deleteQueue", "=", "append", "(", "deleteQueue", ",", "cert", ")", "\n", "continue", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "visitedNames", "[", "name", "]", ";", "ok", "{", "continue", "\n", "}", "\n", "for", "_", ",", "name", ":=", "range", "cert", ".", "Names", "{", "visitedNames", "[", "name", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "timeLeft", ":=", "cert", ".", "NotAfter", ".", "Sub", "(", "time", ".", "Now", "(", ")", ".", "UTC", "(", ")", ")", "\n", "if", "timeLeft", "<", "RenewDurationBefore", "{", "log", ".", "Printf", "(", "\"[INFO] Certificate for %v expires in %v; attempting renewal\"", ",", "cert", ".", "Names", ",", "timeLeft", ")", "\n", "if", "cert", ".", "Config", "==", "nil", "{", "log", ".", "Printf", "(", "\"[ERROR] %s: No associated TLS config; unable to renew\"", ",", "name", ")", "\n", "continue", "\n", "}", "\n", "renewQueue", "=", "append", "(", "renewQueue", ",", "cert", ")", "\n", "}", "\n", "}", "\n", "certCacheMu", ".", "RUnlock", "(", ")", "\n", "for", "_", ",", "cert", ":=", "range", "renewQueue", "{", "var", "renewName", "string", "\n", "for", "_", ",", "name", ":=", "range", "cert", ".", "Names", "{", "if", "name", "!=", "\"\"", "{", "renewName", "=", "name", "\n", "break", "\n", "}", "\n", "}", "\n", "err", ":=", "cert", ".", "Config", ".", "RenewCert", "(", "renewName", ",", "allowPrompts", ")", "\n", "if", "err", "!=", "nil", "{", "if", "allowPrompts", "{", "return", "err", "\n", "}", "\n", "log", ".", "Printf", "(", "\"[ERROR] %v\"", ",", "err", ")", "\n", "if", "cert", ".", "Config", ".", "OnDemand", "{", "deleteQueue", "=", "append", "(", "deleteQueue", ",", "cert", ")", "\n", "}", "\n", "}", "else", "{", "if", "cert", ".", "Names", "[", "len", "(", "cert", ".", "Names", ")", "-", "1", "]", "==", "\"\"", "{", "certCacheMu", ".", "Lock", "(", ")", "\n", "delete", "(", "certCache", ",", "\"\"", ")", "\n", "certCacheMu", ".", "Unlock", "(", ")", "\n", "}", "\n", "_", ",", "err", ":=", "CacheManagedCertificate", "(", "cert", ".", "Names", "[", "0", "]", ",", "cert", ".", "Config", ")", "\n", "if", "err", "!=", "nil", "{", "if", "allowPrompts", "{", "return", "err", "\n", "}", "\n", "log", ".", "Printf", "(", "\"[ERROR] %v\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "for", "_", ",", "cert", ":=", "range", "deleteQueue", "{", "certCacheMu", ".", "Lock", "(", ")", "\n", "for", "_", ",", "name", ":=", "range", "cert", ".", "Names", "{", "delete", "(", "certCache", ",", "name", ")", "\n", "}", "\n", "certCacheMu", ".", "Unlock", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// RenewManagedCertificates renews managed certificates.
[ "RenewManagedCertificates", "renews", "managed", "certificates", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/maintain.go#L67-L175
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/maintain.go
freshOCSP
func freshOCSP(resp *ocsp.Response) bool { // start checking OCSP staple about halfway through validity period for good measure refreshTime := resp.ThisUpdate.Add(resp.NextUpdate.Sub(resp.ThisUpdate) / 2) return time.Now().Before(refreshTime) }
go
func freshOCSP(resp *ocsp.Response) bool { // start checking OCSP staple about halfway through validity period for good measure refreshTime := resp.ThisUpdate.Add(resp.NextUpdate.Sub(resp.ThisUpdate) / 2) return time.Now().Before(refreshTime) }
[ "func", "freshOCSP", "(", "resp", "*", "ocsp", ".", "Response", ")", "bool", "{", "refreshTime", ":=", "resp", ".", "ThisUpdate", ".", "Add", "(", "resp", ".", "NextUpdate", ".", "Sub", "(", "resp", ".", "ThisUpdate", ")", "/", "2", ")", "\n", "return", "time", ".", "Now", "(", ")", ".", "Before", "(", "refreshTime", ")", "\n", "}" ]
// freshOCSP returns true if resp is still fresh, // meaning that it is not expedient to get an // updated response from the OCSP server.
[ "freshOCSP", "returns", "true", "if", "resp", "is", "still", "fresh", "meaning", "that", "it", "is", "not", "expedient", "to", "get", "an", "updated", "response", "from", "the", "OCSP", "server", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/maintain.go#L295-L299
train
inverse-inc/packetfence
go/caddy/pfipset/utils.go
initIPSet
func (IPSET *pfIPSET) initIPSet(ctx context.Context, db *sql.DB) { logger := log.LoggerWContext(ctx) IPSET.ListALL, _ = ipset.ListAll() rows, err := db.Query("select distinct n.mac, i.ip, n.category_id as node_id from node as n left join locationlog as l on n.mac=l.mac left join ip4log as i on n.mac=i.mac where l.connection_type = \"inline\" and n.status=\"reg\" and n.mac=i.mac and i.end_time > NOW()") if err != nil { // Log here logger.Error("Error while fetching the inline nodes in the database: " + err.Error()) return } defer rows.Close() var ( IpStr string Mac string NodeId string ) for rows.Next() { err := rows.Scan(&Mac, &IpStr, &NodeId) if err != nil { // Log here logger.Error(err.Error()) return } for k, v := range IPSET.Network { if k.Contains(net.ParseIP(IpStr)) { if v == "inlinel2" { IPSET.IPSEThandleLayer2(ctx, IpStr, Mac, k.IP.String(), "Reg", NodeId) IPSET.IPSEThandleMarkIpL2(ctx, IpStr, k.IP.String(), NodeId) } if v == "inlinel3" { IPSET.IPSEThandleLayer3(ctx, IpStr, k.IP.String(), "Reg", NodeId) IPSET.IPSEThandleMarkIpL3(ctx, IpStr, k.IP.String(), NodeId) } break } } } }
go
func (IPSET *pfIPSET) initIPSet(ctx context.Context, db *sql.DB) { logger := log.LoggerWContext(ctx) IPSET.ListALL, _ = ipset.ListAll() rows, err := db.Query("select distinct n.mac, i.ip, n.category_id as node_id from node as n left join locationlog as l on n.mac=l.mac left join ip4log as i on n.mac=i.mac where l.connection_type = \"inline\" and n.status=\"reg\" and n.mac=i.mac and i.end_time > NOW()") if err != nil { // Log here logger.Error("Error while fetching the inline nodes in the database: " + err.Error()) return } defer rows.Close() var ( IpStr string Mac string NodeId string ) for rows.Next() { err := rows.Scan(&Mac, &IpStr, &NodeId) if err != nil { // Log here logger.Error(err.Error()) return } for k, v := range IPSET.Network { if k.Contains(net.ParseIP(IpStr)) { if v == "inlinel2" { IPSET.IPSEThandleLayer2(ctx, IpStr, Mac, k.IP.String(), "Reg", NodeId) IPSET.IPSEThandleMarkIpL2(ctx, IpStr, k.IP.String(), NodeId) } if v == "inlinel3" { IPSET.IPSEThandleLayer3(ctx, IpStr, k.IP.String(), "Reg", NodeId) IPSET.IPSEThandleMarkIpL3(ctx, IpStr, k.IP.String(), NodeId) } break } } } }
[ "func", "(", "IPSET", "*", "pfIPSET", ")", "initIPSet", "(", "ctx", "context", ".", "Context", ",", "db", "*", "sql", ".", "DB", ")", "{", "logger", ":=", "log", ".", "LoggerWContext", "(", "ctx", ")", "\n", "IPSET", ".", "ListALL", ",", "_", "=", "ipset", ".", "ListAll", "(", ")", "\n", "rows", ",", "err", ":=", "db", ".", "Query", "(", "\"select distinct n.mac, i.ip, n.category_id as node_id from node as n left join locationlog as l on n.mac=l.mac left join ip4log as i on n.mac=i.mac where l.connection_type = \\\"inline\\\" and n.status=\\\"reg\\\" and n.mac=i.mac and i.end_time > NOW()\"", ")", "\n", "\\\"", "\n", "\\\"", "\n", "\\\"", "\n", "\\\"", "\n", "}" ]
// initIPSet fetch the database to remove already assigned ip addresses
[ "initIPSet", "fetch", "the", "database", "to", "remove", "already", "assigned", "ip", "addresses" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/pfipset/utils.go#L124-L161
train
inverse-inc/packetfence
go/caddy/pfipset/utils.go
detectType
func (IPSET *pfIPSET) detectType(ctx context.Context) error { IPSET.ListALL, _ = ipset.ListAll() var NetIndex net.IPNet IPSET.Network = make(map[*net.IPNet]string) var interfaces pfconfigdriver.ListenInts pfconfigdriver.FetchDecodeSocket(ctx, &interfaces) var keyConfNet pfconfigdriver.PfconfigKeys keyConfNet.PfconfigNS = "config::Network" keyConfNet.PfconfigHostnameOverlay = "yes" pfconfigdriver.FetchDecodeSocket(ctx, &keyConfNet) var keyConfCluster pfconfigdriver.NetInterface keyConfCluster.PfconfigNS = "config::Pf(CLUSTER," + pfconfigdriver.FindClusterName(ctx) + ")" for _, v := range interfaces.Element { keyConfCluster.PfconfigHashNS = "interface " + v pfconfigdriver.FetchDecodeSocket(ctx, &keyConfCluster) // Nothing in keyConfCluster.Ip so we are not in cluster mode eth, _ := net.InterfaceByName(v) adresses, _ := eth.Addrs() for _, adresse := range adresses { var NetIP *net.IPNet var IP net.IP IP, NetIP, _ = net.ParseCIDR(adresse.String()) if IP.To4() == nil { continue } a, b := NetIP.Mask.Size() if a == b { continue } for _, key := range keyConfNet.Keys { var ConfNet pfconfigdriver.NetworkConf ConfNet.PfconfigHashNS = key pfconfigdriver.FetchDecodeSocket(ctx, &ConfNet) if (NetIP.Contains(net.ParseIP(ConfNet.DhcpStart)) && NetIP.Contains(net.ParseIP(ConfNet.DhcpEnd))) || NetIP.Contains(net.ParseIP(ConfNet.NextHop)) { NetIndex.Mask = net.IPMask(net.ParseIP(ConfNet.Netmask)) NetIndex.IP = net.ParseIP(key) Index := NetIndex IPSET.Network[&Index] = ConfNet.Type } } } } return nil }
go
func (IPSET *pfIPSET) detectType(ctx context.Context) error { IPSET.ListALL, _ = ipset.ListAll() var NetIndex net.IPNet IPSET.Network = make(map[*net.IPNet]string) var interfaces pfconfigdriver.ListenInts pfconfigdriver.FetchDecodeSocket(ctx, &interfaces) var keyConfNet pfconfigdriver.PfconfigKeys keyConfNet.PfconfigNS = "config::Network" keyConfNet.PfconfigHostnameOverlay = "yes" pfconfigdriver.FetchDecodeSocket(ctx, &keyConfNet) var keyConfCluster pfconfigdriver.NetInterface keyConfCluster.PfconfigNS = "config::Pf(CLUSTER," + pfconfigdriver.FindClusterName(ctx) + ")" for _, v := range interfaces.Element { keyConfCluster.PfconfigHashNS = "interface " + v pfconfigdriver.FetchDecodeSocket(ctx, &keyConfCluster) // Nothing in keyConfCluster.Ip so we are not in cluster mode eth, _ := net.InterfaceByName(v) adresses, _ := eth.Addrs() for _, adresse := range adresses { var NetIP *net.IPNet var IP net.IP IP, NetIP, _ = net.ParseCIDR(adresse.String()) if IP.To4() == nil { continue } a, b := NetIP.Mask.Size() if a == b { continue } for _, key := range keyConfNet.Keys { var ConfNet pfconfigdriver.NetworkConf ConfNet.PfconfigHashNS = key pfconfigdriver.FetchDecodeSocket(ctx, &ConfNet) if (NetIP.Contains(net.ParseIP(ConfNet.DhcpStart)) && NetIP.Contains(net.ParseIP(ConfNet.DhcpEnd))) || NetIP.Contains(net.ParseIP(ConfNet.NextHop)) { NetIndex.Mask = net.IPMask(net.ParseIP(ConfNet.Netmask)) NetIndex.IP = net.ParseIP(key) Index := NetIndex IPSET.Network[&Index] = ConfNet.Type } } } } return nil }
[ "func", "(", "IPSET", "*", "pfIPSET", ")", "detectType", "(", "ctx", "context", ".", "Context", ")", "error", "{", "IPSET", ".", "ListALL", ",", "_", "=", "ipset", ".", "ListAll", "(", ")", "\n", "var", "NetIndex", "net", ".", "IPNet", "\n", "IPSET", ".", "Network", "=", "make", "(", "map", "[", "*", "net", ".", "IPNet", "]", "string", ")", "\n", "var", "interfaces", "pfconfigdriver", ".", "ListenInts", "\n", "pfconfigdriver", ".", "FetchDecodeSocket", "(", "ctx", ",", "&", "interfaces", ")", "\n", "var", "keyConfNet", "pfconfigdriver", ".", "PfconfigKeys", "\n", "keyConfNet", ".", "PfconfigNS", "=", "\"config::Network\"", "\n", "keyConfNet", ".", "PfconfigHostnameOverlay", "=", "\"yes\"", "\n", "pfconfigdriver", ".", "FetchDecodeSocket", "(", "ctx", ",", "&", "keyConfNet", ")", "\n", "var", "keyConfCluster", "pfconfigdriver", ".", "NetInterface", "\n", "keyConfCluster", ".", "PfconfigNS", "=", "\"config::Pf(CLUSTER,\"", "+", "pfconfigdriver", ".", "FindClusterName", "(", "ctx", ")", "+", "\")\"", "\n", "for", "_", ",", "v", ":=", "range", "interfaces", ".", "Element", "{", "keyConfCluster", ".", "PfconfigHashNS", "=", "\"interface \"", "+", "v", "\n", "pfconfigdriver", ".", "FetchDecodeSocket", "(", "ctx", ",", "&", "keyConfCluster", ")", "\n", "eth", ",", "_", ":=", "net", ".", "InterfaceByName", "(", "v", ")", "\n", "adresses", ",", "_", ":=", "eth", ".", "Addrs", "(", ")", "\n", "for", "_", ",", "adresse", ":=", "range", "adresses", "{", "var", "NetIP", "*", "net", ".", "IPNet", "\n", "var", "IP", "net", ".", "IP", "\n", "IP", ",", "NetIP", ",", "_", "=", "net", ".", "ParseCIDR", "(", "adresse", ".", "String", "(", ")", ")", "\n", "if", "IP", ".", "To4", "(", ")", "==", "nil", "{", "continue", "\n", "}", "\n", "a", ",", "b", ":=", "NetIP", ".", "Mask", ".", "Size", "(", ")", "\n", "if", "a", "==", "b", "{", "continue", "\n", "}", "\n", "for", "_", ",", "key", ":=", "range", "keyConfNet", ".", "Keys", "{", "var", "ConfNet", "pfconfigdriver", ".", "NetworkConf", "\n", "ConfNet", ".", "PfconfigHashNS", "=", "key", "\n", "pfconfigdriver", ".", "FetchDecodeSocket", "(", "ctx", ",", "&", "ConfNet", ")", "\n", "if", "(", "NetIP", ".", "Contains", "(", "net", ".", "ParseIP", "(", "ConfNet", ".", "DhcpStart", ")", ")", "&&", "NetIP", ".", "Contains", "(", "net", ".", "ParseIP", "(", "ConfNet", ".", "DhcpEnd", ")", ")", ")", "||", "NetIP", ".", "Contains", "(", "net", ".", "ParseIP", "(", "ConfNet", ".", "NextHop", ")", ")", "{", "NetIndex", ".", "Mask", "=", "net", ".", "IPMask", "(", "net", ".", "ParseIP", "(", "ConfNet", ".", "Netmask", ")", ")", "\n", "NetIndex", ".", "IP", "=", "net", ".", "ParseIP", "(", "key", ")", "\n", "Index", ":=", "NetIndex", "\n", "IPSET", ".", "Network", "[", "&", "Index", "]", "=", "ConfNet", ".", "Type", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// detectType of each network
[ "detectType", "of", "each", "network" ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/pfipset/utils.go#L164-L215
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/certificates.go
cacheUnmanagedCertificatePEMFile
func cacheUnmanagedCertificatePEMFile(certFile, keyFile string) error { cert, err := makeCertificateFromDisk(certFile, keyFile) if err != nil { return err } cacheCertificate(cert) return nil }
go
func cacheUnmanagedCertificatePEMFile(certFile, keyFile string) error { cert, err := makeCertificateFromDisk(certFile, keyFile) if err != nil { return err } cacheCertificate(cert) return nil }
[ "func", "cacheUnmanagedCertificatePEMFile", "(", "certFile", ",", "keyFile", "string", ")", "error", "{", "cert", ",", "err", ":=", "makeCertificateFromDisk", "(", "certFile", ",", "keyFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cacheCertificate", "(", "cert", ")", "\n", "return", "nil", "\n", "}" ]
// cacheUnmanagedCertificatePEMFile loads a certificate for host using certFile // and keyFile, which must be in PEM format. It stores the certificate in // memory. The Managed and OnDemand flags of the certificate will be set to // false. // // This function is safe for concurrent use.
[ "cacheUnmanagedCertificatePEMFile", "loads", "a", "certificate", "for", "host", "using", "certFile", "and", "keyFile", "which", "must", "be", "in", "PEM", "format", ".", "It", "stores", "the", "certificate", "in", "memory", ".", "The", "Managed", "and", "OnDemand", "flags", "of", "the", "certificate", "will", "be", "set", "to", "false", ".", "This", "function", "is", "safe", "for", "concurrent", "use", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/certificates.go#L117-L124
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/certificates.go
cacheUnmanagedCertificatePEMBytes
func cacheUnmanagedCertificatePEMBytes(certBytes, keyBytes []byte) error { cert, err := makeCertificate(certBytes, keyBytes) if err != nil { return err } cacheCertificate(cert) return nil }
go
func cacheUnmanagedCertificatePEMBytes(certBytes, keyBytes []byte) error { cert, err := makeCertificate(certBytes, keyBytes) if err != nil { return err } cacheCertificate(cert) return nil }
[ "func", "cacheUnmanagedCertificatePEMBytes", "(", "certBytes", ",", "keyBytes", "[", "]", "byte", ")", "error", "{", "cert", ",", "err", ":=", "makeCertificate", "(", "certBytes", ",", "keyBytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cacheCertificate", "(", "cert", ")", "\n", "return", "nil", "\n", "}" ]
// cacheUnmanagedCertificatePEMBytes makes a certificate out of the PEM bytes // of the certificate and key, then caches it in memory. // // This function is safe for concurrent use.
[ "cacheUnmanagedCertificatePEMBytes", "makes", "a", "certificate", "out", "of", "the", "PEM", "bytes", "of", "the", "certificate", "and", "key", "then", "caches", "it", "in", "memory", ".", "This", "function", "is", "safe", "for", "concurrent", "use", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/certificates.go#L130-L137
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/certificates.go
makeCertificate
func makeCertificate(certPEMBlock, keyPEMBlock []byte) (Certificate, error) { var cert Certificate // Convert to a tls.Certificate tlsCert, err := tls.X509KeyPair(certPEMBlock, keyPEMBlock) if err != nil { return cert, err } if len(tlsCert.Certificate) == 0 { return cert, errors.New("certificate is empty") } cert.Certificate = tlsCert // Parse leaf certificate, extract relevant metadata, and staple OCSP leaf, err := x509.ParseCertificate(tlsCert.Certificate[0]) if err != nil { return cert, err } err = fillCertFromLeaf(&cert, leaf) if err != nil { return cert, err } err = stapleOCSP(&cert, certPEMBlock) if err != nil { log.Printf("[WARNING] Stapling OCSP: %v", err) } return cert, nil }
go
func makeCertificate(certPEMBlock, keyPEMBlock []byte) (Certificate, error) { var cert Certificate // Convert to a tls.Certificate tlsCert, err := tls.X509KeyPair(certPEMBlock, keyPEMBlock) if err != nil { return cert, err } if len(tlsCert.Certificate) == 0 { return cert, errors.New("certificate is empty") } cert.Certificate = tlsCert // Parse leaf certificate, extract relevant metadata, and staple OCSP leaf, err := x509.ParseCertificate(tlsCert.Certificate[0]) if err != nil { return cert, err } err = fillCertFromLeaf(&cert, leaf) if err != nil { return cert, err } err = stapleOCSP(&cert, certPEMBlock) if err != nil { log.Printf("[WARNING] Stapling OCSP: %v", err) } return cert, nil }
[ "func", "makeCertificate", "(", "certPEMBlock", ",", "keyPEMBlock", "[", "]", "byte", ")", "(", "Certificate", ",", "error", ")", "{", "var", "cert", "Certificate", "\n", "tlsCert", ",", "err", ":=", "tls", ".", "X509KeyPair", "(", "certPEMBlock", ",", "keyPEMBlock", ")", "\n", "if", "err", "!=", "nil", "{", "return", "cert", ",", "err", "\n", "}", "\n", "if", "len", "(", "tlsCert", ".", "Certificate", ")", "==", "0", "{", "return", "cert", ",", "errors", ".", "New", "(", "\"certificate is empty\"", ")", "\n", "}", "\n", "cert", ".", "Certificate", "=", "tlsCert", "\n", "leaf", ",", "err", ":=", "x509", ".", "ParseCertificate", "(", "tlsCert", ".", "Certificate", "[", "0", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "cert", ",", "err", "\n", "}", "\n", "err", "=", "fillCertFromLeaf", "(", "&", "cert", ",", "leaf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "cert", ",", "err", "\n", "}", "\n", "err", "=", "stapleOCSP", "(", "&", "cert", ",", "certPEMBlock", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"[WARNING] Stapling OCSP: %v\"", ",", "err", ")", "\n", "}", "\n", "return", "cert", ",", "nil", "\n", "}" ]
// makeCertificate turns a certificate PEM bundle and a key PEM block into // a Certificate, with OCSP and other relevant metadata tagged with it, // except for the OnDemand and Managed flags. It is up to the caller to // set those properties.
[ "makeCertificate", "turns", "a", "certificate", "PEM", "bundle", "and", "a", "key", "PEM", "block", "into", "a", "Certificate", "with", "OCSP", "and", "other", "relevant", "metadata", "tagged", "with", "it", "except", "for", "the", "OnDemand", "and", "Managed", "flags", ".", "It", "is", "up", "to", "the", "caller", "to", "set", "those", "properties", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/certificates.go#L159-L187
train
inverse-inc/packetfence
go/caddy/caddy/caddytls/certificates.go
fillCertFromLeaf
func fillCertFromLeaf(cert *Certificate, leaf *x509.Certificate) error { if leaf.Subject.CommonName != "" { cert.Names = []string{strings.ToLower(leaf.Subject.CommonName)} } for _, name := range leaf.DNSNames { if name != leaf.Subject.CommonName { cert.Names = append(cert.Names, strings.ToLower(name)) } } for _, ip := range leaf.IPAddresses { if ipStr := ip.String(); ipStr != leaf.Subject.CommonName { cert.Names = append(cert.Names, strings.ToLower(ipStr)) } } for _, email := range leaf.EmailAddresses { if email != leaf.Subject.CommonName { cert.Names = append(cert.Names, strings.ToLower(email)) } } if len(cert.Names) == 0 { return errors.New("certificate has no names") } cert.NotAfter = leaf.NotAfter return nil }
go
func fillCertFromLeaf(cert *Certificate, leaf *x509.Certificate) error { if leaf.Subject.CommonName != "" { cert.Names = []string{strings.ToLower(leaf.Subject.CommonName)} } for _, name := range leaf.DNSNames { if name != leaf.Subject.CommonName { cert.Names = append(cert.Names, strings.ToLower(name)) } } for _, ip := range leaf.IPAddresses { if ipStr := ip.String(); ipStr != leaf.Subject.CommonName { cert.Names = append(cert.Names, strings.ToLower(ipStr)) } } for _, email := range leaf.EmailAddresses { if email != leaf.Subject.CommonName { cert.Names = append(cert.Names, strings.ToLower(email)) } } if len(cert.Names) == 0 { return errors.New("certificate has no names") } cert.NotAfter = leaf.NotAfter return nil }
[ "func", "fillCertFromLeaf", "(", "cert", "*", "Certificate", ",", "leaf", "*", "x509", ".", "Certificate", ")", "error", "{", "if", "leaf", ".", "Subject", ".", "CommonName", "!=", "\"\"", "{", "cert", ".", "Names", "=", "[", "]", "string", "{", "strings", ".", "ToLower", "(", "leaf", ".", "Subject", ".", "CommonName", ")", "}", "\n", "}", "\n", "for", "_", ",", "name", ":=", "range", "leaf", ".", "DNSNames", "{", "if", "name", "!=", "leaf", ".", "Subject", ".", "CommonName", "{", "cert", ".", "Names", "=", "append", "(", "cert", ".", "Names", ",", "strings", ".", "ToLower", "(", "name", ")", ")", "\n", "}", "\n", "}", "\n", "for", "_", ",", "ip", ":=", "range", "leaf", ".", "IPAddresses", "{", "if", "ipStr", ":=", "ip", ".", "String", "(", ")", ";", "ipStr", "!=", "leaf", ".", "Subject", ".", "CommonName", "{", "cert", ".", "Names", "=", "append", "(", "cert", ".", "Names", ",", "strings", ".", "ToLower", "(", "ipStr", ")", ")", "\n", "}", "\n", "}", "\n", "for", "_", ",", "email", ":=", "range", "leaf", ".", "EmailAddresses", "{", "if", "email", "!=", "leaf", ".", "Subject", ".", "CommonName", "{", "cert", ".", "Names", "=", "append", "(", "cert", ".", "Names", ",", "strings", ".", "ToLower", "(", "email", ")", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "cert", ".", "Names", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"certificate has no names\"", ")", "\n", "}", "\n", "cert", ".", "NotAfter", "=", "leaf", ".", "NotAfter", "\n", "return", "nil", "\n", "}" ]
// fillCertFromLeaf populates cert.Names and cert.NotAfter // using data in leaf.
[ "fillCertFromLeaf", "populates", "cert", ".", "Names", "and", "cert", ".", "NotAfter", "using", "data", "in", "leaf", "." ]
f29912bde7974931d699aba60aa8fde1c5d9a826
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/caddy/caddy/caddytls/certificates.go#L191-L215
train
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", "{", "cert", ".", "Names", "=", "append", "(", "cert", ".", "Names", ",", "\"\"", ")", "\n", "certCache", "[", "\"\"", "]", "=", "cert", "\n", "}", "\n", "for", "len", "(", "certCache", ")", "+", "len", "(", "cert", ".", "Names", ")", ">", "10000", "{", "for", "key", ":=", "range", "certCache", "{", "if", "key", "==", "\"\"", "{", "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", "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", "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", "return", "h", ".", "Next", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "}", "else", "{", "panic", "(", "\"Unable to obtain pfconfigpool lock in caddy middleware\"", ")", "\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", "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", "(", ")", "{", "uh", ".", "Lock", "(", ")", "\n", "if", "uh", ".", "CheckURL", "==", "\"\"", "||", "uh", ".", "Checking", "{", "uh", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n", "uh", ".", "Checking", "=", "true", "\n", "uh", ".", "Unlock", "(", ")", "\n", "r", ",", "err", ":=", "healthClient", ".", "Get", "(", "uh", ".", "CheckURL", ")", "\n", "defer", "func", "(", ")", "{", "uh", ".", "Lock", "(", ")", "\n", "uh", ".", "Checking", "=", "false", "\n", "uh", ".", "Unlock", "(", ")", "\n", "}", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"[WARNING] Host %s health check probe failed: %v\"", ",", "uh", ".", "Name", ",", "err", ")", "\n", "return", "\n", "}", "\n", "if", "err", "==", "nil", "{", "io", ".", "Copy", "(", "ioutil", ".", "Discard", ",", "r", ".", "Body", ")", "\n", "r", ".", "Body", ".", "Close", "(", ")", "\n", "if", "r", ".", "StatusCode", "<", "200", "||", "r", ".", "StatusCode", ">=", "400", "{", "log", ".", "Printf", "(", "\"[WARNING] Host %s health check returned HTTP code %d\"", ",", "uh", ".", "Name", ",", "r", ".", "StatusCode", ")", "\n", "return", "\n", "}", "\n", "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", "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", "h", ":=", "u", ".", "Policy", ".", "Select", "(", "pool", ")", "\n", "if", "h", "!=", "nil", "{", "return", "h", "\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", "{", "hostName", ":=", "name", "\n", "ret", ",", "err", ":=", "url", ".", "Parse", "(", "name", ")", "\n", "if", "err", "==", "nil", "&&", "len", "(", "ret", ".", "Host", ")", ">", "0", "{", "hostName", "=", "ret", ".", "Host", "\n", "}", "\n", "checkHostName", ",", "checkPort", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "hostName", ")", "\n", "if", "err", "!=", "nil", "{", "checkHostName", "=", "hostName", "\n", "}", "\n", "if", "u", ".", "Port", "!=", "\"\"", "{", "checkPort", "=", "u", ".", "Port", "\n", "}", "\n", "checkURL", ":=", "\"http://\"", "+", "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", "pfconfigdriver", ".", "PfconfigPool", ".", "AddStruct", "(", "ctx", ",", "&", "redisclient", ".", "Config", ")", "\n", "var", "network", "string", "\n", "if", "redisclient", ".", "Config", ".", "RedisArgs", ".", "Server", "[", "0", "]", "==", "'/'", "{", "network", "=", "\"unix\"", "\n", "}", "else", "{", "network", "=", "\"tcp\"", "\n", "}", "\n", "jobStatus", ".", "redis", "=", "redis", ".", "NewClient", "(", "&", "redis", ".", "Options", "{", "Addr", ":", "redisclient", ".", "Config", ".", "RedisArgs", ".", "Server", ",", "Network", ":", "network", ",", "}", ")", "\n", "router", ":=", "httprouter", ".", "New", "(", ")", "\n", "router", ".", "GET", "(", "\"/api/v1/pfqueue/task/:job_id/status\"", ",", "jobStatus", ".", "handleStatus", ")", "\n", "router", ".", "GET", "(", "\"/api/v1/pfqueue/task/:job_id/status/poll\"", ",", "jobStatus", ".", "handleStatusPoll", ")", "\n", "jobStatus", ".", "router", "=", "router", "\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 panic: %s.\"", ",", "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", "if", "option", "!=", "nil", "{", "option", ".", "Option", "=", "append", "(", "option", ".", "Option", ",", "&", "dns", ".", "EDNS0_LOCAL", "{", "Code", ":", "ednsStubCode", ",", "Data", ":", "[", "]", "byte", "{", "1", "}", "}", ")", "\n", "return", "m", "\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", "(", "\"proto: %s\"", ",", "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", "{", "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", "+", "\".port\"", ",", "DefaultPort", ",", "\"Default port\"", ")", "\n", "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\"", ")", ",", "\\n", ",", "}", "\n", "}", ",", "\\n", ",", "}", ")", "\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", "{", "if", "fw", ".", "Vsys", "==", "\"\"", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Debug", "(", "\"Setting default value for vsys as it isn't defined\"", ")", "\n", "fw", ".", "Vsys", "=", "\"1\"", "\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", "==", "\"syslog\"", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Info", "(", "\"Sending SSO to PaloAlto using syslog\"", ")", "\n", "return", "fw", ".", "startSyslog", "(", "ctx", ",", "info", ",", "timeout", ")", "\n", "}", "else", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Info", "(", "\"Sending SSO to PaloAlto using HTTP\"", ")", "\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", "(", "\"udp\"", ",", "fw", ".", "PfconfigHashNS", "+", "\":514\"", ",", "syslog", ".", "LOG_ERR", "|", "syslog", ".", "LOG_LOCAL5", ",", "\"pfsso\"", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Error", "(", "fmt", ".", "Sprintf", "(", "\"Error connecting to PaloAlto: %s\"", ",", "err", ")", ")", "\n", "return", "nil", ",", "err", "\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", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "writer", ".", "Err", "(", "line", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Error", "(", "fmt", ".", "Sprintf", "(", "\"Error sending message to PaloAlto: %s\"", ",", "err", ")", ")", "\n", "return", "err", "\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", "(", "\"Group <packetfence> User <%s> Address <%s> assigned to session\"", ",", "info", "[", "\"username\"", "]", ",", "info", "[", "\"ip\"", "]", ")", ")", ";", "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", "{", "timeout", "=", "timeout", "/", "60", "\n", "t", ":=", "template", ".", "New", "(", "\"PaloAlto.startHttp\"", ")", "\n", "t", ".", "Parse", "(", "`<uid-message>\t\t<version>1.0</version>\t\t<type>update</type>\t\t<payload>\t\t\t\t<login>\t\t\t\t\t\t<entry name=\"{{.Username}}\" ip=\"{{.Ip}}\" timeout=\"{{.Timeout}}\"/>\t\t\t\t</login>\t\t</payload></uid-message>`", ")", "\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", "==", "\"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.\"", ")", "\n", "return", "false", ",", "nil", "\n", "}", "else", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Info", "(", "\"Sending SSO to PaloAlto using HTTP\"", ")", "\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", "(", "\"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", ")", "}", "}", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Error", "(", "fmt", ".", "Sprintf", "(", "\"Error contacting PaloAlto: %s\"", ",", "err", ")", ")", "\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", "(", "\"X-PacketFence-Tenant-Id\"", ")", "\n", "tokenInfo", ",", "_", ":=", "tam", ".", "tokenBackend", ".", "TokenInfoForToken", "(", "token", ")", "\n", "if", "tokenInfo", "==", "nil", "{", "return", "false", ",", "errors", ".", "New", "(", "\"Invalid token info\"", ")", "\n", "}", "\n", "var", "tenantId", "int", "\n", "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\"", ")", "\n", "}", "else", "if", "xptid", "==", "\"\"", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Debug", "(", "\"Empty X-PacketFence-Tenant-Id, defaulting to token tenant ID\"", ")", "\n", "tenantId", "=", "tokenInfo", ".", "TenantId", "\n", "r", ".", "Header", ".", "Set", "(", "\"X-PacketFence-Tenant-Id\"", ",", "strconv", ".", "Itoa", "(", "tenantId", ")", ")", "\n", "}", "else", "{", "var", "err", "error", "\n", "tenantId", ",", "err", "=", "strconv", ".", "Atoi", "(", "xptid", ")", "\n", "if", "err", "!=", "nil", "{", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"Impossible to parse X-PacketFence-Tenant-Id %s into a valid number, error: %s\"", ",", "xptid", ",", "err", ")", "\n", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Warn", "(", "msg", ")", "\n", "return", "false", ",", "errors", ".", "New", "(", "msg", ")", "\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", "(", "\"X-PacketFence-Admin-Roles\"", ",", "strings", ".", "Join", "(", "roles", ",", "\",\"", ")", ")", "\n", "r", ".", "Header", ".", "Set", "(", "\"X-PacketFence-Username\"", ",", "tokenInfo", ".", "Username", ")", "\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", "(", "\"Invalid token info\"", ")", "\n", "}", "\n", "authAdminRoles", ",", "err", ":=", "tam", ".", "isAuthorizedAdminActions", "(", "ctx", ",", "method", ",", "path", ",", "tokenInfo", ".", "AdminActions", "(", ")", ")", "\n", "if", "!", "authAdminRoles", "||", "err", "!=", "nil", "{", "return", "authAdminRoles", ",", "err", "\n", "}", "\n", "authTenant", ",", "err", ":=", "tam", ".", "isAuthorizedTenantId", "(", "ctx", ",", "tenantId", ",", "tokenInfo", ".", "TenantId", ")", "\n", "if", "!", "authTenant", "||", "err", "!=", "nil", "{", "return", "authTenant", ",", "err", "\n", "}", "\n", "authConfig", ",", "err", ":=", "tam", ".", "isAuthorizedConfigNamespace", "(", "ctx", ",", "path", ",", "tokenInfo", ".", "TenantId", ")", "\n", "if", "!", "authConfig", "||", "err", "!=", "nil", "{", "return", "authConfig", ",", "err", "\n", "}", "\n", "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", "{", "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", "offset", ",", "end", ":=", "0", ",", "false", "\n", "for", "i", ":=", "0", ";", "i", "<", "targetStrip", ";", "i", "++", "{", "offset", ",", "end", "=", "dns", ".", "NextLabel", "(", "name", ",", "offset", ")", "\n", "}", "\n", "if", "end", "{", "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", "(", "\"Sending SSO through mocked Firewall SSO\"", ")", "\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", "(", "\"Sending SSO through mocked Firewall SSO\"", ")", "\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", "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", "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", "output", ":=", "sharedutils", ".", "EnvOrDefault", "(", "\"LOG_OUTPUT\"", ",", "\"syslog\"", ")", "\n", "if", "output", "==", "\"syslog\"", "{", "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", "logger", ".", "processPid", "=", "strconv", ".", "Itoa", "(", "os", ".", "Getpid", "(", ")", ")", "\n", "ctx", "=", "context", ".", "WithValue", "(", "ctx", ",", "LoggerKey", ",", "logger", ")", "\n", "level", ":=", "sharedutils", ".", "EnvOrDefault", "(", "\"LOG_LEVEL\"", ",", "\"\"", ")", "\n", "if", "level", "!=", "\"\"", "{", "logger", ".", "logger", ".", "Info", "(", "\"Setting log level to \"", "+", "level", ")", "\n", "ctx", "=", "LoggerSetLevel", "(", "ctx", ",", "level", ")", "\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", "var", "logger", "LoggerStruct", "\n", "logger", "=", "loggerInt", ".", "(", "LoggerStruct", ")", "\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", ")", "\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", "(", "\"tcp\"", ",", "s", ".", "address", ",", "time", ".", "Second", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "enc", ",", "err", ":=", "fs", ".", "NewEncoder", "(", "c", ",", "&", "fs", ".", "EncoderOptions", "{", "ContentType", ":", "[", "]", "byte", "(", "\"protobuf:dnstap.Dnstap\"", ")", ",", "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", "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", "[", "\"username\"", "]", ",", "MAC", ":", "info", "[", "\"mac\"", "]", ",", "IP", ":", "info", "[", "\"ip\"", "]", ",", "Role", ":", "info", "[", "\"role\"", "]", ",", "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", "(", "\"Cannot encode JSON-RPC call: %s\"", ",", "err", ")", ")", "\n", "return", "err", "\n", "}", "\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"POST\"", ",", "\"https://\"", "+", "fw", ".", "PfconfigHashNS", "+", "\":\"", "+", "fw", ".", "Port", ",", "bytes", ".", "NewBuffer", "(", "body", ")", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Error", "(", "fmt", ".", "Sprintf", "(", "\"Cannot create HTTP request for JSON-RPC call: %s\"", ",", "err", ")", ")", "\n", "return", "err", "\n", "}", "\n", "req", ".", "Header", ".", "Set", "(", "\"Content-Type\"", ",", "\"application/json\"", ")", "\n", "req", ".", "SetBasicAuth", "(", "fw", ".", "Username", ",", "fw", ".", "Password", ")", "\n", "resp", ",", "err", ":=", "fw", ".", "getHttpClient", "(", "ctx", ")", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Error", "(", "fmt", ".", "Sprintf", "(", "\"Cannot make HTTP request for JSON-RPC call: %s\"", ",", "err", ")", ")", "\n", "return", "err", "\n", "}", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "var", "result", "[", "1", "]", "string", "\n", "err", "=", "json2", ".", "DecodeClientResponse", "(", "resp", ".", "Body", ",", "&", "result", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "LoggerWContext", "(", "ctx", ")", ".", "Error", "(", "fmt", ".", "Sprintf", "(", "\"Cannot decode JSON-RPC response: %s\"", ",", "err", ")", ")", "\n", "return", "err", "\n", "}", "\n", "if", "result", "[", "0", "]", "==", "\"OK\"", "{", "return", "nil", "\n", "}", "else", "{", "return", "fmt", ".", "Errorf", "(", "\"JSON-RPC call returned an error: %s\"", ",", "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", ",", "\"Start\"", ",", "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", ",", "\"Stop\"", ",", "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", "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", "for", "_", ",", "rgx", ":=", "range", "p", ".", "endpointBlackList", "{", "if", "rgx", ".", "MatchString", "(", "e", ")", "{", "return", "false", "\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", ",", "\"localhost\"", ")", "\n", "p", ".", "addToEndpointList", "(", "ctx", ",", "\"127.0.0.1\"", ")", "\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", "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", "writeLen", ":=", "int64", "(", "len", "(", "p", ")", ")", "\n", "if", "writeLen", ">", "l", ".", "max", "(", ")", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"write length %d exceeds maximum file size %d\"", ",", "writeLen", ",", "l", ".", "max", "(", ")", ",", ")", "\n", "}", "\n", "if", "l", ".", "file", "==", "nil", "{", "if", "err", "=", "l", ".", "openExistingOrNew", "(", "len", "(", "p", ")", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "}", "\n", "if", "l", ".", "size", "+", "writeLen", ">", "l", ".", "max", "(", ")", "{", "if", "err", ":=", "l", ".", "rotate", "(", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "}", "\n", "n", ",", "err", "=", "l", ".", "file", ".", "Write", "(", "p", ")", "\n", "l", ".", "size", "+=", "int64", "(", "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", "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", "(", "\"error getting log file info: %s\"", ",", "err", ")", "\n", "}", "\n", "if", "info", ".", "Size", "(", ")", "+", "int64", "(", "writeLen", ")", ">=", "l", ".", "max", "(", ")", "{", "return", "l", ".", "rotate", "(", ")", "\n", "}", "\n", "file", ",", "err", ":=", "os", ".", "OpenFile", "(", "filename", ",", "os", ".", "O_APPEND", "|", "os", ".", "O_WRONLY", ",", "0644", ")", "\n", "if", "err", "!=", "nil", "{", "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", "]", ")", "+", "\"-lumberjack.log\"", "\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", "files", ",", "err", ":=", "l", ".", "oldLogFiles", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "var", "compress", ",", "remove", "[", "]", "logInfo", "\n", "if", "l", ".", "MaxBackups", ">", "0", "&&", "l", ".", "MaxBackups", "<", "len", "(", "files", ")", "{", "preserved", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "var", "remaining", "[", "]", "logInfo", "\n", "for", "_", ",", "f", ":=", "range", "files", "{", "fn", ":=", "f", ".", "Name", "(", ")", "\n", "if", "strings", ".", "HasSuffix", "(", "fn", ",", "compressSuffix", ")", "{", "fn", "=", "fn", "[", ":", "len", "(", "fn", ")", "-", "len", "(", "compressSuffix", ")", "]", "\n", "}", "\n", "preserved", "[", "fn", "]", "=", "true", "\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", "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", "if", "l", ".", "Compress", "{", "for", "_", ",", "f", ":=", "range", "files", "{", "if", "!", "strings", ".", "HasSuffix", "(", "f", ".", "Name", "(", ")", ",", "compressSuffix", ")", "{", "compress", "=", "append", "(", "compress", ",", "f", ")", "\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", "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", "(", "\"can't read log file directory: %s\"", ",", "err", ")", "\n", "}", "\n", "logFiles", ":=", "[", "]", "logInfo", "{", "}", "\n", "prefix", ",", "ext", ":=", "l", ".", "prefixAndExt", "(", ")", "\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", "}", "\n", "sort", ".", "Sort", "(", "byFormatTime", "(", "logFiles", ")", ")", "\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", "(", "\"mismatched prefix\"", ")", "\n", "}", "\n", "if", "!", "strings", ".", "HasSuffix", "(", "filename", ",", "ext", ")", "{", "return", "time", ".", "Time", "{", "}", ",", "errors", ".", "New", "(", "\"mismatched extension\"", ")", "\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", "(", "\"failed to open log file: %v\"", ",", "err", ")", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "fi", ",", "err", ":=", "os_Stat", "(", "src", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"failed to stat log file: %v\"", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "chown", "(", "dst", ",", "fi", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"failed to chown compressed log file: %v\"", ",", "err", ")", "\n", "}", "\n", "gzf", ",", "err", ":=", "os", ".", "OpenFile", "(", "dst", ",", "os", ".", "O_CREATE", "|", "os", ".", "O_TRUNC", "|", "os", ".", "O_WRONLY", ",", "fi", ".", "Mode", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"failed to open compressed log file: %v\"", ",", "err", ")", "\n", "}", "\n", "defer", "gzf", ".", "Close", "(", ")", "\n", "gz", ":=", "gzip", ".", "NewWriter", "(", "gzf", ")", "\n", "defer", "func", "(", ")", "{", "if", "err", "!=", "nil", "{", "os", ".", "Remove", "(", "dst", ")", "\n", "err", "=", "fmt", ".", "Errorf", "(", "\"failed to compress log file: %v\"", ",", "err", ")", "\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", "if", "err", ":=", "f", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "os", ".", "Remove", "(", "src", ")", ";", "err", "!=", "nil", "{", "return", "err", "\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", "if", "c", ".", "HardMaxCacheSize", ">", "0", "{", "maxShardSize", "=", "convertMBToBytes", "(", "c", ".", "HardMaxCacheSize", ")", "/", "c", ".", "Shards", "\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", "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", "(", "\"cannot marshal cache stats. error: %s\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"Content-Type\"", ",", "\"application/json; charset=utf-8\"", ")", "\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