id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
144,700
mesosphere/mesos-dns
records/generator.go
ipsTo4And6
func ipsTo4And6(allIPs []net.IP) (ips []net.IP) { var ipv4, ipv6 net.IP for _, ip := range allIPs { if ipv4 != nil && ipv6 != nil { break } else if t4 := ip.To4(); t4 != nil { if ipv4 == nil { ipv4 = t4 } } else if t6 := ip.To16(); t6 != nil { if ipv6 == nil { ipv6 = t6 } } } ips = []net.IP{} if ipv4 != nil { ips = append(ips, ipv4) } if ipv6 != nil { ips = append(ips, ipv6) } return }
go
func ipsTo4And6(allIPs []net.IP) (ips []net.IP) { var ipv4, ipv6 net.IP for _, ip := range allIPs { if ipv4 != nil && ipv6 != nil { break } else if t4 := ip.To4(); t4 != nil { if ipv4 == nil { ipv4 = t4 } } else if t6 := ip.To16(); t6 != nil { if ipv6 == nil { ipv6 = t6 } } } ips = []net.IP{} if ipv4 != nil { ips = append(ips, ipv4) } if ipv6 != nil { ips = append(ips, ipv6) } return }
[ "func", "ipsTo4And6", "(", "allIPs", "[", "]", "net", ".", "IP", ")", "(", "ips", "[", "]", "net", ".", "IP", ")", "{", "var", "ipv4", ",", "ipv6", "net", ".", "IP", "\n", "for", "_", ",", "ip", ":=", "range", "allIPs", "{", "if", "ipv4", "!=", "nil", "&&", "ipv6", "!=", "nil", "{", "break", "\n", "}", "else", "if", "t4", ":=", "ip", ".", "To4", "(", ")", ";", "t4", "!=", "nil", "{", "if", "ipv4", "==", "nil", "{", "ipv4", "=", "t4", "\n", "}", "\n", "}", "else", "if", "t6", ":=", "ip", ".", "To16", "(", ")", ";", "t6", "!=", "nil", "{", "if", "ipv6", "==", "nil", "{", "ipv6", "=", "t6", "\n", "}", "\n", "}", "\n", "}", "\n", "ips", "=", "[", "]", "net", ".", "IP", "{", "}", "\n", "if", "ipv4", "!=", "nil", "{", "ips", "=", "append", "(", "ips", ",", "ipv4", ")", "\n", "}", "\n", "if", "ipv6", "!=", "nil", "{", "ips", "=", "append", "(", "ips", ",", "ipv6", ")", "\n", "}", "\n", "return", "\n", "}" ]
// ipsTo4And6 returns a list with at most 1 ipv4 and 1 ipv6 // from a list of IPs
[ "ipsTo4And6", "returns", "a", "list", "with", "at", "most", "1", "ipv4", "and", "1", "ipv6", "from", "a", "list", "of", "IPs" ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/records/generator.go#L572-L595
144,701
mesosphere/mesos-dns
records/generator.go
hostToIPs
func hostToIPs(hostname string) (ips []net.IP) { if ip := net.ParseIP(hostname); ip != nil { ips = []net.IP{ip} } else if allIPs, err := net.LookupIP(hostname); err == nil { ips = ipsTo4And6(allIPs) } if len(ips) == 0 { logging.VeryVerbose.Printf("cannot translate hostname %q into an ipv4 or ipv6 address", hostname) } return }
go
func hostToIPs(hostname string) (ips []net.IP) { if ip := net.ParseIP(hostname); ip != nil { ips = []net.IP{ip} } else if allIPs, err := net.LookupIP(hostname); err == nil { ips = ipsTo4And6(allIPs) } if len(ips) == 0 { logging.VeryVerbose.Printf("cannot translate hostname %q into an ipv4 or ipv6 address", hostname) } return }
[ "func", "hostToIPs", "(", "hostname", "string", ")", "(", "ips", "[", "]", "net", ".", "IP", ")", "{", "if", "ip", ":=", "net", ".", "ParseIP", "(", "hostname", ")", ";", "ip", "!=", "nil", "{", "ips", "=", "[", "]", "net", ".", "IP", "{", "ip", "}", "\n", "}", "else", "if", "allIPs", ",", "err", ":=", "net", ".", "LookupIP", "(", "hostname", ")", ";", "err", "==", "nil", "{", "ips", "=", "ipsTo4And6", "(", "allIPs", ")", "\n", "}", "\n", "if", "len", "(", "ips", ")", "==", "0", "{", "logging", ".", "VeryVerbose", ".", "Printf", "(", "\"", "\"", ",", "hostname", ")", "\n", "}", "\n", "return", "\n", "}" ]
// hostToIPs attempts to parse a hostname into an ip. // If that doesn't work it will perform a lookup and try to // find one ipv4 and one ipv6 in the results.
[ "hostToIPs", "attempts", "to", "parse", "a", "hostname", "into", "an", "ip", ".", "If", "that", "doesn", "t", "work", "it", "will", "perform", "a", "lookup", "and", "try", "to", "find", "one", "ipv4", "and", "one", "ipv6", "in", "the", "results", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/records/generator.go#L600-L610
144,702
mesosphere/mesos-dns
records/generator.go
slaveIDTail
func slaveIDTail(slaveID string) string { fields := strings.Split(slaveID, "-") return strings.ToLower(fields[len(fields)-1]) }
go
func slaveIDTail(slaveID string) string { fields := strings.Split(slaveID, "-") return strings.ToLower(fields[len(fields)-1]) }
[ "func", "slaveIDTail", "(", "slaveID", "string", ")", "string", "{", "fields", ":=", "strings", ".", "Split", "(", "slaveID", ",", "\"", "\"", ")", "\n", "return", "strings", ".", "ToLower", "(", "fields", "[", "len", "(", "fields", ")", "-", "1", "]", ")", "\n", "}" ]
// return the slave number from a Mesos slave id
[ "return", "the", "slave", "number", "from", "a", "Mesos", "slave", "id" ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/records/generator.go#L613-L616
144,703
mesosphere/mesos-dns
exchanger/exchanger.go
Decorate
func Decorate(ex Exchanger, ds ...Decorator) Exchanger { decorated := ex for _, decorate := range ds { decorated = decorate(decorated) } return decorated }
go
func Decorate(ex Exchanger, ds ...Decorator) Exchanger { decorated := ex for _, decorate := range ds { decorated = decorate(decorated) } return decorated }
[ "func", "Decorate", "(", "ex", "Exchanger", ",", "ds", "...", "Decorator", ")", "Exchanger", "{", "decorated", ":=", "ex", "\n", "for", "_", ",", "decorate", ":=", "range", "ds", "{", "decorated", "=", "decorate", "(", "decorated", ")", "\n", "}", "\n", "return", "decorated", "\n", "}" ]
// Decorate decorates an Exchanger with the given Decorators.
[ "Decorate", "decorates", "an", "Exchanger", "with", "the", "given", "Decorators", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/exchanger/exchanger.go#L42-L48
144,704
mesosphere/mesos-dns
exchanger/exchanger.go
ErrorLogging
func ErrorLogging(l *log.Logger) Decorator { return func(ex Exchanger) Exchanger { return Func(func(m *dns.Msg, a string) (r *dns.Msg, rtt time.Duration, err error) { defer func() { if err != nil { l.Printf("%v: exchanging %#v with %q", err, m, a) } }() return ex.Exchange(m, a) }) } }
go
func ErrorLogging(l *log.Logger) Decorator { return func(ex Exchanger) Exchanger { return Func(func(m *dns.Msg, a string) (r *dns.Msg, rtt time.Duration, err error) { defer func() { if err != nil { l.Printf("%v: exchanging %#v with %q", err, m, a) } }() return ex.Exchange(m, a) }) } }
[ "func", "ErrorLogging", "(", "l", "*", "log", ".", "Logger", ")", "Decorator", "{", "return", "func", "(", "ex", "Exchanger", ")", "Exchanger", "{", "return", "Func", "(", "func", "(", "m", "*", "dns", ".", "Msg", ",", "a", "string", ")", "(", "r", "*", "dns", ".", "Msg", ",", "rtt", "time", ".", "Duration", ",", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "if", "err", "!=", "nil", "{", "l", ".", "Printf", "(", "\"", "\"", ",", "err", ",", "m", ",", "a", ")", "\n", "}", "\n", "}", "(", ")", "\n", "return", "ex", ".", "Exchange", "(", "m", ",", "a", ")", "\n", "}", ")", "\n", "}", "\n", "}" ]
// ErrorLogging returns a Decorator which logs an Exchanger's errors to the given // logger.
[ "ErrorLogging", "returns", "a", "Decorator", "which", "logs", "an", "Exchanger", "s", "errors", "to", "the", "given", "logger", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/exchanger/exchanger.go#L52-L63
144,705
mesosphere/mesos-dns
exchanger/exchanger.go
Instrumentation
func Instrumentation(total, success, failure logging.Counter) Decorator { return func(ex Exchanger) Exchanger { return Func(func(m *dns.Msg, a string) (r *dns.Msg, rtt time.Duration, err error) { defer func() { if total.Inc(); err != nil { failure.Inc() } else { success.Inc() } }() return ex.Exchange(m, a) }) } }
go
func Instrumentation(total, success, failure logging.Counter) Decorator { return func(ex Exchanger) Exchanger { return Func(func(m *dns.Msg, a string) (r *dns.Msg, rtt time.Duration, err error) { defer func() { if total.Inc(); err != nil { failure.Inc() } else { success.Inc() } }() return ex.Exchange(m, a) }) } }
[ "func", "Instrumentation", "(", "total", ",", "success", ",", "failure", "logging", ".", "Counter", ")", "Decorator", "{", "return", "func", "(", "ex", "Exchanger", ")", "Exchanger", "{", "return", "Func", "(", "func", "(", "m", "*", "dns", ".", "Msg", ",", "a", "string", ")", "(", "r", "*", "dns", ".", "Msg", ",", "rtt", "time", ".", "Duration", ",", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "if", "total", ".", "Inc", "(", ")", ";", "err", "!=", "nil", "{", "failure", ".", "Inc", "(", ")", "\n", "}", "else", "{", "success", ".", "Inc", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n", "return", "ex", ".", "Exchange", "(", "m", ",", "a", ")", "\n", "}", ")", "\n", "}", "\n", "}" ]
// Instrumentation returns a Decorator which instruments an Exchanger with the given // counters.
[ "Instrumentation", "returns", "a", "Decorator", "which", "instruments", "an", "Exchanger", "with", "the", "given", "counters", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/exchanger/exchanger.go#L67-L80
144,706
mesosphere/mesos-dns
httpcli/doer.go
New
func New(am AuthMechanism, cm ConfigMap, options ...Option) Doer { defaultClient := &http.Client{} for i := range options { if options[i] != nil { options[i](defaultClient) } } df, ok := factoryFor(am) if !ok { panic(fmt.Sprintf("unregistered auth mechanism %q", am)) } return df(cm, defaultClient) }
go
func New(am AuthMechanism, cm ConfigMap, options ...Option) Doer { defaultClient := &http.Client{} for i := range options { if options[i] != nil { options[i](defaultClient) } } df, ok := factoryFor(am) if !ok { panic(fmt.Sprintf("unregistered auth mechanism %q", am)) } return df(cm, defaultClient) }
[ "func", "New", "(", "am", "AuthMechanism", ",", "cm", "ConfigMap", ",", "options", "...", "Option", ")", "Doer", "{", "defaultClient", ":=", "&", "http", ".", "Client", "{", "}", "\n", "for", "i", ":=", "range", "options", "{", "if", "options", "[", "i", "]", "!=", "nil", "{", "options", "[", "i", "]", "(", "defaultClient", ")", "\n", "}", "\n", "}", "\n\n", "df", ",", "ok", ":=", "factoryFor", "(", "am", ")", "\n", "if", "!", "ok", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "am", ")", ")", "\n", "}", "\n", "return", "df", "(", "cm", ",", "defaultClient", ")", "\n", "}" ]
// New generates and returns an HTTP transactor given an optional IAM configuration and some set of // functional options.
[ "New", "generates", "and", "returns", "an", "HTTP", "transactor", "given", "an", "optional", "IAM", "configuration", "and", "some", "set", "of", "functional", "options", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/httpcli/doer.go#L38-L51
144,707
mesosphere/mesos-dns
httpcli/doer.go
Timeout
func Timeout(timeout time.Duration) Option { return func(client *http.Client) { client.Timeout = timeout } }
go
func Timeout(timeout time.Duration) Option { return func(client *http.Client) { client.Timeout = timeout } }
[ "func", "Timeout", "(", "timeout", "time", ".", "Duration", ")", "Option", "{", "return", "func", "(", "client", "*", "http", ".", "Client", ")", "{", "client", ".", "Timeout", "=", "timeout", "\n", "}", "\n", "}" ]
// Timeout returns an Option that configures client timeout
[ "Timeout", "returns", "an", "Option", "that", "configures", "client", "timeout" ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/httpcli/doer.go#L54-L58
144,708
mesosphere/mesos-dns
httpcli/doer.go
Transport
func Transport(tr http.RoundTripper) Option { return func(client *http.Client) { client.Transport = tr } }
go
func Transport(tr http.RoundTripper) Option { return func(client *http.Client) { client.Transport = tr } }
[ "func", "Transport", "(", "tr", "http", ".", "RoundTripper", ")", "Option", "{", "return", "func", "(", "client", "*", "http", ".", "Client", ")", "{", "client", ".", "Transport", "=", "tr", "\n", "}", "\n", "}" ]
// Transport returns an Option that configures client transport
[ "Transport", "returns", "an", "Option", "that", "configures", "client", "transport" ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/httpcli/doer.go#L61-L65
144,709
mesosphere/mesos-dns
httpcli/doer.go
TLSConfig
func TLSConfig(enabled bool, caPool *x509.CertPool, cert tls.Certificate) (opt urls.Option, config *tls.Config) { opt = urls.Scheme("http") if enabled { opt = urls.Scheme("https") config = &tls.Config{ Certificates: []tls.Certificate{cert}, RootCAs: caPool, InsecureSkipVerify: caPool == nil, } } return }
go
func TLSConfig(enabled bool, caPool *x509.CertPool, cert tls.Certificate) (opt urls.Option, config *tls.Config) { opt = urls.Scheme("http") if enabled { opt = urls.Scheme("https") config = &tls.Config{ Certificates: []tls.Certificate{cert}, RootCAs: caPool, InsecureSkipVerify: caPool == nil, } } return }
[ "func", "TLSConfig", "(", "enabled", "bool", ",", "caPool", "*", "x509", ".", "CertPool", ",", "cert", "tls", ".", "Certificate", ")", "(", "opt", "urls", ".", "Option", ",", "config", "*", "tls", ".", "Config", ")", "{", "opt", "=", "urls", ".", "Scheme", "(", "\"", "\"", ")", "\n", "if", "enabled", "{", "opt", "=", "urls", ".", "Scheme", "(", "\"", "\"", ")", "\n", "config", "=", "&", "tls", ".", "Config", "{", "Certificates", ":", "[", "]", "tls", ".", "Certificate", "{", "cert", "}", ",", "RootCAs", ":", "caPool", ",", "InsecureSkipVerify", ":", "caPool", "==", "nil", ",", "}", "\n", "}", "\n", "return", "\n", "}" ]
// TLSConfig generates and returns a recommended URL generation option and TLS configuration.
[ "TLSConfig", "generates", "and", "returns", "a", "recommended", "URL", "generation", "option", "and", "TLS", "configuration", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/httpcli/doer.go#L68-L79
144,710
mesosphere/mesos-dns
resolver/resolver.go
New
func New(version string, config records.Config) *Resolver { generatorOptions := []records.Option{ records.WithConfig(config), } recordGenerator := records.NewRecordGenerator(generatorOptions...) r := &Resolver{ version: version, config: config, ready: make(chan struct{}), rs: recordGenerator, // rand.Sources aren't safe for concurrent use, except the global one. // See: https://github.com/golang/go/issues/3611 rng: rand.New(&lockedSource{src: rand.NewSource(time.Now().UnixNano())}), masters: append([]string{""}, config.Masters...), generatorOptions: generatorOptions, } timeout := 5 * time.Second if config.Timeout != 0 { timeout = time.Duration(config.Timeout) * time.Second } r.zoneFwds = make(map[string]exchanger.Forwarder) if config.ExternalOn { for zone, resolvers := range config.ZoneResolvers { r.zoneFwds[zone] = exchanger.NewForwarder(resolvers, exchangers(timeout, "udp", "tcp")) } r.defaultFwd = exchanger.NewForwarder( config.Resolvers, exchangers(timeout, "udp", "tcp")) } else { r.defaultFwd = exchanger.NewForwarder( make([]string, 0), exchangers(timeout, "udp", "tcp")) } return r }
go
func New(version string, config records.Config) *Resolver { generatorOptions := []records.Option{ records.WithConfig(config), } recordGenerator := records.NewRecordGenerator(generatorOptions...) r := &Resolver{ version: version, config: config, ready: make(chan struct{}), rs: recordGenerator, // rand.Sources aren't safe for concurrent use, except the global one. // See: https://github.com/golang/go/issues/3611 rng: rand.New(&lockedSource{src: rand.NewSource(time.Now().UnixNano())}), masters: append([]string{""}, config.Masters...), generatorOptions: generatorOptions, } timeout := 5 * time.Second if config.Timeout != 0 { timeout = time.Duration(config.Timeout) * time.Second } r.zoneFwds = make(map[string]exchanger.Forwarder) if config.ExternalOn { for zone, resolvers := range config.ZoneResolvers { r.zoneFwds[zone] = exchanger.NewForwarder(resolvers, exchangers(timeout, "udp", "tcp")) } r.defaultFwd = exchanger.NewForwarder( config.Resolvers, exchangers(timeout, "udp", "tcp")) } else { r.defaultFwd = exchanger.NewForwarder( make([]string, 0), exchangers(timeout, "udp", "tcp")) } return r }
[ "func", "New", "(", "version", "string", ",", "config", "records", ".", "Config", ")", "*", "Resolver", "{", "generatorOptions", ":=", "[", "]", "records", ".", "Option", "{", "records", ".", "WithConfig", "(", "config", ")", ",", "}", "\n", "recordGenerator", ":=", "records", ".", "NewRecordGenerator", "(", "generatorOptions", "...", ")", "\n", "r", ":=", "&", "Resolver", "{", "version", ":", "version", ",", "config", ":", "config", ",", "ready", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "rs", ":", "recordGenerator", ",", "// rand.Sources aren't safe for concurrent use, except the global one.", "// See: https://github.com/golang/go/issues/3611", "rng", ":", "rand", ".", "New", "(", "&", "lockedSource", "{", "src", ":", "rand", ".", "NewSource", "(", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ")", "}", ")", ",", "masters", ":", "append", "(", "[", "]", "string", "{", "\"", "\"", "}", ",", "config", ".", "Masters", "...", ")", ",", "generatorOptions", ":", "generatorOptions", ",", "}", "\n\n", "timeout", ":=", "5", "*", "time", ".", "Second", "\n", "if", "config", ".", "Timeout", "!=", "0", "{", "timeout", "=", "time", ".", "Duration", "(", "config", ".", "Timeout", ")", "*", "time", ".", "Second", "\n", "}", "\n\n", "r", ".", "zoneFwds", "=", "make", "(", "map", "[", "string", "]", "exchanger", ".", "Forwarder", ")", "\n", "if", "config", ".", "ExternalOn", "{", "for", "zone", ",", "resolvers", ":=", "range", "config", ".", "ZoneResolvers", "{", "r", ".", "zoneFwds", "[", "zone", "]", "=", "exchanger", ".", "NewForwarder", "(", "resolvers", ",", "exchangers", "(", "timeout", ",", "\"", "\"", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "r", ".", "defaultFwd", "=", "exchanger", ".", "NewForwarder", "(", "config", ".", "Resolvers", ",", "exchangers", "(", "timeout", ",", "\"", "\"", ",", "\"", "\"", ")", ")", "\n", "}", "else", "{", "r", ".", "defaultFwd", "=", "exchanger", ".", "NewForwarder", "(", "make", "(", "[", "]", "string", ",", "0", ")", ",", "exchangers", "(", "timeout", ",", "\"", "\"", ",", "\"", "\"", ")", ")", "\n", "}", "\n\n", "return", "r", "\n", "}" ]
// New returns a Resolver with the given version and configuration.
[ "New", "returns", "a", "Resolver", "with", "the", "given", "version", "and", "configuration", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/resolver/resolver.go#L42-L77
144,711
mesosphere/mesos-dns
resolver/resolver.go
Reload
func (res *Resolver) Reload() { t := records.NewRecordGenerator(res.generatorOptions...) err := t.ParseState(res.config, res.masters...) if err == nil { timestamp := uint32(time.Now().Unix()) // may need to refactor for fairness res.rsLock.Lock() defer res.rsLock.Unlock() atomic.StoreUint32(&res.config.SOASerial, timestamp) res.rs = t select { case <-res.ready: // noop because channel is already closed default: close(res.ready) } } else { logging.Error.Printf("Warning: Error generating records: %v; keeping old DNS state", err) } logging.PrintCurLog() }
go
func (res *Resolver) Reload() { t := records.NewRecordGenerator(res.generatorOptions...) err := t.ParseState(res.config, res.masters...) if err == nil { timestamp := uint32(time.Now().Unix()) // may need to refactor for fairness res.rsLock.Lock() defer res.rsLock.Unlock() atomic.StoreUint32(&res.config.SOASerial, timestamp) res.rs = t select { case <-res.ready: // noop because channel is already closed default: close(res.ready) } } else { logging.Error.Printf("Warning: Error generating records: %v; keeping old DNS state", err) } logging.PrintCurLog() }
[ "func", "(", "res", "*", "Resolver", ")", "Reload", "(", ")", "{", "t", ":=", "records", ".", "NewRecordGenerator", "(", "res", ".", "generatorOptions", "...", ")", "\n", "err", ":=", "t", ".", "ParseState", "(", "res", ".", "config", ",", "res", ".", "masters", "...", ")", "\n\n", "if", "err", "==", "nil", "{", "timestamp", ":=", "uint32", "(", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", ")", "\n", "// may need to refactor for fairness", "res", ".", "rsLock", ".", "Lock", "(", ")", "\n", "defer", "res", ".", "rsLock", ".", "Unlock", "(", ")", "\n", "atomic", ".", "StoreUint32", "(", "&", "res", ".", "config", ".", "SOASerial", ",", "timestamp", ")", "\n", "res", ".", "rs", "=", "t", "\n", "select", "{", "case", "<-", "res", ".", "ready", ":", "// noop because channel is already closed", "default", ":", "close", "(", "res", ".", "ready", ")", "\n", "}", "\n", "}", "else", "{", "logging", ".", "Error", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "logging", ".", "PrintCurLog", "(", ")", "\n", "}" ]
// Reload triggers a new state load from the configured mesos masters. // This method is not goroutine-safe.
[ "Reload", "triggers", "a", "new", "state", "load", "from", "the", "configured", "mesos", "masters", ".", "This", "method", "is", "not", "goroutine", "-", "safe", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/resolver/resolver.go#L173-L195
144,712
mesosphere/mesos-dns
resolver/resolver.go
formatSRV
func (res *Resolver) formatSRV(name string, target string) (*dns.SRV, error) { ttl := uint32(res.config.TTL) h, port, err := net.SplitHostPort(target) if err != nil { return nil, errors.New("invalid target") } p, err := strconv.Atoi(port) if err != nil { return nil, errors.New("invalid target port") } return &dns.SRV{ Hdr: dns.RR_Header{ Name: name, Rrtype: dns.TypeSRV, Class: dns.ClassINET, Ttl: ttl, }, Priority: 0, Weight: res.config.SRVRecordDefaultWeight, Port: uint16(p), Target: h, }, nil }
go
func (res *Resolver) formatSRV(name string, target string) (*dns.SRV, error) { ttl := uint32(res.config.TTL) h, port, err := net.SplitHostPort(target) if err != nil { return nil, errors.New("invalid target") } p, err := strconv.Atoi(port) if err != nil { return nil, errors.New("invalid target port") } return &dns.SRV{ Hdr: dns.RR_Header{ Name: name, Rrtype: dns.TypeSRV, Class: dns.ClassINET, Ttl: ttl, }, Priority: 0, Weight: res.config.SRVRecordDefaultWeight, Port: uint16(p), Target: h, }, nil }
[ "func", "(", "res", "*", "Resolver", ")", "formatSRV", "(", "name", "string", ",", "target", "string", ")", "(", "*", "dns", ".", "SRV", ",", "error", ")", "{", "ttl", ":=", "uint32", "(", "res", ".", "config", ".", "TTL", ")", "\n\n", "h", ",", "port", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "target", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "p", ",", "err", ":=", "strconv", ".", "Atoi", "(", "port", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "&", "dns", ".", "SRV", "{", "Hdr", ":", "dns", ".", "RR_Header", "{", "Name", ":", "name", ",", "Rrtype", ":", "dns", ".", "TypeSRV", ",", "Class", ":", "dns", ".", "ClassINET", ",", "Ttl", ":", "ttl", ",", "}", ",", "Priority", ":", "0", ",", "Weight", ":", "res", ".", "config", ".", "SRVRecordDefaultWeight", ",", "Port", ":", "uint16", "(", "p", ")", ",", "Target", ":", "h", ",", "}", ",", "nil", "\n", "}" ]
// formatSRV returns the SRV resource record for target
[ "formatSRV", "returns", "the", "SRV", "resource", "record", "for", "target" ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/resolver/resolver.go#L198-L222
144,713
mesosphere/mesos-dns
resolver/resolver.go
formatA
func (res *Resolver) formatA(dom string, target string) (*dns.A, error) { ttl := uint32(res.config.TTL) a := net.ParseIP(target) if a == nil { return nil, errors.New("invalid target") } return &dns.A{ Hdr: dns.RR_Header{ Name: dom, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: ttl}, A: a.To4(), }, nil }
go
func (res *Resolver) formatA(dom string, target string) (*dns.A, error) { ttl := uint32(res.config.TTL) a := net.ParseIP(target) if a == nil { return nil, errors.New("invalid target") } return &dns.A{ Hdr: dns.RR_Header{ Name: dom, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: ttl}, A: a.To4(), }, nil }
[ "func", "(", "res", "*", "Resolver", ")", "formatA", "(", "dom", "string", ",", "target", "string", ")", "(", "*", "dns", ".", "A", ",", "error", ")", "{", "ttl", ":=", "uint32", "(", "res", ".", "config", ".", "TTL", ")", "\n\n", "a", ":=", "net", ".", "ParseIP", "(", "target", ")", "\n", "if", "a", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "&", "dns", ".", "A", "{", "Hdr", ":", "dns", ".", "RR_Header", "{", "Name", ":", "dom", ",", "Rrtype", ":", "dns", ".", "TypeA", ",", "Class", ":", "dns", ".", "ClassINET", ",", "Ttl", ":", "ttl", "}", ",", "A", ":", "a", ".", "To4", "(", ")", ",", "}", ",", "nil", "\n", "}" ]
// returns the A resource record for target // assumes target is a well formed IPv4 address
[ "returns", "the", "A", "resource", "record", "for", "target", "assumes", "target", "is", "a", "well", "formed", "IPv4", "address" ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/resolver/resolver.go#L226-L242
144,714
mesosphere/mesos-dns
resolver/resolver.go
formatAAAA
func (res *Resolver) formatAAAA(dom string, target string) (*dns.AAAA, error) { ttl := uint32(res.config.TTL) aaaa := net.ParseIP(target) if aaaa == nil { return nil, errors.New("invalid target") } return &dns.AAAA{ Hdr: dns.RR_Header{ Name: dom, Rrtype: dns.TypeAAAA, Class: dns.ClassINET, Ttl: ttl}, AAAA: aaaa.To16(), }, nil }
go
func (res *Resolver) formatAAAA(dom string, target string) (*dns.AAAA, error) { ttl := uint32(res.config.TTL) aaaa := net.ParseIP(target) if aaaa == nil { return nil, errors.New("invalid target") } return &dns.AAAA{ Hdr: dns.RR_Header{ Name: dom, Rrtype: dns.TypeAAAA, Class: dns.ClassINET, Ttl: ttl}, AAAA: aaaa.To16(), }, nil }
[ "func", "(", "res", "*", "Resolver", ")", "formatAAAA", "(", "dom", "string", ",", "target", "string", ")", "(", "*", "dns", ".", "AAAA", ",", "error", ")", "{", "ttl", ":=", "uint32", "(", "res", ".", "config", ".", "TTL", ")", "\n\n", "aaaa", ":=", "net", ".", "ParseIP", "(", "target", ")", "\n", "if", "aaaa", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "&", "dns", ".", "AAAA", "{", "Hdr", ":", "dns", ".", "RR_Header", "{", "Name", ":", "dom", ",", "Rrtype", ":", "dns", ".", "TypeAAAA", ",", "Class", ":", "dns", ".", "ClassINET", ",", "Ttl", ":", "ttl", "}", ",", "AAAA", ":", "aaaa", ".", "To16", "(", ")", ",", "}", ",", "nil", "\n", "}" ]
// returns the AAAA resource record for target // assumes target is a well formed IPv6 address
[ "returns", "the", "AAAA", "resource", "record", "for", "target", "assumes", "target", "is", "a", "well", "formed", "IPv6", "address" ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/resolver/resolver.go#L246-L262
144,715
mesosphere/mesos-dns
resolver/resolver.go
formatSOA
func (res *Resolver) formatSOA(dom string) *dns.SOA { ttl := uint32(res.config.TTL) return &dns.SOA{ Hdr: dns.RR_Header{ Name: dom, Rrtype: dns.TypeSOA, Class: dns.ClassINET, Ttl: ttl, }, Ns: res.config.SOAMname, Mbox: res.config.SOARname, Serial: atomic.LoadUint32(&res.config.SOASerial), Refresh: res.config.SOARefresh, Retry: res.config.SOARetry, Expire: res.config.SOAExpire, Minttl: ttl, } }
go
func (res *Resolver) formatSOA(dom string) *dns.SOA { ttl := uint32(res.config.TTL) return &dns.SOA{ Hdr: dns.RR_Header{ Name: dom, Rrtype: dns.TypeSOA, Class: dns.ClassINET, Ttl: ttl, }, Ns: res.config.SOAMname, Mbox: res.config.SOARname, Serial: atomic.LoadUint32(&res.config.SOASerial), Refresh: res.config.SOARefresh, Retry: res.config.SOARetry, Expire: res.config.SOAExpire, Minttl: ttl, } }
[ "func", "(", "res", "*", "Resolver", ")", "formatSOA", "(", "dom", "string", ")", "*", "dns", ".", "SOA", "{", "ttl", ":=", "uint32", "(", "res", ".", "config", ".", "TTL", ")", "\n\n", "return", "&", "dns", ".", "SOA", "{", "Hdr", ":", "dns", ".", "RR_Header", "{", "Name", ":", "dom", ",", "Rrtype", ":", "dns", ".", "TypeSOA", ",", "Class", ":", "dns", ".", "ClassINET", ",", "Ttl", ":", "ttl", ",", "}", ",", "Ns", ":", "res", ".", "config", ".", "SOAMname", ",", "Mbox", ":", "res", ".", "config", ".", "SOARname", ",", "Serial", ":", "atomic", ".", "LoadUint32", "(", "&", "res", ".", "config", ".", "SOASerial", ")", ",", "Refresh", ":", "res", ".", "config", ".", "SOARefresh", ",", "Retry", ":", "res", ".", "config", ".", "SOARetry", ",", "Expire", ":", "res", ".", "config", ".", "SOAExpire", ",", "Minttl", ":", "ttl", ",", "}", "\n", "}" ]
// formatSOA returns the SOA resource record for the mesos domain
[ "formatSOA", "returns", "the", "SOA", "resource", "record", "for", "the", "mesos", "domain" ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/resolver/resolver.go#L265-L283
144,716
mesosphere/mesos-dns
resolver/resolver.go
formatNS
func (res *Resolver) formatNS(dom string) *dns.NS { ttl := uint32(res.config.TTL) return &dns.NS{ Hdr: dns.RR_Header{ Name: dom, Rrtype: dns.TypeNS, Class: dns.ClassINET, Ttl: ttl, }, Ns: res.config.SOAMname, } }
go
func (res *Resolver) formatNS(dom string) *dns.NS { ttl := uint32(res.config.TTL) return &dns.NS{ Hdr: dns.RR_Header{ Name: dom, Rrtype: dns.TypeNS, Class: dns.ClassINET, Ttl: ttl, }, Ns: res.config.SOAMname, } }
[ "func", "(", "res", "*", "Resolver", ")", "formatNS", "(", "dom", "string", ")", "*", "dns", ".", "NS", "{", "ttl", ":=", "uint32", "(", "res", ".", "config", ".", "TTL", ")", "\n\n", "return", "&", "dns", ".", "NS", "{", "Hdr", ":", "dns", ".", "RR_Header", "{", "Name", ":", "dom", ",", "Rrtype", ":", "dns", ".", "TypeNS", ",", "Class", ":", "dns", ".", "ClassINET", ",", "Ttl", ":", "ttl", ",", "}", ",", "Ns", ":", "res", ".", "config", ".", "SOAMname", ",", "}", "\n", "}" ]
// formatNS returns the NS record for the mesos domain
[ "formatNS", "returns", "the", "NS", "record", "for", "the", "mesos", "domain" ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/resolver/resolver.go#L286-L298
144,717
mesosphere/mesos-dns
resolver/resolver.go
shuffleAnswers
func shuffleAnswers(rng *rand.Rand, answers []dns.RR) []dns.RR { n := len(answers) for i := 0; i < n; i++ { r := i + rng.Intn(n-i) answers[r], answers[i] = answers[i], answers[r] } return answers }
go
func shuffleAnswers(rng *rand.Rand, answers []dns.RR) []dns.RR { n := len(answers) for i := 0; i < n; i++ { r := i + rng.Intn(n-i) answers[r], answers[i] = answers[i], answers[r] } return answers }
[ "func", "shuffleAnswers", "(", "rng", "*", "rand", ".", "Rand", ",", "answers", "[", "]", "dns", ".", "RR", ")", "[", "]", "dns", ".", "RR", "{", "n", ":=", "len", "(", "answers", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "n", ";", "i", "++", "{", "r", ":=", "i", "+", "rng", ".", "Intn", "(", "n", "-", "i", ")", "\n", "answers", "[", "r", "]", ",", "answers", "[", "i", "]", "=", "answers", "[", "i", "]", ",", "answers", "[", "r", "]", "\n", "}", "\n\n", "return", "answers", "\n", "}" ]
// reorders answers for very basic load balancing
[ "reorders", "answers", "for", "very", "basic", "load", "balancing" ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/resolver/resolver.go#L301-L309
144,718
mesosphere/mesos-dns
resolver/resolver.go
HandleNonMesos
func (res *Resolver) HandleNonMesos(fwd exchanger.Forwarder) func( dns.ResponseWriter, *dns.Msg) { return func(w dns.ResponseWriter, r *dns.Msg) { logging.CurLog.NonMesosRequests.Inc() m, err := fwd(r, w.RemoteAddr().Network()) if err != nil { m = new(dns.Msg).SetRcode(r, rcode(err)) } else if len(m.Answer) == 0 { logging.CurLog.NonMesosNXDomain.Inc() } reply(w, m, res.config.SetTruncateBit) } }
go
func (res *Resolver) HandleNonMesos(fwd exchanger.Forwarder) func( dns.ResponseWriter, *dns.Msg) { return func(w dns.ResponseWriter, r *dns.Msg) { logging.CurLog.NonMesosRequests.Inc() m, err := fwd(r, w.RemoteAddr().Network()) if err != nil { m = new(dns.Msg).SetRcode(r, rcode(err)) } else if len(m.Answer) == 0 { logging.CurLog.NonMesosNXDomain.Inc() } reply(w, m, res.config.SetTruncateBit) } }
[ "func", "(", "res", "*", "Resolver", ")", "HandleNonMesos", "(", "fwd", "exchanger", ".", "Forwarder", ")", "func", "(", "dns", ".", "ResponseWriter", ",", "*", "dns", ".", "Msg", ")", "{", "return", "func", "(", "w", "dns", ".", "ResponseWriter", ",", "r", "*", "dns", ".", "Msg", ")", "{", "logging", ".", "CurLog", ".", "NonMesosRequests", ".", "Inc", "(", ")", "\n", "m", ",", "err", ":=", "fwd", "(", "r", ",", "w", ".", "RemoteAddr", "(", ")", ".", "Network", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "m", "=", "new", "(", "dns", ".", "Msg", ")", ".", "SetRcode", "(", "r", ",", "rcode", "(", "err", ")", ")", "\n", "}", "else", "if", "len", "(", "m", ".", "Answer", ")", "==", "0", "{", "logging", ".", "CurLog", ".", "NonMesosNXDomain", ".", "Inc", "(", ")", "\n", "}", "\n", "reply", "(", "w", ",", "m", ",", "res", ".", "config", ".", "SetTruncateBit", ")", "\n", "}", "\n", "}" ]
// HandleNonMesos handles non-mesos queries by forwarding to configured // external DNS servers.
[ "HandleNonMesos", "handles", "non", "-", "mesos", "queries", "by", "forwarding", "to", "configured", "external", "DNS", "servers", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/resolver/resolver.go#L313-L325
144,719
mesosphere/mesos-dns
resolver/resolver.go
reply
func reply(w dns.ResponseWriter, m *dns.Msg, setTruncateBit bool) { m.Compress = true // https://github.com/mesosphere/mesos-dns/issues/{170,173,174} maxsize := maxMsgSize(isUDP(w), m.IsEdns0()) truncate(m, maxsize, setTruncateBit) if err := w.WriteMsg(m); err != nil { logging.Error.Println(err) } }
go
func reply(w dns.ResponseWriter, m *dns.Msg, setTruncateBit bool) { m.Compress = true // https://github.com/mesosphere/mesos-dns/issues/{170,173,174} maxsize := maxMsgSize(isUDP(w), m.IsEdns0()) truncate(m, maxsize, setTruncateBit) if err := w.WriteMsg(m); err != nil { logging.Error.Println(err) } }
[ "func", "reply", "(", "w", "dns", ".", "ResponseWriter", ",", "m", "*", "dns", ".", "Msg", ",", "setTruncateBit", "bool", ")", "{", "m", ".", "Compress", "=", "true", "// https://github.com/mesosphere/mesos-dns/issues/{170,173,174}", "\n", "maxsize", ":=", "maxMsgSize", "(", "isUDP", "(", "w", ")", ",", "m", ".", "IsEdns0", "(", ")", ")", "\n", "truncate", "(", "m", ",", "maxsize", ",", "setTruncateBit", ")", "\n", "if", "err", ":=", "w", ".", "WriteMsg", "(", "m", ")", ";", "err", "!=", "nil", "{", "logging", ".", "Error", ".", "Println", "(", "err", ")", "\n", "}", "\n", "}" ]
// reply writes the given dns.Msg out to the given dns.ResponseWriter, // compressing the message first and truncating it accordingly.
[ "reply", "writes", "the", "given", "dns", ".", "Msg", "out", "to", "the", "given", "dns", ".", "ResponseWriter", "compressing", "the", "message", "first", "and", "truncating", "it", "accordingly", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/resolver/resolver.go#L495-L502
144,720
mesosphere/mesos-dns
resolver/resolver.go
isUDP
func isUDP(w dns.ResponseWriter) bool { return strings.HasPrefix(w.RemoteAddr().Network(), "udp") }
go
func isUDP(w dns.ResponseWriter) bool { return strings.HasPrefix(w.RemoteAddr().Network(), "udp") }
[ "func", "isUDP", "(", "w", "dns", ".", "ResponseWriter", ")", "bool", "{", "return", "strings", ".", "HasPrefix", "(", "w", ".", "RemoteAddr", "(", ")", ".", "Network", "(", ")", ",", "\"", "\"", ")", "\n", "}" ]
// isUDP returns true if the transmission channel in use is UDP.
[ "isUDP", "returns", "true", "if", "the", "transmission", "channel", "in", "use", "is", "UDP", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/resolver/resolver.go#L505-L507
144,721
mesosphere/mesos-dns
resolver/resolver.go
LaunchHTTP
func (res *Resolver) LaunchHTTP() <-chan error { defer util.HandleCrash() res.configureHTTP() listenAddress := net.JoinHostPort(res.config.HTTPListener, strconv.Itoa(res.config.HTTPPort)) errCh := make(chan error, 1) go func() { var err error defer func() { errCh <- err }() if err = http.ListenAndServe(listenAddress, nil); err != nil { err = fmt.Errorf("failed to setup http server: %v", err) } else { logging.Error.Println("Not serving http requests any more.") } }() return errCh }
go
func (res *Resolver) LaunchHTTP() <-chan error { defer util.HandleCrash() res.configureHTTP() listenAddress := net.JoinHostPort(res.config.HTTPListener, strconv.Itoa(res.config.HTTPPort)) errCh := make(chan error, 1) go func() { var err error defer func() { errCh <- err }() if err = http.ListenAndServe(listenAddress, nil); err != nil { err = fmt.Errorf("failed to setup http server: %v", err) } else { logging.Error.Println("Not serving http requests any more.") } }() return errCh }
[ "func", "(", "res", "*", "Resolver", ")", "LaunchHTTP", "(", ")", "<-", "chan", "error", "{", "defer", "util", ".", "HandleCrash", "(", ")", "\n\n", "res", ".", "configureHTTP", "(", ")", "\n", "listenAddress", ":=", "net", ".", "JoinHostPort", "(", "res", ".", "config", ".", "HTTPListener", ",", "strconv", ".", "Itoa", "(", "res", ".", "config", ".", "HTTPPort", ")", ")", "\n\n", "errCh", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n", "go", "func", "(", ")", "{", "var", "err", "error", "\n", "defer", "func", "(", ")", "{", "errCh", "<-", "err", "}", "(", ")", "\n\n", "if", "err", "=", "http", ".", "ListenAndServe", "(", "listenAddress", ",", "nil", ")", ";", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "else", "{", "logging", ".", "Error", ".", "Println", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "(", ")", "\n", "return", "errCh", "\n", "}" ]
// LaunchHTTP starts an HTTP server for the Resolver, returning a error channel // to which errors are asynchronously sent.
[ "LaunchHTTP", "starts", "an", "HTTP", "server", "for", "the", "Resolver", "returning", "a", "error", "channel", "to", "which", "errors", "are", "asynchronously", "sent", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/resolver/resolver.go#L604-L622
144,722
mesosphere/mesos-dns
resolver/resolver.go
RestConfig
func (res *Resolver) RestConfig(req *restful.Request, resp *restful.Response) { if err := resp.WriteAsJson(res.config); err != nil { logging.Error.Println(err) } }
go
func (res *Resolver) RestConfig(req *restful.Request, resp *restful.Response) { if err := resp.WriteAsJson(res.config); err != nil { logging.Error.Println(err) } }
[ "func", "(", "res", "*", "Resolver", ")", "RestConfig", "(", "req", "*", "restful", ".", "Request", ",", "resp", "*", "restful", ".", "Response", ")", "{", "if", "err", ":=", "resp", ".", "WriteAsJson", "(", "res", ".", "config", ")", ";", "err", "!=", "nil", "{", "logging", ".", "Error", ".", "Println", "(", "err", ")", "\n", "}", "\n", "}" ]
// RestConfig handles HTTP requests of Resolver configuration.
[ "RestConfig", "handles", "HTTP", "requests", "of", "Resolver", "configuration", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/resolver/resolver.go#L625-L629
144,723
mesosphere/mesos-dns
resolver/resolver.go
RestEnumerate
func (res *Resolver) RestEnumerate(req *restful.Request, resp *restful.Response) { enumData := res.records().EnumData if err := resp.WriteAsJson(enumData); err != nil { logging.Error.Println(err) } }
go
func (res *Resolver) RestEnumerate(req *restful.Request, resp *restful.Response) { enumData := res.records().EnumData if err := resp.WriteAsJson(enumData); err != nil { logging.Error.Println(err) } }
[ "func", "(", "res", "*", "Resolver", ")", "RestEnumerate", "(", "req", "*", "restful", ".", "Request", ",", "resp", "*", "restful", ".", "Response", ")", "{", "enumData", ":=", "res", ".", "records", "(", ")", ".", "EnumData", "\n", "if", "err", ":=", "resp", ".", "WriteAsJson", "(", "enumData", ")", ";", "err", "!=", "nil", "{", "logging", ".", "Error", ".", "Println", "(", "err", ")", "\n", "}", "\n", "}" ]
// RestEnumerate handles HTTP requests of the enumeration data
[ "RestEnumerate", "handles", "HTTP", "requests", "of", "the", "enumeration", "data" ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/resolver/resolver.go#L632-L638
144,724
mesosphere/mesos-dns
resolver/resolver.go
RestAXFR
func (res *Resolver) RestAXFR(req *restful.Request, resp *restful.Response) { records := res.records() AXFRRecords := models.AXFRRecords{ SRVs: records.SRVs.ToAXFRResourceRecordSet(), As: records.As.ToAXFRResourceRecordSet(), AAAAs: records.AAAAs.ToAXFRResourceRecordSet(), } AXFR := models.AXFR{ Records: AXFRRecords, Serial: atomic.LoadUint32(&res.config.SOASerial), Mname: res.config.SOAMname, Rname: res.config.SOARname, TTL: res.config.TTL, RefreshSeconds: res.config.RefreshSeconds, Domain: res.config.Domain, } if err := resp.WriteAsJson(AXFR); err != nil { logging.Error.Println(err) } }
go
func (res *Resolver) RestAXFR(req *restful.Request, resp *restful.Response) { records := res.records() AXFRRecords := models.AXFRRecords{ SRVs: records.SRVs.ToAXFRResourceRecordSet(), As: records.As.ToAXFRResourceRecordSet(), AAAAs: records.AAAAs.ToAXFRResourceRecordSet(), } AXFR := models.AXFR{ Records: AXFRRecords, Serial: atomic.LoadUint32(&res.config.SOASerial), Mname: res.config.SOAMname, Rname: res.config.SOARname, TTL: res.config.TTL, RefreshSeconds: res.config.RefreshSeconds, Domain: res.config.Domain, } if err := resp.WriteAsJson(AXFR); err != nil { logging.Error.Println(err) } }
[ "func", "(", "res", "*", "Resolver", ")", "RestAXFR", "(", "req", "*", "restful", ".", "Request", ",", "resp", "*", "restful", ".", "Response", ")", "{", "records", ":=", "res", ".", "records", "(", ")", "\n\n", "AXFRRecords", ":=", "models", ".", "AXFRRecords", "{", "SRVs", ":", "records", ".", "SRVs", ".", "ToAXFRResourceRecordSet", "(", ")", ",", "As", ":", "records", ".", "As", ".", "ToAXFRResourceRecordSet", "(", ")", ",", "AAAAs", ":", "records", ".", "AAAAs", ".", "ToAXFRResourceRecordSet", "(", ")", ",", "}", "\n", "AXFR", ":=", "models", ".", "AXFR", "{", "Records", ":", "AXFRRecords", ",", "Serial", ":", "atomic", ".", "LoadUint32", "(", "&", "res", ".", "config", ".", "SOASerial", ")", ",", "Mname", ":", "res", ".", "config", ".", "SOAMname", ",", "Rname", ":", "res", ".", "config", ".", "SOARname", ",", "TTL", ":", "res", ".", "config", ".", "TTL", ",", "RefreshSeconds", ":", "res", ".", "config", ".", "RefreshSeconds", ",", "Domain", ":", "res", ".", "config", ".", "Domain", ",", "}", "\n\n", "if", "err", ":=", "resp", ".", "WriteAsJson", "(", "AXFR", ")", ";", "err", "!=", "nil", "{", "logging", ".", "Error", ".", "Println", "(", "err", ")", "\n", "}", "\n", "}" ]
// RestAXFR handles HTTP requests to turn the zone into a transferable format
[ "RestAXFR", "handles", "HTTP", "requests", "to", "turn", "the", "zone", "into", "a", "transferable", "format" ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/resolver/resolver.go#L641-L662
144,725
mesosphere/mesos-dns
resolver/resolver.go
RestVersion
func (res *Resolver) RestVersion(req *restful.Request, resp *restful.Response) { err := resp.WriteAsJson(map[string]string{ "Service": "Mesos-DNS", "Version": res.version, "URL": "https://github.com/mesosphere/mesos-dns", }) if err != nil { logging.Error.Println(err) } }
go
func (res *Resolver) RestVersion(req *restful.Request, resp *restful.Response) { err := resp.WriteAsJson(map[string]string{ "Service": "Mesos-DNS", "Version": res.version, "URL": "https://github.com/mesosphere/mesos-dns", }) if err != nil { logging.Error.Println(err) } }
[ "func", "(", "res", "*", "Resolver", ")", "RestVersion", "(", "req", "*", "restful", ".", "Request", ",", "resp", "*", "restful", ".", "Response", ")", "{", "err", ":=", "resp", ".", "WriteAsJson", "(", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "res", ".", "version", ",", "\"", "\"", ":", "\"", "\"", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "Error", ".", "Println", "(", "err", ")", "\n", "}", "\n", "}" ]
// RestVersion handles HTTP requests of Mesos-DNS version.
[ "RestVersion", "handles", "HTTP", "requests", "of", "Mesos", "-", "DNS", "version", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/resolver/resolver.go#L665-L674
144,726
mesosphere/mesos-dns
resolver/resolver.go
RestHost
func (res *Resolver) RestHost(req *restful.Request, resp *restful.Response) { host := req.PathParameter("host") // clean up host name dom := strings.ToLower(cleanWild(host)) if dom[len(dom)-1] != '.' { dom += "." } rs := res.records() type record struct { Host string `json:"host"` IP string `json:"ip"` } aRRs := rs.As[dom] aaaaRRs := rs.AAAAs[dom] records := make([]record, 0, len(aRRs)+len(aaaaRRs)) for ip := range aRRs { records = append(records, record{dom, ip}) } for ip := range aaaaRRs { records = append(records, record{dom, ip}) } if len(records) == 0 { records = append(records, record{}) } if err := resp.WriteAsJson(records); err != nil { logging.Error.Println(err) } stats(dom, res.config.Domain+".", len(aRRs) > 0) }
go
func (res *Resolver) RestHost(req *restful.Request, resp *restful.Response) { host := req.PathParameter("host") // clean up host name dom := strings.ToLower(cleanWild(host)) if dom[len(dom)-1] != '.' { dom += "." } rs := res.records() type record struct { Host string `json:"host"` IP string `json:"ip"` } aRRs := rs.As[dom] aaaaRRs := rs.AAAAs[dom] records := make([]record, 0, len(aRRs)+len(aaaaRRs)) for ip := range aRRs { records = append(records, record{dom, ip}) } for ip := range aaaaRRs { records = append(records, record{dom, ip}) } if len(records) == 0 { records = append(records, record{}) } if err := resp.WriteAsJson(records); err != nil { logging.Error.Println(err) } stats(dom, res.config.Domain+".", len(aRRs) > 0) }
[ "func", "(", "res", "*", "Resolver", ")", "RestHost", "(", "req", "*", "restful", ".", "Request", ",", "resp", "*", "restful", ".", "Response", ")", "{", "host", ":=", "req", ".", "PathParameter", "(", "\"", "\"", ")", "\n", "// clean up host name", "dom", ":=", "strings", ".", "ToLower", "(", "cleanWild", "(", "host", ")", ")", "\n", "if", "dom", "[", "len", "(", "dom", ")", "-", "1", "]", "!=", "'.'", "{", "dom", "+=", "\"", "\"", "\n", "}", "\n", "rs", ":=", "res", ".", "records", "(", ")", "\n\n", "type", "record", "struct", "{", "Host", "string", "`json:\"host\"`", "\n", "IP", "string", "`json:\"ip\"`", "\n", "}", "\n\n", "aRRs", ":=", "rs", ".", "As", "[", "dom", "]", "\n", "aaaaRRs", ":=", "rs", ".", "AAAAs", "[", "dom", "]", "\n", "records", ":=", "make", "(", "[", "]", "record", ",", "0", ",", "len", "(", "aRRs", ")", "+", "len", "(", "aaaaRRs", ")", ")", "\n", "for", "ip", ":=", "range", "aRRs", "{", "records", "=", "append", "(", "records", ",", "record", "{", "dom", ",", "ip", "}", ")", "\n", "}", "\n", "for", "ip", ":=", "range", "aaaaRRs", "{", "records", "=", "append", "(", "records", ",", "record", "{", "dom", ",", "ip", "}", ")", "\n", "}", "\n\n", "if", "len", "(", "records", ")", "==", "0", "{", "records", "=", "append", "(", "records", ",", "record", "{", "}", ")", "\n", "}", "\n\n", "if", "err", ":=", "resp", ".", "WriteAsJson", "(", "records", ")", ";", "err", "!=", "nil", "{", "logging", ".", "Error", ".", "Println", "(", "err", ")", "\n", "}", "\n\n", "stats", "(", "dom", ",", "res", ".", "config", ".", "Domain", "+", "\"", "\"", ",", "len", "(", "aRRs", ")", ">", "0", ")", "\n", "}" ]
// RestHost handles HTTP requests of DNS A records of the given host.
[ "RestHost", "handles", "HTTP", "requests", "of", "DNS", "A", "records", "of", "the", "given", "host", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/resolver/resolver.go#L677-L710
144,727
mesosphere/mesos-dns
resolver/resolver.go
RestPorts
func (res *Resolver) RestPorts(req *restful.Request, resp *restful.Response) { err := resp.WriteErrorString(http.StatusNotImplemented, "To be implemented...") if err != nil { logging.Error.Println(err) } }
go
func (res *Resolver) RestPorts(req *restful.Request, resp *restful.Response) { err := resp.WriteErrorString(http.StatusNotImplemented, "To be implemented...") if err != nil { logging.Error.Println(err) } }
[ "func", "(", "res", "*", "Resolver", ")", "RestPorts", "(", "req", "*", "restful", ".", "Request", ",", "resp", "*", "restful", ".", "Response", ")", "{", "err", ":=", "resp", ".", "WriteErrorString", "(", "http", ".", "StatusNotImplemented", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "Error", ".", "Println", "(", "err", ")", "\n", "}", "\n", "}" ]
// RestPorts is an HTTP handler which is currently not implemented.
[ "RestPorts", "is", "an", "HTTP", "handler", "which", "is", "currently", "not", "implemented", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/resolver/resolver.go#L727-L732
144,728
mesosphere/mesos-dns
resolver/resolver.go
RestService
func (res *Resolver) RestService(req *restful.Request, resp *restful.Response) { service := req.PathParameter("service") // clean up service name dom := strings.ToLower(cleanWild(service)) if dom[len(dom)-1] != '.' { dom += "." } rs := res.records() type record struct { Service string `json:"service"` Host string `json:"host"` IP string `json:"ip"` Port string `json:"port"` } srvRRs := rs.SRVs[dom] records := make([]record, 0, len(srvRRs)) for s := range srvRRs { host, port, err := net.SplitHostPort(s) if err != nil { logging.Error.Println(err) continue } if aR, aOk := rs.As.First(host); aOk { records = append(records, record{service, host, aR, port}) } if aaaaR, aaaaOk := rs.AAAAs.First(host); aaaaOk { records = append(records, record{service, host, aaaaR, port}) } } if len(records) == 0 { records = append(records, record{}) } if err := resp.WriteAsJson(records); err != nil { logging.Error.Println(err) } stats(dom, res.config.Domain+".", len(srvRRs) > 0) }
go
func (res *Resolver) RestService(req *restful.Request, resp *restful.Response) { service := req.PathParameter("service") // clean up service name dom := strings.ToLower(cleanWild(service)) if dom[len(dom)-1] != '.' { dom += "." } rs := res.records() type record struct { Service string `json:"service"` Host string `json:"host"` IP string `json:"ip"` Port string `json:"port"` } srvRRs := rs.SRVs[dom] records := make([]record, 0, len(srvRRs)) for s := range srvRRs { host, port, err := net.SplitHostPort(s) if err != nil { logging.Error.Println(err) continue } if aR, aOk := rs.As.First(host); aOk { records = append(records, record{service, host, aR, port}) } if aaaaR, aaaaOk := rs.AAAAs.First(host); aaaaOk { records = append(records, record{service, host, aaaaR, port}) } } if len(records) == 0 { records = append(records, record{}) } if err := resp.WriteAsJson(records); err != nil { logging.Error.Println(err) } stats(dom, res.config.Domain+".", len(srvRRs) > 0) }
[ "func", "(", "res", "*", "Resolver", ")", "RestService", "(", "req", "*", "restful", ".", "Request", ",", "resp", "*", "restful", ".", "Response", ")", "{", "service", ":=", "req", ".", "PathParameter", "(", "\"", "\"", ")", "\n", "// clean up service name", "dom", ":=", "strings", ".", "ToLower", "(", "cleanWild", "(", "service", ")", ")", "\n", "if", "dom", "[", "len", "(", "dom", ")", "-", "1", "]", "!=", "'.'", "{", "dom", "+=", "\"", "\"", "\n", "}", "\n", "rs", ":=", "res", ".", "records", "(", ")", "\n\n", "type", "record", "struct", "{", "Service", "string", "`json:\"service\"`", "\n", "Host", "string", "`json:\"host\"`", "\n", "IP", "string", "`json:\"ip\"`", "\n", "Port", "string", "`json:\"port\"`", "\n", "}", "\n\n", "srvRRs", ":=", "rs", ".", "SRVs", "[", "dom", "]", "\n", "records", ":=", "make", "(", "[", "]", "record", ",", "0", ",", "len", "(", "srvRRs", ")", ")", "\n", "for", "s", ":=", "range", "srvRRs", "{", "host", ",", "port", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "Error", ".", "Println", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "if", "aR", ",", "aOk", ":=", "rs", ".", "As", ".", "First", "(", "host", ")", ";", "aOk", "{", "records", "=", "append", "(", "records", ",", "record", "{", "service", ",", "host", ",", "aR", ",", "port", "}", ")", "\n", "}", "\n", "if", "aaaaR", ",", "aaaaOk", ":=", "rs", ".", "AAAAs", ".", "First", "(", "host", ")", ";", "aaaaOk", "{", "records", "=", "append", "(", "records", ",", "record", "{", "service", ",", "host", ",", "aaaaR", ",", "port", "}", ")", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "records", ")", "==", "0", "{", "records", "=", "append", "(", "records", ",", "record", "{", "}", ")", "\n", "}", "\n\n", "if", "err", ":=", "resp", ".", "WriteAsJson", "(", "records", ")", ";", "err", "!=", "nil", "{", "logging", ".", "Error", ".", "Println", "(", "err", ")", "\n", "}", "\n\n", "stats", "(", "dom", ",", "res", ".", "config", ".", "Domain", "+", "\"", "\"", ",", "len", "(", "srvRRs", ")", ">", "0", ")", "\n", "}" ]
// RestService handles HTTP requests of DNS SRV records for the given name.
[ "RestService", "handles", "HTTP", "requests", "of", "DNS", "SRV", "records", "for", "the", "given", "name", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/resolver/resolver.go#L735-L776
144,729
mesosphere/mesos-dns
resolver/resolver.go
panicRecover
func panicRecover(f func(w dns.ResponseWriter, r *dns.Msg)) func(w dns.ResponseWriter, r *dns.Msg) { return func(w dns.ResponseWriter, r *dns.Msg) { defer func() { if rec := recover(); rec != nil { m := new(dns.Msg) m.SetRcode(r, 2) if err := w.WriteMsg(m); err != nil { logging.Error.Println(err) } logging.Error.Println(rec) } }() f(w, r) } }
go
func panicRecover(f func(w dns.ResponseWriter, r *dns.Msg)) func(w dns.ResponseWriter, r *dns.Msg) { return func(w dns.ResponseWriter, r *dns.Msg) { defer func() { if rec := recover(); rec != nil { m := new(dns.Msg) m.SetRcode(r, 2) if err := w.WriteMsg(m); err != nil { logging.Error.Println(err) } logging.Error.Println(rec) } }() f(w, r) } }
[ "func", "panicRecover", "(", "f", "func", "(", "w", "dns", ".", "ResponseWriter", ",", "r", "*", "dns", ".", "Msg", ")", ")", "func", "(", "w", "dns", ".", "ResponseWriter", ",", "r", "*", "dns", ".", "Msg", ")", "{", "return", "func", "(", "w", "dns", ".", "ResponseWriter", ",", "r", "*", "dns", ".", "Msg", ")", "{", "defer", "func", "(", ")", "{", "if", "rec", ":=", "recover", "(", ")", ";", "rec", "!=", "nil", "{", "m", ":=", "new", "(", "dns", ".", "Msg", ")", "\n", "m", ".", "SetRcode", "(", "r", ",", "2", ")", "\n", "if", "err", ":=", "w", ".", "WriteMsg", "(", "m", ")", ";", "err", "!=", "nil", "{", "logging", ".", "Error", ".", "Println", "(", "err", ")", "\n", "}", "\n", "logging", ".", "Error", ".", "Println", "(", "rec", ")", "\n", "}", "\n", "}", "(", ")", "\n", "f", "(", "w", ",", "r", ")", "\n", "}", "\n", "}" ]
// panicRecover catches any panics from the resolvers and sets an error // code of server failure
[ "panicRecover", "catches", "any", "panics", "from", "the", "resolvers", "and", "sets", "an", "error", "code", "of", "server", "failure" ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/resolver/resolver.go#L780-L794
144,730
mesosphere/mesos-dns
resolver/resolver.go
cleanWild
func cleanWild(name string) string { if strings.Contains(name, ".*") { return strings.Replace(name, ".*", "", -1) } return name }
go
func cleanWild(name string) string { if strings.Contains(name, ".*") { return strings.Replace(name, ".*", "", -1) } return name }
[ "func", "cleanWild", "(", "name", "string", ")", "string", "{", "if", "strings", ".", "Contains", "(", "name", ",", "\"", "\"", ")", "{", "return", "strings", ".", "Replace", "(", "name", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "}", "\n", "return", "name", "\n", "}" ]
// cleanWild strips any wildcards out thus mapping cleanly to the // original serviceName
[ "cleanWild", "strips", "any", "wildcards", "out", "thus", "mapping", "cleanly", "to", "the", "original", "serviceName" ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/resolver/resolver.go#L798-L803
144,731
mesosphere/mesos-dns
urls/urls.go
With
func (b Builder) With(options ...Option) Builder { for i := range options { if options[i] != nil { options[i](&b) } } return b }
go
func (b Builder) With(options ...Option) Builder { for i := range options { if options[i] != nil { options[i](&b) } } return b }
[ "func", "(", "b", "Builder", ")", "With", "(", "options", "...", "Option", ")", "Builder", "{", "for", "i", ":=", "range", "options", "{", "if", "options", "[", "i", "]", "!=", "nil", "{", "options", "[", "i", "]", "(", "&", "b", ")", "\n", "}", "\n", "}", "\n", "return", "b", "\n", "}" ]
// With configures a net.URL via a Builder wrapper, returns the modified result
[ "With", "configures", "a", "net", ".", "URL", "via", "a", "Builder", "wrapper", "returns", "the", "modified", "result" ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/urls/urls.go#L17-L24
144,732
mesosphere/mesos-dns
httpcli/basic/basic.go
Register
func Register() { httpcli.Register(httpcli.AuthBasic, httpcli.DoerFactory(func(cm httpcli.ConfigMap, c *http.Client) (doer httpcli.Doer) { obj := cm.FindOrPanic(httpcli.AuthBasic) config, ok := obj.(Credentials) if !ok { panic(fmt.Errorf("expected Credentials instead of %#+v", obj)) } validate(config) if c != nil { doer = Doer(c, config) } return })) }
go
func Register() { httpcli.Register(httpcli.AuthBasic, httpcli.DoerFactory(func(cm httpcli.ConfigMap, c *http.Client) (doer httpcli.Doer) { obj := cm.FindOrPanic(httpcli.AuthBasic) config, ok := obj.(Credentials) if !ok { panic(fmt.Errorf("expected Credentials instead of %#+v", obj)) } validate(config) if c != nil { doer = Doer(c, config) } return })) }
[ "func", "Register", "(", ")", "{", "httpcli", ".", "Register", "(", "httpcli", ".", "AuthBasic", ",", "httpcli", ".", "DoerFactory", "(", "func", "(", "cm", "httpcli", ".", "ConfigMap", ",", "c", "*", "http", ".", "Client", ")", "(", "doer", "httpcli", ".", "Doer", ")", "{", "obj", ":=", "cm", ".", "FindOrPanic", "(", "httpcli", ".", "AuthBasic", ")", "\n", "config", ",", "ok", ":=", "obj", ".", "(", "Credentials", ")", "\n", "if", "!", "ok", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "obj", ")", ")", "\n", "}", "\n", "validate", "(", "config", ")", "\n", "if", "c", "!=", "nil", "{", "doer", "=", "Doer", "(", "c", ",", "config", ")", "\n", "}", "\n", "return", "\n", "}", ")", ")", "\n", "}" ]
// Register registers a DoerFactory for HTTP Basic authentication
[ "Register", "registers", "a", "DoerFactory", "for", "HTTP", "Basic", "authentication" ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/httpcli/basic/basic.go#L11-L24
144,733
mesosphere/mesos-dns
httpcli/basic/basic.go
Doer
func Doer(client httpcli.Doer, credentials Credentials) httpcli.Doer { return httpcli.DoerFunc(func(req *http.Request) (*http.Response, error) { req.SetBasicAuth(credentials.Principal, credentials.Secret) return client.Do(req) }) }
go
func Doer(client httpcli.Doer, credentials Credentials) httpcli.Doer { return httpcli.DoerFunc(func(req *http.Request) (*http.Response, error) { req.SetBasicAuth(credentials.Principal, credentials.Secret) return client.Do(req) }) }
[ "func", "Doer", "(", "client", "httpcli", ".", "Doer", ",", "credentials", "Credentials", ")", "httpcli", ".", "Doer", "{", "return", "httpcli", ".", "DoerFunc", "(", "func", "(", "req", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "req", ".", "SetBasicAuth", "(", "credentials", ".", "Principal", ",", "credentials", ".", "Secret", ")", "\n", "return", "client", ".", "Do", "(", "req", ")", "\n", "}", ")", "\n", "}" ]
// Doer wraps an HTTP transactor given basic credentials
[ "Doer", "wraps", "an", "HTTP", "transactor", "given", "basic", "credentials" ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/httpcli/basic/basic.go#L33-L38
144,734
mesosphere/mesos-dns
httpcli/config.go
ToConfigMap
func (cmo ConfigMapOptions) ToConfigMap() (m ConfigMap) { m = make(ConfigMap) for _, opt := range cmo { if opt != nil { opt(m) } } if len(m) == 0 { m = nil } return m }
go
func (cmo ConfigMapOptions) ToConfigMap() (m ConfigMap) { m = make(ConfigMap) for _, opt := range cmo { if opt != nil { opt(m) } } if len(m) == 0 { m = nil } return m }
[ "func", "(", "cmo", "ConfigMapOptions", ")", "ToConfigMap", "(", ")", "(", "m", "ConfigMap", ")", "{", "m", "=", "make", "(", "ConfigMap", ")", "\n", "for", "_", ",", "opt", ":=", "range", "cmo", "{", "if", "opt", "!=", "nil", "{", "opt", "(", "m", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "m", ")", "==", "0", "{", "m", "=", "nil", "\n", "}", "\n", "return", "m", "\n", "}" ]
// ToConfigMap generates a ConfigMap from the given options. If no map entries are generated // then a nil ConfigMap is returned.
[ "ToConfigMap", "generates", "a", "ConfigMap", "from", "the", "given", "options", ".", "If", "no", "map", "entries", "are", "generated", "then", "a", "nil", "ConfigMap", "is", "returned", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/httpcli/config.go#L63-L74
144,735
mesosphere/mesos-dns
httpcli/config.go
FindOrPanic
func (cm ConfigMap) FindOrPanic(am AuthMechanism) interface{} { obj, ok := cm[am] if !ok { panic(ErrMissingConfiguration) } return obj }
go
func (cm ConfigMap) FindOrPanic(am AuthMechanism) interface{} { obj, ok := cm[am] if !ok { panic(ErrMissingConfiguration) } return obj }
[ "func", "(", "cm", "ConfigMap", ")", "FindOrPanic", "(", "am", "AuthMechanism", ")", "interface", "{", "}", "{", "obj", ",", "ok", ":=", "cm", "[", "am", "]", "\n", "if", "!", "ok", "{", "panic", "(", "ErrMissingConfiguration", ")", "\n", "}", "\n", "return", "obj", "\n", "}" ]
// FindOrPanic returns the mapped configuration for the given auth mechanism or else panics
[ "FindOrPanic", "returns", "the", "mapped", "configuration", "for", "the", "given", "auth", "mechanism", "or", "else", "panics" ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/httpcli/config.go#L77-L83
144,736
mesosphere/mesos-dns
httpcli/config.go
Register
func Register(am AuthMechanism, df DoerFactory) { registry.Lock() defer registry.Unlock() if _, ok := registry.factories[am]; ok { panic(ErrDuplicateAuthRegistration) } registry.factories[am] = df }
go
func Register(am AuthMechanism, df DoerFactory) { registry.Lock() defer registry.Unlock() if _, ok := registry.factories[am]; ok { panic(ErrDuplicateAuthRegistration) } registry.factories[am] = df }
[ "func", "Register", "(", "am", "AuthMechanism", ",", "df", "DoerFactory", ")", "{", "registry", ".", "Lock", "(", ")", "\n", "defer", "registry", ".", "Unlock", "(", ")", "\n\n", "if", "_", ",", "ok", ":=", "registry", ".", "factories", "[", "am", "]", ";", "ok", "{", "panic", "(", "ErrDuplicateAuthRegistration", ")", "\n", "}", "\n", "registry", ".", "factories", "[", "am", "]", "=", "df", "\n", "}" ]
// Register associates an AuthMechanism with a DoerFactory
[ "Register", "associates", "an", "AuthMechanism", "with", "a", "DoerFactory" ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/httpcli/config.go#L86-L94
144,737
mesosphere/mesos-dns
httpcli/config.go
Validate
func Validate(am AuthMechanism, cm ConfigMap) (err error) { df, ok := factoryFor(am) if !ok { err = ErrUnregisteredFactory } else { defer func() { // recover from a factory panic if v := recover(); v != nil { if verr, ok := v.(error); ok { err = verr } else { panic(v) // unexpected, forward this up the stack } } }() if shouldBeNil := df(cm, nil); shouldBeNil != nil { err = ErrIllegalDoerFactoryImplementation } } return }
go
func Validate(am AuthMechanism, cm ConfigMap) (err error) { df, ok := factoryFor(am) if !ok { err = ErrUnregisteredFactory } else { defer func() { // recover from a factory panic if v := recover(); v != nil { if verr, ok := v.(error); ok { err = verr } else { panic(v) // unexpected, forward this up the stack } } }() if shouldBeNil := df(cm, nil); shouldBeNil != nil { err = ErrIllegalDoerFactoryImplementation } } return }
[ "func", "Validate", "(", "am", "AuthMechanism", ",", "cm", "ConfigMap", ")", "(", "err", "error", ")", "{", "df", ",", "ok", ":=", "factoryFor", "(", "am", ")", "\n", "if", "!", "ok", "{", "err", "=", "ErrUnregisteredFactory", "\n", "}", "else", "{", "defer", "func", "(", ")", "{", "// recover from a factory panic", "if", "v", ":=", "recover", "(", ")", ";", "v", "!=", "nil", "{", "if", "verr", ",", "ok", ":=", "v", ".", "(", "error", ")", ";", "ok", "{", "err", "=", "verr", "\n", "}", "else", "{", "panic", "(", "v", ")", "// unexpected, forward this up the stack", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "if", "shouldBeNil", ":=", "df", "(", "cm", ",", "nil", ")", ";", "shouldBeNil", "!=", "nil", "{", "err", "=", "ErrIllegalDoerFactoryImplementation", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// Validate checks that the given AuthMechainsm and ConfigMap are compatible with the // registered set of DoerFactory instances.
[ "Validate", "checks", "that", "the", "given", "AuthMechainsm", "and", "ConfigMap", "are", "compatible", "with", "the", "registered", "set", "of", "DoerFactory", "instances", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/httpcli/config.go#L113-L133
144,738
mesosphere/mesos-dns
logging/logging.go
String
func (lc *LogCounter) String() string { return strconv.FormatUint(atomic.LoadUint64(&lc.value), 10) }
go
func (lc *LogCounter) String() string { return strconv.FormatUint(atomic.LoadUint64(&lc.value), 10) }
[ "func", "(", "lc", "*", "LogCounter", ")", "String", "(", ")", "string", "{", "return", "strconv", ".", "FormatUint", "(", "atomic", ".", "LoadUint64", "(", "&", "lc", ".", "value", ")", ",", "10", ")", "\n", "}" ]
// String returns a string represention of the counter.
[ "String", "returns", "a", "string", "represention", "of", "the", "counter", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/logging/logging.go#L43-L45
144,739
mesosphere/mesos-dns
logging/logging.go
SetupLogs
func SetupLogs() { // initialize logging flags if glog.V(2) { VeryVerboseFlag = true } else if glog.V(1) { VerboseFlag = true } logopts := log.Ldate | log.Ltime | log.Lshortfile if VerboseFlag { Verbose = log.New(os.Stdout, "VERBOSE: ", logopts) VeryVerbose = log.New(ioutil.Discard, "VERY VERBOSE: ", logopts) } else if VeryVerboseFlag { Verbose = log.New(os.Stdout, "VERY VERBOSE: ", logopts) VeryVerbose = Verbose } else { Verbose = log.New(ioutil.Discard, "VERBOSE: ", logopts) VeryVerbose = log.New(ioutil.Discard, "VERY VERBOSE: ", logopts) } Error = log.New(os.Stderr, "ERROR: ", logopts) }
go
func SetupLogs() { // initialize logging flags if glog.V(2) { VeryVerboseFlag = true } else if glog.V(1) { VerboseFlag = true } logopts := log.Ldate | log.Ltime | log.Lshortfile if VerboseFlag { Verbose = log.New(os.Stdout, "VERBOSE: ", logopts) VeryVerbose = log.New(ioutil.Discard, "VERY VERBOSE: ", logopts) } else if VeryVerboseFlag { Verbose = log.New(os.Stdout, "VERY VERBOSE: ", logopts) VeryVerbose = Verbose } else { Verbose = log.New(ioutil.Discard, "VERBOSE: ", logopts) VeryVerbose = log.New(ioutil.Discard, "VERY VERBOSE: ", logopts) } Error = log.New(os.Stderr, "ERROR: ", logopts) }
[ "func", "SetupLogs", "(", ")", "{", "// initialize logging flags", "if", "glog", ".", "V", "(", "2", ")", "{", "VeryVerboseFlag", "=", "true", "\n", "}", "else", "if", "glog", ".", "V", "(", "1", ")", "{", "VerboseFlag", "=", "true", "\n", "}", "\n\n", "logopts", ":=", "log", ".", "Ldate", "|", "log", ".", "Ltime", "|", "log", ".", "Lshortfile", "\n\n", "if", "VerboseFlag", "{", "Verbose", "=", "log", ".", "New", "(", "os", ".", "Stdout", ",", "\"", "\"", ",", "logopts", ")", "\n", "VeryVerbose", "=", "log", ".", "New", "(", "ioutil", ".", "Discard", ",", "\"", "\"", ",", "logopts", ")", "\n", "}", "else", "if", "VeryVerboseFlag", "{", "Verbose", "=", "log", ".", "New", "(", "os", ".", "Stdout", ",", "\"", "\"", ",", "logopts", ")", "\n", "VeryVerbose", "=", "Verbose", "\n", "}", "else", "{", "Verbose", "=", "log", ".", "New", "(", "ioutil", ".", "Discard", ",", "\"", "\"", ",", "logopts", ")", "\n", "VeryVerbose", "=", "log", ".", "New", "(", "ioutil", ".", "Discard", ",", "\"", "\"", ",", "logopts", ")", "\n", "}", "\n\n", "Error", "=", "log", ".", "New", "(", "os", ".", "Stderr", ",", "\"", "\"", ",", "logopts", ")", "\n", "}" ]
// SetupLogs provides the following logs // Verbose = optional verbosity // VeryVerbose = optional verbosity // Error = stderr
[ "SetupLogs", "provides", "the", "following", "logs", "Verbose", "=", "optional", "verbosity", "VeryVerbose", "=", "optional", "verbosity", "Error", "=", "stderr" ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/logging/logging.go#L82-L104
144,740
mesosphere/mesos-dns
detect/masters.go
NewMasters
func NewMasters(masters []string, changed chan<- []string) *Masters { return &Masters{ masters: append([]string{""}, masters...), changed: changed, } }
go
func NewMasters(masters []string, changed chan<- []string) *Masters { return &Masters{ masters: append([]string{""}, masters...), changed: changed, } }
[ "func", "NewMasters", "(", "masters", "[", "]", "string", ",", "changed", "chan", "<-", "[", "]", "string", ")", "*", "Masters", "{", "return", "&", "Masters", "{", "masters", ":", "append", "(", "[", "]", "string", "{", "\"", "\"", "}", ",", "masters", "...", ")", ",", "changed", ":", "changed", ",", "}", "\n", "}" ]
// NewMasters returns a new Masters detector with the given initial masters // and the given changed channel to which master changes will be sent to. // Initially the leader is unknown which is represented by // setting the first item of the sent masters slice to be empty.
[ "NewMasters", "returns", "a", "new", "Masters", "detector", "with", "the", "given", "initial", "masters", "and", "the", "given", "changed", "channel", "to", "which", "master", "changes", "will", "be", "sent", "to", ".", "Initially", "the", "leader", "is", "unknown", "which", "is", "represented", "by", "setting", "the", "first", "item", "of", "the", "sent", "masters", "slice", "to", "be", "empty", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/detect/masters.go#L36-L41
144,741
mesosphere/mesos-dns
detect/masters.go
OnMasterChanged
func (ms *Masters) OnMasterChanged(leader *mesos.MasterInfo) { logging.VeryVerbose.Println("Updated leader: ", leader) ms.masters = ordered(masterAddr(leader), ms.masters[1:]) emit(ms.changed, ms.masters) }
go
func (ms *Masters) OnMasterChanged(leader *mesos.MasterInfo) { logging.VeryVerbose.Println("Updated leader: ", leader) ms.masters = ordered(masterAddr(leader), ms.masters[1:]) emit(ms.changed, ms.masters) }
[ "func", "(", "ms", "*", "Masters", ")", "OnMasterChanged", "(", "leader", "*", "mesos", ".", "MasterInfo", ")", "{", "logging", ".", "VeryVerbose", ".", "Println", "(", "\"", "\"", ",", "leader", ")", "\n", "ms", ".", "masters", "=", "ordered", "(", "masterAddr", "(", "leader", ")", ",", "ms", ".", "masters", "[", "1", ":", "]", ")", "\n", "emit", "(", "ms", ".", "changed", ",", "ms", ".", "masters", ")", "\n", "}" ]
// OnMasterChanged sets the given MasterInfo as the current leader // leaving the remaining masters unchanged and emits the current masters state. // It implements the detector.MasterChanged interface.
[ "OnMasterChanged", "sets", "the", "given", "MasterInfo", "as", "the", "current", "leader", "leaving", "the", "remaining", "masters", "unchanged", "and", "emits", "the", "current", "masters", "state", ".", "It", "implements", "the", "detector", ".", "MasterChanged", "interface", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/detect/masters.go#L46-L50
144,742
mesosphere/mesos-dns
detect/masters.go
UpdatedMasters
func (ms *Masters) UpdatedMasters(infos []*mesos.MasterInfo) { logging.VeryVerbose.Println("Updated masters: ", infos) masters := make([]string, 0, len(infos)) for _, info := range infos { if addr := masterAddr(info); addr != "" { masters = append(masters, addr) } } ms.masters = ordered(ms.masters[0], masters) emit(ms.changed, ms.masters) }
go
func (ms *Masters) UpdatedMasters(infos []*mesos.MasterInfo) { logging.VeryVerbose.Println("Updated masters: ", infos) masters := make([]string, 0, len(infos)) for _, info := range infos { if addr := masterAddr(info); addr != "" { masters = append(masters, addr) } } ms.masters = ordered(ms.masters[0], masters) emit(ms.changed, ms.masters) }
[ "func", "(", "ms", "*", "Masters", ")", "UpdatedMasters", "(", "infos", "[", "]", "*", "mesos", ".", "MasterInfo", ")", "{", "logging", ".", "VeryVerbose", ".", "Println", "(", "\"", "\"", ",", "infos", ")", "\n", "masters", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "infos", ")", ")", "\n", "for", "_", ",", "info", ":=", "range", "infos", "{", "if", "addr", ":=", "masterAddr", "(", "info", ")", ";", "addr", "!=", "\"", "\"", "{", "masters", "=", "append", "(", "masters", ",", "addr", ")", "\n", "}", "\n", "}", "\n", "ms", ".", "masters", "=", "ordered", "(", "ms", ".", "masters", "[", "0", "]", ",", "masters", ")", "\n", "emit", "(", "ms", ".", "changed", ",", "ms", ".", "masters", ")", "\n", "}" ]
// UpdatedMasters sets the given slice of MasterInfo as the current remaining masters // leaving the current leader unchanged and emits the current masters state. // It implements the detector.AllMasters interface.
[ "UpdatedMasters", "sets", "the", "given", "slice", "of", "MasterInfo", "as", "the", "current", "remaining", "masters", "leaving", "the", "current", "leader", "unchanged", "and", "emits", "the", "current", "masters", "state", ".", "It", "implements", "the", "detector", ".", "AllMasters", "interface", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/detect/masters.go#L55-L65
144,743
mesosphere/mesos-dns
detect/masters.go
ordered
func ordered(leader string, masters []string) []string { ms := append(make([]string, 0, len(masters)+1), leader) for _, m := range masters { if m != leader { ms = append(ms, m) } } return ms }
go
func ordered(leader string, masters []string) []string { ms := append(make([]string, 0, len(masters)+1), leader) for _, m := range masters { if m != leader { ms = append(ms, m) } } return ms }
[ "func", "ordered", "(", "leader", "string", ",", "masters", "[", "]", "string", ")", "[", "]", "string", "{", "ms", ":=", "append", "(", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "masters", ")", "+", "1", ")", ",", "leader", ")", "\n", "for", "_", ",", "m", ":=", "range", "masters", "{", "if", "m", "!=", "leader", "{", "ms", "=", "append", "(", "ms", ",", "m", ")", "\n", "}", "\n", "}", "\n", "return", "ms", "\n", "}" ]
// ordered returns a slice of masters with the given leader in the first position
[ "ordered", "returns", "a", "slice", "of", "masters", "with", "the", "given", "leader", "in", "the", "first", "position" ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/detect/masters.go#L72-L80
144,744
mesosphere/mesos-dns
exchanger/forwarder.go
Forward
func (f Forwarder) Forward(m *dns.Msg, proto string) (*dns.Msg, error) { return f(m, proto) }
go
func (f Forwarder) Forward(m *dns.Msg, proto string) (*dns.Msg, error) { return f(m, proto) }
[ "func", "(", "f", "Forwarder", ")", "Forward", "(", "m", "*", "dns", ".", "Msg", ",", "proto", "string", ")", "(", "*", "dns", ".", "Msg", ",", "error", ")", "{", "return", "f", "(", "m", ",", "proto", ")", "\n", "}" ]
// Forward is an utility method that calls f itself.
[ "Forward", "is", "an", "utility", "method", "that", "calls", "f", "itself", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/exchanger/forwarder.go#L15-L17
144,745
mesosphere/mesos-dns
httpcli/iam/iam.go
Doer
func Doer(client *http.Client, config Config) httpcli.Doer { return httpcli.DoerFunc(func(req *http.Request) (*http.Response, error) { // TODO if we still have a valid token, try using it first token := jwt.New(jwt.SigningMethodRS256) token.Claims["uid"] = config.ID token.Claims["exp"] = time.Now().Add(time.Hour).Unix() // SignedString will treat secret as PEM-encoded key tokenStr, err := token.SignedString([]byte(config.PrivateKey)) if err != nil { return nil, err } authReq := struct { UID string `json:"uid"` Token string `json:"token,omitempty"` }{ UID: config.ID, Token: tokenStr, } b, err := json.Marshal(authReq) if err != nil { return nil, err } authBody := bytes.NewBuffer(b) resp, err := client.Post(config.LoginEndpoint, "application/json", authBody) if err != nil { return nil, err } defer errorutil.Ignore(resp.Body.Close) if resp.StatusCode != 200 { return nil, httpcli.ErrAuthFailed } var authResp struct { Token string `json:"token"` } err = json.NewDecoder(resp.Body).Decode(&authResp) if err != nil { return nil, err } if req.Header == nil { req.Header = make(http.Header) } req.Header.Set("Authorization", "token="+authResp.Token) return client.Do(req) }) }
go
func Doer(client *http.Client, config Config) httpcli.Doer { return httpcli.DoerFunc(func(req *http.Request) (*http.Response, error) { // TODO if we still have a valid token, try using it first token := jwt.New(jwt.SigningMethodRS256) token.Claims["uid"] = config.ID token.Claims["exp"] = time.Now().Add(time.Hour).Unix() // SignedString will treat secret as PEM-encoded key tokenStr, err := token.SignedString([]byte(config.PrivateKey)) if err != nil { return nil, err } authReq := struct { UID string `json:"uid"` Token string `json:"token,omitempty"` }{ UID: config.ID, Token: tokenStr, } b, err := json.Marshal(authReq) if err != nil { return nil, err } authBody := bytes.NewBuffer(b) resp, err := client.Post(config.LoginEndpoint, "application/json", authBody) if err != nil { return nil, err } defer errorutil.Ignore(resp.Body.Close) if resp.StatusCode != 200 { return nil, httpcli.ErrAuthFailed } var authResp struct { Token string `json:"token"` } err = json.NewDecoder(resp.Body).Decode(&authResp) if err != nil { return nil, err } if req.Header == nil { req.Header = make(http.Header) } req.Header.Set("Authorization", "token="+authResp.Token) return client.Do(req) }) }
[ "func", "Doer", "(", "client", "*", "http", ".", "Client", ",", "config", "Config", ")", "httpcli", ".", "Doer", "{", "return", "httpcli", ".", "DoerFunc", "(", "func", "(", "req", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "// TODO if we still have a valid token, try using it first", "token", ":=", "jwt", ".", "New", "(", "jwt", ".", "SigningMethodRS256", ")", "\n", "token", ".", "Claims", "[", "\"", "\"", "]", "=", "config", ".", "ID", "\n", "token", ".", "Claims", "[", "\"", "\"", "]", "=", "time", ".", "Now", "(", ")", ".", "Add", "(", "time", ".", "Hour", ")", ".", "Unix", "(", ")", "\n", "// SignedString will treat secret as PEM-encoded key", "tokenStr", ",", "err", ":=", "token", ".", "SignedString", "(", "[", "]", "byte", "(", "config", ".", "PrivateKey", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "authReq", ":=", "struct", "{", "UID", "string", "`json:\"uid\"`", "\n", "Token", "string", "`json:\"token,omitempty\"`", "\n", "}", "{", "UID", ":", "config", ".", "ID", ",", "Token", ":", "tokenStr", ",", "}", "\n\n", "b", ",", "err", ":=", "json", ".", "Marshal", "(", "authReq", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "authBody", ":=", "bytes", ".", "NewBuffer", "(", "b", ")", "\n", "resp", ",", "err", ":=", "client", ".", "Post", "(", "config", ".", "LoginEndpoint", ",", "\"", "\"", ",", "authBody", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "errorutil", ".", "Ignore", "(", "resp", ".", "Body", ".", "Close", ")", "\n", "if", "resp", ".", "StatusCode", "!=", "200", "{", "return", "nil", ",", "httpcli", ".", "ErrAuthFailed", "\n", "}", "\n\n", "var", "authResp", "struct", "{", "Token", "string", "`json:\"token\"`", "\n", "}", "\n", "err", "=", "json", ".", "NewDecoder", "(", "resp", ".", "Body", ")", ".", "Decode", "(", "&", "authResp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "req", ".", "Header", "==", "nil", "{", "req", ".", "Header", "=", "make", "(", "http", ".", "Header", ")", "\n", "}", "\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", "+", "authResp", ".", "Token", ")", "\n\n", "return", "client", ".", "Do", "(", "req", ")", "\n", "}", ")", "\n", "}" ]
// Doer wraps an HTTP transactor given an IAM configuration
[ "Doer", "wraps", "an", "HTTP", "transactor", "given", "an", "IAM", "configuration" ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/httpcli/iam/iam.go#L38-L88
144,746
mesosphere/mesos-dns
records/labels/labels.go
DomainFrag
func DomainFrag(name, sep string, label Func) string { var labels []string for _, part := range strings.Split(name, sep) { if lab := label(part); lab != "" { labels = append(labels, lab) } } return strings.Join(labels, sep) }
go
func DomainFrag(name, sep string, label Func) string { var labels []string for _, part := range strings.Split(name, sep) { if lab := label(part); lab != "" { labels = append(labels, lab) } } return strings.Join(labels, sep) }
[ "func", "DomainFrag", "(", "name", ",", "sep", "string", ",", "label", "Func", ")", "string", "{", "var", "labels", "[", "]", "string", "\n", "for", "_", ",", "part", ":=", "range", "strings", ".", "Split", "(", "name", ",", "sep", ")", "{", "if", "lab", ":=", "label", "(", "part", ")", ";", "lab", "!=", "\"", "\"", "{", "labels", "=", "append", "(", "labels", ",", "lab", ")", "\n", "}", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "labels", ",", "sep", ")", "\n", "}" ]
// DomainFrag mangles the given name in order to produce a valid domain fragment. // A valid domain fragment will consist of one or more host name labels // concatenated by the given separator.
[ "DomainFrag", "mangles", "the", "given", "name", "in", "order", "to", "produce", "a", "valid", "domain", "fragment", ".", "A", "valid", "domain", "fragment", "will", "consist", "of", "one", "or", "more", "host", "name", "labels", "concatenated", "by", "the", "given", "separator", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/records/labels/labels.go#L14-L22
144,747
mesosphere/mesos-dns
records/labels/labels.go
label
func label(name []byte, maxlen int, left, right string) []byte { return trimCut(bytes.Map(mapping, name), maxlen, left, right) }
go
func label(name []byte, maxlen int, left, right string) []byte { return trimCut(bytes.Map(mapping, name), maxlen, left, right) }
[ "func", "label", "(", "name", "[", "]", "byte", ",", "maxlen", "int", ",", "left", ",", "right", "string", ")", "[", "]", "byte", "{", "return", "trimCut", "(", "bytes", ".", "Map", "(", "mapping", ",", "name", ")", ",", "maxlen", ",", "left", ",", "right", ")", "\n", "}" ]
// label computes a label from the given name with maxlen length and the // left and right cutsets trimmed from their respective ends.
[ "label", "computes", "a", "label", "from", "the", "given", "name", "with", "maxlen", "length", "and", "the", "left", "and", "right", "cutsets", "trimmed", "from", "their", "respective", "ends", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/records/labels/labels.go#L41-L43
144,748
mesosphere/mesos-dns
records/labels/labels.go
mapping
func mapping(r rune) rune { switch { case r >= 'A' && r <= 'Z': return r - ('A' - 'a') case r >= 'a' && r <= 'z': fallthrough case r >= '0' && r <= '9': return r case r == '-' || r == '.' || r == '_': return '-' default: return -1 } }
go
func mapping(r rune) rune { switch { case r >= 'A' && r <= 'Z': return r - ('A' - 'a') case r >= 'a' && r <= 'z': fallthrough case r >= '0' && r <= '9': return r case r == '-' || r == '.' || r == '_': return '-' default: return -1 } }
[ "func", "mapping", "(", "r", "rune", ")", "rune", "{", "switch", "{", "case", "r", ">=", "'A'", "&&", "r", "<=", "'Z'", ":", "return", "r", "-", "(", "'A'", "-", "'a'", ")", "\n", "case", "r", ">=", "'a'", "&&", "r", "<=", "'z'", ":", "fallthrough", "\n", "case", "r", ">=", "'0'", "&&", "r", "<=", "'9'", ":", "return", "r", "\n", "case", "r", "==", "'-'", "||", "r", "==", "'.'", "||", "r", "==", "'_'", ":", "return", "'-'", "\n", "default", ":", "return", "-", "1", "\n", "}", "\n", "}" ]
// mapping maps a given rune to its valid DNS label counterpart.
[ "mapping", "maps", "a", "given", "rune", "to", "its", "valid", "DNS", "label", "counterpart", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/records/labels/labels.go#L46-L59
144,749
mesosphere/mesos-dns
records/state/state.go
Ports
func (r Resources) Ports() []string { if r.PortRanges == "" || r.PortRanges == "[]" { return []string{} } rhs := strings.Split(r.PortRanges, "[")[1] lhs := strings.Split(rhs, "]")[0] yports := []string{} mports := strings.Split(lhs, ",") for _, port := range mports { tmp := strings.TrimSpace(port) pz := strings.Split(tmp, "-") lo, err := strconv.Atoi(pz[0]) if err != nil { logging.Error.Println(err) continue } hi, err := strconv.Atoi(pz[1]) if err != nil { logging.Error.Println(err) continue } for t := lo; t <= hi; t++ { yports = append(yports, strconv.Itoa(t)) } } return yports }
go
func (r Resources) Ports() []string { if r.PortRanges == "" || r.PortRanges == "[]" { return []string{} } rhs := strings.Split(r.PortRanges, "[")[1] lhs := strings.Split(rhs, "]")[0] yports := []string{} mports := strings.Split(lhs, ",") for _, port := range mports { tmp := strings.TrimSpace(port) pz := strings.Split(tmp, "-") lo, err := strconv.Atoi(pz[0]) if err != nil { logging.Error.Println(err) continue } hi, err := strconv.Atoi(pz[1]) if err != nil { logging.Error.Println(err) continue } for t := lo; t <= hi; t++ { yports = append(yports, strconv.Itoa(t)) } } return yports }
[ "func", "(", "r", "Resources", ")", "Ports", "(", ")", "[", "]", "string", "{", "if", "r", ".", "PortRanges", "==", "\"", "\"", "||", "r", ".", "PortRanges", "==", "\"", "\"", "{", "return", "[", "]", "string", "{", "}", "\n", "}", "\n\n", "rhs", ":=", "strings", ".", "Split", "(", "r", ".", "PortRanges", ",", "\"", "\"", ")", "[", "1", "]", "\n", "lhs", ":=", "strings", ".", "Split", "(", "rhs", ",", "\"", "\"", ")", "[", "0", "]", "\n\n", "yports", ":=", "[", "]", "string", "{", "}", "\n\n", "mports", ":=", "strings", ".", "Split", "(", "lhs", ",", "\"", "\"", ")", "\n", "for", "_", ",", "port", ":=", "range", "mports", "{", "tmp", ":=", "strings", ".", "TrimSpace", "(", "port", ")", "\n", "pz", ":=", "strings", ".", "Split", "(", "tmp", ",", "\"", "\"", ")", "\n", "lo", ",", "err", ":=", "strconv", ".", "Atoi", "(", "pz", "[", "0", "]", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "Error", ".", "Println", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "hi", ",", "err", ":=", "strconv", ".", "Atoi", "(", "pz", "[", "1", "]", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "Error", ".", "Println", "(", "err", ")", "\n", "continue", "\n", "}", "\n\n", "for", "t", ":=", "lo", ";", "t", "<=", "hi", ";", "t", "++", "{", "yports", "=", "append", "(", "yports", ",", "strconv", ".", "Itoa", "(", "t", ")", ")", "\n", "}", "\n", "}", "\n", "return", "yports", "\n", "}" ]
// Ports returns a slice of individual ports expanded from PortRanges.
[ "Ports", "returns", "a", "slice", "of", "individual", "ports", "expanded", "from", "PortRanges", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/records/state/state.go#L19-L49
144,750
mesosphere/mesos-dns
records/state/state.go
IP
func (t *Task) IP(srcs ...string) string { if ips := t.IPs(srcs...); len(ips) > 0 { return ips[0].String() } return "" }
go
func (t *Task) IP(srcs ...string) string { if ips := t.IPs(srcs...); len(ips) > 0 { return ips[0].String() } return "" }
[ "func", "(", "t", "*", "Task", ")", "IP", "(", "srcs", "...", "string", ")", "string", "{", "if", "ips", ":=", "t", ".", "IPs", "(", "srcs", "...", ")", ";", "len", "(", "ips", ")", ">", "0", "{", "return", "ips", "[", "0", "]", ".", "String", "(", ")", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// IP returns the first Task IP found in the given sources.
[ "IP", "returns", "the", "first", "Task", "IP", "found", "in", "the", "given", "sources", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/records/state/state.go#L106-L111
144,751
mesosphere/mesos-dns
records/state/state.go
IPs
func (t *Task) IPs(srcs ...string) (ips []net.IP) { if t == nil { return nil } for i := range srcs { if src, ok := sources[srcs[i]]; ok { for _, srcIP := range src(t) { if ip := net.ParseIP(srcIP); len(ip) > 0 { ips = append(ips, ip) } } } } return ips }
go
func (t *Task) IPs(srcs ...string) (ips []net.IP) { if t == nil { return nil } for i := range srcs { if src, ok := sources[srcs[i]]; ok { for _, srcIP := range src(t) { if ip := net.ParseIP(srcIP); len(ip) > 0 { ips = append(ips, ip) } } } } return ips }
[ "func", "(", "t", "*", "Task", ")", "IPs", "(", "srcs", "...", "string", ")", "(", "ips", "[", "]", "net", ".", "IP", ")", "{", "if", "t", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "for", "i", ":=", "range", "srcs", "{", "if", "src", ",", "ok", ":=", "sources", "[", "srcs", "[", "i", "]", "]", ";", "ok", "{", "for", "_", ",", "srcIP", ":=", "range", "src", "(", "t", ")", "{", "if", "ip", ":=", "net", ".", "ParseIP", "(", "srcIP", ")", ";", "len", "(", "ip", ")", ">", "0", "{", "ips", "=", "append", "(", "ips", ",", "ip", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "ips", "\n", "}" ]
// IPs returns a slice of IPs sourced from the given sources with ascending // priority.
[ "IPs", "returns", "a", "slice", "of", "IPs", "sourced", "from", "the", "given", "sources", "with", "ascending", "priority", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/records/state/state.go#L115-L129
144,752
mesosphere/mesos-dns
records/state/state.go
statusIPs
func statusIPs(st []Status, src func(*Status) []string) []string { // the state we extract from mesos makes no guarantees re: the order // of the task statuses so we should check the timestamps to avoid problems // down the line. we can't rely on seeing the same sequence. (@joris) // https://github.com/apache/mesos/blob/0.24.0/src/slave/slave.cpp#L5226-L5238 ts, j := -1.0, -1 for i := range st { if st[i].State == "TASK_RUNNING" && st[i].Timestamp > ts { ts, j = st[i].Timestamp, i } } if j >= 0 { return src(&st[j]) } return nil }
go
func statusIPs(st []Status, src func(*Status) []string) []string { // the state we extract from mesos makes no guarantees re: the order // of the task statuses so we should check the timestamps to avoid problems // down the line. we can't rely on seeing the same sequence. (@joris) // https://github.com/apache/mesos/blob/0.24.0/src/slave/slave.cpp#L5226-L5238 ts, j := -1.0, -1 for i := range st { if st[i].State == "TASK_RUNNING" && st[i].Timestamp > ts { ts, j = st[i].Timestamp, i } } if j >= 0 { return src(&st[j]) } return nil }
[ "func", "statusIPs", "(", "st", "[", "]", "Status", ",", "src", "func", "(", "*", "Status", ")", "[", "]", "string", ")", "[", "]", "string", "{", "// the state we extract from mesos makes no guarantees re: the order", "// of the task statuses so we should check the timestamps to avoid problems", "// down the line. we can't rely on seeing the same sequence. (@joris)", "// https://github.com/apache/mesos/blob/0.24.0/src/slave/slave.cpp#L5226-L5238", "ts", ",", "j", ":=", "-", "1.0", ",", "-", "1", "\n", "for", "i", ":=", "range", "st", "{", "if", "st", "[", "i", "]", ".", "State", "==", "\"", "\"", "&&", "st", "[", "i", "]", ".", "Timestamp", ">", "ts", "{", "ts", ",", "j", "=", "st", "[", "i", "]", ".", "Timestamp", ",", "i", "\n", "}", "\n", "}", "\n", "if", "j", ">=", "0", "{", "return", "src", "(", "&", "st", "[", "j", "]", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// statusIPs returns the latest running status IPs extracted with the given src
[ "statusIPs", "returns", "the", "latest", "running", "status", "IPs", "extracted", "with", "the", "given", "src" ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/records/state/state.go#L186-L201
144,753
mesosphere/mesos-dns
records/state/state.go
HostPort
func (f Framework) HostPort() (string, string) { if f.PID.UPID != nil { return f.PID.Host, f.PID.Port } return f.Hostname, "" }
go
func (f Framework) HostPort() (string, string) { if f.PID.UPID != nil { return f.PID.Host, f.PID.Port } return f.Hostname, "" }
[ "func", "(", "f", "Framework", ")", "HostPort", "(", ")", "(", "string", ",", "string", ")", "{", "if", "f", ".", "PID", ".", "UPID", "!=", "nil", "{", "return", "f", ".", "PID", ".", "Host", ",", "f", ".", "PID", ".", "Port", "\n", "}", "\n", "return", "f", ".", "Hostname", ",", "\"", "\"", "\n", "}" ]
// HostPort returns the hostname and port where a framework's scheduler is // listening on.
[ "HostPort", "returns", "the", "hostname", "and", "port", "where", "a", "framework", "s", "scheduler", "is", "listening", "on", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/records/state/state.go#L227-L232
144,754
mesosphere/mesos-dns
records/state/state.go
UnmarshalJSON
func (p *PID) UnmarshalJSON(data []byte) (err error) { p.UPID, err = upid.Parse(string(bytes.Trim(data, `" `))) return err }
go
func (p *PID) UnmarshalJSON(data []byte) (err error) { p.UPID, err = upid.Parse(string(bytes.Trim(data, `" `))) return err }
[ "func", "(", "p", "*", "PID", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "(", "err", "error", ")", "{", "p", ".", "UPID", ",", "err", "=", "upid", ".", "Parse", "(", "string", "(", "bytes", ".", "Trim", "(", "data", ",", "`\" `", ")", ")", ")", "\n", "return", "err", "\n", "}" ]
// UnmarshalJSON implements the json.Unmarshaler interface for PIDs.
[ "UnmarshalJSON", "implements", "the", "json", ".", "Unmarshaler", "interface", "for", "PIDs", "." ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/records/state/state.go#L245-L248
144,755
mesosphere/mesos-dns
records/config.go
NewConfig
func NewConfig() Config { return Config{ ZkDetectionTimeout: 30, RefreshSeconds: 60, TTL: 60, SRVRecordDefaultWeight: 1, Domain: "mesos", Port: 53, Timeout: 5, StateTimeoutSeconds: 300, SOARname: "root.ns1.mesos", SOAMname: "ns1.mesos", SOARefresh: 60, SOARetry: 600, SOAExpire: 86400, SOAMinttl: 60, ZoneResolvers: map[string][]string{}, Resolvers: []string{"8.8.8.8"}, Listener: "0.0.0.0", HTTPListener: "0.0.0.0", HTTPPort: 8123, DNSOn: true, HTTPOn: true, ExternalOn: true, SetTruncateBit: true, RecurseOn: true, IPSources: []string{"netinfo", "mesos", "host"}, EnumerationOn: true, MesosAuthentication: httpcli.AuthNone, } }
go
func NewConfig() Config { return Config{ ZkDetectionTimeout: 30, RefreshSeconds: 60, TTL: 60, SRVRecordDefaultWeight: 1, Domain: "mesos", Port: 53, Timeout: 5, StateTimeoutSeconds: 300, SOARname: "root.ns1.mesos", SOAMname: "ns1.mesos", SOARefresh: 60, SOARetry: 600, SOAExpire: 86400, SOAMinttl: 60, ZoneResolvers: map[string][]string{}, Resolvers: []string{"8.8.8.8"}, Listener: "0.0.0.0", HTTPListener: "0.0.0.0", HTTPPort: 8123, DNSOn: true, HTTPOn: true, ExternalOn: true, SetTruncateBit: true, RecurseOn: true, IPSources: []string{"netinfo", "mesos", "host"}, EnumerationOn: true, MesosAuthentication: httpcli.AuthNone, } }
[ "func", "NewConfig", "(", ")", "Config", "{", "return", "Config", "{", "ZkDetectionTimeout", ":", "30", ",", "RefreshSeconds", ":", "60", ",", "TTL", ":", "60", ",", "SRVRecordDefaultWeight", ":", "1", ",", "Domain", ":", "\"", "\"", ",", "Port", ":", "53", ",", "Timeout", ":", "5", ",", "StateTimeoutSeconds", ":", "300", ",", "SOARname", ":", "\"", "\"", ",", "SOAMname", ":", "\"", "\"", ",", "SOARefresh", ":", "60", ",", "SOARetry", ":", "600", ",", "SOAExpire", ":", "86400", ",", "SOAMinttl", ":", "60", ",", "ZoneResolvers", ":", "map", "[", "string", "]", "[", "]", "string", "{", "}", ",", "Resolvers", ":", "[", "]", "string", "{", "\"", "\"", "}", ",", "Listener", ":", "\"", "\"", ",", "HTTPListener", ":", "\"", "\"", ",", "HTTPPort", ":", "8123", ",", "DNSOn", ":", "true", ",", "HTTPOn", ":", "true", ",", "ExternalOn", ":", "true", ",", "SetTruncateBit", ":", "true", ",", "RecurseOn", ":", "true", ",", "IPSources", ":", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", ",", "EnumerationOn", ":", "true", ",", "MesosAuthentication", ":", "httpcli", ".", "AuthNone", ",", "}", "\n", "}" ]
// NewConfig return the default config of the resolver
[ "NewConfig", "return", "the", "default", "config", "of", "the", "resolver" ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/records/config.go#L114-L144
144,756
mesosphere/mesos-dns
records/config.go
SetConfig
func SetConfig(cjson string) Config { c, err := readConfig(cjson) if err != nil { logging.Error.Fatal(err) } logging.Verbose.Printf("config loaded from %q", c.File) // validate and complete configuration file err = validateEnabledServices(c) if err != nil { logging.Error.Fatalf("service validation failed: %v", err) } if err = validateMasters(c.Masters); err != nil { logging.Error.Fatal(err) } c.initResolvers() if err = validateIPSources(c.IPSources); err != nil { logging.Error.Fatalf("IPSources validation failed: %v", err) } if c.StateTimeoutSeconds <= 0 { logging.Error.Fatal("Invalid HTTP Timeout: ", c.StateTimeoutSeconds) } c.Domain = strings.ToLower(c.Domain) err = validateDomainName(c.Domain) if err != nil { logging.Error.Fatalf("%s is not a valid domain name", c.Domain) } c.initSOA() c.initCertificates() c.initMesosAuthentication() c.log() return *c }
go
func SetConfig(cjson string) Config { c, err := readConfig(cjson) if err != nil { logging.Error.Fatal(err) } logging.Verbose.Printf("config loaded from %q", c.File) // validate and complete configuration file err = validateEnabledServices(c) if err != nil { logging.Error.Fatalf("service validation failed: %v", err) } if err = validateMasters(c.Masters); err != nil { logging.Error.Fatal(err) } c.initResolvers() if err = validateIPSources(c.IPSources); err != nil { logging.Error.Fatalf("IPSources validation failed: %v", err) } if c.StateTimeoutSeconds <= 0 { logging.Error.Fatal("Invalid HTTP Timeout: ", c.StateTimeoutSeconds) } c.Domain = strings.ToLower(c.Domain) err = validateDomainName(c.Domain) if err != nil { logging.Error.Fatalf("%s is not a valid domain name", c.Domain) } c.initSOA() c.initCertificates() c.initMesosAuthentication() c.log() return *c }
[ "func", "SetConfig", "(", "cjson", "string", ")", "Config", "{", "c", ",", "err", ":=", "readConfig", "(", "cjson", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "Error", ".", "Fatal", "(", "err", ")", "\n", "}", "\n", "logging", ".", "Verbose", ".", "Printf", "(", "\"", "\"", ",", "c", ".", "File", ")", "\n", "// validate and complete configuration file", "err", "=", "validateEnabledServices", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "Error", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "err", "=", "validateMasters", "(", "c", ".", "Masters", ")", ";", "err", "!=", "nil", "{", "logging", ".", "Error", ".", "Fatal", "(", "err", ")", "\n", "}", "\n\n", "c", ".", "initResolvers", "(", ")", "\n\n", "if", "err", "=", "validateIPSources", "(", "c", ".", "IPSources", ")", ";", "err", "!=", "nil", "{", "logging", ".", "Error", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "c", ".", "StateTimeoutSeconds", "<=", "0", "{", "logging", ".", "Error", ".", "Fatal", "(", "\"", "\"", ",", "c", ".", "StateTimeoutSeconds", ")", "\n", "}", "\n\n", "c", ".", "Domain", "=", "strings", ".", "ToLower", "(", "c", ".", "Domain", ")", "\n\n", "err", "=", "validateDomainName", "(", "c", ".", "Domain", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "Error", ".", "Fatalf", "(", "\"", "\"", ",", "c", ".", "Domain", ")", "\n", "}", "\n\n", "c", ".", "initSOA", "(", ")", "\n", "c", ".", "initCertificates", "(", ")", "\n", "c", ".", "initMesosAuthentication", "(", ")", "\n", "c", ".", "log", "(", ")", "\n\n", "return", "*", "c", "\n", "}" ]
// SetConfig instantiates a Config struct read in from config.json
[ "SetConfig", "instantiates", "a", "Config", "struct", "read", "in", "from", "config", ".", "json" ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/records/config.go#L147-L185
144,757
mesosphere/mesos-dns
records/config.go
nonLocalAddies
func nonLocalAddies(cservers []string) []string { bad := localAddies() good := []string{} for i := 0; i < len(cservers); i++ { local := false for x := 0; x < len(bad); x++ { if cservers[i] == bad[x] { local = true } } if !local { good = append(good, cservers[i]) } } return good }
go
func nonLocalAddies(cservers []string) []string { bad := localAddies() good := []string{} for i := 0; i < len(cservers); i++ { local := false for x := 0; x < len(bad); x++ { if cservers[i] == bad[x] { local = true } } if !local { good = append(good, cservers[i]) } } return good }
[ "func", "nonLocalAddies", "(", "cservers", "[", "]", "string", ")", "[", "]", "string", "{", "bad", ":=", "localAddies", "(", ")", "\n\n", "good", ":=", "[", "]", "string", "{", "}", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "cservers", ")", ";", "i", "++", "{", "local", ":=", "false", "\n", "for", "x", ":=", "0", ";", "x", "<", "len", "(", "bad", ")", ";", "x", "++", "{", "if", "cservers", "[", "i", "]", "==", "bad", "[", "x", "]", "{", "local", "=", "true", "\n", "}", "\n", "}", "\n\n", "if", "!", "local", "{", "good", "=", "append", "(", "good", ",", "cservers", "[", "i", "]", ")", "\n", "}", "\n", "}", "\n\n", "return", "good", "\n", "}" ]
// Returns non-local nameserver entries
[ "Returns", "non", "-", "local", "nameserver", "entries" ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/records/config.go#L384-L403
144,758
mesosphere/mesos-dns
records/config.go
localAddies
func localAddies() []string { addies, err := net.InterfaceAddrs() if err != nil { logging.Error.Println(err) } bad := []string{} for i := 0; i < len(addies); i++ { ip, _, err := net.ParseCIDR(addies[i].String()) if err != nil { logging.Error.Println(err) } // The servers in cservers above could include // ipv6, so we should include local ipv6 for // that filtering if t4 := ip.To4(); t4 != nil { bad = append(bad, t4.String()) } else if t6 := ip.To16(); t6 != nil { bad = append(bad, t6.String()) } } return bad }
go
func localAddies() []string { addies, err := net.InterfaceAddrs() if err != nil { logging.Error.Println(err) } bad := []string{} for i := 0; i < len(addies); i++ { ip, _, err := net.ParseCIDR(addies[i].String()) if err != nil { logging.Error.Println(err) } // The servers in cservers above could include // ipv6, so we should include local ipv6 for // that filtering if t4 := ip.To4(); t4 != nil { bad = append(bad, t4.String()) } else if t6 := ip.To16(); t6 != nil { bad = append(bad, t6.String()) } } return bad }
[ "func", "localAddies", "(", ")", "[", "]", "string", "{", "addies", ",", "err", ":=", "net", ".", "InterfaceAddrs", "(", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "Error", ".", "Println", "(", "err", ")", "\n", "}", "\n\n", "bad", ":=", "[", "]", "string", "{", "}", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "addies", ")", ";", "i", "++", "{", "ip", ",", "_", ",", "err", ":=", "net", ".", "ParseCIDR", "(", "addies", "[", "i", "]", ".", "String", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "Error", ".", "Println", "(", "err", ")", "\n", "}", "\n", "// The servers in cservers above could include", "// ipv6, so we should include local ipv6 for", "// that filtering", "if", "t4", ":=", "ip", ".", "To4", "(", ")", ";", "t4", "!=", "nil", "{", "bad", "=", "append", "(", "bad", ",", "t4", ".", "String", "(", ")", ")", "\n", "}", "else", "if", "t6", ":=", "ip", ".", "To16", "(", ")", ";", "t6", "!=", "nil", "{", "bad", "=", "append", "(", "bad", ",", "t6", ".", "String", "(", ")", ")", "\n", "}", "\n", "}", "\n\n", "return", "bad", "\n", "}" ]
// Returns an array of local ipv4 addresses
[ "Returns", "an", "array", "of", "local", "ipv4", "addresses" ]
65cb06fff5493c3caa8fc00d26e89fbedab9d95e
https://github.com/mesosphere/mesos-dns/blob/65cb06fff5493c3caa8fc00d26e89fbedab9d95e/records/config.go#L406-L430
144,759
libp2p/go-reuseport
interface.go
Listen
func Listen(network, address string) (net.Listener, error) { return listenConfig.Listen(context.Background(), network, address) }
go
func Listen(network, address string) (net.Listener, error) { return listenConfig.Listen(context.Background(), network, address) }
[ "func", "Listen", "(", "network", ",", "address", "string", ")", "(", "net", ".", "Listener", ",", "error", ")", "{", "return", "listenConfig", ".", "Listen", "(", "context", ".", "Background", "(", ")", ",", "network", ",", "address", ")", "\n", "}" ]
// Listen listens at the given network and address. see net.Listen // Returns a net.Listener created from a file discriptor for a socket // with SO_REUSEPORT and SO_REUSEADDR option set.
[ "Listen", "listens", "at", "the", "given", "network", "and", "address", ".", "see", "net", ".", "Listen", "Returns", "a", "net", ".", "Listener", "created", "from", "a", "file", "discriptor", "for", "a", "socket", "with", "SO_REUSEPORT", "and", "SO_REUSEADDR", "option", "set", "." ]
b72b23b78b80078df1a7991f6ca39942cb8cc5e1
https://github.com/libp2p/go-reuseport/blob/b72b23b78b80078df1a7991f6ca39942cb8cc5e1/interface.go#L40-L42
144,760
libp2p/go-reuseport
interface.go
ListenPacket
func ListenPacket(network, address string) (net.PacketConn, error) { return listenConfig.ListenPacket(context.Background(), network, address) }
go
func ListenPacket(network, address string) (net.PacketConn, error) { return listenConfig.ListenPacket(context.Background(), network, address) }
[ "func", "ListenPacket", "(", "network", ",", "address", "string", ")", "(", "net", ".", "PacketConn", ",", "error", ")", "{", "return", "listenConfig", ".", "ListenPacket", "(", "context", ".", "Background", "(", ")", ",", "network", ",", "address", ")", "\n", "}" ]
// ListenPacket listens at the given network and address. see net.ListenPacket // Returns a net.Listener created from a file discriptor for a socket // with SO_REUSEPORT and SO_REUSEADDR option set.
[ "ListenPacket", "listens", "at", "the", "given", "network", "and", "address", ".", "see", "net", ".", "ListenPacket", "Returns", "a", "net", ".", "Listener", "created", "from", "a", "file", "discriptor", "for", "a", "socket", "with", "SO_REUSEPORT", "and", "SO_REUSEADDR", "option", "set", "." ]
b72b23b78b80078df1a7991f6ca39942cb8cc5e1
https://github.com/libp2p/go-reuseport/blob/b72b23b78b80078df1a7991f6ca39942cb8cc5e1/interface.go#L47-L49
144,761
libp2p/go-reuseport
interface.go
Dial
func Dial(network, laddr, raddr string) (net.Conn, error) { nla, err := ResolveAddr(network, laddr) if err != nil { return nil, errors.Wrap(err, "resolving local addr") } d := net.Dialer{ Control: Control, LocalAddr: nla, } return d.Dial(network, raddr) }
go
func Dial(network, laddr, raddr string) (net.Conn, error) { nla, err := ResolveAddr(network, laddr) if err != nil { return nil, errors.Wrap(err, "resolving local addr") } d := net.Dialer{ Control: Control, LocalAddr: nla, } return d.Dial(network, raddr) }
[ "func", "Dial", "(", "network", ",", "laddr", ",", "raddr", "string", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "nla", ",", "err", ":=", "ResolveAddr", "(", "network", ",", "laddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "d", ":=", "net", ".", "Dialer", "{", "Control", ":", "Control", ",", "LocalAddr", ":", "nla", ",", "}", "\n", "return", "d", ".", "Dial", "(", "network", ",", "raddr", ")", "\n", "}" ]
// Dial dials the given network and address. see net.Dialer.Dial // Returns a net.Conn created from a file descriptor for a socket // with SO_REUSEPORT and SO_REUSEADDR option set.
[ "Dial", "dials", "the", "given", "network", "and", "address", ".", "see", "net", ".", "Dialer", ".", "Dial", "Returns", "a", "net", ".", "Conn", "created", "from", "a", "file", "descriptor", "for", "a", "socket", "with", "SO_REUSEPORT", "and", "SO_REUSEADDR", "option", "set", "." ]
b72b23b78b80078df1a7991f6ca39942cb8cc5e1
https://github.com/libp2p/go-reuseport/blob/b72b23b78b80078df1a7991f6ca39942cb8cc5e1/interface.go#L54-L64
144,762
etcd-io/gofail
runtime/failpoint.go
Acquire
func (fp *Failpoint) Acquire() (interface{}, error) { fp.mu.RLock() if fp.t == nil { fp.mu.RUnlock() return nil, ErrDisabled } v, err := fp.t.eval() if v == nil { err = ErrDisabled } if err != nil { fp.mu.RUnlock() } return v, err }
go
func (fp *Failpoint) Acquire() (interface{}, error) { fp.mu.RLock() if fp.t == nil { fp.mu.RUnlock() return nil, ErrDisabled } v, err := fp.t.eval() if v == nil { err = ErrDisabled } if err != nil { fp.mu.RUnlock() } return v, err }
[ "func", "(", "fp", "*", "Failpoint", ")", "Acquire", "(", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "fp", ".", "mu", ".", "RLock", "(", ")", "\n", "if", "fp", ".", "t", "==", "nil", "{", "fp", ".", "mu", ".", "RUnlock", "(", ")", "\n", "return", "nil", ",", "ErrDisabled", "\n", "}", "\n", "v", ",", "err", ":=", "fp", ".", "t", ".", "eval", "(", ")", "\n", "if", "v", "==", "nil", "{", "err", "=", "ErrDisabled", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "fp", ".", "mu", ".", "RUnlock", "(", ")", "\n", "}", "\n", "return", "v", ",", "err", "\n", "}" ]
// Acquire gets evalutes the failpoint terms; if the failpoint // is active, it will return a value. Otherwise, returns a non-nil error.
[ "Acquire", "gets", "evalutes", "the", "failpoint", "terms", ";", "if", "the", "failpoint", "is", "active", "it", "will", "return", "a", "value", ".", "Otherwise", "returns", "a", "non", "-", "nil", "error", "." ]
51ce9a71510a58bad5ae66ddd278ef28762a1550
https://github.com/etcd-io/gofail/blob/51ce9a71510a58bad5ae66ddd278ef28762a1550/runtime/failpoint.go#L35-L49
144,763
etcd-io/gofail
runtime/failpoint.go
BadType
func (fp *Failpoint) BadType(v interface{}, t string) { fmt.Printf("failpoint: %q got value %v of type \"%T\" but expected type %q\n", fp.t.fpath, v, v, t) }
go
func (fp *Failpoint) BadType(v interface{}, t string) { fmt.Printf("failpoint: %q got value %v of type \"%T\" but expected type %q\n", fp.t.fpath, v, v, t) }
[ "func", "(", "fp", "*", "Failpoint", ")", "BadType", "(", "v", "interface", "{", "}", ",", "t", "string", ")", "{", "fmt", ".", "Printf", "(", "\"", "\\\"", "\\\"", "\\n", "\"", ",", "fp", ".", "t", ".", "fpath", ",", "v", ",", "v", ",", "t", ")", "\n", "}" ]
// BadType is called when the failpoint evaluates to the wrong type.
[ "BadType", "is", "called", "when", "the", "failpoint", "evaluates", "to", "the", "wrong", "type", "." ]
51ce9a71510a58bad5ae66ddd278ef28762a1550
https://github.com/etcd-io/gofail/blob/51ce9a71510a58bad5ae66ddd278ef28762a1550/runtime/failpoint.go#L55-L57
144,764
etcd-io/gofail
code/failpoint.go
newFailpoint
func newFailpoint(l string) (*Failpoint, error) { if !strings.HasPrefix(strings.TrimSpace(l), "// gofail:") { // not a failpoint return nil, nil } cmd := strings.SplitAfter(l, "// gofail:")[1] fields := strings.Fields(cmd) if len(fields) != 3 || fields[0] != "var" { return nil, fmt.Errorf("failpoint: malformed comment header %q", l) } return &Failpoint{name: fields[1], varType: fields[2], ws: strings.Split(l, "//")[0]}, nil }
go
func newFailpoint(l string) (*Failpoint, error) { if !strings.HasPrefix(strings.TrimSpace(l), "// gofail:") { // not a failpoint return nil, nil } cmd := strings.SplitAfter(l, "// gofail:")[1] fields := strings.Fields(cmd) if len(fields) != 3 || fields[0] != "var" { return nil, fmt.Errorf("failpoint: malformed comment header %q", l) } return &Failpoint{name: fields[1], varType: fields[2], ws: strings.Split(l, "//")[0]}, nil }
[ "func", "newFailpoint", "(", "l", "string", ")", "(", "*", "Failpoint", ",", "error", ")", "{", "if", "!", "strings", ".", "HasPrefix", "(", "strings", ".", "TrimSpace", "(", "l", ")", ",", "\"", "\"", ")", "{", "// not a failpoint", "return", "nil", ",", "nil", "\n", "}", "\n", "cmd", ":=", "strings", ".", "SplitAfter", "(", "l", ",", "\"", "\"", ")", "[", "1", "]", "\n", "fields", ":=", "strings", ".", "Fields", "(", "cmd", ")", "\n", "if", "len", "(", "fields", ")", "!=", "3", "||", "fields", "[", "0", "]", "!=", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "l", ")", "\n", "}", "\n", "return", "&", "Failpoint", "{", "name", ":", "fields", "[", "1", "]", ",", "varType", ":", "fields", "[", "2", "]", ",", "ws", ":", "strings", ".", "Split", "(", "l", ",", "\"", "\"", ")", "[", "0", "]", "}", ",", "nil", "\n", "}" ]
// newFailpoint makes a new failpoint based on the a line containing a // failpoint comment header.
[ "newFailpoint", "makes", "a", "new", "failpoint", "based", "on", "the", "a", "line", "containing", "a", "failpoint", "comment", "header", "." ]
51ce9a71510a58bad5ae66ddd278ef28762a1550
https://github.com/etcd-io/gofail/blob/51ce9a71510a58bad5ae66ddd278ef28762a1550/code/failpoint.go#L34-L45
144,765
etcd-io/gofail
code/failpoint.go
flush
func (fp *Failpoint) flush(dst io.Writer) error { if len(fp.code) == 0 { return fp.flushSingle(dst) } return fp.flushMulti(dst) }
go
func (fp *Failpoint) flush(dst io.Writer) error { if len(fp.code) == 0 { return fp.flushSingle(dst) } return fp.flushMulti(dst) }
[ "func", "(", "fp", "*", "Failpoint", ")", "flush", "(", "dst", "io", ".", "Writer", ")", "error", "{", "if", "len", "(", "fp", ".", "code", ")", "==", "0", "{", "return", "fp", ".", "flushSingle", "(", "dst", ")", "\n", "}", "\n", "return", "fp", ".", "flushMulti", "(", "dst", ")", "\n", "}" ]
// flush writes the failpoint code to a buffer
[ "flush", "writes", "the", "failpoint", "code", "to", "a", "buffer" ]
51ce9a71510a58bad5ae66ddd278ef28762a1550
https://github.com/etcd-io/gofail/blob/51ce9a71510a58bad5ae66ddd278ef28762a1550/code/failpoint.go#L48-L53
144,766
etcd-io/gofail
code/rewrite.go
ToFailpoints
func ToFailpoints(wdst io.Writer, rsrc io.Reader) (fps []*Failpoint, err error) { var curfp *Failpoint dst := bufio.NewWriter(wdst) defer func() { if err == nil && curfp != nil { err = curfp.flush(dst) } if err == nil { err = dst.Flush() } }() src := bufio.NewReader(rsrc) for err == nil { l, rerr := src.ReadString('\n') if curfp != nil { if strings.HasPrefix(strings.TrimSpace(l), "//") { if len(l) > 0 && l[len(l)-1] == '\n' { l = l[:len(l)-1] } curfp.code = append(curfp.code, strings.Replace(l, "//", "\t", 1)) continue } else { curfp.flush(dst) fps = append(fps, curfp) curfp = nil } } else if label := gofailLabel(l); label != "" { // expose gofail label l = label } else if curfp, err = newFailpoint(l); err != nil { return } else if curfp != nil { // found a new failpoint continue } if _, err = dst.WriteString(l); err != nil { return } if rerr == io.EOF { break } } return }
go
func ToFailpoints(wdst io.Writer, rsrc io.Reader) (fps []*Failpoint, err error) { var curfp *Failpoint dst := bufio.NewWriter(wdst) defer func() { if err == nil && curfp != nil { err = curfp.flush(dst) } if err == nil { err = dst.Flush() } }() src := bufio.NewReader(rsrc) for err == nil { l, rerr := src.ReadString('\n') if curfp != nil { if strings.HasPrefix(strings.TrimSpace(l), "//") { if len(l) > 0 && l[len(l)-1] == '\n' { l = l[:len(l)-1] } curfp.code = append(curfp.code, strings.Replace(l, "//", "\t", 1)) continue } else { curfp.flush(dst) fps = append(fps, curfp) curfp = nil } } else if label := gofailLabel(l); label != "" { // expose gofail label l = label } else if curfp, err = newFailpoint(l); err != nil { return } else if curfp != nil { // found a new failpoint continue } if _, err = dst.WriteString(l); err != nil { return } if rerr == io.EOF { break } } return }
[ "func", "ToFailpoints", "(", "wdst", "io", ".", "Writer", ",", "rsrc", "io", ".", "Reader", ")", "(", "fps", "[", "]", "*", "Failpoint", ",", "err", "error", ")", "{", "var", "curfp", "*", "Failpoint", "\n\n", "dst", ":=", "bufio", ".", "NewWriter", "(", "wdst", ")", "\n", "defer", "func", "(", ")", "{", "if", "err", "==", "nil", "&&", "curfp", "!=", "nil", "{", "err", "=", "curfp", ".", "flush", "(", "dst", ")", "\n", "}", "\n", "if", "err", "==", "nil", "{", "err", "=", "dst", ".", "Flush", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "src", ":=", "bufio", ".", "NewReader", "(", "rsrc", ")", "\n", "for", "err", "==", "nil", "{", "l", ",", "rerr", ":=", "src", ".", "ReadString", "(", "'\\n'", ")", "\n", "if", "curfp", "!=", "nil", "{", "if", "strings", ".", "HasPrefix", "(", "strings", ".", "TrimSpace", "(", "l", ")", ",", "\"", "\"", ")", "{", "if", "len", "(", "l", ")", ">", "0", "&&", "l", "[", "len", "(", "l", ")", "-", "1", "]", "==", "'\\n'", "{", "l", "=", "l", "[", ":", "len", "(", "l", ")", "-", "1", "]", "\n", "}", "\n", "curfp", ".", "code", "=", "append", "(", "curfp", ".", "code", ",", "strings", ".", "Replace", "(", "l", ",", "\"", "\"", ",", "\"", "\\t", "\"", ",", "1", ")", ")", "\n", "continue", "\n", "}", "else", "{", "curfp", ".", "flush", "(", "dst", ")", "\n", "fps", "=", "append", "(", "fps", ",", "curfp", ")", "\n", "curfp", "=", "nil", "\n", "}", "\n", "}", "else", "if", "label", ":=", "gofailLabel", "(", "l", ")", ";", "label", "!=", "\"", "\"", "{", "// expose gofail label", "l", "=", "label", "\n", "}", "else", "if", "curfp", ",", "err", "=", "newFailpoint", "(", "l", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "else", "if", "curfp", "!=", "nil", "{", "// found a new failpoint", "continue", "\n", "}", "\n", "if", "_", ",", "err", "=", "dst", ".", "WriteString", "(", "l", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "rerr", "==", "io", ".", "EOF", "{", "break", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// ToFailpoints turns all gofail comments into failpoint code. Returns a list of // all failpoints it activated.
[ "ToFailpoints", "turns", "all", "gofail", "comments", "into", "failpoint", "code", ".", "Returns", "a", "list", "of", "all", "failpoints", "it", "activated", "." ]
51ce9a71510a58bad5ae66ddd278ef28762a1550
https://github.com/etcd-io/gofail/blob/51ce9a71510a58bad5ae66ddd278ef28762a1550/code/rewrite.go#L26-L71
144,767
etcd-io/gofail
code/rewrite.go
ToComments
func ToComments(wdst io.Writer, rsrc io.Reader) (fps []*Failpoint, err error) { src := bufio.NewReader(rsrc) dst := bufio.NewWriter(wdst) ws := "" unmatchedBraces := 0 for err == nil { l, rerr := src.ReadString('\n') err = rerr lTrim := strings.TrimSpace(l) if unmatchedBraces > 0 { opening, closing := numBraces(l) unmatchedBraces += opening - closing if unmatchedBraces == 0 { // strip off badType footer lTrim = strings.Split(lTrim, "; __badType")[0] } s := ws + "//" + wsPrefix(l, ws)[1:] + lTrim + "\n" dst.WriteString(s) continue } isHdr := strings.Contains(l, ", __fpErr := __fp_") && strings.HasPrefix(lTrim, "if") if isHdr { ws = strings.Split(l, "i")[0] n := strings.Split(strings.Split(l, "__fp_")[1], ".")[0] t := strings.Split(strings.Split(l, ".(")[1], ")")[0] dst.WriteString(ws + "// gofail: var " + n + " " + t + "\n") if !strings.Contains(l, "; __badType") { // not single liner unmatchedBraces = 1 } fps = append(fps, &Failpoint{name: n, varType: t}) continue } if isLabel := strings.Contains(l, "\t/* gofail-label */"); isLabel { l = strings.Replace(l, "/* gofail-label */", "// gofail:", 1) } if _, werr := dst.WriteString(l); werr != nil { return fps, werr } } if err == io.EOF { err = nil } dst.Flush() return }
go
func ToComments(wdst io.Writer, rsrc io.Reader) (fps []*Failpoint, err error) { src := bufio.NewReader(rsrc) dst := bufio.NewWriter(wdst) ws := "" unmatchedBraces := 0 for err == nil { l, rerr := src.ReadString('\n') err = rerr lTrim := strings.TrimSpace(l) if unmatchedBraces > 0 { opening, closing := numBraces(l) unmatchedBraces += opening - closing if unmatchedBraces == 0 { // strip off badType footer lTrim = strings.Split(lTrim, "; __badType")[0] } s := ws + "//" + wsPrefix(l, ws)[1:] + lTrim + "\n" dst.WriteString(s) continue } isHdr := strings.Contains(l, ", __fpErr := __fp_") && strings.HasPrefix(lTrim, "if") if isHdr { ws = strings.Split(l, "i")[0] n := strings.Split(strings.Split(l, "__fp_")[1], ".")[0] t := strings.Split(strings.Split(l, ".(")[1], ")")[0] dst.WriteString(ws + "// gofail: var " + n + " " + t + "\n") if !strings.Contains(l, "; __badType") { // not single liner unmatchedBraces = 1 } fps = append(fps, &Failpoint{name: n, varType: t}) continue } if isLabel := strings.Contains(l, "\t/* gofail-label */"); isLabel { l = strings.Replace(l, "/* gofail-label */", "// gofail:", 1) } if _, werr := dst.WriteString(l); werr != nil { return fps, werr } } if err == io.EOF { err = nil } dst.Flush() return }
[ "func", "ToComments", "(", "wdst", "io", ".", "Writer", ",", "rsrc", "io", ".", "Reader", ")", "(", "fps", "[", "]", "*", "Failpoint", ",", "err", "error", ")", "{", "src", ":=", "bufio", ".", "NewReader", "(", "rsrc", ")", "\n", "dst", ":=", "bufio", ".", "NewWriter", "(", "wdst", ")", "\n", "ws", ":=", "\"", "\"", "\n", "unmatchedBraces", ":=", "0", "\n", "for", "err", "==", "nil", "{", "l", ",", "rerr", ":=", "src", ".", "ReadString", "(", "'\\n'", ")", "\n", "err", "=", "rerr", "\n", "lTrim", ":=", "strings", ".", "TrimSpace", "(", "l", ")", "\n\n", "if", "unmatchedBraces", ">", "0", "{", "opening", ",", "closing", ":=", "numBraces", "(", "l", ")", "\n", "unmatchedBraces", "+=", "opening", "-", "closing", "\n", "if", "unmatchedBraces", "==", "0", "{", "// strip off badType footer", "lTrim", "=", "strings", ".", "Split", "(", "lTrim", ",", "\"", "\"", ")", "[", "0", "]", "\n", "}", "\n", "s", ":=", "ws", "+", "\"", "\"", "+", "wsPrefix", "(", "l", ",", "ws", ")", "[", "1", ":", "]", "+", "lTrim", "+", "\"", "\\n", "\"", "\n", "dst", ".", "WriteString", "(", "s", ")", "\n", "continue", "\n", "}", "\n\n", "isHdr", ":=", "strings", ".", "Contains", "(", "l", ",", "\"", "\"", ")", "&&", "strings", ".", "HasPrefix", "(", "lTrim", ",", "\"", "\"", ")", "\n", "if", "isHdr", "{", "ws", "=", "strings", ".", "Split", "(", "l", ",", "\"", "\"", ")", "[", "0", "]", "\n", "n", ":=", "strings", ".", "Split", "(", "strings", ".", "Split", "(", "l", ",", "\"", "\"", ")", "[", "1", "]", ",", "\"", "\"", ")", "[", "0", "]", "\n", "t", ":=", "strings", ".", "Split", "(", "strings", ".", "Split", "(", "l", ",", "\"", "\"", ")", "[", "1", "]", ",", "\"", "\"", ")", "[", "0", "]", "\n", "dst", ".", "WriteString", "(", "ws", "+", "\"", "\"", "+", "n", "+", "\"", "\"", "+", "t", "+", "\"", "\\n", "\"", ")", "\n", "if", "!", "strings", ".", "Contains", "(", "l", ",", "\"", "\"", ")", "{", "// not single liner", "unmatchedBraces", "=", "1", "\n", "}", "\n", "fps", "=", "append", "(", "fps", ",", "&", "Failpoint", "{", "name", ":", "n", ",", "varType", ":", "t", "}", ")", "\n", "continue", "\n", "}", "\n\n", "if", "isLabel", ":=", "strings", ".", "Contains", "(", "l", ",", "\"", "\\t", "\"", ")", ";", "isLabel", "{", "l", "=", "strings", ".", "Replace", "(", "l", ",", "\"", "\"", ",", "\"", "\"", ",", "1", ")", "\n", "}", "\n\n", "if", "_", ",", "werr", ":=", "dst", ".", "WriteString", "(", "l", ")", ";", "werr", "!=", "nil", "{", "return", "fps", ",", "werr", "\n", "}", "\n", "}", "\n", "if", "err", "==", "io", ".", "EOF", "{", "err", "=", "nil", "\n", "}", "\n", "dst", ".", "Flush", "(", ")", "\n", "return", "\n", "}" ]
// ToComments turns all failpoint code into GOFAIL comments. It returns // a list of all failpoints it deactivated.
[ "ToComments", "turns", "all", "failpoint", "code", "into", "GOFAIL", "comments", ".", "It", "returns", "a", "list", "of", "all", "failpoints", "it", "deactivated", "." ]
51ce9a71510a58bad5ae66ddd278ef28762a1550
https://github.com/etcd-io/gofail/blob/51ce9a71510a58bad5ae66ddd278ef28762a1550/code/rewrite.go#L75-L124
144,768
etcd-io/gofail
code/rewrite.go
wsPrefix
func wsPrefix(l, wsPfx string) string { lws := "" if len(wsPfx) == 0 { lws = l } else { wsSplit := strings.SplitAfter(l, wsPfx) if len(wsSplit) < 2 { return "" } lws = strings.Join(wsSplit[1:], "") } for i, c := range lws { if !unicode.IsSpace(c) { return lws[:i] } } return lws }
go
func wsPrefix(l, wsPfx string) string { lws := "" if len(wsPfx) == 0 { lws = l } else { wsSplit := strings.SplitAfter(l, wsPfx) if len(wsSplit) < 2 { return "" } lws = strings.Join(wsSplit[1:], "") } for i, c := range lws { if !unicode.IsSpace(c) { return lws[:i] } } return lws }
[ "func", "wsPrefix", "(", "l", ",", "wsPfx", "string", ")", "string", "{", "lws", ":=", "\"", "\"", "\n", "if", "len", "(", "wsPfx", ")", "==", "0", "{", "lws", "=", "l", "\n", "}", "else", "{", "wsSplit", ":=", "strings", ".", "SplitAfter", "(", "l", ",", "wsPfx", ")", "\n", "if", "len", "(", "wsSplit", ")", "<", "2", "{", "return", "\"", "\"", "\n", "}", "\n", "lws", "=", "strings", ".", "Join", "(", "wsSplit", "[", "1", ":", "]", ",", "\"", "\"", ")", "\n", "}", "\n", "for", "i", ",", "c", ":=", "range", "lws", "{", "if", "!", "unicode", ".", "IsSpace", "(", "c", ")", "{", "return", "lws", "[", ":", "i", "]", "\n", "}", "\n", "}", "\n", "return", "lws", "\n", "}" ]
// wsPrefix computes the left padding of a line given a whitespace prefix.
[ "wsPrefix", "computes", "the", "left", "padding", "of", "a", "line", "given", "a", "whitespace", "prefix", "." ]
51ce9a71510a58bad5ae66ddd278ef28762a1550
https://github.com/etcd-io/gofail/blob/51ce9a71510a58bad5ae66ddd278ef28762a1550/code/rewrite.go#L150-L167
144,769
etcd-io/gofail
runtime/runtime.go
Enable
func Enable(failpath, inTerms string) error { unlock, err := enableAndLock(failpath, inTerms) if unlock != nil { unlock() } return err }
go
func Enable(failpath, inTerms string) error { unlock, err := enableAndLock(failpath, inTerms) if unlock != nil { unlock() } return err }
[ "func", "Enable", "(", "failpath", ",", "inTerms", "string", ")", "error", "{", "unlock", ",", "err", ":=", "enableAndLock", "(", "failpath", ",", "inTerms", ")", "\n", "if", "unlock", "!=", "nil", "{", "unlock", "(", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Enable sets a failpoint to a given failpoint description.
[ "Enable", "sets", "a", "failpoint", "to", "a", "given", "failpoint", "description", "." ]
51ce9a71510a58bad5ae66ddd278ef28762a1550
https://github.com/etcd-io/gofail/blob/51ce9a71510a58bad5ae66ddd278ef28762a1550/runtime/runtime.go#L56-L62
144,770
etcd-io/gofail
runtime/runtime.go
enableAndLock
func enableAndLock(failpath, inTerms string) (func(), error) { t, err := newTerms(failpath, inTerms) if err != nil { fmt.Printf("failed to enable \"%s=%s\" (%v)\n", failpath, inTerms, err) return nil, err } failpointsMu.RLock() fp := failpoints[failpath] failpointsMu.RUnlock() if fp == nil { return nil, ErrNoExist } fp.mu.Lock() fp.t = t return func() { fp.mu.Unlock() }, nil }
go
func enableAndLock(failpath, inTerms string) (func(), error) { t, err := newTerms(failpath, inTerms) if err != nil { fmt.Printf("failed to enable \"%s=%s\" (%v)\n", failpath, inTerms, err) return nil, err } failpointsMu.RLock() fp := failpoints[failpath] failpointsMu.RUnlock() if fp == nil { return nil, ErrNoExist } fp.mu.Lock() fp.t = t return func() { fp.mu.Unlock() }, nil }
[ "func", "enableAndLock", "(", "failpath", ",", "inTerms", "string", ")", "(", "func", "(", ")", ",", "error", ")", "{", "t", ",", "err", ":=", "newTerms", "(", "failpath", ",", "inTerms", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"", "\\\"", "\\\"", "\\n", "\"", ",", "failpath", ",", "inTerms", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "failpointsMu", ".", "RLock", "(", ")", "\n", "fp", ":=", "failpoints", "[", "failpath", "]", "\n", "failpointsMu", ".", "RUnlock", "(", ")", "\n", "if", "fp", "==", "nil", "{", "return", "nil", ",", "ErrNoExist", "\n", "}", "\n", "fp", ".", "mu", ".", "Lock", "(", ")", "\n", "fp", ".", "t", "=", "t", "\n", "return", "func", "(", ")", "{", "fp", ".", "mu", ".", "Unlock", "(", ")", "}", ",", "nil", "\n", "}" ]
// enableAndLock enables a failpoint and returns a function to unlock it
[ "enableAndLock", "enables", "a", "failpoint", "and", "returns", "a", "function", "to", "unlock", "it" ]
51ce9a71510a58bad5ae66ddd278ef28762a1550
https://github.com/etcd-io/gofail/blob/51ce9a71510a58bad5ae66ddd278ef28762a1550/runtime/runtime.go#L65-L80
144,771
etcd-io/gofail
runtime/runtime.go
Disable
func Disable(failpath string) error { failpointsMu.RLock() fp := failpoints[failpath] failpointsMu.RUnlock() if fp == nil { return ErrNoExist } fp.mu.Lock() defer fp.mu.Unlock() if fp.t == nil { return ErrDisabled } fp.t = nil return nil }
go
func Disable(failpath string) error { failpointsMu.RLock() fp := failpoints[failpath] failpointsMu.RUnlock() if fp == nil { return ErrNoExist } fp.mu.Lock() defer fp.mu.Unlock() if fp.t == nil { return ErrDisabled } fp.t = nil return nil }
[ "func", "Disable", "(", "failpath", "string", ")", "error", "{", "failpointsMu", ".", "RLock", "(", ")", "\n", "fp", ":=", "failpoints", "[", "failpath", "]", "\n", "failpointsMu", ".", "RUnlock", "(", ")", "\n", "if", "fp", "==", "nil", "{", "return", "ErrNoExist", "\n", "}", "\n", "fp", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "fp", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "fp", ".", "t", "==", "nil", "{", "return", "ErrDisabled", "\n", "}", "\n", "fp", ".", "t", "=", "nil", "\n", "return", "nil", "\n", "}" ]
// Disable stops a failpoint from firing.
[ "Disable", "stops", "a", "failpoint", "from", "firing", "." ]
51ce9a71510a58bad5ae66ddd278ef28762a1550
https://github.com/etcd-io/gofail/blob/51ce9a71510a58bad5ae66ddd278ef28762a1550/runtime/runtime.go#L83-L97
144,772
etcd-io/gofail
runtime/runtime.go
Status
func Status(failpath string) (string, error) { failpointsMu.RLock() fp := failpoints[failpath] failpointsMu.RUnlock() if fp == nil { return "", ErrNoExist } fp.mu.RLock() t := fp.t fp.mu.RUnlock() if t == nil { return "", ErrDisabled } return t.desc, nil }
go
func Status(failpath string) (string, error) { failpointsMu.RLock() fp := failpoints[failpath] failpointsMu.RUnlock() if fp == nil { return "", ErrNoExist } fp.mu.RLock() t := fp.t fp.mu.RUnlock() if t == nil { return "", ErrDisabled } return t.desc, nil }
[ "func", "Status", "(", "failpath", "string", ")", "(", "string", ",", "error", ")", "{", "failpointsMu", ".", "RLock", "(", ")", "\n", "fp", ":=", "failpoints", "[", "failpath", "]", "\n", "failpointsMu", ".", "RUnlock", "(", ")", "\n", "if", "fp", "==", "nil", "{", "return", "\"", "\"", ",", "ErrNoExist", "\n", "}", "\n", "fp", ".", "mu", ".", "RLock", "(", ")", "\n", "t", ":=", "fp", ".", "t", "\n", "fp", ".", "mu", ".", "RUnlock", "(", ")", "\n", "if", "t", "==", "nil", "{", "return", "\"", "\"", ",", "ErrDisabled", "\n", "}", "\n", "return", "t", ".", "desc", ",", "nil", "\n", "}" ]
// Status gives the current setting for the failpoint
[ "Status", "gives", "the", "current", "setting", "for", "the", "failpoint" ]
51ce9a71510a58bad5ae66ddd278ef28762a1550
https://github.com/etcd-io/gofail/blob/51ce9a71510a58bad5ae66ddd278ef28762a1550/runtime/runtime.go#L100-L114
144,773
etcd-io/gofail
code/binding.go
Write
func (b *Binding) Write(dst io.Writer) error { hdr := "// GENERATED BY GOFAIL. DO NOT EDIT.\n\n" + "package " + b.pkg + "\n\nimport \"github.com/etcd-io/gofail/runtime\"\n\n" if _, err := fmt.Fprint(dst, hdr); err != nil { return err } for _, fp := range b.fps { _, err := fmt.Fprintf( dst, "var %s *runtime.Failpoint = runtime.NewFailpoint(%q, %q)\n", fp.Runtime(), b.fppath, fp.Name()) if err != nil { return err } } return nil }
go
func (b *Binding) Write(dst io.Writer) error { hdr := "// GENERATED BY GOFAIL. DO NOT EDIT.\n\n" + "package " + b.pkg + "\n\nimport \"github.com/etcd-io/gofail/runtime\"\n\n" if _, err := fmt.Fprint(dst, hdr); err != nil { return err } for _, fp := range b.fps { _, err := fmt.Fprintf( dst, "var %s *runtime.Failpoint = runtime.NewFailpoint(%q, %q)\n", fp.Runtime(), b.fppath, fp.Name()) if err != nil { return err } } return nil }
[ "func", "(", "b", "*", "Binding", ")", "Write", "(", "dst", "io", ".", "Writer", ")", "error", "{", "hdr", ":=", "\"", "\\n", "\\n", "\"", "+", "\"", "\"", "+", "b", ".", "pkg", "+", "\"", "\\n", "\\n", "\\\"", "\\\"", "\\n", "\\n", "\"", "\n", "if", "_", ",", "err", ":=", "fmt", ".", "Fprint", "(", "dst", ",", "hdr", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "_", ",", "fp", ":=", "range", "b", ".", "fps", "{", "_", ",", "err", ":=", "fmt", ".", "Fprintf", "(", "dst", ",", "\"", "\\n", "\"", ",", "fp", ".", "Runtime", "(", ")", ",", "b", ".", "fppath", ",", "fp", ".", "Name", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Write writes the fp.generated.go file for a package.
[ "Write", "writes", "the", "fp", ".", "generated", ".", "go", "file", "for", "a", "package", "." ]
51ce9a71510a58bad5ae66ddd278ef28762a1550
https://github.com/etcd-io/gofail/blob/51ce9a71510a58bad5ae66ddd278ef28762a1550/code/binding.go#L33-L52
144,774
rjeczalik/notify
watcher_fen.go
Init
func (f *fen) Init() (err error) { f.p, err = f.cf.portCreate() return }
go
func (f *fen) Init() (err error) { f.p, err = f.cf.portCreate() return }
[ "func", "(", "f", "*", "fen", ")", "Init", "(", ")", "(", "err", "error", ")", "{", "f", ".", "p", ",", "err", "=", "f", ".", "cf", ".", "portCreate", "(", ")", "\n", "return", "\n", "}" ]
// init initializes FEN.
[ "init", "initializes", "FEN", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_fen.go#L87-L90
144,775
rjeczalik/notify
watchpoint.go
Add
func (wp watchpoint) Add(c chan<- EventInfo, e Event) (diff eventDiff) { wp[c] |= e diff[0] = wp[nil] diff[1] = diff[0] | e wp[nil] = diff[1] &^ omit // Strip diff from internal events. diff[0] &^= internal diff[1] &^= internal if diff[0] == diff[1] { return none } return }
go
func (wp watchpoint) Add(c chan<- EventInfo, e Event) (diff eventDiff) { wp[c] |= e diff[0] = wp[nil] diff[1] = diff[0] | e wp[nil] = diff[1] &^ omit // Strip diff from internal events. diff[0] &^= internal diff[1] &^= internal if diff[0] == diff[1] { return none } return }
[ "func", "(", "wp", "watchpoint", ")", "Add", "(", "c", "chan", "<-", "EventInfo", ",", "e", "Event", ")", "(", "diff", "eventDiff", ")", "{", "wp", "[", "c", "]", "|=", "e", "\n", "diff", "[", "0", "]", "=", "wp", "[", "nil", "]", "\n", "diff", "[", "1", "]", "=", "diff", "[", "0", "]", "|", "e", "\n", "wp", "[", "nil", "]", "=", "diff", "[", "1", "]", "&^", "omit", "\n", "// Strip diff from internal events.", "diff", "[", "0", "]", "&^=", "internal", "\n", "diff", "[", "1", "]", "&^=", "internal", "\n", "if", "diff", "[", "0", "]", "==", "diff", "[", "1", "]", "{", "return", "none", "\n", "}", "\n", "return", "\n", "}" ]
// Add assumes neither c nor e are nil or zero values.
[ "Add", "assumes", "neither", "c", "nor", "e", "are", "nil", "or", "zero", "values", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watchpoint.go#L44-L56
144,776
rjeczalik/notify
watcher_readdcw.go
readDirChanges
func (g *grip) readDirChanges() error { handle := syscall.Handle(atomic.LoadUintptr((*uintptr)(&g.handle))) if handle == syscall.InvalidHandle { return nil // Handle was closed. } return syscall.ReadDirectoryChanges( handle, &g.buffer[0], uint32(unsafe.Sizeof(g.buffer)), g.recursive, encode(g.filter), nil, (*syscall.Overlapped)(unsafe.Pointer(g.ovlapped)), 0, ) }
go
func (g *grip) readDirChanges() error { handle := syscall.Handle(atomic.LoadUintptr((*uintptr)(&g.handle))) if handle == syscall.InvalidHandle { return nil // Handle was closed. } return syscall.ReadDirectoryChanges( handle, &g.buffer[0], uint32(unsafe.Sizeof(g.buffer)), g.recursive, encode(g.filter), nil, (*syscall.Overlapped)(unsafe.Pointer(g.ovlapped)), 0, ) }
[ "func", "(", "g", "*", "grip", ")", "readDirChanges", "(", ")", "error", "{", "handle", ":=", "syscall", ".", "Handle", "(", "atomic", ".", "LoadUintptr", "(", "(", "*", "uintptr", ")", "(", "&", "g", ".", "handle", ")", ")", ")", "\n", "if", "handle", "==", "syscall", ".", "InvalidHandle", "{", "return", "nil", "// Handle was closed.", "\n", "}", "\n\n", "return", "syscall", ".", "ReadDirectoryChanges", "(", "handle", ",", "&", "g", ".", "buffer", "[", "0", "]", ",", "uint32", "(", "unsafe", ".", "Sizeof", "(", "g", ".", "buffer", ")", ")", ",", "g", ".", "recursive", ",", "encode", "(", "g", ".", "filter", ")", ",", "nil", ",", "(", "*", "syscall", ".", "Overlapped", ")", "(", "unsafe", ".", "Pointer", "(", "g", ".", "ovlapped", ")", ")", ",", "0", ",", ")", "\n", "}" ]
// readDirChanges tells the system to store file change information in grip's // buffer. Directory changes that occur between calls to this function are added // to the buffer and then, returned with the next call.
[ "readDirChanges", "tells", "the", "system", "to", "store", "file", "change", "information", "in", "grip", "s", "buffer", ".", "Directory", "changes", "that", "occur", "between", "calls", "to", "this", "function", "are", "added", "to", "the", "buffer", "and", "then", "returned", "with", "the", "next", "call", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_readdcw.go#L111-L127
144,777
rjeczalik/notify
watcher_readdcw.go
encode
func encode(filter uint32) uint32 { e := Event(filter & (onlyNGlobalEvents | onlyNotifyChanges)) if e&dirmarker != 0 { return uint32(FileNotifyChangeDirName) } if e&Create != 0 { e = (e ^ Create) | FileNotifyChangeFileName } if e&Remove != 0 { e = (e ^ Remove) | FileNotifyChangeFileName } if e&Write != 0 { e = (e ^ Write) | FileNotifyChangeAttributes | FileNotifyChangeSize | FileNotifyChangeCreation | FileNotifyChangeSecurity } if e&Rename != 0 { e = (e ^ Rename) | FileNotifyChangeFileName } return uint32(e) }
go
func encode(filter uint32) uint32 { e := Event(filter & (onlyNGlobalEvents | onlyNotifyChanges)) if e&dirmarker != 0 { return uint32(FileNotifyChangeDirName) } if e&Create != 0 { e = (e ^ Create) | FileNotifyChangeFileName } if e&Remove != 0 { e = (e ^ Remove) | FileNotifyChangeFileName } if e&Write != 0 { e = (e ^ Write) | FileNotifyChangeAttributes | FileNotifyChangeSize | FileNotifyChangeCreation | FileNotifyChangeSecurity } if e&Rename != 0 { e = (e ^ Rename) | FileNotifyChangeFileName } return uint32(e) }
[ "func", "encode", "(", "filter", "uint32", ")", "uint32", "{", "e", ":=", "Event", "(", "filter", "&", "(", "onlyNGlobalEvents", "|", "onlyNotifyChanges", ")", ")", "\n", "if", "e", "&", "dirmarker", "!=", "0", "{", "return", "uint32", "(", "FileNotifyChangeDirName", ")", "\n", "}", "\n", "if", "e", "&", "Create", "!=", "0", "{", "e", "=", "(", "e", "^", "Create", ")", "|", "FileNotifyChangeFileName", "\n", "}", "\n", "if", "e", "&", "Remove", "!=", "0", "{", "e", "=", "(", "e", "^", "Remove", ")", "|", "FileNotifyChangeFileName", "\n", "}", "\n", "if", "e", "&", "Write", "!=", "0", "{", "e", "=", "(", "e", "^", "Write", ")", "|", "FileNotifyChangeAttributes", "|", "FileNotifyChangeSize", "|", "FileNotifyChangeCreation", "|", "FileNotifyChangeSecurity", "\n", "}", "\n", "if", "e", "&", "Rename", "!=", "0", "{", "e", "=", "(", "e", "^", "Rename", ")", "|", "FileNotifyChangeFileName", "\n", "}", "\n", "return", "uint32", "(", "e", ")", "\n", "}" ]
// encode transforms a generic filter, which contains platform independent and // implementation specific bit fields, to value that can be used as NotifyFilter // parameter in ReadDirectoryChangesW function.
[ "encode", "transforms", "a", "generic", "filter", "which", "contains", "platform", "independent", "and", "implementation", "specific", "bit", "fields", "to", "value", "that", "can", "be", "used", "as", "NotifyFilter", "parameter", "in", "ReadDirectoryChangesW", "function", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_readdcw.go#L132-L151
144,778
rjeczalik/notify
watcher_readdcw.go
closeHandle
func (wd *watched) closeHandle() (err error) { for _, g := range wd.digrip { if g == nil { continue } for { handle := syscall.Handle(atomic.LoadUintptr((*uintptr)(&g.handle))) if handle == syscall.InvalidHandle { break // Already closed. } e := syscall.CloseHandle(handle) if e != nil && err == nil { err = e } // Set invalid handle even when CloseHandle fails. This will leak // the handle but, since we can't close it anyway, there won't be // any difference. if atomic.CompareAndSwapUintptr((*uintptr)(&g.handle), (uintptr)(handle), (uintptr)(syscall.InvalidHandle)) { break } } } return }
go
func (wd *watched) closeHandle() (err error) { for _, g := range wd.digrip { if g == nil { continue } for { handle := syscall.Handle(atomic.LoadUintptr((*uintptr)(&g.handle))) if handle == syscall.InvalidHandle { break // Already closed. } e := syscall.CloseHandle(handle) if e != nil && err == nil { err = e } // Set invalid handle even when CloseHandle fails. This will leak // the handle but, since we can't close it anyway, there won't be // any difference. if atomic.CompareAndSwapUintptr((*uintptr)(&g.handle), (uintptr)(handle), (uintptr)(syscall.InvalidHandle)) { break } } } return }
[ "func", "(", "wd", "*", "watched", ")", "closeHandle", "(", ")", "(", "err", "error", ")", "{", "for", "_", ",", "g", ":=", "range", "wd", ".", "digrip", "{", "if", "g", "==", "nil", "{", "continue", "\n", "}", "\n\n", "for", "{", "handle", ":=", "syscall", ".", "Handle", "(", "atomic", ".", "LoadUintptr", "(", "(", "*", "uintptr", ")", "(", "&", "g", ".", "handle", ")", ")", ")", "\n", "if", "handle", "==", "syscall", ".", "InvalidHandle", "{", "break", "// Already closed.", "\n", "}", "\n\n", "e", ":=", "syscall", ".", "CloseHandle", "(", "handle", ")", "\n", "if", "e", "!=", "nil", "&&", "err", "==", "nil", "{", "err", "=", "e", "\n", "}", "\n\n", "// Set invalid handle even when CloseHandle fails. This will leak", "// the handle but, since we can't close it anyway, there won't be", "// any difference.", "if", "atomic", ".", "CompareAndSwapUintptr", "(", "(", "*", "uintptr", ")", "(", "&", "g", ".", "handle", ")", ",", "(", "uintptr", ")", "(", "handle", ")", ",", "(", "uintptr", ")", "(", "syscall", ".", "InvalidHandle", ")", ")", "{", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// closeHandle closes handles that are stored in digrip array. Function always // tries to close all of the handlers before it exits, even when there are errors // returned from the operating system kernel.
[ "closeHandle", "closes", "handles", "that", "are", "stored", "in", "digrip", "array", ".", "Function", "always", "tries", "to", "close", "all", "of", "the", "handlers", "before", "it", "exits", "even", "when", "there", "are", "errors", "returned", "from", "the", "operating", "system", "kernel", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_readdcw.go#L226-L253
144,779
rjeczalik/notify
watcher_readdcw.go
newWatcher
func newWatcher(c chan<- EventInfo) watcher { r := &readdcw{ m: make(map[string]*watched), cph: syscall.InvalidHandle, c: c, } runtime.SetFinalizer(r, func(r *readdcw) { if r.cph != syscall.InvalidHandle { syscall.CloseHandle(r.cph) } }) return r }
go
func newWatcher(c chan<- EventInfo) watcher { r := &readdcw{ m: make(map[string]*watched), cph: syscall.InvalidHandle, c: c, } runtime.SetFinalizer(r, func(r *readdcw) { if r.cph != syscall.InvalidHandle { syscall.CloseHandle(r.cph) } }) return r }
[ "func", "newWatcher", "(", "c", "chan", "<-", "EventInfo", ")", "watcher", "{", "r", ":=", "&", "readdcw", "{", "m", ":", "make", "(", "map", "[", "string", "]", "*", "watched", ")", ",", "cph", ":", "syscall", ".", "InvalidHandle", ",", "c", ":", "c", ",", "}", "\n", "runtime", ".", "SetFinalizer", "(", "r", ",", "func", "(", "r", "*", "readdcw", ")", "{", "if", "r", ".", "cph", "!=", "syscall", ".", "InvalidHandle", "{", "syscall", ".", "CloseHandle", "(", "r", ".", "cph", ")", "\n", "}", "\n", "}", ")", "\n", "return", "r", "\n", "}" ]
// NewWatcher creates new non-recursive watcher backed by ReadDirectoryChangesW.
[ "NewWatcher", "creates", "new", "non", "-", "recursive", "watcher", "backed", "by", "ReadDirectoryChangesW", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_readdcw.go#L268-L280
144,780
rjeczalik/notify
watcher_readdcw.go
Watch
func (r *readdcw) Watch(path string, event Event) error { return r.watch(path, event, false) }
go
func (r *readdcw) Watch(path string, event Event) error { return r.watch(path, event, false) }
[ "func", "(", "r", "*", "readdcw", ")", "Watch", "(", "path", "string", ",", "event", "Event", ")", "error", "{", "return", "r", ".", "watch", "(", "path", ",", "event", ",", "false", ")", "\n", "}" ]
// Watch implements notify.Watcher interface.
[ "Watch", "implements", "notify", ".", "Watcher", "interface", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_readdcw.go#L283-L285
144,781
rjeczalik/notify
watcher_readdcw.go
RecursiveWatch
func (r *readdcw) RecursiveWatch(path string, event Event) error { return r.watch(path, event, true) }
go
func (r *readdcw) RecursiveWatch(path string, event Event) error { return r.watch(path, event, true) }
[ "func", "(", "r", "*", "readdcw", ")", "RecursiveWatch", "(", "path", "string", ",", "event", "Event", ")", "error", "{", "return", "r", ".", "watch", "(", "path", ",", "event", ",", "true", ")", "\n", "}" ]
// RecursiveWatch implements notify.RecursiveWatcher interface.
[ "RecursiveWatch", "implements", "notify", ".", "RecursiveWatcher", "interface", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_readdcw.go#L288-L290
144,782
rjeczalik/notify
watcher_readdcw.go
Rewatch
func (r *readdcw) Rewatch(path string, oldevent, newevent Event) error { return r.rewatch(path, uint32(oldevent), uint32(newevent), false) }
go
func (r *readdcw) Rewatch(path string, oldevent, newevent Event) error { return r.rewatch(path, uint32(oldevent), uint32(newevent), false) }
[ "func", "(", "r", "*", "readdcw", ")", "Rewatch", "(", "path", "string", ",", "oldevent", ",", "newevent", "Event", ")", "error", "{", "return", "r", ".", "rewatch", "(", "path", ",", "uint32", "(", "oldevent", ")", ",", "uint32", "(", "newevent", ")", ",", "false", ")", "\n", "}" ]
// Rewatch implements notify.Rewatcher interface.
[ "Rewatch", "implements", "notify", ".", "Rewatcher", "interface", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_readdcw.go#L451-L453
144,783
rjeczalik/notify
watcher_readdcw.go
RecursiveRewatch
func (r *readdcw) RecursiveRewatch(oldpath, newpath string, oldevent, newevent Event) error { if oldpath != newpath { if err := r.unwatch(oldpath); err != nil { return err } return r.watch(newpath, newevent, true) } return r.rewatch(newpath, uint32(oldevent), uint32(newevent), true) }
go
func (r *readdcw) RecursiveRewatch(oldpath, newpath string, oldevent, newevent Event) error { if oldpath != newpath { if err := r.unwatch(oldpath); err != nil { return err } return r.watch(newpath, newevent, true) } return r.rewatch(newpath, uint32(oldevent), uint32(newevent), true) }
[ "func", "(", "r", "*", "readdcw", ")", "RecursiveRewatch", "(", "oldpath", ",", "newpath", "string", ",", "oldevent", ",", "newevent", "Event", ")", "error", "{", "if", "oldpath", "!=", "newpath", "{", "if", "err", ":=", "r", ".", "unwatch", "(", "oldpath", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "r", ".", "watch", "(", "newpath", ",", "newevent", ",", "true", ")", "\n", "}", "\n", "return", "r", ".", "rewatch", "(", "newpath", ",", "uint32", "(", "oldevent", ")", ",", "uint32", "(", "newevent", ")", ",", "true", ")", "\n", "}" ]
// RecursiveRewatch implements notify.RecursiveRewatcher interface.
[ "RecursiveRewatch", "implements", "notify", ".", "RecursiveRewatcher", "interface", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_readdcw.go#L456-L465
144,784
rjeczalik/notify
watcher_readdcw.go
Close
func (r *readdcw) Close() (err error) { r.Lock() if !r.start { r.Unlock() return nil } for _, wd := range r.m { wd.filter &^= onlyMachineStates wd.filter |= stateCPClose if e := wd.closeHandle(); e != nil && err == nil { err = e } } r.start = false r.Unlock() r.wg.Add(1) if e := syscall.PostQueuedCompletionStatus(r.cph, 0, stateCPClose, nil); e != nil && err == nil { return e } r.wg.Wait() return }
go
func (r *readdcw) Close() (err error) { r.Lock() if !r.start { r.Unlock() return nil } for _, wd := range r.m { wd.filter &^= onlyMachineStates wd.filter |= stateCPClose if e := wd.closeHandle(); e != nil && err == nil { err = e } } r.start = false r.Unlock() r.wg.Add(1) if e := syscall.PostQueuedCompletionStatus(r.cph, 0, stateCPClose, nil); e != nil && err == nil { return e } r.wg.Wait() return }
[ "func", "(", "r", "*", "readdcw", ")", "Close", "(", ")", "(", "err", "error", ")", "{", "r", ".", "Lock", "(", ")", "\n", "if", "!", "r", ".", "start", "{", "r", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "}", "\n", "for", "_", ",", "wd", ":=", "range", "r", ".", "m", "{", "wd", ".", "filter", "&^=", "onlyMachineStates", "\n", "wd", ".", "filter", "|=", "stateCPClose", "\n", "if", "e", ":=", "wd", ".", "closeHandle", "(", ")", ";", "e", "!=", "nil", "&&", "err", "==", "nil", "{", "err", "=", "e", "\n", "}", "\n", "}", "\n", "r", ".", "start", "=", "false", "\n", "r", ".", "Unlock", "(", ")", "\n", "r", ".", "wg", ".", "Add", "(", "1", ")", "\n", "if", "e", ":=", "syscall", ".", "PostQueuedCompletionStatus", "(", "r", ".", "cph", ",", "0", ",", "stateCPClose", ",", "nil", ")", ";", "e", "!=", "nil", "&&", "err", "==", "nil", "{", "return", "e", "\n", "}", "\n", "r", ".", "wg", ".", "Wait", "(", ")", "\n", "return", "\n", "}" ]
// Close resets the whole watcher object, closes all existing file descriptors, // and sends stateCPClose state as completion key to the main watcher's loop.
[ "Close", "resets", "the", "whole", "watcher", "object", "closes", "all", "existing", "file", "descriptors", "and", "sends", "stateCPClose", "state", "as", "completion", "key", "to", "the", "main", "watcher", "s", "loop", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_readdcw.go#L547-L568
144,785
rjeczalik/notify
watcher_readdcw.go
gensys
func gensys(filter uint32, ge, se Event) (gene, syse Event) { isdir := filter&uint32(dirmarker) != 0 if isdir && filter&uint32(FileNotifyChangeDirName) != 0 || !isdir && filter&uint32(FileNotifyChangeFileName) != 0 || filter&uint32(fileNotifyChangeModified) != 0 { syse = se } if filter&uint32(ge) != 0 { gene = ge } return }
go
func gensys(filter uint32, ge, se Event) (gene, syse Event) { isdir := filter&uint32(dirmarker) != 0 if isdir && filter&uint32(FileNotifyChangeDirName) != 0 || !isdir && filter&uint32(FileNotifyChangeFileName) != 0 || filter&uint32(fileNotifyChangeModified) != 0 { syse = se } if filter&uint32(ge) != 0 { gene = ge } return }
[ "func", "gensys", "(", "filter", "uint32", ",", "ge", ",", "se", "Event", ")", "(", "gene", ",", "syse", "Event", ")", "{", "isdir", ":=", "filter", "&", "uint32", "(", "dirmarker", ")", "!=", "0", "\n", "if", "isdir", "&&", "filter", "&", "uint32", "(", "FileNotifyChangeDirName", ")", "!=", "0", "||", "!", "isdir", "&&", "filter", "&", "uint32", "(", "FileNotifyChangeFileName", ")", "!=", "0", "||", "filter", "&", "uint32", "(", "fileNotifyChangeModified", ")", "!=", "0", "{", "syse", "=", "se", "\n", "}", "\n", "if", "filter", "&", "uint32", "(", "ge", ")", "!=", "0", "{", "gene", "=", "ge", "\n", "}", "\n", "return", "\n", "}" ]
// gensys decides whether the Windows action, system-independent event or both // of them should be returned. Since the grip's filter may be atomically changed // during watcher lifetime, it is possible that neither Windows nor notify masks // are watched by the user when this function is called.
[ "gensys", "decides", "whether", "the", "Windows", "action", "system", "-", "independent", "event", "or", "both", "of", "them", "should", "be", "returned", ".", "Since", "the", "grip", "s", "filter", "may", "be", "atomically", "changed", "during", "watcher", "lifetime", "it", "is", "possible", "that", "neither", "Windows", "nor", "notify", "masks", "are", "watched", "by", "the", "user", "when", "this", "function", "is", "called", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_readdcw.go#L594-L605
144,786
rjeczalik/notify
watcher_fsevents.go
splitflags
func splitflags(set uint32) (e []uint32) { for i := uint32(1); set != 0; i, set = i<<1, set>>1 { if (set & 1) != 0 { e = append(e, i) } } return }
go
func splitflags(set uint32) (e []uint32) { for i := uint32(1); set != 0; i, set = i<<1, set>>1 { if (set & 1) != 0 { e = append(e, i) } } return }
[ "func", "splitflags", "(", "set", "uint32", ")", "(", "e", "[", "]", "uint32", ")", "{", "for", "i", ":=", "uint32", "(", "1", ")", ";", "set", "!=", "0", ";", "i", ",", "set", "=", "i", "<<", "1", ",", "set", ">>", "1", "{", "if", "(", "set", "&", "1", ")", "!=", "0", "{", "e", "=", "append", "(", "e", ",", "i", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// splitflags separates event flags from single set into slice of flags.
[ "splitflags", "separates", "event", "flags", "from", "single", "set", "into", "slice", "of", "flags", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_fsevents.go#L30-L37
144,787
rjeczalik/notify
watcher_fsevents.go
Dispatch
func (w *watch) Dispatch(ev []FSEvent) { events := atomic.LoadUint32(&w.events) isrec := (atomic.LoadInt32(&w.isrec) == 1) for i := range ev { if ev[i].Flags&FSEventsHistoryDone != 0 { w.flushed = true continue } if !w.flushed { continue } dbgprintf("%v (0x%x) (%s, i=%d, ID=%d, len=%d)\n", Event(ev[i].Flags), ev[i].Flags, ev[i].Path, i, ev[i].ID, len(ev)) if ev[i].Flags&failure != 0 { // TODO(rjeczalik): missing error handling continue } if !strings.HasPrefix(ev[i].Path, w.path) { continue } n := len(w.path) base := "" if len(ev[i].Path) > n { if ev[i].Path[n] != '/' { continue } base = ev[i].Path[n+1:] if !isrec && strings.IndexByte(base, '/') != -1 { continue } } // TODO(rjeczalik): get diff only from filtered events? e := w.strip(string(base), ev[i].Flags) & events if e == 0 { continue } for _, e := range splitflags(e) { dbgprintf("%d: single event: %v", ev[i].ID, Event(e)) w.c <- &event{ fse: ev[i], event: Event(e), } } } }
go
func (w *watch) Dispatch(ev []FSEvent) { events := atomic.LoadUint32(&w.events) isrec := (atomic.LoadInt32(&w.isrec) == 1) for i := range ev { if ev[i].Flags&FSEventsHistoryDone != 0 { w.flushed = true continue } if !w.flushed { continue } dbgprintf("%v (0x%x) (%s, i=%d, ID=%d, len=%d)\n", Event(ev[i].Flags), ev[i].Flags, ev[i].Path, i, ev[i].ID, len(ev)) if ev[i].Flags&failure != 0 { // TODO(rjeczalik): missing error handling continue } if !strings.HasPrefix(ev[i].Path, w.path) { continue } n := len(w.path) base := "" if len(ev[i].Path) > n { if ev[i].Path[n] != '/' { continue } base = ev[i].Path[n+1:] if !isrec && strings.IndexByte(base, '/') != -1 { continue } } // TODO(rjeczalik): get diff only from filtered events? e := w.strip(string(base), ev[i].Flags) & events if e == 0 { continue } for _, e := range splitflags(e) { dbgprintf("%d: single event: %v", ev[i].ID, Event(e)) w.c <- &event{ fse: ev[i], event: Event(e), } } } }
[ "func", "(", "w", "*", "watch", ")", "Dispatch", "(", "ev", "[", "]", "FSEvent", ")", "{", "events", ":=", "atomic", ".", "LoadUint32", "(", "&", "w", ".", "events", ")", "\n", "isrec", ":=", "(", "atomic", ".", "LoadInt32", "(", "&", "w", ".", "isrec", ")", "==", "1", ")", "\n", "for", "i", ":=", "range", "ev", "{", "if", "ev", "[", "i", "]", ".", "Flags", "&", "FSEventsHistoryDone", "!=", "0", "{", "w", ".", "flushed", "=", "true", "\n", "continue", "\n", "}", "\n", "if", "!", "w", ".", "flushed", "{", "continue", "\n", "}", "\n", "dbgprintf", "(", "\"", "\\n", "\"", ",", "Event", "(", "ev", "[", "i", "]", ".", "Flags", ")", ",", "ev", "[", "i", "]", ".", "Flags", ",", "ev", "[", "i", "]", ".", "Path", ",", "i", ",", "ev", "[", "i", "]", ".", "ID", ",", "len", "(", "ev", ")", ")", "\n", "if", "ev", "[", "i", "]", ".", "Flags", "&", "failure", "!=", "0", "{", "// TODO(rjeczalik): missing error handling", "continue", "\n", "}", "\n", "if", "!", "strings", ".", "HasPrefix", "(", "ev", "[", "i", "]", ".", "Path", ",", "w", ".", "path", ")", "{", "continue", "\n", "}", "\n", "n", ":=", "len", "(", "w", ".", "path", ")", "\n", "base", ":=", "\"", "\"", "\n", "if", "len", "(", "ev", "[", "i", "]", ".", "Path", ")", ">", "n", "{", "if", "ev", "[", "i", "]", ".", "Path", "[", "n", "]", "!=", "'/'", "{", "continue", "\n", "}", "\n", "base", "=", "ev", "[", "i", "]", ".", "Path", "[", "n", "+", "1", ":", "]", "\n", "if", "!", "isrec", "&&", "strings", ".", "IndexByte", "(", "base", ",", "'/'", ")", "!=", "-", "1", "{", "continue", "\n", "}", "\n", "}", "\n", "// TODO(rjeczalik): get diff only from filtered events?", "e", ":=", "w", ".", "strip", "(", "string", "(", "base", ")", ",", "ev", "[", "i", "]", ".", "Flags", ")", "&", "events", "\n", "if", "e", "==", "0", "{", "continue", "\n", "}", "\n", "for", "_", ",", "e", ":=", "range", "splitflags", "(", "e", ")", "{", "dbgprintf", "(", "\"", "\"", ",", "ev", "[", "i", "]", ".", "ID", ",", "Event", "(", "e", ")", ")", "\n", "w", ".", "c", "<-", "&", "event", "{", "fse", ":", "ev", "[", "i", "]", ",", "event", ":", "Event", "(", "e", ")", ",", "}", "\n", "}", "\n", "}", "\n", "}" ]
// Dispatch is a stream function which forwards given file events for the watched // path to underlying FileInfo channel.
[ "Dispatch", "is", "a", "stream", "function", "which", "forwards", "given", "file", "events", "for", "the", "watched", "path", "to", "underlying", "FileInfo", "channel", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_fsevents.go#L119-L163
144,788
rjeczalik/notify
watcher_fsevents.go
Stop
func (w *watch) Stop() { w.stream.Stop() // TODO(rjeczalik): make (*stream).Stop flush synchronously undelivered events, // so the following hack can be removed. It should flush all the streams // concurrently as we care not to block too much here. atomic.StoreUint32(&w.events, 0) atomic.StoreInt32(&w.isrec, 0) }
go
func (w *watch) Stop() { w.stream.Stop() // TODO(rjeczalik): make (*stream).Stop flush synchronously undelivered events, // so the following hack can be removed. It should flush all the streams // concurrently as we care not to block too much here. atomic.StoreUint32(&w.events, 0) atomic.StoreInt32(&w.isrec, 0) }
[ "func", "(", "w", "*", "watch", ")", "Stop", "(", ")", "{", "w", ".", "stream", ".", "Stop", "(", ")", "\n", "// TODO(rjeczalik): make (*stream).Stop flush synchronously undelivered events,", "// so the following hack can be removed. It should flush all the streams", "// concurrently as we care not to block too much here.", "atomic", ".", "StoreUint32", "(", "&", "w", ".", "events", ",", "0", ")", "\n", "atomic", ".", "StoreInt32", "(", "&", "w", ".", "isrec", ",", "0", ")", "\n", "}" ]
// Stop closes underlying FSEvents stream and stops dispatching events.
[ "Stop", "closes", "underlying", "FSEvents", "stream", "and", "stops", "dispatching", "events", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_fsevents.go#L166-L173
144,789
rjeczalik/notify
watcher_fsevents.go
Watch
func (fse *fsevents) Watch(path string, event Event) error { return fse.watch(path, event, 0) }
go
func (fse *fsevents) Watch(path string, event Event) error { return fse.watch(path, event, 0) }
[ "func", "(", "fse", "*", "fsevents", ")", "Watch", "(", "path", "string", ",", "event", "Event", ")", "error", "{", "return", "fse", ".", "watch", "(", "path", ",", "event", ",", "0", ")", "\n", "}" ]
// Watch implements Watcher interface. It fails with non-nil error when setting // the watch-point by FSEvents fails or with errAlreadyWatched error when // the given path is already watched.
[ "Watch", "implements", "Watcher", "interface", ".", "It", "fails", "with", "non", "-", "nil", "error", "when", "setting", "the", "watch", "-", "point", "by", "FSEvents", "fails", "or", "with", "errAlreadyWatched", "error", "when", "the", "given", "path", "is", "already", "watched", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_fsevents.go#L221-L223
144,790
rjeczalik/notify
watcher_fsevents.go
Rewatch
func (fse *fsevents) Rewatch(path string, oldevent, newevent Event) error { w, ok := fse.watches[path] if !ok { return errNotWatched } if !atomic.CompareAndSwapUint32(&w.events, uint32(oldevent), uint32(newevent)) { return errInvalidEventSet } atomic.StoreInt32(&w.isrec, 0) return nil }
go
func (fse *fsevents) Rewatch(path string, oldevent, newevent Event) error { w, ok := fse.watches[path] if !ok { return errNotWatched } if !atomic.CompareAndSwapUint32(&w.events, uint32(oldevent), uint32(newevent)) { return errInvalidEventSet } atomic.StoreInt32(&w.isrec, 0) return nil }
[ "func", "(", "fse", "*", "fsevents", ")", "Rewatch", "(", "path", "string", ",", "oldevent", ",", "newevent", "Event", ")", "error", "{", "w", ",", "ok", ":=", "fse", ".", "watches", "[", "path", "]", "\n", "if", "!", "ok", "{", "return", "errNotWatched", "\n", "}", "\n", "if", "!", "atomic", ".", "CompareAndSwapUint32", "(", "&", "w", ".", "events", ",", "uint32", "(", "oldevent", ")", ",", "uint32", "(", "newevent", ")", ")", "{", "return", "errInvalidEventSet", "\n", "}", "\n", "atomic", ".", "StoreInt32", "(", "&", "w", ".", "isrec", ",", "0", ")", "\n", "return", "nil", "\n", "}" ]
// Rewatch implements Watcher interface. It fails with errNotWatched when // the given path is not being watched or with errInvalidEventSet when oldevent // does not match event set the watch-point currently holds.
[ "Rewatch", "implements", "Watcher", "interface", ".", "It", "fails", "with", "errNotWatched", "when", "the", "given", "path", "is", "not", "being", "watched", "or", "with", "errInvalidEventSet", "when", "oldevent", "does", "not", "match", "event", "set", "the", "watch", "-", "point", "currently", "holds", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_fsevents.go#L234-L244
144,791
rjeczalik/notify
watcher_fsevents.go
Close
func (fse *fsevents) Close() error { for _, w := range fse.watches { w.Stop() } fse.watches = nil return nil }
go
func (fse *fsevents) Close() error { for _, w := range fse.watches { w.Stop() } fse.watches = nil return nil }
[ "func", "(", "fse", "*", "fsevents", ")", "Close", "(", ")", "error", "{", "for", "_", ",", "w", ":=", "range", "fse", ".", "watches", "{", "w", ".", "Stop", "(", ")", "\n", "}", "\n", "fse", ".", "watches", "=", "nil", "\n", "return", "nil", "\n", "}" ]
// Close unwatches all watch-points.
[ "Close", "unwatches", "all", "watch", "-", "points", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_fsevents.go#L305-L311
144,792
rjeczalik/notify
watcher_fsevents_cgo.go
init
func init() { wg.Add(1) go func() { // There is exactly one run loop per thread. Lock this goroutine to its // thread to ensure that it's not rescheduled on a different thread while // setting up the run loop. runtime.LockOSThread() runloop = C.CFRunLoopGetCurrent() C.CFRunLoopAddSource(runloop, source, C.kCFRunLoopDefaultMode) C.CFRunLoopRun() panic("runloop has just unexpectedly stopped") }() C.CFRunLoopSourceSignal(source) }
go
func init() { wg.Add(1) go func() { // There is exactly one run loop per thread. Lock this goroutine to its // thread to ensure that it's not rescheduled on a different thread while // setting up the run loop. runtime.LockOSThread() runloop = C.CFRunLoopGetCurrent() C.CFRunLoopAddSource(runloop, source, C.kCFRunLoopDefaultMode) C.CFRunLoopRun() panic("runloop has just unexpectedly stopped") }() C.CFRunLoopSourceSignal(source) }
[ "func", "init", "(", ")", "{", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "// There is exactly one run loop per thread. Lock this goroutine to its", "// thread to ensure that it's not rescheduled on a different thread while", "// setting up the run loop.", "runtime", ".", "LockOSThread", "(", ")", "\n", "runloop", "=", "C", ".", "CFRunLoopGetCurrent", "(", ")", "\n", "C", ".", "CFRunLoopAddSource", "(", "runloop", ",", "source", ",", "C", ".", "kCFRunLoopDefaultMode", ")", "\n", "C", ".", "CFRunLoopRun", "(", ")", "\n", "panic", "(", "\"", "\"", ")", "\n", "}", "(", ")", "\n", "C", ".", "CFRunLoopSourceSignal", "(", "source", ")", "\n", "}" ]
// initializes the global runloop and ensures any created stream awaits its // readiness.
[ "initializes", "the", "global", "runloop", "and", "ensures", "any", "created", "stream", "awaits", "its", "readiness", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_fsevents_cgo.go#L63-L76
144,793
rjeczalik/notify
watcher_fsevents_cgo.go
newStream
func newStream(path string, fn streamFunc) *stream { return &stream{ path: path, info: streamFuncs.add(fn), } }
go
func newStream(path string, fn streamFunc) *stream { return &stream{ path: path, info: streamFuncs.add(fn), } }
[ "func", "newStream", "(", "path", "string", ",", "fn", "streamFunc", ")", "*", "stream", "{", "return", "&", "stream", "{", "path", ":", "path", ",", "info", ":", "streamFuncs", ".", "add", "(", "fn", ")", ",", "}", "\n", "}" ]
// NewStream creates a stream for given path, listening for file events and // calling fn upon receiving any.
[ "NewStream", "creates", "a", "stream", "for", "given", "path", "listening", "for", "file", "events", "and", "calling", "fn", "upon", "receiving", "any", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_fsevents_cgo.go#L155-L160
144,794
rjeczalik/notify
watcher_fsevents_cgo.go
Start
func (s *stream) Start() error { if s.ref != nilstream { return nil } wg.Wait() p := C.CFStringCreateWithCStringNoCopy(C.kCFAllocatorDefault, C.CString(s.path), C.kCFStringEncodingUTF8, C.kCFAllocatorDefault) path := C.CFArrayCreate(C.kCFAllocatorDefault, (*unsafe.Pointer)(unsafe.Pointer(&p)), 1, nil) ctx := C.FSEventStreamContext{} ref := C.EventStreamCreate(&ctx, C.uintptr_t(s.info), path, C.FSEventStreamEventId(atomic.LoadUint64(&since)), latency, flags) if ref == nilstream { return errCreate } C.FSEventStreamScheduleWithRunLoop(ref, runloop, C.kCFRunLoopDefaultMode) if C.FSEventStreamStart(ref) == C.Boolean(0) { C.FSEventStreamInvalidate(ref) return errStart } C.CFRunLoopWakeUp(runloop) s.ref = ref return nil }
go
func (s *stream) Start() error { if s.ref != nilstream { return nil } wg.Wait() p := C.CFStringCreateWithCStringNoCopy(C.kCFAllocatorDefault, C.CString(s.path), C.kCFStringEncodingUTF8, C.kCFAllocatorDefault) path := C.CFArrayCreate(C.kCFAllocatorDefault, (*unsafe.Pointer)(unsafe.Pointer(&p)), 1, nil) ctx := C.FSEventStreamContext{} ref := C.EventStreamCreate(&ctx, C.uintptr_t(s.info), path, C.FSEventStreamEventId(atomic.LoadUint64(&since)), latency, flags) if ref == nilstream { return errCreate } C.FSEventStreamScheduleWithRunLoop(ref, runloop, C.kCFRunLoopDefaultMode) if C.FSEventStreamStart(ref) == C.Boolean(0) { C.FSEventStreamInvalidate(ref) return errStart } C.CFRunLoopWakeUp(runloop) s.ref = ref return nil }
[ "func", "(", "s", "*", "stream", ")", "Start", "(", ")", "error", "{", "if", "s", ".", "ref", "!=", "nilstream", "{", "return", "nil", "\n", "}", "\n", "wg", ".", "Wait", "(", ")", "\n", "p", ":=", "C", ".", "CFStringCreateWithCStringNoCopy", "(", "C", ".", "kCFAllocatorDefault", ",", "C", ".", "CString", "(", "s", ".", "path", ")", ",", "C", ".", "kCFStringEncodingUTF8", ",", "C", ".", "kCFAllocatorDefault", ")", "\n", "path", ":=", "C", ".", "CFArrayCreate", "(", "C", ".", "kCFAllocatorDefault", ",", "(", "*", "unsafe", ".", "Pointer", ")", "(", "unsafe", ".", "Pointer", "(", "&", "p", ")", ")", ",", "1", ",", "nil", ")", "\n", "ctx", ":=", "C", ".", "FSEventStreamContext", "{", "}", "\n", "ref", ":=", "C", ".", "EventStreamCreate", "(", "&", "ctx", ",", "C", ".", "uintptr_t", "(", "s", ".", "info", ")", ",", "path", ",", "C", ".", "FSEventStreamEventId", "(", "atomic", ".", "LoadUint64", "(", "&", "since", ")", ")", ",", "latency", ",", "flags", ")", "\n", "if", "ref", "==", "nilstream", "{", "return", "errCreate", "\n", "}", "\n", "C", ".", "FSEventStreamScheduleWithRunLoop", "(", "ref", ",", "runloop", ",", "C", ".", "kCFRunLoopDefaultMode", ")", "\n", "if", "C", ".", "FSEventStreamStart", "(", "ref", ")", "==", "C", ".", "Boolean", "(", "0", ")", "{", "C", ".", "FSEventStreamInvalidate", "(", "ref", ")", "\n", "return", "errStart", "\n", "}", "\n", "C", ".", "CFRunLoopWakeUp", "(", "runloop", ")", "\n", "s", ".", "ref", "=", "ref", "\n", "return", "nil", "\n", "}" ]
// Start creates a FSEventStream for the given path and schedules it with // global runloop. It's a nop if the stream was already started.
[ "Start", "creates", "a", "FSEventStream", "for", "the", "given", "path", "and", "schedules", "it", "with", "global", "runloop", ".", "It", "s", "a", "nop", "if", "the", "stream", "was", "already", "started", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_fsevents_cgo.go#L164-L184
144,795
rjeczalik/notify
watcher_fsevents_cgo.go
Stop
func (s *stream) Stop() { if s.ref == nilstream { return } wg.Wait() C.FSEventStreamStop(s.ref) C.FSEventStreamInvalidate(s.ref) C.CFRunLoopWakeUp(runloop) s.ref = nilstream streamFuncs.delete(s.info) }
go
func (s *stream) Stop() { if s.ref == nilstream { return } wg.Wait() C.FSEventStreamStop(s.ref) C.FSEventStreamInvalidate(s.ref) C.CFRunLoopWakeUp(runloop) s.ref = nilstream streamFuncs.delete(s.info) }
[ "func", "(", "s", "*", "stream", ")", "Stop", "(", ")", "{", "if", "s", ".", "ref", "==", "nilstream", "{", "return", "\n", "}", "\n", "wg", ".", "Wait", "(", ")", "\n", "C", ".", "FSEventStreamStop", "(", "s", ".", "ref", ")", "\n", "C", ".", "FSEventStreamInvalidate", "(", "s", ".", "ref", ")", "\n", "C", ".", "CFRunLoopWakeUp", "(", "runloop", ")", "\n", "s", ".", "ref", "=", "nilstream", "\n", "streamFuncs", ".", "delete", "(", "s", ".", "info", ")", "\n", "}" ]
// Stop stops underlying FSEventStream and unregisters it from global runloop.
[ "Stop", "stops", "underlying", "FSEventStream", "and", "unregisters", "it", "from", "global", "runloop", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_fsevents_cgo.go#L187-L197
144,796
rjeczalik/notify
util.go
nonil
func nonil(err ...error) error { for _, err := range err { if err != nil { return err } } return nil }
go
func nonil(err ...error) error { for _, err := range err { if err != nil { return err } } return nil }
[ "func", "nonil", "(", "err", "...", "error", ")", "error", "{", "for", "_", ",", "err", ":=", "range", "err", "{", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// nonil gives first non-nil error from the given arguments.
[ "nonil", "gives", "first", "non", "-", "nil", "error", "from", "the", "given", "arguments", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/util.go#L41-L48
144,797
rjeczalik/notify
util.go
canonical
func canonical(p string) (string, error) { p, err := filepath.Abs(p) if err != nil { return "", err } for i, j, depth := 1, 0, 1; i < len(p); i, depth = i+1, depth+1 { if depth > 128 { return "", &os.PathError{Op: "canonical", Path: p, Err: errDepth} } if j = strings.IndexRune(p[i:], '/'); j == -1 { j, i = i, len(p) } else { j, i = i, i+j } fi, err := os.Lstat(p[:i]) if err != nil { return "", err } if fi.Mode()&os.ModeSymlink == os.ModeSymlink { s, err := os.Readlink(p[:i]) if err != nil { return "", err } if filepath.IsAbs(s) { p = "/" + s + p[i:] } else { p = p[:j] + s + p[i:] } i = 1 // no guarantee s is canonical, start all over } } return filepath.Clean(p), nil }
go
func canonical(p string) (string, error) { p, err := filepath.Abs(p) if err != nil { return "", err } for i, j, depth := 1, 0, 1; i < len(p); i, depth = i+1, depth+1 { if depth > 128 { return "", &os.PathError{Op: "canonical", Path: p, Err: errDepth} } if j = strings.IndexRune(p[i:], '/'); j == -1 { j, i = i, len(p) } else { j, i = i, i+j } fi, err := os.Lstat(p[:i]) if err != nil { return "", err } if fi.Mode()&os.ModeSymlink == os.ModeSymlink { s, err := os.Readlink(p[:i]) if err != nil { return "", err } if filepath.IsAbs(s) { p = "/" + s + p[i:] } else { p = p[:j] + s + p[i:] } i = 1 // no guarantee s is canonical, start all over } } return filepath.Clean(p), nil }
[ "func", "canonical", "(", "p", "string", ")", "(", "string", ",", "error", ")", "{", "p", ",", "err", ":=", "filepath", ".", "Abs", "(", "p", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "for", "i", ",", "j", ",", "depth", ":=", "1", ",", "0", ",", "1", ";", "i", "<", "len", "(", "p", ")", ";", "i", ",", "depth", "=", "i", "+", "1", ",", "depth", "+", "1", "{", "if", "depth", ">", "128", "{", "return", "\"", "\"", ",", "&", "os", ".", "PathError", "{", "Op", ":", "\"", "\"", ",", "Path", ":", "p", ",", "Err", ":", "errDepth", "}", "\n", "}", "\n", "if", "j", "=", "strings", ".", "IndexRune", "(", "p", "[", "i", ":", "]", ",", "'/'", ")", ";", "j", "==", "-", "1", "{", "j", ",", "i", "=", "i", ",", "len", "(", "p", ")", "\n", "}", "else", "{", "j", ",", "i", "=", "i", ",", "i", "+", "j", "\n", "}", "\n", "fi", ",", "err", ":=", "os", ".", "Lstat", "(", "p", "[", ":", "i", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "if", "fi", ".", "Mode", "(", ")", "&", "os", ".", "ModeSymlink", "==", "os", ".", "ModeSymlink", "{", "s", ",", "err", ":=", "os", ".", "Readlink", "(", "p", "[", ":", "i", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "if", "filepath", ".", "IsAbs", "(", "s", ")", "{", "p", "=", "\"", "\"", "+", "s", "+", "p", "[", "i", ":", "]", "\n", "}", "else", "{", "p", "=", "p", "[", ":", "j", "]", "+", "s", "+", "p", "[", "i", ":", "]", "\n", "}", "\n", "i", "=", "1", "// no guarantee s is canonical, start all over", "\n", "}", "\n", "}", "\n", "return", "filepath", ".", "Clean", "(", "p", ")", ",", "nil", "\n", "}" ]
// canonical resolves any symlink in the given path and returns it in a clean form. // It expects the path to be absolute. It fails to resolve circular symlinks by // maintaining a simple iteration limit.
[ "canonical", "resolves", "any", "symlink", "in", "the", "given", "path", "and", "returns", "it", "in", "a", "clean", "form", ".", "It", "expects", "the", "path", "to", "be", "absolute", ".", "It", "fails", "to", "resolve", "circular", "symlinks", "by", "maintaining", "a", "simple", "iteration", "limit", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/util.go#L67-L99
144,798
rjeczalik/notify
watcher_trigger.go
newWatcher
func newWatcher(c chan<- EventInfo) watcher { t := &trg{ s: make(chan struct{}, 1), pthLkp: make(map[string]*watched, 0), c: c, } t.t = newTrigger(t.pthLkp) if err := t.t.Init(); err != nil { t.Close() return watcherStub{fmt.Errorf("failed setting up watcher: %v", err)} } go t.monitor() return t }
go
func newWatcher(c chan<- EventInfo) watcher { t := &trg{ s: make(chan struct{}, 1), pthLkp: make(map[string]*watched, 0), c: c, } t.t = newTrigger(t.pthLkp) if err := t.t.Init(); err != nil { t.Close() return watcherStub{fmt.Errorf("failed setting up watcher: %v", err)} } go t.monitor() return t }
[ "func", "newWatcher", "(", "c", "chan", "<-", "EventInfo", ")", "watcher", "{", "t", ":=", "&", "trg", "{", "s", ":", "make", "(", "chan", "struct", "{", "}", ",", "1", ")", ",", "pthLkp", ":", "make", "(", "map", "[", "string", "]", "*", "watched", ",", "0", ")", ",", "c", ":", "c", ",", "}", "\n", "t", ".", "t", "=", "newTrigger", "(", "t", ".", "pthLkp", ")", "\n", "if", "err", ":=", "t", ".", "t", ".", "Init", "(", ")", ";", "err", "!=", "nil", "{", "t", ".", "Close", "(", ")", "\n", "return", "watcherStub", "{", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "}", "\n", "}", "\n", "go", "t", ".", "monitor", "(", ")", "\n", "return", "t", "\n", "}" ]
// newWatcher returns new watcher's implementation.
[ "newWatcher", "returns", "new", "watcher", "s", "implementation", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_trigger.go#L101-L114
144,799
rjeczalik/notify
watcher_trigger.go
Close
func (t *trg) Close() (err error) { t.Lock() if err = t.t.Stop(); err != nil { t.Unlock() return } <-t.s var e error for _, w := range t.pthLkp { if e = t.unwatch(w.p, w.fi); e != nil { dbgprintf("trg: unwatch %q failed: %q\n", w.p, e) err = nonil(err, e) } } if e = t.t.Close(); e != nil { dbgprintf("trg: closing native watch failed: %q\n", e) err = nonil(err, e) } if remaining := len(t.pthLkp); remaining != 0 { err = nonil(err, fmt.Errorf("Not all watches were removed: len(t.pthLkp) == %v", len(t.pthLkp))) } t.Unlock() return }
go
func (t *trg) Close() (err error) { t.Lock() if err = t.t.Stop(); err != nil { t.Unlock() return } <-t.s var e error for _, w := range t.pthLkp { if e = t.unwatch(w.p, w.fi); e != nil { dbgprintf("trg: unwatch %q failed: %q\n", w.p, e) err = nonil(err, e) } } if e = t.t.Close(); e != nil { dbgprintf("trg: closing native watch failed: %q\n", e) err = nonil(err, e) } if remaining := len(t.pthLkp); remaining != 0 { err = nonil(err, fmt.Errorf("Not all watches were removed: len(t.pthLkp) == %v", len(t.pthLkp))) } t.Unlock() return }
[ "func", "(", "t", "*", "trg", ")", "Close", "(", ")", "(", "err", "error", ")", "{", "t", ".", "Lock", "(", ")", "\n", "if", "err", "=", "t", ".", "t", ".", "Stop", "(", ")", ";", "err", "!=", "nil", "{", "t", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n", "<-", "t", ".", "s", "\n", "var", "e", "error", "\n", "for", "_", ",", "w", ":=", "range", "t", ".", "pthLkp", "{", "if", "e", "=", "t", ".", "unwatch", "(", "w", ".", "p", ",", "w", ".", "fi", ")", ";", "e", "!=", "nil", "{", "dbgprintf", "(", "\"", "\\n", "\"", ",", "w", ".", "p", ",", "e", ")", "\n", "err", "=", "nonil", "(", "err", ",", "e", ")", "\n", "}", "\n", "}", "\n", "if", "e", "=", "t", ".", "t", ".", "Close", "(", ")", ";", "e", "!=", "nil", "{", "dbgprintf", "(", "\"", "\\n", "\"", ",", "e", ")", "\n", "err", "=", "nonil", "(", "err", ",", "e", ")", "\n", "}", "\n", "if", "remaining", ":=", "len", "(", "t", ".", "pthLkp", ")", ";", "remaining", "!=", "0", "{", "err", "=", "nonil", "(", "err", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "t", ".", "pthLkp", ")", ")", ")", "\n", "}", "\n", "t", ".", "Unlock", "(", ")", "\n", "return", "\n", "}" ]
// Close implements watcher.
[ "Close", "implements", "watcher", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_trigger.go#L117-L140